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