blob: 512b6895011bfb0c380cd41289579a58b70db8c3 [file] [log] [blame]
Dan Gohman45b31972008-05-14 00:24:14 +00001//===-- UnrollLoop.cpp - Loop unrolling utilities -------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements some loop unrolling utilities. It does not define any
11// actual pass or policy, but provides a single function to perform loop
12// unrolling.
13//
Dan Gohman45b31972008-05-14 00:24:14 +000014// The process of unrolling can produce extraneous basic blocks linked with
15// unconditional branches. This will be corrected in the future.
Chris Lattnerb298db72011-01-11 08:00:40 +000016//
Dan Gohman45b31972008-05-14 00:24:14 +000017//===----------------------------------------------------------------------===//
18
19#define DEBUG_TYPE "loop-unroll"
20#include "llvm/Transforms/Utils/UnrollLoop.h"
21#include "llvm/BasicBlock.h"
22#include "llvm/ADT/Statistic.h"
Duncan Sandsb6133d12010-11-23 20:26:33 +000023#include "llvm/Analysis/InstructionSimplify.h"
Andrew Trickb1eede12011-08-10 00:28:10 +000024#include "llvm/Analysis/LoopIterator.h"
Dan Gohman45b31972008-05-14 00:24:14 +000025#include "llvm/Analysis/LoopPass.h"
Dan Gohman572365e2010-07-26 18:02:06 +000026#include "llvm/Analysis/ScalarEvolution.h"
Dan Gohman45b31972008-05-14 00:24:14 +000027#include "llvm/Support/Debug.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000028#include "llvm/Support/raw_ostream.h"
Chris Lattner29874e02008-12-03 19:44:02 +000029#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Dan Gohman45b31972008-05-14 00:24:14 +000030#include "llvm/Transforms/Utils/Cloning.h"
31#include "llvm/Transforms/Utils/Local.h"
Andrew Trick39f40292011-08-10 04:29:49 +000032#include "llvm/Transforms/Utils/SimplifyIndVar.h"
Dan Gohman45b31972008-05-14 00:24:14 +000033using namespace llvm;
34
Chris Lattner29874e02008-12-03 19:44:02 +000035// TODO: Should these be here or in LoopUnroll?
Dan Gohman45b31972008-05-14 00:24:14 +000036STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
Chris Lattnerb298db72011-01-11 08:00:40 +000037STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
Dan Gohman45b31972008-05-14 00:24:14 +000038
39/// RemapInstruction - Convert the instruction operands from referencing the
Devang Patel29d3dd82010-06-23 23:55:51 +000040/// current values into those specified by VMap.
Dan Gohman45b31972008-05-14 00:24:14 +000041static inline void RemapInstruction(Instruction *I,
Rafael Espindola1ed219a2010-10-13 01:36:30 +000042 ValueToValueMapTy &VMap) {
Dan Gohman45b31972008-05-14 00:24:14 +000043 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
44 Value *Op = I->getOperand(op);
Rafael Espindola1ed219a2010-10-13 01:36:30 +000045 ValueToValueMapTy::iterator It = VMap.find(Op);
Devang Patel29d3dd82010-06-23 23:55:51 +000046 if (It != VMap.end())
Dan Gohmanb56c9662009-10-31 14:46:50 +000047 I->setOperand(op, It->second);
Dan Gohman45b31972008-05-14 00:24:14 +000048 }
Jay Foad95c3e482011-06-23 09:09:15 +000049
50 if (PHINode *PN = dyn_cast<PHINode>(I)) {
51 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
52 ValueToValueMapTy::iterator It = VMap.find(PN->getIncomingBlock(i));
53 if (It != VMap.end())
54 PN->setIncomingBlock(i, cast<BasicBlock>(It->second));
55 }
56 }
Dan Gohman45b31972008-05-14 00:24:14 +000057}
58
Dan Gohman438b5832009-10-31 17:33:01 +000059/// FoldBlockIntoPredecessor - Folds a basic block into its predecessor if it
60/// only has one predecessor, and that predecessor only has one successor.
61/// The LoopInfo Analysis that is passed will be kept consistent.
62/// Returns the new combined block.
Andrew Trick1009c322011-08-03 18:32:11 +000063static BasicBlock *FoldBlockIntoPredecessor(BasicBlock *BB, LoopInfo* LI,
64 LPPassManager *LPM) {
Dan Gohman438b5832009-10-31 17:33:01 +000065 // Merge basic blocks into their predecessor if there is only one distinct
66 // pred, and if there is only one distinct successor of the predecessor, and
67 // if there are no PHI nodes.
68 BasicBlock *OnlyPred = BB->getSinglePredecessor();
69 if (!OnlyPred) return 0;
70
71 if (OnlyPred->getTerminator()->getNumSuccessors() != 1)
72 return 0;
73
David Greenea9ad9c22010-01-05 01:26:41 +000074 DEBUG(dbgs() << "Merging: " << *BB << "into: " << *OnlyPred);
Dan Gohman438b5832009-10-31 17:33:01 +000075
76 // Resolve any PHI nodes at the start of the block. They are all
77 // guaranteed to have exactly one entry if they exist, unless there are
78 // multiple duplicate (but guaranteed to be equal) entries for the
79 // incoming edges. This occurs when there are multiple edges from
80 // OnlyPred to OnlySucc.
81 FoldSingleEntryPHINodes(BB);
82
83 // Delete the unconditional branch from the predecessor...
84 OnlyPred->getInstList().pop_back();
85
Dan Gohman438b5832009-10-31 17:33:01 +000086 // Make all PHI nodes that referred to BB now refer to Pred as their
87 // source...
88 BB->replaceAllUsesWith(OnlyPred);
89
Jay Foad95c3e482011-06-23 09:09:15 +000090 // Move all definitions in the successor to the predecessor...
91 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
92
Dan Gohman438b5832009-10-31 17:33:01 +000093 std::string OldName = BB->getName();
94
95 // Erase basic block from the function...
Andrew Trick1009c322011-08-03 18:32:11 +000096
97 // ScalarEvolution holds references to loop exit blocks.
98 if (ScalarEvolution *SE = LPM->getAnalysisIfAvailable<ScalarEvolution>()) {
99 if (Loop *L = LI->getLoopFor(BB))
100 SE->forgetLoop(L);
101 }
Dan Gohman438b5832009-10-31 17:33:01 +0000102 LI->removeBlock(BB);
103 BB->eraseFromParent();
104
105 // Inherit predecessor's name if it exists...
106 if (!OldName.empty() && !OnlyPred->hasName())
107 OnlyPred->setName(OldName);
108
109 return OnlyPred;
110}
111
Dan Gohman45b31972008-05-14 00:24:14 +0000112/// Unroll the given loop by Count. The loop must be in LCSSA form. Returns true
Chris Lattnerf5ebfb02011-02-18 04:25:21 +0000113/// if unrolling was successful, or false if the loop was unmodified. Unrolling
Dan Gohman45b31972008-05-14 00:24:14 +0000114/// can only fail when the loop's latch block is not terminated by a conditional
115/// branch instruction. However, if the trip count (and multiple) are not known,
116/// loop unrolling will mostly produce more code that is no faster.
117///
Andrew Trick478849e2011-07-25 22:17:47 +0000118/// TripCount is generally defined as the number of times the loop header
119/// executes. UnrollLoop relaxes the definition to permit early exits: here
120/// TripCount is the iteration on which control exits LatchBlock if no early
121/// exits were taken. Note that UnrollLoop assumes that the loop counter test
122/// terminates LatchBlock in order to remove unnecesssary instances of the
123/// test. In other words, control may exit the loop prior to TripCount
124/// iterations via an early branch, but control may not exit the loop from the
125/// LatchBlock's terminator prior to TripCount iterations.
126///
127/// Similarly, TripMultiple divides the number of times that the LatchBlock may
128/// execute without exiting the loop.
129///
Dan Gohman45b31972008-05-14 00:24:14 +0000130/// The LoopInfo Analysis that is passed will be kept consistent.
131///
132/// If a LoopPassManager is passed in, and the loop is fully removed, it will be
133/// removed from the LoopPassManager as well. LPM can also be NULL.
Andrew Trick39f40292011-08-10 04:29:49 +0000134///
135/// This utility preserves LoopInfo. If DominatorTree or ScalarEvolution are
Andrew Trick7cb3dcb2011-08-10 18:07:05 +0000136/// available it must also preserve those analyses.
Andrew Trick2045ce12011-07-23 00:33:05 +0000137bool llvm::UnrollLoop(Loop *L, unsigned Count, unsigned TripCount,
Andrew Trick5d734482011-12-09 06:19:40 +0000138 bool AllowRuntime, unsigned TripMultiple,
139 LoopInfo *LI, LPPassManager *LPM) {
Dan Gohman692ad8d2009-11-05 19:44:06 +0000140 BasicBlock *Preheader = L->getLoopPreheader();
141 if (!Preheader) {
David Greenea9ad9c22010-01-05 01:26:41 +0000142 DEBUG(dbgs() << " Can't unroll; loop preheader-insertion failed.\n");
Dan Gohman692ad8d2009-11-05 19:44:06 +0000143 return false;
144 }
145
Dan Gohman45b31972008-05-14 00:24:14 +0000146 BasicBlock *LatchBlock = L->getLoopLatch();
Dan Gohman692ad8d2009-11-05 19:44:06 +0000147 if (!LatchBlock) {
David Greenea9ad9c22010-01-05 01:26:41 +0000148 DEBUG(dbgs() << " Can't unroll; loop exit-block-insertion failed.\n");
Dan Gohman692ad8d2009-11-05 19:44:06 +0000149 return false;
150 }
151
152 BasicBlock *Header = L->getHeader();
Dan Gohman45b31972008-05-14 00:24:14 +0000153 BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
Andrew Trickba033772011-07-23 00:29:16 +0000154
Dan Gohman45b31972008-05-14 00:24:14 +0000155 if (!BI || BI->isUnconditional()) {
156 // The loop-rotate pass can be helpful to avoid this in many cases.
David Greenea9ad9c22010-01-05 01:26:41 +0000157 DEBUG(dbgs() <<
Chris Lattnerbdff5482009-08-23 04:37:46 +0000158 " Can't unroll; loop not terminated by a conditional branch.\n");
Dan Gohman45b31972008-05-14 00:24:14 +0000159 return false;
160 }
Andrew Trickba033772011-07-23 00:29:16 +0000161
Chris Lattnerf5ebfb02011-02-18 04:25:21 +0000162 if (Header->hasAddressTaken()) {
163 // The loop-rotate pass can be helpful to avoid this in many cases.
164 DEBUG(dbgs() <<
165 " Won't unroll loop: address of header block is taken.\n");
166 return false;
167 }
Dan Gohman45b31972008-05-14 00:24:14 +0000168
Dan Gohman45b31972008-05-14 00:24:14 +0000169 if (TripCount != 0)
David Greenea9ad9c22010-01-05 01:26:41 +0000170 DEBUG(dbgs() << " Trip Count = " << TripCount << "\n");
Dan Gohman45b31972008-05-14 00:24:14 +0000171 if (TripMultiple != 1)
David Greenea9ad9c22010-01-05 01:26:41 +0000172 DEBUG(dbgs() << " Trip Multiple = " << TripMultiple << "\n");
Dan Gohman45b31972008-05-14 00:24:14 +0000173
174 // Effectively "DCE" unrolled iterations that are beyond the tripcount
175 // and will never be executed.
176 if (TripCount != 0 && Count > TripCount)
177 Count = TripCount;
178
Andrew Trick1da28272011-12-16 02:03:48 +0000179 // Don't enter the unroll code if there is nothing to do. This way we don't
180 // need to support "partial unrolling by 1".
181 if (TripCount == 0 && Count < 2)
182 return false;
183
Dan Gohman45b31972008-05-14 00:24:14 +0000184 assert(Count > 0);
185 assert(TripMultiple > 0);
186 assert(TripCount == 0 || TripCount % TripMultiple == 0);
187
188 // Are we eliminating the loop control altogether?
189 bool CompletelyUnroll = Count == TripCount;
190
Andrew Trick5d734482011-12-09 06:19:40 +0000191 // We assume a run-time trip count if the compiler cannot
192 // figure out the loop trip count and the unroll-runtime
193 // flag is specified.
194 bool RuntimeTripCount = (TripCount == 0 && Count > 0 && AllowRuntime);
195
196 if (RuntimeTripCount && !UnrollRuntimeLoopProlog(L, Count, LI, LPM))
197 return false;
198
199 // Notify ScalarEvolution that the loop will be substantially changed,
200 // if not outright eliminated.
201 ScalarEvolution *SE = LPM->getAnalysisIfAvailable<ScalarEvolution>();
202 if (SE)
203 SE->forgetLoop(L);
204
Dan Gohman45b31972008-05-14 00:24:14 +0000205 // If we know the trip count, we know the multiple...
206 unsigned BreakoutTrip = 0;
207 if (TripCount != 0) {
208 BreakoutTrip = TripCount % Count;
209 TripMultiple = 0;
210 } else {
211 // Figure out what multiple to use.
212 BreakoutTrip = TripMultiple =
213 (unsigned)GreatestCommonDivisor64(Count, TripMultiple);
214 }
215
216 if (CompletelyUnroll) {
David Greenea9ad9c22010-01-05 01:26:41 +0000217 DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName()
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000218 << " with trip count " << TripCount << "!\n");
Dan Gohman45b31972008-05-14 00:24:14 +0000219 } else {
David Greenea9ad9c22010-01-05 01:26:41 +0000220 DEBUG(dbgs() << "UNROLLING loop %" << Header->getName()
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000221 << " by " << Count);
Dan Gohman45b31972008-05-14 00:24:14 +0000222 if (TripMultiple == 0 || BreakoutTrip != TripMultiple) {
David Greenea9ad9c22010-01-05 01:26:41 +0000223 DEBUG(dbgs() << " with a breakout at trip " << BreakoutTrip);
Dan Gohman45b31972008-05-14 00:24:14 +0000224 } else if (TripMultiple != 1) {
David Greenea9ad9c22010-01-05 01:26:41 +0000225 DEBUG(dbgs() << " with " << TripMultiple << " trips per branch");
Andrew Trick5d734482011-12-09 06:19:40 +0000226 } else if (RuntimeTripCount) {
227 DEBUG(dbgs() << " with run-time trip count");
Dan Gohman45b31972008-05-14 00:24:14 +0000228 }
David Greenea9ad9c22010-01-05 01:26:41 +0000229 DEBUG(dbgs() << "!\n");
Dan Gohman45b31972008-05-14 00:24:14 +0000230 }
231
232 std::vector<BasicBlock*> LoopBlocks = L->getBlocks();
233
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000234 bool ContinueOnTrue = L->contains(BI->getSuccessor(0));
Dan Gohman45b31972008-05-14 00:24:14 +0000235 BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);
236
237 // For the first iteration of the loop, we should use the precloned values for
238 // PHI nodes. Insert associations now.
Devang Patel39430842010-04-20 22:24:18 +0000239 ValueToValueMapTy LastValueMap;
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000240 std::vector<PHINode*> OrigPHINode;
Dan Gohman45b31972008-05-14 00:24:14 +0000241 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
Andrew Trick70d0ca92011-08-09 03:11:29 +0000242 OrigPHINode.push_back(cast<PHINode>(I));
Dan Gohman45b31972008-05-14 00:24:14 +0000243 }
244
245 std::vector<BasicBlock*> Headers;
246 std::vector<BasicBlock*> Latches;
247 Headers.push_back(Header);
248 Latches.push_back(LatchBlock);
249
Andrew Trickb1eede12011-08-10 00:28:10 +0000250 // The current on-the-fly SSA update requires blocks to be processed in
251 // reverse postorder so that LastValueMap contains the correct value at each
252 // exit.
253 LoopBlocksDFS DFS(L);
Andrew Trick2d31ae32011-08-10 01:59:05 +0000254 DFS.perform(LI);
255
Andrew Trickb1eede12011-08-10 00:28:10 +0000256 // Stash the DFS iterators before adding blocks to the loop.
257 LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO();
258 LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO();
259
Dan Gohman45b31972008-05-14 00:24:14 +0000260 for (unsigned It = 1; It != Count; ++It) {
Dan Gohman45b31972008-05-14 00:24:14 +0000261 std::vector<BasicBlock*> NewBlocks;
Andrew Trickba033772011-07-23 00:29:16 +0000262
Andrew Trickb1eede12011-08-10 00:28:10 +0000263 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
Devang Patel29d3dd82010-06-23 23:55:51 +0000264 ValueToValueMapTy VMap;
265 BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It));
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000266 Header->getParent()->getBasicBlockList().push_back(New);
Dan Gohman45b31972008-05-14 00:24:14 +0000267
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000268 // Loop over all of the PHI nodes in the block, changing them to use the
269 // incoming values from the previous block.
270 if (*BB == Header)
271 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
Devang Patel29d3dd82010-06-23 23:55:51 +0000272 PHINode *NewPHI = cast<PHINode>(VMap[OrigPHINode[i]]);
Dan Gohman45b31972008-05-14 00:24:14 +0000273 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
274 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
Dan Gohman92329c72009-12-18 01:24:09 +0000275 if (It > 1 && L->contains(InValI))
Dan Gohman45b31972008-05-14 00:24:14 +0000276 InVal = LastValueMap[InValI];
Devang Patel29d3dd82010-06-23 23:55:51 +0000277 VMap[OrigPHINode[i]] = InVal;
Dan Gohman45b31972008-05-14 00:24:14 +0000278 New->getInstList().erase(NewPHI);
279 }
280
281 // Update our running map of newest clones
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000282 LastValueMap[*BB] = New;
Devang Patel29d3dd82010-06-23 23:55:51 +0000283 for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
Dan Gohman45b31972008-05-14 00:24:14 +0000284 VI != VE; ++VI)
285 LastValueMap[VI->first] = VI->second;
286
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000287 L->addBasicBlockToLoop(New, LI->getBase());
288
Andrew Trickb1eede12011-08-10 00:28:10 +0000289 // Add phi entries for newly created values to all exit blocks.
290 for (succ_iterator SI = succ_begin(*BB), SE = succ_end(*BB);
291 SI != SE; ++SI) {
292 if (L->contains(*SI))
293 continue;
294 for (BasicBlock::iterator BBI = (*SI)->begin();
295 PHINode *phi = dyn_cast<PHINode>(BBI); ++BBI) {
296 Value *Incoming = phi->getIncomingValueForBlock(*BB);
297 ValueToValueMapTy::iterator It = LastValueMap.find(Incoming);
298 if (It != LastValueMap.end())
299 Incoming = It->second;
300 phi->addIncoming(Incoming, New);
301 }
302 }
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000303 // Keep track of new headers and latches as we create them, so that
304 // we can insert the proper branches later.
305 if (*BB == Header)
306 Headers.push_back(New);
Andrew Trickb1eede12011-08-10 00:28:10 +0000307 if (*BB == LatchBlock)
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000308 Latches.push_back(New);
309
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000310 NewBlocks.push_back(New);
Dan Gohman45b31972008-05-14 00:24:14 +0000311 }
Andrew Trickba033772011-07-23 00:29:16 +0000312
Dan Gohman45b31972008-05-14 00:24:14 +0000313 // Remap all instructions in the most recent iteration
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000314 for (unsigned i = 0; i < NewBlocks.size(); ++i)
Dan Gohman45b31972008-05-14 00:24:14 +0000315 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
316 E = NewBlocks[i]->end(); I != E; ++I)
Rafael Espindola1ed219a2010-10-13 01:36:30 +0000317 ::RemapInstruction(I, LastValueMap);
Dan Gohman45b31972008-05-14 00:24:14 +0000318 }
Andrew Trickba033772011-07-23 00:29:16 +0000319
Andrew Trickb1eede12011-08-10 00:28:10 +0000320 // Loop over the PHI nodes in the original block, setting incoming values.
321 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
322 PHINode *PN = OrigPHINode[i];
323 if (CompletelyUnroll) {
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000324 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
325 Header->getInstList().erase(PN);
326 }
Andrew Trickb1eede12011-08-10 00:28:10 +0000327 else if (Count > 1) {
328 Value *InVal = PN->removeIncomingValue(LatchBlock, false);
329 // If this value was defined in the loop, take the value defined by the
330 // last iteration of the loop.
331 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
332 if (L->contains(InValI))
333 InVal = LastValueMap[InVal];
334 }
335 assert(Latches.back() == LastValueMap[LatchBlock] && "bad last latch");
336 PN->addIncoming(InVal, Latches.back());
337 }
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000338 }
Dan Gohman45b31972008-05-14 00:24:14 +0000339
340 // Now that all the basic blocks for the unrolled iterations are in place,
341 // set up the branches to connect them.
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000342 for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
Dan Gohman45b31972008-05-14 00:24:14 +0000343 // The original branch was replicated in each unrolled iteration.
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000344 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
Dan Gohman45b31972008-05-14 00:24:14 +0000345
346 // The branch destination.
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000347 unsigned j = (i + 1) % e;
348 BasicBlock *Dest = Headers[j];
Dan Gohman45b31972008-05-14 00:24:14 +0000349 bool NeedConditional = true;
350
Andrew Trick5d734482011-12-09 06:19:40 +0000351 if (RuntimeTripCount && j != 0) {
352 NeedConditional = false;
353 }
354
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000355 // For a complete unroll, make the last iteration end with a branch
356 // to the exit block.
357 if (CompletelyUnroll && j == 0) {
Dan Gohman45b31972008-05-14 00:24:14 +0000358 Dest = LoopExit;
359 NeedConditional = false;
360 }
361
362 // If we know the trip count or a multiple of it, we can safely use an
363 // unconditional branch for some iterations.
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000364 if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) {
Dan Gohman45b31972008-05-14 00:24:14 +0000365 NeedConditional = false;
366 }
367
368 if (NeedConditional) {
369 // Update the conditional branch's successor for the following
370 // iteration.
371 Term->setSuccessor(!ContinueOnTrue, Dest);
372 } else {
Andrew Trickb1eede12011-08-10 00:28:10 +0000373 // Remove phi operands at this loop exit
374 if (Dest != LoopExit) {
375 BasicBlock *BB = Latches[i];
376 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
377 SI != SE; ++SI) {
378 if (*SI == Headers[i])
379 continue;
380 for (BasicBlock::iterator BBI = (*SI)->begin();
381 PHINode *Phi = dyn_cast<PHINode>(BBI); ++BBI) {
382 Phi->removeIncomingValue(BB, false);
383 }
384 }
385 }
Jay Foad8f9ffbd2011-01-07 20:25:56 +0000386 // Replace the conditional branch with an unconditional one.
387 BranchInst::Create(Dest, Term);
388 Term->eraseFromParent();
Jay Foadcd35e092011-06-21 10:33:19 +0000389 }
390 }
391
Jay Foad95c3e482011-06-23 09:09:15 +0000392 // Merge adjacent basic blocks, if possible.
393 for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
394 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
395 if (Term->isUnconditional()) {
396 BasicBlock *Dest = Term->getSuccessor(0);
Andrew Trick1009c322011-08-03 18:32:11 +0000397 if (BasicBlock *Fold = FoldBlockIntoPredecessor(Dest, LI, LPM))
Jay Foad95c3e482011-06-23 09:09:15 +0000398 std::replace(Latches.begin(), Latches.end(), Dest, Fold);
399 }
400 }
Andrew Trickba033772011-07-23 00:29:16 +0000401
Andrew Trick39f40292011-08-10 04:29:49 +0000402 // FIXME: Reconstruct dom info, because it is not preserved properly.
Andrew Trick7cb3dcb2011-08-10 18:07:05 +0000403 // Incrementally updating domtree after loop unrolling would be easy.
Andrew Trick39f40292011-08-10 04:29:49 +0000404 if (DominatorTree *DT = LPM->getAnalysisIfAvailable<DominatorTree>())
405 DT->runOnFunction(*L->getHeader()->getParent());
406
407 // Simplify any new induction variables in the partially unrolled loop.
408 if (SE && !CompletelyUnroll) {
409 SmallVector<WeakVH, 16> DeadInsts;
410 simplifyLoopIVs(L, SE, LPM, DeadInsts);
411
412 // Aggressively clean up dead instructions that simplifyLoopIVs already
413 // identified. Any remaining should be cleaned up below.
414 while (!DeadInsts.empty())
415 if (Instruction *Inst =
416 dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
417 RecursivelyDeleteTriviallyDeadInstructions(Inst);
418 }
419
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000420 // At this point, the code is well formed. We now do a quick sweep over the
421 // inserted code, doing constant propagation and dead code elimination as we
422 // go.
423 const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();
424 for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
425 BBE = NewLoopBlocks.end(); BB != BBE; ++BB)
426 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {
Dan Gohman45b31972008-05-14 00:24:14 +0000427 Instruction *Inst = I++;
428
429 if (isInstructionTriviallyDead(Inst))
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000430 (*BB)->getInstList().erase(Inst);
Duncan Sandsb6133d12010-11-23 20:26:33 +0000431 else if (Value *V = SimplifyInstruction(Inst))
432 if (LI->replacementPreservesLCSSAForm(Inst, V)) {
433 Inst->replaceAllUsesWith(V);
434 (*BB)->getInstList().erase(Inst);
435 }
Dan Gohman45b31972008-05-14 00:24:14 +0000436 }
Dan Gohman45b31972008-05-14 00:24:14 +0000437
438 NumCompletelyUnrolled += CompletelyUnroll;
439 ++NumUnrolled;
440 // Remove the loop from the LoopPassManager if it's completely removed.
441 if (CompletelyUnroll && LPM != NULL)
442 LPM->deleteLoopFromQueue(L);
443
Dan Gohman45b31972008-05-14 00:24:14 +0000444 return true;
445}