Rename removeDeadNodes to removeTriviallyDeadNodes
[oota-llvm.git] / include / llvm / Analysis / DataStructure / 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 class TDDataStructures;        // A collection of td graphs for a program
28
29 //===----------------------------------------------------------------------===//
30 // DSNodeHandle - Implement a "handle" to a data structure node that takes care
31 // of all of the add/un'refing of the node to prevent the backpointers in the
32 // graph from getting out of date.
33 //
34 class DSNodeHandle {
35   DSNode *N;
36 public:
37   // Allow construction, destruction, and assignment...
38   DSNodeHandle(DSNode *n = 0) : N(0) { operator=(n); }
39   DSNodeHandle(const DSNodeHandle &H) : N(0) { operator=(H.N); }
40   ~DSNodeHandle() { operator=(0); }
41   DSNodeHandle &operator=(const DSNodeHandle &H) {operator=(H.N); return *this;}
42
43   // Assignment of DSNode*, implement all of the add/un'refing (defined later)
44   inline DSNodeHandle &operator=(DSNode *n);
45
46   // Allow automatic, implicit, conversion to DSNode*
47   operator DSNode*() { return N; }
48   operator const DSNode*() const { return N; }
49   operator bool() const { return N != 0; }
50   operator bool() { return N != 0; }
51
52   bool operator<(const DSNodeHandle &H) const {  // Allow sorting
53     return N < H.N;
54   }
55   bool operator==(const DSNodeHandle &H) const { return N == H.N; }
56   bool operator!=(const DSNodeHandle &H) const { return N != H.N; }
57   bool operator==(const DSNode *Node) const { return N == Node; }
58   bool operator!=(const DSNode *Node) const { return N != Node; }
59
60   // Allow explicit conversion to DSNode...
61   DSNode *get() { return N; }
62   const DSNode *get() const { return N; }
63
64   // Allow this to be treated like a pointer...
65   DSNode *operator->() { return N; }
66   const DSNode *operator->() const { return N; }
67 };
68
69
70 //===----------------------------------------------------------------------===//
71 // DSNode - Data structure node class
72 //
73 // This class keeps track of a node's type, and the fields in the data
74 // structure.
75 //
76 //
77 class DSNode {
78   const Type *Ty;
79   std::vector<DSNodeHandle> Links;
80   std::vector<DSNodeHandle*> Referrers;
81
82   // Globals - The list of global values that are merged into this node.
83   std::vector<GlobalValue*> Globals;
84
85   void operator=(const DSNode &); // DO NOT IMPLEMENT
86 public:
87   enum NodeTy {
88     ShadowNode = 0 << 0,   // Nothing is known about this node...
89     ScalarNode = 1 << 0,   // Scalar of the current function contains this value
90     AllocaNode = 1 << 1,   // This node was allocated with alloca
91     NewNode    = 1 << 2,   // This node was allocated with malloc
92     GlobalNode = 1 << 3,   // This node was allocated by a global var decl
93     SubElement = 1 << 4,   // This node is a part of some other node
94     CastNode   = 1 << 5,   // This node is accessed in unsafe ways
95     Incomplete = 1 << 6,   // This node may not be complete
96   };
97
98   // NodeType - A union of the above bits.  "Shadow" nodes do not add any flags
99   // to the nodes in the data structure graph, so it is possible to have nodes
100   // with a value of 0 for their NodeType.  Scalar and Alloca markers go away
101   // when function graphs are inlined.
102   //
103   unsigned char NodeType;
104
105   DSNode(enum NodeTy NT, const Type *T);
106   DSNode(const DSNode &);
107
108   ~DSNode() {
109 #ifndef NDEBUG
110     dropAllReferences();  // Only needed to satisfy assertion checks...
111 #endif
112     assert(Referrers.empty() && "Referrers to dead node exist!");
113   }
114
115   // Iterator for graph interface...
116   typedef DSNodeIterator iterator;
117   inline iterator begin();   // Defined in DataStructureGraph.h
118   inline iterator end();
119
120   // Accessors
121   const Type *getType() const { return Ty; }
122
123   unsigned getNumLinks() const { return Links.size(); }
124   DSNode *getLink(unsigned i) {
125     assert(i < getNumLinks() && "Field links access out of range...");
126     return Links[i];
127   }
128   const DSNode *getLink(unsigned i) const {
129     assert(i < getNumLinks() && "Field links access out of range...");
130     return Links[i];
131   }
132
133   void setLink(unsigned i, DSNode *N) {
134     assert(i < getNumLinks() && "Field links access out of range...");
135     Links[i] = N;
136   }
137
138   // addGlobal - Add an entry for a global value to the Globals list.  This also
139   // marks the node with the 'G' flag if it does not already have it.
140   //
141   void addGlobal(GlobalValue *GV);
142   const std::vector<GlobalValue*> &getGlobals() const { return Globals; }
143   std::vector<GlobalValue*> &getGlobals() { return Globals; }
144
145   // addEdgeTo - Add an edge from the current node to the specified node.  This
146   // can cause merging of nodes in the graph.
147   //
148   void addEdgeTo(unsigned LinkNo, DSNode *N);
149   void addEdgeTo(DSNode *N) {
150     assert(getNumLinks() == 1 && "Must specify a field number to add edge if "
151            " more than one field exists!");
152     addEdgeTo(0, N);
153   }
154
155   // mergeWith - Merge this node into the specified node, moving all links to
156   // and from the argument node into the current node.  The specified node may
157   // be a null pointer (in which case, nothing happens).
158   //
159   void mergeWith(DSNode *N);
160
161   // addReferrer - Keep the referrer set up to date...
162   void addReferrer(DSNodeHandle *H) { Referrers.push_back(H); }
163   void removeReferrer(DSNodeHandle *H);
164   const std::vector<DSNodeHandle*> &getReferrers() const { return Referrers; }
165
166   void print(std::ostream &O, const DSGraph *G) const;
167   void dump() const;
168
169   std::string getCaption(const DSGraph *G) const;
170
171   void dropAllReferences() {
172     Links.clear();
173   }
174 };
175
176
177 inline DSNodeHandle &DSNodeHandle::operator=(DSNode *n) {
178   if (N) N->removeReferrer(this);
179   N = n;
180   if (N) N->addReferrer(this);
181   return *this;
182 }
183
184
185 // DSGraph - The graph that represents a function.
186 //
187 class DSGraph {
188   Function &Func;
189   std::vector<DSNode*> Nodes;
190   DSNodeHandle RetNode;               // Node that gets returned...
191   std::map<Value*, DSNodeHandle> ValueMap;
192
193   // FunctionCalls - This vector maintains a single entry for each call
194   // instruction in the current graph.  Each call entry contains DSNodeHandles
195   // that refer to the arguments that are passed into the function call.  The
196   // first entry in the vector is the scalar that holds the return value for the
197   // call, the second is the function scalar being invoked, and the rest are
198   // pointer arguments to the function.
199   //
200   std::vector<std::vector<DSNodeHandle> > FunctionCalls;
201
202   // OrigFunctionCalls - This vector retains a copy of the original function
203   // calls of the current graph.  This is needed to support top-down inlining
204   // after bottom-up inlining is complete, since the latter deletes call nodes.
205   // 
206   std::vector<std::vector<DSNodeHandle> > OrigFunctionCalls;
207
208   // PendingCallers - This vector records all unresolved callers of the
209   // current function, i.e., ones whose graphs have not been inlined into
210   // the current graph.  As long as there are unresolved callers, the nodes
211   // for formal arguments in the current graph cannot be eliminated, and
212   // nodes in the graph reachable from the formal argument nodes or
213   // global variable nodes must be considered incomplete. 
214   std::vector<Function*> PendingCallers;
215   
216 private:
217   // Define the interface only accessable to DataStructure
218   friend class LocalDataStructures;
219   friend class BUDataStructures;
220   friend class TDDataStructures;
221   DSGraph(Function &F);            // Compute the local DSGraph
222   DSGraph(const DSGraph &DSG);     // Copy ctor
223   ~DSGraph();
224
225   // clone all the call nodes and save the copies in OrigFunctionCalls
226   void saveOrigFunctionCalls() {
227     assert(OrigFunctionCalls.size() == 0 && "Do this only once!");
228     OrigFunctionCalls = FunctionCalls;
229   }
230   
231   // get the saved copies of the original function call nodes
232   std::vector<std::vector<DSNodeHandle> > &getOrigFunctionCalls() {
233     return OrigFunctionCalls;
234   }
235
236   void operator=(const DSGraph &); // DO NOT IMPLEMENT
237 public:
238
239   Function &getFunction() const { return Func; }
240
241   // getValueMap - Get a map that describes what the nodes the scalars in this
242   // function point to...
243   //
244   std::map<Value*, DSNodeHandle> &getValueMap() { return ValueMap; }
245   const std::map<Value*, DSNodeHandle> &getValueMap() const { return ValueMap;}
246
247   std::vector<std::vector<DSNodeHandle> > &getFunctionCalls() {
248     return FunctionCalls;
249   }
250
251   const DSNode *getRetNode() const { return RetNode; }
252
253   unsigned getGraphSize() const {
254     return Nodes.size();
255   }
256
257   void print(std::ostream &O) const;
258   void dump() const;
259
260   // maskNodeTypes - Apply a mask to all of the node types in the graph.  This
261   // is useful for clearing out markers like Scalar or Incomplete.
262   //
263   void maskNodeTypes(unsigned char Mask);
264   void maskIncompleteMarkers() { maskNodeTypes(~DSNode::Incomplete); }
265
266   // markIncompleteNodes - Traverse the graph, identifying nodes that may be
267   // modified by other functions that have not been resolved yet.  This marks
268   // nodes that are reachable through three sources of "unknownness":
269   //   Global Variables, Function Calls, and Incoming Arguments
270   //
271   // For any node that may have unknown components (because something outside
272   // the scope of current analysis may have modified it), the 'Incomplete' flag
273   // is added to the NodeType.
274   //
275   void markIncompleteNodes();
276
277   // removeTriviallyDeadNodes - After the graph has been constructed, this
278   // method removes all unreachable nodes that are created because they got
279   // merged with other nodes in the graph.
280   //
281   void removeTriviallyDeadNodes();
282
283   // removeDeadNodes - Use a more powerful reachability analysis to eliminate
284   // subgraphs that are unreachable.  This often occurs because the data
285   // structure doesn't "escape" into it's caller, and thus should be eliminated
286   // from the caller's graph entirely.  This is only appropriate to use when
287   // inlining graphs.
288   //
289   void removeDeadNodes();
290
291
292   // AddCaller - add a known caller node into the graph and mark it pending.
293   // getCallers - get a vector of the functions that call this one
294   // getCallersPending - get a matching vector of bools indicating if each
295   //                     caller's DSGraph has been resolved into this one.
296   // 
297   void addCaller(Function& caller) {
298     PendingCallers.push_back(&caller);
299   }
300   std::vector<Function*>& getPendingCallers() {
301     return PendingCallers;
302   }
303   
304   // cloneInto - Clone the specified DSGraph into the current graph, returning
305   // the Return node of the graph.  The translated ValueMap for the old function
306   // is filled into the OldValMap member.  If StripLocals is set to true, Scalar
307   // and Alloca markers are removed from the graph, as the graph is being cloned
308   // into a calling function's graph.
309   //
310   DSNode *cloneInto(const DSGraph &G, std::map<Value*, DSNodeHandle> &OldValMap,
311                     std::map<const DSNode*, DSNode*>& OldNodeMap,
312                     bool StripLocals = true);
313 private:
314   bool isNodeDead(DSNode *N);
315 };
316
317
318
319 // LocalDataStructures - The analysis that computes the local data structure
320 // graphs for all of the functions in the program.
321 //
322 // FIXME: This should be a Function pass that can be USED by a Pass, and would
323 // be automatically preserved.  Until we can do that, this is a Pass.
324 //
325 class LocalDataStructures : public Pass {
326   // DSInfo, one graph for each function
327   std::map<Function*, DSGraph*> DSInfo;
328 public:
329   static AnalysisID ID;            // DataStructure Analysis ID 
330
331   LocalDataStructures(AnalysisID id) { assert(id == ID); }
332   ~LocalDataStructures() { releaseMemory(); }
333
334   virtual const char *getPassName() const {
335     return "Local Data Structure Analysis";
336   }
337
338   virtual bool run(Module &M);
339
340   // getDSGraph - Return the data structure graph for the specified function.
341   DSGraph &getDSGraph(Function &F) const {
342     std::map<Function*, DSGraph*>::const_iterator I = DSInfo.find(&F);
343     assert(I != DSInfo.end() && "Function not in module!");
344     return *I->second;
345   }
346
347   // print - Print out the analysis results...
348   void print(std::ostream &O, Module *M) const;
349
350   // If the pass pipeline is done with this pass, we can release our memory...
351   virtual void releaseMemory();
352
353   // getAnalysisUsage - This obviously provides a data structure graph.
354   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
355     AU.setPreservesAll();
356     AU.addProvided(ID);
357   }
358 };
359
360
361 // BUDataStructures - The analysis that computes the interprocedurally closed
362 // data structure graphs for all of the functions in the program.  This pass
363 // only performs a "Bottom Up" propogation (hence the name).
364 //
365 class BUDataStructures : public Pass {
366   // DSInfo, one graph for each function
367   std::map<Function*, DSGraph*> DSInfo;
368 public:
369   static AnalysisID ID;            // BUDataStructure Analysis ID 
370
371   BUDataStructures(AnalysisID id) { assert(id == ID); }
372   ~BUDataStructures() { releaseMemory(); }
373
374   virtual const char *getPassName() const {
375     return "Bottom-Up Data Structure Analysis Closure";
376   }
377
378   virtual bool run(Module &M);
379
380   // getDSGraph - Return the data structure graph for the specified function.
381   DSGraph &getDSGraph(Function &F) const {
382     std::map<Function*, DSGraph*>::const_iterator I = DSInfo.find(&F);
383     assert(I != DSInfo.end() && "Function not in module!");
384     return *I->second;
385   }
386   
387   // print - Print out the analysis results...
388   void print(std::ostream &O, Module *M) const;
389
390   // If the pass pipeline is done with this pass, we can release our memory...
391   virtual void releaseMemory();
392
393   // getAnalysisUsage - This obviously provides a data structure graph.
394   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
395     AU.setPreservesAll();
396     AU.addProvided(ID);
397     AU.addRequired(LocalDataStructures::ID);
398   }
399 private:
400   DSGraph &calculateGraph(Function &F);
401 };
402
403
404 // TDDataStructures - Analysis that computes new data structure graphs
405 // for each function using the closed graphs for the callers computed
406 // by the bottom-up pass.
407 //
408 class TDDataStructures : public Pass {
409   // DSInfo, one graph for each function
410   std::map<Function*, DSGraph*> DSInfo;
411 public:
412   static AnalysisID ID;            // TDDataStructure Analysis ID 
413
414   TDDataStructures(AnalysisID id) { assert(id == ID); }
415   ~TDDataStructures() { releaseMemory(); }
416
417   virtual const char *getPassName() const {
418     return "Top-down Data Structure Analysis Closure";
419   }
420
421   virtual bool run(Module &M);
422
423   // getDSGraph - Return the data structure graph for the specified function.
424   DSGraph &getDSGraph(Function &F) const {
425     std::map<Function*, DSGraph*>::const_iterator I = DSInfo.find(&F);
426     assert(I != DSInfo.end() && "Function not in module!");
427     return *I->second;
428   }
429
430   // print - Print out the analysis results...
431   void print(std::ostream &O, Module *M) const;
432
433   // If the pass pipeline is done with this pass, we can release our memory...
434   virtual void releaseMemory();
435
436   // getAnalysisUsage - This obviously provides a data structure graph.
437   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
438     AU.setPreservesAll();
439     AU.addProvided(ID);
440     AU.addRequired(BUDataStructures::ID);
441   }
442 private:
443   DSGraph &calculateGraph(Function &F);
444   void pushGraphIntoCallee(DSGraph &callerGraph, DSGraph &calleeGraph,
445                            std::map<Value*, DSNodeHandle> &OldValMap,
446                            std::map<const DSNode*, DSNode*> &OldNodeMap);
447 };
448 #endif