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. Other strategies 20 // include generate a loop before or after the unrolled loop. 21 // 22 //===----------------------------------------------------------------------===// 23 24 #include "llvm/Transforms/Utils/UnrollLoop.h" 25 #include "llvm/ADT/Statistic.h" 26 #include "llvm/Analysis/AliasAnalysis.h" 27 #include "llvm/Analysis/LoopIterator.h" 28 #include "llvm/Analysis/LoopPass.h" 29 #include "llvm/Analysis/ScalarEvolution.h" 30 #include "llvm/Analysis/ScalarEvolutionExpander.h" 31 #include "llvm/IR/BasicBlock.h" 32 #include "llvm/IR/Dominators.h" 33 #include "llvm/IR/Metadata.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 <algorithm> 40 41 using namespace llvm; 42 43 #define DEBUG_TYPE "loop-unroll" 44 45 STATISTIC(NumRuntimeUnrolled, 46 "Number of loops unrolled with run-time trip counts"); 47 48 /// Connect the unrolling prolog code to the original loop. 49 /// The unrolling prolog code contains code to execute the 50 /// 'extra' iterations if the run-time trip count modulo the 51 /// unroll count is non-zero. 52 /// 53 /// This function performs the following: 54 /// - Create PHI nodes at prolog end block to combine values 55 /// that exit the prolog code and jump around the prolog. 56 /// - Add a PHI operand to a PHI node at the loop exit block 57 /// for values that exit the prolog and go around the loop. 58 /// - Branch around the original loop if the trip count is less 59 /// than the unroll factor. 60 /// 61 static void ConnectProlog(Loop *L, Value *TripCount, unsigned Count, 62 BasicBlock *LastPrologBB, BasicBlock *PrologEnd, 63 BasicBlock *OrigPH, BasicBlock *NewPH, 64 ValueToValueMapTy &VMap, AliasAnalysis *AA, 65 DominatorTree *DT, LoopInfo *LI, Pass *P) { 66 BasicBlock *Latch = L->getLoopLatch(); 67 assert(Latch && "Loop must have a latch"); 68 69 // Create a PHI node for each outgoing value from the original loop 70 // (which means it is an outgoing value from the prolog code too). 71 // The new PHI node is inserted in the prolog end basic block. 72 // The new PHI name is added as an operand of a PHI node in either 73 // the loop header or the loop exit block. 74 for (succ_iterator SBI = succ_begin(Latch), SBE = succ_end(Latch); 75 SBI != SBE; ++SBI) { 76 for (BasicBlock::iterator BBI = (*SBI)->begin(); 77 PHINode *PN = dyn_cast<PHINode>(BBI); ++BBI) { 78 79 // Add a new PHI node to the prolog end block and add the 80 // appropriate incoming values. 81 PHINode *NewPN = PHINode::Create(PN->getType(), 2, PN->getName()+".unr", 82 PrologEnd->getTerminator()); 83 // Adding a value to the new PHI node from the original loop preheader. 84 // This is the value that skips all the prolog code. 85 if (L->contains(PN)) { 86 NewPN->addIncoming(PN->getIncomingValueForBlock(NewPH), OrigPH); 87 } else { 88 NewPN->addIncoming(Constant::getNullValue(PN->getType()), OrigPH); 89 } 90 91 Value *V = PN->getIncomingValueForBlock(Latch); 92 if (Instruction *I = dyn_cast<Instruction>(V)) { 93 if (L->contains(I)) { 94 V = VMap[I]; 95 } 96 } 97 // Adding a value to the new PHI node from the last prolog block 98 // that was created. 99 NewPN->addIncoming(V, LastPrologBB); 100 101 // Update the existing PHI node operand with the value from the 102 // new PHI node. How this is done depends on if the existing 103 // PHI node is in the original loop block, or the exit block. 104 if (L->contains(PN)) { 105 PN->setIncomingValue(PN->getBasicBlockIndex(NewPH), NewPN); 106 } else { 107 PN->addIncoming(NewPN, PrologEnd); 108 } 109 } 110 } 111 112 // Create a branch around the orignal loop, which is taken if the 113 // trip count is less than the unroll factor. 114 Instruction *InsertPt = PrologEnd->getTerminator(); 115 Instruction *BrLoopExit = 116 new ICmpInst(InsertPt, ICmpInst::ICMP_ULT, TripCount, 117 ConstantInt::get(TripCount->getType(), Count)); 118 BasicBlock *Exit = L->getUniqueExitBlock(); 119 assert(Exit && "Loop must have a single exit block only"); 120 // Split the exit to maintain loop canonicalization guarantees 121 SmallVector<BasicBlock*, 4> Preds(pred_begin(Exit), pred_end(Exit)); 122 SplitBlockPredecessors(Exit, Preds, ".unr-lcssa", AA, DT, LI, 123 P->mustPreserveAnalysisID(LCSSAID)); 124 // Add the branch to the exit block (around the unrolled loop) 125 BranchInst::Create(Exit, NewPH, BrLoopExit, InsertPt); 126 InsertPt->eraseFromParent(); 127 } 128 129 /// Create a clone of the blocks in a loop and connect them together. 130 /// If UnrollProlog is true, loop structure will not be cloned, otherwise a new 131 /// loop will be created including all cloned blocks, and the iterator of it 132 /// switches to count NewIter down to 0. 133 /// 134 static void CloneLoopBlocks(Loop *L, Value *NewIter, const bool UnrollProlog, 135 BasicBlock *InsertTop, BasicBlock *InsertBot, 136 std::vector<BasicBlock *> &NewBlocks, 137 LoopBlocksDFS &LoopBlocks, ValueToValueMapTy &VMap, 138 LoopInfo *LI) { 139 BasicBlock *Preheader = L->getLoopPreheader(); 140 BasicBlock *Header = L->getHeader(); 141 BasicBlock *Latch = L->getLoopLatch(); 142 Function *F = Header->getParent(); 143 LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO(); 144 LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO(); 145 Loop *NewLoop = 0; 146 Loop *ParentLoop = L->getParentLoop(); 147 if (!UnrollProlog) { 148 NewLoop = new Loop(); 149 if (ParentLoop) 150 ParentLoop->addChildLoop(NewLoop); 151 else 152 LI->addTopLevelLoop(NewLoop); 153 } 154 155 // For each block in the original loop, create a new copy, 156 // and update the value map with the newly created values. 157 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) { 158 BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, ".prol", F); 159 NewBlocks.push_back(NewBB); 160 161 if (NewLoop) 162 NewLoop->addBasicBlockToLoop(NewBB, *LI); 163 else if (ParentLoop) 164 ParentLoop->addBasicBlockToLoop(NewBB, *LI); 165 166 VMap[*BB] = NewBB; 167 if (Header == *BB) { 168 // For the first block, add a CFG connection to this newly 169 // created block. 170 InsertTop->getTerminator()->setSuccessor(0, NewBB); 171 172 } 173 if (Latch == *BB) { 174 // For the last block, if UnrollProlog is true, create a direct jump to 175 // InsertBot. If not, create a loop back to cloned head. 176 VMap.erase((*BB)->getTerminator()); 177 BasicBlock *FirstLoopBB = cast<BasicBlock>(VMap[Header]); 178 BranchInst *LatchBR = cast<BranchInst>(NewBB->getTerminator()); 179 if (UnrollProlog) { 180 LatchBR->eraseFromParent(); 181 BranchInst::Create(InsertBot, NewBB); 182 } else { 183 PHINode *NewIdx = PHINode::Create(NewIter->getType(), 2, "prol.iter", 184 FirstLoopBB->getFirstNonPHI()); 185 IRBuilder<> Builder(LatchBR); 186 Value *IdxSub = 187 Builder.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1), 188 NewIdx->getName() + ".sub"); 189 Value *IdxCmp = 190 Builder.CreateIsNotNull(IdxSub, NewIdx->getName() + ".cmp"); 191 BranchInst::Create(FirstLoopBB, InsertBot, IdxCmp, NewBB); 192 NewIdx->addIncoming(NewIter, InsertTop); 193 NewIdx->addIncoming(IdxSub, NewBB); 194 LatchBR->eraseFromParent(); 195 } 196 } 197 } 198 199 // Change the incoming values to the ones defined in the preheader or 200 // cloned loop. 201 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) { 202 PHINode *NewPHI = cast<PHINode>(VMap[I]); 203 if (UnrollProlog) { 204 VMap[I] = NewPHI->getIncomingValueForBlock(Preheader); 205 cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI); 206 } else { 207 unsigned idx = NewPHI->getBasicBlockIndex(Preheader); 208 NewPHI->setIncomingBlock(idx, InsertTop); 209 BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]); 210 idx = NewPHI->getBasicBlockIndex(Latch); 211 Value *InVal = NewPHI->getIncomingValue(idx); 212 NewPHI->setIncomingBlock(idx, NewLatch); 213 if (VMap[InVal]) 214 NewPHI->setIncomingValue(idx, VMap[InVal]); 215 } 216 } 217 if (NewLoop) { 218 // Add unroll disable metadata to disable future unrolling for this loop. 219 SmallVector<Metadata *, 4> MDs; 220 // Reserve first location for self reference to the LoopID metadata node. 221 MDs.push_back(nullptr); 222 MDNode *LoopID = NewLoop->getLoopID(); 223 if (LoopID) { 224 // First remove any existing loop unrolling metadata. 225 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) { 226 bool IsUnrollMetadata = false; 227 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i)); 228 if (MD) { 229 const MDString *S = dyn_cast<MDString>(MD->getOperand(0)); 230 IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll."); 231 } 232 if (!IsUnrollMetadata) 233 MDs.push_back(LoopID->getOperand(i)); 234 } 235 } 236 237 LLVMContext &Context = NewLoop->getHeader()->getContext(); 238 SmallVector<Metadata *, 1> DisableOperands; 239 DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable")); 240 MDNode *DisableNode = MDNode::get(Context, DisableOperands); 241 MDs.push_back(DisableNode); 242 243 MDNode *NewLoopID = MDNode::get(Context, MDs); 244 // Set operand 0 to refer to the loop id itself. 245 NewLoopID->replaceOperandWith(0, NewLoopID); 246 NewLoop->setLoopID(NewLoopID); 247 } 248 } 249 250 /// Insert code in the prolog code when unrolling a loop with a 251 /// run-time trip-count. 252 /// 253 /// This method assumes that the loop unroll factor is total number 254 /// of loop bodes in the loop after unrolling. (Some folks refer 255 /// to the unroll factor as the number of *extra* copies added). 256 /// We assume also that the loop unroll factor is a power-of-two. So, after 257 /// unrolling the loop, the number of loop bodies executed is 2, 258 /// 4, 8, etc. Note - LLVM converts the if-then-sequence to a switch 259 /// instruction in SimplifyCFG.cpp. Then, the backend decides how code for 260 /// the switch instruction is generated. 261 /// 262 /// extraiters = tripcount % loopfactor 263 /// if (extraiters == 0) jump Loop: 264 /// else jump Prol 265 /// Prol: LoopBody; 266 /// extraiters -= 1 // Omitted if unroll factor is 2. 267 /// if (extraiters != 0) jump Prol: // Omitted if unroll factor is 2. 268 /// if (tripcount < loopfactor) jump End 269 /// Loop: 270 /// ... 271 /// End: 272 /// 273 bool llvm::UnrollRuntimeLoopProlog(Loop *L, unsigned Count, LoopInfo *LI, 274 LPPassManager *LPM) { 275 // for now, only unroll loops that contain a single exit 276 if (!L->getExitingBlock()) 277 return false; 278 279 // Make sure the loop is in canonical form, and there is a single 280 // exit block only. 281 if (!L->isLoopSimplifyForm() || !L->getUniqueExitBlock()) 282 return false; 283 284 // Use Scalar Evolution to compute the trip count. This allows more 285 // loops to be unrolled than relying on induction var simplification 286 if (!LPM) 287 return false; 288 ScalarEvolution *SE = LPM->getAnalysisIfAvailable<ScalarEvolution>(); 289 if (!SE) 290 return false; 291 292 // Only unroll loops with a computable trip count and the trip count needs 293 // to be an int value (allowing a pointer type is a TODO item) 294 const SCEV *BECount = SE->getBackedgeTakenCount(L); 295 if (isa<SCEVCouldNotCompute>(BECount) || !BECount->getType()->isIntegerTy()) 296 return false; 297 298 // If BECount is INT_MAX, we can't compute trip-count without overflow. 299 if (BECount->isAllOnesValue()) 300 return false; 301 302 // Add 1 since the backedge count doesn't include the first loop iteration 303 const SCEV *TripCountSC = 304 SE->getAddExpr(BECount, SE->getConstant(BECount->getType(), 1)); 305 if (isa<SCEVCouldNotCompute>(TripCountSC)) 306 return false; 307 308 // We only handle cases when the unroll factor is a power of 2. 309 // Count is the loop unroll factor, the number of extra copies added + 1. 310 if ((Count & (Count-1)) != 0) 311 return false; 312 313 // If this loop is nested, then the loop unroller changes the code in 314 // parent loop, so the Scalar Evolution pass needs to be run again 315 if (Loop *ParentLoop = L->getParentLoop()) 316 SE->forgetLoop(ParentLoop); 317 318 // Grab analyses that we preserve. 319 auto *DTWP = LPM->getAnalysisIfAvailable<DominatorTreeWrapperPass>(); 320 auto *DT = DTWP ? &DTWP->getDomTree() : nullptr; 321 322 BasicBlock *PH = L->getLoopPreheader(); 323 BasicBlock *Header = L->getHeader(); 324 BasicBlock *Latch = L->getLoopLatch(); 325 // It helps to splits the original preheader twice, one for the end of the 326 // prolog code and one for a new loop preheader 327 BasicBlock *PEnd = SplitEdge(PH, Header, DT, LI); 328 BasicBlock *NewPH = SplitBlock(PEnd, PEnd->getTerminator(), DT, LI); 329 BranchInst *PreHeaderBR = cast<BranchInst>(PH->getTerminator()); 330 331 // Compute the number of extra iterations required, which is: 332 // extra iterations = run-time trip count % (loop unroll factor + 1) 333 SCEVExpander Expander(*SE, "loop-unroll"); 334 Value *TripCount = Expander.expandCodeFor(TripCountSC, TripCountSC->getType(), 335 PreHeaderBR); 336 337 IRBuilder<> B(PreHeaderBR); 338 Value *ModVal = B.CreateAnd(TripCount, Count - 1, "xtraiter"); 339 340 // Check if for no extra iterations, then jump to cloned/unrolled loop. 341 // We have to check that the trip count computation didn't overflow when 342 // adding one to the backedge taken count. 343 Value *LCmp = B.CreateIsNotNull(ModVal, "lcmp.mod"); 344 Value *OverflowCheck = B.CreateIsNull(TripCount, "lcmp.overflow"); 345 Value *BranchVal = B.CreateOr(OverflowCheck, LCmp, "lcmp.or"); 346 347 // Branch to either the extra iterations or the cloned/unrolled loop 348 // We will fix up the true branch label when adding loop body copies 349 BranchInst::Create(PEnd, PEnd, BranchVal, PreHeaderBR); 350 assert(PreHeaderBR->isUnconditional() && 351 PreHeaderBR->getSuccessor(0) == PEnd && 352 "CFG edges in Preheader are not correct"); 353 PreHeaderBR->eraseFromParent(); 354 Function *F = Header->getParent(); 355 // Get an ordered list of blocks in the loop to help with the ordering of the 356 // cloned blocks in the prolog code 357 LoopBlocksDFS LoopBlocks(L); 358 LoopBlocks.perform(LI); 359 360 // 361 // For each extra loop iteration, create a copy of the loop's basic blocks 362 // and generate a condition that branches to the copy depending on the 363 // number of 'left over' iterations. 364 // 365 std::vector<BasicBlock *> NewBlocks; 366 ValueToValueMapTy VMap; 367 368 // If unroll count is 2 and we can't overflow in tripcount computation (which 369 // is BECount + 1), then we don't need a loop for prologue, and we can unroll 370 // it. We can be sure that we don't overflow only if tripcount is a constant. 371 bool UnrollPrologue = (Count == 2 && isa<ConstantInt>(TripCount)); 372 373 // Clone all the basic blocks in the loop. If Count is 2, we don't clone 374 // the loop, otherwise we create a cloned loop to execute the extra 375 // iterations. This function adds the appropriate CFG connections. 376 CloneLoopBlocks(L, ModVal, UnrollPrologue, PH, PEnd, NewBlocks, LoopBlocks, 377 VMap, LI); 378 379 // Insert the cloned blocks into function just before the original loop 380 F->getBasicBlockList().splice(PEnd, F->getBasicBlockList(), NewBlocks[0], 381 F->end()); 382 383 // Rewrite the cloned instruction operands to use the values 384 // created when the clone is created. 385 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i) { 386 for (BasicBlock::iterator I = NewBlocks[i]->begin(), 387 E = NewBlocks[i]->end(); 388 I != E; ++I) { 389 RemapInstruction(I, VMap, 390 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries); 391 } 392 } 393 394 // Connect the prolog code to the original loop and update the 395 // PHI functions. 396 BasicBlock *LastLoopBB = cast<BasicBlock>(VMap[Latch]); 397 ConnectProlog(L, TripCount, Count, LastLoopBB, PEnd, PH, NewPH, VMap, 398 /*AliasAnalysis*/ nullptr, DT, LI, LPM->getAsPass()); 399 NumRuntimeUnrolled++; 400 return true; 401 } 402