LLVM API Documentation

Andersens.cpp

Go to the documentation of this file.
00001 //===- Andersens.cpp - Andersen's Interprocedural Alias Analysis ----------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file defines an implementation of Andersen's interprocedural alias
00011 // analysis
00012 //
00013 // In pointer analysis terms, this is a subset-based, flow-insensitive,
00014 // field-sensitive, and context-insensitive algorithm pointer algorithm.
00015 //
00016 // This algorithm is implemented as three stages:
00017 //   1. Object identification.
00018 //   2. Inclusion constraint identification.
00019 //   3. Offline constraint graph optimization
00020 //   4. Inclusion constraint solving.
00021 //
00022 // The object identification stage identifies all of the memory objects in the
00023 // program, which includes globals, heap allocated objects, and stack allocated
00024 // objects.
00025 //
00026 // The inclusion constraint identification stage finds all inclusion constraints
00027 // in the program by scanning the program, looking for pointer assignments and
00028 // other statements that effect the points-to graph.  For a statement like "A =
00029 // B", this statement is processed to indicate that A can point to anything that
00030 // B can point to.  Constraints can handle copies, loads, and stores, and
00031 // address taking.
00032 //
00033 // The offline constraint graph optimization portion includes offline variable
00034 // substitution algorithms intended to compute pointer and location
00035 // equivalences.  Pointer equivalences are those pointers that will have the
00036 // same points-to sets, and location equivalences are those variables that
00037 // always appear together in points-to sets.  It also includes an offline
00038 // cycle detection algorithm that allows cycles to be collapsed sooner 
00039 // during solving.
00040 //
00041 // The inclusion constraint solving phase iteratively propagates the inclusion
00042 // constraints until a fixed point is reached.  This is an O(N^3) algorithm.
00043 //
00044 // Function constraints are handled as if they were structs with X fields.
00045 // Thus, an access to argument X of function Y is an access to node index
00046 // getNode(Y) + X.  This representation allows handling of indirect calls
00047 // without any issues.  To wit, an indirect call Y(a,b) is equivalent to
00048 // *(Y + 1) = a, *(Y + 2) = b.
00049 // The return node for a function is always located at getNode(F) +
00050 // CallReturnPos. The arguments start at getNode(F) + CallArgPos.
00051 //
00052 // Future Improvements:
00053 //   Use of BDD's.
00054 //===----------------------------------------------------------------------===//
00055 
00056 #define DEBUG_TYPE "anders-aa"
00057 #include "llvm/Constants.h"
00058 #include "llvm/DerivedTypes.h"
00059 #include "llvm/Instructions.h"
00060 #include "llvm/Module.h"
00061 #include "llvm/Pass.h"
00062 #include "llvm/Support/Compiler.h"
00063 #include "llvm/Support/InstIterator.h"
00064 #include "llvm/Support/InstVisitor.h"
00065 #include "llvm/Analysis/AliasAnalysis.h"
00066 #include "llvm/Analysis/Passes.h"
00067 #include "llvm/Support/Debug.h"
00068 #include "llvm/ADT/Statistic.h"
00069 #include "llvm/ADT/SparseBitVector.h"
00070 #include "llvm/ADT/DenseSet.h"
00071 #include <algorithm>
00072 #include <set>
00073 #include <list>
00074 #include <map>
00075 #include <stack>
00076 #include <vector>
00077 #include <queue>
00078 
00079 // Determining the actual set of nodes the universal set can consist of is very
00080 // expensive because it means propagating around very large sets.  We rely on
00081 // other analysis being able to determine which nodes can never be pointed to in
00082 // order to disambiguate further than "points-to anything".
00083 #define FULL_UNIVERSAL 0
00084 
00085 using namespace llvm;
00086 STATISTIC(NumIters      , "Number of iterations to reach convergence");
00087 STATISTIC(NumConstraints, "Number of constraints");
00088 STATISTIC(NumNodes      , "Number of nodes");
00089 STATISTIC(NumUnified    , "Number of variables unified");
00090 STATISTIC(NumErased     , "Number of redundant constraints erased");
00091 
00092 static const unsigned SelfRep = (unsigned)-1;
00093 static const unsigned Unvisited = (unsigned)-1;
00094 // Position of the function return node relative to the function node.
00095 static const unsigned CallReturnPos = 1;
00096 // Position of the function call node relative to the function node.
00097 static const unsigned CallFirstArgPos = 2;
00098 
00099 namespace {
00100   struct BitmapKeyInfo {
00101     static inline SparseBitVector<> *getEmptyKey() {
00102       return reinterpret_cast<SparseBitVector<> *>(-1);
00103     }
00104     static inline SparseBitVector<> *getTombstoneKey() {
00105       return reinterpret_cast<SparseBitVector<> *>(-2);
00106     }
00107     static unsigned getHashValue(const SparseBitVector<> *bitmap) {
00108       return bitmap->getHashValue();
00109     }
00110     static bool isEqual(const SparseBitVector<> *LHS,
00111                         const SparseBitVector<> *RHS) {
00112       if (LHS == RHS)
00113         return true;
00114       else if (LHS == getEmptyKey() || RHS == getEmptyKey()
00115                || LHS == getTombstoneKey() || RHS == getTombstoneKey())
00116         return false;
00117 
00118       return *LHS == *RHS;
00119     }
00120 
00121     static bool isPod() { return true; }
00122   };
00123 
00124   class VISIBILITY_HIDDEN Andersens : public ModulePass, public AliasAnalysis,
00125                                       private InstVisitor<Andersens> {
00126     struct Node;
00127 
00128     /// Constraint - Objects of this structure are used to represent the various
00129     /// constraints identified by the algorithm.  The constraints are 'copy',
00130     /// for statements like "A = B", 'load' for statements like "A = *B",
00131     /// 'store' for statements like "*A = B", and AddressOf for statements like
00132     /// A = alloca;  The Offset is applied as *(A + K) = B for stores,
00133     /// A = *(B + K) for loads, and A = B + K for copies.  It is
00134     /// illegal on addressof constraints (because it is statically
00135     /// resolvable to A = &C where C = B + K)
00136 
00137     struct Constraint {
00138       enum ConstraintType { Copy, Load, Store, AddressOf } Type;
00139       unsigned Dest;
00140       unsigned Src;
00141       unsigned Offset;
00142 
00143       Constraint(ConstraintType Ty, unsigned D, unsigned S, unsigned O = 0)
00144         : Type(Ty), Dest(D), Src(S), Offset(O) {
00145         assert((Offset == 0 || Ty != AddressOf) &&
00146                "Offset is illegal on addressof constraints");
00147       }
00148 
00149       bool operator==(const Constraint &RHS) const {
00150         return RHS.Type == Type
00151           && RHS.Dest == Dest
00152           && RHS.Src == Src
00153           && RHS.Offset == Offset;
00154       }
00155 
00156       bool operator!=(const Constraint &RHS) const {
00157         return !(*this == RHS);
00158       }
00159 
00160       bool operator<(const Constraint &RHS) const {
00161         if (RHS.Type != Type)
00162           return RHS.Type < Type;
00163         else if (RHS.Dest != Dest)
00164           return RHS.Dest < Dest;
00165         else if (RHS.Src != Src)
00166           return RHS.Src < Src;
00167         return RHS.Offset < Offset;
00168       }
00169     };
00170 
00171     // Information DenseSet requires implemented in order to be able to do
00172     // it's thing
00173     struct PairKeyInfo {
00174       static inline std::pair<unsigned, unsigned> getEmptyKey() {
00175         return std::make_pair(~0U, ~0U);
00176       }
00177       static inline std::pair<unsigned, unsigned> getTombstoneKey() {
00178         return std::make_pair(~0U - 1, ~0U - 1);
00179       }
00180       static unsigned getHashValue(const std::pair<unsigned, unsigned> &P) {
00181         return P.first ^ P.second;
00182       }
00183       static unsigned isEqual(const std::pair<unsigned, unsigned> &LHS,
00184                               const std::pair<unsigned, unsigned> &RHS) {
00185         return LHS == RHS;
00186       }
00187     };
00188     
00189     struct ConstraintKeyInfo {
00190       static inline Constraint getEmptyKey() {
00191         return Constraint(Constraint::Copy, ~0U, ~0U, ~0U);
00192       }
00193       static inline Constraint getTombstoneKey() {
00194         return Constraint(Constraint::Copy, ~0U - 1, ~0U - 1, ~0U - 1);
00195       }
00196       static unsigned getHashValue(const Constraint &C) {
00197         return C.Src ^ C.Dest ^ C.Type ^ C.Offset;
00198       }
00199       static bool isEqual(const Constraint &LHS,
00200                           const Constraint &RHS) {
00201         return LHS.Type == RHS.Type && LHS.Dest == RHS.Dest
00202           && LHS.Src == RHS.Src && LHS.Offset == RHS.Offset;
00203       }
00204     };
00205 
00206     // Node class - This class is used to represent a node in the constraint
00207     // graph.  Due to various optimizations, it is not always the case that
00208     // there is a mapping from a Node to a Value.  In particular, we add
00209     // artificial Node's that represent the set of pointed-to variables shared
00210     // for each location equivalent Node.
00211     struct Node {
00212     private:
00213       static unsigned Counter;
00214 
00215     public:
00216       Value *Val;
00217       SparseBitVector<> *Edges;
00218       SparseBitVector<> *PointsTo;
00219       SparseBitVector<> *OldPointsTo;
00220       std::list<Constraint> Constraints;
00221 
00222       // Pointer and location equivalence labels
00223       unsigned PointerEquivLabel;
00224       unsigned LocationEquivLabel;
00225       // Predecessor edges, both real and implicit
00226       SparseBitVector<> *PredEdges;
00227       SparseBitVector<> *ImplicitPredEdges;
00228       // Set of nodes that point to us, only use for location equivalence.
00229       SparseBitVector<> *PointedToBy;
00230       // Number of incoming edges, used during variable substitution to early
00231       // free the points-to sets
00232       unsigned NumInEdges;
00233       // True if our points-to set is in the Set2PEClass map
00234       bool StoredInHash;
00235       // True if our node has no indirect constraints (complex or otherwise)
00236       bool Direct;
00237       // True if the node is address taken, *or* it is part of a group of nodes
00238       // that must be kept together.  This is set to true for functions and
00239       // their arg nodes, which must be kept at the same position relative to
00240       // their base function node.
00241       bool AddressTaken;
00242 
00243       // Nodes in cycles (or in equivalence classes) are united together using a
00244       // standard union-find representation with path compression.  NodeRep
00245       // gives the index into GraphNodes for the representative Node.
00246       unsigned NodeRep;
00247 
00248       // Modification timestamp.  Assigned from Counter.
00249       // Used for work list prioritization.
00250       unsigned Timestamp;
00251 
00252       explicit Node(bool direct = true) :
00253         Val(0), Edges(0), PointsTo(0), OldPointsTo(0), 
00254         PointerEquivLabel(0), LocationEquivLabel(0), PredEdges(0),
00255         ImplicitPredEdges(0), PointedToBy(0), NumInEdges(0),
00256         StoredInHash(false), Direct(direct), AddressTaken(false),
00257         NodeRep(SelfRep), Timestamp(0) { }
00258 
00259       Node *setValue(Value *V) {
00260         assert(Val == 0 && "Value already set for this node!");
00261         Val = V;
00262         return this;
00263       }
00264 
00265       /// getValue - Return the LLVM value corresponding to this node.
00266       ///
00267       Value *getValue() const { return Val; }
00268 
00269       /// addPointerTo - Add a pointer to the list of pointees of this node,
00270       /// returning true if this caused a new pointer to be added, or false if
00271       /// we already knew about the points-to relation.
00272       bool addPointerTo(unsigned Node) {
00273         return PointsTo->test_and_set(Node);
00274       }
00275 
00276       /// intersects - Return true if the points-to set of this node intersects
00277       /// with the points-to set of the specified node.
00278       bool intersects(Node *N) const;
00279 
00280       /// intersectsIgnoring - Return true if the points-to set of this node
00281       /// intersects with the points-to set of the specified node on any nodes
00282       /// except for the specified node to ignore.
00283       bool intersectsIgnoring(Node *N, unsigned) const;
00284 
00285       // Timestamp a node (used for work list prioritization)
00286       void Stamp() {
00287         Timestamp = Counter++;
00288       }
00289 
00290       bool isRep() const {
00291         return( (int) NodeRep < 0 );
00292       }
00293     };
00294 
00295     struct WorkListElement {
00296       Node* node;
00297       unsigned Timestamp;
00298       WorkListElement(Node* n, unsigned t) : node(n), Timestamp(t) {}
00299 
00300       // Note that we reverse the sense of the comparison because we
00301       // actually want to give low timestamps the priority over high,
00302       // whereas priority is typically interpreted as a greater value is
00303       // given high priority.
00304       bool operator<(const WorkListElement& that) const {
00305         return( this->Timestamp > that.Timestamp );
00306       }
00307     };
00308 
00309     // Priority-queue based work list specialized for Nodes.
00310     class WorkList {
00311       std::priority_queue<WorkListElement> Q;
00312 
00313     public:
00314       void insert(Node* n) {
00315         Q.push( WorkListElement(n, n->Timestamp) );
00316       }
00317 
00318       // We automatically discard non-representative nodes and nodes
00319       // that were in the work list twice (we keep a copy of the
00320       // timestamp in the work list so we can detect this situation by
00321       // comparing against the node's current timestamp).
00322       Node* pop() {
00323         while( !Q.empty() ) {
00324           WorkListElement x = Q.top(); Q.pop();
00325           Node* INode = x.node;
00326 
00327           if( INode->isRep() &&
00328               INode->Timestamp == x.Timestamp ) {
00329             return(x.node);
00330           }
00331         }
00332         return(0);
00333       }
00334 
00335       bool empty() {
00336         return Q.empty();
00337       }
00338     };
00339 
00340     /// GraphNodes - This vector is populated as part of the object
00341     /// identification stage of the analysis, which populates this vector with a
00342     /// node for each memory object and fills in the ValueNodes map.
00343     std::vector<Node> GraphNodes;
00344 
00345     /// ValueNodes - This map indicates the Node that a particular Value* is
00346     /// represented by.  This contains entries for all pointers.
00347     DenseMap<Value*, unsigned> ValueNodes;
00348 
00349     /// ObjectNodes - This map contains entries for each memory object in the
00350     /// program: globals, alloca's and mallocs.
00351     DenseMap<Value*, unsigned> ObjectNodes;
00352 
00353     /// ReturnNodes - This map contains an entry for each function in the
00354     /// program that returns a value.
00355     DenseMap<Function*, unsigned> ReturnNodes;
00356 
00357     /// VarargNodes - This map contains the entry used to represent all pointers
00358     /// passed through the varargs portion of a function call for a particular
00359     /// function.  An entry is not present in this map for functions that do not
00360     /// take variable arguments.
00361     DenseMap<Function*, unsigned> VarargNodes;
00362 
00363 
00364     /// Constraints - This vector contains a list of all of the constraints
00365     /// identified by the program.
00366     std::vector<Constraint> Constraints;
00367 
00368     // Map from graph node to maximum K value that is allowed (for functions,
00369     // this is equivalent to the number of arguments + CallFirstArgPos)
00370     std::map<unsigned, unsigned> MaxK;
00371 
00372     /// This enum defines the GraphNodes indices that correspond to important
00373     /// fixed sets.
00374     enum {
00375       UniversalSet = 0,
00376       NullPtr      = 1,
00377       NullObject   = 2,
00378       NumberSpecialNodes
00379     };
00380     // Stack for Tarjan's
00381     std::stack<unsigned> SCCStack;
00382     // Map from Graph Node to DFS number
00383     std::vector<unsigned> Node2DFS;
00384     // Map from Graph Node to Deleted from graph.
00385     std::vector<bool> Node2Deleted;
00386     // Same as Node Maps, but implemented as std::map because it is faster to
00387     // clear 
00388     std::map<unsigned, unsigned> Tarjan2DFS;
00389     std::map<unsigned, bool> Tarjan2Deleted;
00390     // Current DFS number
00391     unsigned DFSNumber;
00392 
00393     // Work lists.
00394     WorkList w1, w2;
00395     WorkList *CurrWL, *NextWL; // "current" and "next" work lists
00396 
00397     // Offline variable substitution related things
00398 
00399     // Temporary rep storage, used because we can't collapse SCC's in the
00400     // predecessor graph by uniting the variables permanently, we can only do so
00401     // for the successor graph.
00402     std::vector<unsigned> VSSCCRep;
00403     // Mapping from node to whether we have visited it during SCC finding yet.
00404     std::vector<bool> Node2Visited;
00405     // During variable substitution, we create unknowns to represent the unknown
00406     // value that is a dereference of a variable.  These nodes are known as
00407     // "ref" nodes (since they represent the value of dereferences).
00408     unsigned FirstRefNode;
00409     // During HVN, we create represent address taken nodes as if they were
00410     // unknown (since HVN, unlike HU, does not evaluate unions).
00411     unsigned FirstAdrNode;
00412     // Current pointer equivalence class number
00413     unsigned PEClass;
00414     // Mapping from points-to sets to equivalence classes
00415     typedef DenseMap<SparseBitVector<> *, unsigned, BitmapKeyInfo> BitVectorMap;
00416     BitVectorMap Set2PEClass;
00417     // Mapping from pointer equivalences to the representative node.  -1 if we
00418     // have no representative node for this pointer equivalence class yet.
00419     std::vector<int> PEClass2Node;
00420     // Mapping from pointer equivalences to representative node.  This includes
00421     // pointer equivalent but not location equivalent variables. -1 if we have
00422     // no representative node for this pointer equivalence class yet.
00423     std::vector<int> PENLEClass2Node;
00424     // Union/Find for HCD
00425     std::vector<unsigned> HCDSCCRep;
00426     // HCD's offline-detected cycles; "Statically DeTected"
00427     // -1 if not part of such a cycle, otherwise a representative node.
00428     std::vector<int> SDT;
00429     // Whether to use SDT (UniteNodes can use it during solving, but not before)
00430     bool SDTActive;
00431 
00432   public:
00433     static char ID;
00434     Andersens() : ModulePass(&ID) {}
00435 
00436     bool runOnModule(Module &M) {
00437       InitializeAliasAnalysis(this);
00438       IdentifyObjects(M);
00439       CollectConstraints(M);
00440 #undef DEBUG_TYPE
00441 #define DEBUG_TYPE "anders-aa-constraints"
00442       DEBUG(PrintConstraints());
00443 #undef DEBUG_TYPE
00444 #define DEBUG_TYPE "anders-aa"
00445       SolveConstraints();
00446       DEBUG(PrintPointsToGraph());
00447 
00448       // Free the constraints list, as we don't need it to respond to alias
00449       // requests.
00450       std::vector<Constraint>().swap(Constraints);
00451       //These are needed for Print() (-analyze in opt)
00452       //ObjectNodes.clear();
00453       //ReturnNodes.clear();
00454       //VarargNodes.clear();
00455       return false;
00456     }
00457 
00458     void releaseMemory() {
00459       // FIXME: Until we have transitively required passes working correctly,
00460       // this cannot be enabled!  Otherwise, using -count-aa with the pass
00461       // causes memory to be freed too early. :(
00462 #if 0
00463       // The memory objects and ValueNodes data structures at the only ones that
00464       // are still live after construction.
00465       std::vector<Node>().swap(GraphNodes);
00466       ValueNodes.clear();
00467 #endif
00468     }
00469 
00470     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00471       AliasAnalysis::getAnalysisUsage(AU);
00472       AU.setPreservesAll();                         // Does not transform code
00473     }
00474 
00475     //------------------------------------------------
00476     // Implement the AliasAnalysis API
00477     //
00478     AliasResult alias(const Value *V1, unsigned V1Size,
00479                       const Value *V2, unsigned V2Size);
00480     virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
00481     virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
00482     void getMustAliases(Value *P, std::vector<Value*> &RetVals);
00483     bool pointsToConstantMemory(const Value *P);
00484 
00485     virtual void deleteValue(Value *V) {
00486       ValueNodes.erase(V);
00487       getAnalysis<AliasAnalysis>().deleteValue(V);
00488     }
00489 
00490     virtual void copyValue(Value *From, Value *To) {
00491       ValueNodes[To] = ValueNodes[From];
00492       getAnalysis<AliasAnalysis>().copyValue(From, To);
00493     }
00494 
00495   private:
00496     /// getNode - Return the node corresponding to the specified pointer scalar.
00497     ///
00498     unsigned getNode(Value *V) {
00499       if (Constant *C = dyn_cast<Constant>(V))
00500         if (!isa<GlobalValue>(C))
00501           return getNodeForConstantPointer(C);
00502 
00503       DenseMap<Value*, unsigned>::iterator I = ValueNodes.find(V);
00504       if (I == ValueNodes.end()) {
00505 #ifndef NDEBUG
00506         V->dump();
00507 #endif
00508         assert(0 && "Value does not have a node in the points-to graph!");
00509       }
00510       return I->second;
00511     }
00512 
00513     /// getObject - Return the node corresponding to the memory object for the
00514     /// specified global or allocation instruction.
00515     unsigned getObject(Value *V) const {
00516       DenseMap<Value*, unsigned>::iterator I = ObjectNodes.find(V);
00517       assert(I != ObjectNodes.end() &&
00518              "Value does not have an object in the points-to graph!");
00519       return I->second;
00520     }
00521 
00522     /// getReturnNode - Return the node representing the return value for the
00523     /// specified function.
00524     unsigned getReturnNode(Function *F) const {
00525       DenseMap<Function*, unsigned>::iterator I = ReturnNodes.find(F);
00526       assert(I != ReturnNodes.end() && "Function does not return a value!");
00527       return I->second;
00528     }
00529 
00530     /// getVarargNode - Return the node representing the variable arguments
00531     /// formal for the specified function.
00532     unsigned getVarargNode(Function *F) const {
00533       DenseMap<Function*, unsigned>::iterator I = VarargNodes.find(F);
00534       assert(I != VarargNodes.end() && "Function does not take var args!");
00535       return I->second;
00536     }
00537 
00538     /// getNodeValue - Get the node for the specified LLVM value and set the
00539     /// value for it to be the specified value.
00540     unsigned getNodeValue(Value &V) {
00541       unsigned Index = getNode(&V);
00542       GraphNodes[Index].setValue(&V);
00543       return Index;
00544     }
00545 
00546     unsigned UniteNodes(unsigned First, unsigned Second,
00547                         bool UnionByRank = true);
00548     unsigned FindNode(unsigned Node);
00549     unsigned FindNode(unsigned Node) const;
00550 
00551     void IdentifyObjects(Module &M);
00552     void CollectConstraints(Module &M);
00553     bool AnalyzeUsesOfFunction(Value *);
00554     void CreateConstraintGraph();
00555     void OptimizeConstraints();
00556     unsigned FindEquivalentNode(unsigned, unsigned);
00557     void ClumpAddressTaken();
00558     void RewriteConstraints();
00559     void HU();
00560     void HVN();
00561     void HCD();
00562     void Search(unsigned Node);
00563     void UnitePointerEquivalences();
00564     void SolveConstraints();
00565     bool QueryNode(unsigned Node);
00566     void Condense(unsigned Node);
00567     void HUValNum(unsigned Node);
00568     void HVNValNum(unsigned Node);
00569     unsigned getNodeForConstantPointer(Constant *C);
00570     unsigned getNodeForConstantPointerTarget(Constant *C);
00571     void AddGlobalInitializerConstraints(unsigned, Constant *C);
00572 
00573     void AddConstraintsForNonInternalLinkage(Function *F);
00574     void AddConstraintsForCall(CallSite CS, Function *F);
00575     bool AddConstraintsForExternalCall(CallSite CS, Function *F);
00576 
00577 
00578     void PrintNode(const Node *N) const;
00579     void PrintConstraints() const ;
00580     void PrintConstraint(const Constraint &) const;
00581     void PrintLabels() const;
00582     void PrintPointsToGraph() const;
00583 
00584     //===------------------------------------------------------------------===//
00585     // Instruction visitation methods for adding constraints
00586     //
00587     friend class InstVisitor<Andersens>;
00588     void visitReturnInst(ReturnInst &RI);
00589     void visitInvokeInst(InvokeInst &II) { visitCallSite(CallSite(&II)); }
00590     void visitCallInst(CallInst &CI) { visitCallSite(CallSite(&CI)); }
00591     void visitCallSite(CallSite CS);
00592     void visitAllocationInst(AllocationInst &AI);
00593     void visitLoadInst(LoadInst &LI);
00594     void visitStoreInst(StoreInst &SI);
00595     void visitGetElementPtrInst(GetElementPtrInst &GEP);
00596     void visitPHINode(PHINode &PN);
00597     void visitCastInst(CastInst &CI);
00598     void visitICmpInst(ICmpInst &ICI) {} // NOOP!
00599     void visitFCmpInst(FCmpInst &ICI) {} // NOOP!
00600     void visitSelectInst(SelectInst &SI);
00601     void visitVAArg(VAArgInst &I);
00602     void visitInstruction(Instruction &I);
00603 
00604     //===------------------------------------------------------------------===//
00605     // Implement Analyize interface
00606     //
00607     void print(std::ostream &O, const Module* M) const {
00608       PrintPointsToGraph();
00609     }
00610   };
00611 }
00612 
00613 char Andersens::ID = 0;
00614 static RegisterPass<Andersens>
00615 X("anders-aa", "Andersen's Interprocedural Alias Analysis", false, true);
00616 static RegisterAnalysisGroup<AliasAnalysis> Y(X);
00617 
00618 // Initialize Timestamp Counter (static).
00619 unsigned Andersens::Node::Counter = 0;
00620 
00621 ModulePass *llvm::createAndersensPass() { return new Andersens(); }
00622 
00623 //===----------------------------------------------------------------------===//
00624 //                  AliasAnalysis Interface Implementation
00625 //===----------------------------------------------------------------------===//
00626 
00627 AliasAnalysis::AliasResult Andersens::alias(const Value *V1, unsigned V1Size,
00628                                             const Value *V2, unsigned V2Size) {
00629   Node *N1 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V1)))];
00630   Node *N2 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V2)))];
00631 
00632   // Check to see if the two pointers are known to not alias.  They don't alias
00633   // if their points-to sets do not intersect.
00634   if (!N1->intersectsIgnoring(N2, NullObject))
00635     return NoAlias;
00636 
00637   return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
00638 }
00639 
00640 AliasAnalysis::ModRefResult
00641 Andersens::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
00642   // The only thing useful that we can contribute for mod/ref information is
00643   // when calling external function calls: if we know that memory never escapes
00644   // from the program, it cannot be modified by an external call.
00645   //
00646   // NOTE: This is not really safe, at least not when the entire program is not
00647   // available.  The deal is that the external function could call back into the
00648   // program and modify stuff.  We ignore this technical niggle for now.  This
00649   // is, after all, a "research quality" implementation of Andersen's analysis.
00650   if (Function *F = CS.getCalledFunction())
00651     if (F->isDeclaration()) {
00652       Node *N1 = &GraphNodes[FindNode(getNode(P))];
00653 
00654       if (N1->PointsTo->empty())
00655         return NoModRef;
00656 #if FULL_UNIVERSAL
00657       if (!UniversalSet->PointsTo->test(FindNode(getNode(P))))
00658         return NoModRef;  // Universal set does not contain P
00659 #else
00660       if (!N1->PointsTo->test(UniversalSet))
00661         return NoModRef;  // P doesn't point to the universal set.
00662 #endif
00663     }
00664 
00665   return AliasAnalysis::getModRefInfo(CS, P, Size);
00666 }
00667 
00668 AliasAnalysis::ModRefResult
00669 Andersens::getModRefInfo(CallSite CS1, CallSite CS2) {
00670   return AliasAnalysis::getModRefInfo(CS1,CS2);
00671 }
00672 
00673 /// getMustAlias - We can provide must alias information if we know that a
00674 /// pointer can only point to a specific function or the null pointer.
00675 /// Unfortunately we cannot determine must-alias information for global
00676 /// variables or any other memory memory objects because we do not track whether
00677 /// a pointer points to the beginning of an object or a field of it.
00678 void Andersens::getMustAliases(Value *P, std::vector<Value*> &RetVals) {
00679   Node *N = &GraphNodes[FindNode(getNode(P))];
00680   if (N->PointsTo->count() == 1) {
00681     Node *Pointee = &GraphNodes[N->PointsTo->find_first()];
00682     // If a function is the only object in the points-to set, then it must be
00683     // the destination.  Note that we can't handle global variables here,
00684     // because we don't know if the pointer is actually pointing to a field of
00685     // the global or to the beginning of it.
00686     if (Value *V = Pointee->getValue()) {
00687       if (Function *F = dyn_cast<Function>(V))
00688         RetVals.push_back(F);
00689     } else {
00690       // If the object in the points-to set is the null object, then the null
00691       // pointer is a must alias.
00692       if (Pointee == &GraphNodes[NullObject])
00693         RetVals.push_back(Constant::getNullValue(P->getType()));
00694     }
00695   }
00696   AliasAnalysis::getMustAliases(P, RetVals);
00697 }
00698 
00699 /// pointsToConstantMemory - If we can determine that this pointer only points
00700 /// to constant memory, return true.  In practice, this means that if the
00701 /// pointer can only point to constant globals, functions, or the null pointer,
00702 /// return true.
00703 ///
00704 bool Andersens::pointsToConstantMemory(const Value *P) {
00705   Node *N = &GraphNodes[FindNode(getNode(const_cast<Value*>(P)))];
00706   unsigned i;
00707 
00708   for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
00709        bi != N->PointsTo->end();
00710        ++bi) {
00711     i = *bi;
00712     Node *Pointee = &GraphNodes[i];
00713     if (Value *V = Pointee->getValue()) {
00714       if (!isa<GlobalValue>(V) || (isa<GlobalVariable>(V) &&
00715                                    !cast<GlobalVariable>(V)->isConstant()))
00716         return AliasAnalysis::pointsToConstantMemory(P);
00717     } else {
00718       if (i != NullObject)
00719         return AliasAnalysis::pointsToConstantMemory(P);
00720     }
00721   }
00722 
00723   return true;
00724 }
00725 
00726 //===----------------------------------------------------------------------===//
00727 //                       Object Identification Phase
00728 //===----------------------------------------------------------------------===//
00729 
00730 /// IdentifyObjects - This stage scans the program, adding an entry to the
00731 /// GraphNodes list for each memory object in the program (global stack or
00732 /// heap), and populates the ValueNodes and ObjectNodes maps for these objects.
00733 ///
00734 void Andersens::IdentifyObjects(Module &M) {
00735   unsigned NumObjects = 0;
00736 
00737   // Object #0 is always the universal set: the object that we don't know
00738   // anything about.
00739   assert(NumObjects == UniversalSet && "Something changed!");
00740   ++NumObjects;
00741 
00742   // Object #1 always represents the null pointer.
00743   assert(NumObjects == NullPtr && "Something changed!");
00744   ++NumObjects;
00745 
00746   // Object #2 always represents the null object (the object pointed to by null)
00747   assert(NumObjects == NullObject && "Something changed!");
00748   ++NumObjects;
00749 
00750   // Add all the globals first.
00751   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
00752        I != E; ++I) {
00753     ObjectNodes[I] = NumObjects++;
00754     ValueNodes[I] = NumObjects++;
00755   }
00756 
00757   // Add nodes for all of the functions and the instructions inside of them.
00758   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
00759     // The function itself is a memory object.
00760     unsigned First = NumObjects;
00761     ValueNodes[F] = NumObjects++;
00762     if (isa<PointerType>(F->getFunctionType()->getReturnType()))
00763       ReturnNodes[F] = NumObjects++;
00764     if (F->getFunctionType()->isVarArg())
00765       VarargNodes[F] = NumObjects++;
00766 
00767 
00768     // Add nodes for all of the incoming pointer arguments.
00769     for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
00770          I != E; ++I)
00771       {
00772         if (isa<PointerType>(I->getType()))
00773           ValueNodes[I] = NumObjects++;
00774       }
00775     MaxK[First] = NumObjects - First;
00776 
00777     // Scan the function body, creating a memory object for each heap/stack
00778     // allocation in the body of the function and a node to represent all
00779     // pointer values defined by instructions and used as operands.
00780     for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
00781       // If this is an heap or stack allocation, create a node for the memory
00782       // object.
00783       if (isa<PointerType>(II->getType())) {
00784         ValueNodes[&*II] = NumObjects++;
00785         if (AllocationInst *AI = dyn_cast<AllocationInst>(&*II))
00786           ObjectNodes[AI] = NumObjects++;
00787       }
00788 
00789       // Calls to inline asm need to be added as well because the callee isn't
00790       // referenced anywhere else.
00791       if (CallInst *CI = dyn_cast<CallInst>(&*II)) {
00792         Value *Callee = CI->getCalledValue();
00793         if (isa<InlineAsm>(Callee))
00794           ValueNodes[Callee] = NumObjects++;
00795       }
00796     }
00797   }
00798 
00799   // Now that we know how many objects to create, make them all now!
00800   GraphNodes.resize(NumObjects);
00801   NumNodes += NumObjects;
00802 }
00803 
00804 //===----------------------------------------------------------------------===//
00805 //                     Constraint Identification Phase
00806 //===----------------------------------------------------------------------===//
00807 
00808 /// getNodeForConstantPointer - Return the node corresponding to the constant
00809 /// pointer itself.
00810 unsigned Andersens::getNodeForConstantPointer(Constant *C) {
00811   assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
00812 
00813   if (isa<ConstantPointerNull>(C) || isa<UndefValue>(C))
00814     return NullPtr;
00815   else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
00816     return getNode(GV);
00817   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
00818     switch (CE->getOpcode()) {
00819     case Instruction::GetElementPtr:
00820       return getNodeForConstantPointer(CE->getOperand(0));
00821     case Instruction::IntToPtr:
00822       return UniversalSet;
00823     case Instruction::BitCast:
00824       return getNodeForConstantPointer(CE->getOperand(0));
00825     default:
00826       cerr << "Constant Expr not yet handled: " << *CE << "\n";
00827       assert(0);
00828     }
00829   } else {
00830     assert(0 && "Unknown constant pointer!");
00831   }
00832   return 0;
00833 }
00834 
00835 /// getNodeForConstantPointerTarget - Return the node POINTED TO by the
00836 /// specified constant pointer.
00837 unsigned Andersens::getNodeForConstantPointerTarget(Constant *C) {
00838   assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
00839 
00840   if (isa<ConstantPointerNull>(C))
00841     return NullObject;
00842   else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
00843     return getObject(GV);
00844   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
00845     switch (CE->getOpcode()) {
00846     case Instruction::GetElementPtr:
00847       return getNodeForConstantPointerTarget(CE->getOperand(0));
00848     case Instruction::IntToPtr:
00849       return UniversalSet;
00850     case Instruction::BitCast:
00851       return getNodeForConstantPointerTarget(CE->getOperand(0));
00852     default:
00853       cerr << "Constant Expr not yet handled: " << *CE << "\n";
00854       assert(0);
00855     }
00856   } else {
00857     assert(0 && "Unknown constant pointer!");
00858   }
00859   return 0;
00860 }
00861 
00862 /// AddGlobalInitializerConstraints - Add inclusion constraints for the memory
00863 /// object N, which contains values indicated by C.
00864 void Andersens::AddGlobalInitializerConstraints(unsigned NodeIndex,
00865                                                 Constant *C) {
00866   if (C->getType()->isSingleValueType()) {
00867     if (isa<PointerType>(C->getType()))
00868       Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
00869                                        getNodeForConstantPointer(C)));
00870   } else if (C->isNullValue()) {
00871     Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
00872                                      NullObject));
00873     return;
00874   } else if (!isa<UndefValue>(C)) {
00875     // If this is an array or struct, include constraints for each element.
00876     assert(isa<ConstantArray>(C) || isa<ConstantStruct>(C));
00877     for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
00878       AddGlobalInitializerConstraints(NodeIndex,
00879                                       cast<Constant>(C->getOperand(i)));
00880   }
00881 }
00882 
00883 /// AddConstraintsForNonInternalLinkage - If this function does not have
00884 /// internal linkage, realize that we can't trust anything passed into or
00885 /// returned by this function.
00886 void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
00887   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
00888     if (isa<PointerType>(I->getType()))
00889       // If this is an argument of an externally accessible function, the
00890       // incoming pointer might point to anything.
00891       Constraints.push_back(Constraint(Constraint::Copy, getNode(I),
00892                                        UniversalSet));
00893 }
00894 
00895 /// AddConstraintsForCall - If this is a call to a "known" function, add the
00896 /// constraints and return true.  If this is a call to an unknown function,
00897 /// return false.
00898 bool Andersens::AddConstraintsForExternalCall(CallSite CS, Function *F) {
00899   assert(F->isDeclaration() && "Not an external function!");
00900 
00901   // These functions don't induce any points-to constraints.
00902   if (F->getName() == "atoi" || F->getName() == "atof" ||
00903       F->getName() == "atol" || F->getName() == "atoll" ||
00904       F->getName() == "remove" || F->getName() == "unlink" ||
00905       F->getName() == "rename" || F->getName() == "memcmp" ||
00906       F->getName() == "llvm.memset" ||
00907       F->getName() == "strcmp" || F->getName() == "strncmp" ||
00908       F->getName() == "execl" || F->getName() == "execlp" ||
00909       F->getName() == "execle" || F->getName() == "execv" ||
00910       F->getName() == "execvp" || F->getName() == "chmod" ||
00911       F->getName() == "puts" || F->getName() == "write" ||
00912       F->getName() == "open" || F->getName() == "create" ||
00913       F->getName() == "truncate" || F->getName() == "chdir" ||
00914       F->getName() == "mkdir" || F->getName() == "rmdir" ||
00915       F->getName() == "read" || F->getName() == "pipe" ||
00916       F->getName() == "wait" || F->getName() == "time" ||
00917       F->getName() == "stat" || F->getName() == "fstat" ||
00918       F->getName() == "lstat" || F->getName() == "strtod" ||
00919       F->getName() == "strtof" || F->getName() == "strtold" ||
00920       F->getName() == "fopen" || F->getName() == "fdopen" ||
00921       F->getName() == "freopen" ||
00922       F->getName() == "fflush" || F->getName() == "feof" ||
00923       F->getName() == "fileno" || F->getName() == "clearerr" ||
00924       F->getName() == "rewind" || F->getName() == "ftell" ||
00925       F->getName() == "ferror" || F->getName() == "fgetc" ||
00926       F->getName() == "fgetc" || F->getName() == "_IO_getc" ||
00927       F->getName() == "fwrite" || F->getName() == "fread" ||
00928       F->getName() == "fgets" || F->getName() == "ungetc" ||
00929       F->getName() == "fputc" ||
00930       F->getName() == "fputs" || F->getName() == "putc" ||
00931       F->getName() == "ftell" || F->getName() == "rewind" ||
00932       F->getName() == "_IO_putc" || F->getName() == "fseek" ||
00933       F->getName() == "fgetpos" || F->getName() == "fsetpos" ||
00934       F->getName() == "printf" || F->getName() == "fprintf" ||
00935       F->getName() == "sprintf" || F->getName() == "vprintf" ||
00936       F->getName() == "vfprintf" || F->getName() == "vsprintf" ||
00937       F->getName() == "scanf" || F->getName() == "fscanf" ||
00938       F->getName() == "sscanf" || F->getName() == "__assert_fail" ||
00939       F->getName() == "modf")
00940     return true;
00941 
00942 
00943   // These functions do induce points-to edges.
00944   if (F->getName() == "llvm.memcpy" ||
00945       F->getName() == "llvm.memmove" ||
00946       F->getName() == "memmove") {
00947 
00948     const FunctionType *FTy = F->getFunctionType();
00949     if (FTy->getNumParams() > 1 && 
00950         isa<PointerType>(FTy->getParamType(0)) &&
00951         isa<PointerType>(FTy->getParamType(1))) {
00952 
00953       // *Dest = *Src, which requires an artificial graph node to represent the
00954       // constraint.  It is broken up into *Dest = temp, temp = *Src
00955       unsigned FirstArg = getNode(CS.getArgument(0));
00956       unsigned SecondArg = getNode(CS.getArgument(1));
00957       unsigned TempArg = GraphNodes.size();
00958       GraphNodes.push_back(Node());
00959       Constraints.push_back(Constraint(Constraint::Store,
00960                                        FirstArg, TempArg));
00961       Constraints.push_back(Constraint(Constraint::Load,
00962                                        TempArg, SecondArg));
00963       // In addition, Dest = Src
00964       Constraints.push_back(Constraint(Constraint::Copy,
00965                                        FirstArg, SecondArg));
00966       return true;
00967     }
00968   }
00969 
00970   // Result = Arg0
00971   if (F->getName() == "realloc" || F->getName() == "strchr" ||
00972       F->getName() == "strrchr" || F->getName() == "strstr" ||
00973       F->getName() == "strtok") {
00974     const FunctionType *FTy = F->getFunctionType();
00975     if (FTy->getNumParams() > 0 && 
00976         isa<PointerType>(FTy->getParamType(0))) {
00977       Constraints.push_back(Constraint(Constraint::Copy,
00978                                        getNode(CS.getInstruction()),
00979                                        getNode(CS.getArgument(0))));
00980       return true;
00981     }
00982   }
00983 
00984   return false;
00985 }
00986 
00987 
00988 
00989 /// AnalyzeUsesOfFunction - Look at all of the users of the specified function.
00990 /// If this is used by anything complex (i.e., the address escapes), return
00991 /// true.
00992 bool Andersens::AnalyzeUsesOfFunction(Value *V) {
00993 
00994   if (!isa<PointerType>(V->getType())) return true;
00995 
00996   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
00997     if (dyn_cast<LoadInst>(*UI)) {
00998       return false;
00999     } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
01000       if (V == SI->getOperand(1)) {
01001         return false;
01002       } else if (SI->getOperand(1)) {
01003         return true;  // Storing the pointer
01004       }
01005     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
01006       if (AnalyzeUsesOfFunction(GEP)) return true;
01007     } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
01008       // Make sure that this is just the function being called, not that it is
01009       // passing into the function.
01010       for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
01011         if (CI->getOperand(i) == V) return true;
01012     } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
01013       // Make sure that this is just the function being called, not that it is
01014       // passing into the function.
01015       for (unsigned i = 3, e = II->getNumOperands(); i != e; ++i)
01016         if (II->getOperand(i) == V) return true;
01017     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
01018       if (CE->getOpcode() == Instruction::GetElementPtr ||
01019           CE->getOpcode() == Instruction::BitCast) {
01020         if (AnalyzeUsesOfFunction(CE))
01021           return true;
01022       } else {
01023         return true;
01024       }
01025     } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(*UI)) {
01026       if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
01027         return true;  // Allow comparison against null.
01028     } else if (dyn_cast<FreeInst>(*UI)) {
01029       return false;
01030     } else {
01031       return true;
01032     }
01033   return false;
01034 }
01035 
01036 /// CollectConstraints - This stage scans the program, adding a constraint to
01037 /// the Constraints list for each instruction in the program that induces a
01038 /// constraint, and setting up the initial points-to graph.
01039 ///
01040 void Andersens::CollectConstraints(Module &M) {
01041   // First, the universal set points to itself.
01042   Constraints.push_back(Constraint(Constraint::AddressOf, UniversalSet,
01043                                    UniversalSet));
01044   Constraints.push_back(Constraint(Constraint::Store, UniversalSet,
01045                                    UniversalSet));
01046 
01047   // Next, the null pointer points to the null object.
01048   Constraints.push_back(Constraint(Constraint::AddressOf, NullPtr, NullObject));
01049 
01050   // Next, add any constraints on global variables and their initializers.
01051   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
01052        I != E; ++I) {
01053     // Associate the address of the global object as pointing to the memory for
01054     // the global: &G = <G memory>
01055     unsigned ObjectIndex = getObject(I);
01056     Node *Object = &GraphNodes[ObjectIndex];
01057     Object->setValue(I);
01058     Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(*I),
01059                                      ObjectIndex));
01060 
01061     if (I->hasInitializer()) {
01062       AddGlobalInitializerConstraints(ObjectIndex, I->getInitializer());
01063     } else {
01064       // If it doesn't have an initializer (i.e. it's defined in another
01065       // translation unit), it points to the universal set.
01066       Constraints.push_back(Constraint(Constraint::Copy, ObjectIndex,
01067                                        UniversalSet));
01068     }
01069   }
01070 
01071   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
01072     // Set up the return value node.
01073     if (isa<PointerType>(F->getFunctionType()->getReturnType()))
01074       GraphNodes[getReturnNode(F)].setValue(F);
01075     if (F->getFunctionType()->isVarArg())
01076       GraphNodes[getVarargNode(F)].setValue(F);
01077 
01078     // Set up incoming argument nodes.
01079     for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
01080          I != E; ++I)
01081       if (isa<PointerType>(I->getType()))
01082         getNodeValue(*I);
01083 
01084     // At some point we should just add constraints for the escaping functions
01085     // at solve time, but this slows down solving. For now, we simply mark
01086     // address taken functions as escaping and treat them as external.
01087     if (!F->hasLocalLinkage() || AnalyzeUsesOfFunction(F))
01088       AddConstraintsForNonInternalLinkage(F);
01089 
01090     if (!F->isDeclaration()) {
01091       // Scan the function body, creating a memory object for each heap/stack
01092       // allocation in the body of the function and a node to represent all
01093       // pointer values defined by instructions and used as operands.
01094       visit(F);
01095     } else {
01096       // External functions that return pointers return the universal set.
01097       if (isa<PointerType>(F->getFunctionType()->getReturnType()))
01098         Constraints.push_back(Constraint(Constraint::Copy,
01099                                          getReturnNode(F),
01100                                          UniversalSet));
01101 
01102       // Any pointers that are passed into the function have the universal set
01103       // stored into them.
01104       for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
01105            I != E; ++I)
01106         if (isa<PointerType>(I->getType())) {
01107           // Pointers passed into external functions could have anything stored
01108           // through them.
01109           Constraints.push_back(Constraint(Constraint::Store, getNode(I),
01110                                            UniversalSet));
01111           // Memory objects passed into external function calls can have the
01112           // universal set point to them.
01113 #if FULL_UNIVERSAL
01114           Constraints.push_back(Constraint(Constraint::Copy,
01115                                            UniversalSet,
01116                                            getNode(I)));
01117 #else
01118           Constraints.push_back(Constraint(Constraint::Copy,
01119                                            getNode(I),
01120                                            UniversalSet));
01121 #endif
01122         }
01123 
01124       // If this is an external varargs function, it can also store pointers
01125       // into any pointers passed through the varargs section.
01126       if (F->getFunctionType()->isVarArg())
01127         Constraints.push_back(Constraint(Constraint::Store, getVarargNode(F),
01128                                          UniversalSet));
01129     }
01130   }
01131   NumConstraints += Constraints.size();
01132 }
01133 
01134 
01135 void Andersens::visitInstruction(Instruction &I) {
01136 #ifdef NDEBUG
01137   return;          // This function is just a big assert.
01138 #endif
01139   if (isa<BinaryOperator>(I))
01140     return;
01141   // Most instructions don't have any effect on pointer values.
01142   switch (I.getOpcode()) {
01143   case Instruction::Br:
01144   case Instruction::Switch:
01145   case Instruction::Unwind:
01146   case Instruction::Unreachable:
01147   case Instruction::Free:
01148   case Instruction::ICmp:
01149   case Instruction::FCmp:
01150     return;
01151   default:
01152     // Is this something we aren't handling yet?
01153     cerr << "Unknown instruction: " << I;
01154     abort();
01155   }
01156 }
01157 
01158 void Andersens::visitAllocationInst(AllocationInst &AI) {
01159   unsigned ObjectIndex = getObject(&AI);
01160   GraphNodes[ObjectIndex].setValue(&AI);
01161   Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(AI),
01162                                    ObjectIndex));
01163 }
01164 
01165 void Andersens::visitReturnInst(ReturnInst &RI) {
01166   if (RI.getNumOperands() && isa<PointerType>(RI.getOperand(0)->getType()))
01167     // return V   -->   <Copy/retval{F}/v>
01168     Constraints.push_back(Constraint(Constraint::Copy,
01169                                      getReturnNode(RI.getParent()->getParent()),
01170                                      getNode(RI.getOperand(0))));
01171 }
01172 
01173 void Andersens::visitLoadInst(LoadInst &LI) {
01174   if (isa<PointerType>(LI.getType()))
01175     // P1 = load P2  -->  <Load/P1/P2>
01176     Constraints.push_back(Constraint(Constraint::Load, getNodeValue(LI),
01177                                      getNode(LI.getOperand(0))));
01178 }
01179 
01180 void Andersens::visitStoreInst(StoreInst &SI) {
01181   if (isa<PointerType>(SI.getOperand(0)->getType()))
01182     // store P1, P2  -->  <Store/P2/P1>
01183     Constraints.push_back(Constraint(Constraint::Store,
01184                                      getNode(SI.getOperand(1)),
01185                                      getNode(SI.getOperand(0))));
01186 }
01187 
01188 void Andersens::visitGetElementPtrInst(GetElementPtrInst &GEP) {
01189   // P1 = getelementptr P2, ... --> <Copy/P1/P2>
01190   Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(GEP),
01191                                    getNode(GEP.getOperand(0))));
01192 }
01193 
01194 void Andersens::visitPHINode(PHINode &PN) {
01195   if (isa<PointerType>(PN.getType())) {
01196     unsigned PNN = getNodeValue(PN);
01197     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
01198       // P1 = phi P2, P3  -->  <Copy/P1/P2>, <Copy/P1/P3>, ...
01199       Constraints.push_back(Constraint(Constraint::Copy, PNN,
01200                                        getNode(PN.getIncomingValue(i))));
01201   }
01202 }
01203 
01204 void Andersens::visitCastInst(CastInst &CI) {
01205   Value *Op = CI.getOperand(0);
01206   if (isa<PointerType>(CI.getType())) {
01207     if (isa<PointerType>(Op->getType())) {
01208       // P1 = cast P2  --> <Copy/P1/P2>
01209       Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
01210                                        getNode(CI.getOperand(0))));
01211     } else {
01212       // P1 = cast int --> <Copy/P1/Univ>
01213 #if 0
01214       Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
01215                                        UniversalSet));
01216 #else
01217       getNodeValue(CI);
01218 #endif
01219     }
01220   } else if (isa<PointerType>(Op->getType())) {
01221     // int = cast P1 --> <Copy/Univ/P1>
01222 #if 0
01223     Constraints.push_back(Constraint(Constraint::Copy,
01224                                      UniversalSet,
01225                                      getNode(CI.getOperand(0))));
01226 #else
01227     getNode(CI.getOperand(0));
01228 #endif
01229   }
01230 }
01231 
01232 void Andersens::visitSelectInst(SelectInst &SI) {
01233   if (isa<PointerType>(SI.getType())) {
01234     unsigned SIN = getNodeValue(SI);
01235     // P1 = select C, P2, P3   ---> <Copy/P1/P2>, <Copy/P1/P3>
01236     Constraints.push_back(Constraint(Constraint::Copy, SIN,
01237                                      getNode(SI.getOperand(1))));
01238     Constraints.push_back(Constraint(Constraint::Copy, SIN,
01239                                      getNode(SI.getOperand(2))));
01240   }
01241 }
01242 
01243 void Andersens::visitVAArg(VAArgInst &I) {
01244   assert(0 && "vaarg not handled yet!");
01245 }
01246 
01247 /// AddConstraintsForCall - Add constraints for a call with actual arguments
01248 /// specified by CS to the function specified by F.  Note that the types of
01249 /// arguments might not match up in the case where this is an indirect call and
01250 /// the function pointer has been casted.  If this is the case, do something
01251 /// reasonable.
01252 void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
01253   Value *CallValue = CS.getCalledValue();
01254   bool IsDeref = F == NULL;
01255 
01256   // If this is a call to an external function, try to handle it directly to get
01257   // some taste of context sensitivity.
01258   if (F && F->isDeclaration() && AddConstraintsForExternalCall(CS, F))
01259     return;
01260 
01261   if (isa<PointerType>(CS.getType())) {
01262     unsigned CSN = getNode(CS.getInstruction());
01263     if (!F || isa<PointerType>(F->getFunctionType()->getReturnType())) {
01264       if (IsDeref)
01265         Constraints.push_back(Constraint(Constraint::Load, CSN,
01266                                          getNode(CallValue), CallReturnPos));
01267       else
01268         Constraints.push_back(Constraint(Constraint::Copy, CSN,
01269                                          getNode(CallValue) + CallReturnPos));
01270     } else {
01271       // If the function returns a non-pointer value, handle this just like we
01272       // treat a nonpointer cast to pointer.
01273       Constraints.push_back(Constraint(Constraint::Copy, CSN,
01274                                        UniversalSet));
01275     }
01276   } else if (F && isa<PointerType>(F->getFunctionType()->getReturnType())) {
01277 #if FULL_UNIVERSAL
01278     Constraints.push_back(Constraint(Constraint::Copy,
01279                                      UniversalSet,
01280                                      getNode(CallValue) + CallReturnPos));
01281 #else
01282     Constraints.push_back(Constraint(Constraint::Copy,
01283                                       getNode(CallValue) + CallReturnPos,
01284                                       UniversalSet));
01285 #endif
01286                           
01287     
01288   }
01289 
01290   CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
01291   bool external = !F ||  F->isDeclaration();
01292   if (F) {
01293     // Direct Call
01294     Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
01295     for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI) 
01296       {
01297 #if !FULL_UNIVERSAL
01298         if (external && isa<PointerType>((*ArgI)->getType())) 
01299           {
01300             // Add constraint that ArgI can now point to anything due to
01301             // escaping, as can everything it points to. The second portion of
01302             // this should be taken care of by universal = *universal
01303             Constraints.push_back(Constraint(Constraint::Copy,
01304                                              getNode(*ArgI),
01305                                              UniversalSet));
01306           }
01307 #endif
01308         if (isa<PointerType>(AI->getType())) {
01309           if (isa<PointerType>((*ArgI)->getType())) {
01310             // Copy the actual argument into the formal argument.
01311             Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
01312                                              getNode(*ArgI)));
01313           } else {
01314             Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
01315                                              UniversalSet));
01316           }
01317         } else if (isa<PointerType>((*ArgI)->getType())) {
01318 #if FULL_UNIVERSAL
01319           Constraints.push_back(Constraint(Constraint::Copy,
01320                                            UniversalSet,
01321                                            getNode(*ArgI)));
01322 #else
01323           Constraints.push_back(Constraint(Constraint::Copy,
01324                                            getNode(*ArgI),
01325                                            UniversalSet));
01326 #endif
01327         }
01328       }
01329   } else {
01330     //Indirect Call
01331     unsigned ArgPos = CallFirstArgPos;
01332     for (; ArgI != ArgE; ++ArgI) {
01333       if (isa<PointerType>((*ArgI)->getType())) {
01334         // Copy the actual argument into the formal argument.
01335         Constraints.push_back(Constraint(Constraint::Store,
01336                                          getNode(CallValue),
01337                                          getNode(*ArgI), ArgPos++));
01338       } else {
01339         Constraints.push_back(Constraint(Constraint::Store,
01340                                          getNode (CallValue),
01341                                          UniversalSet, ArgPos++));
01342       }
01343     }
01344   }
01345   // Copy all pointers passed through the varargs section to the varargs node.
01346   if (F && F->getFunctionType()->isVarArg())
01347     for (; ArgI != ArgE; ++ArgI)
01348       if (isa<PointerType>((*ArgI)->getType()))
01349         Constraints.push_back(Constraint(Constraint::Copy, getVarargNode(F),
01350                                          getNode(*ArgI)));
01351   // If more arguments are passed in than we track, just drop them on the floor.
01352 }
01353 
01354 void Andersens::visitCallSite(CallSite CS) {
01355   if (isa<PointerType>(CS.getType()))
01356     getNodeValue(*CS.getInstruction());
01357 
01358   if (Function *F = CS.getCalledFunction()) {
01359     AddConstraintsForCall(CS, F);
01360   } else {
01361     AddConstraintsForCall(CS, NULL);
01362   }
01363 }
01364 
01365 //===----------------------------------------------------------------------===//
01366 //                         Constraint Solving Phase
01367 //===----------------------------------------------------------------------===//
01368 
01369 /// intersects - Return true if the points-to set of this node intersects
01370 /// with the points-to set of the specified node.
01371 bool Andersens::Node::intersects(Node *N) const {
01372   return PointsTo->intersects(N->PointsTo);
01373 }
01374 
01375 /// intersectsIgnoring - Return true if the points-to set of this node
01376 /// intersects with the points-to set of the specified node on any nodes
01377 /// except for the specified node to ignore.
01378 bool Andersens::Node::intersectsIgnoring(Node *N, unsigned Ignoring) const {
01379   // TODO: If we are only going to call this with the same value for Ignoring,
01380   // we should move the special values out of the points-to bitmap.
01381   bool WeHadIt = PointsTo->test(Ignoring);
01382   bool NHadIt = N->PointsTo->test(Ignoring);
01383   bool Result = false;
01384   if (WeHadIt)
01385     PointsTo->reset(Ignoring);
01386   if (NHadIt)
01387     N->PointsTo->reset(Ignoring);
01388   Result = PointsTo->intersects(N->PointsTo);
01389   if (WeHadIt)
01390     PointsTo->set(Ignoring);
01391   if (NHadIt)
01392     N->PointsTo->set(Ignoring);
01393   return Result;
01394 }
01395 
01396 void dumpToDOUT(SparseBitVector<> *bitmap) {
01397 #ifndef NDEBUG
01398   dump(*bitmap, DOUT);
01399 #endif
01400 }
01401 
01402 
01403 /// Clump together address taken variables so that the points-to sets use up
01404 /// less space and can be operated on faster.
01405 
01406 void Andersens::ClumpAddressTaken() {
01407 #undef DEBUG_TYPE
01408 #define DEBUG_TYPE "anders-aa-renumber"
01409   std::vector<unsigned> Translate;
01410   std::vector<Node> NewGraphNodes;
01411 
01412   Translate.resize(GraphNodes.size());
01413   unsigned NewPos = 0;
01414 
01415   for (unsigned i = 0; i < Constraints.size(); ++i) {
01416     Constraint &C = Constraints[i];
01417     if (C.Type == Constraint::AddressOf) {
01418       GraphNodes[C.Src].AddressTaken = true;
01419     }
01420   }
01421   for (unsigned i = 0; i < NumberSpecialNodes; ++i) {
01422     unsigned Pos = NewPos++;
01423     Translate[i] = Pos;
01424     NewGraphNodes.push_back(GraphNodes[i]);
01425     DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
01426   }
01427 
01428   // I believe this ends up being faster than making two vectors and splicing
01429   // them.
01430   for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
01431     if (GraphNodes[i].AddressTaken) {
01432       unsigned Pos = NewPos++;
01433       Translate[i] = Pos;
01434       NewGraphNodes.push_back(GraphNodes[i]);
01435       DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
01436     }
01437   }
01438 
01439   for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
01440     if (!GraphNodes[i].AddressTaken) {
01441       unsigned Pos = NewPos++;
01442       Translate[i] = Pos;
01443       NewGraphNodes.push_back(GraphNodes[i]);
01444       DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
01445     }
01446   }
01447 
01448   for (DenseMap<Value*, unsigned>::iterator Iter = ValueNodes.begin();
01449        Iter != ValueNodes.end();
01450        ++Iter)
01451     Iter->second = Translate[Iter->second];
01452 
01453   for (DenseMap<Value*, unsigned>::iterator Iter = ObjectNodes.begin();
01454        Iter != ObjectNodes.end();
01455        ++Iter)
01456     Iter->second = Translate[Iter->second];
01457 
01458   for (DenseMap<Function*, unsigned>::iterator Iter = ReturnNodes.begin();
01459        Iter != ReturnNodes.end();
01460        ++Iter)
01461     Iter->second = Translate[Iter->second];
01462 
01463   for (DenseMap<Function*, unsigned>::iterator Iter = VarargNodes.begin();
01464        Iter != VarargNodes.end();
01465        ++Iter)
01466     Iter->second = Translate[Iter->second];
01467 
01468   for (unsigned i = 0; i < Constraints.size(); ++i) {
01469     Constraint &C = Constraints[i];
01470     C.Src = Translate[C.Src];
01471     C.Dest = Translate[C.Dest];
01472   }
01473 
01474   GraphNodes.swap(NewGraphNodes);
01475 #undef DEBUG_TYPE
01476 #define DEBUG_TYPE "anders-aa"
01477 }
01478 
01479 /// The technique used here is described in "Exploiting Pointer and Location
01480 /// Equivalence to Optimize Pointer Analysis. In the 14th International Static
01481 /// Analysis Symposium (SAS), August 2007."  It is known as the "HVN" algorithm,
01482 /// and is equivalent to value numbering the collapsed constraint graph without
01483 /// evaluating unions.  This is used as a pre-pass to HU in order to resolve
01484 /// first order pointer dereferences and speed up/reduce memory usage of HU.
01485 /// Running both is equivalent to HRU without the iteration
01486 /// HVN in more detail:
01487 /// Imagine the set of constraints was simply straight line code with no loops
01488 /// (we eliminate cycles, so there are no loops), such as:
01489 /// E = &D
01490 /// E = &C
01491 /// E = F
01492 /// F = G
01493 /// G = F
01494 /// Applying value numbering to this code tells us:
01495 /// G == F == E
01496 ///
01497 /// For HVN, this is as far as it goes.  We assign new value numbers to every
01498 /// "address node", and every "reference node".
01499 /// To get the optimal result for this, we use a DFS + SCC (since all nodes in a
01500 /// cycle must have the same value number since the = operation is really
01501 /// inclusion, not overwrite), and value number nodes we receive points-to sets
01502 /// before we value our own node.
01503 /// The advantage of HU over HVN is that HU considers the inclusion property, so
01504 /// that if you have
01505 /// E = &D
01506 /// E = &C
01507 /// E = F
01508 /// F = G
01509 /// F = &D
01510 /// G = F
01511 /// HU will determine that G == F == E.  HVN will not, because it cannot prove
01512 /// that the points to information ends up being the same because they all
01513 /// receive &D from E anyway.
01514 
01515 void Andersens::HVN() {
01516   DOUT << "Beginning HVN\n";
01517   // Build a predecessor graph.  This is like our constraint graph with the
01518   // edges going in the opposite direction, and there are edges for all the
01519   // constraints, instead of just copy constraints.  We also build implicit
01520   // edges for constraints are implied but not explicit.  I.E for the constraint
01521   // a = &b, we add implicit edges *a = b.  This helps us capture more cycles
01522   for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
01523     Constraint &C = Constraints[i];
01524     if (C.Type == Constraint::AddressOf) {
01525       GraphNodes[C.Src].AddressTaken = true;
01526       GraphNodes[C.Src].Direct = false;
01527 
01528       // Dest = &src edge
01529       unsigned AdrNode = C.Src + FirstAdrNode;
01530       if (!GraphNodes[C.Dest].PredEdges)
01531         GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
01532       GraphNodes[C.Dest].PredEdges->set(AdrNode);
01533 
01534       // *Dest = src edge
01535       unsigned RefNode = C.Dest + FirstRefNode;
01536       if (!GraphNodes[RefNode].ImplicitPredEdges)
01537         GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
01538       GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
01539     } else if (C.Type == Constraint::Load) {
01540       if (C.Offset == 0) {
01541         // dest = *src edge
01542         if (!GraphNodes[C.Dest].PredEdges)
01543           GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
01544         GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
01545       } else {
01546         GraphNodes[C.Dest].Direct = false;
01547       }
01548     } else if (C.Type == Constraint::Store) {
01549       if (C.Offset == 0) {
01550         // *dest = src edge
01551         unsigned RefNode = C.Dest + FirstRefNode;
01552         if (!GraphNodes[RefNode].PredEdges)
01553           GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
01554         GraphNodes[RefNode].PredEdges->set(C.Src);
01555       }
01556     } else {
01557       // Dest = Src edge and *Dest = *Src edge
01558       if (!GraphNodes[C.Dest].PredEdges)
01559         GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
01560       GraphNodes[C.Dest].PredEdges->set(C.Src);
01561       unsigned RefNode = C.Dest + FirstRefNode;
01562       if (!GraphNodes[RefNode].ImplicitPredEdges)
01563         GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
01564       GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
01565     }
01566   }
01567   PEClass = 1;
01568   // Do SCC finding first to condense our predecessor graph
01569   DFSNumber = 0;
01570   Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
01571   Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
01572   Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
01573 
01574   for (unsigned i = 0; i < FirstRefNode; ++i) {
01575     unsigned Node = VSSCCRep[i];
01576     if (!Node2Visited[Node])
01577       HVNValNum(Node);
01578   }
01579   for (BitVectorMap::iterator Iter = Set2PEClass.begin();
01580        Iter != Set2PEClass.end();
01581        ++Iter)
01582     delete Iter->first;
01583   Set2PEClass.clear();
01584   Node2DFS.clear();
01585   Node2Deleted.clear();
01586   Node2Visited.clear();
01587   DOUT << "Finished HVN\n";
01588 
01589 }
01590 
01591 /// This is the workhorse of HVN value numbering. We combine SCC finding at the
01592 /// same time because it's easy.
01593 void Andersens::HVNValNum(unsigned NodeIndex) {
01594   unsigned MyDFS = DFSNumber++;
01595   Node *N = &GraphNodes[NodeIndex];
01596   Node2Visited[NodeIndex] = true;
01597   Node2DFS[NodeIndex] = MyDFS;
01598 
01599   // First process all our explicit edges
01600   if (N->PredEdges)
01601     for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
01602          Iter != N->PredEdges->end();
01603          ++Iter) {
01604       unsigned j = VSSCCRep[*Iter];
01605       if (!Node2Deleted[j]) {
01606         if (!Node2Visited[j])
01607           HVNValNum(j);
01608         if (Node2DFS[NodeIndex] > Node2DFS[j])
01609           Node2DFS[NodeIndex] = Node2DFS[j];
01610       }
01611     }
01612 
01613   // Now process all the implicit edges
01614   if (N->ImplicitPredEdges)
01615     for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
01616          Iter != N->ImplicitPredEdges->end();
01617          ++Iter) {
01618       unsigned j = VSSCCRep[*Iter];
01619       if (!Node2Deleted[j]) {
01620         if (!Node2Visited[j])
01621           HVNValNum(j);
01622         if (Node2DFS[NodeIndex] > Node2DFS[j])
01623           Node2DFS[NodeIndex] = Node2DFS[j];
01624       }
01625     }
01626 
01627   // See if we found any cycles
01628   if (MyDFS == Node2DFS[NodeIndex]) {
01629     while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
01630       unsigned CycleNodeIndex = SCCStack.top();
01631       Node *CycleNode = &GraphNodes[CycleNodeIndex];
01632       VSSCCRep[CycleNodeIndex] = NodeIndex;
01633       // Unify the nodes
01634       N->Direct &= CycleNode->Direct;
01635 
01636       if (CycleNode->PredEdges) {
01637         if (!N->PredEdges)
01638           N->PredEdges = new SparseBitVector<>;
01639         *(N->PredEdges) |= CycleNode->PredEdges;
01640         delete CycleNode->PredEdges;
01641         CycleNode->PredEdges = NULL;
01642       }
01643       if (CycleNode->ImplicitPredEdges) {
01644         if (!N->ImplicitPredEdges)
01645           N->ImplicitPredEdges = new SparseBitVector<>;
01646         *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
01647         delete CycleNode->ImplicitPredEdges;
01648         CycleNode->ImplicitPredEdges = NULL;
01649       }
01650 
01651       SCCStack.pop();
01652     }
01653 
01654     Node2Deleted[NodeIndex] = true;
01655 
01656     if (!N->Direct) {
01657       GraphNodes[NodeIndex].PointerEquivLabel = PEClass++;
01658       return;
01659     }
01660 
01661     // Collect labels of successor nodes
01662     bool AllSame = true;
01663     unsigned First = ~0;
01664     SparseBitVector<> *Labels = new SparseBitVector<>;
01665     bool Used = false;
01666 
01667     if (N->PredEdges)
01668       for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
01669            Iter != N->PredEdges->end();
01670          ++Iter) {
01671         unsigned j = VSSCCRep[*Iter];
01672         unsigned Label = GraphNodes[j].PointerEquivLabel;
01673         // Ignore labels that are equal to us or non-pointers
01674         if (j == NodeIndex || Label == 0)
01675           continue;
01676         if (First == (unsigned)~0)
01677           First = Label;
01678         else if (First != Label)
01679           AllSame = false;
01680         Labels->set(Label);
01681     }
01682 
01683     // We either have a non-pointer, a copy of an existing node, or a new node.
01684     // Assign the appropriate pointer equivalence label.
01685     if (Labels->empty()) {
01686       GraphNodes[NodeIndex].PointerEquivLabel = 0;
01687     } else if (AllSame) {
01688       GraphNodes[NodeIndex].PointerEquivLabel = First;
01689     } else {
01690       GraphNodes[NodeIndex].PointerEquivLabel = Set2PEClass[Labels];
01691       if (GraphNodes[NodeIndex].PointerEquivLabel == 0) {
01692         unsigned EquivClass = PEClass++;
01693         Set2PEClass[Labels] = EquivClass;
01694         GraphNodes[NodeIndex].PointerEquivLabel = EquivClass;
01695         Used = true;
01696       }
01697     }
01698     if (!Used)
01699       delete Labels;
01700   } else {
01701     SCCStack.push(NodeIndex);
01702   }
01703 }
01704 
01705 /// The technique used here is described in "Exploiting Pointer and Location
01706 /// Equivalence to Optimize Pointer Analysis. In the 14th International Static
01707 /// Analysis Symposium (SAS), August 2007."  It is known as the "HU" algorithm,
01708 /// and is equivalent to value numbering the collapsed constraint graph
01709 /// including evaluating unions.
01710 void Andersens::HU() {
01711   DOUT << "Beginning HU\n";
01712   // Build a predecessor graph.  This is like our constraint graph with the
01713   // edges going in the opposite direction, and there are edges for all the
01714   // constraints, instead of just copy constraints.  We also build implicit
01715   // edges for constraints are implied but not explicit.  I.E for the constraint
01716   // a = &b, we add implicit edges *a = b.  This helps us capture more cycles
01717   for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
01718     Constraint &C = Constraints[i];
01719     if (C.Type == Constraint::AddressOf) {
01720       GraphNodes[C.Src].AddressTaken = true;
01721       GraphNodes[C.Src].Direct = false;
01722 
01723       GraphNodes[C.Dest].PointsTo->set(C.Src);
01724       // *Dest = src edge
01725       unsigned RefNode = C.Dest + FirstRefNode;
01726       if (!GraphNodes[RefNode].ImplicitPredEdges)
01727         GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
01728       GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
01729       GraphNodes[C.Src].PointedToBy->set(C.Dest);
01730     } else if (C.Type == Constraint::Load) {
01731       if (C.Offset == 0) {
01732         // dest = *src edge
01733         if (!GraphNodes[C.Dest].PredEdges)
01734           GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
01735         GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
01736       } else {
01737         GraphNodes[C.Dest].Direct = false;
01738       }
01739     } else if (C.Type == Constraint::Store) {
01740       if (C.Offset == 0) {
01741         // *dest = src edge
01742         unsigned RefNode = C.Dest + FirstRefNode;
01743         if (!GraphNodes[RefNode].PredEdges)
01744           GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
01745         GraphNodes[RefNode].PredEdges->set(C.Src);
01746       }
01747     } else {
01748       // Dest = Src edge and *Dest = *Src edg
01749       if (!GraphNodes[C.Dest].PredEdges)
01750         GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
01751       GraphNodes[C.Dest].PredEdges->set(C.Src);
01752       unsigned RefNode = C.Dest + FirstRefNode;
01753       if (!GraphNodes[RefNode].ImplicitPredEdges)
01754         GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
01755       GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
01756     }
01757   }
01758   PEClass = 1;
01759   // Do SCC finding first to condense our predecessor graph
01760   DFSNumber = 0;
01761   Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
01762   Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
01763   Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
01764 
01765   for (unsigned i = 0; i < FirstRefNode; ++i) {
01766     if (FindNode(i) == i) {
01767       unsigned Node = VSSCCRep[i];
01768       if (!Node2Visited[Node])
01769         Condense(Node);
01770     }
01771   }
01772 
01773   // Reset tables for actual labeling
01774   Node2DFS.clear();
01775   Node2Visited.clear();
01776   Node2Deleted.clear();
01777   // Pre-grow our densemap so that we don't get really bad behavior
01778   Set2PEClass.resize(GraphNodes.size());
01779 
01780   // Visit the condensed graph and generate pointer equivalence labels.
01781   Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
01782   for (unsigned i = 0; i < FirstRefNode; ++i) {
01783     if (FindNode(i) == i) {
01784       unsigned Node = VSSCCRep[i];
01785       if (!Node2Visited[Node])
01786         HUValNum(Node);
01787     }
01788   }
01789   // PEClass nodes will be deleted by the deleting of N->PointsTo in our caller.
01790   Set2PEClass.clear();
01791   DOUT << "Finished HU\n";
01792 }
01793 
01794 
01795 /// Implementation of standard Tarjan SCC algorithm as modified by Nuutilla.
01796 void Andersens::Condense(unsigned NodeIndex) {
01797   unsigned MyDFS = DFSNumber++;
01798   Node *N = &GraphNodes[NodeIndex];
01799   Node2Visited[NodeIndex] = true;
01800   Node2DFS[NodeIndex] = MyDFS;
01801 
01802   // First process all our explicit edges
01803   if (N->PredEdges)
01804     for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
01805          Iter != N->PredEdges->end();
01806          ++Iter) {
01807       unsigned j = VSSCCRep[*Iter];
01808       if (!Node2Deleted[j]) {
01809         if (!Node2Visited[j])
01810           Condense(j);
01811         if (Node2DFS[NodeIndex] > Node2DFS[j])
01812           Node2DFS[NodeIndex] = Node2DFS[j];
01813       }
01814     }
01815 
01816   // Now process all the implicit edges
01817   if (N->ImplicitPredEdges)
01818     for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
01819          Iter != N->ImplicitPredEdges->end();
01820          ++Iter) {
01821       unsigned j = VSSCCRep[*Iter];
01822       if (!Node2Deleted[j]) {
01823         if (!Node2Visited[j])
01824           Condense(j);
01825         if (Node2DFS[NodeIndex] > Node2DFS[j])
01826           Node2DFS[NodeIndex] = Node2DFS[j];
01827       }
01828     }
01829 
01830   // See if we found any cycles
01831   if (MyDFS == Node2DFS[NodeIndex]) {
01832     while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
01833       unsigned CycleNodeIndex = SCCStack.top();
01834       Node *CycleNode = &GraphNodes[CycleNodeIndex];
01835       VSSCCRep[CycleNodeIndex] = NodeIndex;
01836       // Unify the nodes
01837       N->Direct &= CycleNode->Direct;
01838 
01839       *(N->PointsTo) |= CycleNode->PointsTo;
01840       delete CycleNode->PointsTo;
01841       CycleNode->PointsTo = NULL;
01842       if (CycleNode->PredEdges) {
01843         if (!N->PredEdges)
01844           N->PredEdges = new SparseBitVector<>;
01845         *(N->PredEdges) |= CycleNode->PredEdges;
01846         delete CycleNode->PredEdges;
01847         CycleNode->PredEdges = NULL;
01848       }
01849       if (CycleNode->ImplicitPredEdges) {
01850         if (!N->ImplicitPredEdges)
01851           N->ImplicitPredEdges = new SparseBitVector<>;
01852         *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
01853         delete CycleNode->ImplicitPredEdges;
01854         CycleNode->ImplicitPredEdges = NULL;
01855       }
01856       SCCStack.pop();
01857     }
01858 
01859     Node2Deleted[NodeIndex] = true;
01860 
01861     // Set up number of incoming edges for other nodes
01862     if (N->PredEdges)
01863       for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
01864            Iter != N->PredEdges->end();
01865            ++Iter)
01866         ++GraphNodes[VSSCCRep[*Iter]].NumInEdges;
01867   } else {
01868     SCCStack.push(NodeIndex);
01869   }
01870 }
01871 
01872 void Andersens::HUValNum(unsigned NodeIndex) {
01873   Node *N = &GraphNodes[NodeIndex];
01874   Node2Visited[NodeIndex] = true;
01875 
01876   // Eliminate dereferences of non-pointers for those non-pointers we have
01877   // already identified.  These are ref nodes whose non-ref node:
01878   // 1. Has already been visited determined to point to nothing (and thus, a
01879   // dereference of it must point to nothing)
01880   // 2. Any direct node with no predecessor edges in our graph and with no
01881   // points-to set (since it can't point to anything either, being that it
01882   // receives no points-to sets and has none).
01883   if (NodeIndex >= FirstRefNode) {
01884     unsigned j = VSSCCRep[FindNode(NodeIndex - FirstRefNode)];
01885     if ((Node2Visited[j] && !GraphNodes[j].PointerEquivLabel)
01886         || (GraphNodes[j].Direct && !GraphNodes[j].PredEdges
01887             && GraphNodes[j].PointsTo->empty())){
01888       return;
01889     }
01890   }
01891     // Process all our explicit edges
01892   if (N->PredEdges)
01893     for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
01894          Iter != N->PredEdges->end();
01895          ++Iter) {
01896       unsigned j = VSSCCRep[*Iter];
01897       if (!Node2Visited[j])
01898         HUValNum(j);
01899 
01900       // If this edge turned out to be the same as us, or got no pointer
01901       // equivalence label (and thus points to nothing) , just decrement our
01902       // incoming edges and continue.
01903       if (j == NodeIndex || GraphNodes[j].PointerEquivLabel == 0) {
01904         --GraphNodes[j].NumInEdges;
01905         continue;
01906       }
01907 
01908       *(N->PointsTo) |= GraphNodes[j].PointsTo;
01909 
01910       // If we didn't end up storing this in the hash, and we're done with all
01911       // the edges, we don't need the points-to set anymore.
01912       --GraphNodes[j].NumInEdges;
01913       if (!GraphNodes[j].NumInEdges && !GraphNodes[j].StoredInHash) {
01914         delete GraphNodes[j].PointsTo;
01915         GraphNodes[j].PointsTo = NULL;
01916       }
01917     }
01918   // If this isn't a direct node, generate a fresh variable.
01919   if (!N->Direct) {
01920     N->PointsTo->set(FirstRefNode + NodeIndex);
01921   }
01922 
01923   // See If we have something equivalent to us, if not, generate a new
01924   // equivalence class.
01925   if (N->PointsTo->empty()) {
01926     delete N->PointsTo;
01927     N->PointsTo = NULL;
01928   } else {
01929     if (N->Direct) {
01930       N->PointerEquivLabel = Set2PEClass[N->PointsTo];
01931       if (N->PointerEquivLabel == 0) {
01932         unsigned EquivClass = PEClass++;
01933         N->StoredInHash = true;
01934         Set2PEClass[N->PointsTo] = EquivClass;
01935         N->PointerEquivLabel = EquivClass;
01936       }
01937     } else {
01938       N->PointerEquivLabel = PEClass++;
01939     }
01940   }
01941 }
01942 
01943 /// Rewrite our list of constraints so that pointer equivalent nodes are
01944 /// replaced by their the pointer equivalence class representative.
01945 void Andersens::RewriteConstraints() {
01946   std::vector<Constraint> NewConstraints;
01947   DenseSet<Constraint, ConstraintKeyInfo> Seen;
01948 
01949   PEClass2Node.clear();
01950   PENLEClass2Node.clear();
01951 
01952   // We may have from 1 to Graphnodes + 1 equivalence classes.
01953   PEClass2Node.insert(PEClass2Node.begin(), GraphNodes.size() + 1, -1);
01954   PENLEClass2Node.insert(PENLEClass2Node.begin(), GraphNodes.size() + 1, -1);
01955 
01956   // Rewrite constraints, ignoring non-pointer constraints, uniting equivalent
01957   // nodes, and rewriting constraints to use the representative nodes.
01958   for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
01959     Constraint &C = Constraints[i];
01960     unsigned RHSNode = FindNode(C.Src);
01961     unsigned LHSNode = FindNode(C.Dest);
01962     unsigned RHSLabel = GraphNodes[VSSCCRep[RHSNode]].PointerEquivLabel;
01963     unsigned LHSLabel = GraphNodes[VSSCCRep[LHSNode]].PointerEquivLabel;
01964 
01965     // First we try to eliminate constraints for things we can prove don't point
01966     // to anything.
01967     if (LHSLabel == 0) {
01968       DEBUG(PrintNode(&GraphNodes[LHSNode]));
01969       DOUT << " is a non-pointer, ignoring constraint.\n";
01970       continue;
01971     }
01972     if (RHSLabel == 0) {
01973       DEBUG(PrintNode(&GraphNodes[RHSNode]));
01974       DOUT << " is a non-pointer, ignoring constraint.\n";
01975       continue;
01976     }
01977     // This constraint may be useless, and it may become useless as we translate
01978     // it.
01979     if (C.Src == C.Dest && C.Type == Constraint::Copy)
01980       continue;
01981 
01982     C.Src = FindEquivalentNode(RHSNode, RHSLabel);
01983     C.Dest = FindEquivalentNode(FindNode(LHSNode), LHSLabel);
01984     if ((C.Src == C.Dest && C.Type == Constraint::Copy)
01985         || Seen.count(C))
01986       continue;
01987 
01988     Seen.insert(C);
01989     NewConstraints.push_back(C);
01990   }
01991   Constraints.swap(NewConstraints);
01992   PEClass2Node.clear();
01993 }
01994 
01995 /// See if we have a node that is pointer equivalent to the one being asked
01996 /// about, and if so, unite them and return the equivalent node.  Otherwise,
01997 /// return the original node.
01998 unsigned Andersens::FindEquivalentNode(unsigned NodeIndex,
01999                                        unsigned NodeLabel) {
02000   if (!GraphNodes[NodeIndex].AddressTaken) {
02001     if (PEClass2Node[NodeLabel] != -1) {
02002       // We found an existing node with the same pointer label, so unify them.
02003       // We specifically request that Union-By-Rank not be used so that
02004       // PEClass2Node[NodeLabel] U= NodeIndex and not the other way around.
02005       return UniteNodes(PEClass2Node[NodeLabel], NodeIndex, false);
02006     } else {
02007       PEClass2Node[NodeLabel] = NodeIndex;
02008       PENLEClass2Node[NodeLabel] = NodeIndex;
02009     }
02010   } else if (PENLEClass2Node[NodeLabel] == -1) {
02011     PENLEClass2Node[NodeLabel] = NodeIndex;
02012   }
02013 
02014   return NodeIndex;
02015 }
02016 
02017 void Andersens::PrintLabels() const {
02018   for (unsigned i = 0; i < GraphNodes.size(); ++i) {
02019     if (i < FirstRefNode) {
02020       PrintNode(&GraphNodes[i]);
02021     } else if (i < FirstAdrNode) {
02022       DOUT << "REF(";
02023       PrintNode(&GraphNodes[i-FirstRefNode]);
02024       DOUT <<")";
02025     } else {
02026       DOUT << "ADR(";
02027       PrintNode(&GraphNodes[i-FirstAdrNode]);
02028       DOUT <<")";
02029     }
02030 
02031     DOUT << " has pointer label " << GraphNodes[i].PointerEquivLabel
02032          << " and SCC rep " << VSSCCRep[i]
02033          << " and is " << (GraphNodes[i].Direct ? "Direct" : "Not direct")
02034          << "\n";
02035   }
02036 }
02037 
02038 /// The technique used here is described in "The Ant and the
02039 /// Grasshopper: Fast and Accurate Pointer Analysis for Millions of
02040 /// Lines of Code. In Programming Language Design and Implementation
02041 /// (PLDI), June 2007." It is known as the "HCD" (Hybrid Cycle
02042 /// Detection) algorithm. It is called a hybrid because it performs an
02043 /// offline analysis and uses its results during the solving (online)
02044 /// phase. This is just the offline portion; the results of this
02045 /// operation are stored in SDT and are later used in SolveContraints()
02046 /// and UniteNodes().
02047 void Andersens::HCD() {
02048   DOUT << "Starting HCD.\n";
02049   HCDSCCRep.resize(GraphNodes.size());
02050 
02051   for (unsigned i = 0; i < GraphNodes.size(); ++i) {
02052     GraphNodes[i].Edges = new SparseBitVector<>;
02053     HCDSCCRep[i] = i;
02054   }
02055 
02056   for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
02057     Constraint &C = Constraints[i];
02058     assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
02059     if (C.Type == Constraint::AddressOf) {
02060       continue;
02061     } else if (C.Type == Constraint::Load) {
02062       if( C.Offset == 0 )
02063         GraphNodes[C.Dest].Edges->set(C.Src + FirstRefNode);
02064     } else if (C.Type == Constraint::Store) {
02065       if( C.Offset == 0 )
02066         GraphNodes[C.Dest + FirstRefNode].Edges->set(C.Src);
02067     } else {
02068       GraphNodes[C.Dest].Edges->set(C.Src);
02069     }
02070   }
02071 
02072   Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
02073   Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
02074   Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
02075   SDT.insert(SDT.begin(), GraphNodes.size() / 2, -1);
02076 
02077   DFSNumber = 0;
02078   for (unsigned i = 0; i < GraphNodes.size(); ++i) {
02079     unsigned Node = HCDSCCRep[i];
02080     if (!Node2Deleted[Node])
02081       Search(Node);
02082   }
02083 
02084   for (unsigned i = 0; i < GraphNodes.size(); ++i)
02085     if (GraphNodes[i].Edges != NULL) {
02086       delete GraphNodes[i].Edges;
02087       GraphNodes[i].Edges = NULL;
02088     }
02089 
02090   while( !SCCStack.empty() )
02091     SCCStack.pop();
02092 
02093   Node2DFS.clear();
02094   Node2Visited.clear();
02095   Node2Deleted.clear();
02096   HCDSCCRep.clear();
02097   DOUT << "HCD complete.\n";
02098 }
02099 
02100 // Component of HCD: 
02101 // Use Nuutila's variant of Tarjan's algorithm to detect
02102 // Strongly-Connected Components (SCCs). For non-trivial SCCs
02103 // containing ref nodes, insert the appropriate information in SDT.
02104 void Andersens::Search(unsigned Node) {
02105   unsigned MyDFS = DFSNumber++;
02106 
02107   Node2Visited[Node] = true;
02108   Node2DFS[Node] = MyDFS;
02109 
02110   for (SparseBitVector<>::iterator Iter = GraphNodes[Node].Edges->begin(),
02111                                    End  = GraphNodes[Node].Edges->end();
02112        Iter != End;
02113        ++Iter) {
02114     unsigned J = HCDSCCRep[*Iter];
02115     assert(GraphNodes[J].isRep() && "Debug check; must be representative");
02116     if (!Node2Deleted[J]) {
02117       if (!Node2Visited[J])
02118         Search(J);
02119       if (Node2DFS[Node] > Node2DFS[J])
02120         Node2DFS[Node] = Node2DFS[J];
02121     }
02122   }
02123 
02124   if( MyDFS != Node2DFS[Node] ) {
02125     SCCStack.push(Node);
02126     return;
02127   }
02128 
02129   // This node is the root of a SCC, so process it.
02130   //
02131   // If the SCC is "non-trivial" (not a singleton) and contains a reference 
02132   // node, we place this SCC into SDT.  We unite the nodes in any case.
02133   if (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
02134     SparseBitVector<> SCC;
02135 
02136     SCC.set(Node);
02137 
02138     bool Ref = (Node >= FirstRefNode);
02139 
02140     Node2Deleted[Node] = true;
02141 
02142     do {
02143       unsigned P = SCCStack.top(); SCCStack.pop();
02144       Ref |= (P >= FirstRefNode);
02145       SCC.set(P);
02146       HCDSCCRep[P] = Node;
02147     } while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS);
02148 
02149     if (Ref) {
02150       unsigned Rep = SCC.find_first();
02151       assert(Rep < FirstRefNode && "The SCC didn't have a non-Ref node!");
02152 
02153       SparseBitVector<>::iterator i = SCC.begin();
02154 
02155       // Skip over the non-ref nodes
02156       while( *i < FirstRefNode )
02157         ++i;
02158 
02159       while( i != SCC.end() )
02160         SDT[ (*i++) - FirstRefNode ] = Rep;
02161     }
02162   }
02163 }
02164 
02165 
02166 /// Optimize the constraints by performing offline variable substitution and
02167 /// other optimizations.
02168 void Andersens::OptimizeConstraints() {
02169   DOUT << "Beginning constraint optimization\n";
02170 
02171   SDTActive = false;
02172 
02173   // Function related nodes need to stay in the same relative position and can't
02174   // be location equivalent.
02175   for (std::map<unsigned, unsigned>::iterator Iter = MaxK.begin();
02176        Iter != MaxK.end();
02177        ++Iter) {
02178     for (unsigned i = Iter->first;
02179          i != Iter->first + Iter->second;
02180          ++i) {
02181       GraphNodes[i].AddressTaken = true;
02182       GraphNodes[i].Direct = false;
02183     }
02184   }
02185 
02186   ClumpAddressTaken();
02187   FirstRefNode = GraphNodes.size();
02188   FirstAdrNode = FirstRefNode + GraphNodes.size();
02189   GraphNodes.insert(GraphNodes.end(), 2 * GraphNodes.size(),
02190                     Node(false));
02191   VSSCCRep.resize(GraphNodes.size());
02192   for (unsigned i = 0; i < GraphNodes.size(); ++i) {
02193     VSSCCRep[i] = i;
02194   }
02195   HVN();
02196   for (unsigned i = 0; i < GraphNodes.size(); ++i) {
02197     Node *N = &GraphNodes[i];
02198     delete N->PredEdges;
02199     N->PredEdges = NULL;
02200     delete N->ImplicitPredEdges;
02201     N->ImplicitPredEdges = NULL;
02202   }
02203 #undef DEBUG_TYPE
02204 #define DEBUG_TYPE "anders-aa-labels"
02205   DEBUG(PrintLabels());
02206 #undef DEBUG_TYPE
02207 #define DEBUG_TYPE "anders-aa"
02208   RewriteConstraints();
02209   // Delete the adr nodes.
02210   GraphNodes.resize(FirstRefNode * 2);
02211 
02212   // Now perform HU
02213   for (unsigned i = 0; i < GraphNodes.size(); ++i) {
02214     Node *N = &GraphNodes[i];
02215     if (FindNode(i) == i) {
02216       N->PointsTo = new SparseBitVector<>;
02217       N->PointedToBy = new SparseBitVector<>;
02218       // Reset our labels
02219     }
02220     VSSCCRep[i] = i;
02221     N->PointerEquivLabel = 0;
02222   }
02223   HU();
02224 #undef DEBUG_TYPE
02225 #define DEBUG_TYPE "anders-aa-labels"
02226   DEBUG(PrintLabels());
02227 #undef DEBUG_TYPE
02228 #define DEBUG_TYPE "anders-aa"
02229   RewriteConstraints();
02230   for (unsigned i = 0; i < GraphNodes.size(); ++i) {
02231     if (FindNode(i) == i) {
02232       Node *N = &GraphNodes[i];
02233       delete N->PointsTo;
02234       N->PointsTo = NULL;
02235       delete N->PredEdges;
02236       N->PredEdges = NULL;
02237       delete N->ImplicitPredEdges;
02238       N->ImplicitPredEdges = NULL;
02239       delete N->PointedToBy;
02240       N->PointedToBy = NULL;
02241     }
02242   }
02243 
02244   // perform Hybrid Cycle Detection (HCD)
02245   HCD();
02246   SDTActive = true;
02247 
02248   // No longer any need for the upper half of GraphNodes (for ref nodes).
02249   GraphNodes.erase(GraphNodes.begin() + FirstRefNode, GraphNodes.end());
02250 
02251   // HCD complete.
02252 
02253   DOUT << "Finished constraint optimization\n";
02254   FirstRefNode = 0;
02255   FirstAdrNode = 0;
02256 }
02257 
02258 /// Unite pointer but not location equivalent variables, now that the constraint
02259 /// graph is built.
02260 void Andersens::UnitePointerEquivalences() {
02261   DOUT << "Uniting remaining pointer equivalences\n";
02262   for (unsigned i = 0; i < GraphNodes.size(); ++i) {
02263     if (GraphNodes[i].AddressTaken && GraphNodes[i].isRep()) {
02264       unsigned Label = GraphNodes[i].PointerEquivLabel;
02265 
02266       if (Label && PENLEClass2Node[Label] != -1)
02267         UniteNodes(i, PENLEClass2Node[Label]);
02268     }
02269   }
02270   DOUT << "Finished remaining pointer equivalences\n";
02271   PENLEClass2Node.clear();
02272 }
02273 
02274 /// Create the constraint graph used for solving points-to analysis.
02275 ///
02276 void Andersens::CreateConstraintGraph() {
02277   for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
02278     Constraint &C = Constraints[i];
02279     assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
02280     if (C.Type == Constraint::AddressOf)
02281       GraphNodes[C.Dest].PointsTo->set(C.Src);
02282     else if (C.Type == Constraint::Load)
02283       GraphNodes[C.Src].Constraints.push_back(C);
02284     else if (C.Type == Constraint::Store)
02285       GraphNodes[C.Dest].Constraints.push_back(C);
02286     else if (C.Offset != 0)
02287       GraphNodes[C.Src].Constraints.push_back(C);
02288     else
02289       GraphNodes[C.Src].Edges->set(C.Dest);
02290   }
02291 }
02292 
02293 // Perform DFS and cycle detection.
02294 bool Andersens::QueryNode(unsigned Node) {
02295   assert(GraphNodes[Node].isRep() && "Querying a non-rep node");
02296   unsigned OurDFS = ++DFSNumber;
02297   SparseBitVector<> ToErase;
02298   SparseBitVector<> NewEdges;
02299   Tarjan2DFS[Node] = OurDFS;
02300 
02301   // Changed denotes a change from a recursive call that we will bubble up.
02302   // Merged is set if we actually merge a node ourselves.
02303   bool Changed = false, Merged = false;
02304 
02305   for (SparseBitVector<>::iterator bi = GraphNodes[Node].Edges->begin();
02306        bi != GraphNodes[Node].Edges->end();
02307        ++bi) {
02308     unsigned RepNode = FindNode(*bi);
02309     // If this edge points to a non-representative node but we are
02310     // already planning to add an edge to its representative, we have no
02311     // need for this edge anymore.
02312     if (RepNode != *bi && NewEdges.test(RepNode)){
02313       ToErase.set(*bi);
02314       continue;
02315     }
02316 
02317     // Continue about our DFS.
02318     if (!Tarjan2Deleted[RepNode]){
02319       if (Tarjan2DFS[RepNode] == 0) {
02320         Changed |= QueryNode(RepNode);
02321         // May have been changed by QueryNode
02322         RepNode = FindNode(RepNode);
02323       }
02324       if (Tarjan2DFS[RepNode] < Tarjan2DFS[Node])
02325         Tarjan2DFS[Node] = Tarjan2DFS[RepNode];
02326     }
02327 
02328     // We may have just discovered that this node is part of a cycle, in
02329     // which case we can also erase it.
02330     if (RepNode != *bi) {
02331       ToErase.set(*bi);
02332       NewEdges.set(RepNode);
02333     }
02334   }
02335 
02336   GraphNodes[Node].Edges->intersectWithComplement(ToErase);
02337   GraphNodes[Node].Edges |= NewEdges;
02338 
02339   // If this node is a root of a non-trivial SCC, place it on our 
02340   // worklist to be processed.
02341   if (OurDFS == Tarjan2DFS[Node]) {
02342     while (!SCCStack.empty() && Tarjan2DFS[SCCStack.top()] >= OurDFS) {
02343       Node = UniteNodes(Node, SCCStack.top());
02344 
02345       SCCStack.pop();
02346       Merged = true;
02347     }
02348     Tarjan2Deleted[Node] = true;
02349 
02350     if (Merged)
02351       NextWL->insert(&GraphNodes[Node]);
02352   } else {
02353     SCCStack.push(Node);
02354   }
02355 
02356   return(Changed | Merged);
02357 }
02358 
02359 /// SolveConstraints - This stage iteratively processes the constraints list
02360 /// propagating constraints (adding edges to the Nodes in the points-to graph)
02361 /// until a fixed point is reached.
02362 ///
02363 /// We use a variant of the technique called "Lazy Cycle Detection", which is
02364 /// described in "The Ant and the Grasshopper: Fast and Accurate Pointer
02365 /// Analysis for Millions of Lines of Code. In Programming Language Design and
02366 /// Implementation (PLDI), June 2007."
02367 /// The paper describes performing cycle detection one node at a time, which can
02368 /// be expensive if there are no cycles, but there are long chains of nodes that
02369 /// it heuristically believes are cycles (because it will DFS from each node
02370 /// without state from previous nodes).
02371 /// Instead, we use the heuristic to build a worklist of nodes to check, then
02372 /// cycle detect them all at the same time to do this more cheaply.  This
02373 /// catches cycles slightly later than the original technique did, but does it
02374 /// make significantly cheaper.
02375 
02376 void Andersens::SolveConstraints() {
02377   CurrWL = &w1;
02378   NextWL = &w2;
02379 
02380   OptimizeConstraints();
02381 #undef DEBUG_TYPE
02382 #define DEBUG_TYPE "anders-aa-constraints"
02383       DEBUG(PrintConstraints());
02384 #undef DEBUG_TYPE
02385 #define DEBUG_TYPE "anders-aa"
02386 
02387   for (unsigned i = 0; i < GraphNodes.size(); ++i) {
02388     Node *N = &GraphNodes[i];
02389     N->PointsTo = new SparseBitVector<>;
02390     N->OldPointsTo = new SparseBitVector<>;
02391     N->Edges = new SparseBitVector<>;
02392   }
02393   CreateConstraintGraph();
02394   UnitePointerEquivalences();
02395   assert(SCCStack.empty() && "SCC Stack should be empty by now!");
02396   Node2DFS.clear();
02397   Node2Deleted.clear();
02398   Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
02399   Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
02400   DFSNumber = 0;
02401   DenseSet<Constraint, ConstraintKeyInfo> Seen;
02402   DenseSet<std::pair<unsigned,unsigned>, PairKeyInfo> EdgesChecked;
02403 
02404   // Order graph and add initial nodes to work list.
02405   for (unsigned i = 0; i < GraphNodes.size(); ++i) {
02406     Node *INode = &GraphNodes[i];
02407 
02408     // Add to work list if it's a representative and can contribute to the
02409     // calculation right now.
02410     if (INode->isRep() && !INode->PointsTo->empty()
02411         && (!INode->Edges->empty() || !INode->Constraints.empty())) {
02412       INode->Stamp();
02413       CurrWL->insert(INode);
02414     }
02415   }
02416   std::queue<unsigned int> TarjanWL;
02417 #if !FULL_UNIVERSAL
02418   // "Rep and special variables" - in order for HCD to maintain conservative
02419   // results when !FULL_UNIVERSAL, we need to treat the special variables in
02420   // the same way that the !FULL_UNIVERSAL tweak does throughout the rest of
02421   // the analysis - it's ok to add edges from the special nodes, but never
02422   // *to* the special nodes.
02423   std::vector<unsigned int> RSV;
02424 #endif
02425   while( !CurrWL->empty() ) {
02426     DOUT << "Starting iteration #" << ++NumIters << "\n";
02427 
02428     Node* CurrNode;
02429     unsigned CurrNodeIndex;
02430 
02431     // Actual cycle checking code.  We cycle check all of the lazy cycle
02432     // candidates from the last iteration in one go.
02433     if (!TarjanWL.empty()) {
02434       DFSNumber = 0;
02435       
02436       Tarjan2DFS.clear();
02437       Tarjan2Deleted.clear();
02438       while (!TarjanWL.empty()) {
02439         unsigned int ToTarjan = TarjanWL.front();
02440         TarjanWL.pop();
02441         if (!Tarjan2Deleted[ToTarjan]
02442             && GraphNodes[ToTarjan].isRep()
02443             && Tarjan2DFS[ToTarjan] == 0)
02444           QueryNode(ToTarjan);
02445       }
02446     }
02447     
02448     // Add to work list if it's a representative and can contribute to the
02449     // calculation right now.
02450     while( (CurrNode = CurrWL->pop()) != NULL ) {
02451       CurrNodeIndex = CurrNode - &GraphNodes[0];
02452       CurrNode->Stamp();
02453       
02454           
02455       // Figure out the changed points to bits
02456       SparseBitVector<> CurrPointsTo;
02457       CurrPointsTo.intersectWithComplement(CurrNode->PointsTo,
02458                                            CurrNode->OldPointsTo);
02459       if (CurrPointsTo.empty())
02460         continue;
02461 
02462       *(CurrNode->OldPointsTo) |= CurrPointsTo;
02463 
02464       // Check the offline-computed equivalencies from HCD.
02465       bool SCC = false;
02466       unsigned Rep;
02467 
02468       if (SDT[CurrNodeIndex] >= 0) {
02469         SCC = true;
02470         Rep = FindNode(SDT[CurrNodeIndex]);
02471 
02472 #if !FULL_UNIVERSAL
02473         RSV.clear();
02474 #endif
02475         for (SparseBitVector<>::iterator bi = CurrPointsTo.begin();
02476              bi != CurrPointsTo.end(); ++bi) {
02477           unsigned Node = FindNode(*bi);
02478 #if !FULL_UNIVERSAL
02479           if (Node < NumberSpecialNodes) {
02480             RSV.push_back(Node);
02481             continue;
02482           }
02483 #endif
02484           Rep = UniteNodes(Rep,Node);
02485         }
02486 #if !FULL_UNIVERSAL
02487         RSV.push_back(Rep);
02488 #endif
02489 
02490         NextWL->insert(&GraphNodes[Rep]);
02491 
02492         if ( ! CurrNode->isRep() )
02493           continue;
02494       }
02495 
02496       Seen.clear();
02497 
02498       /* Now process the constraints for this node.  */
02499       for (std::list<Constraint>::iterator li = CurrNode->Constraints.begin();
02500            li != CurrNode->Constraints.end(); ) {
02501         li->Src = FindNode(li->Src);
02502         li->Dest = FindNode(li->Dest);
02503 
02504         // Delete redundant constraints
02505         if( Seen.count(*li) ) {
02506           std::list<Constraint>::iterator lk = li; li++;
02507 
02508           CurrNode->Constraints.erase(lk);
02509           ++NumErased;
02510           continue;
02511         }
02512         Seen.insert(*li);
02513 
02514         // Src and Dest will be the vars we are going to process.
02515         // This may look a bit ugly, but what it does is allow us to process
02516         // both store and load constraints with the same code.
02517         // Load constraints say that every member of our RHS solution has K
02518         // added to it, and that variable gets an edge to LHS. We also union
02519         // RHS+K's solution into the LHS solution.
02520         // Store constraints say that every member of our LHS solution has K
02521         // added to it, and that variable gets an edge from RHS. We also union
02522         // RHS's solution into the LHS+K solution.
02523         unsigned *Src;
02524         unsigned *Dest;
02525         unsigned K = li->Offset;
02526         unsigned CurrMember;
02527         if (li->Type == Constraint::Load) {
02528           Src = &CurrMember;
02529           Dest = &li->Dest;
02530         } else if (li->Type == Constraint::Store) {
02531           Src = &li->Src;
02532           Dest = &CurrMember;
02533         } else {
02534           // TODO Handle offseted copy constraint
02535           li++;
02536           continue;
02537         }
02538 
02539         // See if we can use Hybrid Cycle Detection (that is, check
02540         // if it was a statically detected offline equivalence that
02541         // involves pointers; if so, remove the redundant constraints).
02542         if( SCC && K == 0 ) {
02543 #if FULL_UNIVERSAL
02544           CurrMember = Rep;
02545 
02546           if (GraphNodes[*Src].Edges->test_and_set(*Dest))
02547             if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
02548               NextWL->insert(&GraphNodes[*Dest]);
02549 #else
02550           for (unsigned i=0; i < RSV.size(); ++i) {
02551             CurrMember = RSV[i];
02552 
02553             if (*Dest < NumberSpecialNodes)
02554               continue;
02555             if (GraphNodes[*Src].Edges->test_and_set(*Dest))
02556               if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
02557                 NextWL->insert(&GraphNodes[*Dest]);
02558           }
02559 #endif
02560           // since all future elements of the points-to set will be
02561           // equivalent to the current ones, the complex constraints
02562           // become redundant.
02563           //
02564           std::list<Constraint>::iterator lk = li; li++;
02565 #if !FULL_UNIVERSAL
02566           // In this case, we can still erase the constraints when the
02567           // elements of the points-to sets are referenced by *Dest,
02568           // but not when they are referenced by *Src (i.e. for a Load
02569           // constraint). This is because if another special variable is
02570           // put into the points-to set later, we still need to add the
02571           // new edge from that special variable.
02572           if( lk->Type != Constraint::Load)
02573 #endif
02574           GraphNodes[CurrNodeIndex].Constraints.erase(lk);
02575         } else {
02576           const SparseBitVector<> &Solution = CurrPointsTo;
02577 
02578           for (SparseBitVector<>::iterator bi = Solution.begin();
02579                bi != Solution.end();
02580                ++bi) {
02581             CurrMember = *bi;
02582 
02583             // Need to increment the member by K since that is where we are
02584             // supposed to copy to/from.  Note that in positive weight cycles,
02585             // which occur in address taking of fields, K can go past
02586             // MaxK[CurrMember] elements, even though that is all it could point
02587             // to.
02588             if (K > 0 && K > MaxK[CurrMember])
02589               continue;
02590             else
02591               CurrMember = FindNode(CurrMember + K);
02592 
02593             // Add an edge to the graph, so we can just do regular
02594             // bitmap ior next time.  It may also let us notice a cycle.
02595 #if !FULL_UNIVERSAL
02596             if (*Dest < NumberSpecialNodes)
02597               continue;
02598 #endif
02599             if (GraphNodes[*Src].Edges->test_and_set(*Dest))
02600               if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
02601                 NextWL->insert(&GraphNodes[*Dest]);
02602 
02603           }
02604           li++;
02605         }
02606       }
02607       SparseBitVector<> NewEdges;
02608       SparseBitVector<> ToErase;
02609 
02610       // Now all we have left to do is propagate points-to info along the
02611       // edges, erasing the redundant edges.
02612       for (SparseBitVector<>::iterator bi = CurrNode->Edges->begin();
02613            bi != CurrNode->Edges->end();
02614            ++bi) {
02615 
02616         unsigned DestVar = *bi;
02617         unsigned Rep = FindNode(DestVar);
02618 
02619         // If we ended up with this node as our destination, or we've already
02620         // got an edge for the representative, delete the current edge.
02621         if (Rep == CurrNodeIndex ||
02622             (Rep != DestVar && NewEdges.test(Rep))) {
02623             ToErase.set(DestVar);
02624             continue;
02625         }
02626         
02627         std::pair<unsigned,unsigned> edge(CurrNodeIndex,Rep);
02628         
02629         // This is where we do lazy cycle detection.
02630         // If this is a cycle candidate (equal points-to sets and this
02631         // particular edge has not been cycle-checked previously), add to the
02632         // list to check for cycles on the next iteration.
02633         if (!EdgesChecked.count(edge) &&
02634             *(GraphNodes[Rep].PointsTo) == *(CurrNode->PointsTo)) {
02635           EdgesChecked.insert(edge);
02636           TarjanWL.push(Rep);
02637         }
02638         // Union the points-to sets into the dest
02639 #if !FULL_UNIVERSAL
02640         if (Rep >= NumberSpecialNodes)
02641 #endif
02642         if (GraphNodes[Rep].PointsTo |= CurrPointsTo) {
02643           NextWL->insert(&GraphNodes[Rep]);
02644         }
02645         // If this edge's destination was collapsed, rewrite the edge.
02646         if (Rep != DestVar) {
02647           ToErase.set(DestVar);
02648           NewEdges.set(Rep);
02649         }
02650       }
02651       CurrNode->Edges->intersectWithComplement(ToErase);
02652       CurrNode->Edges |= NewEdges;
02653     }
02654 
02655     // Switch to other work list.
02656     WorkList* t = CurrWL; CurrWL = NextWL; NextWL = t;
02657   }
02658 
02659 
02660   Node2DFS.clear();
02661   Node2Deleted.clear();
02662   for (unsigned i = 0; i < GraphNodes.size(); ++i) {
02663     Node *N = &GraphNodes[i];
02664     delete N->OldPointsTo;
02665     delete N->Edges;
02666   }
02667   SDTActive = false;
02668   SDT.clear();
02669 }
02670 
02671 //===----------------------------------------------------------------------===//
02672 //                               Union-Find
02673 //===----------------------------------------------------------------------===//
02674 
02675 // Unite nodes First and Second, returning the one which is now the
02676 // representative node.  First and Second are indexes into GraphNodes
02677 unsigned Andersens::UniteNodes(unsigned First, unsigned Second,
02678                                bool UnionByRank) {
02679   assert (First < GraphNodes.size() && Second < GraphNodes.size() &&
02680           "Attempting to merge nodes that don't exist");
02681 
02682   Node *FirstNode = &GraphNodes[First];
02683   Node *SecondNode = &GraphNodes[Second];
02684 
02685   assert (SecondNode->isRep() && FirstNode->isRep() &&
02686           "Trying to unite two non-representative nodes!");
02687   if (First == Second)
02688     return First;
02689 
02690   if (UnionByRank) {
02691     int RankFirst  = (int) FirstNode ->NodeRep;
02692     int RankSecond = (int) SecondNode->NodeRep;
02693 
02694     // Rank starts at -1 and gets decremented as it increases.
02695     // Translation: higher rank, lower NodeRep value, which is always negative.
02696     if (RankFirst > RankSecond) {
02697       unsigned t = First; First = Second; Second = t;
02698       Node* tp = FirstNode; FirstNode = SecondNode; SecondNode = tp;
02699     } else if (RankFirst == RankSecond) {
02700       FirstNode->NodeRep = (unsigned) (RankFirst - 1);
02701     }
02702   }
02703 
02704   SecondNode->NodeRep = First;
02705 #if !FULL_UNIVERSAL
02706   if (First >= NumberSpecialNodes)
02707 #endif
02708   if (FirstNode->PointsTo && SecondNode->PointsTo)
02709     FirstNode->PointsTo |= *(SecondNode->PointsTo);
02710   if (FirstNode->Edges && SecondNode->Edges)
02711     FirstNode->Edges |= *(SecondNode->Edges);
02712   if (!SecondNode->Constraints.empty())
02713     FirstNode->Constraints.splice(FirstNode->Constraints.begin(),
02714                                   SecondNode->Constraints);
02715   if (FirstNode->OldPointsTo) {
02716     delete FirstNode->OldPointsTo;
02717     FirstNode->OldPointsTo = new SparseBitVector<>;
02718   }
02719 
02720   // Destroy interesting parts of the merged-from node.
02721   delete SecondNode->OldPointsTo;
02722   delete SecondNode->Edges;
02723   delete SecondNode->PointsTo;
02724   SecondNode->Edges = NULL;
02725   SecondNode->PointsTo = NULL;
02726   SecondNode->OldPointsTo = NULL;
02727 
02728   NumUnified++;
02729   DOUT << "Unified Node ";
02730   DEBUG(PrintNode(FirstNode));
02731   DOUT << " and Node ";
02732   DEBUG(PrintNode(SecondNode));
02733   DOUT << "\n";
02734 
02735   if (SDTActive)
02736     if (SDT[Second] >= 0) {
02737       if (SDT[First] < 0)
02738         SDT[First] = SDT[Second];
02739       else {
02740         UniteNodes( FindNode(SDT[First]), FindNode(SDT[Second]) );
02741         First = FindNode(First);
02742       }
02743     }
02744 
02745   return First;
02746 }
02747 
02748 // Find the index into GraphNodes of the node representing Node, performing
02749 // path compression along the way
02750 unsigned Andersens::FindNode(unsigned NodeIndex) {
02751   assert (NodeIndex < GraphNodes.size()
02752           && "Attempting to find a node that can't exist");
02753   Node *N = &GraphNodes[NodeIndex];
02754   if (N->isRep())
02755     return NodeIndex;
02756   else
02757     return (N->NodeRep = FindNode(N->NodeRep));
02758 }
02759 
02760 // Find the index into GraphNodes of the node representing Node, 
02761 // don't perform path compression along the way (for Print)
02762 unsigned Andersens::FindNode(unsigned NodeIndex) const {
02763   assert (NodeIndex < GraphNodes.size()
02764           && "Attempting to find a node that can't exist");
02765   const Node *N = &GraphNodes[NodeIndex];
02766   if (N->isRep())
02767     return NodeIndex;
02768   else
02769     return FindNode(N->NodeRep);
02770 }
02771 
02772 //===----------------------------------------------------------------------===//
02773 //                               Debugging Output
02774 //===----------------------------------------------------------------------===//
02775 
02776 void Andersens::PrintNode(const Node *N) const {
02777   if (N == &GraphNodes[UniversalSet]) {
02778     cerr << "<universal>";
02779     return;
02780   } else if (N == &GraphNodes[NullPtr]) {
02781     cerr << "<nullptr>";
02782     return;
02783   } else if (N == &GraphNodes[NullObject]) {
02784     cerr << "<null>";
02785     return;
02786   }
02787   if (!N->getValue()) {
02788     cerr << "artificial" << (intptr_t) N;
02789     return;
02790   }
02791 
02792   assert(N->getValue() != 0 && "Never set node label!");
02793   Value *V = N->getValue();
02794   if (Function *F = dyn_cast<Function>(V)) {
02795     if (isa<PointerType>(F->getFunctionType()->getReturnType()) &&
02796         N == &GraphNodes[getReturnNode(F)]) {
02797       cerr << F->getName() << ":retval";
02798       return;
02799     } else if (F->getFunctionType()->isVarArg() &&
02800                N == &GraphNodes[getVarargNode(F)]) {
02801       cerr << F->getName() << ":vararg";
02802       return;
02803     }
02804   }
02805 
02806   if (Instruction *I = dyn_cast<Instruction>(V))
02807     cerr << I->getParent()->getParent()->getName() << ":";
02808   else if (Argument *Arg = dyn_cast<Argument>(V))
02809     cerr << Arg->getParent()->getName() << ":";
02810 
02811   if (V->hasName())
02812     cerr << V->getName();
02813   else
02814     cerr << "(unnamed)";
02815 
02816   if (isa<GlobalValue>(V) || isa<AllocationInst>(V))
02817     if (N == &GraphNodes[getObject(V)])
02818       cerr << "<mem>";
02819 }
02820 void Andersens::PrintConstraint(const Constraint &C) const {
02821   if (C.Type == Constraint::Store) {
02822     cerr << "*";
02823     if (C.Offset != 0)
02824       cerr << "(";
02825   }
02826   PrintNode(&GraphNodes[C.Dest]);
02827   if (C.Type == Constraint::Store && C.Offset != 0)
02828     cerr << " + " << C.Offset << ")";
02829   cerr << " = ";
02830   if (C.Type == Constraint::Load) {
02831     cerr << "*";
02832     if (C.Offset != 0)
02833       cerr << "(";
02834   }
02835   else if (C.Type == Constraint::AddressOf)
02836     cerr << "&";
02837   PrintNode(&GraphNodes[C.Src]);
02838   if (C.Offset != 0 && C.Type != Constraint::Store)
02839     cerr << " + " << C.Offset;
02840   if (C.Type == Constraint::Load && C.Offset != 0)
02841     cerr << ")";
02842   cerr << "\n";
02843 }
02844 
02845 void Andersens::PrintConstraints() const {
02846   cerr << "Constraints:\n";
02847 
02848   for (unsigned i = 0, e = Constraints.size(); i != e; ++i)
02849     PrintConstraint(Constraints[i]);
02850 }
02851 
02852 void Andersens::PrintPointsToGraph() const {
02853   cerr << "Points-to graph:\n";
02854   for (unsigned i = 0, e = GraphNodes.size(); i != e; ++i) {
02855     const Node *N = &GraphNodes[i];
02856     if (FindNode(i) != i) {
02857       PrintNode(N);
02858       cerr << "\t--> same as ";
02859       PrintNode(&GraphNodes[FindNode(i)]);
02860       cerr << "\n";
02861     } else {
02862       cerr << "[" << (N->PointsTo->count()) << "] ";
02863       PrintNode(N);
02864       cerr << "\t--> ";
02865 
02866       bool first = true;
02867       for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
02868            bi != N->PointsTo->end();
02869            ++bi) {
02870         if (!first)
02871           cerr << ", ";
02872         PrintNode(&GraphNodes[*bi]);
02873         first = false;
02874       }
02875       cerr << "\n";
02876     }
02877   }
02878 }