Instead of using a bool that constant has to be explained, use a self
[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 "Support/STLExtras.h"
13 #include "Support/Statistic.h"
14 #include <algorithm>
15 #include <set>
16
17 using std::vector;
18
19 namespace {
20   Statistic<> NumFolds("dsnode", "Number of nodes completely folded");
21 };
22
23 namespace DS {   // TODO: FIXME
24   extern TargetData TD;
25 }
26 using namespace DS;
27
28 //===----------------------------------------------------------------------===//
29 // DSNode Implementation
30 //===----------------------------------------------------------------------===//
31
32 DSNode::DSNode(enum NodeTy NT, const Type *T)
33   : Ty(Type::VoidTy), Size(0), NodeType(NT) {
34   // Add the type entry if it is specified...
35   if (T) mergeTypeInfo(T, 0);
36 }
37
38 // DSNode copy constructor... do not copy over the referrers list!
39 DSNode::DSNode(const DSNode &N)
40   : Links(N.Links), Globals(N.Globals), Ty(N.Ty), Size(N.Size), 
41     NodeType(N.NodeType) {
42 }
43
44 void DSNode::removeReferrer(DSNodeHandle *H) {
45   // Search backwards, because we depopulate the list from the back for
46   // efficiency (because it's a vector).
47   vector<DSNodeHandle*>::reverse_iterator I =
48     std::find(Referrers.rbegin(), Referrers.rend(), H);
49   assert(I != Referrers.rend() && "Referrer not pointing to node!");
50   Referrers.erase(I.base()-1);
51 }
52
53 // addGlobal - Add an entry for a global value to the Globals list.  This also
54 // marks the node with the 'G' flag if it does not already have it.
55 //
56 void DSNode::addGlobal(GlobalValue *GV) {
57   // Keep the list sorted.
58   vector<GlobalValue*>::iterator I =
59     std::lower_bound(Globals.begin(), Globals.end(), GV);
60
61   if (I == Globals.end() || *I != GV) {
62     //assert(GV->getType()->getElementType() == Ty);
63     Globals.insert(I, GV);
64     NodeType |= GlobalNode;
65   }
66 }
67
68 /// foldNodeCompletely - If we determine that this node has some funny
69 /// behavior happening to it that we cannot represent, we fold it down to a
70 /// single, completely pessimistic, node.  This node is represented as a
71 /// single byte with a single TypeEntry of "void".
72 ///
73 void DSNode::foldNodeCompletely() {
74   if (isNodeCompletelyFolded()) return;
75
76   ++NumFolds;
77
78   // We are no longer typed at all...
79   Ty = DSTypeRec(Type::VoidTy, true);
80   Size = 1;
81
82   // Loop over all of our referrers, making them point to our zero bytes of
83   // space.
84   for (vector<DSNodeHandle*>::iterator I = Referrers.begin(), E=Referrers.end();
85        I != E; ++I)
86     (*I)->setOffset(0);
87
88   // If we have links, merge all of our outgoing links together...
89   for (unsigned i = 1, e = Links.size(); i < e; ++i)
90     Links[0].mergeWith(Links[i]);
91   Links.resize(1);
92 }
93
94 /// isNodeCompletelyFolded - Return true if this node has been completely
95 /// folded down to something that can never be expanded, effectively losing
96 /// all of the field sensitivity that may be present in the node.
97 ///
98 bool DSNode::isNodeCompletelyFolded() const {
99   return getSize() == 1 && Ty.Ty == Type::VoidTy && Ty.isArray;
100 }
101
102
103 /// mergeTypeInfo - This method merges the specified type into the current node
104 /// at the specified offset.  This may update the current node's type record if
105 /// this gives more information to the node, it may do nothing to the node if
106 /// this information is already known, or it may merge the node completely (and
107 /// return true) if the information is incompatible with what is already known.
108 ///
109 /// This method returns true if the node is completely folded, otherwise false.
110 ///
111 bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset) {
112   // Check to make sure the Size member is up-to-date.  Size can be one of the
113   // following:
114   //  Size = 0, Ty = Void: Nothing is known about this node.
115   //  Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
116   //  Size = 1, Ty = Void, Array = 1: The node is collapsed
117   //  Otherwise, sizeof(Ty) = Size
118   //
119   assert(((Size == 0 && Ty.Ty == Type::VoidTy && !Ty.isArray) ||
120           (Size == 0 && !Ty.Ty->isSized() && !Ty.isArray) ||
121           (Size == 1 && Ty.Ty == Type::VoidTy && Ty.isArray) ||
122           (Size == 0 && !Ty.Ty->isSized() && !Ty.isArray) ||
123           (TD.getTypeSize(Ty.Ty) == Size)) &&
124          "Size member of DSNode doesn't match the type structure!");
125   assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
126
127   if (Offset == 0 && NewTy == Ty.Ty)
128     return false;  // This should be a common case, handle it efficiently
129
130   // Return true immediately if the node is completely folded.
131   if (isNodeCompletelyFolded()) return true;
132
133   // Figure out how big the new type we're merging in is...
134   unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
135
136   // Otherwise check to see if we can fold this type into the current node.  If
137   // we can't, we fold the node completely, if we can, we potentially update our
138   // internal state.
139   //
140   if (Ty.Ty == Type::VoidTy) {
141     // If this is the first type that this node has seen, just accept it without
142     // question....
143     assert(Offset == 0 && "Cannot have an offset into a void node!");
144     assert(Ty.isArray == false && "This shouldn't happen!");
145     Ty.Ty = NewTy;
146     Size = NewTySize;
147
148     // Calculate the number of outgoing links from this node.
149     Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
150     return false;
151   }
152
153   // Handle node expansion case here...
154   if (Offset+NewTySize > Size) {
155     // It is illegal to grow this node if we have treated it as an array of
156     // objects...
157     if (Ty.isArray) {
158       foldNodeCompletely();
159       return true;
160     }
161
162     if (Offset) {  // We could handle this case, but we don't for now...
163       DEBUG(std::cerr << "UNIMP: Trying to merge a growth type into "
164                       << "offset != 0: Collapsing!\n");
165       foldNodeCompletely();
166       return true;
167     }
168
169     // Okay, the situation is nice and simple, we are trying to merge a type in
170     // at offset 0 that is bigger than our current type.  Implement this by
171     // switching to the new type and then merge in the smaller one, which should
172     // hit the other code path here.  If the other code path decides it's not
173     // ok, it will collapse the node as appropriate.
174     //
175     const Type *OldTy = Ty.Ty;
176     Ty.Ty = NewTy;
177     Size = NewTySize;
178
179     // Must grow links to be the appropriate size...
180     Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
181
182     // Merge in the old type now... which is guaranteed to be smaller than the
183     // "current" type.
184     return mergeTypeInfo(OldTy, 0);
185   }
186
187   assert(Offset <= Size &&
188          "Cannot merge something into a part of our type that doesn't exist!");
189
190   // Find the section of Ty.Ty that NewTy overlaps with... first we find the
191   // type that starts at offset Offset.
192   //
193   unsigned O = 0;
194   const Type *SubType = Ty.Ty;
195   while (O < Offset) {
196     assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
197
198     switch (SubType->getPrimitiveID()) {
199     case Type::StructTyID: {
200       const StructType *STy = cast<StructType>(SubType);
201       const StructLayout &SL = *TD.getStructLayout(STy);
202
203       unsigned i = 0, e = SL.MemberOffsets.size();
204       for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
205         /* empty */;
206
207       // The offset we are looking for must be in the i'th element...
208       SubType = STy->getElementTypes()[i];
209       O += SL.MemberOffsets[i];
210       break;
211     }
212     case Type::ArrayTyID: {
213       SubType = cast<ArrayType>(SubType)->getElementType();
214       unsigned ElSize = TD.getTypeSize(SubType);
215       unsigned Remainder = (Offset-O) % ElSize;
216       O = Offset-Remainder;
217       break;
218     }
219     default:
220       assert(0 && "Unknown type!");
221     }
222   }
223
224   assert(O == Offset && "Could not achieve the correct offset!");
225
226   // If we found our type exactly, early exit
227   if (SubType == NewTy) return false;
228
229   // Okay, so we found the leader type at the offset requested.  Search the list
230   // of types that starts at this offset.  If SubType is currently an array or
231   // structure, the type desired may actually be the first element of the
232   // composite type...
233   //
234   unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
235   while (SubType != NewTy) {
236     const Type *NextSubType = 0;
237     unsigned NextSubTypeSize;
238     switch (SubType->getPrimitiveID()) {
239     case Type::StructTyID:
240       NextSubType = cast<StructType>(SubType)->getElementTypes()[0];
241       NextSubTypeSize = TD.getTypeSize(SubType);
242       break;
243     case Type::ArrayTyID:
244       NextSubType = cast<ArrayType>(SubType)->getElementType();
245       NextSubTypeSize = TD.getTypeSize(SubType);
246       break;
247     default: ;
248       // fall out 
249     }
250
251     if (NextSubType == 0)
252       break;   // In the default case, break out of the loop
253
254     if (NextSubTypeSize < NewTySize)
255       break;   // Don't allow shrinking to a smaller type than NewTySize
256     SubType = NextSubType;
257     SubTypeSize = NextSubTypeSize;
258   }
259
260   // If we found the type exactly, return it...
261   if (SubType == NewTy)
262     return false;
263
264   // Check to see if we have a compatible, but different type...
265   if (NewTySize == SubTypeSize) {
266     // Check to see if this type is obviously convertable... int -> uint f.e.
267     if (NewTy->isLosslesslyConvertableTo(SubType))
268       return false;
269
270     // Check to see if we have a pointer & integer mismatch going on here,
271     // loading a pointer as a long, for example.
272     //
273     if (SubType->isInteger() && isa<PointerType>(NewTy) ||
274         NewTy->isInteger() && isa<PointerType>(SubType))
275       return false;
276
277   }
278
279
280   DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: " << Ty.Ty
281                   << "\n due to:" << NewTy << " @ " << Offset << "!\n"
282                   << "SubType: " << SubType << "\n\n");
283
284   foldNodeCompletely();
285   return true;
286 }
287
288
289
290 // addEdgeTo - Add an edge from the current node to the specified node.  This
291 // can cause merging of nodes in the graph.
292 //
293 void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
294   if (NH.getNode() == 0) return;       // Nothing to do
295
296   DSNodeHandle &ExistingEdge = getLink(Offset);
297   if (ExistingEdge.getNode()) {
298     // Merge the two nodes...
299     ExistingEdge.mergeWith(NH);
300   } else {                             // No merging to perform...
301     setLink(Offset, NH);               // Just force a link in there...
302   }
303 }
304
305
306 // MergeSortedVectors - Efficiently merge a vector into another vector where
307 // duplicates are not allowed and both are sorted.  This assumes that 'T's are
308 // efficiently copyable and have sane comparison semantics.
309 //
310 template<typename T>
311 void MergeSortedVectors(vector<T> &Dest, const vector<T> &Src) {
312   // By far, the most common cases will be the simple ones.  In these cases,
313   // avoid having to allocate a temporary vector...
314   //
315   if (Src.empty()) {             // Nothing to merge in...
316     return;
317   } else if (Dest.empty()) {     // Just copy the result in...
318     Dest = Src;
319   } else if (Src.size() == 1) {  // Insert a single element...
320     const T &V = Src[0];
321     typename vector<T>::iterator I =
322       std::lower_bound(Dest.begin(), Dest.end(), V);
323     if (I == Dest.end() || *I != Src[0])  // If not already contained...
324       Dest.insert(I, Src[0]);
325   } else if (Dest.size() == 1) {
326     T Tmp = Dest[0];                      // Save value in temporary...
327     Dest = Src;                           // Copy over list...
328     typename vector<T>::iterator I =
329       std::lower_bound(Dest.begin(), Dest.end(),Tmp);
330     if (I == Dest.end() || *I != Src[0])  // If not already contained...
331       Dest.insert(I, Src[0]);
332
333   } else {
334     // Make a copy to the side of Dest...
335     vector<T> Old(Dest);
336     
337     // Make space for all of the type entries now...
338     Dest.resize(Dest.size()+Src.size());
339     
340     // Merge the two sorted ranges together... into Dest.
341     std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
342     
343     // Now erase any duplicate entries that may have accumulated into the 
344     // vectors (because they were in both of the input sets)
345     Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
346   }
347 }
348
349
350 // mergeWith - Merge this node and the specified node, moving all links to and
351 // from the argument node into the current node, deleting the node argument.
352 // Offset indicates what offset the specified node is to be merged into the
353 // current node.
354 //
355 // The specified node may be a null pointer (in which case, nothing happens).
356 //
357 void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
358   DSNode *N = NH.getNode();
359   if (N == 0 || (N == this && NH.getOffset() == Offset))
360     return;  // Noop
361
362   if (N == this) {
363     // We cannot merge two pieces of the same node together, collapse the node
364     // completely.
365     DEBUG(std::cerr << "Attempting to merge two chunks of"
366                     << " the same node together!\n");
367     foldNodeCompletely();
368     return;
369   }
370
371   // Merge the type entries of the two nodes together...
372   if (N->Ty.Ty != Type::VoidTy)
373     mergeTypeInfo(N->Ty.Ty, Offset);
374
375   // If we are merging a node with a completely folded node, then both nodes are
376   // now completely folded.
377   //
378   if (isNodeCompletelyFolded()) {
379     if (!N->isNodeCompletelyFolded())
380       N->foldNodeCompletely();
381   } else if (N->isNodeCompletelyFolded()) {
382     foldNodeCompletely();
383     Offset = 0;
384   }
385   N = NH.getNode();
386
387   if (this == N || N == 0) return;
388
389   // If both nodes are not at offset 0, make sure that we are merging the node
390   // at an later offset into the node with the zero offset.
391   //
392   if (Offset > NH.getOffset()) {
393     N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
394     return;
395   } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
396     // If the offsets are the same, merge the smaller node into the bigger node
397     N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
398     return;
399   }
400
401 #if 0
402   std::cerr << "\n\nMerging:\n";
403   N->print(std::cerr, 0);
404   std::cerr << " and:\n";
405   print(std::cerr, 0);
406 #endif
407
408   // Now we know that Offset <= NH.Offset, so convert it so our "Offset" (with
409   // respect to NH.Offset) is now zero.
410   //
411   unsigned NOffset = NH.getOffset()-Offset;
412   unsigned NSize = N->getSize();
413
414   // Remove all edges pointing at N, causing them to point to 'this' instead.
415   // Make sure to adjust their offset, not just the node pointer.
416   //
417   while (!N->Referrers.empty()) {
418     DSNodeHandle &Ref = *N->Referrers.back();
419     Ref = DSNodeHandle(this, NOffset+Ref.getOffset());
420   }
421
422   // Make all of the outgoing links of N now be outgoing links of this.  This
423   // can cause recursive merging!
424   //
425   for (unsigned i = 0; i < NSize; i += DS::PointerSize) {
426     DSNodeHandle &Link = N->getLink(i);
427     if (Link.getNode()) {
428       addEdgeTo((i+NOffset) % getSize(), Link);
429
430       // It's possible that after adding the new edge that some recursive
431       // merging just occured, causing THIS node to get merged into oblivion.
432       // If that happens, we must not try to merge any more edges into it!
433       //
434       if (Size == 0) return;
435     }
436   }
437
438   // Now that there are no outgoing edges, all of the Links are dead.
439   N->Links.clear();
440   N->Size = 0;
441   N->Ty.Ty = Type::VoidTy;
442   N->Ty.isArray = false;
443
444   // Merge the node types
445   NodeType |= N->NodeType;
446   N->NodeType = 0;   // N is now a dead node.
447
448   // Merge the globals list...
449   if (!N->Globals.empty()) {
450     MergeSortedVectors(Globals, N->Globals);
451
452     // Delete the globals from the old node...
453     N->Globals.clear();
454   }
455 }
456
457 //===----------------------------------------------------------------------===//
458 // DSCallSite Implementation
459 //===----------------------------------------------------------------------===//
460
461 // Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
462 Function &DSCallSite::getCaller() const {
463   return *Inst->getParent()->getParent();
464 }
465
466
467 //===----------------------------------------------------------------------===//
468 // DSGraph Implementation
469 //===----------------------------------------------------------------------===//
470
471 DSGraph::DSGraph(const DSGraph &G) : Func(G.Func) {
472   std::map<const DSNode*, DSNode*> NodeMap;
473   RetNode = cloneInto(G, ScalarMap, NodeMap);
474 }
475
476 DSGraph::DSGraph(const DSGraph &G, std::map<const DSNode*, DSNode*> &NodeMap)
477   : Func(G.Func) {
478   RetNode = cloneInto(G, ScalarMap, NodeMap);
479 }
480
481 DSGraph::~DSGraph() {
482   FunctionCalls.clear();
483   ScalarMap.clear();
484   RetNode.setNode(0);
485
486 #ifndef NDEBUG
487   // Drop all intra-node references, so that assertions don't fail...
488   std::for_each(Nodes.begin(), Nodes.end(),
489                 std::mem_fun(&DSNode::dropAllReferences));
490 #endif
491
492   // Delete all of the nodes themselves...
493   std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
494 }
495
496 // dump - Allow inspection of graph in a debugger.
497 void DSGraph::dump() const { print(std::cerr); }
498
499
500 // Helper function used to clone a function list.
501 // 
502 static void CopyFunctionCallsList(const vector<DSCallSite>& fromCalls,
503                                   vector<DSCallSite> &toCalls,
504                                   std::map<const DSNode*, DSNode*> &NodeMap) {
505   unsigned FC = toCalls.size();  // FirstCall
506   toCalls.reserve(FC+fromCalls.size());
507   for (unsigned i = 0, ei = fromCalls.size(); i != ei; ++i)
508     toCalls.push_back(DSCallSite(fromCalls[i], NodeMap));
509 }
510
511 /// remapLinks - Change all of the Links in the current node according to the
512 /// specified mapping.
513 ///
514 void DSNode::remapLinks(std::map<const DSNode*, DSNode*> &OldNodeMap) {
515   for (unsigned i = 0, e = Links.size(); i != e; ++i) 
516     Links[i].setNode(OldNodeMap[Links[i].getNode()]);
517 }
518
519
520 // cloneInto - Clone the specified DSGraph into the current graph, returning the
521 // Return node of the graph.  The translated ScalarMap for the old function is
522 // filled into the OldValMap member.  If StripAllocas is set to true, Alloca
523 // markers are removed from the graph, as the graph is being cloned into a
524 // calling function's graph.
525 //
526 DSNodeHandle DSGraph::cloneInto(const DSGraph &G, 
527                                 std::map<Value*, DSNodeHandle> &OldValMap,
528                                 std::map<const DSNode*, DSNode*> &OldNodeMap,
529                                 AllocaBit StripAllocas) {
530   assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
531
532   unsigned FN = Nodes.size();           // First new node...
533
534   // Duplicate all of the nodes, populating the node map...
535   Nodes.reserve(FN+G.Nodes.size());
536   for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
537     DSNode *Old = G.Nodes[i];
538     DSNode *New = new DSNode(*Old);
539     Nodes.push_back(New);
540     OldNodeMap[Old] = New;
541   }
542
543   // Rewrite the links in the new nodes to point into the current graph now.
544   for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
545     Nodes[i]->remapLinks(OldNodeMap);
546
547   // Remove alloca markers as specified
548   if (StripAllocas == StripAllocaBit)
549     for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
550       Nodes[i]->NodeType &= ~DSNode::AllocaNode;
551
552   // Copy the value map... and merge all of the global nodes...
553   for (std::map<Value*, DSNodeHandle>::const_iterator I = G.ScalarMap.begin(),
554          E = G.ScalarMap.end(); I != E; ++I) {
555     DSNodeHandle &H = OldValMap[I->first];
556     H.setNode(OldNodeMap[I->second.getNode()]);
557     H.setOffset(I->second.getOffset());
558
559     if (isa<GlobalValue>(I->first)) {  // Is this a global?
560       std::map<Value*, DSNodeHandle>::iterator GVI = ScalarMap.find(I->first);
561       if (GVI != ScalarMap.end()) {   // Is the global value in this fn already?
562         GVI->second.mergeWith(H);
563       } else {
564         ScalarMap[I->first] = H;      // Add global pointer to this graph
565       }
566     }
567   }
568   // Copy the function calls list...
569   CopyFunctionCallsList(G.FunctionCalls, FunctionCalls, OldNodeMap);
570
571
572   // Return the returned node pointer...
573   return DSNodeHandle(OldNodeMap[G.RetNode.getNode()], G.RetNode.getOffset());
574 }
575
576 /// mergeInGraph - The method is used for merging graphs together.  If the
577 /// argument graph is not *this, it makes a clone of the specified graph, then
578 /// merges the nodes specified in the call site with the formal arguments in the
579 /// graph.
580 ///
581 void DSGraph::mergeInGraph(DSCallSite &CS, const DSGraph &Graph,
582                            AllocaBit StripAllocas) {
583   std::map<Value*, DSNodeHandle> OldValMap;
584   DSNodeHandle RetVal;
585   std::map<Value*, DSNodeHandle> *ScalarMap = &OldValMap;
586
587   // If this is not a recursive call, clone the graph into this graph...
588   if (&Graph != this) {
589     // Clone the callee's graph into the current graph, keeping
590     // track of where scalars in the old graph _used_ to point,
591     // and of the new nodes matching nodes of the old graph.
592     std::map<const DSNode*, DSNode*> OldNodeMap;
593     
594     // The clone call may invalidate any of the vectors in the data
595     // structure graph.  Strip locals and don't copy the list of callers
596     RetVal = cloneInto(Graph, OldValMap, OldNodeMap, StripAllocas);
597     ScalarMap = &OldValMap;
598   } else {
599     RetVal = getRetNode();
600     ScalarMap = &getScalarMap();
601   }
602
603   // Merge the return value with the return value of the context...
604   RetVal.mergeWith(CS.getRetVal());
605
606   // Resolve all of the function arguments...
607   Function &F = Graph.getFunction();
608   Function::aiterator AI = F.abegin();
609   for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
610     // Advance the argument iterator to the first pointer argument...
611     while (!isPointerType(AI->getType())) {
612       ++AI;
613 #ifndef NDEBUG
614       if (AI == F.aend())
615         std::cerr << "Bad call to Function: " << F.getName() << "\n";
616 #endif
617       assert(AI != F.aend() && "# Args provided is not # Args required!");
618     }
619     
620     // Add the link from the argument scalar to the provided value
621     DSNodeHandle &NH = (*ScalarMap)[AI];
622     assert(NH.getNode() && "Pointer argument without scalarmap entry?");
623     NH.mergeWith(CS.getPtrArg(i));
624   }
625 }
626
627 #if 0
628 // cloneGlobalInto - Clone the given global node and all its target links
629 // (and all their llinks, recursively).
630 // 
631 DSNode *DSGraph::cloneGlobalInto(const DSNode *GNode) {
632   if (GNode == 0 || GNode->getGlobals().size() == 0) return 0;
633
634   // If a clone has already been created for GNode, return it.
635   DSNodeHandle& ValMapEntry = ScalarMap[GNode->getGlobals()[0]];
636   if (ValMapEntry != 0)
637     return ValMapEntry;
638
639   // Clone the node and update the ValMap.
640   DSNode* NewNode = new DSNode(*GNode);
641   ValMapEntry = NewNode;                // j=0 case of loop below!
642   Nodes.push_back(NewNode);
643   for (unsigned j = 1, N = NewNode->getGlobals().size(); j < N; ++j)
644     ScalarMap[NewNode->getGlobals()[j]] = NewNode;
645
646   // Rewrite the links in the new node to point into the current graph.
647   for (unsigned j = 0, e = GNode->getNumLinks(); j != e; ++j)
648     NewNode->setLink(j, cloneGlobalInto(GNode->getLink(j)));
649
650   return NewNode;
651 }
652 #endif
653
654
655 // markIncompleteNodes - Mark the specified node as having contents that are not
656 // known with the current analysis we have performed.  Because a node makes all
657 // of the nodes it can reach imcomplete if the node itself is incomplete, we
658 // must recursively traverse the data structure graph, marking all reachable
659 // nodes as incomplete.
660 //
661 static void markIncompleteNode(DSNode *N) {
662   // Stop recursion if no node, or if node already marked...
663   if (N == 0 || (N->NodeType & DSNode::Incomplete)) return;
664
665   // Actually mark the node
666   N->NodeType |= DSNode::Incomplete;
667
668   // Recusively process children...
669   for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
670     if (DSNode *DSN = N->getLink(i).getNode())
671       markIncompleteNode(DSN);
672 }
673
674
675 // markIncompleteNodes - Traverse the graph, identifying nodes that may be
676 // modified by other functions that have not been resolved yet.  This marks
677 // nodes that are reachable through three sources of "unknownness":
678 //
679 //  Global Variables, Function Calls, and Incoming Arguments
680 //
681 // For any node that may have unknown components (because something outside the
682 // scope of current analysis may have modified it), the 'Incomplete' flag is
683 // added to the NodeType.
684 //
685 void DSGraph::markIncompleteNodes(bool markFormalArgs) {
686   // Mark any incoming arguments as incomplete...
687   if (markFormalArgs && Func)
688     for (Function::aiterator I = Func->abegin(), E = Func->aend(); I != E; ++I)
689       if (isPointerType(I->getType()) && ScalarMap.find(I) != ScalarMap.end())
690         markIncompleteNode(ScalarMap[I].getNode());
691
692   // Mark stuff passed into functions calls as being incomplete...
693   for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
694     DSCallSite &Call = FunctionCalls[i];
695     // Then the return value is certainly incomplete!
696     markIncompleteNode(Call.getRetVal().getNode());
697
698     // All objects pointed to by function arguments are incomplete though!
699     for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
700       markIncompleteNode(Call.getPtrArg(i).getNode());
701   }
702
703   // Mark all of the nodes pointed to by global nodes as incomplete...
704   for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
705     if (Nodes[i]->NodeType & DSNode::GlobalNode) {
706       DSNode *N = Nodes[i];
707       // FIXME: Make more efficient by looking over Links directly
708       for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
709         if (DSNode *DSN = N->getLink(i).getNode())
710           markIncompleteNode(DSN);
711     }
712 }
713
714 // removeRefsToGlobal - Helper function that removes globals from the
715 // ScalarMap so that the referrer count will go down to zero.
716 static void removeRefsToGlobal(DSNode* N,
717                                std::map<Value*, DSNodeHandle> &ScalarMap) {
718   while (!N->getGlobals().empty()) {
719     GlobalValue *GV = N->getGlobals().back();
720     N->getGlobals().pop_back();      
721     ScalarMap.erase(GV);
722   }
723 }
724
725
726 // isNodeDead - This method checks to see if a node is dead, and if it isn't, it
727 // checks to see if there are simple transformations that it can do to make it
728 // dead.
729 //
730 bool DSGraph::isNodeDead(DSNode *N) {
731   // Is it a trivially dead shadow node...
732   if (N->getReferrers().empty() && N->NodeType == 0)
733     return true;
734
735   // Is it a function node or some other trivially unused global?
736   if ((N->NodeType & ~DSNode::GlobalNode) == 0 && N->getSize() == 0 &&
737       N->getReferrers().size() == N->getGlobals().size()) {
738
739     // Remove the globals from the ScalarMap, so that the referrer count will go
740     // down to zero.
741     removeRefsToGlobal(N, ScalarMap);
742     assert(N->getReferrers().empty() && "Referrers should all be gone now!");
743     return true;
744   }
745
746   return false;
747 }
748
749 static void removeIdenticalCalls(vector<DSCallSite> &Calls,
750                                  const std::string &where) {
751   // Remove trivially identical function calls
752   unsigned NumFns = Calls.size();
753   std::sort(Calls.begin(), Calls.end());
754   Calls.erase(std::unique(Calls.begin(), Calls.end()),
755               Calls.end());
756
757   DEBUG(if (NumFns != Calls.size())
758           std::cerr << "Merged " << (NumFns-Calls.size())
759                     << " call nodes in " << where << "\n";);
760 }
761
762 // removeTriviallyDeadNodes - After the graph has been constructed, this method
763 // removes all unreachable nodes that are created because they got merged with
764 // other nodes in the graph.  These nodes will all be trivially unreachable, so
765 // we don't have to perform any non-trivial analysis here.
766 //
767 void DSGraph::removeTriviallyDeadNodes(bool KeepAllGlobals) {
768   for (unsigned i = 0; i != Nodes.size(); ++i)
769     if (!KeepAllGlobals || !(Nodes[i]->NodeType & DSNode::GlobalNode))
770       if (isNodeDead(Nodes[i])) {               // This node is dead!
771         delete Nodes[i];                        // Free memory...
772         Nodes.erase(Nodes.begin()+i--);         // Remove from node list...
773       }
774
775   removeIdenticalCalls(FunctionCalls, Func ? Func->getName() : "");
776 }
777
778
779 // markAlive - Simple graph walker that recursively traverses the graph, marking
780 // stuff to be alive.
781 //
782 static void markAlive(DSNode *N, std::set<DSNode*> &Alive) {
783   if (N == 0) return;
784
785   Alive.insert(N);
786   for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
787     if (DSNode *DSN = N->getLink(i).getNode())
788       if (!Alive.count(DSN))
789         markAlive(DSN, Alive);
790 }
791
792 static bool checkGlobalAlive(DSNode *N, std::set<DSNode*> &Alive,
793                              std::set<DSNode*> &Visiting) {
794   if (N == 0) return false;
795
796   if (Visiting.count(N)) return false; // terminate recursion on a cycle
797   Visiting.insert(N);
798
799   // If any immediate successor is alive, N is alive
800   for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
801     if (DSNode *DSN = N->getLink(i).getNode())
802       if (Alive.count(DSN)) {
803         Visiting.erase(N);
804         return true;
805       }
806
807   // Else if any successor reaches a live node, N is alive
808   for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
809     if (DSNode *DSN = N->getLink(i).getNode())
810       if (checkGlobalAlive(DSN, Alive, Visiting)) {
811         Visiting.erase(N); return true;
812       }
813
814   Visiting.erase(N);
815   return false;
816 }
817
818
819 // markGlobalsIteration - Recursive helper function for markGlobalsAlive().
820 // This would be unnecessary if function calls were real nodes!  In that case,
821 // the simple iterative loop in the first few lines below suffice.
822 // 
823 static void markGlobalsIteration(std::set<DSNode*>& GlobalNodes,
824                                  vector<DSCallSite> &Calls,
825                                  std::set<DSNode*> &Alive,
826                                  bool FilterCalls) {
827
828   // Iterate, marking globals or cast nodes alive until no new live nodes
829   // are added to Alive
830   std::set<DSNode*> Visiting;           // Used to identify cycles 
831   std::set<DSNode*>::iterator I = GlobalNodes.begin(), E = GlobalNodes.end();
832   for (size_t liveCount = 0; liveCount < Alive.size(); ) {
833     liveCount = Alive.size();
834     for ( ; I != E; ++I)
835       if (Alive.count(*I) == 0) {
836         Visiting.clear();
837         if (checkGlobalAlive(*I, Alive, Visiting))
838           markAlive(*I, Alive);
839       }
840   }
841
842   // Find function calls with some dead and some live nodes.
843   // Since all call nodes must be live if any one is live, we have to mark
844   // all nodes of the call as live and continue the iteration (via recursion).
845   if (FilterCalls) {
846     bool Recurse = false;
847     for (unsigned i = 0, ei = Calls.size(); i < ei; ++i) {
848       bool CallIsDead = true, CallHasDeadArg = false;
849       DSCallSite &CS = Calls[i];
850       for (unsigned j = 0, ej = CS.getNumPtrArgs(); j != ej; ++j)
851         if (DSNode *N = CS.getPtrArg(j).getNode()) {
852           bool ArgIsDead  = !Alive.count(N);
853           CallHasDeadArg |= ArgIsDead;
854           CallIsDead     &= ArgIsDead;
855         }
856
857       if (DSNode *N = CS.getRetVal().getNode()) {
858         bool RetIsDead  = !Alive.count(N);
859         CallHasDeadArg |= RetIsDead;
860         CallIsDead     &= RetIsDead;
861       }
862
863       DSNode *N = CS.getCallee().getNode();
864       bool FnIsDead  = !Alive.count(N);
865       CallHasDeadArg |= FnIsDead;
866       CallIsDead     &= FnIsDead;
867
868       if (!CallIsDead && CallHasDeadArg) {
869         // Some node in this call is live and another is dead.
870         // Mark all nodes of call as live and iterate once more.
871         Recurse = true;
872         for (unsigned j = 0, ej = CS.getNumPtrArgs(); j != ej; ++j)
873           markAlive(CS.getPtrArg(j).getNode(), Alive);
874         markAlive(CS.getRetVal().getNode(), Alive);
875         markAlive(CS.getCallee().getNode(), Alive);
876       }
877     }
878     if (Recurse)
879       markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
880   }
881 }
882
883
884 // markGlobalsAlive - Mark global nodes and cast nodes alive if they
885 // can reach any other live node.  Since this can produce new live nodes,
886 // we use a simple iterative algorithm.
887 // 
888 static void markGlobalsAlive(DSGraph &G, std::set<DSNode*> &Alive,
889                              bool FilterCalls) {
890   // Add global and cast nodes to a set so we don't walk all nodes every time
891   std::set<DSNode*> GlobalNodes;
892   for (unsigned i = 0, e = G.getNodes().size(); i != e; ++i)
893     if (G.getNodes()[i]->NodeType & DSNode::GlobalNode)
894       GlobalNodes.insert(G.getNodes()[i]);
895
896   // Add all call nodes to the same set
897   vector<DSCallSite> &Calls = G.getFunctionCalls();
898   if (FilterCalls) {
899     for (unsigned i = 0, e = Calls.size(); i != e; ++i) {
900       for (unsigned j = 0, e = Calls[i].getNumPtrArgs(); j != e; ++j)
901         if (DSNode *N = Calls[i].getPtrArg(j).getNode())
902           GlobalNodes.insert(N);
903       if (DSNode *N = Calls[i].getRetVal().getNode())
904         GlobalNodes.insert(N);
905       if (DSNode *N = Calls[i].getCallee().getNode())
906         GlobalNodes.insert(N);
907     }
908   }
909
910   // Iterate and recurse until no new live node are discovered.
911   // This would be a simple iterative loop if function calls were real nodes!
912   markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
913
914   // Free up references to dead globals from the ScalarMap
915   std::set<DSNode*>::iterator I = GlobalNodes.begin(), E = GlobalNodes.end();
916   for( ; I != E; ++I)
917     if (Alive.count(*I) == 0)
918       removeRefsToGlobal(*I, G.getScalarMap());
919
920   // Delete dead function calls
921   if (FilterCalls)
922     for (int ei = Calls.size(), i = ei-1; i >= 0; --i) {
923       bool CallIsDead = true;
924       for (unsigned j = 0, ej = Calls[i].getNumPtrArgs();
925            CallIsDead && j != ej; ++j)
926         CallIsDead = Alive.count(Calls[i].getPtrArg(j).getNode()) == 0;
927       if (CallIsDead)
928         Calls.erase(Calls.begin() + i); // remove the call entirely
929     }
930 }
931
932 // removeDeadNodes - Use a more powerful reachability analysis to eliminate
933 // subgraphs that are unreachable.  This often occurs because the data
934 // structure doesn't "escape" into it's caller, and thus should be eliminated
935 // from the caller's graph entirely.  This is only appropriate to use when
936 // inlining graphs.
937 //
938 void DSGraph::removeDeadNodes(bool KeepAllGlobals, bool KeepCalls) {
939   assert((!KeepAllGlobals || KeepCalls) &&
940          "KeepAllGlobals without KeepCalls is meaningless");
941
942   // Reduce the amount of work we have to do...
943   removeTriviallyDeadNodes(KeepAllGlobals);
944
945   // FIXME: Merge nontrivially identical call nodes...
946
947   // Alive - a set that holds all nodes found to be reachable/alive.
948   std::set<DSNode*> Alive;
949
950   // If KeepCalls, mark all nodes reachable by call nodes as alive...
951   if (KeepCalls)
952     for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
953       for (unsigned j = 0, e = FunctionCalls[i].getNumPtrArgs(); j != e; ++j)
954         markAlive(FunctionCalls[i].getPtrArg(j).getNode(), Alive);
955       markAlive(FunctionCalls[i].getRetVal().getNode(), Alive);
956       markAlive(FunctionCalls[i].getCallee().getNode(), Alive);
957     }
958
959   // Mark all nodes reachable by scalar nodes as alive...
960   for (std::map<Value*, DSNodeHandle>::iterator I = ScalarMap.begin(),
961          E = ScalarMap.end(); I != E; ++I)
962     markAlive(I->second.getNode(), Alive);
963
964 #if 0
965   // Marge all nodes reachable by global nodes, as alive.  Isn't this covered by
966   // the ScalarMap?
967   //
968   if (KeepAllGlobals)
969     for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
970       if (Nodes[i]->NodeType & DSNode::GlobalNode)
971         markAlive(Nodes[i], Alive);
972 #endif
973
974   // The return value is alive as well...
975   markAlive(RetNode.getNode(), Alive);
976
977   // Mark all globals or cast nodes that can reach a live node as alive.
978   // This also marks all nodes reachable from such nodes as alive.
979   // Of course, if KeepAllGlobals is specified, they would be live already.
980   if (!KeepAllGlobals)
981     markGlobalsAlive(*this, Alive, !KeepCalls);
982
983   // Loop over all unreachable nodes, dropping their references...
984   vector<DSNode*> DeadNodes;
985   DeadNodes.reserve(Nodes.size());     // Only one allocation is allowed.
986   for (unsigned i = 0; i != Nodes.size(); ++i)
987     if (!Alive.count(Nodes[i])) {
988       DSNode *N = Nodes[i];
989       Nodes.erase(Nodes.begin()+i--);  // Erase node from alive list.
990       DeadNodes.push_back(N);          // Add node to our list of dead nodes
991       N->dropAllReferences();          // Drop all outgoing edges
992     }
993   
994   // Delete all dead nodes...
995   std::for_each(DeadNodes.begin(), DeadNodes.end(), deleter<DSNode>);
996 }
997
998
999
1000 // maskNodeTypes - Apply a mask to all of the node types in the graph.  This
1001 // is useful for clearing out markers like Scalar or Incomplete.
1002 //
1003 void DSGraph::maskNodeTypes(unsigned char Mask) {
1004   for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1005     Nodes[i]->NodeType &= Mask;
1006 }
1007
1008
1009 #if 0
1010 //===----------------------------------------------------------------------===//
1011 // GlobalDSGraph Implementation
1012 //===----------------------------------------------------------------------===//
1013
1014 GlobalDSGraph::GlobalDSGraph() : DSGraph(*(Function*)0, this) {
1015 }
1016
1017 GlobalDSGraph::~GlobalDSGraph() {
1018   assert(Referrers.size() == 0 &&
1019          "Deleting global graph while references from other graphs exist");
1020 }
1021
1022 void GlobalDSGraph::addReference(const DSGraph* referrer) {
1023   if (referrer != this)
1024     Referrers.insert(referrer);
1025 }
1026
1027 void GlobalDSGraph::removeReference(const DSGraph* referrer) {
1028   if (referrer != this) {
1029     assert(Referrers.find(referrer) != Referrers.end() && "This is very bad!");
1030     Referrers.erase(referrer);
1031     if (Referrers.size() == 0)
1032       delete this;
1033   }
1034 }
1035
1036 #if 0
1037 // Bits used in the next function
1038 static const char ExternalTypeBits = DSNode::GlobalNode | DSNode::HeapNode;
1039
1040
1041 // GlobalDSGraph::cloneNodeInto - Clone a global node and all its externally
1042 // visible target links (and recursively their such links) into this graph.
1043 // NodeCache maps the node being cloned to its clone in the Globals graph,
1044 // in order to track cycles.
1045 // GlobalsAreFinal is a flag that says whether it is safe to assume that
1046 // an existing global node is complete.  This is important to avoid
1047 // reinserting all globals when inserting Calls to functions.
1048 // This is a helper function for cloneGlobals and cloneCalls.
1049 // 
1050 DSNode* GlobalDSGraph::cloneNodeInto(DSNode *OldNode,
1051                                     std::map<const DSNode*, DSNode*> &NodeCache,
1052                                     bool GlobalsAreFinal) {
1053   if (OldNode == 0) return 0;
1054
1055   // The caller should check this is an external node.  Just more  efficient...
1056   assert((OldNode->NodeType & ExternalTypeBits) && "Non-external node");
1057
1058   // If a clone has already been created for OldNode, return it.
1059   DSNode*& CacheEntry = NodeCache[OldNode];
1060   if (CacheEntry != 0)
1061     return CacheEntry;
1062
1063   // The result value...
1064   DSNode* NewNode = 0;
1065
1066   // If nodes already exist for any of the globals of OldNode,
1067   // merge all such nodes together since they are merged in OldNode.
1068   // If ValueCacheIsFinal==true, look for an existing node that has
1069   // an identical list of globals and return it if it exists.
1070   //
1071   for (unsigned j = 0, N = OldNode->getGlobals().size(); j != N; ++j)
1072     if (DSNode *PrevNode = ScalarMap[OldNode->getGlobals()[j]].getNode()) {
1073       if (NewNode == 0) {
1074         NewNode = PrevNode;             // first existing node found
1075         if (GlobalsAreFinal && j == 0)
1076           if (OldNode->getGlobals() == PrevNode->getGlobals()) {
1077             CacheEntry = NewNode;
1078             return NewNode;
1079           }
1080       }
1081       else if (NewNode != PrevNode) {   // found another, different from prev
1082         // update ValMap *before* merging PrevNode into NewNode
1083         for (unsigned k = 0, NK = PrevNode->getGlobals().size(); k < NK; ++k)
1084           ScalarMap[PrevNode->getGlobals()[k]] = NewNode;
1085         NewNode->mergeWith(PrevNode);
1086       }
1087     } else if (NewNode != 0) {
1088       ScalarMap[OldNode->getGlobals()[j]] = NewNode; // add the merged node
1089     }
1090
1091   // If no existing node was found, clone the node and update the ValMap.
1092   if (NewNode == 0) {
1093     NewNode = new DSNode(*OldNode);
1094     Nodes.push_back(NewNode);
1095     for (unsigned j = 0, e = NewNode->getNumLinks(); j != e; ++j)
1096       NewNode->setLink(j, 0);
1097     for (unsigned j = 0, N = NewNode->getGlobals().size(); j < N; ++j)
1098       ScalarMap[NewNode->getGlobals()[j]] = NewNode;
1099   }
1100   else
1101     NewNode->NodeType |= OldNode->NodeType; // Markers may be different!
1102
1103   // Add the entry to NodeCache
1104   CacheEntry = NewNode;
1105
1106   // Rewrite the links in the new node to point into the current graph,
1107   // but only for links to external nodes.  Set other links to NULL.
1108   for (unsigned j = 0, e = OldNode->getNumLinks(); j != e; ++j) {
1109     DSNode* OldTarget = OldNode->getLink(j);
1110     if (OldTarget && (OldTarget->NodeType & ExternalTypeBits)) {
1111       DSNode* NewLink = this->cloneNodeInto(OldTarget, NodeCache);
1112       if (NewNode->getLink(j))
1113         NewNode->getLink(j)->mergeWith(NewLink);
1114       else
1115         NewNode->setLink(j, NewLink);
1116     }
1117   }
1118
1119   // Remove all local markers
1120   NewNode->NodeType &= ~(DSNode::AllocaNode | DSNode::ScalarNode);
1121
1122   return NewNode;
1123 }
1124
1125
1126 // GlobalDSGraph::cloneGlobals - Clone global nodes and all their externally
1127 // visible target links (and recursively their such links) into this graph.
1128 // 
1129 void GlobalDSGraph::cloneGlobals(DSGraph& Graph, bool CloneCalls) {
1130   std::map<const DSNode*, DSNode*> NodeCache;
1131 #if 0
1132   for (unsigned i = 0, N = Graph.Nodes.size(); i < N; ++i)
1133     if (Graph.Nodes[i]->NodeType & DSNode::GlobalNode)
1134       GlobalsGraph->cloneNodeInto(Graph.Nodes[i], NodeCache, false);
1135   if (CloneCalls)
1136     GlobalsGraph->cloneCalls(Graph);
1137
1138   GlobalsGraph->removeDeadNodes(/*KeepAllGlobals*/ true, /*KeepCalls*/ true);
1139 #endif
1140 }
1141
1142
1143 // GlobalDSGraph::cloneCalls - Clone function calls and their visible target
1144 // links (and recursively their such links) into this graph.
1145 // 
1146 void GlobalDSGraph::cloneCalls(DSGraph& Graph) {
1147   std::map<const DSNode*, DSNode*> NodeCache;
1148   vector<DSCallSite >& FromCalls =Graph.FunctionCalls;
1149
1150   FunctionCalls.reserve(FunctionCalls.size() + FromCalls.size());
1151
1152   for (int i = 0, ei = FromCalls.size(); i < ei; ++i) {
1153     DSCallSite& callCopy = FunctionCalls.back();
1154     callCopy.reserve(FromCalls[i].size());
1155     for (unsigned j = 0, ej = FromCalls[i].size(); j != ej; ++j)
1156       callCopy.push_back
1157         ((FromCalls[i][j] && (FromCalls[i][j]->NodeType & ExternalTypeBits))
1158          ? cloneNodeInto(FromCalls[i][j], NodeCache, true)
1159          : 0);
1160   }
1161
1162   // remove trivially identical function calls
1163   removeIdenticalCalls(FunctionCalls, "Globals Graph");
1164 }
1165 #endif
1166
1167 #endif