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