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 30 #define DEBUG_TYPE "lcssa" 31 #include "llvm/Transforms/Scalar.h" 32 #include "llvm/Constants.h" 33 #include "llvm/Pass.h" 34 #include "llvm/Function.h" 35 #include "llvm/Instructions.h" 36 #include "llvm/Analysis/Dominators.h" 37 #include "llvm/Analysis/LoopPass.h" 38 #include "llvm/Analysis/ScalarEvolution.h" 39 #include "llvm/Transforms/Utils/SSAUpdater.h" 40 #include "llvm/ADT/Statistic.h" 41 #include "llvm/ADT/STLExtras.h" 42 #include "llvm/Support/PredIteratorCache.h" 43 using namespace llvm; 44 45 STATISTIC(NumLCSSA, "Number of live out of a loop variables"); 46 47 namespace { 48 struct LCSSA : public LoopPass { 49 static char ID; // Pass identification, replacement for typeid 50 LCSSA() : LoopPass(&ID) {} 51 52 // Cached analysis information for the current function. 53 DominatorTree *DT; 54 std::vector<BasicBlock*> LoopBlocks; 55 PredIteratorCache PredCache; 56 Loop *L; 57 58 virtual bool runOnLoop(Loop *L, LPPassManager &LPM); 59 60 /// This transformation requires natural loop information & requires that 61 /// loop preheaders be inserted into the CFG. It maintains both of these, 62 /// as well as the CFG. It also requires dominator information. 63 /// 64 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 65 AU.setPreservesCFG(); 66 67 AU.addRequiredTransitive<DominatorTree>(); 68 AU.addPreserved<DominatorTree>(); 69 AU.addPreserved<DominanceFrontier>(); 70 AU.addRequiredTransitive<LoopInfo>(); 71 AU.addPreserved<LoopInfo>(); 72 73 // LCSSA doesn't actually require LoopSimplify, but the PassManager 74 // doesn't know how to schedule LoopSimplify by itself. 75 AU.addRequiredID(LoopSimplifyID); 76 AU.addPreservedID(LoopSimplifyID); 77 78 AU.addPreserved<ScalarEvolution>(); 79 } 80 private: 81 bool ProcessInstruction(Instruction *Inst, 82 const SmallVectorImpl<BasicBlock*> &ExitBlocks); 83 84 /// verifyAnalysis() - Verify loop nest. 85 virtual void verifyAnalysis() const { 86 // Check the special guarantees that LCSSA makes. 87 assert(L->isLCSSAForm(*DT) && "LCSSA form not preserved!"); 88 } 89 90 /// inLoop - returns true if the given block is within the current loop 91 bool inLoop(BasicBlock *B) const { 92 return std::binary_search(LoopBlocks.begin(), LoopBlocks.end(), B); 93 } 94 }; 95 } 96 97 char LCSSA::ID = 0; 98 static RegisterPass<LCSSA> X("lcssa", "Loop-Closed SSA Form Pass"); 99 100 Pass *llvm::createLCSSAPass() { return new LCSSA(); } 101 const PassInfo *const llvm::LCSSAID = &X; 102 103 104 /// BlockDominatesAnExit - Return true if the specified block dominates at least 105 /// one of the blocks in the specified list. 106 static bool BlockDominatesAnExit(BasicBlock *BB, 107 const SmallVectorImpl<BasicBlock*> &ExitBlocks, 108 DominatorTree *DT) { 109 DomTreeNode *DomNode = DT->getNode(BB); 110 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) 111 if (DT->dominates(DomNode, DT->getNode(ExitBlocks[i]))) 112 return true; 113 114 return false; 115 } 116 117 118 /// runOnFunction - Process all loops in the function, inner-most out. 119 bool LCSSA::runOnLoop(Loop *TheLoop, LPPassManager &LPM) { 120 L = TheLoop; 121 122 DT = &getAnalysis<DominatorTree>(); 123 124 // Get the set of exiting blocks. 125 SmallVector<BasicBlock*, 8> ExitBlocks; 126 L->getExitBlocks(ExitBlocks); 127 128 if (ExitBlocks.empty()) 129 return false; 130 131 // Speed up queries by creating a sorted vector of blocks. 132 LoopBlocks.clear(); 133 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end()); 134 array_pod_sort(LoopBlocks.begin(), LoopBlocks.end()); 135 136 // Look at all the instructions in the loop, checking to see if they have uses 137 // outside the loop. If so, rewrite those uses. 138 bool MadeChange = false; 139 140 for (Loop::block_iterator BBI = L->block_begin(), E = L->block_end(); 141 BBI != E; ++BBI) { 142 BasicBlock *BB = *BBI; 143 144 // For large loops, avoid use-scanning by using dominance information: In 145 // particular, if a block does not dominate any of the loop exits, then none 146 // of the values defined in the block could be used outside the loop. 147 if (!BlockDominatesAnExit(BB, ExitBlocks, DT)) 148 continue; 149 150 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); 151 I != E; ++I) { 152 // Reject two common cases fast: instructions with no uses (like stores) 153 // and instructions with one use that is in the same block as this. 154 if (I->use_empty() || 155 (I->hasOneUse() && I->use_back()->getParent() == BB && 156 !isa<PHINode>(I->use_back()))) 157 continue; 158 159 MadeChange |= ProcessInstruction(I, ExitBlocks); 160 } 161 } 162 163 assert(L->isLCSSAForm(*DT)); 164 PredCache.clear(); 165 166 return MadeChange; 167 } 168 169 /// isExitBlock - Return true if the specified block is in the list. 170 static bool isExitBlock(BasicBlock *BB, 171 const SmallVectorImpl<BasicBlock*> &ExitBlocks) { 172 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) 173 if (ExitBlocks[i] == BB) 174 return true; 175 return false; 176 } 177 178 /// ProcessInstruction - Given an instruction in the loop, check to see if it 179 /// has any uses that are outside the current loop. If so, insert LCSSA PHI 180 /// nodes and rewrite the uses. 181 bool LCSSA::ProcessInstruction(Instruction *Inst, 182 const SmallVectorImpl<BasicBlock*> &ExitBlocks) { 183 SmallVector<Use*, 16> UsesToRewrite; 184 185 BasicBlock *InstBB = Inst->getParent(); 186 187 for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end(); 188 UI != E; ++UI) { 189 User *U = *UI; 190 BasicBlock *UserBB = cast<Instruction>(U)->getParent(); 191 if (PHINode *PN = dyn_cast<PHINode>(U)) 192 UserBB = PN->getIncomingBlock(UI); 193 194 if (InstBB != UserBB && !inLoop(UserBB)) 195 UsesToRewrite.push_back(&UI.getUse()); 196 } 197 198 // If there are no uses outside the loop, exit with no change. 199 if (UsesToRewrite.empty()) return false; 200 201 ++NumLCSSA; // We are applying the transformation 202 203 // Invoke instructions are special in that their result value is not available 204 // along their unwind edge. The code below tests to see whether DomBB dominates 205 // the value, so adjust DomBB to the normal destination block, which is 206 // effectively where the value is first usable. 207 BasicBlock *DomBB = Inst->getParent(); 208 if (InvokeInst *Inv = dyn_cast<InvokeInst>(Inst)) 209 DomBB = Inv->getNormalDest(); 210 211 DomTreeNode *DomNode = DT->getNode(DomBB); 212 213 SSAUpdater SSAUpdate; 214 SSAUpdate.Initialize(Inst); 215 216 // Insert the LCSSA phi's into all of the exit blocks dominated by the 217 // value, and add them to the Phi's map. 218 for (SmallVectorImpl<BasicBlock*>::const_iterator BBI = ExitBlocks.begin(), 219 BBE = ExitBlocks.end(); BBI != BBE; ++BBI) { 220 BasicBlock *ExitBB = *BBI; 221 if (!DT->dominates(DomNode, DT->getNode(ExitBB))) continue; 222 223 // If we already inserted something for this BB, don't reprocess it. 224 if (SSAUpdate.HasValueForBlock(ExitBB)) continue; 225 226 PHINode *PN = PHINode::Create(Inst->getType(), Inst->getName()+".lcssa", 227 ExitBB->begin()); 228 PN->reserveOperandSpace(PredCache.GetNumPreds(ExitBB)); 229 230 // Add inputs from inside the loop for this PHI. 231 for (BasicBlock **PI = PredCache.GetPreds(ExitBB); *PI; ++PI) { 232 PN->addIncoming(Inst, *PI); 233 234 // If the exit block has a predecessor not within the loop, arrange for 235 // the incoming value use corresponding to that predecessor to be 236 // rewritten in terms of a different LCSSA PHI. 237 if (!inLoop(*PI)) 238 UsesToRewrite.push_back( 239 &PN->getOperandUse( 240 PN->getOperandNumForIncomingValue(PN->getNumIncomingValues()-1))); 241 } 242 243 // Remember that this phi makes the value alive in this block. 244 SSAUpdate.AddAvailableValue(ExitBB, PN); 245 } 246 247 // Rewrite all uses outside the loop in terms of the new PHIs we just 248 // inserted. 249 for (unsigned i = 0, e = UsesToRewrite.size(); i != e; ++i) { 250 // If this use is in an exit block, rewrite to use the newly inserted PHI. 251 // This is required for correctness because SSAUpdate doesn't handle uses in 252 // the same block. It assumes the PHI we inserted is at the end of the 253 // block. 254 Instruction *User = cast<Instruction>(UsesToRewrite[i]->getUser()); 255 BasicBlock *UserBB = User->getParent(); 256 if (PHINode *PN = dyn_cast<PHINode>(User)) 257 UserBB = PN->getIncomingBlock(*UsesToRewrite[i]); 258 259 if (isa<PHINode>(UserBB->begin()) && 260 isExitBlock(UserBB, ExitBlocks)) { 261 UsesToRewrite[i]->set(UserBB->begin()); 262 continue; 263 } 264 265 // Otherwise, do full PHI insertion. 266 SSAUpdate.RewriteUse(*UsesToRewrite[i]); 267 } 268 269 return true; 270 } 271 272