blob: 3ffdfac33b601df50a20e415b5a301ad78f0163e [file] [log] [blame]
Chris Lattner946b2552004-04-18 05:20:17 +00001//===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Chris Lattner946b2552004-04-18 05:20:17 +00003// 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.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
Chris Lattner946b2552004-04-18 05:20:17 +00008//===----------------------------------------------------------------------===//
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//
Owen Andersone001d812006-08-24 21:28:19 +000014// This pass will multi-block loops only if they contain no non-unrolled
15// subloops. The process of unrolling can produce extraneous basic blocks
16// linked with unconditional branches. This will be corrected in the future.
Chris Lattner946b2552004-04-18 05:20:17 +000017//
18//===----------------------------------------------------------------------===//
19
20#define DEBUG_TYPE "loop-unroll"
21#include "llvm/Transforms/Scalar.h"
22#include "llvm/Constants.h"
23#include "llvm/Function.h"
24#include "llvm/Instructions.h"
25#include "llvm/Analysis/LoopInfo.h"
26#include "llvm/Transforms/Utils/Cloning.h"
27#include "llvm/Transforms/Utils/Local.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000028#include "llvm/Support/CommandLine.h"
29#include "llvm/Support/Debug.h"
30#include "llvm/ADT/Statistic.h"
31#include "llvm/ADT/STLExtras.h"
Chris Lattner6d048a02004-11-22 17:18:36 +000032#include "llvm/IntrinsicInst.h"
Chris Lattner946b2552004-04-18 05:20:17 +000033#include <cstdio>
Chris Lattnerbc021772004-04-19 03:01:23 +000034#include <set>
Reid Spencerce078332004-10-18 14:38:48 +000035#include <algorithm>
Chris Lattnerc597b8a2006-01-22 23:32:06 +000036#include <iostream>
Chris Lattner946b2552004-04-18 05:20:17 +000037using namespace llvm;
38
39namespace {
40 Statistic<> NumUnrolled("loop-unroll", "Number of loops completely unrolled");
41
42 cl::opt<unsigned>
Chris Lattnerd1525022004-04-18 18:06:14 +000043 UnrollThreshold("unroll-threshold", cl::init(100), cl::Hidden,
Chris Lattner946b2552004-04-18 05:20:17 +000044 cl::desc("The cut-off point for loop unrolling"));
45
46 class LoopUnroll : public FunctionPass {
47 LoopInfo *LI; // The current loop information
48 public:
49 virtual bool runOnFunction(Function &F);
50 bool visitLoop(Loop *L);
51
52 /// This transformation requires natural loop information & requires that
53 /// loop preheaders be inserted into the CFG...
54 ///
55 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner946b2552004-04-18 05:20:17 +000056 AU.addRequiredID(LoopSimplifyID);
Owen Andersone001d812006-08-24 21:28:19 +000057 AU.addRequiredID(LCSSAID);
Chris Lattner946b2552004-04-18 05:20:17 +000058 AU.addRequired<LoopInfo>();
Owen Andersone001d812006-08-24 21:28:19 +000059 AU.addPreservedID(LCSSAID);
Chris Lattnerf2cc8412004-04-18 05:38:37 +000060 AU.addPreserved<LoopInfo>();
Chris Lattner946b2552004-04-18 05:20:17 +000061 }
62 };
63 RegisterOpt<LoopUnroll> X("loop-unroll", "Unroll loops");
64}
65
66FunctionPass *llvm::createLoopUnrollPass() { return new LoopUnroll(); }
67
68bool LoopUnroll::runOnFunction(Function &F) {
69 bool Changed = false;
70 LI = &getAnalysis<LoopInfo>();
71
Chris Lattnerf2cc8412004-04-18 05:38:37 +000072 // Transform all the top-level loops. Copy the loop list so that the child
73 // can update the loop tree if it needs to delete the loop.
74 std::vector<Loop*> SubLoops(LI->begin(), LI->end());
75 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
76 Changed |= visitLoop(SubLoops[i]);
Chris Lattner946b2552004-04-18 05:20:17 +000077
78 return Changed;
79}
80
81/// ApproximateLoopSize - Approximate the size of the loop after it has been
82/// unrolled.
83static unsigned ApproximateLoopSize(const Loop *L) {
84 unsigned Size = 0;
85 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
86 BasicBlock *BB = L->getBlocks()[i];
87 Instruction *Term = BB->getTerminator();
88 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
89 if (isa<PHINode>(I) && BB == L->getHeader()) {
90 // Ignore PHI nodes in the header.
91 } else if (I->hasOneUse() && I->use_back() == Term) {
92 // Ignore instructions only used by the loop terminator.
Chris Lattner6d048a02004-11-22 17:18:36 +000093 } else if (DbgInfoIntrinsic *DbgI = dyn_cast<DbgInfoIntrinsic>(I)) {
Jeff Cohen82639852005-04-23 21:38:35 +000094 // Ignore debug instructions
Chris Lattner946b2552004-04-18 05:20:17 +000095 } else {
96 ++Size;
97 }
98
99 // TODO: Ignore expressions derived from PHI and constants if inval of phi
100 // is a constant, or if operation is associative. This will get induction
101 // variables.
102 }
103 }
104
105 return Size;
106}
107
Misha Brukmanb1c93172005-04-21 23:48:37 +0000108// RemapInstruction - Convert the instruction operands from referencing the
Chris Lattner946b2552004-04-18 05:20:17 +0000109// current values into those specified by ValueMap.
110//
Misha Brukmanb1c93172005-04-21 23:48:37 +0000111static inline void RemapInstruction(Instruction *I,
Chris Lattner946b2552004-04-18 05:20:17 +0000112 std::map<const Value *, Value*> &ValueMap) {
113 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
114 Value *Op = I->getOperand(op);
115 std::map<const Value *, Value*>::iterator It = ValueMap.find(Op);
116 if (It != ValueMap.end()) Op = It->second;
117 I->setOperand(op, Op);
118 }
119}
120
Chris Lattner946b2552004-04-18 05:20:17 +0000121bool LoopUnroll::visitLoop(Loop *L) {
122 bool Changed = false;
123
124 // Recurse through all subloops before we process this loop. Copy the loop
125 // list so that the child can update the loop tree if it needs to delete the
126 // loop.
127 std::vector<Loop*> SubLoops(L->begin(), L->end());
128 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
129 Changed |= visitLoop(SubLoops[i]);
130
Owen Andersone001d812006-08-24 21:28:19 +0000131 BasicBlock* Header = L->getHeader();
132 BasicBlock* LatchBlock = L->getLoopLatch();
Chris Lattner946b2552004-04-18 05:20:17 +0000133
Owen Andersone001d812006-08-24 21:28:19 +0000134 BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
Chris Lattner946b2552004-04-18 05:20:17 +0000135 if (BI == 0) return Changed; // Must end in a conditional branch
136
137 ConstantInt *TripCountC = dyn_cast_or_null<ConstantInt>(L->getTripCount());
138 if (!TripCountC) return Changed; // Must have constant trip count!
139
Chris Lattner47f395c2005-01-08 19:37:20 +0000140 uint64_t TripCountFull = TripCountC->getRawValue();
141 if (TripCountFull != TripCountC->getRawValue() || TripCountFull == 0)
Chris Lattner946b2552004-04-18 05:20:17 +0000142 return Changed; // More than 2^32 iterations???
143
144 unsigned LoopSize = ApproximateLoopSize(L);
Owen Andersone001d812006-08-24 21:28:19 +0000145 DEBUG(std::cerr << "Loop Unroll: F[" << Header->getParent()->getName()
146 << "] Loop %" << Header->getName() << " Loop Size = "
147 << LoopSize << " Trip Count = " << TripCountFull << " - ");
Chris Lattner47f395c2005-01-08 19:37:20 +0000148 uint64_t Size = (uint64_t)LoopSize*TripCountFull;
Chris Lattnerc12c9452004-05-13 20:43:31 +0000149 if (Size > UnrollThreshold) {
150 DEBUG(std::cerr << "TOO LARGE: " << Size << ">" << UnrollThreshold << "\n");
Chris Lattner946b2552004-04-18 05:20:17 +0000151 return Changed;
152 }
153 DEBUG(std::cerr << "UNROLLING!\n");
Misha Brukmanb1c93172005-04-21 23:48:37 +0000154
Owen Andersone001d812006-08-24 21:28:19 +0000155 std::vector<BasicBlock*> LoopBlocks = L->getBlocks();
156
Chris Lattner47f395c2005-01-08 19:37:20 +0000157 unsigned TripCount = (unsigned)TripCountFull;
158
Owen Andersone001d812006-08-24 21:28:19 +0000159 BasicBlock *LoopExit = BI->getSuccessor(L->contains(BI->getSuccessor(0)));
Chris Lattner946b2552004-04-18 05:20:17 +0000160
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;
Owen Andersone001d812006-08-24 21:28:19 +0000165 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
Reid Spencer66149462004-09-15 17:06:42 +0000166 PHINode *PN = cast<PHINode>(I);
Chris Lattner946b2552004-04-18 05:20:17 +0000167 OrigPHINode.push_back(PN);
Owen Andersone001d812006-08-24 21:28:19 +0000168 if (Instruction *I =
169 dyn_cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock)))
170 if (L->contains(I->getParent()))
Chris Lattner946b2552004-04-18 05:20:17 +0000171 LastValueMap[I] = I;
172 }
173
174 // Remove the exit branch from the loop
Owen Andersone001d812006-08-24 21:28:19 +0000175 LatchBlock->getInstList().erase(BI);
176
177 std::vector<BasicBlock*> Headers;
178 std::vector<BasicBlock*> Latches;
179 Headers.push_back(Header);
180 Latches.push_back(LatchBlock);
Chris Lattner946b2552004-04-18 05:20:17 +0000181
182 assert(TripCount != 0 && "Trip count of 0 is impossible!");
183 for (unsigned It = 1; It != TripCount; ++It) {
184 char SuffixBuffer[100];
185 sprintf(SuffixBuffer, ".%d", It);
Owen Andersone001d812006-08-24 21:28:19 +0000186
187 std::vector<BasicBlock*> NewBlocks;
188
189 for (std::vector<BasicBlock*>::iterator BB = LoopBlocks.begin(),
190 E = LoopBlocks.end(); BB != E; ++BB) {
191 std::map<const Value*, Value*> ValueMap;
192 BasicBlock *New = CloneBasicBlock(*BB, ValueMap, SuffixBuffer);
193 Header->getParent()->getBasicBlockList().push_back(New);
Chris Lattner946b2552004-04-18 05:20:17 +0000194
Owen Andersone001d812006-08-24 21:28:19 +0000195 // Loop over all of the PHI nodes in the block, changing them to use the
196 // incoming values from the previous block.
197 if (*BB == Header)
198 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
199 PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]);
200 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
201 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
202 if (It > 1 && L->contains(InValI->getParent()))
203 InVal = LastValueMap[InValI];
204 ValueMap[OrigPHINode[i]] = InVal;
205 New->getInstList().erase(NewPHI);
206 }
207
208 // Update our running map of newest clones
209 LastValueMap[*BB] = New;
210 for (std::map<const Value*, Value*>::iterator VI = ValueMap.begin(),
211 VE = ValueMap.end(); VI != VE; ++VI)
212 LastValueMap[VI->first] = VI->second;
213
214 L->addBasicBlockToLoop(New, *LI);
215
216 // Add phi entries for newly created values to all exit blocks except
217 // the successor of the latch block. The successor of the exit block will
218 // be updated specially after unrolling all the way.
219 if (*BB != LatchBlock)
220 for (Value::use_iterator UI = (*BB)->use_begin(), UE = (*BB)->use_end();
221 UI != UE; ++UI) {
222 Instruction* UseInst = cast<Instruction>(*UI);
223 if (isa<PHINode>(UseInst) && !L->contains(UseInst->getParent())) {
224 PHINode* phi = cast<PHINode>(UseInst);
225 Value* Incoming = phi->getIncomingValueForBlock(*BB);
226 if (isa<Instruction>(Incoming))
227 Incoming = LastValueMap[Incoming];
228
229 phi->addIncoming(Incoming, New);
230 }
231 }
232
233 // Keep track of new headers and latches as we create them, so that
234 // we can insert the proper branches later.
235 if (*BB == Header)
236 Headers.push_back(New);
237 if (*BB == LatchBlock)
238 Latches.push_back(New);
239
240 NewBlocks.push_back(New);
Chris Lattner946b2552004-04-18 05:20:17 +0000241 }
Owen Andersone001d812006-08-24 21:28:19 +0000242
243 // Remap all instructions in the most recent iteration
244 for (unsigned i = 0; i < NewBlocks.size(); ++i)
245 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
246 E = NewBlocks[i]->end(); I != E; ++I)
Chris Lattner230bcb62004-04-18 17:32:39 +0000247 RemapInstruction(I, LastValueMap);
Chris Lattner230bcb62004-04-18 17:32:39 +0000248 }
Chris Lattner946b2552004-04-18 05:20:17 +0000249
Owen Andersone001d812006-08-24 21:28:19 +0000250 // Insert the branches that link the different iterations together
251 for (unsigned i = 0; i < Latches.size()-1; ++i)
252 new BranchInst(Headers[i+1], Latches[i]);
253
254 // Finally, add an unconditional branch to the block to continue into the exit
255 // block.
256 new BranchInst(LoopExit, Latches[Latches.size()-1]);
257
258 // Update PHI nodes that reference the final latch block
259 if (TripCount > 1) {
260 std::set<PHINode*> Users;
261 for (Value::use_iterator UI = LatchBlock->use_begin(),
262 UE = LatchBlock->use_end(); UI != UE; ++UI)
263 if (PHINode* phi = dyn_cast<PHINode>(*UI))
264 Users.insert(phi);
265
266 for (std::set<PHINode*>::iterator SI = Users.begin(), SE = Users.end();
267 SI != SE; ++SI) {
268 Value* InVal = (*SI)->getIncomingValueForBlock(LatchBlock);
269 if (isa<Instruction>(InVal))
270 InVal = LastValueMap[InVal];
271 (*SI)->removeIncomingValue(LatchBlock, false);
272 (*SI)->addIncoming(InVal, cast<BasicBlock>(LastValueMap[LatchBlock]));
273 }
274 }
Chris Lattner946b2552004-04-18 05:20:17 +0000275
276 // Now loop over the PHI nodes in the original block, setting them to their
277 // incoming values.
278 BasicBlock *Preheader = L->getLoopPreheader();
279 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
280 PHINode *PN = OrigPHINode[i];
281 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
Owen Andersone001d812006-08-24 21:28:19 +0000282 Header->getInstList().erase(PN);
283 }
Chris Lattner946b2552004-04-18 05:20:17 +0000284
285 // At this point, the code is well formed. We now do a quick sweep over the
286 // inserted code, doing constant propagation and dead code elimination as we
287 // go.
Owen Andersone001d812006-08-24 21:28:19 +0000288 const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();
289 for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
290 E = NewLoopBlocks.end(); BB != E; ++BB)
291 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {
292 Instruction *Inst = I++;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000293
Owen Andersone001d812006-08-24 21:28:19 +0000294 if (isInstructionTriviallyDead(Inst))
295 (*BB)->getInstList().erase(Inst);
296 else if (Constant *C = ConstantFoldInstruction(Inst)) {
297 Inst->replaceAllUsesWith(C);
298 (*BB)->getInstList().erase(Inst);
299 }
Chris Lattner946b2552004-04-18 05:20:17 +0000300 }
Chris Lattner946b2552004-04-18 05:20:17 +0000301
Chris Lattnerf2cc8412004-04-18 05:38:37 +0000302 // Update the loop information for this loop.
303 Loop *Parent = L->getParentLoop();
304
305 // Move all of the basic blocks in the loop into the parent loop.
Owen Andersone001d812006-08-24 21:28:19 +0000306 for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
307 E = NewLoopBlocks.end(); BB != E; ++BB)
308 LI->changeLoopFor(*BB, Parent);
Chris Lattnerf2cc8412004-04-18 05:38:37 +0000309
310 // Remove the loop from the parent.
311 if (Parent)
312 delete Parent->removeChildLoop(std::find(Parent->begin(), Parent->end(),L));
313 else
314 delete LI->removeLoop(std::find(LI->begin(), LI->end(), L));
315
Chris Lattner946b2552004-04-18 05:20:17 +0000316 ++NumUnrolled;
317 return true;
318}