Make error messages more useful than jsut an abort
[oota-llvm.git] / lib / Analysis / DataStructure / Steensgaard.cpp
1 //===- Steensgaard.cpp - Context Insensitive Alias Analysis ---------------===//
2 //
3 // This pass uses the data structure graphs to implement a simple context
4 // insensitive alias analysis.  It does this by computing the local analysis
5 // graphs for all of the functions, then merging them together into a single big
6 // graph without cloning.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/Analysis/DataStructure.h"
11 #include "llvm/Analysis/DSGraph.h"
12 #include "llvm/Analysis/AliasAnalysis.h"
13 #include "llvm/Module.h"
14 #include "Support/Statistic.h"
15
16 namespace {
17   class Steens : public Pass, public AliasAnalysis {
18     DSGraph *ResultGraph;
19     DSGraph *GlobalsGraph;  // FIXME: Eliminate globals graph stuff from DNE
20   public:
21     Steens() : ResultGraph(0), GlobalsGraph(0) {}
22     ~Steens() {
23       releaseMyMemory();
24       assert(ResultGraph == 0 && "releaseMemory not called?");
25     }
26
27     //------------------------------------------------
28     // Implement the Pass API
29     //
30
31     // run - Build up the result graph, representing the pointer graph for the
32     // program.
33     //
34     bool run(Module &M);
35
36     virtual void releaseMyMemory() { delete ResultGraph; ResultGraph = 0; }
37
38     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
39       AliasAnalysis::getAnalysisUsage(AU);
40       AU.setPreservesAll();                    // Does not transform code...
41       AU.addRequired<LocalDataStructures>();   // Uses local dsgraph
42       AU.addRequired<AliasAnalysis>();         // Chains to another AA impl...
43     }
44
45     // print - Implement the Pass::print method...
46     void print(std::ostream &O, const Module *M) const {
47       assert(ResultGraph && "Result graph has not yet been computed!");
48       ResultGraph->writeGraphToFile(O, "steensgaards");
49     }
50
51     //------------------------------------------------
52     // Implement the AliasAnalysis API
53     //  
54
55     // alias - This is the only method here that does anything interesting...
56     AliasResult alias(const Value *V1, unsigned V1Size,
57                       const Value *V2, unsigned V2Size);
58     
59   private:
60     void ResolveFunctionCall(Function *F, const DSCallSite &Call,
61                              DSNodeHandle &RetVal);
62   };
63
64   // Register the pass...
65   RegisterOpt<Steens> X("steens-aa",
66                         "Steensgaard's alias analysis (DSGraph based)");
67
68   // Register as an implementation of AliasAnalysis
69   RegisterAnalysisGroup<AliasAnalysis, Steens> Y;
70 }
71
72
73 /// ResolveFunctionCall - Resolve the actual arguments of a call to function F
74 /// with the specified call site descriptor.  This function links the arguments
75 /// and the return value for the call site context-insensitively.
76 ///
77 void Steens::ResolveFunctionCall(Function *F, const DSCallSite &Call,
78                                  DSNodeHandle &RetVal) {
79   assert(ResultGraph != 0 && "Result graph not allocated!");
80   hash_map<Value*, DSNodeHandle> &ValMap = ResultGraph->getScalarMap();
81
82   // Handle the return value of the function...
83   if (Call.getRetVal().getNode() && RetVal.getNode())
84     RetVal.mergeWith(Call.getRetVal());
85
86   // Loop over all pointer arguments, resolving them to their provided pointers
87   unsigned PtrArgIdx = 0;
88   for (Function::aiterator AI = F->abegin(), AE = F->aend();
89        AI != AE && PtrArgIdx < Call.getNumPtrArgs(); ++AI) {
90     hash_map<Value*, DSNodeHandle>::iterator I = ValMap.find(AI);
91     if (I != ValMap.end())    // If its a pointer argument...
92       I->second.mergeWith(Call.getPtrArg(PtrArgIdx++));
93   }
94 }
95
96
97 /// run - Build up the result graph, representing the pointer graph for the
98 /// program.
99 ///
100 bool Steens::run(Module &M) {
101   InitializeAliasAnalysis(this);
102   assert(ResultGraph == 0 && "Result graph already allocated!");
103   LocalDataStructures &LDS = getAnalysis<LocalDataStructures>();
104
105   // Create a new, empty, graph...
106   ResultGraph = new DSGraph();
107   GlobalsGraph = new DSGraph();
108   ResultGraph->setGlobalsGraph(GlobalsGraph);
109   ResultGraph->setPrintAuxCalls();
110
111   // RetValMap - Keep track of the return values for all functions that return
112   // valid pointers.
113   //
114   hash_map<Function*, DSNodeHandle> RetValMap;
115
116   // Loop over the rest of the module, merging graphs for non-external functions
117   // into this graph.
118   //
119   unsigned Count = 0;
120   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
121     if (!I->isExternal()) {
122       hash_map<Value*, DSNodeHandle> ValMap;
123       {  // Scope to free NodeMap memory ASAP
124         hash_map<const DSNode*, DSNodeHandle> NodeMap;
125         const DSGraph &FDSG = LDS.getDSGraph(*I);
126         DSNodeHandle RetNode = ResultGraph->cloneInto(FDSG, ValMap, NodeMap);
127
128         // Keep track of the return node of the function's graph if it returns a
129         // value...
130         //
131         if (RetNode.getNode())
132           RetValMap[I] = RetNode;
133       }
134
135       // Incorporate the inlined Function's ScalarMap into the global
136       // ScalarMap...
137       hash_map<Value*, DSNodeHandle> &GVM = ResultGraph->getScalarMap();
138       for (hash_map<Value*, DSNodeHandle>::iterator I = ValMap.begin(),
139              E = ValMap.end(); I != E; ++I)
140         GVM[I->first].mergeWith(I->second);
141
142       if ((++Count & 1) == 0)   // Prune nodes out every other time...
143         ResultGraph->removeTriviallyDeadNodes();
144     }
145
146   // FIXME: Must recalculate and use the Incomplete markers!!
147
148   // Now that we have all of the graphs inlined, we can go about eliminating
149   // call nodes...
150   //
151   std::vector<DSCallSite> &Calls =
152     ResultGraph->getAuxFunctionCalls();
153   assert(Calls.empty() && "Aux call list is already in use??");
154
155   // Start with a copy of the original call sites...
156   Calls = ResultGraph->getFunctionCalls();
157
158   for (unsigned i = 0; i != Calls.size(); ) {
159     DSCallSite &CurCall = Calls[i];
160     
161     // Loop over the called functions, eliminating as many as possible...
162     std::vector<GlobalValue*> CallTargets;
163     if (CurCall.isDirectCall())
164       CallTargets.push_back(CurCall.getCalleeFunc());
165     else 
166       CallTargets = CurCall.getCalleeNode()->getGlobals();
167
168     for (unsigned c = 0; c != CallTargets.size(); ) {
169       // If we can eliminate this function call, do so!
170       bool Eliminated = false;
171       if (Function *F = dyn_cast<Function>(CallTargets[c]))
172         if (!F->isExternal()) {
173           ResolveFunctionCall(F, CurCall, RetValMap[F]);
174           Eliminated = true;
175         }
176       if (Eliminated) {
177         CallTargets[c] = CallTargets.back();
178         CallTargets.pop_back();
179       } else
180         ++c;  // Cannot eliminate this call, skip over it...
181     }
182
183     if (CallTargets.empty()) {        // Eliminated all calls?
184       CurCall = Calls.back();         // Remove entry
185       Calls.pop_back();
186     } else
187       ++i;                            // Skip this call site...
188   }
189
190   RetValMap.clear();
191
192   // Update the "incomplete" markers on the nodes, ignoring unknownness due to
193   // incoming arguments...
194   ResultGraph->maskIncompleteMarkers();
195   ResultGraph->markIncompleteNodes(DSGraph::IgnoreFormalArgs);
196
197   // Remove any nodes that are dead after all of the merging we have done...
198   // FIXME: We should be able to disable the globals graph for steens!
199   ResultGraph->removeDeadNodes(DSGraph::KeepUnreachableGlobals);
200
201   DEBUG(print(std::cerr, &M));
202   return false;
203 }
204
205 // alias - This is the only method here that does anything interesting...
206 AliasAnalysis::AliasResult Steens::alias(const Value *V1, unsigned V1Size,
207                                          const Value *V2, unsigned V2Size) {
208   // FIXME: HANDLE Size argument!
209   assert(ResultGraph && "Result graph has not been computed yet!");
210
211   hash_map<Value*, DSNodeHandle> &GSM = ResultGraph->getScalarMap();
212
213   hash_map<Value*, DSNodeHandle>::iterator I = GSM.find(const_cast<Value*>(V1));
214   if (I != GSM.end() && I->second.getNode()) {
215     DSNodeHandle &V1H = I->second;
216     hash_map<Value*, DSNodeHandle>::iterator J=GSM.find(const_cast<Value*>(V2));
217     if (J != GSM.end() && J->second.getNode()) {
218       DSNodeHandle &V2H = J->second;
219       // If the two pointers point to different data structure graph nodes, they
220       // cannot alias!
221       if (V1H.getNode() != V2H.getNode())    // FIXME: Handle incompleteness!
222         return NoAlias;
223
224       // FIXME: If the two pointers point to the same node, and the offsets are
225       // different, and the LinkIndex vector doesn't alias the section, then the
226       // two pointers do not alias.  We need access size information for the two
227       // accesses though!
228       //
229     }
230   }
231
232   // If we cannot determine alias properties based on our graph, fall back on
233   // some other AA implementation.
234   //
235   return getAnalysis<AliasAnalysis>().alias(V1, V1Size, V2, V2Size);
236 }