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