Change the mem2reg interface to accept a TargetData argument
[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/Dominators.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/DerivedTypes.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/Support/InstVisitor.h"
32 #include "llvm/Support/CFG.h"
33 #include "Support/Statistic.h"
34 #include "Support/CommandLine.h"
35 #include "llvm/Assembly/Writer.h"
36 #include <algorithm>
37
38 namespace {
39   cl::opt<bool> DisablePromotion("disable-licm-promotion", cl::Hidden,
40                              cl::desc("Disable memory promotion in LICM pass"));
41
42   Statistic<> NumHoisted("licm", "Number of instructions hoisted out of loop");
43   Statistic<> NumHoistedLoads("licm", "Number of load insts hoisted");
44   Statistic<> NumPromoted("licm", "Number of memory locations promoted to registers");
45
46   /// LoopBodyInfo - We recursively traverse loops from most-deeply-nested to
47   /// least-deeply-nested.  For all of the loops nested within the current one,
48   /// we keep track of information so that we don't have to repeat queries.
49   ///
50   struct LoopBodyInfo {
51     std::vector<CallInst*> Calls;          // Call instructions in loop
52     std::vector<InvokeInst*> Invokes;      // Invoke instructions in loop
53
54     // StoredPointers - Targets of store instructions...
55     std::set<Value*> StoredPointers;
56
57     // LoadedPointers - Source pointers for load instructions...
58     std::set<Value*> LoadedPointers;
59
60     enum PointerClass {
61       PointerUnknown = 0, // Nothing is known about this pointer yet
62       PointerMustStore,   // Memory is stored to ONLY through this pointer
63       PointerMayStore,    // Memory is stored to through this or other pointers
64       PointerNoStore      // Memory is not modified in this loop
65     };
66
67     // PointerIsModified - Keep track of information as we find out about it in
68     // the loop body...
69     //
70     std::map<Value*, enum PointerClass> PointerIsModified;
71
72     /// CantModifyAnyPointers - Return true if no memory modifying instructions
73     /// occur in this loop.  This is just a conservative approximation, because
74     /// a call may not actually store anything.
75     bool CantModifyAnyPointers() const {
76       return Calls.empty() && Invokes.empty() && StoredPointers.empty();
77     }
78
79     /// incorporate - Incorporate information about a subloop into the current
80     /// loop.
81     void incorporate(const LoopBodyInfo &OtherLBI);
82     void incorporate(BasicBlock &BB);  // do the same for a basic block
83
84     PointerClass getPointerInfo(Value *V, AliasAnalysis &AA) {
85       PointerClass &VInfo = PointerIsModified[V];
86       if (VInfo == PointerUnknown)
87         VInfo = calculatePointerInfo(V, AA);
88       return VInfo;
89     }
90   private:
91     /// calculatePointerInfo - Calculate information about the specified
92     /// pointer.
93     PointerClass calculatePointerInfo(Value *V, AliasAnalysis &AA) const;
94   };
95 }
96
97 /// incorporate - Incorporate information about a subloop into the current loop.
98 void LoopBodyInfo::incorporate(const LoopBodyInfo &OtherLBI) {
99   // Do not incorporate NonModifiedPointers (which is just a cache) because it
100   // is too much trouble to make sure it's still valid.
101   Calls.insert  (Calls.end(),  OtherLBI.Calls.begin(),  OtherLBI.Calls.end());
102   Invokes.insert(Invokes.end(),OtherLBI.Invokes.begin(),OtherLBI.Invokes.end());
103   StoredPointers.insert(OtherLBI.StoredPointers.begin(),
104                         OtherLBI.StoredPointers.end());
105   LoadedPointers.insert(OtherLBI.LoadedPointers.begin(),
106                         OtherLBI.LoadedPointers.end());
107 }
108
109 void LoopBodyInfo::incorporate(BasicBlock &BB) {
110   for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
111     if (CallInst *CI = dyn_cast<CallInst>(&*I))
112       Calls.push_back(CI);
113     else if (StoreInst *SI = dyn_cast<StoreInst>(&*I))
114       StoredPointers.insert(SI->getOperand(1));
115     else if (LoadInst *LI = dyn_cast<LoadInst>(&*I))
116       LoadedPointers.insert(LI->getOperand(0));
117
118   if (InvokeInst *II = dyn_cast<InvokeInst>(BB.getTerminator()))
119     Invokes.push_back(II);
120 }
121
122
123 // calculatePointerInfo - Calculate information about the specified pointer.
124 LoopBodyInfo::PointerClass LoopBodyInfo::calculatePointerInfo(Value *V,
125                                                       AliasAnalysis &AA) const {
126   for (unsigned i = 0, e = Calls.size(); i != e; ++i)
127     if (AA.getModRefInfo(Calls[i], V, ~0))
128       return PointerMayStore;
129
130   for (unsigned i = 0, e = Invokes.size(); i != e; ++i)
131     if (AA.getModRefInfo(Invokes[i], V, ~0))
132       return PointerMayStore;
133
134   PointerClass Result = PointerNoStore;
135   for (std::set<Value*>::const_iterator I = StoredPointers.begin(),
136          E = StoredPointers.end(); I != E; ++I)
137     if (AA.alias(V, ~0, *I, ~0))
138       if (V == *I)
139         Result = PointerMustStore;   // If this is the only alias, return must
140       else
141         return PointerMayStore;      // We have to return may
142   return Result;
143 }
144
145 namespace {
146   struct LICM : public FunctionPass, public InstVisitor<LICM> {
147     virtual bool runOnFunction(Function &F);
148
149     /// This transformation requires natural loop information & requires that
150     /// loop preheaders be inserted into the CFG...
151     ///
152     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
153       AU.setPreservesCFG();
154       AU.addRequiredID(LoopPreheadersID);
155       AU.addRequired<LoopInfo>();
156       AU.addRequired<DominatorTree>();
157       AU.addRequired<DominanceFrontier>();
158       AU.addRequired<AliasAnalysis>();
159     }
160
161   private:
162     LoopInfo      *LI;       // Current LoopInfo
163     AliasAnalysis *AA;       // Current AliasAnalysis information
164     bool Changed;            // Set to true when we change anything.
165     BasicBlock *Preheader;   // The preheader block of the current loop...
166     Loop *CurLoop;           // The current loop we are working on...
167     LoopBodyInfo *CurLBI;    // Information about the current loop...
168
169     /// visitLoop - Hoist expressions out of the specified loop...    
170     ///
171     void visitLoop(Loop *L, LoopBodyInfo &LBI);
172
173     /// HoistRegion - Walk the specified region of the CFG (defined by all
174     /// blocks dominated by the specified block, and that are in the current
175     /// loop) in depth first order w.r.t the DominatorTree.  This allows us to
176     /// visit defintions before uses, allowing us to hoist a loop body in one
177     /// pass without iteration.
178     ///
179     void HoistRegion(DominatorTree::Node *N);
180
181     /// inSubLoop - Little predicate that returns true if the specified basic
182     /// block is in a subloop of the current one, not the current one itself.
183     ///
184     bool inSubLoop(BasicBlock *BB) {
185       assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
186       for (unsigned i = 0, e = CurLoop->getSubLoops().size(); i != e; ++i)
187         if (CurLoop->getSubLoops()[i]->contains(BB))
188           return true;  // A subloop actually contains this block!
189       return false;
190     }
191
192     /// hoist - When an instruction is found to only use loop invariant operands
193     /// that is safe to hoist, this instruction is called to do the dirty work.
194     ///
195     void hoist(Instruction &I);
196
197     /// pointerInvalidatedByLoop - Return true if the body of this loop may
198     /// store into the memory location pointed to by V.
199     /// 
200     bool pointerInvalidatedByLoop(Value *V) {
201       // Check to see if any of the basic blocks in CurLoop invalidate V.
202       return CurLBI->getPointerInfo(V, *AA) != LoopBodyInfo::PointerNoStore;
203     }
204
205     /// isLoopInvariant - Return true if the specified value is loop invariant
206     ///
207     inline bool isLoopInvariant(Value *V) {
208       if (Instruction *I = dyn_cast<Instruction>(V))
209         return !CurLoop->contains(I->getParent());
210       return true;  // All non-instructions are loop invariant
211     }
212
213     /// PromoteValuesInLoop - Look at the stores in the loop and promote as many
214     /// to scalars as we can.
215     ///
216     void PromoteValuesInLoop();
217
218     /// findPromotableValuesInLoop - Check the current loop for stores to
219     /// definate pointers, which are not loaded and stored through may aliases.
220     /// If these are found, create an alloca for the value, add it to the
221     /// PromotedValues list, and keep track of the mapping from value to
222     /// alloca...
223     ///
224     void findPromotableValuesInLoop(
225                    std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
226                                     std::map<Value*, AllocaInst*> &Val2AlMap);
227     
228
229     /// Instruction visitation handlers... these basically control whether or
230     /// not the specified instruction types are hoisted.
231     ///
232     friend class InstVisitor<LICM>;
233     void visitBinaryOperator(Instruction &I) {
234       if (isLoopInvariant(I.getOperand(0)) && isLoopInvariant(I.getOperand(1)))
235         hoist(I);
236     }
237     void visitCastInst(CastInst &CI) {
238       Instruction &I = (Instruction&)CI;
239       if (isLoopInvariant(I.getOperand(0))) hoist(I);
240     }
241     void visitShiftInst(ShiftInst &I) { visitBinaryOperator((Instruction&)I); }
242
243     void visitLoadInst(LoadInst &LI);
244
245     void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
246       Instruction &I = (Instruction&)GEPI;
247       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
248         if (!isLoopInvariant(I.getOperand(i))) return;
249       hoist(I);
250     }
251   };
252
253   RegisterOpt<LICM> X("licm", "Loop Invariant Code Motion");
254 }
255
256 Pass *createLICMPass() { return new LICM(); }
257
258 /// runOnFunction - For LICM, this simply traverses the loop structure of the
259 /// function, hoisting expressions out of loops if possible.
260 ///
261 bool LICM::runOnFunction(Function &) {
262   Changed = false;
263
264   // Get our Loop and Alias Analysis information...
265   LI = &getAnalysis<LoopInfo>();
266   AA = &getAnalysis<AliasAnalysis>();
267
268   // Hoist expressions out of all of the top-level loops.
269   const std::vector<Loop*> &TopLevelLoops = LI->getTopLevelLoops();
270   for (std::vector<Loop*>::const_iterator I = TopLevelLoops.begin(),
271          E = TopLevelLoops.end(); I != E; ++I) {
272     LoopBodyInfo LBI;
273     LICM::visitLoop(*I, LBI);
274   }
275   return Changed;
276 }
277
278
279 /// visitLoop - Hoist expressions out of the specified loop...    
280 ///
281 void LICM::visitLoop(Loop *L, LoopBodyInfo &LBI) {
282   // Recurse through all subloops before we process this loop...
283   for (std::vector<Loop*>::const_iterator I = L->getSubLoops().begin(),
284          E = L->getSubLoops().end(); I != E; ++I) {
285     LoopBodyInfo SubLBI;
286     LICM::visitLoop(*I, SubLBI);
287
288     // Incorporate information about the subloops into this loop...
289     LBI.incorporate(SubLBI);
290   }
291   CurLoop = L;
292   CurLBI = &LBI;
293
294   // Get the preheader block to move instructions into...
295   Preheader = L->getLoopPreheader();
296   assert(Preheader&&"Preheader insertion pass guarantees we have a preheader!");
297
298   // Loop over the body of this loop, looking for calls, invokes, and stores.
299   // Because subloops have already been incorporated into LBI, we skip blocks in
300   // subloops.
301   //
302   const std::vector<BasicBlock*> &LoopBBs = L->getBlocks();
303   for (std::vector<BasicBlock*>::const_iterator I = LoopBBs.begin(),
304          E = LoopBBs.end(); I != E; ++I)
305     if (LI->getLoopFor(*I) == L)        // Ignore blocks in subloops...
306       LBI.incorporate(**I);             // Incorporate the specified basic block
307
308   // We want to visit all of the instructions in this loop... that are not parts
309   // of our subloops (they have already had their invariants hoisted out of
310   // their loop, into this loop, so there is no need to process the BODIES of
311   // the subloops).
312   //
313   // Traverse the body of the loop in depth first order on the dominator tree so
314   // that we are guaranteed to see definitions before we see uses.  This allows
315   // us to perform the LICM transformation in one pass, without iteration.
316   //
317   HoistRegion(getAnalysis<DominatorTree>()[L->getHeader()]);
318
319   // Now that all loop invariants have been removed from the loop, promote any
320   // memory references to scalars that we can...
321   if (!DisablePromotion)
322     PromoteValuesInLoop();
323
324   // Clear out loops state information for the next iteration
325   CurLoop = 0;
326   Preheader = 0;
327 }
328
329 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
330 /// dominated by the specified block, and that are in the current loop) in depth
331 /// first order w.r.t the DominatorTree.  This allows us to visit defintions
332 /// before uses, allowing us to hoist a loop body in one pass without iteration.
333 ///
334 void LICM::HoistRegion(DominatorTree::Node *N) {
335   assert(N != 0 && "Null dominator tree node?");
336
337   // If this subregion is not in the top level loop at all, exit.
338   if (!CurLoop->contains(N->getNode())) return;
339
340   // Only need to hoist the contents of this block if it is not part of a
341   // subloop (which would already have been hoisted)
342   if (!inSubLoop(N->getNode()))
343     visit(*N->getNode());
344
345   const std::vector<DominatorTree::Node*> &Children = N->getChildren();
346   for (unsigned i = 0, e = Children.size(); i != e; ++i)
347     HoistRegion(Children[i]);
348 }
349
350
351 /// hoist - When an instruction is found to only use loop invariant operands
352 /// that is safe to hoist, this instruction is called to do the dirty work.
353 ///
354 void LICM::hoist(Instruction &Inst) {
355   DEBUG(std::cerr << "LICM hoisting to";
356         WriteAsOperand(std::cerr, Preheader, false);
357         std::cerr << ": " << Inst);
358
359   // Remove the instruction from its current basic block... but don't delete the
360   // instruction.
361   Inst.getParent()->getInstList().remove(&Inst);
362
363   // Insert the new node in Preheader, before the terminator.
364   Preheader->getInstList().insert(Preheader->getTerminator(), &Inst);
365   
366   ++NumHoisted;
367   Changed = true;
368 }
369
370
371 void LICM::visitLoadInst(LoadInst &LI) {
372   if (isLoopInvariant(LI.getOperand(0)) &&
373       !pointerInvalidatedByLoop(LI.getOperand(0))) {
374     hoist(LI);
375     ++NumHoistedLoads;
376   }
377 }
378
379 /// PromoteValuesInLoop - Try to promote memory values to scalars by sinking
380 /// stores out of the loop and moving loads to before the loop.  We do this by
381 /// looping over the stores in the loop, looking for stores to Must pointers
382 /// which are loop invariant.  We promote these memory locations to use allocas
383 /// instead.  These allocas can easily be raised to register values by the
384 /// PromoteMem2Reg functionality.
385 ///
386 void LICM::PromoteValuesInLoop() {
387   // PromotedValues - List of values that are promoted out of the loop.  Each
388   // value has an alloca instruction for it, and a cannonical version of the
389   // pointer.
390   std::vector<std::pair<AllocaInst*, Value*> > PromotedValues;
391   std::map<Value*, AllocaInst*> ValueToAllocaMap; // Map of ptr to alloca
392
393   findPromotableValuesInLoop(PromotedValues, ValueToAllocaMap);
394   if (ValueToAllocaMap.empty()) return;   // If there are values to promote...
395
396   Changed = true;
397   NumPromoted += PromotedValues.size();
398
399   // Emit a copy from the value into the alloca'd value in the loop preheader
400   TerminatorInst *LoopPredInst = Preheader->getTerminator();
401   for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
402     // Load from the memory we are promoting...
403     LoadInst *LI = new LoadInst(PromotedValues[i].second, 
404                                 PromotedValues[i].second->getName()+".promoted",
405                                 LoopPredInst);
406     // Store into the temporary alloca...
407     new StoreInst(LI, PromotedValues[i].first, LoopPredInst);
408   }
409   
410   // Scan the basic blocks in the loop, replacing uses of our pointers with
411   // uses of the allocas in question.  If we find a branch that exits the
412   // loop, make sure to put reload code into all of the successors of the
413   // loop.
414   //
415   const std::vector<BasicBlock*> &LoopBBs = CurLoop->getBlocks();
416   for (std::vector<BasicBlock*>::const_iterator I = LoopBBs.begin(),
417          E = LoopBBs.end(); I != E; ++I) {
418     // Rewrite all loads and stores in the block of the pointer...
419     for (BasicBlock::iterator II = (*I)->begin(), E = (*I)->end();
420          II != E; ++II) {
421       if (LoadInst *L = dyn_cast<LoadInst>(&*II)) {
422         std::map<Value*, AllocaInst*>::iterator
423           I = ValueToAllocaMap.find(L->getOperand(0));
424         if (I != ValueToAllocaMap.end())
425           L->setOperand(0, I->second);    // Rewrite load instruction...
426       } else if (StoreInst *S = dyn_cast<StoreInst>(&*II)) {
427         std::map<Value*, AllocaInst*>::iterator
428           I = ValueToAllocaMap.find(S->getOperand(1));
429         if (I != ValueToAllocaMap.end())
430           S->setOperand(1, I->second);    // Rewrite store instruction...
431       }
432     }
433
434     // Check to see if any successors of this block are outside of the loop.
435     // If so, we need to copy the value from the alloca back into the memory
436     // location...
437     //
438     for (succ_iterator SI = succ_begin(*I), SE = succ_end(*I); SI != SE; ++SI)
439       if (!CurLoop->contains(*SI)) {
440         // Copy all of the allocas into their memory locations...
441         BasicBlock::iterator BI = (*SI)->begin();
442         while (isa<PHINode>(*BI))
443           ++BI;             // Skip over all of the phi nodes in the block...
444         Instruction *InsertPos = BI;
445         for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
446           // Load from the alloca...
447           LoadInst *LI = new LoadInst(PromotedValues[i].first, "", InsertPos);
448           // Store into the memory we promoted...
449           new StoreInst(LI, PromotedValues[i].second, InsertPos);
450         }
451       }
452   }
453
454   // Now that we have done the deed, use the mem2reg functionality to promote
455   // all of the new allocas we just created into real SSA registers...
456   //
457   std::vector<AllocaInst*> PromotedAllocas;
458   PromotedAllocas.reserve(PromotedValues.size());
459   for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i)
460     PromotedAllocas.push_back(PromotedValues[i].first);
461   PromoteMemToReg(PromotedAllocas, getAnalysis<DominanceFrontier>(),
462                   AA->getTargetData());
463 }
464
465 /// findPromotableValuesInLoop - Check the current loop for stores to definate
466 /// pointers, which are not loaded and stored through may aliases.  If these are
467 /// found, create an alloca for the value, add it to the PromotedValues list,
468 /// and keep track of the mapping from value to alloca...
469 ///
470 void LICM::findPromotableValuesInLoop(
471                    std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
472                              std::map<Value*, AllocaInst*> &ValueToAllocaMap) {
473   Instruction *FnStart = CurLoop->getHeader()->getParent()->begin()->begin();
474
475   for (std::set<Value*>::iterator I = CurLBI->StoredPointers.begin(),
476          E = CurLBI->StoredPointers.end(); I != E; ++I) {
477     Value *V = *I;
478     if (isLoopInvariant(V) &&
479         CurLBI->getPointerInfo(V, *AA) == LoopBodyInfo::PointerMustStore) {
480
481       // Don't add a new entry for this stored pointer if it aliases something
482       // we have already processed.
483       std::map<Value*, AllocaInst*>::iterator V2AMI = 
484         ValueToAllocaMap.lower_bound(V);
485       if (V2AMI == ValueToAllocaMap.end() || V2AMI->first != V) {
486         // Check to make sure that any loads in the loop are either NO or MUST
487         // aliases.  We cannot rewrite loads that _might_ come from this memory
488         // location.
489
490         bool PointerOk = true;
491         for (std::set<Value*>::const_iterator I =CurLBI->LoadedPointers.begin(),
492                E = CurLBI->LoadedPointers.end(); PointerOk && I != E; ++I)
493           switch (AA->alias(V, ~0, *I, ~0)) {
494           case AliasAnalysis::MustAlias:
495             if (V->getType() != (*I)->getType())
496               PointerOk = false;
497             break;
498           case AliasAnalysis::MayAlias:
499             PointerOk = false;
500           case AliasAnalysis::NoAlias:
501             break;
502           }
503
504         if (PointerOk) {
505           const Type *Ty = cast<PointerType>(V->getType())->getElementType();
506           AllocaInst *AI = new AllocaInst(Ty, 0, V->getName()+".tmp", FnStart);
507           PromotedValues.push_back(std::make_pair(AI, V));
508           ValueToAllocaMap.insert(V2AMI, std::make_pair(V, AI));
509
510           DEBUG(std::cerr << "LICM: Promoting value: " << *V << "\n");
511
512           // Loop over all of the loads and stores that alias this pointer,
513           // adding them to the Value2AllocaMap as well...
514           for (std::set<Value*>::const_iterator
515                  I = CurLBI->LoadedPointers.begin(),
516                  E = CurLBI->LoadedPointers.end(); I != E; ++I)
517             if (AA->alias(V, ~0, *I, ~0) == AliasAnalysis::MustAlias)
518               ValueToAllocaMap[*I] = AI;
519
520           for (std::set<Value*>::const_iterator
521                  I = CurLBI->StoredPointers.begin(),
522                  E = CurLBI->StoredPointers.end(); I != E; ++I)
523             if (AA->alias(V, ~0, *I, ~0) == AliasAnalysis::MustAlias)
524               ValueToAllocaMap[*I] = AI;
525         }
526       }
527     }
528   }
529 }