bdf8d810fb667127098fbbdd3171d545e172eac4
[oota-llvm.git] / lib / Analysis / DataStructure / DataStructure.cpp
1 //===- DataStructure.cpp - Implement the core data structure analysis -----===//
2 //
3 // This file implements the core data structure functionality.
4 //
5 //===----------------------------------------------------------------------===//
6
7 #include "llvm/Analysis/DSGraph.h"
8 #include "llvm/Function.h"
9 #include "llvm/iOther.h"
10 #include "llvm/DerivedTypes.h"
11 #include "llvm/Target/TargetData.h"
12 #include "llvm/Assembly/Writer.h"
13 #include "Support/Debug.h"
14 #include "Support/STLExtras.h"
15 #include "Support/Statistic.h"
16 #include "Support/Timer.h"
17 #include <algorithm>
18
19 namespace {
20   Statistic<> NumFolds          ("dsnode", "Number of nodes completely folded");
21   Statistic<> NumCallNodesMerged("dsnode", "Number of call nodes merged");
22 };
23
24 namespace DS {   // TODO: FIXME
25   extern TargetData TD;
26 }
27 using namespace DS;
28
29 DSNode *DSNodeHandle::HandleForwarding() const {
30   assert(!N->ForwardNH.isNull() && "Can only be invoked if forwarding!");
31
32   // Handle node forwarding here!
33   DSNode *Next = N->ForwardNH.getNode();  // Cause recursive shrinkage
34   Offset += N->ForwardNH.getOffset();
35
36   if (--N->NumReferrers == 0) {
37     // Removing the last referrer to the node, sever the forwarding link
38     N->stopForwarding();
39   }
40
41   N = Next;
42   N->NumReferrers++;
43   if (N->Size <= Offset) {
44     assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
45     Offset = 0;
46   }
47   return N;
48 }
49
50 //===----------------------------------------------------------------------===//
51 // DSNode Implementation
52 //===----------------------------------------------------------------------===//
53
54 DSNode::DSNode(const Type *T, DSGraph *G)
55   : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
56   // Add the type entry if it is specified...
57   if (T) mergeTypeInfo(T, 0);
58   G->getNodes().push_back(this);
59 }
60
61 // DSNode copy constructor... do not copy over the referrers list!
62 DSNode::DSNode(const DSNode &N, DSGraph *G)
63   : NumReferrers(0), Size(N.Size), ParentGraph(G),
64     Ty(N.Ty), Links(N.Links), Globals(N.Globals), NodeType(N.NodeType) {
65   G->getNodes().push_back(this);
66 }
67
68 void DSNode::assertOK() const {
69   assert((Ty != Type::VoidTy ||
70           Ty == Type::VoidTy && (Size == 0 ||
71                                  (NodeType & DSNode::Array))) &&
72          "Node not OK!");
73
74   assert(ParentGraph && "Node has no parent?");
75   const DSGraph::ScalarMapTy &SM = ParentGraph->getScalarMap();
76   for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
77     assert(SM.find(Globals[i]) != SM.end());
78     assert(SM.find(Globals[i])->second.getNode() == this);
79   }
80 }
81
82 /// forwardNode - Mark this node as being obsolete, and all references to it
83 /// should be forwarded to the specified node and offset.
84 ///
85 void DSNode::forwardNode(DSNode *To, unsigned Offset) {
86   assert(this != To && "Cannot forward a node to itself!");
87   assert(ForwardNH.isNull() && "Already forwarding from this node!");
88   if (To->Size <= 1) Offset = 0;
89   assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
90          "Forwarded offset is wrong!");
91   ForwardNH.setNode(To);
92   ForwardNH.setOffset(Offset);
93   NodeType = DEAD;
94   Size = 0;
95   Ty = Type::VoidTy;
96 }
97
98 // addGlobal - Add an entry for a global value to the Globals list.  This also
99 // marks the node with the 'G' flag if it does not already have it.
100 //
101 void DSNode::addGlobal(GlobalValue *GV) {
102   // Keep the list sorted.
103   std::vector<GlobalValue*>::iterator I =
104     std::lower_bound(Globals.begin(), Globals.end(), GV);
105
106   if (I == Globals.end() || *I != GV) {
107     //assert(GV->getType()->getElementType() == Ty);
108     Globals.insert(I, GV);
109     NodeType |= GlobalNode;
110   }
111 }
112
113 /// foldNodeCompletely - If we determine that this node has some funny
114 /// behavior happening to it that we cannot represent, we fold it down to a
115 /// single, completely pessimistic, node.  This node is represented as a
116 /// single byte with a single TypeEntry of "void".
117 ///
118 void DSNode::foldNodeCompletely() {
119   if (isNodeCompletelyFolded()) return;  // If this node is already folded...
120
121   ++NumFolds;
122
123   // Create the node we are going to forward to...
124   DSNode *DestNode = new DSNode(0, ParentGraph);
125   DestNode->NodeType = NodeType|DSNode::Array;
126   DestNode->Ty = Type::VoidTy;
127   DestNode->Size = 1;
128   DestNode->Globals.swap(Globals);
129
130   // Start forwarding to the destination node...
131   forwardNode(DestNode, 0);
132   
133   if (Links.size()) {
134     DestNode->Links.push_back(Links[0]);
135     DSNodeHandle NH(DestNode);
136
137     // If we have links, merge all of our outgoing links together...
138     for (unsigned i = Links.size()-1; i != 0; --i)
139       NH.getNode()->Links[0].mergeWith(Links[i]);
140     Links.clear();
141   } else {
142     DestNode->Links.resize(1);
143   }
144 }
145
146 /// isNodeCompletelyFolded - Return true if this node has been completely
147 /// folded down to something that can never be expanded, effectively losing
148 /// all of the field sensitivity that may be present in the node.
149 ///
150 bool DSNode::isNodeCompletelyFolded() const {
151   return getSize() == 1 && Ty == Type::VoidTy && isArray();
152 }
153
154
155 namespace {
156   /// TypeElementWalker Class - Used for implementation of physical subtyping...
157   ///
158   class TypeElementWalker {
159     struct StackState {
160       const Type *Ty;
161       unsigned Offset;
162       unsigned Idx;
163       StackState(const Type *T, unsigned Off = 0)
164         : Ty(T), Offset(Off), Idx(0) {}
165     };
166
167     std::vector<StackState> Stack;
168   public:
169     TypeElementWalker(const Type *T) {
170       Stack.push_back(T);
171       StepToLeaf();
172     }
173
174     bool isDone() const { return Stack.empty(); }
175     const Type *getCurrentType()   const { return Stack.back().Ty;     }
176     unsigned    getCurrentOffset() const { return Stack.back().Offset; }
177
178     void StepToNextType() {
179       PopStackAndAdvance();
180       StepToLeaf();
181     }
182
183   private:
184     /// PopStackAndAdvance - Pop the current element off of the stack and
185     /// advance the underlying element to the next contained member.
186     void PopStackAndAdvance() {
187       assert(!Stack.empty() && "Cannot pop an empty stack!");
188       Stack.pop_back();
189       while (!Stack.empty()) {
190         StackState &SS = Stack.back();
191         if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
192           ++SS.Idx;
193           if (SS.Idx != ST->getElementTypes().size()) {
194             const StructLayout *SL = TD.getStructLayout(ST);
195             SS.Offset += SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1];
196             return;
197           }
198           Stack.pop_back();  // At the end of the structure
199         } else {
200           const ArrayType *AT = cast<ArrayType>(SS.Ty);
201           ++SS.Idx;
202           if (SS.Idx != AT->getNumElements()) {
203             SS.Offset += TD.getTypeSize(AT->getElementType());
204             return;
205           }
206           Stack.pop_back();  // At the end of the array
207         }
208       }
209     }
210
211     /// StepToLeaf - Used by physical subtyping to move to the first leaf node
212     /// on the type stack.
213     void StepToLeaf() {
214       if (Stack.empty()) return;
215       while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
216         StackState &SS = Stack.back();
217         if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
218           if (ST->getElementTypes().empty()) {
219             assert(SS.Idx == 0);
220             PopStackAndAdvance();
221           } else {
222             // Step into the structure...
223             assert(SS.Idx < ST->getElementTypes().size());
224             const StructLayout *SL = TD.getStructLayout(ST);
225             Stack.push_back(StackState(ST->getElementTypes()[SS.Idx],
226                                        SS.Offset+SL->MemberOffsets[SS.Idx]));
227           }
228         } else {
229           const ArrayType *AT = cast<ArrayType>(SS.Ty);
230           if (AT->getNumElements() == 0) {
231             assert(SS.Idx == 0);
232             PopStackAndAdvance();
233           } else {
234             // Step into the array...
235             assert(SS.Idx < AT->getNumElements());
236             Stack.push_back(StackState(AT->getElementType(),
237                                        SS.Offset+SS.Idx*
238                                        TD.getTypeSize(AT->getElementType())));
239           }
240         }
241       }
242     }
243   };
244 }
245
246 /// ElementTypesAreCompatible - Check to see if the specified types are
247 /// "physically" compatible.  If so, return true, else return false.  We only
248 /// have to check the fields in T1: T2 may be larger than T1.
249 ///
250 static bool ElementTypesAreCompatible(const Type *T1, const Type *T2) {
251   TypeElementWalker T1W(T1), T2W(T2);
252   
253   while (!T1W.isDone() && !T2W.isDone()) {
254     if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
255       return false;
256
257     const Type *T1 = T1W.getCurrentType();
258     const Type *T2 = T2W.getCurrentType();
259     if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
260       return false;
261     
262     T1W.StepToNextType();
263     T2W.StepToNextType();
264   }
265   
266   return T1W.isDone();
267 }
268
269
270 /// mergeTypeInfo - This method merges the specified type into the current node
271 /// at the specified offset.  This may update the current node's type record if
272 /// this gives more information to the node, it may do nothing to the node if
273 /// this information is already known, or it may merge the node completely (and
274 /// return true) if the information is incompatible with what is already known.
275 ///
276 /// This method returns true if the node is completely folded, otherwise false.
277 ///
278 bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
279                            bool FoldIfIncompatible) {
280   // Check to make sure the Size member is up-to-date.  Size can be one of the
281   // following:
282   //  Size = 0, Ty = Void: Nothing is known about this node.
283   //  Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
284   //  Size = 1, Ty = Void, Array = 1: The node is collapsed
285   //  Otherwise, sizeof(Ty) = Size
286   //
287   assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
288           (Size == 0 && !Ty->isSized() && !isArray()) ||
289           (Size == 1 && Ty == Type::VoidTy && isArray()) ||
290           (Size == 0 && !Ty->isSized() && !isArray()) ||
291           (TD.getTypeSize(Ty) == Size)) &&
292          "Size member of DSNode doesn't match the type structure!");
293   assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
294
295   if (Offset == 0 && NewTy == Ty)
296     return false;  // This should be a common case, handle it efficiently
297
298   // Return true immediately if the node is completely folded.
299   if (isNodeCompletelyFolded()) return true;
300
301   // If this is an array type, eliminate the outside arrays because they won't
302   // be used anyway.  This greatly reduces the size of large static arrays used
303   // as global variables, for example.
304   //
305   bool WillBeArray = false;
306   while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
307     // FIXME: we might want to keep small arrays, but must be careful about
308     // things like: [2 x [10000 x int*]]
309     NewTy = AT->getElementType();
310     WillBeArray = true;
311   }
312
313   // Figure out how big the new type we're merging in is...
314   unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
315
316   // Otherwise check to see if we can fold this type into the current node.  If
317   // we can't, we fold the node completely, if we can, we potentially update our
318   // internal state.
319   //
320   if (Ty == Type::VoidTy) {
321     // If this is the first type that this node has seen, just accept it without
322     // question....
323     assert(Offset == 0 && "Cannot have an offset into a void node!");
324     assert(!isArray() && "This shouldn't happen!");
325     Ty = NewTy;
326     NodeType &= ~Array;
327     if (WillBeArray) NodeType |= Array;
328     Size = NewTySize;
329
330     // Calculate the number of outgoing links from this node.
331     Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
332     return false;
333   }
334
335   // Handle node expansion case here...
336   if (Offset+NewTySize > Size) {
337     // It is illegal to grow this node if we have treated it as an array of
338     // objects...
339     if (isArray()) {
340       if (FoldIfIncompatible) foldNodeCompletely();
341       return true;
342     }
343
344     if (Offset) {  // We could handle this case, but we don't for now...
345       std::cerr << "UNIMP: Trying to merge a growth type into "
346                 << "offset != 0: Collapsing!\n";
347       if (FoldIfIncompatible) foldNodeCompletely();
348       return true;
349     }
350
351     // Okay, the situation is nice and simple, we are trying to merge a type in
352     // at offset 0 that is bigger than our current type.  Implement this by
353     // switching to the new type and then merge in the smaller one, which should
354     // hit the other code path here.  If the other code path decides it's not
355     // ok, it will collapse the node as appropriate.
356     //
357     const Type *OldTy = Ty;
358     Ty = NewTy;
359     NodeType &= ~Array;
360     if (WillBeArray) NodeType |= Array;
361     Size = NewTySize;
362
363     // Must grow links to be the appropriate size...
364     Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
365
366     // Merge in the old type now... which is guaranteed to be smaller than the
367     // "current" type.
368     return mergeTypeInfo(OldTy, 0);
369   }
370
371   assert(Offset <= Size &&
372          "Cannot merge something into a part of our type that doesn't exist!");
373
374   // Find the section of Ty that NewTy overlaps with... first we find the
375   // type that starts at offset Offset.
376   //
377   unsigned O = 0;
378   const Type *SubType = Ty;
379   while (O < Offset) {
380     assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
381
382     switch (SubType->getPrimitiveID()) {
383     case Type::StructTyID: {
384       const StructType *STy = cast<StructType>(SubType);
385       const StructLayout &SL = *TD.getStructLayout(STy);
386
387       unsigned i = 0, e = SL.MemberOffsets.size();
388       for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
389         /* empty */;
390
391       // The offset we are looking for must be in the i'th element...
392       SubType = STy->getElementTypes()[i];
393       O += SL.MemberOffsets[i];
394       break;
395     }
396     case Type::ArrayTyID: {
397       SubType = cast<ArrayType>(SubType)->getElementType();
398       unsigned ElSize = TD.getTypeSize(SubType);
399       unsigned Remainder = (Offset-O) % ElSize;
400       O = Offset-Remainder;
401       break;
402     }
403     default:
404       if (FoldIfIncompatible) foldNodeCompletely();
405       return true;
406     }
407   }
408
409   assert(O == Offset && "Could not achieve the correct offset!");
410
411   // If we found our type exactly, early exit
412   if (SubType == NewTy) return false;
413
414   unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
415
416   // Ok, we are getting desperate now.  Check for physical subtyping, where we
417   // just require each element in the node to be compatible.
418   if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
419       SubTypeSize && SubTypeSize < 256 && 
420       ElementTypesAreCompatible(NewTy, SubType))
421     return false;
422
423   // Okay, so we found the leader type at the offset requested.  Search the list
424   // of types that starts at this offset.  If SubType is currently an array or
425   // structure, the type desired may actually be the first element of the
426   // composite type...
427   //
428   unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
429   while (SubType != NewTy) {
430     const Type *NextSubType = 0;
431     unsigned NextSubTypeSize = 0;
432     unsigned NextPadSize = 0;
433     switch (SubType->getPrimitiveID()) {
434     case Type::StructTyID: {
435       const StructType *STy = cast<StructType>(SubType);
436       const StructLayout &SL = *TD.getStructLayout(STy);
437       if (SL.MemberOffsets.size() > 1)
438         NextPadSize = SL.MemberOffsets[1];
439       else
440         NextPadSize = SubTypeSize;
441       NextSubType = STy->getElementTypes()[0];
442       NextSubTypeSize = TD.getTypeSize(NextSubType);
443       break;
444     }
445     case Type::ArrayTyID:
446       NextSubType = cast<ArrayType>(SubType)->getElementType();
447       NextSubTypeSize = TD.getTypeSize(NextSubType);
448       NextPadSize = NextSubTypeSize;
449       break;
450     default: ;
451       // fall out 
452     }
453
454     if (NextSubType == 0)
455       break;   // In the default case, break out of the loop
456
457     if (NextPadSize < NewTySize)
458       break;   // Don't allow shrinking to a smaller type than NewTySize
459     SubType = NextSubType;
460     SubTypeSize = NextSubTypeSize;
461     PadSize = NextPadSize;
462   }
463
464   // If we found the type exactly, return it...
465   if (SubType == NewTy)
466     return false;
467
468   // Check to see if we have a compatible, but different type...
469   if (NewTySize == SubTypeSize) {
470     // Check to see if this type is obviously convertible... int -> uint f.e.
471     if (NewTy->isLosslesslyConvertibleTo(SubType))
472       return false;
473
474     // Check to see if we have a pointer & integer mismatch going on here,
475     // loading a pointer as a long, for example.
476     //
477     if (SubType->isInteger() && isa<PointerType>(NewTy) ||
478         NewTy->isInteger() && isa<PointerType>(SubType))
479       return false;
480   } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
481     // We are accessing the field, plus some structure padding.  Ignore the
482     // structure padding.
483     return false;
484   }
485
486   Module *M = 0;
487   if (getParentGraph()->getReturnNodes().size())
488     M = getParentGraph()->getReturnNodes().begin()->first->getParent();
489   DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
490         WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
491         WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
492                   << "SubType: ";
493         WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
494
495   if (FoldIfIncompatible) foldNodeCompletely();
496   return true;
497 }
498
499
500
501 // addEdgeTo - Add an edge from the current node to the specified node.  This
502 // can cause merging of nodes in the graph.
503 //
504 void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
505   if (NH.getNode() == 0) return;       // Nothing to do
506
507   DSNodeHandle &ExistingEdge = getLink(Offset);
508   if (ExistingEdge.getNode()) {
509     // Merge the two nodes...
510     ExistingEdge.mergeWith(NH);
511   } else {                             // No merging to perform...
512     setLink(Offset, NH);               // Just force a link in there...
513   }
514 }
515
516
517 // MergeSortedVectors - Efficiently merge a vector into another vector where
518 // duplicates are not allowed and both are sorted.  This assumes that 'T's are
519 // efficiently copyable and have sane comparison semantics.
520 //
521 static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
522                                const std::vector<GlobalValue*> &Src) {
523   // By far, the most common cases will be the simple ones.  In these cases,
524   // avoid having to allocate a temporary vector...
525   //
526   if (Src.empty()) {             // Nothing to merge in...
527     return;
528   } else if (Dest.empty()) {     // Just copy the result in...
529     Dest = Src;
530   } else if (Src.size() == 1) {  // Insert a single element...
531     const GlobalValue *V = Src[0];
532     std::vector<GlobalValue*>::iterator I =
533       std::lower_bound(Dest.begin(), Dest.end(), V);
534     if (I == Dest.end() || *I != Src[0])  // If not already contained...
535       Dest.insert(I, Src[0]);
536   } else if (Dest.size() == 1) {
537     GlobalValue *Tmp = Dest[0];           // Save value in temporary...
538     Dest = Src;                           // Copy over list...
539     std::vector<GlobalValue*>::iterator I =
540       std::lower_bound(Dest.begin(), Dest.end(), Tmp);
541     if (I == Dest.end() || *I != Tmp)     // If not already contained...
542       Dest.insert(I, Tmp);
543
544   } else {
545     // Make a copy to the side of Dest...
546     std::vector<GlobalValue*> Old(Dest);
547     
548     // Make space for all of the type entries now...
549     Dest.resize(Dest.size()+Src.size());
550     
551     // Merge the two sorted ranges together... into Dest.
552     std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
553     
554     // Now erase any duplicate entries that may have accumulated into the 
555     // vectors (because they were in both of the input sets)
556     Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
557   }
558 }
559
560
561 // MergeNodes() - Helper function for DSNode::mergeWith().
562 // This function does the hard work of merging two nodes, CurNodeH
563 // and NH after filtering out trivial cases and making sure that
564 // CurNodeH.offset >= NH.offset.
565 // 
566 // ***WARNING***
567 // Since merging may cause either node to go away, we must always
568 // use the node-handles to refer to the nodes.  These node handles are
569 // automatically updated during merging, so will always provide access
570 // to the correct node after a merge.
571 //
572 void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
573   assert(CurNodeH.getOffset() >= NH.getOffset() &&
574          "This should have been enforced in the caller.");
575
576   // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
577   // respect to NH.Offset) is now zero.  NOffset is the distance from the base
578   // of our object that N starts from.
579   //
580   unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
581   unsigned NSize = NH.getNode()->getSize();
582
583   // If the two nodes are of different size, and the smaller node has the array
584   // bit set, collapse!
585   if (NSize != CurNodeH.getNode()->getSize()) {
586     if (NSize < CurNodeH.getNode()->getSize()) {
587       if (NH.getNode()->isArray())
588         NH.getNode()->foldNodeCompletely();
589     } else if (CurNodeH.getNode()->isArray()) {
590       NH.getNode()->foldNodeCompletely();
591     }
592   }
593
594   // Merge the type entries of the two nodes together...    
595   if (NH.getNode()->Ty != Type::VoidTy)
596     CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
597   assert(!CurNodeH.getNode()->isDeadNode());
598
599   // If we are merging a node with a completely folded node, then both nodes are
600   // now completely folded.
601   //
602   if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
603     if (!NH.getNode()->isNodeCompletelyFolded()) {
604       NH.getNode()->foldNodeCompletely();
605       assert(NH.getNode() && NH.getOffset() == 0 &&
606              "folding did not make offset 0?");
607       NOffset = NH.getOffset();
608       NSize = NH.getNode()->getSize();
609       assert(NOffset == 0 && NSize == 1);
610     }
611   } else if (NH.getNode()->isNodeCompletelyFolded()) {
612     CurNodeH.getNode()->foldNodeCompletely();
613     assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
614            "folding did not make offset 0?");
615     NOffset = NH.getOffset();
616     NSize = NH.getNode()->getSize();
617     assert(NOffset == 0 && NSize == 1);
618   }
619
620   DSNode *N = NH.getNode();
621   if (CurNodeH.getNode() == N || N == 0) return;
622   assert(!CurNodeH.getNode()->isDeadNode());
623
624   // Merge the NodeType information...
625   CurNodeH.getNode()->NodeType |= N->NodeType;
626
627   // Start forwarding to the new node!
628   N->forwardNode(CurNodeH.getNode(), NOffset);
629   assert(!CurNodeH.getNode()->isDeadNode());
630
631   // Make all of the outgoing links of N now be outgoing links of CurNodeH.
632   //
633   for (unsigned i = 0; i < N->getNumLinks(); ++i) {
634     DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
635     if (Link.getNode()) {
636       // Compute the offset into the current node at which to
637       // merge this link.  In the common case, this is a linear
638       // relation to the offset in the original node (with
639       // wrapping), but if the current node gets collapsed due to
640       // recursive merging, we must make sure to merge in all remaining
641       // links at offset zero.
642       unsigned MergeOffset = 0;
643       DSNode *CN = CurNodeH.getNode();
644       if (CN->Size != 1)
645         MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
646       CN->addEdgeTo(MergeOffset, Link);
647     }
648   }
649
650   // Now that there are no outgoing edges, all of the Links are dead.
651   N->Links.clear();
652
653   // Merge the globals list...
654   if (!N->Globals.empty()) {
655     MergeSortedVectors(CurNodeH.getNode()->Globals, N->Globals);
656
657     // Delete the globals from the old node...
658     std::vector<GlobalValue*>().swap(N->Globals);
659   }
660 }
661
662
663 // mergeWith - Merge this node and the specified node, moving all links to and
664 // from the argument node into the current node, deleting the node argument.
665 // Offset indicates what offset the specified node is to be merged into the
666 // current node.
667 //
668 // The specified node may be a null pointer (in which case, nothing happens).
669 //
670 void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
671   DSNode *N = NH.getNode();
672   if (N == 0 || (N == this && NH.getOffset() == Offset))
673     return;  // Noop
674
675   assert(!N->isDeadNode() && !isDeadNode());
676   assert(!hasNoReferrers() && "Should not try to fold a useless node!");
677
678   if (N == this) {
679     // We cannot merge two pieces of the same node together, collapse the node
680     // completely.
681     DEBUG(std::cerr << "Attempting to merge two chunks of"
682                     << " the same node together!\n");
683     foldNodeCompletely();
684     return;
685   }
686
687   // If both nodes are not at offset 0, make sure that we are merging the node
688   // at an later offset into the node with the zero offset.
689   //
690   if (Offset < NH.getOffset()) {
691     N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
692     return;
693   } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
694     // If the offsets are the same, merge the smaller node into the bigger node
695     N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
696     return;
697   }
698
699   // Ok, now we can merge the two nodes.  Use a static helper that works with
700   // two node handles, since "this" may get merged away at intermediate steps.
701   DSNodeHandle CurNodeH(this, Offset);
702   DSNodeHandle NHCopy(NH);
703   DSNode::MergeNodes(CurNodeH, NHCopy);
704 }
705
706 //===----------------------------------------------------------------------===//
707 // DSCallSite Implementation
708 //===----------------------------------------------------------------------===//
709
710 // Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
711 Function &DSCallSite::getCaller() const {
712   return *Site.getInstruction()->getParent()->getParent();
713 }
714
715
716 //===----------------------------------------------------------------------===//
717 // DSGraph Implementation
718 //===----------------------------------------------------------------------===//
719
720 /// getFunctionNames - Return a space separated list of the name of the
721 /// functions in this graph (if any)
722 std::string DSGraph::getFunctionNames() const {
723   switch (getReturnNodes().size()) {
724   case 0: return "Globals graph";
725   case 1: return getReturnNodes().begin()->first->getName();
726   default:
727     std::string Return;
728     for (DSGraph::ReturnNodesTy::const_iterator I = getReturnNodes().begin();
729          I != getReturnNodes().end(); ++I)
730       Return += I->first->getName() + " ";
731     Return.erase(Return.end()-1, Return.end());   // Remove last space character
732     return Return;
733   }
734 }
735
736
737 DSGraph::DSGraph(const DSGraph &G) : GlobalsGraph(0) {
738   PrintAuxCalls = false;
739   NodeMapTy NodeMap;
740   cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
741   InlinedGlobals.clear();               // clear set of "up-to-date" globals
742 }
743
744 DSGraph::DSGraph(const DSGraph &G, NodeMapTy &NodeMap)
745   : GlobalsGraph(0) {
746   PrintAuxCalls = false;
747   cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
748   InlinedGlobals.clear();               // clear set of "up-to-date" globals
749 }
750
751 DSGraph::~DSGraph() {
752   FunctionCalls.clear();
753   AuxFunctionCalls.clear();
754   InlinedGlobals.clear();
755   ScalarMap.clear();
756   ReturnNodes.clear();
757
758   // Drop all intra-node references, so that assertions don't fail...
759   std::for_each(Nodes.begin(), Nodes.end(),
760                 std::mem_fun(&DSNode::dropAllReferences));
761
762   // Delete all of the nodes themselves...
763   std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
764 }
765
766 // dump - Allow inspection of graph in a debugger.
767 void DSGraph::dump() const { print(std::cerr); }
768
769
770 /// remapLinks - Change all of the Links in the current node according to the
771 /// specified mapping.
772 ///
773 void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
774   for (unsigned i = 0, e = Links.size(); i != e; ++i) {
775     DSNodeHandle &H = OldNodeMap[Links[i].getNode()];
776     Links[i].setNode(H.getNode());
777     Links[i].setOffset(Links[i].getOffset()+H.getOffset());
778   }
779 }
780
781
782 /// cloneReachableNodes - Clone all reachable nodes from *Node into the
783 /// current graph.  This is a recursive function.  The map OldNodeMap is a
784 /// map from the original nodes to their clones.
785 /// 
786 void DSGraph::cloneReachableNodes(const DSNode*  Node,
787                                   unsigned BitsToClear,
788                                   NodeMapTy& OldNodeMap,
789                                   NodeMapTy& CompletedNodeMap) {
790   if (CompletedNodeMap.find(Node) != CompletedNodeMap.end())
791     return;
792
793   DSNodeHandle& NH = OldNodeMap[Node];
794   if (NH.getNode() != NULL)
795     return;
796
797   // else Node has not yet been cloned: clone it and clear the specified bits
798   NH = new DSNode(*Node, this);          // enters in OldNodeMap
799   NH.getNode()->maskNodeTypes(~BitsToClear);
800
801   // now recursively clone nodes pointed to by this node
802   for (unsigned i = 0, e = Node->getNumLinks(); i != e; ++i) {
803     const DSNodeHandle &Link = Node->getLink(i << DS::PointerShift);
804     if (const DSNode* nextNode = Link.getNode())
805       cloneReachableNodes(nextNode, BitsToClear, OldNodeMap, CompletedNodeMap);
806   }
807 }
808
809 void DSGraph::cloneReachableSubgraph(const DSGraph& G,
810                                      const hash_set<const DSNode*>& RootNodes,
811                                      NodeMapTy& OldNodeMap,
812                                      NodeMapTy& CompletedNodeMap,
813                                      unsigned CloneFlags) {
814   if (RootNodes.empty())
815     return;
816
817   assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
818   assert(&G != this && "Cannot clone graph into itself!");
819   assert((*RootNodes.begin())->getParentGraph() == &G &&
820          "Root nodes do not belong to this graph!");
821
822   // Remove alloca or mod/ref bits as specified...
823   unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
824     | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
825     | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
826   BitsToClear |= DSNode::DEAD;  // Clear dead flag...
827
828   // Clone all nodes reachable from each root node, using a recursive helper
829   for (hash_set<const DSNode*>::const_iterator I = RootNodes.begin(),
830          E = RootNodes.end(); I != E; ++I)
831     cloneReachableNodes(*I, BitsToClear, OldNodeMap, CompletedNodeMap);
832
833   // Merge the map entries in OldNodeMap and CompletedNodeMap to remap links
834   NodeMapTy MergedMap(OldNodeMap);
835   MergedMap.insert(CompletedNodeMap.begin(), CompletedNodeMap.end());
836
837   // Rewrite the links in the newly created nodes (the nodes in OldNodeMap)
838   // to point into the current graph.  MergedMap gives the full mapping.
839   for (NodeMapTy::iterator I=OldNodeMap.begin(), E=OldNodeMap.end(); I!= E; ++I)
840     I->second.getNode()->remapLinks(MergedMap);
841
842   // Now merge cloned global nodes with their copies in the current graph
843   // Just look through OldNodeMap to find such nodes!
844   for (NodeMapTy::iterator I=OldNodeMap.begin(), E=OldNodeMap.end(); I!= E; ++I)
845     if (I->first->isGlobalNode()) {
846       DSNodeHandle &GClone = I->second;
847       assert(GClone.getNode() != NULL && "NULL node in OldNodeMap?");
848       const std::vector<GlobalValue*> &Globals = I->first->getGlobals();
849       for (unsigned gi = 0, ge = Globals.size(); gi != ge; ++gi) {
850         DSNodeHandle &GH = ScalarMap[Globals[gi]];
851         GH.mergeWith(GClone);
852       }
853     }
854 }
855
856
857 /// updateFromGlobalGraph - This function rematerializes global nodes and
858 /// nodes reachable from them from the globals graph into the current graph.
859 /// It invokes cloneReachableSubgraph, using the globals in the current graph
860 /// as the roots.  It also uses the vector InlinedGlobals to avoid cloning and
861 /// merging globals that are already up-to-date in the current graph.  In
862 /// practice, in the TD pass, this is likely to be a large fraction of the
863 /// live global nodes in each function (since most live nodes are likely to
864 /// have been brought up-to-date in at _some_ caller or callee).
865 /// 
866 void DSGraph::updateFromGlobalGraph() {
867
868   // Use a map to keep track of the mapping between nodes in the globals graph
869   // and this graph for up-to-date global nodes, which do not need to be cloned.
870   NodeMapTy CompletedMap;
871
872   // Put the live, non-up-to-date global nodes into a set and the up-to-date
873   // ones in the map above, mapping node in GlobalsGraph to the up-to-date node.
874   hash_set<const DSNode*> GlobalNodeSet;
875   for (ScalarMapTy::const_iterator I = getScalarMap().begin(),
876          E = getScalarMap().end(); I != E; ++I)
877     if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
878       DSNode* GNode = I->second.getNode();
879       assert(GNode && "No node for live global in current Graph?");
880       if (const DSNode* GGNode = GlobalsGraph->ScalarMap[GV].getNode())
881         if (InlinedGlobals.count(GV) == 0) // GNode is not up-to-date
882           GlobalNodeSet.insert(GGNode);
883         else {                                       // GNode is up-to-date 
884           CompletedMap[GGNode] = I->second;
885           assert(GGNode->getNumLinks() == GNode->getNumLinks() &&
886                  "Links dont match in a node that is supposed to be up-to-date?"
887                  "\nremapLinks() will not work if the links don't match!");
888         }
889     }
890
891   // Clone the subgraph reachable from the vector of nodes in GlobalNodes
892   // and merge the cloned global nodes with the corresponding ones, if any.
893   NodeMapTy OldNodeMap;
894   cloneReachableSubgraph(*GlobalsGraph, GlobalNodeSet, OldNodeMap,CompletedMap);
895
896   // Merging global nodes leaves behind unused nodes: get rid of them now.
897   OldNodeMap.clear();      // remove references before dead node cleanup 
898   CompletedMap.clear();    // remove references before dead node cleanup 
899   removeTriviallyDeadNodes();
900 }
901
902 /// cloneInto - Clone the specified DSGraph into the current graph.  The
903 /// translated ScalarMap for the old function is filled into the OldValMap
904 /// member, and the translated ReturnNodes map is returned into ReturnNodes.
905 ///
906 /// The CloneFlags member controls various aspects of the cloning process.
907 ///
908 void DSGraph::cloneInto(const DSGraph &G, ScalarMapTy &OldValMap,
909                         ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
910                         unsigned CloneFlags) {
911   assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
912   assert(&G != this && "Cannot clone graph into itself!");
913
914   unsigned FN = Nodes.size();           // First new node...
915
916   // Duplicate all of the nodes, populating the node map...
917   Nodes.reserve(FN+G.Nodes.size());
918
919   // Remove alloca or mod/ref bits as specified...
920   unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
921     | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
922     | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
923   BitsToClear |= DSNode::DEAD;  // Clear dead flag...
924   for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
925     DSNode *Old = G.Nodes[i];
926     DSNode *New = new DSNode(*Old, this);
927     New->maskNodeTypes(~BitsToClear);
928     OldNodeMap[Old] = New;
929   }
930
931 #ifndef NDEBUG
932   Timer::addPeakMemoryMeasurement();
933 #endif
934
935   // Rewrite the links in the new nodes to point into the current graph now.
936   for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
937     Nodes[i]->remapLinks(OldNodeMap);
938
939   // Copy the scalar map... merging all of the global nodes...
940   for (ScalarMapTy::const_iterator I = G.ScalarMap.begin(),
941          E = G.ScalarMap.end(); I != E; ++I) {
942     DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
943     DSNodeHandle &H = OldValMap[I->first];
944     H.mergeWith(DSNodeHandle(MappedNode.getNode(),
945                              I->second.getOffset()+MappedNode.getOffset()));
946
947     // If this is a global, add the global to this fn or merge if already exists
948     if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
949       ScalarMap[GV].mergeWith(H);
950       InlinedGlobals.insert(GV);
951     }
952   }
953
954   if (!(CloneFlags & DontCloneCallNodes)) {
955     // Copy the function calls list...
956     unsigned FC = FunctionCalls.size();  // FirstCall
957     FunctionCalls.reserve(FC+G.FunctionCalls.size());
958     for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
959       FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
960   }
961
962   if (!(CloneFlags & DontCloneAuxCallNodes)) {
963     // Copy the auxiliary function calls list...
964     unsigned FC = AuxFunctionCalls.size();  // FirstCall
965     AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
966     for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
967       AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
968   }
969
970   // Map the return node pointers over...
971   for (ReturnNodesTy::const_iterator I = G.getReturnNodes().begin(),
972          E = G.getReturnNodes().end(); I != E; ++I) {
973     const DSNodeHandle &Ret = I->second;
974     DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
975     OldReturnNodes.insert(std::make_pair(I->first,
976                           DSNodeHandle(MappedRet.getNode(),
977                                        MappedRet.getOffset()+Ret.getOffset())));
978   }
979 }
980
981 /// mergeInGraph - The method is used for merging graphs together.  If the
982 /// argument graph is not *this, it makes a clone of the specified graph, then
983 /// merges the nodes specified in the call site with the formal arguments in the
984 /// graph.
985 ///
986 void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
987                            const DSGraph &Graph, unsigned CloneFlags) {
988   ScalarMapTy OldValMap, *ScalarMap;
989   DSNodeHandle RetVal;
990
991   // If this is not a recursive call, clone the graph into this graph...
992   if (&Graph != this) {
993     // Clone the callee's graph into the current graph, keeping
994     // track of where scalars in the old graph _used_ to point,
995     // and of the new nodes matching nodes of the old graph.
996     NodeMapTy OldNodeMap;
997     
998     // The clone call may invalidate any of the vectors in the data
999     // structure graph.  Strip locals and don't copy the list of callers
1000     ReturnNodesTy OldRetNodes;
1001     cloneInto(Graph, OldValMap, OldRetNodes, OldNodeMap, CloneFlags);
1002
1003     // We need to map the arguments for the function to the cloned nodes old
1004     // argument values.  Do this now.
1005     RetVal = OldRetNodes[&F];
1006     ScalarMap = &OldValMap;
1007   } else {
1008     RetVal = getReturnNodeFor(F);
1009     ScalarMap = &getScalarMap();
1010   }
1011
1012   // Merge the return value with the return value of the context...
1013   RetVal.mergeWith(CS.getRetVal());
1014
1015   // Resolve all of the function arguments...
1016   Function::aiterator AI = F.abegin();
1017
1018   for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1019     // Advance the argument iterator to the first pointer argument...
1020     while (AI != F.aend() && !isPointerType(AI->getType())) {
1021       ++AI;
1022 #ifndef NDEBUG
1023       if (AI == F.aend())
1024         std::cerr << "Bad call to Function: " << F.getName() << "\n";
1025 #endif
1026     }
1027     if (AI == F.aend()) break;
1028     
1029     // Add the link from the argument scalar to the provided value
1030     assert(ScalarMap->count(AI) && "Argument not in scalar map?");
1031     DSNodeHandle &NH = (*ScalarMap)[AI];
1032     assert(NH.getNode() && "Pointer argument without scalarmap entry?");
1033     NH.mergeWith(CS.getPtrArg(i));
1034   }
1035 }
1036
1037 /// getCallSiteForArguments - Get the arguments and return value bindings for
1038 /// the specified function in the current graph.
1039 ///
1040 DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1041   std::vector<DSNodeHandle> Args;
1042
1043   for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1044     if (isPointerType(I->getType()))
1045       Args.push_back(getScalarMap().find(I)->second);
1046
1047   return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
1048 }
1049
1050
1051
1052 // markIncompleteNodes - Mark the specified node as having contents that are not
1053 // known with the current analysis we have performed.  Because a node makes all
1054 // of the nodes it can reach incomplete if the node itself is incomplete, we
1055 // must recursively traverse the data structure graph, marking all reachable
1056 // nodes as incomplete.
1057 //
1058 static void markIncompleteNode(DSNode *N) {
1059   // Stop recursion if no node, or if node already marked...
1060   if (N == 0 || N->isIncomplete()) return;
1061
1062   // Actually mark the node
1063   N->setIncompleteMarker();
1064
1065   // Recursively process children...
1066   for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1067     if (DSNode *DSN = N->getLink(i).getNode())
1068       markIncompleteNode(DSN);
1069 }
1070
1071 static void markIncomplete(DSCallSite &Call) {
1072   // Then the return value is certainly incomplete!
1073   markIncompleteNode(Call.getRetVal().getNode());
1074
1075   // All objects pointed to by function arguments are incomplete!
1076   for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1077     markIncompleteNode(Call.getPtrArg(i).getNode());
1078 }
1079
1080 // markIncompleteNodes - Traverse the graph, identifying nodes that may be
1081 // modified by other functions that have not been resolved yet.  This marks
1082 // nodes that are reachable through three sources of "unknownness":
1083 //
1084 //  Global Variables, Function Calls, and Incoming Arguments
1085 //
1086 // For any node that may have unknown components (because something outside the
1087 // scope of current analysis may have modified it), the 'Incomplete' flag is
1088 // added to the NodeType.
1089 //
1090 void DSGraph::markIncompleteNodes(unsigned Flags) {
1091   // Mark any incoming arguments as incomplete...
1092   if (Flags & DSGraph::MarkFormalArgs)
1093     for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1094          FI != E; ++FI) {
1095       Function &F = *FI->first;
1096       if (F.getName() != "main")
1097         for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1098           if (isPointerType(I->getType()) &&
1099               ScalarMap.find(I) != ScalarMap.end())
1100             markIncompleteNode(ScalarMap[I].getNode());
1101     }
1102
1103   // Mark stuff passed into functions calls as being incomplete...
1104   if (!shouldPrintAuxCalls())
1105     for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1106       markIncomplete(FunctionCalls[i]);
1107   else
1108     for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1109       markIncomplete(AuxFunctionCalls[i]);
1110     
1111
1112   // Mark all global nodes as incomplete...
1113   if ((Flags & DSGraph::IgnoreGlobals) == 0)
1114     for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1115       if (Nodes[i]->isGlobalNode() && Nodes[i]->getNumLinks())
1116         markIncompleteNode(Nodes[i]);
1117 }
1118
1119 static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1120   if (DSNode *N = Edge.getNode())  // Is there an edge?
1121     if (N->getNumReferrers() == 1)  // Does it point to a lonely node?
1122       // No interesting info?
1123       if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
1124           N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
1125         Edge.setNode(0);  // Kill the edge!
1126 }
1127
1128 static inline bool nodeContainsExternalFunction(const DSNode *N) {
1129   const std::vector<GlobalValue*> &Globals = N->getGlobals();
1130   for (unsigned i = 0, e = Globals.size(); i != e; ++i)
1131     if (Globals[i]->isExternal())
1132       return true;
1133   return false;
1134 }
1135
1136 static void removeIdenticalCalls(std::vector<DSCallSite> &Calls) {
1137
1138   // Remove trivially identical function calls
1139   unsigned NumFns = Calls.size();
1140   std::sort(Calls.begin(), Calls.end());  // Sort by callee as primary key!
1141
1142   // Scan the call list cleaning it up as necessary...
1143   DSNode   *LastCalleeNode = 0;
1144   Function *LastCalleeFunc = 0;
1145   unsigned NumDuplicateCalls = 0;
1146   bool LastCalleeContainsExternalFunction = false;
1147   for (unsigned i = 0; i != Calls.size(); ++i) {
1148     DSCallSite &CS = Calls[i];
1149
1150     // If the Callee is a useless edge, this must be an unreachable call site,
1151     // eliminate it.
1152     if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
1153         CS.getCalleeNode()->getNodeFlags() == 0) {  // No useful info?
1154       std::cerr << "WARNING: Useless call site found??\n";
1155       CS.swap(Calls.back());
1156       Calls.pop_back();
1157       --i;
1158     } else {
1159       // If the return value or any arguments point to a void node with no
1160       // information at all in it, and the call node is the only node to point
1161       // to it, remove the edge to the node (killing the node).
1162       //
1163       killIfUselessEdge(CS.getRetVal());
1164       for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1165         killIfUselessEdge(CS.getPtrArg(a));
1166       
1167       // If this call site calls the same function as the last call site, and if
1168       // the function pointer contains an external function, this node will
1169       // never be resolved.  Merge the arguments of the call node because no
1170       // information will be lost.
1171       //
1172       if ((CS.isDirectCall()   && CS.getCalleeFunc() == LastCalleeFunc) ||
1173           (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
1174         ++NumDuplicateCalls;
1175         if (NumDuplicateCalls == 1) {
1176           if (LastCalleeNode)
1177             LastCalleeContainsExternalFunction =
1178               nodeContainsExternalFunction(LastCalleeNode);
1179           else
1180             LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
1181         }
1182         
1183 #if 1
1184         if (LastCalleeContainsExternalFunction ||
1185             // This should be more than enough context sensitivity!
1186             // FIXME: Evaluate how many times this is tripped!
1187             NumDuplicateCalls > 20) {
1188           DSCallSite &OCS = Calls[i-1];
1189           OCS.mergeWith(CS);
1190           
1191           // The node will now be eliminated as a duplicate!
1192           if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
1193             CS = OCS;
1194           else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
1195             OCS = CS;
1196         }
1197 #endif
1198       } else {
1199         if (CS.isDirectCall()) {
1200           LastCalleeFunc = CS.getCalleeFunc();
1201           LastCalleeNode = 0;
1202         } else {
1203           LastCalleeNode = CS.getCalleeNode();
1204           LastCalleeFunc = 0;
1205         }
1206         NumDuplicateCalls = 0;
1207       }
1208     }
1209   }
1210
1211   Calls.erase(std::unique(Calls.begin(), Calls.end()),
1212               Calls.end());
1213
1214   // Track the number of call nodes merged away...
1215   NumCallNodesMerged += NumFns-Calls.size();
1216
1217   DEBUG(if (NumFns != Calls.size())
1218           std::cerr << "Merged " << (NumFns-Calls.size()) << " call nodes.\n";);
1219 }
1220
1221
1222 // removeTriviallyDeadNodes - After the graph has been constructed, this method
1223 // removes all unreachable nodes that are created because they got merged with
1224 // other nodes in the graph.  These nodes will all be trivially unreachable, so
1225 // we don't have to perform any non-trivial analysis here.
1226 //
1227 void DSGraph::removeTriviallyDeadNodes() {
1228   removeIdenticalCalls(FunctionCalls);
1229   removeIdenticalCalls(AuxFunctionCalls);
1230
1231   // Loop over all of the nodes in the graph, calling getNode on each field.
1232   // This will cause all nodes to update their forwarding edges, causing
1233   // forwarded nodes to be delete-able.
1234   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1235     DSNode *N = Nodes[i];
1236     for (unsigned l = 0, e = N->getNumLinks(); l != e; ++l)
1237       N->getLink(l*N->getPointerSize()).getNode();
1238   }
1239
1240   // Likewise, forward any edges from the scalar nodes...
1241   for (ScalarMapTy::iterator I = ScalarMap.begin(), E = ScalarMap.end();
1242        I != E; ++I)
1243     I->second.getNode();
1244
1245   bool isGlobalsGraph = !GlobalsGraph;
1246
1247   for (unsigned i = 0; i != Nodes.size(); ++i) {
1248     DSNode *Node = Nodes[i];
1249
1250     // Do not remove *any* global nodes in the globals graph.
1251     // This is a special case because such nodes may not have I, M, R flags set.
1252     if (Node->isGlobalNode() && isGlobalsGraph)
1253       continue;
1254
1255     if (Node->isComplete() && !Node->isModified() && !Node->isRead()) {
1256       // This is a useless node if it has no mod/ref info (checked above),
1257       // outgoing edges (which it cannot, as it is not modified in this
1258       // context), and it has no incoming edges.  If it is a global node it may
1259       // have all of these properties and still have incoming edges, due to the
1260       // scalar map, so we check those now.
1261       //
1262       if (Node->getNumReferrers() == Node->getGlobals().size()) {
1263         const std::vector<GlobalValue*> &Globals = Node->getGlobals();
1264
1265         // Loop through and make sure all of the globals are referring directly
1266         // to the node...
1267         for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1268           DSNode *N = ScalarMap.find(Globals[j])->second.getNode();
1269           assert(N == Node && "ScalarMap doesn't match globals list!");
1270         }
1271
1272         // Make sure NumReferrers still agrees, if so, the node is truly dead.
1273         if (Node->getNumReferrers() == Globals.size()) {
1274           for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1275             ScalarMap.erase(Globals[j]);
1276           Node->makeNodeDead();
1277         }
1278       }
1279
1280 #ifdef SANER_CODE_FOR_CHECKING_IF_ALL_REFERRERS_ARE_FROM_SCALARMAP
1281       //
1282       // *** It seems to me that we should be able to simply check if 
1283       // *** there are fewer or equal #referrers as #globals and make
1284       // *** sure that all those referrers are in the scalar map?
1285       // 
1286       if (Node->getNumReferrers() <= Node->getGlobals().size()) {
1287         const std::vector<GlobalValue*> &Globals = Node->getGlobals();
1288
1289 #ifndef NDEBUG
1290         // Loop through and make sure all of the globals are referring directly
1291         // to the node...
1292         for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1293           DSNode *N = ScalarMap.find(Globals[j])->second.getNode();
1294           assert(N == Node && "ScalarMap doesn't match globals list!");
1295         }
1296 #endif
1297
1298         // Make sure NumReferrers still agrees.  The node is truly dead.
1299         assert(Node->getNumReferrers() == Globals.size());
1300         for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1301           ScalarMap.erase(Globals[j]);
1302         Node->makeNodeDead();
1303       }
1304 #endif
1305     }
1306
1307     if (Node->getNodeFlags() == 0 && Node->hasNoReferrers()) {
1308       // This node is dead!
1309       delete Node;                        // Free memory...
1310       Nodes[i--] = Nodes.back();
1311       Nodes.pop_back();                   // Remove from node list...
1312     }
1313   }
1314 }
1315
1316
1317 /// markReachableNodes - This method recursively traverses the specified
1318 /// DSNodes, marking any nodes which are reachable.  All reachable nodes it adds
1319 /// to the set, which allows it to only traverse visited nodes once.
1320 ///
1321 void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
1322   if (this == 0) return;
1323   assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
1324   if (ReachableNodes.count(this)) return;          // Already marked reachable
1325   ReachableNodes.insert(this);                     // Is reachable now
1326
1327   for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
1328     getLink(i).getNode()->markReachableNodes(ReachableNodes);
1329 }
1330
1331 void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
1332   getRetVal().getNode()->markReachableNodes(Nodes);
1333   if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
1334   
1335   for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1336     getPtrArg(i).getNode()->markReachableNodes(Nodes);
1337 }
1338
1339 // CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1340 // looking for a node that is marked alive.  If an alive node is found, return
1341 // true, otherwise return false.  If an alive node is reachable, this node is
1342 // marked as alive...
1343 //
1344 static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
1345                                hash_set<DSNode*> &Visited,
1346                                bool IgnoreGlobals) {
1347   if (N == 0) return false;
1348   assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
1349
1350   // If this is a global node, it will end up in the globals graph anyway, so we
1351   // don't need to worry about it.
1352   if (IgnoreGlobals && N->isGlobalNode()) return false;
1353
1354   // If we know that this node is alive, return so!
1355   if (Alive.count(N)) return true;
1356
1357   // Otherwise, we don't think the node is alive yet, check for infinite
1358   // recursion.
1359   if (Visited.count(N)) return false;  // Found a cycle
1360   Visited.insert(N);   // No recursion, insert into Visited...
1361
1362   for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1363     if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited,
1364                            IgnoreGlobals)) {
1365       N->markReachableNodes(Alive);
1366       return true;
1367     }
1368   return false;
1369 }
1370
1371 // CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1372 // alive nodes.
1373 //
1374 static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
1375                                   hash_set<DSNode*> &Visited,
1376                                   bool IgnoreGlobals) {
1377   if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
1378                          IgnoreGlobals))
1379     return true;
1380   if (CS.isIndirectCall() &&
1381       CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
1382     return true;
1383   for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1384     if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
1385                            IgnoreGlobals))
1386       return true;
1387   return false;
1388 }
1389
1390 // removeDeadNodes - Use a more powerful reachability analysis to eliminate
1391 // subgraphs that are unreachable.  This often occurs because the data
1392 // structure doesn't "escape" into it's caller, and thus should be eliminated
1393 // from the caller's graph entirely.  This is only appropriate to use when
1394 // inlining graphs.
1395 //
1396 void DSGraph::removeDeadNodes(unsigned Flags) {
1397   DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
1398
1399   // Reduce the amount of work we have to do... remove dummy nodes left over by
1400   // merging...
1401   removeTriviallyDeadNodes();
1402
1403   // FIXME: Merge non-trivially identical call nodes...
1404
1405   // Alive - a set that holds all nodes found to be reachable/alive.
1406   hash_set<DSNode*> Alive;
1407   std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
1408
1409   // Mark all nodes reachable by (non-global) scalar nodes as alive...
1410   for (ScalarMapTy::iterator I = ScalarMap.begin(), E = ScalarMap.end(); I !=E;)
1411     if (isa<GlobalValue>(I->first)) {             // Keep track of global nodes
1412       assert(I->second.getNode() && "Null global node?");
1413       assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
1414       GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
1415       ++I;
1416     } else {
1417       // Check to see if this is a worthless node generated for non-pointer
1418       // values, such as integers.  Consider an addition of long types: A+B.
1419       // Assuming we can track all uses of the value in this context, and it is
1420       // NOT used as a pointer, we can delete the node.  We will be able to
1421       // detect this situation if the node pointed to ONLY has Unknown bit set
1422       // in the node.  In this case, the node is not incomplete, does not point
1423       // to any other nodes (no mod/ref bits set), and is therefore
1424       // uninteresting for data structure analysis.  If we run across one of
1425       // these, prune the scalar pointing to it.
1426       //
1427       DSNode *N = I->second.getNode();
1428       if (N->getNodeFlags() == DSNode::UnknownNode && !isa<Argument>(I->first)){
1429         ScalarMap.erase(I++);
1430       } else {
1431         I->second.getNode()->markReachableNodes(Alive);
1432         ++I;
1433       }
1434     }
1435
1436   // The return value is alive as well...
1437   for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1438        I != E; ++I)
1439     I->second.getNode()->markReachableNodes(Alive);
1440
1441   // Mark any nodes reachable by primary calls as alive...
1442   for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1443     FunctionCalls[i].markReachableNodes(Alive);
1444
1445   // Copy and merge all information about globals to the GlobalsGraph
1446   // if this is not a final pass (where unreachable globals are removed)
1447   NodeMapTy GlobalNodeMap;
1448   hash_set<const DSNode*> GlobalNodeSet;
1449
1450   for (std::vector<std::pair<Value*, DSNode*> >::const_iterator
1451          I = GlobalNodes.begin(), E = GlobalNodes.end(); I != E; ++I)
1452     GlobalNodeSet.insert(I->second);    // put global nodes into a set
1453
1454   // Now find globals and aux call nodes that are already live or reach a live
1455   // value (which makes them live in turn), and continue till no more are found.
1456   // 
1457   bool Iterate;
1458   hash_set<DSNode*> Visited;
1459   std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1460   do {
1461     Visited.clear();
1462     // If any global node points to a non-global that is "alive", the global is
1463     // "alive" as well...  Remove it from the GlobalNodes list so we only have
1464     // unreachable globals in the list.
1465     //
1466     Iterate = false;
1467     if (!(Flags & DSGraph::RemoveUnreachableGlobals))
1468        for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1469          if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited, 
1470                                 Flags & DSGraph::RemoveUnreachableGlobals)) {
1471            std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
1472            GlobalNodes.pop_back();                          // erase efficiently
1473            Iterate = true;
1474          }
1475
1476     // Mark only unresolvable call nodes for moving to the GlobalsGraph since
1477     // call nodes that get resolved will be difficult to remove from that graph.
1478     // The final unresolved call nodes must be handled specially at the end of
1479     // the BU pass (i.e., in main or other roots of the call graph).
1480     for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1481       if (!AuxFCallsAlive[i] &&
1482           (AuxFunctionCalls[i].isIndirectCall()
1483            || CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited,
1484                                   Flags & DSGraph::RemoveUnreachableGlobals))) {
1485         AuxFunctionCalls[i].markReachableNodes(Alive);
1486         AuxFCallsAlive[i] = true;
1487         Iterate = true;
1488       }
1489   } while (Iterate);
1490
1491   // Move dead aux function calls to the end of the list
1492   unsigned CurIdx = 0;
1493   for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1494     if (AuxFCallsAlive[i])
1495       AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
1496
1497   // Copy and merge all global nodes and dead aux call nodes into the
1498   // GlobalsGraph, and all nodes reachable from those nodes
1499   // 
1500   if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1501
1502     // First, add the dead aux call nodes to the set of root nodes for cloning
1503     // -- return value at this call site, if any
1504     // -- actual arguments passed at this call site
1505     // -- callee node at this call site, if this is an indirect call
1506     for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i) {
1507       if (const DSNode* RetNode = AuxFunctionCalls[i].getRetVal().getNode())
1508         GlobalNodeSet.insert(RetNode);
1509       for (unsigned j=0, N=AuxFunctionCalls[i].getNumPtrArgs(); j < N; ++j)
1510         if (const DSNode* ArgTarget=AuxFunctionCalls[i].getPtrArg(j).getNode())
1511           GlobalNodeSet.insert(ArgTarget);
1512       if (AuxFunctionCalls[i].isIndirectCall())
1513         GlobalNodeSet.insert(AuxFunctionCalls[i].getCalleeNode());
1514     }
1515     
1516     // There are no "pre-completed" nodes so use any empty map for those.
1517     // Strip all alloca bits since the current function is only for the BU pass.
1518     // Strip all incomplete bits since they are short-lived properties and they
1519     // will be correctly computed when rematerializing nodes into the functions.
1520     // 
1521     NodeMapTy CompletedMap;
1522     GlobalsGraph->cloneReachableSubgraph(*this, GlobalNodeSet,
1523                                          GlobalNodeMap, CompletedMap,
1524                                          (DSGraph::StripAllocaBit |
1525                                           DSGraph::StripIncompleteBit));
1526   }
1527
1528   // Remove all dead aux function calls...
1529   if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1530     assert(GlobalsGraph && "No globals graph available??");
1531
1532     // Copy the unreachable call nodes to the globals graph, updating
1533     // their target pointers using the GlobalNodeMap
1534     for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i)
1535       GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(AuxFunctionCalls[i],
1536                                                           GlobalNodeMap));
1537   }
1538   // Crop all the useless ones out...
1539   AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1540                          AuxFunctionCalls.end());
1541
1542   // We are finally done with the GlobalNodeMap so we can clear it and
1543   // then get rid of unused nodes in the GlobalsGraph produced by merging.
1544   GlobalNodeMap.clear();
1545   GlobalsGraph->removeTriviallyDeadNodes();
1546
1547   // At this point, any nodes which are visited, but not alive, are nodes
1548   // which can be removed.  Loop over all nodes, eliminating completely
1549   // unreachable nodes.
1550   //
1551   std::vector<DSNode*> DeadNodes;
1552   DeadNodes.reserve(Nodes.size());
1553   for (unsigned i = 0; i != Nodes.size(); ++i)
1554     if (!Alive.count(Nodes[i])) {
1555       DSNode *N = Nodes[i];
1556       Nodes[i--] = Nodes.back();            // move node to end of vector
1557       Nodes.pop_back();                     // Erase node from alive list.
1558       DeadNodes.push_back(N);
1559       N->dropAllReferences();
1560     } else {
1561       assert(Nodes[i]->getForwardNode() == 0 && "Alive forwarded node?");
1562     }
1563
1564   // Remove all unreachable globals from the ScalarMap.
1565   // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
1566   // In either case, the dead nodes will not be in the set Alive.
1567   for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i) {
1568     assert(((Flags & DSGraph::RemoveUnreachableGlobals) ||
1569             !Alive.count(GlobalNodes[i].second)) && "huh? non-dead global");
1570     if (!Alive.count(GlobalNodes[i].second))
1571       ScalarMap.erase(GlobalNodes[i].first);
1572   }
1573
1574   // Delete all dead nodes now since their referrer counts are zero.
1575   for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1576     delete DeadNodes[i];
1577
1578   DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
1579 }
1580
1581 void DSGraph::AssertGraphOK() const {
1582   for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1583     Nodes[i]->assertOK();
1584
1585   for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
1586          E = ScalarMap.end(); I != E; ++I) {
1587     assert(I->second.getNode() && "Null node in scalarmap!");
1588     AssertNodeInGraph(I->second.getNode());
1589     if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
1590       assert(I->second.getNode()->isGlobalNode() &&
1591              "Global points to node, but node isn't global?");
1592       AssertNodeContainsGlobal(I->second.getNode(), GV);
1593     }
1594   }
1595   AssertCallNodesInGraph();
1596   AssertAuxCallNodesInGraph();
1597 }
1598
1599 /// mergeInGlobalsGraph - This method is useful for clients to incorporate the
1600 /// globals graph into the DS, BU or TD graph for a function.  This code retains
1601 /// all globals, i.e., does not delete unreachable globals after they are
1602 /// inlined.
1603 ///
1604 void DSGraph::mergeInGlobalsGraph() {
1605   NodeMapTy GlobalNodeMap;
1606   ScalarMapTy OldValMap;
1607   ReturnNodesTy OldRetNodes;
1608   cloneInto(*GlobalsGraph, OldValMap, OldRetNodes, GlobalNodeMap,
1609             DSGraph::KeepAllocaBit | DSGraph::DontCloneCallNodes |
1610             DSGraph::DontCloneAuxCallNodes);
1611   
1612   // Now merge existing global nodes in the GlobalsGraph with their copies
1613   for (ScalarMapTy::iterator I = ScalarMap.begin(), E = ScalarMap.end(); 
1614        I != E; ++I)
1615     if (isa<GlobalValue>(I->first)) {             // Found a global node
1616       DSNodeHandle &GH = I->second;
1617       DSNodeHandle &GGNodeH = GlobalsGraph->getScalarMap()[I->first];
1618       GH.mergeWith(GlobalNodeMap[GGNodeH.getNode()]);
1619     }
1620   
1621   // Merging leaves behind unused nodes: get rid of them now.
1622   GlobalNodeMap.clear();
1623   OldValMap.clear();
1624   OldRetNodes.clear();
1625   removeTriviallyDeadNodes();
1626 }