Fix problem breaking GAP, use hasNoReferrers more
[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; i < Links.size(); ++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       foldNodeCompletely();
237       return true;
238     }
239   }
240
241   assert(O == Offset && "Could not achieve the correct offset!");
242
243   // If we found our type exactly, early exit
244   if (SubType == NewTy) return false;
245
246   // Okay, so we found the leader type at the offset requested.  Search the list
247   // of types that starts at this offset.  If SubType is currently an array or
248   // structure, the type desired may actually be the first element of the
249   // composite type...
250   //
251   unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
252   unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
253   while (SubType != NewTy) {
254     const Type *NextSubType = 0;
255     unsigned NextSubTypeSize = 0;
256     unsigned NextPadSize = 0;
257     switch (SubType->getPrimitiveID()) {
258     case Type::StructTyID: {
259       const StructType *STy = cast<StructType>(SubType);
260       const StructLayout &SL = *TD.getStructLayout(STy);
261       if (SL.MemberOffsets.size() > 1)
262         NextPadSize = SL.MemberOffsets[1];
263       else
264         NextPadSize = SubTypeSize;
265       NextSubType = STy->getElementTypes()[0];
266       NextSubTypeSize = TD.getTypeSize(NextSubType);
267       break;
268     }
269     case Type::ArrayTyID:
270       NextSubType = cast<ArrayType>(SubType)->getElementType();
271       NextSubTypeSize = TD.getTypeSize(NextSubType);
272       NextPadSize = NextSubTypeSize;
273       break;
274     default: ;
275       // fall out 
276     }
277
278     if (NextSubType == 0)
279       break;   // In the default case, break out of the loop
280
281     if (NextPadSize < NewTySize)
282       break;   // Don't allow shrinking to a smaller type than NewTySize
283     SubType = NextSubType;
284     SubTypeSize = NextSubTypeSize;
285     PadSize = NextPadSize;
286   }
287
288   // If we found the type exactly, return it...
289   if (SubType == NewTy)
290     return false;
291
292   // Check to see if we have a compatible, but different type...
293   if (NewTySize == SubTypeSize) {
294     // Check to see if this type is obviously convertable... int -> uint f.e.
295     if (NewTy->isLosslesslyConvertableTo(SubType))
296       return false;
297
298     // Check to see if we have a pointer & integer mismatch going on here,
299     // loading a pointer as a long, for example.
300     //
301     if (SubType->isInteger() && isa<PointerType>(NewTy) ||
302         NewTy->isInteger() && isa<PointerType>(SubType))
303       return false;
304   } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
305     // We are accessing the field, plus some structure padding.  Ignore the
306     // structure padding.
307     return false;
308   }
309
310
311   DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: " << Ty
312                   << "\n due to:" << NewTy << " @ " << Offset << "!\n"
313                   << "SubType: " << SubType << "\n\n");
314
315   foldNodeCompletely();
316   return true;
317 }
318
319
320
321 // addEdgeTo - Add an edge from the current node to the specified node.  This
322 // can cause merging of nodes in the graph.
323 //
324 void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
325   if (NH.getNode() == 0) return;       // Nothing to do
326
327   DSNodeHandle &ExistingEdge = getLink(Offset);
328   if (ExistingEdge.getNode()) {
329     // Merge the two nodes...
330     ExistingEdge.mergeWith(NH);
331   } else {                             // No merging to perform...
332     setLink(Offset, NH);               // Just force a link in there...
333   }
334 }
335
336
337 // MergeSortedVectors - Efficiently merge a vector into another vector where
338 // duplicates are not allowed and both are sorted.  This assumes that 'T's are
339 // efficiently copyable and have sane comparison semantics.
340 //
341 static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
342                                const std::vector<GlobalValue*> &Src) {
343   // By far, the most common cases will be the simple ones.  In these cases,
344   // avoid having to allocate a temporary vector...
345   //
346   if (Src.empty()) {             // Nothing to merge in...
347     return;
348   } else if (Dest.empty()) {     // Just copy the result in...
349     Dest = Src;
350   } else if (Src.size() == 1) {  // Insert a single element...
351     const GlobalValue *V = Src[0];
352     std::vector<GlobalValue*>::iterator I =
353       std::lower_bound(Dest.begin(), Dest.end(), V);
354     if (I == Dest.end() || *I != Src[0])  // If not already contained...
355       Dest.insert(I, Src[0]);
356   } else if (Dest.size() == 1) {
357     GlobalValue *Tmp = Dest[0];           // Save value in temporary...
358     Dest = Src;                           // Copy over list...
359     std::vector<GlobalValue*>::iterator I =
360       std::lower_bound(Dest.begin(), Dest.end(), Tmp);
361     if (I == Dest.end() || *I != Tmp)     // If not already contained...
362       Dest.insert(I, Tmp);
363
364   } else {
365     // Make a copy to the side of Dest...
366     std::vector<GlobalValue*> Old(Dest);
367     
368     // Make space for all of the type entries now...
369     Dest.resize(Dest.size()+Src.size());
370     
371     // Merge the two sorted ranges together... into Dest.
372     std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
373     
374     // Now erase any duplicate entries that may have accumulated into the 
375     // vectors (because they were in both of the input sets)
376     Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
377   }
378 }
379
380
381 // MergeNodes() - Helper function for DSNode::mergeWith().
382 // This function does the hard work of merging two nodes, CurNodeH
383 // and NH after filtering out trivial cases and making sure that
384 // CurNodeH.offset >= NH.offset.
385 // 
386 // ***WARNING***
387 // Since merging may cause either node to go away, we must always
388 // use the node-handles to refer to the nodes.  These node handles are
389 // automatically updated during merging, so will always provide access
390 // to the correct node after a merge.
391 //
392 void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
393   assert(CurNodeH.getOffset() >= NH.getOffset() &&
394          "This should have been enforced in the caller.");
395
396   // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
397   // respect to NH.Offset) is now zero.  NOffset is the distance from the base
398   // of our object that N starts from.
399   //
400   unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
401   unsigned NSize = NH.getNode()->getSize();
402
403   // Merge the type entries of the two nodes together...
404   if (NH.getNode()->Ty != Type::VoidTy) {
405     CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
406   }
407   assert((CurNodeH.getNode()->NodeType & DSNode::DEAD) == 0);
408
409   // If we are merging a node with a completely folded node, then both nodes are
410   // now completely folded.
411   //
412   if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
413     if (!NH.getNode()->isNodeCompletelyFolded()) {
414       NH.getNode()->foldNodeCompletely();
415       assert(NH.getOffset()==0 && "folding did not make offset 0?");
416       NOffset = NH.getOffset();
417       NSize = NH.getNode()->getSize();
418       assert(NOffset == 0 && NSize == 1);
419     }
420   } else if (NH.getNode()->isNodeCompletelyFolded()) {
421     CurNodeH.getNode()->foldNodeCompletely();
422     assert(CurNodeH.getOffset()==0 && "folding did not make offset 0?");
423     NOffset = NH.getOffset();
424     NSize = NH.getNode()->getSize();
425     assert(NOffset == 0 && NSize == 1);
426   }
427
428   if (CurNodeH.getNode() == NH.getNode() || NH.getNode() == 0) return;
429   assert((CurNodeH.getNode()->NodeType & DSNode::DEAD) == 0);
430
431   // Remove all edges pointing at N, causing them to point to 'this' instead.
432   // Make sure to adjust their offset, not just the node pointer.
433   // Also, be careful to use the DSNode* rather than NH since NH is one of
434   // the referrers and once NH refers to CurNodeH.getNode() this will
435   // become an infinite loop.
436   DSNode* N = NH.getNode();
437   unsigned OldNHOffset = NH.getOffset();
438   while (!N->Referrers.empty()) {
439     DSNodeHandle &Ref = *N->Referrers.back();
440     Ref = DSNodeHandle(CurNodeH.getNode(), NOffset+Ref.getOffset());
441   }
442   NH = DSNodeHandle(N, OldNHOffset);  // reset NH to point back to where it was
443
444   assert((CurNodeH.getNode()->NodeType & DSNode::DEAD) == 0);
445
446   // Make all of the outgoing links of *NH now be outgoing links of
447   // this.  This can cause recursive merging!
448   // 
449   for (unsigned i = 0; i < NH.getNode()->getSize(); i += DS::PointerSize) {
450     DSNodeHandle &Link = NH.getNode()->getLink(i);
451     if (Link.getNode()) {
452       // Compute the offset into the current node at which to
453       // merge this link.  In the common case, this is a linear
454       // relation to the offset in the original node (with
455       // wrapping), but if the current node gets collapsed due to
456       // recursive merging, we must make sure to merge in all remaining
457       // links at offset zero.
458       unsigned MergeOffset = 0;
459       if (CurNodeH.getNode()->Size != 1)
460         MergeOffset = (i+NOffset) % CurNodeH.getNode()->getSize();
461       CurNodeH.getNode()->addEdgeTo(MergeOffset, Link);
462     }
463   }
464
465   // Now that there are no outgoing edges, all of the Links are dead.
466   NH.getNode()->Links.clear();
467   NH.getNode()->Size = 0;
468   NH.getNode()->Ty = Type::VoidTy;
469
470   // Merge the node types
471   CurNodeH.getNode()->NodeType |= NH.getNode()->NodeType;
472   NH.getNode()->NodeType = DEAD;   // NH is now a dead node.
473
474   // Merge the globals list...
475   if (!NH.getNode()->Globals.empty()) {
476     MergeSortedVectors(CurNodeH.getNode()->Globals, NH.getNode()->Globals);
477
478     // Delete the globals from the old node...
479     NH.getNode()->Globals.clear();
480   }
481 }
482
483
484 // mergeWith - Merge this node and the specified node, moving all links to and
485 // from the argument node into the current node, deleting the node argument.
486 // Offset indicates what offset the specified node is to be merged into the
487 // current node.
488 //
489 // The specified node may be a null pointer (in which case, nothing happens).
490 //
491 void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
492   DSNode *N = NH.getNode();
493   if (N == 0 || (N == this && NH.getOffset() == Offset))
494     return;  // Noop
495
496   assert((N->NodeType & DSNode::DEAD) == 0);
497   assert((NodeType & DSNode::DEAD) == 0);
498   assert(!hasNoReferrers() && "Should not try to fold a useless node!");
499
500   if (N == this) {
501     // We cannot merge two pieces of the same node together, collapse the node
502     // completely.
503     DEBUG(std::cerr << "Attempting to merge two chunks of"
504                     << " the same node together!\n");
505     foldNodeCompletely();
506     return;
507   }
508
509   // If both nodes are not at offset 0, make sure that we are merging the node
510   // at an later offset into the node with the zero offset.
511   //
512   if (Offset < NH.getOffset()) {
513     N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
514     return;
515   } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
516     // If the offsets are the same, merge the smaller node into the bigger node
517     N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
518     return;
519   }
520
521   // Ok, now we can merge the two nodes.  Use a static helper that works with
522   // two node handles, since "this" may get merged away at intermediate steps.
523   DSNodeHandle CurNodeH(this, Offset);
524   DSNodeHandle NHCopy(NH);
525   DSNode::MergeNodes(CurNodeH, NHCopy);
526 }
527
528 //===----------------------------------------------------------------------===//
529 // DSCallSite Implementation
530 //===----------------------------------------------------------------------===//
531
532 // Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
533 Function &DSCallSite::getCaller() const {
534   return *Inst->getParent()->getParent();
535 }
536
537
538 //===----------------------------------------------------------------------===//
539 // DSGraph Implementation
540 //===----------------------------------------------------------------------===//
541
542 DSGraph::DSGraph(const DSGraph &G) : Func(G.Func), GlobalsGraph(0) {
543   PrintAuxCalls = false;
544   hash_map<const DSNode*, DSNodeHandle> NodeMap;
545   RetNode = cloneInto(G, ScalarMap, NodeMap);
546 }
547
548 DSGraph::DSGraph(const DSGraph &G,
549                  hash_map<const DSNode*, DSNodeHandle> &NodeMap)
550   : Func(G.Func), GlobalsGraph(0) {
551   PrintAuxCalls = false;
552   RetNode = cloneInto(G, ScalarMap, NodeMap);
553 }
554
555 DSGraph::~DSGraph() {
556   FunctionCalls.clear();
557   AuxFunctionCalls.clear();
558   ScalarMap.clear();
559   RetNode.setNode(0);
560
561   // Drop all intra-node references, so that assertions don't fail...
562   std::for_each(Nodes.begin(), Nodes.end(),
563                 std::mem_fun(&DSNode::dropAllReferences));
564
565   // Delete all of the nodes themselves...
566   std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
567 }
568
569 // dump - Allow inspection of graph in a debugger.
570 void DSGraph::dump() const { print(std::cerr); }
571
572
573 /// remapLinks - Change all of the Links in the current node according to the
574 /// specified mapping.
575 ///
576 void DSNode::remapLinks(hash_map<const DSNode*, DSNodeHandle> &OldNodeMap) {
577   for (unsigned i = 0, e = Links.size(); i != e; ++i) {
578     DSNodeHandle &H = OldNodeMap[Links[i].getNode()];
579     Links[i].setNode(H.getNode());
580     Links[i].setOffset(Links[i].getOffset()+H.getOffset());
581   }
582 }
583
584
585 // cloneInto - Clone the specified DSGraph into the current graph, returning the
586 // Return node of the graph.  The translated ScalarMap for the old function is
587 // filled into the OldValMap member.  If StripAllocas is set to true, Alloca
588 // markers are removed from the graph, as the graph is being cloned into a
589 // calling function's graph.
590 //
591 DSNodeHandle DSGraph::cloneInto(const DSGraph &G, 
592                                 hash_map<Value*, DSNodeHandle> &OldValMap,
593                               hash_map<const DSNode*, DSNodeHandle> &OldNodeMap,
594                                 unsigned CloneFlags) {
595   assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
596   assert(&G != this && "Cannot clone graph into itself!");
597
598   unsigned FN = Nodes.size();           // First new node...
599
600   // Duplicate all of the nodes, populating the node map...
601   Nodes.reserve(FN+G.Nodes.size());
602
603   // Remove alloca or mod/ref bits as specified...
604   unsigned clearBits = (CloneFlags & StripAllocaBit ? DSNode::AllocaNode : 0)
605     | (CloneFlags & StripModRefBits ? (DSNode::Modified | DSNode::Read) : 0);
606   clearBits |= DSNode::DEAD;  // Clear dead flag...
607   for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
608     DSNode *Old = G.Nodes[i];
609     DSNode *New = new DSNode(*Old);
610     New->NodeType &= ~clearBits;
611     Nodes.push_back(New);
612     OldNodeMap[Old] = New;
613   }
614
615 #ifndef NDEBUG
616   Timer::addPeakMemoryMeasurement();
617 #endif
618
619   // Rewrite the links in the new nodes to point into the current graph now.
620   for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
621     Nodes[i]->remapLinks(OldNodeMap);
622
623   // Copy the scalar map... merging all of the global nodes...
624   for (hash_map<Value*, DSNodeHandle>::const_iterator I = G.ScalarMap.begin(),
625          E = G.ScalarMap.end(); I != E; ++I) {
626     DSNodeHandle &H = OldValMap[I->first];
627     DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
628     H.setNode(MappedNode.getNode());
629     H.setOffset(I->second.getOffset()+MappedNode.getOffset());
630
631     if (isa<GlobalValue>(I->first)) {  // Is this a global?
632       hash_map<Value*, DSNodeHandle>::iterator GVI = ScalarMap.find(I->first);
633       if (GVI != ScalarMap.end())     // Is the global value in this fn already?
634         GVI->second.mergeWith(H);
635       else
636         ScalarMap[I->first] = H;      // Add global pointer to this graph
637     }
638   }
639
640   if (!(CloneFlags & DontCloneCallNodes)) {
641     // Copy the function calls list...
642     unsigned FC = FunctionCalls.size();  // FirstCall
643     FunctionCalls.reserve(FC+G.FunctionCalls.size());
644     for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
645       FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
646   }
647
648   if (!(CloneFlags & DontCloneAuxCallNodes)) {
649     // Copy the auxillary function calls list...
650     unsigned FC = AuxFunctionCalls.size();  // FirstCall
651     AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
652     for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
653       AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
654   }
655
656   // Return the returned node pointer...
657   DSNodeHandle &MappedRet = OldNodeMap[G.RetNode.getNode()];
658   return DSNodeHandle(MappedRet.getNode(),
659                       MappedRet.getOffset()+G.RetNode.getOffset());
660 }
661
662 /// mergeInGraph - The method is used for merging graphs together.  If the
663 /// argument graph is not *this, it makes a clone of the specified graph, then
664 /// merges the nodes specified in the call site with the formal arguments in the
665 /// graph.
666 ///
667 void DSGraph::mergeInGraph(DSCallSite &CS, const DSGraph &Graph,
668                            unsigned CloneFlags) {
669   hash_map<Value*, DSNodeHandle> OldValMap;
670   DSNodeHandle RetVal;
671   hash_map<Value*, DSNodeHandle> *ScalarMap = &OldValMap;
672
673   // If this is not a recursive call, clone the graph into this graph...
674   if (&Graph != this) {
675     // Clone the callee's graph into the current graph, keeping
676     // track of where scalars in the old graph _used_ to point,
677     // and of the new nodes matching nodes of the old graph.
678     hash_map<const DSNode*, DSNodeHandle> OldNodeMap;
679     
680     // The clone call may invalidate any of the vectors in the data
681     // structure graph.  Strip locals and don't copy the list of callers
682     RetVal = cloneInto(Graph, OldValMap, OldNodeMap, CloneFlags);
683     ScalarMap = &OldValMap;
684   } else {
685     RetVal = getRetNode();
686     ScalarMap = &getScalarMap();
687   }
688
689   // Merge the return value with the return value of the context...
690   RetVal.mergeWith(CS.getRetVal());
691
692   // Resolve all of the function arguments...
693   Function &F = Graph.getFunction();
694   Function::aiterator AI = F.abegin();
695
696   for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
697     // Advance the argument iterator to the first pointer argument...
698     while (AI != F.aend() && !isPointerType(AI->getType())) {
699       ++AI;
700 #ifndef NDEBUG
701       if (AI == F.aend())
702         std::cerr << "Bad call to Function: " << F.getName() << "\n";
703 #endif
704     }
705     if (AI == F.aend()) break;
706     
707     // Add the link from the argument scalar to the provided value
708     DSNodeHandle &NH = (*ScalarMap)[AI];
709     assert(NH.getNode() && "Pointer argument without scalarmap entry?");
710     NH.mergeWith(CS.getPtrArg(i));
711   }
712 }
713
714
715 // markIncompleteNodes - Mark the specified node as having contents that are not
716 // known with the current analysis we have performed.  Because a node makes all
717 // of the nodes it can reach imcomplete if the node itself is incomplete, we
718 // must recursively traverse the data structure graph, marking all reachable
719 // nodes as incomplete.
720 //
721 static void markIncompleteNode(DSNode *N) {
722   // Stop recursion if no node, or if node already marked...
723   if (N == 0 || (N->NodeType & DSNode::Incomplete)) return;
724
725   // Actually mark the node
726   N->NodeType |= DSNode::Incomplete;
727
728   // Recusively process children...
729   for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
730     if (DSNode *DSN = N->getLink(i).getNode())
731       markIncompleteNode(DSN);
732 }
733
734 static void markIncomplete(DSCallSite &Call) {
735   // Then the return value is certainly incomplete!
736   markIncompleteNode(Call.getRetVal().getNode());
737
738   // All objects pointed to by function arguments are incomplete!
739   for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
740     markIncompleteNode(Call.getPtrArg(i).getNode());
741 }
742
743 // markIncompleteNodes - Traverse the graph, identifying nodes that may be
744 // modified by other functions that have not been resolved yet.  This marks
745 // nodes that are reachable through three sources of "unknownness":
746 //
747 //  Global Variables, Function Calls, and Incoming Arguments
748 //
749 // For any node that may have unknown components (because something outside the
750 // scope of current analysis may have modified it), the 'Incomplete' flag is
751 // added to the NodeType.
752 //
753 void DSGraph::markIncompleteNodes(unsigned Flags) {
754   // Mark any incoming arguments as incomplete...
755   if ((Flags & DSGraph::MarkFormalArgs) && Func && Func->getName() != "main")
756     for (Function::aiterator I = Func->abegin(), E = Func->aend(); I != E; ++I)
757       if (isPointerType(I->getType()) && ScalarMap.find(I) != ScalarMap.end())
758         markIncompleteNode(ScalarMap[I].getNode());
759
760   // Mark stuff passed into functions calls as being incomplete...
761   if (!shouldPrintAuxCalls())
762     for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
763       markIncomplete(FunctionCalls[i]);
764   else
765     for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
766       markIncomplete(AuxFunctionCalls[i]);
767     
768
769   // Mark all global nodes as incomplete...
770   if ((Flags & DSGraph::IgnoreGlobals) == 0)
771     for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
772       if (Nodes[i]->NodeType & DSNode::GlobalNode)
773         markIncompleteNode(Nodes[i]);
774 }
775
776 static inline void killIfUselessEdge(DSNodeHandle &Edge) {
777   if (DSNode *N = Edge.getNode())  // Is there an edge?
778     if (N->getReferrers().size() == 1)  // Does it point to a lonely node?
779       if ((N->NodeType & ~DSNode::Incomplete) == 0 && // No interesting info?
780           N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
781         Edge.setNode(0);  // Kill the edge!
782 }
783
784 static inline bool nodeContainsExternalFunction(const DSNode *N) {
785   const std::vector<GlobalValue*> &Globals = N->getGlobals();
786   for (unsigned i = 0, e = Globals.size(); i != e; ++i)
787     if (Globals[i]->isExternal())
788       return true;
789   return false;
790 }
791
792 static void removeIdenticalCalls(std::vector<DSCallSite> &Calls,
793                                  const std::string &where) {
794   // Remove trivially identical function calls
795   unsigned NumFns = Calls.size();
796   std::sort(Calls.begin(), Calls.end());  // Sort by callee as primary key!
797
798   // Scan the call list cleaning it up as necessary...
799   DSNode   *LastCalleeNode = 0;
800   Function *LastCalleeFunc = 0;
801   unsigned NumDuplicateCalls = 0;
802   bool LastCalleeContainsExternalFunction = false;
803   for (unsigned i = 0; i != Calls.size(); ++i) {
804     DSCallSite &CS = Calls[i];
805
806     // If the Callee is a useless edge, this must be an unreachable call site,
807     // eliminate it.
808     if (CS.isIndirectCall() && CS.getCalleeNode()->getReferrers().size() == 1 &&
809         CS.getCalleeNode()->NodeType == 0) {  // No useful info?
810       std::cerr << "WARNING: Useless call site found??\n";
811       CS.swap(Calls.back());
812       Calls.pop_back();
813       --i;
814     } else {
815       // If the return value or any arguments point to a void node with no
816       // information at all in it, and the call node is the only node to point
817       // to it, remove the edge to the node (killing the node).
818       //
819       killIfUselessEdge(CS.getRetVal());
820       for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
821         killIfUselessEdge(CS.getPtrArg(a));
822       
823       // If this call site calls the same function as the last call site, and if
824       // the function pointer contains an external function, this node will
825       // never be resolved.  Merge the arguments of the call node because no
826       // information will be lost.
827       //
828       if ((CS.isDirectCall()   && CS.getCalleeFunc() == LastCalleeFunc) ||
829           (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
830         ++NumDuplicateCalls;
831         if (NumDuplicateCalls == 1) {
832           if (LastCalleeNode)
833             LastCalleeContainsExternalFunction =
834               nodeContainsExternalFunction(LastCalleeNode);
835           else
836             LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
837         }
838         
839         if (LastCalleeContainsExternalFunction ||
840             // This should be more than enough context sensitivity!
841             // FIXME: Evaluate how many times this is tripped!
842             NumDuplicateCalls > 20) {
843           DSCallSite &OCS = Calls[i-1];
844           OCS.mergeWith(CS);
845           
846           // The node will now be eliminated as a duplicate!
847           if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
848             CS = OCS;
849           else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
850             OCS = CS;
851         }
852       } else {
853         if (CS.isDirectCall()) {
854           LastCalleeFunc = CS.getCalleeFunc();
855           LastCalleeNode = 0;
856         } else {
857           LastCalleeNode = CS.getCalleeNode();
858           LastCalleeFunc = 0;
859         }
860         NumDuplicateCalls = 0;
861       }
862     }
863   }
864
865   Calls.erase(std::unique(Calls.begin(), Calls.end()),
866               Calls.end());
867
868   // Track the number of call nodes merged away...
869   NumCallNodesMerged += NumFns-Calls.size();
870
871   DEBUG(if (NumFns != Calls.size())
872           std::cerr << "Merged " << (NumFns-Calls.size())
873                     << " call nodes in " << where << "\n";);
874 }
875
876
877 // removeTriviallyDeadNodes - After the graph has been constructed, this method
878 // removes all unreachable nodes that are created because they got merged with
879 // other nodes in the graph.  These nodes will all be trivially unreachable, so
880 // we don't have to perform any non-trivial analysis here.
881 //
882 void DSGraph::removeTriviallyDeadNodes() {
883   removeIdenticalCalls(FunctionCalls, Func ? Func->getName() : "");
884   removeIdenticalCalls(AuxFunctionCalls, Func ? Func->getName() : "");
885
886   for (unsigned i = 0; i != Nodes.size(); ++i) {
887     DSNode *Node = Nodes[i];
888     if (!(Node->NodeType & ~(DSNode::Composition | DSNode::Array |
889                              DSNode::DEAD))) {
890       // This is a useless node if it has no mod/ref info (checked above),
891       // outgoing edges (which it cannot, as it is not modified in this
892       // context), and it has no incoming edges.  If it is a global node it may
893       // have all of these properties and still have incoming edges, due to the
894       // scalar map, so we check those now.
895       //
896       if (Node->getReferrers().size() == Node->getGlobals().size()) {
897         std::vector<GlobalValue*> &Globals = Node->getGlobals();
898         for (unsigned j = 0, e = Globals.size(); j != e; ++j)
899           ScalarMap.erase(Globals[j]);
900         Globals.clear();
901           
902         Node->NodeType = DSNode::DEAD;
903       }
904     }
905
906     if ((Node->NodeType & ~DSNode::DEAD) == 0 && Node->hasNoReferrers()) {
907       // This node is dead!
908       delete Node;                        // Free memory...
909       Nodes.erase(Nodes.begin()+i--);         // Remove from node list...
910     }
911   }
912 }
913
914
915 /// markReachableNodes - This method recursively traverses the specified
916 /// DSNodes, marking any nodes which are reachable.  All reachable nodes it adds
917 /// to the set, which allows it to only traverse visited nodes once.
918 ///
919 void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
920   if (this == 0) return;
921   if (ReachableNodes.count(this)) return;          // Already marked reachable
922   ReachableNodes.insert(this);                     // Is reachable now
923
924   for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
925     getLink(i).getNode()->markReachableNodes(ReachableNodes);
926 }
927
928 void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
929   getRetVal().getNode()->markReachableNodes(Nodes);
930   if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
931   
932   for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
933     getPtrArg(i).getNode()->markReachableNodes(Nodes);
934 }
935
936 // CanReachAliveNodes - Simple graph walker that recursively traverses the graph
937 // looking for a node that is marked alive.  If an alive node is found, return
938 // true, otherwise return false.  If an alive node is reachable, this node is
939 // marked as alive...
940 //
941 static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
942                                hash_set<DSNode*> &Visited) {
943   if (N == 0) return false;
944
945   // If we know that this node is alive, return so!
946   if (Alive.count(N)) return true;
947
948   // Otherwise, we don't think the node is alive yet, check for infinite
949   // recursion.
950   if (Visited.count(N)) return false;  // Found a cycle
951   Visited.insert(N);   // No recursion, insert into Visited...
952
953   for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
954     if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited)) {
955       N->markReachableNodes(Alive);
956       return true;
957     }
958   return false;
959 }
960
961 // CallSiteUsesAliveArgs - Return true if the specified call site can reach any
962 // alive nodes.
963 //
964 static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
965                                   hash_set<DSNode*> &Visited) {
966   if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited))
967     return true;
968   if (CS.isIndirectCall() &&
969       CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited))
970     return true;
971   for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
972     if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited))
973       return true;
974   return false;
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(unsigned Flags) {
984   // Reduce the amount of work we have to do... remove dummy nodes left over by
985   // merging...
986   removeTriviallyDeadNodes();
987
988   // FIXME: Merge nontrivially identical call nodes...
989
990   // Alive - a set that holds all nodes found to be reachable/alive.
991   hash_set<DSNode*> Alive;
992   std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
993
994   // Mark all nodes reachable by (non-global) scalar nodes as alive...
995   for (hash_map<Value*, DSNodeHandle>::iterator I = ScalarMap.begin(),
996          E = ScalarMap.end(); I != E; ++I)
997     if (!isa<GlobalValue>(I->first))
998       I->second.getNode()->markReachableNodes(Alive);
999     else {                   // Keep track of global nodes
1000       GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
1001       assert(I->second.getNode() && "Null global node?");
1002     }
1003
1004   // The return value is alive as well...
1005   RetNode.getNode()->markReachableNodes(Alive);
1006
1007   // Mark any nodes reachable by primary calls as alive...
1008   for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1009     FunctionCalls[i].markReachableNodes(Alive);
1010
1011   bool Iterate;
1012   hash_set<DSNode*> Visited;
1013   std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1014   do {
1015     Visited.clear();
1016     // If any global nodes points to a non-global that is "alive", the global is
1017     // "alive" as well...  Remov it from the GlobalNodes list so we only have
1018     // unreachable globals in the list.
1019     //
1020     Iterate = false;
1021     for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1022       if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited)) {
1023         std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to erase
1024         GlobalNodes.pop_back();                          // Erase efficiently
1025         Iterate = true;
1026       }
1027
1028     for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1029       if (!AuxFCallsAlive[i] &&
1030           CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited)) {
1031         AuxFunctionCalls[i].markReachableNodes(Alive);
1032         AuxFCallsAlive[i] = true;
1033         Iterate = true;
1034       }
1035   } while (Iterate);
1036
1037   // Remove all dead aux function calls...
1038   unsigned CurIdx = 0;
1039   for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1040     if (AuxFCallsAlive[i])
1041       AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
1042   if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1043     assert(GlobalsGraph && "No globals graph available??");
1044     // Move the unreachable call nodes to the globals graph...
1045     GlobalsGraph->AuxFunctionCalls.insert(GlobalsGraph->AuxFunctionCalls.end(),
1046                                           AuxFunctionCalls.begin()+CurIdx,
1047                                           AuxFunctionCalls.end());
1048   }
1049   // Crop all the useless ones out...
1050   AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1051                          AuxFunctionCalls.end());
1052
1053   // At this point, any nodes which are visited, but not alive, are nodes which
1054   // should be moved to the globals graph.  Loop over all nodes, eliminating
1055   // completely unreachable nodes, and moving visited nodes to the globals graph
1056   //
1057   for (unsigned i = 0; i != Nodes.size(); ++i)
1058     if (!Alive.count(Nodes[i])) {
1059       DSNode *N = Nodes[i];
1060       std::swap(Nodes[i--], Nodes.back());  // move node to end of vector
1061       Nodes.pop_back();                // Erase node from alive list.
1062       if (!(Flags & DSGraph::RemoveUnreachableGlobals) &&  // Not in TD pass
1063           Visited.count(N)) {                    // Visited but not alive?
1064         GlobalsGraph->Nodes.push_back(N);        // Move node to globals graph
1065       } else {                                 // Otherwise, delete the node
1066         assert(((N->NodeType & DSNode::GlobalNode) == 0 ||
1067                 (Flags & DSGraph::RemoveUnreachableGlobals))
1068                && "Killing a global?");
1069         while (!N->hasNoReferrers())             // Rewrite referrers
1070           N->getReferrers().back()->setNode(0);
1071         delete N;                                // Usecount is zero
1072       }
1073     }
1074
1075   // Now that the nodes have either been deleted or moved to the globals graph,
1076   // loop over the scalarmap, updating the entries for globals...
1077   //
1078   if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {  // Not in the TD pass?
1079     // In this array we start the remapping, which can cause merging.  Because
1080     // of this, the DSNode pointers in GlobalNodes may be invalidated, so we
1081     // must always go through the ScalarMap (which contains DSNodeHandles [which
1082     // cannot be invalidated by merging]).
1083     //
1084     for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i) {
1085       Value *G = GlobalNodes[i].first;
1086       hash_map<Value*, DSNodeHandle>::iterator I = ScalarMap.find(G);
1087       assert(I != ScalarMap.end() && "Global not in scalar map anymore?");
1088       assert(I->second.getNode() && "Global not pointing to anything?");
1089       assert(!Alive.count(I->second.getNode()) && "Node is alive??");
1090       GlobalsGraph->ScalarMap[G].mergeWith(I->second);
1091       assert(GlobalsGraph->ScalarMap[G].getNode() &&
1092              "Global not pointing to anything?");
1093       ScalarMap.erase(I);
1094     }
1095
1096     // Merging leaves behind silly nodes, we remove them to avoid polluting the
1097     // globals graph.
1098     GlobalsGraph->removeTriviallyDeadNodes();
1099   } else {
1100     // If we are in the top-down pass, remove all unreachable globals from the
1101     // ScalarMap...
1102     for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
1103       ScalarMap.erase(GlobalNodes[i].first);
1104   }
1105
1106   DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
1107 }
1108
1109 void DSGraph::AssertGraphOK() const {
1110   for (hash_map<Value*, DSNodeHandle>::const_iterator I = ScalarMap.begin(),
1111          E = ScalarMap.end(); I != E; ++I) {
1112     assert(I->second.getNode() && "Null node in scalarmap!");
1113     AssertNodeInGraph(I->second.getNode());
1114     if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
1115       assert((I->second.getNode()->NodeType & DSNode::GlobalNode) &&
1116              "Global points to node, but node isn't global?");
1117       AssertNodeContainsGlobal(I->second.getNode(), GV);
1118     }
1119   }
1120   AssertCallNodesInGraph();
1121   AssertAuxCallNodesInGraph();
1122 }
1123
1124
1125 #if 0
1126 //===----------------------------------------------------------------------===//
1127 // GlobalDSGraph Implementation
1128 //===----------------------------------------------------------------------===//
1129
1130 #if 0
1131 // Bits used in the next function
1132 static const char ExternalTypeBits = DSNode::GlobalNode | DSNode::HeapNode;
1133
1134 // cloneGlobalInto - Clone the given global node and all its target links
1135 // (and all their llinks, recursively).
1136 // 
1137 DSNode *DSGraph::cloneGlobalInto(const DSNode *GNode) {
1138   if (GNode == 0 || GNode->getGlobals().size() == 0) return 0;
1139
1140   // If a clone has already been created for GNode, return it.
1141   DSNodeHandle& ValMapEntry = ScalarMap[GNode->getGlobals()[0]];
1142   if (ValMapEntry != 0)
1143     return ValMapEntry;
1144
1145   // Clone the node and update the ValMap.
1146   DSNode* NewNode = new DSNode(*GNode);
1147   ValMapEntry = NewNode;                // j=0 case of loop below!
1148   Nodes.push_back(NewNode);
1149   for (unsigned j = 1, N = NewNode->getGlobals().size(); j < N; ++j)
1150     ScalarMap[NewNode->getGlobals()[j]] = NewNode;
1151
1152   // Rewrite the links in the new node to point into the current graph.
1153   for (unsigned j = 0, e = GNode->getNumLinks(); j != e; ++j)
1154     NewNode->setLink(j, cloneGlobalInto(GNode->getLink(j)));
1155
1156   return NewNode;
1157 }
1158
1159 // GlobalDSGraph::cloneNodeInto - Clone a global node and all its externally
1160 // visible target links (and recursively their such links) into this graph.
1161 // NodeCache maps the node being cloned to its clone in the Globals graph,
1162 // in order to track cycles.
1163 // GlobalsAreFinal is a flag that says whether it is safe to assume that
1164 // an existing global node is complete.  This is important to avoid
1165 // reinserting all globals when inserting Calls to functions.
1166 // This is a helper function for cloneGlobals and cloneCalls.
1167 // 
1168 DSNode* GlobalDSGraph::cloneNodeInto(DSNode *OldNode,
1169                                     hash_map<const DSNode*, DSNode*> &NodeCache,
1170                                     bool GlobalsAreFinal) {
1171   if (OldNode == 0) return 0;
1172
1173   // The caller should check this is an external node.  Just more  efficient...
1174   assert((OldNode->NodeType & ExternalTypeBits) && "Non-external node");
1175
1176   // If a clone has already been created for OldNode, return it.
1177   DSNode*& CacheEntry = NodeCache[OldNode];
1178   if (CacheEntry != 0)
1179     return CacheEntry;
1180
1181   // The result value...
1182   DSNode* NewNode = 0;
1183
1184   // If nodes already exist for any of the globals of OldNode,
1185   // merge all such nodes together since they are merged in OldNode.
1186   // If ValueCacheIsFinal==true, look for an existing node that has
1187   // an identical list of globals and return it if it exists.
1188   //
1189   for (unsigned j = 0, N = OldNode->getGlobals().size(); j != N; ++j)
1190     if (DSNode *PrevNode = ScalarMap[OldNode->getGlobals()[j]].getNode()) {
1191       if (NewNode == 0) {
1192         NewNode = PrevNode;             // first existing node found
1193         if (GlobalsAreFinal && j == 0)
1194           if (OldNode->getGlobals() == PrevNode->getGlobals()) {
1195             CacheEntry = NewNode;
1196             return NewNode;
1197           }
1198       }
1199       else if (NewNode != PrevNode) {   // found another, different from prev
1200         // update ValMap *before* merging PrevNode into NewNode
1201         for (unsigned k = 0, NK = PrevNode->getGlobals().size(); k < NK; ++k)
1202           ScalarMap[PrevNode->getGlobals()[k]] = NewNode;
1203         NewNode->mergeWith(PrevNode);
1204       }
1205     } else if (NewNode != 0) {
1206       ScalarMap[OldNode->getGlobals()[j]] = NewNode; // add the merged node
1207     }
1208
1209   // If no existing node was found, clone the node and update the ValMap.
1210   if (NewNode == 0) {
1211     NewNode = new DSNode(*OldNode);
1212     Nodes.push_back(NewNode);
1213     for (unsigned j = 0, e = NewNode->getNumLinks(); j != e; ++j)
1214       NewNode->setLink(j, 0);
1215     for (unsigned j = 0, N = NewNode->getGlobals().size(); j < N; ++j)
1216       ScalarMap[NewNode->getGlobals()[j]] = NewNode;
1217   }
1218   else
1219     NewNode->NodeType |= OldNode->NodeType; // Markers may be different!
1220
1221   // Add the entry to NodeCache
1222   CacheEntry = NewNode;
1223
1224   // Rewrite the links in the new node to point into the current graph,
1225   // but only for links to external nodes.  Set other links to NULL.
1226   for (unsigned j = 0, e = OldNode->getNumLinks(); j != e; ++j) {
1227     DSNode* OldTarget = OldNode->getLink(j);
1228     if (OldTarget && (OldTarget->NodeType & ExternalTypeBits)) {
1229       DSNode* NewLink = this->cloneNodeInto(OldTarget, NodeCache);
1230       if (NewNode->getLink(j))
1231         NewNode->getLink(j)->mergeWith(NewLink);
1232       else
1233         NewNode->setLink(j, NewLink);
1234     }
1235   }
1236
1237   // Remove all local markers
1238   NewNode->NodeType &= ~(DSNode::AllocaNode | DSNode::ScalarNode);
1239
1240   return NewNode;
1241 }
1242
1243
1244 // GlobalDSGraph::cloneCalls - Clone function calls and their visible target
1245 // links (and recursively their such links) into this graph.
1246 // 
1247 void GlobalDSGraph::cloneCalls(DSGraph& Graph) {
1248   hash_map<const DSNode*, DSNode*> NodeCache;
1249   std::vector<DSCallSite >& FromCalls =Graph.FunctionCalls;
1250
1251   FunctionCalls.reserve(FunctionCalls.size() + FromCalls.size());
1252
1253   for (int i = 0, ei = FromCalls.size(); i < ei; ++i) {
1254     DSCallSite& callCopy = FunctionCalls.back();
1255     callCopy.reserve(FromCalls[i].size());
1256     for (unsigned j = 0, ej = FromCalls[i].size(); j != ej; ++j)
1257       callCopy.push_back
1258         ((FromCalls[i][j] && (FromCalls[i][j]->NodeType & ExternalTypeBits))
1259          ? cloneNodeInto(FromCalls[i][j], NodeCache, true)
1260          : 0);
1261   }
1262
1263   // remove trivially identical function calls
1264   removeIdenticalCalls(FunctionCalls, "Globals Graph");
1265 }
1266 #endif
1267
1268 #endif