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