SSAUpdater.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. //===- SSAUpdater.cpp - Unstructured SSA Update Tool ----------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the SSAUpdater class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/Transforms/Utils/SSAUpdater.h"
  13. #include "llvm/ADT/DenseMap.h"
  14. #include "llvm/ADT/STLExtras.h"
  15. #include "llvm/ADT/SmallVector.h"
  16. #include "llvm/ADT/TinyPtrVector.h"
  17. #include "llvm/Analysis/InstructionSimplify.h"
  18. #include "llvm/IR/BasicBlock.h"
  19. #include "llvm/IR/CFG.h"
  20. #include "llvm/IR/Constants.h"
  21. #include "llvm/IR/DebugLoc.h"
  22. #include "llvm/IR/Instruction.h"
  23. #include "llvm/IR/Instructions.h"
  24. #include "llvm/IR/Module.h"
  25. #include "llvm/IR/Use.h"
  26. #include "llvm/IR/Value.h"
  27. #include "llvm/Support/Casting.h"
  28. #include "llvm/Support/Debug.h"
  29. #include "llvm/Support/raw_ostream.h"
  30. #include "llvm/Transforms/Utils/SSAUpdaterImpl.h"
  31. #include <cassert>
  32. #include <utility>
  33. using namespace llvm;
  34. #define DEBUG_TYPE "ssaupdater"
  35. using AvailableValsTy = DenseMap<BasicBlock *, Value *>;
  36. static AvailableValsTy &getAvailableVals(void *AV) {
  37. return *static_cast<AvailableValsTy*>(AV);
  38. }
  39. SSAUpdater::SSAUpdater(SmallVectorImpl<PHINode *> *NewPHI)
  40. : InsertedPHIs(NewPHI) {}
  41. SSAUpdater::~SSAUpdater() {
  42. delete static_cast<AvailableValsTy*>(AV);
  43. }
  44. void SSAUpdater::Initialize(Type *Ty, StringRef Name) {
  45. if (!AV)
  46. AV = new AvailableValsTy();
  47. else
  48. getAvailableVals(AV).clear();
  49. ProtoType = Ty;
  50. ProtoName = std::string(Name);
  51. }
  52. bool SSAUpdater::HasValueForBlock(BasicBlock *BB) const {
  53. return getAvailableVals(AV).count(BB);
  54. }
  55. Value *SSAUpdater::FindValueForBlock(BasicBlock *BB) const {
  56. return getAvailableVals(AV).lookup(BB);
  57. }
  58. void SSAUpdater::AddAvailableValue(BasicBlock *BB, Value *V) {
  59. assert(ProtoType && "Need to initialize SSAUpdater");
  60. assert(ProtoType == V->getType() &&
  61. "All rewritten values must have the same type");
  62. getAvailableVals(AV)[BB] = V;
  63. }
  64. static bool IsEquivalentPHI(PHINode *PHI,
  65. SmallDenseMap<BasicBlock *, Value *, 8> &ValueMapping) {
  66. unsigned PHINumValues = PHI->getNumIncomingValues();
  67. if (PHINumValues != ValueMapping.size())
  68. return false;
  69. // Scan the phi to see if it matches.
  70. for (unsigned i = 0, e = PHINumValues; i != e; ++i)
  71. if (ValueMapping[PHI->getIncomingBlock(i)] !=
  72. PHI->getIncomingValue(i)) {
  73. return false;
  74. }
  75. return true;
  76. }
  77. Value *SSAUpdater::GetValueAtEndOfBlock(BasicBlock *BB) {
  78. Value *Res = GetValueAtEndOfBlockInternal(BB);
  79. return Res;
  80. }
  81. Value *SSAUpdater::GetValueInMiddleOfBlock(BasicBlock *BB) {
  82. // If there is no definition of the renamed variable in this block, just use
  83. // GetValueAtEndOfBlock to do our work.
  84. if (!HasValueForBlock(BB))
  85. return GetValueAtEndOfBlock(BB);
  86. // Otherwise, we have the hard case. Get the live-in values for each
  87. // predecessor.
  88. SmallVector<std::pair<BasicBlock *, Value *>, 8> PredValues;
  89. Value *SingularValue = nullptr;
  90. // We can get our predecessor info by walking the pred_iterator list, but it
  91. // is relatively slow. If we already have PHI nodes in this block, walk one
  92. // of them to get the predecessor list instead.
  93. if (PHINode *SomePhi = dyn_cast<PHINode>(BB->begin())) {
  94. for (unsigned i = 0, e = SomePhi->getNumIncomingValues(); i != e; ++i) {
  95. BasicBlock *PredBB = SomePhi->getIncomingBlock(i);
  96. Value *PredVal = GetValueAtEndOfBlock(PredBB);
  97. PredValues.push_back(std::make_pair(PredBB, PredVal));
  98. // Compute SingularValue.
  99. if (i == 0)
  100. SingularValue = PredVal;
  101. else if (PredVal != SingularValue)
  102. SingularValue = nullptr;
  103. }
  104. } else {
  105. bool isFirstPred = true;
  106. for (BasicBlock *PredBB : predecessors(BB)) {
  107. Value *PredVal = GetValueAtEndOfBlock(PredBB);
  108. PredValues.push_back(std::make_pair(PredBB, PredVal));
  109. // Compute SingularValue.
  110. if (isFirstPred) {
  111. SingularValue = PredVal;
  112. isFirstPred = false;
  113. } else if (PredVal != SingularValue)
  114. SingularValue = nullptr;
  115. }
  116. }
  117. // If there are no predecessors, just return undef.
  118. if (PredValues.empty())
  119. return UndefValue::get(ProtoType);
  120. // Otherwise, if all the merged values are the same, just use it.
  121. if (SingularValue)
  122. return SingularValue;
  123. // Otherwise, we do need a PHI: check to see if we already have one available
  124. // in this block that produces the right value.
  125. if (isa<PHINode>(BB->begin())) {
  126. SmallDenseMap<BasicBlock *, Value *, 8> ValueMapping(PredValues.begin(),
  127. PredValues.end());
  128. for (PHINode &SomePHI : BB->phis()) {
  129. if (IsEquivalentPHI(&SomePHI, ValueMapping))
  130. return &SomePHI;
  131. }
  132. }
  133. // Ok, we have no way out, insert a new one now.
  134. PHINode *InsertedPHI = PHINode::Create(ProtoType, PredValues.size(),
  135. ProtoName, &BB->front());
  136. // Fill in all the predecessors of the PHI.
  137. for (const auto &PredValue : PredValues)
  138. InsertedPHI->addIncoming(PredValue.second, PredValue.first);
  139. // See if the PHI node can be merged to a single value. This can happen in
  140. // loop cases when we get a PHI of itself and one other value.
  141. if (Value *V =
  142. simplifyInstruction(InsertedPHI, BB->getModule()->getDataLayout())) {
  143. InsertedPHI->eraseFromParent();
  144. return V;
  145. }
  146. // Set the DebugLoc of the inserted PHI, if available.
  147. DebugLoc DL;
  148. if (const Instruction *I = BB->getFirstNonPHI())
  149. DL = I->getDebugLoc();
  150. InsertedPHI->setDebugLoc(DL);
  151. // If the client wants to know about all new instructions, tell it.
  152. if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI);
  153. LLVM_DEBUG(dbgs() << " Inserted PHI: " << *InsertedPHI << "\n");
  154. return InsertedPHI;
  155. }
  156. void SSAUpdater::RewriteUse(Use &U) {
  157. Instruction *User = cast<Instruction>(U.getUser());
  158. Value *V;
  159. if (PHINode *UserPN = dyn_cast<PHINode>(User))
  160. V = GetValueAtEndOfBlock(UserPN->getIncomingBlock(U));
  161. else
  162. V = GetValueInMiddleOfBlock(User->getParent());
  163. U.set(V);
  164. }
  165. void SSAUpdater::RewriteUseAfterInsertions(Use &U) {
  166. Instruction *User = cast<Instruction>(U.getUser());
  167. Value *V;
  168. if (PHINode *UserPN = dyn_cast<PHINode>(User))
  169. V = GetValueAtEndOfBlock(UserPN->getIncomingBlock(U));
  170. else
  171. V = GetValueAtEndOfBlock(User->getParent());
  172. U.set(V);
  173. }
  174. namespace llvm {
  175. template<>
  176. class SSAUpdaterTraits<SSAUpdater> {
  177. public:
  178. using BlkT = BasicBlock;
  179. using ValT = Value *;
  180. using PhiT = PHINode;
  181. using BlkSucc_iterator = succ_iterator;
  182. static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return succ_begin(BB); }
  183. static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return succ_end(BB); }
  184. class PHI_iterator {
  185. private:
  186. PHINode *PHI;
  187. unsigned idx;
  188. public:
  189. explicit PHI_iterator(PHINode *P) // begin iterator
  190. : PHI(P), idx(0) {}
  191. PHI_iterator(PHINode *P, bool) // end iterator
  192. : PHI(P), idx(PHI->getNumIncomingValues()) {}
  193. PHI_iterator &operator++() { ++idx; return *this; }
  194. bool operator==(const PHI_iterator& x) const { return idx == x.idx; }
  195. bool operator!=(const PHI_iterator& x) const { return !operator==(x); }
  196. Value *getIncomingValue() { return PHI->getIncomingValue(idx); }
  197. BasicBlock *getIncomingBlock() { return PHI->getIncomingBlock(idx); }
  198. };
  199. static PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); }
  200. static PHI_iterator PHI_end(PhiT *PHI) {
  201. return PHI_iterator(PHI, true);
  202. }
  203. /// FindPredecessorBlocks - Put the predecessors of Info->BB into the Preds
  204. /// vector, set Info->NumPreds, and allocate space in Info->Preds.
  205. static void FindPredecessorBlocks(BasicBlock *BB,
  206. SmallVectorImpl<BasicBlock *> *Preds) {
  207. // We can get our predecessor info by walking the pred_iterator list,
  208. // but it is relatively slow. If we already have PHI nodes in this
  209. // block, walk one of them to get the predecessor list instead.
  210. if (PHINode *SomePhi = dyn_cast<PHINode>(BB->begin()))
  211. append_range(*Preds, SomePhi->blocks());
  212. else
  213. append_range(*Preds, predecessors(BB));
  214. }
  215. /// GetUndefVal - Get an undefined value of the same type as the value
  216. /// being handled.
  217. static Value *GetUndefVal(BasicBlock *BB, SSAUpdater *Updater) {
  218. return UndefValue::get(Updater->ProtoType);
  219. }
  220. /// CreateEmptyPHI - Create a new PHI instruction in the specified block.
  221. /// Reserve space for the operands but do not fill them in yet.
  222. static Value *CreateEmptyPHI(BasicBlock *BB, unsigned NumPreds,
  223. SSAUpdater *Updater) {
  224. PHINode *PHI = PHINode::Create(Updater->ProtoType, NumPreds,
  225. Updater->ProtoName, &BB->front());
  226. return PHI;
  227. }
  228. /// AddPHIOperand - Add the specified value as an operand of the PHI for
  229. /// the specified predecessor block.
  230. static void AddPHIOperand(PHINode *PHI, Value *Val, BasicBlock *Pred) {
  231. PHI->addIncoming(Val, Pred);
  232. }
  233. /// ValueIsPHI - Check if a value is a PHI.
  234. static PHINode *ValueIsPHI(Value *Val, SSAUpdater *Updater) {
  235. return dyn_cast<PHINode>(Val);
  236. }
  237. /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source
  238. /// operands, i.e., it was just added.
  239. static PHINode *ValueIsNewPHI(Value *Val, SSAUpdater *Updater) {
  240. PHINode *PHI = ValueIsPHI(Val, Updater);
  241. if (PHI && PHI->getNumIncomingValues() == 0)
  242. return PHI;
  243. return nullptr;
  244. }
  245. /// GetPHIValue - For the specified PHI instruction, return the value
  246. /// that it defines.
  247. static Value *GetPHIValue(PHINode *PHI) {
  248. return PHI;
  249. }
  250. };
  251. } // end namespace llvm
  252. /// Check to see if AvailableVals has an entry for the specified BB and if so,
  253. /// return it. If not, construct SSA form by first calculating the required
  254. /// placement of PHIs and then inserting new PHIs where needed.
  255. Value *SSAUpdater::GetValueAtEndOfBlockInternal(BasicBlock *BB) {
  256. AvailableValsTy &AvailableVals = getAvailableVals(AV);
  257. if (Value *V = AvailableVals[BB])
  258. return V;
  259. SSAUpdaterImpl<SSAUpdater> Impl(this, &AvailableVals, InsertedPHIs);
  260. return Impl.GetValue(BB);
  261. }
  262. //===----------------------------------------------------------------------===//
  263. // LoadAndStorePromoter Implementation
  264. //===----------------------------------------------------------------------===//
  265. LoadAndStorePromoter::
  266. LoadAndStorePromoter(ArrayRef<const Instruction *> Insts,
  267. SSAUpdater &S, StringRef BaseName) : SSA(S) {
  268. if (Insts.empty()) return;
  269. const Value *SomeVal;
  270. if (const LoadInst *LI = dyn_cast<LoadInst>(Insts[0]))
  271. SomeVal = LI;
  272. else
  273. SomeVal = cast<StoreInst>(Insts[0])->getOperand(0);
  274. if (BaseName.empty())
  275. BaseName = SomeVal->getName();
  276. SSA.Initialize(SomeVal->getType(), BaseName);
  277. }
  278. void LoadAndStorePromoter::run(const SmallVectorImpl<Instruction *> &Insts) {
  279. // First step: bucket up uses of the alloca by the block they occur in.
  280. // This is important because we have to handle multiple defs/uses in a block
  281. // ourselves: SSAUpdater is purely for cross-block references.
  282. DenseMap<BasicBlock *, TinyPtrVector<Instruction *>> UsesByBlock;
  283. for (Instruction *User : Insts)
  284. UsesByBlock[User->getParent()].push_back(User);
  285. // Okay, now we can iterate over all the blocks in the function with uses,
  286. // processing them. Keep track of which loads are loading a live-in value.
  287. // Walk the uses in the use-list order to be determinstic.
  288. SmallVector<LoadInst *, 32> LiveInLoads;
  289. DenseMap<Value *, Value *> ReplacedLoads;
  290. for (Instruction *User : Insts) {
  291. BasicBlock *BB = User->getParent();
  292. TinyPtrVector<Instruction *> &BlockUses = UsesByBlock[BB];
  293. // If this block has already been processed, ignore this repeat use.
  294. if (BlockUses.empty()) continue;
  295. // Okay, this is the first use in the block. If this block just has a
  296. // single user in it, we can rewrite it trivially.
  297. if (BlockUses.size() == 1) {
  298. // If it is a store, it is a trivial def of the value in the block.
  299. if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
  300. updateDebugInfo(SI);
  301. SSA.AddAvailableValue(BB, SI->getOperand(0));
  302. } else
  303. // Otherwise it is a load, queue it to rewrite as a live-in load.
  304. LiveInLoads.push_back(cast<LoadInst>(User));
  305. BlockUses.clear();
  306. continue;
  307. }
  308. // Otherwise, check to see if this block is all loads.
  309. bool HasStore = false;
  310. for (Instruction *I : BlockUses) {
  311. if (isa<StoreInst>(I)) {
  312. HasStore = true;
  313. break;
  314. }
  315. }
  316. // If so, we can queue them all as live in loads. We don't have an
  317. // efficient way to tell which on is first in the block and don't want to
  318. // scan large blocks, so just add all loads as live ins.
  319. if (!HasStore) {
  320. for (Instruction *I : BlockUses)
  321. LiveInLoads.push_back(cast<LoadInst>(I));
  322. BlockUses.clear();
  323. continue;
  324. }
  325. // Otherwise, we have mixed loads and stores (or just a bunch of stores).
  326. // Since SSAUpdater is purely for cross-block values, we need to determine
  327. // the order of these instructions in the block. If the first use in the
  328. // block is a load, then it uses the live in value. The last store defines
  329. // the live out value. We handle this by doing a linear scan of the block.
  330. Value *StoredValue = nullptr;
  331. for (Instruction &I : *BB) {
  332. if (LoadInst *L = dyn_cast<LoadInst>(&I)) {
  333. // If this is a load from an unrelated pointer, ignore it.
  334. if (!isInstInList(L, Insts)) continue;
  335. // If we haven't seen a store yet, this is a live in use, otherwise
  336. // use the stored value.
  337. if (StoredValue) {
  338. replaceLoadWithValue(L, StoredValue);
  339. L->replaceAllUsesWith(StoredValue);
  340. ReplacedLoads[L] = StoredValue;
  341. } else {
  342. LiveInLoads.push_back(L);
  343. }
  344. continue;
  345. }
  346. if (StoreInst *SI = dyn_cast<StoreInst>(&I)) {
  347. // If this is a store to an unrelated pointer, ignore it.
  348. if (!isInstInList(SI, Insts)) continue;
  349. updateDebugInfo(SI);
  350. // Remember that this is the active value in the block.
  351. StoredValue = SI->getOperand(0);
  352. }
  353. }
  354. // The last stored value that happened is the live-out for the block.
  355. assert(StoredValue && "Already checked that there is a store in block");
  356. SSA.AddAvailableValue(BB, StoredValue);
  357. BlockUses.clear();
  358. }
  359. // Okay, now we rewrite all loads that use live-in values in the loop,
  360. // inserting PHI nodes as necessary.
  361. for (LoadInst *ALoad : LiveInLoads) {
  362. Value *NewVal = SSA.GetValueInMiddleOfBlock(ALoad->getParent());
  363. replaceLoadWithValue(ALoad, NewVal);
  364. // Avoid assertions in unreachable code.
  365. if (NewVal == ALoad) NewVal = PoisonValue::get(NewVal->getType());
  366. ALoad->replaceAllUsesWith(NewVal);
  367. ReplacedLoads[ALoad] = NewVal;
  368. }
  369. // Allow the client to do stuff before we start nuking things.
  370. doExtraRewritesBeforeFinalDeletion();
  371. // Now that everything is rewritten, delete the old instructions from the
  372. // function. They should all be dead now.
  373. for (Instruction *User : Insts) {
  374. if (!shouldDelete(User))
  375. continue;
  376. // If this is a load that still has uses, then the load must have been added
  377. // as a live value in the SSAUpdate data structure for a block (e.g. because
  378. // the loaded value was stored later). In this case, we need to recursively
  379. // propagate the updates until we get to the real value.
  380. if (!User->use_empty()) {
  381. Value *NewVal = ReplacedLoads[User];
  382. assert(NewVal && "not a replaced load?");
  383. // Propagate down to the ultimate replacee. The intermediately loads
  384. // could theoretically already have been deleted, so we don't want to
  385. // dereference the Value*'s.
  386. DenseMap<Value*, Value*>::iterator RLI = ReplacedLoads.find(NewVal);
  387. while (RLI != ReplacedLoads.end()) {
  388. NewVal = RLI->second;
  389. RLI = ReplacedLoads.find(NewVal);
  390. }
  391. replaceLoadWithValue(cast<LoadInst>(User), NewVal);
  392. User->replaceAllUsesWith(NewVal);
  393. }
  394. instructionDeleted(User);
  395. User->eraseFromParent();
  396. }
  397. }
  398. bool
  399. LoadAndStorePromoter::isInstInList(Instruction *I,
  400. const SmallVectorImpl<Instruction *> &Insts)
  401. const {
  402. return is_contained(Insts, I);
  403. }