b67aaddde32c094fa7802283b96c446d8df148f1
[oota-llvm.git] / lib / Analysis / LoadValueNumbering.cpp
1 //===- LoadValueNumbering.cpp - Load Value #'ing Implementation -*- C++ -*-===//
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 file implements a value numbering pass that value numbers load and call
11 // instructions.  To do this, it finds lexically identical load instructions,
12 // and uses alias analysis to determine which loads are guaranteed to produce
13 // the same value.  To value number call instructions, it looks for calls to
14 // functions that do not write to memory which do not have intervening
15 // instructions that clobber the memory that is read from.
16 //
17 // This pass builds off of another value numbering pass to implement value
18 // numbering for non-load and non-call instructions.  It uses Alias Analysis so
19 // that it can disambiguate the load instructions.  The more powerful these base
20 // analyses are, the more powerful the resultant value numbering will be.
21 //
22 //===----------------------------------------------------------------------===//
23
24 #include "llvm/Analysis/LoadValueNumbering.h"
25 #include "llvm/Function.h"
26 #include "llvm/iMemory.h"
27 #include "llvm/iOther.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Type.h"
30 #include "llvm/Analysis/ValueNumbering.h"
31 #include "llvm/Analysis/AliasAnalysis.h"
32 #include "llvm/Analysis/Dominators.h"
33 #include "llvm/Support/CFG.h"
34 #include "llvm/Target/TargetData.h"
35 #include <set>
36 using namespace llvm;
37
38 namespace {
39   // FIXME: This should not be a FunctionPass.
40   struct LoadVN : public FunctionPass, public ValueNumbering {
41     
42     /// Pass Implementation stuff.  This doesn't do any analysis.
43     ///
44     bool runOnFunction(Function &) { return false; }
45     
46     /// getAnalysisUsage - Does not modify anything.  It uses Value Numbering
47     /// and Alias Analysis.
48     ///
49     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
50     
51     /// getEqualNumberNodes - Return nodes with the same value number as the
52     /// specified Value.  This fills in the argument vector with any equal
53     /// values.
54     ///
55     virtual void getEqualNumberNodes(Value *V1,
56                                      std::vector<Value*> &RetVals) const;
57
58     /// getCallEqualNumberNodes - Given a call instruction, find other calls
59     /// that have the same value number.
60     void getCallEqualNumberNodes(CallInst *CI,
61                                  std::vector<Value*> &RetVals) const;
62   };
63
64   // Register this pass...
65   RegisterOpt<LoadVN> X("load-vn", "Load Value Numbering");
66
67   // Declare that we implement the ValueNumbering interface
68   RegisterAnalysisGroup<ValueNumbering, LoadVN> Y;
69 }
70
71 Pass *llvm::createLoadValueNumberingPass() { return new LoadVN(); }
72
73
74 /// getAnalysisUsage - Does not modify anything.  It uses Value Numbering and
75 /// Alias Analysis.
76 ///
77 void LoadVN::getAnalysisUsage(AnalysisUsage &AU) const {
78   AU.setPreservesAll();
79   AU.addRequired<AliasAnalysis>();
80   AU.addRequired<ValueNumbering>();
81   AU.addRequired<DominatorSet>();
82   AU.addRequired<TargetData>();
83 }
84
85 static bool isPathTransparentTo(BasicBlock *CurBlock, BasicBlock *Dom,
86                                 Value *Ptr, unsigned Size, AliasAnalysis &AA,
87                                 std::set<BasicBlock*> &Visited,
88                                 std::map<BasicBlock*, bool> &TransparentBlocks){
89   // If we have already checked out this path, or if we reached our destination,
90   // stop searching, returning success.
91   if (CurBlock == Dom || !Visited.insert(CurBlock).second)
92     return true;
93   
94   // Check whether this block is known transparent or not.
95   std::map<BasicBlock*, bool>::iterator TBI =
96     TransparentBlocks.lower_bound(CurBlock);
97
98   if (TBI == TransparentBlocks.end() || TBI->first != CurBlock) {
99     // If this basic block can modify the memory location, then the path is not
100     // transparent!
101     if (AA.canBasicBlockModify(*CurBlock, Ptr, Size)) {
102       TransparentBlocks.insert(TBI, std::make_pair(CurBlock, false));
103       return false;
104     }
105       TransparentBlocks.insert(TBI, std::make_pair(CurBlock, true));
106   } else if (!TBI->second)
107     // This block is known non-transparent, so that path can't be either.
108     return false;
109   
110   // The current block is known to be transparent.  The entire path is
111   // transparent if all of the predecessors paths to the parent is also
112   // transparent to the memory location.
113   for (pred_iterator PI = pred_begin(CurBlock), E = pred_end(CurBlock);
114        PI != E; ++PI)
115     if (!isPathTransparentTo(*PI, Dom, Ptr, Size, AA, Visited,
116                              TransparentBlocks))
117       return false;
118   return true;
119 }
120
121 /// getCallEqualNumberNodes - Given a call instruction, find other calls that
122 /// have the same value number.
123 void LoadVN::getCallEqualNumberNodes(CallInst *CI,
124                                      std::vector<Value*> &RetVals) const {
125   Function *CF = CI->getCalledFunction();
126   if (CF == 0) return;  // Indirect call.
127   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
128   if (!AA.onlyReadsMemory(CF)) return;  // Nothing we can do.
129
130   // Scan all of the arguments of the function, looking for one that is not
131   // global.  In particular, we would prefer to have an argument or instruction
132   // operand to chase the def-use chains of.
133   Value *Op = CF;
134   for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
135     if (isa<Argument>(CI->getOperand(i)) ||
136         isa<Instruction>(CI->getOperand(i))) {
137       Op = CI->getOperand(i);
138       break;
139     }
140
141   // Identify all lexically identical calls in this function.
142   std::vector<CallInst*> IdenticalCalls;
143
144   Function *CIFunc = CI->getParent()->getParent();
145   for (Value::use_iterator UI = Op->use_begin(), E = Op->use_end(); UI != E;
146        ++UI)
147     if (CallInst *C = dyn_cast<CallInst>(*UI))
148       if (C->getNumOperands() == CI->getNumOperands() &&
149           C->getOperand(0) == CI->getOperand(0) &&
150           C->getParent()->getParent() == CIFunc && C != CI) {
151         bool AllOperandsEqual = true;
152         for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
153           if (C->getOperand(i) != CI->getOperand(i)) {
154             AllOperandsEqual = false;
155             break;
156           }
157
158         if (AllOperandsEqual)
159           IdenticalCalls.push_back(C);
160       }
161   
162   if (IdenticalCalls.empty()) return;
163
164   // Eliminate duplicates, which could occur if we chose a value that is passed
165   // into a call site multiple times.
166   std::sort(IdenticalCalls.begin(), IdenticalCalls.end());
167   IdenticalCalls.erase(std::unique(IdenticalCalls.begin(),IdenticalCalls.end()),
168                        IdenticalCalls.end());
169
170   // If the call reads memory, we must make sure that there are no stores
171   // between the calls in question.
172   //
173   // FIXME: This should use mod/ref information.  What we really care about it
174   // whether an intervening instruction could modify memory that is read, not
175   // ANY memory.
176   //
177   if (!AA.doesNotAccessMemory(CF)) {
178     DominatorSet &DomSetInfo = getAnalysis<DominatorSet>();
179     BasicBlock *CIBB = CI->getParent();
180     for (unsigned i = 0; i != IdenticalCalls.size(); ++i) {
181       CallInst *C = IdenticalCalls[i];
182       bool CantEqual = false;
183
184       if (DomSetInfo.dominates(CIBB, C->getParent())) {
185         // FIXME: we currently only handle the case where both calls are in the
186         // same basic block.
187         if (CIBB != C->getParent()) {
188           CantEqual = true;
189         } else {
190           Instruction *First = CI, *Second = C;
191           if (!DomSetInfo.dominates(CI, C))
192             std::swap(First, Second);
193           
194           // Scan the instructions between the calls, checking for stores or
195           // calls to dangerous functions.
196           BasicBlock::iterator I = First;
197           for (++First; I != BasicBlock::iterator(Second); ++I) {
198             if (isa<StoreInst>(I)) {
199               // FIXME: We could use mod/ref information to make this much
200               // better!
201               CantEqual = true;
202               break;
203             } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
204               if (CI->getCalledFunction() == 0 ||
205                   !AA.onlyReadsMemory(CI->getCalledFunction())) {
206                 CantEqual = true;
207                 break;
208               }
209             } else if (I->mayWriteToMemory()) {
210               CantEqual = true;
211               break;
212             }
213           }
214         }
215
216       } else if (DomSetInfo.dominates(C->getParent(), CIBB)) {
217         // FIXME: We could implement this, but we don't for now.
218         CantEqual = true;
219       } else {
220         // FIXME: if one doesn't dominate the other, we can't tell yet.
221         CantEqual = true;
222       }
223
224
225       if (CantEqual) {
226         // This call does not produce the same value as the one in the query.
227         std::swap(IdenticalCalls[i--], IdenticalCalls.back());
228         IdenticalCalls.pop_back();
229       }
230     }
231   }
232
233   // Any calls that are identical and not destroyed will produce equal values!
234   for (unsigned i = 0, e = IdenticalCalls.size(); i != e; ++i)
235     RetVals.push_back(IdenticalCalls[i]);
236 }
237
238 // getEqualNumberNodes - Return nodes with the same value number as the
239 // specified Value.  This fills in the argument vector with any equal values.
240 //
241 void LoadVN::getEqualNumberNodes(Value *V,
242                                  std::vector<Value*> &RetVals) const {
243   // If the alias analysis has any must alias information to share with us, we
244   // can definitely use it.
245   if (isa<PointerType>(V->getType()))
246     getAnalysis<AliasAnalysis>().getMustAliases(V, RetVals);
247
248   if (!isa<LoadInst>(V)) {
249     if (CallInst *CI = dyn_cast<CallInst>(V))
250       getCallEqualNumberNodes(CI, RetVals);
251
252     // Not a load instruction?  Just chain to the base value numbering
253     // implementation to satisfy the request...
254     assert(&getAnalysis<ValueNumbering>() != (ValueNumbering*)this &&
255            "getAnalysis() returned this!");
256
257     return getAnalysis<ValueNumbering>().getEqualNumberNodes(V, RetVals);
258   }
259
260   // Volatile loads cannot be replaced with the value of other loads.
261   LoadInst *LI = cast<LoadInst>(V);
262   if (LI->isVolatile())
263     return getAnalysis<ValueNumbering>().getEqualNumberNodes(V, RetVals);
264   
265   // If we have a load instruction, find all of the load and store instructions
266   // that use the same source operand.  We implement this recursively, because
267   // there could be a load of a load of a load that are all identical.  We are
268   // guaranteed that this cannot be an infinite recursion because load
269   // instructions would have to pass through a PHI node in order for there to be
270   // a cycle.  The PHI node would be handled by the else case here, breaking the
271   // infinite recursion.
272   //
273   std::vector<Value*> PointerSources;
274   getEqualNumberNodes(LI->getOperand(0), PointerSources);
275   PointerSources.push_back(LI->getOperand(0));
276   
277   BasicBlock *LoadBB = LI->getParent();
278   Function *F = LoadBB->getParent();
279   
280   // Now that we know the set of equivalent source pointers for the load
281   // instruction, look to see if there are any load or store candidates that are
282   // identical.
283   //
284   std::map<BasicBlock*, std::vector<LoadInst*> >  CandidateLoads;
285   std::map<BasicBlock*, std::vector<StoreInst*> > CandidateStores;
286   
287   while (!PointerSources.empty()) {
288     Value *Source = PointerSources.back();
289     PointerSources.pop_back();                // Get a source pointer...
290     
291     for (Value::use_iterator UI = Source->use_begin(), UE = Source->use_end();
292          UI != UE; ++UI)
293       if (LoadInst *Cand = dyn_cast<LoadInst>(*UI)) {// Is a load of source?
294         if (Cand->getParent()->getParent() == F &&   // In the same function?
295             Cand != LI && !Cand->isVolatile())       // Not LI itself?
296           CandidateLoads[Cand->getParent()].push_back(Cand);     // Got one...
297       } else if (StoreInst *Cand = dyn_cast<StoreInst>(*UI)) {
298         if (Cand->getParent()->getParent() == F && !Cand->isVolatile() &&
299             Cand->getOperand(1) == Source)  // It's a store THROUGH the ptr...
300           CandidateStores[Cand->getParent()].push_back(Cand);
301       }
302   }
303   
304   // Get alias analysis & dominators.
305   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
306   DominatorSet &DomSetInfo = getAnalysis<DominatorSet>();
307   Value *LoadPtr = LI->getOperand(0);
308   // Find out how many bytes of memory are loaded by the load instruction...
309   unsigned LoadSize = getAnalysis<TargetData>().getTypeSize(LI->getType());
310
311   // Find all of the candidate loads and stores that are in the same block as
312   // the defining instruction.
313   std::set<Instruction*> Instrs;
314   Instrs.insert(CandidateLoads[LoadBB].begin(), CandidateLoads[LoadBB].end());
315   CandidateLoads.erase(LoadBB);
316   Instrs.insert(CandidateStores[LoadBB].begin(), CandidateStores[LoadBB].end());
317   CandidateStores.erase(LoadBB);
318
319   // Figure out if the load is invalidated from the entry of the block it is in
320   // until the actual instruction.  This scans the block backwards from LI.  If
321   // we see any candidate load or store instructions, then we know that the
322   // candidates have the same value # as LI.
323   bool LoadInvalidatedInBBBefore = false;
324   for (BasicBlock::iterator I = LI; I != LoadBB->begin(); ) {
325     --I;
326     // If this instruction is a candidate load before LI, we know there are no
327     // invalidating instructions between it and LI, so they have the same value
328     // number.
329     if (isa<LoadInst>(I) && Instrs.count(I)) {
330       RetVals.push_back(I);
331       Instrs.erase(I);
332     }
333
334     if (AA.getModRefInfo(I, LoadPtr, LoadSize) & AliasAnalysis::Mod) {
335       // If the invalidating instruction is a store, and its in our candidate
336       // set, then we can do store-load forwarding: the load has the same value
337       // # as the stored value.
338       if (isa<StoreInst>(I) && Instrs.count(I)) {
339         Instrs.erase(I);
340         RetVals.push_back(I->getOperand(0));
341       }
342
343       LoadInvalidatedInBBBefore = true;
344       break;
345     }
346   }
347
348   // Figure out if the load is invalidated between the load and the exit of the
349   // block it is defined in.  While we are scanning the current basic block, if
350   // we see any candidate loads, then we know they have the same value # as LI.
351   //
352   bool LoadInvalidatedInBBAfter = false;
353   for (BasicBlock::iterator I = LI->getNext(); I != LoadBB->end(); ++I) {
354     // If this instruction is a load, then this instruction returns the same
355     // value as LI.
356     if (isa<LoadInst>(I) && Instrs.count(I)) {
357       RetVals.push_back(I);
358       Instrs.erase(I);
359     }
360
361     if (AA.getModRefInfo(I, LoadPtr, LoadSize) & AliasAnalysis::Mod) {
362       LoadInvalidatedInBBAfter = true;
363       break;
364     }
365   }
366
367   // If there is anything left in the Instrs set, it could not possibly equal
368   // LI.
369   Instrs.clear();
370
371   // TransparentBlocks - For each basic block the load/store is alive across,
372   // figure out if the pointer is invalidated or not.  If it is invalidated, the
373   // boolean is set to false, if it's not it is set to true.  If we don't know
374   // yet, the entry is not in the map.
375   std::map<BasicBlock*, bool> TransparentBlocks;
376
377   // Loop over all of the basic blocks that also load the value.  If the value
378   // is live across the CFG from the source to destination blocks, and if the
379   // value is not invalidated in either the source or destination blocks, add it
380   // to the equivalence sets.
381   for (std::map<BasicBlock*, std::vector<LoadInst*> >::iterator
382          I = CandidateLoads.begin(), E = CandidateLoads.end(); I != E; ++I) {
383     bool CantEqual = false;
384
385     // Right now we only can handle cases where one load dominates the other.
386     // FIXME: generalize this!
387     BasicBlock *BB1 = I->first, *BB2 = LoadBB;
388     if (DomSetInfo.dominates(BB1, BB2)) {
389       // The other load dominates LI.  If the loaded value is killed entering
390       // the LoadBB block, we know the load is not live.
391       if (LoadInvalidatedInBBBefore)
392         CantEqual = true;
393     } else if (DomSetInfo.dominates(BB2, BB1)) {
394       std::swap(BB1, BB2);          // Canonicalize
395       // LI dominates the other load.  If the loaded value is killed exiting
396       // the LoadBB block, we know the load is not live.
397       if (LoadInvalidatedInBBAfter)
398         CantEqual = true;
399     } else {
400       // None of these loads can VN the same.
401       CantEqual = true;
402     }
403
404     if (!CantEqual) {
405       // Ok, at this point, we know that BB1 dominates BB2, and that there is
406       // nothing in the LI block that kills the loaded value.  Check to see if
407       // the value is live across the CFG.
408       std::set<BasicBlock*> Visited;
409       for (pred_iterator PI = pred_begin(BB2), E = pred_end(BB2); PI!=E; ++PI)
410         if (!isPathTransparentTo(*PI, BB1, LoadPtr, LoadSize, AA,
411                                  Visited, TransparentBlocks)) {
412           // None of these loads can VN the same.
413           CantEqual = true;
414           break;
415         }
416     }
417
418     // If the loads can equal so far, scan the basic block that contains the
419     // loads under consideration to see if they are invalidated in the block.
420     // For any loads that are not invalidated, add them to the equivalence
421     // set!
422     if (!CantEqual) {
423       Instrs.insert(I->second.begin(), I->second.end());
424       if (BB1 == LoadBB) {
425         // If LI dominates the block in question, check to see if any of the
426         // loads in this block are invalidated before they are reached.
427         for (BasicBlock::iterator BBI = I->first->begin(); ; ++BBI) {
428           if (isa<LoadInst>(BBI) && Instrs.count(BBI)) {
429             // The load is in the set!
430             RetVals.push_back(BBI);
431             Instrs.erase(BBI);
432             if (Instrs.empty()) break;
433           } else if (AA.getModRefInfo(BBI, LoadPtr, LoadSize)
434                              & AliasAnalysis::Mod) {
435             // If there is a modifying instruction, nothing below it will value
436             // # the same.
437             break;
438           }
439         }
440       } else {
441         // If the block dominates LI, make sure that the loads in the block are
442         // not invalidated before the block ends.
443         BasicBlock::iterator BBI = I->first->end();
444         while (1) {
445           --BBI;
446           if (isa<LoadInst>(BBI) && Instrs.count(BBI)) {
447             // The load is in the set!
448             RetVals.push_back(BBI);
449             Instrs.erase(BBI);
450             if (Instrs.empty()) break;
451           } else if (AA.getModRefInfo(BBI, LoadPtr, LoadSize)
452                              & AliasAnalysis::Mod) {
453             // If there is a modifying instruction, nothing above it will value
454             // # the same.
455             break;
456           }
457         }
458       }
459
460       Instrs.clear();
461     }
462   }
463
464   // Handle candidate stores.  If the loaded location is clobbered on entrance
465   // to the LoadBB, no store outside of the LoadBB can value number equal, so
466   // quick exit.
467   if (LoadInvalidatedInBBBefore)
468     return;
469
470   for (std::map<BasicBlock*, std::vector<StoreInst*> >::iterator
471          I = CandidateStores.begin(), E = CandidateStores.end(); I != E; ++I)
472     if (DomSetInfo.dominates(I->first, LoadBB)) {
473       // Check to see if the path from the store to the load is transparent
474       // w.r.t. the memory location.
475       bool CantEqual = false;
476       std::set<BasicBlock*> Visited;
477       for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB);
478            PI != E; ++PI)
479         if (!isPathTransparentTo(*PI, I->first, LoadPtr, LoadSize, AA,
480                                  Visited, TransparentBlocks)) {
481           // None of these stores can VN the same.
482           CantEqual = true;
483           break;
484         }
485       Visited.clear();
486       if (!CantEqual) {
487         // Okay, the path from the store block to the load block is clear, and
488         // we know that there are no invalidating instructions from the start
489         // of the load block to the load itself.  Now we just scan the store
490         // block.
491
492         BasicBlock::iterator BBI = I->first->end();
493         while (1) {
494           --BBI;
495           if (AA.getModRefInfo(BBI, LoadPtr, LoadSize)& AliasAnalysis::Mod){
496             // If the invalidating instruction is one of the candidates,
497             // then it provides the value the load loads.
498             if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
499               if (std::find(I->second.begin(), I->second.end(), SI) !=
500                   I->second.end())
501                 RetVals.push_back(SI->getOperand(0));
502             break;
503           }
504         }
505       }
506     }
507 }