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