9d14891e49f0d7b1e79aa691be7cf0e1e1422d42
[oota-llvm.git] / lib / Transforms / Scalar / LoopUnroll.cpp
1 //===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===//
2 //
3 //                     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.
7 //
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/LoopInfo.h"
26 #include "llvm/Transforms/Utils/Cloning.h"
27 #include "llvm/Transforms/Utils/Local.h"
28 #include "llvm/Support/CFG.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/IntrinsicInst.h"
34 #include <cstdio>
35 #include <set>
36 #include <algorithm>
37 using namespace llvm;
38
39 namespace {
40   Statistic<> NumUnrolled("loop-unroll", "Number of loops completely unrolled");
41
42   cl::opt<unsigned>
43   UnrollThreshold("unroll-threshold", cl::init(100), cl::Hidden,
44                   cl::desc("The cut-off point for loop unrolling"));
45
46   class LoopUnroll : public FunctionPass {
47     LoopInfo *LI;  // The current loop information
48   public:
49     virtual bool runOnFunction(Function &F);
50     bool visitLoop(Loop *L);
51     BasicBlock* FoldBlockIntoPredecessor(BasicBlock* BB);
52
53     /// This transformation requires natural loop information & requires that
54     /// loop preheaders be inserted into the CFG...
55     ///
56     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
57       AU.addRequiredID(LoopSimplifyID);
58       AU.addRequiredID(LCSSAID);
59       AU.addRequired<LoopInfo>();
60       AU.addPreservedID(LCSSAID);
61       AU.addPreserved<LoopInfo>();
62     }
63   };
64   RegisterPass<LoopUnroll> X("loop-unroll", "Unroll loops");
65 }
66
67 FunctionPass *llvm::createLoopUnrollPass() { return new LoopUnroll(); }
68
69 bool LoopUnroll::runOnFunction(Function &F) {
70   bool Changed = false;
71   LI = &getAnalysis<LoopInfo>();
72
73   // Transform all the top-level loops.  Copy the loop list so that the child
74   // can update the loop tree if it needs to delete the loop.
75   std::vector<Loop*> SubLoops(LI->begin(), LI->end());
76   for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
77     Changed |= visitLoop(SubLoops[i]);
78
79   return Changed;
80 }
81
82 /// ApproximateLoopSize - Approximate the size of the loop after it has been
83 /// unrolled.
84 static unsigned ApproximateLoopSize(const Loop *L) {
85   unsigned Size = 0;
86   for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
87     BasicBlock *BB = L->getBlocks()[i];
88     Instruction *Term = BB->getTerminator();
89     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
90       if (isa<PHINode>(I) && BB == L->getHeader()) {
91         // Ignore PHI nodes in the header.
92       } else if (I->hasOneUse() && I->use_back() == Term) {
93         // Ignore instructions only used by the loop terminator.
94       } else if (isa<DbgInfoIntrinsic>(I)) {
95         // Ignore debug instructions
96       } else {
97         ++Size;
98       }
99
100       // TODO: Ignore expressions derived from PHI and constants if inval of phi
101       // is a constant, or if operation is associative.  This will get induction
102       // variables.
103     }
104   }
105
106   return Size;
107 }
108
109 // RemapInstruction - Convert the instruction operands from referencing the
110 // current values into those specified by ValueMap.
111 //
112 static inline void RemapInstruction(Instruction *I,
113                                     std::map<const Value *, Value*> &ValueMap) {
114   for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
115     Value *Op = I->getOperand(op);
116     std::map<const Value *, Value*>::iterator It = ValueMap.find(Op);
117     if (It != ValueMap.end()) Op = It->second;
118     I->setOperand(op, Op);
119   }
120 }
121
122 // FoldBlockIntoPredecessor - Folds a basic block into its predecessor if it
123 // only has one predecessor, and that predecessor only has one successor.
124 // Returns the new combined block.
125 BasicBlock* LoopUnroll::FoldBlockIntoPredecessor(BasicBlock* BB) {
126   // Merge basic blocks into their predecessor if there is only one distinct
127   // pred, and if there is only one distinct successor of the predecessor, and
128   // if there are no PHI nodes.
129   //
130   BasicBlock *OnlyPred = BB->getSinglePredecessor();
131   if (!OnlyPred) return 0;
132
133   if (OnlyPred->getTerminator()->getNumSuccessors() != 1)
134     return 0;
135
136   DOUT << "Merging: " << *BB << "into: " << *OnlyPred;
137
138   // Resolve any PHI nodes at the start of the block.  They are all
139   // guaranteed to have exactly one entry if they exist, unless there are
140   // multiple duplicate (but guaranteed to be equal) entries for the
141   // incoming edges.  This occurs when there are multiple edges from
142   // OnlyPred to OnlySucc.
143   //
144   while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
145     PN->replaceAllUsesWith(PN->getIncomingValue(0));
146     BB->getInstList().pop_front();  // Delete the phi node...
147   }
148
149   // Delete the unconditional branch from the predecessor...
150   OnlyPred->getInstList().pop_back();
151
152   // Move all definitions in the successor to the predecessor...
153   OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
154
155   // Make all PHI nodes that referred to BB now refer to Pred as their
156   // source...
157   BB->replaceAllUsesWith(OnlyPred);
158
159   std::string OldName = BB->getName();
160
161   // Erase basic block from the function...
162   LI->removeBlock(BB);
163   BB->eraseFromParent();
164
165   // Inherit predecessors name if it exists...
166   if (!OldName.empty() && !OnlyPred->hasName())
167     OnlyPred->setName(OldName);
168
169   return OnlyPred;
170 }
171
172 bool LoopUnroll::visitLoop(Loop *L) {
173   bool Changed = false;
174
175   // Recurse through all subloops before we process this loop.  Copy the loop
176   // list so that the child can update the loop tree if it needs to delete the
177   // loop.
178   std::vector<Loop*> SubLoops(L->begin(), L->end());
179   for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
180     Changed |= visitLoop(SubLoops[i]);
181
182   BasicBlock* Header = L->getHeader();
183   BasicBlock* LatchBlock = L->getLoopLatch();
184
185   BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
186   if (BI == 0) return Changed;  // Must end in a conditional branch
187
188   ConstantInt *TripCountC = dyn_cast_or_null<ConstantInt>(L->getTripCount());
189   if (!TripCountC) return Changed;  // Must have constant trip count!
190
191   uint64_t TripCountFull = TripCountC->getZExtValue();
192   if (TripCountFull != TripCountC->getZExtValue() || TripCountFull == 0)
193     return Changed; // More than 2^32 iterations???
194
195   unsigned LoopSize = ApproximateLoopSize(L);
196   DOUT << "Loop Unroll: F[" << Header->getParent()->getName()
197        << "] Loop %" << Header->getName() << " Loop Size = "
198        << LoopSize << " Trip Count = " << TripCountFull << " - ";
199   uint64_t Size = (uint64_t)LoopSize*TripCountFull;
200   if (Size > UnrollThreshold) {
201     DOUT << "TOO LARGE: " << Size << ">" << UnrollThreshold << "\n";
202     return Changed;
203   }
204   DOUT << "UNROLLING!\n";
205
206   std::vector<BasicBlock*> LoopBlocks = L->getBlocks();
207
208   unsigned TripCount = (unsigned)TripCountFull;
209
210   BasicBlock *LoopExit = BI->getSuccessor(L->contains(BI->getSuccessor(0))); 
211
212   // For the first iteration of the loop, we should use the precloned values for
213   // PHI nodes.  Insert associations now.
214   std::map<const Value*, Value*> LastValueMap;
215   std::vector<PHINode*> OrigPHINode;
216   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
217     PHINode *PN = cast<PHINode>(I);
218     OrigPHINode.push_back(PN);
219     if (Instruction *I = 
220                 dyn_cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock)))
221       if (L->contains(I->getParent()))
222         LastValueMap[I] = I;
223   }
224
225   // Remove the exit branch from the loop
226   LatchBlock->getInstList().erase(BI);
227   
228   std::vector<BasicBlock*> Headers;
229   std::vector<BasicBlock*> Latches;
230   Headers.push_back(Header);
231   Latches.push_back(LatchBlock);
232
233   assert(TripCount != 0 && "Trip count of 0 is impossible!");
234   for (unsigned It = 1; It != TripCount; ++It) {
235     char SuffixBuffer[100];
236     sprintf(SuffixBuffer, ".%d", It);
237     
238     std::vector<BasicBlock*> NewBlocks;
239     
240     for (std::vector<BasicBlock*>::iterator BB = LoopBlocks.begin(),
241          E = LoopBlocks.end(); BB != E; ++BB) {
242       std::map<const Value*, Value*> ValueMap;
243       BasicBlock *New = CloneBasicBlock(*BB, ValueMap, SuffixBuffer);
244       Header->getParent()->getBasicBlockList().push_back(New);
245
246       // Loop over all of the PHI nodes in the block, changing them to use the
247       // incoming values from the previous block.
248       if (*BB == Header)
249         for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
250           PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]);
251           Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
252           if (Instruction *InValI = dyn_cast<Instruction>(InVal))
253             if (It > 1 && L->contains(InValI->getParent()))
254               InVal = LastValueMap[InValI];
255           ValueMap[OrigPHINode[i]] = InVal;
256           New->getInstList().erase(NewPHI);
257         }
258
259       // Update our running map of newest clones
260       LastValueMap[*BB] = New;
261       for (std::map<const Value*, Value*>::iterator VI = ValueMap.begin(),
262            VE = ValueMap.end(); VI != VE; ++VI)
263         LastValueMap[VI->first] = VI->second;
264
265       L->addBasicBlockToLoop(New, *LI);
266
267       // Add phi entries for newly created values to all exit blocks except
268       // the successor of the latch block.  The successor of the exit block will
269       // be updated specially after unrolling all the way.
270       if (*BB != LatchBlock)
271         for (Value::use_iterator UI = (*BB)->use_begin(), UE = (*BB)->use_end();
272              UI != UE; ++UI) {
273           Instruction* UseInst = cast<Instruction>(*UI);
274           if (isa<PHINode>(UseInst) && !L->contains(UseInst->getParent())) {
275             PHINode* phi = cast<PHINode>(UseInst);
276             Value* Incoming = phi->getIncomingValueForBlock(*BB);
277             if (isa<Instruction>(Incoming))
278               Incoming = LastValueMap[Incoming];
279           
280             phi->addIncoming(Incoming, New);
281           }
282         }
283
284       // Keep track of new headers and latches as we create them, so that
285       // we can insert the proper branches later.
286       if (*BB == Header)
287         Headers.push_back(New);
288       if (*BB == LatchBlock)
289         Latches.push_back(New);
290
291       NewBlocks.push_back(New);
292     }
293     
294     // Remap all instructions in the most recent iteration
295     for (unsigned i = 0; i < NewBlocks.size(); ++i)
296       for (BasicBlock::iterator I = NewBlocks[i]->begin(),
297            E = NewBlocks[i]->end(); I != E; ++I)
298         RemapInstruction(I, LastValueMap);
299   }
300
301   
302  
303   // Update PHI nodes that reference the final latch block
304   if (TripCount > 1) {
305     std::set<PHINode*> Users;
306     for (Value::use_iterator UI = LatchBlock->use_begin(),
307          UE = LatchBlock->use_end(); UI != UE; ++UI)
308       if (PHINode* phi = dyn_cast<PHINode>(*UI))
309         Users.insert(phi);
310         
311     for (std::set<PHINode*>::iterator SI = Users.begin(), SE = Users.end();
312          SI != SE; ++SI) {
313       Value* InVal = (*SI)->getIncomingValueForBlock(LatchBlock);
314       if (isa<Instruction>(InVal))
315         InVal = LastValueMap[InVal];
316       (*SI)->removeIncomingValue(LatchBlock, false);
317       if (InVal)
318         (*SI)->addIncoming(InVal, cast<BasicBlock>(LastValueMap[LatchBlock]));
319     }
320   }
321
322   // Now loop over the PHI nodes in the original block, setting them to their
323   // incoming values.
324   BasicBlock *Preheader = L->getLoopPreheader();
325   for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
326     PHINode *PN = OrigPHINode[i];
327     PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
328     Header->getInstList().erase(PN);
329   }
330   
331   //  Insert the branches that link the different iterations together
332   for (unsigned i = 0; i < Latches.size()-1; ++i) {
333     new BranchInst(Headers[i+1], Latches[i]);
334     if(BasicBlock* Fold = FoldBlockIntoPredecessor(Headers[i+1])) {
335       std::replace(Latches.begin(), Latches.end(), Headers[i+1], Fold);
336       std::replace(Headers.begin(), Headers.end(), Headers[i+1], Fold);
337     }
338   }
339   
340   // Finally, add an unconditional branch to the block to continue into the exit
341   // block.
342   new BranchInst(LoopExit, Latches[Latches.size()-1]);
343   FoldBlockIntoPredecessor(LoopExit);
344   
345   // At this point, the code is well formed.  We now do a quick sweep over the
346   // inserted code, doing constant propagation and dead code elimination as we
347   // go.
348   const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();
349   for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
350        BBE = NewLoopBlocks.end(); BB != BBE; ++BB)
351     for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {
352       Instruction *Inst = I++;
353
354       if (isInstructionTriviallyDead(Inst))
355         (*BB)->getInstList().erase(Inst);
356       else if (Constant *C = ConstantFoldInstruction(Inst)) {
357         Inst->replaceAllUsesWith(C);
358         (*BB)->getInstList().erase(Inst);
359       }
360     }
361
362   // Update the loop information for this loop.
363   Loop *Parent = L->getParentLoop();
364
365   // Move all of the basic blocks in the loop into the parent loop.
366   for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
367        E = NewLoopBlocks.end(); BB != E; ++BB)
368     LI->changeLoopFor(*BB, Parent);
369
370   // Remove the loop from the parent.
371   if (Parent)
372     delete Parent->removeChildLoop(std::find(Parent->begin(), Parent->end(),L));
373   else
374     delete LI->removeLoop(std::find(LI->begin(), LI->end(), L));
375
376   ++NumUnrolled;
377   return true;
378 }