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