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