First cut at implementing bottom up analysis
[oota-llvm.git] / include / llvm / Analysis / DataStructure.h
1 //===- DataStructure.h - Build data structure graphs -------------*- C++ -*--=//
2 //
3 // Implement the LLVM data structure analysis library.
4 //
5 //===----------------------------------------------------------------------===//
6
7 #ifndef LLVM_ANALYSIS_DATA_STRUCTURE_H
8 #define LLVM_ANALYSIS_DATA_STRUCTURE_H
9
10 #include "llvm/Pass.h"
11 #include <string>
12
13 // Hack around broken gdb! stack traces from system assert don't work, but do
14 // from a fault.  :(
15 #undef assert
16 #define assert(x) \
17   do { if (!(x)) { std::cerr << "assertion failure!: " #x "\n"; \
18        int *P = 0; *P = 17; }} while (0)
19
20 class Type;
21 class GlobalValue;
22 class DSNode;                  // Each node in the graph
23 class DSGraph;                 // A graph for a function
24 class DSNodeIterator;          // Data structure graph traversal iterator
25 class LocalDataStructures;     // A collection of local graphs for a program
26 class BUDataStructures;        // A collection of bu graphs for a program
27
28 //===----------------------------------------------------------------------===//
29 // DSNodeHandle - Implement a "handle" to a data structure node that takes care
30 // of all of the add/un'refing of the node to prevent the backpointers in the
31 // graph from getting out of date.
32 //
33 class DSNodeHandle {
34   DSNode *N;
35 public:
36   // Allow construction, destruction, and assignment...
37   DSNodeHandle(DSNode *n = 0) : N(0) { operator=(n); }
38   DSNodeHandle(const DSNodeHandle &H) : N(0) { operator=(H.N); }
39   ~DSNodeHandle() { operator=(0); }
40   DSNodeHandle &operator=(const DSNodeHandle &H) {operator=(H.N); return *this;}
41
42   // Assignment of DSNode*, implement all of the add/un'refing (defined later)
43   inline DSNodeHandle &operator=(DSNode *n);
44
45   // Allow automatic, implicit, conversion to DSNode*
46   operator DSNode*() { return N; }
47   operator const DSNode*() const { return N; }
48   operator bool() const { return N != 0; }
49   operator bool() { return N != 0; }
50
51   bool operator<(const DSNodeHandle &H) const {  // Allow sorting
52     return N < H.N;
53   }
54   bool operator==(const DSNodeHandle &H) const { return N == H.N; }
55   bool operator!=(const DSNodeHandle &H) const { return N != H.N; }
56   bool operator==(const DSNode *Node) const { return N == Node; }
57   bool operator!=(const DSNode *Node) const { return N != Node; }
58
59   // Allow explicit conversion to DSNode...
60   DSNode *get() { return N; }
61   const DSNode *get() const { return N; }
62
63   // Allow this to be treated like a pointer...
64   DSNode *operator->() { return N; }
65   const DSNode *operator->() const { return N; }
66 };
67
68
69 //===----------------------------------------------------------------------===//
70 // DSNode - Data structure node class
71 //
72 // This class keeps track of a node's type, and the fields in the data
73 // structure.
74 //
75 //
76 class DSNode {
77   const Type *Ty;
78   std::vector<DSNodeHandle> Links;
79   std::vector<DSNodeHandle*> Referrers;
80
81   // Globals - The list of global values that are merged into this node.
82   std::vector<GlobalValue*> Globals;
83
84   void operator=(const DSNode &); // DO NOT IMPLEMENT
85 public:
86   enum NodeTy {
87     ShadowNode = 0 << 0,   // Nothing is known about this node...
88     ScalarNode = 1 << 0,   // Scalar of the current function contains this value
89     AllocaNode = 1 << 1,   // This node was allocated with alloca
90     NewNode    = 1 << 2,   // This node was allocated with malloc
91     GlobalNode = 1 << 3,   // This node was allocated by a global var decl
92     SubElement = 1 << 4,   // This node is a part of some other node
93     CastNode   = 1 << 5,   // This node is accessed in unsafe ways
94     Incomplete = 1 << 6,   // This node may not be complete
95   };
96
97   // NodeType - A union of the above bits.  "Shadow" nodes do not add any flags
98   // to the nodes in the data structure graph, so it is possible to have nodes
99   // with a value of 0 for their NodeType.  Scalar and Alloca markers go away
100   // when function graphs are inlined.
101   //
102   unsigned char NodeType;
103
104   DSNode(enum NodeTy NT, const Type *T);
105   DSNode(const DSNode &);
106
107   ~DSNode() {
108 #ifndef NDEBUG
109     dropAllReferences();  // Only needed to satisfy assertion checks...
110 #endif
111     assert(Referrers.empty() && "Referrers to dead node exist!");
112   }
113
114   // Iterator for graph interface...
115   typedef DSNodeIterator iterator;
116   inline iterator begin();   // Defined in DataStructureGraph.h
117   inline iterator end();
118
119   // Accessors
120   const Type *getType() const { return Ty; }
121
122   unsigned getNumLinks() const { return Links.size(); }
123   DSNode *getLink(unsigned i) {
124     assert(i < getNumLinks() && "Field links access out of range...");
125     return Links[i];
126   }
127   const DSNode *getLink(unsigned i) const {
128     assert(i < getNumLinks() && "Field links access out of range...");
129     return Links[i];
130   }
131
132   void setLink(unsigned i, DSNode *N) {
133     assert(i < getNumLinks() && "Field links access out of range...");
134     Links[i] = N;
135   }
136
137   // addGlobal - Add an entry for a global value to the Globals list.  This also
138   // marks the node with the 'G' flag if it does not already have it.
139   //
140   void addGlobal(GlobalValue *GV);
141   const std::vector<GlobalValue*> &getGlobals() const { return Globals; }
142   std::vector<GlobalValue*> &getGlobals() { return Globals; }
143
144   // addEdgeTo - Add an edge from the current node to the specified node.  This
145   // can cause merging of nodes in the graph.
146   //
147   void addEdgeTo(unsigned LinkNo, DSNode *N);
148   void addEdgeTo(DSNode *N) {
149     assert(getNumLinks() == 1 && "Must specify a field number to add edge if "
150            " more than one field exists!");
151     addEdgeTo(0, N);
152   }
153
154   // mergeWith - Merge this node into the specified node, moving all links to
155   // and from the argument node into the current node.  The specified node may
156   // be a null pointer (in which case, nothing happens).
157   //
158   void mergeWith(DSNode *N);
159
160   // addReferrer - Keep the referrer set up to date...
161   void addReferrer(DSNodeHandle *H) { Referrers.push_back(H); }
162   void removeReferrer(DSNodeHandle *H);
163   const std::vector<DSNodeHandle*> &getReferrers() const { return Referrers; }
164
165   void print(std::ostream &O, const DSGraph *G) const;
166   void dump() const;
167
168   std::string getCaption(const DSGraph *G) const;
169
170   void dropAllReferences() {
171     Links.clear();
172   }
173 };
174
175
176 inline DSNodeHandle &DSNodeHandle::operator=(DSNode *n) {
177   if (N) N->removeReferrer(this);
178   N = n;
179   if (N) N->addReferrer(this);
180   return *this;
181 }
182
183
184 // DSGraph - The graph that represents a function.
185 //
186 class DSGraph {
187   Function &Func;
188   std::vector<DSNode*> Nodes;
189   DSNodeHandle RetNode;               // Node that gets returned...
190   std::map<Value*, DSNodeHandle> ValueMap;
191
192   // FunctionCalls - This vector maintains a single entry for each call
193   // instruction in the current graph.  Each call entry contains DSNodeHandles
194   // that refer to the arguments that are passed into the function call.  The
195   // first entry in the vector is the scalar that holds the return value for the
196   // call, the second is the function scalar being invoked, and the rest are
197   // pointer arguments to the function.
198   //
199   std::vector<std::vector<DSNodeHandle> > FunctionCalls;
200
201 private:
202   // Define the interface only accessable to DataStructure
203   friend class LocalDataStructures;
204   friend class BUDataStructures;
205   DSGraph(Function &F);            // Compute the local DSGraph
206   DSGraph(const DSGraph &DSG);     // Copy ctor
207   ~DSGraph();
208
209   void operator=(const DSGraph &); // DO NOT IMPLEMENT
210 public:
211
212   Function &getFunction() const { return Func; }
213
214   // getValueMap - Get a map that describes what the nodes the scalars in this
215   // function point to...
216   //
217   std::map<Value*, DSNodeHandle> &getValueMap() { return ValueMap; }
218   const std::map<Value*, DSNodeHandle> &getValueMap() const { return ValueMap;}
219
220   std::vector<std::vector<DSNodeHandle> > &getFunctionCalls() {
221     return FunctionCalls;
222   }
223
224   const DSNode *getRetNode() const { return RetNode; }
225
226   unsigned getGraphSize() const {
227     return Nodes.size();
228   }
229
230   void print(std::ostream &O) const;
231   void dump() const;
232
233   // maskNodeTypes - Apply a mask to all of the node types in the graph.  This
234   // is useful for clearing out markers like Scalar or Incomplete.
235   //
236   void maskNodeTypes(unsigned char Mask);
237   void maskIncompleteMarkers() { maskNodeTypes(~DSNode::Incomplete); }
238
239
240   // markIncompleteNodes - Traverse the graph, identifying nodes that may be
241   // modified by other functions that have not been resolved yet.  This marks
242   // nodes that are reachable through three sources of "unknownness":
243   //   Global Variables, Function Calls, and Incoming Arguments
244   //
245   // For any node that may have unknown components (because something outside
246   // the scope of current analysis may have modified it), the 'Incomplete' flag
247   // is added to the NodeType.
248   //
249   void markIncompleteNodes();
250
251   // removeDeadNodes - After the graph has been constructed, this method removes
252   // all unreachable nodes that are created because they got merged with other
253   // nodes in the graph.
254   //
255   void removeDeadNodes();
256
257   // cloneInto - Clone the specified DSGraph into the current graph, returning
258   // the Return node of the graph.  The translated ValueMap for the old function
259   // is filled into the OldValMap member.  If StripLocals is set to true, Scalar
260   // and Alloca markers are removed from the graph, as the graph is being cloned
261   // into a calling function's graph.
262   //
263   DSNode *cloneInto(const DSGraph &G, std::map<Value*, DSNodeHandle> &OldValMap,
264                     bool StripLocals = true);
265 private:
266   bool isNodeDead(DSNode *N);
267 };
268
269
270
271 // LocalDataStructures - The analysis that computes the local data structure
272 // graphs for all of the functions in the program.
273 //
274 // FIXME: This should be a Function pass that can be USED by a Pass, and would
275 // be automatically preserved.  Until we can do that, this is a Pass.
276 //
277 class LocalDataStructures : public Pass {
278   // DSInfo, one graph for each function
279   std::map<Function*, DSGraph*> DSInfo;
280 public:
281   static AnalysisID ID;            // DataStructure Analysis ID 
282
283   LocalDataStructures(AnalysisID id) { assert(id == ID); }
284   ~LocalDataStructures() { releaseMemory(); }
285
286   virtual const char *getPassName() const {
287     return "Local Data Structure Analysis";
288   }
289
290   virtual bool run(Module &M);
291
292   // getDSGraph - Return the data structure graph for the specified function.
293   DSGraph &getDSGraph(Function &F) const {
294     std::map<Function*, DSGraph*>::const_iterator I = DSInfo.find(&F);
295     assert(I != DSInfo.end() && "Function not in module!");
296     return *I->second;
297   }
298
299   // print - Print out the analysis results...
300   void print(std::ostream &O, Module *M) const;
301
302   // If the pass pipeline is done with this pass, we can release our memory...
303   virtual void releaseMemory();
304
305   // getAnalysisUsage - This obviously provides a data structure graph.
306   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
307     AU.setPreservesAll();
308     AU.addProvided(ID);
309   }
310 };
311
312
313 // BUDataStructures - The analysis that computes the interprocedurally closed
314 // data structure graphs for all of the functions in the program.  This pass
315 // only performs a "Bottom Up" propogation (hence the name).
316 //
317 class BUDataStructures : public Pass {
318   // DSInfo, one graph for each function
319   std::map<Function*, DSGraph*> DSInfo;
320 public:
321   static AnalysisID ID;            // BUDataStructure Analysis ID 
322
323   BUDataStructures(AnalysisID id) { assert(id == ID); }
324   ~BUDataStructures() { releaseMemory(); }
325
326   virtual const char *getPassName() const {
327     return "Bottom-Up Data Structure Analysis Closure";
328   }
329
330   virtual bool run(Module &M);
331
332   // getDSGraph - Return the data structure graph for the specified function.
333   DSGraph &getDSGraph(Function &F) const {
334     std::map<Function*, DSGraph*>::const_iterator I = DSInfo.find(&F);
335     assert(I != DSInfo.end() && "Function not in module!");
336     return *I->second;
337   }
338
339   // print - Print out the analysis results...
340   void print(std::ostream &O, Module *M) const;
341
342   // If the pass pipeline is done with this pass, we can release our memory...
343   virtual void releaseMemory();
344
345   // getAnalysisUsage - This obviously provides a data structure graph.
346   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
347     AU.setPreservesAll();
348     AU.addProvided(ID);
349     AU.addRequired(LocalDataStructures::ID);
350   }
351 private:
352   DSGraph &calculateGraph(Function &F);
353 };
354
355 #endif