blob: cde80eec7879a694b111dcac9775400bbe0e5c84 [file] [log] [blame]
Chris Lattner3b04a8a2004-06-28 06:33:13 +00001//===- 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
Chris Lattnerfe98f272004-07-27 06:40:37 +000011// 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.
Chris Lattner3b04a8a2004-06-28 06:33:13 +000014//
15//===----------------------------------------------------------------------===//
16
Chris Lattner3b04a8a2004-06-28 06:33:13 +000017#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"
Chris Lattnerfe98f272004-07-27 06:40:37 +000024#include "llvm/Support/InstIterator.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000025#include "llvm/Support/CommandLine.h"
26#include "llvm/ADT/Statistic.h"
27#include "llvm/ADT/SCCIterator.h"
Chris Lattner3b04a8a2004-06-28 06:33:13 +000028#include <set>
29using namespace llvm;
30
31namespace {
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");
Chris Lattnerfe98f272004-07-27 06:40:37 +000038 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");
Chris Lattner3b04a8a2004-06-28 06:33:13 +000044
Chris Lattnerfe98f272004-07-27 06:40:37 +000045 /// 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;
Chris Lattner105d26a2004-07-27 07:46:26 +000065
66 FunctionRecord() : FunctionEffect(0) {}
Chris Lattnerfe98f272004-07-27 06:40:37 +000067 };
68
69 /// GlobalsModRef - The actual analysis pass.
Chris Lattnerb12914b2004-09-20 04:48:05 +000070 class GlobalsModRef : public ModulePass, public AliasAnalysis {
Chris Lattnerfe98f272004-07-27 06:40:37 +000071 /// NonAddressTakenGlobals - The globals that do not have their addresses
72 /// taken.
73 std::set<GlobalValue*> NonAddressTakenGlobals;
Chris Lattner3b04a8a2004-06-28 06:33:13 +000074
75 /// FunctionInfo - For each function, keep track of what globals are
76 /// modified or read.
Chris Lattnerfe98f272004-07-27 06:40:37 +000077 std::map<Function*, FunctionRecord> FunctionInfo;
Chris Lattner3b04a8a2004-06-28 06:33:13 +000078
79 public:
Chris Lattnerb12914b2004-09-20 04:48:05 +000080 bool runOnModule(Module &M) {
Chris Lattner3b04a8a2004-06-28 06:33:13 +000081 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);
Reid Spencer4a7ebfa2004-12-07 08:11:24 +000099 ModRefResult getModRefInfo(CallSite CS1, CallSite CS2) {
100 return AliasAnalysis::getModRefInfo(CS1,CS2);
101 }
Chris Lattner3b04a8a2004-06-28 06:33:13 +0000102 bool hasNoModRefInfoForCalls() const { return false; }
103
Chris Lattner0af024c2004-12-15 07:22:13 +0000104 /// getModRefBehavior - Return the behavior of the specified function if
105 /// called from the specified call site. The call site may be null in which
106 /// case the most generic behavior of this function should be returned.
107 virtual ModRefBehavior getModRefBehavior(Function *F, CallSite CS) {
Chris Lattnerfe98f272004-07-27 06:40:37 +0000108 if (FunctionRecord *FR = getFunctionInfo(F))
109 if (FR->FunctionEffect == 0)
Chris Lattner0af024c2004-12-15 07:22:13 +0000110 return DoesNotAccessMemory;
111 else if ((FR->FunctionEffect & Mod) == 0)
112 return OnlyReadsMemory;
113 return AliasAnalysis::getModRefBehavior(F, CS);
Chris Lattnerfe98f272004-07-27 06:40:37 +0000114 }
Chris Lattnerfe98f272004-07-27 06:40:37 +0000115
Chris Lattner3b04a8a2004-06-28 06:33:13 +0000116 virtual void deleteValue(Value *V);
117 virtual void copyValue(Value *From, Value *To);
118
119 private:
Chris Lattnerfe98f272004-07-27 06:40:37 +0000120 /// getFunctionInfo - Return the function info for the function, or null if
121 /// the function calls an external function (in which case we don't have
122 /// anything useful to say about it).
123 FunctionRecord *getFunctionInfo(Function *F) {
124 std::map<Function*, FunctionRecord>::iterator I = FunctionInfo.find(F);
125 if (I != FunctionInfo.end())
126 return &I->second;
127 return 0;
128 }
129
Chris Lattner3b04a8a2004-06-28 06:33:13 +0000130 void AnalyzeGlobals(Module &M);
131 void AnalyzeCallGraph(CallGraph &CG, Module &M);
Chris Lattnerfe98f272004-07-27 06:40:37 +0000132 void AnalyzeSCC(std::vector<CallGraphNode *> &SCC);
Chris Lattner3b04a8a2004-06-28 06:33:13 +0000133 bool AnalyzeUsesOfGlobal(Value *V, std::vector<Function*> &Readers,
134 std::vector<Function*> &Writers);
135 };
136
137 RegisterOpt<GlobalsModRef> X("globalsmodref-aa",
138 "Simple mod/ref analysis for globals");
139 RegisterAnalysisGroup<AliasAnalysis, GlobalsModRef> Y;
140}
141
142Pass *llvm::createGlobalsModRefPass() { return new GlobalsModRef(); }
143
144
145/// AnalyzeGlobalUses - Scan through the users of all of the internal
146/// GlobalValue's in the program. If none of them have their "Address taken"
147/// (really, their address passed to something nontrivial), record this fact,
148/// and record the functions that they are used directly in.
149void GlobalsModRef::AnalyzeGlobals(Module &M) {
150 std::vector<Function*> Readers, Writers;
151 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
152 if (I->hasInternalLinkage()) {
153 if (!AnalyzeUsesOfGlobal(I, Readers, Writers)) {
Chris Lattnerfe98f272004-07-27 06:40:37 +0000154 // Remember that we are tracking this global.
155 NonAddressTakenGlobals.insert(I);
Chris Lattner3b04a8a2004-06-28 06:33:13 +0000156 ++NumNonAddrTakenFunctions;
157 }
158 Readers.clear(); Writers.clear();
159 }
160
161 for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
Chris Lattner3b04a8a2004-06-28 06:33:13 +0000162 if (I->hasInternalLinkage()) {
163 if (!AnalyzeUsesOfGlobal(I, Readers, Writers)) {
164 // Remember that we are tracking this global, and the mod/ref fns
Chris Lattnerfe98f272004-07-27 06:40:37 +0000165 NonAddressTakenGlobals.insert(I);
166 for (unsigned i = 0, e = Readers.size(); i != e; ++i)
167 FunctionInfo[Readers[i]].GlobalInfo[I] |= Ref;
168
169 if (!I->isConstant()) // No need to keep track of writers to constants
170 for (unsigned i = 0, e = Writers.size(); i != e; ++i)
171 FunctionInfo[Writers[i]].GlobalInfo[I] |= Mod;
Chris Lattner3b04a8a2004-06-28 06:33:13 +0000172 ++NumNonAddrTakenGlobalVars;
173 }
174 Readers.clear(); Writers.clear();
175 }
176}
177
178/// AnalyzeUsesOfGlobal - Look at all of the users of the specified global value
179/// derived pointer. If this is used by anything complex (i.e., the address
180/// escapes), return true. Also, while we are at it, keep track of those
181/// functions that read and write to the value.
182bool GlobalsModRef::AnalyzeUsesOfGlobal(Value *V,
183 std::vector<Function*> &Readers,
184 std::vector<Function*> &Writers) {
Chris Lattnerfe98f272004-07-27 06:40:37 +0000185 if (!isa<PointerType>(V->getType())) return true;
Chris Lattner3b04a8a2004-06-28 06:33:13 +0000186
187 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
188 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
189 Readers.push_back(LI->getParent()->getParent());
190 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
191 if (V == SI->getOperand(0)) return true; // Storing the pointer
192 Writers.push_back(SI->getParent()->getParent());
193 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
194 if (AnalyzeUsesOfGlobal(GEP, Readers, Writers)) return true;
195 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
196 // Make sure that this is just the function being called, not that it is
197 // passing into the function.
198 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
199 if (CI->getOperand(i) == V) return true;
200 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
201 // Make sure that this is just the function being called, not that it is
202 // passing into the function.
203 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
204 if (CI->getOperand(i) == V) return true;
205 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
206 // Make sure that this is just the function being called, not that it is
207 // passing into the function.
208 for (unsigned i = 3, e = II->getNumOperands(); i != e; ++i)
209 if (II->getOperand(i) == V) return true;
210 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
211 if (CE->getOpcode() == Instruction::GetElementPtr ||
212 CE->getOpcode() == Instruction::Cast) {
213 if (AnalyzeUsesOfGlobal(CE, Readers, Writers))
214 return true;
215 } else {
216 return true;
217 }
Reid Spencere8404342004-07-18 00:18:30 +0000218 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(*UI)) {
219 if (AnalyzeUsesOfGlobal(GV, Readers, Writers)) return true;
Chris Lattner3b04a8a2004-06-28 06:33:13 +0000220 } else {
221 return true;
222 }
223 return false;
224}
225
226/// AnalyzeCallGraph - At this point, we know the functions where globals are
227/// immediately stored to and read from. Propagate this information up the call
Chris Lattnerfe98f272004-07-27 06:40:37 +0000228/// graph to all callers and compute the mod/ref info for all memory for each
229/// function.
Chris Lattner3b04a8a2004-06-28 06:33:13 +0000230void GlobalsModRef::AnalyzeCallGraph(CallGraph &CG, Module &M) {
Chris Lattner3b04a8a2004-06-28 06:33:13 +0000231 // We do a bottom-up SCC traversal of the call graph. In other words, we
232 // visit all callees before callers (leaf-first).
Chris Lattnerfe98f272004-07-27 06:40:37 +0000233 for (scc_iterator<CallGraph*> I = scc_begin(&CG), E = scc_end(&CG); I!=E; ++I)
Chris Lattner105d26a2004-07-27 07:46:26 +0000234 if ((*I).size() != 1) {
Chris Lattnerfe98f272004-07-27 06:40:37 +0000235 AnalyzeSCC(*I);
Chris Lattner105d26a2004-07-27 07:46:26 +0000236 } else if (Function *F = (*I)[0]->getFunction()) {
237 if (!F->isExternal()) {
238 // Nonexternal function.
239 AnalyzeSCC(*I);
240 } else {
241 // Otherwise external function. Handle intrinsics and other special
242 // cases here.
243 if (getAnalysis<AliasAnalysis>().doesNotAccessMemory(F))
244 // If it does not access memory, process the function, causing us to
245 // realize it doesn't do anything (the body is empty).
246 AnalyzeSCC(*I);
247 else {
248 // Otherwise, don't process it. This will cause us to conservatively
249 // assume the worst.
250 }
251 }
252 } else {
253 // Do not process the external node, assume the worst.
254 }
Chris Lattnerfe98f272004-07-27 06:40:37 +0000255}
Chris Lattner3b04a8a2004-06-28 06:33:13 +0000256
Chris Lattnerfe98f272004-07-27 06:40:37 +0000257void GlobalsModRef::AnalyzeSCC(std::vector<CallGraphNode *> &SCC) {
258 assert(!SCC.empty() && "SCC with no functions?");
259 FunctionRecord &FR = FunctionInfo[SCC[0]->getFunction()];
260
261 bool CallsExternal = false;
262 unsigned FunctionEffect = 0;
263
264 // Collect the mod/ref properties due to called functions. We only compute
265 // one mod-ref set
266 for (unsigned i = 0, e = SCC.size(); i != e && !CallsExternal; ++i)
267 for (CallGraphNode::iterator CI = SCC[i]->begin(), E = SCC[i]->end();
268 CI != E; ++CI)
269 if (Function *Callee = (*CI)->getFunction()) {
270 if (FunctionRecord *CalleeFR = getFunctionInfo(Callee)) {
271 // Propagate function effect up.
272 FunctionEffect |= CalleeFR->FunctionEffect;
273
274 // Incorporate callee's effects on globals into our info.
275 for (std::map<GlobalValue*, unsigned>::iterator GI =
276 CalleeFR->GlobalInfo.begin(), E = CalleeFR->GlobalInfo.end();
277 GI != E; ++GI)
278 FR.GlobalInfo[GI->first] |= GI->second;
279
Chris Lattner3b04a8a2004-06-28 06:33:13 +0000280 } else {
Chris Lattnerfe98f272004-07-27 06:40:37 +0000281 CallsExternal = true;
282 break;
Chris Lattner3b04a8a2004-06-28 06:33:13 +0000283 }
Chris Lattnerfe98f272004-07-27 06:40:37 +0000284 } else {
285 CallsExternal = true;
286 break;
Chris Lattner3b04a8a2004-06-28 06:33:13 +0000287 }
Chris Lattnerfe98f272004-07-27 06:40:37 +0000288
289 // If this SCC calls an external function, we can't say anything about it, so
290 // remove all SCC functions from the FunctionInfo map.
291 if (CallsExternal) {
Chris Lattner3b04a8a2004-06-28 06:33:13 +0000292 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
Chris Lattnerfe98f272004-07-27 06:40:37 +0000293 FunctionInfo.erase(SCC[i]->getFunction());
294 return;
Chris Lattner3b04a8a2004-06-28 06:33:13 +0000295 }
Chris Lattnerfe98f272004-07-27 06:40:37 +0000296
297 // Otherwise, unless we already know that this function mod/refs memory, scan
298 // the function bodies to see if there are any explicit loads or stores.
299 if (FunctionEffect != ModRef) {
300 for (unsigned i = 0, e = SCC.size(); i != e && FunctionEffect != ModRef;++i)
301 for (inst_iterator II = inst_begin(SCC[i]->getFunction()),
302 E = inst_end(SCC[i]->getFunction());
303 II != E && FunctionEffect != ModRef; ++II)
304 if (isa<LoadInst>(*II))
305 FunctionEffect |= Ref;
306 else if (isa<StoreInst>(*II))
307 FunctionEffect |= Mod;
308 }
309
310 if ((FunctionEffect & Mod) == 0)
311 ++NumReadMemFunctions;
312 if (FunctionEffect == 0)
313 ++NumNoMemFunctions;
314 FR.FunctionEffect = FunctionEffect;
315
316 // Finally, now that we know the full effect on this SCC, clone the
317 // information to each function in the SCC.
318 for (unsigned i = 1, e = SCC.size(); i != e; ++i)
319 FunctionInfo[SCC[i]->getFunction()] = FR;
Chris Lattner3b04a8a2004-06-28 06:33:13 +0000320}
321
322
323
324/// getUnderlyingObject - This traverses the use chain to figure out what object
325/// the specified value points to. If the value points to, or is derived from,
326/// a global object, return it.
327static const GlobalValue *getUnderlyingObject(const Value *V) {
Chris Lattnerfe98f272004-07-27 06:40:37 +0000328 if (!isa<PointerType>(V->getType())) return 0;
Chris Lattner3b04a8a2004-06-28 06:33:13 +0000329
330 // If we are at some type of object... return it.
331 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
332
333 // Traverse through different addressing mechanisms...
334 if (const Instruction *I = dyn_cast<Instruction>(V)) {
335 if (isa<CastInst>(I) || isa<GetElementPtrInst>(I))
336 return getUnderlyingObject(I->getOperand(0));
337 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
338 if (CE->getOpcode() == Instruction::Cast ||
339 CE->getOpcode() == Instruction::GetElementPtr)
340 return getUnderlyingObject(CE->getOperand(0));
Chris Lattner3b04a8a2004-06-28 06:33:13 +0000341 }
342 return 0;
343}
344
345/// alias - If one of the pointers is to a global that we are tracking, and the
346/// other is some random pointer, we know there cannot be an alias, because the
347/// address of the global isn't taken.
348AliasAnalysis::AliasResult
349GlobalsModRef::alias(const Value *V1, unsigned V1Size,
350 const Value *V2, unsigned V2Size) {
351 GlobalValue *GV1 = const_cast<GlobalValue*>(getUnderlyingObject(V1));
352 GlobalValue *GV2 = const_cast<GlobalValue*>(getUnderlyingObject(V2));
353
354 // If the global's address is taken, pretend we don't know it's a pointer to
355 // the global.
356 if (GV1 && !NonAddressTakenGlobals.count(GV1)) GV1 = 0;
357 if (GV2 && !NonAddressTakenGlobals.count(GV2)) GV2 = 0;
358
359 if ((GV1 || GV2) && GV1 != GV2)
360 return NoAlias;
361
362 return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
363}
364
365AliasAnalysis::ModRefResult
366GlobalsModRef::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
367 unsigned Known = ModRef;
368
369 // If we are asking for mod/ref info of a direct call with a pointer to a
Chris Lattnerfe98f272004-07-27 06:40:37 +0000370 // global we are tracking, return information if we have it.
Chris Lattner3b04a8a2004-06-28 06:33:13 +0000371 if (GlobalValue *GV = const_cast<GlobalValue*>(getUnderlyingObject(P)))
372 if (GV->hasInternalLinkage())
Chris Lattnerfe98f272004-07-27 06:40:37 +0000373 if (Function *F = CS.getCalledFunction())
374 if (NonAddressTakenGlobals.count(GV))
375 if (FunctionRecord *FR = getFunctionInfo(F))
376 Known = FR->getInfoForGlobal(GV);
Chris Lattner3b04a8a2004-06-28 06:33:13 +0000377
378 if (Known == NoModRef)
379 return NoModRef; // No need to query other mod/ref analyses
380 return ModRefResult(Known & AliasAnalysis::getModRefInfo(CS, P, Size));
381}
382
383
384//===----------------------------------------------------------------------===//
385// Methods to update the analysis as a result of the client transformation.
386//
387void GlobalsModRef::deleteValue(Value *V) {
Chris Lattnerfe98f272004-07-27 06:40:37 +0000388 if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
389 NonAddressTakenGlobals.erase(GV);
Chris Lattner3b04a8a2004-06-28 06:33:13 +0000390}
391
392void GlobalsModRef::copyValue(Value *From, Value *To) {
Chris Lattner3b04a8a2004-06-28 06:33:13 +0000393}