Only clone global nodes between graphs if both graphs have the global.
[oota-llvm.git] / lib / Analysis / DataStructure / DataStructure.cpp
1 //===- DataStructure.cpp - Implement the core data structure analysis -----===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the core data structure functionality.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Analysis/DSGraph.h"
15 #include "llvm/Function.h"
16 #include "llvm/GlobalVariable.h"
17 #include "llvm/iOther.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Target/TargetData.h"
20 #include "llvm/Assembly/Writer.h"
21 #include "Support/CommandLine.h"
22 #include "Support/Debug.h"
23 #include "Support/STLExtras.h"
24 #include "Support/Statistic.h"
25 #include "Support/Timer.h"
26 #include <algorithm>
27 using namespace llvm;
28
29 namespace {
30   Statistic<> NumFolds          ("dsa", "Number of nodes completely folded");
31   Statistic<> NumCallNodesMerged("dsa", "Number of call nodes merged");
32   Statistic<> NumNodeAllocated  ("dsa", "Number of nodes allocated");
33   Statistic<> NumDNE            ("dsa", "Number of nodes removed by reachability");
34   Statistic<> NumTrivialDNE     ("dsa", "Number of nodes trivially removed");
35   Statistic<> NumTrivialGlobalDNE("dsa", "Number of globals trivially removed");
36 };
37
38 #if 1
39 #define TIME_REGION(VARNAME, DESC) \
40    NamedRegionTimer VARNAME(DESC)
41 #else
42 #define TIME_REGION(VARNAME, DESC)
43 #endif
44
45 using namespace DS;
46
47 DSNode *DSNodeHandle::HandleForwarding() const {
48   assert(N->isForwarding() && "Can only be invoked if forwarding!");
49
50   // Handle node forwarding here!
51   DSNode *Next = N->ForwardNH.getNode();  // Cause recursive shrinkage
52   Offset += N->ForwardNH.getOffset();
53
54   if (--N->NumReferrers == 0) {
55     // Removing the last referrer to the node, sever the forwarding link
56     N->stopForwarding();
57   }
58
59   N = Next;
60   N->NumReferrers++;
61   if (N->Size <= Offset) {
62     assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
63     Offset = 0;
64   }
65   return N;
66 }
67
68 //===----------------------------------------------------------------------===//
69 // DSNode Implementation
70 //===----------------------------------------------------------------------===//
71
72 DSNode::DSNode(const Type *T, DSGraph *G)
73   : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
74   // Add the type entry if it is specified...
75   if (T) mergeTypeInfo(T, 0);
76   if (G) G->addNode(this);
77   ++NumNodeAllocated;
78 }
79
80 // DSNode copy constructor... do not copy over the referrers list!
81 DSNode::DSNode(const DSNode &N, DSGraph *G, bool NullLinks)
82   : NumReferrers(0), Size(N.Size), ParentGraph(G),
83     Ty(N.Ty), Globals(N.Globals), NodeType(N.NodeType) {
84   if (!NullLinks)
85     Links = N.Links;
86   else
87     Links.resize(N.Links.size()); // Create the appropriate number of null links
88   G->addNode(this);
89   ++NumNodeAllocated;
90 }
91
92 /// getTargetData - Get the target data object used to construct this node.
93 ///
94 const TargetData &DSNode::getTargetData() const {
95   return ParentGraph->getTargetData();
96 }
97
98 void DSNode::assertOK() const {
99   assert((Ty != Type::VoidTy ||
100           Ty == Type::VoidTy && (Size == 0 ||
101                                  (NodeType & DSNode::Array))) &&
102          "Node not OK!");
103
104   assert(ParentGraph && "Node has no parent?");
105   const DSScalarMap &SM = ParentGraph->getScalarMap();
106   for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
107     assert(SM.count(Globals[i]));
108     assert(SM.find(Globals[i])->second.getNode() == this);
109   }
110 }
111
112 /// forwardNode - Mark this node as being obsolete, and all references to it
113 /// should be forwarded to the specified node and offset.
114 ///
115 void DSNode::forwardNode(DSNode *To, unsigned Offset) {
116   assert(this != To && "Cannot forward a node to itself!");
117   assert(ForwardNH.isNull() && "Already forwarding from this node!");
118   if (To->Size <= 1) Offset = 0;
119   assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
120          "Forwarded offset is wrong!");
121   ForwardNH.setNode(To);
122   ForwardNH.setOffset(Offset);
123   NodeType = DEAD;
124   Size = 0;
125   Ty = Type::VoidTy;
126
127   // Remove this node from the parent graph's Nodes list.
128   ParentGraph->unlinkNode(this);  
129   ParentGraph = 0;
130 }
131
132 // addGlobal - Add an entry for a global value to the Globals list.  This also
133 // marks the node with the 'G' flag if it does not already have it.
134 //
135 void DSNode::addGlobal(GlobalValue *GV) {
136   // Keep the list sorted.
137   std::vector<GlobalValue*>::iterator I =
138     std::lower_bound(Globals.begin(), Globals.end(), GV);
139
140   if (I == Globals.end() || *I != GV) {
141     //assert(GV->getType()->getElementType() == Ty);
142     Globals.insert(I, GV);
143     NodeType |= GlobalNode;
144   }
145 }
146
147 /// foldNodeCompletely - If we determine that this node has some funny
148 /// behavior happening to it that we cannot represent, we fold it down to a
149 /// single, completely pessimistic, node.  This node is represented as a
150 /// single byte with a single TypeEntry of "void".
151 ///
152 void DSNode::foldNodeCompletely() {
153   if (isNodeCompletelyFolded()) return;  // If this node is already folded...
154
155   ++NumFolds;
156
157   // If this node has a size that is <= 1, we don't need to create a forwarding
158   // node.
159   if (getSize() <= 1) {
160     NodeType |= DSNode::Array;
161     Ty = Type::VoidTy;
162     Size = 1;
163     assert(Links.size() <= 1 && "Size is 1, but has more links?");
164     Links.resize(1);
165   } else {
166     // Create the node we are going to forward to.  This is required because
167     // some referrers may have an offset that is > 0.  By forcing them to
168     // forward, the forwarder has the opportunity to correct the offset.
169     DSNode *DestNode = new DSNode(0, ParentGraph);
170     DestNode->NodeType = NodeType|DSNode::Array;
171     DestNode->Ty = Type::VoidTy;
172     DestNode->Size = 1;
173     DestNode->Globals.swap(Globals);
174     
175     // Start forwarding to the destination node...
176     forwardNode(DestNode, 0);
177     
178     if (!Links.empty()) {
179       DestNode->Links.reserve(1);
180       
181       DSNodeHandle NH(DestNode);
182       DestNode->Links.push_back(Links[0]);
183       
184       // If we have links, merge all of our outgoing links together...
185       for (unsigned i = Links.size()-1; i != 0; --i)
186         NH.getNode()->Links[0].mergeWith(Links[i]);
187       Links.clear();
188     } else {
189       DestNode->Links.resize(1);
190     }
191   }
192 }
193
194 /// isNodeCompletelyFolded - Return true if this node has been completely
195 /// folded down to something that can never be expanded, effectively losing
196 /// all of the field sensitivity that may be present in the node.
197 ///
198 bool DSNode::isNodeCompletelyFolded() const {
199   return getSize() == 1 && Ty == Type::VoidTy && isArray();
200 }
201
202 namespace {
203   /// TypeElementWalker Class - Used for implementation of physical subtyping...
204   ///
205   class TypeElementWalker {
206     struct StackState {
207       const Type *Ty;
208       unsigned Offset;
209       unsigned Idx;
210       StackState(const Type *T, unsigned Off = 0)
211         : Ty(T), Offset(Off), Idx(0) {}
212     };
213
214     std::vector<StackState> Stack;
215     const TargetData &TD;
216   public:
217     TypeElementWalker(const Type *T, const TargetData &td) : TD(td) {
218       Stack.push_back(T);
219       StepToLeaf();
220     }
221
222     bool isDone() const { return Stack.empty(); }
223     const Type *getCurrentType()   const { return Stack.back().Ty;     }
224     unsigned    getCurrentOffset() const { return Stack.back().Offset; }
225
226     void StepToNextType() {
227       PopStackAndAdvance();
228       StepToLeaf();
229     }
230
231   private:
232     /// PopStackAndAdvance - Pop the current element off of the stack and
233     /// advance the underlying element to the next contained member.
234     void PopStackAndAdvance() {
235       assert(!Stack.empty() && "Cannot pop an empty stack!");
236       Stack.pop_back();
237       while (!Stack.empty()) {
238         StackState &SS = Stack.back();
239         if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
240           ++SS.Idx;
241           if (SS.Idx != ST->getNumElements()) {
242             const StructLayout *SL = TD.getStructLayout(ST);
243             SS.Offset += SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1];
244             return;
245           }
246           Stack.pop_back();  // At the end of the structure
247         } else {
248           const ArrayType *AT = cast<ArrayType>(SS.Ty);
249           ++SS.Idx;
250           if (SS.Idx != AT->getNumElements()) {
251             SS.Offset += TD.getTypeSize(AT->getElementType());
252             return;
253           }
254           Stack.pop_back();  // At the end of the array
255         }
256       }
257     }
258
259     /// StepToLeaf - Used by physical subtyping to move to the first leaf node
260     /// on the type stack.
261     void StepToLeaf() {
262       if (Stack.empty()) return;
263       while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
264         StackState &SS = Stack.back();
265         if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
266           if (ST->getNumElements() == 0) {
267             assert(SS.Idx == 0);
268             PopStackAndAdvance();
269           } else {
270             // Step into the structure...
271             assert(SS.Idx < ST->getNumElements());
272             const StructLayout *SL = TD.getStructLayout(ST);
273             Stack.push_back(StackState(ST->getElementType(SS.Idx),
274                                        SS.Offset+SL->MemberOffsets[SS.Idx]));
275           }
276         } else {
277           const ArrayType *AT = cast<ArrayType>(SS.Ty);
278           if (AT->getNumElements() == 0) {
279             assert(SS.Idx == 0);
280             PopStackAndAdvance();
281           } else {
282             // Step into the array...
283             assert(SS.Idx < AT->getNumElements());
284             Stack.push_back(StackState(AT->getElementType(),
285                                        SS.Offset+SS.Idx*
286                                        TD.getTypeSize(AT->getElementType())));
287           }
288         }
289       }
290     }
291   };
292 } // end anonymous namespace
293
294 /// ElementTypesAreCompatible - Check to see if the specified types are
295 /// "physically" compatible.  If so, return true, else return false.  We only
296 /// have to check the fields in T1: T2 may be larger than T1.  If AllowLargerT1
297 /// is true, then we also allow a larger T1.
298 ///
299 static bool ElementTypesAreCompatible(const Type *T1, const Type *T2,
300                                       bool AllowLargerT1, const TargetData &TD){
301   TypeElementWalker T1W(T1, TD), T2W(T2, TD);
302   
303   while (!T1W.isDone() && !T2W.isDone()) {
304     if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
305       return false;
306
307     const Type *T1 = T1W.getCurrentType();
308     const Type *T2 = T2W.getCurrentType();
309     if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
310       return false;
311     
312     T1W.StepToNextType();
313     T2W.StepToNextType();
314   }
315   
316   return AllowLargerT1 || T1W.isDone();
317 }
318
319
320 /// mergeTypeInfo - This method merges the specified type into the current node
321 /// at the specified offset.  This may update the current node's type record if
322 /// this gives more information to the node, it may do nothing to the node if
323 /// this information is already known, or it may merge the node completely (and
324 /// return true) if the information is incompatible with what is already known.
325 ///
326 /// This method returns true if the node is completely folded, otherwise false.
327 ///
328 bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
329                            bool FoldIfIncompatible) {
330   const TargetData &TD = getTargetData();
331   // Check to make sure the Size member is up-to-date.  Size can be one of the
332   // following:
333   //  Size = 0, Ty = Void: Nothing is known about this node.
334   //  Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
335   //  Size = 1, Ty = Void, Array = 1: The node is collapsed
336   //  Otherwise, sizeof(Ty) = Size
337   //
338   assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
339           (Size == 0 && !Ty->isSized() && !isArray()) ||
340           (Size == 1 && Ty == Type::VoidTy && isArray()) ||
341           (Size == 0 && !Ty->isSized() && !isArray()) ||
342           (TD.getTypeSize(Ty) == Size)) &&
343          "Size member of DSNode doesn't match the type structure!");
344   assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
345
346   if (Offset == 0 && NewTy == Ty)
347     return false;  // This should be a common case, handle it efficiently
348
349   // Return true immediately if the node is completely folded.
350   if (isNodeCompletelyFolded()) return true;
351
352   // If this is an array type, eliminate the outside arrays because they won't
353   // be used anyway.  This greatly reduces the size of large static arrays used
354   // as global variables, for example.
355   //
356   bool WillBeArray = false;
357   while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
358     // FIXME: we might want to keep small arrays, but must be careful about
359     // things like: [2 x [10000 x int*]]
360     NewTy = AT->getElementType();
361     WillBeArray = true;
362   }
363
364   // Figure out how big the new type we're merging in is...
365   unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
366
367   // Otherwise check to see if we can fold this type into the current node.  If
368   // we can't, we fold the node completely, if we can, we potentially update our
369   // internal state.
370   //
371   if (Ty == Type::VoidTy) {
372     // If this is the first type that this node has seen, just accept it without
373     // question....
374     assert(Offset == 0 && !isArray() &&
375            "Cannot have an offset into a void node!");
376     Ty = NewTy;
377     NodeType &= ~Array;
378     if (WillBeArray) NodeType |= Array;
379     Size = NewTySize;
380
381     // Calculate the number of outgoing links from this node.
382     Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
383     return false;
384   }
385
386   // Handle node expansion case here...
387   if (Offset+NewTySize > Size) {
388     // It is illegal to grow this node if we have treated it as an array of
389     // objects...
390     if (isArray()) {
391       if (FoldIfIncompatible) foldNodeCompletely();
392       return true;
393     }
394
395     if (Offset) {  // We could handle this case, but we don't for now...
396       std::cerr << "UNIMP: Trying to merge a growth type into "
397                 << "offset != 0: Collapsing!\n";
398       if (FoldIfIncompatible) foldNodeCompletely();
399       return true;
400     }
401
402     // Okay, the situation is nice and simple, we are trying to merge a type in
403     // at offset 0 that is bigger than our current type.  Implement this by
404     // switching to the new type and then merge in the smaller one, which should
405     // hit the other code path here.  If the other code path decides it's not
406     // ok, it will collapse the node as appropriate.
407     //
408     const Type *OldTy = Ty;
409     Ty = NewTy;
410     NodeType &= ~Array;
411     if (WillBeArray) NodeType |= Array;
412     Size = NewTySize;
413
414     // Must grow links to be the appropriate size...
415     Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
416
417     // Merge in the old type now... which is guaranteed to be smaller than the
418     // "current" type.
419     return mergeTypeInfo(OldTy, 0);
420   }
421
422   assert(Offset <= Size &&
423          "Cannot merge something into a part of our type that doesn't exist!");
424
425   // Find the section of Ty that NewTy overlaps with... first we find the
426   // type that starts at offset Offset.
427   //
428   unsigned O = 0;
429   const Type *SubType = Ty;
430   while (O < Offset) {
431     assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
432
433     switch (SubType->getPrimitiveID()) {
434     case Type::StructTyID: {
435       const StructType *STy = cast<StructType>(SubType);
436       const StructLayout &SL = *TD.getStructLayout(STy);
437
438       unsigned i = 0, e = SL.MemberOffsets.size();
439       for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
440         /* empty */;
441
442       // The offset we are looking for must be in the i'th element...
443       SubType = STy->getElementType(i);
444       O += SL.MemberOffsets[i];
445       break;
446     }
447     case Type::ArrayTyID: {
448       SubType = cast<ArrayType>(SubType)->getElementType();
449       unsigned ElSize = TD.getTypeSize(SubType);
450       unsigned Remainder = (Offset-O) % ElSize;
451       O = Offset-Remainder;
452       break;
453     }
454     default:
455       if (FoldIfIncompatible) foldNodeCompletely();
456       return true;
457     }
458   }
459
460   assert(O == Offset && "Could not achieve the correct offset!");
461
462   // If we found our type exactly, early exit
463   if (SubType == NewTy) return false;
464
465   // Differing function types don't require us to merge.  They are not values anyway.
466   if (isa<FunctionType>(SubType) &&
467       isa<FunctionType>(NewTy)) return false;
468
469   unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
470
471   // Ok, we are getting desperate now.  Check for physical subtyping, where we
472   // just require each element in the node to be compatible.
473   if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
474       SubTypeSize && SubTypeSize < 256 && 
475       ElementTypesAreCompatible(NewTy, SubType, !isArray(), TD))
476     return false;
477
478   // Okay, so we found the leader type at the offset requested.  Search the list
479   // of types that starts at this offset.  If SubType is currently an array or
480   // structure, the type desired may actually be the first element of the
481   // composite type...
482   //
483   unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
484   while (SubType != NewTy) {
485     const Type *NextSubType = 0;
486     unsigned NextSubTypeSize = 0;
487     unsigned NextPadSize = 0;
488     switch (SubType->getPrimitiveID()) {
489     case Type::StructTyID: {
490       const StructType *STy = cast<StructType>(SubType);
491       const StructLayout &SL = *TD.getStructLayout(STy);
492       if (SL.MemberOffsets.size() > 1)
493         NextPadSize = SL.MemberOffsets[1];
494       else
495         NextPadSize = SubTypeSize;
496       NextSubType = STy->getElementType(0);
497       NextSubTypeSize = TD.getTypeSize(NextSubType);
498       break;
499     }
500     case Type::ArrayTyID:
501       NextSubType = cast<ArrayType>(SubType)->getElementType();
502       NextSubTypeSize = TD.getTypeSize(NextSubType);
503       NextPadSize = NextSubTypeSize;
504       break;
505     default: ;
506       // fall out 
507     }
508
509     if (NextSubType == 0)
510       break;   // In the default case, break out of the loop
511
512     if (NextPadSize < NewTySize)
513       break;   // Don't allow shrinking to a smaller type than NewTySize
514     SubType = NextSubType;
515     SubTypeSize = NextSubTypeSize;
516     PadSize = NextPadSize;
517   }
518
519   // If we found the type exactly, return it...
520   if (SubType == NewTy)
521     return false;
522
523   // Check to see if we have a compatible, but different type...
524   if (NewTySize == SubTypeSize) {
525     // Check to see if this type is obviously convertible... int -> uint f.e.
526     if (NewTy->isLosslesslyConvertibleTo(SubType))
527       return false;
528
529     // Check to see if we have a pointer & integer mismatch going on here,
530     // loading a pointer as a long, for example.
531     //
532     if (SubType->isInteger() && isa<PointerType>(NewTy) ||
533         NewTy->isInteger() && isa<PointerType>(SubType))
534       return false;
535   } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
536     // We are accessing the field, plus some structure padding.  Ignore the
537     // structure padding.
538     return false;
539   }
540
541   Module *M = 0;
542   if (getParentGraph()->getReturnNodes().size())
543     M = getParentGraph()->getReturnNodes().begin()->first->getParent();
544   DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
545         WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
546         WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
547                   << "SubType: ";
548         WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
549
550   if (FoldIfIncompatible) foldNodeCompletely();
551   return true;
552 }
553
554
555
556 // addEdgeTo - Add an edge from the current node to the specified node.  This
557 // can cause merging of nodes in the graph.
558 //
559 void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
560   if (NH.isNull()) return;       // Nothing to do
561
562   DSNodeHandle &ExistingEdge = getLink(Offset);
563   if (!ExistingEdge.isNull()) {
564     // Merge the two nodes...
565     ExistingEdge.mergeWith(NH);
566   } else {                             // No merging to perform...
567     setLink(Offset, NH);               // Just force a link in there...
568   }
569 }
570
571
572 // MergeSortedVectors - Efficiently merge a vector into another vector where
573 // duplicates are not allowed and both are sorted.  This assumes that 'T's are
574 // efficiently copyable and have sane comparison semantics.
575 //
576 static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
577                                const std::vector<GlobalValue*> &Src) {
578   // By far, the most common cases will be the simple ones.  In these cases,
579   // avoid having to allocate a temporary vector...
580   //
581   if (Src.empty()) {             // Nothing to merge in...
582     return;
583   } else if (Dest.empty()) {     // Just copy the result in...
584     Dest = Src;
585   } else if (Src.size() == 1) {  // Insert a single element...
586     const GlobalValue *V = Src[0];
587     std::vector<GlobalValue*>::iterator I =
588       std::lower_bound(Dest.begin(), Dest.end(), V);
589     if (I == Dest.end() || *I != Src[0])  // If not already contained...
590       Dest.insert(I, Src[0]);
591   } else if (Dest.size() == 1) {
592     GlobalValue *Tmp = Dest[0];           // Save value in temporary...
593     Dest = Src;                           // Copy over list...
594     std::vector<GlobalValue*>::iterator I =
595       std::lower_bound(Dest.begin(), Dest.end(), Tmp);
596     if (I == Dest.end() || *I != Tmp)     // If not already contained...
597       Dest.insert(I, Tmp);
598
599   } else {
600     // Make a copy to the side of Dest...
601     std::vector<GlobalValue*> Old(Dest);
602     
603     // Make space for all of the type entries now...
604     Dest.resize(Dest.size()+Src.size());
605     
606     // Merge the two sorted ranges together... into Dest.
607     std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
608     
609     // Now erase any duplicate entries that may have accumulated into the 
610     // vectors (because they were in both of the input sets)
611     Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
612   }
613 }
614
615 void DSNode::mergeGlobals(const std::vector<GlobalValue*> &RHS) {
616   MergeSortedVectors(Globals, RHS);
617 }
618
619 // MergeNodes - Helper function for DSNode::mergeWith().
620 // This function does the hard work of merging two nodes, CurNodeH
621 // and NH after filtering out trivial cases and making sure that
622 // CurNodeH.offset >= NH.offset.
623 // 
624 // ***WARNING***
625 // Since merging may cause either node to go away, we must always
626 // use the node-handles to refer to the nodes.  These node handles are
627 // automatically updated during merging, so will always provide access
628 // to the correct node after a merge.
629 //
630 void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
631   assert(CurNodeH.getOffset() >= NH.getOffset() &&
632          "This should have been enforced in the caller.");
633
634   // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
635   // respect to NH.Offset) is now zero.  NOffset is the distance from the base
636   // of our object that N starts from.
637   //
638   unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
639   unsigned NSize = NH.getNode()->getSize();
640
641   // If the two nodes are of different size, and the smaller node has the array
642   // bit set, collapse!
643   if (NSize != CurNodeH.getNode()->getSize()) {
644     if (NSize < CurNodeH.getNode()->getSize()) {
645       if (NH.getNode()->isArray())
646         NH.getNode()->foldNodeCompletely();
647     } else if (CurNodeH.getNode()->isArray()) {
648       NH.getNode()->foldNodeCompletely();
649     }
650   }
651
652   // Merge the type entries of the two nodes together...    
653   if (NH.getNode()->Ty != Type::VoidTy)
654     CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
655   assert(!CurNodeH.getNode()->isDeadNode());
656
657   // If we are merging a node with a completely folded node, then both nodes are
658   // now completely folded.
659   //
660   if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
661     if (!NH.getNode()->isNodeCompletelyFolded()) {
662       NH.getNode()->foldNodeCompletely();
663       assert(NH.getNode() && NH.getOffset() == 0 &&
664              "folding did not make offset 0?");
665       NOffset = NH.getOffset();
666       NSize = NH.getNode()->getSize();
667       assert(NOffset == 0 && NSize == 1);
668     }
669   } else if (NH.getNode()->isNodeCompletelyFolded()) {
670     CurNodeH.getNode()->foldNodeCompletely();
671     assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
672            "folding did not make offset 0?");
673     NOffset = NH.getOffset();
674     NSize = NH.getNode()->getSize();
675     assert(NOffset == 0 && NSize == 1);
676   }
677
678   DSNode *N = NH.getNode();
679   if (CurNodeH.getNode() == N || N == 0) return;
680   assert(!CurNodeH.getNode()->isDeadNode());
681
682   // Merge the NodeType information.
683   CurNodeH.getNode()->NodeType |= N->NodeType;
684
685   // Start forwarding to the new node!
686   N->forwardNode(CurNodeH.getNode(), NOffset);
687   assert(!CurNodeH.getNode()->isDeadNode());
688
689   // Make all of the outgoing links of N now be outgoing links of CurNodeH.
690   //
691   for (unsigned i = 0; i < N->getNumLinks(); ++i) {
692     DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
693     if (Link.getNode()) {
694       // Compute the offset into the current node at which to
695       // merge this link.  In the common case, this is a linear
696       // relation to the offset in the original node (with
697       // wrapping), but if the current node gets collapsed due to
698       // recursive merging, we must make sure to merge in all remaining
699       // links at offset zero.
700       unsigned MergeOffset = 0;
701       DSNode *CN = CurNodeH.getNode();
702       if (CN->Size != 1)
703         MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
704       CN->addEdgeTo(MergeOffset, Link);
705     }
706   }
707
708   // Now that there are no outgoing edges, all of the Links are dead.
709   N->Links.clear();
710
711   // Merge the globals list...
712   if (!N->Globals.empty()) {
713     CurNodeH.getNode()->mergeGlobals(N->Globals);
714
715     // Delete the globals from the old node...
716     std::vector<GlobalValue*>().swap(N->Globals);
717   }
718 }
719
720
721 // mergeWith - Merge this node and the specified node, moving all links to and
722 // from the argument node into the current node, deleting the node argument.
723 // Offset indicates what offset the specified node is to be merged into the
724 // current node.
725 //
726 // The specified node may be a null pointer (in which case, we update it to
727 // point to this node).
728 //
729 void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
730   DSNode *N = NH.getNode();
731   if (N == this && NH.getOffset() == Offset)
732     return;  // Noop
733
734   // If the RHS is a null node, make it point to this node!
735   if (N == 0) {
736     NH.mergeWith(DSNodeHandle(this, Offset));
737     return;
738   }
739
740   assert(!N->isDeadNode() && !isDeadNode());
741   assert(!hasNoReferrers() && "Should not try to fold a useless node!");
742
743   if (N == this) {
744     // We cannot merge two pieces of the same node together, collapse the node
745     // completely.
746     DEBUG(std::cerr << "Attempting to merge two chunks of"
747                     << " the same node together!\n");
748     foldNodeCompletely();
749     return;
750   }
751
752   // If both nodes are not at offset 0, make sure that we are merging the node
753   // at an later offset into the node with the zero offset.
754   //
755   if (Offset < NH.getOffset()) {
756     N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
757     return;
758   } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
759     // If the offsets are the same, merge the smaller node into the bigger node
760     N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
761     return;
762   }
763
764   // Ok, now we can merge the two nodes.  Use a static helper that works with
765   // two node handles, since "this" may get merged away at intermediate steps.
766   DSNodeHandle CurNodeH(this, Offset);
767   DSNodeHandle NHCopy(NH);
768   DSNode::MergeNodes(CurNodeH, NHCopy);
769 }
770
771
772 //===----------------------------------------------------------------------===//
773 // ReachabilityCloner Implementation
774 //===----------------------------------------------------------------------===//
775
776 DSNodeHandle ReachabilityCloner::getClonedNH(const DSNodeHandle &SrcNH) {
777   if (SrcNH.isNull()) return DSNodeHandle();
778   const DSNode *SN = SrcNH.getNode();
779
780   DSNodeHandle &NH = NodeMap[SN];
781   if (!NH.isNull())    // Node already mapped?
782     return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
783
784   DSNode *DN = new DSNode(*SN, &Dest, true /* Null out all links */);
785   DN->maskNodeTypes(BitsToKeep);
786   NH = DN;
787   
788   // Next, recursively clone all outgoing links as necessary.  Note that
789   // adding these links can cause the node to collapse itself at any time, and
790   // the current node may be merged with arbitrary other nodes.  For this
791   // reason, we must always go through NH.
792   DN = 0;
793   for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
794     const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
795     if (!SrcEdge.isNull()) {
796       const DSNodeHandle &DestEdge = getClonedNH(SrcEdge);
797       // Compute the offset into the current node at which to
798       // merge this link.  In the common case, this is a linear
799       // relation to the offset in the original node (with
800       // wrapping), but if the current node gets collapsed due to
801       // recursive merging, we must make sure to merge in all remaining
802       // links at offset zero.
803       unsigned MergeOffset = 0;
804       DSNode *CN = NH.getNode();
805       if (CN->getSize() != 1)
806         MergeOffset = ((i << DS::PointerShift)+NH.getOffset()
807                        - SrcNH.getOffset()) %CN->getSize();
808       CN->addEdgeTo(MergeOffset, DestEdge);
809     }
810   }
811   
812   // If this node contains any globals, make sure they end up in the scalar
813   // map with the correct offset.
814   for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
815        I != E; ++I) {
816     GlobalValue *GV = *I;
817     const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
818     DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
819     assert(DestGNH.getNode() == NH.getNode() &&"Global mapping inconsistent");
820     Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
821                                        DestGNH.getOffset()+SrcGNH.getOffset()));
822     
823     if (CloneFlags & DSGraph::UpdateInlinedGlobals)
824       Dest.getInlinedGlobals().insert(GV);
825   }
826
827   return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
828 }
829
830 void ReachabilityCloner::merge(const DSNodeHandle &NH,
831                                const DSNodeHandle &SrcNH) {
832   if (SrcNH.isNull()) return;  // Noop
833   if (NH.isNull()) {
834     // If there is no destination node, just clone the source and assign the
835     // destination node to be it.
836     NH.mergeWith(getClonedNH(SrcNH));
837     return;
838   }
839
840   // Okay, at this point, we know that we have both a destination and a source
841   // node that need to be merged.  Check to see if the source node has already
842   // been cloned.
843   const DSNode *SN = SrcNH.getNode();
844   DSNodeHandle &SCNH = NodeMap[SN];  // SourceClonedNodeHandle
845   if (!SCNH.isNull()) {   // Node already cloned?
846     NH.mergeWith(DSNodeHandle(SCNH.getNode(),
847                               SCNH.getOffset()+SrcNH.getOffset()));
848
849     return;  // Nothing to do!
850   }
851
852   // Okay, so the source node has not already been cloned.  Instead of creating
853   // a new DSNode, only to merge it into the one we already have, try to perform
854   // the merge in-place.  The only case we cannot handle here is when the offset
855   // into the existing node is less than the offset into the virtual node we are
856   // merging in.  In this case, we have to extend the existing node, which
857   // requires an allocation anyway.
858   DSNode *DN = NH.getNode();   // Make sure the Offset is up-to-date
859   if (NH.getOffset() >= SrcNH.getOffset()) {
860     if (!DN->isNodeCompletelyFolded()) {
861       // Make sure the destination node is folded if the source node is folded.
862       if (SN->isNodeCompletelyFolded()) {
863         DN->foldNodeCompletely();
864         DN = NH.getNode();
865       } else if (SN->getSize() != DN->getSize()) {
866         // If the two nodes are of different size, and the smaller node has the
867         // array bit set, collapse!
868         if (SN->getSize() < DN->getSize()) {
869           if (SN->isArray()) {
870             DN->foldNodeCompletely();
871             DN = NH.getNode();
872           }
873         } else if (DN->isArray()) {
874           DN->foldNodeCompletely();
875           DN = NH.getNode();
876         }
877       }
878     
879       // Merge the type entries of the two nodes together...    
880       if (SN->getType() != Type::VoidTy && !DN->isNodeCompletelyFolded()) {
881         DN->mergeTypeInfo(SN->getType(), NH.getOffset()-SrcNH.getOffset());
882         DN = NH.getNode();
883       }
884     }
885
886     assert(!DN->isDeadNode());
887     
888     // Merge the NodeType information.
889     DN->mergeNodeFlags(SN->getNodeFlags() & BitsToKeep);
890
891     // Before we start merging outgoing links and updating the scalar map, make
892     // sure it is known that this is the representative node for the src node.
893     SCNH = DSNodeHandle(DN, NH.getOffset()-SrcNH.getOffset());
894
895     // If the source node contains any globals, make sure they end up in the
896     // scalar map with the correct offset.
897     if (SN->global_begin() != SN->global_end()) {
898       // Update the globals in the destination node itself.
899       DN->mergeGlobals(SN->getGlobals());
900
901       // Update the scalar map for the graph we are merging the source node
902       // into.
903       for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
904            I != E; ++I) {
905         GlobalValue *GV = *I;
906         const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
907         DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
908         assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
909         Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
910                                       DestGNH.getOffset()+SrcGNH.getOffset()));
911         
912         if (CloneFlags & DSGraph::UpdateInlinedGlobals)
913           Dest.getInlinedGlobals().insert(GV);
914       }
915     }
916   } else {
917     // We cannot handle this case without allocating a temporary node.  Fall
918     // back on being simple.
919     DSNode *NewDN = new DSNode(*SN, &Dest, true /* Null out all links */);
920     NewDN->maskNodeTypes(BitsToKeep);
921
922     unsigned NHOffset = NH.getOffset();
923     NH.mergeWith(DSNodeHandle(NewDN, SrcNH.getOffset()));
924
925     assert(NH.getNode() &&
926            (NH.getOffset() > NHOffset ||
927             (NH.getOffset() == 0 && NH.getNode()->isNodeCompletelyFolded())) &&
928            "Merging did not adjust the offset!");
929
930     // Before we start merging outgoing links and updating the scalar map, make
931     // sure it is known that this is the representative node for the src node.
932     SCNH = DSNodeHandle(NH.getNode(), NH.getOffset()-SrcNH.getOffset());
933
934     // If the source node contained any globals, make sure to create entries 
935     // in the scalar map for them!
936     for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
937          I != E; ++I) {
938       GlobalValue *GV = *I;
939       const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
940       DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
941       assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
942       assert(SrcGNH.getNode() == SN && "Global mapping inconsistent");
943       Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
944                                     DestGNH.getOffset()+SrcGNH.getOffset()));
945       
946       if (CloneFlags & DSGraph::UpdateInlinedGlobals)
947         Dest.getInlinedGlobals().insert(GV);
948     }
949   }
950
951
952   // Next, recursively merge all outgoing links as necessary.  Note that
953   // adding these links can cause the destination node to collapse itself at
954   // any time, and the current node may be merged with arbitrary other nodes.
955   // For this reason, we must always go through NH.
956   DN = 0;
957   for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
958     const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
959     if (!SrcEdge.isNull()) {
960       // Compute the offset into the current node at which to
961       // merge this link.  In the common case, this is a linear
962       // relation to the offset in the original node (with
963       // wrapping), but if the current node gets collapsed due to
964       // recursive merging, we must make sure to merge in all remaining
965       // links at offset zero.
966       unsigned MergeOffset = 0;
967       DSNode *CN = SCNH.getNode();
968       if (CN->getSize() != 1)
969         MergeOffset = ((i << DS::PointerShift)+SCNH.getOffset()) %CN->getSize();
970       
971       DSNodeHandle &Link = CN->getLink(MergeOffset);
972       if (!Link.isNull()) {
973         // Perform the recursive merging.  Make sure to create a temporary NH,
974         // because the Link can disappear in the process of recursive merging.
975         DSNodeHandle Tmp = Link;
976         merge(Tmp, SrcEdge);
977       } else {
978         merge(Link, SrcEdge);
979       }
980     }
981   }
982 }
983
984 /// mergeCallSite - Merge the nodes reachable from the specified src call
985 /// site into the nodes reachable from DestCS.
986 void ReachabilityCloner::mergeCallSite(const DSCallSite &DestCS,
987                                        const DSCallSite &SrcCS) {
988   merge(DestCS.getRetVal(), SrcCS.getRetVal());
989   unsigned MinArgs = DestCS.getNumPtrArgs();
990   if (SrcCS.getNumPtrArgs() < MinArgs) MinArgs = SrcCS.getNumPtrArgs();
991   
992   for (unsigned a = 0; a != MinArgs; ++a)
993     merge(DestCS.getPtrArg(a), SrcCS.getPtrArg(a));
994 }
995
996
997 //===----------------------------------------------------------------------===//
998 // DSCallSite Implementation
999 //===----------------------------------------------------------------------===//
1000
1001 // Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
1002 Function &DSCallSite::getCaller() const {
1003   return *Site.getInstruction()->getParent()->getParent();
1004 }
1005
1006 void DSCallSite::InitNH(DSNodeHandle &NH, const DSNodeHandle &Src,
1007                         ReachabilityCloner &RC) {
1008   NH = RC.getClonedNH(Src);
1009 }
1010
1011 //===----------------------------------------------------------------------===//
1012 // DSGraph Implementation
1013 //===----------------------------------------------------------------------===//
1014
1015 /// getFunctionNames - Return a space separated list of the name of the
1016 /// functions in this graph (if any)
1017 std::string DSGraph::getFunctionNames() const {
1018   switch (getReturnNodes().size()) {
1019   case 0: return "Globals graph";
1020   case 1: return getReturnNodes().begin()->first->getName();
1021   default:
1022     std::string Return;
1023     for (DSGraph::ReturnNodesTy::const_iterator I = getReturnNodes().begin();
1024          I != getReturnNodes().end(); ++I)
1025       Return += I->first->getName() + " ";
1026     Return.erase(Return.end()-1, Return.end());   // Remove last space character
1027     return Return;
1028   }
1029 }
1030
1031
1032 DSGraph::DSGraph(const DSGraph &G) : GlobalsGraph(0), TD(G.TD) {
1033   PrintAuxCalls = false;
1034   NodeMapTy NodeMap;
1035   cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
1036 }
1037
1038 DSGraph::DSGraph(const DSGraph &G, NodeMapTy &NodeMap)
1039   : GlobalsGraph(0), TD(G.TD) {
1040   PrintAuxCalls = false;
1041   cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
1042 }
1043
1044 DSGraph::~DSGraph() {
1045   FunctionCalls.clear();
1046   AuxFunctionCalls.clear();
1047   InlinedGlobals.clear();
1048   ScalarMap.clear();
1049   ReturnNodes.clear();
1050
1051   // Drop all intra-node references, so that assertions don't fail...
1052   for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1053     (*NI)->dropAllReferences();
1054
1055   // Free all of the nodes.
1056   Nodes.clear();
1057 }
1058
1059 // dump - Allow inspection of graph in a debugger.
1060 void DSGraph::dump() const { print(std::cerr); }
1061
1062
1063 /// remapLinks - Change all of the Links in the current node according to the
1064 /// specified mapping.
1065 ///
1066 void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
1067   for (unsigned i = 0, e = Links.size(); i != e; ++i)
1068     if (DSNode *N = Links[i].getNode()) {
1069       DSGraph::NodeMapTy::const_iterator ONMI = OldNodeMap.find(N);
1070       if (ONMI != OldNodeMap.end()) {
1071         Links[i].setNode(ONMI->second.getNode());
1072         Links[i].setOffset(Links[i].getOffset()+ONMI->second.getOffset());
1073       }
1074     }
1075 }
1076
1077 /// updateFromGlobalGraph - This function rematerializes global nodes and
1078 /// nodes reachable from them from the globals graph into the current graph.
1079 /// It uses the vector InlinedGlobals to avoid cloning and merging globals that
1080 /// are already up-to-date in the current graph.  In practice, in the TD pass,
1081 /// this is likely to be a large fraction of the live global nodes in each
1082 /// function (since most live nodes are likely to have been brought up-to-date
1083 /// in at _some_ caller or callee).
1084 /// 
1085 void DSGraph::updateFromGlobalGraph() {
1086   TIME_REGION(X, "updateFromGlobalGraph");
1087   ReachabilityCloner RC(*this, *GlobalsGraph, 0);
1088
1089   // Clone the non-up-to-date global nodes into this graph.
1090   for (DSScalarMap::global_iterator I = getScalarMap().global_begin(),
1091          E = getScalarMap().global_end(); I != E; ++I)
1092     if (InlinedGlobals.count(*I) == 0) { // GNode is not up-to-date
1093       DSScalarMap::iterator It = GlobalsGraph->ScalarMap.find(*I);
1094       if (It != GlobalsGraph->ScalarMap.end())
1095         RC.merge(getNodeForValue(*I), It->second);
1096     }
1097 }
1098
1099 /// cloneInto - Clone the specified DSGraph into the current graph.  The
1100 /// translated ScalarMap for the old function is filled into the OldValMap
1101 /// member, and the translated ReturnNodes map is returned into ReturnNodes.
1102 ///
1103 /// The CloneFlags member controls various aspects of the cloning process.
1104 ///
1105 void DSGraph::cloneInto(const DSGraph &G, DSScalarMap &OldValMap,
1106                         ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
1107                         unsigned CloneFlags) {
1108   TIME_REGION(X, "cloneInto");
1109   assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
1110   assert(&G != this && "Cannot clone graph into itself!");
1111
1112   // Remove alloca or mod/ref bits as specified...
1113   unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
1114     | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
1115     | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
1116   BitsToClear |= DSNode::DEAD;  // Clear dead flag...
1117
1118   for (node_iterator I = G.node_begin(), E = G.node_end(); I != E; ++I) {
1119     assert(!(*I)->isForwarding() &&
1120            "Forward nodes shouldn't be in node list!");
1121     DSNode *New = new DSNode(**I, this);
1122     New->maskNodeTypes(~BitsToClear);
1123     OldNodeMap[*I] = New;
1124   }
1125   
1126 #ifndef NDEBUG
1127   Timer::addPeakMemoryMeasurement();
1128 #endif
1129   
1130   // Rewrite the links in the new nodes to point into the current graph now.
1131   // Note that we don't loop over the node's list to do this.  The problem is
1132   // that remaping links can cause recursive merging to happen, which means
1133   // that node_iterator's can get easily invalidated!  Because of this, we
1134   // loop over the OldNodeMap, which contains all of the new nodes as the
1135   // .second element of the map elements.  Also note that if we remap a node
1136   // more than once, we won't break anything.
1137   for (NodeMapTy::iterator I = OldNodeMap.begin(), E = OldNodeMap.end();
1138        I != E; ++I)
1139     I->second.getNode()->remapLinks(OldNodeMap);
1140
1141   // Copy the scalar map... merging all of the global nodes...
1142   for (DSScalarMap::const_iterator I = G.ScalarMap.begin(),
1143          E = G.ScalarMap.end(); I != E; ++I) {
1144     DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
1145     DSNodeHandle &H = OldValMap[I->first];
1146     H.mergeWith(DSNodeHandle(MappedNode.getNode(),
1147                              I->second.getOffset()+MappedNode.getOffset()));
1148
1149     // If this is a global, add the global to this fn or merge if already exists
1150     if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
1151       ScalarMap[GV].mergeWith(H);
1152       if (CloneFlags & DSGraph::UpdateInlinedGlobals)
1153         InlinedGlobals.insert(GV);
1154     }
1155   }
1156
1157   if (!(CloneFlags & DontCloneCallNodes)) {
1158     // Copy the function calls list...
1159     unsigned FC = FunctionCalls.size();  // FirstCall
1160     FunctionCalls.reserve(FC+G.FunctionCalls.size());
1161     for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
1162       FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
1163   }
1164
1165   if (!(CloneFlags & DontCloneAuxCallNodes)) {
1166     // Copy the auxiliary function calls list...
1167     unsigned FC = AuxFunctionCalls.size();  // FirstCall
1168     AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
1169     for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
1170       AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
1171   }
1172
1173   // Map the return node pointers over...
1174   for (ReturnNodesTy::const_iterator I = G.getReturnNodes().begin(),
1175          E = G.getReturnNodes().end(); I != E; ++I) {
1176     const DSNodeHandle &Ret = I->second;
1177     DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
1178     OldReturnNodes.insert(std::make_pair(I->first,
1179                           DSNodeHandle(MappedRet.getNode(),
1180                                        MappedRet.getOffset()+Ret.getOffset())));
1181   }
1182 }
1183
1184
1185 /// mergeInGraph - The method is used for merging graphs together.  If the
1186 /// argument graph is not *this, it makes a clone of the specified graph, then
1187 /// merges the nodes specified in the call site with the formal arguments in the
1188 /// graph.
1189 ///
1190 void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1191                            const DSGraph &Graph, unsigned CloneFlags) {
1192   TIME_REGION(X, "mergeInGraph");
1193
1194   // If this is not a recursive call, clone the graph into this graph...
1195   if (&Graph != this) {
1196     // Clone the callee's graph into the current graph, keeping track of where
1197     // scalars in the old graph _used_ to point, and of the new nodes matching
1198     // nodes of the old graph.
1199     ReachabilityCloner RC(*this, Graph, CloneFlags);
1200     
1201     // Set up argument bindings
1202     Function::aiterator AI = F.abegin();
1203     for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1204       // Advance the argument iterator to the first pointer argument...
1205       while (AI != F.aend() && !isPointerType(AI->getType())) {
1206         ++AI;
1207 #ifndef NDEBUG  // FIXME: We should merge vararg arguments!
1208         if (AI == F.aend() && !F.getFunctionType()->isVarArg())
1209           std::cerr << "Bad call to Function: " << F.getName() << "\n";
1210 #endif
1211       }
1212       if (AI == F.aend()) break;
1213       
1214       // Add the link from the argument scalar to the provided value.
1215       RC.merge(CS.getPtrArg(i), Graph.getNodeForValue(AI));
1216     }
1217     
1218     // Map the return node pointer over.
1219     if (!CS.getRetVal().isNull())
1220       RC.merge(CS.getRetVal(), Graph.getReturnNodeFor(F));
1221     
1222     // If requested, copy the calls or aux-calls lists.
1223     if (!(CloneFlags & DontCloneCallNodes)) {
1224       // Copy the function calls list...
1225       FunctionCalls.reserve(FunctionCalls.size()+Graph.FunctionCalls.size());
1226       for (unsigned i = 0, ei = Graph.FunctionCalls.size(); i != ei; ++i)
1227         FunctionCalls.push_back(DSCallSite(Graph.FunctionCalls[i], RC));
1228     }
1229     
1230     if (!(CloneFlags & DontCloneAuxCallNodes)) {
1231       // Copy the auxiliary function calls list...
1232       AuxFunctionCalls.reserve(AuxFunctionCalls.size()+
1233                                Graph.AuxFunctionCalls.size());
1234       for (unsigned i = 0, ei = Graph.AuxFunctionCalls.size(); i != ei; ++i)
1235         AuxFunctionCalls.push_back(DSCallSite(Graph.AuxFunctionCalls[i], RC));
1236     }
1237     
1238     // Clone over all globals that appear in the caller and callee graphs.
1239     for (DSScalarMap::global_iterator GI = Graph.getScalarMap().global_begin(),
1240            E = Graph.getScalarMap().global_end(); GI != E; ++GI)
1241       if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*GI))
1242         if (ScalarMap.count(GV))
1243           RC.merge(ScalarMap[GV], Graph.getNodeForValue(GV));
1244   } else {
1245     DSNodeHandle RetVal = getReturnNodeFor(F);
1246
1247     // Merge the return value with the return value of the context...
1248     RetVal.mergeWith(CS.getRetVal());
1249     
1250     // Resolve all of the function arguments...
1251     Function::aiterator AI = F.abegin();
1252     
1253     for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1254       // Advance the argument iterator to the first pointer argument...
1255       while (AI != F.aend() && !isPointerType(AI->getType())) {
1256         ++AI;
1257 #ifndef NDEBUG // FIXME: We should merge varargs arguments!!
1258         if (AI == F.aend() && !F.getFunctionType()->isVarArg())
1259           std::cerr << "Bad call to Function: " << F.getName() << "\n";
1260 #endif
1261       }
1262       if (AI == F.aend()) break;
1263       
1264       // Add the link from the argument scalar to the provided value
1265       DSNodeHandle &NH = getNodeForValue(AI);
1266       assert(NH.getNode() && "Pointer argument without scalarmap entry?");
1267       NH.mergeWith(CS.getPtrArg(i));
1268     }
1269   }
1270 }
1271
1272 /// getCallSiteForArguments - Get the arguments and return value bindings for
1273 /// the specified function in the current graph.
1274 ///
1275 DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1276   std::vector<DSNodeHandle> Args;
1277
1278   for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1279     if (isPointerType(I->getType()))
1280       Args.push_back(getNodeForValue(I));
1281
1282   return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
1283 }
1284
1285
1286
1287 // markIncompleteNodes - Mark the specified node as having contents that are not
1288 // known with the current analysis we have performed.  Because a node makes all
1289 // of the nodes it can reach incomplete if the node itself is incomplete, we
1290 // must recursively traverse the data structure graph, marking all reachable
1291 // nodes as incomplete.
1292 //
1293 static void markIncompleteNode(DSNode *N) {
1294   // Stop recursion if no node, or if node already marked...
1295   if (N == 0 || N->isIncomplete()) return;
1296
1297   // Actually mark the node
1298   N->setIncompleteMarker();
1299
1300   // Recursively process children...
1301   for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1302     if (DSNode *DSN = N->getLink(i).getNode())
1303       markIncompleteNode(DSN);
1304 }
1305
1306 static void markIncomplete(DSCallSite &Call) {
1307   // Then the return value is certainly incomplete!
1308   markIncompleteNode(Call.getRetVal().getNode());
1309
1310   // All objects pointed to by function arguments are incomplete!
1311   for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1312     markIncompleteNode(Call.getPtrArg(i).getNode());
1313 }
1314
1315 // markIncompleteNodes - Traverse the graph, identifying nodes that may be
1316 // modified by other functions that have not been resolved yet.  This marks
1317 // nodes that are reachable through three sources of "unknownness":
1318 //
1319 //  Global Variables, Function Calls, and Incoming Arguments
1320 //
1321 // For any node that may have unknown components (because something outside the
1322 // scope of current analysis may have modified it), the 'Incomplete' flag is
1323 // added to the NodeType.
1324 //
1325 void DSGraph::markIncompleteNodes(unsigned Flags) {
1326   // Mark any incoming arguments as incomplete...
1327   if (Flags & DSGraph::MarkFormalArgs)
1328     for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1329          FI != E; ++FI) {
1330       Function &F = *FI->first;
1331       if (F.getName() != "main")
1332         for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1333           if (isPointerType(I->getType()))
1334             markIncompleteNode(getNodeForValue(I).getNode());
1335     }
1336
1337   // Mark stuff passed into functions calls as being incomplete...
1338   if (!shouldPrintAuxCalls())
1339     for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1340       markIncomplete(FunctionCalls[i]);
1341   else
1342     for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1343       markIncomplete(AuxFunctionCalls[i]);
1344     
1345
1346   // Mark all global nodes as incomplete...
1347   if ((Flags & DSGraph::IgnoreGlobals) == 0)
1348     for (DSScalarMap::global_iterator I = ScalarMap.global_begin(),
1349            E = ScalarMap.global_end(); I != E; ++I)
1350       if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I))
1351         if (!GV->isConstant())
1352           markIncompleteNode(ScalarMap[GV].getNode());
1353 }
1354
1355 static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1356   if (DSNode *N = Edge.getNode())  // Is there an edge?
1357     if (N->getNumReferrers() == 1)  // Does it point to a lonely node?
1358       // No interesting info?
1359       if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
1360           N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
1361         Edge.setNode(0);  // Kill the edge!
1362 }
1363
1364 static inline bool nodeContainsExternalFunction(const DSNode *N) {
1365   const std::vector<GlobalValue*> &Globals = N->getGlobals();
1366   for (unsigned i = 0, e = Globals.size(); i != e; ++i)
1367     if (Globals[i]->isExternal())
1368       return true;
1369   return false;
1370 }
1371
1372 static void removeIdenticalCalls(std::vector<DSCallSite> &Calls) {
1373   // Remove trivially identical function calls
1374   unsigned NumFns = Calls.size();
1375   std::sort(Calls.begin(), Calls.end());  // Sort by callee as primary key!
1376
1377 #if 1
1378   // Scan the call list cleaning it up as necessary...
1379   DSNode   *LastCalleeNode = 0;
1380   Function *LastCalleeFunc = 0;
1381   unsigned NumDuplicateCalls = 0;
1382   bool LastCalleeContainsExternalFunction = false;
1383   for (unsigned i = 0; i != Calls.size(); ++i) {
1384     DSCallSite &CS = Calls[i];
1385
1386     // If the Callee is a useless edge, this must be an unreachable call site,
1387     // eliminate it.
1388     if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
1389         CS.getCalleeNode()->isComplete() &&
1390         CS.getCalleeNode()->getGlobals().empty()) {  // No useful info?
1391 #ifndef NDEBUG
1392       std::cerr << "WARNING: Useless call site found.\n";
1393 #endif
1394       CS.swap(Calls.back());
1395       Calls.pop_back();
1396       --i;
1397     } else {
1398       // If the return value or any arguments point to a void node with no
1399       // information at all in it, and the call node is the only node to point
1400       // to it, remove the edge to the node (killing the node).
1401       //
1402       killIfUselessEdge(CS.getRetVal());
1403       for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1404         killIfUselessEdge(CS.getPtrArg(a));
1405       
1406       // If this call site calls the same function as the last call site, and if
1407       // the function pointer contains an external function, this node will
1408       // never be resolved.  Merge the arguments of the call node because no
1409       // information will be lost.
1410       //
1411       if ((CS.isDirectCall()   && CS.getCalleeFunc() == LastCalleeFunc) ||
1412           (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
1413         ++NumDuplicateCalls;
1414         if (NumDuplicateCalls == 1) {
1415           if (LastCalleeNode)
1416             LastCalleeContainsExternalFunction =
1417               nodeContainsExternalFunction(LastCalleeNode);
1418           else
1419             LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
1420         }
1421      
1422         // It is not clear why, but enabling this code makes DSA really
1423         // sensitive to node forwarding.  Basically, with this enabled, DSA
1424         // performs different number of inlinings based on which nodes are
1425         // forwarding or not.  This is clearly a problem, so this code is
1426         // disabled until this can be resolved.
1427 #if 1
1428         if (LastCalleeContainsExternalFunction
1429 #if 0
1430             ||
1431             // This should be more than enough context sensitivity!
1432             // FIXME: Evaluate how many times this is tripped!
1433             NumDuplicateCalls > 20
1434 #endif
1435             ) {
1436           DSCallSite &OCS = Calls[i-1];
1437           OCS.mergeWith(CS);
1438           
1439           // The node will now be eliminated as a duplicate!
1440           if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
1441             CS = OCS;
1442           else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
1443             OCS = CS;
1444         }
1445 #endif
1446       } else {
1447         if (CS.isDirectCall()) {
1448           LastCalleeFunc = CS.getCalleeFunc();
1449           LastCalleeNode = 0;
1450         } else {
1451           LastCalleeNode = CS.getCalleeNode();
1452           LastCalleeFunc = 0;
1453         }
1454         NumDuplicateCalls = 0;
1455       }
1456     }
1457   }
1458 #endif
1459   Calls.erase(std::unique(Calls.begin(), Calls.end()), Calls.end());
1460
1461   // Track the number of call nodes merged away...
1462   NumCallNodesMerged += NumFns-Calls.size();
1463
1464   DEBUG(if (NumFns != Calls.size())
1465           std::cerr << "Merged " << (NumFns-Calls.size()) << " call nodes.\n";);
1466 }
1467
1468
1469 // removeTriviallyDeadNodes - After the graph has been constructed, this method
1470 // removes all unreachable nodes that are created because they got merged with
1471 // other nodes in the graph.  These nodes will all be trivially unreachable, so
1472 // we don't have to perform any non-trivial analysis here.
1473 //
1474 void DSGraph::removeTriviallyDeadNodes() {
1475   TIME_REGION(X, "removeTriviallyDeadNodes");
1476
1477   // Loop over all of the nodes in the graph, calling getNode on each field.
1478   // This will cause all nodes to update their forwarding edges, causing
1479   // forwarded nodes to be delete-able.
1480   for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI) {
1481     DSNode *N = *NI;
1482     for (unsigned l = 0, e = N->getNumLinks(); l != e; ++l)
1483       N->getLink(l*N->getPointerSize()).getNode();
1484   }
1485
1486   // NOTE: This code is disabled.  Though it should, in theory, allow us to
1487   // remove more nodes down below, the scan of the scalar map is incredibly
1488   // expensive for certain programs (with large SCCs).  In the future, if we can
1489   // make the scalar map scan more efficient, then we can reenable this.
1490 #if 0
1491   { TIME_REGION(X, "removeTriviallyDeadNodes:scalarmap");
1492
1493   // Likewise, forward any edges from the scalar nodes.  While we are at it,
1494   // clean house a bit.
1495   for (DSScalarMap::iterator I = ScalarMap.begin(),E = ScalarMap.end();I != E;){
1496     I->second.getNode();
1497     ++I;
1498   }
1499   }
1500 #endif
1501   bool isGlobalsGraph = !GlobalsGraph;
1502
1503   for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E; ) {
1504     DSNode &Node = *NI;
1505
1506     // Do not remove *any* global nodes in the globals graph.
1507     // This is a special case because such nodes may not have I, M, R flags set.
1508     if (Node.isGlobalNode() && isGlobalsGraph) {
1509       ++NI;
1510       continue;
1511     }
1512
1513     if (Node.isComplete() && !Node.isModified() && !Node.isRead()) {
1514       // This is a useless node if it has no mod/ref info (checked above),
1515       // outgoing edges (which it cannot, as it is not modified in this
1516       // context), and it has no incoming edges.  If it is a global node it may
1517       // have all of these properties and still have incoming edges, due to the
1518       // scalar map, so we check those now.
1519       //
1520       if (Node.getNumReferrers() == Node.getGlobals().size()) {
1521         const std::vector<GlobalValue*> &Globals = Node.getGlobals();
1522
1523         // Loop through and make sure all of the globals are referring directly
1524         // to the node...
1525         for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1526           DSNode *N = getNodeForValue(Globals[j]).getNode();
1527           assert(N == &Node && "ScalarMap doesn't match globals list!");
1528         }
1529
1530         // Make sure NumReferrers still agrees, if so, the node is truly dead.
1531         if (Node.getNumReferrers() == Globals.size()) {
1532           for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1533             ScalarMap.erase(Globals[j]);
1534           Node.makeNodeDead();
1535           ++NumTrivialGlobalDNE;
1536         }
1537       }
1538     }
1539
1540     if (Node.getNodeFlags() == 0 && Node.hasNoReferrers()) {
1541       // This node is dead!
1542       NI = Nodes.erase(NI);    // Erase & remove from node list.
1543       ++NumTrivialDNE;
1544     } else {
1545       ++NI;
1546     }
1547   }
1548
1549   removeIdenticalCalls(FunctionCalls);
1550   removeIdenticalCalls(AuxFunctionCalls);
1551 }
1552
1553
1554 /// markReachableNodes - This method recursively traverses the specified
1555 /// DSNodes, marking any nodes which are reachable.  All reachable nodes it adds
1556 /// to the set, which allows it to only traverse visited nodes once.
1557 ///
1558 void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
1559   if (this == 0) return;
1560   assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
1561   if (ReachableNodes.insert(this).second)        // Is newly reachable?
1562     for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
1563       getLink(i).getNode()->markReachableNodes(ReachableNodes);
1564 }
1565
1566 void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
1567   getRetVal().getNode()->markReachableNodes(Nodes);
1568   if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
1569   
1570   for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1571     getPtrArg(i).getNode()->markReachableNodes(Nodes);
1572 }
1573
1574 // CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1575 // looking for a node that is marked alive.  If an alive node is found, return
1576 // true, otherwise return false.  If an alive node is reachable, this node is
1577 // marked as alive...
1578 //
1579 static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
1580                                hash_set<DSNode*> &Visited,
1581                                bool IgnoreGlobals) {
1582   if (N == 0) return false;
1583   assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
1584
1585   // If this is a global node, it will end up in the globals graph anyway, so we
1586   // don't need to worry about it.
1587   if (IgnoreGlobals && N->isGlobalNode()) return false;
1588
1589   // If we know that this node is alive, return so!
1590   if (Alive.count(N)) return true;
1591
1592   // Otherwise, we don't think the node is alive yet, check for infinite
1593   // recursion.
1594   if (Visited.count(N)) return false;  // Found a cycle
1595   Visited.insert(N);   // No recursion, insert into Visited...
1596
1597   for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1598     if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited,
1599                            IgnoreGlobals)) {
1600       N->markReachableNodes(Alive);
1601       return true;
1602     }
1603   return false;
1604 }
1605
1606 // CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1607 // alive nodes.
1608 //
1609 static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
1610                                   hash_set<DSNode*> &Visited,
1611                                   bool IgnoreGlobals) {
1612   if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
1613                          IgnoreGlobals))
1614     return true;
1615   if (CS.isIndirectCall() &&
1616       CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
1617     return true;
1618   for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1619     if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
1620                            IgnoreGlobals))
1621       return true;
1622   return false;
1623 }
1624
1625 // removeDeadNodes - Use a more powerful reachability analysis to eliminate
1626 // subgraphs that are unreachable.  This often occurs because the data
1627 // structure doesn't "escape" into it's caller, and thus should be eliminated
1628 // from the caller's graph entirely.  This is only appropriate to use when
1629 // inlining graphs.
1630 //
1631 void DSGraph::removeDeadNodes(unsigned Flags) {
1632   DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
1633
1634   // Reduce the amount of work we have to do... remove dummy nodes left over by
1635   // merging...
1636   removeTriviallyDeadNodes();
1637
1638   TIME_REGION(X, "removeDeadNodes");
1639
1640   // FIXME: Merge non-trivially identical call nodes...
1641
1642   // Alive - a set that holds all nodes found to be reachable/alive.
1643   hash_set<DSNode*> Alive;
1644   std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
1645
1646   // Copy and merge all information about globals to the GlobalsGraph if this is
1647   // not a final pass (where unreachable globals are removed).
1648   //
1649   // Strip all alloca bits since the current function is only for the BU pass.
1650   // Strip all incomplete bits since they are short-lived properties and they
1651   // will be correctly computed when rematerializing nodes into the functions.
1652   //
1653   ReachabilityCloner GGCloner(*GlobalsGraph, *this, DSGraph::StripAllocaBit |
1654                               DSGraph::StripIncompleteBit);
1655
1656   // Mark all nodes reachable by (non-global) scalar nodes as alive...
1657   { TIME_REGION(Y, "removeDeadNodes:scalarscan");
1658   for (DSScalarMap::iterator I = ScalarMap.begin(), E = ScalarMap.end(); I !=E;)
1659     if (isa<GlobalValue>(I->first)) {             // Keep track of global nodes
1660       assert(I->second.getNode() && "Null global node?");
1661       assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
1662       GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
1663
1664       // Make sure that all globals are cloned over as roots.
1665       if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1666         DSGraph::ScalarMapTy::iterator SMI = 
1667           GlobalsGraph->getScalarMap().find(I->first);
1668         if (SMI != GlobalsGraph->getScalarMap().end())
1669           GGCloner.merge(SMI->second, I->second);
1670         else
1671           GGCloner.getClonedNH(I->second);
1672       }
1673       ++I;
1674     } else {
1675       DSNode *N = I->second.getNode();
1676 #if 0
1677       // Check to see if this is a worthless node generated for non-pointer
1678       // values, such as integers.  Consider an addition of long types: A+B.
1679       // Assuming we can track all uses of the value in this context, and it is
1680       // NOT used as a pointer, we can delete the node.  We will be able to
1681       // detect this situation if the node pointed to ONLY has Unknown bit set
1682       // in the node.  In this case, the node is not incomplete, does not point
1683       // to any other nodes (no mod/ref bits set), and is therefore
1684       // uninteresting for data structure analysis.  If we run across one of
1685       // these, prune the scalar pointing to it.
1686       //
1687       if (N->getNodeFlags() == DSNode::UnknownNode && !isa<Argument>(I->first))
1688         ScalarMap.erase(I++);
1689       else {
1690 #endif
1691         N->markReachableNodes(Alive);
1692         ++I;
1693       //}
1694     }
1695   }
1696
1697   // The return values are alive as well.
1698   for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1699        I != E; ++I)
1700     I->second.getNode()->markReachableNodes(Alive);
1701
1702   // Mark any nodes reachable by primary calls as alive...
1703   for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1704     FunctionCalls[i].markReachableNodes(Alive);
1705
1706
1707   // Now find globals and aux call nodes that are already live or reach a live
1708   // value (which makes them live in turn), and continue till no more are found.
1709   // 
1710   bool Iterate;
1711   hash_set<DSNode*> Visited;
1712   std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1713   do {
1714     Visited.clear();
1715     // If any global node points to a non-global that is "alive", the global is
1716     // "alive" as well...  Remove it from the GlobalNodes list so we only have
1717     // unreachable globals in the list.
1718     //
1719     Iterate = false;
1720     if (!(Flags & DSGraph::RemoveUnreachableGlobals))
1721       for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1722         if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited, 
1723                                Flags & DSGraph::RemoveUnreachableGlobals)) {
1724           std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
1725           GlobalNodes.pop_back();                          // erase efficiently
1726           Iterate = true;
1727         }
1728
1729     // Mark only unresolvable call nodes for moving to the GlobalsGraph since
1730     // call nodes that get resolved will be difficult to remove from that graph.
1731     // The final unresolved call nodes must be handled specially at the end of
1732     // the BU pass (i.e., in main or other roots of the call graph).
1733     for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1734       if (!AuxFCallsAlive[i] &&
1735           (AuxFunctionCalls[i].isIndirectCall()
1736            || CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited,
1737                                   Flags & DSGraph::RemoveUnreachableGlobals))) {
1738         AuxFunctionCalls[i].markReachableNodes(Alive);
1739         AuxFCallsAlive[i] = true;
1740         Iterate = true;
1741       }
1742   } while (Iterate);
1743
1744   // Move dead aux function calls to the end of the list
1745   unsigned CurIdx = 0;
1746   for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1747     if (AuxFCallsAlive[i])
1748       AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
1749
1750   // Copy and merge all global nodes and dead aux call nodes into the
1751   // GlobalsGraph, and all nodes reachable from those nodes
1752   // 
1753   if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1754     // Copy the unreachable call nodes to the globals graph, updating their
1755     // target pointers using the GGCloner
1756     for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i)
1757       GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(AuxFunctionCalls[i],
1758                                                           GGCloner));
1759   }
1760   // Crop all the useless ones out...
1761   AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1762                          AuxFunctionCalls.end());
1763
1764   // We are finally done with the GGCloner so we can destroy it.
1765   GGCloner.destroy();
1766
1767   // At this point, any nodes which are visited, but not alive, are nodes
1768   // which can be removed.  Loop over all nodes, eliminating completely
1769   // unreachable nodes.
1770   //
1771   std::vector<DSNode*> DeadNodes;
1772   DeadNodes.reserve(Nodes.size());
1773   for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E;) {
1774     DSNode *N = NI++;
1775     assert(!N->isForwarding() && "Forwarded node in nodes list?");
1776
1777     if (!Alive.count(N)) {
1778       Nodes.remove(N);
1779       assert(!N->isForwarding() && "Cannot remove a forwarding node!");
1780       DeadNodes.push_back(N);
1781       N->dropAllReferences();
1782       ++NumDNE;
1783     }
1784   }
1785
1786   // Remove all unreachable globals from the ScalarMap.
1787   // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
1788   // In either case, the dead nodes will not be in the set Alive.
1789   for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
1790     if (!Alive.count(GlobalNodes[i].second))
1791       ScalarMap.erase(GlobalNodes[i].first);
1792     else
1793       assert((Flags & DSGraph::RemoveUnreachableGlobals) && "non-dead global");
1794
1795   // Delete all dead nodes now since their referrer counts are zero.
1796   for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1797     delete DeadNodes[i];
1798
1799   DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
1800 }
1801
1802 void DSGraph::AssertGraphOK() const {
1803   for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1804     (*NI)->assertOK();
1805
1806   for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
1807          E = ScalarMap.end(); I != E; ++I) {
1808     assert(I->second.getNode() && "Null node in scalarmap!");
1809     AssertNodeInGraph(I->second.getNode());
1810     if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
1811       assert(I->second.getNode()->isGlobalNode() &&
1812              "Global points to node, but node isn't global?");
1813       AssertNodeContainsGlobal(I->second.getNode(), GV);
1814     }
1815   }
1816   AssertCallNodesInGraph();
1817   AssertAuxCallNodesInGraph();
1818 }
1819
1820 /// computeNodeMapping - Given roots in two different DSGraphs, traverse the
1821 /// nodes reachable from the two graphs, computing the mapping of nodes from
1822 /// the first to the second graph.
1823 ///
1824 void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
1825                                  const DSNodeHandle &NH2, NodeMapTy &NodeMap,
1826                                  bool StrictChecking) {
1827   DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
1828   if (N1 == 0 || N2 == 0) return;
1829
1830   DSNodeHandle &Entry = NodeMap[N1];
1831   if (Entry.getNode()) {
1832     // Termination of recursion!
1833     assert(!StrictChecking ||
1834            (Entry.getNode() == N2 &&
1835             Entry.getOffset() == (NH2.getOffset()-NH1.getOffset())) &&
1836            "Inconsistent mapping detected!");
1837     return;
1838   }
1839   
1840   Entry.setNode(N2);
1841   Entry.setOffset(NH2.getOffset()-NH1.getOffset());
1842
1843   // Loop over all of the fields that N1 and N2 have in common, recursively
1844   // mapping the edges together now.
1845   int N2Idx = NH2.getOffset()-NH1.getOffset();
1846   unsigned N2Size = N2->getSize();
1847   for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize)
1848     if (unsigned(N2Idx)+i < N2Size)
1849       computeNodeMapping(N1->getLink(i), N2->getLink(N2Idx+i), NodeMap);
1850 }