Fix a crash related to updating Phi nodes in the original header block. This was
[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/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/IntrinsicInst.h"
33 #include <cstdio>
34 #include <set>
35 #include <algorithm>
36 #include <iostream>
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
52     /// This transformation requires natural loop information & requires that
53     /// loop preheaders be inserted into the CFG...
54     ///
55     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
56       AU.addRequiredID(LoopSimplifyID);
57       AU.addRequiredID(LCSSAID);
58       AU.addRequired<LoopInfo>();
59       AU.addPreservedID(LCSSAID);
60       AU.addPreserved<LoopInfo>();
61     }
62   };
63   RegisterOpt<LoopUnroll> X("loop-unroll", "Unroll loops");
64 }
65
66 FunctionPass *llvm::createLoopUnrollPass() { return new LoopUnroll(); }
67
68 bool LoopUnroll::runOnFunction(Function &F) {
69   bool Changed = false;
70   LI = &getAnalysis<LoopInfo>();
71
72   // Transform all the top-level loops.  Copy the loop list so that the child
73   // can update the loop tree if it needs to delete the loop.
74   std::vector<Loop*> SubLoops(LI->begin(), LI->end());
75   for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
76     Changed |= visitLoop(SubLoops[i]);
77
78   return Changed;
79 }
80
81 /// ApproximateLoopSize - Approximate the size of the loop after it has been
82 /// unrolled.
83 static unsigned ApproximateLoopSize(const Loop *L) {
84   unsigned Size = 0;
85   for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
86     BasicBlock *BB = L->getBlocks()[i];
87     Instruction *Term = BB->getTerminator();
88     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
89       if (isa<PHINode>(I) && BB == L->getHeader()) {
90         // Ignore PHI nodes in the header.
91       } else if (I->hasOneUse() && I->use_back() == Term) {
92         // Ignore instructions only used by the loop terminator.
93       } else if (DbgInfoIntrinsic *DbgI = dyn_cast<DbgInfoIntrinsic>(I)) {
94         // Ignore debug instructions
95       } else {
96         ++Size;
97       }
98
99       // TODO: Ignore expressions derived from PHI and constants if inval of phi
100       // is a constant, or if operation is associative.  This will get induction
101       // variables.
102     }
103   }
104
105   return Size;
106 }
107
108 // RemapInstruction - Convert the instruction operands from referencing the
109 // current values into those specified by ValueMap.
110 //
111 static inline void RemapInstruction(Instruction *I,
112                                     std::map<const Value *, Value*> &ValueMap) {
113   for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
114     Value *Op = I->getOperand(op);
115     std::map<const Value *, Value*>::iterator It = ValueMap.find(Op);
116     if (It != ValueMap.end()) Op = It->second;
117     I->setOperand(op, Op);
118   }
119 }
120
121 bool LoopUnroll::visitLoop(Loop *L) {
122   bool Changed = false;
123
124   // Recurse through all subloops before we process this loop.  Copy the loop
125   // list so that the child can update the loop tree if it needs to delete the
126   // loop.
127   std::vector<Loop*> SubLoops(L->begin(), L->end());
128   for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
129     Changed |= visitLoop(SubLoops[i]);
130
131   BasicBlock* Header = L->getHeader();
132   BasicBlock* LatchBlock = L->getLoopLatch();
133
134   BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
135   if (BI == 0) return Changed;  // Must end in a conditional branch
136
137   ConstantInt *TripCountC = dyn_cast_or_null<ConstantInt>(L->getTripCount());
138   if (!TripCountC) return Changed;  // Must have constant trip count!
139
140   uint64_t TripCountFull = TripCountC->getRawValue();
141   if (TripCountFull != TripCountC->getRawValue() || TripCountFull == 0)
142     return Changed; // More than 2^32 iterations???
143
144   unsigned LoopSize = ApproximateLoopSize(L);
145   DEBUG(std::cerr << "Loop Unroll: F[" << Header->getParent()->getName()
146         << "] Loop %" << Header->getName() << " Loop Size = "
147         << LoopSize << " Trip Count = " << TripCountFull << " - ");
148   uint64_t Size = (uint64_t)LoopSize*TripCountFull;
149   if (Size > UnrollThreshold) {
150     DEBUG(std::cerr << "TOO LARGE: " << Size << ">" << UnrollThreshold << "\n");
151     return Changed;
152   }
153   DEBUG(std::cerr << "UNROLLING!\n");
154
155   std::vector<BasicBlock*> LoopBlocks = L->getBlocks();
156
157   unsigned TripCount = (unsigned)TripCountFull;
158
159   BasicBlock *LoopExit = BI->getSuccessor(L->contains(BI->getSuccessor(0))); 
160
161   // For the first iteration of the loop, we should use the precloned values for
162   // PHI nodes.  Insert associations now.
163   std::map<const Value*, Value*> LastValueMap;
164   std::vector<PHINode*> OrigPHINode;
165   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
166     PHINode *PN = cast<PHINode>(I);
167     OrigPHINode.push_back(PN);
168     if (Instruction *I = 
169                 dyn_cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock)))
170       if (L->contains(I->getParent()))
171         LastValueMap[I] = I;
172   }
173
174   // Remove the exit branch from the loop
175   LatchBlock->getInstList().erase(BI);
176   
177   std::vector<BasicBlock*> Headers;
178   std::vector<BasicBlock*> Latches;
179   Headers.push_back(Header);
180   Latches.push_back(LatchBlock);
181
182   assert(TripCount != 0 && "Trip count of 0 is impossible!");
183   for (unsigned It = 1; It != TripCount; ++It) {
184     char SuffixBuffer[100];
185     sprintf(SuffixBuffer, ".%d", It);
186     
187     std::vector<BasicBlock*> NewBlocks;
188     
189     for (std::vector<BasicBlock*>::iterator BB = LoopBlocks.begin(),
190          E = LoopBlocks.end(); BB != E; ++BB) {
191       std::map<const Value*, Value*> ValueMap;
192       BasicBlock *New = CloneBasicBlock(*BB, ValueMap, SuffixBuffer);
193       Header->getParent()->getBasicBlockList().push_back(New);
194
195       // Loop over all of the PHI nodes in the block, changing them to use the
196       // incoming values from the previous block.
197       if (*BB == Header)
198         for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
199           PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]);
200           Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
201           if (Instruction *InValI = dyn_cast<Instruction>(InVal))
202             if (It > 1 && L->contains(InValI->getParent()))
203               InVal = LastValueMap[InValI];
204           ValueMap[OrigPHINode[i]] = InVal;
205           New->getInstList().erase(NewPHI);
206         }
207
208       // Update our running map of newest clones
209       LastValueMap[*BB] = New;
210       for (std::map<const Value*, Value*>::iterator VI = ValueMap.begin(),
211            VE = ValueMap.end(); VI != VE; ++VI)
212         LastValueMap[VI->first] = VI->second;
213
214       L->addBasicBlockToLoop(New, *LI);
215
216       // Add phi entries for newly created values to all exit blocks except
217       // the successor of the latch block.  The successor of the exit block will
218       // be updated specially after unrolling all the way.
219       if (*BB != LatchBlock)
220         for (Value::use_iterator UI = (*BB)->use_begin(), UE = (*BB)->use_end();
221              UI != UE; ++UI) {
222           Instruction* UseInst = cast<Instruction>(*UI);
223           if (isa<PHINode>(UseInst) && !L->contains(UseInst->getParent())) {
224             PHINode* phi = cast<PHINode>(UseInst);
225             Value* Incoming = phi->getIncomingValueForBlock(*BB);
226             if (isa<Instruction>(Incoming))
227               Incoming = LastValueMap[Incoming];
228           
229             phi->addIncoming(Incoming, New);
230           }
231         }
232
233       // Keep track of new headers and latches as we create them, so that
234       // we can insert the proper branches later.
235       if (*BB == Header)
236         Headers.push_back(New);
237       if (*BB == LatchBlock)
238         Latches.push_back(New);
239
240       NewBlocks.push_back(New);
241     }
242     
243     // Remap all instructions in the most recent iteration
244     for (unsigned i = 0; i < NewBlocks.size(); ++i)
245       for (BasicBlock::iterator I = NewBlocks[i]->begin(),
246            E = NewBlocks[i]->end(); I != E; ++I)
247         RemapInstruction(I, LastValueMap);
248   }
249
250   //  Insert the branches that link the different iterations together
251   for (unsigned i = 0; i < Latches.size()-1; ++i)
252     new BranchInst(Headers[i+1], Latches[i]);
253   
254   // Finally, add an unconditional branch to the block to continue into the exit
255   // block.
256   new BranchInst(LoopExit, Latches[Latches.size()-1]);
257  
258   // Update PHI nodes that reference the final latch block
259   if (TripCount > 1) {
260     std::set<PHINode*> Users;
261     for (Value::use_iterator UI = LatchBlock->use_begin(),
262          UE = LatchBlock->use_end(); UI != UE; ++UI)
263       if (PHINode* phi = dyn_cast<PHINode>(*UI))
264         Users.insert(phi);
265         
266     for (std::set<PHINode*>::iterator SI = Users.begin(), SE = Users.end();
267          SI != SE; ++SI) {
268       Value* InVal = (*SI)->getIncomingValueForBlock(LatchBlock);
269       if (isa<Instruction>(InVal))
270         InVal = LastValueMap[InVal];
271       (*SI)->removeIncomingValue(LatchBlock, false);
272       if (InVal)
273         (*SI)->addIncoming(InVal, cast<BasicBlock>(LastValueMap[LatchBlock]));
274     }
275   }
276
277   // Now loop over the PHI nodes in the original block, setting them to their
278   // incoming values.
279   BasicBlock *Preheader = L->getLoopPreheader();
280   for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
281     PHINode *PN = OrigPHINode[i];
282     PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
283     Header->getInstList().erase(PN);
284   }  
285
286   // At this point, the code is well formed.  We now do a quick sweep over the
287   // inserted code, doing constant propagation and dead code elimination as we
288   // go.
289   const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();
290   for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
291        E = NewLoopBlocks.end(); BB != E; ++BB)
292     for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {
293       Instruction *Inst = I++;
294
295       if (isInstructionTriviallyDead(Inst))
296         (*BB)->getInstList().erase(Inst);
297       else if (Constant *C = ConstantFoldInstruction(Inst)) {
298         Inst->replaceAllUsesWith(C);
299         (*BB)->getInstList().erase(Inst);
300       }
301     }
302
303   // Update the loop information for this loop.
304   Loop *Parent = L->getParentLoop();
305
306   // Move all of the basic blocks in the loop into the parent loop.
307   for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
308        E = NewLoopBlocks.end(); BB != E; ++BB)
309     LI->changeLoopFor(*BB, Parent);
310
311   // Remove the loop from the parent.
312   if (Parent)
313     delete Parent->removeChildLoop(std::find(Parent->begin(), Parent->end(),L));
314   else
315     delete LI->removeLoop(std::find(LI->begin(), LI->end(), L));
316
317   ++NumUnrolled;
318   return true;
319 }