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