friendlier error message
[oota-llvm.git] / lib / Analysis / DataStructure / Steensgaard.cpp
1 //===- Steensgaard.cpp - Context Insensitive Alias Analysis ---------------===//
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 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.
14 //
15 //===----------------------------------------------------------------------===//
16
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"
23 #include <iostream>
24 using namespace llvm;
25
26 namespace {
27   class Steens : public ModulePass, public AliasAnalysis {
28     DSGraph *ResultGraph;
29
30     EquivalenceClasses<GlobalValue*> GlobalECs;  // Always empty
31   public:
32     Steens() : ResultGraph(0) {}
33     ~Steens() {
34       releaseMyMemory();
35       assert(ResultGraph == 0 && "releaseMemory not called?");
36     }
37
38     //------------------------------------------------
39     // Implement the Pass API
40     //
41
42     // run - Build up the result graph, representing the pointer graph for the
43     // program.
44     //
45     bool runOnModule(Module &M);
46
47     virtual void releaseMyMemory() { delete ResultGraph; ResultGraph = 0; }
48
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
53     }
54
55     // print - Implement the Pass::print method...
56     void print(std::ostream &O, const Module *M) const {
57       assert(ResultGraph && "Result graph has not yet been computed!");
58       ResultGraph->writeGraphToFile(O, "steensgaards");
59     }
60
61     //------------------------------------------------
62     // Implement the AliasAnalysis API
63     //
64
65     AliasResult alias(const Value *V1, unsigned V1Size,
66                       const Value *V2, unsigned V2Size);
67
68     ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
69
70   private:
71     void ResolveFunctionCall(Function *F, const DSCallSite &Call,
72                              DSNodeHandle &RetVal);
73   };
74
75   // Register the pass...
76   RegisterOpt<Steens> X("steens-aa",
77                         "Steensgaard's alias analysis (DSGraph based)");
78
79   // Register as an implementation of AliasAnalysis
80   RegisterAnalysisGroup<AliasAnalysis, Steens> Y;
81 }
82
83 ModulePass *llvm::createSteensgaardPass() { return new Steens(); }
84
85 /// ResolveFunctionCall - Resolve the actual arguments of a call to function F
86 /// with the specified call site descriptor.  This function links the arguments
87 /// and the return value for the call site context-insensitively.
88 ///
89 void Steens::ResolveFunctionCall(Function *F, const DSCallSite &Call,
90                                  DSNodeHandle &RetVal) {
91   assert(ResultGraph != 0 && "Result graph not allocated!");
92   DSGraph::ScalarMapTy &ValMap = ResultGraph->getScalarMap();
93
94   // Handle the return value of the function...
95   if (Call.getRetVal().getNode() && RetVal.getNode())
96     RetVal.mergeWith(Call.getRetVal());
97
98   // Loop over all pointer arguments, resolving them to their provided pointers
99   unsigned PtrArgIdx = 0;
100   for (Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
101        AI != AE && PtrArgIdx < Call.getNumPtrArgs(); ++AI) {
102     DSGraph::ScalarMapTy::iterator I = ValMap.find(AI);
103     if (I != ValMap.end())    // If its a pointer argument...
104       I->second.mergeWith(Call.getPtrArg(PtrArgIdx++));
105   }
106 }
107
108
109 /// run - Build up the result graph, representing the pointer graph for the
110 /// program.
111 ///
112 bool Steens::runOnModule(Module &M) {
113   InitializeAliasAnalysis(this);
114   assert(ResultGraph == 0 && "Result graph already allocated!");
115   LocalDataStructures &LDS = getAnalysis<LocalDataStructures>();
116
117   // Create a new, empty, graph...
118   ResultGraph = new DSGraph(GlobalECs, getTargetData());
119   ResultGraph->spliceFrom(LDS.getGlobalsGraph());
120
121   // Loop over the rest of the module, merging graphs for non-external functions
122   // into this graph.
123   //
124   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
125     if (!I->isExternal())
126       ResultGraph->spliceFrom(LDS.getDSGraph(*I));
127
128   ResultGraph->removeTriviallyDeadNodes();
129
130   // FIXME: Must recalculate and use the Incomplete markers!!
131
132   // Now that we have all of the graphs inlined, we can go about eliminating
133   // call nodes...
134   //
135   std::list<DSCallSite> &Calls = ResultGraph->getAuxFunctionCalls();
136   assert(Calls.empty() && "Aux call list is already in use??");
137
138   // Start with a copy of the original call sites.
139   Calls = ResultGraph->getFunctionCalls();
140
141   for (std::list<DSCallSite>::iterator CI = Calls.begin(), E = Calls.end();
142        CI != E;) {
143     DSCallSite &CurCall = *CI++;
144
145     // Loop over the called functions, eliminating as many as possible...
146     std::vector<Function*> CallTargets;
147     if (CurCall.isDirectCall())
148       CallTargets.push_back(CurCall.getCalleeFunc());
149     else
150       CurCall.getCalleeNode()->addFullFunctionList(CallTargets);
151
152     for (unsigned c = 0; c != CallTargets.size(); ) {
153       // If we can eliminate this function call, do so!
154       Function *F = CallTargets[c];
155       if (!F->isExternal()) {
156         ResolveFunctionCall(F, CurCall, ResultGraph->getReturnNodes()[F]);
157         CallTargets[c] = CallTargets.back();
158         CallTargets.pop_back();
159       } else
160         ++c;  // Cannot eliminate this call, skip over it...
161     }
162
163     if (CallTargets.empty()) {        // Eliminated all calls?
164       std::list<DSCallSite>::iterator I = CI;
165       Calls.erase(--I);               // Remove entry
166     }
167   }
168
169   // Remove our knowledge of what the return values of the functions are, except
170   // for functions that are externally visible from this module (e.g. main).  We
171   // keep these functions so that their arguments are marked incomplete.
172   for (DSGraph::ReturnNodesTy::iterator I =
173          ResultGraph->getReturnNodes().begin(),
174          E = ResultGraph->getReturnNodes().end(); I != E; )
175     if (I->first->hasInternalLinkage())
176       ResultGraph->getReturnNodes().erase(I++);
177     else
178       ++I;
179
180   // Update the "incomplete" markers on the nodes, ignoring unknownness due to
181   // incoming arguments...
182   ResultGraph->maskIncompleteMarkers();
183   ResultGraph->markIncompleteNodes(DSGraph::IgnoreGlobals |
184                                    DSGraph::MarkFormalArgs);
185
186   // Remove any nodes that are dead after all of the merging we have done...
187   // FIXME: We should be able to disable the globals graph for steens!
188   //ResultGraph->removeDeadNodes(DSGraph::KeepUnreachableGlobals);
189
190   DEBUG(print(std::cerr, &M));
191   return false;
192 }
193
194 AliasAnalysis::AliasResult Steens::alias(const Value *V1, unsigned V1Size,
195                                          const Value *V2, unsigned V2Size) {
196   assert(ResultGraph && "Result graph has not been computed yet!");
197
198   DSGraph::ScalarMapTy &GSM = ResultGraph->getScalarMap();
199
200   DSGraph::ScalarMapTy::iterator I = GSM.find(const_cast<Value*>(V1));
201   DSGraph::ScalarMapTy::iterator J = GSM.find(const_cast<Value*>(V2));
202   if (I != GSM.end() && !I->second.isNull() &&
203       J != GSM.end() && !J->second.isNull()) {
204     DSNodeHandle &V1H = I->second;
205     DSNodeHandle &V2H = J->second;
206
207     // If at least one of the nodes is complete, we can say something about
208     // this.  If one is complete and the other isn't, then they are obviously
209     // different nodes.  If they are both complete, we can't say anything
210     // useful.
211     if (I->second.getNode()->isComplete() ||
212         J->second.getNode()->isComplete()) {
213       // If the two pointers point to different data structure graph nodes, they
214       // cannot alias!
215       if (V1H.getNode() != V2H.getNode())
216         return NoAlias;
217
218       // See if they point to different offsets...  if so, we may be able to
219       // determine that they do not alias...
220       unsigned O1 = I->second.getOffset(), O2 = J->second.getOffset();
221       if (O1 != O2) {
222         if (O2 < O1) {    // Ensure that O1 <= O2
223           std::swap(V1, V2);
224           std::swap(O1, O2);
225           std::swap(V1Size, V2Size);
226         }
227
228         if (O1+V1Size <= O2)
229           return NoAlias;
230       }
231     }
232   }
233
234   // If we cannot determine alias properties based on our graph, fall back on
235   // some other AA implementation.
236   //
237   return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
238 }
239
240 AliasAnalysis::ModRefResult
241 Steens::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
242   AliasAnalysis::ModRefResult Result = ModRef;
243
244   // Find the node in question.
245   DSGraph::ScalarMapTy &GSM = ResultGraph->getScalarMap();
246   DSGraph::ScalarMapTy::iterator I = GSM.find(P);
247
248   if (I != GSM.end() && !I->second.isNull()) {
249     DSNode *N = I->second.getNode();
250     if (N->isComplete()) {
251       // If this is a direct call to an external function, and if the pointer
252       // points to a complete node, the external function cannot modify or read
253       // the value (we know it's not passed out of the program!).
254       if (Function *F = CS.getCalledFunction())
255         if (F->isExternal())
256           return NoModRef;
257
258       // Otherwise, if the node is complete, but it is only M or R, return this.
259       // This can be useful for globals that should be marked const but are not.
260       if (!N->isModified())
261         Result = (ModRefResult)(Result & ~Mod);
262       if (!N->isRead())
263         Result = (ModRefResult)(Result & ~Ref);
264     }
265   }
266
267   return (ModRefResult)(Result & AliasAnalysis::getModRefInfo(CS, P, Size));
268 }