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