blob: 9b68df05b844fa59afba0a518f6ca3d5042efe59 [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"
Duncan Sands4520dd22008-10-08 07:23:46 +000032#include <cstdio>
Dan Gohman45b31972008-05-14 00:24:14 +000033
34using namespace llvm;
35
Chris Lattner29874e02008-12-03 19:44:02 +000036// TODO: Should these be here or in LoopUnroll?
Dan Gohman45b31972008-05-14 00:24:14 +000037STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
38STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
39
40/// RemapInstruction - Convert the instruction operands from referencing the
41/// current values into those specified by ValueMap.
42static 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);
Dan Gohmanb56c9662009-10-31 14:46:50 +000047 if (It != ValueMap.end())
48 I->setOperand(op, It->second);
Dan Gohman45b31972008-05-14 00:24:14 +000049 }
50}
51
Dan Gohman45b31972008-05-14 00:24:14 +000052/// 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.
57///
58/// The LoopInfo Analysis that is passed will be kept consistent.
59///
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.
Dan Gohman8dbe7f82008-06-24 20:44:42 +000062bool llvm::UnrollLoop(Loop *L, unsigned Count, LoopInfo* LI, LPPassManager* LPM) {
Dan Gohman45b31972008-05-14 00:24:14 +000063 assert(L->isLCSSAForm());
64
65 BasicBlock *Header = L->getHeader();
66 BasicBlock *LatchBlock = L->getLoopLatch();
67 BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
Dan Gohman8dbe7f82008-06-24 20:44:42 +000068
Dan Gohman45b31972008-05-14 00:24:14 +000069 if (!BI || BI->isUnconditional()) {
70 // The loop-rotate pass can be helpful to avoid this in many cases.
Chris Lattnerbdff5482009-08-23 04:37:46 +000071 DEBUG(errs() <<
72 " Can't unroll; loop not terminated by a conditional branch.\n");
Dan Gohman45b31972008-05-14 00:24:14 +000073 return false;
74 }
75
76 // Find trip count
77 unsigned TripCount = L->getSmallConstantTripCount();
78 // Find trip multiple if count is not available
79 unsigned TripMultiple = 1;
80 if (TripCount == 0)
81 TripMultiple = L->getSmallConstantTripMultiple();
82
83 if (TripCount != 0)
Chris Lattnerbdff5482009-08-23 04:37:46 +000084 DEBUG(errs() << " Trip Count = " << TripCount << "\n");
Dan Gohman45b31972008-05-14 00:24:14 +000085 if (TripMultiple != 1)
Chris Lattnerbdff5482009-08-23 04:37:46 +000086 DEBUG(errs() << " Trip Multiple = " << TripMultiple << "\n");
Dan Gohman45b31972008-05-14 00:24:14 +000087
88 // Effectively "DCE" unrolled iterations that are beyond the tripcount
89 // and will never be executed.
90 if (TripCount != 0 && Count > TripCount)
91 Count = TripCount;
92
93 assert(Count > 0);
94 assert(TripMultiple > 0);
95 assert(TripCount == 0 || TripCount % TripMultiple == 0);
96
97 // Are we eliminating the loop control altogether?
98 bool CompletelyUnroll = Count == TripCount;
99
100 // If we know the trip count, we know the multiple...
101 unsigned BreakoutTrip = 0;
102 if (TripCount != 0) {
103 BreakoutTrip = TripCount % Count;
104 TripMultiple = 0;
105 } else {
106 // Figure out what multiple to use.
107 BreakoutTrip = TripMultiple =
108 (unsigned)GreatestCommonDivisor64(Count, TripMultiple);
109 }
110
111 if (CompletelyUnroll) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000112 DEBUG(errs() << "COMPLETELY UNROLLING loop %" << Header->getName()
113 << " with trip count " << TripCount << "!\n");
Dan Gohman45b31972008-05-14 00:24:14 +0000114 } else {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000115 DEBUG(errs() << "UNROLLING loop %" << Header->getName()
116 << " by " << Count);
Dan Gohman45b31972008-05-14 00:24:14 +0000117 if (TripMultiple == 0 || BreakoutTrip != TripMultiple) {
Chris Lattnerbdff5482009-08-23 04:37:46 +0000118 DEBUG(errs() << " with a breakout at trip " << BreakoutTrip);
Dan Gohman45b31972008-05-14 00:24:14 +0000119 } else if (TripMultiple != 1) {
Chris Lattnerbdff5482009-08-23 04:37:46 +0000120 DEBUG(errs() << " with " << TripMultiple << " trips per branch");
Dan Gohman45b31972008-05-14 00:24:14 +0000121 }
Chris Lattnerbdff5482009-08-23 04:37:46 +0000122 DEBUG(errs() << "!\n");
Dan Gohman45b31972008-05-14 00:24:14 +0000123 }
124
125 std::vector<BasicBlock*> LoopBlocks = L->getBlocks();
126
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000127 bool ContinueOnTrue = L->contains(BI->getSuccessor(0));
Dan Gohman45b31972008-05-14 00:24:14 +0000128 BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);
129
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;
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000134 std::vector<PHINode*> OrigPHINode;
Dan Gohman45b31972008-05-14 00:24:14 +0000135 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
136 PHINode *PN = cast<PHINode>(I);
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000137 OrigPHINode.push_back(PN);
Dan Gohman45b31972008-05-14 00:24:14 +0000138 if (Instruction *I =
139 dyn_cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock)))
140 if (L->contains(I->getParent()))
141 LastValueMap[I] = I;
142 }
143
144 std::vector<BasicBlock*> Headers;
145 std::vector<BasicBlock*> Latches;
146 Headers.push_back(Header);
147 Latches.push_back(LatchBlock);
148
149 for (unsigned It = 1; It != Count; ++It) {
150 char SuffixBuffer[100];
151 sprintf(SuffixBuffer, ".%d", It);
152
153 std::vector<BasicBlock*> NewBlocks;
154
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000155 for (std::vector<BasicBlock*>::iterator BB = LoopBlocks.begin(),
156 E = LoopBlocks.end(); BB != E; ++BB) {
Dan Gohman45b31972008-05-14 00:24:14 +0000157 ValueMapTy ValueMap;
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000158 BasicBlock *New = CloneBasicBlock(*BB, ValueMap, SuffixBuffer);
159 Header->getParent()->getBasicBlockList().push_back(New);
Dan Gohman45b31972008-05-14 00:24:14 +0000160
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000161 // Loop over all of the PHI nodes in the block, changing them to use the
162 // incoming values from the previous block.
163 if (*BB == Header)
164 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
165 PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]);
Dan Gohman45b31972008-05-14 00:24:14 +0000166 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];
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000170 ValueMap[OrigPHINode[i]] = InVal;
Dan Gohman45b31972008-05-14 00:24:14 +0000171 New->getInstList().erase(NewPHI);
172 }
173
174 // Update our running map of newest clones
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000175 LastValueMap[*BB] = New;
Dan Gohman45b31972008-05-14 00:24:14 +0000176 for (ValueMapTy::iterator VI = ValueMap.begin(), VE = ValueMap.end();
177 VI != VE; ++VI)
178 LastValueMap[VI->first] = VI->second;
179
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000180 L->addBasicBlockToLoop(New, LI->getBase());
181
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();
187 UI != UE;) {
188 Instruction *UseInst = cast<Instruction>(*UI);
189 ++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);
194 }
Dan Gohman45b31972008-05-14 00:24:14 +0000195 }
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000196
197 // Keep track of new headers and latches as we create them, so that
198 // we can insert the proper branches later.
199 if (*BB == Header)
200 Headers.push_back(New);
201 if (*BB == LatchBlock) {
202 Latches.push_back(New);
203
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
206 // blocks later on.
207 TerminatorInst *Term = New->getTerminator();
208 assert(L->contains(Term->getSuccessor(!ContinueOnTrue)));
209 assert(Term->getSuccessor(ContinueOnTrue) == LoopExit);
210 Term->setSuccessor(!ContinueOnTrue, NULL);
Dan Gohman45b31972008-05-14 00:24:14 +0000211 }
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000212
213 NewBlocks.push_back(New);
Dan Gohman45b31972008-05-14 00:24:14 +0000214 }
215
216 // Remap all instructions in the most recent iteration
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000217 for (unsigned i = 0; i < NewBlocks.size(); ++i)
Dan Gohman45b31972008-05-14 00:24:14 +0000218 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
219 E = NewBlocks[i]->end(); I != E; ++I)
220 RemapInstruction(I, LastValueMap);
221 }
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000222
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.
226 if (Count != 1) {
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))
231 Users.insert(phi);
232
233 BasicBlock *LastIterationBB = cast<BasicBlock>(LastValueMap[LatchBlock]);
234 for (SmallPtrSet<PHINode*,8>::iterator SI = Users.begin(), SE = Users.end();
235 SI != SE; ++SI) {
236 PHINode *PN = *SI;
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];
243 }
244 PN->addIncoming(InVal, LastIterationBB);
245 }
246 }
247
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);
256 }
257 }
Dan Gohman45b31972008-05-14 00:24:14 +0000258
259 // Now that all the basic blocks for the unrolled iterations are in place,
260 // set up the branches to connect them.
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000261 for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
Dan Gohman45b31972008-05-14 00:24:14 +0000262 // The original branch was replicated in each unrolled iteration.
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000263 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
Dan Gohman45b31972008-05-14 00:24:14 +0000264
265 // The branch destination.
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000266 unsigned j = (i + 1) % e;
267 BasicBlock *Dest = Headers[j];
Dan Gohman45b31972008-05-14 00:24:14 +0000268 bool NeedConditional = true;
269
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000270 // For a complete unroll, make the last iteration end with a branch
271 // to the exit block.
272 if (CompletelyUnroll && j == 0) {
Dan Gohman45b31972008-05-14 00:24:14 +0000273 Dest = LoopExit;
274 NeedConditional = false;
275 }
276
277 // If we know the trip count or a multiple of it, we can safely use an
278 // unconditional branch for some iterations.
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000279 if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) {
Dan Gohman45b31972008-05-14 00:24:14 +0000280 NeedConditional = false;
281 }
282
283 if (NeedConditional) {
284 // Update the conditional branch's successor for the following
285 // iteration.
286 Term->setSuccessor(!ContinueOnTrue, Dest);
287 } else {
288 Term->setUnconditionalDest(Dest);
289 // Merge adjacent basic blocks, if possible.
Dan Gohmanf230d8a2009-10-31 16:08:00 +0000290 if (BasicBlock *Fold = MergeBlockIntoPredecessor(Dest, LI)) {
Dan Gohman45b31972008-05-14 00:24:14 +0000291 std::replace(Latches.begin(), Latches.end(), Dest, Fold);
292 std::replace(Headers.begin(), Headers.end(), Dest, Fold);
293 }
294 }
295 }
296
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000297 // 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
299 // go.
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; ) {
Dan Gohman45b31972008-05-14 00:24:14 +0000304 Instruction *Inst = I++;
305
306 if (isInstructionTriviallyDead(Inst))
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000307 (*BB)->getInstList().erase(Inst);
Owen Anderson50895512009-07-06 18:42:36 +0000308 else if (Constant *C = ConstantFoldInstruction(Inst,
309 Header->getContext())) {
Dan Gohman45b31972008-05-14 00:24:14 +0000310 Inst->replaceAllUsesWith(C);
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000311 (*BB)->getInstList().erase(Inst);
Dan Gohman45b31972008-05-14 00:24:14 +0000312 }
313 }
Dan Gohman45b31972008-05-14 00:24:14 +0000314
315 NumCompletelyUnrolled += CompletelyUnroll;
316 ++NumUnrolled;
317 // Remove the loop from the LoopPassManager if it's completely removed.
318 if (CompletelyUnroll && LPM != NULL)
319 LPM->deleteLoopFromQueue(L);
320
321 // If we didn't completely unroll the loop, it should still be in LCSSA form.
322 if (!CompletelyUnroll)
323 assert(L->isLCSSAForm());
324
325 return true;
326}