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 #include "llvm/Transforms/Scalar.h" 31 #include "llvm/ADT/STLExtras.h" 32 #include "llvm/ADT/Statistic.h" 33 #include "llvm/Analysis/AliasAnalysis.h" 34 #include "llvm/Analysis/BasicAliasAnalysis.h" 35 #include "llvm/Analysis/GlobalsModRef.h" 36 #include "llvm/Analysis/LoopPass.h" 37 #include "llvm/Analysis/ScalarEvolution.h" 38 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 39 #include "llvm/IR/Constants.h" 40 #include "llvm/IR/Dominators.h" 41 #include "llvm/IR/Function.h" 42 #include "llvm/IR/Instructions.h" 43 #include "llvm/IR/PredIteratorCache.h" 44 #include "llvm/Pass.h" 45 #include "llvm/Transforms/Utils/LoopUtils.h" 46 #include "llvm/Transforms/Utils/SSAUpdater.h" 47 using namespace llvm; 48 49 #define DEBUG_TYPE "lcssa" 50 51 STATISTIC(NumLCSSA, "Number of live out of a loop variables"); 52 53 /// Return true if the specified block is in the list. 54 static bool isExitBlock(BasicBlock *BB, 55 const SmallVectorImpl<BasicBlock *> &ExitBlocks) { 56 return llvm::any_of(ExitBlocks, [&](BasicBlock *EB) { return EB == BB; }); 57 } 58 59 /// Given an instruction in the loop, check to see if it has any uses that are 60 /// outside the current loop. If so, insert LCSSA PHI nodes and rewrite the 61 /// uses. 62 static bool processInstruction(Loop &L, Instruction &Inst, DominatorTree &DT, 63 const SmallVectorImpl<BasicBlock *> &ExitBlocks, 64 PredIteratorCache &PredCache, LoopInfo *LI) { 65 SmallVector<Use *, 16> UsesToRewrite; 66 67 // Tokens cannot be used in PHI nodes, so we skip over them. 68 // We can run into tokens which are live out of a loop with catchswitch 69 // instructions in Windows EH if the catchswitch has one catchpad which 70 // is inside the loop and another which is not. 71 if (Inst.getType()->isTokenTy()) 72 return false; 73 74 BasicBlock *InstBB = Inst.getParent(); 75 76 for (Use &U : Inst.uses()) { 77 Instruction *User = cast<Instruction>(U.getUser()); 78 BasicBlock *UserBB = User->getParent(); 79 if (PHINode *PN = dyn_cast<PHINode>(User)) 80 UserBB = PN->getIncomingBlock(U); 81 82 if (InstBB != UserBB && !L.contains(UserBB)) 83 UsesToRewrite.push_back(&U); 84 } 85 86 // If there are no uses outside the loop, exit with no change. 87 if (UsesToRewrite.empty()) 88 return false; 89 90 ++NumLCSSA; // We are applying the transformation 91 92 // Invoke instructions are special in that their result value is not available 93 // along their unwind edge. The code below tests to see whether DomBB 94 // dominates the value, so adjust DomBB to the normal destination block, 95 // which is effectively where the value is first usable. 96 BasicBlock *DomBB = Inst.getParent(); 97 if (InvokeInst *Inv = dyn_cast<InvokeInst>(&Inst)) 98 DomBB = Inv->getNormalDest(); 99 100 DomTreeNode *DomNode = DT.getNode(DomBB); 101 102 SmallVector<PHINode *, 16> AddedPHIs; 103 SmallVector<PHINode *, 8> PostProcessPHIs; 104 105 SSAUpdater SSAUpdate; 106 SSAUpdate.Initialize(Inst.getType(), Inst.getName()); 107 108 // Insert the LCSSA phi's into all of the exit blocks dominated by the 109 // value, and add them to the Phi's map. 110 for (BasicBlock *ExitBB : ExitBlocks) { 111 if (!DT.dominates(DomNode, DT.getNode(ExitBB))) 112 continue; 113 114 // If we already inserted something for this BB, don't reprocess it. 115 if (SSAUpdate.HasValueForBlock(ExitBB)) 116 continue; 117 118 PHINode *PN = PHINode::Create(Inst.getType(), PredCache.size(ExitBB), 119 Inst.getName() + ".lcssa", &ExitBB->front()); 120 121 // Add inputs from inside the loop for this PHI. 122 for (BasicBlock *Pred : PredCache.get(ExitBB)) { 123 PN->addIncoming(&Inst, Pred); 124 125 // If the exit block has a predecessor not within the loop, arrange for 126 // the incoming value use corresponding to that predecessor to be 127 // rewritten in terms of a different LCSSA PHI. 128 if (!L.contains(Pred)) 129 UsesToRewrite.push_back( 130 &PN->getOperandUse(PN->getOperandNumForIncomingValue( 131 PN->getNumIncomingValues() - 1))); 132 } 133 134 AddedPHIs.push_back(PN); 135 136 // Remember that this phi makes the value alive in this block. 137 SSAUpdate.AddAvailableValue(ExitBB, PN); 138 139 // LoopSimplify might fail to simplify some loops (e.g. when indirect 140 // branches are involved). In such situations, it might happen that an exit 141 // for Loop L1 is the header of a disjoint Loop L2. Thus, when we create 142 // PHIs in such an exit block, we are also inserting PHIs into L2's header. 143 // This could break LCSSA form for L2 because these inserted PHIs can also 144 // have uses outside of L2. Remember all PHIs in such situation as to 145 // revisit than later on. FIXME: Remove this if indirectbr support into 146 // LoopSimplify gets improved. 147 if (auto *OtherLoop = LI->getLoopFor(ExitBB)) 148 if (!L.contains(OtherLoop)) 149 PostProcessPHIs.push_back(PN); 150 } 151 152 // Rewrite all uses outside the loop in terms of the new PHIs we just 153 // inserted. 154 for (Use *UseToRewrite : UsesToRewrite) { 155 // If this use is in an exit block, rewrite to use the newly inserted PHI. 156 // This is required for correctness because SSAUpdate doesn't handle uses in 157 // the same block. It assumes the PHI we inserted is at the end of the 158 // block. 159 Instruction *User = cast<Instruction>(UseToRewrite->getUser()); 160 BasicBlock *UserBB = User->getParent(); 161 if (PHINode *PN = dyn_cast<PHINode>(User)) 162 UserBB = PN->getIncomingBlock(*UseToRewrite); 163 164 if (isa<PHINode>(UserBB->begin()) && isExitBlock(UserBB, ExitBlocks)) { 165 // Tell the VHs that the uses changed. This updates SCEV's caches. 166 if (UseToRewrite->get()->hasValueHandle()) 167 ValueHandleBase::ValueIsRAUWd(*UseToRewrite, &UserBB->front()); 168 UseToRewrite->set(&UserBB->front()); 169 continue; 170 } 171 172 // Otherwise, do full PHI insertion. 173 SSAUpdate.RewriteUse(*UseToRewrite); 174 } 175 176 // Post process PHI instructions that were inserted into another disjoint loop 177 // and update their exits properly. 178 for (auto *I : PostProcessPHIs) { 179 if (I->use_empty()) 180 continue; 181 182 BasicBlock *PHIBB = I->getParent(); 183 Loop *OtherLoop = LI->getLoopFor(PHIBB); 184 SmallVector<BasicBlock *, 8> EBs; 185 OtherLoop->getExitBlocks(EBs); 186 if (EBs.empty()) 187 continue; 188 189 // Recurse and re-process each PHI instruction. FIXME: we should really 190 // convert this entire thing to a worklist approach where we process a 191 // vector of instructions... 192 processInstruction(*OtherLoop, *I, DT, EBs, PredCache, LI); 193 } 194 195 // Remove PHI nodes that did not have any uses rewritten. 196 for (PHINode *PN : AddedPHIs) 197 if (PN->use_empty()) 198 PN->eraseFromParent(); 199 200 return true; 201 } 202 203 /// Return true if the specified block dominates at least 204 /// one of the blocks in the specified list. 205 static bool 206 blockDominatesAnExit(BasicBlock *BB, 207 DominatorTree &DT, 208 const SmallVectorImpl<BasicBlock *> &ExitBlocks) { 209 DomTreeNode *DomNode = DT.getNode(BB); 210 return llvm::any_of(ExitBlocks, [&](BasicBlock * EB) { 211 return DT.dominates(DomNode, DT.getNode(EB)); 212 }); 213 } 214 215 bool llvm::formLCSSA(Loop &L, DominatorTree &DT, LoopInfo *LI, 216 ScalarEvolution *SE) { 217 bool Changed = false; 218 219 // Get the set of exiting blocks. 220 SmallVector<BasicBlock *, 8> ExitBlocks; 221 L.getExitBlocks(ExitBlocks); 222 223 if (ExitBlocks.empty()) 224 return false; 225 226 PredIteratorCache PredCache; 227 228 // Look at all the instructions in the loop, checking to see if they have uses 229 // outside the loop. If so, rewrite those uses. 230 for (BasicBlock *BB : L.blocks()) { 231 // For large loops, avoid use-scanning by using dominance information: In 232 // particular, if a block does not dominate any of the loop exits, then none 233 // of the values defined in the block could be used outside the loop. 234 if (!blockDominatesAnExit(BB, DT, ExitBlocks)) 235 continue; 236 237 for (Instruction &I : *BB) { 238 // Reject two common cases fast: instructions with no uses (like stores) 239 // and instructions with one use that is in the same block as this. 240 if (I.use_empty() || 241 (I.hasOneUse() && I.user_back()->getParent() == BB && 242 !isa<PHINode>(I.user_back()))) 243 continue; 244 245 Changed |= processInstruction(L, I, DT, ExitBlocks, PredCache, LI); 246 } 247 } 248 249 // If we modified the code, remove any caches about the loop from SCEV to 250 // avoid dangling entries. 251 // FIXME: This is a big hammer, can we clear the cache more selectively? 252 if (SE && Changed) 253 SE->forgetLoop(&L); 254 255 assert(L.isLCSSAForm(DT)); 256 257 return Changed; 258 } 259 260 /// Process a loop nest depth first. 261 bool llvm::formLCSSARecursively(Loop &L, DominatorTree &DT, LoopInfo *LI, 262 ScalarEvolution *SE) { 263 bool Changed = false; 264 265 // Recurse depth-first through inner loops. 266 for (Loop *SubLoop : L.getSubLoops()) 267 Changed |= formLCSSARecursively(*SubLoop, DT, LI, SE); 268 269 Changed |= formLCSSA(L, DT, LI, SE); 270 return Changed; 271 } 272 273 namespace { 274 struct LCSSA : public FunctionPass { 275 static char ID; // Pass identification, replacement for typeid 276 LCSSA() : FunctionPass(ID) { 277 initializeLCSSAPass(*PassRegistry::getPassRegistry()); 278 } 279 280 // Cached analysis information for the current function. 281 DominatorTree *DT; 282 LoopInfo *LI; 283 ScalarEvolution *SE; 284 285 bool runOnFunction(Function &F) override; 286 287 /// This transformation requires natural loop information & requires that 288 /// loop preheaders be inserted into the CFG. It maintains both of these, 289 /// as well as the CFG. It also requires dominator information. 290 void getAnalysisUsage(AnalysisUsage &AU) const override { 291 AU.setPreservesCFG(); 292 293 AU.addRequired<DominatorTreeWrapperPass>(); 294 AU.addRequired<LoopInfoWrapperPass>(); 295 AU.addPreservedID(LoopSimplifyID); 296 AU.addPreserved<AAResultsWrapperPass>(); 297 AU.addPreserved<BasicAAWrapperPass>(); 298 AU.addPreserved<GlobalsAAWrapperPass>(); 299 AU.addPreserved<ScalarEvolutionWrapperPass>(); 300 AU.addPreserved<SCEVAAWrapperPass>(); 301 } 302 }; 303 } 304 305 char LCSSA::ID = 0; 306 INITIALIZE_PASS_BEGIN(LCSSA, "lcssa", "Loop-Closed SSA Form Pass", false, false) 307 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 308 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 309 INITIALIZE_PASS_END(LCSSA, "lcssa", "Loop-Closed SSA Form Pass", false, false) 310 311 Pass *llvm::createLCSSAPass() { return new LCSSA(); } 312 char &llvm::LCSSAID = LCSSA::ID; 313 314 315 /// Process all loops in the function, inner-most out. 316 bool LCSSA::runOnFunction(Function &F) { 317 bool Changed = false; 318 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 319 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 320 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>(); 321 SE = SEWP ? &SEWP->getSE() : nullptr; 322 323 // Simplify each loop nest in the function. 324 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) 325 Changed |= formLCSSARecursively(**I, *DT, LI, SE); 326 327 return Changed; 328 } 329 330