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