SSAUpdaterBulk.cpp 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. //===- SSAUpdaterBulk.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 SSAUpdaterBulk class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/Transforms/Utils/SSAUpdaterBulk.h"
  13. #include "llvm/Analysis/IteratedDominanceFrontier.h"
  14. #include "llvm/IR/BasicBlock.h"
  15. #include "llvm/IR/Dominators.h"
  16. #include "llvm/IR/IRBuilder.h"
  17. #include "llvm/IR/Instructions.h"
  18. #include "llvm/IR/Use.h"
  19. #include "llvm/IR/Value.h"
  20. using namespace llvm;
  21. #define DEBUG_TYPE "ssaupdaterbulk"
  22. /// Helper function for finding a block which should have a value for the given
  23. /// user. For PHI-nodes this block is the corresponding predecessor, for other
  24. /// instructions it's their parent block.
  25. static BasicBlock *getUserBB(Use *U) {
  26. auto *User = cast<Instruction>(U->getUser());
  27. if (auto *UserPN = dyn_cast<PHINode>(User))
  28. return UserPN->getIncomingBlock(*U);
  29. else
  30. return User->getParent();
  31. }
  32. /// Add a new variable to the SSA rewriter. This needs to be called before
  33. /// AddAvailableValue or AddUse calls.
  34. unsigned SSAUpdaterBulk::AddVariable(StringRef Name, Type *Ty) {
  35. unsigned Var = Rewrites.size();
  36. LLVM_DEBUG(dbgs() << "SSAUpdater: Var=" << Var << ": initialized with Ty = "
  37. << *Ty << ", Name = " << Name << "\n");
  38. RewriteInfo RI(Name, Ty);
  39. Rewrites.push_back(RI);
  40. return Var;
  41. }
  42. /// Indicate that a rewritten value is available in the specified block with the
  43. /// specified value.
  44. void SSAUpdaterBulk::AddAvailableValue(unsigned Var, BasicBlock *BB, Value *V) {
  45. assert(Var < Rewrites.size() && "Variable not found!");
  46. LLVM_DEBUG(dbgs() << "SSAUpdater: Var=" << Var
  47. << ": added new available value " << *V << " in "
  48. << BB->getName() << "\n");
  49. Rewrites[Var].Defines[BB] = V;
  50. }
  51. /// Record a use of the symbolic value. This use will be updated with a
  52. /// rewritten value when RewriteAllUses is called.
  53. void SSAUpdaterBulk::AddUse(unsigned Var, Use *U) {
  54. assert(Var < Rewrites.size() && "Variable not found!");
  55. LLVM_DEBUG(dbgs() << "SSAUpdater: Var=" << Var << ": added a use" << *U->get()
  56. << " in " << getUserBB(U)->getName() << "\n");
  57. Rewrites[Var].Uses.push_back(U);
  58. }
  59. // Compute value at the given block BB. We either should already know it, or we
  60. // should be able to recursively reach it going up dominator tree.
  61. Value *SSAUpdaterBulk::computeValueAt(BasicBlock *BB, RewriteInfo &R,
  62. DominatorTree *DT) {
  63. if (!R.Defines.count(BB)) {
  64. if (DT->isReachableFromEntry(BB) && PredCache.get(BB).size()) {
  65. BasicBlock *IDom = DT->getNode(BB)->getIDom()->getBlock();
  66. Value *V = computeValueAt(IDom, R, DT);
  67. R.Defines[BB] = V;
  68. } else
  69. R.Defines[BB] = UndefValue::get(R.Ty);
  70. }
  71. return R.Defines[BB];
  72. }
  73. /// Given sets of UsingBlocks and DefBlocks, compute the set of LiveInBlocks.
  74. /// This is basically a subgraph limited by DefBlocks and UsingBlocks.
  75. static void
  76. ComputeLiveInBlocks(const SmallPtrSetImpl<BasicBlock *> &UsingBlocks,
  77. const SmallPtrSetImpl<BasicBlock *> &DefBlocks,
  78. SmallPtrSetImpl<BasicBlock *> &LiveInBlocks,
  79. PredIteratorCache &PredCache) {
  80. // To determine liveness, we must iterate through the predecessors of blocks
  81. // where the def is live. Blocks are added to the worklist if we need to
  82. // check their predecessors. Start with all the using blocks.
  83. SmallVector<BasicBlock *, 64> LiveInBlockWorklist(UsingBlocks.begin(),
  84. UsingBlocks.end());
  85. // Now that we have a set of blocks where the phi is live-in, recursively add
  86. // their predecessors until we find the full region the value is live.
  87. while (!LiveInBlockWorklist.empty()) {
  88. BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
  89. // The block really is live in here, insert it into the set. If already in
  90. // the set, then it has already been processed.
  91. if (!LiveInBlocks.insert(BB).second)
  92. continue;
  93. // Since the value is live into BB, it is either defined in a predecessor or
  94. // live into it to. Add the preds to the worklist unless they are a
  95. // defining block.
  96. for (BasicBlock *P : PredCache.get(BB)) {
  97. // The value is not live into a predecessor if it defines the value.
  98. if (DefBlocks.count(P))
  99. continue;
  100. // Otherwise it is, add to the worklist.
  101. LiveInBlockWorklist.push_back(P);
  102. }
  103. }
  104. }
  105. /// Perform all the necessary updates, including new PHI-nodes insertion and the
  106. /// requested uses update.
  107. void SSAUpdaterBulk::RewriteAllUses(DominatorTree *DT,
  108. SmallVectorImpl<PHINode *> *InsertedPHIs) {
  109. for (auto &R : Rewrites) {
  110. // Compute locations for new phi-nodes.
  111. // For that we need to initialize DefBlocks from definitions in R.Defines,
  112. // UsingBlocks from uses in R.Uses, then compute LiveInBlocks, and then use
  113. // this set for computing iterated dominance frontier (IDF).
  114. // The IDF blocks are the blocks where we need to insert new phi-nodes.
  115. ForwardIDFCalculator IDF(*DT);
  116. LLVM_DEBUG(dbgs() << "SSAUpdater: rewriting " << R.Uses.size()
  117. << " use(s)\n");
  118. SmallPtrSet<BasicBlock *, 2> DefBlocks;
  119. for (auto &Def : R.Defines)
  120. DefBlocks.insert(Def.first);
  121. IDF.setDefiningBlocks(DefBlocks);
  122. SmallPtrSet<BasicBlock *, 2> UsingBlocks;
  123. for (Use *U : R.Uses)
  124. UsingBlocks.insert(getUserBB(U));
  125. SmallVector<BasicBlock *, 32> IDFBlocks;
  126. SmallPtrSet<BasicBlock *, 32> LiveInBlocks;
  127. ComputeLiveInBlocks(UsingBlocks, DefBlocks, LiveInBlocks, PredCache);
  128. IDF.resetLiveInBlocks();
  129. IDF.setLiveInBlocks(LiveInBlocks);
  130. IDF.calculate(IDFBlocks);
  131. // We've computed IDF, now insert new phi-nodes there.
  132. SmallVector<PHINode *, 4> InsertedPHIsForVar;
  133. for (auto *FrontierBB : IDFBlocks) {
  134. IRBuilder<> B(FrontierBB, FrontierBB->begin());
  135. PHINode *PN = B.CreatePHI(R.Ty, 0, R.Name);
  136. R.Defines[FrontierBB] = PN;
  137. InsertedPHIsForVar.push_back(PN);
  138. if (InsertedPHIs)
  139. InsertedPHIs->push_back(PN);
  140. }
  141. // Fill in arguments of the inserted PHIs.
  142. for (auto *PN : InsertedPHIsForVar) {
  143. BasicBlock *PBB = PN->getParent();
  144. for (BasicBlock *Pred : PredCache.get(PBB))
  145. PN->addIncoming(computeValueAt(Pred, R, DT), Pred);
  146. }
  147. // Rewrite actual uses with the inserted definitions.
  148. SmallPtrSet<Use *, 4> ProcessedUses;
  149. for (Use *U : R.Uses) {
  150. if (!ProcessedUses.insert(U).second)
  151. continue;
  152. Value *V = computeValueAt(getUserBB(U), R, DT);
  153. Value *OldVal = U->get();
  154. assert(OldVal && "Invalid use!");
  155. // Notify that users of the existing value that it is being replaced.
  156. if (OldVal != V && OldVal->hasValueHandle())
  157. ValueHandleBase::ValueIsRAUWd(OldVal, V);
  158. LLVM_DEBUG(dbgs() << "SSAUpdater: replacing " << *OldVal << " with " << *V
  159. << "\n");
  160. U->set(V);
  161. }
  162. }
  163. }