blob: 8b296cb7685c186ca749adf8b0c7ba2ba65ceda2 [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"
30#include <cstdio>
31using namespace llvm;
32
33namespace {
34 Statistic<> NumUnrolled("loop-unroll", "Number of loops completely unrolled");
35
36 cl::opt<unsigned>
37 UnrollThreshold("unroll-threshold", cl::init(100), cl::Hidden,
38 cl::desc("The cut-off point for loop unrolling"));
39
40 class LoopUnroll : public FunctionPass {
41 LoopInfo *LI; // The current loop information
42 public:
43 virtual bool runOnFunction(Function &F);
44 bool visitLoop(Loop *L);
45
46 /// This transformation requires natural loop information & requires that
47 /// loop preheaders be inserted into the CFG...
48 ///
49 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner83bf2882004-04-18 05:20:17 +000050 AU.addRequiredID(LoopSimplifyID);
51 AU.addRequired<LoopInfo>();
Chris Lattner9c2cc462004-04-18 05:38:37 +000052 AU.addPreserved<LoopInfo>();
Chris Lattner83bf2882004-04-18 05:20:17 +000053 }
54 };
55 RegisterOpt<LoopUnroll> X("loop-unroll", "Unroll loops");
56}
57
58FunctionPass *llvm::createLoopUnrollPass() { return new LoopUnroll(); }
59
60bool LoopUnroll::runOnFunction(Function &F) {
61 bool Changed = false;
62 LI = &getAnalysis<LoopInfo>();
63
Chris Lattner9c2cc462004-04-18 05:38:37 +000064 // Transform all the top-level loops. Copy the loop list so that the child
65 // can update the loop tree if it needs to delete the loop.
66 std::vector<Loop*> SubLoops(LI->begin(), LI->end());
67 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
68 Changed |= visitLoop(SubLoops[i]);
Chris Lattner83bf2882004-04-18 05:20:17 +000069
70 return Changed;
71}
72
73/// ApproximateLoopSize - Approximate the size of the loop after it has been
74/// unrolled.
75static unsigned ApproximateLoopSize(const Loop *L) {
76 unsigned Size = 0;
77 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
78 BasicBlock *BB = L->getBlocks()[i];
79 Instruction *Term = BB->getTerminator();
80 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
81 if (isa<PHINode>(I) && BB == L->getHeader()) {
82 // Ignore PHI nodes in the header.
83 } else if (I->hasOneUse() && I->use_back() == Term) {
84 // Ignore instructions only used by the loop terminator.
85 } else {
86 ++Size;
87 }
88
89 // TODO: Ignore expressions derived from PHI and constants if inval of phi
90 // is a constant, or if operation is associative. This will get induction
91 // variables.
92 }
93 }
94
95 return Size;
96}
97
98// RemapInstruction - Convert the instruction operands from referencing the
99// current values into those specified by ValueMap.
100//
101static inline void RemapInstruction(Instruction *I,
102 std::map<const Value *, Value*> &ValueMap) {
103 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
104 Value *Op = I->getOperand(op);
105 std::map<const Value *, Value*>::iterator It = ValueMap.find(Op);
106 if (It != ValueMap.end()) Op = It->second;
107 I->setOperand(op, Op);
108 }
109}
110
111
112bool LoopUnroll::visitLoop(Loop *L) {
113 bool Changed = false;
114
115 // Recurse through all subloops before we process this loop. Copy the loop
116 // list so that the child can update the loop tree if it needs to delete the
117 // loop.
118 std::vector<Loop*> SubLoops(L->begin(), L->end());
119 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
120 Changed |= visitLoop(SubLoops[i]);
121
122 // We only handle single basic block loops right now.
123 if (L->getBlocks().size() != 1)
124 return Changed;
125
126 BasicBlock *BB = L->getHeader();
127 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
128 if (BI == 0) return Changed; // Must end in a conditional branch
129
130 ConstantInt *TripCountC = dyn_cast_or_null<ConstantInt>(L->getTripCount());
131 if (!TripCountC) return Changed; // Must have constant trip count!
132
133 unsigned TripCount = TripCountC->getRawValue();
134 if (TripCount != TripCountC->getRawValue())
135 return Changed; // More than 2^32 iterations???
136
137 unsigned LoopSize = ApproximateLoopSize(L);
138 DEBUG(std::cerr << "Loop Unroll: F[" << BB->getParent()->getName()
139 << "] Loop %" << BB->getName() << " Loop Size = " << LoopSize
140 << " Trip Count = " << TripCount << " - ");
141 if (LoopSize*TripCount > UnrollThreshold) {
142 DEBUG(std::cerr << "TOO LARGE: " << LoopSize*TripCount << ">"
143 << UnrollThreshold << "\n");
144 return Changed;
145 }
146 DEBUG(std::cerr << "UNROLLING!\n");
147
148 assert(L->getExitBlocks().size() == 1 && "Must have exactly one exit block!");
149 BasicBlock *LoopExit = L->getExitBlocks()[0];
150
151 // Create a new basic block to temporarily hold all of the cloned code.
152 BasicBlock *NewBlock = new BasicBlock();
153
154 // For the first iteration of the loop, we should use the precloned values for
155 // PHI nodes. Insert associations now.
156 std::map<const Value*, Value*> LastValueMap;
157 std::vector<PHINode*> OrigPHINode;
158 for (BasicBlock::iterator I = BB->begin();
159 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
160 OrigPHINode.push_back(PN);
161 if (Instruction *I =dyn_cast<Instruction>(PN->getIncomingValueForBlock(BB)))
162 if (I->getParent() == BB)
163 LastValueMap[I] = I;
164 }
165
166 // Remove the exit branch from the loop
167 BB->getInstList().erase(BI);
168
169 assert(TripCount != 0 && "Trip count of 0 is impossible!");
170 for (unsigned It = 1; It != TripCount; ++It) {
171 char SuffixBuffer[100];
172 sprintf(SuffixBuffer, ".%d", It);
173 std::map<const Value*, Value*> ValueMap;
174 BasicBlock *New = CloneBasicBlock(BB, ValueMap, SuffixBuffer);
175
176 // Loop over all of the PHI nodes in the block, changing them to use the
177 // incoming values from the previous block.
178 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
179 PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]);
180 Value *InVal = NewPHI->getIncomingValueForBlock(BB);
181 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
182 if (InValI->getParent() == BB)
183 InVal = LastValueMap[InValI];
184 ValueMap[OrigPHINode[i]] = InVal;
185 New->getInstList().erase(NewPHI);
186 }
187
188 for (BasicBlock::iterator I = New->begin(), E = New->end(); I != E; ++I)
189 RemapInstruction(I, ValueMap);
190
191 // Now that all of the instructions are remapped, splice them into the end
192 // of the NewBlock.
193 NewBlock->getInstList().splice(NewBlock->end(), New->getInstList());
194 delete New;
195
196 // LastValue map now contains values from this iteration.
197 std::swap(LastValueMap, ValueMap);
198 }
199
200 // If there was more than one iteration, replace any uses of values computed
201 // in the loop with values computed during last iteration of the loop.
202 if (TripCount != 1)
203 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
204 std::vector<User*> Users(I->use_begin(), I->use_end());
205 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
206 Instruction *UI = cast<Instruction>(Users[i]);
207 if (UI->getParent() != BB && UI->getParent() != NewBlock)
208 UI->replaceUsesOfWith(I, LastValueMap[I]);
209 }
210 }
211
212 // Now that we cloned the block as many times as we needed, stitch the new
213 // code into the original block and delete the temporary block.
214 BB->getInstList().splice(BB->end(), NewBlock->getInstList());
215 delete NewBlock;
216
217 // Now loop over the PHI nodes in the original block, setting them to their
218 // incoming values.
219 BasicBlock *Preheader = L->getLoopPreheader();
220 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
221 PHINode *PN = OrigPHINode[i];
222 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
223 BB->getInstList().erase(PN);
224 }
225
226 // Finally, add an unconditional branch to the block to continue into the exit
227 // block.
228 new BranchInst(LoopExit, BB);
229
230 // At this point, the code is well formed. We now do a quick sweep over the
231 // inserted code, doing constant propagation and dead code elimination as we
232 // go.
233 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
234 Instruction *Inst = I++;
235
236 if (isInstructionTriviallyDead(Inst))
237 BB->getInstList().erase(Inst);
238 else if (Constant *C = ConstantFoldInstruction(Inst)) {
239 Inst->replaceAllUsesWith(C);
240 BB->getInstList().erase(Inst);
241 }
242 }
243
Chris Lattner9c2cc462004-04-18 05:38:37 +0000244 // Update the loop information for this loop.
245 Loop *Parent = L->getParentLoop();
246
247 // Move all of the basic blocks in the loop into the parent loop.
248 LI->changeLoopFor(BB, Parent);
249
250 // Remove the loop from the parent.
251 if (Parent)
252 delete Parent->removeChildLoop(std::find(Parent->begin(), Parent->end(),L));
253 else
254 delete LI->removeLoop(std::find(LI->begin(), LI->end(), L));
255
256
257 // FIXME: Should update dominator analyses
Chris Lattner83bf2882004-04-18 05:20:17 +0000258
259 // FIXME: Should fold into preheader and exit block
260
261 ++NumUnrolled;
262 return true;
263}