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