1 //===- DSGraph.h - Represent a collection of data structures ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This header defines the data structure graph (DSGraph) and the
11 // ReachabilityCloner class.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_ANALYSIS_DSGRAPH_H
16 #define LLVM_ANALYSIS_DSGRAPH_H
18 #include "llvm/Analysis/DataStructure/DSNode.h"
19 #include "llvm/ADT/hash_map"
20 #include "llvm/ADT/EquivalenceClasses.h"
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.
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.
39 typedef hash_map<Value*, DSNodeHandle> ValueMapTy;
42 typedef hash_set<GlobalValue*> GlobalSetTy;
43 GlobalSetTy GlobalSet;
45 EquivalenceClasses<GlobalValue*> &GlobalECs;
47 DSScalarMap(EquivalenceClasses<GlobalValue*> &ECs) : GlobalECs(ECs) {}
49 EquivalenceClasses<GlobalValue*> &getGlobalECs() const { return GlobalECs; }
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(); }
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);
67 iterator find(Value *V) {
68 iterator I = ValueMap.find(V);
69 if (I != ValueMap.end()) return I;
71 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
72 // If this is a global, check to see if it is equivalenced to something
74 GlobalValue *Leader = getLeaderForGlobal(GV);
76 I = ValueMap.find((Value*)Leader);
80 const_iterator find(Value *V) const {
81 const_iterator I = ValueMap.find(V);
82 if (I != ValueMap.end()) return I;
84 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
85 // If this is a global, check to see if it is equivalenced to something
87 GlobalValue *Leader = getLeaderForGlobal(GV);
89 I = ValueMap.find((Value*)Leader);
94 unsigned count(Value *V) const { return ValueMap.find(V) != ValueMap.end(); }
96 void erase(Value *V) { erase(ValueMap.find(V)); }
98 void eraseIfExists(Value *V) {
100 if (I != end()) erase(I);
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.
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));
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);
118 ValueMap.insert(std::make_pair(New, I->second));
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.
128 if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
129 return AddGlobal(GV);
131 return ValueMap.insert(std::make_pair(V, DSNodeHandle())).first->second;
134 void erase(iterator I) {
135 assert(I != ValueMap.end() && "Cannot erase end!");
136 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first))
146 // Access to the global set: the set of all globals currently in the
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); }
154 DSNodeHandle &AddGlobal(GlobalValue *GV);
158 //===----------------------------------------------------------------------===//
159 /// DSGraph - The graph that represents a function.
163 // Public data-type declarations...
164 typedef DSScalarMap ScalarMapTy;
165 typedef hash_map<Function*, DSNodeHandle> ReturnNodesTy;
166 typedef ilist<DSNode> NodeListTy;
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
171 typedef hash_map<const DSNode*, DSNodeHandle> NodeMapTy;
173 // InvNodeMapTy - This data type is used to represent the inverse of a node
175 typedef hash_multimap<DSNodeHandle, const DSNode*> InvNodeMapTy;
177 DSGraph *GlobalsGraph; // Pointer to the common graph of global objects
178 bool PrintAuxCalls; // Should this graph print the Aux calls vector?
181 ScalarMapTy ScalarMap;
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.
187 ReturnNodesTy ReturnNodes;
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.
195 std::list<DSCallSite> FunctionCalls;
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.
201 std::list<DSCallSite> AuxFunctionCalls;
203 /// TD - This is the target data object for the machine this graph is
205 const TargetData &TD;
207 void operator=(const DSGraph &); // DO NOT IMPLEMENT
208 DSGraph(const DSGraph&); // DO NOT IMPLEMENT
210 // Create a new, empty, DSGraph.
211 DSGraph(EquivalenceClasses<GlobalValue*> &ECs, const TargetData &td)
212 : GlobalsGraph(0), PrintAuxCalls(false), ScalarMap(ECs), TD(td) {}
214 // Compute the local DSGraph
215 DSGraph(EquivalenceClasses<GlobalValue*> &ECs, const TargetData &TD,
216 Function &F, DSGraph *GlobalsGraph);
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
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
226 DSGraph(const DSGraph &DSG, EquivalenceClasses<GlobalValue*> &ECs,
227 unsigned CloneFlags = 0);
230 DSGraph *getGlobalsGraph() const { return GlobalsGraph; }
231 void setGlobalsGraph(DSGraph *G) { GlobalsGraph = G; }
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();
239 /// getTargetData - Return the TargetData object for the current target.
241 const TargetData &getTargetData() const { return TD; }
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.
246 void setPrintAuxCalls() { PrintAuxCalls = true; }
247 bool shouldPrintAuxCalls() const { return PrintAuxCalls; }
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(); }
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(); }
262 /// getFunctionNames - Return a space separated list of the name of the
263 /// functions in this graph (if any)
265 std::string getFunctionNames() const;
267 /// addNode - Add a new node to the graph.
269 void addNode(DSNode *N) { Nodes.push_back(N); }
270 void unlinkNode(DSNode *N) { Nodes.remove(N); }
272 /// getScalarMap - Get a map that describes what the nodes the scalars in this
273 /// function point to...
275 ScalarMapTy &getScalarMap() { return ScalarMap; }
276 const ScalarMapTy &getScalarMap() const { return ScalarMap; }
278 /// getFunctionCalls - Return the list of call sites in the original local
281 const std::list<DSCallSite> &getFunctionCalls() const { return FunctionCalls;}
282 std::list<DSCallSite> &getFunctionCalls() { return FunctionCalls;}
284 /// getAuxFunctionCalls - Get the call sites as modified by whatever passes
287 std::list<DSCallSite> &getAuxFunctionCalls() { return AuxFunctionCalls; }
288 const std::list<DSCallSite> &getAuxFunctionCalls() const {
289 return AuxFunctionCalls;
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(); }
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(); }
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.
306 DSNodeHandle &getNodeForValue(Value *V) { return ScalarMap[V]; }
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");
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(); }
322 /// getReturnNodes - Return the mapping of functions to their return nodes for
325 const ReturnNodesTy &getReturnNodes() const { return ReturnNodes; }
326 ReturnNodesTy &getReturnNodes() { return ReturnNodes; }
328 /// getReturnNodeFor - Return the return node for the specified function.
330 DSNodeHandle &getReturnNodeFor(Function &F) {
331 ReturnNodesTy::iterator I = ReturnNodes.find(&F);
332 assert(I != ReturnNodes.end() && "F not in this DSGraph!");
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!");
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);
348 /// getGraphSize - Return the number of nodes in this graph.
350 unsigned getGraphSize() const {
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
361 DSNode *addObjectToGraph(Value *Ptr, bool UseDeclaredType = true);
364 /// print - Print a dot graph to the specified ostream...
366 void print(std::ostream &O) const;
368 /// dump - call print(std::cerr), for use from the debugger...
372 /// viewGraph - Emit a dot graph, run 'dot', run gv on the postscript file,
373 /// then cleanup. For use from the debugger.
375 void viewGraph() const;
377 void writeGraphToFile(std::ostream &O, const std::string &GraphName) const;
379 /// maskNodeTypes - Apply a mask to all of the node types in the graph. This
380 /// is useful for clearing out markers like Incomplete.
382 void maskNodeTypes(unsigned Mask) {
383 for (node_iterator I = node_begin(), E = node_end(); I != E; ++I)
384 I->maskNodeTypes(Mask);
386 void maskIncompleteMarkers() { maskNodeTypes(~DSNode::Incomplete); }
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
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.
397 enum MarkIncompleteFlags {
398 MarkFormalArgs = 1, IgnoreFormalArgs = 0,
399 IgnoreGlobals = 2, MarkGlobalsIncomplete = 0,
401 void markIncompleteNodes(unsigned Flags);
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.
408 enum RemoveDeadNodesFlags {
409 RemoveUnreachableGlobals = 1, KeepUnreachableGlobals = 0,
411 void removeDeadNodes(unsigned Flags);
413 /// CloneFlags enum - Bits that may be passed into the cloneInto method to
414 /// specify how to clone the function graph.
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,
423 void updateFromGlobalGraph();
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.
429 static void computeNodeMapping(const DSNodeHandle &NH1,
430 const DSNodeHandle &NH2, NodeMapTy &NodeMap,
431 bool StrictChecking = true);
433 /// computeGToGGMapping - Compute the mapping of nodes in the graph to nodes
434 /// in the globals graph.
435 void computeGToGGMapping(NodeMapTy &NodeMap);
437 /// computeGGToGMapping - Compute the mapping of nodes in the global
438 /// graph to nodes in this graph.
439 void computeGGToGMapping(InvNodeMapTy &InvNodeMap);
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);
447 /// cloneInto - Clone the specified DSGraph into the current graph.
449 /// The CloneFlags member controls various aspects of the cloning process.
451 void cloneInto(const DSGraph &G, unsigned CloneFlags = 0);
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;
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.
467 void mergeInGraph(const DSCallSite &CS, std::vector<DSNodeHandle> &Args,
468 const DSGraph &G2, unsigned CloneFlags);
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.
473 void mergeInGraph(const DSCallSite &CS, Function &F, const DSGraph &Graph,
474 unsigned CloneFlags);
476 /// getCallSiteForArguments - Get the arguments and return value bindings for
477 /// the specified function in the current graph.
479 DSCallSite getCallSiteForArguments(Function &F) const;
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;
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!");
490 void AssertNodeContainsGlobal(const DSNode *N, GlobalValue *GV) const;
492 void AssertCallSiteInGraph(const DSCallSite &CS) const;
493 void AssertCallNodesInGraph() const;
494 void AssertAuxCallNodesInGraph() const;
496 void AssertGraphOK() const;
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
503 void removeTriviallyDeadNodes();
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.
513 class ReachabilityCloner {
517 /// BitsToKeep - These bits are retained from the source node when the
518 /// source nodes are merged into the destination graph.
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;
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;
538 DSNodeHandle getClonedNH(const DSNodeHandle &SrcNH);
540 void merge(const DSNodeHandle &NH, const DSNodeHandle &SrcNH);
542 /// mergeCallSite - Merge the nodes reachable from the specified src call
543 /// site into the nodes reachable from DestCS.
545 void mergeCallSite(DSCallSite &DestCS, const DSCallSite &SrcCS);
547 bool clonedAnyNodes() const { return !NodeMap.empty(); }
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);
555 void destroy() { NodeMap.clear(); }
558 } // End llvm namespace