1 //===- DataStructure.h - Build data structure graphs -------------*- C++ -*--=//
3 // Implement the LLVM data structure analysis library.
5 //===----------------------------------------------------------------------===//
7 #ifndef LLVM_ANALYSIS_DATA_STRUCTURE_H
8 #define LLVM_ANALYSIS_DATA_STRUCTURE_H
10 #include "llvm/Pass.h"
15 class DSNode; // Each node in the graph
16 class DSGraph; // A graph for a function
17 class DSNodeIterator; // Data structure graph traversal iterator
18 class LocalDataStructures; // A collection of local graphs for a program
19 class BUDataStructures; // A collection of bu graphs for a program
20 class TDDataStructures; // A collection of td graphs for a program
22 //===----------------------------------------------------------------------===//
23 // DSNodeHandle - Implement a "handle" to a data structure node that takes care
24 // of all of the add/un'refing of the node to prevent the backpointers in the
25 // graph from getting out of date.
30 // Allow construction, destruction, and assignment...
31 DSNodeHandle(DSNode *n = 0) : N(0) { operator=(n); }
32 DSNodeHandle(const DSNodeHandle &H) : N(0) { operator=(H.N); }
33 ~DSNodeHandle() { operator=(0); }
34 DSNodeHandle &operator=(const DSNodeHandle &H) {operator=(H.N); return *this;}
36 // Assignment of DSNode*, implement all of the add/un'refing (defined later)
37 inline DSNodeHandle &operator=(DSNode *n);
39 // Allow automatic, implicit, conversion to DSNode*
40 operator DSNode*() { return N; }
41 operator const DSNode*() const { return N; }
42 operator bool() const { return N != 0; }
43 operator bool() { return N != 0; }
45 bool operator<(const DSNodeHandle &H) const { // Allow sorting
48 bool operator==(const DSNodeHandle &H) const { return N == H.N; }
49 bool operator!=(const DSNodeHandle &H) const { return N != H.N; }
50 bool operator==(const DSNode *Node) const { return N == Node; }
51 bool operator!=(const DSNode *Node) const { return N != Node; }
52 bool operator==(DSNode *Node) const { return N == Node; }
53 bool operator!=(DSNode *Node) const { return N != Node; }
55 // Avoid having comparisons to null cause errors...
56 bool operator==(int X) const {
57 assert(X == 0 && "Bad comparison!");
58 return operator==((DSNode*)0);
60 bool operator!=(int X) const { return !operator==(X); }
62 // Allow explicit conversion to DSNode...
63 DSNode *get() { return N; }
64 const DSNode *get() const { return N; }
66 // Allow this to be treated like a pointer...
67 DSNode *operator->() { return N; }
68 const DSNode *operator->() const { return N; }
72 //===----------------------------------------------------------------------===//
73 // DSNode - Data structure node class
75 // This class keeps track of a node's type, and the fields in the data
81 std::vector<DSNodeHandle> Links;
82 std::vector<DSNodeHandle*> Referrers;
84 // Globals - The list of global values that are merged into this node.
85 std::vector<GlobalValue*> Globals;
87 void operator=(const DSNode &); // DO NOT IMPLEMENT
90 ShadowNode = 0 << 0, // Nothing is known about this node...
91 ScalarNode = 1 << 0, // Scalar of the current function contains this value
92 AllocaNode = 1 << 1, // This node was allocated with alloca
93 NewNode = 1 << 2, // This node was allocated with malloc
94 GlobalNode = 1 << 3, // This node was allocated by a global var decl
95 SubElement = 1 << 4, // This node is a part of some other node
96 CastNode = 1 << 5, // This node is accessed in unsafe ways
97 Incomplete = 1 << 6, // This node may not be complete
100 // NodeType - A union of the above bits. "Shadow" nodes do not add any flags
101 // to the nodes in the data structure graph, so it is possible to have nodes
102 // with a value of 0 for their NodeType. Scalar and Alloca markers go away
103 // when function graphs are inlined.
105 unsigned char NodeType;
107 DSNode(enum NodeTy NT, const Type *T);
108 DSNode(const DSNode &);
112 dropAllReferences(); // Only needed to satisfy assertion checks...
114 assert(Referrers.empty() && "Referrers to dead node exist!");
117 // Iterator for graph interface...
118 typedef DSNodeIterator iterator;
119 inline iterator begin(); // Defined in DataStructureGraph.h
120 inline iterator end();
123 const Type *getType() const { return Ty; }
125 unsigned getNumLinks() const { return Links.size(); }
126 DSNode *getLink(unsigned i) {
127 assert(i < getNumLinks() && "Field links access out of range...");
130 const DSNode *getLink(unsigned i) const {
131 assert(i < getNumLinks() && "Field links access out of range...");
135 void setLink(unsigned i, DSNode *N) {
136 assert(i < getNumLinks() && "Field links access out of range...");
140 // addGlobal - Add an entry for a global value to the Globals list. This also
141 // marks the node with the 'G' flag if it does not already have it.
143 void addGlobal(GlobalValue *GV);
144 const std::vector<GlobalValue*> &getGlobals() const { return Globals; }
145 std::vector<GlobalValue*> &getGlobals() { return Globals; }
147 // addEdgeTo - Add an edge from the current node to the specified node. This
148 // can cause merging of nodes in the graph.
150 void addEdgeTo(unsigned LinkNo, DSNode *N);
151 void addEdgeTo(DSNode *N) {
152 assert(getNumLinks() == 1 && "Must specify a field number to add edge if "
153 " more than one field exists!");
157 // mergeWith - Merge this node into the specified node, moving all links to
158 // and from the argument node into the current node. The specified node may
159 // be a null pointer (in which case, nothing happens).
161 void mergeWith(DSNode *N);
163 // addReferrer - Keep the referrer set up to date...
164 void addReferrer(DSNodeHandle *H) { Referrers.push_back(H); }
165 void removeReferrer(DSNodeHandle *H);
166 const std::vector<DSNodeHandle*> &getReferrers() const { return Referrers; }
168 void print(std::ostream &O, const DSGraph *G) const;
171 std::string getCaption(const DSGraph *G) const;
173 void dropAllReferences() {
179 inline DSNodeHandle &DSNodeHandle::operator=(DSNode *n) {
180 if (N) N->removeReferrer(this);
182 if (N) N->addReferrer(this);
187 // DSGraph - The graph that represents a function.
191 std::vector<DSNode*> Nodes;
192 DSNodeHandle RetNode; // Node that gets returned...
193 std::map<Value*, DSNodeHandle> ValueMap;
195 // FunctionCalls - This vector maintains a single entry for each call
196 // instruction in the current graph. Each call entry contains DSNodeHandles
197 // that refer to the arguments that are passed into the function call. The
198 // first entry in the vector is the scalar that holds the return value for the
199 // call, the second is the function scalar being invoked, and the rest are
200 // pointer arguments to the function.
202 std::vector<std::vector<DSNodeHandle> > FunctionCalls;
204 // OrigFunctionCalls - This vector retains a copy of the original function
205 // calls of the current graph. This is needed to support top-down inlining
206 // after bottom-up inlining is complete, since the latter deletes call nodes.
208 std::vector<std::vector<DSNodeHandle> > OrigFunctionCalls;
210 // PendingCallers - This vector records all unresolved callers of the
211 // current function, i.e., ones whose graphs have not been inlined into
212 // the current graph. As long as there are unresolved callers, the nodes
213 // for formal arguments in the current graph cannot be eliminated, and
214 // nodes in the graph reachable from the formal argument nodes or
215 // global variable nodes must be considered incomplete.
216 std::vector<Function*> PendingCallers;
219 // Define the interface only accessable to DataStructure
220 friend class LocalDataStructures;
221 friend class BUDataStructures;
222 friend class TDDataStructures;
223 DSGraph(Function &F); // Compute the local DSGraph
224 DSGraph(const DSGraph &DSG); // Copy ctor
227 // clone all the call nodes and save the copies in OrigFunctionCalls
228 void saveOrigFunctionCalls() {
229 assert(OrigFunctionCalls.size() == 0 && "Do this only once!");
230 OrigFunctionCalls = FunctionCalls;
233 // get the saved copies of the original function call nodes
234 std::vector<std::vector<DSNodeHandle> > &getOrigFunctionCalls() {
235 return OrigFunctionCalls;
238 void operator=(const DSGraph &); // DO NOT IMPLEMENT
241 Function &getFunction() const { return Func; }
243 // getValueMap - Get a map that describes what the nodes the scalars in this
244 // function point to...
246 std::map<Value*, DSNodeHandle> &getValueMap() { return ValueMap; }
247 const std::map<Value*, DSNodeHandle> &getValueMap() const { return ValueMap;}
249 std::vector<std::vector<DSNodeHandle> > &getFunctionCalls() {
250 return FunctionCalls;
253 const DSNode *getRetNode() const { return RetNode; }
255 unsigned getGraphSize() const {
259 void print(std::ostream &O) const;
262 // maskNodeTypes - Apply a mask to all of the node types in the graph. This
263 // is useful for clearing out markers like Scalar or Incomplete.
265 void maskNodeTypes(unsigned char Mask);
266 void maskIncompleteMarkers() { maskNodeTypes(~DSNode::Incomplete); }
268 // markIncompleteNodes - Traverse the graph, identifying nodes that may be
269 // modified by other functions that have not been resolved yet. This marks
270 // nodes that are reachable through three sources of "unknownness":
271 // Global Variables, Function Calls, and Incoming Arguments
273 // For any node that may have unknown components (because something outside
274 // the scope of current analysis may have modified it), the 'Incomplete' flag
275 // is added to the NodeType.
277 void markIncompleteNodes();
279 // removeTriviallyDeadNodes - After the graph has been constructed, this
280 // method removes all unreachable nodes that are created because they got
281 // merged with other nodes in the graph.
283 void removeTriviallyDeadNodes();
285 // removeDeadNodes - Use a more powerful reachability analysis to eliminate
286 // subgraphs that are unreachable. This often occurs because the data
287 // structure doesn't "escape" into it's caller, and thus should be eliminated
288 // from the caller's graph entirely. This is only appropriate to use when
291 void removeDeadNodes();
294 // AddCaller - add a known caller node into the graph and mark it pending.
295 // getCallers - get a vector of the functions that call this one
296 // getCallersPending - get a matching vector of bools indicating if each
297 // caller's DSGraph has been resolved into this one.
299 void addCaller(Function& caller) {
300 PendingCallers.push_back(&caller);
302 std::vector<Function*>& getPendingCallers() {
303 return PendingCallers;
306 // cloneInto - Clone the specified DSGraph into the current graph, returning
307 // the Return node of the graph. The translated ValueMap for the old function
308 // is filled into the OldValMap member. If StripLocals is set to true, Scalar
309 // and Alloca markers are removed from the graph, as the graph is being cloned
310 // into a calling function's graph.
312 DSNode *cloneInto(const DSGraph &G, std::map<Value*, DSNodeHandle> &OldValMap,
313 std::map<const DSNode*, DSNode*>& OldNodeMap,
314 bool StripLocals = true);
316 bool isNodeDead(DSNode *N);
321 // LocalDataStructures - The analysis that computes the local data structure
322 // graphs for all of the functions in the program.
324 // FIXME: This should be a Function pass that can be USED by a Pass, and would
325 // be automatically preserved. Until we can do that, this is a Pass.
327 class LocalDataStructures : public Pass {
328 // DSInfo, one graph for each function
329 std::map<Function*, DSGraph*> DSInfo;
331 static AnalysisID ID; // DataStructure Analysis ID
333 ~LocalDataStructures() { releaseMemory(); }
335 virtual bool run(Module &M);
337 // getDSGraph - Return the data structure graph for the specified function.
338 DSGraph &getDSGraph(Function &F) const {
339 std::map<Function*, DSGraph*>::const_iterator I = DSInfo.find(&F);
340 assert(I != DSInfo.end() && "Function not in module!");
344 // print - Print out the analysis results...
345 void print(std::ostream &O, Module *M) const;
347 // If the pass pipeline is done with this pass, we can release our memory...
348 virtual void releaseMemory();
350 // getAnalysisUsage - This obviously provides a data structure graph.
351 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
352 AU.setPreservesAll();
358 // BUDataStructures - The analysis that computes the interprocedurally closed
359 // data structure graphs for all of the functions in the program. This pass
360 // only performs a "Bottom Up" propogation (hence the name).
362 class BUDataStructures : public Pass {
363 // DSInfo, one graph for each function
364 std::map<Function*, DSGraph*> DSInfo;
366 static AnalysisID ID; // BUDataStructure Analysis ID
368 ~BUDataStructures() { releaseMemory(); }
370 virtual bool run(Module &M);
372 // getDSGraph - Return the data structure graph for the specified function.
373 DSGraph &getDSGraph(Function &F) const {
374 std::map<Function*, DSGraph*>::const_iterator I = DSInfo.find(&F);
375 assert(I != DSInfo.end() && "Function not in module!");
379 // print - Print out the analysis results...
380 void print(std::ostream &O, Module *M) const;
382 // If the pass pipeline is done with this pass, we can release our memory...
383 virtual void releaseMemory();
385 // getAnalysisUsage - This obviously provides a data structure graph.
386 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
387 AU.setPreservesAll();
389 AU.addRequired(LocalDataStructures::ID);
392 DSGraph &calculateGraph(Function &F);
396 // TDDataStructures - Analysis that computes new data structure graphs
397 // for each function using the closed graphs for the callers computed
398 // by the bottom-up pass.
400 class TDDataStructures : public Pass {
401 // DSInfo, one graph for each function
402 std::map<Function*, DSGraph*> DSInfo;
404 static AnalysisID ID; // TDDataStructure Analysis ID
406 ~TDDataStructures() { releaseMemory(); }
408 virtual const char *getPassName() const {
409 return "Top-down Data Structure Analysis Closure";
412 virtual bool run(Module &M);
414 // getDSGraph - Return the data structure graph for the specified function.
415 DSGraph &getDSGraph(Function &F) const {
416 std::map<Function*, DSGraph*>::const_iterator I = DSInfo.find(&F);
417 assert(I != DSInfo.end() && "Function not in module!");
421 // print - Print out the analysis results...
422 void print(std::ostream &O, Module *M) const;
424 // If the pass pipeline is done with this pass, we can release our memory...
425 virtual void releaseMemory();
427 // getAnalysisUsage - This obviously provides a data structure graph.
428 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
429 AU.setPreservesAll();
431 AU.addRequired(BUDataStructures::ID);
434 DSGraph &calculateGraph(Function &F);
435 void pushGraphIntoCallee(DSGraph &callerGraph, DSGraph &calleeGraph,
436 std::map<Value*, DSNodeHandle> &OldValMap,
437 std::map<const DSNode*, DSNode*> &OldNodeMap);