1 //===-- UnrollLoopRuntime.cpp - Runtime 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 for loops with run-time 10 // trip counts. See LoopUnroll.cpp for unrolling loops with compile-time 11 // trip counts. 12 // 13 // The functions in this file are used to generate extra code when the 14 // run-time trip count modulo the unroll factor is not 0. When this is the 15 // case, we need to generate code to execute these 'left over' iterations. 16 // 17 // The current strategy generates an if-then-else sequence prior to the 18 // unrolled loop to execute the 'left over' iterations before or after the 19 // unrolled loop. 20 // 21 //===----------------------------------------------------------------------===// 22 23 #include "llvm/ADT/SmallPtrSet.h" 24 #include "llvm/ADT/Statistic.h" 25 #include "llvm/Analysis/AliasAnalysis.h" 26 #include "llvm/Analysis/LoopIterator.h" 27 #include "llvm/Analysis/ScalarEvolution.h" 28 #include "llvm/Analysis/ScalarEvolutionExpander.h" 29 #include "llvm/IR/BasicBlock.h" 30 #include "llvm/IR/Dominators.h" 31 #include "llvm/IR/Metadata.h" 32 #include "llvm/IR/Module.h" 33 #include "llvm/Support/Debug.h" 34 #include "llvm/Support/raw_ostream.h" 35 #include "llvm/Transforms/Utils.h" 36 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 37 #include "llvm/Transforms/Utils/Cloning.h" 38 #include "llvm/Transforms/Utils/LoopUtils.h" 39 #include "llvm/Transforms/Utils/UnrollLoop.h" 40 #include <algorithm> 41 42 using namespace llvm; 43 44 #define DEBUG_TYPE "loop-unroll" 45 46 STATISTIC(NumRuntimeUnrolled, 47 "Number of loops unrolled with run-time trip counts"); 48 static cl::opt<bool> UnrollRuntimeMultiExit( 49 "unroll-runtime-multi-exit", cl::init(false), cl::Hidden, 50 cl::desc("Allow runtime unrolling for loops with multiple exits, when " 51 "epilog is generated")); 52 53 /// Connect the unrolling prolog code to the original loop. 54 /// The unrolling prolog code contains code to execute the 55 /// 'extra' iterations if the run-time trip count modulo the 56 /// unroll count is non-zero. 57 /// 58 /// This function performs the following: 59 /// - Create PHI nodes at prolog end block to combine values 60 /// that exit the prolog code and jump around the prolog. 61 /// - Add a PHI operand to a PHI node at the loop exit block 62 /// for values that exit the prolog and go around the loop. 63 /// - Branch around the original loop if the trip count is less 64 /// than the unroll factor. 65 /// 66 static void ConnectProlog(Loop *L, Value *BECount, unsigned Count, 67 BasicBlock *PrologExit, 68 BasicBlock *OriginalLoopLatchExit, 69 BasicBlock *PreHeader, BasicBlock *NewPreHeader, 70 ValueToValueMapTy &VMap, DominatorTree *DT, 71 LoopInfo *LI, bool PreserveLCSSA) { 72 // Loop structure should be the following: 73 // Preheader 74 // PrologHeader 75 // ... 76 // PrologLatch 77 // PrologExit 78 // NewPreheader 79 // Header 80 // ... 81 // Latch 82 // LatchExit 83 BasicBlock *Latch = L->getLoopLatch(); 84 assert(Latch && "Loop must have a latch"); 85 BasicBlock *PrologLatch = cast<BasicBlock>(VMap[Latch]); 86 87 // Create a PHI node for each outgoing value from the original loop 88 // (which means it is an outgoing value from the prolog code too). 89 // The new PHI node is inserted in the prolog end basic block. 90 // The new PHI node value is added as an operand of a PHI node in either 91 // the loop header or the loop exit block. 92 for (BasicBlock *Succ : successors(Latch)) { 93 for (PHINode &PN : Succ->phis()) { 94 // Add a new PHI node to the prolog end block and add the 95 // appropriate incoming values. 96 // TODO: This code assumes that the PrologExit (or the LatchExit block for 97 // prolog loop) contains only one predecessor from the loop, i.e. the 98 // PrologLatch. When supporting multiple-exiting block loops, we can have 99 // two or more blocks that have the LatchExit as the target in the 100 // original loop. 101 PHINode *NewPN = PHINode::Create(PN.getType(), 2, PN.getName() + ".unr", 102 PrologExit->getFirstNonPHI()); 103 // Adding a value to the new PHI node from the original loop preheader. 104 // This is the value that skips all the prolog code. 105 if (L->contains(&PN)) { 106 // Succ is loop header. 107 NewPN->addIncoming(PN.getIncomingValueForBlock(NewPreHeader), 108 PreHeader); 109 } else { 110 // Succ is LatchExit. 111 NewPN->addIncoming(UndefValue::get(PN.getType()), PreHeader); 112 } 113 114 Value *V = PN.getIncomingValueForBlock(Latch); 115 if (Instruction *I = dyn_cast<Instruction>(V)) { 116 if (L->contains(I)) { 117 V = VMap.lookup(I); 118 } 119 } 120 // Adding a value to the new PHI node from the last prolog block 121 // that was created. 122 NewPN->addIncoming(V, PrologLatch); 123 124 // Update the existing PHI node operand with the value from the 125 // new PHI node. How this is done depends on if the existing 126 // PHI node is in the original loop block, or the exit block. 127 if (L->contains(&PN)) 128 PN.setIncomingValueForBlock(NewPreHeader, NewPN); 129 else 130 PN.addIncoming(NewPN, PrologExit); 131 } 132 } 133 134 // Make sure that created prolog loop is in simplified form 135 SmallVector<BasicBlock *, 4> PrologExitPreds; 136 Loop *PrologLoop = LI->getLoopFor(PrologLatch); 137 if (PrologLoop) { 138 for (BasicBlock *PredBB : predecessors(PrologExit)) 139 if (PrologLoop->contains(PredBB)) 140 PrologExitPreds.push_back(PredBB); 141 142 SplitBlockPredecessors(PrologExit, PrologExitPreds, ".unr-lcssa", DT, LI, 143 nullptr, PreserveLCSSA); 144 } 145 146 // Create a branch around the original loop, which is taken if there are no 147 // iterations remaining to be executed after running the prologue. 148 Instruction *InsertPt = PrologExit->getTerminator(); 149 IRBuilder<> B(InsertPt); 150 151 assert(Count != 0 && "nonsensical Count!"); 152 153 // If BECount <u (Count - 1) then (BECount + 1) % Count == (BECount + 1) 154 // This means %xtraiter is (BECount + 1) and all of the iterations of this 155 // loop were executed by the prologue. Note that if BECount <u (Count - 1) 156 // then (BECount + 1) cannot unsigned-overflow. 157 Value *BrLoopExit = 158 B.CreateICmpULT(BECount, ConstantInt::get(BECount->getType(), Count - 1)); 159 // Split the exit to maintain loop canonicalization guarantees 160 SmallVector<BasicBlock *, 4> Preds(predecessors(OriginalLoopLatchExit)); 161 SplitBlockPredecessors(OriginalLoopLatchExit, Preds, ".unr-lcssa", DT, LI, 162 nullptr, PreserveLCSSA); 163 // Add the branch to the exit block (around the unrolled loop) 164 B.CreateCondBr(BrLoopExit, OriginalLoopLatchExit, NewPreHeader); 165 InsertPt->eraseFromParent(); 166 if (DT) 167 DT->changeImmediateDominator(OriginalLoopLatchExit, PrologExit); 168 } 169 170 /// Connect the unrolling epilog code to the original loop. 171 /// The unrolling epilog code contains code to execute the 172 /// 'extra' iterations if the run-time trip count modulo the 173 /// unroll count is non-zero. 174 /// 175 /// This function performs the following: 176 /// - Update PHI nodes at the unrolling loop exit and epilog loop exit 177 /// - Create PHI nodes at the unrolling loop exit to combine 178 /// values that exit the unrolling loop code and jump around it. 179 /// - Update PHI operands in the epilog loop by the new PHI nodes 180 /// - Branch around the epilog loop if extra iters (ModVal) is zero. 181 /// 182 static void ConnectEpilog(Loop *L, Value *ModVal, BasicBlock *NewExit, 183 BasicBlock *Exit, BasicBlock *PreHeader, 184 BasicBlock *EpilogPreHeader, BasicBlock *NewPreHeader, 185 ValueToValueMapTy &VMap, DominatorTree *DT, 186 LoopInfo *LI, bool PreserveLCSSA) { 187 BasicBlock *Latch = L->getLoopLatch(); 188 assert(Latch && "Loop must have a latch"); 189 BasicBlock *EpilogLatch = cast<BasicBlock>(VMap[Latch]); 190 191 // Loop structure should be the following: 192 // 193 // PreHeader 194 // NewPreHeader 195 // Header 196 // ... 197 // Latch 198 // NewExit (PN) 199 // EpilogPreHeader 200 // EpilogHeader 201 // ... 202 // EpilogLatch 203 // Exit (EpilogPN) 204 205 // Update PHI nodes at NewExit and Exit. 206 for (PHINode &PN : NewExit->phis()) { 207 // PN should be used in another PHI located in Exit block as 208 // Exit was split by SplitBlockPredecessors into Exit and NewExit 209 // Basicaly it should look like: 210 // NewExit: 211 // PN = PHI [I, Latch] 212 // ... 213 // Exit: 214 // EpilogPN = PHI [PN, EpilogPreHeader] 215 // 216 // There is EpilogPreHeader incoming block instead of NewExit as 217 // NewExit was spilt 1 more time to get EpilogPreHeader. 218 assert(PN.hasOneUse() && "The phi should have 1 use"); 219 PHINode *EpilogPN = cast<PHINode>(PN.use_begin()->getUser()); 220 assert(EpilogPN->getParent() == Exit && "EpilogPN should be in Exit block"); 221 222 // Add incoming PreHeader from branch around the Loop 223 PN.addIncoming(UndefValue::get(PN.getType()), PreHeader); 224 225 Value *V = PN.getIncomingValueForBlock(Latch); 226 Instruction *I = dyn_cast<Instruction>(V); 227 if (I && L->contains(I)) 228 // If value comes from an instruction in the loop add VMap value. 229 V = VMap.lookup(I); 230 // For the instruction out of the loop, constant or undefined value 231 // insert value itself. 232 EpilogPN->addIncoming(V, EpilogLatch); 233 234 assert(EpilogPN->getBasicBlockIndex(EpilogPreHeader) >= 0 && 235 "EpilogPN should have EpilogPreHeader incoming block"); 236 // Change EpilogPreHeader incoming block to NewExit. 237 EpilogPN->setIncomingBlock(EpilogPN->getBasicBlockIndex(EpilogPreHeader), 238 NewExit); 239 // Now PHIs should look like: 240 // NewExit: 241 // PN = PHI [I, Latch], [undef, PreHeader] 242 // ... 243 // Exit: 244 // EpilogPN = PHI [PN, NewExit], [VMap[I], EpilogLatch] 245 } 246 247 // Create PHI nodes at NewExit (from the unrolling loop Latch and PreHeader). 248 // Update corresponding PHI nodes in epilog loop. 249 for (BasicBlock *Succ : successors(Latch)) { 250 // Skip this as we already updated phis in exit blocks. 251 if (!L->contains(Succ)) 252 continue; 253 for (PHINode &PN : Succ->phis()) { 254 // Add new PHI nodes to the loop exit block and update epilog 255 // PHIs with the new PHI values. 256 PHINode *NewPN = PHINode::Create(PN.getType(), 2, PN.getName() + ".unr", 257 NewExit->getFirstNonPHI()); 258 // Adding a value to the new PHI node from the unrolling loop preheader. 259 NewPN->addIncoming(PN.getIncomingValueForBlock(NewPreHeader), PreHeader); 260 // Adding a value to the new PHI node from the unrolling loop latch. 261 NewPN->addIncoming(PN.getIncomingValueForBlock(Latch), Latch); 262 263 // Update the existing PHI node operand with the value from the new PHI 264 // node. Corresponding instruction in epilog loop should be PHI. 265 PHINode *VPN = cast<PHINode>(VMap[&PN]); 266 VPN->setIncomingValueForBlock(EpilogPreHeader, NewPN); 267 } 268 } 269 270 Instruction *InsertPt = NewExit->getTerminator(); 271 IRBuilder<> B(InsertPt); 272 Value *BrLoopExit = B.CreateIsNotNull(ModVal, "lcmp.mod"); 273 assert(Exit && "Loop must have a single exit block only"); 274 // Split the epilogue exit to maintain loop canonicalization guarantees 275 SmallVector<BasicBlock*, 4> Preds(predecessors(Exit)); 276 SplitBlockPredecessors(Exit, Preds, ".epilog-lcssa", DT, LI, nullptr, 277 PreserveLCSSA); 278 // Add the branch to the exit block (around the unrolling loop) 279 B.CreateCondBr(BrLoopExit, EpilogPreHeader, Exit); 280 InsertPt->eraseFromParent(); 281 if (DT) 282 DT->changeImmediateDominator(Exit, NewExit); 283 284 // Split the main loop exit to maintain canonicalization guarantees. 285 SmallVector<BasicBlock*, 4> NewExitPreds{Latch}; 286 SplitBlockPredecessors(NewExit, NewExitPreds, ".loopexit", DT, LI, nullptr, 287 PreserveLCSSA); 288 } 289 290 /// Create a clone of the blocks in a loop and connect them together. 291 /// If CreateRemainderLoop is false, loop structure will not be cloned, 292 /// otherwise a new loop will be created including all cloned blocks, and the 293 /// iterator of it switches to count NewIter down to 0. 294 /// The cloned blocks should be inserted between InsertTop and InsertBot. 295 /// If loop structure is cloned InsertTop should be new preheader, InsertBot 296 /// new loop exit. 297 /// Return the new cloned loop that is created when CreateRemainderLoop is true. 298 static Loop * 299 CloneLoopBlocks(Loop *L, Value *NewIter, const bool CreateRemainderLoop, 300 const bool UseEpilogRemainder, const bool UnrollRemainder, 301 BasicBlock *InsertTop, 302 BasicBlock *InsertBot, BasicBlock *Preheader, 303 std::vector<BasicBlock *> &NewBlocks, LoopBlocksDFS &LoopBlocks, 304 ValueToValueMapTy &VMap, DominatorTree *DT, LoopInfo *LI) { 305 StringRef suffix = UseEpilogRemainder ? "epil" : "prol"; 306 BasicBlock *Header = L->getHeader(); 307 BasicBlock *Latch = L->getLoopLatch(); 308 Function *F = Header->getParent(); 309 LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO(); 310 LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO(); 311 Loop *ParentLoop = L->getParentLoop(); 312 NewLoopsMap NewLoops; 313 NewLoops[ParentLoop] = ParentLoop; 314 if (!CreateRemainderLoop) 315 NewLoops[L] = ParentLoop; 316 317 // For each block in the original loop, create a new copy, 318 // and update the value map with the newly created values. 319 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) { 320 BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, "." + suffix, F); 321 NewBlocks.push_back(NewBB); 322 323 // If we're unrolling the outermost loop, there's no remainder loop, 324 // and this block isn't in a nested loop, then the new block is not 325 // in any loop. Otherwise, add it to loopinfo. 326 if (CreateRemainderLoop || LI->getLoopFor(*BB) != L || ParentLoop) 327 addClonedBlockToLoopInfo(*BB, NewBB, LI, NewLoops); 328 329 VMap[*BB] = NewBB; 330 if (Header == *BB) { 331 // For the first block, add a CFG connection to this newly 332 // created block. 333 InsertTop->getTerminator()->setSuccessor(0, NewBB); 334 } 335 336 if (DT) { 337 if (Header == *BB) { 338 // The header is dominated by the preheader. 339 DT->addNewBlock(NewBB, InsertTop); 340 } else { 341 // Copy information from original loop to unrolled loop. 342 BasicBlock *IDomBB = DT->getNode(*BB)->getIDom()->getBlock(); 343 DT->addNewBlock(NewBB, cast<BasicBlock>(VMap[IDomBB])); 344 } 345 } 346 347 if (Latch == *BB) { 348 // For the last block, if CreateRemainderLoop is false, create a direct 349 // jump to InsertBot. If not, create a loop back to cloned head. 350 VMap.erase((*BB)->getTerminator()); 351 BasicBlock *FirstLoopBB = cast<BasicBlock>(VMap[Header]); 352 BranchInst *LatchBR = cast<BranchInst>(NewBB->getTerminator()); 353 IRBuilder<> Builder(LatchBR); 354 if (!CreateRemainderLoop) { 355 Builder.CreateBr(InsertBot); 356 } else { 357 PHINode *NewIdx = PHINode::Create(NewIter->getType(), 2, 358 suffix + ".iter", 359 FirstLoopBB->getFirstNonPHI()); 360 Value *IdxSub = 361 Builder.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1), 362 NewIdx->getName() + ".sub"); 363 Value *IdxCmp = 364 Builder.CreateIsNotNull(IdxSub, NewIdx->getName() + ".cmp"); 365 Builder.CreateCondBr(IdxCmp, FirstLoopBB, InsertBot); 366 NewIdx->addIncoming(NewIter, InsertTop); 367 NewIdx->addIncoming(IdxSub, NewBB); 368 } 369 LatchBR->eraseFromParent(); 370 } 371 } 372 373 // Change the incoming values to the ones defined in the preheader or 374 // cloned loop. 375 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) { 376 PHINode *NewPHI = cast<PHINode>(VMap[&*I]); 377 if (!CreateRemainderLoop) { 378 if (UseEpilogRemainder) { 379 unsigned idx = NewPHI->getBasicBlockIndex(Preheader); 380 NewPHI->setIncomingBlock(idx, InsertTop); 381 NewPHI->removeIncomingValue(Latch, false); 382 } else { 383 VMap[&*I] = NewPHI->getIncomingValueForBlock(Preheader); 384 cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI); 385 } 386 } else { 387 unsigned idx = NewPHI->getBasicBlockIndex(Preheader); 388 NewPHI->setIncomingBlock(idx, InsertTop); 389 BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]); 390 idx = NewPHI->getBasicBlockIndex(Latch); 391 Value *InVal = NewPHI->getIncomingValue(idx); 392 NewPHI->setIncomingBlock(idx, NewLatch); 393 if (Value *V = VMap.lookup(InVal)) 394 NewPHI->setIncomingValue(idx, V); 395 } 396 } 397 if (CreateRemainderLoop) { 398 Loop *NewLoop = NewLoops[L]; 399 MDNode *LoopID = NewLoop->getLoopID(); 400 assert(NewLoop && "L should have been cloned"); 401 402 // Only add loop metadata if the loop is not going to be completely 403 // unrolled. 404 if (UnrollRemainder) 405 return NewLoop; 406 407 Optional<MDNode *> NewLoopID = makeFollowupLoopID( 408 LoopID, {LLVMLoopUnrollFollowupAll, LLVMLoopUnrollFollowupRemainder}); 409 if (NewLoopID.hasValue()) { 410 NewLoop->setLoopID(NewLoopID.getValue()); 411 412 // Do not setLoopAlreadyUnrolled if loop attributes have been defined 413 // explicitly. 414 return NewLoop; 415 } 416 417 // Add unroll disable metadata to disable future unrolling for this loop. 418 NewLoop->setLoopAlreadyUnrolled(); 419 return NewLoop; 420 } 421 else 422 return nullptr; 423 } 424 425 /// Returns true if we can safely unroll a multi-exit/exiting loop. OtherExits 426 /// is populated with all the loop exit blocks other than the LatchExit block. 427 static bool 428 canSafelyUnrollMultiExitLoop(Loop *L, SmallVectorImpl<BasicBlock *> &OtherExits, 429 BasicBlock *LatchExit, bool PreserveLCSSA, 430 bool UseEpilogRemainder) { 431 432 // We currently have some correctness constrains in unrolling a multi-exit 433 // loop. Check for these below. 434 435 // We rely on LCSSA form being preserved when the exit blocks are transformed. 436 if (!PreserveLCSSA) 437 return false; 438 SmallVector<BasicBlock *, 4> Exits; 439 L->getUniqueExitBlocks(Exits); 440 for (auto *BB : Exits) 441 if (BB != LatchExit) 442 OtherExits.push_back(BB); 443 444 // TODO: Support multiple exiting blocks jumping to the `LatchExit` when 445 // UnrollRuntimeMultiExit is true. This will need updating the logic in 446 // connectEpilog/connectProlog. 447 if (!LatchExit->getSinglePredecessor()) { 448 LLVM_DEBUG( 449 dbgs() << "Bailout for multi-exit handling when latch exit has >1 " 450 "predecessor.\n"); 451 return false; 452 } 453 // FIXME: We bail out of multi-exit unrolling when epilog loop is generated 454 // and L is an inner loop. This is because in presence of multiple exits, the 455 // outer loop is incorrect: we do not add the EpilogPreheader and exit to the 456 // outer loop. This is automatically handled in the prolog case, so we do not 457 // have that bug in prolog generation. 458 if (UseEpilogRemainder && L->getParentLoop()) 459 return false; 460 461 // All constraints have been satisfied. 462 return true; 463 } 464 465 /// Returns true if we can profitably unroll the multi-exit loop L. Currently, 466 /// we return true only if UnrollRuntimeMultiExit is set to true. 467 static bool canProfitablyUnrollMultiExitLoop( 468 Loop *L, SmallVectorImpl<BasicBlock *> &OtherExits, BasicBlock *LatchExit, 469 bool PreserveLCSSA, bool UseEpilogRemainder) { 470 471 #if !defined(NDEBUG) 472 SmallVector<BasicBlock *, 8> OtherExitsDummyCheck; 473 assert(canSafelyUnrollMultiExitLoop(L, OtherExitsDummyCheck, LatchExit, 474 PreserveLCSSA, UseEpilogRemainder) && 475 "Should be safe to unroll before checking profitability!"); 476 #endif 477 478 // Priority goes to UnrollRuntimeMultiExit if it's supplied. 479 if (UnrollRuntimeMultiExit.getNumOccurrences()) 480 return UnrollRuntimeMultiExit; 481 482 // The main pain point with multi-exit loop unrolling is that once unrolled, 483 // we will not be able to merge all blocks into a straight line code. 484 // There are branches within the unrolled loop that go to the OtherExits. 485 // The second point is the increase in code size, but this is true 486 // irrespective of multiple exits. 487 488 // Note: Both the heuristics below are coarse grained. We are essentially 489 // enabling unrolling of loops that have a single side exit other than the 490 // normal LatchExit (i.e. exiting into a deoptimize block). 491 // The heuristics considered are: 492 // 1. low number of branches in the unrolled version. 493 // 2. high predictability of these extra branches. 494 // We avoid unrolling loops that have more than two exiting blocks. This 495 // limits the total number of branches in the unrolled loop to be atmost 496 // the unroll factor (since one of the exiting blocks is the latch block). 497 SmallVector<BasicBlock*, 4> ExitingBlocks; 498 L->getExitingBlocks(ExitingBlocks); 499 if (ExitingBlocks.size() > 2) 500 return false; 501 502 // The second heuristic is that L has one exit other than the latchexit and 503 // that exit is a deoptimize block. We know that deoptimize blocks are rarely 504 // taken, which also implies the branch leading to the deoptimize block is 505 // highly predictable. 506 return (OtherExits.size() == 1 && 507 OtherExits[0]->getTerminatingDeoptimizeCall()); 508 // TODO: These can be fine-tuned further to consider code size or deopt states 509 // that are captured by the deoptimize exit block. 510 // Also, we can extend this to support more cases, if we actually 511 // know of kinds of multiexit loops that would benefit from unrolling. 512 } 513 514 /// Insert code in the prolog/epilog code when unrolling a loop with a 515 /// run-time trip-count. 516 /// 517 /// This method assumes that the loop unroll factor is total number 518 /// of loop bodies in the loop after unrolling. (Some folks refer 519 /// to the unroll factor as the number of *extra* copies added). 520 /// We assume also that the loop unroll factor is a power-of-two. So, after 521 /// unrolling the loop, the number of loop bodies executed is 2, 522 /// 4, 8, etc. Note - LLVM converts the if-then-sequence to a switch 523 /// instruction in SimplifyCFG.cpp. Then, the backend decides how code for 524 /// the switch instruction is generated. 525 /// 526 /// ***Prolog case*** 527 /// extraiters = tripcount % loopfactor 528 /// if (extraiters == 0) jump Loop: 529 /// else jump Prol: 530 /// Prol: LoopBody; 531 /// extraiters -= 1 // Omitted if unroll factor is 2. 532 /// if (extraiters != 0) jump Prol: // Omitted if unroll factor is 2. 533 /// if (tripcount < loopfactor) jump End: 534 /// Loop: 535 /// ... 536 /// End: 537 /// 538 /// ***Epilog case*** 539 /// extraiters = tripcount % loopfactor 540 /// if (tripcount < loopfactor) jump LoopExit: 541 /// unroll_iters = tripcount - extraiters 542 /// Loop: LoopBody; (executes unroll_iter times); 543 /// unroll_iter -= 1 544 /// if (unroll_iter != 0) jump Loop: 545 /// LoopExit: 546 /// if (extraiters == 0) jump EpilExit: 547 /// Epil: LoopBody; (executes extraiters times) 548 /// extraiters -= 1 // Omitted if unroll factor is 2. 549 /// if (extraiters != 0) jump Epil: // Omitted if unroll factor is 2. 550 /// EpilExit: 551 552 bool llvm::UnrollRuntimeLoopRemainder(Loop *L, unsigned Count, 553 bool AllowExpensiveTripCount, 554 bool UseEpilogRemainder, 555 bool UnrollRemainder, bool ForgetAllSCEV, 556 LoopInfo *LI, ScalarEvolution *SE, 557 DominatorTree *DT, AssumptionCache *AC, 558 bool PreserveLCSSA, Loop **ResultLoop) { 559 LLVM_DEBUG(dbgs() << "Trying runtime unrolling on Loop: \n"); 560 LLVM_DEBUG(L->dump()); 561 LLVM_DEBUG(UseEpilogRemainder ? dbgs() << "Using epilog remainder.\n" 562 : dbgs() << "Using prolog remainder.\n"); 563 564 // Make sure the loop is in canonical form. 565 if (!L->isLoopSimplifyForm()) { 566 LLVM_DEBUG(dbgs() << "Not in simplify form!\n"); 567 return false; 568 } 569 570 // Guaranteed by LoopSimplifyForm. 571 BasicBlock *Latch = L->getLoopLatch(); 572 BasicBlock *Header = L->getHeader(); 573 574 BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator()); 575 576 if (!LatchBR || LatchBR->isUnconditional()) { 577 // The loop-rotate pass can be helpful to avoid this in many cases. 578 LLVM_DEBUG( 579 dbgs() 580 << "Loop latch not terminated by a conditional branch.\n"); 581 return false; 582 } 583 584 unsigned ExitIndex = LatchBR->getSuccessor(0) == Header ? 1 : 0; 585 BasicBlock *LatchExit = LatchBR->getSuccessor(ExitIndex); 586 587 if (L->contains(LatchExit)) { 588 // Cloning the loop basic blocks (`CloneLoopBlocks`) requires that one of the 589 // targets of the Latch be an exit block out of the loop. 590 LLVM_DEBUG( 591 dbgs() 592 << "One of the loop latch successors must be the exit block.\n"); 593 return false; 594 } 595 596 // These are exit blocks other than the target of the latch exiting block. 597 SmallVector<BasicBlock *, 4> OtherExits; 598 bool isMultiExitUnrollingEnabled = 599 canSafelyUnrollMultiExitLoop(L, OtherExits, LatchExit, PreserveLCSSA, 600 UseEpilogRemainder) && 601 canProfitablyUnrollMultiExitLoop(L, OtherExits, LatchExit, PreserveLCSSA, 602 UseEpilogRemainder); 603 // Support only single exit and exiting block unless multi-exit loop unrolling is enabled. 604 if (!isMultiExitUnrollingEnabled && 605 (!L->getExitingBlock() || OtherExits.size())) { 606 LLVM_DEBUG( 607 dbgs() 608 << "Multiple exit/exiting blocks in loop and multi-exit unrolling not " 609 "enabled!\n"); 610 return false; 611 } 612 // Use Scalar Evolution to compute the trip count. This allows more loops to 613 // be unrolled than relying on induction var simplification. 614 if (!SE) 615 return false; 616 617 // Only unroll loops with a computable trip count, and the trip count needs 618 // to be an int value (allowing a pointer type is a TODO item). 619 // We calculate the backedge count by using getExitCount on the Latch block, 620 // which is proven to be the only exiting block in this loop. This is same as 621 // calculating getBackedgeTakenCount on the loop (which computes SCEV for all 622 // exiting blocks). 623 const SCEV *BECountSC = SE->getExitCount(L, Latch); 624 if (isa<SCEVCouldNotCompute>(BECountSC) || 625 !BECountSC->getType()->isIntegerTy()) { 626 LLVM_DEBUG(dbgs() << "Could not compute exit block SCEV\n"); 627 return false; 628 } 629 630 unsigned BEWidth = cast<IntegerType>(BECountSC->getType())->getBitWidth(); 631 632 // Add 1 since the backedge count doesn't include the first loop iteration. 633 const SCEV *TripCountSC = 634 SE->getAddExpr(BECountSC, SE->getConstant(BECountSC->getType(), 1)); 635 if (isa<SCEVCouldNotCompute>(TripCountSC)) { 636 LLVM_DEBUG(dbgs() << "Could not compute trip count SCEV.\n"); 637 return false; 638 } 639 640 BasicBlock *PreHeader = L->getLoopPreheader(); 641 BranchInst *PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator()); 642 const DataLayout &DL = Header->getModule()->getDataLayout(); 643 SCEVExpander Expander(*SE, DL, "loop-unroll"); 644 if (!AllowExpensiveTripCount && 645 Expander.isHighCostExpansion(TripCountSC, L, PreHeaderBR)) { 646 LLVM_DEBUG(dbgs() << "High cost for expanding trip count scev!\n"); 647 return false; 648 } 649 650 // This constraint lets us deal with an overflowing trip count easily; see the 651 // comment on ModVal below. 652 if (Log2_32(Count) > BEWidth) { 653 LLVM_DEBUG( 654 dbgs() 655 << "Count failed constraint on overflow trip count calculation.\n"); 656 return false; 657 } 658 659 // Loop structure is the following: 660 // 661 // PreHeader 662 // Header 663 // ... 664 // Latch 665 // LatchExit 666 667 BasicBlock *NewPreHeader; 668 BasicBlock *NewExit = nullptr; 669 BasicBlock *PrologExit = nullptr; 670 BasicBlock *EpilogPreHeader = nullptr; 671 BasicBlock *PrologPreHeader = nullptr; 672 673 if (UseEpilogRemainder) { 674 // If epilog remainder 675 // Split PreHeader to insert a branch around loop for unrolling. 676 NewPreHeader = SplitBlock(PreHeader, PreHeader->getTerminator(), DT, LI); 677 NewPreHeader->setName(PreHeader->getName() + ".new"); 678 // Split LatchExit to create phi nodes from branch above. 679 SmallVector<BasicBlock*, 4> Preds(predecessors(LatchExit)); 680 NewExit = SplitBlockPredecessors(LatchExit, Preds, ".unr-lcssa", DT, LI, 681 nullptr, PreserveLCSSA); 682 // NewExit gets its DebugLoc from LatchExit, which is not part of the 683 // original Loop. 684 // Fix this by setting Loop's DebugLoc to NewExit. 685 auto *NewExitTerminator = NewExit->getTerminator(); 686 NewExitTerminator->setDebugLoc(Header->getTerminator()->getDebugLoc()); 687 // Split NewExit to insert epilog remainder loop. 688 EpilogPreHeader = SplitBlock(NewExit, NewExitTerminator, DT, LI); 689 EpilogPreHeader->setName(Header->getName() + ".epil.preheader"); 690 } else { 691 // If prolog remainder 692 // Split the original preheader twice to insert prolog remainder loop 693 PrologPreHeader = SplitEdge(PreHeader, Header, DT, LI); 694 PrologPreHeader->setName(Header->getName() + ".prol.preheader"); 695 PrologExit = SplitBlock(PrologPreHeader, PrologPreHeader->getTerminator(), 696 DT, LI); 697 PrologExit->setName(Header->getName() + ".prol.loopexit"); 698 // Split PrologExit to get NewPreHeader. 699 NewPreHeader = SplitBlock(PrologExit, PrologExit->getTerminator(), DT, LI); 700 NewPreHeader->setName(PreHeader->getName() + ".new"); 701 } 702 // Loop structure should be the following: 703 // Epilog Prolog 704 // 705 // PreHeader PreHeader 706 // *NewPreHeader *PrologPreHeader 707 // Header *PrologExit 708 // ... *NewPreHeader 709 // Latch Header 710 // *NewExit ... 711 // *EpilogPreHeader Latch 712 // LatchExit LatchExit 713 714 // Calculate conditions for branch around loop for unrolling 715 // in epilog case and around prolog remainder loop in prolog case. 716 // Compute the number of extra iterations required, which is: 717 // extra iterations = run-time trip count % loop unroll factor 718 PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator()); 719 Value *TripCount = Expander.expandCodeFor(TripCountSC, TripCountSC->getType(), 720 PreHeaderBR); 721 Value *BECount = Expander.expandCodeFor(BECountSC, BECountSC->getType(), 722 PreHeaderBR); 723 IRBuilder<> B(PreHeaderBR); 724 Value *ModVal; 725 // Calculate ModVal = (BECount + 1) % Count. 726 // Note that TripCount is BECount + 1. 727 if (isPowerOf2_32(Count)) { 728 // When Count is power of 2 we don't BECount for epilog case, however we'll 729 // need it for a branch around unrolling loop for prolog case. 730 ModVal = B.CreateAnd(TripCount, Count - 1, "xtraiter"); 731 // 1. There are no iterations to be run in the prolog/epilog loop. 732 // OR 733 // 2. The addition computing TripCount overflowed. 734 // 735 // If (2) is true, we know that TripCount really is (1 << BEWidth) and so 736 // the number of iterations that remain to be run in the original loop is a 737 // multiple Count == (1 << Log2(Count)) because Log2(Count) <= BEWidth (we 738 // explicitly check this above). 739 } else { 740 // As (BECount + 1) can potentially unsigned overflow we count 741 // (BECount % Count) + 1 which is overflow safe as BECount % Count < Count. 742 Value *ModValTmp = B.CreateURem(BECount, 743 ConstantInt::get(BECount->getType(), 744 Count)); 745 Value *ModValAdd = B.CreateAdd(ModValTmp, 746 ConstantInt::get(ModValTmp->getType(), 1)); 747 // At that point (BECount % Count) + 1 could be equal to Count. 748 // To handle this case we need to take mod by Count one more time. 749 ModVal = B.CreateURem(ModValAdd, 750 ConstantInt::get(BECount->getType(), Count), 751 "xtraiter"); 752 } 753 Value *BranchVal = 754 UseEpilogRemainder ? B.CreateICmpULT(BECount, 755 ConstantInt::get(BECount->getType(), 756 Count - 1)) : 757 B.CreateIsNotNull(ModVal, "lcmp.mod"); 758 BasicBlock *RemainderLoop = UseEpilogRemainder ? NewExit : PrologPreHeader; 759 BasicBlock *UnrollingLoop = UseEpilogRemainder ? NewPreHeader : PrologExit; 760 // Branch to either remainder (extra iterations) loop or unrolling loop. 761 B.CreateCondBr(BranchVal, RemainderLoop, UnrollingLoop); 762 PreHeaderBR->eraseFromParent(); 763 if (DT) { 764 if (UseEpilogRemainder) 765 DT->changeImmediateDominator(NewExit, PreHeader); 766 else 767 DT->changeImmediateDominator(PrologExit, PreHeader); 768 } 769 Function *F = Header->getParent(); 770 // Get an ordered list of blocks in the loop to help with the ordering of the 771 // cloned blocks in the prolog/epilog code 772 LoopBlocksDFS LoopBlocks(L); 773 LoopBlocks.perform(LI); 774 775 // 776 // For each extra loop iteration, create a copy of the loop's basic blocks 777 // and generate a condition that branches to the copy depending on the 778 // number of 'left over' iterations. 779 // 780 std::vector<BasicBlock *> NewBlocks; 781 ValueToValueMapTy VMap; 782 783 // For unroll factor 2 remainder loop will have 1 iterations. 784 // Do not create 1 iteration loop. 785 bool CreateRemainderLoop = (Count != 2); 786 787 // Clone all the basic blocks in the loop. If Count is 2, we don't clone 788 // the loop, otherwise we create a cloned loop to execute the extra 789 // iterations. This function adds the appropriate CFG connections. 790 BasicBlock *InsertBot = UseEpilogRemainder ? LatchExit : PrologExit; 791 BasicBlock *InsertTop = UseEpilogRemainder ? EpilogPreHeader : PrologPreHeader; 792 Loop *remainderLoop = CloneLoopBlocks( 793 L, ModVal, CreateRemainderLoop, UseEpilogRemainder, UnrollRemainder, 794 InsertTop, InsertBot, 795 NewPreHeader, NewBlocks, LoopBlocks, VMap, DT, LI); 796 797 // Insert the cloned blocks into the function. 798 F->getBasicBlockList().splice(InsertBot->getIterator(), 799 F->getBasicBlockList(), 800 NewBlocks[0]->getIterator(), 801 F->end()); 802 803 // Now the loop blocks are cloned and the other exiting blocks from the 804 // remainder are connected to the original Loop's exit blocks. The remaining 805 // work is to update the phi nodes in the original loop, and take in the 806 // values from the cloned region. 807 for (auto *BB : OtherExits) { 808 for (auto &II : *BB) { 809 810 // Given we preserve LCSSA form, we know that the values used outside the 811 // loop will be used through these phi nodes at the exit blocks that are 812 // transformed below. 813 if (!isa<PHINode>(II)) 814 break; 815 PHINode *Phi = cast<PHINode>(&II); 816 unsigned oldNumOperands = Phi->getNumIncomingValues(); 817 // Add the incoming values from the remainder code to the end of the phi 818 // node. 819 for (unsigned i =0; i < oldNumOperands; i++){ 820 Value *newVal = VMap.lookup(Phi->getIncomingValue(i)); 821 // newVal can be a constant or derived from values outside the loop, and 822 // hence need not have a VMap value. Also, since lookup already generated 823 // a default "null" VMap entry for this value, we need to populate that 824 // VMap entry correctly, with the mapped entry being itself. 825 if (!newVal) { 826 newVal = Phi->getIncomingValue(i); 827 VMap[Phi->getIncomingValue(i)] = Phi->getIncomingValue(i); 828 } 829 Phi->addIncoming(newVal, 830 cast<BasicBlock>(VMap[Phi->getIncomingBlock(i)])); 831 } 832 } 833 #if defined(EXPENSIVE_CHECKS) && !defined(NDEBUG) 834 for (BasicBlock *SuccBB : successors(BB)) { 835 assert(!(any_of(OtherExits, 836 [SuccBB](BasicBlock *EB) { return EB == SuccBB; }) || 837 SuccBB == LatchExit) && 838 "Breaks the definition of dedicated exits!"); 839 } 840 #endif 841 } 842 843 // Update the immediate dominator of the exit blocks and blocks that are 844 // reachable from the exit blocks. This is needed because we now have paths 845 // from both the original loop and the remainder code reaching the exit 846 // blocks. While the IDom of these exit blocks were from the original loop, 847 // now the IDom is the preheader (which decides whether the original loop or 848 // remainder code should run). 849 if (DT && !L->getExitingBlock()) { 850 SmallVector<BasicBlock *, 16> ChildrenToUpdate; 851 // NB! We have to examine the dom children of all loop blocks, not just 852 // those which are the IDom of the exit blocks. This is because blocks 853 // reachable from the exit blocks can have their IDom as the nearest common 854 // dominator of the exit blocks. 855 for (auto *BB : L->blocks()) { 856 auto *DomNodeBB = DT->getNode(BB); 857 for (auto *DomChild : DomNodeBB->getChildren()) { 858 auto *DomChildBB = DomChild->getBlock(); 859 if (!L->contains(LI->getLoopFor(DomChildBB))) 860 ChildrenToUpdate.push_back(DomChildBB); 861 } 862 } 863 for (auto *BB : ChildrenToUpdate) 864 DT->changeImmediateDominator(BB, PreHeader); 865 } 866 867 // Loop structure should be the following: 868 // Epilog Prolog 869 // 870 // PreHeader PreHeader 871 // NewPreHeader PrologPreHeader 872 // Header PrologHeader 873 // ... ... 874 // Latch PrologLatch 875 // NewExit PrologExit 876 // EpilogPreHeader NewPreHeader 877 // EpilogHeader Header 878 // ... ... 879 // EpilogLatch Latch 880 // LatchExit LatchExit 881 882 // Rewrite the cloned instruction operands to use the values created when the 883 // clone is created. 884 for (BasicBlock *BB : NewBlocks) { 885 for (Instruction &I : *BB) { 886 RemapInstruction(&I, VMap, 887 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); 888 } 889 } 890 891 if (UseEpilogRemainder) { 892 // Connect the epilog code to the original loop and update the 893 // PHI functions. 894 ConnectEpilog(L, ModVal, NewExit, LatchExit, PreHeader, 895 EpilogPreHeader, NewPreHeader, VMap, DT, LI, 896 PreserveLCSSA); 897 898 // Update counter in loop for unrolling. 899 // I should be multiply of Count. 900 IRBuilder<> B2(NewPreHeader->getTerminator()); 901 Value *TestVal = B2.CreateSub(TripCount, ModVal, "unroll_iter"); 902 BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator()); 903 B2.SetInsertPoint(LatchBR); 904 PHINode *NewIdx = PHINode::Create(TestVal->getType(), 2, "niter", 905 Header->getFirstNonPHI()); 906 Value *IdxSub = 907 B2.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1), 908 NewIdx->getName() + ".nsub"); 909 Value *IdxCmp; 910 if (LatchBR->getSuccessor(0) == Header) 911 IdxCmp = B2.CreateIsNotNull(IdxSub, NewIdx->getName() + ".ncmp"); 912 else 913 IdxCmp = B2.CreateIsNull(IdxSub, NewIdx->getName() + ".ncmp"); 914 NewIdx->addIncoming(TestVal, NewPreHeader); 915 NewIdx->addIncoming(IdxSub, Latch); 916 LatchBR->setCondition(IdxCmp); 917 } else { 918 // Connect the prolog code to the original loop and update the 919 // PHI functions. 920 ConnectProlog(L, BECount, Count, PrologExit, LatchExit, PreHeader, 921 NewPreHeader, VMap, DT, LI, PreserveLCSSA); 922 } 923 924 // If this loop is nested, then the loop unroller changes the code in the any 925 // of its parent loops, so the Scalar Evolution pass needs to be run again. 926 SE->forgetTopmostLoop(L); 927 928 // Verify that the Dom Tree is correct. 929 #if defined(EXPENSIVE_CHECKS) && !defined(NDEBUG) 930 if (DT) 931 assert(DT->verify(DominatorTree::VerificationLevel::Full)); 932 #endif 933 934 // Canonicalize to LoopSimplifyForm both original and remainder loops. We 935 // cannot rely on the LoopUnrollPass to do this because it only does 936 // canonicalization for parent/subloops and not the sibling loops. 937 if (OtherExits.size() > 0) { 938 // Generate dedicated exit blocks for the original loop, to preserve 939 // LoopSimplifyForm. 940 formDedicatedExitBlocks(L, DT, LI, nullptr, PreserveLCSSA); 941 // Generate dedicated exit blocks for the remainder loop if one exists, to 942 // preserve LoopSimplifyForm. 943 if (remainderLoop) 944 formDedicatedExitBlocks(remainderLoop, DT, LI, nullptr, PreserveLCSSA); 945 } 946 947 auto UnrollResult = LoopUnrollResult::Unmodified; 948 if (remainderLoop && UnrollRemainder) { 949 LLVM_DEBUG(dbgs() << "Unrolling remainder loop\n"); 950 UnrollResult = 951 UnrollLoop(remainderLoop, 952 {/*Count*/ Count - 1, /*TripCount*/ Count - 1, 953 /*Force*/ false, /*AllowRuntime*/ false, 954 /*AllowExpensiveTripCount*/ false, /*PreserveCondBr*/ true, 955 /*PreserveOnlyFirst*/ false, /*TripMultiple*/ 1, 956 /*PeelCount*/ 0, /*UnrollRemainder*/ false, ForgetAllSCEV}, 957 LI, SE, DT, AC, /*ORE*/ nullptr, PreserveLCSSA); 958 } 959 960 if (ResultLoop && UnrollResult != LoopUnrollResult::FullyUnrolled) 961 *ResultLoop = remainderLoop; 962 NumRuntimeUnrolled++; 963 return true; 964 } 965