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