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