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