blob: e47c86d23b3d0123581f8279759b59d84f4bf480 [file] [log] [blame]
Dan Gohman45b31972008-05-14 00:24:14 +00001//===-- UnrollLoop.cpp - 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. It does not define any
11// actual pass or policy, but provides a single function to perform loop
12// unrolling.
13//
14// It works best when loops have been canonicalized by the -indvars pass,
15// allowing it to determine the trip counts of loops easily.
16//
17// The process of unrolling can produce extraneous basic blocks linked with
18// unconditional branches. This will be corrected in the future.
19//===----------------------------------------------------------------------===//
20
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"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000028#include "llvm/Support/raw_ostream.h"
Chris Lattner29874e02008-12-03 19:44:02 +000029#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Dan Gohman45b31972008-05-14 00:24:14 +000030#include "llvm/Transforms/Utils/Cloning.h"
31#include "llvm/Transforms/Utils/Local.h"
32
33using namespace llvm;
34
Chris Lattner29874e02008-12-03 19:44:02 +000035// TODO: Should these be here or in LoopUnroll?
Dan Gohman45b31972008-05-14 00:24:14 +000036STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
37STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
38
39/// RemapInstruction - Convert the instruction operands from referencing the
40/// current values into those specified by ValueMap.
41static inline void RemapInstruction(Instruction *I,
42 DenseMap<const Value *, Value*> &ValueMap) {
43 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
44 Value *Op = I->getOperand(op);
45 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
Dan Gohmanb56c9662009-10-31 14:46:50 +000046 if (It != ValueMap.end())
47 I->setOperand(op, It->second);
Dan Gohman45b31972008-05-14 00:24:14 +000048 }
49}
50
Dan Gohman438b5832009-10-31 17:33:01 +000051/// FoldBlockIntoPredecessor - Folds a basic block into its predecessor if it
52/// only has one predecessor, and that predecessor only has one successor.
53/// The LoopInfo Analysis that is passed will be kept consistent.
54/// Returns the new combined block.
55static BasicBlock *FoldBlockIntoPredecessor(BasicBlock *BB, LoopInfo* LI) {
56 // Merge basic blocks into their predecessor if there is only one distinct
57 // pred, and if there is only one distinct successor of the predecessor, and
58 // if there are no PHI nodes.
59 BasicBlock *OnlyPred = BB->getSinglePredecessor();
60 if (!OnlyPred) return 0;
61
62 if (OnlyPred->getTerminator()->getNumSuccessors() != 1)
63 return 0;
64
David Greenea9ad9c22010-01-05 01:26:41 +000065 DEBUG(dbgs() << "Merging: " << *BB << "into: " << *OnlyPred);
Dan Gohman438b5832009-10-31 17:33:01 +000066
67 // Resolve any PHI nodes at the start of the block. They are all
68 // guaranteed to have exactly one entry if they exist, unless there are
69 // multiple duplicate (but guaranteed to be equal) entries for the
70 // incoming edges. This occurs when there are multiple edges from
71 // OnlyPred to OnlySucc.
72 FoldSingleEntryPHINodes(BB);
73
74 // Delete the unconditional branch from the predecessor...
75 OnlyPred->getInstList().pop_back();
76
77 // Move all definitions in the successor to the predecessor...
78 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
79
80 // Make all PHI nodes that referred to BB now refer to Pred as their
81 // source...
82 BB->replaceAllUsesWith(OnlyPred);
83
84 std::string OldName = BB->getName();
85
86 // Erase basic block from the function...
87 LI->removeBlock(BB);
88 BB->eraseFromParent();
89
90 // Inherit predecessor's name if it exists...
91 if (!OldName.empty() && !OnlyPred->hasName())
92 OnlyPred->setName(OldName);
93
94 return OnlyPred;
95}
96
Dan Gohman45b31972008-05-14 00:24:14 +000097/// Unroll the given loop by Count. The loop must be in LCSSA form. Returns true
98/// if unrolling was succesful, or false if the loop was unmodified. Unrolling
99/// can only fail when the loop's latch block is not terminated by a conditional
100/// branch instruction. However, if the trip count (and multiple) are not known,
101/// loop unrolling will mostly produce more code that is no faster.
102///
103/// The LoopInfo Analysis that is passed will be kept consistent.
104///
105/// If a LoopPassManager is passed in, and the loop is fully removed, it will be
106/// removed from the LoopPassManager as well. LPM can also be NULL.
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000107bool llvm::UnrollLoop(Loop *L, unsigned Count, LoopInfo* LI, LPPassManager* LPM) {
Dan Gohman45b31972008-05-14 00:24:14 +0000108 assert(L->isLCSSAForm());
109
Dan Gohman692ad8d2009-11-05 19:44:06 +0000110 BasicBlock *Preheader = L->getLoopPreheader();
111 if (!Preheader) {
David Greenea9ad9c22010-01-05 01:26:41 +0000112 DEBUG(dbgs() << " Can't unroll; loop preheader-insertion failed.\n");
Dan Gohman692ad8d2009-11-05 19:44:06 +0000113 return false;
114 }
115
Dan Gohman45b31972008-05-14 00:24:14 +0000116 BasicBlock *LatchBlock = L->getLoopLatch();
Dan Gohman692ad8d2009-11-05 19:44:06 +0000117 if (!LatchBlock) {
David Greenea9ad9c22010-01-05 01:26:41 +0000118 DEBUG(dbgs() << " Can't unroll; loop exit-block-insertion failed.\n");
Dan Gohman692ad8d2009-11-05 19:44:06 +0000119 return false;
120 }
121
122 BasicBlock *Header = L->getHeader();
Dan Gohman45b31972008-05-14 00:24:14 +0000123 BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000124
Dan Gohman45b31972008-05-14 00:24:14 +0000125 if (!BI || BI->isUnconditional()) {
126 // The loop-rotate pass can be helpful to avoid this in many cases.
David Greenea9ad9c22010-01-05 01:26:41 +0000127 DEBUG(dbgs() <<
Chris Lattnerbdff5482009-08-23 04:37:46 +0000128 " Can't unroll; loop not terminated by a conditional branch.\n");
Dan Gohman45b31972008-05-14 00:24:14 +0000129 return false;
130 }
131
132 // Find trip count
133 unsigned TripCount = L->getSmallConstantTripCount();
134 // Find trip multiple if count is not available
135 unsigned TripMultiple = 1;
136 if (TripCount == 0)
137 TripMultiple = L->getSmallConstantTripMultiple();
138
139 if (TripCount != 0)
David Greenea9ad9c22010-01-05 01:26:41 +0000140 DEBUG(dbgs() << " Trip Count = " << TripCount << "\n");
Dan Gohman45b31972008-05-14 00:24:14 +0000141 if (TripMultiple != 1)
David Greenea9ad9c22010-01-05 01:26:41 +0000142 DEBUG(dbgs() << " Trip Multiple = " << TripMultiple << "\n");
Dan Gohman45b31972008-05-14 00:24:14 +0000143
144 // Effectively "DCE" unrolled iterations that are beyond the tripcount
145 // and will never be executed.
146 if (TripCount != 0 && Count > TripCount)
147 Count = TripCount;
148
149 assert(Count > 0);
150 assert(TripMultiple > 0);
151 assert(TripCount == 0 || TripCount % TripMultiple == 0);
152
153 // Are we eliminating the loop control altogether?
154 bool CompletelyUnroll = Count == TripCount;
155
156 // If we know the trip count, we know the multiple...
157 unsigned BreakoutTrip = 0;
158 if (TripCount != 0) {
159 BreakoutTrip = TripCount % Count;
160 TripMultiple = 0;
161 } else {
162 // Figure out what multiple to use.
163 BreakoutTrip = TripMultiple =
164 (unsigned)GreatestCommonDivisor64(Count, TripMultiple);
165 }
166
167 if (CompletelyUnroll) {
David Greenea9ad9c22010-01-05 01:26:41 +0000168 DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName()
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000169 << " with trip count " << TripCount << "!\n");
Dan Gohman45b31972008-05-14 00:24:14 +0000170 } else {
David Greenea9ad9c22010-01-05 01:26:41 +0000171 DEBUG(dbgs() << "UNROLLING loop %" << Header->getName()
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000172 << " by " << Count);
Dan Gohman45b31972008-05-14 00:24:14 +0000173 if (TripMultiple == 0 || BreakoutTrip != TripMultiple) {
David Greenea9ad9c22010-01-05 01:26:41 +0000174 DEBUG(dbgs() << " with a breakout at trip " << BreakoutTrip);
Dan Gohman45b31972008-05-14 00:24:14 +0000175 } else if (TripMultiple != 1) {
David Greenea9ad9c22010-01-05 01:26:41 +0000176 DEBUG(dbgs() << " with " << TripMultiple << " trips per branch");
Dan Gohman45b31972008-05-14 00:24:14 +0000177 }
David Greenea9ad9c22010-01-05 01:26:41 +0000178 DEBUG(dbgs() << "!\n");
Dan Gohman45b31972008-05-14 00:24:14 +0000179 }
180
181 std::vector<BasicBlock*> LoopBlocks = L->getBlocks();
182
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000183 bool ContinueOnTrue = L->contains(BI->getSuccessor(0));
Dan Gohman45b31972008-05-14 00:24:14 +0000184 BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);
185
186 // For the first iteration of the loop, we should use the precloned values for
187 // PHI nodes. Insert associations now.
188 typedef DenseMap<const Value*, Value*> ValueMapTy;
189 ValueMapTy LastValueMap;
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000190 std::vector<PHINode*> OrigPHINode;
Dan Gohman45b31972008-05-14 00:24:14 +0000191 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
192 PHINode *PN = cast<PHINode>(I);
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000193 OrigPHINode.push_back(PN);
Dan Gohman45b31972008-05-14 00:24:14 +0000194 if (Instruction *I =
195 dyn_cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock)))
Dan Gohman92329c72009-12-18 01:24:09 +0000196 if (L->contains(I))
Dan Gohman45b31972008-05-14 00:24:14 +0000197 LastValueMap[I] = I;
198 }
199
200 std::vector<BasicBlock*> Headers;
201 std::vector<BasicBlock*> Latches;
202 Headers.push_back(Header);
203 Latches.push_back(LatchBlock);
204
205 for (unsigned It = 1; It != Count; ++It) {
Dan Gohman45b31972008-05-14 00:24:14 +0000206 std::vector<BasicBlock*> NewBlocks;
207
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000208 for (std::vector<BasicBlock*>::iterator BB = LoopBlocks.begin(),
209 E = LoopBlocks.end(); BB != E; ++BB) {
Dan Gohman45b31972008-05-14 00:24:14 +0000210 ValueMapTy ValueMap;
Benjamin Kramer5deb57c2010-01-27 19:58:47 +0000211 BasicBlock *New = CloneBasicBlock(*BB, ValueMap, "." + Twine(It));
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000212 Header->getParent()->getBasicBlockList().push_back(New);
Dan Gohman45b31972008-05-14 00:24:14 +0000213
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000214 // Loop over all of the PHI nodes in the block, changing them to use the
215 // incoming values from the previous block.
216 if (*BB == Header)
217 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
218 PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]);
Dan Gohman45b31972008-05-14 00:24:14 +0000219 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
220 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
Dan Gohman92329c72009-12-18 01:24:09 +0000221 if (It > 1 && L->contains(InValI))
Dan Gohman45b31972008-05-14 00:24:14 +0000222 InVal = LastValueMap[InValI];
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000223 ValueMap[OrigPHINode[i]] = InVal;
Dan Gohman45b31972008-05-14 00:24:14 +0000224 New->getInstList().erase(NewPHI);
225 }
226
227 // Update our running map of newest clones
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000228 LastValueMap[*BB] = New;
Dan Gohman45b31972008-05-14 00:24:14 +0000229 for (ValueMapTy::iterator VI = ValueMap.begin(), VE = ValueMap.end();
230 VI != VE; ++VI)
231 LastValueMap[VI->first] = VI->second;
232
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000233 L->addBasicBlockToLoop(New, LI->getBase());
234
235 // Add phi entries for newly created values to all exit blocks except
236 // the successor of the latch block. The successor of the exit block will
237 // be updated specially after unrolling all the way.
238 if (*BB != LatchBlock)
239 for (Value::use_iterator UI = (*BB)->use_begin(), UE = (*BB)->use_end();
240 UI != UE;) {
241 Instruction *UseInst = cast<Instruction>(*UI);
242 ++UI;
Dan Gohman92329c72009-12-18 01:24:09 +0000243 if (isa<PHINode>(UseInst) && !L->contains(UseInst)) {
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000244 PHINode *phi = cast<PHINode>(UseInst);
245 Value *Incoming = phi->getIncomingValueForBlock(*BB);
246 phi->addIncoming(Incoming, New);
247 }
Dan Gohman45b31972008-05-14 00:24:14 +0000248 }
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000249
250 // Keep track of new headers and latches as we create them, so that
251 // we can insert the proper branches later.
252 if (*BB == Header)
253 Headers.push_back(New);
254 if (*BB == LatchBlock) {
255 Latches.push_back(New);
256
257 // Also, clear out the new latch's back edge so that it doesn't look
258 // like a new loop, so that it's amenable to being merged with adjacent
259 // blocks later on.
260 TerminatorInst *Term = New->getTerminator();
261 assert(L->contains(Term->getSuccessor(!ContinueOnTrue)));
262 assert(Term->getSuccessor(ContinueOnTrue) == LoopExit);
263 Term->setSuccessor(!ContinueOnTrue, NULL);
Dan Gohman45b31972008-05-14 00:24:14 +0000264 }
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000265
266 NewBlocks.push_back(New);
Dan Gohman45b31972008-05-14 00:24:14 +0000267 }
268
269 // Remap all instructions in the most recent iteration
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000270 for (unsigned i = 0; i < NewBlocks.size(); ++i)
Dan Gohman45b31972008-05-14 00:24:14 +0000271 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
272 E = NewBlocks[i]->end(); I != E; ++I)
273 RemapInstruction(I, LastValueMap);
274 }
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000275
276 // The latch block exits the loop. If there are any PHI nodes in the
277 // successor blocks, update them to use the appropriate values computed as the
278 // last iteration of the loop.
279 if (Count != 1) {
280 SmallPtrSet<PHINode*, 8> Users;
281 for (Value::use_iterator UI = LatchBlock->use_begin(),
282 UE = LatchBlock->use_end(); UI != UE; ++UI)
283 if (PHINode *phi = dyn_cast<PHINode>(*UI))
284 Users.insert(phi);
285
286 BasicBlock *LastIterationBB = cast<BasicBlock>(LastValueMap[LatchBlock]);
287 for (SmallPtrSet<PHINode*,8>::iterator SI = Users.begin(), SE = Users.end();
288 SI != SE; ++SI) {
289 PHINode *PN = *SI;
290 Value *InVal = PN->removeIncomingValue(LatchBlock, false);
291 // If this value was defined in the loop, take the value defined by the
292 // last iteration of the loop.
293 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
Dan Gohman92329c72009-12-18 01:24:09 +0000294 if (L->contains(InValI))
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000295 InVal = LastValueMap[InVal];
296 }
297 PN->addIncoming(InVal, LastIterationBB);
298 }
299 }
300
301 // Now, if we're doing complete unrolling, loop over the PHI nodes in the
302 // original block, setting them to their incoming values.
303 if (CompletelyUnroll) {
304 BasicBlock *Preheader = L->getLoopPreheader();
305 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
306 PHINode *PN = OrigPHINode[i];
307 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
308 Header->getInstList().erase(PN);
309 }
310 }
Dan Gohman45b31972008-05-14 00:24:14 +0000311
312 // Now that all the basic blocks for the unrolled iterations are in place,
313 // set up the branches to connect them.
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000314 for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
Dan Gohman45b31972008-05-14 00:24:14 +0000315 // The original branch was replicated in each unrolled iteration.
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000316 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
Dan Gohman45b31972008-05-14 00:24:14 +0000317
318 // The branch destination.
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000319 unsigned j = (i + 1) % e;
320 BasicBlock *Dest = Headers[j];
Dan Gohman45b31972008-05-14 00:24:14 +0000321 bool NeedConditional = true;
322
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000323 // For a complete unroll, make the last iteration end with a branch
324 // to the exit block.
325 if (CompletelyUnroll && j == 0) {
Dan Gohman45b31972008-05-14 00:24:14 +0000326 Dest = LoopExit;
327 NeedConditional = false;
328 }
329
330 // If we know the trip count or a multiple of it, we can safely use an
331 // unconditional branch for some iterations.
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000332 if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) {
Dan Gohman45b31972008-05-14 00:24:14 +0000333 NeedConditional = false;
334 }
335
336 if (NeedConditional) {
337 // Update the conditional branch's successor for the following
338 // iteration.
339 Term->setSuccessor(!ContinueOnTrue, Dest);
340 } else {
341 Term->setUnconditionalDest(Dest);
342 // Merge adjacent basic blocks, if possible.
Dan Gohman438b5832009-10-31 17:33:01 +0000343 if (BasicBlock *Fold = FoldBlockIntoPredecessor(Dest, LI)) {
Dan Gohman45b31972008-05-14 00:24:14 +0000344 std::replace(Latches.begin(), Latches.end(), Dest, Fold);
345 std::replace(Headers.begin(), Headers.end(), Dest, Fold);
346 }
347 }
348 }
349
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000350 // At this point, the code is well formed. We now do a quick sweep over the
351 // inserted code, doing constant propagation and dead code elimination as we
352 // go.
353 const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();
354 for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
355 BBE = NewLoopBlocks.end(); BB != BBE; ++BB)
356 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {
Dan Gohman45b31972008-05-14 00:24:14 +0000357 Instruction *Inst = I++;
358
359 if (isInstructionTriviallyDead(Inst))
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000360 (*BB)->getInstList().erase(Inst);
Chris Lattner7b550cc2009-11-06 04:27:31 +0000361 else if (Constant *C = ConstantFoldInstruction(Inst)) {
Dan Gohman45b31972008-05-14 00:24:14 +0000362 Inst->replaceAllUsesWith(C);
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000363 (*BB)->getInstList().erase(Inst);
Dan Gohman45b31972008-05-14 00:24:14 +0000364 }
365 }
Dan Gohman45b31972008-05-14 00:24:14 +0000366
367 NumCompletelyUnrolled += CompletelyUnroll;
368 ++NumUnrolled;
369 // Remove the loop from the LoopPassManager if it's completely removed.
370 if (CompletelyUnroll && LPM != NULL)
371 LPM->deleteLoopFromQueue(L);
372
373 // If we didn't completely unroll the loop, it should still be in LCSSA form.
374 if (!CompletelyUnroll)
375 assert(L->isLCSSAForm());
376
377 return true;
378}