7d91918dba11d392c83b8b095308f7eb99645720
[oota-llvm.git] / include / llvm / Analysis / DataStructure / DSNode.h
1 //===- DSNode.h - Node definition for datastructure graphs ------*- C++ -*-===//
2 //
3 // Data structure graph nodes and some implementation of DSNodeHandle.
4 //
5 //===----------------------------------------------------------------------===//
6
7 #ifndef LLVM_ANALYSIS_DSNODE_H
8 #define LLVM_ANALYSIS_DSNODE_H
9
10 #include "llvm/Analysis/DSSupport.h"
11
12 template<typename BaseType>
13 class DSNodeIterator;          // Data structure graph traversal iterator
14
15 //===----------------------------------------------------------------------===//
16 /// DSNode - Data structure node class
17 ///
18 /// This class represents an untyped memory object of Size bytes.  It keeps
19 /// track of any pointers that have been stored into the object as well as the
20 /// different types represented in this object.
21 ///
22 class DSNode {
23   /// NumReferrers - The number of DSNodeHandles pointing to this node... if
24   /// this is a forwarding node, then this is the number of node handles which
25   /// are still forwarding over us.
26   ///
27   unsigned NumReferrers;
28
29   /// ForwardNH - This NodeHandle contain the node (and offset into the node)
30   /// that this node really is.  When nodes get folded together, the node to be
31   /// eliminated has these fields filled in, otherwise ForwardNH.getNode() is
32   /// null.
33   DSNodeHandle ForwardNH;
34
35   /// Size - The current size of the node.  This should be equal to the size of
36   /// the current type record.
37   ///
38   unsigned Size;
39
40   /// ParentGraph - The graph this node is currently embedded into.
41   ///
42   DSGraph *ParentGraph;
43
44   /// Ty - Keep track of the current outer most type of this object, in addition
45   /// to whether or not it has been indexed like an array or not.  If the
46   /// isArray bit is set, the node cannot grow.
47   ///
48   const Type *Ty;                 // The type itself...
49
50   /// Links - Contains one entry for every sizeof(void*) bytes in this memory
51   /// object.  Note that if the node is not a multiple of size(void*) bytes
52   /// large, that there is an extra entry for the "remainder" of the node as
53   /// well.  For this reason, nodes of 1 byte in size do have one link.
54   ///
55   std::vector<DSNodeHandle> Links;
56
57   /// Globals - The list of global values that are merged into this node.
58   ///
59   std::vector<GlobalValue*> Globals;
60
61   void operator=(const DSNode &); // DO NOT IMPLEMENT
62   DSNode(const DSNode &);         // DO NOT IMPLEMENT
63 public:
64   enum NodeTy {
65     ShadowNode  = 0,        // Nothing is known about this node...
66     AllocaNode  = 1 << 0,   // This node was allocated with alloca
67     HeapNode    = 1 << 1,   // This node was allocated with malloc
68     GlobalNode  = 1 << 2,   // This node was allocated by a global var decl
69     UnknownNode = 1 << 3,   // This node points to unknown allocated memory 
70     Incomplete  = 1 << 4,   // This node may not be complete
71
72     Modified    = 1 << 5,   // This node is modified in this context
73     Read        = 1 << 6,   // This node is read in this context
74
75     Array       = 1 << 7,   // This node is treated like an array
76     //#ifndef NDEBUG
77     DEAD        = 1 << 8,   // This node is dead and should not be pointed to
78     //#endif
79
80     Composition = AllocaNode | HeapNode | GlobalNode | UnknownNode,
81   };
82   
83   /// NodeType - A union of the above bits.  "Shadow" nodes do not add any flags
84   /// to the nodes in the data structure graph, so it is possible to have nodes
85   /// with a value of 0 for their NodeType.
86   ///
87 private:
88   unsigned short NodeType;
89 public:
90
91   DSNode(const Type *T, DSGraph *G);
92   DSNode(const DSNode &, DSGraph *G);
93
94   ~DSNode() {
95     dropAllReferences();
96     assert(hasNoReferrers() && "Referrers to dead node exist!");
97   }
98
99   // Iterator for graph interface... Defined in DSGraphTraits.h
100   typedef DSNodeIterator<DSNode> iterator;
101   typedef DSNodeIterator<const DSNode> const_iterator;
102   inline iterator begin();
103   inline iterator end();
104   inline const_iterator begin() const;
105   inline const_iterator end() const;
106
107   //===--------------------------------------------------
108   // Accessors
109
110   /// getSize - Return the maximum number of bytes occupied by this object...
111   ///
112   unsigned getSize() const { return Size; }
113
114   // getType - Return the node type of this object...
115   const Type *getType() const { return Ty; }
116   bool isArray() const { return NodeType & Array; }
117
118   /// hasNoReferrers - Return true if nothing is pointing to this node at all.
119   ///
120   bool hasNoReferrers() const { return getNumReferrers() == 0; }
121
122   /// getNumReferrers - This method returns the number of referrers to the
123   /// current node.  Note that if this node is a forwarding node, this will
124   /// return the number of nodes forwarding over the node!
125   unsigned getNumReferrers() const { return NumReferrers; }
126
127   DSGraph *getParentGraph() const { return ParentGraph; }
128   void setParentGraph(DSGraph *G) { ParentGraph = G; }
129
130
131   /// getForwardNode - This method returns the node that this node is forwarded
132   /// to, if any.
133   DSNode *getForwardNode() const { return ForwardNH.getNode(); }
134   void stopForwarding() {
135     assert(!ForwardNH.isNull() &&
136            "Node isn't forwarding, cannot stopForwarding!");
137     ForwardNH.setNode(0);
138   }
139
140   /// hasLink - Return true if this memory object has a link in slot #LinkNo
141   ///
142   bool hasLink(unsigned Offset) const {
143     assert((Offset & ((1 << DS::PointerShift)-1)) == 0 &&
144            "Pointer offset not aligned correctly!");
145     unsigned Index = Offset >> DS::PointerShift;
146     assert(Index < Links.size() && "Link index is out of range!");
147     return Links[Index].getNode();
148   }
149
150   /// getLink - Return the link at the specified offset.
151   DSNodeHandle &getLink(unsigned Offset) {
152     assert((Offset & ((1 << DS::PointerShift)-1)) == 0 &&
153            "Pointer offset not aligned correctly!");
154     unsigned Index = Offset >> DS::PointerShift;
155     assert(Index < Links.size() && "Link index is out of range!");
156     return Links[Index];
157   }
158   const DSNodeHandle &getLink(unsigned Offset) const {
159     assert((Offset & ((1 << DS::PointerShift)-1)) == 0 &&
160            "Pointer offset not aligned correctly!");
161     unsigned Index = Offset >> DS::PointerShift;
162     assert(Index < Links.size() && "Link index is out of range!");
163     return Links[Index];
164   }
165
166   /// getNumLinks - Return the number of links in a node...
167   ///
168   unsigned getNumLinks() const { return Links.size(); }
169
170   /// mergeTypeInfo - This method merges the specified type into the current
171   /// node at the specified offset.  This may update the current node's type
172   /// record if this gives more information to the node, it may do nothing to
173   /// the node if this information is already known, or it may merge the node
174   /// completely (and return true) if the information is incompatible with what
175   /// is already known.
176   ///
177   /// This method returns true if the node is completely folded, otherwise
178   /// false.
179   ///
180   bool mergeTypeInfo(const Type *Ty, unsigned Offset,
181                      bool FoldIfIncompatible = true);
182
183   /// foldNodeCompletely - If we determine that this node has some funny
184   /// behavior happening to it that we cannot represent, we fold it down to a
185   /// single, completely pessimistic, node.  This node is represented as a
186   /// single byte with a single TypeEntry of "void" with isArray = true.
187   ///
188   void foldNodeCompletely();
189
190   /// isNodeCompletelyFolded - Return true if this node has been completely
191   /// folded down to something that can never be expanded, effectively losing
192   /// all of the field sensitivity that may be present in the node.
193   ///
194   bool isNodeCompletelyFolded() const;
195
196   /// setLink - Set the link at the specified offset to the specified
197   /// NodeHandle, replacing what was there.  It is uncommon to use this method,
198   /// instead one of the higher level methods should be used, below.
199   ///
200   void setLink(unsigned Offset, const DSNodeHandle &NH) {
201     assert((Offset & ((1 << DS::PointerShift)-1)) == 0 &&
202            "Pointer offset not aligned correctly!");
203     unsigned Index = Offset >> DS::PointerShift;
204     assert(Index < Links.size() && "Link index is out of range!");
205     Links[Index] = NH;
206   }
207
208   /// getPointerSize - Return the size of a pointer for the current target.
209   ///
210   unsigned getPointerSize() const { return DS::PointerSize; }
211
212   /// addEdgeTo - Add an edge from the current node to the specified node.  This
213   /// can cause merging of nodes in the graph.
214   ///
215   void addEdgeTo(unsigned Offset, const DSNodeHandle &NH);
216
217   /// mergeWith - Merge this node and the specified node, moving all links to
218   /// and from the argument node into the current node, deleting the node
219   /// argument.  Offset indicates what offset the specified node is to be merged
220   /// into the current node.
221   ///
222   /// The specified node may be a null pointer (in which case, nothing happens).
223   ///
224   void mergeWith(const DSNodeHandle &NH, unsigned Offset);
225
226   /// addGlobal - Add an entry for a global value to the Globals list.  This
227   /// also marks the node with the 'G' flag if it does not already have it.
228   ///
229   void addGlobal(GlobalValue *GV);
230   const std::vector<GlobalValue*> &getGlobals() const { return Globals; }
231
232   /// maskNodeTypes - Apply a mask to the node types bitfield.
233   ///
234   void maskNodeTypes(unsigned Mask) {
235     NodeType &= Mask;
236   }
237
238   /// getNodeFlags - Return all of the flags set on the node.  If the DEAD flag
239   /// is set, hide it from the caller.
240   unsigned getNodeFlags() const { return NodeType & ~DEAD; }
241
242   bool isAllocaNode()  const { return NodeType & AllocaNode; }
243   bool isHeapNode()    const { return NodeType & HeapNode; }
244   bool isGlobalNode()  const { return NodeType & GlobalNode; }
245   bool isUnknownNode() const { return NodeType & UnknownNode; }
246
247   bool isModified() const   { return NodeType & Modified; }
248   bool isRead() const       { return NodeType & Read; }
249
250   bool isIncomplete() const { return NodeType & Incomplete; }
251   bool isComplete() const   { return !isIncomplete(); }
252   bool isDeadNode() const   { return NodeType & DEAD; }
253
254   DSNode *setAllocaNodeMarker()  { NodeType |= AllocaNode;  return this; }
255   DSNode *setHeapNodeMarker()    { NodeType |= HeapNode;    return this; }
256   DSNode *setGlobalNodeMarker()  { NodeType |= GlobalNode;  return this; }
257   DSNode *setUnknownNodeMarker() { NodeType |= UnknownNode; return this; }
258
259   DSNode *setIncompleteMarker() { NodeType |= Incomplete; return this; }
260   DSNode *setModifiedMarker()   { NodeType |= Modified;   return this; }
261   DSNode *setReadMarker()       { NodeType |= Read;       return this; }
262
263   void makeNodeDead() {
264     Globals.clear();
265     assert(hasNoReferrers() && "Dead node shouldn't have refs!");
266     NodeType = DEAD;
267   }
268
269   /// forwardNode - Mark this node as being obsolete, and all references to it
270   /// should be forwarded to the specified node and offset.
271   ///
272   void forwardNode(DSNode *To, unsigned Offset);
273
274   void print(std::ostream &O, const DSGraph *G) const;
275   void dump() const;
276
277   void assertOK() const;
278
279   void dropAllReferences() {
280     Links.clear();
281     if (!ForwardNH.isNull())
282       ForwardNH.setNode(0);
283   }
284
285   /// remapLinks - Change all of the Links in the current node according to the
286   /// specified mapping.
287   void remapLinks(hash_map<const DSNode*, DSNodeHandle> &OldNodeMap);
288
289   /// markReachableNodes - This method recursively traverses the specified
290   /// DSNodes, marking any nodes which are reachable.  All reachable nodes it
291   /// adds to the set, which allows it to only traverse visited nodes once.
292   ///
293   void markReachableNodes(hash_set<DSNode*> &ReachableNodes);
294
295 private:
296   friend class DSNodeHandle;
297
298   // static mergeNodes - Helper for mergeWith()
299   static void MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH);
300 };
301
302
303 //===----------------------------------------------------------------------===//
304 // Define inline DSNodeHandle functions that depend on the definition of DSNode
305 //
306 inline DSNode *DSNodeHandle::getNode() const {
307   assert((!N || Offset < N->Size || (N->Size == 0 && Offset == 0) ||
308           !N->ForwardNH.isNull()) && "Node handle offset out of range!");
309   if (!N || N->ForwardNH.isNull())
310     return N;
311
312   return HandleForwarding();
313 }
314
315 inline void DSNodeHandle::setNode(DSNode *n) {
316   assert(!n || !n->getForwardNode() && "Cannot set node to a forwarded node!");
317   if (N) N->NumReferrers--;
318   N = n;
319   if (N) {
320     N->NumReferrers++;
321     if (Offset >= N->Size) {
322       assert((Offset == 0 || N->Size == 1) &&
323              "Pointer to non-collapsed node with invalid offset!");
324       Offset = 0;
325     }
326   }
327   assert(!N || ((N->NodeType & DSNode::DEAD) == 0));
328   assert((!N || Offset < N->Size || (N->Size == 0 && Offset == 0) ||
329           !N->ForwardNH.isNull()) && "Node handle offset out of range!");
330 }
331
332 inline bool DSNodeHandle::hasLink(unsigned Num) const {
333   assert(N && "DSNodeHandle does not point to a node yet!");
334   return getNode()->hasLink(Num+Offset);
335 }
336
337
338 /// getLink - Treat this current node pointer as a pointer to a structure of
339 /// some sort.  This method will return the pointer a mem[this+Num]
340 ///
341 inline const DSNodeHandle &DSNodeHandle::getLink(unsigned Off) const {
342   assert(N && "DSNodeHandle does not point to a node yet!");
343   return getNode()->getLink(Offset+Off);
344 }
345 inline DSNodeHandle &DSNodeHandle::getLink(unsigned Off) {
346   assert(N && "DSNodeHandle does not point to a node yet!");
347   return getNode()->getLink(Off+Offset);
348 }
349
350 inline void DSNodeHandle::setLink(unsigned Off, const DSNodeHandle &NH) {
351   assert(N && "DSNodeHandle does not point to a node yet!");
352   getNode()->setLink(Off+Offset, NH);
353 }
354
355 ///  addEdgeTo - Add an edge from the current node to the specified node.  This
356 /// can cause merging of nodes in the graph.
357 ///
358 inline void DSNodeHandle::addEdgeTo(unsigned Off, const DSNodeHandle &Node) {
359   assert(N && "DSNodeHandle does not point to a node yet!");
360   getNode()->addEdgeTo(Off+Offset, Node);
361 }
362
363 /// mergeWith - Merge the logical node pointed to by 'this' with the node
364 /// pointed to by 'N'.
365 ///
366 inline void DSNodeHandle::mergeWith(const DSNodeHandle &Node) {
367   if (N != 0)
368     getNode()->mergeWith(Node, Offset);
369   else     // No node to merge with, so just point to Node
370     *this = Node;
371 }
372
373 #endif