blob: 3bff2737bcdcc115e2d31c3fe63a7ebfa82eca77 [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"
Owen Anderson62c84fe2006-08-28 02:09:46 +000028#include "llvm/Support/CFG.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000029#include "llvm/Support/CommandLine.h"
30#include "llvm/Support/Debug.h"
31#include "llvm/ADT/Statistic.h"
32#include "llvm/ADT/STLExtras.h"
Chris Lattner6d048a02004-11-22 17:18:36 +000033#include "llvm/IntrinsicInst.h"
Chris Lattner946b2552004-04-18 05:20:17 +000034#include <cstdio>
Chris Lattnerbc021772004-04-19 03:01:23 +000035#include <set>
Reid Spencerce078332004-10-18 14:38:48 +000036#include <algorithm>
Chris Lattnerc597b8a2006-01-22 23:32:06 +000037#include <iostream>
Chris Lattner946b2552004-04-18 05:20:17 +000038using namespace llvm;
39
40namespace {
41 Statistic<> NumUnrolled("loop-unroll", "Number of loops completely unrolled");
42
43 cl::opt<unsigned>
Chris Lattnerd1525022004-04-18 18:06:14 +000044 UnrollThreshold("unroll-threshold", cl::init(100), cl::Hidden,
Chris Lattner946b2552004-04-18 05:20:17 +000045 cl::desc("The cut-off point for loop unrolling"));
46
47 class LoopUnroll : public FunctionPass {
48 LoopInfo *LI; // The current loop information
49 public:
50 virtual bool runOnFunction(Function &F);
51 bool visitLoop(Loop *L);
Owen Anderson62c84fe2006-08-28 02:09:46 +000052 BasicBlock* FoldBlockIntoPredecessor(BasicBlock* BB);
Chris Lattner946b2552004-04-18 05:20:17 +000053
54 /// This transformation requires natural loop information & requires that
55 /// loop preheaders be inserted into the CFG...
56 ///
57 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner946b2552004-04-18 05:20:17 +000058 AU.addRequiredID(LoopSimplifyID);
Owen Andersone001d812006-08-24 21:28:19 +000059 AU.addRequiredID(LCSSAID);
Chris Lattner946b2552004-04-18 05:20:17 +000060 AU.addRequired<LoopInfo>();
Owen Andersone001d812006-08-24 21:28:19 +000061 AU.addPreservedID(LCSSAID);
Chris Lattnerf2cc8412004-04-18 05:38:37 +000062 AU.addPreserved<LoopInfo>();
Chris Lattner946b2552004-04-18 05:20:17 +000063 }
64 };
Chris Lattnerc2d3d312006-08-27 22:42:52 +000065 RegisterPass<LoopUnroll> X("loop-unroll", "Unroll loops");
Chris Lattner946b2552004-04-18 05:20:17 +000066}
67
68FunctionPass *llvm::createLoopUnrollPass() { return new LoopUnroll(); }
69
70bool LoopUnroll::runOnFunction(Function &F) {
71 bool Changed = false;
72 LI = &getAnalysis<LoopInfo>();
73
Chris Lattnerf2cc8412004-04-18 05:38:37 +000074 // Transform all the top-level loops. Copy the loop list so that the child
75 // can update the loop tree if it needs to delete the loop.
76 std::vector<Loop*> SubLoops(LI->begin(), LI->end());
77 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
78 Changed |= visitLoop(SubLoops[i]);
Chris Lattner946b2552004-04-18 05:20:17 +000079
80 return Changed;
81}
82
83/// ApproximateLoopSize - Approximate the size of the loop after it has been
84/// unrolled.
85static unsigned ApproximateLoopSize(const Loop *L) {
86 unsigned Size = 0;
87 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
88 BasicBlock *BB = L->getBlocks()[i];
89 Instruction *Term = BB->getTerminator();
90 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
91 if (isa<PHINode>(I) && BB == L->getHeader()) {
92 // Ignore PHI nodes in the header.
93 } else if (I->hasOneUse() && I->use_back() == Term) {
94 // Ignore instructions only used by the loop terminator.
Chris Lattner6d048a02004-11-22 17:18:36 +000095 } else if (DbgInfoIntrinsic *DbgI = dyn_cast<DbgInfoIntrinsic>(I)) {
Jeff Cohen82639852005-04-23 21:38:35 +000096 // Ignore debug instructions
Chris Lattner946b2552004-04-18 05:20:17 +000097 } else {
98 ++Size;
99 }
100
101 // TODO: Ignore expressions derived from PHI and constants if inval of phi
102 // is a constant, or if operation is associative. This will get induction
103 // variables.
104 }
105 }
106
107 return Size;
108}
109
Misha Brukmanb1c93172005-04-21 23:48:37 +0000110// RemapInstruction - Convert the instruction operands from referencing the
Chris Lattner946b2552004-04-18 05:20:17 +0000111// current values into those specified by ValueMap.
112//
Misha Brukmanb1c93172005-04-21 23:48:37 +0000113static inline void RemapInstruction(Instruction *I,
Chris Lattner946b2552004-04-18 05:20:17 +0000114 std::map<const Value *, Value*> &ValueMap) {
115 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
116 Value *Op = I->getOperand(op);
117 std::map<const Value *, Value*>::iterator It = ValueMap.find(Op);
118 if (It != ValueMap.end()) Op = It->second;
119 I->setOperand(op, Op);
120 }
121}
122
Owen Anderson62c84fe2006-08-28 02:09:46 +0000123// FoldBlockIntoPredecessor - Folds a basic block into its predecessor if it
124// only has one predecessor, and that predecessor only has one successor.
125// Returns the new combined block.
126BasicBlock* LoopUnroll::FoldBlockIntoPredecessor(BasicBlock* BB) {
127 // Merge basic blocks into their predecessor if there is only one distinct
128 // pred, and if there is only one distinct successor of the predecessor, and
129 // if there are no PHI nodes.
130 //
131 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
132 BasicBlock *OnlyPred = *PI++;
133 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
134 if (*PI != OnlyPred) {
135 OnlyPred = 0; // There are multiple different predecessors...
136 break;
137 }
138
139 BasicBlock *OnlySucc = 0;
140 if (OnlyPred && OnlyPred != BB && // Don't break self loops
141 OnlyPred->getTerminator()->getOpcode() != Instruction::Invoke) {
142 // Check to see if there is only one distinct successor...
143 succ_iterator SI(succ_begin(OnlyPred)), SE(succ_end(OnlyPred));
144 OnlySucc = BB;
145 for (; SI != SE; ++SI)
146 if (*SI != OnlySucc) {
147 OnlySucc = 0; // There are multiple distinct successors!
148 break;
149 }
150 }
151
152 if (OnlySucc) {
153 DEBUG(std::cerr << "Merging: " << *BB << "into: " << *OnlyPred);
154 TerminatorInst *Term = OnlyPred->getTerminator();
155
156 // Resolve any PHI nodes at the start of the block. They are all
157 // guaranteed to have exactly one entry if they exist, unless there are
158 // multiple duplicate (but guaranteed to be equal) entries for the
159 // incoming edges. This occurs when there are multiple edges from
160 // OnlyPred to OnlySucc.
161 //
162 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
163 PN->replaceAllUsesWith(PN->getIncomingValue(0));
164 BB->getInstList().pop_front(); // Delete the phi node...
165 }
166
167 // Delete the unconditional branch from the predecessor...
168 OnlyPred->getInstList().pop_back();
169
170 // Move all definitions in the successor to the predecessor...
171 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
172
173 // Make all PHI nodes that referred to BB now refer to Pred as their
174 // source...
175 BB->replaceAllUsesWith(OnlyPred);
176
177 std::string OldName = BB->getName();
178
179 // Erase basic block from the function...
180 LI->removeBlock(BB);
181 BB->eraseFromParent();
182
183 // Inherit predecessors name if it exists...
184 if (!OldName.empty() && !OnlyPred->hasName())
185 OnlyPred->setName(OldName);
186
187 return OnlyPred;
188 }
189
190 return 0;
191}
192
Chris Lattner946b2552004-04-18 05:20:17 +0000193bool LoopUnroll::visitLoop(Loop *L) {
194 bool Changed = false;
195
196 // Recurse through all subloops before we process this loop. Copy the loop
197 // list so that the child can update the loop tree if it needs to delete the
198 // loop.
199 std::vector<Loop*> SubLoops(L->begin(), L->end());
200 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
201 Changed |= visitLoop(SubLoops[i]);
202
Owen Andersone001d812006-08-24 21:28:19 +0000203 BasicBlock* Header = L->getHeader();
204 BasicBlock* LatchBlock = L->getLoopLatch();
Chris Lattner946b2552004-04-18 05:20:17 +0000205
Owen Andersone001d812006-08-24 21:28:19 +0000206 BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
Chris Lattner946b2552004-04-18 05:20:17 +0000207 if (BI == 0) return Changed; // Must end in a conditional branch
208
209 ConstantInt *TripCountC = dyn_cast_or_null<ConstantInt>(L->getTripCount());
210 if (!TripCountC) return Changed; // Must have constant trip count!
211
Chris Lattner47f395c2005-01-08 19:37:20 +0000212 uint64_t TripCountFull = TripCountC->getRawValue();
213 if (TripCountFull != TripCountC->getRawValue() || TripCountFull == 0)
Chris Lattner946b2552004-04-18 05:20:17 +0000214 return Changed; // More than 2^32 iterations???
215
216 unsigned LoopSize = ApproximateLoopSize(L);
Owen Andersone001d812006-08-24 21:28:19 +0000217 DEBUG(std::cerr << "Loop Unroll: F[" << Header->getParent()->getName()
218 << "] Loop %" << Header->getName() << " Loop Size = "
219 << LoopSize << " Trip Count = " << TripCountFull << " - ");
Chris Lattner47f395c2005-01-08 19:37:20 +0000220 uint64_t Size = (uint64_t)LoopSize*TripCountFull;
Chris Lattnerc12c9452004-05-13 20:43:31 +0000221 if (Size > UnrollThreshold) {
222 DEBUG(std::cerr << "TOO LARGE: " << Size << ">" << UnrollThreshold << "\n");
Chris Lattner946b2552004-04-18 05:20:17 +0000223 return Changed;
224 }
225 DEBUG(std::cerr << "UNROLLING!\n");
Misha Brukmanb1c93172005-04-21 23:48:37 +0000226
Owen Andersone001d812006-08-24 21:28:19 +0000227 std::vector<BasicBlock*> LoopBlocks = L->getBlocks();
228
Chris Lattner47f395c2005-01-08 19:37:20 +0000229 unsigned TripCount = (unsigned)TripCountFull;
230
Owen Andersone001d812006-08-24 21:28:19 +0000231 BasicBlock *LoopExit = BI->getSuccessor(L->contains(BI->getSuccessor(0)));
Chris Lattner946b2552004-04-18 05:20:17 +0000232
233 // For the first iteration of the loop, we should use the precloned values for
234 // PHI nodes. Insert associations now.
235 std::map<const Value*, Value*> LastValueMap;
236 std::vector<PHINode*> OrigPHINode;
Owen Andersone001d812006-08-24 21:28:19 +0000237 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
Reid Spencer66149462004-09-15 17:06:42 +0000238 PHINode *PN = cast<PHINode>(I);
Chris Lattner946b2552004-04-18 05:20:17 +0000239 OrigPHINode.push_back(PN);
Owen Andersone001d812006-08-24 21:28:19 +0000240 if (Instruction *I =
241 dyn_cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock)))
242 if (L->contains(I->getParent()))
Chris Lattner946b2552004-04-18 05:20:17 +0000243 LastValueMap[I] = I;
244 }
245
246 // Remove the exit branch from the loop
Owen Andersone001d812006-08-24 21:28:19 +0000247 LatchBlock->getInstList().erase(BI);
248
249 std::vector<BasicBlock*> Headers;
250 std::vector<BasicBlock*> Latches;
251 Headers.push_back(Header);
252 Latches.push_back(LatchBlock);
Chris Lattner946b2552004-04-18 05:20:17 +0000253
254 assert(TripCount != 0 && "Trip count of 0 is impossible!");
255 for (unsigned It = 1; It != TripCount; ++It) {
256 char SuffixBuffer[100];
257 sprintf(SuffixBuffer, ".%d", It);
Owen Andersone001d812006-08-24 21:28:19 +0000258
259 std::vector<BasicBlock*> NewBlocks;
260
261 for (std::vector<BasicBlock*>::iterator BB = LoopBlocks.begin(),
262 E = LoopBlocks.end(); BB != E; ++BB) {
263 std::map<const Value*, Value*> ValueMap;
264 BasicBlock *New = CloneBasicBlock(*BB, ValueMap, SuffixBuffer);
265 Header->getParent()->getBasicBlockList().push_back(New);
Chris Lattner946b2552004-04-18 05:20:17 +0000266
Owen Andersone001d812006-08-24 21:28:19 +0000267 // Loop over all of the PHI nodes in the block, changing them to use the
268 // incoming values from the previous block.
269 if (*BB == Header)
270 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
271 PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]);
272 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
273 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
274 if (It > 1 && L->contains(InValI->getParent()))
275 InVal = LastValueMap[InValI];
276 ValueMap[OrigPHINode[i]] = InVal;
277 New->getInstList().erase(NewPHI);
278 }
279
280 // Update our running map of newest clones
281 LastValueMap[*BB] = New;
282 for (std::map<const Value*, Value*>::iterator VI = ValueMap.begin(),
283 VE = ValueMap.end(); VI != VE; ++VI)
284 LastValueMap[VI->first] = VI->second;
285
286 L->addBasicBlockToLoop(New, *LI);
287
288 // Add phi entries for newly created values to all exit blocks except
289 // the successor of the latch block. The successor of the exit block will
290 // be updated specially after unrolling all the way.
291 if (*BB != LatchBlock)
292 for (Value::use_iterator UI = (*BB)->use_begin(), UE = (*BB)->use_end();
293 UI != UE; ++UI) {
294 Instruction* UseInst = cast<Instruction>(*UI);
295 if (isa<PHINode>(UseInst) && !L->contains(UseInst->getParent())) {
296 PHINode* phi = cast<PHINode>(UseInst);
297 Value* Incoming = phi->getIncomingValueForBlock(*BB);
298 if (isa<Instruction>(Incoming))
299 Incoming = LastValueMap[Incoming];
300
301 phi->addIncoming(Incoming, New);
302 }
303 }
304
305 // Keep track of new headers and latches as we create them, so that
306 // we can insert the proper branches later.
307 if (*BB == Header)
308 Headers.push_back(New);
309 if (*BB == LatchBlock)
310 Latches.push_back(New);
311
312 NewBlocks.push_back(New);
Chris Lattner946b2552004-04-18 05:20:17 +0000313 }
Owen Andersone001d812006-08-24 21:28:19 +0000314
315 // Remap all instructions in the most recent iteration
316 for (unsigned i = 0; i < NewBlocks.size(); ++i)
317 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
318 E = NewBlocks[i]->end(); I != E; ++I)
Chris Lattner230bcb62004-04-18 17:32:39 +0000319 RemapInstruction(I, LastValueMap);
Chris Lattner230bcb62004-04-18 17:32:39 +0000320 }
Chris Lattner946b2552004-04-18 05:20:17 +0000321
Owen Andersone001d812006-08-24 21:28:19 +0000322
Owen Andersone001d812006-08-24 21:28:19 +0000323
324 // Update PHI nodes that reference the final latch block
325 if (TripCount > 1) {
326 std::set<PHINode*> Users;
327 for (Value::use_iterator UI = LatchBlock->use_begin(),
328 UE = LatchBlock->use_end(); UI != UE; ++UI)
329 if (PHINode* phi = dyn_cast<PHINode>(*UI))
330 Users.insert(phi);
331
332 for (std::set<PHINode*>::iterator SI = Users.begin(), SE = Users.end();
333 SI != SE; ++SI) {
334 Value* InVal = (*SI)->getIncomingValueForBlock(LatchBlock);
335 if (isa<Instruction>(InVal))
336 InVal = LastValueMap[InVal];
337 (*SI)->removeIncomingValue(LatchBlock, false);
Owen Anderson403b95a2006-08-25 22:13:55 +0000338 if (InVal)
339 (*SI)->addIncoming(InVal, cast<BasicBlock>(LastValueMap[LatchBlock]));
Owen Andersone001d812006-08-24 21:28:19 +0000340 }
341 }
Chris Lattner946b2552004-04-18 05:20:17 +0000342
343 // Now loop over the PHI nodes in the original block, setting them to their
344 // incoming values.
345 BasicBlock *Preheader = L->getLoopPreheader();
346 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
347 PHINode *PN = OrigPHINode[i];
348 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
Owen Andersone001d812006-08-24 21:28:19 +0000349 Header->getInstList().erase(PN);
Owen Anderson62c84fe2006-08-28 02:09:46 +0000350 }
351
352 // Insert the branches that link the different iterations together
353 for (unsigned i = 0; i < Latches.size()-1; ++i) {
354 new BranchInst(Headers[i+1], Latches[i]);
355 if(BasicBlock* Fold = FoldBlockIntoPredecessor(Headers[i+1])) {
356 std::replace(Latches.begin(), Latches.end(), Headers[i+1], Fold);
357 std::replace(Headers.begin(), Headers.end(), Headers[i+1], Fold);
358 }
359 }
360
361 // Finally, add an unconditional branch to the block to continue into the exit
362 // block.
363 new BranchInst(LoopExit, Latches[Latches.size()-1]);
364 FoldBlockIntoPredecessor(LoopExit);
365
Chris Lattner946b2552004-04-18 05:20:17 +0000366 // At this point, the code is well formed. We now do a quick sweep over the
367 // inserted code, doing constant propagation and dead code elimination as we
368 // go.
Owen Andersone001d812006-08-24 21:28:19 +0000369 const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();
370 for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
Owen Anderson62c84fe2006-08-28 02:09:46 +0000371 BBE = NewLoopBlocks.end(); BB != BBE; ++BB)
Owen Andersone001d812006-08-24 21:28:19 +0000372 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {
373 Instruction *Inst = I++;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000374
Owen Andersone001d812006-08-24 21:28:19 +0000375 if (isInstructionTriviallyDead(Inst))
376 (*BB)->getInstList().erase(Inst);
377 else if (Constant *C = ConstantFoldInstruction(Inst)) {
378 Inst->replaceAllUsesWith(C);
379 (*BB)->getInstList().erase(Inst);
380 }
Chris Lattner946b2552004-04-18 05:20:17 +0000381 }
Chris Lattner946b2552004-04-18 05:20:17 +0000382
Chris Lattnerf2cc8412004-04-18 05:38:37 +0000383 // Update the loop information for this loop.
384 Loop *Parent = L->getParentLoop();
385
386 // Move all of the basic blocks in the loop into the parent loop.
Owen Andersone001d812006-08-24 21:28:19 +0000387 for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
388 E = NewLoopBlocks.end(); BB != E; ++BB)
389 LI->changeLoopFor(*BB, Parent);
Chris Lattnerf2cc8412004-04-18 05:38:37 +0000390
391 // Remove the loop from the parent.
392 if (Parent)
393 delete Parent->removeChildLoop(std::find(Parent->begin(), Parent->end(),L));
394 else
395 delete LI->removeLoop(std::find(LI->begin(), LI->end(), L));
396
Chris Lattner946b2552004-04-18 05:20:17 +0000397 ++NumUnrolled;
398 return true;
399}