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