blob: 63493dc66a311e3c74051529816ee93bc7d4a739 [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"
28#include "llvm/Transforms/Utils/Cloning.h"
29#include "llvm/Transforms/Utils/Local.h"
Duncan Sands4520dd22008-10-08 07:23:46 +000030#include <cstdio>
Dan Gohman45b31972008-05-14 00:24:14 +000031
32using namespace llvm;
33
34/* TODO: Should these be here or in LoopUnroll? */
35STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
36STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
37
38/// RemapInstruction - Convert the instruction operands from referencing the
39/// current values into those specified by ValueMap.
40static 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);
47 }
48}
49
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.
54static 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;
60
61 if (OnlyPred->getTerminator()->getNumSuccessors() != 1)
62 return 0;
63
64 DOUT << "Merging: " << *BB << "into: " << *OnlyPred;
65
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.
71 //
72 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
73 PN->replaceAllUsesWith(PN->getIncomingValue(0));
74 BB->getInstList().pop_front(); // Delete the phi node...
75 }
76
77 // Delete the unconditional branch from the predecessor...
78 OnlyPred->getInstList().pop_back();
79
80 // Move all definitions in the successor to the predecessor...
81 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
82
83 // Make all PHI nodes that referred to BB now refer to Pred as their
84 // source...
85 BB->replaceAllUsesWith(OnlyPred);
86
87 std::string OldName = BB->getName();
88
89 // Erase basic block from the function...
90 LI->removeBlock(BB);
91 BB->eraseFromParent();
92
93 // Inherit predecessor's name if it exists...
94 if (!OldName.empty() && !OnlyPred->hasName())
95 OnlyPred->setName(OldName);
96
97 return OnlyPred;
98}
99
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.
105///
106/// The LoopInfo Analysis that is passed will be kept consistent.
107///
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.
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000110bool llvm::UnrollLoop(Loop *L, unsigned Count, LoopInfo* LI, LPPassManager* LPM) {
Dan Gohman45b31972008-05-14 00:24:14 +0000111 assert(L->isLCSSAForm());
112
113 BasicBlock *Header = L->getHeader();
114 BasicBlock *LatchBlock = L->getLoopLatch();
115 BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000116
Dan Gohman45b31972008-05-14 00:24:14 +0000117 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";
120 return false;
121 }
122
123 // Find trip count
124 unsigned TripCount = L->getSmallConstantTripCount();
125 // Find trip multiple if count is not available
126 unsigned TripMultiple = 1;
127 if (TripCount == 0)
128 TripMultiple = L->getSmallConstantTripMultiple();
129
130 if (TripCount != 0)
131 DOUT << " Trip Count = " << TripCount << "\n";
132 if (TripMultiple != 1)
133 DOUT << " Trip Multiple = " << TripMultiple << "\n";
134
135 // Effectively "DCE" unrolled iterations that are beyond the tripcount
136 // and will never be executed.
137 if (TripCount != 0 && Count > TripCount)
138 Count = TripCount;
139
140 assert(Count > 0);
141 assert(TripMultiple > 0);
142 assert(TripCount == 0 || TripCount % TripMultiple == 0);
143
144 // Are we eliminating the loop control altogether?
145 bool CompletelyUnroll = Count == TripCount;
146
147 // If we know the trip count, we know the multiple...
148 unsigned BreakoutTrip = 0;
149 if (TripCount != 0) {
150 BreakoutTrip = TripCount % Count;
151 TripMultiple = 0;
152 } else {
153 // Figure out what multiple to use.
154 BreakoutTrip = TripMultiple =
155 (unsigned)GreatestCommonDivisor64(Count, TripMultiple);
156 }
157
158 if (CompletelyUnroll) {
159 DOUT << "COMPLETELY UNROLLING loop %" << Header->getName()
160 << " with trip count " << TripCount << "!\n";
161 } else {
162 DOUT << "UNROLLING loop %" << Header->getName()
163 << " by " << Count;
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";
168 }
169 DOUT << "!\n";
170 }
171
172 std::vector<BasicBlock*> LoopBlocks = L->getBlocks();
173
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000174 bool ContinueOnTrue = L->contains(BI->getSuccessor(0));
Dan Gohman45b31972008-05-14 00:24:14 +0000175 BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);
176
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;
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000181 std::vector<PHINode*> OrigPHINode;
Dan Gohman45b31972008-05-14 00:24:14 +0000182 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
183 PHINode *PN = cast<PHINode>(I);
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000184 OrigPHINode.push_back(PN);
Dan Gohman45b31972008-05-14 00:24:14 +0000185 if (Instruction *I =
186 dyn_cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock)))
187 if (L->contains(I->getParent()))
188 LastValueMap[I] = I;
189 }
190
191 std::vector<BasicBlock*> Headers;
192 std::vector<BasicBlock*> Latches;
193 Headers.push_back(Header);
194 Latches.push_back(LatchBlock);
195
196 for (unsigned It = 1; It != Count; ++It) {
197 char SuffixBuffer[100];
198 sprintf(SuffixBuffer, ".%d", It);
199
200 std::vector<BasicBlock*> NewBlocks;
201
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000202 for (std::vector<BasicBlock*>::iterator BB = LoopBlocks.begin(),
203 E = LoopBlocks.end(); BB != E; ++BB) {
Dan Gohman45b31972008-05-14 00:24:14 +0000204 ValueMapTy ValueMap;
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000205 BasicBlock *New = CloneBasicBlock(*BB, ValueMap, SuffixBuffer);
206 Header->getParent()->getBasicBlockList().push_back(New);
Dan Gohman45b31972008-05-14 00:24:14 +0000207
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000208 // Loop over all of the PHI nodes in the block, changing them to use the
209 // incoming values from the previous block.
210 if (*BB == Header)
211 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
212 PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]);
Dan Gohman45b31972008-05-14 00:24:14 +0000213 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];
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000217 ValueMap[OrigPHINode[i]] = InVal;
Dan Gohman45b31972008-05-14 00:24:14 +0000218 New->getInstList().erase(NewPHI);
219 }
220
221 // Update our running map of newest clones
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000222 LastValueMap[*BB] = New;
Dan Gohman45b31972008-05-14 00:24:14 +0000223 for (ValueMapTy::iterator VI = ValueMap.begin(), VE = ValueMap.end();
224 VI != VE; ++VI)
225 LastValueMap[VI->first] = VI->second;
226
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000227 L->addBasicBlockToLoop(New, LI->getBase());
228
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();
234 UI != UE;) {
235 Instruction *UseInst = cast<Instruction>(*UI);
236 ++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);
241 }
Dan Gohman45b31972008-05-14 00:24:14 +0000242 }
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000243
244 // Keep track of new headers and latches as we create them, so that
245 // we can insert the proper branches later.
246 if (*BB == Header)
247 Headers.push_back(New);
248 if (*BB == LatchBlock) {
249 Latches.push_back(New);
250
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
253 // blocks later on.
254 TerminatorInst *Term = New->getTerminator();
255 assert(L->contains(Term->getSuccessor(!ContinueOnTrue)));
256 assert(Term->getSuccessor(ContinueOnTrue) == LoopExit);
257 Term->setSuccessor(!ContinueOnTrue, NULL);
Dan Gohman45b31972008-05-14 00:24:14 +0000258 }
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000259
260 NewBlocks.push_back(New);
Dan Gohman45b31972008-05-14 00:24:14 +0000261 }
262
263 // Remap all instructions in the most recent iteration
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000264 for (unsigned i = 0; i < NewBlocks.size(); ++i)
Dan Gohman45b31972008-05-14 00:24:14 +0000265 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
266 E = NewBlocks[i]->end(); I != E; ++I)
267 RemapInstruction(I, LastValueMap);
268 }
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000269
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.
273 if (Count != 1) {
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))
278 Users.insert(phi);
279
280 BasicBlock *LastIterationBB = cast<BasicBlock>(LastValueMap[LatchBlock]);
281 for (SmallPtrSet<PHINode*,8>::iterator SI = Users.begin(), SE = Users.end();
282 SI != SE; ++SI) {
283 PHINode *PN = *SI;
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];
290 }
291 PN->addIncoming(InVal, LastIterationBB);
292 }
293 }
294
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);
303 }
304 }
Dan Gohman45b31972008-05-14 00:24:14 +0000305
306 // Now that all the basic blocks for the unrolled iterations are in place,
307 // set up the branches to connect them.
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000308 for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
Dan Gohman45b31972008-05-14 00:24:14 +0000309 // The original branch was replicated in each unrolled iteration.
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000310 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
Dan Gohman45b31972008-05-14 00:24:14 +0000311
312 // The branch destination.
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000313 unsigned j = (i + 1) % e;
314 BasicBlock *Dest = Headers[j];
Dan Gohman45b31972008-05-14 00:24:14 +0000315 bool NeedConditional = true;
316
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000317 // For a complete unroll, make the last iteration end with a branch
318 // to the exit block.
319 if (CompletelyUnroll && j == 0) {
Dan Gohman45b31972008-05-14 00:24:14 +0000320 Dest = LoopExit;
321 NeedConditional = false;
322 }
323
324 // If we know the trip count or a multiple of it, we can safely use an
325 // unconditional branch for some iterations.
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000326 if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) {
Dan Gohman45b31972008-05-14 00:24:14 +0000327 NeedConditional = false;
328 }
329
330 if (NeedConditional) {
331 // Update the conditional branch's successor for the following
332 // iteration.
333 Term->setSuccessor(!ContinueOnTrue, Dest);
334 } else {
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);
340 }
341 }
342 }
343
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000344 // 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
346 // go.
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; ) {
Dan Gohman45b31972008-05-14 00:24:14 +0000351 Instruction *Inst = I++;
352
353 if (isInstructionTriviallyDead(Inst))
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000354 (*BB)->getInstList().erase(Inst);
Dan Gohman45b31972008-05-14 00:24:14 +0000355 else if (Constant *C = ConstantFoldInstruction(Inst)) {
356 Inst->replaceAllUsesWith(C);
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000357 (*BB)->getInstList().erase(Inst);
Dan Gohman45b31972008-05-14 00:24:14 +0000358 }
359 }
Dan Gohman45b31972008-05-14 00:24:14 +0000360
361 NumCompletelyUnrolled += CompletelyUnroll;
362 ++NumUnrolled;
363 // Remove the loop from the LoopPassManager if it's completely removed.
364 if (CompletelyUnroll && LPM != NULL)
365 LPM->deleteLoopFromQueue(L);
366
367 // If we didn't completely unroll the loop, it should still be in LCSSA form.
368 if (!CompletelyUnroll)
369 assert(L->isLCSSAForm());
370
371 return true;
372}