Reverting back to original 1.8 version so I can manually merge in patch.
[llvm-complete.git] / lib / Transforms / Scalar / LoopUnroll.cpp
blob1dcf78d7c8d379e610eb51037dd2658197abbfed
1 //===-- 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.
14 // This pass is currently extremely limited. It only currently only unrolls
15 // single basic block loops that execute a constant number of times.
17 //===----------------------------------------------------------------------===//
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 "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/IntrinsicInst.h"
32 #include <cstdio>
33 #include <set>
34 #include <algorithm>
35 #include <iostream>
36 using namespace llvm;
38 namespace {
39 Statistic<> NumUnrolled("loop-unroll", "Number of loops completely unrolled");
41 cl::opt<unsigned>
42 UnrollThreshold("unroll-threshold", cl::init(100), cl::Hidden,
43 cl::desc("The cut-off point for loop unrolling"));
45 class LoopUnroll : public FunctionPass {
46 LoopInfo *LI; // The current loop information
47 public:
48 virtual bool runOnFunction(Function &F);
49 bool visitLoop(Loop *L);
51 /// This transformation requires natural loop information & requires that
52 /// loop preheaders be inserted into the CFG...
53 ///
54 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
55 AU.addRequiredID(LoopSimplifyID);
56 AU.addRequired<LoopInfo>();
57 AU.addPreserved<LoopInfo>();
60 RegisterOpt<LoopUnroll> X("loop-unroll", "Unroll loops");
63 FunctionPass *llvm::createLoopUnrollPass() { return new LoopUnroll(); }
65 bool LoopUnroll::runOnFunction(Function &F) {
66 bool Changed = false;
67 LI = &getAnalysis<LoopInfo>();
69 // Transform all the top-level loops. Copy the loop list so that the child
70 // can update the loop tree if it needs to delete the loop.
71 std::vector<Loop*> SubLoops(LI->begin(), LI->end());
72 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
73 Changed |= visitLoop(SubLoops[i]);
75 return Changed;
78 /// ApproximateLoopSize - Approximate the size of the loop after it has been
79 /// unrolled.
80 static unsigned ApproximateLoopSize(const Loop *L) {
81 unsigned Size = 0;
82 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
83 BasicBlock *BB = L->getBlocks()[i];
84 Instruction *Term = BB->getTerminator();
85 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
86 if (isa<PHINode>(I) && BB == L->getHeader()) {
87 // Ignore PHI nodes in the header.
88 } else if (I->hasOneUse() && I->use_back() == Term) {
89 // Ignore instructions only used by the loop terminator.
90 } else if (DbgInfoIntrinsic *DbgI = dyn_cast<DbgInfoIntrinsic>(I)) {
91 // Ignore debug instructions
92 } else {
93 ++Size;
96 // TODO: Ignore expressions derived from PHI and constants if inval of phi
97 // is a constant, or if operation is associative. This will get induction
98 // variables.
102 return Size;
105 // RemapInstruction - Convert the instruction operands from referencing the
106 // current values into those specified by ValueMap.
108 static inline void RemapInstruction(Instruction *I,
109 std::map<const Value *, Value*> &ValueMap) {
110 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
111 Value *Op = I->getOperand(op);
112 std::map<const Value *, Value*>::iterator It = ValueMap.find(Op);
113 if (It != ValueMap.end()) Op = It->second;
114 I->setOperand(op, Op);
118 bool LoopUnroll::visitLoop(Loop *L) {
119 bool Changed = false;
121 // Recurse through all subloops before we process this loop. Copy the loop
122 // list so that the child can update the loop tree if it needs to delete the
123 // loop.
124 std::vector<Loop*> SubLoops(L->begin(), L->end());
125 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
126 Changed |= visitLoop(SubLoops[i]);
128 // We only handle single basic block loops right now.
129 if (L->getBlocks().size() != 1)
130 return Changed;
132 BasicBlock *BB = L->getHeader();
133 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
134 if (BI == 0) return Changed; // Must end in a conditional branch
136 ConstantInt *TripCountC = dyn_cast_or_null<ConstantInt>(L->getTripCount());
137 if (!TripCountC) return Changed; // Must have constant trip count!
139 uint64_t TripCountFull = TripCountC->getRawValue();
140 if (TripCountFull != TripCountC->getRawValue() || TripCountFull == 0)
141 return Changed; // More than 2^32 iterations???
143 unsigned LoopSize = ApproximateLoopSize(L);
144 DEBUG(std::cerr << "Loop Unroll: F[" << BB->getParent()->getName()
145 << "] Loop %" << BB->getName() << " Loop Size = " << LoopSize
146 << " Trip Count = " << TripCountFull << " - ");
147 uint64_t Size = (uint64_t)LoopSize*TripCountFull;
148 if (Size > UnrollThreshold) {
149 DEBUG(std::cerr << "TOO LARGE: " << Size << ">" << UnrollThreshold << "\n");
150 return Changed;
152 DEBUG(std::cerr << "UNROLLING!\n");
154 unsigned TripCount = (unsigned)TripCountFull;
156 BasicBlock *LoopExit = BI->getSuccessor(L->contains(BI->getSuccessor(0)));
158 // Create a new basic block to temporarily hold all of the cloned code.
159 BasicBlock *NewBlock = new BasicBlock();
161 // For the first iteration of the loop, we should use the precloned values for
162 // PHI nodes. Insert associations now.
163 std::map<const Value*, Value*> LastValueMap;
164 std::vector<PHINode*> OrigPHINode;
165 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I) {
166 PHINode *PN = cast<PHINode>(I);
167 OrigPHINode.push_back(PN);
168 if (Instruction *I =dyn_cast<Instruction>(PN->getIncomingValueForBlock(BB)))
169 if (I->getParent() == BB)
170 LastValueMap[I] = I;
173 // Remove the exit branch from the loop
174 BB->getInstList().erase(BI);
176 assert(TripCount != 0 && "Trip count of 0 is impossible!");
177 for (unsigned It = 1; It != TripCount; ++It) {
178 char SuffixBuffer[100];
179 sprintf(SuffixBuffer, ".%d", It);
180 std::map<const Value*, Value*> ValueMap;
181 BasicBlock *New = CloneBasicBlock(BB, ValueMap, SuffixBuffer);
183 // Loop over all of the PHI nodes in the block, changing them to use the
184 // incoming values from the previous block.
185 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
186 PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]);
187 Value *InVal = NewPHI->getIncomingValueForBlock(BB);
188 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
189 if (InValI->getParent() == BB)
190 InVal = LastValueMap[InValI];
191 ValueMap[OrigPHINode[i]] = InVal;
192 New->getInstList().erase(NewPHI);
195 for (BasicBlock::iterator I = New->begin(), E = New->end(); I != E; ++I)
196 RemapInstruction(I, ValueMap);
198 // Now that all of the instructions are remapped, splice them into the end
199 // of the NewBlock.
200 NewBlock->getInstList().splice(NewBlock->end(), New->getInstList());
201 delete New;
203 // LastValue map now contains values from this iteration.
204 std::swap(LastValueMap, ValueMap);
207 // If there was more than one iteration, replace any uses of values computed
208 // in the loop with values computed during the last iteration of the loop.
209 if (TripCount != 1) {
210 std::set<User*> Users;
211 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
212 Users.insert(I->use_begin(), I->use_end());
214 // We don't want to reprocess entries with PHI nodes in them. For this
215 // reason, we look at each operand of each user exactly once, performing the
216 // substitution exactly once.
217 for (std::set<User*>::iterator UI = Users.begin(), E = Users.end(); UI != E;
218 ++UI) {
219 Instruction *I = cast<Instruction>(*UI);
220 if (I->getParent() != BB && I->getParent() != NewBlock)
221 RemapInstruction(I, LastValueMap);
225 // Now that we cloned the block as many times as we needed, stitch the new
226 // code into the original block and delete the temporary block.
227 BB->getInstList().splice(BB->end(), NewBlock->getInstList());
228 delete NewBlock;
230 // Now loop over the PHI nodes in the original block, setting them to their
231 // incoming values.
232 BasicBlock *Preheader = L->getLoopPreheader();
233 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
234 PHINode *PN = OrigPHINode[i];
235 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
236 BB->getInstList().erase(PN);
239 // Finally, add an unconditional branch to the block to continue into the exit
240 // block.
241 new BranchInst(LoopExit, BB);
243 // At this point, the code is well formed. We now do a quick sweep over the
244 // inserted code, doing constant propagation and dead code elimination as we
245 // go.
246 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
247 Instruction *Inst = I++;
249 if (isInstructionTriviallyDead(Inst))
250 BB->getInstList().erase(Inst);
251 else if (Constant *C = ConstantFoldInstruction(Inst)) {
252 Inst->replaceAllUsesWith(C);
253 BB->getInstList().erase(Inst);
257 // Update the loop information for this loop.
258 Loop *Parent = L->getParentLoop();
260 // Move all of the basic blocks in the loop into the parent loop.
261 LI->changeLoopFor(BB, Parent);
263 // Remove the loop from the parent.
264 if (Parent)
265 delete Parent->removeChildLoop(std::find(Parent->begin(), Parent->end(),L));
266 else
267 delete LI->removeLoop(std::find(LI->begin(), LI->end(), L));
269 // Remove single-entry Phis from the exit block.
270 for (BasicBlock::iterator ExitInstr = LoopExit->begin();
271 PHINode* PN = dyn_cast<PHINode>(ExitInstr); ++ExitInstr) {
272 assert(PN->getNumIncomingValues() == 1
273 && "Block should only have one pred, so Phi's must be single entry");
274 PN->replaceAllUsesWith(PN->getOperand(0));
275 PN->eraseFromParent();
278 // FIXME: Should update dominator analyses
280 // Now that everything is up-to-date that will be, we fold the loop block into
281 // the preheader and exit block, updating our analyses as we go.
282 LoopExit->getInstList().splice(LoopExit->begin(), BB->getInstList(),
283 BB->getInstList().begin(),
284 prior(BB->getInstList().end()));
285 LoopExit->getInstList().splice(LoopExit->begin(), Preheader->getInstList(),
286 Preheader->getInstList().begin(),
287 prior(Preheader->getInstList().end()));
289 // Make all other blocks in the program branch to LoopExit now instead of
290 // Preheader.
291 Preheader->replaceAllUsesWith(LoopExit);
293 Function *F = LoopExit->getParent();
294 if (Parent) {
295 // Otherwise, if this is a sub-loop, and the preheader was the loop header
296 // of the parent loop, move the exit block to be the new parent loop header.
297 if (Parent->getHeader() == Preheader) {
298 assert(Parent->contains(LoopExit) &&
299 "Exit block isn't contained in parent?");
300 Parent->moveToHeader(LoopExit);
302 } else {
303 // If the preheader was the entry block of this function, move the exit
304 // block to be the new entry of the function.
305 if (Preheader == &F->front())
306 F->getBasicBlockList().splice(F->begin(),
307 F->getBasicBlockList(), LoopExit);
310 // Remove BB and LoopExit from our analyses.
311 LI->removeBlock(Preheader);
312 LI->removeBlock(BB);
314 // Actually delete the blocks now.
315 F->getBasicBlockList().erase(Preheader);
316 F->getBasicBlockList().erase(BB);
318 ++NumUnrolled;
319 return true;