Ignore redundant constraints
[oota-llvm.git] / lib / Analysis / IPA / Andersens.cpp
1 //===- Andersens.cpp - Andersen's Interprocedural Alias 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 defines an implementation of Andersen's interprocedural alias
11 // analysis
12 //
13 // In pointer analysis terms, this is a subset-based, flow-insensitive,
14 // field-sensitive, and context-insensitive algorithm pointer algorithm.
15 //
16 // This algorithm is implemented as three stages:
17 //   1. Object identification.
18 //   2. Inclusion constraint identification.
19 //   3. Offline constraint graph optimization
20 //   4. Inclusion constraint solving.
21 //
22 // The object identification stage identifies all of the memory objects in the
23 // program, which includes globals, heap allocated objects, and stack allocated
24 // objects.
25 //
26 // The inclusion constraint identification stage finds all inclusion constraints
27 // in the program by scanning the program, looking for pointer assignments and
28 // other statements that effect the points-to graph.  For a statement like "A =
29 // B", this statement is processed to indicate that A can point to anything that
30 // B can point to.  Constraints can handle copies, loads, and stores, and
31 // address taking.
32 //
33 // The offline constraint graph optimization portion includes offline variable
34 // substitution algorithms intended to computer pointer and location
35 // equivalences.  Pointer equivalences are those pointers that will have the
36 // same points-to sets, and location equivalences are those variables that
37 // always appear together in points-to sets.
38 //
39 // The inclusion constraint solving phase iteratively propagates the inclusion
40 // constraints until a fixed point is reached.  This is an O(N^3) algorithm.
41 //
42 // Function constraints are handled as if they were structs with X fields.
43 // Thus, an access to argument X of function Y is an access to node index
44 // getNode(Y) + X.  This representation allows handling of indirect calls
45 // without any issues.  To wit, an indirect call Y(a,b) is equivalent to
46 // *(Y + 1) = a, *(Y + 2) = b.
47 // The return node for a function is always located at getNode(F) +
48 // CallReturnPos. The arguments start at getNode(F) + CallArgPos.
49 //
50 // Future Improvements:
51 //   Offline detection of online cycles.  Use of BDD's.
52 //===----------------------------------------------------------------------===//
53
54 #define DEBUG_TYPE "anders-aa"
55 #include "llvm/Constants.h"
56 #include "llvm/DerivedTypes.h"
57 #include "llvm/Instructions.h"
58 #include "llvm/Module.h"
59 #include "llvm/Pass.h"
60 #include "llvm/Support/Compiler.h"
61 #include "llvm/Support/InstIterator.h"
62 #include "llvm/Support/InstVisitor.h"
63 #include "llvm/Analysis/AliasAnalysis.h"
64 #include "llvm/Analysis/Passes.h"
65 #include "llvm/Support/Debug.h"
66 #include "llvm/ADT/Statistic.h"
67 #include "llvm/ADT/SparseBitVector.h"
68 #include "llvm/ADT/DenseMap.h"
69 #include <algorithm>
70 #include <set>
71 #include <list>
72 #include <stack>
73 #include <vector>
74
75 using namespace llvm;
76 STATISTIC(NumIters      , "Number of iterations to reach convergence");
77 STATISTIC(NumConstraints, "Number of constraints");
78 STATISTIC(NumNodes      , "Number of nodes");
79 STATISTIC(NumUnified    , "Number of variables unified");
80
81 namespace {
82   const unsigned SelfRep = (unsigned)-1;
83   const unsigned Unvisited = (unsigned)-1;
84   // Position of the function return node relative to the function node.
85   const unsigned CallReturnPos = 1;
86   // Position of the function call node relative to the function node.
87   const unsigned CallFirstArgPos = 2;
88
89   struct BitmapKeyInfo {
90     static inline SparseBitVector<> *getEmptyKey() {
91       return reinterpret_cast<SparseBitVector<> *>(-1);
92     }
93     static inline SparseBitVector<> *getTombstoneKey() {
94       return reinterpret_cast<SparseBitVector<> *>(-2);
95     }
96     static unsigned getHashValue(const SparseBitVector<> *bitmap) {
97       return bitmap->getHashValue();
98     }
99     static bool isEqual(const SparseBitVector<> *LHS,
100                         const SparseBitVector<> *RHS) {
101       if (LHS == RHS)
102         return true;
103       else if (LHS == getEmptyKey() || RHS == getEmptyKey()
104                || LHS == getTombstoneKey() || RHS == getTombstoneKey())
105         return false;
106
107       return *LHS == *RHS;
108     }
109
110     static bool isPod() { return true; }
111   };
112
113   class VISIBILITY_HIDDEN Andersens : public ModulePass, public AliasAnalysis,
114                                       private InstVisitor<Andersens> {
115     class Node;
116
117     /// Constraint - Objects of this structure are used to represent the various
118     /// constraints identified by the algorithm.  The constraints are 'copy',
119     /// for statements like "A = B", 'load' for statements like "A = *B",
120     /// 'store' for statements like "*A = B", and AddressOf for statements like
121     /// A = alloca;  The Offset is applied as *(A + K) = B for stores,
122     /// A = *(B + K) for loads, and A = B + K for copies.  It is
123     /// illegal on addressof constraints (because it is statically
124     /// resolvable to A = &C where C = B + K)
125
126     struct Constraint {
127       enum ConstraintType { Copy, Load, Store, AddressOf } Type;
128       unsigned Dest;
129       unsigned Src;
130       unsigned Offset;
131
132       Constraint(ConstraintType Ty, unsigned D, unsigned S, unsigned O = 0)
133         : Type(Ty), Dest(D), Src(S), Offset(O) {
134         assert(Offset == 0 || Ty != AddressOf &&
135                "Offset is illegal on addressof constraints");
136       }
137       bool operator==(const Constraint &RHS) const {
138         return RHS.Type == Type
139           && RHS.Dest == Dest
140           && RHS.Src == Src
141           && RHS.Offset == Offset;
142       }
143       bool operator<(const Constraint &RHS) const {
144         if (RHS.Type != Type)
145           return RHS.Type < Type;
146         else if (RHS.Dest != Dest)
147           return RHS.Dest < Dest;
148         else if (RHS.Src != Src)
149           return RHS.Src < Src;
150         return RHS.Offset < Offset;
151       }
152     };
153
154     // Node class - This class is used to represent a node in the constraint
155     // graph.  Due to various optimizations, it is not always the case that
156     // there is a mapping from a Node to a Value.  In particular, we add
157     // artificial Node's that represent the set of pointed-to variables shared
158     // for each location equivalent Node.
159     struct Node {
160       Value *Val;
161       SparseBitVector<> *Edges;
162       SparseBitVector<> *PointsTo;
163       SparseBitVector<> *OldPointsTo;
164       bool Changed;
165       std::list<Constraint> Constraints;
166
167       // Pointer and location equivalence labels
168       unsigned PointerEquivLabel;
169       unsigned LocationEquivLabel;
170       // Predecessor edges, both real and implicit
171       SparseBitVector<> *PredEdges;
172       SparseBitVector<> *ImplicitPredEdges;
173       // Set of nodes that point to us, only use for location equivalence.
174       SparseBitVector<> *PointedToBy;
175       // Number of incoming edges, used during variable substitution to early
176       // free the points-to sets
177       unsigned NumInEdges;
178       // True if our points-to set is in the Set2PEClass map
179       bool StoredInHash;
180       // True if our node has no indirect constraints (complex or otherwise)
181       bool Direct;
182       // True if the node is address taken, *or* it is part of a group of nodes
183       // that must be kept together.  This is set to true for functions and
184       // their arg nodes, which must be kept at the same position relative to
185       // their base function node.
186       bool AddressTaken;
187
188       // Nodes in cycles (or in equivalence classes) are united together using a
189       // standard union-find representation with path compression.  NodeRep
190       // gives the index into GraphNodes for the representative Node.
191       unsigned NodeRep;
192     public:
193
194       Node(bool direct = true) :
195         Val(0), Edges(0), PointsTo(0), OldPointsTo(0), Changed(false),
196         PointerEquivLabel(0), LocationEquivLabel(0), PredEdges(0),
197         ImplicitPredEdges(0), PointedToBy(0), NumInEdges(0),
198         StoredInHash(false), Direct(direct), AddressTaken(false),
199         NodeRep(SelfRep) { }
200
201       Node *setValue(Value *V) {
202         assert(Val == 0 && "Value already set for this node!");
203         Val = V;
204         return this;
205       }
206
207       /// getValue - Return the LLVM value corresponding to this node.
208       ///
209       Value *getValue() const { return Val; }
210
211       /// addPointerTo - Add a pointer to the list of pointees of this node,
212       /// returning true if this caused a new pointer to be added, or false if
213       /// we already knew about the points-to relation.
214       bool addPointerTo(unsigned Node) {
215         return PointsTo->test_and_set(Node);
216       }
217
218       /// intersects - Return true if the points-to set of this node intersects
219       /// with the points-to set of the specified node.
220       bool intersects(Node *N) const;
221
222       /// intersectsIgnoring - Return true if the points-to set of this node
223       /// intersects with the points-to set of the specified node on any nodes
224       /// except for the specified node to ignore.
225       bool intersectsIgnoring(Node *N, unsigned) const;
226     };
227
228     /// GraphNodes - This vector is populated as part of the object
229     /// identification stage of the analysis, which populates this vector with a
230     /// node for each memory object and fills in the ValueNodes map.
231     std::vector<Node> GraphNodes;
232
233     /// ValueNodes - This map indicates the Node that a particular Value* is
234     /// represented by.  This contains entries for all pointers.
235     DenseMap<Value*, unsigned> ValueNodes;
236
237     /// ObjectNodes - This map contains entries for each memory object in the
238     /// program: globals, alloca's and mallocs.
239     DenseMap<Value*, unsigned> ObjectNodes;
240
241     /// ReturnNodes - This map contains an entry for each function in the
242     /// program that returns a value.
243     DenseMap<Function*, unsigned> ReturnNodes;
244
245     /// VarargNodes - This map contains the entry used to represent all pointers
246     /// passed through the varargs portion of a function call for a particular
247     /// function.  An entry is not present in this map for functions that do not
248     /// take variable arguments.
249     DenseMap<Function*, unsigned> VarargNodes;
250
251
252     /// Constraints - This vector contains a list of all of the constraints
253     /// identified by the program.
254     std::vector<Constraint> Constraints;
255
256     // Map from graph node to maximum K value that is allowed (for functions,
257     // this is equivalent to the number of arguments + CallFirstArgPos)
258     std::map<unsigned, unsigned> MaxK;
259
260     /// This enum defines the GraphNodes indices that correspond to important
261     /// fixed sets.
262     enum {
263       UniversalSet = 0,
264       NullPtr      = 1,
265       NullObject   = 2,
266       NumberSpecialNodes
267     };
268     // Stack for Tarjan's
269     std::stack<unsigned> SCCStack;
270     // Topological Index -> Graph node
271     std::vector<unsigned> Topo2Node;
272     // Graph Node -> Topological Index;
273     std::vector<unsigned> Node2Topo;
274     // Map from Graph Node to DFS number
275     std::vector<unsigned> Node2DFS;
276     // Map from Graph Node to Deleted from graph.
277     std::vector<bool> Node2Deleted;
278     // Current DFS and RPO numbers
279     unsigned DFSNumber;
280     unsigned RPONumber;
281
282     // Offline variable substitution related things
283
284     // Temporary rep storage, used because we can't collapse SCC's in the
285     // predecessor graph by uniting the variables permanently, we can only do so
286     // for the successor graph.
287     std::vector<unsigned> VSSCCRep;
288     // Mapping from node to whether we have visited it during SCC finding yet.
289     std::vector<bool> Node2Visited;
290     // During variable substitution, we create unknowns to represent the unknown
291     // value that is a dereference of a variable.  These nodes are known as
292     // "ref" nodes (since they represent the value of dereferences).
293     unsigned FirstRefNode;
294     // During HVN, we create represent address taken nodes as if they were
295     // unknown (since HVN, unlike HU, does not evaluate unions).
296     unsigned FirstAdrNode;
297     // Current pointer equivalence class number
298     unsigned PEClass;
299     // Mapping from points-to sets to equivalence classes
300     typedef DenseMap<SparseBitVector<> *, unsigned, BitmapKeyInfo> BitVectorMap;
301     BitVectorMap Set2PEClass;
302     // Mapping from pointer equivalences to the representative node.  -1 if we
303     // have no representative node for this pointer equivalence class yet.
304     std::vector<int> PEClass2Node;
305     // Mapping from pointer equivalences to representative node.  This includes
306     // pointer equivalent but not location equivalent variables. -1 if we have
307     // no representative node for this pointer equivalence class yet.
308     std::vector<int> PENLEClass2Node;
309
310   public:
311     static char ID;
312     Andersens() : ModulePass((intptr_t)&ID) {}
313
314     bool runOnModule(Module &M) {
315       InitializeAliasAnalysis(this);
316       IdentifyObjects(M);
317       CollectConstraints(M);
318 #undef DEBUG_TYPE
319 #define DEBUG_TYPE "anders-aa-constraints"
320       DEBUG(PrintConstraints());
321 #undef DEBUG_TYPE
322 #define DEBUG_TYPE "anders-aa"
323       SolveConstraints();
324       DEBUG(PrintPointsToGraph());
325
326       // Free the constraints list, as we don't need it to respond to alias
327       // requests.
328       ObjectNodes.clear();
329       ReturnNodes.clear();
330       VarargNodes.clear();
331       std::vector<Constraint>().swap(Constraints);
332       return false;
333     }
334
335     void releaseMemory() {
336       // FIXME: Until we have transitively required passes working correctly,
337       // this cannot be enabled!  Otherwise, using -count-aa with the pass
338       // causes memory to be freed too early. :(
339 #if 0
340       // The memory objects and ValueNodes data structures at the only ones that
341       // are still live after construction.
342       std::vector<Node>().swap(GraphNodes);
343       ValueNodes.clear();
344 #endif
345     }
346
347     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
348       AliasAnalysis::getAnalysisUsage(AU);
349       AU.setPreservesAll();                         // Does not transform code
350     }
351
352     //------------------------------------------------
353     // Implement the AliasAnalysis API
354     //
355     AliasResult alias(const Value *V1, unsigned V1Size,
356                       const Value *V2, unsigned V2Size);
357     virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
358     virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
359     void getMustAliases(Value *P, std::vector<Value*> &RetVals);
360     bool pointsToConstantMemory(const Value *P);
361
362     virtual void deleteValue(Value *V) {
363       ValueNodes.erase(V);
364       getAnalysis<AliasAnalysis>().deleteValue(V);
365     }
366
367     virtual void copyValue(Value *From, Value *To) {
368       ValueNodes[To] = ValueNodes[From];
369       getAnalysis<AliasAnalysis>().copyValue(From, To);
370     }
371
372   private:
373     /// getNode - Return the node corresponding to the specified pointer scalar.
374     ///
375     unsigned getNode(Value *V) {
376       if (Constant *C = dyn_cast<Constant>(V))
377         if (!isa<GlobalValue>(C))
378           return getNodeForConstantPointer(C);
379
380       DenseMap<Value*, unsigned>::iterator I = ValueNodes.find(V);
381       if (I == ValueNodes.end()) {
382 #ifndef NDEBUG
383         V->dump();
384 #endif
385         assert(0 && "Value does not have a node in the points-to graph!");
386       }
387       return I->second;
388     }
389
390     /// getObject - Return the node corresponding to the memory object for the
391     /// specified global or allocation instruction.
392     unsigned getObject(Value *V) {
393       DenseMap<Value*, unsigned>::iterator I = ObjectNodes.find(V);
394       assert(I != ObjectNodes.end() &&
395              "Value does not have an object in the points-to graph!");
396       return I->second;
397     }
398
399     /// getReturnNode - Return the node representing the return value for the
400     /// specified function.
401     unsigned getReturnNode(Function *F) {
402       DenseMap<Function*, unsigned>::iterator I = ReturnNodes.find(F);
403       assert(I != ReturnNodes.end() && "Function does not return a value!");
404       return I->second;
405     }
406
407     /// getVarargNode - Return the node representing the variable arguments
408     /// formal for the specified function.
409     unsigned getVarargNode(Function *F) {
410       DenseMap<Function*, unsigned>::iterator I = VarargNodes.find(F);
411       assert(I != VarargNodes.end() && "Function does not take var args!");
412       return I->second;
413     }
414
415     /// getNodeValue - Get the node for the specified LLVM value and set the
416     /// value for it to be the specified value.
417     unsigned getNodeValue(Value &V) {
418       unsigned Index = getNode(&V);
419       GraphNodes[Index].setValue(&V);
420       return Index;
421     }
422
423     unsigned UniteNodes(unsigned First, unsigned Second);
424     unsigned FindNode(unsigned Node);
425
426     void IdentifyObjects(Module &M);
427     void CollectConstraints(Module &M);
428     bool AnalyzeUsesOfFunction(Value *);
429     void CreateConstraintGraph();
430     void OptimizeConstraints();
431     unsigned FindEquivalentNode(unsigned, unsigned);
432     void ClumpAddressTaken();
433     void RewriteConstraints();
434     void HU();
435     void HVN();
436     void UnitePointerEquivalences();
437     void SolveConstraints();
438     void QueryNode(unsigned Node);
439     void Condense(unsigned Node);
440     void HUValNum(unsigned Node);
441     void HVNValNum(unsigned Node);
442     unsigned getNodeForConstantPointer(Constant *C);
443     unsigned getNodeForConstantPointerTarget(Constant *C);
444     void AddGlobalInitializerConstraints(unsigned, Constant *C);
445
446     void AddConstraintsForNonInternalLinkage(Function *F);
447     void AddConstraintsForCall(CallSite CS, Function *F);
448     bool AddConstraintsForExternalCall(CallSite CS, Function *F);
449
450
451     void PrintNode(Node *N);
452     void PrintConstraints();
453     void PrintConstraint(const Constraint &);
454     void PrintLabels();
455     void PrintPointsToGraph();
456
457     //===------------------------------------------------------------------===//
458     // Instruction visitation methods for adding constraints
459     //
460     friend class InstVisitor<Andersens>;
461     void visitReturnInst(ReturnInst &RI);
462     void visitInvokeInst(InvokeInst &II) { visitCallSite(CallSite(&II)); }
463     void visitCallInst(CallInst &CI) { visitCallSite(CallSite(&CI)); }
464     void visitCallSite(CallSite CS);
465     void visitAllocationInst(AllocationInst &AI);
466     void visitLoadInst(LoadInst &LI);
467     void visitStoreInst(StoreInst &SI);
468     void visitGetElementPtrInst(GetElementPtrInst &GEP);
469     void visitPHINode(PHINode &PN);
470     void visitCastInst(CastInst &CI);
471     void visitICmpInst(ICmpInst &ICI) {} // NOOP!
472     void visitFCmpInst(FCmpInst &ICI) {} // NOOP!
473     void visitSelectInst(SelectInst &SI);
474     void visitVAArg(VAArgInst &I);
475     void visitInstruction(Instruction &I);
476
477   };
478
479   char Andersens::ID = 0;
480   RegisterPass<Andersens> X("anders-aa",
481                             "Andersen's Interprocedural Alias Analysis");
482   RegisterAnalysisGroup<AliasAnalysis> Y(X);
483 }
484
485 ModulePass *llvm::createAndersensPass() { return new Andersens(); }
486
487 //===----------------------------------------------------------------------===//
488 //                  AliasAnalysis Interface Implementation
489 //===----------------------------------------------------------------------===//
490
491 AliasAnalysis::AliasResult Andersens::alias(const Value *V1, unsigned V1Size,
492                                             const Value *V2, unsigned V2Size) {
493   Node *N1 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V1)))];
494   Node *N2 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V2)))];
495
496   // Check to see if the two pointers are known to not alias.  They don't alias
497   // if their points-to sets do not intersect.
498   if (!N1->intersectsIgnoring(N2, NullObject))
499     return NoAlias;
500
501   return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
502 }
503
504 AliasAnalysis::ModRefResult
505 Andersens::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
506   // The only thing useful that we can contribute for mod/ref information is
507   // when calling external function calls: if we know that memory never escapes
508   // from the program, it cannot be modified by an external call.
509   //
510   // NOTE: This is not really safe, at least not when the entire program is not
511   // available.  The deal is that the external function could call back into the
512   // program and modify stuff.  We ignore this technical niggle for now.  This
513   // is, after all, a "research quality" implementation of Andersen's analysis.
514   if (Function *F = CS.getCalledFunction())
515     if (F->isDeclaration()) {
516       Node *N1 = &GraphNodes[FindNode(getNode(P))];
517
518       if (N1->PointsTo->empty())
519         return NoModRef;
520
521       if (!N1->PointsTo->test(UniversalSet))
522         return NoModRef;  // P doesn't point to the universal set.
523     }
524
525   return AliasAnalysis::getModRefInfo(CS, P, Size);
526 }
527
528 AliasAnalysis::ModRefResult
529 Andersens::getModRefInfo(CallSite CS1, CallSite CS2) {
530   return AliasAnalysis::getModRefInfo(CS1,CS2);
531 }
532
533 /// getMustAlias - We can provide must alias information if we know that a
534 /// pointer can only point to a specific function or the null pointer.
535 /// Unfortunately we cannot determine must-alias information for global
536 /// variables or any other memory memory objects because we do not track whether
537 /// a pointer points to the beginning of an object or a field of it.
538 void Andersens::getMustAliases(Value *P, std::vector<Value*> &RetVals) {
539   Node *N = &GraphNodes[FindNode(getNode(P))];
540   if (N->PointsTo->count() == 1) {
541     Node *Pointee = &GraphNodes[N->PointsTo->find_first()];
542     // If a function is the only object in the points-to set, then it must be
543     // the destination.  Note that we can't handle global variables here,
544     // because we don't know if the pointer is actually pointing to a field of
545     // the global or to the beginning of it.
546     if (Value *V = Pointee->getValue()) {
547       if (Function *F = dyn_cast<Function>(V))
548         RetVals.push_back(F);
549     } else {
550       // If the object in the points-to set is the null object, then the null
551       // pointer is a must alias.
552       if (Pointee == &GraphNodes[NullObject])
553         RetVals.push_back(Constant::getNullValue(P->getType()));
554     }
555   }
556   AliasAnalysis::getMustAliases(P, RetVals);
557 }
558
559 /// pointsToConstantMemory - If we can determine that this pointer only points
560 /// to constant memory, return true.  In practice, this means that if the
561 /// pointer can only point to constant globals, functions, or the null pointer,
562 /// return true.
563 ///
564 bool Andersens::pointsToConstantMemory(const Value *P) {
565   Node *N = &GraphNodes[FindNode(getNode((Value*)P))];
566   unsigned i;
567
568   for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
569        bi != N->PointsTo->end();
570        ++bi) {
571     i = *bi;
572     Node *Pointee = &GraphNodes[i];
573     if (Value *V = Pointee->getValue()) {
574       if (!isa<GlobalValue>(V) || (isa<GlobalVariable>(V) &&
575                                    !cast<GlobalVariable>(V)->isConstant()))
576         return AliasAnalysis::pointsToConstantMemory(P);
577     } else {
578       if (i != NullObject)
579         return AliasAnalysis::pointsToConstantMemory(P);
580     }
581   }
582
583   return true;
584 }
585
586 //===----------------------------------------------------------------------===//
587 //                       Object Identification Phase
588 //===----------------------------------------------------------------------===//
589
590 /// IdentifyObjects - This stage scans the program, adding an entry to the
591 /// GraphNodes list for each memory object in the program (global stack or
592 /// heap), and populates the ValueNodes and ObjectNodes maps for these objects.
593 ///
594 void Andersens::IdentifyObjects(Module &M) {
595   unsigned NumObjects = 0;
596
597   // Object #0 is always the universal set: the object that we don't know
598   // anything about.
599   assert(NumObjects == UniversalSet && "Something changed!");
600   ++NumObjects;
601
602   // Object #1 always represents the null pointer.
603   assert(NumObjects == NullPtr && "Something changed!");
604   ++NumObjects;
605
606   // Object #2 always represents the null object (the object pointed to by null)
607   assert(NumObjects == NullObject && "Something changed!");
608   ++NumObjects;
609
610   // Add all the globals first.
611   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
612        I != E; ++I) {
613     ObjectNodes[I] = NumObjects++;
614     ValueNodes[I] = NumObjects++;
615   }
616
617   // Add nodes for all of the functions and the instructions inside of them.
618   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
619     // The function itself is a memory object.
620     unsigned First = NumObjects;
621     ValueNodes[F] = NumObjects++;
622     if (isa<PointerType>(F->getFunctionType()->getReturnType()))
623       ReturnNodes[F] = NumObjects++;
624     if (F->getFunctionType()->isVarArg())
625       VarargNodes[F] = NumObjects++;
626
627
628     // Add nodes for all of the incoming pointer arguments.
629     for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
630          I != E; ++I)
631       {
632         if (isa<PointerType>(I->getType()))
633           ValueNodes[I] = NumObjects++;
634       }
635     MaxK[First] = NumObjects - First;
636
637     // Scan the function body, creating a memory object for each heap/stack
638     // allocation in the body of the function and a node to represent all
639     // pointer values defined by instructions and used as operands.
640     for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
641       // If this is an heap or stack allocation, create a node for the memory
642       // object.
643       if (isa<PointerType>(II->getType())) {
644         ValueNodes[&*II] = NumObjects++;
645         if (AllocationInst *AI = dyn_cast<AllocationInst>(&*II))
646           ObjectNodes[AI] = NumObjects++;
647       }
648     }
649   }
650
651   // Now that we know how many objects to create, make them all now!
652   GraphNodes.resize(NumObjects);
653   NumNodes += NumObjects;
654 }
655
656 //===----------------------------------------------------------------------===//
657 //                     Constraint Identification Phase
658 //===----------------------------------------------------------------------===//
659
660 /// getNodeForConstantPointer - Return the node corresponding to the constant
661 /// pointer itself.
662 unsigned Andersens::getNodeForConstantPointer(Constant *C) {
663   assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
664
665   if (isa<ConstantPointerNull>(C) || isa<UndefValue>(C))
666     return NullPtr;
667   else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
668     return getNode(GV);
669   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
670     switch (CE->getOpcode()) {
671     case Instruction::GetElementPtr:
672       return getNodeForConstantPointer(CE->getOperand(0));
673     case Instruction::IntToPtr:
674       return UniversalSet;
675     case Instruction::BitCast:
676       return getNodeForConstantPointer(CE->getOperand(0));
677     default:
678       cerr << "Constant Expr not yet handled: " << *CE << "\n";
679       assert(0);
680     }
681   } else {
682     assert(0 && "Unknown constant pointer!");
683   }
684   return 0;
685 }
686
687 /// getNodeForConstantPointerTarget - Return the node POINTED TO by the
688 /// specified constant pointer.
689 unsigned Andersens::getNodeForConstantPointerTarget(Constant *C) {
690   assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
691
692   if (isa<ConstantPointerNull>(C))
693     return NullObject;
694   else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
695     return getObject(GV);
696   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
697     switch (CE->getOpcode()) {
698     case Instruction::GetElementPtr:
699       return getNodeForConstantPointerTarget(CE->getOperand(0));
700     case Instruction::IntToPtr:
701       return UniversalSet;
702     case Instruction::BitCast:
703       return getNodeForConstantPointerTarget(CE->getOperand(0));
704     default:
705       cerr << "Constant Expr not yet handled: " << *CE << "\n";
706       assert(0);
707     }
708   } else {
709     assert(0 && "Unknown constant pointer!");
710   }
711   return 0;
712 }
713
714 /// AddGlobalInitializerConstraints - Add inclusion constraints for the memory
715 /// object N, which contains values indicated by C.
716 void Andersens::AddGlobalInitializerConstraints(unsigned NodeIndex,
717                                                 Constant *C) {
718   if (C->getType()->isFirstClassType()) {
719     if (isa<PointerType>(C->getType()))
720       Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
721                                        getNodeForConstantPointer(C)));
722   } else if (C->isNullValue()) {
723     Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
724                                      NullObject));
725     return;
726   } else if (!isa<UndefValue>(C)) {
727     // If this is an array or struct, include constraints for each element.
728     assert(isa<ConstantArray>(C) || isa<ConstantStruct>(C));
729     for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
730       AddGlobalInitializerConstraints(NodeIndex,
731                                       cast<Constant>(C->getOperand(i)));
732   }
733 }
734
735 /// AddConstraintsForNonInternalLinkage - If this function does not have
736 /// internal linkage, realize that we can't trust anything passed into or
737 /// returned by this function.
738 void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
739   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
740     if (isa<PointerType>(I->getType()))
741       // If this is an argument of an externally accessible function, the
742       // incoming pointer might point to anything.
743       Constraints.push_back(Constraint(Constraint::Copy, getNode(I),
744                                        UniversalSet));
745 }
746
747 /// AddConstraintsForCall - If this is a call to a "known" function, add the
748 /// constraints and return true.  If this is a call to an unknown function,
749 /// return false.
750 bool Andersens::AddConstraintsForExternalCall(CallSite CS, Function *F) {
751   assert(F->isDeclaration() && "Not an external function!");
752
753   // These functions don't induce any points-to constraints.
754   if (F->getName() == "atoi" || F->getName() == "atof" ||
755       F->getName() == "atol" || F->getName() == "atoll" ||
756       F->getName() == "remove" || F->getName() == "unlink" ||
757       F->getName() == "rename" || F->getName() == "memcmp" ||
758       F->getName() == "llvm.memset.i32" ||
759       F->getName() == "llvm.memset.i64" ||
760       F->getName() == "strcmp" || F->getName() == "strncmp" ||
761       F->getName() == "execl" || F->getName() == "execlp" ||
762       F->getName() == "execle" || F->getName() == "execv" ||
763       F->getName() == "execvp" || F->getName() == "chmod" ||
764       F->getName() == "puts" || F->getName() == "write" ||
765       F->getName() == "open" || F->getName() == "create" ||
766       F->getName() == "truncate" || F->getName() == "chdir" ||
767       F->getName() == "mkdir" || F->getName() == "rmdir" ||
768       F->getName() == "read" || F->getName() == "pipe" ||
769       F->getName() == "wait" || F->getName() == "time" ||
770       F->getName() == "stat" || F->getName() == "fstat" ||
771       F->getName() == "lstat" || F->getName() == "strtod" ||
772       F->getName() == "strtof" || F->getName() == "strtold" ||
773       F->getName() == "fopen" || F->getName() == "fdopen" ||
774       F->getName() == "freopen" ||
775       F->getName() == "fflush" || F->getName() == "feof" ||
776       F->getName() == "fileno" || F->getName() == "clearerr" ||
777       F->getName() == "rewind" || F->getName() == "ftell" ||
778       F->getName() == "ferror" || F->getName() == "fgetc" ||
779       F->getName() == "fgetc" || F->getName() == "_IO_getc" ||
780       F->getName() == "fwrite" || F->getName() == "fread" ||
781       F->getName() == "fgets" || F->getName() == "ungetc" ||
782       F->getName() == "fputc" ||
783       F->getName() == "fputs" || F->getName() == "putc" ||
784       F->getName() == "ftell" || F->getName() == "rewind" ||
785       F->getName() == "_IO_putc" || F->getName() == "fseek" ||
786       F->getName() == "fgetpos" || F->getName() == "fsetpos" ||
787       F->getName() == "printf" || F->getName() == "fprintf" ||
788       F->getName() == "sprintf" || F->getName() == "vprintf" ||
789       F->getName() == "vfprintf" || F->getName() == "vsprintf" ||
790       F->getName() == "scanf" || F->getName() == "fscanf" ||
791       F->getName() == "sscanf" || F->getName() == "__assert_fail" ||
792       F->getName() == "modf")
793     return true;
794
795
796   // These functions do induce points-to edges.
797   if (F->getName() == "llvm.memcpy.i32" || F->getName() == "llvm.memcpy.i64" ||
798       F->getName() == "llvm.memmove.i32" ||F->getName() == "llvm.memmove.i64" ||
799       F->getName() == "memmove") {
800
801     // *Dest = *Src, which requires an artificial graph node to represent the
802     // constraint.  It is broken up into *Dest = temp, temp = *Src
803     unsigned FirstArg = getNode(CS.getArgument(0));
804     unsigned SecondArg = getNode(CS.getArgument(1));
805     unsigned TempArg = GraphNodes.size();
806     GraphNodes.push_back(Node());
807     Constraints.push_back(Constraint(Constraint::Store,
808                                      FirstArg, TempArg));
809     Constraints.push_back(Constraint(Constraint::Load,
810                                      TempArg, SecondArg));
811     return true;
812   }
813
814   // Result = Arg0
815   if (F->getName() == "realloc" || F->getName() == "strchr" ||
816       F->getName() == "strrchr" || F->getName() == "strstr" ||
817       F->getName() == "strtok") {
818     Constraints.push_back(Constraint(Constraint::Copy,
819                                      getNode(CS.getInstruction()),
820                                      getNode(CS.getArgument(0))));
821     return true;
822   }
823
824   return false;
825 }
826
827
828
829 /// AnalyzeUsesOfFunction - Look at all of the users of the specified function.
830 /// If this is used by anything complex (i.e., the address escapes), return
831 /// true.
832 bool Andersens::AnalyzeUsesOfFunction(Value *V) {
833
834   if (!isa<PointerType>(V->getType())) return true;
835
836   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
837     if (dyn_cast<LoadInst>(*UI)) {
838       return false;
839     } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
840       if (V == SI->getOperand(1)) {
841         return false;
842       } else if (SI->getOperand(1)) {
843         return true;  // Storing the pointer
844       }
845     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
846       if (AnalyzeUsesOfFunction(GEP)) return true;
847     } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
848       // Make sure that this is just the function being called, not that it is
849       // passing into the function.
850       for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
851         if (CI->getOperand(i) == V) return true;
852     } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
853       // Make sure that this is just the function being called, not that it is
854       // passing into the function.
855       for (unsigned i = 3, e = II->getNumOperands(); i != e; ++i)
856         if (II->getOperand(i) == V) return true;
857     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
858       if (CE->getOpcode() == Instruction::GetElementPtr ||
859           CE->getOpcode() == Instruction::BitCast) {
860         if (AnalyzeUsesOfFunction(CE))
861           return true;
862       } else {
863         return true;
864       }
865     } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(*UI)) {
866       if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
867         return true;  // Allow comparison against null.
868     } else if (dyn_cast<FreeInst>(*UI)) {
869       return false;
870     } else {
871       return true;
872     }
873   return false;
874 }
875
876 /// CollectConstraints - This stage scans the program, adding a constraint to
877 /// the Constraints list for each instruction in the program that induces a
878 /// constraint, and setting up the initial points-to graph.
879 ///
880 void Andersens::CollectConstraints(Module &M) {
881   // First, the universal set points to itself.
882   Constraints.push_back(Constraint(Constraint::AddressOf, UniversalSet,
883                                    UniversalSet));
884   Constraints.push_back(Constraint(Constraint::Store, UniversalSet,
885                                    UniversalSet));
886
887   // Next, the null pointer points to the null object.
888   Constraints.push_back(Constraint(Constraint::AddressOf, NullPtr, NullObject));
889
890   // Next, add any constraints on global variables and their initializers.
891   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
892        I != E; ++I) {
893     // Associate the address of the global object as pointing to the memory for
894     // the global: &G = <G memory>
895     unsigned ObjectIndex = getObject(I);
896     Node *Object = &GraphNodes[ObjectIndex];
897     Object->setValue(I);
898     Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(*I),
899                                      ObjectIndex));
900
901     if (I->hasInitializer()) {
902       AddGlobalInitializerConstraints(ObjectIndex, I->getInitializer());
903     } else {
904       // If it doesn't have an initializer (i.e. it's defined in another
905       // translation unit), it points to the universal set.
906       Constraints.push_back(Constraint(Constraint::Copy, ObjectIndex,
907                                        UniversalSet));
908     }
909   }
910
911   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
912     // Set up the return value node.
913     if (isa<PointerType>(F->getFunctionType()->getReturnType()))
914       GraphNodes[getReturnNode(F)].setValue(F);
915     if (F->getFunctionType()->isVarArg())
916       GraphNodes[getVarargNode(F)].setValue(F);
917
918     // Set up incoming argument nodes.
919     for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
920          I != E; ++I)
921       if (isa<PointerType>(I->getType()))
922         getNodeValue(*I);
923
924     // At some point we should just add constraints for the escaping functions
925     // at solve time, but this slows down solving. For now, we simply mark
926     // address taken functions as escaping and treat them as external.
927     if (!F->hasInternalLinkage() || AnalyzeUsesOfFunction(F))
928       AddConstraintsForNonInternalLinkage(F);
929
930     if (!F->isDeclaration()) {
931       // Scan the function body, creating a memory object for each heap/stack
932       // allocation in the body of the function and a node to represent all
933       // pointer values defined by instructions and used as operands.
934       visit(F);
935     } else {
936       // External functions that return pointers return the universal set.
937       if (isa<PointerType>(F->getFunctionType()->getReturnType()))
938         Constraints.push_back(Constraint(Constraint::Copy,
939                                          getReturnNode(F),
940                                          UniversalSet));
941
942       // Any pointers that are passed into the function have the universal set
943       // stored into them.
944       for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
945            I != E; ++I)
946         if (isa<PointerType>(I->getType())) {
947           // Pointers passed into external functions could have anything stored
948           // through them.
949           Constraints.push_back(Constraint(Constraint::Store, getNode(I),
950                                            UniversalSet));
951           // Memory objects passed into external function calls can have the
952           // universal set point to them.
953           Constraints.push_back(Constraint(Constraint::Copy,
954                                            UniversalSet,
955                                            getNode(I)));
956         }
957
958       // If this is an external varargs function, it can also store pointers
959       // into any pointers passed through the varargs section.
960       if (F->getFunctionType()->isVarArg())
961         Constraints.push_back(Constraint(Constraint::Store, getVarargNode(F),
962                                          UniversalSet));
963     }
964   }
965   NumConstraints += Constraints.size();
966 }
967
968
969 void Andersens::visitInstruction(Instruction &I) {
970 #ifdef NDEBUG
971   return;          // This function is just a big assert.
972 #endif
973   if (isa<BinaryOperator>(I))
974     return;
975   // Most instructions don't have any effect on pointer values.
976   switch (I.getOpcode()) {
977   case Instruction::Br:
978   case Instruction::Switch:
979   case Instruction::Unwind:
980   case Instruction::Unreachable:
981   case Instruction::Free:
982   case Instruction::ICmp:
983   case Instruction::FCmp:
984     return;
985   default:
986     // Is this something we aren't handling yet?
987     cerr << "Unknown instruction: " << I;
988     abort();
989   }
990 }
991
992 void Andersens::visitAllocationInst(AllocationInst &AI) {
993   unsigned ObjectIndex = getObject(&AI);
994   GraphNodes[ObjectIndex].setValue(&AI);
995   Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(AI),
996                                    ObjectIndex));
997 }
998
999 void Andersens::visitReturnInst(ReturnInst &RI) {
1000   if (RI.getNumOperands() && isa<PointerType>(RI.getOperand(0)->getType()))
1001     // return V   -->   <Copy/retval{F}/v>
1002     Constraints.push_back(Constraint(Constraint::Copy,
1003                                      getReturnNode(RI.getParent()->getParent()),
1004                                      getNode(RI.getOperand(0))));
1005 }
1006
1007 void Andersens::visitLoadInst(LoadInst &LI) {
1008   if (isa<PointerType>(LI.getType()))
1009     // P1 = load P2  -->  <Load/P1/P2>
1010     Constraints.push_back(Constraint(Constraint::Load, getNodeValue(LI),
1011                                      getNode(LI.getOperand(0))));
1012 }
1013
1014 void Andersens::visitStoreInst(StoreInst &SI) {
1015   if (isa<PointerType>(SI.getOperand(0)->getType()))
1016     // store P1, P2  -->  <Store/P2/P1>
1017     Constraints.push_back(Constraint(Constraint::Store,
1018                                      getNode(SI.getOperand(1)),
1019                                      getNode(SI.getOperand(0))));
1020 }
1021
1022 void Andersens::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1023   // P1 = getelementptr P2, ... --> <Copy/P1/P2>
1024   Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(GEP),
1025                                    getNode(GEP.getOperand(0))));
1026 }
1027
1028 void Andersens::visitPHINode(PHINode &PN) {
1029   if (isa<PointerType>(PN.getType())) {
1030     unsigned PNN = getNodeValue(PN);
1031     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1032       // P1 = phi P2, P3  -->  <Copy/P1/P2>, <Copy/P1/P3>, ...
1033       Constraints.push_back(Constraint(Constraint::Copy, PNN,
1034                                        getNode(PN.getIncomingValue(i))));
1035   }
1036 }
1037
1038 void Andersens::visitCastInst(CastInst &CI) {
1039   Value *Op = CI.getOperand(0);
1040   if (isa<PointerType>(CI.getType())) {
1041     if (isa<PointerType>(Op->getType())) {
1042       // P1 = cast P2  --> <Copy/P1/P2>
1043       Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
1044                                        getNode(CI.getOperand(0))));
1045     } else {
1046       // P1 = cast int --> <Copy/P1/Univ>
1047 #if 0
1048       Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
1049                                        UniversalSet));
1050 #else
1051       getNodeValue(CI);
1052 #endif
1053     }
1054   } else if (isa<PointerType>(Op->getType())) {
1055     // int = cast P1 --> <Copy/Univ/P1>
1056 #if 0
1057     Constraints.push_back(Constraint(Constraint::Copy,
1058                                      UniversalSet,
1059                                      getNode(CI.getOperand(0))));
1060 #else
1061     getNode(CI.getOperand(0));
1062 #endif
1063   }
1064 }
1065
1066 void Andersens::visitSelectInst(SelectInst &SI) {
1067   if (isa<PointerType>(SI.getType())) {
1068     unsigned SIN = getNodeValue(SI);
1069     // P1 = select C, P2, P3   ---> <Copy/P1/P2>, <Copy/P1/P3>
1070     Constraints.push_back(Constraint(Constraint::Copy, SIN,
1071                                      getNode(SI.getOperand(1))));
1072     Constraints.push_back(Constraint(Constraint::Copy, SIN,
1073                                      getNode(SI.getOperand(2))));
1074   }
1075 }
1076
1077 void Andersens::visitVAArg(VAArgInst &I) {
1078   assert(0 && "vaarg not handled yet!");
1079 }
1080
1081 /// AddConstraintsForCall - Add constraints for a call with actual arguments
1082 /// specified by CS to the function specified by F.  Note that the types of
1083 /// arguments might not match up in the case where this is an indirect call and
1084 /// the function pointer has been casted.  If this is the case, do something
1085 /// reasonable.
1086 void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
1087   Value *CallValue = CS.getCalledValue();
1088   bool IsDeref = F == NULL;
1089
1090   // If this is a call to an external function, try to handle it directly to get
1091   // some taste of context sensitivity.
1092   if (F && F->isDeclaration() && AddConstraintsForExternalCall(CS, F))
1093     return;
1094
1095   if (isa<PointerType>(CS.getType())) {
1096     unsigned CSN = getNode(CS.getInstruction());
1097     if (!F || isa<PointerType>(F->getFunctionType()->getReturnType())) {
1098       if (IsDeref)
1099         Constraints.push_back(Constraint(Constraint::Load, CSN,
1100                                          getNode(CallValue), CallReturnPos));
1101       else
1102         Constraints.push_back(Constraint(Constraint::Copy, CSN,
1103                                          getNode(CallValue) + CallReturnPos));
1104     } else {
1105       // If the function returns a non-pointer value, handle this just like we
1106       // treat a nonpointer cast to pointer.
1107       Constraints.push_back(Constraint(Constraint::Copy, CSN,
1108                                        UniversalSet));
1109     }
1110   } else if (F && isa<PointerType>(F->getFunctionType()->getReturnType())) {
1111     Constraints.push_back(Constraint(Constraint::Copy,
1112                                      UniversalSet,
1113                                      getNode(CallValue) + CallReturnPos));
1114   }
1115
1116   CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
1117   if (F) {
1118     // Direct Call
1119     Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1120     for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI)
1121       if (isa<PointerType>(AI->getType())) {
1122         if (isa<PointerType>((*ArgI)->getType())) {
1123           // Copy the actual argument into the formal argument.
1124           Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1125                                            getNode(*ArgI)));
1126         } else {
1127           Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1128                                            UniversalSet));
1129         }
1130       } else if (isa<PointerType>((*ArgI)->getType())) {
1131         Constraints.push_back(Constraint(Constraint::Copy,
1132                                          UniversalSet,
1133                                          getNode(*ArgI)));
1134       }
1135   } else {
1136     //Indirect Call
1137     unsigned ArgPos = CallFirstArgPos;
1138     for (; ArgI != ArgE; ++ArgI) {
1139       if (isa<PointerType>((*ArgI)->getType())) {
1140         // Copy the actual argument into the formal argument.
1141         Constraints.push_back(Constraint(Constraint::Store,
1142                                          getNode(CallValue),
1143                                          getNode(*ArgI), ArgPos++));
1144       } else {
1145         Constraints.push_back(Constraint(Constraint::Store,
1146                                          getNode (CallValue),
1147                                          UniversalSet, ArgPos++));
1148       }
1149     }
1150   }
1151   // Copy all pointers passed through the varargs section to the varargs node.
1152   if (F && F->getFunctionType()->isVarArg())
1153     for (; ArgI != ArgE; ++ArgI)
1154       if (isa<PointerType>((*ArgI)->getType()))
1155         Constraints.push_back(Constraint(Constraint::Copy, getVarargNode(F),
1156                                          getNode(*ArgI)));
1157   // If more arguments are passed in than we track, just drop them on the floor.
1158 }
1159
1160 void Andersens::visitCallSite(CallSite CS) {
1161   if (isa<PointerType>(CS.getType()))
1162     getNodeValue(*CS.getInstruction());
1163
1164   if (Function *F = CS.getCalledFunction()) {
1165     AddConstraintsForCall(CS, F);
1166   } else {
1167     AddConstraintsForCall(CS, NULL);
1168   }
1169 }
1170
1171 //===----------------------------------------------------------------------===//
1172 //                         Constraint Solving Phase
1173 //===----------------------------------------------------------------------===//
1174
1175 /// intersects - Return true if the points-to set of this node intersects
1176 /// with the points-to set of the specified node.
1177 bool Andersens::Node::intersects(Node *N) const {
1178   return PointsTo->intersects(N->PointsTo);
1179 }
1180
1181 /// intersectsIgnoring - Return true if the points-to set of this node
1182 /// intersects with the points-to set of the specified node on any nodes
1183 /// except for the specified node to ignore.
1184 bool Andersens::Node::intersectsIgnoring(Node *N, unsigned Ignoring) const {
1185   // TODO: If we are only going to call this with the same value for Ignoring,
1186   // we should move the special values out of the points-to bitmap.
1187   bool WeHadIt = PointsTo->test(Ignoring);
1188   bool NHadIt = N->PointsTo->test(Ignoring);
1189   bool Result = false;
1190   if (WeHadIt)
1191     PointsTo->reset(Ignoring);
1192   if (NHadIt)
1193     N->PointsTo->reset(Ignoring);
1194   Result = PointsTo->intersects(N->PointsTo);
1195   if (WeHadIt)
1196     PointsTo->set(Ignoring);
1197   if (NHadIt)
1198     N->PointsTo->set(Ignoring);
1199   return Result;
1200 }
1201
1202 void dumpToDOUT(SparseBitVector<> *bitmap) {
1203 #ifndef NDEBUG
1204   dump(*bitmap, DOUT);
1205 #endif
1206 }
1207
1208
1209 /// Clump together address taken variables so that the points-to sets use up
1210 /// less space and can be operated on faster.
1211
1212 void Andersens::ClumpAddressTaken() {
1213 #undef DEBUG_TYPE
1214 #define DEBUG_TYPE "anders-aa-renumber"
1215   std::vector<unsigned> Translate;
1216   std::vector<Node> NewGraphNodes;
1217
1218   Translate.resize(GraphNodes.size());
1219   unsigned NewPos = 0;
1220
1221   for (unsigned i = 0; i < Constraints.size(); ++i) {
1222     Constraint &C = Constraints[i];
1223     if (C.Type == Constraint::AddressOf) {
1224       GraphNodes[C.Src].AddressTaken = true;
1225     }
1226   }
1227   for (unsigned i = 0; i < NumberSpecialNodes; ++i) {
1228     unsigned Pos = NewPos++;
1229     Translate[i] = Pos;
1230     NewGraphNodes.push_back(GraphNodes[i]);
1231     DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1232   }
1233
1234   // I believe this ends up being faster than making two vectors and splicing
1235   // them.
1236   for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1237     if (GraphNodes[i].AddressTaken) {
1238       unsigned Pos = NewPos++;
1239       Translate[i] = Pos;
1240       NewGraphNodes.push_back(GraphNodes[i]);
1241       DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1242     }
1243   }
1244
1245   for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1246     if (!GraphNodes[i].AddressTaken) {
1247       unsigned Pos = NewPos++;
1248       Translate[i] = Pos;
1249       NewGraphNodes.push_back(GraphNodes[i]);
1250       DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1251     }
1252   }
1253
1254   for (DenseMap<Value*, unsigned>::iterator Iter = ValueNodes.begin();
1255        Iter != ValueNodes.end();
1256        ++Iter)
1257     Iter->second = Translate[Iter->second];
1258
1259   for (DenseMap<Value*, unsigned>::iterator Iter = ObjectNodes.begin();
1260        Iter != ObjectNodes.end();
1261        ++Iter)
1262     Iter->second = Translate[Iter->second];
1263
1264   for (DenseMap<Function*, unsigned>::iterator Iter = ReturnNodes.begin();
1265        Iter != ReturnNodes.end();
1266        ++Iter)
1267     Iter->second = Translate[Iter->second];
1268
1269   for (DenseMap<Function*, unsigned>::iterator Iter = VarargNodes.begin();
1270        Iter != VarargNodes.end();
1271        ++Iter)
1272     Iter->second = Translate[Iter->second];
1273
1274   for (unsigned i = 0; i < Constraints.size(); ++i) {
1275     Constraint &C = Constraints[i];
1276     C.Src = Translate[C.Src];
1277     C.Dest = Translate[C.Dest];
1278   }
1279
1280   GraphNodes.swap(NewGraphNodes);
1281 #undef DEBUG_TYPE
1282 #define DEBUG_TYPE "anders-aa"
1283 }
1284
1285 /// The technique used here is described in "Exploiting Pointer and Location
1286 /// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1287 /// Analysis Symposium (SAS), August 2007."  It is known as the "HVN" algorithm,
1288 /// and is equivalent to value numbering the collapsed constraint graph without
1289 /// evaluating unions.  This is used as a pre-pass to HU in order to resolve
1290 /// first order pointer dereferences and speed up/reduce memory usage of HU.
1291 /// Running both is equivalent to HRU without the iteration
1292 /// HVN in more detail:
1293 /// Imagine the set of constraints was simply straight line code with no loops
1294 /// (we eliminate cycles, so there are no loops), such as:
1295 /// E = &D
1296 /// E = &C
1297 /// E = F
1298 /// F = G
1299 /// G = F
1300 /// Applying value numbering to this code tells us:
1301 /// G == F == E
1302 ///
1303 /// For HVN, this is as far as it goes.  We assign new value numbers to every
1304 /// "address node", and every "reference node".
1305 /// To get the optimal result for this, we use a DFS + SCC (since all nodes in a
1306 /// cycle must have the same value number since the = operation is really
1307 /// inclusion, not overwrite), and value number nodes we receive points-to sets
1308 /// before we value our own node.
1309 /// The advantage of HU over HVN is that HU considers the inclusion property, so
1310 /// that if you have
1311 /// E = &D
1312 /// E = &C
1313 /// E = F
1314 /// F = G
1315 /// F = &D
1316 /// G = F
1317 /// HU will determine that G == F == E.  HVN will not, because it cannot prove
1318 /// that the points to information ends up being the same because they all
1319 /// receive &D from E anyway.
1320
1321 void Andersens::HVN() {
1322   DOUT << "Beginning HVN\n";
1323   // Build a predecessor graph.  This is like our constraint graph with the
1324   // edges going in the opposite direction, and there are edges for all the
1325   // constraints, instead of just copy constraints.  We also build implicit
1326   // edges for constraints are implied but not explicit.  I.E for the constraint
1327   // a = &b, we add implicit edges *a = b.  This helps us capture more cycles
1328   for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1329     Constraint &C = Constraints[i];
1330     if (C.Type == Constraint::AddressOf) {
1331       GraphNodes[C.Src].AddressTaken = true;
1332       GraphNodes[C.Src].Direct = false;
1333
1334       // Dest = &src edge
1335       unsigned AdrNode = C.Src + FirstAdrNode;
1336       if (!GraphNodes[C.Dest].PredEdges)
1337         GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1338       GraphNodes[C.Dest].PredEdges->set(AdrNode);
1339
1340       // *Dest = src edge
1341       unsigned RefNode = C.Dest + FirstRefNode;
1342       if (!GraphNodes[RefNode].ImplicitPredEdges)
1343         GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1344       GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1345     } else if (C.Type == Constraint::Load) {
1346       if (C.Offset == 0) {
1347         // dest = *src edge
1348         if (!GraphNodes[C.Dest].PredEdges)
1349           GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1350         GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1351       } else {
1352         GraphNodes[C.Dest].Direct = false;
1353       }
1354     } else if (C.Type == Constraint::Store) {
1355       if (C.Offset == 0) {
1356         // *dest = src edge
1357         unsigned RefNode = C.Dest + FirstRefNode;
1358         if (!GraphNodes[RefNode].PredEdges)
1359           GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1360         GraphNodes[RefNode].PredEdges->set(C.Src);
1361       }
1362     } else {
1363       // Dest = Src edge and *Dest = *Src edge
1364       if (!GraphNodes[C.Dest].PredEdges)
1365         GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1366       GraphNodes[C.Dest].PredEdges->set(C.Src);
1367       unsigned RefNode = C.Dest + FirstRefNode;
1368       if (!GraphNodes[RefNode].ImplicitPredEdges)
1369         GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1370       GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1371     }
1372   }
1373   PEClass = 1;
1374   // Do SCC finding first to condense our predecessor graph
1375   DFSNumber = 0;
1376   Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1377   Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1378   Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1379
1380   for (unsigned i = 0; i < FirstRefNode; ++i) {
1381     unsigned Node = VSSCCRep[i];
1382     if (!Node2Visited[Node])
1383       HVNValNum(Node);
1384   }
1385   for (BitVectorMap::iterator Iter = Set2PEClass.begin();
1386        Iter != Set2PEClass.end();
1387        ++Iter)
1388     delete Iter->first;
1389   Set2PEClass.clear();
1390   Node2DFS.clear();
1391   Node2Deleted.clear();
1392   Node2Visited.clear();
1393   DOUT << "Finished HVN\n";
1394
1395 }
1396
1397 /// This is the workhorse of HVN value numbering. We combine SCC finding at the
1398 /// same time because it's easy.
1399 void Andersens::HVNValNum(unsigned NodeIndex) {
1400   unsigned MyDFS = DFSNumber++;
1401   Node *N = &GraphNodes[NodeIndex];
1402   Node2Visited[NodeIndex] = true;
1403   Node2DFS[NodeIndex] = MyDFS;
1404
1405   // First process all our explicit edges
1406   if (N->PredEdges)
1407     for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1408          Iter != N->PredEdges->end();
1409          ++Iter) {
1410       unsigned j = VSSCCRep[*Iter];
1411       if (!Node2Deleted[j]) {
1412         if (!Node2Visited[j])
1413           HVNValNum(j);
1414         if (Node2DFS[NodeIndex] > Node2DFS[j])
1415           Node2DFS[NodeIndex] = Node2DFS[j];
1416       }
1417     }
1418
1419   // Now process all the implicit edges
1420   if (N->ImplicitPredEdges)
1421     for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1422          Iter != N->ImplicitPredEdges->end();
1423          ++Iter) {
1424       unsigned j = VSSCCRep[*Iter];
1425       if (!Node2Deleted[j]) {
1426         if (!Node2Visited[j])
1427           HVNValNum(j);
1428         if (Node2DFS[NodeIndex] > Node2DFS[j])
1429           Node2DFS[NodeIndex] = Node2DFS[j];
1430       }
1431     }
1432
1433   // See if we found any cycles
1434   if (MyDFS == Node2DFS[NodeIndex]) {
1435     while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1436       unsigned CycleNodeIndex = SCCStack.top();
1437       Node *CycleNode = &GraphNodes[CycleNodeIndex];
1438       VSSCCRep[CycleNodeIndex] = NodeIndex;
1439       // Unify the nodes
1440       N->Direct &= CycleNode->Direct;
1441
1442       if (CycleNode->PredEdges) {
1443         if (!N->PredEdges)
1444           N->PredEdges = new SparseBitVector<>;
1445         *(N->PredEdges) |= CycleNode->PredEdges;
1446         delete CycleNode->PredEdges;
1447         CycleNode->PredEdges = NULL;
1448       }
1449       if (CycleNode->ImplicitPredEdges) {
1450         if (!N->ImplicitPredEdges)
1451           N->ImplicitPredEdges = new SparseBitVector<>;
1452         *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1453         delete CycleNode->ImplicitPredEdges;
1454         CycleNode->ImplicitPredEdges = NULL;
1455       }
1456
1457       SCCStack.pop();
1458     }
1459
1460     Node2Deleted[NodeIndex] = true;
1461
1462     if (!N->Direct) {
1463       GraphNodes[NodeIndex].PointerEquivLabel = PEClass++;
1464       return;
1465     }
1466
1467     // Collect labels of successor nodes
1468     bool AllSame = true;
1469     unsigned First = ~0;
1470     SparseBitVector<> *Labels = new SparseBitVector<>;
1471     bool Used = false;
1472
1473     if (N->PredEdges)
1474       for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1475            Iter != N->PredEdges->end();
1476          ++Iter) {
1477         unsigned j = VSSCCRep[*Iter];
1478         unsigned Label = GraphNodes[j].PointerEquivLabel;
1479         // Ignore labels that are equal to us or non-pointers
1480         if (j == NodeIndex || Label == 0)
1481           continue;
1482         if (First == (unsigned)~0)
1483           First = Label;
1484         else if (First != Label)
1485           AllSame = false;
1486         Labels->set(Label);
1487     }
1488
1489     // We either have a non-pointer, a copy of an existing node, or a new node.
1490     // Assign the appropriate pointer equivalence label.
1491     if (Labels->empty()) {
1492       GraphNodes[NodeIndex].PointerEquivLabel = 0;
1493     } else if (AllSame) {
1494       GraphNodes[NodeIndex].PointerEquivLabel = First;
1495     } else {
1496       GraphNodes[NodeIndex].PointerEquivLabel = Set2PEClass[Labels];
1497       if (GraphNodes[NodeIndex].PointerEquivLabel == 0) {
1498         unsigned EquivClass = PEClass++;
1499         Set2PEClass[Labels] = EquivClass;
1500         GraphNodes[NodeIndex].PointerEquivLabel = EquivClass;
1501         Used = true;
1502       }
1503     }
1504     if (!Used)
1505       delete Labels;
1506   } else {
1507     SCCStack.push(NodeIndex);
1508   }
1509 }
1510
1511 /// The technique used here is described in "Exploiting Pointer and Location
1512 /// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1513 /// Analysis Symposium (SAS), August 2007."  It is known as the "HU" algorithm,
1514 /// and is equivalent to value numbering the collapsed constraint graph
1515 /// including evaluating unions.
1516 void Andersens::HU() {
1517   DOUT << "Beginning HU\n";
1518   // Build a predecessor graph.  This is like our constraint graph with the
1519   // edges going in the opposite direction, and there are edges for all the
1520   // constraints, instead of just copy constraints.  We also build implicit
1521   // edges for constraints are implied but not explicit.  I.E for the constraint
1522   // a = &b, we add implicit edges *a = b.  This helps us capture more cycles
1523   for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1524     Constraint &C = Constraints[i];
1525     if (C.Type == Constraint::AddressOf) {
1526       GraphNodes[C.Src].AddressTaken = true;
1527       GraphNodes[C.Src].Direct = false;
1528
1529       GraphNodes[C.Dest].PointsTo->set(C.Src);
1530       // *Dest = src edge
1531       unsigned RefNode = C.Dest + FirstRefNode;
1532       if (!GraphNodes[RefNode].ImplicitPredEdges)
1533         GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1534       GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1535       GraphNodes[C.Src].PointedToBy->set(C.Dest);
1536     } else if (C.Type == Constraint::Load) {
1537       if (C.Offset == 0) {
1538         // dest = *src edge
1539         if (!GraphNodes[C.Dest].PredEdges)
1540           GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1541         GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1542       } else {
1543         GraphNodes[C.Dest].Direct = false;
1544       }
1545     } else if (C.Type == Constraint::Store) {
1546       if (C.Offset == 0) {
1547         // *dest = src edge
1548         unsigned RefNode = C.Dest + FirstRefNode;
1549         if (!GraphNodes[RefNode].PredEdges)
1550           GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1551         GraphNodes[RefNode].PredEdges->set(C.Src);
1552       }
1553     } else {
1554       // Dest = Src edge and *Dest = *Src edg
1555       if (!GraphNodes[C.Dest].PredEdges)
1556         GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1557       GraphNodes[C.Dest].PredEdges->set(C.Src);
1558       unsigned RefNode = C.Dest + FirstRefNode;
1559       if (!GraphNodes[RefNode].ImplicitPredEdges)
1560         GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1561       GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1562     }
1563   }
1564   PEClass = 1;
1565   // Do SCC finding first to condense our predecessor graph
1566   DFSNumber = 0;
1567   Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1568   Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1569   Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1570
1571   for (unsigned i = 0; i < FirstRefNode; ++i) {
1572     if (FindNode(i) == i) {
1573       unsigned Node = VSSCCRep[i];
1574       if (!Node2Visited[Node])
1575         Condense(Node);
1576     }
1577   }
1578
1579   // Reset tables for actual labeling
1580   Node2DFS.clear();
1581   Node2Visited.clear();
1582   Node2Deleted.clear();
1583   // Pre-grow our densemap so that we don't get really bad behavior
1584   Set2PEClass.resize(GraphNodes.size());
1585
1586   // Visit the condensed graph and generate pointer equivalence labels.
1587   Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1588   for (unsigned i = 0; i < FirstRefNode; ++i) {
1589     if (FindNode(i) == i) {
1590       unsigned Node = VSSCCRep[i];
1591       if (!Node2Visited[Node])
1592         HUValNum(Node);
1593     }
1594   }
1595   // PEClass nodes will be deleted by the deleting of N->PointsTo in our caller.
1596   Set2PEClass.clear();
1597   DOUT << "Finished HU\n";
1598 }
1599
1600
1601 /// Implementation of standard Tarjan SCC algorithm as modified by Nuutilla.
1602 void Andersens::Condense(unsigned NodeIndex) {
1603   unsigned MyDFS = DFSNumber++;
1604   Node *N = &GraphNodes[NodeIndex];
1605   Node2Visited[NodeIndex] = true;
1606   Node2DFS[NodeIndex] = MyDFS;
1607
1608   // First process all our explicit edges
1609   if (N->PredEdges)
1610     for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1611          Iter != N->PredEdges->end();
1612          ++Iter) {
1613       unsigned j = VSSCCRep[*Iter];
1614       if (!Node2Deleted[j]) {
1615         if (!Node2Visited[j])
1616           Condense(j);
1617         if (Node2DFS[NodeIndex] > Node2DFS[j])
1618           Node2DFS[NodeIndex] = Node2DFS[j];
1619       }
1620     }
1621
1622   // Now process all the implicit edges
1623   if (N->ImplicitPredEdges)
1624     for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1625          Iter != N->ImplicitPredEdges->end();
1626          ++Iter) {
1627       unsigned j = VSSCCRep[*Iter];
1628       if (!Node2Deleted[j]) {
1629         if (!Node2Visited[j])
1630           Condense(j);
1631         if (Node2DFS[NodeIndex] > Node2DFS[j])
1632           Node2DFS[NodeIndex] = Node2DFS[j];
1633       }
1634     }
1635
1636   // See if we found any cycles
1637   if (MyDFS == Node2DFS[NodeIndex]) {
1638     while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1639       unsigned CycleNodeIndex = SCCStack.top();
1640       Node *CycleNode = &GraphNodes[CycleNodeIndex];
1641       VSSCCRep[CycleNodeIndex] = NodeIndex;
1642       // Unify the nodes
1643       N->Direct &= CycleNode->Direct;
1644
1645       *(N->PointsTo) |= CycleNode->PointsTo;
1646       delete CycleNode->PointsTo;
1647       CycleNode->PointsTo = NULL;
1648       if (CycleNode->PredEdges) {
1649         if (!N->PredEdges)
1650           N->PredEdges = new SparseBitVector<>;
1651         *(N->PredEdges) |= CycleNode->PredEdges;
1652         delete CycleNode->PredEdges;
1653         CycleNode->PredEdges = NULL;
1654       }
1655       if (CycleNode->ImplicitPredEdges) {
1656         if (!N->ImplicitPredEdges)
1657           N->ImplicitPredEdges = new SparseBitVector<>;
1658         *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1659         delete CycleNode->ImplicitPredEdges;
1660         CycleNode->ImplicitPredEdges = NULL;
1661       }
1662       SCCStack.pop();
1663     }
1664
1665     Node2Deleted[NodeIndex] = true;
1666
1667     // Set up number of incoming edges for other nodes
1668     if (N->PredEdges)
1669       for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1670            Iter != N->PredEdges->end();
1671            ++Iter)
1672         ++GraphNodes[VSSCCRep[*Iter]].NumInEdges;
1673   } else {
1674     SCCStack.push(NodeIndex);
1675   }
1676 }
1677
1678 void Andersens::HUValNum(unsigned NodeIndex) {
1679   Node *N = &GraphNodes[NodeIndex];
1680   Node2Visited[NodeIndex] = true;
1681
1682   // Eliminate dereferences of non-pointers for those non-pointers we have
1683   // already identified.  These are ref nodes whose non-ref node:
1684   // 1. Has already been visited determined to point to nothing (and thus, a
1685   // dereference of it must point to nothing)
1686   // 2. Any direct node with no predecessor edges in our graph and with no
1687   // points-to set (since it can't point to anything either, being that it
1688   // receives no points-to sets and has none).
1689   if (NodeIndex >= FirstRefNode) {
1690     unsigned j = VSSCCRep[FindNode(NodeIndex - FirstRefNode)];
1691     if ((Node2Visited[j] && !GraphNodes[j].PointerEquivLabel)
1692         || (GraphNodes[j].Direct && !GraphNodes[j].PredEdges
1693             && GraphNodes[j].PointsTo->empty())){
1694       return;
1695     }
1696   }
1697     // Process all our explicit edges
1698   if (N->PredEdges)
1699     for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1700          Iter != N->PredEdges->end();
1701          ++Iter) {
1702       unsigned j = VSSCCRep[*Iter];
1703       if (!Node2Visited[j])
1704         HUValNum(j);
1705
1706       // If this edge turned out to be the same as us, or got no pointer
1707       // equivalence label (and thus points to nothing) , just decrement our
1708       // incoming edges and continue.
1709       if (j == NodeIndex || GraphNodes[j].PointerEquivLabel == 0) {
1710         --GraphNodes[j].NumInEdges;
1711         continue;
1712       }
1713
1714       *(N->PointsTo) |= GraphNodes[j].PointsTo;
1715
1716       // If we didn't end up storing this in the hash, and we're done with all
1717       // the edges, we don't need the points-to set anymore.
1718       --GraphNodes[j].NumInEdges;
1719       if (!GraphNodes[j].NumInEdges && !GraphNodes[j].StoredInHash) {
1720         delete GraphNodes[j].PointsTo;
1721         GraphNodes[j].PointsTo = NULL;
1722       }
1723     }
1724   // If this isn't a direct node, generate a fresh variable.
1725   if (!N->Direct) {
1726     N->PointsTo->set(FirstRefNode + NodeIndex);
1727   }
1728
1729   // See If we have something equivalent to us, if not, generate a new
1730   // equivalence class.
1731   if (N->PointsTo->empty()) {
1732     delete N->PointsTo;
1733     N->PointsTo = NULL;
1734   } else {
1735     if (N->Direct) {
1736       N->PointerEquivLabel = Set2PEClass[N->PointsTo];
1737       if (N->PointerEquivLabel == 0) {
1738         unsigned EquivClass = PEClass++;
1739         N->StoredInHash = true;
1740         Set2PEClass[N->PointsTo] = EquivClass;
1741         N->PointerEquivLabel = EquivClass;
1742       }
1743     } else {
1744       N->PointerEquivLabel = PEClass++;
1745     }
1746   }
1747 }
1748
1749 /// Rewrite our list of constraints so that pointer equivalent nodes are
1750 /// replaced by their the pointer equivalence class representative.
1751 void Andersens::RewriteConstraints() {
1752   std::vector<Constraint> NewConstraints;
1753   std::set<Constraint> Seen;
1754
1755   PEClass2Node.clear();
1756   PENLEClass2Node.clear();
1757
1758   // We may have from 1 to Graphnodes + 1 equivalence classes.
1759   PEClass2Node.insert(PEClass2Node.begin(), GraphNodes.size() + 1, -1);
1760   PENLEClass2Node.insert(PENLEClass2Node.begin(), GraphNodes.size() + 1, -1);
1761
1762   // Rewrite constraints, ignoring non-pointer constraints, uniting equivalent
1763   // nodes, and rewriting constraints to use the representative nodes.
1764   for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1765     Constraint &C = Constraints[i];
1766     unsigned RHSNode = FindNode(C.Src);
1767     unsigned LHSNode = FindNode(C.Dest);
1768     unsigned RHSLabel = GraphNodes[VSSCCRep[RHSNode]].PointerEquivLabel;
1769     unsigned LHSLabel = GraphNodes[VSSCCRep[LHSNode]].PointerEquivLabel;
1770
1771     // First we try to eliminate constraints for things we can prove don't point
1772     // to anything.
1773     if (LHSLabel == 0) {
1774       DEBUG(PrintNode(&GraphNodes[LHSNode]));
1775       DOUT << " is a non-pointer, ignoring constraint.\n";
1776       continue;
1777     }
1778     if (RHSLabel == 0) {
1779       DEBUG(PrintNode(&GraphNodes[RHSNode]));
1780       DOUT << " is a non-pointer, ignoring constraint.\n";
1781       continue;
1782     }
1783     // This constraint may be useless, and it may become useless as we translate
1784     // it.
1785     if (C.Src == C.Dest && C.Type == Constraint::Copy)
1786       continue;
1787
1788     C.Src = FindEquivalentNode(RHSNode, RHSLabel);
1789     C.Dest = FindEquivalentNode(FindNode(LHSNode), LHSLabel);
1790     if (C.Src == C.Dest && C.Type == Constraint::Copy
1791         || Seen.count(C) != 0)
1792       continue;
1793
1794     Seen.insert(C);
1795     NewConstraints.push_back(C);
1796   }
1797   Constraints.swap(NewConstraints);
1798   PEClass2Node.clear();
1799 }
1800
1801 /// See if we have a node that is pointer equivalent to the one being asked
1802 /// about, and if so, unite them and return the equivalent node.  Otherwise,
1803 /// return the original node.
1804 unsigned Andersens::FindEquivalentNode(unsigned NodeIndex,
1805                                        unsigned NodeLabel) {
1806   if (!GraphNodes[NodeIndex].AddressTaken) {
1807     if (PEClass2Node[NodeLabel] != -1) {
1808       // We found an existing node with the same pointer label, so unify them.
1809       return UniteNodes(PEClass2Node[NodeLabel], NodeIndex);
1810     } else {
1811       PEClass2Node[NodeLabel] = NodeIndex;
1812       PENLEClass2Node[NodeLabel] = NodeIndex;
1813     }
1814   } else if (PENLEClass2Node[NodeLabel] == -1) {
1815     PENLEClass2Node[NodeLabel] = NodeIndex;
1816   }
1817
1818   return NodeIndex;
1819 }
1820
1821 void Andersens::PrintLabels() {
1822   for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1823     if (i < FirstRefNode) {
1824       PrintNode(&GraphNodes[i]);
1825     } else if (i < FirstAdrNode) {
1826       DOUT << "REF(";
1827       PrintNode(&GraphNodes[i-FirstRefNode]);
1828       DOUT <<")";
1829     } else {
1830       DOUT << "ADR(";
1831       PrintNode(&GraphNodes[i-FirstAdrNode]);
1832       DOUT <<")";
1833     }
1834
1835     DOUT << " has pointer label " << GraphNodes[i].PointerEquivLabel
1836          << " and SCC rep " << VSSCCRep[i]
1837          << " and is " << (GraphNodes[i].Direct ? "Direct" : "Not direct")
1838          << "\n";
1839   }
1840 }
1841
1842 /// Optimize the constraints by performing offline variable substitution and
1843 /// other optimizations.
1844 void Andersens::OptimizeConstraints() {
1845   DOUT << "Beginning constraint optimization\n";
1846
1847   // Function related nodes need to stay in the same relative position and can't
1848   // be location equivalent.
1849   for (std::map<unsigned, unsigned>::iterator Iter = MaxK.begin();
1850        Iter != MaxK.end();
1851        ++Iter) {
1852     for (unsigned i = Iter->first;
1853          i != Iter->first + Iter->second;
1854          ++i) {
1855       GraphNodes[i].AddressTaken = true;
1856       GraphNodes[i].Direct = false;
1857     }
1858   }
1859
1860   ClumpAddressTaken();
1861   FirstRefNode = GraphNodes.size();
1862   FirstAdrNode = FirstRefNode + GraphNodes.size();
1863   GraphNodes.insert(GraphNodes.end(), 2 * GraphNodes.size(),
1864                     Node(false));
1865   VSSCCRep.resize(GraphNodes.size());
1866   for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1867     VSSCCRep[i] = i;
1868   }
1869   HVN();
1870   for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1871     Node *N = &GraphNodes[i];
1872     delete N->PredEdges;
1873     N->PredEdges = NULL;
1874     delete N->ImplicitPredEdges;
1875     N->ImplicitPredEdges = NULL;
1876   }
1877 #undef DEBUG_TYPE
1878 #define DEBUG_TYPE "anders-aa-labels"
1879   DEBUG(PrintLabels());
1880 #undef DEBUG_TYPE
1881 #define DEBUG_TYPE "anders-aa"
1882   RewriteConstraints();
1883   // Delete the adr nodes.
1884   GraphNodes.resize(FirstRefNode * 2);
1885
1886   // Now perform HU
1887   for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1888     Node *N = &GraphNodes[i];
1889     if (FindNode(i) == i) {
1890       N->PointsTo = new SparseBitVector<>;
1891       N->PointedToBy = new SparseBitVector<>;
1892       // Reset our labels
1893     }
1894     VSSCCRep[i] = i;
1895     N->PointerEquivLabel = 0;
1896   }
1897   HU();
1898 #undef DEBUG_TYPE
1899 #define DEBUG_TYPE "anders-aa-labels"
1900   DEBUG(PrintLabels());
1901 #undef DEBUG_TYPE
1902 #define DEBUG_TYPE "anders-aa"
1903   RewriteConstraints();
1904   for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1905     if (FindNode(i) == i) {
1906       Node *N = &GraphNodes[i];
1907       delete N->PointsTo;
1908       delete N->PredEdges;
1909       delete N->ImplicitPredEdges;
1910       delete N->PointedToBy;
1911     }
1912   }
1913   GraphNodes.erase(GraphNodes.begin() + FirstRefNode, GraphNodes.end());
1914   DOUT << "Finished constraint optimization\n";
1915   FirstRefNode = 0;
1916   FirstAdrNode = 0;
1917 }
1918
1919 /// Unite pointer but not location equivalent variables, now that the constraint
1920 /// graph is built.
1921 void Andersens::UnitePointerEquivalences() {
1922   DOUT << "Uniting remaining pointer equivalences\n";
1923   for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1924     if (GraphNodes[i].AddressTaken && GraphNodes[i].NodeRep == SelfRep) {
1925       unsigned Label = GraphNodes[i].PointerEquivLabel;
1926
1927       if (Label && PENLEClass2Node[Label] != -1)
1928         UniteNodes(i, PENLEClass2Node[Label]);
1929     }
1930   }
1931   DOUT << "Finished remaining pointer equivalences\n";
1932   PENLEClass2Node.clear();
1933 }
1934
1935 /// Create the constraint graph used for solving points-to analysis.
1936 ///
1937 void Andersens::CreateConstraintGraph() {
1938   for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1939     Constraint &C = Constraints[i];
1940     assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
1941     if (C.Type == Constraint::AddressOf)
1942       GraphNodes[C.Dest].PointsTo->set(C.Src);
1943     else if (C.Type == Constraint::Load)
1944       GraphNodes[C.Src].Constraints.push_back(C);
1945     else if (C.Type == Constraint::Store)
1946       GraphNodes[C.Dest].Constraints.push_back(C);
1947     else if (C.Offset != 0)
1948       GraphNodes[C.Src].Constraints.push_back(C);
1949     else
1950       GraphNodes[C.Src].Edges->set(C.Dest);
1951   }
1952 }
1953
1954 // Perform cycle detection, DFS, and RPO finding.
1955 void Andersens::QueryNode(unsigned Node) {
1956   assert(GraphNodes[Node].NodeRep == SelfRep && "Querying a non-rep node");
1957   unsigned OurDFS = ++DFSNumber;
1958   SparseBitVector<> ToErase;
1959   SparseBitVector<> NewEdges;
1960   Node2DFS[Node] = OurDFS;
1961
1962   for (SparseBitVector<>::iterator bi = GraphNodes[Node].Edges->begin();
1963        bi != GraphNodes[Node].Edges->end();
1964        ++bi) {
1965     unsigned RepNode = FindNode(*bi);
1966     // If we are going to add an edge to repnode, we have no need for the edge
1967     // to e anymore.
1968     if (RepNode != *bi && NewEdges.test(RepNode)){
1969       ToErase.set(*bi);
1970       continue;
1971     }
1972
1973     // Continue about our DFS.
1974     if (!Node2Deleted[RepNode]){
1975       if (Node2DFS[RepNode] == 0) {
1976         QueryNode(RepNode);
1977         // May have been changed by query
1978         RepNode = FindNode(RepNode);
1979       }
1980       if (Node2DFS[RepNode] < Node2DFS[Node])
1981         Node2DFS[Node] = Node2DFS[RepNode];
1982     }
1983     // We may have just discovered that e belongs to a cycle, in which case we
1984     // can also erase it.
1985     if (RepNode != *bi) {
1986       ToErase.set(*bi);
1987       NewEdges.set(RepNode);
1988     }
1989   }
1990
1991   GraphNodes[Node].Edges->intersectWithComplement(ToErase);
1992   GraphNodes[Node].Edges |= NewEdges;
1993
1994   // If this node is a root of a non-trivial SCC, place it on our worklist to be
1995   // processed
1996   if (OurDFS == Node2DFS[Node]) {
1997     bool Changed = false;
1998     while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= OurDFS) {
1999       Node = UniteNodes(Node, FindNode(SCCStack.top()));
2000
2001       SCCStack.pop();
2002       Changed = true;
2003     }
2004     Node2Deleted[Node] = true;
2005     RPONumber++;
2006
2007     Topo2Node.at(GraphNodes.size() - RPONumber) = Node;
2008     Node2Topo[Node] = GraphNodes.size() - RPONumber;
2009     if (Changed)
2010       GraphNodes[Node].Changed = true;
2011   } else {
2012     SCCStack.push(Node);
2013   }
2014 }
2015
2016
2017 /// SolveConstraints - This stage iteratively processes the constraints list
2018 /// propagating constraints (adding edges to the Nodes in the points-to graph)
2019 /// until a fixed point is reached.
2020 ///
2021 void Andersens::SolveConstraints() {
2022   bool Changed = true;
2023   unsigned Iteration = 0;
2024
2025   OptimizeConstraints();
2026 #undef DEBUG_TYPE
2027 #define DEBUG_TYPE "anders-aa-constraints"
2028       DEBUG(PrintConstraints());
2029 #undef DEBUG_TYPE
2030 #define DEBUG_TYPE "anders-aa"
2031
2032   for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2033     Node *N = &GraphNodes[i];
2034     N->PointsTo = new SparseBitVector<>;
2035     N->OldPointsTo = new SparseBitVector<>;
2036     N->Edges = new SparseBitVector<>;
2037   }
2038   CreateConstraintGraph();
2039   UnitePointerEquivalences();
2040   assert(SCCStack.empty() && "SCC Stack should be empty by now!");
2041   Topo2Node.insert(Topo2Node.begin(), GraphNodes.size(), Unvisited);
2042   Node2Topo.insert(Node2Topo.begin(), GraphNodes.size(), Unvisited);
2043   Node2DFS.clear();
2044   Node2Deleted.clear();
2045   Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2046   Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2047   DFSNumber = 0;
2048   RPONumber = 0;
2049   // Order graph and mark starting nodes as changed.
2050   for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2051     unsigned N = FindNode(i);
2052     Node *INode = &GraphNodes[i];
2053     if (Node2DFS[N] == 0) {
2054       QueryNode(N);
2055       // Mark as changed if it's a representation and can contribute to the
2056       // calculation right now.
2057       if (INode->NodeRep == SelfRep && !INode->PointsTo->empty()
2058           && (!INode->Edges->empty() || !INode->Constraints.empty()))
2059         INode->Changed = true;
2060     }
2061   }
2062
2063   do {
2064     Changed = false;
2065     ++NumIters;
2066     DOUT << "Starting iteration #" << Iteration++ << "\n";
2067     // TODO: In the microoptimization category, we could just make Topo2Node
2068     // a fast map and thus only contain the visited nodes.
2069     for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2070       unsigned CurrNodeIndex = Topo2Node[i];
2071       Node *CurrNode;
2072
2073       // We may not revisit all nodes on every iteration
2074       if (CurrNodeIndex == Unvisited)
2075         continue;
2076       CurrNode = &GraphNodes[CurrNodeIndex];
2077       // See if this is a node we need to process on this iteration
2078       if (!CurrNode->Changed || CurrNode->NodeRep != SelfRep)
2079         continue;
2080       CurrNode->Changed = false;
2081
2082       // Figure out the changed points to bits
2083       SparseBitVector<> CurrPointsTo;
2084       CurrPointsTo.intersectWithComplement(CurrNode->PointsTo,
2085                                            CurrNode->OldPointsTo);
2086       if (CurrPointsTo.empty()){
2087         continue;
2088       }
2089       *(CurrNode->OldPointsTo) |= CurrPointsTo;
2090
2091       /* Now process the constraints for this node.  */
2092       for (std::list<Constraint>::iterator li = CurrNode->Constraints.begin();
2093            li != CurrNode->Constraints.end(); ) {
2094         li->Src = FindNode(li->Src);
2095         li->Dest = FindNode(li->Dest);
2096
2097         // TODO: We could delete redundant constraints here.
2098         // Src and Dest will be the vars we are going to process.
2099         // This may look a bit ugly, but what it does is allow us to process
2100         // both store and load constraints with the same code.
2101         // Load constraints say that every member of our RHS solution has K
2102         // added to it, and that variable gets an edge to LHS. We also union
2103         // RHS+K's solution into the LHS solution.
2104         // Store constraints say that every member of our LHS solution has K
2105         // added to it, and that variable gets an edge from RHS. We also union
2106         // RHS's solution into the LHS+K solution.
2107         unsigned *Src;
2108         unsigned *Dest;
2109         unsigned K = li->Offset;
2110         unsigned CurrMember;
2111         if (li->Type == Constraint::Load) {
2112           Src = &CurrMember;
2113           Dest = &li->Dest;
2114         } else if (li->Type == Constraint::Store) {
2115           Src = &li->Src;
2116           Dest = &CurrMember;
2117         } else {
2118           // TODO Handle offseted copy constraint
2119           li++;
2120           continue;
2121         }
2122         // TODO: hybrid cycle detection would go here, we should check
2123         // if it was a statically detected offline equivalence that
2124         // involves pointers , and if so, remove the redundant constraints.
2125
2126         const SparseBitVector<> &Solution = CurrPointsTo;
2127
2128         for (SparseBitVector<>::iterator bi = Solution.begin();
2129              bi != Solution.end();
2130              ++bi) {
2131           CurrMember = *bi;
2132
2133           // Need to increment the member by K since that is where we are
2134           // supposed to copy to/from.  Note that in positive weight cycles,
2135           // which occur in address taking of fields, K can go past
2136           // MaxK[CurrMember] elements, even though that is all it could point
2137           // to.
2138           if (K > 0 && K > MaxK[CurrMember])
2139             continue;
2140           else
2141             CurrMember = FindNode(CurrMember + K);
2142
2143           // Add an edge to the graph, so we can just do regular bitmap ior next
2144           // time.  It may also let us notice a cycle.
2145           if (GraphNodes[*Src].Edges->test_and_set(*Dest)) {
2146             if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo)) {
2147               GraphNodes[*Dest].Changed = true;
2148               // If we changed a node we've already processed, we need another
2149               // iteration.
2150               if (Node2Topo[*Dest] <= i)
2151                 Changed = true;
2152             }
2153           }
2154         }
2155         li++;
2156       }
2157       SparseBitVector<> NewEdges;
2158       SparseBitVector<> ToErase;
2159
2160       // Now all we have left to do is propagate points-to info along the
2161       // edges, erasing the redundant edges.
2162
2163
2164       for (SparseBitVector<>::iterator bi = CurrNode->Edges->begin();
2165            bi != CurrNode->Edges->end();
2166            ++bi) {
2167
2168         unsigned DestVar = *bi;
2169         unsigned Rep = FindNode(DestVar);
2170
2171         // If we ended up with this node as our destination, or we've already
2172         // got an edge for the representative, delete the current edge.
2173         if (Rep == CurrNodeIndex ||
2174             (Rep != DestVar && NewEdges.test(Rep))) {
2175           ToErase.set(DestVar);
2176           continue;
2177         }
2178         // Union the points-to sets into the dest
2179         if (GraphNodes[Rep].PointsTo |= CurrPointsTo) {
2180           GraphNodes[Rep].Changed = true;
2181           if (Node2Topo[Rep] <= i)
2182             Changed = true;
2183         }
2184         // If this edge's destination was collapsed, rewrite the edge.
2185         if (Rep != DestVar) {
2186           ToErase.set(DestVar);
2187           NewEdges.set(Rep);
2188         }
2189       }
2190       CurrNode->Edges->intersectWithComplement(ToErase);
2191       CurrNode->Edges |= NewEdges;
2192     }
2193     if (Changed) {
2194       DFSNumber = RPONumber = 0;
2195       Node2Deleted.clear();
2196       Topo2Node.clear();
2197       Node2Topo.clear();
2198       Node2DFS.clear();
2199       Topo2Node.insert(Topo2Node.begin(), GraphNodes.size(), Unvisited);
2200       Node2Topo.insert(Node2Topo.begin(), GraphNodes.size(), Unvisited);
2201       Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2202       Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2203       // Rediscover the DFS/Topo ordering, and cycle detect.
2204       for (unsigned j = 0; j < GraphNodes.size(); j++) {
2205         unsigned JRep = FindNode(j);
2206         if (Node2DFS[JRep] == 0)
2207           QueryNode(JRep);
2208       }
2209     }
2210
2211   } while (Changed);
2212
2213   Node2Topo.clear();
2214   Topo2Node.clear();
2215   Node2DFS.clear();
2216   Node2Deleted.clear();
2217   for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2218     Node *N = &GraphNodes[i];
2219     delete N->OldPointsTo;
2220     delete N->Edges;
2221   }
2222 }
2223
2224 //===----------------------------------------------------------------------===//
2225 //                               Union-Find
2226 //===----------------------------------------------------------------------===//
2227
2228 // Unite nodes First and Second, returning the one which is now the
2229 // representative node.  First and Second are indexes into GraphNodes
2230 unsigned Andersens::UniteNodes(unsigned First, unsigned Second) {
2231   assert (First < GraphNodes.size() && Second < GraphNodes.size() &&
2232           "Attempting to merge nodes that don't exist");
2233   // TODO: implement union by rank
2234   Node *FirstNode = &GraphNodes[First];
2235   Node *SecondNode = &GraphNodes[Second];
2236
2237   assert (SecondNode->NodeRep == SelfRep && FirstNode->NodeRep == SelfRep &&
2238           "Trying to unite two non-representative nodes!");
2239   if (First == Second)
2240     return First;
2241
2242   SecondNode->NodeRep = First;
2243   FirstNode->Changed |= SecondNode->Changed;
2244   if (FirstNode->PointsTo && SecondNode->PointsTo)
2245     FirstNode->PointsTo |= *(SecondNode->PointsTo);
2246   if (FirstNode->Edges && SecondNode->Edges)
2247     FirstNode->Edges |= *(SecondNode->Edges);
2248   if (!FirstNode->Constraints.empty() && !SecondNode->Constraints.empty())
2249     FirstNode->Constraints.splice(FirstNode->Constraints.begin(),
2250                                   SecondNode->Constraints);
2251   if (FirstNode->OldPointsTo) {
2252     delete FirstNode->OldPointsTo;
2253     FirstNode->OldPointsTo = new SparseBitVector<>;
2254   }
2255
2256   // Destroy interesting parts of the merged-from node.
2257   delete SecondNode->OldPointsTo;
2258   delete SecondNode->Edges;
2259   delete SecondNode->PointsTo;
2260   SecondNode->Edges = NULL;
2261   SecondNode->PointsTo = NULL;
2262   SecondNode->OldPointsTo = NULL;
2263
2264   NumUnified++;
2265   DOUT << "Unified Node ";
2266   DEBUG(PrintNode(FirstNode));
2267   DOUT << " and Node ";
2268   DEBUG(PrintNode(SecondNode));
2269   DOUT << "\n";
2270
2271   // TODO: Handle SDT
2272   return First;
2273 }
2274
2275 // Find the index into GraphNodes of the node representing Node, performing
2276 // path compression along the way
2277 unsigned Andersens::FindNode(unsigned NodeIndex) {
2278   assert (NodeIndex < GraphNodes.size()
2279           && "Attempting to find a node that can't exist");
2280   Node *N = &GraphNodes[NodeIndex];
2281   if (N->NodeRep == SelfRep)
2282     return NodeIndex;
2283   else
2284     return (N->NodeRep = FindNode(N->NodeRep));
2285 }
2286
2287 //===----------------------------------------------------------------------===//
2288 //                               Debugging Output
2289 //===----------------------------------------------------------------------===//
2290
2291 void Andersens::PrintNode(Node *N) {
2292   if (N == &GraphNodes[UniversalSet]) {
2293     cerr << "<universal>";
2294     return;
2295   } else if (N == &GraphNodes[NullPtr]) {
2296     cerr << "<nullptr>";
2297     return;
2298   } else if (N == &GraphNodes[NullObject]) {
2299     cerr << "<null>";
2300     return;
2301   }
2302   if (!N->getValue()) {
2303     cerr << "artificial" << (intptr_t) N;
2304     return;
2305   }
2306
2307   assert(N->getValue() != 0 && "Never set node label!");
2308   Value *V = N->getValue();
2309   if (Function *F = dyn_cast<Function>(V)) {
2310     if (isa<PointerType>(F->getFunctionType()->getReturnType()) &&
2311         N == &GraphNodes[getReturnNode(F)]) {
2312       cerr << F->getName() << ":retval";
2313       return;
2314     } else if (F->getFunctionType()->isVarArg() &&
2315                N == &GraphNodes[getVarargNode(F)]) {
2316       cerr << F->getName() << ":vararg";
2317       return;
2318     }
2319   }
2320
2321   if (Instruction *I = dyn_cast<Instruction>(V))
2322     cerr << I->getParent()->getParent()->getName() << ":";
2323   else if (Argument *Arg = dyn_cast<Argument>(V))
2324     cerr << Arg->getParent()->getName() << ":";
2325
2326   if (V->hasName())
2327     cerr << V->getName();
2328   else
2329     cerr << "(unnamed)";
2330
2331   if (isa<GlobalValue>(V) || isa<AllocationInst>(V))
2332     if (N == &GraphNodes[getObject(V)])
2333       cerr << "<mem>";
2334 }
2335 void Andersens::PrintConstraint(const Constraint &C) {
2336   if (C.Type == Constraint::Store) {
2337     cerr << "*";
2338     if (C.Offset != 0)
2339       cerr << "(";
2340   }
2341   PrintNode(&GraphNodes[C.Dest]);
2342   if (C.Type == Constraint::Store && C.Offset != 0)
2343     cerr << " + " << C.Offset << ")";
2344   cerr << " = ";
2345   if (C.Type == Constraint::Load) {
2346     cerr << "*";
2347     if (C.Offset != 0)
2348       cerr << "(";
2349   }
2350   else if (C.Type == Constraint::AddressOf)
2351     cerr << "&";
2352   PrintNode(&GraphNodes[C.Src]);
2353   if (C.Offset != 0 && C.Type != Constraint::Store)
2354     cerr << " + " << C.Offset;
2355   if (C.Type == Constraint::Load && C.Offset != 0)
2356     cerr << ")";
2357   cerr << "\n";
2358 }
2359
2360 void Andersens::PrintConstraints() {
2361   cerr << "Constraints:\n";
2362
2363   for (unsigned i = 0, e = Constraints.size(); i != e; ++i)
2364     PrintConstraint(Constraints[i]);
2365 }
2366
2367 void Andersens::PrintPointsToGraph() {
2368   cerr << "Points-to graph:\n";
2369   for (unsigned i = 0, e = GraphNodes.size(); i != e; ++i) {
2370     Node *N = &GraphNodes[i];
2371     if (FindNode (i) != i) {
2372       PrintNode(N);
2373       cerr << "\t--> same as ";
2374       PrintNode(&GraphNodes[FindNode(i)]);
2375       cerr << "\n";
2376     } else {
2377       cerr << "[" << (N->PointsTo->count()) << "] ";
2378       PrintNode(N);
2379       cerr << "\t--> ";
2380
2381       bool first = true;
2382       for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
2383            bi != N->PointsTo->end();
2384            ++bi) {
2385         if (!first)
2386           cerr << ", ";
2387         PrintNode(&GraphNodes[*bi]);
2388         first = false;
2389       }
2390       cerr << "\n";
2391     }
2392   }
2393 }