'Pass' should now not be derived from by clients. Instead, they should derive
[oota-llvm.git] / lib / Analysis / IPA / GlobalsModRef.cpp
1 //===- GlobalsModRef.cpp - Simple Mod/Ref Analysis for Globals ------------===//
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 simple pass provides alias and mod/ref information for global values
11 // that do not have their address taken, and keeps track of whether functions
12 // read or write memory (are "pure").  For this simple (but very common) case,
13 // we can provide pretty accurate and useful information.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/Analysis/Passes.h"
18 #include "llvm/Module.h"
19 #include "llvm/Pass.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Constants.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/Analysis/CallGraph.h"
24 #include "llvm/Support/InstIterator.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/SCCIterator.h"
28 #include <set>
29 using namespace llvm;
30
31 namespace {
32   Statistic<>
33   NumNonAddrTakenGlobalVars("globalsmodref-aa",
34                             "Number of global vars without address taken");
35   Statistic<>
36   NumNonAddrTakenFunctions("globalsmodref-aa",
37                            "Number of functions without address taken");
38   Statistic<>
39   NumNoMemFunctions("globalsmodref-aa",
40                     "Number of functions that do not access memory");
41   Statistic<>
42   NumReadMemFunctions("globalsmodref-aa",
43                       "Number of functions that only read memory");
44
45   /// FunctionRecord - One instance of this structure is stored for every
46   /// function in the program.  Later, the entries for these functions are
47   /// removed if the function is found to call an external function (in which
48   /// case we know nothing about it.
49   struct FunctionRecord {
50     /// GlobalInfo - Maintain mod/ref info for all of the globals without
51     /// addresses taken that are read or written (transitively) by this
52     /// function.
53     std::map<GlobalValue*, unsigned> GlobalInfo;
54
55     unsigned getInfoForGlobal(GlobalValue *GV) const {
56       std::map<GlobalValue*, unsigned>::const_iterator I = GlobalInfo.find(GV);
57       if (I != GlobalInfo.end())
58         return I->second;
59       return 0;
60     }
61     
62     /// FunctionEffect - Capture whether or not this function reads or writes to
63     /// ANY memory.  If not, we can do a lot of aggressive analysis on it.
64     unsigned FunctionEffect;
65
66     FunctionRecord() : FunctionEffect(0) {}
67   };
68
69   /// GlobalsModRef - The actual analysis pass.
70   class GlobalsModRef : public ModulePass, public AliasAnalysis {
71     /// NonAddressTakenGlobals - The globals that do not have their addresses
72     /// taken.
73     std::set<GlobalValue*> NonAddressTakenGlobals;
74
75     /// FunctionInfo - For each function, keep track of what globals are
76     /// modified or read.
77     std::map<Function*, FunctionRecord> FunctionInfo;
78
79   public:
80     bool runOnModule(Module &M) {
81       InitializeAliasAnalysis(this);                 // set up super class
82       AnalyzeGlobals(M);                          // find non-addr taken globals
83       AnalyzeCallGraph(getAnalysis<CallGraph>(), M); // Propagate on CG
84       return false;
85     }
86
87     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
88       AliasAnalysis::getAnalysisUsage(AU);
89       AU.addRequired<CallGraph>();
90       AU.setPreservesAll();                         // Does not transform code
91     }
92
93     //------------------------------------------------
94     // Implement the AliasAnalysis API
95     //  
96     AliasResult alias(const Value *V1, unsigned V1Size,
97                       const Value *V2, unsigned V2Size);
98     ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
99     bool hasNoModRefInfoForCalls() const { return false; }
100
101     bool doesNotAccessMemory(Function *F) {
102       if (FunctionRecord *FR = getFunctionInfo(F))
103         if (FR->FunctionEffect == 0)
104           return true;
105       return AliasAnalysis::doesNotAccessMemory(F);
106     }
107     bool onlyReadsMemory(Function *F) {
108       if (FunctionRecord *FR = getFunctionInfo(F))
109         if ((FR->FunctionEffect & Mod) == 0)
110           return true;
111       return AliasAnalysis::onlyReadsMemory(F);
112     }
113
114
115     virtual void deleteValue(Value *V);
116     virtual void copyValue(Value *From, Value *To);
117
118   private:
119     /// getFunctionInfo - Return the function info for the function, or null if
120     /// the function calls an external function (in which case we don't have
121     /// anything useful to say about it).
122     FunctionRecord *getFunctionInfo(Function *F) {
123       std::map<Function*, FunctionRecord>::iterator I = FunctionInfo.find(F);
124       if (I != FunctionInfo.end())
125         return &I->second;
126       return 0;
127     }
128
129     void AnalyzeGlobals(Module &M);
130     void AnalyzeCallGraph(CallGraph &CG, Module &M);
131     void AnalyzeSCC(std::vector<CallGraphNode *> &SCC);
132     bool AnalyzeUsesOfGlobal(Value *V, std::vector<Function*> &Readers,
133                              std::vector<Function*> &Writers);
134   };
135   
136   RegisterOpt<GlobalsModRef> X("globalsmodref-aa",
137                                "Simple mod/ref analysis for globals");
138   RegisterAnalysisGroup<AliasAnalysis, GlobalsModRef> Y;
139 }
140
141 Pass *llvm::createGlobalsModRefPass() { return new GlobalsModRef(); }
142
143
144 /// AnalyzeGlobalUses - Scan through the users of all of the internal
145 /// GlobalValue's in the program.  If none of them have their "Address taken"
146 /// (really, their address passed to something nontrivial), record this fact,
147 /// and record the functions that they are used directly in.
148 void GlobalsModRef::AnalyzeGlobals(Module &M) {
149   std::vector<Function*> Readers, Writers;
150   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
151     if (I->hasInternalLinkage()) {
152       if (!AnalyzeUsesOfGlobal(I, Readers, Writers)) {
153         // Remember that we are tracking this global.
154         NonAddressTakenGlobals.insert(I);
155         ++NumNonAddrTakenFunctions;
156       }
157       Readers.clear(); Writers.clear();
158     }
159
160   for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
161     if (I->hasInternalLinkage()) {
162       if (!AnalyzeUsesOfGlobal(I, Readers, Writers)) {
163         // Remember that we are tracking this global, and the mod/ref fns
164         NonAddressTakenGlobals.insert(I);
165         for (unsigned i = 0, e = Readers.size(); i != e; ++i)
166           FunctionInfo[Readers[i]].GlobalInfo[I] |= Ref;
167
168         if (!I->isConstant())  // No need to keep track of writers to constants
169           for (unsigned i = 0, e = Writers.size(); i != e; ++i)
170             FunctionInfo[Writers[i]].GlobalInfo[I] |= Mod;
171         ++NumNonAddrTakenGlobalVars;
172       }
173       Readers.clear(); Writers.clear();
174     }
175 }
176
177 /// AnalyzeUsesOfGlobal - Look at all of the users of the specified global value
178 /// derived pointer.  If this is used by anything complex (i.e., the address
179 /// escapes), return true.  Also, while we are at it, keep track of those
180 /// functions that read and write to the value.
181 bool GlobalsModRef::AnalyzeUsesOfGlobal(Value *V,
182                                         std::vector<Function*> &Readers,
183                                         std::vector<Function*> &Writers) {
184   if (!isa<PointerType>(V->getType())) return true;
185
186   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
187     if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
188       Readers.push_back(LI->getParent()->getParent());
189     } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
190       if (V == SI->getOperand(0)) return true;  // Storing the pointer
191       Writers.push_back(SI->getParent()->getParent());
192     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
193       if (AnalyzeUsesOfGlobal(GEP, Readers, Writers)) return true;
194     } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
195       // Make sure that this is just the function being called, not that it is
196       // passing into the function.
197       for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
198         if (CI->getOperand(i) == V) return true;
199     } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
200       // Make sure that this is just the function being called, not that it is
201       // passing into the function.
202       for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
203         if (CI->getOperand(i) == V) return true;
204     } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
205       // Make sure that this is just the function being called, not that it is
206       // passing into the function.
207       for (unsigned i = 3, e = II->getNumOperands(); i != e; ++i)
208         if (II->getOperand(i) == V) return true;
209     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
210       if (CE->getOpcode() == Instruction::GetElementPtr ||
211           CE->getOpcode() == Instruction::Cast) {
212         if (AnalyzeUsesOfGlobal(CE, Readers, Writers))
213           return true;
214       } else {
215         return true;
216       }        
217     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(*UI)) {
218       if (AnalyzeUsesOfGlobal(GV, Readers, Writers)) return true;
219     } else {
220       return true;
221     }
222   return false;
223 }
224
225 /// AnalyzeCallGraph - At this point, we know the functions where globals are
226 /// immediately stored to and read from.  Propagate this information up the call
227 /// graph to all callers and compute the mod/ref info for all memory for each
228 /// function.  
229 void GlobalsModRef::AnalyzeCallGraph(CallGraph &CG, Module &M) {
230   // We do a bottom-up SCC traversal of the call graph.  In other words, we
231   // visit all callees before callers (leaf-first).
232   for (scc_iterator<CallGraph*> I = scc_begin(&CG), E = scc_end(&CG); I!=E; ++I)
233     if ((*I).size() != 1) {
234       AnalyzeSCC(*I);
235     } else if (Function *F = (*I)[0]->getFunction()) {
236       if (!F->isExternal()) {
237         // Nonexternal function.
238         AnalyzeSCC(*I);
239       } else {
240         // Otherwise external function.  Handle intrinsics and other special
241         // cases here.
242         if (getAnalysis<AliasAnalysis>().doesNotAccessMemory(F))
243           // If it does not access memory, process the function, causing us to
244           // realize it doesn't do anything (the body is empty).
245           AnalyzeSCC(*I);
246         else {
247           // Otherwise, don't process it.  This will cause us to conservatively
248           // assume the worst.
249         }
250       }
251     } else {
252       // Do not process the external node, assume the worst.
253     }
254 }
255
256 void GlobalsModRef::AnalyzeSCC(std::vector<CallGraphNode *> &SCC) {
257   assert(!SCC.empty() && "SCC with no functions?");
258   FunctionRecord &FR = FunctionInfo[SCC[0]->getFunction()];
259
260   bool CallsExternal = false;
261   unsigned FunctionEffect = 0;
262
263   // Collect the mod/ref properties due to called functions.  We only compute
264   // one mod-ref set
265   for (unsigned i = 0, e = SCC.size(); i != e && !CallsExternal; ++i)
266     for (CallGraphNode::iterator CI = SCC[i]->begin(), E = SCC[i]->end();
267          CI != E; ++CI)
268       if (Function *Callee = (*CI)->getFunction()) {
269         if (FunctionRecord *CalleeFR = getFunctionInfo(Callee)) {
270           // Propagate function effect up.
271           FunctionEffect |= CalleeFR->FunctionEffect;
272
273           // Incorporate callee's effects on globals into our info.
274           for (std::map<GlobalValue*, unsigned>::iterator GI =
275                  CalleeFR->GlobalInfo.begin(), E = CalleeFR->GlobalInfo.end();
276                GI != E; ++GI)
277             FR.GlobalInfo[GI->first] |= GI->second;
278
279         } else {
280           CallsExternal = true;
281           break;
282         }
283       } else {
284         CallsExternal = true;
285         break;
286       }
287
288   // If this SCC calls an external function, we can't say anything about it, so
289   // remove all SCC functions from the FunctionInfo map.
290   if (CallsExternal) {
291     for (unsigned i = 0, e = SCC.size(); i != e; ++i)
292       FunctionInfo.erase(SCC[i]->getFunction());
293     return;
294   }
295   
296   // Otherwise, unless we already know that this function mod/refs memory, scan
297   // the function bodies to see if there are any explicit loads or stores.
298   if (FunctionEffect != ModRef) {
299     for (unsigned i = 0, e = SCC.size(); i != e && FunctionEffect != ModRef;++i)
300       for (inst_iterator II = inst_begin(SCC[i]->getFunction()),
301              E = inst_end(SCC[i]->getFunction()); 
302            II != E && FunctionEffect != ModRef; ++II)
303         if (isa<LoadInst>(*II))
304           FunctionEffect |= Ref;
305         else if (isa<StoreInst>(*II))
306           FunctionEffect |= Mod;
307   }
308
309   if ((FunctionEffect & Mod) == 0)
310     ++NumReadMemFunctions;
311   if (FunctionEffect == 0)
312     ++NumNoMemFunctions;
313   FR.FunctionEffect = FunctionEffect;
314
315   // Finally, now that we know the full effect on this SCC, clone the
316   // information to each function in the SCC.
317   for (unsigned i = 1, e = SCC.size(); i != e; ++i)
318     FunctionInfo[SCC[i]->getFunction()] = FR;
319 }
320
321
322
323 /// getUnderlyingObject - This traverses the use chain to figure out what object
324 /// the specified value points to.  If the value points to, or is derived from,
325 /// a global object, return it.
326 static const GlobalValue *getUnderlyingObject(const Value *V) {
327   if (!isa<PointerType>(V->getType())) return 0;
328
329   // If we are at some type of object... return it.
330   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
331   
332   // Traverse through different addressing mechanisms...
333   if (const Instruction *I = dyn_cast<Instruction>(V)) {
334     if (isa<CastInst>(I) || isa<GetElementPtrInst>(I))
335       return getUnderlyingObject(I->getOperand(0));
336   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
337     if (CE->getOpcode() == Instruction::Cast ||
338         CE->getOpcode() == Instruction::GetElementPtr)
339       return getUnderlyingObject(CE->getOperand(0));
340   }
341   return 0;
342 }
343
344 /// alias - If one of the pointers is to a global that we are tracking, and the
345 /// other is some random pointer, we know there cannot be an alias, because the
346 /// address of the global isn't taken.
347 AliasAnalysis::AliasResult
348 GlobalsModRef::alias(const Value *V1, unsigned V1Size,
349                      const Value *V2, unsigned V2Size) {
350   GlobalValue *GV1 = const_cast<GlobalValue*>(getUnderlyingObject(V1));
351   GlobalValue *GV2 = const_cast<GlobalValue*>(getUnderlyingObject(V2));
352
353   // If the global's address is taken, pretend we don't know it's a pointer to
354   // the global.
355   if (GV1 && !NonAddressTakenGlobals.count(GV1)) GV1 = 0;
356   if (GV2 && !NonAddressTakenGlobals.count(GV2)) GV2 = 0;
357
358   if ((GV1 || GV2) && GV1 != GV2)
359     return NoAlias;
360
361   return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
362 }
363
364 AliasAnalysis::ModRefResult
365 GlobalsModRef::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
366   unsigned Known = ModRef;
367
368   // If we are asking for mod/ref info of a direct call with a pointer to a
369   // global we are tracking, return information if we have it.
370   if (GlobalValue *GV = const_cast<GlobalValue*>(getUnderlyingObject(P)))
371     if (GV->hasInternalLinkage())
372       if (Function *F = CS.getCalledFunction())
373         if (NonAddressTakenGlobals.count(GV))
374           if (FunctionRecord *FR = getFunctionInfo(F))
375             Known = FR->getInfoForGlobal(GV);
376
377   if (Known == NoModRef)
378     return NoModRef; // No need to query other mod/ref analyses
379   return ModRefResult(Known & AliasAnalysis::getModRefInfo(CS, P, Size));
380 }
381
382
383 //===----------------------------------------------------------------------===//
384 // Methods to update the analysis as a result of the client transformation.
385 //
386 void GlobalsModRef::deleteValue(Value *V) {
387   if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
388     NonAddressTakenGlobals.erase(GV);
389 }
390
391 void GlobalsModRef::copyValue(Value *From, Value *To) {
392 }