1 //===- Andersens.cpp - Andersen's Interprocedural Alias Analysis ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines an implementation of Andersen's interprocedural alias
13 // In pointer analysis terms, this is a subset-based, flow-insensitive,
14 // field-sensitive, and context-insensitive algorithm pointer algorithm.
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.
22 // The object identification stage identifies all of the memory objects in the
23 // program, which includes globals, heap allocated objects, and stack allocated
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
33 // The offline constraint graph optimization portion includes offline variable
34 // substitution algorithms intended to compute pointer and location
35 // equivalences. Pointer equivalences are those pointers that will have the
36 // same points-to sets, and location equivalences are those variables that
37 // always appear together in points-to sets. It also includes an offline
38 // cycle detection algorithm that allows cycles to be collapsed sooner
41 // The inclusion constraint solving phase iteratively propagates the inclusion
42 // constraints until a fixed point is reached. This is an O(N^3) algorithm.
44 // Function constraints are handled as if they were structs with X fields.
45 // Thus, an access to argument X of function Y is an access to node index
46 // getNode(Y) + X. This representation allows handling of indirect calls
47 // without any issues. To wit, an indirect call Y(a,b) is equivalent to
48 // *(Y + 1) = a, *(Y + 2) = b.
49 // The return node for a function is always located at getNode(F) +
50 // CallReturnPos. The arguments start at getNode(F) + CallArgPos.
52 // Future Improvements:
54 //===----------------------------------------------------------------------===//
56 #define DEBUG_TYPE "anders-aa"
57 #include "llvm/Constants.h"
58 #include "llvm/DerivedTypes.h"
59 #include "llvm/Instructions.h"
60 #include "llvm/Module.h"
61 #include "llvm/Pass.h"
62 #include "llvm/Support/Compiler.h"
63 #include "llvm/Support/InstIterator.h"
64 #include "llvm/Support/InstVisitor.h"
65 #include "llvm/Analysis/AliasAnalysis.h"
66 #include "llvm/Analysis/Passes.h"
67 #include "llvm/Support/Debug.h"
68 #include "llvm/System/Atomic.h"
69 #include "llvm/ADT/Statistic.h"
70 #include "llvm/ADT/SparseBitVector.h"
71 #include "llvm/ADT/DenseSet.h"
80 // Determining the actual set of nodes the universal set can consist of is very
81 // expensive because it means propagating around very large sets. We rely on
82 // other analysis being able to determine which nodes can never be pointed to in
83 // order to disambiguate further than "points-to anything".
84 #define FULL_UNIVERSAL 0
87 STATISTIC(NumIters , "Number of iterations to reach convergence");
88 STATISTIC(NumConstraints, "Number of constraints");
89 STATISTIC(NumNodes , "Number of nodes");
90 STATISTIC(NumUnified , "Number of variables unified");
91 STATISTIC(NumErased , "Number of redundant constraints erased");
93 static const unsigned SelfRep = (unsigned)-1;
94 static const unsigned Unvisited = (unsigned)-1;
95 // Position of the function return node relative to the function node.
96 static const unsigned CallReturnPos = 1;
97 // Position of the function call node relative to the function node.
98 static const unsigned CallFirstArgPos = 2;
101 struct BitmapKeyInfo {
102 static inline SparseBitVector<> *getEmptyKey() {
103 return reinterpret_cast<SparseBitVector<> *>(-1);
105 static inline SparseBitVector<> *getTombstoneKey() {
106 return reinterpret_cast<SparseBitVector<> *>(-2);
108 static unsigned getHashValue(const SparseBitVector<> *bitmap) {
109 return bitmap->getHashValue();
111 static bool isEqual(const SparseBitVector<> *LHS,
112 const SparseBitVector<> *RHS) {
115 else if (LHS == getEmptyKey() || RHS == getEmptyKey()
116 || LHS == getTombstoneKey() || RHS == getTombstoneKey())
122 static bool isPod() { return true; }
125 class VISIBILITY_HIDDEN Andersens : public ModulePass, public AliasAnalysis,
126 private InstVisitor<Andersens> {
129 /// Constraint - Objects of this structure are used to represent the various
130 /// constraints identified by the algorithm. The constraints are 'copy',
131 /// for statements like "A = B", 'load' for statements like "A = *B",
132 /// 'store' for statements like "*A = B", and AddressOf for statements like
133 /// A = alloca; The Offset is applied as *(A + K) = B for stores,
134 /// A = *(B + K) for loads, and A = B + K for copies. It is
135 /// illegal on addressof constraints (because it is statically
136 /// resolvable to A = &C where C = B + K)
139 enum ConstraintType { Copy, Load, Store, AddressOf } Type;
144 Constraint(ConstraintType Ty, unsigned D, unsigned S, unsigned O = 0)
145 : Type(Ty), Dest(D), Src(S), Offset(O) {
146 assert((Offset == 0 || Ty != AddressOf) &&
147 "Offset is illegal on addressof constraints");
150 bool operator==(const Constraint &RHS) const {
151 return RHS.Type == Type
154 && RHS.Offset == Offset;
157 bool operator!=(const Constraint &RHS) const {
158 return !(*this == RHS);
161 bool operator<(const Constraint &RHS) const {
162 if (RHS.Type != Type)
163 return RHS.Type < Type;
164 else if (RHS.Dest != Dest)
165 return RHS.Dest < Dest;
166 else if (RHS.Src != Src)
167 return RHS.Src < Src;
168 return RHS.Offset < Offset;
172 // Information DenseSet requires implemented in order to be able to do
175 static inline std::pair<unsigned, unsigned> getEmptyKey() {
176 return std::make_pair(~0U, ~0U);
178 static inline std::pair<unsigned, unsigned> getTombstoneKey() {
179 return std::make_pair(~0U - 1, ~0U - 1);
181 static unsigned getHashValue(const std::pair<unsigned, unsigned> &P) {
182 return P.first ^ P.second;
184 static unsigned isEqual(const std::pair<unsigned, unsigned> &LHS,
185 const std::pair<unsigned, unsigned> &RHS) {
190 struct ConstraintKeyInfo {
191 static inline Constraint getEmptyKey() {
192 return Constraint(Constraint::Copy, ~0U, ~0U, ~0U);
194 static inline Constraint getTombstoneKey() {
195 return Constraint(Constraint::Copy, ~0U - 1, ~0U - 1, ~0U - 1);
197 static unsigned getHashValue(const Constraint &C) {
198 return C.Src ^ C.Dest ^ C.Type ^ C.Offset;
200 static bool isEqual(const Constraint &LHS,
201 const Constraint &RHS) {
202 return LHS.Type == RHS.Type && LHS.Dest == RHS.Dest
203 && LHS.Src == RHS.Src && LHS.Offset == RHS.Offset;
207 // Node class - This class is used to represent a node in the constraint
208 // graph. Due to various optimizations, it is not always the case that
209 // there is a mapping from a Node to a Value. In particular, we add
210 // artificial Node's that represent the set of pointed-to variables shared
211 // for each location equivalent Node.
214 static volatile sys::cas_flag Counter;
218 SparseBitVector<> *Edges;
219 SparseBitVector<> *PointsTo;
220 SparseBitVector<> *OldPointsTo;
221 std::list<Constraint> Constraints;
223 // Pointer and location equivalence labels
224 unsigned PointerEquivLabel;
225 unsigned LocationEquivLabel;
226 // Predecessor edges, both real and implicit
227 SparseBitVector<> *PredEdges;
228 SparseBitVector<> *ImplicitPredEdges;
229 // Set of nodes that point to us, only use for location equivalence.
230 SparseBitVector<> *PointedToBy;
231 // Number of incoming edges, used during variable substitution to early
232 // free the points-to sets
234 // True if our points-to set is in the Set2PEClass map
236 // True if our node has no indirect constraints (complex or otherwise)
238 // True if the node is address taken, *or* it is part of a group of nodes
239 // that must be kept together. This is set to true for functions and
240 // their arg nodes, which must be kept at the same position relative to
241 // their base function node.
244 // Nodes in cycles (or in equivalence classes) are united together using a
245 // standard union-find representation with path compression. NodeRep
246 // gives the index into GraphNodes for the representative Node.
249 // Modification timestamp. Assigned from Counter.
250 // Used for work list prioritization.
253 explicit Node(bool direct = true) :
254 Val(0), Edges(0), PointsTo(0), OldPointsTo(0),
255 PointerEquivLabel(0), LocationEquivLabel(0), PredEdges(0),
256 ImplicitPredEdges(0), PointedToBy(0), NumInEdges(0),
257 StoredInHash(false), Direct(direct), AddressTaken(false),
258 NodeRep(SelfRep), Timestamp(0) { }
260 Node *setValue(Value *V) {
261 assert(Val == 0 && "Value already set for this node!");
266 /// getValue - Return the LLVM value corresponding to this node.
268 Value *getValue() const { return Val; }
270 /// addPointerTo - Add a pointer to the list of pointees of this node,
271 /// returning true if this caused a new pointer to be added, or false if
272 /// we already knew about the points-to relation.
273 bool addPointerTo(unsigned Node) {
274 return PointsTo->test_and_set(Node);
277 /// intersects - Return true if the points-to set of this node intersects
278 /// with the points-to set of the specified node.
279 bool intersects(Node *N) const;
281 /// intersectsIgnoring - Return true if the points-to set of this node
282 /// intersects with the points-to set of the specified node on any nodes
283 /// except for the specified node to ignore.
284 bool intersectsIgnoring(Node *N, unsigned) const;
286 // Timestamp a node (used for work list prioritization)
288 Timestamp = sys::AtomicIncrement(&Counter);
293 return( (int) NodeRep < 0 );
297 struct WorkListElement {
300 WorkListElement(Node* n, unsigned t) : node(n), Timestamp(t) {}
302 // Note that we reverse the sense of the comparison because we
303 // actually want to give low timestamps the priority over high,
304 // whereas priority is typically interpreted as a greater value is
305 // given high priority.
306 bool operator<(const WorkListElement& that) const {
307 return( this->Timestamp > that.Timestamp );
311 // Priority-queue based work list specialized for Nodes.
313 std::priority_queue<WorkListElement> Q;
316 void insert(Node* n) {
317 Q.push( WorkListElement(n, n->Timestamp) );
320 // We automatically discard non-representative nodes and nodes
321 // that were in the work list twice (we keep a copy of the
322 // timestamp in the work list so we can detect this situation by
323 // comparing against the node's current timestamp).
325 while( !Q.empty() ) {
326 WorkListElement x = Q.top(); Q.pop();
327 Node* INode = x.node;
329 if( INode->isRep() &&
330 INode->Timestamp == x.Timestamp ) {
342 /// GraphNodes - This vector is populated as part of the object
343 /// identification stage of the analysis, which populates this vector with a
344 /// node for each memory object and fills in the ValueNodes map.
345 std::vector<Node> GraphNodes;
347 /// ValueNodes - This map indicates the Node that a particular Value* is
348 /// represented by. This contains entries for all pointers.
349 DenseMap<Value*, unsigned> ValueNodes;
351 /// ObjectNodes - This map contains entries for each memory object in the
352 /// program: globals, alloca's and mallocs.
353 DenseMap<Value*, unsigned> ObjectNodes;
355 /// ReturnNodes - This map contains an entry for each function in the
356 /// program that returns a value.
357 DenseMap<Function*, unsigned> ReturnNodes;
359 /// VarargNodes - This map contains the entry used to represent all pointers
360 /// passed through the varargs portion of a function call for a particular
361 /// function. An entry is not present in this map for functions that do not
362 /// take variable arguments.
363 DenseMap<Function*, unsigned> VarargNodes;
366 /// Constraints - This vector contains a list of all of the constraints
367 /// identified by the program.
368 std::vector<Constraint> Constraints;
370 // Map from graph node to maximum K value that is allowed (for functions,
371 // this is equivalent to the number of arguments + CallFirstArgPos)
372 std::map<unsigned, unsigned> MaxK;
374 /// This enum defines the GraphNodes indices that correspond to important
382 // Stack for Tarjan's
383 std::stack<unsigned> SCCStack;
384 // Map from Graph Node to DFS number
385 std::vector<unsigned> Node2DFS;
386 // Map from Graph Node to Deleted from graph.
387 std::vector<bool> Node2Deleted;
388 // Same as Node Maps, but implemented as std::map because it is faster to
390 std::map<unsigned, unsigned> Tarjan2DFS;
391 std::map<unsigned, bool> Tarjan2Deleted;
392 // Current DFS number
397 WorkList *CurrWL, *NextWL; // "current" and "next" work lists
399 // Offline variable substitution related things
401 // Temporary rep storage, used because we can't collapse SCC's in the
402 // predecessor graph by uniting the variables permanently, we can only do so
403 // for the successor graph.
404 std::vector<unsigned> VSSCCRep;
405 // Mapping from node to whether we have visited it during SCC finding yet.
406 std::vector<bool> Node2Visited;
407 // During variable substitution, we create unknowns to represent the unknown
408 // value that is a dereference of a variable. These nodes are known as
409 // "ref" nodes (since they represent the value of dereferences).
410 unsigned FirstRefNode;
411 // During HVN, we create represent address taken nodes as if they were
412 // unknown (since HVN, unlike HU, does not evaluate unions).
413 unsigned FirstAdrNode;
414 // Current pointer equivalence class number
416 // Mapping from points-to sets to equivalence classes
417 typedef DenseMap<SparseBitVector<> *, unsigned, BitmapKeyInfo> BitVectorMap;
418 BitVectorMap Set2PEClass;
419 // Mapping from pointer equivalences to the representative node. -1 if we
420 // have no representative node for this pointer equivalence class yet.
421 std::vector<int> PEClass2Node;
422 // Mapping from pointer equivalences to representative node. This includes
423 // pointer equivalent but not location equivalent variables. -1 if we have
424 // no representative node for this pointer equivalence class yet.
425 std::vector<int> PENLEClass2Node;
426 // Union/Find for HCD
427 std::vector<unsigned> HCDSCCRep;
428 // HCD's offline-detected cycles; "Statically DeTected"
429 // -1 if not part of such a cycle, otherwise a representative node.
430 std::vector<int> SDT;
431 // Whether to use SDT (UniteNodes can use it during solving, but not before)
436 Andersens() : ModulePass(&ID) {}
438 bool runOnModule(Module &M) {
439 InitializeAliasAnalysis(this);
441 CollectConstraints(M);
443 #define DEBUG_TYPE "anders-aa-constraints"
444 DEBUG(PrintConstraints());
446 #define DEBUG_TYPE "anders-aa"
448 DEBUG(PrintPointsToGraph());
450 // Free the constraints list, as we don't need it to respond to alias
452 std::vector<Constraint>().swap(Constraints);
453 //These are needed for Print() (-analyze in opt)
454 //ObjectNodes.clear();
455 //ReturnNodes.clear();
456 //VarargNodes.clear();
460 void releaseMemory() {
461 // FIXME: Until we have transitively required passes working correctly,
462 // this cannot be enabled! Otherwise, using -count-aa with the pass
463 // causes memory to be freed too early. :(
465 // The memory objects and ValueNodes data structures at the only ones that
466 // are still live after construction.
467 std::vector<Node>().swap(GraphNodes);
472 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
473 AliasAnalysis::getAnalysisUsage(AU);
474 AU.setPreservesAll(); // Does not transform code
477 //------------------------------------------------
478 // Implement the AliasAnalysis API
480 AliasResult alias(const Value *V1, unsigned V1Size,
481 const Value *V2, unsigned V2Size);
482 virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
483 virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
484 void getMustAliases(Value *P, std::vector<Value*> &RetVals);
485 bool pointsToConstantMemory(const Value *P);
487 virtual void deleteValue(Value *V) {
489 getAnalysis<AliasAnalysis>().deleteValue(V);
492 virtual void copyValue(Value *From, Value *To) {
493 ValueNodes[To] = ValueNodes[From];
494 getAnalysis<AliasAnalysis>().copyValue(From, To);
498 /// getNode - Return the node corresponding to the specified pointer scalar.
500 unsigned getNode(Value *V) {
501 if (Constant *C = dyn_cast<Constant>(V))
502 if (!isa<GlobalValue>(C))
503 return getNodeForConstantPointer(C);
505 DenseMap<Value*, unsigned>::iterator I = ValueNodes.find(V);
506 if (I == ValueNodes.end()) {
510 assert(0 && "Value does not have a node in the points-to graph!");
515 /// getObject - Return the node corresponding to the memory object for the
516 /// specified global or allocation instruction.
517 unsigned getObject(Value *V) const {
518 DenseMap<Value*, unsigned>::iterator I = ObjectNodes.find(V);
519 assert(I != ObjectNodes.end() &&
520 "Value does not have an object in the points-to graph!");
524 /// getReturnNode - Return the node representing the return value for the
525 /// specified function.
526 unsigned getReturnNode(Function *F) const {
527 DenseMap<Function*, unsigned>::iterator I = ReturnNodes.find(F);
528 assert(I != ReturnNodes.end() && "Function does not return a value!");
532 /// getVarargNode - Return the node representing the variable arguments
533 /// formal for the specified function.
534 unsigned getVarargNode(Function *F) const {
535 DenseMap<Function*, unsigned>::iterator I = VarargNodes.find(F);
536 assert(I != VarargNodes.end() && "Function does not take var args!");
540 /// getNodeValue - Get the node for the specified LLVM value and set the
541 /// value for it to be the specified value.
542 unsigned getNodeValue(Value &V) {
543 unsigned Index = getNode(&V);
544 GraphNodes[Index].setValue(&V);
548 unsigned UniteNodes(unsigned First, unsigned Second,
549 bool UnionByRank = true);
550 unsigned FindNode(unsigned Node);
551 unsigned FindNode(unsigned Node) const;
553 void IdentifyObjects(Module &M);
554 void CollectConstraints(Module &M);
555 bool AnalyzeUsesOfFunction(Value *);
556 void CreateConstraintGraph();
557 void OptimizeConstraints();
558 unsigned FindEquivalentNode(unsigned, unsigned);
559 void ClumpAddressTaken();
560 void RewriteConstraints();
564 void Search(unsigned Node);
565 void UnitePointerEquivalences();
566 void SolveConstraints();
567 bool QueryNode(unsigned Node);
568 void Condense(unsigned Node);
569 void HUValNum(unsigned Node);
570 void HVNValNum(unsigned Node);
571 unsigned getNodeForConstantPointer(Constant *C);
572 unsigned getNodeForConstantPointerTarget(Constant *C);
573 void AddGlobalInitializerConstraints(unsigned, Constant *C);
575 void AddConstraintsForNonInternalLinkage(Function *F);
576 void AddConstraintsForCall(CallSite CS, Function *F);
577 bool AddConstraintsForExternalCall(CallSite CS, Function *F);
580 void PrintNode(const Node *N) const;
581 void PrintConstraints() const ;
582 void PrintConstraint(const Constraint &) const;
583 void PrintLabels() const;
584 void PrintPointsToGraph() const;
586 //===------------------------------------------------------------------===//
587 // Instruction visitation methods for adding constraints
589 friend class InstVisitor<Andersens>;
590 void visitReturnInst(ReturnInst &RI);
591 void visitInvokeInst(InvokeInst &II) { visitCallSite(CallSite(&II)); }
592 void visitCallInst(CallInst &CI) { visitCallSite(CallSite(&CI)); }
593 void visitCallSite(CallSite CS);
594 void visitAllocationInst(AllocationInst &AI);
595 void visitLoadInst(LoadInst &LI);
596 void visitStoreInst(StoreInst &SI);
597 void visitGetElementPtrInst(GetElementPtrInst &GEP);
598 void visitPHINode(PHINode &PN);
599 void visitCastInst(CastInst &CI);
600 void visitICmpInst(ICmpInst &ICI) {} // NOOP!
601 void visitFCmpInst(FCmpInst &ICI) {} // NOOP!
602 void visitSelectInst(SelectInst &SI);
603 void visitVAArg(VAArgInst &I);
604 void visitInstruction(Instruction &I);
606 //===------------------------------------------------------------------===//
607 // Implement Analyize interface
609 void print(std::ostream &O, const Module* M) const {
610 PrintPointsToGraph();
615 char Andersens::ID = 0;
616 static RegisterPass<Andersens>
617 X("anders-aa", "Andersen's Interprocedural Alias Analysis", false, true);
618 static RegisterAnalysisGroup<AliasAnalysis> Y(X);
620 // Initialize Timestamp Counter (static).
621 volatile llvm::sys::cas_flag Andersens::Node::Counter = 0;
623 ModulePass *llvm::createAndersensPass() { return new Andersens(); }
625 //===----------------------------------------------------------------------===//
626 // AliasAnalysis Interface Implementation
627 //===----------------------------------------------------------------------===//
629 AliasAnalysis::AliasResult Andersens::alias(const Value *V1, unsigned V1Size,
630 const Value *V2, unsigned V2Size) {
631 Node *N1 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V1)))];
632 Node *N2 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V2)))];
634 // Check to see if the two pointers are known to not alias. They don't alias
635 // if their points-to sets do not intersect.
636 if (!N1->intersectsIgnoring(N2, NullObject))
639 return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
642 AliasAnalysis::ModRefResult
643 Andersens::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
644 // The only thing useful that we can contribute for mod/ref information is
645 // when calling external function calls: if we know that memory never escapes
646 // from the program, it cannot be modified by an external call.
648 // NOTE: This is not really safe, at least not when the entire program is not
649 // available. The deal is that the external function could call back into the
650 // program and modify stuff. We ignore this technical niggle for now. This
651 // is, after all, a "research quality" implementation of Andersen's analysis.
652 if (Function *F = CS.getCalledFunction())
653 if (F->isDeclaration()) {
654 Node *N1 = &GraphNodes[FindNode(getNode(P))];
656 if (N1->PointsTo->empty())
659 if (!UniversalSet->PointsTo->test(FindNode(getNode(P))))
660 return NoModRef; // Universal set does not contain P
662 if (!N1->PointsTo->test(UniversalSet))
663 return NoModRef; // P doesn't point to the universal set.
667 return AliasAnalysis::getModRefInfo(CS, P, Size);
670 AliasAnalysis::ModRefResult
671 Andersens::getModRefInfo(CallSite CS1, CallSite CS2) {
672 return AliasAnalysis::getModRefInfo(CS1,CS2);
675 /// getMustAlias - We can provide must alias information if we know that a
676 /// pointer can only point to a specific function or the null pointer.
677 /// Unfortunately we cannot determine must-alias information for global
678 /// variables or any other memory memory objects because we do not track whether
679 /// a pointer points to the beginning of an object or a field of it.
680 void Andersens::getMustAliases(Value *P, std::vector<Value*> &RetVals) {
681 Node *N = &GraphNodes[FindNode(getNode(P))];
682 if (N->PointsTo->count() == 1) {
683 Node *Pointee = &GraphNodes[N->PointsTo->find_first()];
684 // If a function is the only object in the points-to set, then it must be
685 // the destination. Note that we can't handle global variables here,
686 // because we don't know if the pointer is actually pointing to a field of
687 // the global or to the beginning of it.
688 if (Value *V = Pointee->getValue()) {
689 if (Function *F = dyn_cast<Function>(V))
690 RetVals.push_back(F);
692 // If the object in the points-to set is the null object, then the null
693 // pointer is a must alias.
694 if (Pointee == &GraphNodes[NullObject])
695 RetVals.push_back(Constant::getNullValue(P->getType()));
698 AliasAnalysis::getMustAliases(P, RetVals);
701 /// pointsToConstantMemory - If we can determine that this pointer only points
702 /// to constant memory, return true. In practice, this means that if the
703 /// pointer can only point to constant globals, functions, or the null pointer,
706 bool Andersens::pointsToConstantMemory(const Value *P) {
707 Node *N = &GraphNodes[FindNode(getNode(const_cast<Value*>(P)))];
710 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
711 bi != N->PointsTo->end();
714 Node *Pointee = &GraphNodes[i];
715 if (Value *V = Pointee->getValue()) {
716 if (!isa<GlobalValue>(V) || (isa<GlobalVariable>(V) &&
717 !cast<GlobalVariable>(V)->isConstant()))
718 return AliasAnalysis::pointsToConstantMemory(P);
721 return AliasAnalysis::pointsToConstantMemory(P);
728 //===----------------------------------------------------------------------===//
729 // Object Identification Phase
730 //===----------------------------------------------------------------------===//
732 /// IdentifyObjects - This stage scans the program, adding an entry to the
733 /// GraphNodes list for each memory object in the program (global stack or
734 /// heap), and populates the ValueNodes and ObjectNodes maps for these objects.
736 void Andersens::IdentifyObjects(Module &M) {
737 unsigned NumObjects = 0;
739 // Object #0 is always the universal set: the object that we don't know
741 assert(NumObjects == UniversalSet && "Something changed!");
744 // Object #1 always represents the null pointer.
745 assert(NumObjects == NullPtr && "Something changed!");
748 // Object #2 always represents the null object (the object pointed to by null)
749 assert(NumObjects == NullObject && "Something changed!");
752 // Add all the globals first.
753 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
755 ObjectNodes[I] = NumObjects++;
756 ValueNodes[I] = NumObjects++;
759 // Add nodes for all of the functions and the instructions inside of them.
760 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
761 // The function itself is a memory object.
762 unsigned First = NumObjects;
763 ValueNodes[F] = NumObjects++;
764 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
765 ReturnNodes[F] = NumObjects++;
766 if (F->getFunctionType()->isVarArg())
767 VarargNodes[F] = NumObjects++;
770 // Add nodes for all of the incoming pointer arguments.
771 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
774 if (isa<PointerType>(I->getType()))
775 ValueNodes[I] = NumObjects++;
777 MaxK[First] = NumObjects - First;
779 // Scan the function body, creating a memory object for each heap/stack
780 // allocation in the body of the function and a node to represent all
781 // pointer values defined by instructions and used as operands.
782 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
783 // If this is an heap or stack allocation, create a node for the memory
785 if (isa<PointerType>(II->getType())) {
786 ValueNodes[&*II] = NumObjects++;
787 if (AllocationInst *AI = dyn_cast<AllocationInst>(&*II))
788 ObjectNodes[AI] = NumObjects++;
791 // Calls to inline asm need to be added as well because the callee isn't
792 // referenced anywhere else.
793 if (CallInst *CI = dyn_cast<CallInst>(&*II)) {
794 Value *Callee = CI->getCalledValue();
795 if (isa<InlineAsm>(Callee))
796 ValueNodes[Callee] = NumObjects++;
801 // Now that we know how many objects to create, make them all now!
802 GraphNodes.resize(NumObjects);
803 NumNodes += NumObjects;
806 //===----------------------------------------------------------------------===//
807 // Constraint Identification Phase
808 //===----------------------------------------------------------------------===//
810 /// getNodeForConstantPointer - Return the node corresponding to the constant
812 unsigned Andersens::getNodeForConstantPointer(Constant *C) {
813 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
815 if (isa<ConstantPointerNull>(C) || isa<UndefValue>(C))
817 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
819 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
820 switch (CE->getOpcode()) {
821 case Instruction::GetElementPtr:
822 return getNodeForConstantPointer(CE->getOperand(0));
823 case Instruction::IntToPtr:
825 case Instruction::BitCast:
826 return getNodeForConstantPointer(CE->getOperand(0));
828 cerr << "Constant Expr not yet handled: " << *CE << "\n";
832 assert(0 && "Unknown constant pointer!");
837 /// getNodeForConstantPointerTarget - Return the node POINTED TO by the
838 /// specified constant pointer.
839 unsigned Andersens::getNodeForConstantPointerTarget(Constant *C) {
840 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
842 if (isa<ConstantPointerNull>(C))
844 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
845 return getObject(GV);
846 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
847 switch (CE->getOpcode()) {
848 case Instruction::GetElementPtr:
849 return getNodeForConstantPointerTarget(CE->getOperand(0));
850 case Instruction::IntToPtr:
852 case Instruction::BitCast:
853 return getNodeForConstantPointerTarget(CE->getOperand(0));
855 cerr << "Constant Expr not yet handled: " << *CE << "\n";
859 assert(0 && "Unknown constant pointer!");
864 /// AddGlobalInitializerConstraints - Add inclusion constraints for the memory
865 /// object N, which contains values indicated by C.
866 void Andersens::AddGlobalInitializerConstraints(unsigned NodeIndex,
868 if (C->getType()->isSingleValueType()) {
869 if (isa<PointerType>(C->getType()))
870 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
871 getNodeForConstantPointer(C)));
872 } else if (C->isNullValue()) {
873 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
876 } else if (!isa<UndefValue>(C)) {
877 // If this is an array or struct, include constraints for each element.
878 assert(isa<ConstantArray>(C) || isa<ConstantStruct>(C));
879 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
880 AddGlobalInitializerConstraints(NodeIndex,
881 cast<Constant>(C->getOperand(i)));
885 /// AddConstraintsForNonInternalLinkage - If this function does not have
886 /// internal linkage, realize that we can't trust anything passed into or
887 /// returned by this function.
888 void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
889 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
890 if (isa<PointerType>(I->getType()))
891 // If this is an argument of an externally accessible function, the
892 // incoming pointer might point to anything.
893 Constraints.push_back(Constraint(Constraint::Copy, getNode(I),
897 /// AddConstraintsForCall - If this is a call to a "known" function, add the
898 /// constraints and return true. If this is a call to an unknown function,
900 bool Andersens::AddConstraintsForExternalCall(CallSite CS, Function *F) {
901 assert(F->isDeclaration() && "Not an external function!");
903 // These functions don't induce any points-to constraints.
904 if (F->getName() == "atoi" || F->getName() == "atof" ||
905 F->getName() == "atol" || F->getName() == "atoll" ||
906 F->getName() == "remove" || F->getName() == "unlink" ||
907 F->getName() == "rename" || F->getName() == "memcmp" ||
908 F->getName() == "llvm.memset" ||
909 F->getName() == "strcmp" || F->getName() == "strncmp" ||
910 F->getName() == "execl" || F->getName() == "execlp" ||
911 F->getName() == "execle" || F->getName() == "execv" ||
912 F->getName() == "execvp" || F->getName() == "chmod" ||
913 F->getName() == "puts" || F->getName() == "write" ||
914 F->getName() == "open" || F->getName() == "create" ||
915 F->getName() == "truncate" || F->getName() == "chdir" ||
916 F->getName() == "mkdir" || F->getName() == "rmdir" ||
917 F->getName() == "read" || F->getName() == "pipe" ||
918 F->getName() == "wait" || F->getName() == "time" ||
919 F->getName() == "stat" || F->getName() == "fstat" ||
920 F->getName() == "lstat" || F->getName() == "strtod" ||
921 F->getName() == "strtof" || F->getName() == "strtold" ||
922 F->getName() == "fopen" || F->getName() == "fdopen" ||
923 F->getName() == "freopen" ||
924 F->getName() == "fflush" || F->getName() == "feof" ||
925 F->getName() == "fileno" || F->getName() == "clearerr" ||
926 F->getName() == "rewind" || F->getName() == "ftell" ||
927 F->getName() == "ferror" || F->getName() == "fgetc" ||
928 F->getName() == "fgetc" || F->getName() == "_IO_getc" ||
929 F->getName() == "fwrite" || F->getName() == "fread" ||
930 F->getName() == "fgets" || F->getName() == "ungetc" ||
931 F->getName() == "fputc" ||
932 F->getName() == "fputs" || F->getName() == "putc" ||
933 F->getName() == "ftell" || F->getName() == "rewind" ||
934 F->getName() == "_IO_putc" || F->getName() == "fseek" ||
935 F->getName() == "fgetpos" || F->getName() == "fsetpos" ||
936 F->getName() == "printf" || F->getName() == "fprintf" ||
937 F->getName() == "sprintf" || F->getName() == "vprintf" ||
938 F->getName() == "vfprintf" || F->getName() == "vsprintf" ||
939 F->getName() == "scanf" || F->getName() == "fscanf" ||
940 F->getName() == "sscanf" || F->getName() == "__assert_fail" ||
941 F->getName() == "modf")
945 // These functions do induce points-to edges.
946 if (F->getName() == "llvm.memcpy" ||
947 F->getName() == "llvm.memmove" ||
948 F->getName() == "memmove") {
950 const FunctionType *FTy = F->getFunctionType();
951 if (FTy->getNumParams() > 1 &&
952 isa<PointerType>(FTy->getParamType(0)) &&
953 isa<PointerType>(FTy->getParamType(1))) {
955 // *Dest = *Src, which requires an artificial graph node to represent the
956 // constraint. It is broken up into *Dest = temp, temp = *Src
957 unsigned FirstArg = getNode(CS.getArgument(0));
958 unsigned SecondArg = getNode(CS.getArgument(1));
959 unsigned TempArg = GraphNodes.size();
960 GraphNodes.push_back(Node());
961 Constraints.push_back(Constraint(Constraint::Store,
963 Constraints.push_back(Constraint(Constraint::Load,
964 TempArg, SecondArg));
965 // In addition, Dest = Src
966 Constraints.push_back(Constraint(Constraint::Copy,
967 FirstArg, SecondArg));
973 if (F->getName() == "realloc" || F->getName() == "strchr" ||
974 F->getName() == "strrchr" || F->getName() == "strstr" ||
975 F->getName() == "strtok") {
976 const FunctionType *FTy = F->getFunctionType();
977 if (FTy->getNumParams() > 0 &&
978 isa<PointerType>(FTy->getParamType(0))) {
979 Constraints.push_back(Constraint(Constraint::Copy,
980 getNode(CS.getInstruction()),
981 getNode(CS.getArgument(0))));
991 /// AnalyzeUsesOfFunction - Look at all of the users of the specified function.
992 /// If this is used by anything complex (i.e., the address escapes), return
994 bool Andersens::AnalyzeUsesOfFunction(Value *V) {
996 if (!isa<PointerType>(V->getType())) return true;
998 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
999 if (dyn_cast<LoadInst>(*UI)) {
1001 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
1002 if (V == SI->getOperand(1)) {
1004 } else if (SI->getOperand(1)) {
1005 return true; // Storing the pointer
1007 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1008 if (AnalyzeUsesOfFunction(GEP)) return true;
1009 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
1010 // Make sure that this is just the function being called, not that it is
1011 // passing into the function.
1012 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
1013 if (CI->getOperand(i) == V) return true;
1014 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
1015 // Make sure that this is just the function being called, not that it is
1016 // passing into the function.
1017 for (unsigned i = 3, e = II->getNumOperands(); i != e; ++i)
1018 if (II->getOperand(i) == V) return true;
1019 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
1020 if (CE->getOpcode() == Instruction::GetElementPtr ||
1021 CE->getOpcode() == Instruction::BitCast) {
1022 if (AnalyzeUsesOfFunction(CE))
1027 } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(*UI)) {
1028 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1029 return true; // Allow comparison against null.
1030 } else if (dyn_cast<FreeInst>(*UI)) {
1038 /// CollectConstraints - This stage scans the program, adding a constraint to
1039 /// the Constraints list for each instruction in the program that induces a
1040 /// constraint, and setting up the initial points-to graph.
1042 void Andersens::CollectConstraints(Module &M) {
1043 // First, the universal set points to itself.
1044 Constraints.push_back(Constraint(Constraint::AddressOf, UniversalSet,
1046 Constraints.push_back(Constraint(Constraint::Store, UniversalSet,
1049 // Next, the null pointer points to the null object.
1050 Constraints.push_back(Constraint(Constraint::AddressOf, NullPtr, NullObject));
1052 // Next, add any constraints on global variables and their initializers.
1053 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1055 // Associate the address of the global object as pointing to the memory for
1056 // the global: &G = <G memory>
1057 unsigned ObjectIndex = getObject(I);
1058 Node *Object = &GraphNodes[ObjectIndex];
1059 Object->setValue(I);
1060 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(*I),
1063 if (I->hasInitializer()) {
1064 AddGlobalInitializerConstraints(ObjectIndex, I->getInitializer());
1066 // If it doesn't have an initializer (i.e. it's defined in another
1067 // translation unit), it points to the universal set.
1068 Constraints.push_back(Constraint(Constraint::Copy, ObjectIndex,
1073 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1074 // Set up the return value node.
1075 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
1076 GraphNodes[getReturnNode(F)].setValue(F);
1077 if (F->getFunctionType()->isVarArg())
1078 GraphNodes[getVarargNode(F)].setValue(F);
1080 // Set up incoming argument nodes.
1081 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
1083 if (isa<PointerType>(I->getType()))
1086 // At some point we should just add constraints for the escaping functions
1087 // at solve time, but this slows down solving. For now, we simply mark
1088 // address taken functions as escaping and treat them as external.
1089 if (!F->hasLocalLinkage() || AnalyzeUsesOfFunction(F))
1090 AddConstraintsForNonInternalLinkage(F);
1092 if (!F->isDeclaration()) {
1093 // Scan the function body, creating a memory object for each heap/stack
1094 // allocation in the body of the function and a node to represent all
1095 // pointer values defined by instructions and used as operands.
1098 // External functions that return pointers return the universal set.
1099 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
1100 Constraints.push_back(Constraint(Constraint::Copy,
1104 // Any pointers that are passed into the function have the universal set
1105 // stored into them.
1106 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
1108 if (isa<PointerType>(I->getType())) {
1109 // Pointers passed into external functions could have anything stored
1111 Constraints.push_back(Constraint(Constraint::Store, getNode(I),
1113 // Memory objects passed into external function calls can have the
1114 // universal set point to them.
1116 Constraints.push_back(Constraint(Constraint::Copy,
1120 Constraints.push_back(Constraint(Constraint::Copy,
1126 // If this is an external varargs function, it can also store pointers
1127 // into any pointers passed through the varargs section.
1128 if (F->getFunctionType()->isVarArg())
1129 Constraints.push_back(Constraint(Constraint::Store, getVarargNode(F),
1133 NumConstraints += Constraints.size();
1137 void Andersens::visitInstruction(Instruction &I) {
1139 return; // This function is just a big assert.
1141 if (isa<BinaryOperator>(I))
1143 // Most instructions don't have any effect on pointer values.
1144 switch (I.getOpcode()) {
1145 case Instruction::Br:
1146 case Instruction::Switch:
1147 case Instruction::Unwind:
1148 case Instruction::Unreachable:
1149 case Instruction::Free:
1150 case Instruction::ICmp:
1151 case Instruction::FCmp:
1154 // Is this something we aren't handling yet?
1155 cerr << "Unknown instruction: " << I;
1160 void Andersens::visitAllocationInst(AllocationInst &AI) {
1161 unsigned ObjectIndex = getObject(&AI);
1162 GraphNodes[ObjectIndex].setValue(&AI);
1163 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(AI),
1167 void Andersens::visitReturnInst(ReturnInst &RI) {
1168 if (RI.getNumOperands() && isa<PointerType>(RI.getOperand(0)->getType()))
1169 // return V --> <Copy/retval{F}/v>
1170 Constraints.push_back(Constraint(Constraint::Copy,
1171 getReturnNode(RI.getParent()->getParent()),
1172 getNode(RI.getOperand(0))));
1175 void Andersens::visitLoadInst(LoadInst &LI) {
1176 if (isa<PointerType>(LI.getType()))
1177 // P1 = load P2 --> <Load/P1/P2>
1178 Constraints.push_back(Constraint(Constraint::Load, getNodeValue(LI),
1179 getNode(LI.getOperand(0))));
1182 void Andersens::visitStoreInst(StoreInst &SI) {
1183 if (isa<PointerType>(SI.getOperand(0)->getType()))
1184 // store P1, P2 --> <Store/P2/P1>
1185 Constraints.push_back(Constraint(Constraint::Store,
1186 getNode(SI.getOperand(1)),
1187 getNode(SI.getOperand(0))));
1190 void Andersens::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1191 // P1 = getelementptr P2, ... --> <Copy/P1/P2>
1192 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(GEP),
1193 getNode(GEP.getOperand(0))));
1196 void Andersens::visitPHINode(PHINode &PN) {
1197 if (isa<PointerType>(PN.getType())) {
1198 unsigned PNN = getNodeValue(PN);
1199 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1200 // P1 = phi P2, P3 --> <Copy/P1/P2>, <Copy/P1/P3>, ...
1201 Constraints.push_back(Constraint(Constraint::Copy, PNN,
1202 getNode(PN.getIncomingValue(i))));
1206 void Andersens::visitCastInst(CastInst &CI) {
1207 Value *Op = CI.getOperand(0);
1208 if (isa<PointerType>(CI.getType())) {
1209 if (isa<PointerType>(Op->getType())) {
1210 // P1 = cast P2 --> <Copy/P1/P2>
1211 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
1212 getNode(CI.getOperand(0))));
1214 // P1 = cast int --> <Copy/P1/Univ>
1216 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
1222 } else if (isa<PointerType>(Op->getType())) {
1223 // int = cast P1 --> <Copy/Univ/P1>
1225 Constraints.push_back(Constraint(Constraint::Copy,
1227 getNode(CI.getOperand(0))));
1229 getNode(CI.getOperand(0));
1234 void Andersens::visitSelectInst(SelectInst &SI) {
1235 if (isa<PointerType>(SI.getType())) {
1236 unsigned SIN = getNodeValue(SI);
1237 // P1 = select C, P2, P3 ---> <Copy/P1/P2>, <Copy/P1/P3>
1238 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1239 getNode(SI.getOperand(1))));
1240 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1241 getNode(SI.getOperand(2))));
1245 void Andersens::visitVAArg(VAArgInst &I) {
1246 assert(0 && "vaarg not handled yet!");
1249 /// AddConstraintsForCall - Add constraints for a call with actual arguments
1250 /// specified by CS to the function specified by F. Note that the types of
1251 /// arguments might not match up in the case where this is an indirect call and
1252 /// the function pointer has been casted. If this is the case, do something
1254 void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
1255 Value *CallValue = CS.getCalledValue();
1256 bool IsDeref = F == NULL;
1258 // If this is a call to an external function, try to handle it directly to get
1259 // some taste of context sensitivity.
1260 if (F && F->isDeclaration() && AddConstraintsForExternalCall(CS, F))
1263 if (isa<PointerType>(CS.getType())) {
1264 unsigned CSN = getNode(CS.getInstruction());
1265 if (!F || isa<PointerType>(F->getFunctionType()->getReturnType())) {
1267 Constraints.push_back(Constraint(Constraint::Load, CSN,
1268 getNode(CallValue), CallReturnPos));
1270 Constraints.push_back(Constraint(Constraint::Copy, CSN,
1271 getNode(CallValue) + CallReturnPos));
1273 // If the function returns a non-pointer value, handle this just like we
1274 // treat a nonpointer cast to pointer.
1275 Constraints.push_back(Constraint(Constraint::Copy, CSN,
1278 } else if (F && isa<PointerType>(F->getFunctionType()->getReturnType())) {
1280 Constraints.push_back(Constraint(Constraint::Copy,
1282 getNode(CallValue) + CallReturnPos));
1284 Constraints.push_back(Constraint(Constraint::Copy,
1285 getNode(CallValue) + CallReturnPos,
1292 CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
1293 bool external = !F || F->isDeclaration();
1296 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1297 for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI)
1300 if (external && isa<PointerType>((*ArgI)->getType()))
1302 // Add constraint that ArgI can now point to anything due to
1303 // escaping, as can everything it points to. The second portion of
1304 // this should be taken care of by universal = *universal
1305 Constraints.push_back(Constraint(Constraint::Copy,
1310 if (isa<PointerType>(AI->getType())) {
1311 if (isa<PointerType>((*ArgI)->getType())) {
1312 // Copy the actual argument into the formal argument.
1313 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1316 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1319 } else if (isa<PointerType>((*ArgI)->getType())) {
1321 Constraints.push_back(Constraint(Constraint::Copy,
1325 Constraints.push_back(Constraint(Constraint::Copy,
1333 unsigned ArgPos = CallFirstArgPos;
1334 for (; ArgI != ArgE; ++ArgI) {
1335 if (isa<PointerType>((*ArgI)->getType())) {
1336 // Copy the actual argument into the formal argument.
1337 Constraints.push_back(Constraint(Constraint::Store,
1339 getNode(*ArgI), ArgPos++));
1341 Constraints.push_back(Constraint(Constraint::Store,
1342 getNode (CallValue),
1343 UniversalSet, ArgPos++));
1347 // Copy all pointers passed through the varargs section to the varargs node.
1348 if (F && F->getFunctionType()->isVarArg())
1349 for (; ArgI != ArgE; ++ArgI)
1350 if (isa<PointerType>((*ArgI)->getType()))
1351 Constraints.push_back(Constraint(Constraint::Copy, getVarargNode(F),
1353 // If more arguments are passed in than we track, just drop them on the floor.
1356 void Andersens::visitCallSite(CallSite CS) {
1357 if (isa<PointerType>(CS.getType()))
1358 getNodeValue(*CS.getInstruction());
1360 if (Function *F = CS.getCalledFunction()) {
1361 AddConstraintsForCall(CS, F);
1363 AddConstraintsForCall(CS, NULL);
1367 //===----------------------------------------------------------------------===//
1368 // Constraint Solving Phase
1369 //===----------------------------------------------------------------------===//
1371 /// intersects - Return true if the points-to set of this node intersects
1372 /// with the points-to set of the specified node.
1373 bool Andersens::Node::intersects(Node *N) const {
1374 return PointsTo->intersects(N->PointsTo);
1377 /// intersectsIgnoring - Return true if the points-to set of this node
1378 /// intersects with the points-to set of the specified node on any nodes
1379 /// except for the specified node to ignore.
1380 bool Andersens::Node::intersectsIgnoring(Node *N, unsigned Ignoring) const {
1381 // TODO: If we are only going to call this with the same value for Ignoring,
1382 // we should move the special values out of the points-to bitmap.
1383 bool WeHadIt = PointsTo->test(Ignoring);
1384 bool NHadIt = N->PointsTo->test(Ignoring);
1385 bool Result = false;
1387 PointsTo->reset(Ignoring);
1389 N->PointsTo->reset(Ignoring);
1390 Result = PointsTo->intersects(N->PointsTo);
1392 PointsTo->set(Ignoring);
1394 N->PointsTo->set(Ignoring);
1398 void dumpToDOUT(SparseBitVector<> *bitmap) {
1400 dump(*bitmap, DOUT);
1405 /// Clump together address taken variables so that the points-to sets use up
1406 /// less space and can be operated on faster.
1408 void Andersens::ClumpAddressTaken() {
1410 #define DEBUG_TYPE "anders-aa-renumber"
1411 std::vector<unsigned> Translate;
1412 std::vector<Node> NewGraphNodes;
1414 Translate.resize(GraphNodes.size());
1415 unsigned NewPos = 0;
1417 for (unsigned i = 0; i < Constraints.size(); ++i) {
1418 Constraint &C = Constraints[i];
1419 if (C.Type == Constraint::AddressOf) {
1420 GraphNodes[C.Src].AddressTaken = true;
1423 for (unsigned i = 0; i < NumberSpecialNodes; ++i) {
1424 unsigned Pos = NewPos++;
1426 NewGraphNodes.push_back(GraphNodes[i]);
1427 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1430 // I believe this ends up being faster than making two vectors and splicing
1432 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1433 if (GraphNodes[i].AddressTaken) {
1434 unsigned Pos = NewPos++;
1436 NewGraphNodes.push_back(GraphNodes[i]);
1437 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1441 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1442 if (!GraphNodes[i].AddressTaken) {
1443 unsigned Pos = NewPos++;
1445 NewGraphNodes.push_back(GraphNodes[i]);
1446 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1450 for (DenseMap<Value*, unsigned>::iterator Iter = ValueNodes.begin();
1451 Iter != ValueNodes.end();
1453 Iter->second = Translate[Iter->second];
1455 for (DenseMap<Value*, unsigned>::iterator Iter = ObjectNodes.begin();
1456 Iter != ObjectNodes.end();
1458 Iter->second = Translate[Iter->second];
1460 for (DenseMap<Function*, unsigned>::iterator Iter = ReturnNodes.begin();
1461 Iter != ReturnNodes.end();
1463 Iter->second = Translate[Iter->second];
1465 for (DenseMap<Function*, unsigned>::iterator Iter = VarargNodes.begin();
1466 Iter != VarargNodes.end();
1468 Iter->second = Translate[Iter->second];
1470 for (unsigned i = 0; i < Constraints.size(); ++i) {
1471 Constraint &C = Constraints[i];
1472 C.Src = Translate[C.Src];
1473 C.Dest = Translate[C.Dest];
1476 GraphNodes.swap(NewGraphNodes);
1478 #define DEBUG_TYPE "anders-aa"
1481 /// The technique used here is described in "Exploiting Pointer and Location
1482 /// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1483 /// Analysis Symposium (SAS), August 2007." It is known as the "HVN" algorithm,
1484 /// and is equivalent to value numbering the collapsed constraint graph without
1485 /// evaluating unions. This is used as a pre-pass to HU in order to resolve
1486 /// first order pointer dereferences and speed up/reduce memory usage of HU.
1487 /// Running both is equivalent to HRU without the iteration
1488 /// HVN in more detail:
1489 /// Imagine the set of constraints was simply straight line code with no loops
1490 /// (we eliminate cycles, so there are no loops), such as:
1496 /// Applying value numbering to this code tells us:
1499 /// For HVN, this is as far as it goes. We assign new value numbers to every
1500 /// "address node", and every "reference node".
1501 /// To get the optimal result for this, we use a DFS + SCC (since all nodes in a
1502 /// cycle must have the same value number since the = operation is really
1503 /// inclusion, not overwrite), and value number nodes we receive points-to sets
1504 /// before we value our own node.
1505 /// The advantage of HU over HVN is that HU considers the inclusion property, so
1506 /// that if you have
1513 /// HU will determine that G == F == E. HVN will not, because it cannot prove
1514 /// that the points to information ends up being the same because they all
1515 /// receive &D from E anyway.
1517 void Andersens::HVN() {
1518 DOUT << "Beginning HVN\n";
1519 // Build a predecessor graph. This is like our constraint graph with the
1520 // edges going in the opposite direction, and there are edges for all the
1521 // constraints, instead of just copy constraints. We also build implicit
1522 // edges for constraints are implied but not explicit. I.E for the constraint
1523 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1524 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1525 Constraint &C = Constraints[i];
1526 if (C.Type == Constraint::AddressOf) {
1527 GraphNodes[C.Src].AddressTaken = true;
1528 GraphNodes[C.Src].Direct = false;
1531 unsigned AdrNode = C.Src + FirstAdrNode;
1532 if (!GraphNodes[C.Dest].PredEdges)
1533 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1534 GraphNodes[C.Dest].PredEdges->set(AdrNode);
1537 unsigned RefNode = C.Dest + FirstRefNode;
1538 if (!GraphNodes[RefNode].ImplicitPredEdges)
1539 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1540 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1541 } else if (C.Type == Constraint::Load) {
1542 if (C.Offset == 0) {
1544 if (!GraphNodes[C.Dest].PredEdges)
1545 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1546 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1548 GraphNodes[C.Dest].Direct = false;
1550 } else if (C.Type == Constraint::Store) {
1551 if (C.Offset == 0) {
1553 unsigned RefNode = C.Dest + FirstRefNode;
1554 if (!GraphNodes[RefNode].PredEdges)
1555 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1556 GraphNodes[RefNode].PredEdges->set(C.Src);
1559 // Dest = Src edge and *Dest = *Src edge
1560 if (!GraphNodes[C.Dest].PredEdges)
1561 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1562 GraphNodes[C.Dest].PredEdges->set(C.Src);
1563 unsigned RefNode = C.Dest + FirstRefNode;
1564 if (!GraphNodes[RefNode].ImplicitPredEdges)
1565 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1566 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1570 // Do SCC finding first to condense our predecessor graph
1572 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1573 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1574 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1576 for (unsigned i = 0; i < FirstRefNode; ++i) {
1577 unsigned Node = VSSCCRep[i];
1578 if (!Node2Visited[Node])
1581 for (BitVectorMap::iterator Iter = Set2PEClass.begin();
1582 Iter != Set2PEClass.end();
1585 Set2PEClass.clear();
1587 Node2Deleted.clear();
1588 Node2Visited.clear();
1589 DOUT << "Finished HVN\n";
1593 /// This is the workhorse of HVN value numbering. We combine SCC finding at the
1594 /// same time because it's easy.
1595 void Andersens::HVNValNum(unsigned NodeIndex) {
1596 unsigned MyDFS = DFSNumber++;
1597 Node *N = &GraphNodes[NodeIndex];
1598 Node2Visited[NodeIndex] = true;
1599 Node2DFS[NodeIndex] = MyDFS;
1601 // First process all our explicit edges
1603 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1604 Iter != N->PredEdges->end();
1606 unsigned j = VSSCCRep[*Iter];
1607 if (!Node2Deleted[j]) {
1608 if (!Node2Visited[j])
1610 if (Node2DFS[NodeIndex] > Node2DFS[j])
1611 Node2DFS[NodeIndex] = Node2DFS[j];
1615 // Now process all the implicit edges
1616 if (N->ImplicitPredEdges)
1617 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1618 Iter != N->ImplicitPredEdges->end();
1620 unsigned j = VSSCCRep[*Iter];
1621 if (!Node2Deleted[j]) {
1622 if (!Node2Visited[j])
1624 if (Node2DFS[NodeIndex] > Node2DFS[j])
1625 Node2DFS[NodeIndex] = Node2DFS[j];
1629 // See if we found any cycles
1630 if (MyDFS == Node2DFS[NodeIndex]) {
1631 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1632 unsigned CycleNodeIndex = SCCStack.top();
1633 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1634 VSSCCRep[CycleNodeIndex] = NodeIndex;
1636 N->Direct &= CycleNode->Direct;
1638 if (CycleNode->PredEdges) {
1640 N->PredEdges = new SparseBitVector<>;
1641 *(N->PredEdges) |= CycleNode->PredEdges;
1642 delete CycleNode->PredEdges;
1643 CycleNode->PredEdges = NULL;
1645 if (CycleNode->ImplicitPredEdges) {
1646 if (!N->ImplicitPredEdges)
1647 N->ImplicitPredEdges = new SparseBitVector<>;
1648 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1649 delete CycleNode->ImplicitPredEdges;
1650 CycleNode->ImplicitPredEdges = NULL;
1656 Node2Deleted[NodeIndex] = true;
1659 GraphNodes[NodeIndex].PointerEquivLabel = PEClass++;
1663 // Collect labels of successor nodes
1664 bool AllSame = true;
1665 unsigned First = ~0;
1666 SparseBitVector<> *Labels = new SparseBitVector<>;
1670 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1671 Iter != N->PredEdges->end();
1673 unsigned j = VSSCCRep[*Iter];
1674 unsigned Label = GraphNodes[j].PointerEquivLabel;
1675 // Ignore labels that are equal to us or non-pointers
1676 if (j == NodeIndex || Label == 0)
1678 if (First == (unsigned)~0)
1680 else if (First != Label)
1685 // We either have a non-pointer, a copy of an existing node, or a new node.
1686 // Assign the appropriate pointer equivalence label.
1687 if (Labels->empty()) {
1688 GraphNodes[NodeIndex].PointerEquivLabel = 0;
1689 } else if (AllSame) {
1690 GraphNodes[NodeIndex].PointerEquivLabel = First;
1692 GraphNodes[NodeIndex].PointerEquivLabel = Set2PEClass[Labels];
1693 if (GraphNodes[NodeIndex].PointerEquivLabel == 0) {
1694 unsigned EquivClass = PEClass++;
1695 Set2PEClass[Labels] = EquivClass;
1696 GraphNodes[NodeIndex].PointerEquivLabel = EquivClass;
1703 SCCStack.push(NodeIndex);
1707 /// The technique used here is described in "Exploiting Pointer and Location
1708 /// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1709 /// Analysis Symposium (SAS), August 2007." It is known as the "HU" algorithm,
1710 /// and is equivalent to value numbering the collapsed constraint graph
1711 /// including evaluating unions.
1712 void Andersens::HU() {
1713 DOUT << "Beginning HU\n";
1714 // Build a predecessor graph. This is like our constraint graph with the
1715 // edges going in the opposite direction, and there are edges for all the
1716 // constraints, instead of just copy constraints. We also build implicit
1717 // edges for constraints are implied but not explicit. I.E for the constraint
1718 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1719 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1720 Constraint &C = Constraints[i];
1721 if (C.Type == Constraint::AddressOf) {
1722 GraphNodes[C.Src].AddressTaken = true;
1723 GraphNodes[C.Src].Direct = false;
1725 GraphNodes[C.Dest].PointsTo->set(C.Src);
1727 unsigned RefNode = C.Dest + FirstRefNode;
1728 if (!GraphNodes[RefNode].ImplicitPredEdges)
1729 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1730 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1731 GraphNodes[C.Src].PointedToBy->set(C.Dest);
1732 } else if (C.Type == Constraint::Load) {
1733 if (C.Offset == 0) {
1735 if (!GraphNodes[C.Dest].PredEdges)
1736 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1737 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1739 GraphNodes[C.Dest].Direct = false;
1741 } else if (C.Type == Constraint::Store) {
1742 if (C.Offset == 0) {
1744 unsigned RefNode = C.Dest + FirstRefNode;
1745 if (!GraphNodes[RefNode].PredEdges)
1746 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1747 GraphNodes[RefNode].PredEdges->set(C.Src);
1750 // Dest = Src edge and *Dest = *Src edg
1751 if (!GraphNodes[C.Dest].PredEdges)
1752 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1753 GraphNodes[C.Dest].PredEdges->set(C.Src);
1754 unsigned RefNode = C.Dest + FirstRefNode;
1755 if (!GraphNodes[RefNode].ImplicitPredEdges)
1756 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1757 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1761 // Do SCC finding first to condense our predecessor graph
1763 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1764 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1765 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1767 for (unsigned i = 0; i < FirstRefNode; ++i) {
1768 if (FindNode(i) == i) {
1769 unsigned Node = VSSCCRep[i];
1770 if (!Node2Visited[Node])
1775 // Reset tables for actual labeling
1777 Node2Visited.clear();
1778 Node2Deleted.clear();
1779 // Pre-grow our densemap so that we don't get really bad behavior
1780 Set2PEClass.resize(GraphNodes.size());
1782 // Visit the condensed graph and generate pointer equivalence labels.
1783 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1784 for (unsigned i = 0; i < FirstRefNode; ++i) {
1785 if (FindNode(i) == i) {
1786 unsigned Node = VSSCCRep[i];
1787 if (!Node2Visited[Node])
1791 // PEClass nodes will be deleted by the deleting of N->PointsTo in our caller.
1792 Set2PEClass.clear();
1793 DOUT << "Finished HU\n";
1797 /// Implementation of standard Tarjan SCC algorithm as modified by Nuutilla.
1798 void Andersens::Condense(unsigned NodeIndex) {
1799 unsigned MyDFS = DFSNumber++;
1800 Node *N = &GraphNodes[NodeIndex];
1801 Node2Visited[NodeIndex] = true;
1802 Node2DFS[NodeIndex] = MyDFS;
1804 // First process all our explicit edges
1806 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1807 Iter != N->PredEdges->end();
1809 unsigned j = VSSCCRep[*Iter];
1810 if (!Node2Deleted[j]) {
1811 if (!Node2Visited[j])
1813 if (Node2DFS[NodeIndex] > Node2DFS[j])
1814 Node2DFS[NodeIndex] = Node2DFS[j];
1818 // Now process all the implicit edges
1819 if (N->ImplicitPredEdges)
1820 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1821 Iter != N->ImplicitPredEdges->end();
1823 unsigned j = VSSCCRep[*Iter];
1824 if (!Node2Deleted[j]) {
1825 if (!Node2Visited[j])
1827 if (Node2DFS[NodeIndex] > Node2DFS[j])
1828 Node2DFS[NodeIndex] = Node2DFS[j];
1832 // See if we found any cycles
1833 if (MyDFS == Node2DFS[NodeIndex]) {
1834 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1835 unsigned CycleNodeIndex = SCCStack.top();
1836 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1837 VSSCCRep[CycleNodeIndex] = NodeIndex;
1839 N->Direct &= CycleNode->Direct;
1841 *(N->PointsTo) |= CycleNode->PointsTo;
1842 delete CycleNode->PointsTo;
1843 CycleNode->PointsTo = NULL;
1844 if (CycleNode->PredEdges) {
1846 N->PredEdges = new SparseBitVector<>;
1847 *(N->PredEdges) |= CycleNode->PredEdges;
1848 delete CycleNode->PredEdges;
1849 CycleNode->PredEdges = NULL;
1851 if (CycleNode->ImplicitPredEdges) {
1852 if (!N->ImplicitPredEdges)
1853 N->ImplicitPredEdges = new SparseBitVector<>;
1854 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1855 delete CycleNode->ImplicitPredEdges;
1856 CycleNode->ImplicitPredEdges = NULL;
1861 Node2Deleted[NodeIndex] = true;
1863 // Set up number of incoming edges for other nodes
1865 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1866 Iter != N->PredEdges->end();
1868 ++GraphNodes[VSSCCRep[*Iter]].NumInEdges;
1870 SCCStack.push(NodeIndex);
1874 void Andersens::HUValNum(unsigned NodeIndex) {
1875 Node *N = &GraphNodes[NodeIndex];
1876 Node2Visited[NodeIndex] = true;
1878 // Eliminate dereferences of non-pointers for those non-pointers we have
1879 // already identified. These are ref nodes whose non-ref node:
1880 // 1. Has already been visited determined to point to nothing (and thus, a
1881 // dereference of it must point to nothing)
1882 // 2. Any direct node with no predecessor edges in our graph and with no
1883 // points-to set (since it can't point to anything either, being that it
1884 // receives no points-to sets and has none).
1885 if (NodeIndex >= FirstRefNode) {
1886 unsigned j = VSSCCRep[FindNode(NodeIndex - FirstRefNode)];
1887 if ((Node2Visited[j] && !GraphNodes[j].PointerEquivLabel)
1888 || (GraphNodes[j].Direct && !GraphNodes[j].PredEdges
1889 && GraphNodes[j].PointsTo->empty())){
1893 // Process all our explicit edges
1895 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1896 Iter != N->PredEdges->end();
1898 unsigned j = VSSCCRep[*Iter];
1899 if (!Node2Visited[j])
1902 // If this edge turned out to be the same as us, or got no pointer
1903 // equivalence label (and thus points to nothing) , just decrement our
1904 // incoming edges and continue.
1905 if (j == NodeIndex || GraphNodes[j].PointerEquivLabel == 0) {
1906 --GraphNodes[j].NumInEdges;
1910 *(N->PointsTo) |= GraphNodes[j].PointsTo;
1912 // If we didn't end up storing this in the hash, and we're done with all
1913 // the edges, we don't need the points-to set anymore.
1914 --GraphNodes[j].NumInEdges;
1915 if (!GraphNodes[j].NumInEdges && !GraphNodes[j].StoredInHash) {
1916 delete GraphNodes[j].PointsTo;
1917 GraphNodes[j].PointsTo = NULL;
1920 // If this isn't a direct node, generate a fresh variable.
1922 N->PointsTo->set(FirstRefNode + NodeIndex);
1925 // See If we have something equivalent to us, if not, generate a new
1926 // equivalence class.
1927 if (N->PointsTo->empty()) {
1932 N->PointerEquivLabel = Set2PEClass[N->PointsTo];
1933 if (N->PointerEquivLabel == 0) {
1934 unsigned EquivClass = PEClass++;
1935 N->StoredInHash = true;
1936 Set2PEClass[N->PointsTo] = EquivClass;
1937 N->PointerEquivLabel = EquivClass;
1940 N->PointerEquivLabel = PEClass++;
1945 /// Rewrite our list of constraints so that pointer equivalent nodes are
1946 /// replaced by their the pointer equivalence class representative.
1947 void Andersens::RewriteConstraints() {
1948 std::vector<Constraint> NewConstraints;
1949 DenseSet<Constraint, ConstraintKeyInfo> Seen;
1951 PEClass2Node.clear();
1952 PENLEClass2Node.clear();
1954 // We may have from 1 to Graphnodes + 1 equivalence classes.
1955 PEClass2Node.insert(PEClass2Node.begin(), GraphNodes.size() + 1, -1);
1956 PENLEClass2Node.insert(PENLEClass2Node.begin(), GraphNodes.size() + 1, -1);
1958 // Rewrite constraints, ignoring non-pointer constraints, uniting equivalent
1959 // nodes, and rewriting constraints to use the representative nodes.
1960 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1961 Constraint &C = Constraints[i];
1962 unsigned RHSNode = FindNode(C.Src);
1963 unsigned LHSNode = FindNode(C.Dest);
1964 unsigned RHSLabel = GraphNodes[VSSCCRep[RHSNode]].PointerEquivLabel;
1965 unsigned LHSLabel = GraphNodes[VSSCCRep[LHSNode]].PointerEquivLabel;
1967 // First we try to eliminate constraints for things we can prove don't point
1969 if (LHSLabel == 0) {
1970 DEBUG(PrintNode(&GraphNodes[LHSNode]));
1971 DOUT << " is a non-pointer, ignoring constraint.\n";
1974 if (RHSLabel == 0) {
1975 DEBUG(PrintNode(&GraphNodes[RHSNode]));
1976 DOUT << " is a non-pointer, ignoring constraint.\n";
1979 // This constraint may be useless, and it may become useless as we translate
1981 if (C.Src == C.Dest && C.Type == Constraint::Copy)
1984 C.Src = FindEquivalentNode(RHSNode, RHSLabel);
1985 C.Dest = FindEquivalentNode(FindNode(LHSNode), LHSLabel);
1986 if ((C.Src == C.Dest && C.Type == Constraint::Copy)
1991 NewConstraints.push_back(C);
1993 Constraints.swap(NewConstraints);
1994 PEClass2Node.clear();
1997 /// See if we have a node that is pointer equivalent to the one being asked
1998 /// about, and if so, unite them and return the equivalent node. Otherwise,
1999 /// return the original node.
2000 unsigned Andersens::FindEquivalentNode(unsigned NodeIndex,
2001 unsigned NodeLabel) {
2002 if (!GraphNodes[NodeIndex].AddressTaken) {
2003 if (PEClass2Node[NodeLabel] != -1) {
2004 // We found an existing node with the same pointer label, so unify them.
2005 // We specifically request that Union-By-Rank not be used so that
2006 // PEClass2Node[NodeLabel] U= NodeIndex and not the other way around.
2007 return UniteNodes(PEClass2Node[NodeLabel], NodeIndex, false);
2009 PEClass2Node[NodeLabel] = NodeIndex;
2010 PENLEClass2Node[NodeLabel] = NodeIndex;
2012 } else if (PENLEClass2Node[NodeLabel] == -1) {
2013 PENLEClass2Node[NodeLabel] = NodeIndex;
2019 void Andersens::PrintLabels() const {
2020 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2021 if (i < FirstRefNode) {
2022 PrintNode(&GraphNodes[i]);
2023 } else if (i < FirstAdrNode) {
2025 PrintNode(&GraphNodes[i-FirstRefNode]);
2029 PrintNode(&GraphNodes[i-FirstAdrNode]);
2033 DOUT << " has pointer label " << GraphNodes[i].PointerEquivLabel
2034 << " and SCC rep " << VSSCCRep[i]
2035 << " and is " << (GraphNodes[i].Direct ? "Direct" : "Not direct")
2040 /// The technique used here is described in "The Ant and the
2041 /// Grasshopper: Fast and Accurate Pointer Analysis for Millions of
2042 /// Lines of Code. In Programming Language Design and Implementation
2043 /// (PLDI), June 2007." It is known as the "HCD" (Hybrid Cycle
2044 /// Detection) algorithm. It is called a hybrid because it performs an
2045 /// offline analysis and uses its results during the solving (online)
2046 /// phase. This is just the offline portion; the results of this
2047 /// operation are stored in SDT and are later used in SolveContraints()
2048 /// and UniteNodes().
2049 void Andersens::HCD() {
2050 DOUT << "Starting HCD.\n";
2051 HCDSCCRep.resize(GraphNodes.size());
2053 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2054 GraphNodes[i].Edges = new SparseBitVector<>;
2058 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2059 Constraint &C = Constraints[i];
2060 assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
2061 if (C.Type == Constraint::AddressOf) {
2063 } else if (C.Type == Constraint::Load) {
2065 GraphNodes[C.Dest].Edges->set(C.Src + FirstRefNode);
2066 } else if (C.Type == Constraint::Store) {
2068 GraphNodes[C.Dest + FirstRefNode].Edges->set(C.Src);
2070 GraphNodes[C.Dest].Edges->set(C.Src);
2074 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2075 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2076 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
2077 SDT.insert(SDT.begin(), GraphNodes.size() / 2, -1);
2080 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2081 unsigned Node = HCDSCCRep[i];
2082 if (!Node2Deleted[Node])
2086 for (unsigned i = 0; i < GraphNodes.size(); ++i)
2087 if (GraphNodes[i].Edges != NULL) {
2088 delete GraphNodes[i].Edges;
2089 GraphNodes[i].Edges = NULL;
2092 while( !SCCStack.empty() )
2096 Node2Visited.clear();
2097 Node2Deleted.clear();
2099 DOUT << "HCD complete.\n";
2102 // Component of HCD:
2103 // Use Nuutila's variant of Tarjan's algorithm to detect
2104 // Strongly-Connected Components (SCCs). For non-trivial SCCs
2105 // containing ref nodes, insert the appropriate information in SDT.
2106 void Andersens::Search(unsigned Node) {
2107 unsigned MyDFS = DFSNumber++;
2109 Node2Visited[Node] = true;
2110 Node2DFS[Node] = MyDFS;
2112 for (SparseBitVector<>::iterator Iter = GraphNodes[Node].Edges->begin(),
2113 End = GraphNodes[Node].Edges->end();
2116 unsigned J = HCDSCCRep[*Iter];
2117 assert(GraphNodes[J].isRep() && "Debug check; must be representative");
2118 if (!Node2Deleted[J]) {
2119 if (!Node2Visited[J])
2121 if (Node2DFS[Node] > Node2DFS[J])
2122 Node2DFS[Node] = Node2DFS[J];
2126 if( MyDFS != Node2DFS[Node] ) {
2127 SCCStack.push(Node);
2131 // This node is the root of a SCC, so process it.
2133 // If the SCC is "non-trivial" (not a singleton) and contains a reference
2134 // node, we place this SCC into SDT. We unite the nodes in any case.
2135 if (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
2136 SparseBitVector<> SCC;
2140 bool Ref = (Node >= FirstRefNode);
2142 Node2Deleted[Node] = true;
2145 unsigned P = SCCStack.top(); SCCStack.pop();
2146 Ref |= (P >= FirstRefNode);
2148 HCDSCCRep[P] = Node;
2149 } while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS);
2152 unsigned Rep = SCC.find_first();
2153 assert(Rep < FirstRefNode && "The SCC didn't have a non-Ref node!");
2155 SparseBitVector<>::iterator i = SCC.begin();
2157 // Skip over the non-ref nodes
2158 while( *i < FirstRefNode )
2161 while( i != SCC.end() )
2162 SDT[ (*i++) - FirstRefNode ] = Rep;
2168 /// Optimize the constraints by performing offline variable substitution and
2169 /// other optimizations.
2170 void Andersens::OptimizeConstraints() {
2171 DOUT << "Beginning constraint optimization\n";
2175 // Function related nodes need to stay in the same relative position and can't
2176 // be location equivalent.
2177 for (std::map<unsigned, unsigned>::iterator Iter = MaxK.begin();
2180 for (unsigned i = Iter->first;
2181 i != Iter->first + Iter->second;
2183 GraphNodes[i].AddressTaken = true;
2184 GraphNodes[i].Direct = false;
2188 ClumpAddressTaken();
2189 FirstRefNode = GraphNodes.size();
2190 FirstAdrNode = FirstRefNode + GraphNodes.size();
2191 GraphNodes.insert(GraphNodes.end(), 2 * GraphNodes.size(),
2193 VSSCCRep.resize(GraphNodes.size());
2194 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2198 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2199 Node *N = &GraphNodes[i];
2200 delete N->PredEdges;
2201 N->PredEdges = NULL;
2202 delete N->ImplicitPredEdges;
2203 N->ImplicitPredEdges = NULL;
2206 #define DEBUG_TYPE "anders-aa-labels"
2207 DEBUG(PrintLabels());
2209 #define DEBUG_TYPE "anders-aa"
2210 RewriteConstraints();
2211 // Delete the adr nodes.
2212 GraphNodes.resize(FirstRefNode * 2);
2215 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2216 Node *N = &GraphNodes[i];
2217 if (FindNode(i) == i) {
2218 N->PointsTo = new SparseBitVector<>;
2219 N->PointedToBy = new SparseBitVector<>;
2223 N->PointerEquivLabel = 0;
2227 #define DEBUG_TYPE "anders-aa-labels"
2228 DEBUG(PrintLabels());
2230 #define DEBUG_TYPE "anders-aa"
2231 RewriteConstraints();
2232 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2233 if (FindNode(i) == i) {
2234 Node *N = &GraphNodes[i];
2237 delete N->PredEdges;
2238 N->PredEdges = NULL;
2239 delete N->ImplicitPredEdges;
2240 N->ImplicitPredEdges = NULL;
2241 delete N->PointedToBy;
2242 N->PointedToBy = NULL;
2246 // perform Hybrid Cycle Detection (HCD)
2250 // No longer any need for the upper half of GraphNodes (for ref nodes).
2251 GraphNodes.erase(GraphNodes.begin() + FirstRefNode, GraphNodes.end());
2255 DOUT << "Finished constraint optimization\n";
2260 /// Unite pointer but not location equivalent variables, now that the constraint
2262 void Andersens::UnitePointerEquivalences() {
2263 DOUT << "Uniting remaining pointer equivalences\n";
2264 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2265 if (GraphNodes[i].AddressTaken && GraphNodes[i].isRep()) {
2266 unsigned Label = GraphNodes[i].PointerEquivLabel;
2268 if (Label && PENLEClass2Node[Label] != -1)
2269 UniteNodes(i, PENLEClass2Node[Label]);
2272 DOUT << "Finished remaining pointer equivalences\n";
2273 PENLEClass2Node.clear();
2276 /// Create the constraint graph used for solving points-to analysis.
2278 void Andersens::CreateConstraintGraph() {
2279 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2280 Constraint &C = Constraints[i];
2281 assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
2282 if (C.Type == Constraint::AddressOf)
2283 GraphNodes[C.Dest].PointsTo->set(C.Src);
2284 else if (C.Type == Constraint::Load)
2285 GraphNodes[C.Src].Constraints.push_back(C);
2286 else if (C.Type == Constraint::Store)
2287 GraphNodes[C.Dest].Constraints.push_back(C);
2288 else if (C.Offset != 0)
2289 GraphNodes[C.Src].Constraints.push_back(C);
2291 GraphNodes[C.Src].Edges->set(C.Dest);
2295 // Perform DFS and cycle detection.
2296 bool Andersens::QueryNode(unsigned Node) {
2297 assert(GraphNodes[Node].isRep() && "Querying a non-rep node");
2298 unsigned OurDFS = ++DFSNumber;
2299 SparseBitVector<> ToErase;
2300 SparseBitVector<> NewEdges;
2301 Tarjan2DFS[Node] = OurDFS;
2303 // Changed denotes a change from a recursive call that we will bubble up.
2304 // Merged is set if we actually merge a node ourselves.
2305 bool Changed = false, Merged = false;
2307 for (SparseBitVector<>::iterator bi = GraphNodes[Node].Edges->begin();
2308 bi != GraphNodes[Node].Edges->end();
2310 unsigned RepNode = FindNode(*bi);
2311 // If this edge points to a non-representative node but we are
2312 // already planning to add an edge to its representative, we have no
2313 // need for this edge anymore.
2314 if (RepNode != *bi && NewEdges.test(RepNode)){
2319 // Continue about our DFS.
2320 if (!Tarjan2Deleted[RepNode]){
2321 if (Tarjan2DFS[RepNode] == 0) {
2322 Changed |= QueryNode(RepNode);
2323 // May have been changed by QueryNode
2324 RepNode = FindNode(RepNode);
2326 if (Tarjan2DFS[RepNode] < Tarjan2DFS[Node])
2327 Tarjan2DFS[Node] = Tarjan2DFS[RepNode];
2330 // We may have just discovered that this node is part of a cycle, in
2331 // which case we can also erase it.
2332 if (RepNode != *bi) {
2334 NewEdges.set(RepNode);
2338 GraphNodes[Node].Edges->intersectWithComplement(ToErase);
2339 GraphNodes[Node].Edges |= NewEdges;
2341 // If this node is a root of a non-trivial SCC, place it on our
2342 // worklist to be processed.
2343 if (OurDFS == Tarjan2DFS[Node]) {
2344 while (!SCCStack.empty() && Tarjan2DFS[SCCStack.top()] >= OurDFS) {
2345 Node = UniteNodes(Node, SCCStack.top());
2350 Tarjan2Deleted[Node] = true;
2353 NextWL->insert(&GraphNodes[Node]);
2355 SCCStack.push(Node);
2358 return(Changed | Merged);
2361 /// SolveConstraints - This stage iteratively processes the constraints list
2362 /// propagating constraints (adding edges to the Nodes in the points-to graph)
2363 /// until a fixed point is reached.
2365 /// We use a variant of the technique called "Lazy Cycle Detection", which is
2366 /// described in "The Ant and the Grasshopper: Fast and Accurate Pointer
2367 /// Analysis for Millions of Lines of Code. In Programming Language Design and
2368 /// Implementation (PLDI), June 2007."
2369 /// The paper describes performing cycle detection one node at a time, which can
2370 /// be expensive if there are no cycles, but there are long chains of nodes that
2371 /// it heuristically believes are cycles (because it will DFS from each node
2372 /// without state from previous nodes).
2373 /// Instead, we use the heuristic to build a worklist of nodes to check, then
2374 /// cycle detect them all at the same time to do this more cheaply. This
2375 /// catches cycles slightly later than the original technique did, but does it
2376 /// make significantly cheaper.
2378 void Andersens::SolveConstraints() {
2382 OptimizeConstraints();
2384 #define DEBUG_TYPE "anders-aa-constraints"
2385 DEBUG(PrintConstraints());
2387 #define DEBUG_TYPE "anders-aa"
2389 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2390 Node *N = &GraphNodes[i];
2391 N->PointsTo = new SparseBitVector<>;
2392 N->OldPointsTo = new SparseBitVector<>;
2393 N->Edges = new SparseBitVector<>;
2395 CreateConstraintGraph();
2396 UnitePointerEquivalences();
2397 assert(SCCStack.empty() && "SCC Stack should be empty by now!");
2399 Node2Deleted.clear();
2400 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2401 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2403 DenseSet<Constraint, ConstraintKeyInfo> Seen;
2404 DenseSet<std::pair<unsigned,unsigned>, PairKeyInfo> EdgesChecked;
2406 // Order graph and add initial nodes to work list.
2407 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2408 Node *INode = &GraphNodes[i];
2410 // Add to work list if it's a representative and can contribute to the
2411 // calculation right now.
2412 if (INode->isRep() && !INode->PointsTo->empty()
2413 && (!INode->Edges->empty() || !INode->Constraints.empty())) {
2415 CurrWL->insert(INode);
2418 std::queue<unsigned int> TarjanWL;
2420 // "Rep and special variables" - in order for HCD to maintain conservative
2421 // results when !FULL_UNIVERSAL, we need to treat the special variables in
2422 // the same way that the !FULL_UNIVERSAL tweak does throughout the rest of
2423 // the analysis - it's ok to add edges from the special nodes, but never
2424 // *to* the special nodes.
2425 std::vector<unsigned int> RSV;
2427 while( !CurrWL->empty() ) {
2428 DOUT << "Starting iteration #" << ++NumIters << "\n";
2431 unsigned CurrNodeIndex;
2433 // Actual cycle checking code. We cycle check all of the lazy cycle
2434 // candidates from the last iteration in one go.
2435 if (!TarjanWL.empty()) {
2439 Tarjan2Deleted.clear();
2440 while (!TarjanWL.empty()) {
2441 unsigned int ToTarjan = TarjanWL.front();
2443 if (!Tarjan2Deleted[ToTarjan]
2444 && GraphNodes[ToTarjan].isRep()
2445 && Tarjan2DFS[ToTarjan] == 0)
2446 QueryNode(ToTarjan);
2450 // Add to work list if it's a representative and can contribute to the
2451 // calculation right now.
2452 while( (CurrNode = CurrWL->pop()) != NULL ) {
2453 CurrNodeIndex = CurrNode - &GraphNodes[0];
2457 // Figure out the changed points to bits
2458 SparseBitVector<> CurrPointsTo;
2459 CurrPointsTo.intersectWithComplement(CurrNode->PointsTo,
2460 CurrNode->OldPointsTo);
2461 if (CurrPointsTo.empty())
2464 *(CurrNode->OldPointsTo) |= CurrPointsTo;
2466 // Check the offline-computed equivalencies from HCD.
2470 if (SDT[CurrNodeIndex] >= 0) {
2472 Rep = FindNode(SDT[CurrNodeIndex]);
2477 for (SparseBitVector<>::iterator bi = CurrPointsTo.begin();
2478 bi != CurrPointsTo.end(); ++bi) {
2479 unsigned Node = FindNode(*bi);
2481 if (Node < NumberSpecialNodes) {
2482 RSV.push_back(Node);
2486 Rep = UniteNodes(Rep,Node);
2492 NextWL->insert(&GraphNodes[Rep]);
2494 if ( ! CurrNode->isRep() )
2500 /* Now process the constraints for this node. */
2501 for (std::list<Constraint>::iterator li = CurrNode->Constraints.begin();
2502 li != CurrNode->Constraints.end(); ) {
2503 li->Src = FindNode(li->Src);
2504 li->Dest = FindNode(li->Dest);
2506 // Delete redundant constraints
2507 if( Seen.count(*li) ) {
2508 std::list<Constraint>::iterator lk = li; li++;
2510 CurrNode->Constraints.erase(lk);
2516 // Src and Dest will be the vars we are going to process.
2517 // This may look a bit ugly, but what it does is allow us to process
2518 // both store and load constraints with the same code.
2519 // Load constraints say that every member of our RHS solution has K
2520 // added to it, and that variable gets an edge to LHS. We also union
2521 // RHS+K's solution into the LHS solution.
2522 // Store constraints say that every member of our LHS solution has K
2523 // added to it, and that variable gets an edge from RHS. We also union
2524 // RHS's solution into the LHS+K solution.
2527 unsigned K = li->Offset;
2528 unsigned CurrMember;
2529 if (li->Type == Constraint::Load) {
2532 } else if (li->Type == Constraint::Store) {
2536 // TODO Handle offseted copy constraint
2541 // See if we can use Hybrid Cycle Detection (that is, check
2542 // if it was a statically detected offline equivalence that
2543 // involves pointers; if so, remove the redundant constraints).
2544 if( SCC && K == 0 ) {
2548 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2549 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2550 NextWL->insert(&GraphNodes[*Dest]);
2552 for (unsigned i=0; i < RSV.size(); ++i) {
2553 CurrMember = RSV[i];
2555 if (*Dest < NumberSpecialNodes)
2557 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2558 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2559 NextWL->insert(&GraphNodes[*Dest]);
2562 // since all future elements of the points-to set will be
2563 // equivalent to the current ones, the complex constraints
2564 // become redundant.
2566 std::list<Constraint>::iterator lk = li; li++;
2568 // In this case, we can still erase the constraints when the
2569 // elements of the points-to sets are referenced by *Dest,
2570 // but not when they are referenced by *Src (i.e. for a Load
2571 // constraint). This is because if another special variable is
2572 // put into the points-to set later, we still need to add the
2573 // new edge from that special variable.
2574 if( lk->Type != Constraint::Load)
2576 GraphNodes[CurrNodeIndex].Constraints.erase(lk);
2578 const SparseBitVector<> &Solution = CurrPointsTo;
2580 for (SparseBitVector<>::iterator bi = Solution.begin();
2581 bi != Solution.end();
2585 // Need to increment the member by K since that is where we are
2586 // supposed to copy to/from. Note that in positive weight cycles,
2587 // which occur in address taking of fields, K can go past
2588 // MaxK[CurrMember] elements, even though that is all it could point
2590 if (K > 0 && K > MaxK[CurrMember])
2593 CurrMember = FindNode(CurrMember + K);
2595 // Add an edge to the graph, so we can just do regular
2596 // bitmap ior next time. It may also let us notice a cycle.
2598 if (*Dest < NumberSpecialNodes)
2601 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2602 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2603 NextWL->insert(&GraphNodes[*Dest]);
2609 SparseBitVector<> NewEdges;
2610 SparseBitVector<> ToErase;
2612 // Now all we have left to do is propagate points-to info along the
2613 // edges, erasing the redundant edges.
2614 for (SparseBitVector<>::iterator bi = CurrNode->Edges->begin();
2615 bi != CurrNode->Edges->end();
2618 unsigned DestVar = *bi;
2619 unsigned Rep = FindNode(DestVar);
2621 // If we ended up with this node as our destination, or we've already
2622 // got an edge for the representative, delete the current edge.
2623 if (Rep == CurrNodeIndex ||
2624 (Rep != DestVar && NewEdges.test(Rep))) {
2625 ToErase.set(DestVar);
2629 std::pair<unsigned,unsigned> edge(CurrNodeIndex,Rep);
2631 // This is where we do lazy cycle detection.
2632 // If this is a cycle candidate (equal points-to sets and this
2633 // particular edge has not been cycle-checked previously), add to the
2634 // list to check for cycles on the next iteration.
2635 if (!EdgesChecked.count(edge) &&
2636 *(GraphNodes[Rep].PointsTo) == *(CurrNode->PointsTo)) {
2637 EdgesChecked.insert(edge);
2640 // Union the points-to sets into the dest
2642 if (Rep >= NumberSpecialNodes)
2644 if (GraphNodes[Rep].PointsTo |= CurrPointsTo) {
2645 NextWL->insert(&GraphNodes[Rep]);
2647 // If this edge's destination was collapsed, rewrite the edge.
2648 if (Rep != DestVar) {
2649 ToErase.set(DestVar);
2653 CurrNode->Edges->intersectWithComplement(ToErase);
2654 CurrNode->Edges |= NewEdges;
2657 // Switch to other work list.
2658 WorkList* t = CurrWL; CurrWL = NextWL; NextWL = t;
2663 Node2Deleted.clear();
2664 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2665 Node *N = &GraphNodes[i];
2666 delete N->OldPointsTo;
2673 //===----------------------------------------------------------------------===//
2675 //===----------------------------------------------------------------------===//
2677 // Unite nodes First and Second, returning the one which is now the
2678 // representative node. First and Second are indexes into GraphNodes
2679 unsigned Andersens::UniteNodes(unsigned First, unsigned Second,
2681 assert (First < GraphNodes.size() && Second < GraphNodes.size() &&
2682 "Attempting to merge nodes that don't exist");
2684 Node *FirstNode = &GraphNodes[First];
2685 Node *SecondNode = &GraphNodes[Second];
2687 assert (SecondNode->isRep() && FirstNode->isRep() &&
2688 "Trying to unite two non-representative nodes!");
2689 if (First == Second)
2693 int RankFirst = (int) FirstNode ->NodeRep;
2694 int RankSecond = (int) SecondNode->NodeRep;
2696 // Rank starts at -1 and gets decremented as it increases.
2697 // Translation: higher rank, lower NodeRep value, which is always negative.
2698 if (RankFirst > RankSecond) {
2699 unsigned t = First; First = Second; Second = t;
2700 Node* tp = FirstNode; FirstNode = SecondNode; SecondNode = tp;
2701 } else if (RankFirst == RankSecond) {
2702 FirstNode->NodeRep = (unsigned) (RankFirst - 1);
2706 SecondNode->NodeRep = First;
2708 if (First >= NumberSpecialNodes)
2710 if (FirstNode->PointsTo && SecondNode->PointsTo)
2711 FirstNode->PointsTo |= *(SecondNode->PointsTo);
2712 if (FirstNode->Edges && SecondNode->Edges)
2713 FirstNode->Edges |= *(SecondNode->Edges);
2714 if (!SecondNode->Constraints.empty())
2715 FirstNode->Constraints.splice(FirstNode->Constraints.begin(),
2716 SecondNode->Constraints);
2717 if (FirstNode->OldPointsTo) {
2718 delete FirstNode->OldPointsTo;
2719 FirstNode->OldPointsTo = new SparseBitVector<>;
2722 // Destroy interesting parts of the merged-from node.
2723 delete SecondNode->OldPointsTo;
2724 delete SecondNode->Edges;
2725 delete SecondNode->PointsTo;
2726 SecondNode->Edges = NULL;
2727 SecondNode->PointsTo = NULL;
2728 SecondNode->OldPointsTo = NULL;
2731 DOUT << "Unified Node ";
2732 DEBUG(PrintNode(FirstNode));
2733 DOUT << " and Node ";
2734 DEBUG(PrintNode(SecondNode));
2738 if (SDT[Second] >= 0) {
2740 SDT[First] = SDT[Second];
2742 UniteNodes( FindNode(SDT[First]), FindNode(SDT[Second]) );
2743 First = FindNode(First);
2750 // Find the index into GraphNodes of the node representing Node, performing
2751 // path compression along the way
2752 unsigned Andersens::FindNode(unsigned NodeIndex) {
2753 assert (NodeIndex < GraphNodes.size()
2754 && "Attempting to find a node that can't exist");
2755 Node *N = &GraphNodes[NodeIndex];
2759 return (N->NodeRep = FindNode(N->NodeRep));
2762 // Find the index into GraphNodes of the node representing Node,
2763 // don't perform path compression along the way (for Print)
2764 unsigned Andersens::FindNode(unsigned NodeIndex) const {
2765 assert (NodeIndex < GraphNodes.size()
2766 && "Attempting to find a node that can't exist");
2767 const Node *N = &GraphNodes[NodeIndex];
2771 return FindNode(N->NodeRep);
2774 //===----------------------------------------------------------------------===//
2776 //===----------------------------------------------------------------------===//
2778 void Andersens::PrintNode(const Node *N) const {
2779 if (N == &GraphNodes[UniversalSet]) {
2780 cerr << "<universal>";
2782 } else if (N == &GraphNodes[NullPtr]) {
2783 cerr << "<nullptr>";
2785 } else if (N == &GraphNodes[NullObject]) {
2789 if (!N->getValue()) {
2790 cerr << "artificial" << (intptr_t) N;
2794 assert(N->getValue() != 0 && "Never set node label!");
2795 Value *V = N->getValue();
2796 if (Function *F = dyn_cast<Function>(V)) {
2797 if (isa<PointerType>(F->getFunctionType()->getReturnType()) &&
2798 N == &GraphNodes[getReturnNode(F)]) {
2799 cerr << F->getName() << ":retval";
2801 } else if (F->getFunctionType()->isVarArg() &&
2802 N == &GraphNodes[getVarargNode(F)]) {
2803 cerr << F->getName() << ":vararg";
2808 if (Instruction *I = dyn_cast<Instruction>(V))
2809 cerr << I->getParent()->getParent()->getName() << ":";
2810 else if (Argument *Arg = dyn_cast<Argument>(V))
2811 cerr << Arg->getParent()->getName() << ":";
2814 cerr << V->getName();
2816 cerr << "(unnamed)";
2818 if (isa<GlobalValue>(V) || isa<AllocationInst>(V))
2819 if (N == &GraphNodes[getObject(V)])
2822 void Andersens::PrintConstraint(const Constraint &C) const {
2823 if (C.Type == Constraint::Store) {
2828 PrintNode(&GraphNodes[C.Dest]);
2829 if (C.Type == Constraint::Store && C.Offset != 0)
2830 cerr << " + " << C.Offset << ")";
2832 if (C.Type == Constraint::Load) {
2837 else if (C.Type == Constraint::AddressOf)
2839 PrintNode(&GraphNodes[C.Src]);
2840 if (C.Offset != 0 && C.Type != Constraint::Store)
2841 cerr << " + " << C.Offset;
2842 if (C.Type == Constraint::Load && C.Offset != 0)
2847 void Andersens::PrintConstraints() const {
2848 cerr << "Constraints:\n";
2850 for (unsigned i = 0, e = Constraints.size(); i != e; ++i)
2851 PrintConstraint(Constraints[i]);
2854 void Andersens::PrintPointsToGraph() const {
2855 cerr << "Points-to graph:\n";
2856 for (unsigned i = 0, e = GraphNodes.size(); i != e; ++i) {
2857 const Node *N = &GraphNodes[i];
2858 if (FindNode(i) != i) {
2860 cerr << "\t--> same as ";
2861 PrintNode(&GraphNodes[FindNode(i)]);
2864 cerr << "[" << (N->PointsTo->count()) << "] ";
2869 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
2870 bi != N->PointsTo->end();
2874 PrintNode(&GraphNodes[*bi]);