Implement a "union-findy" version of DS-Analysis, which eliminates the
[oota-llvm.git] / lib / Analysis / DataStructure / DataStructure.cpp
1 //===- DataStructure.cpp - Implement the core data structure analysis -----===//
2 //
3 // This file implements the core data structure functionality.
4 //
5 //===----------------------------------------------------------------------===//
6
7 #include "llvm/Analysis/DSGraph.h"
8 #include "llvm/Function.h"
9 #include "llvm/iOther.h"
10 #include "llvm/DerivedTypes.h"
11 #include "llvm/Target/TargetData.h"
12 #include "Support/STLExtras.h"
13 #include "Support/Statistic.h"
14 #include "Support/Timer.h"
15 #include <algorithm>
16
17 namespace {
18   Statistic<> NumFolds          ("dsnode", "Number of nodes completely folded");
19   Statistic<> NumCallNodesMerged("dsnode", "Number of call nodes merged");
20 };
21
22 namespace DS {   // TODO: FIXME
23   extern TargetData TD;
24 }
25 using namespace DS;
26
27 //===----------------------------------------------------------------------===//
28 // DSNode Implementation
29 //===----------------------------------------------------------------------===//
30
31 DSNode::DSNode(unsigned NT, const Type *T, DSGraph *G)
32   : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(NT) {
33   // Add the type entry if it is specified...
34   if (T) mergeTypeInfo(T, 0);
35   G->getNodes().push_back(this);
36 }
37
38 // DSNode copy constructor... do not copy over the referrers list!
39 DSNode::DSNode(const DSNode &N, DSGraph *G)
40   : NumReferrers(0), Size(N.Size), ParentGraph(G), Ty(N.Ty),
41     Links(N.Links), Globals(N.Globals), NodeType(N.NodeType) {
42   G->getNodes().push_back(this);
43 }
44
45 void DSNode::assertOK() const {
46   assert((Ty != Type::VoidTy ||
47           Ty == Type::VoidTy && (Size == 0 ||
48                                  (NodeType & DSNode::Array))) &&
49          "Node not OK!");
50 }
51
52 /// forwardNode - Mark this node as being obsolete, and all references to it
53 /// should be forwarded to the specified node and offset.
54 ///
55 void DSNode::forwardNode(DSNode *To, unsigned Offset) {
56   assert(this != To && "Cannot forward a node to itself!");
57   assert(ForwardNH.isNull() && "Already forwarding from this node!");
58   if (To->Size <= 1) Offset = 0;
59   assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
60          "Forwarded offset is wrong!");
61   ForwardNH.setNode(To);
62   ForwardNH.setOffset(Offset);
63   NodeType = DEAD;
64   Size = 0;
65   Ty = Type::VoidTy;
66 }
67
68 // addGlobal - Add an entry for a global value to the Globals list.  This also
69 // marks the node with the 'G' flag if it does not already have it.
70 //
71 void DSNode::addGlobal(GlobalValue *GV) {
72   // Keep the list sorted.
73   std::vector<GlobalValue*>::iterator I =
74     std::lower_bound(Globals.begin(), Globals.end(), GV);
75
76   if (I == Globals.end() || *I != GV) {
77     //assert(GV->getType()->getElementType() == Ty);
78     Globals.insert(I, GV);
79     NodeType |= GlobalNode;
80   }
81 }
82
83 /// foldNodeCompletely - If we determine that this node has some funny
84 /// behavior happening to it that we cannot represent, we fold it down to a
85 /// single, completely pessimistic, node.  This node is represented as a
86 /// single byte with a single TypeEntry of "void".
87 ///
88 void DSNode::foldNodeCompletely() {
89   assert(!hasNoReferrers() &&
90          "Why would we collapse a node with no referrers?");
91   if (isNodeCompletelyFolded()) return;  // If this node is already folded...
92
93   ++NumFolds;
94
95   // Create the node we are going to forward to...
96   DSNode *DestNode = new DSNode(NodeType|DSNode::Array, 0, ParentGraph);
97   DestNode->Ty = Type::VoidTy;
98   DestNode->Size = 1;
99   DestNode->Globals.swap(Globals);
100
101   // Start forwarding to the destination node...
102   forwardNode(DestNode, 0);
103   
104   if (Links.size()) {
105     DestNode->Links.push_back(Links[0]);
106     DSNodeHandle NH(DestNode);
107
108     // If we have links, merge all of our outgoing links together...
109     for (unsigned i = Links.size()-1; i != 0; --i)
110       NH.getNode()->Links[0].mergeWith(Links[i]);
111     Links.clear();
112   } else {
113     DestNode->Links.resize(1);
114   }
115 }
116
117 /// isNodeCompletelyFolded - Return true if this node has been completely
118 /// folded down to something that can never be expanded, effectively losing
119 /// all of the field sensitivity that may be present in the node.
120 ///
121 bool DSNode::isNodeCompletelyFolded() const {
122   return getSize() == 1 && Ty == Type::VoidTy && isArray();
123 }
124
125
126 /// mergeTypeInfo - This method merges the specified type into the current node
127 /// at the specified offset.  This may update the current node's type record if
128 /// this gives more information to the node, it may do nothing to the node if
129 /// this information is already known, or it may merge the node completely (and
130 /// return true) if the information is incompatible with what is already known.
131 ///
132 /// This method returns true if the node is completely folded, otherwise false.
133 ///
134 bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset) {
135   // Check to make sure the Size member is up-to-date.  Size can be one of the
136   // following:
137   //  Size = 0, Ty = Void: Nothing is known about this node.
138   //  Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
139   //  Size = 1, Ty = Void, Array = 1: The node is collapsed
140   //  Otherwise, sizeof(Ty) = Size
141   //
142   assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
143           (Size == 0 && !Ty->isSized() && !isArray()) ||
144           (Size == 1 && Ty == Type::VoidTy && isArray()) ||
145           (Size == 0 && !Ty->isSized() && !isArray()) ||
146           (TD.getTypeSize(Ty) == Size)) &&
147          "Size member of DSNode doesn't match the type structure!");
148   assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
149
150   if (Offset == 0 && NewTy == Ty)
151     return false;  // This should be a common case, handle it efficiently
152
153   // Return true immediately if the node is completely folded.
154   if (isNodeCompletelyFolded()) return true;
155
156   // If this is an array type, eliminate the outside arrays because they won't
157   // be used anyway.  This greatly reduces the size of large static arrays used
158   // as global variables, for example.
159   //
160   bool WillBeArray = false;
161   while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
162     // FIXME: we might want to keep small arrays, but must be careful about
163     // things like: [2 x [10000 x int*]]
164     NewTy = AT->getElementType();
165     WillBeArray = true;
166   }
167
168   // Figure out how big the new type we're merging in is...
169   unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
170
171   // Otherwise check to see if we can fold this type into the current node.  If
172   // we can't, we fold the node completely, if we can, we potentially update our
173   // internal state.
174   //
175   if (Ty == Type::VoidTy) {
176     // If this is the first type that this node has seen, just accept it without
177     // question....
178     assert(Offset == 0 && "Cannot have an offset into a void node!");
179     assert(!isArray() && "This shouldn't happen!");
180     Ty = NewTy;
181     NodeType &= ~Array;
182     if (WillBeArray) NodeType |= Array;
183     Size = NewTySize;
184
185     // Calculate the number of outgoing links from this node.
186     Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
187     return false;
188   }
189
190   // Handle node expansion case here...
191   if (Offset+NewTySize > Size) {
192     // It is illegal to grow this node if we have treated it as an array of
193     // objects...
194     if (isArray()) {
195       foldNodeCompletely();
196       return true;
197     }
198
199     if (Offset) {  // We could handle this case, but we don't for now...
200       DEBUG(std::cerr << "UNIMP: Trying to merge a growth type into "
201                       << "offset != 0: Collapsing!\n");
202       foldNodeCompletely();
203       return true;
204     }
205
206     // Okay, the situation is nice and simple, we are trying to merge a type in
207     // at offset 0 that is bigger than our current type.  Implement this by
208     // switching to the new type and then merge in the smaller one, which should
209     // hit the other code path here.  If the other code path decides it's not
210     // ok, it will collapse the node as appropriate.
211     //
212     const Type *OldTy = Ty;
213     Ty = NewTy;
214     NodeType &= ~Array;
215     if (WillBeArray) NodeType |= Array;
216     Size = NewTySize;
217
218     // Must grow links to be the appropriate size...
219     Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
220
221     // Merge in the old type now... which is guaranteed to be smaller than the
222     // "current" type.
223     return mergeTypeInfo(OldTy, 0);
224   }
225
226   assert(Offset <= Size &&
227          "Cannot merge something into a part of our type that doesn't exist!");
228
229   // Find the section of Ty that NewTy overlaps with... first we find the
230   // type that starts at offset Offset.
231   //
232   unsigned O = 0;
233   const Type *SubType = Ty;
234   while (O < Offset) {
235     assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
236
237     switch (SubType->getPrimitiveID()) {
238     case Type::StructTyID: {
239       const StructType *STy = cast<StructType>(SubType);
240       const StructLayout &SL = *TD.getStructLayout(STy);
241
242       unsigned i = 0, e = SL.MemberOffsets.size();
243       for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
244         /* empty */;
245
246       // The offset we are looking for must be in the i'th element...
247       SubType = STy->getElementTypes()[i];
248       O += SL.MemberOffsets[i];
249       break;
250     }
251     case Type::ArrayTyID: {
252       SubType = cast<ArrayType>(SubType)->getElementType();
253       unsigned ElSize = TD.getTypeSize(SubType);
254       unsigned Remainder = (Offset-O) % ElSize;
255       O = Offset-Remainder;
256       break;
257     }
258     default:
259       foldNodeCompletely();
260       return true;
261     }
262   }
263
264   assert(O == Offset && "Could not achieve the correct offset!");
265
266   // If we found our type exactly, early exit
267   if (SubType == NewTy) return false;
268
269   // Okay, so we found the leader type at the offset requested.  Search the list
270   // of types that starts at this offset.  If SubType is currently an array or
271   // structure, the type desired may actually be the first element of the
272   // composite type...
273   //
274   unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
275   unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
276   while (SubType != NewTy) {
277     const Type *NextSubType = 0;
278     unsigned NextSubTypeSize = 0;
279     unsigned NextPadSize = 0;
280     switch (SubType->getPrimitiveID()) {
281     case Type::StructTyID: {
282       const StructType *STy = cast<StructType>(SubType);
283       const StructLayout &SL = *TD.getStructLayout(STy);
284       if (SL.MemberOffsets.size() > 1)
285         NextPadSize = SL.MemberOffsets[1];
286       else
287         NextPadSize = SubTypeSize;
288       NextSubType = STy->getElementTypes()[0];
289       NextSubTypeSize = TD.getTypeSize(NextSubType);
290       break;
291     }
292     case Type::ArrayTyID:
293       NextSubType = cast<ArrayType>(SubType)->getElementType();
294       NextSubTypeSize = TD.getTypeSize(NextSubType);
295       NextPadSize = NextSubTypeSize;
296       break;
297     default: ;
298       // fall out 
299     }
300
301     if (NextSubType == 0)
302       break;   // In the default case, break out of the loop
303
304     if (NextPadSize < NewTySize)
305       break;   // Don't allow shrinking to a smaller type than NewTySize
306     SubType = NextSubType;
307     SubTypeSize = NextSubTypeSize;
308     PadSize = NextPadSize;
309   }
310
311   // If we found the type exactly, return it...
312   if (SubType == NewTy)
313     return false;
314
315   // Check to see if we have a compatible, but different type...
316   if (NewTySize == SubTypeSize) {
317     // Check to see if this type is obviously convertable... int -> uint f.e.
318     if (NewTy->isLosslesslyConvertableTo(SubType))
319       return false;
320
321     // Check to see if we have a pointer & integer mismatch going on here,
322     // loading a pointer as a long, for example.
323     //
324     if (SubType->isInteger() && isa<PointerType>(NewTy) ||
325         NewTy->isInteger() && isa<PointerType>(SubType))
326       return false;
327   } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
328     // We are accessing the field, plus some structure padding.  Ignore the
329     // structure padding.
330     return false;
331   }
332
333
334   DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: " << Ty
335                   << "\n due to:" << NewTy << " @ " << Offset << "!\n"
336                   << "SubType: " << SubType << "\n\n");
337
338   foldNodeCompletely();
339   return true;
340 }
341
342
343
344 // addEdgeTo - Add an edge from the current node to the specified node.  This
345 // can cause merging of nodes in the graph.
346 //
347 void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
348   if (NH.getNode() == 0) return;       // Nothing to do
349
350   DSNodeHandle &ExistingEdge = getLink(Offset);
351   if (ExistingEdge.getNode()) {
352     // Merge the two nodes...
353     ExistingEdge.mergeWith(NH);
354   } else {                             // No merging to perform...
355     setLink(Offset, NH);               // Just force a link in there...
356   }
357 }
358
359
360 // MergeSortedVectors - Efficiently merge a vector into another vector where
361 // duplicates are not allowed and both are sorted.  This assumes that 'T's are
362 // efficiently copyable and have sane comparison semantics.
363 //
364 static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
365                                const std::vector<GlobalValue*> &Src) {
366   // By far, the most common cases will be the simple ones.  In these cases,
367   // avoid having to allocate a temporary vector...
368   //
369   if (Src.empty()) {             // Nothing to merge in...
370     return;
371   } else if (Dest.empty()) {     // Just copy the result in...
372     Dest = Src;
373   } else if (Src.size() == 1) {  // Insert a single element...
374     const GlobalValue *V = Src[0];
375     std::vector<GlobalValue*>::iterator I =
376       std::lower_bound(Dest.begin(), Dest.end(), V);
377     if (I == Dest.end() || *I != Src[0])  // If not already contained...
378       Dest.insert(I, Src[0]);
379   } else if (Dest.size() == 1) {
380     GlobalValue *Tmp = Dest[0];           // Save value in temporary...
381     Dest = Src;                           // Copy over list...
382     std::vector<GlobalValue*>::iterator I =
383       std::lower_bound(Dest.begin(), Dest.end(), Tmp);
384     if (I == Dest.end() || *I != Tmp)     // If not already contained...
385       Dest.insert(I, Tmp);
386
387   } else {
388     // Make a copy to the side of Dest...
389     std::vector<GlobalValue*> Old(Dest);
390     
391     // Make space for all of the type entries now...
392     Dest.resize(Dest.size()+Src.size());
393     
394     // Merge the two sorted ranges together... into Dest.
395     std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
396     
397     // Now erase any duplicate entries that may have accumulated into the 
398     // vectors (because they were in both of the input sets)
399     Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
400   }
401 }
402
403
404 // MergeNodes() - Helper function for DSNode::mergeWith().
405 // This function does the hard work of merging two nodes, CurNodeH
406 // and NH after filtering out trivial cases and making sure that
407 // CurNodeH.offset >= NH.offset.
408 // 
409 // ***WARNING***
410 // Since merging may cause either node to go away, we must always
411 // use the node-handles to refer to the nodes.  These node handles are
412 // automatically updated during merging, so will always provide access
413 // to the correct node after a merge.
414 //
415 void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
416   assert(CurNodeH.getOffset() >= NH.getOffset() &&
417          "This should have been enforced in the caller.");
418
419   // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
420   // respect to NH.Offset) is now zero.  NOffset is the distance from the base
421   // of our object that N starts from.
422   //
423   unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
424   unsigned NSize = NH.getNode()->getSize();
425
426   // Merge the type entries of the two nodes together...
427   if (NH.getNode()->Ty != Type::VoidTy)
428     CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
429   assert((CurNodeH.getNode()->NodeType & DSNode::DEAD) == 0);
430
431   // If we are merging a node with a completely folded node, then both nodes are
432   // now completely folded.
433   //
434   if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
435     if (!NH.getNode()->isNodeCompletelyFolded()) {
436       NH.getNode()->foldNodeCompletely();
437       assert(NH.getNode() && NH.getOffset() == 0 &&
438              "folding did not make offset 0?");
439       NOffset = NH.getOffset();
440       NSize = NH.getNode()->getSize();
441       assert(NOffset == 0 && NSize == 1);
442     }
443   } else if (NH.getNode()->isNodeCompletelyFolded()) {
444     CurNodeH.getNode()->foldNodeCompletely();
445     assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
446            "folding did not make offset 0?");
447     NOffset = NH.getOffset();
448     NSize = NH.getNode()->getSize();
449     assert(NOffset == 0 && NSize == 1);
450   }
451
452   DSNode *N = NH.getNode();
453   if (CurNodeH.getNode() == N || N == 0) return;
454   assert((CurNodeH.getNode()->NodeType & DSNode::DEAD) == 0);
455
456   // Start forwarding to the new node!
457   CurNodeH.getNode()->NodeType |= N->NodeType;
458   N->forwardNode(CurNodeH.getNode(), NOffset);
459   assert((CurNodeH.getNode()->NodeType & DSNode::DEAD) == 0);
460
461   // Make all of the outgoing links of N now be outgoing links of CurNodeH.
462   //
463   for (unsigned i = 0; i < N->getNumLinks(); ++i) {
464     DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
465     if (Link.getNode()) {
466       // Compute the offset into the current node at which to
467       // merge this link.  In the common case, this is a linear
468       // relation to the offset in the original node (with
469       // wrapping), but if the current node gets collapsed due to
470       // recursive merging, we must make sure to merge in all remaining
471       // links at offset zero.
472       unsigned MergeOffset = 0;
473       DSNode *CN = CurNodeH.getNode();
474       if (CN->Size != 1)
475         MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
476       CN->addEdgeTo(MergeOffset, Link);
477     }
478   }
479
480   // Now that there are no outgoing edges, all of the Links are dead.
481   N->Links.clear();
482
483   // Merge the globals list...
484   if (!N->Globals.empty()) {
485     MergeSortedVectors(CurNodeH.getNode()->Globals, N->Globals);
486
487     // Delete the globals from the old node...
488     std::vector<GlobalValue*>().swap(N->Globals);
489   }
490 }
491
492
493 // mergeWith - Merge this node and the specified node, moving all links to and
494 // from the argument node into the current node, deleting the node argument.
495 // Offset indicates what offset the specified node is to be merged into the
496 // current node.
497 //
498 // The specified node may be a null pointer (in which case, nothing happens).
499 //
500 void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
501   DSNode *N = NH.getNode();
502   if (N == 0 || (N == this && NH.getOffset() == Offset))
503     return;  // Noop
504
505   assert((N->NodeType & DSNode::DEAD) == 0);
506   assert((NodeType & DSNode::DEAD) == 0);
507   assert(!hasNoReferrers() && "Should not try to fold a useless node!");
508
509   if (N == this) {
510     // We cannot merge two pieces of the same node together, collapse the node
511     // completely.
512     DEBUG(std::cerr << "Attempting to merge two chunks of"
513                     << " the same node together!\n");
514     foldNodeCompletely();
515     return;
516   }
517
518   // If both nodes are not at offset 0, make sure that we are merging the node
519   // at an later offset into the node with the zero offset.
520   //
521   if (Offset < NH.getOffset()) {
522     N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
523     return;
524   } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
525     // If the offsets are the same, merge the smaller node into the bigger node
526     N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
527     return;
528   }
529
530   // Ok, now we can merge the two nodes.  Use a static helper that works with
531   // two node handles, since "this" may get merged away at intermediate steps.
532   DSNodeHandle CurNodeH(this, Offset);
533   DSNodeHandle NHCopy(NH);
534   DSNode::MergeNodes(CurNodeH, NHCopy);
535 }
536
537 //===----------------------------------------------------------------------===//
538 // DSCallSite Implementation
539 //===----------------------------------------------------------------------===//
540
541 // Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
542 Function &DSCallSite::getCaller() const {
543   return *Inst->getParent()->getParent();
544 }
545
546
547 //===----------------------------------------------------------------------===//
548 // DSGraph Implementation
549 //===----------------------------------------------------------------------===//
550
551 DSGraph::DSGraph(const DSGraph &G) : Func(G.Func), GlobalsGraph(0) {
552   PrintAuxCalls = false;
553   hash_map<const DSNode*, DSNodeHandle> NodeMap;
554   RetNode = cloneInto(G, ScalarMap, NodeMap);
555 }
556
557 DSGraph::DSGraph(const DSGraph &G,
558                  hash_map<const DSNode*, DSNodeHandle> &NodeMap)
559   : Func(G.Func), GlobalsGraph(0) {
560   PrintAuxCalls = false;
561   RetNode = cloneInto(G, ScalarMap, NodeMap);
562 }
563
564 DSGraph::~DSGraph() {
565   FunctionCalls.clear();
566   AuxFunctionCalls.clear();
567   ScalarMap.clear();
568   RetNode.setNode(0);
569
570   // Drop all intra-node references, so that assertions don't fail...
571   std::for_each(Nodes.begin(), Nodes.end(),
572                 std::mem_fun(&DSNode::dropAllReferences));
573
574   // Delete all of the nodes themselves...
575   std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
576 }
577
578 // dump - Allow inspection of graph in a debugger.
579 void DSGraph::dump() const { print(std::cerr); }
580
581
582 /// remapLinks - Change all of the Links in the current node according to the
583 /// specified mapping.
584 ///
585 void DSNode::remapLinks(hash_map<const DSNode*, DSNodeHandle> &OldNodeMap) {
586   for (unsigned i = 0, e = Links.size(); i != e; ++i) {
587     DSNodeHandle &H = OldNodeMap[Links[i].getNode()];
588     Links[i].setNode(H.getNode());
589     Links[i].setOffset(Links[i].getOffset()+H.getOffset());
590   }
591 }
592
593
594 // cloneInto - Clone the specified DSGraph into the current graph, returning the
595 // Return node of the graph.  The translated ScalarMap for the old function is
596 // filled into the OldValMap member.  If StripAllocas is set to true, Alloca
597 // markers are removed from the graph, as the graph is being cloned into a
598 // calling function's graph.
599 //
600 DSNodeHandle DSGraph::cloneInto(const DSGraph &G, 
601                                 hash_map<Value*, DSNodeHandle> &OldValMap,
602                               hash_map<const DSNode*, DSNodeHandle> &OldNodeMap,
603                                 unsigned CloneFlags) {
604   assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
605   assert(&G != this && "Cannot clone graph into itself!");
606
607   unsigned FN = Nodes.size();           // First new node...
608
609   // Duplicate all of the nodes, populating the node map...
610   Nodes.reserve(FN+G.Nodes.size());
611
612   // Remove alloca or mod/ref bits as specified...
613   unsigned clearBits = (CloneFlags & StripAllocaBit ? DSNode::AllocaNode : 0)
614     | (CloneFlags & StripModRefBits ? (DSNode::Modified | DSNode::Read) : 0);
615   clearBits |= DSNode::DEAD;  // Clear dead flag...
616   for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
617     DSNode *Old = G.Nodes[i];
618     DSNode *New = new DSNode(*Old, this);
619     New->NodeType &= ~clearBits;
620     OldNodeMap[Old] = New;
621   }
622
623 #ifndef NDEBUG
624   Timer::addPeakMemoryMeasurement();
625 #endif
626
627   // Rewrite the links in the new nodes to point into the current graph now.
628   for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
629     Nodes[i]->remapLinks(OldNodeMap);
630
631   // Copy the scalar map... merging all of the global nodes...
632   for (hash_map<Value*, DSNodeHandle>::const_iterator I = G.ScalarMap.begin(),
633          E = G.ScalarMap.end(); I != E; ++I) {
634     DSNodeHandle &H = OldValMap[I->first];
635     DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
636     H.setOffset(I->second.getOffset()+MappedNode.getOffset());
637     H.setNode(MappedNode.getNode());
638
639     if (isa<GlobalValue>(I->first)) {  // Is this a global?
640       hash_map<Value*, DSNodeHandle>::iterator GVI = ScalarMap.find(I->first);
641       if (GVI != ScalarMap.end())     // Is the global value in this fn already?
642         GVI->second.mergeWith(H);
643       else
644         ScalarMap[I->first] = H;      // Add global pointer to this graph
645     }
646   }
647
648   if (!(CloneFlags & DontCloneCallNodes)) {
649     // Copy the function calls list...
650     unsigned FC = FunctionCalls.size();  // FirstCall
651     FunctionCalls.reserve(FC+G.FunctionCalls.size());
652     for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
653       FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
654   }
655
656   if (!(CloneFlags & DontCloneAuxCallNodes)) {
657     // Copy the auxillary function calls list...
658     unsigned FC = AuxFunctionCalls.size();  // FirstCall
659     AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
660     for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
661       AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
662   }
663
664   // Return the returned node pointer...
665   DSNodeHandle &MappedRet = OldNodeMap[G.RetNode.getNode()];
666   return DSNodeHandle(MappedRet.getNode(),
667                       MappedRet.getOffset()+G.RetNode.getOffset());
668 }
669
670 /// mergeInGraph - The method is used for merging graphs together.  If the
671 /// argument graph is not *this, it makes a clone of the specified graph, then
672 /// merges the nodes specified in the call site with the formal arguments in the
673 /// graph.
674 ///
675 void DSGraph::mergeInGraph(DSCallSite &CS, const DSGraph &Graph,
676                            unsigned CloneFlags) {
677   hash_map<Value*, DSNodeHandle> OldValMap;
678   DSNodeHandle RetVal;
679   hash_map<Value*, DSNodeHandle> *ScalarMap = &OldValMap;
680
681   // If this is not a recursive call, clone the graph into this graph...
682   if (&Graph != this) {
683     // Clone the callee's graph into the current graph, keeping
684     // track of where scalars in the old graph _used_ to point,
685     // and of the new nodes matching nodes of the old graph.
686     hash_map<const DSNode*, DSNodeHandle> OldNodeMap;
687     
688     // The clone call may invalidate any of the vectors in the data
689     // structure graph.  Strip locals and don't copy the list of callers
690     RetVal = cloneInto(Graph, OldValMap, OldNodeMap, CloneFlags);
691     ScalarMap = &OldValMap;
692   } else {
693     RetVal = getRetNode();
694     ScalarMap = &getScalarMap();
695   }
696
697   // Merge the return value with the return value of the context...
698   RetVal.mergeWith(CS.getRetVal());
699
700   // Resolve all of the function arguments...
701   Function &F = Graph.getFunction();
702   Function::aiterator AI = F.abegin();
703
704   for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
705     // Advance the argument iterator to the first pointer argument...
706     while (AI != F.aend() && !isPointerType(AI->getType())) {
707       ++AI;
708 #ifndef NDEBUG
709       if (AI == F.aend())
710         std::cerr << "Bad call to Function: " << F.getName() << "\n";
711 #endif
712     }
713     if (AI == F.aend()) break;
714     
715     // Add the link from the argument scalar to the provided value
716     assert(ScalarMap->count(AI) && "Argument not in scalar map?");
717     DSNodeHandle &NH = (*ScalarMap)[AI];
718     assert(NH.getNode() && "Pointer argument without scalarmap entry?");
719     NH.mergeWith(CS.getPtrArg(i));
720   }
721 }
722
723
724 // markIncompleteNodes - Mark the specified node as having contents that are not
725 // known with the current analysis we have performed.  Because a node makes all
726 // of the nodes it can reach imcomplete if the node itself is incomplete, we
727 // must recursively traverse the data structure graph, marking all reachable
728 // nodes as incomplete.
729 //
730 static void markIncompleteNode(DSNode *N) {
731   // Stop recursion if no node, or if node already marked...
732   if (N == 0 || (N->NodeType & DSNode::Incomplete)) return;
733
734   // Actually mark the node
735   N->NodeType |= DSNode::Incomplete;
736
737   // Recusively process children...
738   for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
739     if (DSNode *DSN = N->getLink(i).getNode())
740       markIncompleteNode(DSN);
741 }
742
743 static void markIncomplete(DSCallSite &Call) {
744   // Then the return value is certainly incomplete!
745   markIncompleteNode(Call.getRetVal().getNode());
746
747   // All objects pointed to by function arguments are incomplete!
748   for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
749     markIncompleteNode(Call.getPtrArg(i).getNode());
750 }
751
752 // markIncompleteNodes - Traverse the graph, identifying nodes that may be
753 // modified by other functions that have not been resolved yet.  This marks
754 // nodes that are reachable through three sources of "unknownness":
755 //
756 //  Global Variables, Function Calls, and Incoming Arguments
757 //
758 // For any node that may have unknown components (because something outside the
759 // scope of current analysis may have modified it), the 'Incomplete' flag is
760 // added to the NodeType.
761 //
762 void DSGraph::markIncompleteNodes(unsigned Flags) {
763   // Mark any incoming arguments as incomplete...
764   if ((Flags & DSGraph::MarkFormalArgs) && Func && Func->getName() != "main")
765     for (Function::aiterator I = Func->abegin(), E = Func->aend(); I != E; ++I)
766       if (isPointerType(I->getType()) && ScalarMap.find(I) != ScalarMap.end())
767         markIncompleteNode(ScalarMap[I].getNode());
768
769   // Mark stuff passed into functions calls as being incomplete...
770   if (!shouldPrintAuxCalls())
771     for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
772       markIncomplete(FunctionCalls[i]);
773   else
774     for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
775       markIncomplete(AuxFunctionCalls[i]);
776     
777
778   // Mark all global nodes as incomplete...
779   if ((Flags & DSGraph::IgnoreGlobals) == 0)
780     for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
781       if (Nodes[i]->NodeType & DSNode::GlobalNode)
782         markIncompleteNode(Nodes[i]);
783 }
784
785 static inline void killIfUselessEdge(DSNodeHandle &Edge) {
786   if (DSNode *N = Edge.getNode())  // Is there an edge?
787     if (N->getNumReferrers() == 1)  // Does it point to a lonely node?
788       if ((N->NodeType & ~DSNode::Incomplete) == 0 && // No interesting info?
789           N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
790         Edge.setNode(0);  // Kill the edge!
791 }
792
793 static inline bool nodeContainsExternalFunction(const DSNode *N) {
794   const std::vector<GlobalValue*> &Globals = N->getGlobals();
795   for (unsigned i = 0, e = Globals.size(); i != e; ++i)
796     if (Globals[i]->isExternal())
797       return true;
798   return false;
799 }
800
801 static void removeIdenticalCalls(std::vector<DSCallSite> &Calls,
802                                  const std::string &where) {
803   // Remove trivially identical function calls
804   unsigned NumFns = Calls.size();
805   std::sort(Calls.begin(), Calls.end());  // Sort by callee as primary key!
806
807   // Scan the call list cleaning it up as necessary...
808   DSNode   *LastCalleeNode = 0;
809   Function *LastCalleeFunc = 0;
810   unsigned NumDuplicateCalls = 0;
811   bool LastCalleeContainsExternalFunction = false;
812   for (unsigned i = 0; i != Calls.size(); ++i) {
813     DSCallSite &CS = Calls[i];
814
815     // If the Callee is a useless edge, this must be an unreachable call site,
816     // eliminate it.
817     if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
818         CS.getCalleeNode()->NodeType == 0) {  // No useful info?
819       std::cerr << "WARNING: Useless call site found??\n";
820       CS.swap(Calls.back());
821       Calls.pop_back();
822       --i;
823     } else {
824       // If the return value or any arguments point to a void node with no
825       // information at all in it, and the call node is the only node to point
826       // to it, remove the edge to the node (killing the node).
827       //
828       killIfUselessEdge(CS.getRetVal());
829       for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
830         killIfUselessEdge(CS.getPtrArg(a));
831       
832       // If this call site calls the same function as the last call site, and if
833       // the function pointer contains an external function, this node will
834       // never be resolved.  Merge the arguments of the call node because no
835       // information will be lost.
836       //
837       if ((CS.isDirectCall()   && CS.getCalleeFunc() == LastCalleeFunc) ||
838           (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
839         ++NumDuplicateCalls;
840         if (NumDuplicateCalls == 1) {
841           if (LastCalleeNode)
842             LastCalleeContainsExternalFunction =
843               nodeContainsExternalFunction(LastCalleeNode);
844           else
845             LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
846         }
847         
848         if (LastCalleeContainsExternalFunction ||
849             // This should be more than enough context sensitivity!
850             // FIXME: Evaluate how many times this is tripped!
851             NumDuplicateCalls > 20) {
852           DSCallSite &OCS = Calls[i-1];
853           OCS.mergeWith(CS);
854           
855           // The node will now be eliminated as a duplicate!
856           if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
857             CS = OCS;
858           else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
859             OCS = CS;
860         }
861       } else {
862         if (CS.isDirectCall()) {
863           LastCalleeFunc = CS.getCalleeFunc();
864           LastCalleeNode = 0;
865         } else {
866           LastCalleeNode = CS.getCalleeNode();
867           LastCalleeFunc = 0;
868         }
869         NumDuplicateCalls = 0;
870       }
871     }
872   }
873
874   Calls.erase(std::unique(Calls.begin(), Calls.end()),
875               Calls.end());
876
877   // Track the number of call nodes merged away...
878   NumCallNodesMerged += NumFns-Calls.size();
879
880   DEBUG(if (NumFns != Calls.size())
881           std::cerr << "Merged " << (NumFns-Calls.size())
882                     << " call nodes in " << where << "\n";);
883 }
884
885
886 // removeTriviallyDeadNodes - After the graph has been constructed, this method
887 // removes all unreachable nodes that are created because they got merged with
888 // other nodes in the graph.  These nodes will all be trivially unreachable, so
889 // we don't have to perform any non-trivial analysis here.
890 //
891 void DSGraph::removeTriviallyDeadNodes() {
892   removeIdenticalCalls(FunctionCalls, Func ? Func->getName() : "");
893   removeIdenticalCalls(AuxFunctionCalls, Func ? Func->getName() : "");
894
895   for (unsigned i = 0; i != Nodes.size(); ++i) {
896     DSNode *Node = Nodes[i];
897     if (!(Node->NodeType & ~(DSNode::Composition | DSNode::Array |
898                              DSNode::DEAD))) {
899       // This is a useless node if it has no mod/ref info (checked above),
900       // outgoing edges (which it cannot, as it is not modified in this
901       // context), and it has no incoming edges.  If it is a global node it may
902       // have all of these properties and still have incoming edges, due to the
903       // scalar map, so we check those now.
904       //
905       if (Node->getNumReferrers() == Node->getGlobals().size()) {
906         std::vector<GlobalValue*> &Globals = Node->getGlobals();
907
908         // Loop through and make sure all of the globals are referring directly
909         // to the node...
910         for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
911           DSNode *N = ScalarMap.find(Globals[j])->second.getNode();
912           assert(N == Node && "ScalarMap doesn't match globals list!");
913         }
914
915         // Make sure numreferrers still agrees, if so, the node is truely dead.
916         if (Node->getNumReferrers() == Globals.size()) {
917           for (unsigned j = 0, e = Globals.size(); j != e; ++j)
918             ScalarMap.erase(Globals[j]);
919
920           Globals.clear();
921           assert(Node->hasNoReferrers() && "Shouldn't have refs now!");
922           
923           Node->NodeType = DSNode::DEAD;
924         }
925       }
926     }
927
928     if ((Node->NodeType & ~DSNode::DEAD) == 0 && Node->hasNoReferrers()) {
929       // This node is dead!
930       delete Node;                        // Free memory...
931       Nodes[i--] = Nodes.back();
932       Nodes.pop_back();                   // Remove from node list...
933     }
934   }
935 }
936
937
938 /// markReachableNodes - This method recursively traverses the specified
939 /// DSNodes, marking any nodes which are reachable.  All reachable nodes it adds
940 /// to the set, which allows it to only traverse visited nodes once.
941 ///
942 void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
943   if (this == 0) return;
944   assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
945   if (ReachableNodes.count(this)) return;          // Already marked reachable
946   ReachableNodes.insert(this);                     // Is reachable now
947
948   for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
949     getLink(i).getNode()->markReachableNodes(ReachableNodes);
950 }
951
952 void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
953   getRetVal().getNode()->markReachableNodes(Nodes);
954   if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
955   
956   for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
957     getPtrArg(i).getNode()->markReachableNodes(Nodes);
958 }
959
960 // CanReachAliveNodes - Simple graph walker that recursively traverses the graph
961 // looking for a node that is marked alive.  If an alive node is found, return
962 // true, otherwise return false.  If an alive node is reachable, this node is
963 // marked as alive...
964 //
965 static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
966                                hash_set<DSNode*> &Visited) {
967   if (N == 0) return false;
968   assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
969
970   // If we know that this node is alive, return so!
971   if (Alive.count(N)) return true;
972
973   // Otherwise, we don't think the node is alive yet, check for infinite
974   // recursion.
975   if (Visited.count(N)) return false;  // Found a cycle
976   Visited.insert(N);   // No recursion, insert into Visited...
977
978   for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
979     if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited)) {
980       N->markReachableNodes(Alive);
981       return true;
982     }
983   return false;
984 }
985
986 // CallSiteUsesAliveArgs - Return true if the specified call site can reach any
987 // alive nodes.
988 //
989 static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
990                                   hash_set<DSNode*> &Visited) {
991   if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited))
992     return true;
993   if (CS.isIndirectCall() &&
994       CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited))
995     return true;
996   for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
997     if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited))
998       return true;
999   return false;
1000 }
1001
1002 // removeDeadNodes - Use a more powerful reachability analysis to eliminate
1003 // subgraphs that are unreachable.  This often occurs because the data
1004 // structure doesn't "escape" into it's caller, and thus should be eliminated
1005 // from the caller's graph entirely.  This is only appropriate to use when
1006 // inlining graphs.
1007 //
1008 void DSGraph::removeDeadNodes(unsigned Flags) {
1009   // Reduce the amount of work we have to do... remove dummy nodes left over by
1010   // merging...
1011   removeTriviallyDeadNodes();
1012
1013   // FIXME: Merge nontrivially identical call nodes...
1014
1015   // Alive - a set that holds all nodes found to be reachable/alive.
1016   hash_set<DSNode*> Alive;
1017   std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
1018
1019   // Mark all nodes reachable by (non-global) scalar nodes as alive...
1020   for (hash_map<Value*, DSNodeHandle>::iterator I = ScalarMap.begin(),
1021          E = ScalarMap.end(); I != E; ++I)
1022     if (!isa<GlobalValue>(I->first))
1023       I->second.getNode()->markReachableNodes(Alive);
1024     else {                   // Keep track of global nodes
1025       GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
1026       assert(I->second.getNode() && "Null global node?");
1027     }
1028
1029   // The return value is alive as well...
1030   RetNode.getNode()->markReachableNodes(Alive);
1031
1032   // Mark any nodes reachable by primary calls as alive...
1033   for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1034     FunctionCalls[i].markReachableNodes(Alive);
1035
1036   bool Iterate;
1037   hash_set<DSNode*> Visited;
1038   std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1039   do {
1040     Visited.clear();
1041     // If any global nodes points to a non-global that is "alive", the global is
1042     // "alive" as well...  Remove it from the GlobalNodes list so we only have
1043     // unreachable globals in the list.
1044     //
1045     Iterate = false;
1046     for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1047       if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited)) {
1048         std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to erase
1049         GlobalNodes.pop_back();                          // Erase efficiently
1050         Iterate = true;
1051       }
1052
1053     for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1054       if (!AuxFCallsAlive[i] &&
1055           CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited)) {
1056         AuxFunctionCalls[i].markReachableNodes(Alive);
1057         AuxFCallsAlive[i] = true;
1058         Iterate = true;
1059       }
1060   } while (Iterate);
1061
1062   // Remove all dead aux function calls...
1063   unsigned CurIdx = 0;
1064   for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1065     if (AuxFCallsAlive[i])
1066       AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
1067   if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1068     assert(GlobalsGraph && "No globals graph available??");
1069     // Move the unreachable call nodes to the globals graph...
1070     GlobalsGraph->AuxFunctionCalls.insert(GlobalsGraph->AuxFunctionCalls.end(),
1071                                           AuxFunctionCalls.begin()+CurIdx,
1072                                           AuxFunctionCalls.end());
1073   }
1074   // Crop all the useless ones out...
1075   AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1076                          AuxFunctionCalls.end());
1077
1078   // At this point, any nodes which are visited, but not alive, are nodes which
1079   // should be moved to the globals graph.  Loop over all nodes, eliminating
1080   // completely unreachable nodes, and moving visited nodes to the globals graph
1081   //
1082   std::vector<DSNode*> DeadNodes;
1083   DeadNodes.reserve(Nodes.size());
1084   for (unsigned i = 0; i != Nodes.size(); ++i)
1085     if (!Alive.count(Nodes[i])) {
1086       DSNode *N = Nodes[i];
1087       Nodes[i--] = Nodes.back();            // move node to end of vector
1088       Nodes.pop_back();                     // Erase node from alive list.
1089       if (!(Flags & DSGraph::RemoveUnreachableGlobals) &&  // Not in TD pass
1090           Visited.count(N)) {                    // Visited but not alive?
1091         GlobalsGraph->Nodes.push_back(N);        // Move node to globals graph
1092         N->setParentGraph(GlobalsGraph);
1093       } else {                                 // Otherwise, delete the node
1094         assert(((N->NodeType & DSNode::GlobalNode) == 0 ||
1095                 (Flags & DSGraph::RemoveUnreachableGlobals))
1096                && "Killing a global?");
1097         //std::cerr << "[" << i+1 << "/" << DeadNodes.size()
1098         //          << "] Node is dead: "; N->dump();
1099         DeadNodes.push_back(N);
1100         N->dropAllReferences();
1101       }
1102     } else {
1103       assert(Nodes[i]->getForwardNode() == 0 && "Alive forwarded node?");
1104     }
1105
1106   // Now that the nodes have either been deleted or moved to the globals graph,
1107   // loop over the scalarmap, updating the entries for globals...
1108   //
1109   if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {  // Not in the TD pass?
1110     // In this array we start the remapping, which can cause merging.  Because
1111     // of this, the DSNode pointers in GlobalNodes may be invalidated, so we
1112     // must always go through the ScalarMap (which contains DSNodeHandles [which
1113     // cannot be invalidated by merging]).
1114     //
1115     for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i) {
1116       Value *G = GlobalNodes[i].first;
1117       hash_map<Value*, DSNodeHandle>::iterator I = ScalarMap.find(G);
1118       assert(I != ScalarMap.end() && "Global not in scalar map anymore?");
1119       assert(I->second.getNode() && "Global not pointing to anything?");
1120       assert(!Alive.count(I->second.getNode()) && "Node is alive??");
1121       GlobalsGraph->ScalarMap[G].mergeWith(I->second);
1122       assert(GlobalsGraph->ScalarMap[G].getNode() &&
1123              "Global not pointing to anything?");
1124       ScalarMap.erase(I);
1125     }
1126
1127     // Merging leaves behind silly nodes, we remove them to avoid polluting the
1128     // globals graph.
1129     if (!GlobalNodes.empty())
1130       GlobalsGraph->removeTriviallyDeadNodes();
1131   } else {
1132     // If we are in the top-down pass, remove all unreachable globals from the
1133     // ScalarMap...
1134     for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
1135       ScalarMap.erase(GlobalNodes[i].first);
1136   }
1137
1138   // Loop over all of the dead nodes now, deleting them since their referrer
1139   // count is zero.
1140   for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1141     delete DeadNodes[i];
1142
1143   DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
1144 }
1145
1146 void DSGraph::AssertGraphOK() const {
1147   for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1148     Nodes[i]->assertOK();
1149   return;  // FIXME: remove
1150   for (hash_map<Value*, DSNodeHandle>::const_iterator I = ScalarMap.begin(),
1151          E = ScalarMap.end(); I != E; ++I) {
1152     assert(I->second.getNode() && "Null node in scalarmap!");
1153     AssertNodeInGraph(I->second.getNode());
1154     if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
1155       assert((I->second.getNode()->NodeType & DSNode::GlobalNode) &&
1156              "Global points to node, but node isn't global?");
1157       AssertNodeContainsGlobal(I->second.getNode(), GV);
1158     }
1159   }
1160   AssertCallNodesInGraph();
1161   AssertAuxCallNodesInGraph();
1162 }