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