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 LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, 339 OptimizationRemarkEmitter *ORE, bool PreserveLCSSA, Loop **RemainderLoop) { 340 341 BasicBlock *Preheader = L->getLoopPreheader(); 342 if (!Preheader) { 343 LLVM_DEBUG(dbgs() << " Can't unroll; loop preheader-insertion failed.\n"); 344 return LoopUnrollResult::Unmodified; 345 } 346 347 BasicBlock *LatchBlock = L->getLoopLatch(); 348 if (!LatchBlock) { 349 LLVM_DEBUG(dbgs() << " Can't unroll; loop exit-block-insertion failed.\n"); 350 return LoopUnrollResult::Unmodified; 351 } 352 353 // Loops with indirectbr cannot be cloned. 354 if (!L->isSafeToClone()) { 355 LLVM_DEBUG(dbgs() << " Can't unroll; Loop body cannot be cloned.\n"); 356 return LoopUnrollResult::Unmodified; 357 } 358 359 // The current loop unroll pass can only unroll loops with a single latch 360 // that's a conditional branch exiting the loop. 361 // FIXME: The implementation can be extended to work with more complicated 362 // cases, e.g. loops with multiple latches. 363 BasicBlock *Header = L->getHeader(); 364 BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator()); 365 366 if (!BI || BI->isUnconditional()) { 367 // The loop-rotate pass can be helpful to avoid this in many cases. 368 LLVM_DEBUG( 369 dbgs() 370 << " Can't unroll; loop not terminated by a conditional branch.\n"); 371 return LoopUnrollResult::Unmodified; 372 } 373 374 auto CheckSuccessors = [&](unsigned S1, unsigned S2) { 375 return BI->getSuccessor(S1) == Header && !L->contains(BI->getSuccessor(S2)); 376 }; 377 378 if (!CheckSuccessors(0, 1) && !CheckSuccessors(1, 0)) { 379 LLVM_DEBUG(dbgs() << "Can't unroll; only loops with one conditional latch" 380 " exiting the loop can be unrolled\n"); 381 return LoopUnrollResult::Unmodified; 382 } 383 384 if (Header->hasAddressTaken()) { 385 // The loop-rotate pass can be helpful to avoid this in many cases. 386 LLVM_DEBUG( 387 dbgs() << " Won't unroll loop: address of header block is taken.\n"); 388 return LoopUnrollResult::Unmodified; 389 } 390 391 if (TripCount != 0) 392 LLVM_DEBUG(dbgs() << " Trip Count = " << TripCount << "\n"); 393 if (TripMultiple != 1) 394 LLVM_DEBUG(dbgs() << " Trip Multiple = " << TripMultiple << "\n"); 395 396 // Effectively "DCE" unrolled iterations that are beyond the tripcount 397 // and will never be executed. 398 if (TripCount != 0 && Count > TripCount) 399 Count = TripCount; 400 401 // Don't enter the unroll code if there is nothing to do. 402 if (TripCount == 0 && Count < 2 && PeelCount == 0) { 403 LLVM_DEBUG(dbgs() << "Won't unroll; almost nothing to do\n"); 404 return LoopUnrollResult::Unmodified; 405 } 406 407 assert(Count > 0); 408 assert(TripMultiple > 0); 409 assert(TripCount == 0 || TripCount % TripMultiple == 0); 410 411 // Are we eliminating the loop control altogether? 412 bool CompletelyUnroll = Count == TripCount; 413 SmallVector<BasicBlock *, 4> ExitBlocks; 414 L->getExitBlocks(ExitBlocks); 415 std::vector<BasicBlock*> OriginalLoopBlocks = L->getBlocks(); 416 417 // Go through all exits of L and see if there are any phi-nodes there. We just 418 // conservatively assume that they're inserted to preserve LCSSA form, which 419 // means that complete unrolling might break this form. We need to either fix 420 // it in-place after the transformation, or entirely rebuild LCSSA. TODO: For 421 // now we just recompute LCSSA for the outer loop, but it should be possible 422 // to fix it in-place. 423 bool NeedToFixLCSSA = PreserveLCSSA && CompletelyUnroll && 424 any_of(ExitBlocks, [](const BasicBlock *BB) { 425 return isa<PHINode>(BB->begin()); 426 }); 427 428 // We assume a run-time trip count if the compiler cannot 429 // figure out the loop trip count and the unroll-runtime 430 // flag is specified. 431 bool RuntimeTripCount = (TripCount == 0 && Count > 0 && AllowRuntime); 432 433 assert((!RuntimeTripCount || !PeelCount) && 434 "Did not expect runtime trip-count unrolling " 435 "and peeling for the same loop"); 436 437 bool Peeled = false; 438 if (PeelCount) { 439 Peeled = peelLoop(L, PeelCount, LI, SE, DT, AC, PreserveLCSSA); 440 441 // Successful peeling may result in a change in the loop preheader/trip 442 // counts. If we later unroll the loop, we want these to be updated. 443 if (Peeled) { 444 BasicBlock *ExitingBlock = L->getExitingBlock(); 445 assert(ExitingBlock && "Loop without exiting block?"); 446 Preheader = L->getLoopPreheader(); 447 TripCount = SE->getSmallConstantTripCount(L, ExitingBlock); 448 TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock); 449 } 450 } 451 452 // Loops containing convergent instructions must have a count that divides 453 // their TripMultiple. 454 LLVM_DEBUG( 455 { 456 bool HasConvergent = false; 457 for (auto &BB : L->blocks()) 458 for (auto &I : *BB) 459 if (auto CS = CallSite(&I)) 460 HasConvergent |= CS.isConvergent(); 461 assert((!HasConvergent || TripMultiple % Count == 0) && 462 "Unroll count must divide trip multiple if loop contains a " 463 "convergent operation."); 464 }); 465 466 bool EpilogProfitability = 467 UnrollRuntimeEpilog.getNumOccurrences() ? UnrollRuntimeEpilog 468 : isEpilogProfitable(L); 469 470 if (RuntimeTripCount && TripMultiple % Count != 0 && 471 !UnrollRuntimeLoopRemainder(L, Count, AllowExpensiveTripCount, 472 EpilogProfitability, UnrollRemainder, LI, SE, 473 DT, AC, PreserveLCSSA, RemainderLoop)) { 474 if (Force) 475 RuntimeTripCount = false; 476 else { 477 LLVM_DEBUG(dbgs() << "Won't unroll; remainder loop could not be " 478 "generated when assuming runtime trip count\n"); 479 return LoopUnrollResult::Unmodified; 480 } 481 } 482 483 // If we know the trip count, we know the multiple... 484 unsigned BreakoutTrip = 0; 485 if (TripCount != 0) { 486 BreakoutTrip = TripCount % Count; 487 TripMultiple = 0; 488 } else { 489 // Figure out what multiple to use. 490 BreakoutTrip = TripMultiple = 491 (unsigned)GreatestCommonDivisor64(Count, TripMultiple); 492 } 493 494 using namespace ore; 495 // Report the unrolling decision. 496 if (CompletelyUnroll) { 497 LLVM_DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName() 498 << " with trip count " << TripCount << "!\n"); 499 if (ORE) 500 ORE->emit([&]() { 501 return OptimizationRemark(DEBUG_TYPE, "FullyUnrolled", L->getStartLoc(), 502 L->getHeader()) 503 << "completely unrolled loop with " 504 << NV("UnrollCount", TripCount) << " iterations"; 505 }); 506 } else if (PeelCount) { 507 LLVM_DEBUG(dbgs() << "PEELING loop %" << Header->getName() 508 << " with iteration count " << PeelCount << "!\n"); 509 if (ORE) 510 ORE->emit([&]() { 511 return OptimizationRemark(DEBUG_TYPE, "Peeled", L->getStartLoc(), 512 L->getHeader()) 513 << " peeled loop by " << NV("PeelCount", PeelCount) 514 << " iterations"; 515 }); 516 } else { 517 auto DiagBuilder = [&]() { 518 OptimizationRemark Diag(DEBUG_TYPE, "PartialUnrolled", L->getStartLoc(), 519 L->getHeader()); 520 return Diag << "unrolled loop by a factor of " 521 << NV("UnrollCount", Count); 522 }; 523 524 LLVM_DEBUG(dbgs() << "UNROLLING loop %" << Header->getName() << " by " 525 << Count); 526 if (TripMultiple == 0 || BreakoutTrip != TripMultiple) { 527 LLVM_DEBUG(dbgs() << " with a breakout at trip " << BreakoutTrip); 528 if (ORE) 529 ORE->emit([&]() { 530 return DiagBuilder() << " with a breakout at trip " 531 << NV("BreakoutTrip", BreakoutTrip); 532 }); 533 } else if (TripMultiple != 1) { 534 LLVM_DEBUG(dbgs() << " with " << TripMultiple << " trips per branch"); 535 if (ORE) 536 ORE->emit([&]() { 537 return DiagBuilder() << " with " << NV("TripMultiple", TripMultiple) 538 << " trips per branch"; 539 }); 540 } else if (RuntimeTripCount) { 541 LLVM_DEBUG(dbgs() << " with run-time trip count"); 542 if (ORE) 543 ORE->emit( 544 [&]() { return DiagBuilder() << " with run-time trip count"; }); 545 } 546 LLVM_DEBUG(dbgs() << "!\n"); 547 } 548 549 // We are going to make changes to this loop. SCEV may be keeping cached info 550 // about it, in particular about backedge taken count. The changes we make 551 // are guaranteed to invalidate this information for our loop. It is tempting 552 // to only invalidate the loop being unrolled, but it is incorrect as long as 553 // all exiting branches from all inner loops have impact on the outer loops, 554 // and if something changes inside them then any of outer loops may also 555 // change. When we forget outermost loop, we also forget all contained loops 556 // and this is what we need here. 557 if (SE) 558 SE->forgetTopmostLoop(L); 559 560 bool ContinueOnTrue = L->contains(BI->getSuccessor(0)); 561 BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue); 562 563 // For the first iteration of the loop, we should use the precloned values for 564 // PHI nodes. Insert associations now. 565 ValueToValueMapTy LastValueMap; 566 std::vector<PHINode*> OrigPHINode; 567 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) { 568 OrigPHINode.push_back(cast<PHINode>(I)); 569 } 570 571 std::vector<BasicBlock*> Headers; 572 std::vector<BasicBlock*> Latches; 573 Headers.push_back(Header); 574 Latches.push_back(LatchBlock); 575 576 // The current on-the-fly SSA update requires blocks to be processed in 577 // reverse postorder so that LastValueMap contains the correct value at each 578 // exit. 579 LoopBlocksDFS DFS(L); 580 DFS.perform(LI); 581 582 // Stash the DFS iterators before adding blocks to the loop. 583 LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO(); 584 LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO(); 585 586 std::vector<BasicBlock*> UnrolledLoopBlocks = L->getBlocks(); 587 588 // Loop Unrolling might create new loops. While we do preserve LoopInfo, we 589 // might break loop-simplified form for these loops (as they, e.g., would 590 // share the same exit blocks). We'll keep track of loops for which we can 591 // break this so that later we can re-simplify them. 592 SmallSetVector<Loop *, 4> LoopsToSimplify; 593 for (Loop *SubLoop : *L) 594 LoopsToSimplify.insert(SubLoop); 595 596 if (Header->getParent()->isDebugInfoForProfiling()) 597 for (BasicBlock *BB : L->getBlocks()) 598 for (Instruction &I : *BB) 599 if (!isa<DbgInfoIntrinsic>(&I)) 600 if (const DILocation *DIL = I.getDebugLoc()) { 601 auto NewDIL = DIL->cloneByMultiplyingDuplicationFactor(Count); 602 if (NewDIL) 603 I.setDebugLoc(NewDIL.getValue()); 604 else 605 LLVM_DEBUG(dbgs() 606 << "Failed to create new discriminator: " 607 << DIL->getFilename() << " Line: " << DIL->getLine()); 608 } 609 610 for (unsigned It = 1; It != Count; ++It) { 611 std::vector<BasicBlock*> NewBlocks; 612 SmallDenseMap<const Loop *, Loop *, 4> NewLoops; 613 NewLoops[L] = L; 614 615 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) { 616 ValueToValueMapTy VMap; 617 BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It)); 618 Header->getParent()->getBasicBlockList().push_back(New); 619 620 assert((*BB != Header || LI->getLoopFor(*BB) == L) && 621 "Header should not be in a sub-loop"); 622 // Tell LI about New. 623 const Loop *OldLoop = addClonedBlockToLoopInfo(*BB, New, LI, NewLoops); 624 if (OldLoop) 625 LoopsToSimplify.insert(NewLoops[OldLoop]); 626 627 if (*BB == Header) 628 // Loop over all of the PHI nodes in the block, changing them to use 629 // the incoming values from the previous block. 630 for (PHINode *OrigPHI : OrigPHINode) { 631 PHINode *NewPHI = cast<PHINode>(VMap[OrigPHI]); 632 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock); 633 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) 634 if (It > 1 && L->contains(InValI)) 635 InVal = LastValueMap[InValI]; 636 VMap[OrigPHI] = InVal; 637 New->getInstList().erase(NewPHI); 638 } 639 640 // Update our running map of newest clones 641 LastValueMap[*BB] = New; 642 for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end(); 643 VI != VE; ++VI) 644 LastValueMap[VI->first] = VI->second; 645 646 // Add phi entries for newly created values to all exit blocks. 647 for (BasicBlock *Succ : successors(*BB)) { 648 if (L->contains(Succ)) 649 continue; 650 for (PHINode &PHI : Succ->phis()) { 651 Value *Incoming = PHI.getIncomingValueForBlock(*BB); 652 ValueToValueMapTy::iterator It = LastValueMap.find(Incoming); 653 if (It != LastValueMap.end()) 654 Incoming = It->second; 655 PHI.addIncoming(Incoming, New); 656 } 657 } 658 // Keep track of new headers and latches as we create them, so that 659 // we can insert the proper branches later. 660 if (*BB == Header) 661 Headers.push_back(New); 662 if (*BB == LatchBlock) 663 Latches.push_back(New); 664 665 NewBlocks.push_back(New); 666 UnrolledLoopBlocks.push_back(New); 667 668 // Update DomTree: since we just copy the loop body, and each copy has a 669 // dedicated entry block (copy of the header block), this header's copy 670 // dominates all copied blocks. That means, dominance relations in the 671 // copied body are the same as in the original body. 672 if (DT) { 673 if (*BB == Header) 674 DT->addNewBlock(New, Latches[It - 1]); 675 else { 676 auto BBDomNode = DT->getNode(*BB); 677 auto BBIDom = BBDomNode->getIDom(); 678 BasicBlock *OriginalBBIDom = BBIDom->getBlock(); 679 DT->addNewBlock( 680 New, cast<BasicBlock>(LastValueMap[cast<Value>(OriginalBBIDom)])); 681 } 682 } 683 } 684 685 // Remap all instructions in the most recent iteration 686 for (BasicBlock *NewBlock : NewBlocks) { 687 for (Instruction &I : *NewBlock) { 688 ::remapInstruction(&I, LastValueMap); 689 if (auto *II = dyn_cast<IntrinsicInst>(&I)) 690 if (II->getIntrinsicID() == Intrinsic::assume) 691 AC->registerAssumption(II); 692 } 693 } 694 } 695 696 // Loop over the PHI nodes in the original block, setting incoming values. 697 for (PHINode *PN : OrigPHINode) { 698 if (CompletelyUnroll) { 699 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader)); 700 Header->getInstList().erase(PN); 701 } 702 else if (Count > 1) { 703 Value *InVal = PN->removeIncomingValue(LatchBlock, false); 704 // If this value was defined in the loop, take the value defined by the 705 // last iteration of the loop. 706 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) { 707 if (L->contains(InValI)) 708 InVal = LastValueMap[InVal]; 709 } 710 assert(Latches.back() == LastValueMap[LatchBlock] && "bad last latch"); 711 PN->addIncoming(InVal, Latches.back()); 712 } 713 } 714 715 // Now that all the basic blocks for the unrolled iterations are in place, 716 // set up the branches to connect them. 717 for (unsigned i = 0, e = Latches.size(); i != e; ++i) { 718 // The original branch was replicated in each unrolled iteration. 719 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator()); 720 721 // The branch destination. 722 unsigned j = (i + 1) % e; 723 BasicBlock *Dest = Headers[j]; 724 bool NeedConditional = true; 725 726 if (RuntimeTripCount && j != 0) { 727 NeedConditional = false; 728 } 729 730 // For a complete unroll, make the last iteration end with a branch 731 // to the exit block. 732 if (CompletelyUnroll) { 733 if (j == 0) 734 Dest = LoopExit; 735 // If using trip count upper bound to completely unroll, we need to keep 736 // the conditional branch except the last one because the loop may exit 737 // after any iteration. 738 assert(NeedConditional && 739 "NeedCondition cannot be modified by both complete " 740 "unrolling and runtime unrolling"); 741 NeedConditional = (PreserveCondBr && j && !(PreserveOnlyFirst && i != 0)); 742 } else if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) { 743 // If we know the trip count or a multiple of it, we can safely use an 744 // unconditional branch for some iterations. 745 NeedConditional = false; 746 } 747 748 if (NeedConditional) { 749 // Update the conditional branch's successor for the following 750 // iteration. 751 Term->setSuccessor(!ContinueOnTrue, Dest); 752 } else { 753 // Remove phi operands at this loop exit 754 if (Dest != LoopExit) { 755 BasicBlock *BB = Latches[i]; 756 for (BasicBlock *Succ: successors(BB)) { 757 if (Succ == Headers[i]) 758 continue; 759 for (PHINode &Phi : Succ->phis()) 760 Phi.removeIncomingValue(BB, false); 761 } 762 } 763 // Replace the conditional branch with an unconditional one. 764 BranchInst::Create(Dest, Term); 765 Term->eraseFromParent(); 766 } 767 } 768 769 // Update dominators of blocks we might reach through exits. 770 // Immediate dominator of such block might change, because we add more 771 // routes which can lead to the exit: we can now reach it from the copied 772 // iterations too. 773 if (DT && Count > 1) { 774 for (auto *BB : OriginalLoopBlocks) { 775 auto *BBDomNode = DT->getNode(BB); 776 SmallVector<BasicBlock *, 16> ChildrenToUpdate; 777 for (auto *ChildDomNode : BBDomNode->getChildren()) { 778 auto *ChildBB = ChildDomNode->getBlock(); 779 if (!L->contains(ChildBB)) 780 ChildrenToUpdate.push_back(ChildBB); 781 } 782 BasicBlock *NewIDom; 783 if (BB == LatchBlock) { 784 // The latch is special because we emit unconditional branches in 785 // some cases where the original loop contained a conditional branch. 786 // Since the latch is always at the bottom of the loop, if the latch 787 // dominated an exit before unrolling, the new dominator of that exit 788 // must also be a latch. Specifically, the dominator is the first 789 // latch which ends in a conditional branch, or the last latch if 790 // there is no such latch. 791 NewIDom = Latches.back(); 792 for (BasicBlock *IterLatch : Latches) { 793 Instruction *Term = IterLatch->getTerminator(); 794 if (isa<BranchInst>(Term) && cast<BranchInst>(Term)->isConditional()) { 795 NewIDom = IterLatch; 796 break; 797 } 798 } 799 } else { 800 // The new idom of the block will be the nearest common dominator 801 // of all copies of the previous idom. This is equivalent to the 802 // nearest common dominator of the previous idom and the first latch, 803 // which dominates all copies of the previous idom. 804 NewIDom = DT->findNearestCommonDominator(BB, LatchBlock); 805 } 806 for (auto *ChildBB : ChildrenToUpdate) 807 DT->changeImmediateDominator(ChildBB, NewIDom); 808 } 809 } 810 811 assert(!DT || !UnrollVerifyDomtree || 812 DT->verify(DominatorTree::VerificationLevel::Fast)); 813 814 // Merge adjacent basic blocks, if possible. 815 for (BasicBlock *Latch : Latches) { 816 BranchInst *Term = cast<BranchInst>(Latch->getTerminator()); 817 if (Term->isUnconditional()) { 818 BasicBlock *Dest = Term->getSuccessor(0); 819 if (BasicBlock *Fold = foldBlockIntoPredecessor(Dest, LI, SE, DT)) { 820 // Dest has been folded into Fold. Update our worklists accordingly. 821 std::replace(Latches.begin(), Latches.end(), Dest, Fold); 822 UnrolledLoopBlocks.erase(std::remove(UnrolledLoopBlocks.begin(), 823 UnrolledLoopBlocks.end(), Dest), 824 UnrolledLoopBlocks.end()); 825 } 826 } 827 } 828 829 // At this point, the code is well formed. We now simplify the unrolled loop, 830 // doing constant propagation and dead code elimination as we go. 831 simplifyLoopAfterUnroll(L, !CompletelyUnroll && (Count > 1 || Peeled), LI, SE, 832 DT, AC); 833 834 NumCompletelyUnrolled += CompletelyUnroll; 835 ++NumUnrolled; 836 837 Loop *OuterL = L->getParentLoop(); 838 // Update LoopInfo if the loop is completely removed. 839 if (CompletelyUnroll) 840 LI->erase(L); 841 842 // After complete unrolling most of the blocks should be contained in OuterL. 843 // However, some of them might happen to be out of OuterL (e.g. if they 844 // precede a loop exit). In this case we might need to insert PHI nodes in 845 // order to preserve LCSSA form. 846 // We don't need to check this if we already know that we need to fix LCSSA 847 // form. 848 // TODO: For now we just recompute LCSSA for the outer loop in this case, but 849 // it should be possible to fix it in-place. 850 if (PreserveLCSSA && OuterL && CompletelyUnroll && !NeedToFixLCSSA) 851 NeedToFixLCSSA |= ::needToInsertPhisForLCSSA(OuterL, UnrolledLoopBlocks, LI); 852 853 // If we have a pass and a DominatorTree we should re-simplify impacted loops 854 // to ensure subsequent analyses can rely on this form. We want to simplify 855 // at least one layer outside of the loop that was unrolled so that any 856 // changes to the parent loop exposed by the unrolling are considered. 857 if (DT) { 858 if (OuterL) { 859 // OuterL includes all loops for which we can break loop-simplify, so 860 // it's sufficient to simplify only it (it'll recursively simplify inner 861 // loops too). 862 if (NeedToFixLCSSA) { 863 // LCSSA must be performed on the outermost affected loop. The unrolled 864 // loop's last loop latch is guaranteed to be in the outermost loop 865 // after LoopInfo's been updated by LoopInfo::erase. 866 Loop *LatchLoop = LI->getLoopFor(Latches.back()); 867 Loop *FixLCSSALoop = OuterL; 868 if (!FixLCSSALoop->contains(LatchLoop)) 869 while (FixLCSSALoop->getParentLoop() != LatchLoop) 870 FixLCSSALoop = FixLCSSALoop->getParentLoop(); 871 872 formLCSSARecursively(*FixLCSSALoop, *DT, LI, SE); 873 } else if (PreserveLCSSA) { 874 assert(OuterL->isLCSSAForm(*DT) && 875 "Loops should be in LCSSA form after loop-unroll."); 876 } 877 878 // TODO: That potentially might be compile-time expensive. We should try 879 // to fix the loop-simplified form incrementally. 880 simplifyLoop(OuterL, DT, LI, SE, AC, PreserveLCSSA); 881 } else { 882 // Simplify loops for which we might've broken loop-simplify form. 883 for (Loop *SubLoop : LoopsToSimplify) 884 simplifyLoop(SubLoop, DT, LI, SE, AC, PreserveLCSSA); 885 } 886 } 887 888 return CompletelyUnroll ? LoopUnrollResult::FullyUnrolled 889 : LoopUnrollResult::PartiallyUnrolled; 890 } 891 892 /// Given an llvm.loop loop id metadata node, returns the loop hint metadata 893 /// node with the given name (for example, "llvm.loop.unroll.count"). If no 894 /// such metadata node exists, then nullptr is returned. 895 MDNode *llvm::GetUnrollMetadata(MDNode *LoopID, StringRef Name) { 896 // First operand should refer to the loop id itself. 897 assert(LoopID->getNumOperands() > 0 && "requires at least one operand"); 898 assert(LoopID->getOperand(0) == LoopID && "invalid loop id"); 899 900 for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) { 901 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i)); 902 if (!MD) 903 continue; 904 905 MDString *S = dyn_cast<MDString>(MD->getOperand(0)); 906 if (!S) 907 continue; 908 909 if (Name.equals(S->getString())) 910 return MD; 911 } 912 return nullptr; 913 } 914