Unfortunately, a previous patch was not safe. Revert it, reimplement
[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 /// getFunctionArgumentsForCall - Given a function that is currently in this
1308 /// graph, return the DSNodeHandles that correspond to the pointer-compatible
1309 /// function arguments.  The vector is filled in with the return value (or
1310 /// null if it is not pointer compatible), followed by all of the
1311 /// pointer-compatible arguments.
1312 void DSGraph::getFunctionArgumentsForCall(Function *F,
1313                                        std::vector<DSNodeHandle> &Args) const {
1314   Args.push_back(getReturnNodeFor(*F));
1315   for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1316        AI != E; ++AI)
1317     if (isPointerType(AI->getType())) {
1318       Args.push_back(getNodeForValue(AI));
1319       assert(!Args.back().isNull() && "Pointer argument w/o scalarmap entry!?");
1320     }
1321 }
1322
1323 /// PathExistsToClonedNode - Return true if there is a path from this node to a
1324 /// node cloned by RC that does not go through another global node.  Use the
1325 /// NodeInfo map to cache information so this is an efficient depth first
1326 /// traversal.
1327 static bool PathExistsToClonedNode(const DSNode *N, ReachabilityCloner &RC,
1328                                    std::map<const DSNode*, bool> &NodeInfo) {
1329   std::map<const DSNode*, bool>::iterator I = NodeInfo.find(N);
1330   if (I != NodeInfo.end())
1331     return I->second;
1332
1333   // FIXME: we are potentially re-scc'ing chunks of the graph for all of the
1334   // roots!  We need an SCC iterator that supports multiple roots.
1335   //
1336   // FIXME: This should stop traversal of SCCs when we find something in RC!
1337   scc_iterator<const DSNode*> SCCI = scc_begin(N), SCCE = scc_end(N);
1338   for (; SCCI != SCCE; ++SCCI) {
1339     std::vector<const DSNode*> &SCC = *SCCI;
1340     assert(!SCC.empty() && "empty scc??");
1341
1342     if (NodeInfo.count(SCC[0]))
1343       continue;  // already processed.
1344
1345     bool SCCReachesClonedNode = false;
1346
1347     for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
1348       const DSNode *N = SCC[i];
1349
1350       if (RC.hasClonedNode(N)) {
1351         SCCReachesClonedNode = true;
1352         goto OutOfLoop;
1353       }
1354
1355       for (DSNode::const_edge_iterator EI = N->edge_begin(), E = N->edge_end();
1356            EI != E; ++EI)
1357         if (const DSNode *Succ = EI->getNode())
1358           if (NodeInfo[Succ]) {
1359             SCCReachesClonedNode = true;
1360             goto OutOfLoop;
1361           }
1362     }
1363
1364   OutOfLoop:
1365     for (unsigned i = 0, e = SCC.size(); i != e; ++i)
1366       NodeInfo[SCC[i]] = SCCReachesClonedNode;
1367   }
1368
1369   return NodeInfo[N];
1370 }
1371
1372 static bool PathExistsToClonedNode(const DSCallSite &CS, ReachabilityCloner &RC,
1373                                    std::map<const DSNode*, bool> &NodeInfo) {
1374   if (PathExistsToClonedNode(CS.getRetVal().getNode(), RC, NodeInfo))
1375     return true;
1376   for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1377     if (PathExistsToClonedNode(CS.getPtrArg(i).getNode(), RC, NodeInfo))
1378       return true;
1379   return false;
1380 }
1381
1382
1383 /// mergeInCallFromOtherGraph - This graph merges in the minimal number of
1384 /// nodes from G2 into 'this' graph, merging the bindings specified by the
1385 /// call site (in this graph) with the bindings specified by the vector in G2.
1386 /// The two DSGraphs must be different.
1387 ///
1388 void DSGraph::mergeInGraph(const DSCallSite &CS, 
1389                            std::vector<DSNodeHandle> &Args,
1390                            const DSGraph &Graph, unsigned CloneFlags) {
1391   TIME_REGION(X, "mergeInGraph");
1392
1393   assert((CloneFlags & DontCloneCallNodes) &&
1394          "Doesn't support copying of call nodes!");
1395
1396   // If this is not a recursive call, clone the graph into this graph...
1397   if (&Graph == this) {
1398     // Merge the return value with the return value of the context.
1399     Args[0].mergeWith(CS.getRetVal());
1400     
1401     // Resolve all of the function arguments.
1402     for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i) {
1403       if (i == Args.size()-1)
1404         break;
1405       
1406       // Add the link from the argument scalar to the provided value.
1407       Args[i+1].mergeWith(CS.getPtrArg(i));
1408     }
1409     return;
1410   }
1411
1412   // Clone the callee's graph into the current graph, keeping track of where
1413   // scalars in the old graph _used_ to point, and of the new nodes matching
1414   // nodes of the old graph.
1415   ReachabilityCloner RC(*this, Graph, CloneFlags);
1416     
1417   // Map the return node pointer over.
1418   if (!CS.getRetVal().isNull())
1419     RC.merge(CS.getRetVal(), Args[0]);
1420
1421   // Map over all of the arguments.
1422   for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i) {
1423     if (i == Args.size()-1)
1424       break;
1425       
1426     // Add the link from the argument scalar to the provided value.
1427     RC.merge(CS.getPtrArg(i), Args[i+1]);
1428   }
1429     
1430   // We generally don't want to copy global nodes or aux calls from the callee
1431   // graph to the caller graph.  However, we have to copy them if there is a
1432   // path from the node to a node we have already copied which does not go
1433   // through another global.  Compute the set of node that can reach globals and
1434   // aux call nodes to copy over, then do it.
1435   std::vector<const DSCallSite*> AuxCallToCopy;
1436   std::vector<GlobalValue*> GlobalsToCopy;
1437
1438   // NodesReachCopiedNodes - Memoize results for efficiency.  Contains a
1439   // true/false value for every visited node that reaches a copied node without
1440   // going through a global.
1441   std::map<const DSNode*, bool> NodesReachCopiedNodes;
1442   NodesReachCopiedNodes[0] = false;  // Initialize null.
1443
1444   if (!(CloneFlags & DontCloneAuxCallNodes))
1445     for (afc_iterator I = Graph.afc_begin(), E = Graph.afc_end(); I!=E; ++I)
1446       if (PathExistsToClonedNode(*I, RC, NodesReachCopiedNodes))
1447         AuxCallToCopy.push_back(&*I);
1448
1449   DSScalarMap GSM = Graph.getScalarMap();
1450   for (DSScalarMap::global_iterator GI = GSM.global_begin(),
1451          E = GSM.global_end(); GI != E; ++GI)
1452     if (PathExistsToClonedNode(Graph.getNodeForValue(*GI).getNode(), RC,
1453                                NodesReachCopiedNodes))
1454       GlobalsToCopy.push_back(*GI);
1455
1456   // Copy aux calls that are needed.
1457   for (unsigned i = 0, e = AuxCallToCopy.size(); i != e; ++i)
1458     AuxFunctionCalls.push_back(DSCallSite(*AuxCallToCopy[i], RC));
1459   
1460   // Copy globals that are needed.
1461   for (unsigned i = 0, e = GlobalsToCopy.size(); i != e; ++i)
1462     RC.getClonedNH(Graph.getNodeForValue(GlobalsToCopy[i]));
1463 }
1464
1465
1466
1467 /// mergeInGraph - The method is used for merging graphs together.  If the
1468 /// argument graph is not *this, it makes a clone of the specified graph, then
1469 /// merges the nodes specified in the call site with the formal arguments in the
1470 /// graph.
1471 ///
1472 void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1473                            const DSGraph &Graph, unsigned CloneFlags) {
1474   // Set up argument bindings.
1475   std::vector<DSNodeHandle> Args;
1476   Graph.getFunctionArgumentsForCall(&F, Args);
1477
1478   mergeInGraph(CS, Args, Graph, CloneFlags);
1479 }
1480
1481 /// getCallSiteForArguments - Get the arguments and return value bindings for
1482 /// the specified function in the current graph.
1483 ///
1484 DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1485   std::vector<DSNodeHandle> Args;
1486
1487   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
1488     if (isPointerType(I->getType()))
1489       Args.push_back(getNodeForValue(I));
1490
1491   return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
1492 }
1493
1494 /// getDSCallSiteForCallSite - Given an LLVM CallSite object that is live in
1495 /// the context of this graph, return the DSCallSite for it.
1496 DSCallSite DSGraph::getDSCallSiteForCallSite(CallSite CS) const {
1497   DSNodeHandle RetVal;
1498   Instruction *I = CS.getInstruction();
1499   if (isPointerType(I->getType()))
1500     RetVal = getNodeForValue(I);
1501
1502   std::vector<DSNodeHandle> Args;
1503   Args.reserve(CS.arg_end()-CS.arg_begin());
1504
1505   // Calculate the arguments vector...
1506   for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I)
1507     if (isPointerType((*I)->getType()))
1508       if (isa<ConstantPointerNull>(*I))
1509         Args.push_back(DSNodeHandle());
1510       else
1511         Args.push_back(getNodeForValue(*I));
1512
1513   // Add a new function call entry...
1514   if (Function *F = CS.getCalledFunction())
1515     return DSCallSite(CS, RetVal, F, Args);
1516   else
1517     return DSCallSite(CS, RetVal,
1518                       getNodeForValue(CS.getCalledValue()).getNode(), Args);
1519 }
1520
1521
1522
1523 // markIncompleteNodes - Mark the specified node as having contents that are not
1524 // known with the current analysis we have performed.  Because a node makes all
1525 // of the nodes it can reach incomplete if the node itself is incomplete, we
1526 // must recursively traverse the data structure graph, marking all reachable
1527 // nodes as incomplete.
1528 //
1529 static void markIncompleteNode(DSNode *N) {
1530   // Stop recursion if no node, or if node already marked...
1531   if (N == 0 || N->isIncomplete()) return;
1532
1533   // Actually mark the node
1534   N->setIncompleteMarker();
1535
1536   // Recursively process children...
1537   for (DSNode::edge_iterator I = N->edge_begin(),E = N->edge_end(); I != E; ++I)
1538     if (DSNode *DSN = I->getNode())
1539       markIncompleteNode(DSN);
1540 }
1541
1542 static void markIncomplete(DSCallSite &Call) {
1543   // Then the return value is certainly incomplete!
1544   markIncompleteNode(Call.getRetVal().getNode());
1545
1546   // All objects pointed to by function arguments are incomplete!
1547   for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1548     markIncompleteNode(Call.getPtrArg(i).getNode());
1549 }
1550
1551 // markIncompleteNodes - Traverse the graph, identifying nodes that may be
1552 // modified by other functions that have not been resolved yet.  This marks
1553 // nodes that are reachable through three sources of "unknownness":
1554 //
1555 //  Global Variables, Function Calls, and Incoming Arguments
1556 //
1557 // For any node that may have unknown components (because something outside the
1558 // scope of current analysis may have modified it), the 'Incomplete' flag is
1559 // added to the NodeType.
1560 //
1561 void DSGraph::markIncompleteNodes(unsigned Flags) {
1562   // Mark any incoming arguments as incomplete.
1563   if (Flags & DSGraph::MarkFormalArgs)
1564     for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1565          FI != E; ++FI) {
1566       Function &F = *FI->first;
1567       for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
1568         if (isPointerType(I->getType()))
1569           markIncompleteNode(getNodeForValue(I).getNode());
1570       markIncompleteNode(FI->second.getNode());
1571     }
1572
1573   // Mark stuff passed into functions calls as being incomplete.
1574   if (!shouldPrintAuxCalls())
1575     for (std::list<DSCallSite>::iterator I = FunctionCalls.begin(),
1576            E = FunctionCalls.end(); I != E; ++I)
1577       markIncomplete(*I);
1578   else
1579     for (std::list<DSCallSite>::iterator I = AuxFunctionCalls.begin(),
1580            E = AuxFunctionCalls.end(); I != E; ++I)
1581       markIncomplete(*I);
1582
1583   // Mark all global nodes as incomplete.
1584   for (DSScalarMap::global_iterator I = ScalarMap.global_begin(),
1585          E = ScalarMap.global_end(); I != E; ++I)
1586     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I))
1587       if (!GV->hasInitializer() ||    // Always mark external globals incomp.
1588           (!GV->isConstant() && (Flags & DSGraph::IgnoreGlobals) == 0))
1589         markIncompleteNode(ScalarMap[GV].getNode());
1590 }
1591
1592 static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1593   if (DSNode *N = Edge.getNode())  // Is there an edge?
1594     if (N->getNumReferrers() == 1)  // Does it point to a lonely node?
1595       // No interesting info?
1596       if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
1597           N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
1598         Edge.setTo(0, 0);  // Kill the edge!
1599 }
1600
1601 static inline bool nodeContainsExternalFunction(const DSNode *N) {
1602   std::vector<Function*> Funcs;
1603   N->addFullFunctionList(Funcs);
1604   for (unsigned i = 0, e = Funcs.size(); i != e; ++i)
1605     if (Funcs[i]->isExternal()) return true;
1606   return false;
1607 }
1608
1609 static void removeIdenticalCalls(std::list<DSCallSite> &Calls) {
1610   // Remove trivially identical function calls
1611   Calls.sort();  // Sort by callee as primary key!
1612
1613   // Scan the call list cleaning it up as necessary...
1614   DSNodeHandle LastCalleeNode;
1615   Function *LastCalleeFunc = 0;
1616   unsigned NumDuplicateCalls = 0;
1617   bool LastCalleeContainsExternalFunction = false;
1618
1619   unsigned NumDeleted = 0;
1620   for (std::list<DSCallSite>::iterator I = Calls.begin(), E = Calls.end();
1621        I != E;) {
1622     DSCallSite &CS = *I;
1623     std::list<DSCallSite>::iterator OldIt = I++;
1624
1625     if (!CS.isIndirectCall()) {
1626       LastCalleeNode = 0;
1627     } else {
1628       DSNode *Callee = CS.getCalleeNode();
1629
1630       // If the Callee is a useless edge, this must be an unreachable call site,
1631       // eliminate it.
1632       if (Callee->getNumReferrers() == 1 && Callee->isComplete() &&
1633           Callee->getGlobalsList().empty()) {  // No useful info?
1634 #ifndef NDEBUG
1635         std::cerr << "WARNING: Useless call site found.\n";
1636 #endif
1637         Calls.erase(OldIt);
1638         ++NumDeleted;
1639         continue;
1640       }
1641
1642       // If the last call site in the list has the same callee as this one, and
1643       // if the callee contains an external function, it will never be
1644       // resolvable, just merge the call sites.
1645       if (!LastCalleeNode.isNull() && LastCalleeNode.getNode() == Callee) {
1646         LastCalleeContainsExternalFunction =
1647           nodeContainsExternalFunction(Callee);
1648
1649         std::list<DSCallSite>::iterator PrevIt = OldIt;
1650         --PrevIt;
1651         PrevIt->mergeWith(CS);
1652
1653         // No need to keep this call anymore.
1654         Calls.erase(OldIt);
1655         ++NumDeleted;
1656         continue;
1657       } else {
1658         LastCalleeNode = Callee;
1659       }
1660     }
1661
1662     // If the return value or any arguments point to a void node with no
1663     // information at all in it, and the call node is the only node to point
1664     // to it, remove the edge to the node (killing the node).
1665     //
1666     killIfUselessEdge(CS.getRetVal());
1667     for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1668       killIfUselessEdge(CS.getPtrArg(a));
1669     
1670 #if 0
1671     // If this call site calls the same function as the last call site, and if
1672     // the function pointer contains an external function, this node will
1673     // never be resolved.  Merge the arguments of the call node because no
1674     // information will be lost.
1675     //
1676     if ((CS.isDirectCall()   && CS.getCalleeFunc() == LastCalleeFunc) ||
1677         (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
1678       ++NumDuplicateCalls;
1679       if (NumDuplicateCalls == 1) {
1680         if (LastCalleeNode)
1681           LastCalleeContainsExternalFunction =
1682             nodeContainsExternalFunction(LastCalleeNode);
1683         else
1684           LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
1685       }
1686       
1687       // It is not clear why, but enabling this code makes DSA really
1688       // sensitive to node forwarding.  Basically, with this enabled, DSA
1689       // performs different number of inlinings based on which nodes are
1690       // forwarding or not.  This is clearly a problem, so this code is
1691       // disabled until this can be resolved.
1692 #if 1
1693       if (LastCalleeContainsExternalFunction
1694 #if 0
1695           ||
1696           // This should be more than enough context sensitivity!
1697           // FIXME: Evaluate how many times this is tripped!
1698           NumDuplicateCalls > 20
1699 #endif
1700           ) {
1701         
1702         std::list<DSCallSite>::iterator PrevIt = OldIt;
1703         --PrevIt;
1704         PrevIt->mergeWith(CS);
1705         
1706         // No need to keep this call anymore.
1707         Calls.erase(OldIt);
1708         ++NumDeleted;
1709         continue;
1710       }
1711 #endif
1712     } else {
1713       if (CS.isDirectCall()) {
1714         LastCalleeFunc = CS.getCalleeFunc();
1715         LastCalleeNode = 0;
1716       } else {
1717         LastCalleeNode = CS.getCalleeNode();
1718         LastCalleeFunc = 0;
1719       }
1720       NumDuplicateCalls = 0;
1721     }
1722 #endif
1723
1724     if (I != Calls.end() && CS == *I) {
1725       LastCalleeNode = 0;
1726       Calls.erase(OldIt);
1727       ++NumDeleted;
1728       continue;
1729     }
1730   }
1731
1732   // Resort now that we simplified things.
1733   Calls.sort();
1734
1735   // Now that we are in sorted order, eliminate duplicates.
1736   std::list<DSCallSite>::iterator CI = Calls.begin(), CE = Calls.end();
1737   if (CI != CE)
1738     while (1) {
1739       std::list<DSCallSite>::iterator OldIt = CI++;
1740       if (CI == CE) break;
1741
1742       // If this call site is now the same as the previous one, we can delete it
1743       // as a duplicate.
1744       if (*OldIt == *CI) {
1745         Calls.erase(CI);
1746         CI = OldIt;
1747         ++NumDeleted;
1748       }
1749     }
1750
1751   //Calls.erase(std::unique(Calls.begin(), Calls.end()), Calls.end());
1752
1753   // Track the number of call nodes merged away...
1754   NumCallNodesMerged += NumDeleted;
1755
1756   DEBUG(if (NumDeleted)
1757           std::cerr << "Merged " << NumDeleted << " call nodes.\n";);
1758 }
1759
1760
1761 // removeTriviallyDeadNodes - After the graph has been constructed, this method
1762 // removes all unreachable nodes that are created because they got merged with
1763 // other nodes in the graph.  These nodes will all be trivially unreachable, so
1764 // we don't have to perform any non-trivial analysis here.
1765 //
1766 void DSGraph::removeTriviallyDeadNodes() {
1767   TIME_REGION(X, "removeTriviallyDeadNodes");
1768
1769 #if 0
1770   /// NOTE: This code is disabled.  This slows down DSA on 177.mesa
1771   /// substantially!
1772
1773   // Loop over all of the nodes in the graph, calling getNode on each field.
1774   // This will cause all nodes to update their forwarding edges, causing
1775   // forwarded nodes to be delete-able.
1776   { TIME_REGION(X, "removeTriviallyDeadNodes:node_iterate");
1777   for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI) {
1778     DSNode &N = *NI;
1779     for (unsigned l = 0, e = N.getNumLinks(); l != e; ++l)
1780       N.getLink(l*N.getPointerSize()).getNode();
1781   }
1782   }
1783
1784   // NOTE: This code is disabled.  Though it should, in theory, allow us to
1785   // remove more nodes down below, the scan of the scalar map is incredibly
1786   // expensive for certain programs (with large SCCs).  In the future, if we can
1787   // make the scalar map scan more efficient, then we can reenable this.
1788   { TIME_REGION(X, "removeTriviallyDeadNodes:scalarmap");
1789
1790   // Likewise, forward any edges from the scalar nodes.  While we are at it,
1791   // clean house a bit.
1792   for (DSScalarMap::iterator I = ScalarMap.begin(),E = ScalarMap.end();I != E;){
1793     I->second.getNode();
1794     ++I;
1795   }
1796   }
1797 #endif
1798   bool isGlobalsGraph = !GlobalsGraph;
1799
1800   for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E; ) {
1801     DSNode &Node = *NI;
1802
1803     // Do not remove *any* global nodes in the globals graph.
1804     // This is a special case because such nodes may not have I, M, R flags set.
1805     if (Node.isGlobalNode() && isGlobalsGraph) {
1806       ++NI;
1807       continue;
1808     }
1809
1810     if (Node.isComplete() && !Node.isModified() && !Node.isRead()) {
1811       // This is a useless node if it has no mod/ref info (checked above),
1812       // outgoing edges (which it cannot, as it is not modified in this
1813       // context), and it has no incoming edges.  If it is a global node it may
1814       // have all of these properties and still have incoming edges, due to the
1815       // scalar map, so we check those now.
1816       //
1817       if (Node.getNumReferrers() == Node.getGlobalsList().size()) {
1818         const std::vector<GlobalValue*> &Globals = Node.getGlobalsList();
1819
1820         // Loop through and make sure all of the globals are referring directly
1821         // to the node...
1822         for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1823           DSNode *N = getNodeForValue(Globals[j]).getNode();
1824           assert(N == &Node && "ScalarMap doesn't match globals list!");
1825         }
1826
1827         // Make sure NumReferrers still agrees, if so, the node is truly dead.
1828         if (Node.getNumReferrers() == Globals.size()) {
1829           for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1830             ScalarMap.erase(Globals[j]);
1831           Node.makeNodeDead();
1832           ++NumTrivialGlobalDNE;
1833         }
1834       }
1835     }
1836
1837     if (Node.getNodeFlags() == 0 && Node.hasNoReferrers()) {
1838       // This node is dead!
1839       NI = Nodes.erase(NI);    // Erase & remove from node list.
1840       ++NumTrivialDNE;
1841     } else {
1842       ++NI;
1843     }
1844   }
1845
1846   removeIdenticalCalls(FunctionCalls);
1847   removeIdenticalCalls(AuxFunctionCalls);
1848 }
1849
1850
1851 /// markReachableNodes - This method recursively traverses the specified
1852 /// DSNodes, marking any nodes which are reachable.  All reachable nodes it adds
1853 /// to the set, which allows it to only traverse visited nodes once.
1854 ///
1855 void DSNode::markReachableNodes(hash_set<const DSNode*> &ReachableNodes) const {
1856   if (this == 0) return;
1857   assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
1858   if (ReachableNodes.insert(this).second)        // Is newly reachable?
1859     for (DSNode::const_edge_iterator I = edge_begin(), E = edge_end();
1860          I != E; ++I)
1861       I->getNode()->markReachableNodes(ReachableNodes);
1862 }
1863
1864 void DSCallSite::markReachableNodes(hash_set<const DSNode*> &Nodes) const {
1865   getRetVal().getNode()->markReachableNodes(Nodes);
1866   if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
1867   
1868   for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1869     getPtrArg(i).getNode()->markReachableNodes(Nodes);
1870 }
1871
1872 // CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1873 // looking for a node that is marked alive.  If an alive node is found, return
1874 // true, otherwise return false.  If an alive node is reachable, this node is
1875 // marked as alive...
1876 //
1877 static bool CanReachAliveNodes(DSNode *N, hash_set<const DSNode*> &Alive,
1878                                hash_set<const DSNode*> &Visited,
1879                                bool IgnoreGlobals) {
1880   if (N == 0) return false;
1881   assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
1882
1883   // If this is a global node, it will end up in the globals graph anyway, so we
1884   // don't need to worry about it.
1885   if (IgnoreGlobals && N->isGlobalNode()) return false;
1886
1887   // If we know that this node is alive, return so!
1888   if (Alive.count(N)) return true;
1889
1890   // Otherwise, we don't think the node is alive yet, check for infinite
1891   // recursion.
1892   if (Visited.count(N)) return false;  // Found a cycle
1893   Visited.insert(N);   // No recursion, insert into Visited...
1894
1895   for (DSNode::edge_iterator I = N->edge_begin(),E = N->edge_end(); I != E; ++I)
1896     if (CanReachAliveNodes(I->getNode(), Alive, Visited, IgnoreGlobals)) {
1897       N->markReachableNodes(Alive);
1898       return true;
1899     }
1900   return false;
1901 }
1902
1903 // CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1904 // alive nodes.
1905 //
1906 static bool CallSiteUsesAliveArgs(const DSCallSite &CS,
1907                                   hash_set<const DSNode*> &Alive,
1908                                   hash_set<const DSNode*> &Visited,
1909                                   bool IgnoreGlobals) {
1910   if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
1911                          IgnoreGlobals))
1912     return true;
1913   if (CS.isIndirectCall() &&
1914       CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
1915     return true;
1916   for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1917     if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
1918                            IgnoreGlobals))
1919       return true;
1920   return false;
1921 }
1922
1923 // removeDeadNodes - Use a more powerful reachability analysis to eliminate
1924 // subgraphs that are unreachable.  This often occurs because the data
1925 // structure doesn't "escape" into it's caller, and thus should be eliminated
1926 // from the caller's graph entirely.  This is only appropriate to use when
1927 // inlining graphs.
1928 //
1929 void DSGraph::removeDeadNodes(unsigned Flags) {
1930   DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
1931
1932   // Reduce the amount of work we have to do... remove dummy nodes left over by
1933   // merging...
1934   removeTriviallyDeadNodes();
1935
1936   TIME_REGION(X, "removeDeadNodes");
1937
1938   // FIXME: Merge non-trivially identical call nodes...
1939
1940   // Alive - a set that holds all nodes found to be reachable/alive.
1941   hash_set<const DSNode*> Alive;
1942   std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
1943
1944   // Copy and merge all information about globals to the GlobalsGraph if this is
1945   // not a final pass (where unreachable globals are removed).
1946   //
1947   // Strip all alloca bits since the current function is only for the BU pass.
1948   // Strip all incomplete bits since they are short-lived properties and they
1949   // will be correctly computed when rematerializing nodes into the functions.
1950   //
1951   ReachabilityCloner GGCloner(*GlobalsGraph, *this, DSGraph::StripAllocaBit |
1952                               DSGraph::StripIncompleteBit);
1953
1954   // Mark all nodes reachable by (non-global) scalar nodes as alive...
1955 { TIME_REGION(Y, "removeDeadNodes:scalarscan");
1956   for (DSScalarMap::iterator I = ScalarMap.begin(), E = ScalarMap.end();
1957        I != E; ++I)
1958     if (isa<GlobalValue>(I->first)) {             // Keep track of global nodes
1959       assert(!I->second.isNull() && "Null global node?");
1960       assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
1961       GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
1962
1963       // Make sure that all globals are cloned over as roots.
1964       if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1965         DSGraph::ScalarMapTy::iterator SMI = 
1966           GlobalsGraph->getScalarMap().find(I->first);
1967         if (SMI != GlobalsGraph->getScalarMap().end())
1968           GGCloner.merge(SMI->second, I->second);
1969         else
1970           GGCloner.getClonedNH(I->second);
1971       }
1972     } else {
1973       I->second.getNode()->markReachableNodes(Alive);
1974     }
1975 }
1976
1977   // The return values are alive as well.
1978   for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1979        I != E; ++I)
1980     I->second.getNode()->markReachableNodes(Alive);
1981
1982   // Mark any nodes reachable by primary calls as alive...
1983   for (fc_iterator I = fc_begin(), E = fc_end(); I != E; ++I)
1984     I->markReachableNodes(Alive);
1985
1986
1987   // Now find globals and aux call nodes that are already live or reach a live
1988   // value (which makes them live in turn), and continue till no more are found.
1989   // 
1990   bool Iterate;
1991   hash_set<const DSNode*> Visited;
1992   hash_set<const DSCallSite*> AuxFCallsAlive;
1993   do {
1994     Visited.clear();
1995     // If any global node points to a non-global that is "alive", the global is
1996     // "alive" as well...  Remove it from the GlobalNodes list so we only have
1997     // unreachable globals in the list.
1998     //
1999     Iterate = false;
2000     if (!(Flags & DSGraph::RemoveUnreachableGlobals))
2001       for (unsigned i = 0; i != GlobalNodes.size(); ++i)
2002         if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited, 
2003                                Flags & DSGraph::RemoveUnreachableGlobals)) {
2004           std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
2005           GlobalNodes.pop_back();                          // erase efficiently
2006           Iterate = true;
2007         }
2008
2009     // Mark only unresolvable call nodes for moving to the GlobalsGraph since
2010     // call nodes that get resolved will be difficult to remove from that graph.
2011     // The final unresolved call nodes must be handled specially at the end of
2012     // the BU pass (i.e., in main or other roots of the call graph).
2013     for (afc_iterator CI = afc_begin(), E = afc_end(); CI != E; ++CI)
2014       if (!AuxFCallsAlive.count(&*CI) &&
2015           (CI->isIndirectCall()
2016            || CallSiteUsesAliveArgs(*CI, Alive, Visited,
2017                                   Flags & DSGraph::RemoveUnreachableGlobals))) {
2018         CI->markReachableNodes(Alive);
2019         AuxFCallsAlive.insert(&*CI);
2020         Iterate = true;
2021       }
2022   } while (Iterate);
2023
2024   // Move dead aux function calls to the end of the list
2025   unsigned CurIdx = 0;
2026   for (std::list<DSCallSite>::iterator CI = AuxFunctionCalls.begin(),
2027          E = AuxFunctionCalls.end(); CI != E; )
2028     if (AuxFCallsAlive.count(&*CI))
2029       ++CI;
2030     else {
2031       // Copy and merge global nodes and dead aux call nodes into the
2032       // GlobalsGraph, and all nodes reachable from those nodes.  Update their
2033       // target pointers using the GGCloner.
2034       // 
2035       if (!(Flags & DSGraph::RemoveUnreachableGlobals))
2036         GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(*CI, GGCloner));
2037
2038       AuxFunctionCalls.erase(CI++);
2039     }
2040
2041   // We are finally done with the GGCloner so we can destroy it.
2042   GGCloner.destroy();
2043
2044   // At this point, any nodes which are visited, but not alive, are nodes
2045   // which can be removed.  Loop over all nodes, eliminating completely
2046   // unreachable nodes.
2047   //
2048   std::vector<DSNode*> DeadNodes;
2049   DeadNodes.reserve(Nodes.size());
2050   for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E;) {
2051     DSNode *N = NI++;
2052     assert(!N->isForwarding() && "Forwarded node in nodes list?");
2053
2054     if (!Alive.count(N)) {
2055       Nodes.remove(N);
2056       assert(!N->isForwarding() && "Cannot remove a forwarding node!");
2057       DeadNodes.push_back(N);
2058       N->dropAllReferences();
2059       ++NumDNE;
2060     }
2061   }
2062
2063   // Remove all unreachable globals from the ScalarMap.
2064   // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
2065   // In either case, the dead nodes will not be in the set Alive.
2066   for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
2067     if (!Alive.count(GlobalNodes[i].second))
2068       ScalarMap.erase(GlobalNodes[i].first);
2069     else
2070       assert((Flags & DSGraph::RemoveUnreachableGlobals) && "non-dead global");
2071
2072   // Delete all dead nodes now since their referrer counts are zero.
2073   for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
2074     delete DeadNodes[i];
2075
2076   DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
2077 }
2078
2079 void DSGraph::AssertNodeContainsGlobal(const DSNode *N, GlobalValue *GV) const {
2080   assert(std::find(N->globals_begin(),N->globals_end(), GV) !=
2081          N->globals_end() && "Global value not in node!");
2082 }
2083
2084 void DSGraph::AssertCallSiteInGraph(const DSCallSite &CS) const {
2085   if (CS.isIndirectCall()) {
2086     AssertNodeInGraph(CS.getCalleeNode());
2087 #if 0
2088     if (CS.getNumPtrArgs() && CS.getCalleeNode() == CS.getPtrArg(0).getNode() &&
2089         CS.getCalleeNode() && CS.getCalleeNode()->getGlobals().empty())
2090       std::cerr << "WARNING: WEIRD CALL SITE FOUND!\n";      
2091 #endif
2092   }
2093   AssertNodeInGraph(CS.getRetVal().getNode());
2094   for (unsigned j = 0, e = CS.getNumPtrArgs(); j != e; ++j)
2095     AssertNodeInGraph(CS.getPtrArg(j).getNode());
2096 }
2097
2098 void DSGraph::AssertCallNodesInGraph() const {
2099   for (fc_iterator I = fc_begin(), E = fc_end(); I != E; ++I)
2100     AssertCallSiteInGraph(*I);
2101 }
2102 void DSGraph::AssertAuxCallNodesInGraph() const {
2103   for (afc_iterator I = afc_begin(), E = afc_end(); I != E; ++I)
2104     AssertCallSiteInGraph(*I);
2105 }
2106
2107 void DSGraph::AssertGraphOK() const {
2108   for (node_const_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
2109     NI->assertOK();
2110
2111   for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
2112          E = ScalarMap.end(); I != E; ++I) {
2113     assert(!I->second.isNull() && "Null node in scalarmap!");
2114     AssertNodeInGraph(I->second.getNode());
2115     if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
2116       assert(I->second.getNode()->isGlobalNode() &&
2117              "Global points to node, but node isn't global?");
2118       AssertNodeContainsGlobal(I->second.getNode(), GV);
2119     }
2120   }
2121   AssertCallNodesInGraph();
2122   AssertAuxCallNodesInGraph();
2123
2124   // Check that all pointer arguments to any functions in this graph have
2125   // destinations.
2126   for (ReturnNodesTy::const_iterator RI = ReturnNodes.begin(),
2127          E = ReturnNodes.end();
2128        RI != E; ++RI) {
2129     Function &F = *RI->first;
2130     for (Function::arg_iterator AI = F.arg_begin(); AI != F.arg_end(); ++AI)
2131       if (isPointerType(AI->getType()))
2132         assert(!getNodeForValue(AI).isNull() &&
2133                "Pointer argument must be in the scalar map!");
2134   }
2135 }
2136
2137 /// computeNodeMapping - Given roots in two different DSGraphs, traverse the
2138 /// nodes reachable from the two graphs, computing the mapping of nodes from the
2139 /// first to the second graph.  This mapping may be many-to-one (i.e. the first
2140 /// graph may have multiple nodes representing one node in the second graph),
2141 /// but it will not work if there is a one-to-many or many-to-many mapping.
2142 ///
2143 void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
2144                                  const DSNodeHandle &NH2, NodeMapTy &NodeMap,
2145                                  bool StrictChecking) {
2146   DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
2147   if (N1 == 0 || N2 == 0) return;
2148
2149   DSNodeHandle &Entry = NodeMap[N1];
2150   if (!Entry.isNull()) {
2151     // Termination of recursion!
2152     if (StrictChecking) {
2153       assert(Entry.getNode() == N2 && "Inconsistent mapping detected!");
2154       assert((Entry.getOffset() == (NH2.getOffset()-NH1.getOffset()) ||
2155               Entry.getNode()->isNodeCompletelyFolded()) &&
2156              "Inconsistent mapping detected!");
2157     }
2158     return;
2159   }
2160   
2161   Entry.setTo(N2, NH2.getOffset()-NH1.getOffset());
2162
2163   // Loop over all of the fields that N1 and N2 have in common, recursively
2164   // mapping the edges together now.
2165   int N2Idx = NH2.getOffset()-NH1.getOffset();
2166   unsigned N2Size = N2->getSize();
2167   if (N2Size == 0) return;   // No edges to map to.
2168
2169   for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize) {
2170     const DSNodeHandle &N1NH = N1->getLink(i);
2171     // Don't call N2->getLink if not needed (avoiding crash if N2Idx is not
2172     // aligned right).
2173     if (!N1NH.isNull()) {
2174       if (unsigned(N2Idx)+i < N2Size)
2175         computeNodeMapping(N1NH, N2->getLink(N2Idx+i), NodeMap);
2176       else
2177         computeNodeMapping(N1NH,
2178                            N2->getLink(unsigned(N2Idx+i) % N2Size), NodeMap);
2179     }
2180   }
2181 }
2182
2183
2184 /// computeGToGGMapping - Compute the mapping of nodes in the global graph to
2185 /// nodes in this graph.
2186 void DSGraph::computeGToGGMapping(NodeMapTy &NodeMap) {
2187   DSGraph &GG = *getGlobalsGraph();
2188
2189   DSScalarMap &SM = getScalarMap();
2190   for (DSScalarMap::global_iterator I = SM.global_begin(),
2191          E = SM.global_end(); I != E; ++I)
2192     DSGraph::computeNodeMapping(SM[*I], GG.getNodeForValue(*I), NodeMap);
2193 }
2194                                 
2195 /// computeGGToGMapping - Compute the mapping of nodes in the global graph to
2196 /// nodes in this graph.  Note that any uses of this method are probably bugs,
2197 /// unless it is known that the globals graph has been merged into this graph!
2198 void DSGraph::computeGGToGMapping(InvNodeMapTy &InvNodeMap) {
2199   NodeMapTy NodeMap;
2200   computeGToGGMapping(NodeMap);
2201
2202   while (!NodeMap.empty()) {
2203     InvNodeMap.insert(std::make_pair(NodeMap.begin()->second,
2204                                      NodeMap.begin()->first));
2205     NodeMap.erase(NodeMap.begin());
2206   }
2207 }
2208                                 
2209
2210 /// computeCalleeCallerMapping - Given a call from a function in the current
2211 /// graph to the 'Callee' function (which lives in 'CalleeGraph'), compute the
2212 /// mapping of nodes from the callee to nodes in the caller.
2213 void DSGraph::computeCalleeCallerMapping(DSCallSite CS, const Function &Callee,
2214                                          DSGraph &CalleeGraph,
2215                                          NodeMapTy &NodeMap) {
2216
2217   DSCallSite CalleeArgs =
2218     CalleeGraph.getCallSiteForArguments(const_cast<Function&>(Callee));
2219   
2220   computeNodeMapping(CalleeArgs.getRetVal(), CS.getRetVal(), NodeMap);
2221
2222   unsigned NumArgs = CS.getNumPtrArgs();
2223   if (NumArgs > CalleeArgs.getNumPtrArgs())
2224     NumArgs = CalleeArgs.getNumPtrArgs();
2225
2226   for (unsigned i = 0; i != NumArgs; ++i)
2227     computeNodeMapping(CalleeArgs.getPtrArg(i), CS.getPtrArg(i), NodeMap);
2228     
2229   // Map the nodes that are pointed to by globals.
2230   DSScalarMap &CalleeSM = CalleeGraph.getScalarMap();
2231   DSScalarMap &CallerSM = getScalarMap();
2232
2233   if (CalleeSM.global_size() >= CallerSM.global_size()) {
2234     for (DSScalarMap::global_iterator GI = CallerSM.global_begin(), 
2235            E = CallerSM.global_end(); GI != E; ++GI)
2236       if (CalleeSM.global_count(*GI))
2237         computeNodeMapping(CalleeSM[*GI], CallerSM[*GI], NodeMap);
2238   } else {
2239     for (DSScalarMap::global_iterator GI = CalleeSM.global_begin(), 
2240            E = CalleeSM.global_end(); GI != E; ++GI)
2241       if (CallerSM.global_count(*GI))
2242         computeNodeMapping(CalleeSM[*GI], CallerSM[*GI], NodeMap);
2243   }
2244 }