All DSGraphs keep a reference to the targetdata they are created with. This is
[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.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_ANALYSIS_DSGRAPH_H
15 #define LLVM_ANALYSIS_DSGRAPH_H
16
17 #include "llvm/Analysis/DSNode.h"
18 class GlobalValue;
19
20 //===----------------------------------------------------------------------===//
21 /// DSGraph - The graph that represents a function.
22 ///
23 struct DSGraph {
24   // Public data-type declarations...
25   typedef hash_map<Value*, DSNodeHandle> ScalarMapTy;
26   typedef hash_map<Function*, DSNodeHandle> ReturnNodesTy;
27   typedef hash_set<const GlobalValue*> GlobalSetTy;
28
29   /// NodeMapTy - This data type is used when cloning one graph into another to
30   /// keep track of the correspondence between the nodes in the old and new
31   /// graphs.
32   typedef hash_map<const DSNode*, DSNodeHandle> NodeMapTy;
33 private:
34   DSGraph *GlobalsGraph;   // Pointer to the common graph of global objects
35   bool PrintAuxCalls;      // Should this graph print the Aux calls vector?
36
37   std::vector<DSNode*> Nodes;
38   ScalarMapTy ScalarMap;
39
40   // ReturnNodes - A return value for every function merged into this graph.
41   // Each DSGraph may have multiple functions merged into it at any time, which
42   // is used for representing SCCs.
43   //
44   ReturnNodesTy ReturnNodes;
45
46   // FunctionCalls - This vector maintains a single entry for each call
47   // instruction in the current graph.  The first entry in the vector is the
48   // scalar that holds the return value for the call, the second is the function
49   // scalar being invoked, and the rest are pointer arguments to the function.
50   // This vector is built by the Local graph and is never modified after that.
51   //
52   std::vector<DSCallSite> FunctionCalls;
53
54   // AuxFunctionCalls - This vector contains call sites that have been processed
55   // by some mechanism.  In pratice, the BU Analysis uses this vector to hold
56   // the _unresolved_ call sites, because it cannot modify FunctionCalls.
57   //
58   std::vector<DSCallSite> AuxFunctionCalls;
59
60   // InlinedGlobals - This set records which globals have been inlined from
61   // other graphs (callers or callees, depending on the pass) into this one.
62   // 
63   GlobalSetTy InlinedGlobals;
64
65   /// TD - This is the target data object for the machine this graph is
66   /// constructed for.
67   const TargetData &TD;
68
69   void operator=(const DSGraph &); // DO NOT IMPLEMENT
70
71 public:
72   // Create a new, empty, DSGraph.
73   DSGraph(const TargetData &td)
74     : GlobalsGraph(0), PrintAuxCalls(false), TD(td) {}
75
76   // Compute the local DSGraph
77   DSGraph(const TargetData &td, Function &F, DSGraph *GlobalsGraph);
78
79   // Copy ctor - If you want to capture the node mapping between the source and
80   // destination graph, you may optionally do this by specifying a map to record
81   // this into.
82   //
83   // Note that a copied graph does not retain the GlobalsGraph pointer of the
84   // source.  You need to set a new GlobalsGraph with the setGlobalsGraph
85   // method.
86   //
87   DSGraph(const DSGraph &DSG);
88   DSGraph(const DSGraph &DSG, NodeMapTy &NodeMap);
89   ~DSGraph();
90
91   DSGraph *getGlobalsGraph() const { return GlobalsGraph; }
92   void setGlobalsGraph(DSGraph *G) { GlobalsGraph = G; }
93
94   /// getTargetData - Return the TargetData object for the current target.
95   ///
96   const TargetData &getTargetData() const { return TD; }
97
98   /// setPrintAuxCalls - If you call this method, the auxillary call vector will
99   /// be printed instead of the standard call vector to the dot file.
100   ///
101   void setPrintAuxCalls() { PrintAuxCalls = true; }
102   bool shouldPrintAuxCalls() const { return PrintAuxCalls; }
103
104   /// getNodes - Get a vector of all the nodes in the graph
105   /// 
106   const std::vector<DSNode*> &getNodes() const { return Nodes; }
107         std::vector<DSNode*> &getNodes()       { return Nodes; }
108
109   /// getFunctionNames - Return a space separated list of the name of the
110   /// functions in this graph (if any)
111   std::string getFunctionNames() const;
112
113   /// addNode - Add a new node to the graph.
114   ///
115   void addNode(DSNode *N) { Nodes.push_back(N); }
116
117   /// getScalarMap - Get a map that describes what the nodes the scalars in this
118   /// function point to...
119   ///
120   ScalarMapTy &getScalarMap() { return ScalarMap; }
121   const ScalarMapTy &getScalarMap() const { return ScalarMap; }
122
123   /// getFunctionCalls - Return the list of call sites in the original local
124   /// graph...
125   ///
126   const std::vector<DSCallSite> &getFunctionCalls() const {
127     return FunctionCalls;
128   }
129
130   /// getAuxFunctionCalls - Get the call sites as modified by whatever passes
131   /// have been run.
132   ///
133   std::vector<DSCallSite> &getAuxFunctionCalls() {
134     return AuxFunctionCalls;
135   }
136   const std::vector<DSCallSite> &getAuxFunctionCalls() const {
137     return AuxFunctionCalls;
138   }
139
140   /// getInlinedGlobals - Get the set of globals that are have been inlined
141   /// (from callees in BU or from callers in TD) into the current graph.
142   ///
143   GlobalSetTy& getInlinedGlobals() {
144     return InlinedGlobals;
145   }
146
147   /// getNodeForValue - Given a value that is used or defined in the body of the
148   /// current function, return the DSNode that it points to.
149   ///
150   DSNodeHandle &getNodeForValue(Value *V) { return ScalarMap[V]; }
151
152   const DSNodeHandle &getNodeForValue(Value *V) const {
153     ScalarMapTy::const_iterator I = ScalarMap.find(V);
154     assert(I != ScalarMap.end() &&
155            "Use non-const lookup function if node may not be in the map");
156     return I->second;
157   }
158
159   /// getReturnNodes - Return the mapping of functions to their return nodes for
160   /// this graph.
161   const ReturnNodesTy &getReturnNodes() const { return ReturnNodes; }
162         ReturnNodesTy &getReturnNodes()       { return ReturnNodes; }
163
164   /// getReturnNodeFor - Return the return node for the specified function.
165   ///
166   DSNodeHandle &getReturnNodeFor(Function &F) {
167     ReturnNodesTy::iterator I = ReturnNodes.find(&F);
168     assert(I != ReturnNodes.end() && "F not in this DSGraph!");
169     return I->second;
170   }
171
172   const DSNodeHandle &getReturnNodeFor(Function &F) const {
173     ReturnNodesTy::const_iterator I = ReturnNodes.find(&F);
174     assert(I != ReturnNodes.end() && "F not in this DSGraph!");
175     return I->second;
176   }
177
178   /// getGraphSize - Return the number of nodes in this graph.
179   ///
180   unsigned getGraphSize() const {
181     return Nodes.size();
182   }
183
184   /// print - Print a dot graph to the specified ostream...
185   ///
186   void print(std::ostream &O) const;
187
188   /// dump - call print(std::cerr), for use from the debugger...
189   ///
190   void dump() const;
191
192   /// viewGraph - Emit a dot graph, run 'dot', run gv on the postscript file,
193   /// then cleanup.  For use from the debugger.
194   void viewGraph() const;
195
196   void writeGraphToFile(std::ostream &O, const std::string &GraphName) const;
197
198   /// maskNodeTypes - Apply a mask to all of the node types in the graph.  This
199   /// is useful for clearing out markers like Incomplete.
200   ///
201   void maskNodeTypes(unsigned Mask) {
202     for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
203       Nodes[i]->maskNodeTypes(Mask);
204   }
205   void maskIncompleteMarkers() { maskNodeTypes(~DSNode::Incomplete); }
206
207   // markIncompleteNodes - Traverse the graph, identifying nodes that may be
208   // modified by other functions that have not been resolved yet.  This marks
209   // nodes that are reachable through three sources of "unknownness":
210   //   Global Variables, Function Calls, and Incoming Arguments
211   //
212   // For any node that may have unknown components (because something outside
213   // the scope of current analysis may have modified it), the 'Incomplete' flag
214   // is added to the NodeType.
215   //
216   enum MarkIncompleteFlags {
217     MarkFormalArgs = 1, IgnoreFormalArgs = 0,
218     IgnoreGlobals = 2, MarkGlobalsIncomplete = 0,
219   };
220   void markIncompleteNodes(unsigned Flags);
221
222   // removeDeadNodes - Use a reachability analysis to eliminate subgraphs that
223   // are unreachable.  This often occurs because the data structure doesn't
224   // "escape" into it's caller, and thus should be eliminated from the caller's
225   // graph entirely.  This is only appropriate to use when inlining graphs.
226   //
227   enum RemoveDeadNodesFlags {
228     RemoveUnreachableGlobals = 1, KeepUnreachableGlobals = 0,
229   };
230   void removeDeadNodes(unsigned Flags);
231
232   /// CloneFlags enum - Bits that may be passed into the cloneInto method to
233   /// specify how to clone the function graph.
234   enum CloneFlags {
235     StripAllocaBit        = 1 << 0, KeepAllocaBit     = 0,
236     DontCloneCallNodes    = 1 << 1, CloneCallNodes    = 0,
237     DontCloneAuxCallNodes = 1 << 2, CloneAuxCallNodes = 0,
238     StripModRefBits       = 1 << 3, KeepModRefBits    = 0,
239     StripIncompleteBit    = 1 << 4, KeepIncompleteBit = 0,
240   };
241
242 private:
243   void cloneReachableNodes(const DSNode*  Node,
244                            unsigned BitsToClear,
245                            NodeMapTy& OldNodeMap,
246                            NodeMapTy& CompletedNodeMap);
247
248 public:
249   void updateFromGlobalGraph();
250
251   void cloneReachableSubgraph(const DSGraph& G,
252                               const hash_set<const DSNode*>& RootNodes,
253                               NodeMapTy& OldNodeMap,
254                               NodeMapTy& CompletedNodeMap,
255                               unsigned CloneFlags = 0);
256
257   /// cloneInto - Clone the specified DSGraph into the current graph.  The
258   /// translated ScalarMap for the old function is filled into the OldValMap
259   /// member, and the translated ReturnNodes map is returned into ReturnNodes.
260   ///
261   /// The CloneFlags member controls various aspects of the cloning process.
262   ///
263   void cloneInto(const DSGraph &G, ScalarMapTy &OldValMap,
264                  ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
265                  unsigned CloneFlags = 0);
266
267   /// mergeInGraph - The method is used for merging graphs together.  If the
268   /// argument graph is not *this, it makes a clone of the specified graph, then
269   /// merges the nodes specified in the call site with the formal arguments in
270   /// the graph.  If the StripAlloca's argument is 'StripAllocaBit' then Alloca
271   /// markers are removed from nodes.
272   ///
273   void mergeInGraph(const DSCallSite &CS, Function &F, const DSGraph &Graph,
274                     unsigned CloneFlags);
275
276
277   /// getCallSiteForArguments - Get the arguments and return value bindings for
278   /// the specified function in the current graph.
279   ///
280   DSCallSite getCallSiteForArguments(Function &F) const;
281
282   // Methods for checking to make sure graphs are well formed...
283   void AssertNodeInGraph(const DSNode *N) const {
284     assert((!N || find(Nodes.begin(), Nodes.end(), N) != Nodes.end()) &&
285            "AssertNodeInGraph: Node is not in graph!");
286   }
287   void AssertNodeContainsGlobal(const DSNode *N, GlobalValue *GV) const {
288     assert(std::find(N->getGlobals().begin(), N->getGlobals().end(), GV) !=
289            N->getGlobals().end() && "Global value not in node!");
290   }
291
292   void AssertCallSiteInGraph(const DSCallSite &CS) const {
293     if (CS.isIndirectCall())
294       AssertNodeInGraph(CS.getCalleeNode());
295     AssertNodeInGraph(CS.getRetVal().getNode());
296     for (unsigned j = 0, e = CS.getNumPtrArgs(); j != e; ++j)
297       AssertNodeInGraph(CS.getPtrArg(j).getNode());
298   }
299
300   void AssertCallNodesInGraph() const {
301     for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
302       AssertCallSiteInGraph(FunctionCalls[i]);
303   }
304   void AssertAuxCallNodesInGraph() const {
305     for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
306       AssertCallSiteInGraph(AuxFunctionCalls[i]);
307   }
308
309   void AssertGraphOK() const;
310
311   /// mergeInGlobalsGraph - This method is useful for clients to incorporate the
312   /// globals graph into the DS, BU or TD graph for a function.  This code
313   /// retains all globals, i.e., does not delete unreachable globals after they
314   /// are inlined.
315   ///
316   void mergeInGlobalsGraph();
317
318   /// removeTriviallyDeadNodes - After the graph has been constructed, this
319   /// method removes all unreachable nodes that are created because they got
320   /// merged with other nodes in the graph.  This is used as the first step of
321   /// removeDeadNodes.
322   ///
323   void removeTriviallyDeadNodes();
324 };
325
326 #endif