Abstract out the Nodes collection. Instead of providing a getNodes() method,
[oota-llvm.git] / include / llvm / Analysis / DataStructure / DSGraph.h
1 //===- DSGraph.h - Represent a collection of data structures ----*- C++ -*-===//
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 header defines the data structure graph (DSGraph) and the
11 // ReachabilityCloner class.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_ANALYSIS_DSGRAPH_H
16 #define LLVM_ANALYSIS_DSGRAPH_H
17
18 #include "llvm/Analysis/DSNode.h"
19
20 namespace llvm {
21
22 class GlobalValue;
23
24 //===----------------------------------------------------------------------===//
25 /// DSScalarMap - An instance of this class is used to keep track of all of 
26 /// which DSNode each scalar in a function points to.  This is specialized to
27 /// keep track of globals with nodes in the function, and to keep track of the 
28 /// unique DSNodeHandle being used by the scalar map.
29 ///
30 /// This class is crucial to the efficiency of DSA with some large SCC's.  In 
31 /// these cases, the cost of iterating over the scalar map dominates the cost
32 /// of DSA.  In all of these cases, the DSA phase is really trying to identify 
33 /// globals or unique node handles active in the function.
34 ///
35 class DSScalarMap {
36   typedef hash_map<Value*, DSNodeHandle> ValueMapTy;
37   ValueMapTy ValueMap;
38
39   typedef hash_set<GlobalValue*> GlobalSetTy;
40   GlobalSetTy GlobalSet;
41 public:
42
43   // Compatibility methods: provide an interface compatible with a map of 
44   // Value* to DSNodeHandle's.
45   typedef ValueMapTy::const_iterator const_iterator;
46   typedef ValueMapTy::iterator iterator;
47   iterator begin() { return ValueMap.begin(); }
48   iterator end()   { return ValueMap.end(); }
49   const_iterator begin() const { return ValueMap.begin(); }
50   const_iterator end() const { return ValueMap.end(); }
51   iterator find(Value *V) { return ValueMap.find(V); }
52   const_iterator find(Value *V) const { return ValueMap.find(V); }
53   unsigned count(Value *V) const { return ValueMap.count(V); }
54
55   void erase(Value *V) { erase(find(V)); }
56
57   DSNodeHandle &operator[](Value *V) {
58     std::pair<iterator,bool> IP = 
59       ValueMap.insert(std::make_pair(V, DSNodeHandle()));
60     if (IP.second) {  // Inserted the new entry into the map.
61       if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
62         GlobalSet.insert(GV);
63     }
64     return IP.first->second;
65   }
66
67   void erase(iterator I) { 
68     assert(I != ValueMap.end() && "Cannot erase end!");
69     if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first))
70       GlobalSet.erase(GV);
71     ValueMap.erase(I); 
72   }
73
74   void clear() {
75     ValueMap.clear();
76     GlobalSet.clear();
77   }
78
79   // Access to the global set: the set of all globals currently in the
80   // scalar map.
81   typedef GlobalSetTy::const_iterator global_iterator;
82   global_iterator global_begin() const { return GlobalSet.begin(); }
83   global_iterator global_end() const { return GlobalSet.end(); }
84 };
85
86
87 //===----------------------------------------------------------------------===//
88 /// DSGraph - The graph that represents a function.
89 ///
90 struct DSGraph {
91   // Public data-type declarations...
92   typedef DSScalarMap ScalarMapTy;
93   typedef hash_map<Function*, DSNodeHandle> ReturnNodesTy;
94   typedef hash_set<GlobalValue*> GlobalSetTy;
95   typedef std::vector<DSNode*> NodeListTy;
96
97   /// NodeMapTy - This data type is used when cloning one graph into another to
98   /// keep track of the correspondence between the nodes in the old and new
99   /// graphs.
100   typedef hash_map<const DSNode*, DSNodeHandle> NodeMapTy;
101 private:
102   DSGraph *GlobalsGraph;   // Pointer to the common graph of global objects
103   bool PrintAuxCalls;      // Should this graph print the Aux calls vector?
104
105   NodeListTy Nodes;
106   ScalarMapTy ScalarMap;
107
108   // ReturnNodes - A return value for every function merged into this graph.
109   // Each DSGraph may have multiple functions merged into it at any time, which
110   // is used for representing SCCs.
111   //
112   ReturnNodesTy ReturnNodes;
113
114   // FunctionCalls - This vector maintains a single entry for each call
115   // instruction in the current graph.  The first entry in the vector is the
116   // scalar that holds the return value for the call, the second is the function
117   // scalar being invoked, and the rest are pointer arguments to the function.
118   // This vector is built by the Local graph and is never modified after that.
119   //
120   std::vector<DSCallSite> FunctionCalls;
121
122   // AuxFunctionCalls - This vector contains call sites that have been processed
123   // by some mechanism.  In pratice, the BU Analysis uses this vector to hold
124   // the _unresolved_ call sites, because it cannot modify FunctionCalls.
125   //
126   std::vector<DSCallSite> AuxFunctionCalls;
127
128   // InlinedGlobals - This set records which globals have been inlined from
129   // other graphs (callers or callees, depending on the pass) into this one.
130   // 
131   GlobalSetTy InlinedGlobals;
132
133   /// TD - This is the target data object for the machine this graph is
134   /// constructed for.
135   const TargetData &TD;
136
137   void operator=(const DSGraph &); // DO NOT IMPLEMENT
138
139 public:
140   // Create a new, empty, DSGraph.
141   DSGraph(const TargetData &td)
142     : GlobalsGraph(0), PrintAuxCalls(false), TD(td) {}
143
144   // Compute the local DSGraph
145   DSGraph(const TargetData &td, Function &F, DSGraph *GlobalsGraph);
146
147   // Copy ctor - If you want to capture the node mapping between the source and
148   // destination graph, you may optionally do this by specifying a map to record
149   // this into.
150   //
151   // Note that a copied graph does not retain the GlobalsGraph pointer of the
152   // source.  You need to set a new GlobalsGraph with the setGlobalsGraph
153   // method.
154   //
155   DSGraph(const DSGraph &DSG);
156   DSGraph(const DSGraph &DSG, NodeMapTy &NodeMap);
157   ~DSGraph();
158
159   DSGraph *getGlobalsGraph() const { return GlobalsGraph; }
160   void setGlobalsGraph(DSGraph *G) { GlobalsGraph = G; }
161
162   /// getTargetData - Return the TargetData object for the current target.
163   ///
164   const TargetData &getTargetData() const { return TD; }
165
166   /// setPrintAuxCalls - If you call this method, the auxillary call vector will
167   /// be printed instead of the standard call vector to the dot file.
168   ///
169   void setPrintAuxCalls() { PrintAuxCalls = true; }
170   bool shouldPrintAuxCalls() const { return PrintAuxCalls; }
171
172   /// getNodes - Get a vector of all the nodes in the graph
173   /// 
174   typedef NodeListTy::const_iterator node_iterator;
175   node_iterator node_begin() const { return Nodes.begin(); }
176   node_iterator node_end()   const { return Nodes.end(); }
177
178   /// getFunctionNames - Return a space separated list of the name of the
179   /// functions in this graph (if any)
180   std::string getFunctionNames() const;
181
182   /// addNode - Add a new node to the graph.
183   ///
184   void addNode(DSNode *N) { Nodes.push_back(N); }
185
186   /// getScalarMap - Get a map that describes what the nodes the scalars in this
187   /// function point to...
188   ///
189   ScalarMapTy &getScalarMap() { return ScalarMap; }
190   const ScalarMapTy &getScalarMap() const { return ScalarMap; }
191
192   /// getFunctionCalls - Return the list of call sites in the original local
193   /// graph...
194   ///
195   const std::vector<DSCallSite> &getFunctionCalls() const {
196     return FunctionCalls;
197   }
198
199   /// getAuxFunctionCalls - Get the call sites as modified by whatever passes
200   /// have been run.
201   ///
202   std::vector<DSCallSite> &getAuxFunctionCalls() {
203     return AuxFunctionCalls;
204   }
205   const std::vector<DSCallSite> &getAuxFunctionCalls() const {
206     return AuxFunctionCalls;
207   }
208
209   /// getInlinedGlobals - Get the set of globals that are have been inlined
210   /// (from callees in BU or from callers in TD) into the current graph.
211   ///
212   GlobalSetTy& getInlinedGlobals() {
213     return InlinedGlobals;
214   }
215
216   /// getNodeForValue - Given a value that is used or defined in the body of the
217   /// current function, return the DSNode that it points to.
218   ///
219   DSNodeHandle &getNodeForValue(Value *V) { return ScalarMap[V]; }
220
221   const DSNodeHandle &getNodeForValue(Value *V) const {
222     ScalarMapTy::const_iterator I = ScalarMap.find(V);
223     assert(I != ScalarMap.end() &&
224            "Use non-const lookup function if node may not be in the map");
225     return I->second;
226   }
227
228   /// getReturnNodes - Return the mapping of functions to their return nodes for
229   /// this graph.
230   const ReturnNodesTy &getReturnNodes() const { return ReturnNodes; }
231         ReturnNodesTy &getReturnNodes()       { return ReturnNodes; }
232
233   /// getReturnNodeFor - Return the return node for the specified function.
234   ///
235   DSNodeHandle &getReturnNodeFor(Function &F) {
236     ReturnNodesTy::iterator I = ReturnNodes.find(&F);
237     assert(I != ReturnNodes.end() && "F not in this DSGraph!");
238     return I->second;
239   }
240
241   const DSNodeHandle &getReturnNodeFor(Function &F) const {
242     ReturnNodesTy::const_iterator I = ReturnNodes.find(&F);
243     assert(I != ReturnNodes.end() && "F not in this DSGraph!");
244     return I->second;
245   }
246
247   /// getGraphSize - Return the number of nodes in this graph.
248   ///
249   unsigned getGraphSize() const {
250     return Nodes.size();
251   }
252
253   /// print - Print a dot graph to the specified ostream...
254   ///
255   void print(std::ostream &O) const;
256
257   /// dump - call print(std::cerr), for use from the debugger...
258   ///
259   void dump() const;
260
261   /// viewGraph - Emit a dot graph, run 'dot', run gv on the postscript file,
262   /// then cleanup.  For use from the debugger.
263   void viewGraph() const;
264
265   void writeGraphToFile(std::ostream &O, const std::string &GraphName) const;
266
267   /// maskNodeTypes - Apply a mask to all of the node types in the graph.  This
268   /// is useful for clearing out markers like Incomplete.
269   ///
270   void maskNodeTypes(unsigned Mask) {
271     for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
272       Nodes[i]->maskNodeTypes(Mask);
273   }
274   void maskIncompleteMarkers() { maskNodeTypes(~DSNode::Incomplete); }
275
276   // markIncompleteNodes - Traverse the graph, identifying nodes that may be
277   // modified by other functions that have not been resolved yet.  This marks
278   // nodes that are reachable through three sources of "unknownness":
279   //   Global Variables, Function Calls, and Incoming Arguments
280   //
281   // For any node that may have unknown components (because something outside
282   // the scope of current analysis may have modified it), the 'Incomplete' flag
283   // is added to the NodeType.
284   //
285   enum MarkIncompleteFlags {
286     MarkFormalArgs = 1, IgnoreFormalArgs = 0,
287     IgnoreGlobals = 2, MarkGlobalsIncomplete = 0,
288   };
289   void markIncompleteNodes(unsigned Flags);
290
291   // removeDeadNodes - Use a reachability analysis to eliminate subgraphs that
292   // are unreachable.  This often occurs because the data structure doesn't
293   // "escape" into it's caller, and thus should be eliminated from the caller's
294   // graph entirely.  This is only appropriate to use when inlining graphs.
295   //
296   enum RemoveDeadNodesFlags {
297     RemoveUnreachableGlobals = 1, KeepUnreachableGlobals = 0,
298   };
299   void removeDeadNodes(unsigned Flags);
300
301   /// CloneFlags enum - Bits that may be passed into the cloneInto method to
302   /// specify how to clone the function graph.
303   enum CloneFlags {
304     StripAllocaBit        = 1 << 0, KeepAllocaBit     = 0,
305     DontCloneCallNodes    = 1 << 1, CloneCallNodes    = 0,
306     DontCloneAuxCallNodes = 1 << 2, CloneAuxCallNodes = 0,
307     StripModRefBits       = 1 << 3, KeepModRefBits    = 0,
308     StripIncompleteBit    = 1 << 4, KeepIncompleteBit = 0,
309     UpdateInlinedGlobals  = 1 << 5, DontUpdateInlinedGlobals = 0,
310   };
311
312   void updateFromGlobalGraph();
313
314   /// computeNodeMapping - Given roots in two different DSGraphs, traverse the
315   /// nodes reachable from the two graphs, computing the mapping of nodes from
316   /// the first to the second graph.
317   ///
318   static void computeNodeMapping(const DSNodeHandle &NH1,
319                                  const DSNodeHandle &NH2, NodeMapTy &NodeMap,
320                                  bool StrictChecking = true);
321
322
323   /// cloneInto - Clone the specified DSGraph into the current graph.  The
324   /// translated ScalarMap for the old function is filled into the OldValMap
325   /// member, and the translated ReturnNodes map is returned into ReturnNodes.
326   /// OldNodeMap contains a mapping from the original nodes to the newly cloned
327   /// nodes.
328   ///
329   /// The CloneFlags member controls various aspects of the cloning process.
330   ///
331   void cloneInto(const DSGraph &G, ScalarMapTy &OldValMap,
332                  ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
333                  unsigned CloneFlags = 0);
334
335   /// mergeInGraph - The method is used for merging graphs together.  If the
336   /// argument graph is not *this, it makes a clone of the specified graph, then
337   /// merges the nodes specified in the call site with the formal arguments in
338   /// the graph.  If the StripAlloca's argument is 'StripAllocaBit' then Alloca
339   /// markers are removed from nodes.
340   ///
341   void mergeInGraph(const DSCallSite &CS, Function &F, const DSGraph &Graph,
342                     unsigned CloneFlags);
343
344
345   /// getCallSiteForArguments - Get the arguments and return value bindings for
346   /// the specified function in the current graph.
347   ///
348   DSCallSite getCallSiteForArguments(Function &F) const;
349
350   // Methods for checking to make sure graphs are well formed...
351   void AssertNodeInGraph(const DSNode *N) const {
352     assert((!N || N->getParentGraph() == this) &&
353            "AssertNodeInGraph: Node is not in graph!");
354   }
355   void AssertNodeContainsGlobal(const DSNode *N, GlobalValue *GV) const {
356     assert(std::find(N->getGlobals().begin(), N->getGlobals().end(), GV) !=
357            N->getGlobals().end() && "Global value not in node!");
358   }
359
360   void AssertCallSiteInGraph(const DSCallSite &CS) const {
361     if (CS.isIndirectCall())
362       AssertNodeInGraph(CS.getCalleeNode());
363     AssertNodeInGraph(CS.getRetVal().getNode());
364     for (unsigned j = 0, e = CS.getNumPtrArgs(); j != e; ++j)
365       AssertNodeInGraph(CS.getPtrArg(j).getNode());
366   }
367
368   void AssertCallNodesInGraph() const {
369     for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
370       AssertCallSiteInGraph(FunctionCalls[i]);
371   }
372   void AssertAuxCallNodesInGraph() const {
373     for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
374       AssertCallSiteInGraph(AuxFunctionCalls[i]);
375   }
376
377   void AssertGraphOK() const;
378
379   /// removeTriviallyDeadNodes - After the graph has been constructed, this
380   /// method removes all unreachable nodes that are created because they got
381   /// merged with other nodes in the graph.  This is used as the first step of
382   /// removeDeadNodes.
383   ///
384   void removeTriviallyDeadNodes();
385 };
386
387
388   /// ReachabilityCloner - This class is used to incrementally clone and merge
389   /// nodes from a non-changing source graph into a potentially mutating
390   /// destination graph.  Nodes are only cloned over on demand, either in
391   /// responds to a merge() or getClonedNH() call.  When a node is cloned over,
392   /// all of the nodes reachable from it are automatically brought over as well.
393   class ReachabilityCloner {
394     DSGraph &Dest;
395     const DSGraph &Src;
396
397     /// BitsToKeep - These bits are retained from the source node when the
398     /// source nodes are merged into the destination graph.
399     unsigned BitsToKeep;
400     unsigned CloneFlags;
401
402     // NodeMap - A mapping from nodes in the source graph to the nodes that
403     // represent them in the destination graph.
404     DSGraph::NodeMapTy NodeMap;
405   public:
406     ReachabilityCloner(DSGraph &dest, const DSGraph &src, unsigned cloneFlags)
407       : Dest(dest), Src(src), CloneFlags(cloneFlags) {
408       assert(&Dest != &Src && "Cannot clone from graph to same graph!");
409       BitsToKeep = ~DSNode::DEAD;
410       if (CloneFlags & DSGraph::StripAllocaBit)
411         BitsToKeep &= ~DSNode::AllocaNode;
412       if (CloneFlags & DSGraph::StripModRefBits)
413         BitsToKeep &= ~(DSNode::Modified | DSNode::Read);
414       if (CloneFlags & DSGraph::StripIncompleteBit)
415         BitsToKeep &= ~DSNode::Incomplete;
416     }
417     
418     DSNodeHandle getClonedNH(const DSNodeHandle &SrcNH);
419
420     void merge(const DSNodeHandle &NH, const DSNodeHandle &SrcNH);
421
422     /// mergeCallSite - Merge the nodes reachable from the specified src call
423     /// site into the nodes reachable from DestCS.
424     void mergeCallSite(const DSCallSite &DestCS, const DSCallSite &SrcCS);
425
426     bool clonedNode() const { return !NodeMap.empty(); }
427
428     void destroy() { NodeMap.clear(); }
429   };
430 } // End llvm namespace
431
432 #endif