When removing a function from the function set and adding it to deferred, we
[llvm.git] / lib / Transforms / Utils / LoopUnroll.cpp
blobdd8c154fdd7fc26336e151d953d49eb37de22299
1 //===-- 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.
14 // It works best when loops have been canonicalized by the -indvars pass,
15 // allowing it to determine the trip counts of loops easily.
17 // The process of unrolling can produce extraneous basic blocks linked with
18 // unconditional branches. This will be corrected in the future.
20 //===----------------------------------------------------------------------===//
22 #define DEBUG_TYPE "loop-unroll"
23 #include "llvm/Transforms/Utils/UnrollLoop.h"
24 #include "llvm/BasicBlock.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/Analysis/InstructionSimplify.h"
27 #include "llvm/Analysis/LoopPass.h"
28 #include "llvm/Analysis/ScalarEvolution.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
32 #include "llvm/Transforms/Utils/Cloning.h"
33 #include "llvm/Transforms/Utils/Local.h"
34 using namespace llvm;
36 // TODO: Should these be here or in LoopUnroll?
37 STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
38 STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
40 /// RemapInstruction - Convert the instruction operands from referencing the
41 /// current values into those specified by VMap.
42 static inline void RemapInstruction(Instruction *I,
43 ValueToValueMapTy &VMap) {
44 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
45 Value *Op = I->getOperand(op);
46 ValueToValueMapTy::iterator It = VMap.find(Op);
47 if (It != VMap.end())
48 I->setOperand(op, It->second);
52 /// FoldBlockIntoPredecessor - Folds a basic block into its predecessor if it
53 /// only has one predecessor, and that predecessor only has one successor.
54 /// The LoopInfo Analysis that is passed will be kept consistent.
55 /// Returns the new combined block.
56 static BasicBlock *FoldBlockIntoPredecessor(BasicBlock *BB, LoopInfo* LI) {
57 // Merge basic blocks into their predecessor if there is only one distinct
58 // pred, and if there is only one distinct successor of the predecessor, and
59 // if there are no PHI nodes.
60 BasicBlock *OnlyPred = BB->getSinglePredecessor();
61 if (!OnlyPred) return 0;
63 if (OnlyPred->getTerminator()->getNumSuccessors() != 1)
64 return 0;
66 DEBUG(dbgs() << "Merging: " << *BB << "into: " << *OnlyPred);
68 // Resolve any PHI nodes at the start of the block. They are all
69 // guaranteed to have exactly one entry if they exist, unless there are
70 // multiple duplicate (but guaranteed to be equal) entries for the
71 // incoming edges. This occurs when there are multiple edges from
72 // OnlyPred to OnlySucc.
73 FoldSingleEntryPHINodes(BB);
75 // Delete the unconditional branch from the predecessor...
76 OnlyPred->getInstList().pop_back();
78 // Move all definitions in the successor to the predecessor...
79 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
81 // Make all PHI nodes that referred to BB now refer to Pred as their
82 // source...
83 BB->replaceAllUsesWith(OnlyPred);
85 std::string OldName = BB->getName();
87 // Erase basic block from the function...
88 LI->removeBlock(BB);
89 BB->eraseFromParent();
91 // Inherit predecessor's name if it exists...
92 if (!OldName.empty() && !OnlyPred->hasName())
93 OnlyPred->setName(OldName);
95 return OnlyPred;
98 /// Unroll the given loop by Count. The loop must be in LCSSA form. Returns true
99 /// if unrolling was succesful, or false if the loop was unmodified. Unrolling
100 /// can only fail when the loop's latch block is not terminated by a conditional
101 /// branch instruction. However, if the trip count (and multiple) are not known,
102 /// loop unrolling will mostly produce more code that is no faster.
104 /// The LoopInfo Analysis that is passed will be kept consistent.
106 /// If a LoopPassManager is passed in, and the loop is fully removed, it will be
107 /// removed from the LoopPassManager as well. LPM can also be NULL.
108 bool llvm::UnrollLoop(Loop *L, unsigned Count, LoopInfo* LI, LPPassManager* LPM) {
109 BasicBlock *Preheader = L->getLoopPreheader();
110 if (!Preheader) {
111 DEBUG(dbgs() << " Can't unroll; loop preheader-insertion failed.\n");
112 return false;
115 BasicBlock *LatchBlock = L->getLoopLatch();
116 if (!LatchBlock) {
117 DEBUG(dbgs() << " Can't unroll; loop exit-block-insertion failed.\n");
118 return false;
121 BasicBlock *Header = L->getHeader();
122 BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
124 if (!BI || BI->isUnconditional()) {
125 // The loop-rotate pass can be helpful to avoid this in many cases.
126 DEBUG(dbgs() <<
127 " Can't unroll; loop not terminated by a conditional branch.\n");
128 return false;
131 // Notify ScalarEvolution that the loop will be substantially changed,
132 // if not outright eliminated.
133 if (ScalarEvolution *SE = LPM->getAnalysisIfAvailable<ScalarEvolution>())
134 SE->forgetLoop(L);
136 // Find trip count
137 unsigned TripCount = L->getSmallConstantTripCount();
138 // Find trip multiple if count is not available
139 unsigned TripMultiple = 1;
140 if (TripCount == 0)
141 TripMultiple = L->getSmallConstantTripMultiple();
143 if (TripCount != 0)
144 DEBUG(dbgs() << " Trip Count = " << TripCount << "\n");
145 if (TripMultiple != 1)
146 DEBUG(dbgs() << " Trip Multiple = " << TripMultiple << "\n");
148 // Effectively "DCE" unrolled iterations that are beyond the tripcount
149 // and will never be executed.
150 if (TripCount != 0 && Count > TripCount)
151 Count = TripCount;
153 assert(Count > 0);
154 assert(TripMultiple > 0);
155 assert(TripCount == 0 || TripCount % TripMultiple == 0);
157 // Are we eliminating the loop control altogether?
158 bool CompletelyUnroll = Count == TripCount;
160 // If we know the trip count, we know the multiple...
161 unsigned BreakoutTrip = 0;
162 if (TripCount != 0) {
163 BreakoutTrip = TripCount % Count;
164 TripMultiple = 0;
165 } else {
166 // Figure out what multiple to use.
167 BreakoutTrip = TripMultiple =
168 (unsigned)GreatestCommonDivisor64(Count, TripMultiple);
171 if (CompletelyUnroll) {
172 DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName()
173 << " with trip count " << TripCount << "!\n");
174 } else {
175 DEBUG(dbgs() << "UNROLLING loop %" << Header->getName()
176 << " by " << Count);
177 if (TripMultiple == 0 || BreakoutTrip != TripMultiple) {
178 DEBUG(dbgs() << " with a breakout at trip " << BreakoutTrip);
179 } else if (TripMultiple != 1) {
180 DEBUG(dbgs() << " with " << TripMultiple << " trips per branch");
182 DEBUG(dbgs() << "!\n");
185 std::vector<BasicBlock*> LoopBlocks = L->getBlocks();
187 bool ContinueOnTrue = L->contains(BI->getSuccessor(0));
188 BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);
190 // For the first iteration of the loop, we should use the precloned values for
191 // PHI nodes. Insert associations now.
192 ValueToValueMapTy LastValueMap;
193 std::vector<PHINode*> OrigPHINode;
194 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
195 PHINode *PN = cast<PHINode>(I);
196 OrigPHINode.push_back(PN);
197 if (Instruction *I =
198 dyn_cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock)))
199 if (L->contains(I))
200 LastValueMap[I] = I;
203 std::vector<BasicBlock*> Headers;
204 std::vector<BasicBlock*> Latches;
205 Headers.push_back(Header);
206 Latches.push_back(LatchBlock);
208 for (unsigned It = 1; It != Count; ++It) {
209 std::vector<BasicBlock*> NewBlocks;
211 for (std::vector<BasicBlock*>::iterator BB = LoopBlocks.begin(),
212 E = LoopBlocks.end(); BB != E; ++BB) {
213 ValueToValueMapTy VMap;
214 BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It));
215 Header->getParent()->getBasicBlockList().push_back(New);
217 // Loop over all of the PHI nodes in the block, changing them to use the
218 // incoming values from the previous block.
219 if (*BB == Header)
220 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
221 PHINode *NewPHI = cast<PHINode>(VMap[OrigPHINode[i]]);
222 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
223 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
224 if (It > 1 && L->contains(InValI))
225 InVal = LastValueMap[InValI];
226 VMap[OrigPHINode[i]] = InVal;
227 New->getInstList().erase(NewPHI);
230 // Update our running map of newest clones
231 LastValueMap[*BB] = New;
232 for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
233 VI != VE; ++VI)
234 LastValueMap[VI->first] = VI->second;
236 L->addBasicBlockToLoop(New, LI->getBase());
238 // Add phi entries for newly created values to all exit blocks except
239 // the successor of the latch block. The successor of the exit block will
240 // be updated specially after unrolling all the way.
241 if (*BB != LatchBlock)
242 for (Value::use_iterator UI = (*BB)->use_begin(), UE = (*BB)->use_end();
243 UI != UE;) {
244 Instruction *UseInst = cast<Instruction>(*UI);
245 ++UI;
246 if (isa<PHINode>(UseInst) && !L->contains(UseInst)) {
247 PHINode *phi = cast<PHINode>(UseInst);
248 Value *Incoming = phi->getIncomingValueForBlock(*BB);
249 phi->addIncoming(Incoming, New);
253 // Keep track of new headers and latches as we create them, so that
254 // we can insert the proper branches later.
255 if (*BB == Header)
256 Headers.push_back(New);
257 if (*BB == LatchBlock) {
258 Latches.push_back(New);
260 // Also, clear out the new latch's back edge so that it doesn't look
261 // like a new loop, so that it's amenable to being merged with adjacent
262 // blocks later on.
263 TerminatorInst *Term = New->getTerminator();
264 assert(L->contains(Term->getSuccessor(!ContinueOnTrue)));
265 assert(Term->getSuccessor(ContinueOnTrue) == LoopExit);
266 Term->setSuccessor(!ContinueOnTrue, NULL);
269 NewBlocks.push_back(New);
272 // Remap all instructions in the most recent iteration
273 for (unsigned i = 0; i < NewBlocks.size(); ++i)
274 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
275 E = NewBlocks[i]->end(); I != E; ++I)
276 ::RemapInstruction(I, LastValueMap);
279 // The latch block exits the loop. If there are any PHI nodes in the
280 // successor blocks, update them to use the appropriate values computed as the
281 // last iteration of the loop.
282 if (Count != 1) {
283 SmallPtrSet<PHINode*, 8> Users;
284 for (Value::use_iterator UI = LatchBlock->use_begin(),
285 UE = LatchBlock->use_end(); UI != UE; ++UI)
286 if (PHINode *phi = dyn_cast<PHINode>(*UI))
287 Users.insert(phi);
289 BasicBlock *LastIterationBB = cast<BasicBlock>(LastValueMap[LatchBlock]);
290 for (SmallPtrSet<PHINode*,8>::iterator SI = Users.begin(), SE = Users.end();
291 SI != SE; ++SI) {
292 PHINode *PN = *SI;
293 Value *InVal = PN->removeIncomingValue(LatchBlock, false);
294 // If this value was defined in the loop, take the value defined by the
295 // last iteration of the loop.
296 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
297 if (L->contains(InValI))
298 InVal = LastValueMap[InVal];
300 PN->addIncoming(InVal, LastIterationBB);
304 // Now, if we're doing complete unrolling, loop over the PHI nodes in the
305 // original block, setting them to their incoming values.
306 if (CompletelyUnroll) {
307 BasicBlock *Preheader = L->getLoopPreheader();
308 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
309 PHINode *PN = OrigPHINode[i];
310 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
311 Header->getInstList().erase(PN);
315 // Now that all the basic blocks for the unrolled iterations are in place,
316 // set up the branches to connect them.
317 for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
318 // The original branch was replicated in each unrolled iteration.
319 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
321 // The branch destination.
322 unsigned j = (i + 1) % e;
323 BasicBlock *Dest = Headers[j];
324 bool NeedConditional = true;
326 // For a complete unroll, make the last iteration end with a branch
327 // to the exit block.
328 if (CompletelyUnroll && j == 0) {
329 Dest = LoopExit;
330 NeedConditional = false;
333 // If we know the trip count or a multiple of it, we can safely use an
334 // unconditional branch for some iterations.
335 if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) {
336 NeedConditional = false;
339 if (NeedConditional) {
340 // Update the conditional branch's successor for the following
341 // iteration.
342 Term->setSuccessor(!ContinueOnTrue, Dest);
343 } else {
344 // Replace the conditional branch with an unconditional one.
345 BranchInst::Create(Dest, Term);
346 Term->eraseFromParent();
347 // Merge adjacent basic blocks, if possible.
348 if (BasicBlock *Fold = FoldBlockIntoPredecessor(Dest, LI)) {
349 std::replace(Latches.begin(), Latches.end(), Dest, Fold);
350 std::replace(Headers.begin(), Headers.end(), Dest, Fold);
355 // At this point, the code is well formed. We now do a quick sweep over the
356 // inserted code, doing constant propagation and dead code elimination as we
357 // go.
358 const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();
359 for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
360 BBE = NewLoopBlocks.end(); BB != BBE; ++BB)
361 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {
362 Instruction *Inst = I++;
364 if (isInstructionTriviallyDead(Inst))
365 (*BB)->getInstList().erase(Inst);
366 else if (Value *V = SimplifyInstruction(Inst))
367 if (LI->replacementPreservesLCSSAForm(Inst, V)) {
368 Inst->replaceAllUsesWith(V);
369 (*BB)->getInstList().erase(Inst);
373 NumCompletelyUnrolled += CompletelyUnroll;
374 ++NumUnrolled;
375 // Remove the loop from the LoopPassManager if it's completely removed.
376 if (CompletelyUnroll && LPM != NULL)
377 LPM->deleteLoopFromQueue(L);
379 return true;