1 //===- LoopRotation.cpp - Loop Rotation Pass ------------------------------===// 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 file implements Loop Rotation Pass. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #define DEBUG_TYPE "loop-rotate" 15 #include "llvm/Transforms/Scalar.h" 16 #include "llvm/Function.h" 17 #include "llvm/IntrinsicInst.h" 18 #include "llvm/Analysis/CodeMetrics.h" 19 #include "llvm/Analysis/LoopPass.h" 20 #include "llvm/Analysis/InstructionSimplify.h" 21 #include "llvm/Analysis/ScalarEvolution.h" 22 #include "llvm/Analysis/ValueTracking.h" 23 #include "llvm/Transforms/Utils/Local.h" 24 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 25 #include "llvm/Transforms/Utils/SSAUpdater.h" 26 #include "llvm/Transforms/Utils/ValueMapper.h" 27 #include "llvm/Support/Debug.h" 28 #include "llvm/ADT/Statistic.h" 29 using namespace llvm; 30 31 #define MAX_HEADER_SIZE 16 32 33 STATISTIC(NumRotated, "Number of loops rotated"); 34 namespace { 35 36 class LoopRotate : public LoopPass { 37 public: 38 static char ID; // Pass ID, replacement for typeid 39 LoopRotate() : LoopPass(ID) { 40 initializeLoopRotatePass(*PassRegistry::getPassRegistry()); 41 } 42 43 // LCSSA form makes instruction renaming easier. 44 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 45 AU.addPreserved<DominatorTree>(); 46 AU.addRequired<LoopInfo>(); 47 AU.addPreserved<LoopInfo>(); 48 AU.addRequiredID(LoopSimplifyID); 49 AU.addPreservedID(LoopSimplifyID); 50 AU.addRequiredID(LCSSAID); 51 AU.addPreservedID(LCSSAID); 52 AU.addPreserved<ScalarEvolution>(); 53 } 54 55 bool runOnLoop(Loop *L, LPPassManager &LPM); 56 void simplifyLoopLatch(Loop *L); 57 bool rotateLoop(Loop *L); 58 59 private: 60 LoopInfo *LI; 61 }; 62 } 63 64 char LoopRotate::ID = 0; 65 INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false) 66 INITIALIZE_PASS_DEPENDENCY(LoopInfo) 67 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 68 INITIALIZE_PASS_DEPENDENCY(LCSSA) 69 INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false) 70 71 Pass *llvm::createLoopRotatePass() { return new LoopRotate(); } 72 73 /// Rotate Loop L as many times as possible. Return true if 74 /// the loop is rotated at least once. 75 bool LoopRotate::runOnLoop(Loop *L, LPPassManager &LPM) { 76 LI = &getAnalysis<LoopInfo>(); 77 78 // Simplify the loop latch before attempting to rotate the header 79 // upward. Rotation may not be needed if the loop tail can be folded into the 80 // loop exit. 81 simplifyLoopLatch(L); 82 83 // One loop can be rotated multiple times. 84 bool MadeChange = false; 85 while (rotateLoop(L)) 86 MadeChange = true; 87 88 return MadeChange; 89 } 90 91 /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the 92 /// old header into the preheader. If there were uses of the values produced by 93 /// these instruction that were outside of the loop, we have to insert PHI nodes 94 /// to merge the two values. Do this now. 95 static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader, 96 BasicBlock *OrigPreheader, 97 ValueToValueMapTy &ValueMap) { 98 // Remove PHI node entries that are no longer live. 99 BasicBlock::iterator I, E = OrigHeader->end(); 100 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I) 101 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader)); 102 103 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes 104 // as necessary. 105 SSAUpdater SSA; 106 for (I = OrigHeader->begin(); I != E; ++I) { 107 Value *OrigHeaderVal = I; 108 109 // If there are no uses of the value (e.g. because it returns void), there 110 // is nothing to rewrite. 111 if (OrigHeaderVal->use_empty()) 112 continue; 113 114 Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal]; 115 116 // The value now exits in two versions: the initial value in the preheader 117 // and the loop "next" value in the original header. 118 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName()); 119 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal); 120 SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal); 121 122 // Visit each use of the OrigHeader instruction. 123 for (Value::use_iterator UI = OrigHeaderVal->use_begin(), 124 UE = OrigHeaderVal->use_end(); UI != UE; ) { 125 // Grab the use before incrementing the iterator. 126 Use &U = UI.getUse(); 127 128 // Increment the iterator before removing the use from the list. 129 ++UI; 130 131 // SSAUpdater can't handle a non-PHI use in the same block as an 132 // earlier def. We can easily handle those cases manually. 133 Instruction *UserInst = cast<Instruction>(U.getUser()); 134 if (!isa<PHINode>(UserInst)) { 135 BasicBlock *UserBB = UserInst->getParent(); 136 137 // The original users in the OrigHeader are already using the 138 // original definitions. 139 if (UserBB == OrigHeader) 140 continue; 141 142 // Users in the OrigPreHeader need to use the value to which the 143 // original definitions are mapped. 144 if (UserBB == OrigPreheader) { 145 U = OrigPreHeaderVal; 146 continue; 147 } 148 } 149 150 // Anything else can be handled by SSAUpdater. 151 SSA.RewriteUse(U); 152 } 153 } 154 } 155 156 /// Determine whether the instructions in this range my be safely and cheaply 157 /// speculated. This is not an important enough situation to develop complex 158 /// heuristics. We handle a single arithmetic instruction along with any type 159 /// conversions. 160 static bool shouldSpeculateInstrs(BasicBlock::iterator Begin, 161 BasicBlock::iterator End) { 162 bool seenIncrement = false; 163 for (BasicBlock::iterator I = Begin; I != End; ++I) { 164 165 if (!isSafeToSpeculativelyExecute(I)) 166 return false; 167 168 if (isa<DbgInfoIntrinsic>(I)) 169 continue; 170 171 switch (I->getOpcode()) { 172 default: 173 return false; 174 case Instruction::GetElementPtr: 175 // GEPs are cheap if all indices are constant. 176 if (!cast<GEPOperator>(I)->hasAllConstantIndices()) 177 return false; 178 // fall-thru to increment case 179 case Instruction::Add: 180 case Instruction::Sub: 181 case Instruction::And: 182 case Instruction::Or: 183 case Instruction::Xor: 184 case Instruction::Shl: 185 case Instruction::LShr: 186 case Instruction::AShr: 187 if (seenIncrement) 188 return false; 189 seenIncrement = true; 190 break; 191 case Instruction::Trunc: 192 case Instruction::ZExt: 193 case Instruction::SExt: 194 // ignore type conversions 195 break; 196 } 197 } 198 return true; 199 } 200 201 /// Fold the loop tail into the loop exit by speculating the loop tail 202 /// instructions. Typically, this is a single post-increment. In the case of a 203 /// simple 2-block loop, hoisting the increment can be much better than 204 /// duplicating the entire loop header. In the cast of loops with early exits, 205 /// rotation will not work anyway, but simplifyLoopLatch will put the loop in 206 /// canonical form so downstream passes can handle it. 207 /// 208 /// I don't believe this invalidates SCEV. 209 void LoopRotate::simplifyLoopLatch(Loop *L) { 210 BasicBlock *Latch = L->getLoopLatch(); 211 if (!Latch || Latch->hasAddressTaken()) 212 return; 213 214 BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator()); 215 if (!Jmp || !Jmp->isUnconditional()) 216 return; 217 218 BasicBlock *LastExit = Latch->getSinglePredecessor(); 219 if (!LastExit || !L->isLoopExiting(LastExit)) 220 return; 221 222 BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator()); 223 if (!BI) 224 return; 225 226 if (!shouldSpeculateInstrs(Latch->begin(), Jmp)) 227 return; 228 229 DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into " 230 << LastExit->getName() << "\n"); 231 232 // Hoist the instructions from Latch into LastExit. 233 LastExit->getInstList().splice(BI, Latch->getInstList(), Latch->begin(), Jmp); 234 235 unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1; 236 BasicBlock *Header = Jmp->getSuccessor(0); 237 assert(Header == L->getHeader() && "expected a backward branch"); 238 239 // Remove Latch from the CFG so that LastExit becomes the new Latch. 240 BI->setSuccessor(FallThruPath, Header); 241 Latch->replaceSuccessorsPhiUsesWith(LastExit); 242 Jmp->eraseFromParent(); 243 244 // Nuke the Latch block. 245 assert(Latch->empty() && "unable to evacuate Latch"); 246 LI->removeBlock(Latch); 247 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) 248 DT->eraseNode(Latch); 249 Latch->eraseFromParent(); 250 } 251 252 /// Rotate loop LP. Return true if the loop is rotated. 253 bool LoopRotate::rotateLoop(Loop *L) { 254 // If the loop has only one block then there is not much to rotate. 255 if (L->getBlocks().size() == 1) 256 return false; 257 258 BasicBlock *OrigHeader = L->getHeader(); 259 260 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator()); 261 if (BI == 0 || BI->isUnconditional()) 262 return false; 263 264 // If the loop header is not one of the loop exiting blocks then 265 // either this loop is already rotated or it is not 266 // suitable for loop rotation transformations. 267 if (!L->isLoopExiting(OrigHeader)) 268 return false; 269 270 // Updating PHInodes in loops with multiple exits adds complexity. 271 // Keep it simple, and restrict loop rotation to loops with one exit only. 272 // In future, lift this restriction and support for multiple exits if 273 // required. 274 SmallVector<BasicBlock*, 8> ExitBlocks; 275 L->getExitBlocks(ExitBlocks); 276 if (ExitBlocks.size() > 1) 277 return false; 278 279 // Check size of original header and reject loop if it is very big. 280 { 281 CodeMetrics Metrics; 282 Metrics.analyzeBasicBlock(OrigHeader); 283 if (Metrics.NumInsts > MAX_HEADER_SIZE) 284 return false; 285 } 286 287 // Now, this loop is suitable for rotation. 288 BasicBlock *OrigPreheader = L->getLoopPreheader(); 289 BasicBlock *OrigLatch = L->getLoopLatch(); 290 291 // If the loop could not be converted to canonical form, it must have an 292 // indirectbr in it, just give up. 293 if (OrigPreheader == 0 || OrigLatch == 0) 294 return false; 295 296 // Anything ScalarEvolution may know about this loop or the PHI nodes 297 // in its header will soon be invalidated. 298 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>()) 299 SE->forgetLoop(L); 300 301 // Find new Loop header. NewHeader is a Header's one and only successor 302 // that is inside loop. Header's other successor is outside the 303 // loop. Otherwise loop is not suitable for rotation. 304 BasicBlock *Exit = BI->getSuccessor(0); 305 BasicBlock *NewHeader = BI->getSuccessor(1); 306 if (L->contains(Exit)) 307 std::swap(Exit, NewHeader); 308 assert(NewHeader && "Unable to determine new loop header"); 309 assert(L->contains(NewHeader) && !L->contains(Exit) && 310 "Unable to determine loop header and exit blocks"); 311 312 // This code assumes that the new header has exactly one predecessor. 313 // Remove any single-entry PHI nodes in it. 314 assert(NewHeader->getSinglePredecessor() && 315 "New header doesn't have one pred!"); 316 FoldSingleEntryPHINodes(NewHeader); 317 318 // Begin by walking OrigHeader and populating ValueMap with an entry for 319 // each Instruction. 320 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end(); 321 ValueToValueMapTy ValueMap; 322 323 // For PHI nodes, the value available in OldPreHeader is just the 324 // incoming value from OldPreHeader. 325 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I) 326 ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader); 327 328 // For the rest of the instructions, either hoist to the OrigPreheader if 329 // possible or create a clone in the OldPreHeader if not. 330 TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator(); 331 while (I != E) { 332 Instruction *Inst = I++; 333 334 // If the instruction's operands are invariant and it doesn't read or write 335 // memory, then it is safe to hoist. Doing this doesn't change the order of 336 // execution in the preheader, but does prevent the instruction from 337 // executing in each iteration of the loop. This means it is safe to hoist 338 // something that might trap, but isn't safe to hoist something that reads 339 // memory (without proving that the loop doesn't write). 340 if (L->hasLoopInvariantOperands(Inst) && 341 !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() && 342 !isa<TerminatorInst>(Inst) && !isa<DbgInfoIntrinsic>(Inst) && 343 !isa<AllocaInst>(Inst)) { 344 Inst->moveBefore(LoopEntryBranch); 345 continue; 346 } 347 348 // Otherwise, create a duplicate of the instruction. 349 Instruction *C = Inst->clone(); 350 351 // Eagerly remap the operands of the instruction. 352 RemapInstruction(C, ValueMap, 353 RF_NoModuleLevelChanges|RF_IgnoreMissingEntries); 354 355 // With the operands remapped, see if the instruction constant folds or is 356 // otherwise simplifyable. This commonly occurs because the entry from PHI 357 // nodes allows icmps and other instructions to fold. 358 Value *V = SimplifyInstruction(C); 359 if (V && LI->replacementPreservesLCSSAForm(C, V)) { 360 // If so, then delete the temporary instruction and stick the folded value 361 // in the map. 362 delete C; 363 ValueMap[Inst] = V; 364 } else { 365 // Otherwise, stick the new instruction into the new block! 366 C->setName(Inst->getName()); 367 C->insertBefore(LoopEntryBranch); 368 ValueMap[Inst] = C; 369 } 370 } 371 372 // Along with all the other instructions, we just cloned OrigHeader's 373 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's 374 // successors by duplicating their incoming values for OrigHeader. 375 TerminatorInst *TI = OrigHeader->getTerminator(); 376 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) 377 for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin(); 378 PHINode *PN = dyn_cast<PHINode>(BI); ++BI) 379 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader); 380 381 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove 382 // OrigPreHeader's old terminator (the original branch into the loop), and 383 // remove the corresponding incoming values from the PHI nodes in OrigHeader. 384 LoopEntryBranch->eraseFromParent(); 385 386 // If there were any uses of instructions in the duplicated block outside the 387 // loop, update them, inserting PHI nodes as required 388 RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap); 389 390 // NewHeader is now the header of the loop. 391 L->moveToHeader(NewHeader); 392 assert(L->getHeader() == NewHeader && "Latch block is our new header"); 393 394 395 // At this point, we've finished our major CFG changes. As part of cloning 396 // the loop into the preheader we've simplified instructions and the 397 // duplicated conditional branch may now be branching on a constant. If it is 398 // branching on a constant and if that constant means that we enter the loop, 399 // then we fold away the cond branch to an uncond branch. This simplifies the 400 // loop in cases important for nested loops, and it also means we don't have 401 // to split as many edges. 402 BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator()); 403 assert(PHBI->isConditional() && "Should be clone of BI condbr!"); 404 if (!isa<ConstantInt>(PHBI->getCondition()) || 405 PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero()) 406 != NewHeader) { 407 // The conditional branch can't be folded, handle the general case. 408 // Update DominatorTree to reflect the CFG change we just made. Then split 409 // edges as necessary to preserve LoopSimplify form. 410 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) { 411 // Since OrigPreheader now has the conditional branch to Exit block, it is 412 // the dominator of Exit. 413 DT->changeImmediateDominator(Exit, OrigPreheader); 414 DT->changeImmediateDominator(NewHeader, OrigPreheader); 415 416 // Update OrigHeader to be dominated by the new header block. 417 DT->changeImmediateDominator(OrigHeader, OrigLatch); 418 } 419 420 // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and 421 // thus is not a preheader anymore. Split the edge to form a real preheader. 422 BasicBlock *NewPH = SplitCriticalEdge(OrigPreheader, NewHeader, this); 423 NewPH->setName(NewHeader->getName() + ".lr.ph"); 424 425 // Preserve canonical loop form, which means that 'Exit' should have only one 426 // predecessor. 427 BasicBlock *ExitSplit = SplitCriticalEdge(L->getLoopLatch(), Exit, this); 428 ExitSplit->moveBefore(Exit); 429 } else { 430 // We can fold the conditional branch in the preheader, this makes things 431 // simpler. The first step is to remove the extra edge to the Exit block. 432 Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/); 433 BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI); 434 NewBI->setDebugLoc(PHBI->getDebugLoc()); 435 PHBI->eraseFromParent(); 436 437 // With our CFG finalized, update DomTree if it is available. 438 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) { 439 // Update OrigHeader to be dominated by the new header block. 440 DT->changeImmediateDominator(NewHeader, OrigPreheader); 441 DT->changeImmediateDominator(OrigHeader, OrigLatch); 442 } 443 } 444 445 assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation"); 446 assert(L->getLoopLatch() && "Invalid loop latch after loop rotation"); 447 448 // Now that the CFG and DomTree are in a consistent state again, try to merge 449 // the OrigHeader block into OrigLatch. This will succeed if they are 450 // connected by an unconditional branch. This is just a cleanup so the 451 // emitted code isn't too gross in this common case. 452 MergeBlockIntoPredecessor(OrigHeader, this); 453 454 ++NumRotated; 455 return true; 456 } 457 458