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