blob: 2140b22f2ff590cfc13097396ee414c7c89f2e09 [file] [log] [blame]
Chris Lattner83bf2882004-04-18 05:20:17 +00001//===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
Chris Lattner83bf2882004-04-18 05:20:17 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
Chris Lattner83bf2882004-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 Anderson3b53c4e2006-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 Lattner83bf2882004-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"
Chris Lattner79066fa2007-01-30 23:46:24 +000025#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner83bf2882004-04-18 05:20:17 +000026#include "llvm/Analysis/LoopInfo.h"
Devang Patel3f1a1e02007-03-07 01:38:05 +000027#include "llvm/Analysis/LoopPass.h"
Chris Lattner83bf2882004-04-18 05:20:17 +000028#include "llvm/Transforms/Utils/Cloning.h"
29#include "llvm/Transforms/Utils/Local.h"
Owen Anderson59312b12006-08-28 02:09:46 +000030#include "llvm/Support/CFG.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000031#include "llvm/Support/Compiler.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000032#include "llvm/Support/CommandLine.h"
33#include "llvm/Support/Debug.h"
Dan Gohmanc7678442007-05-11 20:53:41 +000034#include "llvm/Support/MathExtras.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000035#include "llvm/ADT/Statistic.h"
36#include "llvm/ADT/STLExtras.h"
Chris Lattner5e665f52007-02-03 00:08:31 +000037#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner64613ea2004-11-22 17:18:36 +000038#include "llvm/IntrinsicInst.h"
Reid Spencer17e6e442004-10-18 14:38:48 +000039#include <algorithm>
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +000040#include <climits>
41#include <cstdio>
Chris Lattner83bf2882004-04-18 05:20:17 +000042using namespace llvm;
43
Dan Gohmanc7678442007-05-11 20:53:41 +000044STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
Chris Lattner684b22d2007-08-02 16:53:43 +000045STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
Chris Lattner83bf2882004-04-18 05:20:17 +000046
Chris Lattner0e5f4992006-12-19 21:40:18 +000047namespace {
Chris Lattner83bf2882004-04-18 05:20:17 +000048 cl::opt<unsigned>
Dan Gohmanc7678442007-05-11 20:53:41 +000049 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"));
Chris Lattner83bf2882004-04-18 05:20:17 +000057
Devang Patel3f1a1e02007-03-07 01:38:05 +000058 class VISIBILITY_HIDDEN LoopUnroll : public LoopPass {
Chris Lattner83bf2882004-04-18 05:20:17 +000059 LoopInfo *LI; // The current loop information
60 public:
Devang Patel19974732007-05-03 01:11:54 +000061 static char ID; // Pass ID, replacement for typeid
Dan Gohman1cc00962007-05-08 15:19:19 +000062 LoopUnroll() : LoopPass((intptr_t)&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000063
Dan Gohmanc7678442007-05-11 20:53:41 +000064 /// 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
Devang Patel3f1a1e02007-03-07 01:38:05 +000069 bool runOnLoop(Loop *L, LPPassManager &LPM);
Dan Gohmanc7678442007-05-11 20:53:41 +000070 bool unrollLoop(Loop *L, unsigned Count, unsigned Threshold);
Dan Gohman1cc00962007-05-08 15:19:19 +000071 BasicBlock *FoldBlockIntoPredecessor(BasicBlock *BB);
Chris Lattner83bf2882004-04-18 05:20:17 +000072
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 {
Chris Lattner83bf2882004-04-18 05:20:17 +000077 AU.addRequiredID(LoopSimplifyID);
Owen Anderson3b53c4e2006-08-24 21:28:19 +000078 AU.addRequiredID(LCSSAID);
Chris Lattner83bf2882004-04-18 05:20:17 +000079 AU.addRequired<LoopInfo>();
Owen Anderson3b53c4e2006-08-24 21:28:19 +000080 AU.addPreservedID(LCSSAID);
Chris Lattner9c2cc462004-04-18 05:38:37 +000081 AU.addPreserved<LoopInfo>();
Chris Lattner83bf2882004-04-18 05:20:17 +000082 }
83 };
Devang Patel19974732007-05-03 01:11:54 +000084 char LoopUnroll::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +000085 RegisterPass<LoopUnroll> X("loop-unroll", "Unroll loops");
Chris Lattner83bf2882004-04-18 05:20:17 +000086}
87
Devang Patel3f1a1e02007-03-07 01:38:05 +000088LoopPass *llvm::createLoopUnrollPass() { return new LoopUnroll(); }
Chris Lattner83bf2882004-04-18 05:20:17 +000089
Dan Gohmanf742c232007-05-08 15:14:19 +000090/// ApproximateLoopSize - Approximate the size of the loop.
Chris Lattner83bf2882004-04-18 05:20:17 +000091static 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.
Reid Spencer3ed469c2006-11-02 20:25:50 +0000101 } else if (isa<DbgInfoIntrinsic>(I)) {
Jeff Cohen9d809302005-04-23 21:38:35 +0000102 // Ignore debug instructions
Chris Lattner83bf2882004-04-18 05:20:17 +0000103 } else {
104 ++Size;
105 }
106
107 // TODO: Ignore expressions derived from PHI and constants if inval of phi
108 // is a constant, or if operation is associative. This will get induction
109 // variables.
110 }
111 }
112
113 return Size;
114}
115
Misha Brukmanfd939082005-04-21 23:48:37 +0000116// RemapInstruction - Convert the instruction operands from referencing the
Chris Lattner83bf2882004-04-18 05:20:17 +0000117// current values into those specified by ValueMap.
118//
Misha Brukmanfd939082005-04-21 23:48:37 +0000119static inline void RemapInstruction(Instruction *I,
Chris Lattner5e665f52007-02-03 00:08:31 +0000120 DenseMap<const Value *, Value*> &ValueMap) {
Chris Lattner83bf2882004-04-18 05:20:17 +0000121 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
122 Value *Op = I->getOperand(op);
Chris Lattner5e665f52007-02-03 00:08:31 +0000123 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
Chris Lattner83bf2882004-04-18 05:20:17 +0000124 if (It != ValueMap.end()) Op = It->second;
125 I->setOperand(op, Op);
126 }
127}
128
Owen Anderson59312b12006-08-28 02:09:46 +0000129// FoldBlockIntoPredecessor - Folds a basic block into its predecessor if it
130// only has one predecessor, and that predecessor only has one successor.
131// Returns the new combined block.
Dan Gohman1cc00962007-05-08 15:19:19 +0000132BasicBlock *LoopUnroll::FoldBlockIntoPredecessor(BasicBlock *BB) {
Owen Anderson59312b12006-08-28 02:09:46 +0000133 // Merge basic blocks into their predecessor if there is only one distinct
134 // pred, and if there is only one distinct successor of the predecessor, and
135 // if there are no PHI nodes.
136 //
Owen Andersond648e142006-08-29 06:10:56 +0000137 BasicBlock *OnlyPred = BB->getSinglePredecessor();
138 if (!OnlyPred) return 0;
Owen Anderson59312b12006-08-28 02:09:46 +0000139
Owen Andersond648e142006-08-29 06:10:56 +0000140 if (OnlyPred->getTerminator()->getNumSuccessors() != 1)
141 return 0;
142
Bill Wendlingb7427032006-11-26 09:46:52 +0000143 DOUT << "Merging: " << *BB << "into: " << *OnlyPred;
Owen Andersond648e142006-08-29 06:10:56 +0000144
145 // Resolve any PHI nodes at the start of the block. They are all
146 // guaranteed to have exactly one entry if they exist, unless there are
147 // multiple duplicate (but guaranteed to be equal) entries for the
148 // incoming edges. This occurs when there are multiple edges from
149 // OnlyPred to OnlySucc.
150 //
151 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
152 PN->replaceAllUsesWith(PN->getIncomingValue(0));
153 BB->getInstList().pop_front(); // Delete the phi node...
Owen Anderson59312b12006-08-28 02:09:46 +0000154 }
155
Owen Andersond648e142006-08-29 06:10:56 +0000156 // Delete the unconditional branch from the predecessor...
157 OnlyPred->getInstList().pop_back();
Owen Anderson59312b12006-08-28 02:09:46 +0000158
Owen Andersond648e142006-08-29 06:10:56 +0000159 // Move all definitions in the successor to the predecessor...
160 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
Owen Anderson59312b12006-08-28 02:09:46 +0000161
Owen Andersond648e142006-08-29 06:10:56 +0000162 // Make all PHI nodes that referred to BB now refer to Pred as their
163 // source...
164 BB->replaceAllUsesWith(OnlyPred);
Owen Anderson59312b12006-08-28 02:09:46 +0000165
Owen Andersond648e142006-08-29 06:10:56 +0000166 std::string OldName = BB->getName();
Owen Anderson59312b12006-08-28 02:09:46 +0000167
Owen Andersond648e142006-08-29 06:10:56 +0000168 // Erase basic block from the function...
169 LI->removeBlock(BB);
170 BB->eraseFromParent();
Owen Anderson59312b12006-08-28 02:09:46 +0000171
Dan Gohmand9efdb22007-05-14 14:31:17 +0000172 // Inherit predecessor's name if it exists...
Owen Andersond648e142006-08-29 06:10:56 +0000173 if (!OldName.empty() && !OnlyPred->hasName())
174 OnlyPred->setName(OldName);
Owen Anderson59312b12006-08-28 02:09:46 +0000175
Owen Andersond648e142006-08-29 06:10:56 +0000176 return OnlyPred;
Owen Anderson59312b12006-08-28 02:09:46 +0000177}
178
Devang Patel3f1a1e02007-03-07 01:38:05 +0000179bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
Devang Patel3f1a1e02007-03-07 01:38:05 +0000180 LI = &getAnalysis<LoopInfo>();
Chris Lattner83bf2882004-04-18 05:20:17 +0000181
Dan Gohmanc7678442007-05-11 20:53:41 +0000182 // Unroll the loop.
183 if (!unrollLoop(L, UnrollCount, UnrollThreshold))
184 return false;
185
186 // Update the loop information for this loop.
187 // If we completely unrolled the loop, remove it from the parent.
188 if (L->getNumBackEdges() == 0)
189 LPM.deleteLoopFromQueue(L);
190
191 return true;
192}
193
194/// Unroll the given loop by UnrollCount, or by a heuristically-determined
Dan Gohmand9efdb22007-05-14 14:31:17 +0000195/// value if Count is zero. If Threshold is not NoThreshold, it is a value
196/// to limit code size expansion. If the loop size would expand beyond the
197/// threshold value, unrolling is suppressed. The return value is true if
198/// any transformations are performed.
Dan Gohmanc7678442007-05-11 20:53:41 +0000199///
200bool LoopUnroll::unrollLoop(Loop *L, unsigned Count, unsigned Threshold) {
201 assert(L->isLCSSAForm());
202
Dan Gohman1cc00962007-05-08 15:19:19 +0000203 BasicBlock *Header = L->getHeader();
204 BasicBlock *LatchBlock = L->getLoopLatch();
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000205 BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
Chris Lattner83bf2882004-04-18 05:20:17 +0000206
Bill Wendlingb7427032006-11-26 09:46:52 +0000207 DOUT << "Loop Unroll: F[" << Header->getParent()->getName()
Dan Gohmanc7678442007-05-11 20:53:41 +0000208 << "] Loop %" << Header->getName() << "\n";
209
210 if (!BI || BI->isUnconditional()) {
Wojciech Matyjewicz21a715a2008-01-04 20:02:18 +0000211 // The loop-rotate pass can be helpful to avoid this in many cases.
Dan Gohmanc7678442007-05-11 20:53:41 +0000212 DOUT << " Can't unroll; loop not terminated by a conditional branch.\n";
213 return false;
Chris Lattner83bf2882004-04-18 05:20:17 +0000214 }
Dan Gohmanc7678442007-05-11 20:53:41 +0000215
216 // Determine the trip count and/or trip multiple. A TripCount value of zero
217 // is used to mean an unknown trip count. The TripMultiple value is the
218 // greatest known integer multiple of the trip count.
219 unsigned TripCount = 0;
220 unsigned TripMultiple = 1;
221 if (Value *TripCountValue = L->getTripCount()) {
222 if (ConstantInt *TripCountC = dyn_cast<ConstantInt>(TripCountValue)) {
223 // Guard against huge trip counts. This also guards against assertions in
224 // APInt from the use of getZExtValue, below.
225 if (TripCountC->getValue().getActiveBits() <= 32) {
226 TripCount = (unsigned)TripCountC->getZExtValue();
227 }
228 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TripCountValue)) {
229 switch (BO->getOpcode()) {
230 case BinaryOperator::Mul:
231 if (ConstantInt *MultipleC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
232 if (MultipleC->getValue().getActiveBits() <= 32) {
233 TripMultiple = (unsigned)MultipleC->getZExtValue();
234 }
235 }
236 break;
237 default: break;
238 }
239 }
240 }
241 if (TripCount != 0)
242 DOUT << " Trip Count = " << TripCount << "\n";
243 if (TripMultiple != 1)
244 DOUT << " Trip Multiple = " << TripMultiple << "\n";
245
246 // Automatically select an unroll count.
247 if (Count == 0) {
248 // Conservative heuristic: if we know the trip count, see if we can
249 // completely unroll (subject to the threshold, checked below); otherwise
250 // don't unroll.
251 if (TripCount != 0) {
252 Count = TripCount;
253 } else {
254 return false;
255 }
256 }
257
258 // Effectively "DCE" unrolled iterations that are beyond the tripcount
259 // and will never be executed.
260 if (TripCount != 0 && Count > TripCount)
261 Count = TripCount;
262
263 assert(Count > 0);
264 assert(TripMultiple > 0);
265 assert(TripCount == 0 || TripCount % TripMultiple == 0);
266
267 // Enforce the threshold.
268 if (Threshold != NoThreshold) {
269 unsigned LoopSize = ApproximateLoopSize(L);
270 DOUT << " Loop Size = " << LoopSize << "\n";
271 uint64_t Size = (uint64_t)LoopSize*Count;
272 if (TripCount != 1 && Size > Threshold) {
273 DOUT << " TOO LARGE TO UNROLL: "
274 << Size << ">" << Threshold << "\n";
275 return false;
276 }
277 }
278
279 // Are we eliminating the loop control altogether?
280 bool CompletelyUnroll = Count == TripCount;
281
282 // If we know the trip count, we know the multiple...
283 unsigned BreakoutTrip = 0;
284 if (TripCount != 0) {
285 BreakoutTrip = TripCount % Count;
286 TripMultiple = 0;
287 } else {
288 // Figure out what multiple to use.
289 BreakoutTrip = TripMultiple =
290 (unsigned)GreatestCommonDivisor64(Count, TripMultiple);
291 }
292
293 if (CompletelyUnroll) {
294 DOUT << "COMPLETELY UNROLLING loop %" << Header->getName()
295 << " with trip count " << TripCount << "!\n";
296 } else {
297 DOUT << "UNROLLING loop %" << Header->getName()
298 << " by " << Count;
299 if (TripMultiple == 0 || BreakoutTrip != TripMultiple) {
300 DOUT << " with a breakout at trip " << BreakoutTrip;
301 } else if (TripMultiple != 1) {
302 DOUT << " with " << TripMultiple << " trips per branch";
303 }
304 DOUT << "!\n";
305 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000306
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000307 std::vector<BasicBlock*> LoopBlocks = L->getBlocks();
308
Dan Gohmanc7678442007-05-11 20:53:41 +0000309 bool ContinueOnTrue = L->contains(BI->getSuccessor(0));
310 BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);
Chris Lattner83bf2882004-04-18 05:20:17 +0000311
312 // For the first iteration of the loop, we should use the precloned values for
313 // PHI nodes. Insert associations now.
Chris Lattnercaccc992007-05-05 18:49:57 +0000314 typedef DenseMap<const Value*, Value*> ValueMapTy;
315 ValueMapTy LastValueMap;
Chris Lattner83bf2882004-04-18 05:20:17 +0000316 std::vector<PHINode*> OrigPHINode;
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000317 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000318 PHINode *PN = cast<PHINode>(I);
Chris Lattner83bf2882004-04-18 05:20:17 +0000319 OrigPHINode.push_back(PN);
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000320 if (Instruction *I =
321 dyn_cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock)))
322 if (L->contains(I->getParent()))
Chris Lattner83bf2882004-04-18 05:20:17 +0000323 LastValueMap[I] = I;
324 }
325
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000326 std::vector<BasicBlock*> Headers;
327 std::vector<BasicBlock*> Latches;
328 Headers.push_back(Header);
329 Latches.push_back(LatchBlock);
Chris Lattner83bf2882004-04-18 05:20:17 +0000330
Dan Gohmanc7678442007-05-11 20:53:41 +0000331 for (unsigned It = 1; It != Count; ++It) {
Chris Lattner83bf2882004-04-18 05:20:17 +0000332 char SuffixBuffer[100];
333 sprintf(SuffixBuffer, ".%d", It);
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000334
335 std::vector<BasicBlock*> NewBlocks;
336
337 for (std::vector<BasicBlock*>::iterator BB = LoopBlocks.begin(),
338 E = LoopBlocks.end(); BB != E; ++BB) {
Chris Lattnercaccc992007-05-05 18:49:57 +0000339 ValueMapTy ValueMap;
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000340 BasicBlock *New = CloneBasicBlock(*BB, ValueMap, SuffixBuffer);
341 Header->getParent()->getBasicBlockList().push_back(New);
Chris Lattner83bf2882004-04-18 05:20:17 +0000342
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000343 // Loop over all of the PHI nodes in the block, changing them to use the
344 // incoming values from the previous block.
345 if (*BB == Header)
346 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
347 PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]);
348 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
349 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
350 if (It > 1 && L->contains(InValI->getParent()))
351 InVal = LastValueMap[InValI];
352 ValueMap[OrigPHINode[i]] = InVal;
353 New->getInstList().erase(NewPHI);
354 }
355
356 // Update our running map of newest clones
357 LastValueMap[*BB] = New;
Chris Lattnercaccc992007-05-05 18:49:57 +0000358 for (ValueMapTy::iterator VI = ValueMap.begin(), VE = ValueMap.end();
359 VI != VE; ++VI)
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000360 LastValueMap[VI->first] = VI->second;
361
Owen Andersond735ee82007-11-27 03:43:35 +0000362 L->addBasicBlockToLoop(New, LI->getBase());
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000363
364 // Add phi entries for newly created values to all exit blocks except
365 // the successor of the latch block. The successor of the exit block will
366 // be updated specially after unrolling all the way.
367 if (*BB != LatchBlock)
368 for (Value::use_iterator UI = (*BB)->use_begin(), UE = (*BB)->use_end();
Nick Lewyckyc837abe2008-01-27 18:35:00 +0000369 UI != UE;) {
Dan Gohman1cc00962007-05-08 15:19:19 +0000370 Instruction *UseInst = cast<Instruction>(*UI);
Nick Lewyckyc837abe2008-01-27 18:35:00 +0000371 ++UI;
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000372 if (isa<PHINode>(UseInst) && !L->contains(UseInst->getParent())) {
Dan Gohman1cc00962007-05-08 15:19:19 +0000373 PHINode *phi = cast<PHINode>(UseInst);
374 Value *Incoming = phi->getIncomingValueForBlock(*BB);
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000375 phi->addIncoming(Incoming, New);
376 }
377 }
378
379 // Keep track of new headers and latches as we create them, so that
380 // we can insert the proper branches later.
381 if (*BB == Header)
382 Headers.push_back(New);
Dan Gohmanc7678442007-05-11 20:53:41 +0000383 if (*BB == LatchBlock) {
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000384 Latches.push_back(New);
385
Dan Gohmanc7678442007-05-11 20:53:41 +0000386 // Also, clear out the new latch's back edge so that it doesn't look
387 // like a new loop, so that it's amenable to being merged with adjacent
388 // blocks later on.
389 TerminatorInst *Term = New->getTerminator();
390 assert(L->contains(Term->getSuccessor(!ContinueOnTrue)));
391 assert(Term->getSuccessor(ContinueOnTrue) == LoopExit);
392 Term->setSuccessor(!ContinueOnTrue, NULL);
393 }
394
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000395 NewBlocks.push_back(New);
Chris Lattner83bf2882004-04-18 05:20:17 +0000396 }
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000397
398 // Remap all instructions in the most recent iteration
399 for (unsigned i = 0; i < NewBlocks.size(); ++i)
400 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
401 E = NewBlocks[i]->end(); I != E; ++I)
Chris Lattner998f44f2004-04-18 17:32:39 +0000402 RemapInstruction(I, LastValueMap);
Chris Lattner998f44f2004-04-18 17:32:39 +0000403 }
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000404
Chris Lattnercaccc992007-05-05 18:49:57 +0000405 // The latch block exits the loop. If there are any PHI nodes in the
406 // successor blocks, update them to use the appropriate values computed as the
407 // last iteration of the loop.
Dan Gohmanc7678442007-05-11 20:53:41 +0000408 if (Count != 1) {
Chris Lattner5e665f52007-02-03 00:08:31 +0000409 SmallPtrSet<PHINode*, 8> Users;
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000410 for (Value::use_iterator UI = LatchBlock->use_begin(),
411 UE = LatchBlock->use_end(); UI != UE; ++UI)
Dan Gohman1cc00962007-05-08 15:19:19 +0000412 if (PHINode *phi = dyn_cast<PHINode>(*UI))
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000413 Users.insert(phi);
Chris Lattnercaccc992007-05-05 18:49:57 +0000414
415 BasicBlock *LastIterationBB = cast<BasicBlock>(LastValueMap[LatchBlock]);
Chris Lattner5e665f52007-02-03 00:08:31 +0000416 for (SmallPtrSet<PHINode*,8>::iterator SI = Users.begin(), SE = Users.end();
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000417 SI != SE; ++SI) {
Chris Lattnera0c54f32007-05-05 18:36:36 +0000418 PHINode *PN = *SI;
Chris Lattnercaccc992007-05-05 18:49:57 +0000419 Value *InVal = PN->removeIncomingValue(LatchBlock, false);
420 // If this value was defined in the loop, take the value defined by the
421 // last iteration of the loop.
422 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
423 if (L->contains(InValI->getParent()))
424 InVal = LastValueMap[InVal];
Devang Patelac585162007-04-16 23:03:45 +0000425 }
Chris Lattnercaccc992007-05-05 18:49:57 +0000426 PN->addIncoming(InVal, LastIterationBB);
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000427 }
428 }
Chris Lattner83bf2882004-04-18 05:20:17 +0000429
Dan Gohmanc7678442007-05-11 20:53:41 +0000430 // Now, if we're doing complete unrolling, loop over the PHI nodes in the
431 // original block, setting them to their incoming values.
432 if (CompletelyUnroll) {
433 BasicBlock *Preheader = L->getLoopPreheader();
434 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
435 PHINode *PN = OrigPHINode[i];
436 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
437 Header->getInstList().erase(PN);
Owen Anderson59312b12006-08-28 02:09:46 +0000438 }
439 }
Dan Gohmanc7678442007-05-11 20:53:41 +0000440
441 // Now that all the basic blocks for the unrolled iterations are in place,
442 // set up the branches to connect them.
443 for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
444 // The original branch was replicated in each unrolled iteration.
445 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
446
447 // The branch destination.
448 unsigned j = (i + 1) % e;
449 BasicBlock *Dest = Headers[j];
450 bool NeedConditional = true;
451
452 // For a complete unroll, make the last iteration end with a branch
453 // to the exit block.
454 if (CompletelyUnroll && j == 0) {
455 Dest = LoopExit;
456 NeedConditional = false;
457 }
458
459 // If we know the trip count or a multiple of it, we can safely use an
460 // unconditional branch for some iterations.
461 if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) {
462 NeedConditional = false;
463 }
464
465 if (NeedConditional) {
466 // Update the conditional branch's successor for the following
467 // iteration.
468 Term->setSuccessor(!ContinueOnTrue, Dest);
469 } else {
470 Term->setUnconditionalDest(Dest);
471 // Merge adjacent basic blocks, if possible.
472 if (BasicBlock *Fold = FoldBlockIntoPredecessor(Dest)) {
473 std::replace(Latches.begin(), Latches.end(), Dest, Fold);
474 std::replace(Headers.begin(), Headers.end(), Dest, Fold);
475 }
476 }
477 }
Owen Anderson59312b12006-08-28 02:09:46 +0000478
Chris Lattner83bf2882004-04-18 05:20:17 +0000479 // At this point, the code is well formed. We now do a quick sweep over the
480 // inserted code, doing constant propagation and dead code elimination as we
481 // go.
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000482 const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();
483 for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
Owen Anderson59312b12006-08-28 02:09:46 +0000484 BBE = NewLoopBlocks.end(); BB != BBE; ++BB)
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000485 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {
486 Instruction *Inst = I++;
Misha Brukmanfd939082005-04-21 23:48:37 +0000487
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000488 if (isInstructionTriviallyDead(Inst))
489 (*BB)->getInstList().erase(Inst);
490 else if (Constant *C = ConstantFoldInstruction(Inst)) {
491 Inst->replaceAllUsesWith(C);
492 (*BB)->getInstList().erase(Inst);
493 }
Chris Lattner83bf2882004-04-18 05:20:17 +0000494 }
Chris Lattner83bf2882004-04-18 05:20:17 +0000495
Dan Gohmanc7678442007-05-11 20:53:41 +0000496 NumCompletelyUnrolled += CompletelyUnroll;
Chris Lattner83bf2882004-04-18 05:20:17 +0000497 ++NumUnrolled;
498 return true;
499}