blob: 71a5955b76b0d8d82b09d9a751872645570f6a55 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
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 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.
17//
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/ConstantFolding.h"
26#include "llvm/Analysis/LoopInfo.h"
27#include "llvm/Analysis/LoopPass.h"
28#include "llvm/Transforms/Utils/Cloning.h"
29#include "llvm/Transforms/Utils/Local.h"
30#include "llvm/Support/CFG.h"
31#include "llvm/Support/Compiler.h"
32#include "llvm/Support/CommandLine.h"
33#include "llvm/Support/Debug.h"
34#include "llvm/Support/MathExtras.h"
35#include "llvm/ADT/Statistic.h"
36#include "llvm/ADT/STLExtras.h"
37#include "llvm/ADT/SmallPtrSet.h"
38#include "llvm/IntrinsicInst.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000039#include <algorithm>
Anton Korobeynikov357a27d2008-02-20 11:08:44 +000040#include <climits>
41#include <cstdio>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000042using namespace llvm;
43
44STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
Chris Lattner03dc7d72007-08-02 16:53:43 +000045STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000046
47namespace {
48 cl::opt<unsigned>
49 UnrollThreshold
50 ("unroll-threshold", cl::init(100), cl::Hidden,
51 cl::desc("The cut-off point for automatic loop unrolling"));
52
53 cl::opt<unsigned>
54 UnrollCount
55 ("unroll-count", cl::init(0), cl::Hidden,
56 cl::desc("Use this unroll count for all loops, for testing purposes"));
57
58 class VISIBILITY_HIDDEN LoopUnroll : public LoopPass {
59 LoopInfo *LI; // The current loop information
60 public:
61 static char ID; // Pass ID, replacement for typeid
62 LoopUnroll() : LoopPass((intptr_t)&ID) {}
63
64 /// A magic value for use with the Threshold parameter to indicate
65 /// that the loop unroll should be performed regardless of how much
66 /// code expansion would result.
67 static const unsigned NoThreshold = UINT_MAX;
68
69 bool runOnLoop(Loop *L, LPPassManager &LPM);
70 bool unrollLoop(Loop *L, unsigned Count, unsigned Threshold);
71 BasicBlock *FoldBlockIntoPredecessor(BasicBlock *BB);
72
73 /// This transformation requires natural loop information & requires that
74 /// loop preheaders be inserted into the CFG...
75 ///
76 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
77 AU.addRequiredID(LoopSimplifyID);
78 AU.addRequiredID(LCSSAID);
79 AU.addRequired<LoopInfo>();
80 AU.addPreservedID(LCSSAID);
81 AU.addPreserved<LoopInfo>();
82 }
83 };
84 char LoopUnroll::ID = 0;
85 RegisterPass<LoopUnroll> X("loop-unroll", "Unroll loops");
86}
87
88LoopPass *llvm::createLoopUnrollPass() { return new LoopUnroll(); }
89
90/// ApproximateLoopSize - Approximate the size of the loop.
91static unsigned ApproximateLoopSize(const Loop *L) {
92 unsigned Size = 0;
93 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
94 BasicBlock *BB = L->getBlocks()[i];
95 Instruction *Term = BB->getTerminator();
96 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
97 if (isa<PHINode>(I) && BB == L->getHeader()) {
98 // Ignore PHI nodes in the header.
99 } else if (I->hasOneUse() && I->use_back() == Term) {
100 // Ignore instructions only used by the loop terminator.
101 } else if (isa<DbgInfoIntrinsic>(I)) {
102 // Ignore debug instructions
Devang Pateleb485232008-03-17 23:41:20 +0000103 } else if (isa<CallInst>(I)) {
104 if (isa<IntrinsicInst>(I))
105 Size = Size + 3;
106 else
107 Size = Size + 10;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000108 } else {
109 ++Size;
110 }
111
112 // TODO: Ignore expressions derived from PHI and constants if inval of phi
113 // is a constant, or if operation is associative. This will get induction
114 // variables.
115 }
116 }
117
118 return Size;
119}
120
121// RemapInstruction - Convert the instruction operands from referencing the
122// current values into those specified by ValueMap.
123//
124static inline void RemapInstruction(Instruction *I,
125 DenseMap<const Value *, Value*> &ValueMap) {
126 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
127 Value *Op = I->getOperand(op);
128 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
129 if (It != ValueMap.end()) Op = It->second;
130 I->setOperand(op, Op);
131 }
132}
133
134// FoldBlockIntoPredecessor - Folds a basic block into its predecessor if it
135// only has one predecessor, and that predecessor only has one successor.
136// Returns the new combined block.
137BasicBlock *LoopUnroll::FoldBlockIntoPredecessor(BasicBlock *BB) {
138 // Merge basic blocks into their predecessor if there is only one distinct
139 // pred, and if there is only one distinct successor of the predecessor, and
140 // if there are no PHI nodes.
141 //
142 BasicBlock *OnlyPred = BB->getSinglePredecessor();
143 if (!OnlyPred) return 0;
144
145 if (OnlyPred->getTerminator()->getNumSuccessors() != 1)
146 return 0;
147
148 DOUT << "Merging: " << *BB << "into: " << *OnlyPred;
149
150 // Resolve any PHI nodes at the start of the block. They are all
151 // guaranteed to have exactly one entry if they exist, unless there are
152 // multiple duplicate (but guaranteed to be equal) entries for the
153 // incoming edges. This occurs when there are multiple edges from
154 // OnlyPred to OnlySucc.
155 //
156 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
157 PN->replaceAllUsesWith(PN->getIncomingValue(0));
158 BB->getInstList().pop_front(); // Delete the phi node...
159 }
160
161 // Delete the unconditional branch from the predecessor...
162 OnlyPred->getInstList().pop_back();
163
164 // Move all definitions in the successor to the predecessor...
165 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
166
167 // Make all PHI nodes that referred to BB now refer to Pred as their
168 // source...
169 BB->replaceAllUsesWith(OnlyPred);
170
171 std::string OldName = BB->getName();
172
173 // Erase basic block from the function...
174 LI->removeBlock(BB);
175 BB->eraseFromParent();
176
177 // Inherit predecessor's name if it exists...
178 if (!OldName.empty() && !OnlyPred->hasName())
179 OnlyPred->setName(OldName);
180
181 return OnlyPred;
182}
183
184bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
185 LI = &getAnalysis<LoopInfo>();
186
187 // Unroll the loop.
188 if (!unrollLoop(L, UnrollCount, UnrollThreshold))
189 return false;
190
191 // Update the loop information for this loop.
192 // If we completely unrolled the loop, remove it from the parent.
193 if (L->getNumBackEdges() == 0)
194 LPM.deleteLoopFromQueue(L);
195
196 return true;
197}
198
199/// Unroll the given loop by UnrollCount, or by a heuristically-determined
200/// value if Count is zero. If Threshold is not NoThreshold, it is a value
201/// to limit code size expansion. If the loop size would expand beyond the
202/// threshold value, unrolling is suppressed. The return value is true if
203/// any transformations are performed.
204///
205bool LoopUnroll::unrollLoop(Loop *L, unsigned Count, unsigned Threshold) {
206 assert(L->isLCSSAForm());
207
208 BasicBlock *Header = L->getHeader();
209 BasicBlock *LatchBlock = L->getLoopLatch();
210 BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
211
212 DOUT << "Loop Unroll: F[" << Header->getParent()->getName()
213 << "] Loop %" << Header->getName() << "\n";
214
215 if (!BI || BI->isUnconditional()) {
Wojciech Matyjewicz9df2f202008-01-04 20:02:18 +0000216 // The loop-rotate pass can be helpful to avoid this in many cases.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000217 DOUT << " Can't unroll; loop not terminated by a conditional branch.\n";
218 return false;
219 }
220
221 // Determine the trip count and/or trip multiple. A TripCount value of zero
222 // is used to mean an unknown trip count. The TripMultiple value is the
223 // greatest known integer multiple of the trip count.
224 unsigned TripCount = 0;
225 unsigned TripMultiple = 1;
226 if (Value *TripCountValue = L->getTripCount()) {
227 if (ConstantInt *TripCountC = dyn_cast<ConstantInt>(TripCountValue)) {
228 // Guard against huge trip counts. This also guards against assertions in
229 // APInt from the use of getZExtValue, below.
230 if (TripCountC->getValue().getActiveBits() <= 32) {
231 TripCount = (unsigned)TripCountC->getZExtValue();
232 }
233 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TripCountValue)) {
234 switch (BO->getOpcode()) {
235 case BinaryOperator::Mul:
236 if (ConstantInt *MultipleC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
237 if (MultipleC->getValue().getActiveBits() <= 32) {
238 TripMultiple = (unsigned)MultipleC->getZExtValue();
239 }
240 }
241 break;
242 default: break;
243 }
244 }
245 }
246 if (TripCount != 0)
247 DOUT << " Trip Count = " << TripCount << "\n";
248 if (TripMultiple != 1)
249 DOUT << " Trip Multiple = " << TripMultiple << "\n";
250
251 // Automatically select an unroll count.
252 if (Count == 0) {
253 // Conservative heuristic: if we know the trip count, see if we can
254 // completely unroll (subject to the threshold, checked below); otherwise
255 // don't unroll.
256 if (TripCount != 0) {
257 Count = TripCount;
258 } else {
259 return false;
260 }
261 }
262
263 // Effectively "DCE" unrolled iterations that are beyond the tripcount
264 // and will never be executed.
265 if (TripCount != 0 && Count > TripCount)
266 Count = TripCount;
267
268 assert(Count > 0);
269 assert(TripMultiple > 0);
270 assert(TripCount == 0 || TripCount % TripMultiple == 0);
271
272 // Enforce the threshold.
273 if (Threshold != NoThreshold) {
274 unsigned LoopSize = ApproximateLoopSize(L);
275 DOUT << " Loop Size = " << LoopSize << "\n";
276 uint64_t Size = (uint64_t)LoopSize*Count;
277 if (TripCount != 1 && Size > Threshold) {
278 DOUT << " TOO LARGE TO UNROLL: "
279 << Size << ">" << Threshold << "\n";
280 return false;
281 }
282 }
283
284 // Are we eliminating the loop control altogether?
285 bool CompletelyUnroll = Count == TripCount;
286
287 // If we know the trip count, we know the multiple...
288 unsigned BreakoutTrip = 0;
289 if (TripCount != 0) {
290 BreakoutTrip = TripCount % Count;
291 TripMultiple = 0;
292 } else {
293 // Figure out what multiple to use.
294 BreakoutTrip = TripMultiple =
295 (unsigned)GreatestCommonDivisor64(Count, TripMultiple);
296 }
297
298 if (CompletelyUnroll) {
299 DOUT << "COMPLETELY UNROLLING loop %" << Header->getName()
300 << " with trip count " << TripCount << "!\n";
301 } else {
302 DOUT << "UNROLLING loop %" << Header->getName()
303 << " by " << Count;
304 if (TripMultiple == 0 || BreakoutTrip != TripMultiple) {
305 DOUT << " with a breakout at trip " << BreakoutTrip;
306 } else if (TripMultiple != 1) {
307 DOUT << " with " << TripMultiple << " trips per branch";
308 }
309 DOUT << "!\n";
310 }
311
312 std::vector<BasicBlock*> LoopBlocks = L->getBlocks();
313
314 bool ContinueOnTrue = L->contains(BI->getSuccessor(0));
315 BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);
316
317 // For the first iteration of the loop, we should use the precloned values for
318 // PHI nodes. Insert associations now.
319 typedef DenseMap<const Value*, Value*> ValueMapTy;
320 ValueMapTy LastValueMap;
321 std::vector<PHINode*> OrigPHINode;
322 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
323 PHINode *PN = cast<PHINode>(I);
324 OrigPHINode.push_back(PN);
325 if (Instruction *I =
326 dyn_cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock)))
327 if (L->contains(I->getParent()))
328 LastValueMap[I] = I;
329 }
330
331 std::vector<BasicBlock*> Headers;
332 std::vector<BasicBlock*> Latches;
333 Headers.push_back(Header);
334 Latches.push_back(LatchBlock);
335
336 for (unsigned It = 1; It != Count; ++It) {
337 char SuffixBuffer[100];
338 sprintf(SuffixBuffer, ".%d", It);
339
340 std::vector<BasicBlock*> NewBlocks;
341
342 for (std::vector<BasicBlock*>::iterator BB = LoopBlocks.begin(),
343 E = LoopBlocks.end(); BB != E; ++BB) {
344 ValueMapTy ValueMap;
345 BasicBlock *New = CloneBasicBlock(*BB, ValueMap, SuffixBuffer);
346 Header->getParent()->getBasicBlockList().push_back(New);
347
348 // Loop over all of the PHI nodes in the block, changing them to use the
349 // incoming values from the previous block.
350 if (*BB == Header)
351 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
352 PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]);
353 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
354 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
355 if (It > 1 && L->contains(InValI->getParent()))
356 InVal = LastValueMap[InValI];
357 ValueMap[OrigPHINode[i]] = InVal;
358 New->getInstList().erase(NewPHI);
359 }
360
361 // Update our running map of newest clones
362 LastValueMap[*BB] = New;
363 for (ValueMapTy::iterator VI = ValueMap.begin(), VE = ValueMap.end();
364 VI != VE; ++VI)
365 LastValueMap[VI->first] = VI->second;
366
Owen Andersonca0b9d42007-11-27 03:43:35 +0000367 L->addBasicBlockToLoop(New, LI->getBase());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000368
369 // Add phi entries for newly created values to all exit blocks except
370 // the successor of the latch block. The successor of the exit block will
371 // be updated specially after unrolling all the way.
372 if (*BB != LatchBlock)
373 for (Value::use_iterator UI = (*BB)->use_begin(), UE = (*BB)->use_end();
Nick Lewyckyf8104c52008-01-27 18:35:00 +0000374 UI != UE;) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000375 Instruction *UseInst = cast<Instruction>(*UI);
Nick Lewyckyf8104c52008-01-27 18:35:00 +0000376 ++UI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000377 if (isa<PHINode>(UseInst) && !L->contains(UseInst->getParent())) {
378 PHINode *phi = cast<PHINode>(UseInst);
379 Value *Incoming = phi->getIncomingValueForBlock(*BB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000380 phi->addIncoming(Incoming, New);
381 }
382 }
383
384 // Keep track of new headers and latches as we create them, so that
385 // we can insert the proper branches later.
386 if (*BB == Header)
387 Headers.push_back(New);
388 if (*BB == LatchBlock) {
389 Latches.push_back(New);
390
391 // Also, clear out the new latch's back edge so that it doesn't look
392 // like a new loop, so that it's amenable to being merged with adjacent
393 // blocks later on.
394 TerminatorInst *Term = New->getTerminator();
395 assert(L->contains(Term->getSuccessor(!ContinueOnTrue)));
396 assert(Term->getSuccessor(ContinueOnTrue) == LoopExit);
397 Term->setSuccessor(!ContinueOnTrue, NULL);
398 }
399
400 NewBlocks.push_back(New);
401 }
402
403 // Remap all instructions in the most recent iteration
Nick Lewycky95a0d762008-03-09 05:24:34 +0000404 for (unsigned i = 0; i < NewBlocks.size(); ++i) {
405 BasicBlock *NB = NewBlocks[i];
406 if (BasicBlock *UnwindDest = NB->getUnwindDest())
407 NB->setUnwindDest(cast<BasicBlock>(LastValueMap[UnwindDest]));
408
409 for (BasicBlock::iterator I = NB->begin(), E = NB->end(); I != E; ++I)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000410 RemapInstruction(I, LastValueMap);
Nick Lewycky95a0d762008-03-09 05:24:34 +0000411 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000412 }
413
414 // The latch block exits the loop. If there are any PHI nodes in the
415 // successor blocks, update them to use the appropriate values computed as the
416 // last iteration of the loop.
417 if (Count != 1) {
418 SmallPtrSet<PHINode*, 8> Users;
419 for (Value::use_iterator UI = LatchBlock->use_begin(),
420 UE = LatchBlock->use_end(); UI != UE; ++UI)
421 if (PHINode *phi = dyn_cast<PHINode>(*UI))
422 Users.insert(phi);
423
424 BasicBlock *LastIterationBB = cast<BasicBlock>(LastValueMap[LatchBlock]);
425 for (SmallPtrSet<PHINode*,8>::iterator SI = Users.begin(), SE = Users.end();
426 SI != SE; ++SI) {
427 PHINode *PN = *SI;
428 Value *InVal = PN->removeIncomingValue(LatchBlock, false);
429 // If this value was defined in the loop, take the value defined by the
430 // last iteration of the loop.
431 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
432 if (L->contains(InValI->getParent()))
433 InVal = LastValueMap[InVal];
434 }
435 PN->addIncoming(InVal, LastIterationBB);
436 }
437 }
438
439 // Now, if we're doing complete unrolling, loop over the PHI nodes in the
440 // original block, setting them to their incoming values.
441 if (CompletelyUnroll) {
442 BasicBlock *Preheader = L->getLoopPreheader();
443 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
444 PHINode *PN = OrigPHINode[i];
445 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
446 Header->getInstList().erase(PN);
447 }
448 }
449
450 // Now that all the basic blocks for the unrolled iterations are in place,
451 // set up the branches to connect them.
452 for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
453 // The original branch was replicated in each unrolled iteration.
454 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
455
456 // The branch destination.
457 unsigned j = (i + 1) % e;
458 BasicBlock *Dest = Headers[j];
459 bool NeedConditional = true;
460
461 // For a complete unroll, make the last iteration end with a branch
462 // to the exit block.
463 if (CompletelyUnroll && j == 0) {
464 Dest = LoopExit;
465 NeedConditional = false;
466 }
467
468 // If we know the trip count or a multiple of it, we can safely use an
469 // unconditional branch for some iterations.
470 if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) {
471 NeedConditional = false;
472 }
473
474 if (NeedConditional) {
475 // Update the conditional branch's successor for the following
476 // iteration.
477 Term->setSuccessor(!ContinueOnTrue, Dest);
478 } else {
479 Term->setUnconditionalDest(Dest);
480 // Merge adjacent basic blocks, if possible.
481 if (BasicBlock *Fold = FoldBlockIntoPredecessor(Dest)) {
482 std::replace(Latches.begin(), Latches.end(), Dest, Fold);
483 std::replace(Headers.begin(), Headers.end(), Dest, Fold);
484 }
485 }
486 }
487
488 // At this point, the code is well formed. We now do a quick sweep over the
489 // inserted code, doing constant propagation and dead code elimination as we
490 // go.
491 const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();
492 for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
493 BBE = NewLoopBlocks.end(); BB != BBE; ++BB)
494 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {
495 Instruction *Inst = I++;
496
497 if (isInstructionTriviallyDead(Inst))
498 (*BB)->getInstList().erase(Inst);
499 else if (Constant *C = ConstantFoldInstruction(Inst)) {
500 Inst->replaceAllUsesWith(C);
501 (*BB)->getInstList().erase(Inst);
502 }
503 }
504
505 NumCompletelyUnrolled += CompletelyUnroll;
506 ++NumUnrolled;
507 return true;
508}