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