Fixed LICM bug that hoists trapping instructions that are not guaranteed to execute.
[oota-llvm.git] / lib / Transforms / Scalar / LICM.cpp
1 //===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
2 //
3 // This pass is a simple loop invariant code motion pass.  An interesting aspect
4 // of this pass is that it uses alias analysis for two purposes:
5 //
6 //  1. Moving loop invariant loads out of loops.  If we can determine that a
7 //     load inside of a loop never aliases anything stored to, we can hoist it
8 //     like any other instruction.
9 //  2. Scalar Promotion of Memory - If there is a store instruction inside of
10 //     the loop, we try to move the store to happen AFTER the loop instead of
11 //     inside of the loop.  This can only happen if a few conditions are true:
12 //       A. The pointer stored through is loop invariant
13 //       B. There are no stores or loads in the loop which _may_ alias the
14 //          pointer.  There are no calls in the loop which mod/ref the pointer.
15 //     If these conditions are true, we can promote the loads and stores in the
16 //     loop of the pointer to use a temporary alloca'd variable.  We then use
17 //     the mem2reg functionality to construct the appropriate SSA form for the
18 //     variable.
19 //
20 //===----------------------------------------------------------------------===//
21
22 #include "llvm/Transforms/Scalar.h"
23 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
24 #include "llvm/Transforms/Utils/Local.h"
25 #include "llvm/Analysis/LoopInfo.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/AliasSetTracker.h"
28 #include "llvm/Analysis/Dominators.h"
29 #include "llvm/Instructions.h"
30 #include "llvm/DerivedTypes.h"
31 #include "llvm/Target/TargetData.h"
32 #include "llvm/Support/InstVisitor.h"
33 #include "llvm/Support/CFG.h"
34 #include "Support/CommandLine.h"
35 #include "Support/Debug.h"
36 #include "Support/Statistic.h"
37 #include "llvm/Assembly/Writer.h"
38 #include <algorithm>
39
40 namespace {
41   cl::opt<bool> DisablePromotion("disable-licm-promotion", cl::Hidden,
42                              cl::desc("Disable memory promotion in LICM pass"));
43
44   Statistic<> NumHoisted("licm", "Number of instructions hoisted out of loop");
45   Statistic<> NumHoistedLoads("licm", "Number of load insts hoisted");
46   Statistic<> NumPromoted("licm", "Number of memory locations promoted to registers");
47
48   struct LICM : public FunctionPass, public InstVisitor<LICM> {
49     virtual bool runOnFunction(Function &F);
50
51     /// This transformation requires natural loop information & requires that
52     /// loop preheaders be inserted into the CFG...
53     ///
54     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
55       AU.setPreservesCFG();
56       AU.addRequiredID(LoopPreheadersID);
57       AU.addRequired<LoopInfo>();
58       AU.addRequired<DominatorTree>();
59       AU.addRequired<DominanceFrontier>();  // For scalar promotion (mem2reg)
60       AU.addRequired<AliasAnalysis>();
61     }
62
63   private:
64     LoopInfo      *LI;       // Current LoopInfo
65     AliasAnalysis *AA;       // Current AliasAnalysis information
66     bool Changed;            // Set to true when we change anything.
67     BasicBlock *Preheader;   // The preheader block of the current loop...
68     Loop *CurLoop;           // The current loop we are working on...
69     AliasSetTracker *CurAST; // AliasSet information for the current loop...
70     DominatorTree *CurDT;    // Dominator Tree for the current Loop...
71
72     /// visitLoop - Hoist expressions out of the specified loop...    
73     ///
74     void visitLoop(Loop *L, AliasSetTracker &AST);
75
76     /// HoistRegion - Walk the specified region of the CFG (defined by all
77     /// blocks dominated by the specified block, and that are in the current
78     /// loop) in depth first order w.r.t the DominatorTree.  This allows us to
79     /// visit defintions before uses, allowing us to hoist a loop body in one
80     /// pass without iteration.
81     ///
82     void HoistRegion(DominatorTree::Node *N);
83
84     /// inSubLoop - Little predicate that returns true if the specified basic
85     /// block is in a subloop of the current one, not the current one itself.
86     ///
87     bool inSubLoop(BasicBlock *BB) {
88       assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
89       for (unsigned i = 0, e = CurLoop->getSubLoops().size(); i != e; ++i)
90         if (CurLoop->getSubLoops()[i]->contains(BB))
91           return true;  // A subloop actually contains this block!
92       return false;
93     }
94
95     /// hoist - When an instruction is found to only use loop invariant operands
96     /// that is safe to hoist, this instruction is called to do the dirty work.
97     ///
98     void hoist(Instruction &I);
99
100     /// SafeToHoist - Only hoist an instruction if it is not a trapping instruction
101     /// or if it is a trapping instruction and is guaranteed to execute
102     ///
103     bool SafeToHoist(Instruction &I);
104
105     /// pointerInvalidatedByLoop - Return true if the body of this loop may
106     /// store into the memory location pointed to by V.
107     /// 
108     bool pointerInvalidatedByLoop(Value *V) {
109       // Check to see if any of the basic blocks in CurLoop invalidate *V.
110       return CurAST->getAliasSetForPointer(V, 0).isMod();
111     }
112
113     /// isLoopInvariant - Return true if the specified value is loop invariant
114     ///
115     inline bool isLoopInvariant(Value *V) {
116       if (Instruction *I = dyn_cast<Instruction>(V))
117         return !CurLoop->contains(I->getParent());
118       return true;  // All non-instructions are loop invariant
119     }
120
121     /// PromoteValuesInLoop - Look at the stores in the loop and promote as many
122     /// to scalars as we can.
123     ///
124     void PromoteValuesInLoop();
125
126     /// findPromotableValuesInLoop - Check the current loop for stores to
127     /// definate pointers, which are not loaded and stored through may aliases.
128     /// If these are found, create an alloca for the value, add it to the
129     /// PromotedValues list, and keep track of the mapping from value to
130     /// alloca...
131     ///
132     void findPromotableValuesInLoop(
133                    std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
134                                     std::map<Value*, AllocaInst*> &Val2AlMap);
135     
136
137     /// Instruction visitation handlers... these basically control whether or
138     /// not the specified instruction types are hoisted.
139     ///
140     friend class InstVisitor<LICM>;
141     void visitBinaryOperator(Instruction &I) {
142       if (isLoopInvariant(I.getOperand(0)) && isLoopInvariant(I.getOperand(1)) && SafeToHoist(I))
143         hoist(I);
144     }
145     void visitCastInst(CastInst &CI) {
146       Instruction &I = (Instruction&)CI;
147       if (isLoopInvariant(I.getOperand(0)) && SafeToHoist(CI)) hoist(I);
148     }
149     void visitShiftInst(ShiftInst &I) { visitBinaryOperator((Instruction&)I); }
150
151     void visitLoadInst(LoadInst &LI);
152
153     void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
154       Instruction &I = (Instruction&)GEPI;
155       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
156         if (!isLoopInvariant(I.getOperand(i))) return;
157       if(SafeToHoist(GEPI))
158         hoist(I);
159     }
160   };
161
162   RegisterOpt<LICM> X("licm", "Loop Invariant Code Motion");
163 }
164
165 Pass *createLICMPass() { return new LICM(); }
166
167 /// runOnFunction - For LICM, this simply traverses the loop structure of the
168 /// function, hoisting expressions out of loops if possible.
169 ///
170 bool LICM::runOnFunction(Function &) {
171   Changed = false;
172
173   // Get our Loop and Alias Analysis information...
174   LI = &getAnalysis<LoopInfo>();
175   AA = &getAnalysis<AliasAnalysis>();
176
177   // Hoist expressions out of all of the top-level loops.
178   const std::vector<Loop*> &TopLevelLoops = LI->getTopLevelLoops();
179   for (std::vector<Loop*>::const_iterator I = TopLevelLoops.begin(),
180          E = TopLevelLoops.end(); I != E; ++I) {
181     AliasSetTracker AST(*AA);
182     LICM::visitLoop(*I, AST);
183   }
184   return Changed;
185 }
186
187
188 /// visitLoop - Hoist expressions out of the specified loop...    
189 ///
190 void LICM::visitLoop(Loop *L, AliasSetTracker &AST) {
191   // Recurse through all subloops before we process this loop...
192   for (std::vector<Loop*>::const_iterator I = L->getSubLoops().begin(),
193          E = L->getSubLoops().end(); I != E; ++I) {
194     AliasSetTracker SubAST(*AA);
195     LICM::visitLoop(*I, SubAST);
196
197     // Incorporate information about the subloops into this loop...
198     AST.add(SubAST);
199   }
200   CurLoop = L;
201   CurAST = &AST;
202
203   // Get the preheader block to move instructions into...
204   Preheader = L->getLoopPreheader();
205   assert(Preheader&&"Preheader insertion pass guarantees we have a preheader!");
206
207   // Loop over the body of this loop, looking for calls, invokes, and stores.
208   // Because subloops have already been incorporated into AST, we skip blocks in
209   // subloops.
210   //
211   const std::vector<BasicBlock*> &LoopBBs = L->getBlocks();
212   for (std::vector<BasicBlock*>::const_iterator I = LoopBBs.begin(),
213          E = LoopBBs.end(); I != E; ++I)
214     if (LI->getLoopFor(*I) == L)        // Ignore blocks in subloops...
215       AST.add(**I);                     // Incorporate the specified basic block
216
217   // We want to visit all of the instructions in this loop... that are not parts
218   // of our subloops (they have already had their invariants hoisted out of
219   // their loop, into this loop, so there is no need to process the BODIES of
220   // the subloops).
221   //
222   // Traverse the body of the loop in depth first order on the dominator tree so
223   // that we are guaranteed to see definitions before we see uses.  This allows
224   // us to perform the LICM transformation in one pass, without iteration.
225   //
226   CurDT = &getAnalysis<DominatorTree>();
227   
228   HoistRegion(CurDT->getNode(L->getHeader()));
229
230   // Now that all loop invariants have been removed from the loop, promote any
231   // memory references to scalars that we can...
232   if (!DisablePromotion)
233     PromoteValuesInLoop();
234
235   // Clear out loops state information for the next iteration
236   CurLoop = 0;
237   Preheader = 0;
238 }
239
240 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
241 /// dominated by the specified block, and that are in the current loop) in depth
242 /// first order w.r.t the DominatorTree.  This allows us to visit defintions
243 /// before uses, allowing us to hoist a loop body in one pass without iteration.
244 ///
245 void LICM::HoistRegion(DominatorTree::Node *N) {
246   assert(N != 0 && "Null dominator tree node?");
247
248   // If this subregion is not in the top level loop at all, exit.
249   if (!CurLoop->contains(N->getNode())) return;
250
251   // Only need to hoist the contents of this block if it is not part of a
252   // subloop (which would already have been hoisted)
253   if (!inSubLoop(N->getNode()))
254     visit(*N->getNode());
255
256   const std::vector<DominatorTree::Node*> &Children = N->getChildren();
257   for (unsigned i = 0, e = Children.size(); i != e; ++i)
258     HoistRegion(Children[i]);
259 }
260
261
262 /// hoist - When an instruction is found to only use loop invariant operands
263 /// that is safe to hoist, this instruction is called to do the dirty work.
264 ///
265 void LICM::hoist(Instruction &Inst) {
266   DEBUG(std::cerr << "LICM hoisting to";
267         WriteAsOperand(std::cerr, Preheader, false);
268         std::cerr << ": " << Inst);
269
270   // Remove the instruction from its current basic block... but don't delete the
271   // instruction.
272   Inst.getParent()->getInstList().remove(&Inst);
273
274   // Insert the new node in Preheader, before the terminator.
275   Preheader->getInstList().insert(Preheader->getTerminator(), &Inst);
276   
277   ++NumHoisted;
278   Changed = true;
279 }
280
281 /// SafeToHoist - Only hoist an instruction if it is not a trapping instruction
282 /// or if it is a trapping instruction and is guaranteed to execute
283 ///
284 bool LICM::SafeToHoist(Instruction &Inst) {
285
286   //If it is a trapping instruction, then check if its guaranteed to execute.
287   if(Inst.isTrapping()) {
288
289     //Get the instruction's basic block.
290     BasicBlock *InstBB = Inst.getParent();
291     
292     //Get the Dominator Tree Node for the instruction's basic block/
293     DominatorTree::Node *InstDTNode = CurDT->getNode(InstBB);
294
295     //Get the exit blocks for the current loop.
296     const std::vector<BasicBlock* > ExitBlocks = CurLoop->getExitBlocks();
297
298     //For each exit block, get the DT node and walk up the DT until
299     //the instruction's basic block is found or we exit the loop.
300     for(unsigned i=0; i < ExitBlocks.size(); ++i) {
301       DominatorTree::Node *IDom = CurDT->getNode(ExitBlocks[i]);
302       
303       //Using boolean variable because exit nodes are not "contained"
304       //in the loop, so can not use that as the while test condition
305       //for first pass.
306       bool inLoop = true;
307
308       while(inLoop) {
309  
310         //compare Instruction DT node to Current DT Node
311         if(IDom == InstDTNode)
312           return true;
313
314         //Get next Immediate Dominator.
315         IDom = IDom->getIDom();
316
317         //See if we exited the loop.
318         inLoop = CurLoop->contains(IDom->getNode());
319       }
320       return false;
321     }
322   }
323   return true;
324 }
325
326
327 void LICM::visitLoadInst(LoadInst &LI) {
328   if (isLoopInvariant(LI.getOperand(0)) &&
329       !pointerInvalidatedByLoop(LI.getOperand(0)) && SafeToHoist(LI)) {
330     hoist(LI);
331     ++NumHoistedLoads;
332   }
333 }
334
335 /// PromoteValuesInLoop - Try to promote memory values to scalars by sinking
336 /// stores out of the loop and moving loads to before the loop.  We do this by
337 /// looping over the stores in the loop, looking for stores to Must pointers
338 /// which are loop invariant.  We promote these memory locations to use allocas
339 /// instead.  These allocas can easily be raised to register values by the
340 /// PromoteMem2Reg functionality.
341 ///
342 void LICM::PromoteValuesInLoop() {
343   // PromotedValues - List of values that are promoted out of the loop.  Each
344   // value has an alloca instruction for it, and a cannonical version of the
345   // pointer.
346   std::vector<std::pair<AllocaInst*, Value*> > PromotedValues;
347   std::map<Value*, AllocaInst*> ValueToAllocaMap; // Map of ptr to alloca
348
349   findPromotableValuesInLoop(PromotedValues, ValueToAllocaMap);
350   if (ValueToAllocaMap.empty()) return;   // If there are values to promote...
351
352   Changed = true;
353   NumPromoted += PromotedValues.size();
354
355   // Emit a copy from the value into the alloca'd value in the loop preheader
356   TerminatorInst *LoopPredInst = Preheader->getTerminator();
357   for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
358     // Load from the memory we are promoting...
359     LoadInst *LI = new LoadInst(PromotedValues[i].second, 
360                                 PromotedValues[i].second->getName()+".promoted",
361                                 LoopPredInst);
362     // Store into the temporary alloca...
363     new StoreInst(LI, PromotedValues[i].first, LoopPredInst);
364   }
365   
366   // Scan the basic blocks in the loop, replacing uses of our pointers with
367   // uses of the allocas in question.  If we find a branch that exits the
368   // loop, make sure to put reload code into all of the successors of the
369   // loop.
370   //
371   const std::vector<BasicBlock*> &LoopBBs = CurLoop->getBlocks();
372   for (std::vector<BasicBlock*>::const_iterator I = LoopBBs.begin(),
373          E = LoopBBs.end(); I != E; ++I) {
374     // Rewrite all loads and stores in the block of the pointer...
375     for (BasicBlock::iterator II = (*I)->begin(), E = (*I)->end();
376          II != E; ++II) {
377       if (LoadInst *L = dyn_cast<LoadInst>(II)) {
378         std::map<Value*, AllocaInst*>::iterator
379           I = ValueToAllocaMap.find(L->getOperand(0));
380         if (I != ValueToAllocaMap.end())
381           L->setOperand(0, I->second);    // Rewrite load instruction...
382       } else if (StoreInst *S = dyn_cast<StoreInst>(II)) {
383         std::map<Value*, AllocaInst*>::iterator
384           I = ValueToAllocaMap.find(S->getOperand(1));
385         if (I != ValueToAllocaMap.end())
386           S->setOperand(1, I->second);    // Rewrite store instruction...
387       }
388     }
389
390     // Check to see if any successors of this block are outside of the loop.
391     // If so, we need to copy the value from the alloca back into the memory
392     // location...
393     //
394     for (succ_iterator SI = succ_begin(*I), SE = succ_end(*I); SI != SE; ++SI)
395       if (!CurLoop->contains(*SI)) {
396         // Copy all of the allocas into their memory locations...
397         BasicBlock::iterator BI = (*SI)->begin();
398         while (isa<PHINode>(*BI))
399           ++BI;             // Skip over all of the phi nodes in the block...
400         Instruction *InsertPos = BI;
401         for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
402           // Load from the alloca...
403           LoadInst *LI = new LoadInst(PromotedValues[i].first, "", InsertPos);
404           // Store into the memory we promoted...
405           new StoreInst(LI, PromotedValues[i].second, InsertPos);
406         }
407       }
408   }
409
410   // Now that we have done the deed, use the mem2reg functionality to promote
411   // all of the new allocas we just created into real SSA registers...
412   //
413   std::vector<AllocaInst*> PromotedAllocas;
414   PromotedAllocas.reserve(PromotedValues.size());
415   for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i)
416     PromotedAllocas.push_back(PromotedValues[i].first);
417   PromoteMemToReg(PromotedAllocas, getAnalysis<DominanceFrontier>(),
418                   AA->getTargetData());
419 }
420
421 /// findPromotableValuesInLoop - Check the current loop for stores to definate
422 /// pointers, which are not loaded and stored through may aliases.  If these are
423 /// found, create an alloca for the value, add it to the PromotedValues list,
424 /// and keep track of the mapping from value to alloca...
425 ///
426 void LICM::findPromotableValuesInLoop(
427                    std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
428                              std::map<Value*, AllocaInst*> &ValueToAllocaMap) {
429   Instruction *FnStart = CurLoop->getHeader()->getParent()->begin()->begin();
430
431   // Loop over all of the alias sets in the tracker object...
432   for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
433        I != E; ++I) {
434     AliasSet &AS = *I;
435     // We can promote this alias set if it has a store, if it is a "Must" alias
436     // set, and if the pointer is loop invariant.
437     if (!AS.isForwardingAliasSet() && AS.isMod() && AS.isMustAlias() &&
438         isLoopInvariant(AS.begin()->first)) {
439       assert(AS.begin() != AS.end() &&
440              "Must alias set should have at least one pointer element in it!");
441       Value *V = AS.begin()->first;
442
443       // Check that all of the pointers in the alias set have the same type.  We
444       // cannot (yet) promote a memory location that is loaded and stored in
445       // different sizes.
446       bool PointerOk = true;
447       for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
448         if (V->getType() != I->first->getType()) {
449           PointerOk = false;
450           break;
451         }
452
453       if (PointerOk) {
454         const Type *Ty = cast<PointerType>(V->getType())->getElementType();
455         AllocaInst *AI = new AllocaInst(Ty, 0, V->getName()+".tmp", FnStart);
456         PromotedValues.push_back(std::make_pair(AI, V));
457         
458         for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
459           ValueToAllocaMap.insert(std::make_pair(I->first, AI));
460         
461         DEBUG(std::cerr << "LICM: Promoting value: " << *V << "\n");
462       }
463     }
464   }
465 }