blob: 90de9e946daa38bc13a24ef1ec6f48f8c753017a [file] [log] [blame]
Chris Lattner83bf2882004-04-18 05:20:17 +00001//===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass implements a simple loop unroller. It works best when loops have
11// been canonicalized by the -indvars pass, allowing it to determine the trip
12// counts of loops easily.
13//
14// This pass is currently extremely limited. It only currently only unrolls
15// single basic block loops that execute a constant number of times.
16//
17//===----------------------------------------------------------------------===//
18
19#define DEBUG_TYPE "loop-unroll"
20#include "llvm/Transforms/Scalar.h"
21#include "llvm/Constants.h"
22#include "llvm/Function.h"
23#include "llvm/Instructions.h"
24#include "llvm/Analysis/LoopInfo.h"
25#include "llvm/Transforms/Utils/Cloning.h"
26#include "llvm/Transforms/Utils/Local.h"
27#include "Support/CommandLine.h"
28#include "Support/Debug.h"
29#include "Support/Statistic.h"
Chris Lattner50ca0a12004-04-18 06:27:43 +000030#include "Support/STLExtras.h"
Chris Lattner83bf2882004-04-18 05:20:17 +000031#include <cstdio>
32using namespace llvm;
33
34namespace {
35 Statistic<> NumUnrolled("loop-unroll", "Number of loops completely unrolled");
36
37 cl::opt<unsigned>
Chris Lattner50ca0a12004-04-18 06:27:43 +000038 UnrollThreshold("unroll-threshold", cl::init(250), cl::Hidden,
Chris Lattner83bf2882004-04-18 05:20:17 +000039 cl::desc("The cut-off point for loop unrolling"));
40
41 class LoopUnroll : public FunctionPass {
42 LoopInfo *LI; // The current loop information
43 public:
44 virtual bool runOnFunction(Function &F);
45 bool visitLoop(Loop *L);
46
47 /// This transformation requires natural loop information & requires that
48 /// loop preheaders be inserted into the CFG...
49 ///
50 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner83bf2882004-04-18 05:20:17 +000051 AU.addRequiredID(LoopSimplifyID);
52 AU.addRequired<LoopInfo>();
Chris Lattner9c2cc462004-04-18 05:38:37 +000053 AU.addPreserved<LoopInfo>();
Chris Lattner83bf2882004-04-18 05:20:17 +000054 }
55 };
56 RegisterOpt<LoopUnroll> X("loop-unroll", "Unroll loops");
57}
58
59FunctionPass *llvm::createLoopUnrollPass() { return new LoopUnroll(); }
60
61bool LoopUnroll::runOnFunction(Function &F) {
62 bool Changed = false;
63 LI = &getAnalysis<LoopInfo>();
64
Chris Lattner9c2cc462004-04-18 05:38:37 +000065 // Transform all the top-level loops. Copy the loop list so that the child
66 // can update the loop tree if it needs to delete the loop.
67 std::vector<Loop*> SubLoops(LI->begin(), LI->end());
68 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
69 Changed |= visitLoop(SubLoops[i]);
Chris Lattner83bf2882004-04-18 05:20:17 +000070
71 return Changed;
72}
73
74/// ApproximateLoopSize - Approximate the size of the loop after it has been
75/// unrolled.
76static unsigned ApproximateLoopSize(const Loop *L) {
77 unsigned Size = 0;
78 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
79 BasicBlock *BB = L->getBlocks()[i];
80 Instruction *Term = BB->getTerminator();
81 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
82 if (isa<PHINode>(I) && BB == L->getHeader()) {
83 // Ignore PHI nodes in the header.
84 } else if (I->hasOneUse() && I->use_back() == Term) {
85 // Ignore instructions only used by the loop terminator.
86 } else {
87 ++Size;
88 }
89
90 // TODO: Ignore expressions derived from PHI and constants if inval of phi
91 // is a constant, or if operation is associative. This will get induction
92 // variables.
93 }
94 }
95
96 return Size;
97}
98
99// RemapInstruction - Convert the instruction operands from referencing the
100// current values into those specified by ValueMap.
101//
102static inline void RemapInstruction(Instruction *I,
103 std::map<const Value *, Value*> &ValueMap) {
104 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
105 Value *Op = I->getOperand(op);
106 std::map<const Value *, Value*>::iterator It = ValueMap.find(Op);
107 if (It != ValueMap.end()) Op = It->second;
108 I->setOperand(op, Op);
109 }
110}
111
Chris Lattner50ca0a12004-04-18 06:27:43 +0000112static void ChangeExitBlocksFromTo(Loop::iterator I, Loop::iterator E,
113 BasicBlock *Old, BasicBlock *New) {
114 for (; I != E; ++I) {
115 Loop *L = *I;
116 if (L->hasExitBlock(Old)) {
117 L->changeExitBlock(Old, New);
118 ChangeExitBlocksFromTo(L->begin(), L->end(), Old, New);
119 }
120 }
121}
122
Chris Lattner83bf2882004-04-18 05:20:17 +0000123
124bool LoopUnroll::visitLoop(Loop *L) {
125 bool Changed = false;
126
127 // Recurse through all subloops before we process this loop. Copy the loop
128 // list so that the child can update the loop tree if it needs to delete the
129 // loop.
130 std::vector<Loop*> SubLoops(L->begin(), L->end());
131 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
132 Changed |= visitLoop(SubLoops[i]);
133
134 // We only handle single basic block loops right now.
135 if (L->getBlocks().size() != 1)
136 return Changed;
137
138 BasicBlock *BB = L->getHeader();
139 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
140 if (BI == 0) return Changed; // Must end in a conditional branch
141
142 ConstantInt *TripCountC = dyn_cast_or_null<ConstantInt>(L->getTripCount());
143 if (!TripCountC) return Changed; // Must have constant trip count!
144
145 unsigned TripCount = TripCountC->getRawValue();
146 if (TripCount != TripCountC->getRawValue())
147 return Changed; // More than 2^32 iterations???
148
149 unsigned LoopSize = ApproximateLoopSize(L);
150 DEBUG(std::cerr << "Loop Unroll: F[" << BB->getParent()->getName()
151 << "] Loop %" << BB->getName() << " Loop Size = " << LoopSize
152 << " Trip Count = " << TripCount << " - ");
153 if (LoopSize*TripCount > UnrollThreshold) {
154 DEBUG(std::cerr << "TOO LARGE: " << LoopSize*TripCount << ">"
155 << UnrollThreshold << "\n");
156 return Changed;
157 }
158 DEBUG(std::cerr << "UNROLLING!\n");
159
160 assert(L->getExitBlocks().size() == 1 && "Must have exactly one exit block!");
161 BasicBlock *LoopExit = L->getExitBlocks()[0];
162
163 // Create a new basic block to temporarily hold all of the cloned code.
164 BasicBlock *NewBlock = new BasicBlock();
165
166 // For the first iteration of the loop, we should use the precloned values for
167 // PHI nodes. Insert associations now.
168 std::map<const Value*, Value*> LastValueMap;
169 std::vector<PHINode*> OrigPHINode;
170 for (BasicBlock::iterator I = BB->begin();
171 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
172 OrigPHINode.push_back(PN);
173 if (Instruction *I =dyn_cast<Instruction>(PN->getIncomingValueForBlock(BB)))
174 if (I->getParent() == BB)
175 LastValueMap[I] = I;
176 }
177
178 // Remove the exit branch from the loop
179 BB->getInstList().erase(BI);
180
181 assert(TripCount != 0 && "Trip count of 0 is impossible!");
182 for (unsigned It = 1; It != TripCount; ++It) {
183 char SuffixBuffer[100];
184 sprintf(SuffixBuffer, ".%d", It);
185 std::map<const Value*, Value*> ValueMap;
186 BasicBlock *New = CloneBasicBlock(BB, ValueMap, SuffixBuffer);
187
188 // Loop over all of the PHI nodes in the block, changing them to use the
189 // incoming values from the previous block.
190 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
191 PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]);
192 Value *InVal = NewPHI->getIncomingValueForBlock(BB);
193 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
194 if (InValI->getParent() == BB)
195 InVal = LastValueMap[InValI];
196 ValueMap[OrigPHINode[i]] = InVal;
197 New->getInstList().erase(NewPHI);
198 }
199
200 for (BasicBlock::iterator I = New->begin(), E = New->end(); I != E; ++I)
201 RemapInstruction(I, ValueMap);
202
203 // Now that all of the instructions are remapped, splice them into the end
204 // of the NewBlock.
205 NewBlock->getInstList().splice(NewBlock->end(), New->getInstList());
206 delete New;
207
208 // LastValue map now contains values from this iteration.
209 std::swap(LastValueMap, ValueMap);
210 }
211
212 // If there was more than one iteration, replace any uses of values computed
Chris Lattner998f44f2004-04-18 17:32:39 +0000213 // in the loop with values computed during the last iteration of the loop.
214 if (TripCount != 1) {
215 std::set<User*> Users;
216 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
217 Users.insert(I->use_begin(), I->use_end());
218
219 // We don't want to reprocess entries with PHI nodes in them. For this
220 // reason, we look at each operand of each user exactly once, performing the
221 // stubstitution exactly once.
222 for (std::set<User*>::iterator UI = Users.begin(), E = Users.end(); UI != E;
223 ++UI) {
224 Instruction *I = cast<Instruction>(*UI);
225 if (I->getParent() != BB && I->getParent() != NewBlock)
226 RemapInstruction(I, LastValueMap);
Chris Lattner83bf2882004-04-18 05:20:17 +0000227 }
Chris Lattner998f44f2004-04-18 17:32:39 +0000228 }
Chris Lattner83bf2882004-04-18 05:20:17 +0000229
230 // Now that we cloned the block as many times as we needed, stitch the new
231 // code into the original block and delete the temporary block.
232 BB->getInstList().splice(BB->end(), NewBlock->getInstList());
233 delete NewBlock;
234
235 // Now loop over the PHI nodes in the original block, setting them to their
236 // incoming values.
237 BasicBlock *Preheader = L->getLoopPreheader();
238 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
239 PHINode *PN = OrigPHINode[i];
240 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
241 BB->getInstList().erase(PN);
242 }
243
244 // Finally, add an unconditional branch to the block to continue into the exit
245 // block.
246 new BranchInst(LoopExit, BB);
247
248 // At this point, the code is well formed. We now do a quick sweep over the
249 // inserted code, doing constant propagation and dead code elimination as we
250 // go.
251 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
252 Instruction *Inst = I++;
253
254 if (isInstructionTriviallyDead(Inst))
255 BB->getInstList().erase(Inst);
256 else if (Constant *C = ConstantFoldInstruction(Inst)) {
257 Inst->replaceAllUsesWith(C);
258 BB->getInstList().erase(Inst);
259 }
260 }
261
Chris Lattner9c2cc462004-04-18 05:38:37 +0000262 // Update the loop information for this loop.
263 Loop *Parent = L->getParentLoop();
264
265 // Move all of the basic blocks in the loop into the parent loop.
266 LI->changeLoopFor(BB, Parent);
267
268 // Remove the loop from the parent.
269 if (Parent)
270 delete Parent->removeChildLoop(std::find(Parent->begin(), Parent->end(),L));
271 else
272 delete LI->removeLoop(std::find(LI->begin(), LI->end(), L));
273
274
275 // FIXME: Should update dominator analyses
Chris Lattner83bf2882004-04-18 05:20:17 +0000276
Chris Lattner50ca0a12004-04-18 06:27:43 +0000277
278 // Now that everything is up-to-date that will be, we fold the loop block into
279 // the preheader and exit block, updating our analyses as we go.
280 LoopExit->getInstList().splice(LoopExit->begin(), BB->getInstList(),
281 BB->getInstList().begin(),
282 prior(BB->getInstList().end()));
283 LoopExit->getInstList().splice(LoopExit->begin(), Preheader->getInstList(),
284 Preheader->getInstList().begin(),
285 prior(Preheader->getInstList().end()));
286
287 // Make all other blocks in the program branch to LoopExit now instead of
288 // Preheader.
289 Preheader->replaceAllUsesWith(LoopExit);
290
291 // Remove BB and LoopExit from our analyses.
292 LI->removeBlock(Preheader);
293 LI->removeBlock(BB);
294
295 // If any loops used Preheader as an exit block, update them to use LoopExit.
296 if (Parent)
297 ChangeExitBlocksFromTo(Parent->begin(), Parent->end(),
298 Preheader, LoopExit);
299 else
300 ChangeExitBlocksFromTo(LI->begin(), LI->end(),
301 Preheader, LoopExit);
302
Chris Lattnercc439092004-04-18 17:38:42 +0000303 // If the preheader was the entry block of this function, move the exit block
304 // to be the new entry of the loop.
305 Function *F = LoopExit->getParent();
306 if (Preheader == &F->front())
307 F->getBasicBlockList().splice(F->begin(), F->getBasicBlockList(), LoopExit);
Chris Lattner50ca0a12004-04-18 06:27:43 +0000308
309 // Actually delete the blocks now.
Chris Lattnercc439092004-04-18 17:38:42 +0000310 F->getBasicBlockList().erase(Preheader);
311 F->getBasicBlockList().erase(BB);
Chris Lattner83bf2882004-04-18 05:20:17 +0000312
313 ++NumUnrolled;
314 return true;
315}