1 //===- Andersens.cpp - Andersen's Interprocedural Alias Analysis ----------===//
3 // The LLVM Compiler Infrastructure
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.
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 computer pointer and location
35 // equivalences. Pointer equivalences are those pointers that will have the
36 // same points-to sets, and location equivalences are those variables that
37 // always appear together in points-to sets.
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.
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.
50 // Future Improvements:
51 // Offline detection of online cycles. Use of BDD's.
52 //===----------------------------------------------------------------------===//
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"
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");
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;
89 struct BitmapKeyInfo {
90 static inline SparseBitVector<> *getEmptyKey() {
91 return reinterpret_cast<SparseBitVector<> *>(-1);
93 static inline SparseBitVector<> *getTombstoneKey() {
94 return reinterpret_cast<SparseBitVector<> *>(-2);
96 static unsigned getHashValue(const SparseBitVector<> *bitmap) {
97 return bitmap->getHashValue();
99 static bool isEqual(const SparseBitVector<> *LHS,
100 const SparseBitVector<> *RHS) {
103 else if (LHS == getEmptyKey() || RHS == getEmptyKey()
104 || LHS == getTombstoneKey() || RHS == getTombstoneKey())
110 static bool isPod() { return true; }
113 class VISIBILITY_HIDDEN Andersens : public ModulePass, public AliasAnalysis,
114 private InstVisitor<Andersens> {
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)
127 enum ConstraintType { Copy, Load, Store, AddressOf } Type;
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");
137 bool operator==(const Constraint &RHS) const {
138 return RHS.Type == Type
141 && RHS.Offset == Offset;
143 bool operator<(const Constraint &RHS) const {
144 if (RHS.Type != Type)
145 return RHS.Type < Type;
146 else if (RHS.Dest != Dest)
147 return RHS.Dest < Dest;
148 else if (RHS.Src != Src)
149 return RHS.Src < Src;
150 return RHS.Offset < Offset;
154 // Node class - This class is used to represent a node in the constraint
155 // graph. Due to various optimizations, it is not always the case that
156 // there is a mapping from a Node to a Value. In particular, we add
157 // artificial Node's that represent the set of pointed-to variables shared
158 // for each location equivalent Node.
161 SparseBitVector<> *Edges;
162 SparseBitVector<> *PointsTo;
163 SparseBitVector<> *OldPointsTo;
165 std::list<Constraint> Constraints;
167 // Pointer and location equivalence labels
168 unsigned PointerEquivLabel;
169 unsigned LocationEquivLabel;
170 // Predecessor edges, both real and implicit
171 SparseBitVector<> *PredEdges;
172 SparseBitVector<> *ImplicitPredEdges;
173 // Set of nodes that point to us, only use for location equivalence.
174 SparseBitVector<> *PointedToBy;
175 // Number of incoming edges, used during variable substitution to early
176 // free the points-to sets
178 // True if our points-to set is in the Set2PEClass map
180 // True if our node has no indirect constraints (complex or otherwise)
182 // True if the node is address taken, *or* it is part of a group of nodes
183 // that must be kept together. This is set to true for functions and
184 // their arg nodes, which must be kept at the same position relative to
185 // their base function node.
188 // Nodes in cycles (or in equivalence classes) are united together using a
189 // standard union-find representation with path compression. NodeRep
190 // gives the index into GraphNodes for the representative Node.
194 Node(bool direct = true) :
195 Val(0), Edges(0), PointsTo(0), OldPointsTo(0), Changed(false),
196 PointerEquivLabel(0), LocationEquivLabel(0), PredEdges(0),
197 ImplicitPredEdges(0), PointedToBy(0), NumInEdges(0),
198 StoredInHash(false), Direct(direct), AddressTaken(false),
201 Node *setValue(Value *V) {
202 assert(Val == 0 && "Value already set for this node!");
207 /// getValue - Return the LLVM value corresponding to this node.
209 Value *getValue() const { return Val; }
211 /// addPointerTo - Add a pointer to the list of pointees of this node,
212 /// returning true if this caused a new pointer to be added, or false if
213 /// we already knew about the points-to relation.
214 bool addPointerTo(unsigned Node) {
215 return PointsTo->test_and_set(Node);
218 /// intersects - Return true if the points-to set of this node intersects
219 /// with the points-to set of the specified node.
220 bool intersects(Node *N) const;
222 /// intersectsIgnoring - Return true if the points-to set of this node
223 /// intersects with the points-to set of the specified node on any nodes
224 /// except for the specified node to ignore.
225 bool intersectsIgnoring(Node *N, unsigned) const;
228 /// GraphNodes - This vector is populated as part of the object
229 /// identification stage of the analysis, which populates this vector with a
230 /// node for each memory object and fills in the ValueNodes map.
231 std::vector<Node> GraphNodes;
233 /// ValueNodes - This map indicates the Node that a particular Value* is
234 /// represented by. This contains entries for all pointers.
235 DenseMap<Value*, unsigned> ValueNodes;
237 /// ObjectNodes - This map contains entries for each memory object in the
238 /// program: globals, alloca's and mallocs.
239 DenseMap<Value*, unsigned> ObjectNodes;
241 /// ReturnNodes - This map contains an entry for each function in the
242 /// program that returns a value.
243 DenseMap<Function*, unsigned> ReturnNodes;
245 /// VarargNodes - This map contains the entry used to represent all pointers
246 /// passed through the varargs portion of a function call for a particular
247 /// function. An entry is not present in this map for functions that do not
248 /// take variable arguments.
249 DenseMap<Function*, unsigned> VarargNodes;
252 /// Constraints - This vector contains a list of all of the constraints
253 /// identified by the program.
254 std::vector<Constraint> Constraints;
256 // Map from graph node to maximum K value that is allowed (for functions,
257 // this is equivalent to the number of arguments + CallFirstArgPos)
258 std::map<unsigned, unsigned> MaxK;
260 /// This enum defines the GraphNodes indices that correspond to important
268 // Stack for Tarjan's
269 std::stack<unsigned> SCCStack;
270 // Topological Index -> Graph node
271 std::vector<unsigned> Topo2Node;
272 // Graph Node -> Topological Index;
273 std::vector<unsigned> Node2Topo;
274 // Map from Graph Node to DFS number
275 std::vector<unsigned> Node2DFS;
276 // Map from Graph Node to Deleted from graph.
277 std::vector<bool> Node2Deleted;
278 // Current DFS and RPO numbers
282 // Offline variable substitution related things
284 // Temporary rep storage, used because we can't collapse SCC's in the
285 // predecessor graph by uniting the variables permanently, we can only do so
286 // for the successor graph.
287 std::vector<unsigned> VSSCCRep;
288 // Mapping from node to whether we have visited it during SCC finding yet.
289 std::vector<bool> Node2Visited;
290 // During variable substitution, we create unknowns to represent the unknown
291 // value that is a dereference of a variable. These nodes are known as
292 // "ref" nodes (since they represent the value of dereferences).
293 unsigned FirstRefNode;
294 // During HVN, we create represent address taken nodes as if they were
295 // unknown (since HVN, unlike HU, does not evaluate unions).
296 unsigned FirstAdrNode;
297 // Current pointer equivalence class number
299 // Mapping from points-to sets to equivalence classes
300 typedef DenseMap<SparseBitVector<> *, unsigned, BitmapKeyInfo> BitVectorMap;
301 BitVectorMap Set2PEClass;
302 // Mapping from pointer equivalences to the representative node. -1 if we
303 // have no representative node for this pointer equivalence class yet.
304 std::vector<int> PEClass2Node;
305 // Mapping from pointer equivalences to representative node. This includes
306 // pointer equivalent but not location equivalent variables. -1 if we have
307 // no representative node for this pointer equivalence class yet.
308 std::vector<int> PENLEClass2Node;
312 Andersens() : ModulePass((intptr_t)&ID) {}
314 bool runOnModule(Module &M) {
315 InitializeAliasAnalysis(this);
317 CollectConstraints(M);
319 #define DEBUG_TYPE "anders-aa-constraints"
320 DEBUG(PrintConstraints());
322 #define DEBUG_TYPE "anders-aa"
324 DEBUG(PrintPointsToGraph());
326 // Free the constraints list, as we don't need it to respond to alias
331 std::vector<Constraint>().swap(Constraints);
335 void releaseMemory() {
336 // FIXME: Until we have transitively required passes working correctly,
337 // this cannot be enabled! Otherwise, using -count-aa with the pass
338 // causes memory to be freed too early. :(
340 // The memory objects and ValueNodes data structures at the only ones that
341 // are still live after construction.
342 std::vector<Node>().swap(GraphNodes);
347 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
348 AliasAnalysis::getAnalysisUsage(AU);
349 AU.setPreservesAll(); // Does not transform code
352 //------------------------------------------------
353 // Implement the AliasAnalysis API
355 AliasResult alias(const Value *V1, unsigned V1Size,
356 const Value *V2, unsigned V2Size);
357 virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
358 virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
359 void getMustAliases(Value *P, std::vector<Value*> &RetVals);
360 bool pointsToConstantMemory(const Value *P);
362 virtual void deleteValue(Value *V) {
364 getAnalysis<AliasAnalysis>().deleteValue(V);
367 virtual void copyValue(Value *From, Value *To) {
368 ValueNodes[To] = ValueNodes[From];
369 getAnalysis<AliasAnalysis>().copyValue(From, To);
373 /// getNode - Return the node corresponding to the specified pointer scalar.
375 unsigned getNode(Value *V) {
376 if (Constant *C = dyn_cast<Constant>(V))
377 if (!isa<GlobalValue>(C))
378 return getNodeForConstantPointer(C);
380 DenseMap<Value*, unsigned>::iterator I = ValueNodes.find(V);
381 if (I == ValueNodes.end()) {
385 assert(0 && "Value does not have a node in the points-to graph!");
390 /// getObject - Return the node corresponding to the memory object for the
391 /// specified global or allocation instruction.
392 unsigned getObject(Value *V) {
393 DenseMap<Value*, unsigned>::iterator I = ObjectNodes.find(V);
394 assert(I != ObjectNodes.end() &&
395 "Value does not have an object in the points-to graph!");
399 /// getReturnNode - Return the node representing the return value for the
400 /// specified function.
401 unsigned getReturnNode(Function *F) {
402 DenseMap<Function*, unsigned>::iterator I = ReturnNodes.find(F);
403 assert(I != ReturnNodes.end() && "Function does not return a value!");
407 /// getVarargNode - Return the node representing the variable arguments
408 /// formal for the specified function.
409 unsigned getVarargNode(Function *F) {
410 DenseMap<Function*, unsigned>::iterator I = VarargNodes.find(F);
411 assert(I != VarargNodes.end() && "Function does not take var args!");
415 /// getNodeValue - Get the node for the specified LLVM value and set the
416 /// value for it to be the specified value.
417 unsigned getNodeValue(Value &V) {
418 unsigned Index = getNode(&V);
419 GraphNodes[Index].setValue(&V);
423 unsigned UniteNodes(unsigned First, unsigned Second);
424 unsigned FindNode(unsigned Node);
426 void IdentifyObjects(Module &M);
427 void CollectConstraints(Module &M);
428 bool AnalyzeUsesOfFunction(Value *);
429 void CreateConstraintGraph();
430 void OptimizeConstraints();
431 unsigned FindEquivalentNode(unsigned, unsigned);
432 void ClumpAddressTaken();
433 void RewriteConstraints();
436 void UnitePointerEquivalences();
437 void SolveConstraints();
438 void QueryNode(unsigned Node);
439 void Condense(unsigned Node);
440 void HUValNum(unsigned Node);
441 void HVNValNum(unsigned Node);
442 unsigned getNodeForConstantPointer(Constant *C);
443 unsigned getNodeForConstantPointerTarget(Constant *C);
444 void AddGlobalInitializerConstraints(unsigned, Constant *C);
446 void AddConstraintsForNonInternalLinkage(Function *F);
447 void AddConstraintsForCall(CallSite CS, Function *F);
448 bool AddConstraintsForExternalCall(CallSite CS, Function *F);
451 void PrintNode(Node *N);
452 void PrintConstraints();
453 void PrintConstraint(const Constraint &);
455 void PrintPointsToGraph();
457 //===------------------------------------------------------------------===//
458 // Instruction visitation methods for adding constraints
460 friend class InstVisitor<Andersens>;
461 void visitReturnInst(ReturnInst &RI);
462 void visitInvokeInst(InvokeInst &II) { visitCallSite(CallSite(&II)); }
463 void visitCallInst(CallInst &CI) { visitCallSite(CallSite(&CI)); }
464 void visitCallSite(CallSite CS);
465 void visitAllocationInst(AllocationInst &AI);
466 void visitLoadInst(LoadInst &LI);
467 void visitStoreInst(StoreInst &SI);
468 void visitGetElementPtrInst(GetElementPtrInst &GEP);
469 void visitPHINode(PHINode &PN);
470 void visitCastInst(CastInst &CI);
471 void visitICmpInst(ICmpInst &ICI) {} // NOOP!
472 void visitFCmpInst(FCmpInst &ICI) {} // NOOP!
473 void visitSelectInst(SelectInst &SI);
474 void visitVAArg(VAArgInst &I);
475 void visitInstruction(Instruction &I);
479 char Andersens::ID = 0;
480 RegisterPass<Andersens> X("anders-aa",
481 "Andersen's Interprocedural Alias Analysis");
482 RegisterAnalysisGroup<AliasAnalysis> Y(X);
485 ModulePass *llvm::createAndersensPass() { return new Andersens(); }
487 //===----------------------------------------------------------------------===//
488 // AliasAnalysis Interface Implementation
489 //===----------------------------------------------------------------------===//
491 AliasAnalysis::AliasResult Andersens::alias(const Value *V1, unsigned V1Size,
492 const Value *V2, unsigned V2Size) {
493 Node *N1 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V1)))];
494 Node *N2 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V2)))];
496 // Check to see if the two pointers are known to not alias. They don't alias
497 // if their points-to sets do not intersect.
498 if (!N1->intersectsIgnoring(N2, NullObject))
501 return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
504 AliasAnalysis::ModRefResult
505 Andersens::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
506 // The only thing useful that we can contribute for mod/ref information is
507 // when calling external function calls: if we know that memory never escapes
508 // from the program, it cannot be modified by an external call.
510 // NOTE: This is not really safe, at least not when the entire program is not
511 // available. The deal is that the external function could call back into the
512 // program and modify stuff. We ignore this technical niggle for now. This
513 // is, after all, a "research quality" implementation of Andersen's analysis.
514 if (Function *F = CS.getCalledFunction())
515 if (F->isDeclaration()) {
516 Node *N1 = &GraphNodes[FindNode(getNode(P))];
518 if (N1->PointsTo->empty())
521 if (!N1->PointsTo->test(UniversalSet))
522 return NoModRef; // P doesn't point to the universal set.
525 return AliasAnalysis::getModRefInfo(CS, P, Size);
528 AliasAnalysis::ModRefResult
529 Andersens::getModRefInfo(CallSite CS1, CallSite CS2) {
530 return AliasAnalysis::getModRefInfo(CS1,CS2);
533 /// getMustAlias - We can provide must alias information if we know that a
534 /// pointer can only point to a specific function or the null pointer.
535 /// Unfortunately we cannot determine must-alias information for global
536 /// variables or any other memory memory objects because we do not track whether
537 /// a pointer points to the beginning of an object or a field of it.
538 void Andersens::getMustAliases(Value *P, std::vector<Value*> &RetVals) {
539 Node *N = &GraphNodes[FindNode(getNode(P))];
540 if (N->PointsTo->count() == 1) {
541 Node *Pointee = &GraphNodes[N->PointsTo->find_first()];
542 // If a function is the only object in the points-to set, then it must be
543 // the destination. Note that we can't handle global variables here,
544 // because we don't know if the pointer is actually pointing to a field of
545 // the global or to the beginning of it.
546 if (Value *V = Pointee->getValue()) {
547 if (Function *F = dyn_cast<Function>(V))
548 RetVals.push_back(F);
550 // If the object in the points-to set is the null object, then the null
551 // pointer is a must alias.
552 if (Pointee == &GraphNodes[NullObject])
553 RetVals.push_back(Constant::getNullValue(P->getType()));
556 AliasAnalysis::getMustAliases(P, RetVals);
559 /// pointsToConstantMemory - If we can determine that this pointer only points
560 /// to constant memory, return true. In practice, this means that if the
561 /// pointer can only point to constant globals, functions, or the null pointer,
564 bool Andersens::pointsToConstantMemory(const Value *P) {
565 Node *N = &GraphNodes[FindNode(getNode((Value*)P))];
568 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
569 bi != N->PointsTo->end();
572 Node *Pointee = &GraphNodes[i];
573 if (Value *V = Pointee->getValue()) {
574 if (!isa<GlobalValue>(V) || (isa<GlobalVariable>(V) &&
575 !cast<GlobalVariable>(V)->isConstant()))
576 return AliasAnalysis::pointsToConstantMemory(P);
579 return AliasAnalysis::pointsToConstantMemory(P);
586 //===----------------------------------------------------------------------===//
587 // Object Identification Phase
588 //===----------------------------------------------------------------------===//
590 /// IdentifyObjects - This stage scans the program, adding an entry to the
591 /// GraphNodes list for each memory object in the program (global stack or
592 /// heap), and populates the ValueNodes and ObjectNodes maps for these objects.
594 void Andersens::IdentifyObjects(Module &M) {
595 unsigned NumObjects = 0;
597 // Object #0 is always the universal set: the object that we don't know
599 assert(NumObjects == UniversalSet && "Something changed!");
602 // Object #1 always represents the null pointer.
603 assert(NumObjects == NullPtr && "Something changed!");
606 // Object #2 always represents the null object (the object pointed to by null)
607 assert(NumObjects == NullObject && "Something changed!");
610 // Add all the globals first.
611 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
613 ObjectNodes[I] = NumObjects++;
614 ValueNodes[I] = NumObjects++;
617 // Add nodes for all of the functions and the instructions inside of them.
618 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
619 // The function itself is a memory object.
620 unsigned First = NumObjects;
621 ValueNodes[F] = NumObjects++;
622 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
623 ReturnNodes[F] = NumObjects++;
624 if (F->getFunctionType()->isVarArg())
625 VarargNodes[F] = NumObjects++;
628 // Add nodes for all of the incoming pointer arguments.
629 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
632 if (isa<PointerType>(I->getType()))
633 ValueNodes[I] = NumObjects++;
635 MaxK[First] = NumObjects - First;
637 // Scan the function body, creating a memory object for each heap/stack
638 // allocation in the body of the function and a node to represent all
639 // pointer values defined by instructions and used as operands.
640 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
641 // If this is an heap or stack allocation, create a node for the memory
643 if (isa<PointerType>(II->getType())) {
644 ValueNodes[&*II] = NumObjects++;
645 if (AllocationInst *AI = dyn_cast<AllocationInst>(&*II))
646 ObjectNodes[AI] = NumObjects++;
651 // Now that we know how many objects to create, make them all now!
652 GraphNodes.resize(NumObjects);
653 NumNodes += NumObjects;
656 //===----------------------------------------------------------------------===//
657 // Constraint Identification Phase
658 //===----------------------------------------------------------------------===//
660 /// getNodeForConstantPointer - Return the node corresponding to the constant
662 unsigned Andersens::getNodeForConstantPointer(Constant *C) {
663 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
665 if (isa<ConstantPointerNull>(C) || isa<UndefValue>(C))
667 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
669 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
670 switch (CE->getOpcode()) {
671 case Instruction::GetElementPtr:
672 return getNodeForConstantPointer(CE->getOperand(0));
673 case Instruction::IntToPtr:
675 case Instruction::BitCast:
676 return getNodeForConstantPointer(CE->getOperand(0));
678 cerr << "Constant Expr not yet handled: " << *CE << "\n";
682 assert(0 && "Unknown constant pointer!");
687 /// getNodeForConstantPointerTarget - Return the node POINTED TO by the
688 /// specified constant pointer.
689 unsigned Andersens::getNodeForConstantPointerTarget(Constant *C) {
690 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
692 if (isa<ConstantPointerNull>(C))
694 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
695 return getObject(GV);
696 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
697 switch (CE->getOpcode()) {
698 case Instruction::GetElementPtr:
699 return getNodeForConstantPointerTarget(CE->getOperand(0));
700 case Instruction::IntToPtr:
702 case Instruction::BitCast:
703 return getNodeForConstantPointerTarget(CE->getOperand(0));
705 cerr << "Constant Expr not yet handled: " << *CE << "\n";
709 assert(0 && "Unknown constant pointer!");
714 /// AddGlobalInitializerConstraints - Add inclusion constraints for the memory
715 /// object N, which contains values indicated by C.
716 void Andersens::AddGlobalInitializerConstraints(unsigned NodeIndex,
718 if (C->getType()->isFirstClassType()) {
719 if (isa<PointerType>(C->getType()))
720 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
721 getNodeForConstantPointer(C)));
722 } else if (C->isNullValue()) {
723 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
726 } else if (!isa<UndefValue>(C)) {
727 // If this is an array or struct, include constraints for each element.
728 assert(isa<ConstantArray>(C) || isa<ConstantStruct>(C));
729 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
730 AddGlobalInitializerConstraints(NodeIndex,
731 cast<Constant>(C->getOperand(i)));
735 /// AddConstraintsForNonInternalLinkage - If this function does not have
736 /// internal linkage, realize that we can't trust anything passed into or
737 /// returned by this function.
738 void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
739 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
740 if (isa<PointerType>(I->getType()))
741 // If this is an argument of an externally accessible function, the
742 // incoming pointer might point to anything.
743 Constraints.push_back(Constraint(Constraint::Copy, getNode(I),
747 /// AddConstraintsForCall - If this is a call to a "known" function, add the
748 /// constraints and return true. If this is a call to an unknown function,
750 bool Andersens::AddConstraintsForExternalCall(CallSite CS, Function *F) {
751 assert(F->isDeclaration() && "Not an external function!");
753 // These functions don't induce any points-to constraints.
754 if (F->getName() == "atoi" || F->getName() == "atof" ||
755 F->getName() == "atol" || F->getName() == "atoll" ||
756 F->getName() == "remove" || F->getName() == "unlink" ||
757 F->getName() == "rename" || F->getName() == "memcmp" ||
758 F->getName() == "llvm.memset.i32" ||
759 F->getName() == "llvm.memset.i64" ||
760 F->getName() == "strcmp" || F->getName() == "strncmp" ||
761 F->getName() == "execl" || F->getName() == "execlp" ||
762 F->getName() == "execle" || F->getName() == "execv" ||
763 F->getName() == "execvp" || F->getName() == "chmod" ||
764 F->getName() == "puts" || F->getName() == "write" ||
765 F->getName() == "open" || F->getName() == "create" ||
766 F->getName() == "truncate" || F->getName() == "chdir" ||
767 F->getName() == "mkdir" || F->getName() == "rmdir" ||
768 F->getName() == "read" || F->getName() == "pipe" ||
769 F->getName() == "wait" || F->getName() == "time" ||
770 F->getName() == "stat" || F->getName() == "fstat" ||
771 F->getName() == "lstat" || F->getName() == "strtod" ||
772 F->getName() == "strtof" || F->getName() == "strtold" ||
773 F->getName() == "fopen" || F->getName() == "fdopen" ||
774 F->getName() == "freopen" ||
775 F->getName() == "fflush" || F->getName() == "feof" ||
776 F->getName() == "fileno" || F->getName() == "clearerr" ||
777 F->getName() == "rewind" || F->getName() == "ftell" ||
778 F->getName() == "ferror" || F->getName() == "fgetc" ||
779 F->getName() == "fgetc" || F->getName() == "_IO_getc" ||
780 F->getName() == "fwrite" || F->getName() == "fread" ||
781 F->getName() == "fgets" || F->getName() == "ungetc" ||
782 F->getName() == "fputc" ||
783 F->getName() == "fputs" || F->getName() == "putc" ||
784 F->getName() == "ftell" || F->getName() == "rewind" ||
785 F->getName() == "_IO_putc" || F->getName() == "fseek" ||
786 F->getName() == "fgetpos" || F->getName() == "fsetpos" ||
787 F->getName() == "printf" || F->getName() == "fprintf" ||
788 F->getName() == "sprintf" || F->getName() == "vprintf" ||
789 F->getName() == "vfprintf" || F->getName() == "vsprintf" ||
790 F->getName() == "scanf" || F->getName() == "fscanf" ||
791 F->getName() == "sscanf" || F->getName() == "__assert_fail" ||
792 F->getName() == "modf")
796 // These functions do induce points-to edges.
797 if (F->getName() == "llvm.memcpy.i32" || F->getName() == "llvm.memcpy.i64" ||
798 F->getName() == "llvm.memmove.i32" ||F->getName() == "llvm.memmove.i64" ||
799 F->getName() == "memmove") {
801 // *Dest = *Src, which requires an artificial graph node to represent the
802 // constraint. It is broken up into *Dest = temp, temp = *Src
803 unsigned FirstArg = getNode(CS.getArgument(0));
804 unsigned SecondArg = getNode(CS.getArgument(1));
805 unsigned TempArg = GraphNodes.size();
806 GraphNodes.push_back(Node());
807 Constraints.push_back(Constraint(Constraint::Store,
809 Constraints.push_back(Constraint(Constraint::Load,
810 TempArg, SecondArg));
815 if (F->getName() == "realloc" || F->getName() == "strchr" ||
816 F->getName() == "strrchr" || F->getName() == "strstr" ||
817 F->getName() == "strtok") {
818 Constraints.push_back(Constraint(Constraint::Copy,
819 getNode(CS.getInstruction()),
820 getNode(CS.getArgument(0))));
829 /// AnalyzeUsesOfFunction - Look at all of the users of the specified function.
830 /// If this is used by anything complex (i.e., the address escapes), return
832 bool Andersens::AnalyzeUsesOfFunction(Value *V) {
834 if (!isa<PointerType>(V->getType())) return true;
836 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
837 if (dyn_cast<LoadInst>(*UI)) {
839 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
840 if (V == SI->getOperand(1)) {
842 } else if (SI->getOperand(1)) {
843 return true; // Storing the pointer
845 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
846 if (AnalyzeUsesOfFunction(GEP)) return true;
847 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
848 // Make sure that this is just the function being called, not that it is
849 // passing into the function.
850 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
851 if (CI->getOperand(i) == V) return true;
852 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
853 // Make sure that this is just the function being called, not that it is
854 // passing into the function.
855 for (unsigned i = 3, e = II->getNumOperands(); i != e; ++i)
856 if (II->getOperand(i) == V) return true;
857 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
858 if (CE->getOpcode() == Instruction::GetElementPtr ||
859 CE->getOpcode() == Instruction::BitCast) {
860 if (AnalyzeUsesOfFunction(CE))
865 } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(*UI)) {
866 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
867 return true; // Allow comparison against null.
868 } else if (dyn_cast<FreeInst>(*UI)) {
876 /// CollectConstraints - This stage scans the program, adding a constraint to
877 /// the Constraints list for each instruction in the program that induces a
878 /// constraint, and setting up the initial points-to graph.
880 void Andersens::CollectConstraints(Module &M) {
881 // First, the universal set points to itself.
882 Constraints.push_back(Constraint(Constraint::AddressOf, UniversalSet,
884 Constraints.push_back(Constraint(Constraint::Store, UniversalSet,
887 // Next, the null pointer points to the null object.
888 Constraints.push_back(Constraint(Constraint::AddressOf, NullPtr, NullObject));
890 // Next, add any constraints on global variables and their initializers.
891 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
893 // Associate the address of the global object as pointing to the memory for
894 // the global: &G = <G memory>
895 unsigned ObjectIndex = getObject(I);
896 Node *Object = &GraphNodes[ObjectIndex];
898 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(*I),
901 if (I->hasInitializer()) {
902 AddGlobalInitializerConstraints(ObjectIndex, I->getInitializer());
904 // If it doesn't have an initializer (i.e. it's defined in another
905 // translation unit), it points to the universal set.
906 Constraints.push_back(Constraint(Constraint::Copy, ObjectIndex,
911 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
912 // Set up the return value node.
913 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
914 GraphNodes[getReturnNode(F)].setValue(F);
915 if (F->getFunctionType()->isVarArg())
916 GraphNodes[getVarargNode(F)].setValue(F);
918 // Set up incoming argument nodes.
919 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
921 if (isa<PointerType>(I->getType()))
924 // At some point we should just add constraints for the escaping functions
925 // at solve time, but this slows down solving. For now, we simply mark
926 // address taken functions as escaping and treat them as external.
927 if (!F->hasInternalLinkage() || AnalyzeUsesOfFunction(F))
928 AddConstraintsForNonInternalLinkage(F);
930 if (!F->isDeclaration()) {
931 // Scan the function body, creating a memory object for each heap/stack
932 // allocation in the body of the function and a node to represent all
933 // pointer values defined by instructions and used as operands.
936 // External functions that return pointers return the universal set.
937 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
938 Constraints.push_back(Constraint(Constraint::Copy,
942 // Any pointers that are passed into the function have the universal set
944 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
946 if (isa<PointerType>(I->getType())) {
947 // Pointers passed into external functions could have anything stored
949 Constraints.push_back(Constraint(Constraint::Store, getNode(I),
951 // Memory objects passed into external function calls can have the
952 // universal set point to them.
953 Constraints.push_back(Constraint(Constraint::Copy,
958 // If this is an external varargs function, it can also store pointers
959 // into any pointers passed through the varargs section.
960 if (F->getFunctionType()->isVarArg())
961 Constraints.push_back(Constraint(Constraint::Store, getVarargNode(F),
965 NumConstraints += Constraints.size();
969 void Andersens::visitInstruction(Instruction &I) {
971 return; // This function is just a big assert.
973 if (isa<BinaryOperator>(I))
975 // Most instructions don't have any effect on pointer values.
976 switch (I.getOpcode()) {
977 case Instruction::Br:
978 case Instruction::Switch:
979 case Instruction::Unwind:
980 case Instruction::Unreachable:
981 case Instruction::Free:
982 case Instruction::ICmp:
983 case Instruction::FCmp:
986 // Is this something we aren't handling yet?
987 cerr << "Unknown instruction: " << I;
992 void Andersens::visitAllocationInst(AllocationInst &AI) {
993 unsigned ObjectIndex = getObject(&AI);
994 GraphNodes[ObjectIndex].setValue(&AI);
995 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(AI),
999 void Andersens::visitReturnInst(ReturnInst &RI) {
1000 if (RI.getNumOperands() && isa<PointerType>(RI.getOperand(0)->getType()))
1001 // return V --> <Copy/retval{F}/v>
1002 Constraints.push_back(Constraint(Constraint::Copy,
1003 getReturnNode(RI.getParent()->getParent()),
1004 getNode(RI.getOperand(0))));
1007 void Andersens::visitLoadInst(LoadInst &LI) {
1008 if (isa<PointerType>(LI.getType()))
1009 // P1 = load P2 --> <Load/P1/P2>
1010 Constraints.push_back(Constraint(Constraint::Load, getNodeValue(LI),
1011 getNode(LI.getOperand(0))));
1014 void Andersens::visitStoreInst(StoreInst &SI) {
1015 if (isa<PointerType>(SI.getOperand(0)->getType()))
1016 // store P1, P2 --> <Store/P2/P1>
1017 Constraints.push_back(Constraint(Constraint::Store,
1018 getNode(SI.getOperand(1)),
1019 getNode(SI.getOperand(0))));
1022 void Andersens::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1023 // P1 = getelementptr P2, ... --> <Copy/P1/P2>
1024 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(GEP),
1025 getNode(GEP.getOperand(0))));
1028 void Andersens::visitPHINode(PHINode &PN) {
1029 if (isa<PointerType>(PN.getType())) {
1030 unsigned PNN = getNodeValue(PN);
1031 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1032 // P1 = phi P2, P3 --> <Copy/P1/P2>, <Copy/P1/P3>, ...
1033 Constraints.push_back(Constraint(Constraint::Copy, PNN,
1034 getNode(PN.getIncomingValue(i))));
1038 void Andersens::visitCastInst(CastInst &CI) {
1039 Value *Op = CI.getOperand(0);
1040 if (isa<PointerType>(CI.getType())) {
1041 if (isa<PointerType>(Op->getType())) {
1042 // P1 = cast P2 --> <Copy/P1/P2>
1043 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
1044 getNode(CI.getOperand(0))));
1046 // P1 = cast int --> <Copy/P1/Univ>
1048 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
1054 } else if (isa<PointerType>(Op->getType())) {
1055 // int = cast P1 --> <Copy/Univ/P1>
1057 Constraints.push_back(Constraint(Constraint::Copy,
1059 getNode(CI.getOperand(0))));
1061 getNode(CI.getOperand(0));
1066 void Andersens::visitSelectInst(SelectInst &SI) {
1067 if (isa<PointerType>(SI.getType())) {
1068 unsigned SIN = getNodeValue(SI);
1069 // P1 = select C, P2, P3 ---> <Copy/P1/P2>, <Copy/P1/P3>
1070 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1071 getNode(SI.getOperand(1))));
1072 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1073 getNode(SI.getOperand(2))));
1077 void Andersens::visitVAArg(VAArgInst &I) {
1078 assert(0 && "vaarg not handled yet!");
1081 /// AddConstraintsForCall - Add constraints for a call with actual arguments
1082 /// specified by CS to the function specified by F. Note that the types of
1083 /// arguments might not match up in the case where this is an indirect call and
1084 /// the function pointer has been casted. If this is the case, do something
1086 void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
1087 Value *CallValue = CS.getCalledValue();
1088 bool IsDeref = F == NULL;
1090 // If this is a call to an external function, try to handle it directly to get
1091 // some taste of context sensitivity.
1092 if (F && F->isDeclaration() && AddConstraintsForExternalCall(CS, F))
1095 if (isa<PointerType>(CS.getType())) {
1096 unsigned CSN = getNode(CS.getInstruction());
1097 if (!F || isa<PointerType>(F->getFunctionType()->getReturnType())) {
1099 Constraints.push_back(Constraint(Constraint::Load, CSN,
1100 getNode(CallValue), CallReturnPos));
1102 Constraints.push_back(Constraint(Constraint::Copy, CSN,
1103 getNode(CallValue) + CallReturnPos));
1105 // If the function returns a non-pointer value, handle this just like we
1106 // treat a nonpointer cast to pointer.
1107 Constraints.push_back(Constraint(Constraint::Copy, CSN,
1110 } else if (F && isa<PointerType>(F->getFunctionType()->getReturnType())) {
1111 Constraints.push_back(Constraint(Constraint::Copy,
1113 getNode(CallValue) + CallReturnPos));
1116 CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
1119 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1120 for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI)
1121 if (isa<PointerType>(AI->getType())) {
1122 if (isa<PointerType>((*ArgI)->getType())) {
1123 // Copy the actual argument into the formal argument.
1124 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1127 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1130 } else if (isa<PointerType>((*ArgI)->getType())) {
1131 Constraints.push_back(Constraint(Constraint::Copy,
1137 unsigned ArgPos = CallFirstArgPos;
1138 for (; ArgI != ArgE; ++ArgI) {
1139 if (isa<PointerType>((*ArgI)->getType())) {
1140 // Copy the actual argument into the formal argument.
1141 Constraints.push_back(Constraint(Constraint::Store,
1143 getNode(*ArgI), ArgPos++));
1145 Constraints.push_back(Constraint(Constraint::Store,
1146 getNode (CallValue),
1147 UniversalSet, ArgPos++));
1151 // Copy all pointers passed through the varargs section to the varargs node.
1152 if (F && F->getFunctionType()->isVarArg())
1153 for (; ArgI != ArgE; ++ArgI)
1154 if (isa<PointerType>((*ArgI)->getType()))
1155 Constraints.push_back(Constraint(Constraint::Copy, getVarargNode(F),
1157 // If more arguments are passed in than we track, just drop them on the floor.
1160 void Andersens::visitCallSite(CallSite CS) {
1161 if (isa<PointerType>(CS.getType()))
1162 getNodeValue(*CS.getInstruction());
1164 if (Function *F = CS.getCalledFunction()) {
1165 AddConstraintsForCall(CS, F);
1167 AddConstraintsForCall(CS, NULL);
1171 //===----------------------------------------------------------------------===//
1172 // Constraint Solving Phase
1173 //===----------------------------------------------------------------------===//
1175 /// intersects - Return true if the points-to set of this node intersects
1176 /// with the points-to set of the specified node.
1177 bool Andersens::Node::intersects(Node *N) const {
1178 return PointsTo->intersects(N->PointsTo);
1181 /// intersectsIgnoring - Return true if the points-to set of this node
1182 /// intersects with the points-to set of the specified node on any nodes
1183 /// except for the specified node to ignore.
1184 bool Andersens::Node::intersectsIgnoring(Node *N, unsigned Ignoring) const {
1185 // TODO: If we are only going to call this with the same value for Ignoring,
1186 // we should move the special values out of the points-to bitmap.
1187 bool WeHadIt = PointsTo->test(Ignoring);
1188 bool NHadIt = N->PointsTo->test(Ignoring);
1189 bool Result = false;
1191 PointsTo->reset(Ignoring);
1193 N->PointsTo->reset(Ignoring);
1194 Result = PointsTo->intersects(N->PointsTo);
1196 PointsTo->set(Ignoring);
1198 N->PointsTo->set(Ignoring);
1202 void dumpToDOUT(SparseBitVector<> *bitmap) {
1204 dump(*bitmap, DOUT);
1209 /// Clump together address taken variables so that the points-to sets use up
1210 /// less space and can be operated on faster.
1212 void Andersens::ClumpAddressTaken() {
1214 #define DEBUG_TYPE "anders-aa-renumber"
1215 std::vector<unsigned> Translate;
1216 std::vector<Node> NewGraphNodes;
1218 Translate.resize(GraphNodes.size());
1219 unsigned NewPos = 0;
1221 for (unsigned i = 0; i < Constraints.size(); ++i) {
1222 Constraint &C = Constraints[i];
1223 if (C.Type == Constraint::AddressOf) {
1224 GraphNodes[C.Src].AddressTaken = true;
1227 for (unsigned i = 0; i < NumberSpecialNodes; ++i) {
1228 unsigned Pos = NewPos++;
1230 NewGraphNodes.push_back(GraphNodes[i]);
1231 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1234 // I believe this ends up being faster than making two vectors and splicing
1236 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1237 if (GraphNodes[i].AddressTaken) {
1238 unsigned Pos = NewPos++;
1240 NewGraphNodes.push_back(GraphNodes[i]);
1241 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1245 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1246 if (!GraphNodes[i].AddressTaken) {
1247 unsigned Pos = NewPos++;
1249 NewGraphNodes.push_back(GraphNodes[i]);
1250 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1254 for (DenseMap<Value*, unsigned>::iterator Iter = ValueNodes.begin();
1255 Iter != ValueNodes.end();
1257 Iter->second = Translate[Iter->second];
1259 for (DenseMap<Value*, unsigned>::iterator Iter = ObjectNodes.begin();
1260 Iter != ObjectNodes.end();
1262 Iter->second = Translate[Iter->second];
1264 for (DenseMap<Function*, unsigned>::iterator Iter = ReturnNodes.begin();
1265 Iter != ReturnNodes.end();
1267 Iter->second = Translate[Iter->second];
1269 for (DenseMap<Function*, unsigned>::iterator Iter = VarargNodes.begin();
1270 Iter != VarargNodes.end();
1272 Iter->second = Translate[Iter->second];
1274 for (unsigned i = 0; i < Constraints.size(); ++i) {
1275 Constraint &C = Constraints[i];
1276 C.Src = Translate[C.Src];
1277 C.Dest = Translate[C.Dest];
1280 GraphNodes.swap(NewGraphNodes);
1282 #define DEBUG_TYPE "anders-aa"
1285 /// The technique used here is described in "Exploiting Pointer and Location
1286 /// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1287 /// Analysis Symposium (SAS), August 2007." It is known as the "HVN" algorithm,
1288 /// and is equivalent to value numbering the collapsed constraint graph without
1289 /// evaluating unions. This is used as a pre-pass to HU in order to resolve
1290 /// first order pointer dereferences and speed up/reduce memory usage of HU.
1291 /// Running both is equivalent to HRU without the iteration
1292 /// HVN in more detail:
1293 /// Imagine the set of constraints was simply straight line code with no loops
1294 /// (we eliminate cycles, so there are no loops), such as:
1300 /// Applying value numbering to this code tells us:
1303 /// For HVN, this is as far as it goes. We assign new value numbers to every
1304 /// "address node", and every "reference node".
1305 /// To get the optimal result for this, we use a DFS + SCC (since all nodes in a
1306 /// cycle must have the same value number since the = operation is really
1307 /// inclusion, not overwrite), and value number nodes we receive points-to sets
1308 /// before we value our own node.
1309 /// The advantage of HU over HVN is that HU considers the inclusion property, so
1310 /// that if you have
1317 /// HU will determine that G == F == E. HVN will not, because it cannot prove
1318 /// that the points to information ends up being the same because they all
1319 /// receive &D from E anyway.
1321 void Andersens::HVN() {
1322 DOUT << "Beginning HVN\n";
1323 // Build a predecessor graph. This is like our constraint graph with the
1324 // edges going in the opposite direction, and there are edges for all the
1325 // constraints, instead of just copy constraints. We also build implicit
1326 // edges for constraints are implied but not explicit. I.E for the constraint
1327 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1328 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1329 Constraint &C = Constraints[i];
1330 if (C.Type == Constraint::AddressOf) {
1331 GraphNodes[C.Src].AddressTaken = true;
1332 GraphNodes[C.Src].Direct = false;
1335 unsigned AdrNode = C.Src + FirstAdrNode;
1336 if (!GraphNodes[C.Dest].PredEdges)
1337 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1338 GraphNodes[C.Dest].PredEdges->set(AdrNode);
1341 unsigned RefNode = C.Dest + FirstRefNode;
1342 if (!GraphNodes[RefNode].ImplicitPredEdges)
1343 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1344 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1345 } else if (C.Type == Constraint::Load) {
1346 if (C.Offset == 0) {
1348 if (!GraphNodes[C.Dest].PredEdges)
1349 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1350 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1352 GraphNodes[C.Dest].Direct = false;
1354 } else if (C.Type == Constraint::Store) {
1355 if (C.Offset == 0) {
1357 unsigned RefNode = C.Dest + FirstRefNode;
1358 if (!GraphNodes[RefNode].PredEdges)
1359 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1360 GraphNodes[RefNode].PredEdges->set(C.Src);
1363 // Dest = Src edge and *Dest = *Src edge
1364 if (!GraphNodes[C.Dest].PredEdges)
1365 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1366 GraphNodes[C.Dest].PredEdges->set(C.Src);
1367 unsigned RefNode = C.Dest + FirstRefNode;
1368 if (!GraphNodes[RefNode].ImplicitPredEdges)
1369 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1370 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1374 // Do SCC finding first to condense our predecessor graph
1376 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1377 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1378 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1380 for (unsigned i = 0; i < FirstRefNode; ++i) {
1381 unsigned Node = VSSCCRep[i];
1382 if (!Node2Visited[Node])
1385 for (BitVectorMap::iterator Iter = Set2PEClass.begin();
1386 Iter != Set2PEClass.end();
1389 Set2PEClass.clear();
1391 Node2Deleted.clear();
1392 Node2Visited.clear();
1393 DOUT << "Finished HVN\n";
1397 /// This is the workhorse of HVN value numbering. We combine SCC finding at the
1398 /// same time because it's easy.
1399 void Andersens::HVNValNum(unsigned NodeIndex) {
1400 unsigned MyDFS = DFSNumber++;
1401 Node *N = &GraphNodes[NodeIndex];
1402 Node2Visited[NodeIndex] = true;
1403 Node2DFS[NodeIndex] = MyDFS;
1405 // First process all our explicit edges
1407 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1408 Iter != N->PredEdges->end();
1410 unsigned j = VSSCCRep[*Iter];
1411 if (!Node2Deleted[j]) {
1412 if (!Node2Visited[j])
1414 if (Node2DFS[NodeIndex] > Node2DFS[j])
1415 Node2DFS[NodeIndex] = Node2DFS[j];
1419 // Now process all the implicit edges
1420 if (N->ImplicitPredEdges)
1421 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1422 Iter != N->ImplicitPredEdges->end();
1424 unsigned j = VSSCCRep[*Iter];
1425 if (!Node2Deleted[j]) {
1426 if (!Node2Visited[j])
1428 if (Node2DFS[NodeIndex] > Node2DFS[j])
1429 Node2DFS[NodeIndex] = Node2DFS[j];
1433 // See if we found any cycles
1434 if (MyDFS == Node2DFS[NodeIndex]) {
1435 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1436 unsigned CycleNodeIndex = SCCStack.top();
1437 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1438 VSSCCRep[CycleNodeIndex] = NodeIndex;
1440 N->Direct &= CycleNode->Direct;
1442 if (CycleNode->PredEdges) {
1444 N->PredEdges = new SparseBitVector<>;
1445 *(N->PredEdges) |= CycleNode->PredEdges;
1446 delete CycleNode->PredEdges;
1447 CycleNode->PredEdges = NULL;
1449 if (CycleNode->ImplicitPredEdges) {
1450 if (!N->ImplicitPredEdges)
1451 N->ImplicitPredEdges = new SparseBitVector<>;
1452 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1453 delete CycleNode->ImplicitPredEdges;
1454 CycleNode->ImplicitPredEdges = NULL;
1460 Node2Deleted[NodeIndex] = true;
1463 GraphNodes[NodeIndex].PointerEquivLabel = PEClass++;
1467 // Collect labels of successor nodes
1468 bool AllSame = true;
1469 unsigned First = ~0;
1470 SparseBitVector<> *Labels = new SparseBitVector<>;
1474 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1475 Iter != N->PredEdges->end();
1477 unsigned j = VSSCCRep[*Iter];
1478 unsigned Label = GraphNodes[j].PointerEquivLabel;
1479 // Ignore labels that are equal to us or non-pointers
1480 if (j == NodeIndex || Label == 0)
1482 if (First == (unsigned)~0)
1484 else if (First != Label)
1489 // We either have a non-pointer, a copy of an existing node, or a new node.
1490 // Assign the appropriate pointer equivalence label.
1491 if (Labels->empty()) {
1492 GraphNodes[NodeIndex].PointerEquivLabel = 0;
1493 } else if (AllSame) {
1494 GraphNodes[NodeIndex].PointerEquivLabel = First;
1496 GraphNodes[NodeIndex].PointerEquivLabel = Set2PEClass[Labels];
1497 if (GraphNodes[NodeIndex].PointerEquivLabel == 0) {
1498 unsigned EquivClass = PEClass++;
1499 Set2PEClass[Labels] = EquivClass;
1500 GraphNodes[NodeIndex].PointerEquivLabel = EquivClass;
1507 SCCStack.push(NodeIndex);
1511 /// The technique used here is described in "Exploiting Pointer and Location
1512 /// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1513 /// Analysis Symposium (SAS), August 2007." It is known as the "HU" algorithm,
1514 /// and is equivalent to value numbering the collapsed constraint graph
1515 /// including evaluating unions.
1516 void Andersens::HU() {
1517 DOUT << "Beginning HU\n";
1518 // Build a predecessor graph. This is like our constraint graph with the
1519 // edges going in the opposite direction, and there are edges for all the
1520 // constraints, instead of just copy constraints. We also build implicit
1521 // edges for constraints are implied but not explicit. I.E for the constraint
1522 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1523 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1524 Constraint &C = Constraints[i];
1525 if (C.Type == Constraint::AddressOf) {
1526 GraphNodes[C.Src].AddressTaken = true;
1527 GraphNodes[C.Src].Direct = false;
1529 GraphNodes[C.Dest].PointsTo->set(C.Src);
1531 unsigned RefNode = C.Dest + FirstRefNode;
1532 if (!GraphNodes[RefNode].ImplicitPredEdges)
1533 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1534 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1535 GraphNodes[C.Src].PointedToBy->set(C.Dest);
1536 } else if (C.Type == Constraint::Load) {
1537 if (C.Offset == 0) {
1539 if (!GraphNodes[C.Dest].PredEdges)
1540 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1541 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1543 GraphNodes[C.Dest].Direct = false;
1545 } else if (C.Type == Constraint::Store) {
1546 if (C.Offset == 0) {
1548 unsigned RefNode = C.Dest + FirstRefNode;
1549 if (!GraphNodes[RefNode].PredEdges)
1550 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1551 GraphNodes[RefNode].PredEdges->set(C.Src);
1554 // Dest = Src edge and *Dest = *Src edg
1555 if (!GraphNodes[C.Dest].PredEdges)
1556 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1557 GraphNodes[C.Dest].PredEdges->set(C.Src);
1558 unsigned RefNode = C.Dest + FirstRefNode;
1559 if (!GraphNodes[RefNode].ImplicitPredEdges)
1560 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1561 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1565 // Do SCC finding first to condense our predecessor graph
1567 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1568 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1569 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1571 for (unsigned i = 0; i < FirstRefNode; ++i) {
1572 if (FindNode(i) == i) {
1573 unsigned Node = VSSCCRep[i];
1574 if (!Node2Visited[Node])
1579 // Reset tables for actual labeling
1581 Node2Visited.clear();
1582 Node2Deleted.clear();
1583 // Pre-grow our densemap so that we don't get really bad behavior
1584 Set2PEClass.resize(GraphNodes.size());
1586 // Visit the condensed graph and generate pointer equivalence labels.
1587 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1588 for (unsigned i = 0; i < FirstRefNode; ++i) {
1589 if (FindNode(i) == i) {
1590 unsigned Node = VSSCCRep[i];
1591 if (!Node2Visited[Node])
1595 // PEClass nodes will be deleted by the deleting of N->PointsTo in our caller.
1596 Set2PEClass.clear();
1597 DOUT << "Finished HU\n";
1601 /// Implementation of standard Tarjan SCC algorithm as modified by Nuutilla.
1602 void Andersens::Condense(unsigned NodeIndex) {
1603 unsigned MyDFS = DFSNumber++;
1604 Node *N = &GraphNodes[NodeIndex];
1605 Node2Visited[NodeIndex] = true;
1606 Node2DFS[NodeIndex] = MyDFS;
1608 // First process all our explicit edges
1610 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1611 Iter != N->PredEdges->end();
1613 unsigned j = VSSCCRep[*Iter];
1614 if (!Node2Deleted[j]) {
1615 if (!Node2Visited[j])
1617 if (Node2DFS[NodeIndex] > Node2DFS[j])
1618 Node2DFS[NodeIndex] = Node2DFS[j];
1622 // Now process all the implicit edges
1623 if (N->ImplicitPredEdges)
1624 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1625 Iter != N->ImplicitPredEdges->end();
1627 unsigned j = VSSCCRep[*Iter];
1628 if (!Node2Deleted[j]) {
1629 if (!Node2Visited[j])
1631 if (Node2DFS[NodeIndex] > Node2DFS[j])
1632 Node2DFS[NodeIndex] = Node2DFS[j];
1636 // See if we found any cycles
1637 if (MyDFS == Node2DFS[NodeIndex]) {
1638 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1639 unsigned CycleNodeIndex = SCCStack.top();
1640 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1641 VSSCCRep[CycleNodeIndex] = NodeIndex;
1643 N->Direct &= CycleNode->Direct;
1645 *(N->PointsTo) |= CycleNode->PointsTo;
1646 delete CycleNode->PointsTo;
1647 CycleNode->PointsTo = NULL;
1648 if (CycleNode->PredEdges) {
1650 N->PredEdges = new SparseBitVector<>;
1651 *(N->PredEdges) |= CycleNode->PredEdges;
1652 delete CycleNode->PredEdges;
1653 CycleNode->PredEdges = NULL;
1655 if (CycleNode->ImplicitPredEdges) {
1656 if (!N->ImplicitPredEdges)
1657 N->ImplicitPredEdges = new SparseBitVector<>;
1658 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1659 delete CycleNode->ImplicitPredEdges;
1660 CycleNode->ImplicitPredEdges = NULL;
1665 Node2Deleted[NodeIndex] = true;
1667 // Set up number of incoming edges for other nodes
1669 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1670 Iter != N->PredEdges->end();
1672 ++GraphNodes[VSSCCRep[*Iter]].NumInEdges;
1674 SCCStack.push(NodeIndex);
1678 void Andersens::HUValNum(unsigned NodeIndex) {
1679 Node *N = &GraphNodes[NodeIndex];
1680 Node2Visited[NodeIndex] = true;
1682 // Eliminate dereferences of non-pointers for those non-pointers we have
1683 // already identified. These are ref nodes whose non-ref node:
1684 // 1. Has already been visited determined to point to nothing (and thus, a
1685 // dereference of it must point to nothing)
1686 // 2. Any direct node with no predecessor edges in our graph and with no
1687 // points-to set (since it can't point to anything either, being that it
1688 // receives no points-to sets and has none).
1689 if (NodeIndex >= FirstRefNode) {
1690 unsigned j = VSSCCRep[FindNode(NodeIndex - FirstRefNode)];
1691 if ((Node2Visited[j] && !GraphNodes[j].PointerEquivLabel)
1692 || (GraphNodes[j].Direct && !GraphNodes[j].PredEdges
1693 && GraphNodes[j].PointsTo->empty())){
1697 // Process all our explicit edges
1699 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1700 Iter != N->PredEdges->end();
1702 unsigned j = VSSCCRep[*Iter];
1703 if (!Node2Visited[j])
1706 // If this edge turned out to be the same as us, or got no pointer
1707 // equivalence label (and thus points to nothing) , just decrement our
1708 // incoming edges and continue.
1709 if (j == NodeIndex || GraphNodes[j].PointerEquivLabel == 0) {
1710 --GraphNodes[j].NumInEdges;
1714 *(N->PointsTo) |= GraphNodes[j].PointsTo;
1716 // If we didn't end up storing this in the hash, and we're done with all
1717 // the edges, we don't need the points-to set anymore.
1718 --GraphNodes[j].NumInEdges;
1719 if (!GraphNodes[j].NumInEdges && !GraphNodes[j].StoredInHash) {
1720 delete GraphNodes[j].PointsTo;
1721 GraphNodes[j].PointsTo = NULL;
1724 // If this isn't a direct node, generate a fresh variable.
1726 N->PointsTo->set(FirstRefNode + NodeIndex);
1729 // See If we have something equivalent to us, if not, generate a new
1730 // equivalence class.
1731 if (N->PointsTo->empty()) {
1736 N->PointerEquivLabel = Set2PEClass[N->PointsTo];
1737 if (N->PointerEquivLabel == 0) {
1738 unsigned EquivClass = PEClass++;
1739 N->StoredInHash = true;
1740 Set2PEClass[N->PointsTo] = EquivClass;
1741 N->PointerEquivLabel = EquivClass;
1744 N->PointerEquivLabel = PEClass++;
1749 /// Rewrite our list of constraints so that pointer equivalent nodes are
1750 /// replaced by their the pointer equivalence class representative.
1751 void Andersens::RewriteConstraints() {
1752 std::vector<Constraint> NewConstraints;
1753 std::set<Constraint> Seen;
1755 PEClass2Node.clear();
1756 PENLEClass2Node.clear();
1758 // We may have from 1 to Graphnodes + 1 equivalence classes.
1759 PEClass2Node.insert(PEClass2Node.begin(), GraphNodes.size() + 1, -1);
1760 PENLEClass2Node.insert(PENLEClass2Node.begin(), GraphNodes.size() + 1, -1);
1762 // Rewrite constraints, ignoring non-pointer constraints, uniting equivalent
1763 // nodes, and rewriting constraints to use the representative nodes.
1764 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1765 Constraint &C = Constraints[i];
1766 unsigned RHSNode = FindNode(C.Src);
1767 unsigned LHSNode = FindNode(C.Dest);
1768 unsigned RHSLabel = GraphNodes[VSSCCRep[RHSNode]].PointerEquivLabel;
1769 unsigned LHSLabel = GraphNodes[VSSCCRep[LHSNode]].PointerEquivLabel;
1771 // First we try to eliminate constraints for things we can prove don't point
1773 if (LHSLabel == 0) {
1774 DEBUG(PrintNode(&GraphNodes[LHSNode]));
1775 DOUT << " is a non-pointer, ignoring constraint.\n";
1778 if (RHSLabel == 0) {
1779 DEBUG(PrintNode(&GraphNodes[RHSNode]));
1780 DOUT << " is a non-pointer, ignoring constraint.\n";
1783 // This constraint may be useless, and it may become useless as we translate
1785 if (C.Src == C.Dest && C.Type == Constraint::Copy)
1788 C.Src = FindEquivalentNode(RHSNode, RHSLabel);
1789 C.Dest = FindEquivalentNode(FindNode(LHSNode), LHSLabel);
1790 if (C.Src == C.Dest && C.Type == Constraint::Copy
1791 || Seen.count(C) != 0)
1795 NewConstraints.push_back(C);
1797 Constraints.swap(NewConstraints);
1798 PEClass2Node.clear();
1801 /// See if we have a node that is pointer equivalent to the one being asked
1802 /// about, and if so, unite them and return the equivalent node. Otherwise,
1803 /// return the original node.
1804 unsigned Andersens::FindEquivalentNode(unsigned NodeIndex,
1805 unsigned NodeLabel) {
1806 if (!GraphNodes[NodeIndex].AddressTaken) {
1807 if (PEClass2Node[NodeLabel] != -1) {
1808 // We found an existing node with the same pointer label, so unify them.
1809 return UniteNodes(PEClass2Node[NodeLabel], NodeIndex);
1811 PEClass2Node[NodeLabel] = NodeIndex;
1812 PENLEClass2Node[NodeLabel] = NodeIndex;
1814 } else if (PENLEClass2Node[NodeLabel] == -1) {
1815 PENLEClass2Node[NodeLabel] = NodeIndex;
1821 void Andersens::PrintLabels() {
1822 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1823 if (i < FirstRefNode) {
1824 PrintNode(&GraphNodes[i]);
1825 } else if (i < FirstAdrNode) {
1827 PrintNode(&GraphNodes[i-FirstRefNode]);
1831 PrintNode(&GraphNodes[i-FirstAdrNode]);
1835 DOUT << " has pointer label " << GraphNodes[i].PointerEquivLabel
1836 << " and SCC rep " << VSSCCRep[i]
1837 << " and is " << (GraphNodes[i].Direct ? "Direct" : "Not direct")
1842 /// Optimize the constraints by performing offline variable substitution and
1843 /// other optimizations.
1844 void Andersens::OptimizeConstraints() {
1845 DOUT << "Beginning constraint optimization\n";
1847 // Function related nodes need to stay in the same relative position and can't
1848 // be location equivalent.
1849 for (std::map<unsigned, unsigned>::iterator Iter = MaxK.begin();
1852 for (unsigned i = Iter->first;
1853 i != Iter->first + Iter->second;
1855 GraphNodes[i].AddressTaken = true;
1856 GraphNodes[i].Direct = false;
1860 ClumpAddressTaken();
1861 FirstRefNode = GraphNodes.size();
1862 FirstAdrNode = FirstRefNode + GraphNodes.size();
1863 GraphNodes.insert(GraphNodes.end(), 2 * GraphNodes.size(),
1865 VSSCCRep.resize(GraphNodes.size());
1866 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1870 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1871 Node *N = &GraphNodes[i];
1872 delete N->PredEdges;
1873 N->PredEdges = NULL;
1874 delete N->ImplicitPredEdges;
1875 N->ImplicitPredEdges = NULL;
1878 #define DEBUG_TYPE "anders-aa-labels"
1879 DEBUG(PrintLabels());
1881 #define DEBUG_TYPE "anders-aa"
1882 RewriteConstraints();
1883 // Delete the adr nodes.
1884 GraphNodes.resize(FirstRefNode * 2);
1887 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1888 Node *N = &GraphNodes[i];
1889 if (FindNode(i) == i) {
1890 N->PointsTo = new SparseBitVector<>;
1891 N->PointedToBy = new SparseBitVector<>;
1895 N->PointerEquivLabel = 0;
1899 #define DEBUG_TYPE "anders-aa-labels"
1900 DEBUG(PrintLabels());
1902 #define DEBUG_TYPE "anders-aa"
1903 RewriteConstraints();
1904 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1905 if (FindNode(i) == i) {
1906 Node *N = &GraphNodes[i];
1908 delete N->PredEdges;
1909 delete N->ImplicitPredEdges;
1910 delete N->PointedToBy;
1913 GraphNodes.erase(GraphNodes.begin() + FirstRefNode, GraphNodes.end());
1914 DOUT << "Finished constraint optimization\n";
1919 /// Unite pointer but not location equivalent variables, now that the constraint
1921 void Andersens::UnitePointerEquivalences() {
1922 DOUT << "Uniting remaining pointer equivalences\n";
1923 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1924 if (GraphNodes[i].AddressTaken && GraphNodes[i].NodeRep == SelfRep) {
1925 unsigned Label = GraphNodes[i].PointerEquivLabel;
1927 if (Label && PENLEClass2Node[Label] != -1)
1928 UniteNodes(i, PENLEClass2Node[Label]);
1931 DOUT << "Finished remaining pointer equivalences\n";
1932 PENLEClass2Node.clear();
1935 /// Create the constraint graph used for solving points-to analysis.
1937 void Andersens::CreateConstraintGraph() {
1938 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1939 Constraint &C = Constraints[i];
1940 assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
1941 if (C.Type == Constraint::AddressOf)
1942 GraphNodes[C.Dest].PointsTo->set(C.Src);
1943 else if (C.Type == Constraint::Load)
1944 GraphNodes[C.Src].Constraints.push_back(C);
1945 else if (C.Type == Constraint::Store)
1946 GraphNodes[C.Dest].Constraints.push_back(C);
1947 else if (C.Offset != 0)
1948 GraphNodes[C.Src].Constraints.push_back(C);
1950 GraphNodes[C.Src].Edges->set(C.Dest);
1954 // Perform cycle detection, DFS, and RPO finding.
1955 void Andersens::QueryNode(unsigned Node) {
1956 assert(GraphNodes[Node].NodeRep == SelfRep && "Querying a non-rep node");
1957 unsigned OurDFS = ++DFSNumber;
1958 SparseBitVector<> ToErase;
1959 SparseBitVector<> NewEdges;
1960 Node2DFS[Node] = OurDFS;
1962 for (SparseBitVector<>::iterator bi = GraphNodes[Node].Edges->begin();
1963 bi != GraphNodes[Node].Edges->end();
1965 unsigned RepNode = FindNode(*bi);
1966 // If we are going to add an edge to repnode, we have no need for the edge
1968 if (RepNode != *bi && NewEdges.test(RepNode)){
1973 // Continue about our DFS.
1974 if (!Node2Deleted[RepNode]){
1975 if (Node2DFS[RepNode] == 0) {
1977 // May have been changed by query
1978 RepNode = FindNode(RepNode);
1980 if (Node2DFS[RepNode] < Node2DFS[Node])
1981 Node2DFS[Node] = Node2DFS[RepNode];
1983 // We may have just discovered that e belongs to a cycle, in which case we
1984 // can also erase it.
1985 if (RepNode != *bi) {
1987 NewEdges.set(RepNode);
1991 GraphNodes[Node].Edges->intersectWithComplement(ToErase);
1992 GraphNodes[Node].Edges |= NewEdges;
1994 // If this node is a root of a non-trivial SCC, place it on our worklist to be
1996 if (OurDFS == Node2DFS[Node]) {
1997 bool Changed = false;
1998 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= OurDFS) {
1999 Node = UniteNodes(Node, FindNode(SCCStack.top()));
2004 Node2Deleted[Node] = true;
2007 Topo2Node.at(GraphNodes.size() - RPONumber) = Node;
2008 Node2Topo[Node] = GraphNodes.size() - RPONumber;
2010 GraphNodes[Node].Changed = true;
2012 SCCStack.push(Node);
2017 /// SolveConstraints - This stage iteratively processes the constraints list
2018 /// propagating constraints (adding edges to the Nodes in the points-to graph)
2019 /// until a fixed point is reached.
2021 void Andersens::SolveConstraints() {
2022 bool Changed = true;
2023 unsigned Iteration = 0;
2025 OptimizeConstraints();
2027 #define DEBUG_TYPE "anders-aa-constraints"
2028 DEBUG(PrintConstraints());
2030 #define DEBUG_TYPE "anders-aa"
2032 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2033 Node *N = &GraphNodes[i];
2034 N->PointsTo = new SparseBitVector<>;
2035 N->OldPointsTo = new SparseBitVector<>;
2036 N->Edges = new SparseBitVector<>;
2038 CreateConstraintGraph();
2039 UnitePointerEquivalences();
2040 assert(SCCStack.empty() && "SCC Stack should be empty by now!");
2041 Topo2Node.insert(Topo2Node.begin(), GraphNodes.size(), Unvisited);
2042 Node2Topo.insert(Node2Topo.begin(), GraphNodes.size(), Unvisited);
2044 Node2Deleted.clear();
2045 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2046 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2049 // Order graph and mark starting nodes as changed.
2050 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2051 unsigned N = FindNode(i);
2052 Node *INode = &GraphNodes[i];
2053 if (Node2DFS[N] == 0) {
2055 // Mark as changed if it's a representation and can contribute to the
2056 // calculation right now.
2057 if (INode->NodeRep == SelfRep && !INode->PointsTo->empty()
2058 && (!INode->Edges->empty() || !INode->Constraints.empty()))
2059 INode->Changed = true;
2066 DOUT << "Starting iteration #" << Iteration++ << "\n";
2067 // TODO: In the microoptimization category, we could just make Topo2Node
2068 // a fast map and thus only contain the visited nodes.
2069 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2070 unsigned CurrNodeIndex = Topo2Node[i];
2073 // We may not revisit all nodes on every iteration
2074 if (CurrNodeIndex == Unvisited)
2076 CurrNode = &GraphNodes[CurrNodeIndex];
2077 // See if this is a node we need to process on this iteration
2078 if (!CurrNode->Changed || CurrNode->NodeRep != SelfRep)
2080 CurrNode->Changed = false;
2082 // Figure out the changed points to bits
2083 SparseBitVector<> CurrPointsTo;
2084 CurrPointsTo.intersectWithComplement(CurrNode->PointsTo,
2085 CurrNode->OldPointsTo);
2086 if (CurrPointsTo.empty()){
2089 *(CurrNode->OldPointsTo) |= CurrPointsTo;
2091 /* Now process the constraints for this node. */
2092 for (std::list<Constraint>::iterator li = CurrNode->Constraints.begin();
2093 li != CurrNode->Constraints.end(); ) {
2094 li->Src = FindNode(li->Src);
2095 li->Dest = FindNode(li->Dest);
2097 // TODO: We could delete redundant constraints here.
2098 // Src and Dest will be the vars we are going to process.
2099 // This may look a bit ugly, but what it does is allow us to process
2100 // both store and load constraints with the same code.
2101 // Load constraints say that every member of our RHS solution has K
2102 // added to it, and that variable gets an edge to LHS. We also union
2103 // RHS+K's solution into the LHS solution.
2104 // Store constraints say that every member of our LHS solution has K
2105 // added to it, and that variable gets an edge from RHS. We also union
2106 // RHS's solution into the LHS+K solution.
2109 unsigned K = li->Offset;
2110 unsigned CurrMember;
2111 if (li->Type == Constraint::Load) {
2114 } else if (li->Type == Constraint::Store) {
2118 // TODO Handle offseted copy constraint
2122 // TODO: hybrid cycle detection would go here, we should check
2123 // if it was a statically detected offline equivalence that
2124 // involves pointers , and if so, remove the redundant constraints.
2126 const SparseBitVector<> &Solution = CurrPointsTo;
2128 for (SparseBitVector<>::iterator bi = Solution.begin();
2129 bi != Solution.end();
2133 // Need to increment the member by K since that is where we are
2134 // supposed to copy to/from. Note that in positive weight cycles,
2135 // which occur in address taking of fields, K can go past
2136 // MaxK[CurrMember] elements, even though that is all it could point
2138 if (K > 0 && K > MaxK[CurrMember])
2141 CurrMember = FindNode(CurrMember + K);
2143 // Add an edge to the graph, so we can just do regular bitmap ior next
2144 // time. It may also let us notice a cycle.
2145 if (GraphNodes[*Src].Edges->test_and_set(*Dest)) {
2146 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo)) {
2147 GraphNodes[*Dest].Changed = true;
2148 // If we changed a node we've already processed, we need another
2150 if (Node2Topo[*Dest] <= i)
2157 SparseBitVector<> NewEdges;
2158 SparseBitVector<> ToErase;
2160 // Now all we have left to do is propagate points-to info along the
2161 // edges, erasing the redundant edges.
2164 for (SparseBitVector<>::iterator bi = CurrNode->Edges->begin();
2165 bi != CurrNode->Edges->end();
2168 unsigned DestVar = *bi;
2169 unsigned Rep = FindNode(DestVar);
2171 // If we ended up with this node as our destination, or we've already
2172 // got an edge for the representative, delete the current edge.
2173 if (Rep == CurrNodeIndex ||
2174 (Rep != DestVar && NewEdges.test(Rep))) {
2175 ToErase.set(DestVar);
2178 // Union the points-to sets into the dest
2179 if (GraphNodes[Rep].PointsTo |= CurrPointsTo) {
2180 GraphNodes[Rep].Changed = true;
2181 if (Node2Topo[Rep] <= i)
2184 // If this edge's destination was collapsed, rewrite the edge.
2185 if (Rep != DestVar) {
2186 ToErase.set(DestVar);
2190 CurrNode->Edges->intersectWithComplement(ToErase);
2191 CurrNode->Edges |= NewEdges;
2194 DFSNumber = RPONumber = 0;
2195 Node2Deleted.clear();
2199 Topo2Node.insert(Topo2Node.begin(), GraphNodes.size(), Unvisited);
2200 Node2Topo.insert(Node2Topo.begin(), GraphNodes.size(), Unvisited);
2201 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2202 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2203 // Rediscover the DFS/Topo ordering, and cycle detect.
2204 for (unsigned j = 0; j < GraphNodes.size(); j++) {
2205 unsigned JRep = FindNode(j);
2206 if (Node2DFS[JRep] == 0)
2216 Node2Deleted.clear();
2217 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2218 Node *N = &GraphNodes[i];
2219 delete N->OldPointsTo;
2224 //===----------------------------------------------------------------------===//
2226 //===----------------------------------------------------------------------===//
2228 // Unite nodes First and Second, returning the one which is now the
2229 // representative node. First and Second are indexes into GraphNodes
2230 unsigned Andersens::UniteNodes(unsigned First, unsigned Second) {
2231 assert (First < GraphNodes.size() && Second < GraphNodes.size() &&
2232 "Attempting to merge nodes that don't exist");
2233 // TODO: implement union by rank
2234 Node *FirstNode = &GraphNodes[First];
2235 Node *SecondNode = &GraphNodes[Second];
2237 assert (SecondNode->NodeRep == SelfRep && FirstNode->NodeRep == SelfRep &&
2238 "Trying to unite two non-representative nodes!");
2239 if (First == Second)
2242 SecondNode->NodeRep = First;
2243 FirstNode->Changed |= SecondNode->Changed;
2244 if (FirstNode->PointsTo && SecondNode->PointsTo)
2245 FirstNode->PointsTo |= *(SecondNode->PointsTo);
2246 if (FirstNode->Edges && SecondNode->Edges)
2247 FirstNode->Edges |= *(SecondNode->Edges);
2248 if (!FirstNode->Constraints.empty() && !SecondNode->Constraints.empty())
2249 FirstNode->Constraints.splice(FirstNode->Constraints.begin(),
2250 SecondNode->Constraints);
2251 if (FirstNode->OldPointsTo) {
2252 delete FirstNode->OldPointsTo;
2253 FirstNode->OldPointsTo = new SparseBitVector<>;
2256 // Destroy interesting parts of the merged-from node.
2257 delete SecondNode->OldPointsTo;
2258 delete SecondNode->Edges;
2259 delete SecondNode->PointsTo;
2260 SecondNode->Edges = NULL;
2261 SecondNode->PointsTo = NULL;
2262 SecondNode->OldPointsTo = NULL;
2265 DOUT << "Unified Node ";
2266 DEBUG(PrintNode(FirstNode));
2267 DOUT << " and Node ";
2268 DEBUG(PrintNode(SecondNode));
2275 // Find the index into GraphNodes of the node representing Node, performing
2276 // path compression along the way
2277 unsigned Andersens::FindNode(unsigned NodeIndex) {
2278 assert (NodeIndex < GraphNodes.size()
2279 && "Attempting to find a node that can't exist");
2280 Node *N = &GraphNodes[NodeIndex];
2281 if (N->NodeRep == SelfRep)
2284 return (N->NodeRep = FindNode(N->NodeRep));
2287 //===----------------------------------------------------------------------===//
2289 //===----------------------------------------------------------------------===//
2291 void Andersens::PrintNode(Node *N) {
2292 if (N == &GraphNodes[UniversalSet]) {
2293 cerr << "<universal>";
2295 } else if (N == &GraphNodes[NullPtr]) {
2296 cerr << "<nullptr>";
2298 } else if (N == &GraphNodes[NullObject]) {
2302 if (!N->getValue()) {
2303 cerr << "artificial" << (intptr_t) N;
2307 assert(N->getValue() != 0 && "Never set node label!");
2308 Value *V = N->getValue();
2309 if (Function *F = dyn_cast<Function>(V)) {
2310 if (isa<PointerType>(F->getFunctionType()->getReturnType()) &&
2311 N == &GraphNodes[getReturnNode(F)]) {
2312 cerr << F->getName() << ":retval";
2314 } else if (F->getFunctionType()->isVarArg() &&
2315 N == &GraphNodes[getVarargNode(F)]) {
2316 cerr << F->getName() << ":vararg";
2321 if (Instruction *I = dyn_cast<Instruction>(V))
2322 cerr << I->getParent()->getParent()->getName() << ":";
2323 else if (Argument *Arg = dyn_cast<Argument>(V))
2324 cerr << Arg->getParent()->getName() << ":";
2327 cerr << V->getName();
2329 cerr << "(unnamed)";
2331 if (isa<GlobalValue>(V) || isa<AllocationInst>(V))
2332 if (N == &GraphNodes[getObject(V)])
2335 void Andersens::PrintConstraint(const Constraint &C) {
2336 if (C.Type == Constraint::Store) {
2341 PrintNode(&GraphNodes[C.Dest]);
2342 if (C.Type == Constraint::Store && C.Offset != 0)
2343 cerr << " + " << C.Offset << ")";
2345 if (C.Type == Constraint::Load) {
2350 else if (C.Type == Constraint::AddressOf)
2352 PrintNode(&GraphNodes[C.Src]);
2353 if (C.Offset != 0 && C.Type != Constraint::Store)
2354 cerr << " + " << C.Offset;
2355 if (C.Type == Constraint::Load && C.Offset != 0)
2360 void Andersens::PrintConstraints() {
2361 cerr << "Constraints:\n";
2363 for (unsigned i = 0, e = Constraints.size(); i != e; ++i)
2364 PrintConstraint(Constraints[i]);
2367 void Andersens::PrintPointsToGraph() {
2368 cerr << "Points-to graph:\n";
2369 for (unsigned i = 0, e = GraphNodes.size(); i != e; ++i) {
2370 Node *N = &GraphNodes[i];
2371 if (FindNode (i) != i) {
2373 cerr << "\t--> same as ";
2374 PrintNode(&GraphNodes[FindNode(i)]);
2377 cerr << "[" << (N->PointsTo->count()) << "] ";
2382 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
2383 bi != N->PointsTo->end();
2387 PrintNode(&GraphNodes[*bi]);