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