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/Transforms/Utils/Cloning.h"
29 #include "llvm/Transforms/Utils/Local.h"
34 /* TODO: Should these be here or in LoopUnroll? */
35 STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
36 STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
38 /// RemapInstruction - Convert the instruction operands from referencing the
39 /// current values into those specified by ValueMap.
40 static inline void RemapInstruction(Instruction *I,
41 DenseMap<const Value *, Value*> &ValueMap) {
42 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
43 Value *Op = I->getOperand(op);
44 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
45 if (It != ValueMap.end()) Op = It->second;
46 I->setOperand(op, Op);
50 /// FoldBlockIntoPredecessor - Folds a basic block into its predecessor if it
51 /// only has one predecessor, and that predecessor only has one successor.
52 /// The LoopInfo Analysis that is passed will be kept consistent.
53 /// Returns the new combined block.
54 static BasicBlock *FoldBlockIntoPredecessor(BasicBlock *BB, LoopInfo* LI) {
55 // Merge basic blocks into their predecessor if there is only one distinct
56 // pred, and if there is only one distinct successor of the predecessor, and
57 // if there are no PHI nodes.
58 BasicBlock *OnlyPred = BB->getSinglePredecessor();
59 if (!OnlyPred) return 0;
61 if (OnlyPred->getTerminator()->getNumSuccessors() != 1)
64 DOUT << "Merging: " << *BB << "into: " << *OnlyPred;
66 // Resolve any PHI nodes at the start of the block. They are all
67 // guaranteed to have exactly one entry if they exist, unless there are
68 // multiple duplicate (but guaranteed to be equal) entries for the
69 // incoming edges. This occurs when there are multiple edges from
70 // OnlyPred to OnlySucc.
72 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
73 PN->replaceAllUsesWith(PN->getIncomingValue(0));
74 BB->getInstList().pop_front(); // Delete the phi node...
77 // Delete the unconditional branch from the predecessor...
78 OnlyPred->getInstList().pop_back();
80 // Move all definitions in the successor to the predecessor...
81 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
83 // Make all PHI nodes that referred to BB now refer to Pred as their
85 BB->replaceAllUsesWith(OnlyPred);
87 std::string OldName = BB->getName();
89 // Erase basic block from the function...
91 BB->eraseFromParent();
93 // Inherit predecessor's name if it exists...
94 if (!OldName.empty() && !OnlyPred->hasName())
95 OnlyPred->setName(OldName);
100 /// Unroll the given loop by Count. The loop must be in LCSSA form. Returns true
101 /// if unrolling was succesful, or false if the loop was unmodified. Unrolling
102 /// can only fail when the loop's latch block is not terminated by a conditional
103 /// branch instruction. However, if the trip count (and multiple) are not known,
104 /// loop unrolling will mostly produce more code that is no faster.
106 /// The LoopInfo Analysis that is passed will be kept consistent.
108 /// If a LoopPassManager is passed in, and the loop is fully removed, it will be
109 /// removed from the LoopPassManager as well. LPM can also be NULL.
110 bool llvm::UnrollLoop(Loop *L, unsigned Count, LoopInfo* LI, LPPassManager* LPM) {
111 assert(L->isLCSSAForm());
113 BasicBlock *Header = L->getHeader();
114 BasicBlock *LatchBlock = L->getLoopLatch();
115 BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
117 if (!BI || BI->isUnconditional()) {
118 // The loop-rotate pass can be helpful to avoid this in many cases.
119 DOUT << " Can't unroll; loop not terminated by a conditional branch.\n";
124 unsigned TripCount = L->getSmallConstantTripCount();
125 // Find trip multiple if count is not available
126 unsigned TripMultiple = 1;
128 TripMultiple = L->getSmallConstantTripMultiple();
131 DOUT << " Trip Count = " << TripCount << "\n";
132 if (TripMultiple != 1)
133 DOUT << " Trip Multiple = " << TripMultiple << "\n";
135 // Effectively "DCE" unrolled iterations that are beyond the tripcount
136 // and will never be executed.
137 if (TripCount != 0 && Count > TripCount)
141 assert(TripMultiple > 0);
142 assert(TripCount == 0 || TripCount % TripMultiple == 0);
144 // Are we eliminating the loop control altogether?
145 bool CompletelyUnroll = Count == TripCount;
147 // If we know the trip count, we know the multiple...
148 unsigned BreakoutTrip = 0;
149 if (TripCount != 0) {
150 BreakoutTrip = TripCount % Count;
153 // Figure out what multiple to use.
154 BreakoutTrip = TripMultiple =
155 (unsigned)GreatestCommonDivisor64(Count, TripMultiple);
158 if (CompletelyUnroll) {
159 DOUT << "COMPLETELY UNROLLING loop %" << Header->getName()
160 << " with trip count " << TripCount << "!\n";
162 DOUT << "UNROLLING loop %" << Header->getName()
164 if (TripMultiple == 0 || BreakoutTrip != TripMultiple) {
165 DOUT << " with a breakout at trip " << BreakoutTrip;
166 } else if (TripMultiple != 1) {
167 DOUT << " with " << TripMultiple << " trips per branch";
172 std::vector<BasicBlock*> LoopBlocks = L->getBlocks();
174 bool ContinueOnTrue = L->contains(BI->getSuccessor(0));
175 BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);
177 // For the first iteration of the loop, we should use the precloned values for
178 // PHI nodes. Insert associations now.
179 typedef DenseMap<const Value*, Value*> ValueMapTy;
180 ValueMapTy LastValueMap;
181 std::vector<PHINode*> OrigPHINode;
182 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
183 PHINode *PN = cast<PHINode>(I);
184 OrigPHINode.push_back(PN);
186 dyn_cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock)))
187 if (L->contains(I->getParent()))
191 std::vector<BasicBlock*> Headers;
192 std::vector<BasicBlock*> Latches;
193 Headers.push_back(Header);
194 Latches.push_back(LatchBlock);
196 for (unsigned It = 1; It != Count; ++It) {
197 char SuffixBuffer[100];
198 sprintf(SuffixBuffer, ".%d", It);
200 std::vector<BasicBlock*> NewBlocks;
202 for (std::vector<BasicBlock*>::iterator BB = LoopBlocks.begin(),
203 E = LoopBlocks.end(); BB != E; ++BB) {
205 BasicBlock *New = CloneBasicBlock(*BB, ValueMap, SuffixBuffer);
206 Header->getParent()->getBasicBlockList().push_back(New);
208 // Loop over all of the PHI nodes in the block, changing them to use the
209 // incoming values from the previous block.
211 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
212 PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]);
213 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
214 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
215 if (It > 1 && L->contains(InValI->getParent()))
216 InVal = LastValueMap[InValI];
217 ValueMap[OrigPHINode[i]] = InVal;
218 New->getInstList().erase(NewPHI);
221 // Update our running map of newest clones
222 LastValueMap[*BB] = New;
223 for (ValueMapTy::iterator VI = ValueMap.begin(), VE = ValueMap.end();
225 LastValueMap[VI->first] = VI->second;
227 L->addBasicBlockToLoop(New, LI->getBase());
229 // Add phi entries for newly created values to all exit blocks except
230 // the successor of the latch block. The successor of the exit block will
231 // be updated specially after unrolling all the way.
232 if (*BB != LatchBlock)
233 for (Value::use_iterator UI = (*BB)->use_begin(), UE = (*BB)->use_end();
235 Instruction *UseInst = cast<Instruction>(*UI);
237 if (isa<PHINode>(UseInst) && !L->contains(UseInst->getParent())) {
238 PHINode *phi = cast<PHINode>(UseInst);
239 Value *Incoming = phi->getIncomingValueForBlock(*BB);
240 phi->addIncoming(Incoming, New);
244 // Keep track of new headers and latches as we create them, so that
245 // we can insert the proper branches later.
247 Headers.push_back(New);
248 if (*BB == LatchBlock) {
249 Latches.push_back(New);
251 // Also, clear out the new latch's back edge so that it doesn't look
252 // like a new loop, so that it's amenable to being merged with adjacent
254 TerminatorInst *Term = New->getTerminator();
255 assert(L->contains(Term->getSuccessor(!ContinueOnTrue)));
256 assert(Term->getSuccessor(ContinueOnTrue) == LoopExit);
257 Term->setSuccessor(!ContinueOnTrue, NULL);
260 NewBlocks.push_back(New);
263 // Remap all instructions in the most recent iteration
264 for (unsigned i = 0; i < NewBlocks.size(); ++i)
265 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
266 E = NewBlocks[i]->end(); I != E; ++I)
267 RemapInstruction(I, LastValueMap);
270 // The latch block exits the loop. If there are any PHI nodes in the
271 // successor blocks, update them to use the appropriate values computed as the
272 // last iteration of the loop.
274 SmallPtrSet<PHINode*, 8> Users;
275 for (Value::use_iterator UI = LatchBlock->use_begin(),
276 UE = LatchBlock->use_end(); UI != UE; ++UI)
277 if (PHINode *phi = dyn_cast<PHINode>(*UI))
280 BasicBlock *LastIterationBB = cast<BasicBlock>(LastValueMap[LatchBlock]);
281 for (SmallPtrSet<PHINode*,8>::iterator SI = Users.begin(), SE = Users.end();
284 Value *InVal = PN->removeIncomingValue(LatchBlock, false);
285 // If this value was defined in the loop, take the value defined by the
286 // last iteration of the loop.
287 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
288 if (L->contains(InValI->getParent()))
289 InVal = LastValueMap[InVal];
291 PN->addIncoming(InVal, LastIterationBB);
295 // Now, if we're doing complete unrolling, loop over the PHI nodes in the
296 // original block, setting them to their incoming values.
297 if (CompletelyUnroll) {
298 BasicBlock *Preheader = L->getLoopPreheader();
299 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
300 PHINode *PN = OrigPHINode[i];
301 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
302 Header->getInstList().erase(PN);
306 // Now that all the basic blocks for the unrolled iterations are in place,
307 // set up the branches to connect them.
308 for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
309 // The original branch was replicated in each unrolled iteration.
310 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
312 // The branch destination.
313 unsigned j = (i + 1) % e;
314 BasicBlock *Dest = Headers[j];
315 bool NeedConditional = true;
317 // For a complete unroll, make the last iteration end with a branch
318 // to the exit block.
319 if (CompletelyUnroll && j == 0) {
321 NeedConditional = false;
324 // If we know the trip count or a multiple of it, we can safely use an
325 // unconditional branch for some iterations.
326 if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) {
327 NeedConditional = false;
330 if (NeedConditional) {
331 // Update the conditional branch's successor for the following
333 Term->setSuccessor(!ContinueOnTrue, Dest);
335 Term->setUnconditionalDest(Dest);
336 // Merge adjacent basic blocks, if possible.
337 if (BasicBlock *Fold = FoldBlockIntoPredecessor(Dest, LI)) {
338 std::replace(Latches.begin(), Latches.end(), Dest, Fold);
339 std::replace(Headers.begin(), Headers.end(), Dest, Fold);
344 // At this point, the code is well formed. We now do a quick sweep over the
345 // inserted code, doing constant propagation and dead code elimination as we
347 const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();
348 for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
349 BBE = NewLoopBlocks.end(); BB != BBE; ++BB)
350 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {
351 Instruction *Inst = I++;
353 if (isInstructionTriviallyDead(Inst))
354 (*BB)->getInstList().erase(Inst);
355 else if (Constant *C = ConstantFoldInstruction(Inst)) {
356 Inst->replaceAllUsesWith(C);
357 (*BB)->getInstList().erase(Inst);
361 NumCompletelyUnrolled += CompletelyUnroll;
363 // Remove the loop from the LoopPassManager if it's completely removed.
364 if (CompletelyUnroll && LPM != NULL)
365 LPM->deleteLoopFromQueue(L);
367 // If we didn't completely unroll the loop, it should still be in LCSSA form.
368 if (!CompletelyUnroll)
369 assert(L->isLCSSAForm());