1 //===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===//
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 pass implements a simple loop unroller. It works best when loops have
11 // been canonicalized by the -indvars pass, allowing it to determine the trip
12 // counts of loops easily.
14 // This pass will multi-block loops only if they contain no non-unrolled
15 // subloops. The process of unrolling can produce extraneous basic blocks
16 // linked with unconditional branches. This will be corrected in the future.
18 //===----------------------------------------------------------------------===//
20 #define DEBUG_TYPE "loop-unroll"
21 #include "llvm/Transforms/Scalar.h"
22 #include "llvm/Constants.h"
23 #include "llvm/Function.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Analysis/ConstantFolding.h"
26 #include "llvm/Analysis/LoopInfo.h"
27 #include "llvm/Analysis/LoopPass.h"
28 #include "llvm/Transforms/Utils/Cloning.h"
29 #include "llvm/Transforms/Utils/Local.h"
30 #include "llvm/Support/CFG.h"
31 #include "llvm/Support/Compiler.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/STLExtras.h"
37 #include "llvm/ADT/SmallPtrSet.h"
38 #include "llvm/IntrinsicInst.h"
44 STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
45 STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
50 ("unroll-threshold", cl::init(100), cl::Hidden,
51 cl::desc("The cut-off point for automatic loop unrolling"));
55 ("unroll-count", cl::init(0), cl::Hidden,
56 cl::desc("Use this unroll count for all loops, for testing purposes"));
58 class VISIBILITY_HIDDEN LoopUnroll : public LoopPass {
59 LoopInfo *LI; // The current loop information
61 static char ID; // Pass ID, replacement for typeid
62 LoopUnroll() : LoopPass((intptr_t)&ID) {}
64 /// A magic value for use with the Threshold parameter to indicate
65 /// that the loop unroll should be performed regardless of how much
66 /// code expansion would result.
67 static const unsigned NoThreshold = UINT_MAX;
69 bool runOnLoop(Loop *L, LPPassManager &LPM);
70 bool unrollLoop(Loop *L, unsigned Count, unsigned Threshold);
71 BasicBlock *FoldBlockIntoPredecessor(BasicBlock *BB);
73 /// This transformation requires natural loop information & requires that
74 /// loop preheaders be inserted into the CFG...
76 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
77 AU.addRequiredID(LoopSimplifyID);
78 AU.addRequiredID(LCSSAID);
79 AU.addRequired<LoopInfo>();
80 AU.addPreservedID(LCSSAID);
81 AU.addPreserved<LoopInfo>();
84 char LoopUnroll::ID = 0;
85 RegisterPass<LoopUnroll> X("loop-unroll", "Unroll loops");
88 LoopPass *llvm::createLoopUnrollPass() { return new LoopUnroll(); }
90 /// ApproximateLoopSize - Approximate the size of the loop.
91 static unsigned ApproximateLoopSize(const Loop *L) {
93 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
94 BasicBlock *BB = L->getBlocks()[i];
95 Instruction *Term = BB->getTerminator();
96 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
97 if (isa<PHINode>(I) && BB == L->getHeader()) {
98 // Ignore PHI nodes in the header.
99 } else if (I->hasOneUse() && I->use_back() == Term) {
100 // Ignore instructions only used by the loop terminator.
101 } else if (isa<DbgInfoIntrinsic>(I)) {
102 // Ignore debug instructions
107 // TODO: Ignore expressions derived from PHI and constants if inval of phi
108 // is a constant, or if operation is associative. This will get induction
116 // RemapInstruction - Convert the instruction operands from referencing the
117 // current values into those specified by ValueMap.
119 static inline void RemapInstruction(Instruction *I,
120 DenseMap<const Value *, Value*> &ValueMap) {
121 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
122 Value *Op = I->getOperand(op);
123 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
124 if (It != ValueMap.end()) Op = It->second;
125 I->setOperand(op, Op);
129 // FoldBlockIntoPredecessor - Folds a basic block into its predecessor if it
130 // only has one predecessor, and that predecessor only has one successor.
131 // Returns the new combined block.
132 BasicBlock *LoopUnroll::FoldBlockIntoPredecessor(BasicBlock *BB) {
133 // Merge basic blocks into their predecessor if there is only one distinct
134 // pred, and if there is only one distinct successor of the predecessor, and
135 // if there are no PHI nodes.
137 BasicBlock *OnlyPred = BB->getSinglePredecessor();
138 if (!OnlyPred) return 0;
140 if (OnlyPred->getTerminator()->getNumSuccessors() != 1)
143 DOUT << "Merging: " << *BB << "into: " << *OnlyPred;
145 // Resolve any PHI nodes at the start of the block. They are all
146 // guaranteed to have exactly one entry if they exist, unless there are
147 // multiple duplicate (but guaranteed to be equal) entries for the
148 // incoming edges. This occurs when there are multiple edges from
149 // OnlyPred to OnlySucc.
151 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
152 PN->replaceAllUsesWith(PN->getIncomingValue(0));
153 BB->getInstList().pop_front(); // Delete the phi node...
156 // Delete the unconditional branch from the predecessor...
157 OnlyPred->getInstList().pop_back();
159 // Move all definitions in the successor to the predecessor...
160 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
162 // Make all PHI nodes that referred to BB now refer to Pred as their
164 BB->replaceAllUsesWith(OnlyPred);
166 std::string OldName = BB->getName();
168 // Erase basic block from the function...
170 BB->eraseFromParent();
172 // Inherit predecessor's name if it exists...
173 if (!OldName.empty() && !OnlyPred->hasName())
174 OnlyPred->setName(OldName);
179 bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
180 LI = &getAnalysis<LoopInfo>();
183 if (!unrollLoop(L, UnrollCount, UnrollThreshold))
186 // Update the loop information for this loop.
187 // If we completely unrolled the loop, remove it from the parent.
188 if (L->getNumBackEdges() == 0)
189 LPM.deleteLoopFromQueue(L);
194 /// Unroll the given loop by UnrollCount, or by a heuristically-determined
195 /// value if Count is zero. If Threshold is not NoThreshold, it is a value
196 /// to limit code size expansion. If the loop size would expand beyond the
197 /// threshold value, unrolling is suppressed. The return value is true if
198 /// any transformations are performed.
200 bool LoopUnroll::unrollLoop(Loop *L, unsigned Count, unsigned Threshold) {
201 assert(L->isLCSSAForm());
203 BasicBlock *Header = L->getHeader();
204 BasicBlock *LatchBlock = L->getLoopLatch();
205 BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
207 DOUT << "Loop Unroll: F[" << Header->getParent()->getName()
208 << "] Loop %" << Header->getName() << "\n";
210 if (!BI || BI->isUnconditional()) {
211 // The loop-rotate pass can be helpful to avoid this in many cases.
212 DOUT << " Can't unroll; loop not terminated by a conditional branch.\n";
216 // Determine the trip count and/or trip multiple. A TripCount value of zero
217 // is used to mean an unknown trip count. The TripMultiple value is the
218 // greatest known integer multiple of the trip count.
219 unsigned TripCount = 0;
220 unsigned TripMultiple = 1;
221 if (Value *TripCountValue = L->getTripCount()) {
222 if (ConstantInt *TripCountC = dyn_cast<ConstantInt>(TripCountValue)) {
223 // Guard against huge trip counts. This also guards against assertions in
224 // APInt from the use of getZExtValue, below.
225 if (TripCountC->getValue().getActiveBits() <= 32) {
226 TripCount = (unsigned)TripCountC->getZExtValue();
228 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TripCountValue)) {
229 switch (BO->getOpcode()) {
230 case BinaryOperator::Mul:
231 if (ConstantInt *MultipleC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
232 if (MultipleC->getValue().getActiveBits() <= 32) {
233 TripMultiple = (unsigned)MultipleC->getZExtValue();
242 DOUT << " Trip Count = " << TripCount << "\n";
243 if (TripMultiple != 1)
244 DOUT << " Trip Multiple = " << TripMultiple << "\n";
246 // Automatically select an unroll count.
248 // Conservative heuristic: if we know the trip count, see if we can
249 // completely unroll (subject to the threshold, checked below); otherwise
251 if (TripCount != 0) {
258 // Effectively "DCE" unrolled iterations that are beyond the tripcount
259 // and will never be executed.
260 if (TripCount != 0 && Count > TripCount)
264 assert(TripMultiple > 0);
265 assert(TripCount == 0 || TripCount % TripMultiple == 0);
267 // Enforce the threshold.
268 if (Threshold != NoThreshold) {
269 unsigned LoopSize = ApproximateLoopSize(L);
270 DOUT << " Loop Size = " << LoopSize << "\n";
271 uint64_t Size = (uint64_t)LoopSize*Count;
272 if (TripCount != 1 && Size > Threshold) {
273 DOUT << " TOO LARGE TO UNROLL: "
274 << Size << ">" << Threshold << "\n";
279 // Are we eliminating the loop control altogether?
280 bool CompletelyUnroll = Count == TripCount;
282 // If we know the trip count, we know the multiple...
283 unsigned BreakoutTrip = 0;
284 if (TripCount != 0) {
285 BreakoutTrip = TripCount % Count;
288 // Figure out what multiple to use.
289 BreakoutTrip = TripMultiple =
290 (unsigned)GreatestCommonDivisor64(Count, TripMultiple);
293 if (CompletelyUnroll) {
294 DOUT << "COMPLETELY UNROLLING loop %" << Header->getName()
295 << " with trip count " << TripCount << "!\n";
297 DOUT << "UNROLLING loop %" << Header->getName()
299 if (TripMultiple == 0 || BreakoutTrip != TripMultiple) {
300 DOUT << " with a breakout at trip " << BreakoutTrip;
301 } else if (TripMultiple != 1) {
302 DOUT << " with " << TripMultiple << " trips per branch";
307 std::vector<BasicBlock*> LoopBlocks = L->getBlocks();
309 bool ContinueOnTrue = L->contains(BI->getSuccessor(0));
310 BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);
312 // For the first iteration of the loop, we should use the precloned values for
313 // PHI nodes. Insert associations now.
314 typedef DenseMap<const Value*, Value*> ValueMapTy;
315 ValueMapTy LastValueMap;
316 std::vector<PHINode*> OrigPHINode;
317 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
318 PHINode *PN = cast<PHINode>(I);
319 OrigPHINode.push_back(PN);
321 dyn_cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock)))
322 if (L->contains(I->getParent()))
326 std::vector<BasicBlock*> Headers;
327 std::vector<BasicBlock*> Latches;
328 Headers.push_back(Header);
329 Latches.push_back(LatchBlock);
331 for (unsigned It = 1; It != Count; ++It) {
332 char SuffixBuffer[100];
333 sprintf(SuffixBuffer, ".%d", It);
335 std::vector<BasicBlock*> NewBlocks;
337 for (std::vector<BasicBlock*>::iterator BB = LoopBlocks.begin(),
338 E = LoopBlocks.end(); BB != E; ++BB) {
340 BasicBlock *New = CloneBasicBlock(*BB, ValueMap, SuffixBuffer);
341 Header->getParent()->getBasicBlockList().push_back(New);
343 // Loop over all of the PHI nodes in the block, changing them to use the
344 // incoming values from the previous block.
346 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
347 PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]);
348 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
349 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
350 if (It > 1 && L->contains(InValI->getParent()))
351 InVal = LastValueMap[InValI];
352 ValueMap[OrigPHINode[i]] = InVal;
353 New->getInstList().erase(NewPHI);
356 // Update our running map of newest clones
357 LastValueMap[*BB] = New;
358 for (ValueMapTy::iterator VI = ValueMap.begin(), VE = ValueMap.end();
360 LastValueMap[VI->first] = VI->second;
362 L->addBasicBlockToLoop(New, LI->getBase());
364 // Add phi entries for newly created values to all exit blocks except
365 // the successor of the latch block. The successor of the exit block will
366 // be updated specially after unrolling all the way.
367 if (*BB != LatchBlock)
368 for (Value::use_iterator UI = (*BB)->use_begin(), UE = (*BB)->use_end();
370 Instruction *UseInst = cast<Instruction>(*UI);
372 if (isa<PHINode>(UseInst) && !L->contains(UseInst->getParent())) {
373 PHINode *phi = cast<PHINode>(UseInst);
374 Value *Incoming = phi->getIncomingValueForBlock(*BB);
375 phi->addIncoming(Incoming, New);
379 // Keep track of new headers and latches as we create them, so that
380 // we can insert the proper branches later.
382 Headers.push_back(New);
383 if (*BB == LatchBlock) {
384 Latches.push_back(New);
386 // Also, clear out the new latch's back edge so that it doesn't look
387 // like a new loop, so that it's amenable to being merged with adjacent
389 TerminatorInst *Term = New->getTerminator();
390 assert(L->contains(Term->getSuccessor(!ContinueOnTrue)));
391 assert(Term->getSuccessor(ContinueOnTrue) == LoopExit);
392 Term->setSuccessor(!ContinueOnTrue, NULL);
395 NewBlocks.push_back(New);
398 // Remap all instructions in the most recent iteration
399 for (unsigned i = 0; i < NewBlocks.size(); ++i)
400 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
401 E = NewBlocks[i]->end(); I != E; ++I)
402 RemapInstruction(I, LastValueMap);
405 // The latch block exits the loop. If there are any PHI nodes in the
406 // successor blocks, update them to use the appropriate values computed as the
407 // last iteration of the loop.
409 SmallPtrSet<PHINode*, 8> Users;
410 for (Value::use_iterator UI = LatchBlock->use_begin(),
411 UE = LatchBlock->use_end(); UI != UE; ++UI)
412 if (PHINode *phi = dyn_cast<PHINode>(*UI))
415 BasicBlock *LastIterationBB = cast<BasicBlock>(LastValueMap[LatchBlock]);
416 for (SmallPtrSet<PHINode*,8>::iterator SI = Users.begin(), SE = Users.end();
419 Value *InVal = PN->removeIncomingValue(LatchBlock, false);
420 // If this value was defined in the loop, take the value defined by the
421 // last iteration of the loop.
422 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
423 if (L->contains(InValI->getParent()))
424 InVal = LastValueMap[InVal];
426 PN->addIncoming(InVal, LastIterationBB);
430 // Now, if we're doing complete unrolling, loop over the PHI nodes in the
431 // original block, setting them to their incoming values.
432 if (CompletelyUnroll) {
433 BasicBlock *Preheader = L->getLoopPreheader();
434 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
435 PHINode *PN = OrigPHINode[i];
436 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
437 Header->getInstList().erase(PN);
441 // Now that all the basic blocks for the unrolled iterations are in place,
442 // set up the branches to connect them.
443 for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
444 // The original branch was replicated in each unrolled iteration.
445 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
447 // The branch destination.
448 unsigned j = (i + 1) % e;
449 BasicBlock *Dest = Headers[j];
450 bool NeedConditional = true;
452 // For a complete unroll, make the last iteration end with a branch
453 // to the exit block.
454 if (CompletelyUnroll && j == 0) {
456 NeedConditional = false;
459 // If we know the trip count or a multiple of it, we can safely use an
460 // unconditional branch for some iterations.
461 if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) {
462 NeedConditional = false;
465 if (NeedConditional) {
466 // Update the conditional branch's successor for the following
468 Term->setSuccessor(!ContinueOnTrue, Dest);
470 Term->setUnconditionalDest(Dest);
471 // Merge adjacent basic blocks, if possible.
472 if (BasicBlock *Fold = FoldBlockIntoPredecessor(Dest)) {
473 std::replace(Latches.begin(), Latches.end(), Dest, Fold);
474 std::replace(Headers.begin(), Headers.end(), Dest, Fold);
479 // At this point, the code is well formed. We now do a quick sweep over the
480 // inserted code, doing constant propagation and dead code elimination as we
482 const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();
483 for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
484 BBE = NewLoopBlocks.end(); BB != BBE; ++BB)
485 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {
486 Instruction *Inst = I++;
488 if (isInstructionTriviallyDead(Inst))
489 (*BB)->getInstList().erase(Inst);
490 else if (Constant *C = ConstantFoldInstruction(Inst)) {
491 Inst->replaceAllUsesWith(C);
492 (*BB)->getInstList().erase(Inst);
496 NumCompletelyUnrolled += CompletelyUnroll;