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