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