1 //===-- UnrollLoop.cpp - Loop unrolling utilities -------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements some loop unrolling utilities. It does not define any 10 // actual pass or policy, but provides a single function to perform loop 11 // unrolling. 12 // 13 // The process of unrolling can produce extraneous basic blocks linked with 14 // unconditional branches. This will be corrected in the future. 15 // 16 //===----------------------------------------------------------------------===// 17 18 #include "llvm/ADT/SmallPtrSet.h" 19 #include "llvm/ADT/Statistic.h" 20 #include "llvm/Analysis/AssumptionCache.h" 21 #include "llvm/Analysis/InstructionSimplify.h" 22 #include "llvm/Analysis/LoopIterator.h" 23 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 24 #include "llvm/Analysis/ScalarEvolution.h" 25 #include "llvm/IR/BasicBlock.h" 26 #include "llvm/IR/DataLayout.h" 27 #include "llvm/IR/DebugInfoMetadata.h" 28 #include "llvm/IR/Dominators.h" 29 #include "llvm/IR/IntrinsicInst.h" 30 #include "llvm/IR/LLVMContext.h" 31 #include "llvm/Support/CommandLine.h" 32 #include "llvm/Support/Debug.h" 33 #include "llvm/Support/raw_ostream.h" 34 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 35 #include "llvm/Transforms/Utils/Cloning.h" 36 #include "llvm/Transforms/Utils/Local.h" 37 #include "llvm/Transforms/Utils/LoopSimplify.h" 38 #include "llvm/Transforms/Utils/LoopUtils.h" 39 #include "llvm/Transforms/Utils/SimplifyIndVar.h" 40 #include "llvm/Transforms/Utils/UnrollLoop.h" 41 using namespace llvm; 42 43 #define DEBUG_TYPE "loop-unroll" 44 45 // TODO: Should these be here or in LoopUnroll? 46 STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled"); 47 STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)"); 48 STATISTIC(NumUnrolledWithHeader, "Number of loops unrolled without a " 49 "conditional latch (completely or otherwise)"); 50 51 static cl::opt<bool> 52 UnrollRuntimeEpilog("unroll-runtime-epilog", cl::init(false), cl::Hidden, 53 cl::desc("Allow runtime unrolled loops to be unrolled " 54 "with epilog instead of prolog.")); 55 56 static cl::opt<bool> 57 UnrollVerifyDomtree("unroll-verify-domtree", cl::Hidden, 58 cl::desc("Verify domtree after unrolling"), 59 #ifdef EXPENSIVE_CHECKS 60 cl::init(true) 61 #else 62 cl::init(false) 63 #endif 64 ); 65 66 /// Convert the instruction operands from referencing the current values into 67 /// those specified by VMap. 68 void llvm::remapInstruction(Instruction *I, ValueToValueMapTy &VMap) { 69 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) { 70 Value *Op = I->getOperand(op); 71 72 // Unwrap arguments of dbg.value intrinsics. 73 bool Wrapped = false; 74 if (auto *V = dyn_cast<MetadataAsValue>(Op)) 75 if (auto *Unwrapped = dyn_cast<ValueAsMetadata>(V->getMetadata())) { 76 Op = Unwrapped->getValue(); 77 Wrapped = true; 78 } 79 80 auto wrap = [&](Value *V) { 81 auto &C = I->getContext(); 82 return Wrapped ? MetadataAsValue::get(C, ValueAsMetadata::get(V)) : V; 83 }; 84 85 ValueToValueMapTy::iterator It = VMap.find(Op); 86 if (It != VMap.end()) 87 I->setOperand(op, wrap(It->second)); 88 } 89 90 if (PHINode *PN = dyn_cast<PHINode>(I)) { 91 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 92 ValueToValueMapTy::iterator It = VMap.find(PN->getIncomingBlock(i)); 93 if (It != VMap.end()) 94 PN->setIncomingBlock(i, cast<BasicBlock>(It->second)); 95 } 96 } 97 } 98 99 /// Check if unrolling created a situation where we need to insert phi nodes to 100 /// preserve LCSSA form. 101 /// \param Blocks is a vector of basic blocks representing unrolled loop. 102 /// \param L is the outer loop. 103 /// It's possible that some of the blocks are in L, and some are not. In this 104 /// case, if there is a use is outside L, and definition is inside L, we need to 105 /// insert a phi-node, otherwise LCSSA will be broken. 106 /// The function is just a helper function for llvm::UnrollLoop that returns 107 /// true if this situation occurs, indicating that LCSSA needs to be fixed. 108 static bool needToInsertPhisForLCSSA(Loop *L, std::vector<BasicBlock *> Blocks, 109 LoopInfo *LI) { 110 for (BasicBlock *BB : Blocks) { 111 if (LI->getLoopFor(BB) == L) 112 continue; 113 for (Instruction &I : *BB) { 114 for (Use &U : I.operands()) { 115 if (auto Def = dyn_cast<Instruction>(U)) { 116 Loop *DefLoop = LI->getLoopFor(Def->getParent()); 117 if (!DefLoop) 118 continue; 119 if (DefLoop->contains(L)) 120 return true; 121 } 122 } 123 } 124 } 125 return false; 126 } 127 128 /// Adds ClonedBB to LoopInfo, creates a new loop for ClonedBB if necessary 129 /// and adds a mapping from the original loop to the new loop to NewLoops. 130 /// Returns nullptr if no new loop was created and a pointer to the 131 /// original loop OriginalBB was part of otherwise. 132 const Loop* llvm::addClonedBlockToLoopInfo(BasicBlock *OriginalBB, 133 BasicBlock *ClonedBB, LoopInfo *LI, 134 NewLoopsMap &NewLoops) { 135 // Figure out which loop New is in. 136 const Loop *OldLoop = LI->getLoopFor(OriginalBB); 137 assert(OldLoop && "Should (at least) be in the loop being unrolled!"); 138 139 Loop *&NewLoop = NewLoops[OldLoop]; 140 if (!NewLoop) { 141 // Found a new sub-loop. 142 assert(OriginalBB == OldLoop->getHeader() && 143 "Header should be first in RPO"); 144 145 NewLoop = LI->AllocateLoop(); 146 Loop *NewLoopParent = NewLoops.lookup(OldLoop->getParentLoop()); 147 148 if (NewLoopParent) 149 NewLoopParent->addChildLoop(NewLoop); 150 else 151 LI->addTopLevelLoop(NewLoop); 152 153 NewLoop->addBasicBlockToLoop(ClonedBB, *LI); 154 return OldLoop; 155 } else { 156 NewLoop->addBasicBlockToLoop(ClonedBB, *LI); 157 return nullptr; 158 } 159 } 160 161 /// The function chooses which type of unroll (epilog or prolog) is more 162 /// profitabale. 163 /// Epilog unroll is more profitable when there is PHI that starts from 164 /// constant. In this case epilog will leave PHI start from constant, 165 /// but prolog will convert it to non-constant. 166 /// 167 /// loop: 168 /// PN = PHI [I, Latch], [CI, PreHeader] 169 /// I = foo(PN) 170 /// ... 171 /// 172 /// Epilog unroll case. 173 /// loop: 174 /// PN = PHI [I2, Latch], [CI, PreHeader] 175 /// I1 = foo(PN) 176 /// I2 = foo(I1) 177 /// ... 178 /// Prolog unroll case. 179 /// NewPN = PHI [PrologI, Prolog], [CI, PreHeader] 180 /// loop: 181 /// PN = PHI [I2, Latch], [NewPN, PreHeader] 182 /// I1 = foo(PN) 183 /// I2 = foo(I1) 184 /// ... 185 /// 186 static bool isEpilogProfitable(Loop *L) { 187 BasicBlock *PreHeader = L->getLoopPreheader(); 188 BasicBlock *Header = L->getHeader(); 189 assert(PreHeader && Header); 190 for (const PHINode &PN : Header->phis()) { 191 if (isa<ConstantInt>(PN.getIncomingValueForBlock(PreHeader))) 192 return true; 193 } 194 return false; 195 } 196 197 /// Perform some cleanup and simplifications on loops after unrolling. It is 198 /// useful to simplify the IV's in the new loop, as well as do a quick 199 /// simplify/dce pass of the instructions. 200 void llvm::simplifyLoopAfterUnroll(Loop *L, bool SimplifyIVs, LoopInfo *LI, 201 ScalarEvolution *SE, DominatorTree *DT, 202 AssumptionCache *AC) { 203 // Simplify any new induction variables in the partially unrolled loop. 204 if (SE && SimplifyIVs) { 205 SmallVector<WeakTrackingVH, 16> DeadInsts; 206 simplifyLoopIVs(L, SE, DT, LI, DeadInsts); 207 208 // Aggressively clean up dead instructions that simplifyLoopIVs already 209 // identified. Any remaining should be cleaned up below. 210 while (!DeadInsts.empty()) 211 if (Instruction *Inst = 212 dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val())) 213 RecursivelyDeleteTriviallyDeadInstructions(Inst); 214 } 215 216 // At this point, the code is well formed. We now do a quick sweep over the 217 // inserted code, doing constant propagation and dead code elimination as we 218 // go. 219 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout(); 220 for (BasicBlock *BB : L->getBlocks()) { 221 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) { 222 Instruction *Inst = &*I++; 223 224 if (Value *V = SimplifyInstruction(Inst, {DL, nullptr, DT, AC})) 225 if (LI->replacementPreservesLCSSAForm(Inst, V)) 226 Inst->replaceAllUsesWith(V); 227 if (isInstructionTriviallyDead(Inst)) 228 BB->getInstList().erase(Inst); 229 } 230 } 231 232 // TODO: after peeling or unrolling, previously loop variant conditions are 233 // likely to fold to constants, eagerly propagating those here will require 234 // fewer cleanup passes to be run. Alternatively, a LoopEarlyCSE might be 235 // appropriate. 236 } 237 238 /// Unroll the given loop by Count. The loop must be in LCSSA form. Unrolling 239 /// can only fail when the loop's latch block is not terminated by a conditional 240 /// branch instruction. However, if the trip count (and multiple) are not known, 241 /// loop unrolling will mostly produce more code that is no faster. 242 /// 243 /// TripCount is the upper bound of the iteration on which control exits 244 /// LatchBlock. Control may exit the loop prior to TripCount iterations either 245 /// via an early branch in other loop block or via LatchBlock terminator. This 246 /// is relaxed from the general definition of trip count which is the number of 247 /// times the loop header executes. Note that UnrollLoop assumes that the loop 248 /// counter test is in LatchBlock in order to remove unnecesssary instances of 249 /// the test. If control can exit the loop from the LatchBlock's terminator 250 /// prior to TripCount iterations, flag PreserveCondBr needs to be set. 251 /// 252 /// PreserveCondBr indicates whether the conditional branch of the LatchBlock 253 /// needs to be preserved. It is needed when we use trip count upper bound to 254 /// fully unroll the loop. If PreserveOnlyFirst is also set then only the first 255 /// conditional branch needs to be preserved. 256 /// 257 /// Similarly, TripMultiple divides the number of times that the LatchBlock may 258 /// execute without exiting the loop. 259 /// 260 /// If AllowRuntime is true then UnrollLoop will consider unrolling loops that 261 /// have a runtime (i.e. not compile time constant) trip count. Unrolling these 262 /// loops require a unroll "prologue" that runs "RuntimeTripCount % Count" 263 /// iterations before branching into the unrolled loop. UnrollLoop will not 264 /// runtime-unroll the loop if computing RuntimeTripCount will be expensive and 265 /// AllowExpensiveTripCount is false. 266 /// 267 /// If we want to perform PGO-based loop peeling, PeelCount is set to the 268 /// number of iterations we want to peel off. 269 /// 270 /// The LoopInfo Analysis that is passed will be kept consistent. 271 /// 272 /// This utility preserves LoopInfo. It will also preserve ScalarEvolution and 273 /// DominatorTree if they are non-null. 274 /// 275 /// If RemainderLoop is non-null, it will receive the remainder loop (if 276 /// required and not fully unrolled). 277 LoopUnrollResult llvm::UnrollLoop(Loop *L, UnrollLoopOptions ULO, LoopInfo *LI, 278 ScalarEvolution *SE, DominatorTree *DT, 279 AssumptionCache *AC, 280 OptimizationRemarkEmitter *ORE, 281 bool PreserveLCSSA, Loop **RemainderLoop) { 282 283 BasicBlock *Preheader = L->getLoopPreheader(); 284 if (!Preheader) { 285 LLVM_DEBUG(dbgs() << " Can't unroll; loop preheader-insertion failed.\n"); 286 return LoopUnrollResult::Unmodified; 287 } 288 289 BasicBlock *LatchBlock = L->getLoopLatch(); 290 if (!LatchBlock) { 291 LLVM_DEBUG(dbgs() << " Can't unroll; loop exit-block-insertion failed.\n"); 292 return LoopUnrollResult::Unmodified; 293 } 294 295 // Loops with indirectbr cannot be cloned. 296 if (!L->isSafeToClone()) { 297 LLVM_DEBUG(dbgs() << " Can't unroll; Loop body cannot be cloned.\n"); 298 return LoopUnrollResult::Unmodified; 299 } 300 301 // The current loop unroll pass can unroll loops with a single latch or header 302 // that's a conditional branch exiting the loop. 303 // FIXME: The implementation can be extended to work with more complicated 304 // cases, e.g. loops with multiple latches. 305 BasicBlock *Header = L->getHeader(); 306 BranchInst *HeaderBI = dyn_cast<BranchInst>(Header->getTerminator()); 307 BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator()); 308 309 // FIXME: Support loops without conditional latch and multiple exiting blocks. 310 if (!BI || 311 (BI->isUnconditional() && (!HeaderBI || HeaderBI->isUnconditional() || 312 L->getExitingBlock() != Header))) { 313 LLVM_DEBUG(dbgs() << " Can't unroll; loop not terminated by a conditional " 314 "branch in the latch or header.\n"); 315 return LoopUnrollResult::Unmodified; 316 } 317 318 auto CheckLatchSuccessors = [&](unsigned S1, unsigned S2) { 319 return BI->isConditional() && BI->getSuccessor(S1) == Header && 320 !L->contains(BI->getSuccessor(S2)); 321 }; 322 323 // If we have a conditional latch, it must exit the loop. 324 if (BI && BI->isConditional() && !CheckLatchSuccessors(0, 1) && 325 !CheckLatchSuccessors(1, 0)) { 326 LLVM_DEBUG( 327 dbgs() << "Can't unroll; a conditional latch must exit the loop"); 328 return LoopUnrollResult::Unmodified; 329 } 330 331 auto CheckHeaderSuccessors = [&](unsigned S1, unsigned S2) { 332 return HeaderBI && HeaderBI->isConditional() && 333 L->contains(HeaderBI->getSuccessor(S1)) && 334 !L->contains(HeaderBI->getSuccessor(S2)); 335 }; 336 337 // If we do not have a conditional latch, the header must exit the loop. 338 if (BI && !BI->isConditional() && HeaderBI && HeaderBI->isConditional() && 339 !CheckHeaderSuccessors(0, 1) && !CheckHeaderSuccessors(1, 0)) { 340 LLVM_DEBUG(dbgs() << "Can't unroll; conditional header must exit the loop"); 341 return LoopUnrollResult::Unmodified; 342 } 343 344 if (Header->hasAddressTaken()) { 345 // The loop-rotate pass can be helpful to avoid this in many cases. 346 LLVM_DEBUG( 347 dbgs() << " Won't unroll loop: address of header block is taken.\n"); 348 return LoopUnrollResult::Unmodified; 349 } 350 351 if (ULO.TripCount != 0) 352 LLVM_DEBUG(dbgs() << " Trip Count = " << ULO.TripCount << "\n"); 353 if (ULO.TripMultiple != 1) 354 LLVM_DEBUG(dbgs() << " Trip Multiple = " << ULO.TripMultiple << "\n"); 355 356 // Effectively "DCE" unrolled iterations that are beyond the tripcount 357 // and will never be executed. 358 if (ULO.TripCount != 0 && ULO.Count > ULO.TripCount) 359 ULO.Count = ULO.TripCount; 360 361 // Don't enter the unroll code if there is nothing to do. 362 if (ULO.TripCount == 0 && ULO.Count < 2 && ULO.PeelCount == 0) { 363 LLVM_DEBUG(dbgs() << "Won't unroll; almost nothing to do\n"); 364 return LoopUnrollResult::Unmodified; 365 } 366 367 assert(ULO.Count > 0); 368 assert(ULO.TripMultiple > 0); 369 assert(ULO.TripCount == 0 || ULO.TripCount % ULO.TripMultiple == 0); 370 371 // Are we eliminating the loop control altogether? 372 bool CompletelyUnroll = ULO.Count == ULO.TripCount; 373 SmallVector<BasicBlock *, 4> ExitBlocks; 374 L->getExitBlocks(ExitBlocks); 375 std::vector<BasicBlock*> OriginalLoopBlocks = L->getBlocks(); 376 377 // Go through all exits of L and see if there are any phi-nodes there. We just 378 // conservatively assume that they're inserted to preserve LCSSA form, which 379 // means that complete unrolling might break this form. We need to either fix 380 // it in-place after the transformation, or entirely rebuild LCSSA. TODO: For 381 // now we just recompute LCSSA for the outer loop, but it should be possible 382 // to fix it in-place. 383 bool NeedToFixLCSSA = PreserveLCSSA && CompletelyUnroll && 384 any_of(ExitBlocks, [](const BasicBlock *BB) { 385 return isa<PHINode>(BB->begin()); 386 }); 387 388 // We assume a run-time trip count if the compiler cannot 389 // figure out the loop trip count and the unroll-runtime 390 // flag is specified. 391 bool RuntimeTripCount = 392 (ULO.TripCount == 0 && ULO.Count > 0 && ULO.AllowRuntime); 393 394 assert((!RuntimeTripCount || !ULO.PeelCount) && 395 "Did not expect runtime trip-count unrolling " 396 "and peeling for the same loop"); 397 398 bool Peeled = false; 399 if (ULO.PeelCount) { 400 Peeled = peelLoop(L, ULO.PeelCount, LI, SE, DT, AC, PreserveLCSSA); 401 402 // Successful peeling may result in a change in the loop preheader/trip 403 // counts. If we later unroll the loop, we want these to be updated. 404 if (Peeled) { 405 // According to our guards and profitability checks the only 406 // meaningful exit should be latch block. Other exits go to deopt, 407 // so we do not worry about them. 408 BasicBlock *ExitingBlock = L->getLoopLatch(); 409 assert(ExitingBlock && "Loop without exiting block?"); 410 assert(L->isLoopExiting(ExitingBlock) && "Latch is not exiting?"); 411 Preheader = L->getLoopPreheader(); 412 ULO.TripCount = SE->getSmallConstantTripCount(L, ExitingBlock); 413 ULO.TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock); 414 } 415 } 416 417 // Loops containing convergent instructions must have a count that divides 418 // their TripMultiple. 419 LLVM_DEBUG( 420 { 421 bool HasConvergent = false; 422 for (auto &BB : L->blocks()) 423 for (auto &I : *BB) 424 if (auto CS = CallSite(&I)) 425 HasConvergent |= CS.isConvergent(); 426 assert((!HasConvergent || ULO.TripMultiple % ULO.Count == 0) && 427 "Unroll count must divide trip multiple if loop contains a " 428 "convergent operation."); 429 }); 430 431 bool EpilogProfitability = 432 UnrollRuntimeEpilog.getNumOccurrences() ? UnrollRuntimeEpilog 433 : isEpilogProfitable(L); 434 435 if (RuntimeTripCount && ULO.TripMultiple % ULO.Count != 0 && 436 !UnrollRuntimeLoopRemainder(L, ULO.Count, ULO.AllowExpensiveTripCount, 437 EpilogProfitability, ULO.UnrollRemainder, 438 ULO.ForgetAllSCEV, LI, SE, DT, AC, 439 PreserveLCSSA, RemainderLoop)) { 440 if (ULO.Force) 441 RuntimeTripCount = false; 442 else { 443 LLVM_DEBUG(dbgs() << "Won't unroll; remainder loop could not be " 444 "generated when assuming runtime trip count\n"); 445 return LoopUnrollResult::Unmodified; 446 } 447 } 448 449 // If we know the trip count, we know the multiple... 450 unsigned BreakoutTrip = 0; 451 if (ULO.TripCount != 0) { 452 BreakoutTrip = ULO.TripCount % ULO.Count; 453 ULO.TripMultiple = 0; 454 } else { 455 // Figure out what multiple to use. 456 BreakoutTrip = ULO.TripMultiple = 457 (unsigned)GreatestCommonDivisor64(ULO.Count, ULO.TripMultiple); 458 } 459 460 using namespace ore; 461 // Report the unrolling decision. 462 if (CompletelyUnroll) { 463 LLVM_DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName() 464 << " with trip count " << ULO.TripCount << "!\n"); 465 if (ORE) 466 ORE->emit([&]() { 467 return OptimizationRemark(DEBUG_TYPE, "FullyUnrolled", L->getStartLoc(), 468 L->getHeader()) 469 << "completely unrolled loop with " 470 << NV("UnrollCount", ULO.TripCount) << " iterations"; 471 }); 472 } else if (ULO.PeelCount) { 473 LLVM_DEBUG(dbgs() << "PEELING loop %" << Header->getName() 474 << " with iteration count " << ULO.PeelCount << "!\n"); 475 if (ORE) 476 ORE->emit([&]() { 477 return OptimizationRemark(DEBUG_TYPE, "Peeled", L->getStartLoc(), 478 L->getHeader()) 479 << " peeled loop by " << NV("PeelCount", ULO.PeelCount) 480 << " iterations"; 481 }); 482 } else { 483 auto DiagBuilder = [&]() { 484 OptimizationRemark Diag(DEBUG_TYPE, "PartialUnrolled", L->getStartLoc(), 485 L->getHeader()); 486 return Diag << "unrolled loop by a factor of " 487 << NV("UnrollCount", ULO.Count); 488 }; 489 490 LLVM_DEBUG(dbgs() << "UNROLLING loop %" << Header->getName() << " by " 491 << ULO.Count); 492 if (ULO.TripMultiple == 0 || BreakoutTrip != ULO.TripMultiple) { 493 LLVM_DEBUG(dbgs() << " with a breakout at trip " << BreakoutTrip); 494 if (ORE) 495 ORE->emit([&]() { 496 return DiagBuilder() << " with a breakout at trip " 497 << NV("BreakoutTrip", BreakoutTrip); 498 }); 499 } else if (ULO.TripMultiple != 1) { 500 LLVM_DEBUG(dbgs() << " with " << ULO.TripMultiple << " trips per branch"); 501 if (ORE) 502 ORE->emit([&]() { 503 return DiagBuilder() 504 << " with " << NV("TripMultiple", ULO.TripMultiple) 505 << " trips per branch"; 506 }); 507 } else if (RuntimeTripCount) { 508 LLVM_DEBUG(dbgs() << " with run-time trip count"); 509 if (ORE) 510 ORE->emit( 511 [&]() { return DiagBuilder() << " with run-time trip count"; }); 512 } 513 LLVM_DEBUG(dbgs() << "!\n"); 514 } 515 516 // We are going to make changes to this loop. SCEV may be keeping cached info 517 // about it, in particular about backedge taken count. The changes we make 518 // are guaranteed to invalidate this information for our loop. It is tempting 519 // to only invalidate the loop being unrolled, but it is incorrect as long as 520 // all exiting branches from all inner loops have impact on the outer loops, 521 // and if something changes inside them then any of outer loops may also 522 // change. When we forget outermost loop, we also forget all contained loops 523 // and this is what we need here. 524 if (SE) { 525 if (ULO.ForgetAllSCEV) 526 SE->forgetAllLoops(); 527 else 528 SE->forgetTopmostLoop(L); 529 } 530 531 bool ContinueOnTrue; 532 bool LatchIsExiting = BI->isConditional(); 533 BasicBlock *LoopExit = nullptr; 534 if (LatchIsExiting) { 535 ContinueOnTrue = L->contains(BI->getSuccessor(0)); 536 LoopExit = BI->getSuccessor(ContinueOnTrue); 537 } else { 538 NumUnrolledWithHeader++; 539 ContinueOnTrue = L->contains(HeaderBI->getSuccessor(0)); 540 LoopExit = HeaderBI->getSuccessor(ContinueOnTrue); 541 } 542 543 // For the first iteration of the loop, we should use the precloned values for 544 // PHI nodes. Insert associations now. 545 ValueToValueMapTy LastValueMap; 546 std::vector<PHINode*> OrigPHINode; 547 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) { 548 OrigPHINode.push_back(cast<PHINode>(I)); 549 } 550 551 std::vector<BasicBlock *> Headers; 552 std::vector<BasicBlock *> HeaderSucc; 553 std::vector<BasicBlock *> Latches; 554 Headers.push_back(Header); 555 Latches.push_back(LatchBlock); 556 557 if (!LatchIsExiting) { 558 auto *Term = cast<BranchInst>(Header->getTerminator()); 559 if (Term->isUnconditional() || L->contains(Term->getSuccessor(0))) { 560 assert(L->contains(Term->getSuccessor(0))); 561 HeaderSucc.push_back(Term->getSuccessor(0)); 562 } else { 563 assert(L->contains(Term->getSuccessor(1))); 564 HeaderSucc.push_back(Term->getSuccessor(1)); 565 } 566 } 567 568 // The current on-the-fly SSA update requires blocks to be processed in 569 // reverse postorder so that LastValueMap contains the correct value at each 570 // exit. 571 LoopBlocksDFS DFS(L); 572 DFS.perform(LI); 573 574 // Stash the DFS iterators before adding blocks to the loop. 575 LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO(); 576 LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO(); 577 578 std::vector<BasicBlock*> UnrolledLoopBlocks = L->getBlocks(); 579 580 // Loop Unrolling might create new loops. While we do preserve LoopInfo, we 581 // might break loop-simplified form for these loops (as they, e.g., would 582 // share the same exit blocks). We'll keep track of loops for which we can 583 // break this so that later we can re-simplify them. 584 SmallSetVector<Loop *, 4> LoopsToSimplify; 585 for (Loop *SubLoop : *L) 586 LoopsToSimplify.insert(SubLoop); 587 588 if (Header->getParent()->isDebugInfoForProfiling()) 589 for (BasicBlock *BB : L->getBlocks()) 590 for (Instruction &I : *BB) 591 if (!isa<DbgInfoIntrinsic>(&I)) 592 if (const DILocation *DIL = I.getDebugLoc()) { 593 auto NewDIL = DIL->cloneByMultiplyingDuplicationFactor(ULO.Count); 594 if (NewDIL) 595 I.setDebugLoc(NewDIL.getValue()); 596 else 597 LLVM_DEBUG(dbgs() 598 << "Failed to create new discriminator: " 599 << DIL->getFilename() << " Line: " << DIL->getLine()); 600 } 601 602 for (unsigned It = 1; It != ULO.Count; ++It) { 603 std::vector<BasicBlock*> NewBlocks; 604 SmallDenseMap<const Loop *, Loop *, 4> NewLoops; 605 NewLoops[L] = L; 606 607 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) { 608 ValueToValueMapTy VMap; 609 BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It)); 610 Header->getParent()->getBasicBlockList().push_back(New); 611 612 assert((*BB != Header || LI->getLoopFor(*BB) == L) && 613 "Header should not be in a sub-loop"); 614 // Tell LI about New. 615 const Loop *OldLoop = addClonedBlockToLoopInfo(*BB, New, LI, NewLoops); 616 if (OldLoop) 617 LoopsToSimplify.insert(NewLoops[OldLoop]); 618 619 if (*BB == Header) 620 // Loop over all of the PHI nodes in the block, changing them to use 621 // the incoming values from the previous block. 622 for (PHINode *OrigPHI : OrigPHINode) { 623 PHINode *NewPHI = cast<PHINode>(VMap[OrigPHI]); 624 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock); 625 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) 626 if (It > 1 && L->contains(InValI)) 627 InVal = LastValueMap[InValI]; 628 VMap[OrigPHI] = InVal; 629 New->getInstList().erase(NewPHI); 630 } 631 632 // Update our running map of newest clones 633 LastValueMap[*BB] = New; 634 for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end(); 635 VI != VE; ++VI) 636 LastValueMap[VI->first] = VI->second; 637 638 // Add phi entries for newly created values to all exit blocks. 639 for (BasicBlock *Succ : successors(*BB)) { 640 if (L->contains(Succ)) 641 continue; 642 for (PHINode &PHI : Succ->phis()) { 643 Value *Incoming = PHI.getIncomingValueForBlock(*BB); 644 ValueToValueMapTy::iterator It = LastValueMap.find(Incoming); 645 if (It != LastValueMap.end()) 646 Incoming = It->second; 647 PHI.addIncoming(Incoming, New); 648 } 649 } 650 // Keep track of new headers and latches as we create them, so that 651 // we can insert the proper branches later. 652 if (*BB == Header) 653 Headers.push_back(New); 654 if (*BB == LatchBlock) 655 Latches.push_back(New); 656 657 // Keep track of the successor of the new header in the current iteration. 658 for (auto *Pred : predecessors(*BB)) 659 if (Pred == Header) { 660 HeaderSucc.push_back(New); 661 break; 662 } 663 664 NewBlocks.push_back(New); 665 UnrolledLoopBlocks.push_back(New); 666 667 // Update DomTree: since we just copy the loop body, and each copy has a 668 // dedicated entry block (copy of the header block), this header's copy 669 // dominates all copied blocks. That means, dominance relations in the 670 // copied body are the same as in the original body. 671 if (DT) { 672 if (*BB == Header) 673 DT->addNewBlock(New, Latches[It - 1]); 674 else { 675 auto BBDomNode = DT->getNode(*BB); 676 auto BBIDom = BBDomNode->getIDom(); 677 BasicBlock *OriginalBBIDom = BBIDom->getBlock(); 678 DT->addNewBlock( 679 New, cast<BasicBlock>(LastValueMap[cast<Value>(OriginalBBIDom)])); 680 } 681 } 682 } 683 684 // Remap all instructions in the most recent iteration 685 for (BasicBlock *NewBlock : NewBlocks) { 686 for (Instruction &I : *NewBlock) { 687 ::remapInstruction(&I, LastValueMap); 688 if (auto *II = dyn_cast<IntrinsicInst>(&I)) 689 if (II->getIntrinsicID() == Intrinsic::assume) 690 AC->registerAssumption(II); 691 } 692 } 693 } 694 695 // Loop over the PHI nodes in the original block, setting incoming values. 696 for (PHINode *PN : OrigPHINode) { 697 if (CompletelyUnroll) { 698 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader)); 699 Header->getInstList().erase(PN); 700 } else if (ULO.Count > 1) { 701 Value *InVal = PN->removeIncomingValue(LatchBlock, false); 702 // If this value was defined in the loop, take the value defined by the 703 // last iteration of the loop. 704 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) { 705 if (L->contains(InValI)) 706 InVal = LastValueMap[InVal]; 707 } 708 assert(Latches.back() == LastValueMap[LatchBlock] && "bad last latch"); 709 PN->addIncoming(InVal, Latches.back()); 710 } 711 } 712 713 auto setDest = [LoopExit, ContinueOnTrue](BasicBlock *Src, BasicBlock *Dest, 714 ArrayRef<BasicBlock *> NextBlocks, 715 BasicBlock *BlockInLoop, 716 bool NeedConditional) { 717 auto *Term = cast<BranchInst>(Src->getTerminator()); 718 if (NeedConditional) { 719 // Update the conditional branch's successor for the following 720 // iteration. 721 Term->setSuccessor(!ContinueOnTrue, Dest); 722 } else { 723 // Remove phi operands at this loop exit 724 if (Dest != LoopExit) { 725 BasicBlock *BB = Src; 726 for (BasicBlock *Succ : successors(BB)) { 727 // Preserve the incoming value from BB if we are jumping to the block 728 // in the current loop. 729 if (Succ == BlockInLoop) 730 continue; 731 for (PHINode &Phi : Succ->phis()) 732 Phi.removeIncomingValue(BB, false); 733 } 734 } 735 // Replace the conditional branch with an unconditional one. 736 BranchInst::Create(Dest, Term); 737 Term->eraseFromParent(); 738 } 739 }; 740 741 // Now that all the basic blocks for the unrolled iterations are in place, 742 // set up the branches to connect them. 743 if (LatchIsExiting) { 744 // Set up latches to branch to the new header in the unrolled iterations or 745 // the loop exit for the last latch in a fully unrolled loop. 746 for (unsigned i = 0, e = Latches.size(); i != e; ++i) { 747 // The branch destination. 748 unsigned j = (i + 1) % e; 749 BasicBlock *Dest = Headers[j]; 750 bool NeedConditional = true; 751 752 if (RuntimeTripCount && j != 0) { 753 NeedConditional = false; 754 } 755 756 // For a complete unroll, make the last iteration end with a branch 757 // to the exit block. 758 if (CompletelyUnroll) { 759 if (j == 0) 760 Dest = LoopExit; 761 // If using trip count upper bound to completely unroll, we need to keep 762 // the conditional branch except the last one because the loop may exit 763 // after any iteration. 764 assert(NeedConditional && 765 "NeedCondition cannot be modified by both complete " 766 "unrolling and runtime unrolling"); 767 NeedConditional = 768 (ULO.PreserveCondBr && j && !(ULO.PreserveOnlyFirst && i != 0)); 769 } else if (j != BreakoutTrip && 770 (ULO.TripMultiple == 0 || j % ULO.TripMultiple != 0)) { 771 // If we know the trip count or a multiple of it, we can safely use an 772 // unconditional branch for some iterations. 773 NeedConditional = false; 774 } 775 776 setDest(Latches[i], Dest, Headers, Headers[i], NeedConditional); 777 } 778 } else { 779 // Setup headers to branch to their new successors in the unrolled 780 // iterations. 781 for (unsigned i = 0, e = Headers.size(); i != e; ++i) { 782 // The branch destination. 783 unsigned j = (i + 1) % e; 784 BasicBlock *Dest = HeaderSucc[i]; 785 bool NeedConditional = true; 786 787 if (RuntimeTripCount && j != 0) 788 NeedConditional = false; 789 790 if (CompletelyUnroll) 791 // We cannot drop the conditional branch for the last condition, as we 792 // may have to execute the loop body depending on the condition. 793 NeedConditional = j == 0 || ULO.PreserveCondBr; 794 else if (j != BreakoutTrip && 795 (ULO.TripMultiple == 0 || j % ULO.TripMultiple != 0)) 796 // If we know the trip count or a multiple of it, we can safely use an 797 // unconditional branch for some iterations. 798 NeedConditional = false; 799 800 setDest(Headers[i], Dest, Headers, HeaderSucc[i], NeedConditional); 801 } 802 803 // Set up latches to branch to the new header in the unrolled iterations or 804 // the loop exit for the last latch in a fully unrolled loop. 805 806 for (unsigned i = 0, e = Latches.size(); i != e; ++i) { 807 // The original branch was replicated in each unrolled iteration. 808 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator()); 809 810 // The branch destination. 811 unsigned j = (i + 1) % e; 812 BasicBlock *Dest = Headers[j]; 813 814 // When completely unrolling, the last latch becomes unreachable. 815 if (CompletelyUnroll && j == 0) 816 new UnreachableInst(Term->getContext(), Term); 817 else 818 // Replace the conditional branch with an unconditional one. 819 BranchInst::Create(Dest, Term); 820 821 Term->eraseFromParent(); 822 } 823 } 824 825 // Update dominators of blocks we might reach through exits. 826 // Immediate dominator of such block might change, because we add more 827 // routes which can lead to the exit: we can now reach it from the copied 828 // iterations too. 829 if (DT && ULO.Count > 1) { 830 for (auto *BB : OriginalLoopBlocks) { 831 auto *BBDomNode = DT->getNode(BB); 832 SmallVector<BasicBlock *, 16> ChildrenToUpdate; 833 for (auto *ChildDomNode : BBDomNode->getChildren()) { 834 auto *ChildBB = ChildDomNode->getBlock(); 835 if (!L->contains(ChildBB)) 836 ChildrenToUpdate.push_back(ChildBB); 837 } 838 BasicBlock *NewIDom; 839 BasicBlock *&TermBlock = LatchIsExiting ? LatchBlock : Header; 840 auto &TermBlocks = LatchIsExiting ? Latches : Headers; 841 if (BB == TermBlock) { 842 // The latch is special because we emit unconditional branches in 843 // some cases where the original loop contained a conditional branch. 844 // Since the latch is always at the bottom of the loop, if the latch 845 // dominated an exit before unrolling, the new dominator of that exit 846 // must also be a latch. Specifically, the dominator is the first 847 // latch which ends in a conditional branch, or the last latch if 848 // there is no such latch. 849 // For loops exiting from the header, we limit the supported loops 850 // to have a single exiting block. 851 NewIDom = TermBlocks.back(); 852 for (BasicBlock *Iter : TermBlocks) { 853 Instruction *Term = Iter->getTerminator(); 854 if (isa<BranchInst>(Term) && cast<BranchInst>(Term)->isConditional()) { 855 NewIDom = Iter; 856 break; 857 } 858 } 859 } else { 860 // The new idom of the block will be the nearest common dominator 861 // of all copies of the previous idom. This is equivalent to the 862 // nearest common dominator of the previous idom and the first latch, 863 // which dominates all copies of the previous idom. 864 NewIDom = DT->findNearestCommonDominator(BB, LatchBlock); 865 } 866 for (auto *ChildBB : ChildrenToUpdate) 867 DT->changeImmediateDominator(ChildBB, NewIDom); 868 } 869 } 870 871 assert(!DT || !UnrollVerifyDomtree || 872 DT->verify(DominatorTree::VerificationLevel::Fast)); 873 874 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy); 875 // Merge adjacent basic blocks, if possible. 876 for (BasicBlock *Latch : Latches) { 877 BranchInst *Term = dyn_cast<BranchInst>(Latch->getTerminator()); 878 assert((Term || 879 (CompletelyUnroll && !LatchIsExiting && Latch == Latches.back())) && 880 "Need a branch as terminator, except when fully unrolling with " 881 "unconditional latch"); 882 if (Term && Term->isUnconditional()) { 883 BasicBlock *Dest = Term->getSuccessor(0); 884 BasicBlock *Fold = Dest->getUniquePredecessor(); 885 if (MergeBlockIntoPredecessor(Dest, &DTU, LI)) { 886 // Dest has been folded into Fold. Update our worklists accordingly. 887 std::replace(Latches.begin(), Latches.end(), Dest, Fold); 888 UnrolledLoopBlocks.erase(std::remove(UnrolledLoopBlocks.begin(), 889 UnrolledLoopBlocks.end(), Dest), 890 UnrolledLoopBlocks.end()); 891 } 892 } 893 } 894 // Apply updates to the DomTree. 895 DT = &DTU.getDomTree(); 896 897 // At this point, the code is well formed. We now simplify the unrolled loop, 898 // doing constant propagation and dead code elimination as we go. 899 simplifyLoopAfterUnroll(L, !CompletelyUnroll && (ULO.Count > 1 || Peeled), LI, 900 SE, DT, AC); 901 902 NumCompletelyUnrolled += CompletelyUnroll; 903 ++NumUnrolled; 904 905 Loop *OuterL = L->getParentLoop(); 906 // Update LoopInfo if the loop is completely removed. 907 if (CompletelyUnroll) 908 LI->erase(L); 909 910 // After complete unrolling most of the blocks should be contained in OuterL. 911 // However, some of them might happen to be out of OuterL (e.g. if they 912 // precede a loop exit). In this case we might need to insert PHI nodes in 913 // order to preserve LCSSA form. 914 // We don't need to check this if we already know that we need to fix LCSSA 915 // form. 916 // TODO: For now we just recompute LCSSA for the outer loop in this case, but 917 // it should be possible to fix it in-place. 918 if (PreserveLCSSA && OuterL && CompletelyUnroll && !NeedToFixLCSSA) 919 NeedToFixLCSSA |= ::needToInsertPhisForLCSSA(OuterL, UnrolledLoopBlocks, LI); 920 921 // If we have a pass and a DominatorTree we should re-simplify impacted loops 922 // to ensure subsequent analyses can rely on this form. We want to simplify 923 // at least one layer outside of the loop that was unrolled so that any 924 // changes to the parent loop exposed by the unrolling are considered. 925 if (DT) { 926 if (OuterL) { 927 // OuterL includes all loops for which we can break loop-simplify, so 928 // it's sufficient to simplify only it (it'll recursively simplify inner 929 // loops too). 930 if (NeedToFixLCSSA) { 931 // LCSSA must be performed on the outermost affected loop. The unrolled 932 // loop's last loop latch is guaranteed to be in the outermost loop 933 // after LoopInfo's been updated by LoopInfo::erase. 934 Loop *LatchLoop = LI->getLoopFor(Latches.back()); 935 Loop *FixLCSSALoop = OuterL; 936 if (!FixLCSSALoop->contains(LatchLoop)) 937 while (FixLCSSALoop->getParentLoop() != LatchLoop) 938 FixLCSSALoop = FixLCSSALoop->getParentLoop(); 939 940 formLCSSARecursively(*FixLCSSALoop, *DT, LI, SE); 941 } else if (PreserveLCSSA) { 942 assert(OuterL->isLCSSAForm(*DT) && 943 "Loops should be in LCSSA form after loop-unroll."); 944 } 945 946 // TODO: That potentially might be compile-time expensive. We should try 947 // to fix the loop-simplified form incrementally. 948 simplifyLoop(OuterL, DT, LI, SE, AC, nullptr, PreserveLCSSA); 949 } else { 950 // Simplify loops for which we might've broken loop-simplify form. 951 for (Loop *SubLoop : LoopsToSimplify) 952 simplifyLoop(SubLoop, DT, LI, SE, AC, nullptr, PreserveLCSSA); 953 } 954 } 955 956 return CompletelyUnroll ? LoopUnrollResult::FullyUnrolled 957 : LoopUnrollResult::PartiallyUnrolled; 958 } 959 960 /// Given an llvm.loop loop id metadata node, returns the loop hint metadata 961 /// node with the given name (for example, "llvm.loop.unroll.count"). If no 962 /// such metadata node exists, then nullptr is returned. 963 MDNode *llvm::GetUnrollMetadata(MDNode *LoopID, StringRef Name) { 964 // First operand should refer to the loop id itself. 965 assert(LoopID->getNumOperands() > 0 && "requires at least one operand"); 966 assert(LoopID->getOperand(0) == LoopID && "invalid loop id"); 967 968 for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) { 969 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i)); 970 if (!MD) 971 continue; 972 973 MDString *S = dyn_cast<MDString>(MD->getOperand(0)); 974 if (!S) 975 continue; 976 977 if (Name.equals(S->getString())) 978 return MD; 979 } 980 return nullptr; 981 } 982