1 //===- Steensgaard.cpp - Context Insensitive Alias Analysis ---------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This pass uses the data structure graphs to implement a simple context
11 // insensitive alias analysis. It does this by computing the local analysis
12 // graphs for all of the functions, then merging them together into a single big
13 // graph without cloning.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Analysis/DataStructure/DataStructure.h"
18 #include "llvm/Analysis/DataStructure/DSGraph.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Analysis/Passes.h"
21 #include "llvm/Module.h"
22 #include "llvm/Support/Debug.h"
27 class Steens : public ModulePass, public AliasAnalysis {
30 EquivalenceClasses<GlobalValue*> GlobalECs; // Always empty
32 Steens() : ResultGraph(0) {}
35 assert(ResultGraph == 0 && "releaseMemory not called?");
38 //------------------------------------------------
39 // Implement the Pass API
42 // run - Build up the result graph, representing the pointer graph for the
45 bool runOnModule(Module &M);
47 virtual void releaseMyMemory() { delete ResultGraph; ResultGraph = 0; }
49 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
50 AliasAnalysis::getAnalysisUsage(AU);
51 AU.setPreservesAll(); // Does not transform code...
52 AU.addRequired<LocalDataStructures>(); // Uses local dsgraph
55 // print - Implement the Pass::print method...
56 void print(llvm_ostream O, const Module *M) const {
57 if (O.stream()) print(*O.stream(), M);
59 void print(std::ostream &O, const Module *M) const {
60 assert(ResultGraph && "Result graph has not yet been computed!");
61 ResultGraph->writeGraphToFile(O, "steensgaards");
64 //------------------------------------------------
65 // Implement the AliasAnalysis API
68 AliasResult alias(const Value *V1, unsigned V1Size,
69 const Value *V2, unsigned V2Size);
71 virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
72 virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
75 void ResolveFunctionCall(Function *F, const DSCallSite &Call,
76 DSNodeHandle &RetVal);
79 // Register the pass...
80 RegisterPass<Steens> X("steens-aa",
81 "Steensgaard's alias analysis (DSGraph based)");
83 // Register as an implementation of AliasAnalysis
84 RegisterAnalysisGroup<AliasAnalysis> Y(X);
87 ModulePass *llvm::createSteensgaardPass() { return new Steens(); }
89 /// ResolveFunctionCall - Resolve the actual arguments of a call to function F
90 /// with the specified call site descriptor. This function links the arguments
91 /// and the return value for the call site context-insensitively.
93 void Steens::ResolveFunctionCall(Function *F, const DSCallSite &Call,
94 DSNodeHandle &RetVal) {
95 assert(ResultGraph != 0 && "Result graph not allocated!");
96 DSGraph::ScalarMapTy &ValMap = ResultGraph->getScalarMap();
98 // Handle the return value of the function...
99 if (Call.getRetVal().getNode() && RetVal.getNode())
100 RetVal.mergeWith(Call.getRetVal());
102 // Loop over all pointer arguments, resolving them to their provided pointers
103 unsigned PtrArgIdx = 0;
104 for (Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
105 AI != AE && PtrArgIdx < Call.getNumPtrArgs(); ++AI) {
106 DSGraph::ScalarMapTy::iterator I = ValMap.find(AI);
107 if (I != ValMap.end()) // If its a pointer argument...
108 I->second.mergeWith(Call.getPtrArg(PtrArgIdx++));
113 /// run - Build up the result graph, representing the pointer graph for the
116 bool Steens::runOnModule(Module &M) {
117 InitializeAliasAnalysis(this);
118 assert(ResultGraph == 0 && "Result graph already allocated!");
119 LocalDataStructures &LDS = getAnalysis<LocalDataStructures>();
121 // Create a new, empty, graph...
122 ResultGraph = new DSGraph(GlobalECs, getTargetData());
123 ResultGraph->spliceFrom(LDS.getGlobalsGraph());
125 // Loop over the rest of the module, merging graphs for non-external functions
128 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
129 if (!I->isExternal())
130 ResultGraph->spliceFrom(LDS.getDSGraph(*I));
132 ResultGraph->removeTriviallyDeadNodes();
134 // FIXME: Must recalculate and use the Incomplete markers!!
136 // Now that we have all of the graphs inlined, we can go about eliminating
139 std::list<DSCallSite> &Calls = ResultGraph->getAuxFunctionCalls();
140 assert(Calls.empty() && "Aux call list is already in use??");
142 // Start with a copy of the original call sites.
143 Calls = ResultGraph->getFunctionCalls();
145 for (std::list<DSCallSite>::iterator CI = Calls.begin(), E = Calls.end();
147 DSCallSite &CurCall = *CI++;
149 // Loop over the called functions, eliminating as many as possible...
150 std::vector<Function*> CallTargets;
151 if (CurCall.isDirectCall())
152 CallTargets.push_back(CurCall.getCalleeFunc());
154 CurCall.getCalleeNode()->addFullFunctionList(CallTargets);
156 for (unsigned c = 0; c != CallTargets.size(); ) {
157 // If we can eliminate this function call, do so!
158 Function *F = CallTargets[c];
159 if (!F->isExternal()) {
160 ResolveFunctionCall(F, CurCall, ResultGraph->getReturnNodes()[F]);
161 CallTargets[c] = CallTargets.back();
162 CallTargets.pop_back();
164 ++c; // Cannot eliminate this call, skip over it...
167 if (CallTargets.empty()) { // Eliminated all calls?
168 std::list<DSCallSite>::iterator I = CI;
169 Calls.erase(--I); // Remove entry
173 // Remove our knowledge of what the return values of the functions are, except
174 // for functions that are externally visible from this module (e.g. main). We
175 // keep these functions so that their arguments are marked incomplete.
176 for (DSGraph::ReturnNodesTy::iterator I =
177 ResultGraph->getReturnNodes().begin(),
178 E = ResultGraph->getReturnNodes().end(); I != E; )
179 if (I->first->hasInternalLinkage())
180 ResultGraph->getReturnNodes().erase(I++);
184 // Update the "incomplete" markers on the nodes, ignoring unknownness due to
185 // incoming arguments...
186 ResultGraph->maskIncompleteMarkers();
187 ResultGraph->markIncompleteNodes(DSGraph::IgnoreGlobals |
188 DSGraph::MarkFormalArgs);
190 // Remove any nodes that are dead after all of the merging we have done...
191 // FIXME: We should be able to disable the globals graph for steens!
192 //ResultGraph->removeDeadNodes(DSGraph::KeepUnreachableGlobals);
198 AliasAnalysis::AliasResult Steens::alias(const Value *V1, unsigned V1Size,
199 const Value *V2, unsigned V2Size) {
200 assert(ResultGraph && "Result graph has not been computed yet!");
202 DSGraph::ScalarMapTy &GSM = ResultGraph->getScalarMap();
204 DSGraph::ScalarMapTy::iterator I = GSM.find(const_cast<Value*>(V1));
205 DSGraph::ScalarMapTy::iterator J = GSM.find(const_cast<Value*>(V2));
206 if (I != GSM.end() && !I->second.isNull() &&
207 J != GSM.end() && !J->second.isNull()) {
208 DSNodeHandle &V1H = I->second;
209 DSNodeHandle &V2H = J->second;
211 // If at least one of the nodes is complete, we can say something about
212 // this. If one is complete and the other isn't, then they are obviously
213 // different nodes. If they are both complete, we can't say anything
215 if (I->second.getNode()->isComplete() ||
216 J->second.getNode()->isComplete()) {
217 // If the two pointers point to different data structure graph nodes, they
219 if (V1H.getNode() != V2H.getNode())
222 // See if they point to different offsets... if so, we may be able to
223 // determine that they do not alias...
224 unsigned O1 = I->second.getOffset(), O2 = J->second.getOffset();
226 if (O2 < O1) { // Ensure that O1 <= O2
229 std::swap(V1Size, V2Size);
238 // If we cannot determine alias properties based on our graph, fall back on
239 // some other AA implementation.
241 return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
244 AliasAnalysis::ModRefResult
245 Steens::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
246 AliasAnalysis::ModRefResult Result = ModRef;
248 // Find the node in question.
249 DSGraph::ScalarMapTy &GSM = ResultGraph->getScalarMap();
250 DSGraph::ScalarMapTy::iterator I = GSM.find(P);
252 if (I != GSM.end() && !I->second.isNull()) {
253 DSNode *N = I->second.getNode();
254 if (N->isComplete()) {
255 // If this is a direct call to an external function, and if the pointer
256 // points to a complete node, the external function cannot modify or read
257 // the value (we know it's not passed out of the program!).
258 if (Function *F = CS.getCalledFunction())
262 // Otherwise, if the node is complete, but it is only M or R, return this.
263 // This can be useful for globals that should be marked const but are not.
264 if (!N->isModified())
265 Result = (ModRefResult)(Result & ~Mod);
267 Result = (ModRefResult)(Result & ~Ref);
271 return (ModRefResult)(Result & AliasAnalysis::getModRefInfo(CS, P, Size));
274 AliasAnalysis::ModRefResult
275 Steens::getModRefInfo(CallSite CS1, CallSite CS2)
277 return AliasAnalysis::getModRefInfo(CS1,CS2);