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