1 //===-- UnrollLoop.cpp - 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. It does not define any
11 // actual pass or policy, but provides a single function to perform loop
14 // It works best when loops have been canonicalized by the -indvars pass,
15 // allowing it to determine the trip counts of loops easily.
17 // The process of unrolling can produce extraneous basic blocks linked with
18 // unconditional branches. This will be corrected in the future.
19 //===----------------------------------------------------------------------===//
21 #define DEBUG_TYPE "loop-unroll"
22 #include "llvm/Transforms/Utils/UnrollLoop.h"
23 #include "llvm/BasicBlock.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Analysis/ConstantFolding.h"
26 #include "llvm/Analysis/LoopPass.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
30 #include "llvm/Transforms/Utils/Cloning.h"
31 #include "llvm/Transforms/Utils/Local.h"
36 // TODO: Should these be here or in LoopUnroll?
37 STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
38 STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
40 /// RemapInstruction - Convert the instruction operands from referencing the
41 /// current values into those specified by ValueMap.
42 static inline void RemapInstruction(Instruction *I,
43 DenseMap<const Value *, Value*> &ValueMap) {
44 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
45 Value *Op = I->getOperand(op);
46 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
47 if (It != ValueMap.end())
48 I->setOperand(op, It->second);
52 /// Unroll the given loop by Count. The loop must be in LCSSA form. Returns true
53 /// if unrolling was succesful, or false if the loop was unmodified. Unrolling
54 /// can only fail when the loop's latch block is not terminated by a conditional
55 /// branch instruction. However, if the trip count (and multiple) are not known,
56 /// loop unrolling will mostly produce more code that is no faster.
58 /// The LoopInfo Analysis that is passed will be kept consistent.
60 /// If a LoopPassManager is passed in, and the loop is fully removed, it will be
61 /// removed from the LoopPassManager as well. LPM can also be NULL.
62 bool llvm::UnrollLoop(Loop *L, unsigned Count, LoopInfo* LI, LPPassManager* LPM) {
63 assert(L->isLCSSAForm());
65 BasicBlock *Header = L->getHeader();
66 BasicBlock *LatchBlock = L->getLoopLatch();
67 BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
69 if (!BI || BI->isUnconditional()) {
70 // The loop-rotate pass can be helpful to avoid this in many cases.
72 " Can't unroll; loop not terminated by a conditional branch.\n");
77 unsigned TripCount = L->getSmallConstantTripCount();
78 // Find trip multiple if count is not available
79 unsigned TripMultiple = 1;
81 TripMultiple = L->getSmallConstantTripMultiple();
84 DEBUG(errs() << " Trip Count = " << TripCount << "\n");
85 if (TripMultiple != 1)
86 DEBUG(errs() << " Trip Multiple = " << TripMultiple << "\n");
88 // Effectively "DCE" unrolled iterations that are beyond the tripcount
89 // and will never be executed.
90 if (TripCount != 0 && Count > TripCount)
94 assert(TripMultiple > 0);
95 assert(TripCount == 0 || TripCount % TripMultiple == 0);
97 // Are we eliminating the loop control altogether?
98 bool CompletelyUnroll = Count == TripCount;
100 // If we know the trip count, we know the multiple...
101 unsigned BreakoutTrip = 0;
102 if (TripCount != 0) {
103 BreakoutTrip = TripCount % Count;
106 // Figure out what multiple to use.
107 BreakoutTrip = TripMultiple =
108 (unsigned)GreatestCommonDivisor64(Count, TripMultiple);
111 if (CompletelyUnroll) {
112 DEBUG(errs() << "COMPLETELY UNROLLING loop %" << Header->getName()
113 << " with trip count " << TripCount << "!\n");
115 DEBUG(errs() << "UNROLLING loop %" << Header->getName()
117 if (TripMultiple == 0 || BreakoutTrip != TripMultiple) {
118 DEBUG(errs() << " with a breakout at trip " << BreakoutTrip);
119 } else if (TripMultiple != 1) {
120 DEBUG(errs() << " with " << TripMultiple << " trips per branch");
122 DEBUG(errs() << "!\n");
125 std::vector<BasicBlock*> LoopBlocks = L->getBlocks();
127 bool ContinueOnTrue = L->contains(BI->getSuccessor(0));
128 BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);
130 // For the first iteration of the loop, we should use the precloned values for
131 // PHI nodes. Insert associations now.
132 typedef DenseMap<const Value*, Value*> ValueMapTy;
133 ValueMapTy LastValueMap;
134 std::vector<PHINode*> OrigPHINode;
135 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
136 PHINode *PN = cast<PHINode>(I);
137 OrigPHINode.push_back(PN);
139 dyn_cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock)))
140 if (L->contains(I->getParent()))
144 std::vector<BasicBlock*> Headers;
145 std::vector<BasicBlock*> Latches;
146 Headers.push_back(Header);
147 Latches.push_back(LatchBlock);
149 for (unsigned It = 1; It != Count; ++It) {
150 char SuffixBuffer[100];
151 sprintf(SuffixBuffer, ".%d", It);
153 std::vector<BasicBlock*> NewBlocks;
155 for (std::vector<BasicBlock*>::iterator BB = LoopBlocks.begin(),
156 E = LoopBlocks.end(); BB != E; ++BB) {
158 BasicBlock *New = CloneBasicBlock(*BB, ValueMap, SuffixBuffer);
159 Header->getParent()->getBasicBlockList().push_back(New);
161 // Loop over all of the PHI nodes in the block, changing them to use the
162 // incoming values from the previous block.
164 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
165 PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]);
166 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
167 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
168 if (It > 1 && L->contains(InValI->getParent()))
169 InVal = LastValueMap[InValI];
170 ValueMap[OrigPHINode[i]] = InVal;
171 New->getInstList().erase(NewPHI);
174 // Update our running map of newest clones
175 LastValueMap[*BB] = New;
176 for (ValueMapTy::iterator VI = ValueMap.begin(), VE = ValueMap.end();
178 LastValueMap[VI->first] = VI->second;
180 L->addBasicBlockToLoop(New, LI->getBase());
182 // Add phi entries for newly created values to all exit blocks except
183 // the successor of the latch block. The successor of the exit block will
184 // be updated specially after unrolling all the way.
185 if (*BB != LatchBlock)
186 for (Value::use_iterator UI = (*BB)->use_begin(), UE = (*BB)->use_end();
188 Instruction *UseInst = cast<Instruction>(*UI);
190 if (isa<PHINode>(UseInst) && !L->contains(UseInst->getParent())) {
191 PHINode *phi = cast<PHINode>(UseInst);
192 Value *Incoming = phi->getIncomingValueForBlock(*BB);
193 phi->addIncoming(Incoming, New);
197 // Keep track of new headers and latches as we create them, so that
198 // we can insert the proper branches later.
200 Headers.push_back(New);
201 if (*BB == LatchBlock) {
202 Latches.push_back(New);
204 // Also, clear out the new latch's back edge so that it doesn't look
205 // like a new loop, so that it's amenable to being merged with adjacent
207 TerminatorInst *Term = New->getTerminator();
208 assert(L->contains(Term->getSuccessor(!ContinueOnTrue)));
209 assert(Term->getSuccessor(ContinueOnTrue) == LoopExit);
210 Term->setSuccessor(!ContinueOnTrue, NULL);
213 NewBlocks.push_back(New);
216 // Remap all instructions in the most recent iteration
217 for (unsigned i = 0; i < NewBlocks.size(); ++i)
218 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
219 E = NewBlocks[i]->end(); I != E; ++I)
220 RemapInstruction(I, LastValueMap);
223 // The latch block exits the loop. If there are any PHI nodes in the
224 // successor blocks, update them to use the appropriate values computed as the
225 // last iteration of the loop.
227 SmallPtrSet<PHINode*, 8> Users;
228 for (Value::use_iterator UI = LatchBlock->use_begin(),
229 UE = LatchBlock->use_end(); UI != UE; ++UI)
230 if (PHINode *phi = dyn_cast<PHINode>(*UI))
233 BasicBlock *LastIterationBB = cast<BasicBlock>(LastValueMap[LatchBlock]);
234 for (SmallPtrSet<PHINode*,8>::iterator SI = Users.begin(), SE = Users.end();
237 Value *InVal = PN->removeIncomingValue(LatchBlock, false);
238 // If this value was defined in the loop, take the value defined by the
239 // last iteration of the loop.
240 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
241 if (L->contains(InValI->getParent()))
242 InVal = LastValueMap[InVal];
244 PN->addIncoming(InVal, LastIterationBB);
248 // Now, if we're doing complete unrolling, loop over the PHI nodes in the
249 // original block, setting them to their incoming values.
250 if (CompletelyUnroll) {
251 BasicBlock *Preheader = L->getLoopPreheader();
252 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
253 PHINode *PN = OrigPHINode[i];
254 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
255 Header->getInstList().erase(PN);
259 // Now that all the basic blocks for the unrolled iterations are in place,
260 // set up the branches to connect them.
261 for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
262 // The original branch was replicated in each unrolled iteration.
263 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
265 // The branch destination.
266 unsigned j = (i + 1) % e;
267 BasicBlock *Dest = Headers[j];
268 bool NeedConditional = true;
270 // For a complete unroll, make the last iteration end with a branch
271 // to the exit block.
272 if (CompletelyUnroll && j == 0) {
274 NeedConditional = false;
277 // If we know the trip count or a multiple of it, we can safely use an
278 // unconditional branch for some iterations.
279 if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) {
280 NeedConditional = false;
283 if (NeedConditional) {
284 // Update the conditional branch's successor for the following
286 Term->setSuccessor(!ContinueOnTrue, Dest);
288 Term->setUnconditionalDest(Dest);
289 // Merge adjacent basic blocks, if possible.
290 if (BasicBlock *Fold = MergeBlockIntoPredecessor(Dest, LI)) {
291 std::replace(Latches.begin(), Latches.end(), Dest, Fold);
292 std::replace(Headers.begin(), Headers.end(), Dest, Fold);
297 // At this point, the code is well formed. We now do a quick sweep over the
298 // inserted code, doing constant propagation and dead code elimination as we
300 const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();
301 for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
302 BBE = NewLoopBlocks.end(); BB != BBE; ++BB)
303 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {
304 Instruction *Inst = I++;
306 if (isInstructionTriviallyDead(Inst))
307 (*BB)->getInstList().erase(Inst);
308 else if (Constant *C = ConstantFoldInstruction(Inst,
309 Header->getContext())) {
310 Inst->replaceAllUsesWith(C);
311 (*BB)->getInstList().erase(Inst);
315 NumCompletelyUnrolled += CompletelyUnroll;
317 // Remove the loop from the LoopPassManager if it's completely removed.
318 if (CompletelyUnroll && LPM != NULL)
319 LPM->deleteLoopFromQueue(L);
321 // If we didn't completely unroll the loop, it should still be in LCSSA form.
322 if (!CompletelyUnroll)
323 assert(L->isLCSSAForm());