blob: caef7ec5c45f9b27a8dc99012854d5435f5ce962 [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"
Chris Lattner29874e02008-12-03 19:44:02 +000028#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Dan Gohman45b31972008-05-14 00:24:14 +000029#include "llvm/Transforms/Utils/Cloning.h"
30#include "llvm/Transforms/Utils/Local.h"
Duncan Sands4520dd22008-10-08 07:23:46 +000031#include <cstdio>
Dan Gohman45b31972008-05-14 00:24:14 +000032
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);
46 if (It != ValueMap.end()) Op = It->second;
47 I->setOperand(op, Op);
48 }
49}
50
51/// 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
65 DOUT << "Merging: " << *BB << "into: " << *OnlyPred;
66
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.
Chris Lattner29874e02008-12-03 19:44:02 +000072 FoldSingleEntryPHINodes(BB);
Dan Gohman45b31972008-05-14 00:24:14 +000073
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
97/// 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
110 BasicBlock *Header = L->getHeader();
111 BasicBlock *LatchBlock = L->getLoopLatch();
112 BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000113
Dan Gohman45b31972008-05-14 00:24:14 +0000114 if (!BI || BI->isUnconditional()) {
115 // The loop-rotate pass can be helpful to avoid this in many cases.
116 DOUT << " Can't unroll; loop not terminated by a conditional branch.\n";
117 return false;
118 }
119
120 // Find trip count
121 unsigned TripCount = L->getSmallConstantTripCount();
122 // Find trip multiple if count is not available
123 unsigned TripMultiple = 1;
124 if (TripCount == 0)
125 TripMultiple = L->getSmallConstantTripMultiple();
126
127 if (TripCount != 0)
128 DOUT << " Trip Count = " << TripCount << "\n";
129 if (TripMultiple != 1)
130 DOUT << " Trip Multiple = " << TripMultiple << "\n";
131
132 // Effectively "DCE" unrolled iterations that are beyond the tripcount
133 // and will never be executed.
134 if (TripCount != 0 && Count > TripCount)
135 Count = TripCount;
136
137 assert(Count > 0);
138 assert(TripMultiple > 0);
139 assert(TripCount == 0 || TripCount % TripMultiple == 0);
140
141 // Are we eliminating the loop control altogether?
142 bool CompletelyUnroll = Count == TripCount;
143
144 // If we know the trip count, we know the multiple...
145 unsigned BreakoutTrip = 0;
146 if (TripCount != 0) {
147 BreakoutTrip = TripCount % Count;
148 TripMultiple = 0;
149 } else {
150 // Figure out what multiple to use.
151 BreakoutTrip = TripMultiple =
152 (unsigned)GreatestCommonDivisor64(Count, TripMultiple);
153 }
154
155 if (CompletelyUnroll) {
156 DOUT << "COMPLETELY UNROLLING loop %" << Header->getName()
157 << " with trip count " << TripCount << "!\n";
158 } else {
159 DOUT << "UNROLLING loop %" << Header->getName()
160 << " by " << Count;
161 if (TripMultiple == 0 || BreakoutTrip != TripMultiple) {
162 DOUT << " with a breakout at trip " << BreakoutTrip;
163 } else if (TripMultiple != 1) {
164 DOUT << " with " << TripMultiple << " trips per branch";
165 }
166 DOUT << "!\n";
167 }
168
169 std::vector<BasicBlock*> LoopBlocks = L->getBlocks();
170
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000171 bool ContinueOnTrue = L->contains(BI->getSuccessor(0));
Dan Gohman45b31972008-05-14 00:24:14 +0000172 BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);
173
174 // For the first iteration of the loop, we should use the precloned values for
175 // PHI nodes. Insert associations now.
176 typedef DenseMap<const Value*, Value*> ValueMapTy;
177 ValueMapTy LastValueMap;
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000178 std::vector<PHINode*> OrigPHINode;
Dan Gohman45b31972008-05-14 00:24:14 +0000179 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
180 PHINode *PN = cast<PHINode>(I);
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000181 OrigPHINode.push_back(PN);
Dan Gohman45b31972008-05-14 00:24:14 +0000182 if (Instruction *I =
183 dyn_cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock)))
184 if (L->contains(I->getParent()))
185 LastValueMap[I] = I;
186 }
187
188 std::vector<BasicBlock*> Headers;
189 std::vector<BasicBlock*> Latches;
190 Headers.push_back(Header);
191 Latches.push_back(LatchBlock);
192
193 for (unsigned It = 1; It != Count; ++It) {
194 char SuffixBuffer[100];
195 sprintf(SuffixBuffer, ".%d", It);
196
197 std::vector<BasicBlock*> NewBlocks;
198
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000199 for (std::vector<BasicBlock*>::iterator BB = LoopBlocks.begin(),
200 E = LoopBlocks.end(); BB != E; ++BB) {
Dan Gohman45b31972008-05-14 00:24:14 +0000201 ValueMapTy ValueMap;
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000202 BasicBlock *New = CloneBasicBlock(*BB, ValueMap, SuffixBuffer);
203 Header->getParent()->getBasicBlockList().push_back(New);
Dan Gohman45b31972008-05-14 00:24:14 +0000204
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000205 // Loop over all of the PHI nodes in the block, changing them to use the
206 // incoming values from the previous block.
207 if (*BB == Header)
208 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
209 PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]);
Dan Gohman45b31972008-05-14 00:24:14 +0000210 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
211 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
212 if (It > 1 && L->contains(InValI->getParent()))
213 InVal = LastValueMap[InValI];
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000214 ValueMap[OrigPHINode[i]] = InVal;
Dan Gohman45b31972008-05-14 00:24:14 +0000215 New->getInstList().erase(NewPHI);
216 }
217
218 // Update our running map of newest clones
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000219 LastValueMap[*BB] = New;
Dan Gohman45b31972008-05-14 00:24:14 +0000220 for (ValueMapTy::iterator VI = ValueMap.begin(), VE = ValueMap.end();
221 VI != VE; ++VI)
222 LastValueMap[VI->first] = VI->second;
223
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000224 L->addBasicBlockToLoop(New, LI->getBase());
225
226 // Add phi entries for newly created values to all exit blocks except
227 // the successor of the latch block. The successor of the exit block will
228 // be updated specially after unrolling all the way.
229 if (*BB != LatchBlock)
230 for (Value::use_iterator UI = (*BB)->use_begin(), UE = (*BB)->use_end();
231 UI != UE;) {
232 Instruction *UseInst = cast<Instruction>(*UI);
233 ++UI;
234 if (isa<PHINode>(UseInst) && !L->contains(UseInst->getParent())) {
235 PHINode *phi = cast<PHINode>(UseInst);
236 Value *Incoming = phi->getIncomingValueForBlock(*BB);
237 phi->addIncoming(Incoming, New);
238 }
Dan Gohman45b31972008-05-14 00:24:14 +0000239 }
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000240
241 // Keep track of new headers and latches as we create them, so that
242 // we can insert the proper branches later.
243 if (*BB == Header)
244 Headers.push_back(New);
245 if (*BB == LatchBlock) {
246 Latches.push_back(New);
247
248 // Also, clear out the new latch's back edge so that it doesn't look
249 // like a new loop, so that it's amenable to being merged with adjacent
250 // blocks later on.
251 TerminatorInst *Term = New->getTerminator();
252 assert(L->contains(Term->getSuccessor(!ContinueOnTrue)));
253 assert(Term->getSuccessor(ContinueOnTrue) == LoopExit);
254 Term->setSuccessor(!ContinueOnTrue, NULL);
Dan Gohman45b31972008-05-14 00:24:14 +0000255 }
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000256
257 NewBlocks.push_back(New);
Dan Gohman45b31972008-05-14 00:24:14 +0000258 }
259
260 // Remap all instructions in the most recent iteration
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000261 for (unsigned i = 0; i < NewBlocks.size(); ++i)
Dan Gohman45b31972008-05-14 00:24:14 +0000262 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
263 E = NewBlocks[i]->end(); I != E; ++I)
264 RemapInstruction(I, LastValueMap);
265 }
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000266
267 // The latch block exits the loop. If there are any PHI nodes in the
268 // successor blocks, update them to use the appropriate values computed as the
269 // last iteration of the loop.
270 if (Count != 1) {
271 SmallPtrSet<PHINode*, 8> Users;
272 for (Value::use_iterator UI = LatchBlock->use_begin(),
273 UE = LatchBlock->use_end(); UI != UE; ++UI)
274 if (PHINode *phi = dyn_cast<PHINode>(*UI))
275 Users.insert(phi);
276
277 BasicBlock *LastIterationBB = cast<BasicBlock>(LastValueMap[LatchBlock]);
278 for (SmallPtrSet<PHINode*,8>::iterator SI = Users.begin(), SE = Users.end();
279 SI != SE; ++SI) {
280 PHINode *PN = *SI;
281 Value *InVal = PN->removeIncomingValue(LatchBlock, false);
282 // If this value was defined in the loop, take the value defined by the
283 // last iteration of the loop.
284 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
285 if (L->contains(InValI->getParent()))
286 InVal = LastValueMap[InVal];
287 }
288 PN->addIncoming(InVal, LastIterationBB);
289 }
290 }
291
292 // Now, if we're doing complete unrolling, loop over the PHI nodes in the
293 // original block, setting them to their incoming values.
294 if (CompletelyUnroll) {
295 BasicBlock *Preheader = L->getLoopPreheader();
296 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
297 PHINode *PN = OrigPHINode[i];
298 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
299 Header->getInstList().erase(PN);
300 }
301 }
Dan Gohman45b31972008-05-14 00:24:14 +0000302
303 // Now that all the basic blocks for the unrolled iterations are in place,
304 // set up the branches to connect them.
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000305 for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
Dan Gohman45b31972008-05-14 00:24:14 +0000306 // The original branch was replicated in each unrolled iteration.
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000307 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
Dan Gohman45b31972008-05-14 00:24:14 +0000308
309 // The branch destination.
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000310 unsigned j = (i + 1) % e;
311 BasicBlock *Dest = Headers[j];
Dan Gohman45b31972008-05-14 00:24:14 +0000312 bool NeedConditional = true;
313
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000314 // For a complete unroll, make the last iteration end with a branch
315 // to the exit block.
316 if (CompletelyUnroll && j == 0) {
Dan Gohman45b31972008-05-14 00:24:14 +0000317 Dest = LoopExit;
318 NeedConditional = false;
319 }
320
321 // If we know the trip count or a multiple of it, we can safely use an
322 // unconditional branch for some iterations.
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000323 if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) {
Dan Gohman45b31972008-05-14 00:24:14 +0000324 NeedConditional = false;
325 }
326
327 if (NeedConditional) {
328 // Update the conditional branch's successor for the following
329 // iteration.
330 Term->setSuccessor(!ContinueOnTrue, Dest);
331 } else {
332 Term->setUnconditionalDest(Dest);
333 // Merge adjacent basic blocks, if possible.
334 if (BasicBlock *Fold = FoldBlockIntoPredecessor(Dest, LI)) {
335 std::replace(Latches.begin(), Latches.end(), Dest, Fold);
336 std::replace(Headers.begin(), Headers.end(), Dest, Fold);
337 }
338 }
339 }
340
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000341 // At this point, the code is well formed. We now do a quick sweep over the
342 // inserted code, doing constant propagation and dead code elimination as we
343 // go.
344 const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();
345 for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
346 BBE = NewLoopBlocks.end(); BB != BBE; ++BB)
347 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {
Dan Gohman45b31972008-05-14 00:24:14 +0000348 Instruction *Inst = I++;
349
350 if (isInstructionTriviallyDead(Inst))
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000351 (*BB)->getInstList().erase(Inst);
Dan Gohman45b31972008-05-14 00:24:14 +0000352 else if (Constant *C = ConstantFoldInstruction(Inst)) {
353 Inst->replaceAllUsesWith(C);
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000354 (*BB)->getInstList().erase(Inst);
Dan Gohman45b31972008-05-14 00:24:14 +0000355 }
356 }
Dan Gohman45b31972008-05-14 00:24:14 +0000357
358 NumCompletelyUnrolled += CompletelyUnroll;
359 ++NumUnrolled;
360 // Remove the loop from the LoopPassManager if it's completely removed.
361 if (CompletelyUnroll && LPM != NULL)
362 LPM->deleteLoopFromQueue(L);
363
364 // If we didn't completely unroll the loop, it should still be in LCSSA form.
365 if (!CompletelyUnroll)
366 assert(L->isLCSSAForm());
367
368 return true;
369}