LCSSA.cpp 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. //===-- LCSSA.cpp - Convert loops into loop-closed SSA form ---------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This pass transforms loops by placing phi nodes at the end of the loops for
  11. // all values that are live across the loop boundary. For example, it turns
  12. // the left into the right code:
  13. //
  14. // for (...) for (...)
  15. // if (c) if (c)
  16. // X1 = ... X1 = ...
  17. // else else
  18. // X2 = ... X2 = ...
  19. // X3 = phi(X1, X2) X3 = phi(X1, X2)
  20. // ... = X3 + 4 X4 = phi(X3)
  21. // ... = X4 + 4
  22. //
  23. // This is still valid LLVM; the extra phi nodes are purely redundant, and will
  24. // be trivially eliminated by InstCombine. The major benefit of this
  25. // transformation is that it makes many other loop optimizations, such as
  26. // LoopUnswitching, simpler.
  27. //
  28. //===----------------------------------------------------------------------===//
  29. #define DEBUG_TYPE "lcssa"
  30. #include "llvm/Transforms/Scalar.h"
  31. #include "llvm/Constants.h"
  32. #include "llvm/Pass.h"
  33. #include "llvm/Function.h"
  34. #include "llvm/Instructions.h"
  35. #include "llvm/Analysis/Dominators.h"
  36. #include "llvm/Analysis/LoopPass.h"
  37. #include "llvm/Analysis/ScalarEvolution.h"
  38. #include "llvm/Transforms/Utils/SSAUpdater.h"
  39. #include "llvm/ADT/Statistic.h"
  40. #include "llvm/ADT/STLExtras.h"
  41. #include "llvm/Support/PredIteratorCache.h"
  42. using namespace llvm;
  43. STATISTIC(NumLCSSA, "Number of live out of a loop variables");
  44. namespace {
  45. struct LCSSA : public LoopPass {
  46. static char ID; // Pass identification, replacement for typeid
  47. LCSSA() : LoopPass(ID) {}
  48. // Cached analysis information for the current function.
  49. DominatorTree *DT;
  50. std::vector<BasicBlock*> LoopBlocks;
  51. PredIteratorCache PredCache;
  52. Loop *L;
  53. virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
  54. /// This transformation requires natural loop information & requires that
  55. /// loop preheaders be inserted into the CFG. It maintains both of these,
  56. /// as well as the CFG. It also requires dominator information.
  57. ///
  58. virtual void getAnalysisUsage(AnalysisUsage &AU) const {
  59. AU.setPreservesCFG();
  60. AU.addRequired<DominatorTree>();
  61. AU.addPreserved<DominatorTree>();
  62. AU.addPreserved<DominanceFrontier>();
  63. AU.addRequired<LoopInfo>();
  64. AU.addPreserved<LoopInfo>();
  65. AU.addPreservedID(LoopSimplifyID);
  66. AU.addPreserved<ScalarEvolution>();
  67. }
  68. private:
  69. bool ProcessInstruction(Instruction *Inst,
  70. const SmallVectorImpl<BasicBlock*> &ExitBlocks);
  71. /// verifyAnalysis() - Verify loop nest.
  72. virtual void verifyAnalysis() const {
  73. // Check the special guarantees that LCSSA makes.
  74. assert(L->isLCSSAForm(*DT) && "LCSSA form not preserved!");
  75. }
  76. /// inLoop - returns true if the given block is within the current loop
  77. bool inLoop(BasicBlock *B) const {
  78. return std::binary_search(LoopBlocks.begin(), LoopBlocks.end(), B);
  79. }
  80. };
  81. }
  82. char LCSSA::ID = 0;
  83. INITIALIZE_PASS(LCSSA, "lcssa", "Loop-Closed SSA Form Pass", false, false);
  84. Pass *llvm::createLCSSAPass() { return new LCSSA(); }
  85. char &llvm::LCSSAID = LCSSA::ID;
  86. /// BlockDominatesAnExit - Return true if the specified block dominates at least
  87. /// one of the blocks in the specified list.
  88. static bool BlockDominatesAnExit(BasicBlock *BB,
  89. const SmallVectorImpl<BasicBlock*> &ExitBlocks,
  90. DominatorTree *DT) {
  91. DomTreeNode *DomNode = DT->getNode(BB);
  92. for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
  93. if (DT->dominates(DomNode, DT->getNode(ExitBlocks[i])))
  94. return true;
  95. return false;
  96. }
  97. /// runOnFunction - Process all loops in the function, inner-most out.
  98. bool LCSSA::runOnLoop(Loop *TheLoop, LPPassManager &LPM) {
  99. L = TheLoop;
  100. DT = &getAnalysis<DominatorTree>();
  101. // Get the set of exiting blocks.
  102. SmallVector<BasicBlock*, 8> ExitBlocks;
  103. L->getExitBlocks(ExitBlocks);
  104. if (ExitBlocks.empty())
  105. return false;
  106. // Speed up queries by creating a sorted vector of blocks.
  107. LoopBlocks.clear();
  108. LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
  109. array_pod_sort(LoopBlocks.begin(), LoopBlocks.end());
  110. // Look at all the instructions in the loop, checking to see if they have uses
  111. // outside the loop. If so, rewrite those uses.
  112. bool MadeChange = false;
  113. for (Loop::block_iterator BBI = L->block_begin(), E = L->block_end();
  114. BBI != E; ++BBI) {
  115. BasicBlock *BB = *BBI;
  116. // For large loops, avoid use-scanning by using dominance information: In
  117. // particular, if a block does not dominate any of the loop exits, then none
  118. // of the values defined in the block could be used outside the loop.
  119. if (!BlockDominatesAnExit(BB, ExitBlocks, DT))
  120. continue;
  121. for (BasicBlock::iterator I = BB->begin(), E = BB->end();
  122. I != E; ++I) {
  123. // Reject two common cases fast: instructions with no uses (like stores)
  124. // and instructions with one use that is in the same block as this.
  125. if (I->use_empty() ||
  126. (I->hasOneUse() && I->use_back()->getParent() == BB &&
  127. !isa<PHINode>(I->use_back())))
  128. continue;
  129. MadeChange |= ProcessInstruction(I, ExitBlocks);
  130. }
  131. }
  132. assert(L->isLCSSAForm(*DT));
  133. PredCache.clear();
  134. return MadeChange;
  135. }
  136. /// isExitBlock - Return true if the specified block is in the list.
  137. static bool isExitBlock(BasicBlock *BB,
  138. const SmallVectorImpl<BasicBlock*> &ExitBlocks) {
  139. for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
  140. if (ExitBlocks[i] == BB)
  141. return true;
  142. return false;
  143. }
  144. /// ProcessInstruction - Given an instruction in the loop, check to see if it
  145. /// has any uses that are outside the current loop. If so, insert LCSSA PHI
  146. /// nodes and rewrite the uses.
  147. bool LCSSA::ProcessInstruction(Instruction *Inst,
  148. const SmallVectorImpl<BasicBlock*> &ExitBlocks) {
  149. SmallVector<Use*, 16> UsesToRewrite;
  150. BasicBlock *InstBB = Inst->getParent();
  151. for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
  152. UI != E; ++UI) {
  153. User *U = *UI;
  154. BasicBlock *UserBB = cast<Instruction>(U)->getParent();
  155. if (PHINode *PN = dyn_cast<PHINode>(U))
  156. UserBB = PN->getIncomingBlock(UI);
  157. if (InstBB != UserBB && !inLoop(UserBB))
  158. UsesToRewrite.push_back(&UI.getUse());
  159. }
  160. // If there are no uses outside the loop, exit with no change.
  161. if (UsesToRewrite.empty()) return false;
  162. ++NumLCSSA; // We are applying the transformation
  163. // Invoke instructions are special in that their result value is not available
  164. // along their unwind edge. The code below tests to see whether DomBB dominates
  165. // the value, so adjust DomBB to the normal destination block, which is
  166. // effectively where the value is first usable.
  167. BasicBlock *DomBB = Inst->getParent();
  168. if (InvokeInst *Inv = dyn_cast<InvokeInst>(Inst))
  169. DomBB = Inv->getNormalDest();
  170. DomTreeNode *DomNode = DT->getNode(DomBB);
  171. SSAUpdater SSAUpdate;
  172. SSAUpdate.Initialize(Inst);
  173. // Insert the LCSSA phi's into all of the exit blocks dominated by the
  174. // value, and add them to the Phi's map.
  175. for (SmallVectorImpl<BasicBlock*>::const_iterator BBI = ExitBlocks.begin(),
  176. BBE = ExitBlocks.end(); BBI != BBE; ++BBI) {
  177. BasicBlock *ExitBB = *BBI;
  178. if (!DT->dominates(DomNode, DT->getNode(ExitBB))) continue;
  179. // If we already inserted something for this BB, don't reprocess it.
  180. if (SSAUpdate.HasValueForBlock(ExitBB)) continue;
  181. PHINode *PN = PHINode::Create(Inst->getType(), Inst->getName()+".lcssa",
  182. ExitBB->begin());
  183. PN->reserveOperandSpace(PredCache.GetNumPreds(ExitBB));
  184. // Add inputs from inside the loop for this PHI.
  185. for (BasicBlock **PI = PredCache.GetPreds(ExitBB); *PI; ++PI) {
  186. PN->addIncoming(Inst, *PI);
  187. // If the exit block has a predecessor not within the loop, arrange for
  188. // the incoming value use corresponding to that predecessor to be
  189. // rewritten in terms of a different LCSSA PHI.
  190. if (!inLoop(*PI))
  191. UsesToRewrite.push_back(
  192. &PN->getOperandUse(
  193. PN->getOperandNumForIncomingValue(PN->getNumIncomingValues()-1)));
  194. }
  195. // Remember that this phi makes the value alive in this block.
  196. SSAUpdate.AddAvailableValue(ExitBB, PN);
  197. }
  198. // Rewrite all uses outside the loop in terms of the new PHIs we just
  199. // inserted.
  200. for (unsigned i = 0, e = UsesToRewrite.size(); i != e; ++i) {
  201. // If this use is in an exit block, rewrite to use the newly inserted PHI.
  202. // This is required for correctness because SSAUpdate doesn't handle uses in
  203. // the same block. It assumes the PHI we inserted is at the end of the
  204. // block.
  205. Instruction *User = cast<Instruction>(UsesToRewrite[i]->getUser());
  206. BasicBlock *UserBB = User->getParent();
  207. if (PHINode *PN = dyn_cast<PHINode>(User))
  208. UserBB = PN->getIncomingBlock(*UsesToRewrite[i]);
  209. if (isa<PHINode>(UserBB->begin()) &&
  210. isExitBlock(UserBB, ExitBlocks)) {
  211. UsesToRewrite[i]->set(UserBB->begin());
  212. continue;
  213. }
  214. // Otherwise, do full PHI insertion.
  215. SSAUpdate.RewriteUse(*UsesToRewrite[i]);
  216. }
  217. return true;
  218. }