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