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