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