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. Inclusion constraint solving.
21 // The object identification stage identifies all of the memory objects in the
22 // program, which includes globals, heap allocated objects, and stack allocated
25 // The inclusion constraint identification stage finds all inclusion constraints
26 // in the program by scanning the program, looking for pointer assignments and
27 // other statements that effect the points-to graph. For a statement like "A =
28 // B", this statement is processed to indicate that A can point to anything that
29 // B can point to. Constraints can handle copies, loads, and stores, and
32 // The inclusion constraint solving phase iteratively propagates the inclusion
33 // constraints until a fixed point is reached. This is an O(N^3) algorithm.
35 // Function constraints are handled as if they were structs with X fields.
36 // Thus, an access to argument X of function Y is an access to node index
37 // getNode(Y) + X. This representation allows handling of indirect calls
38 // without any issues. To wit, an indirect call Y(a,b) is equivalence to
39 // *(Y + 1) = a, *(Y + 2) = b.
40 // The return node for a function is always located at getNode(F) +
41 // CallReturnPos. The arguments start at getNode(F) + CallArgPos.
43 // Future Improvements:
44 // Offline variable substitution, offline detection of online
45 // cycles. Use of BDD's.
46 //===----------------------------------------------------------------------===//
48 #define DEBUG_TYPE "anders-aa"
49 #include "llvm/Constants.h"
50 #include "llvm/DerivedTypes.h"
51 #include "llvm/Instructions.h"
52 #include "llvm/Module.h"
53 #include "llvm/Pass.h"
54 #include "llvm/Support/Compiler.h"
55 #include "llvm/Support/InstIterator.h"
56 #include "llvm/Support/InstVisitor.h"
57 #include "llvm/Analysis/AliasAnalysis.h"
58 #include "llvm/Analysis/Passes.h"
59 #include "llvm/Support/Debug.h"
60 #include "llvm/ADT/Statistic.h"
61 #include "llvm/ADT/SparseBitVector.h"
69 STATISTIC(NumIters , "Number of iterations to reach convergence");
70 STATISTIC(NumConstraints , "Number of constraints");
71 STATISTIC(NumNodes , "Number of nodes");
72 STATISTIC(NumUnified , "Number of variables unified");
75 const unsigned SelfRep = (unsigned)-1;
76 const unsigned Unvisited = (unsigned)-1;
77 // Position of the function return node relative to the function node.
78 const unsigned CallReturnPos = 2;
79 // Position of the function call node relative to the function node.
80 const unsigned CallFirstArgPos = 3;
82 class VISIBILITY_HIDDEN Andersens : public ModulePass, public AliasAnalysis,
83 private InstVisitor<Andersens> {
86 /// Constraint - Objects of this structure are used to represent the various
87 /// constraints identified by the algorithm. The constraints are 'copy',
88 /// for statements like "A = B", 'load' for statements like "A = *B",
89 /// 'store' for statements like "*A = B", and AddressOf for statements like
90 /// A = alloca; The Offset is applied as *(A + K) = B for stores,
91 /// A = *(B + K) for loads, and A = B + K for copies. It is
92 /// illegal on addressof constraints (Because it is statically
93 /// resolvable to A = &C where C = B + K)
96 enum ConstraintType { Copy, Load, Store, AddressOf } Type;
101 Constraint(ConstraintType Ty, unsigned D, unsigned S, unsigned O = 0)
102 : Type(Ty), Dest(D), Src(S), Offset(O) {
103 assert(Offset == 0 || Ty != AddressOf &&
104 "Offset is illegal on addressof constraints");
108 // Node class - This class is used to represent a node
109 // in the constraint graph. Due to various optimizations,
110 // not always the case that there is a mapping from a Node to a
111 // Value. In particular, we add artificial
112 // Node's that represent the set of pointed-to variables
113 // shared for each location equivalent Node.
116 SparseBitVector<> *Edges;
117 SparseBitVector<> *PointsTo;
118 SparseBitVector<> *OldPointsTo;
120 std::list<Constraint> Constraints;
122 // Nodes in cycles (or in equivalence classes) are united
123 // together using a standard union-find representation with path
124 // compression. NodeRep gives the index into GraphNodes
125 // representative for this one.
126 unsigned NodeRep; public:
128 Node() : Val(0), Edges(0), PointsTo(0), OldPointsTo(0), Changed(false),
132 Node *setValue(Value *V) {
133 assert(Val == 0 && "Value already set for this node!");
138 /// getValue - Return the LLVM value corresponding to this node.
140 Value *getValue() const { return Val; }
142 /// addPointerTo - Add a pointer to the list of pointees of this node,
143 /// returning true if this caused a new pointer to be added, or false if
144 /// we already knew about the points-to relation.
145 bool addPointerTo(unsigned Node) {
146 return PointsTo->test_and_set(Node);
149 /// intersects - Return true if the points-to set of this node intersects
150 /// with the points-to set of the specified node.
151 bool intersects(Node *N) const;
153 /// intersectsIgnoring - Return true if the points-to set of this node
154 /// intersects with the points-to set of the specified node on any nodes
155 /// except for the specified node to ignore.
156 bool intersectsIgnoring(Node *N, unsigned) const;
159 /// GraphNodes - This vector is populated as part of the object
160 /// identification stage of the analysis, which populates this vector with a
161 /// node for each memory object and fills in the ValueNodes map.
162 std::vector<Node> GraphNodes;
164 /// ValueNodes - This map indicates the Node that a particular Value* is
165 /// represented by. This contains entries for all pointers.
166 std::map<Value*, unsigned> ValueNodes;
168 /// ObjectNodes - This map contains entries for each memory object in the
169 /// program: globals, alloca's and mallocs.
170 std::map<Value*, unsigned> ObjectNodes;
172 /// ReturnNodes - This map contains an entry for each function in the
173 /// program that returns a value.
174 std::map<Function*, unsigned> ReturnNodes;
176 /// VarargNodes - This map contains the entry used to represent all pointers
177 /// passed through the varargs portion of a function call for a particular
178 /// function. An entry is not present in this map for functions that do not
179 /// take variable arguments.
180 std::map<Function*, unsigned> VarargNodes;
183 /// Constraints - This vector contains a list of all of the constraints
184 /// identified by the program.
185 std::vector<Constraint> Constraints;
187 // Map from graph node to maximum K value that is allowed (For functions,
188 // this is equivalent to the number of arguments + CallFirstArgPos)
189 std::map<unsigned, unsigned> MaxK;
191 /// This enum defines the GraphNodes indices that correspond to important
199 std::stack<unsigned> SCCStack;
200 // Topological Index -> Graph node
201 std::vector<unsigned> Topo2Node;
202 // Graph Node -> Topological Index;
203 std::vector<unsigned> Node2Topo;
204 // Map from Graph Node to DFS number
205 std::vector<unsigned> Node2DFS;
206 // Map from Graph Node to Deleted from graph.
207 std::vector<bool> Node2Deleted;
208 // Current DFS and RPO numbers
214 Andersens() : ModulePass((intptr_t)&ID) {}
216 bool runOnModule(Module &M) {
217 InitializeAliasAnalysis(this);
219 CollectConstraints(M);
220 DEBUG(PrintConstraints());
222 DEBUG(PrintPointsToGraph());
224 // Free the constraints list, as we don't need it to respond to alias
229 std::vector<Constraint>().swap(Constraints);
233 void releaseMemory() {
234 // FIXME: Until we have transitively required passes working correctly,
235 // this cannot be enabled! Otherwise, using -count-aa with the pass
236 // causes memory to be freed too early. :(
238 // The memory objects and ValueNodes data structures at the only ones that
239 // are still live after construction.
240 std::vector<Node>().swap(GraphNodes);
245 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
246 AliasAnalysis::getAnalysisUsage(AU);
247 AU.setPreservesAll(); // Does not transform code
250 //------------------------------------------------
251 // Implement the AliasAnalysis API
253 AliasResult alias(const Value *V1, unsigned V1Size,
254 const Value *V2, unsigned V2Size);
255 virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
256 virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
257 void getMustAliases(Value *P, std::vector<Value*> &RetVals);
258 bool pointsToConstantMemory(const Value *P);
260 virtual void deleteValue(Value *V) {
262 getAnalysis<AliasAnalysis>().deleteValue(V);
265 virtual void copyValue(Value *From, Value *To) {
266 ValueNodes[To] = ValueNodes[From];
267 getAnalysis<AliasAnalysis>().copyValue(From, To);
271 /// getNode - Return the node corresponding to the specified pointer scalar.
273 unsigned getNode(Value *V) {
274 if (Constant *C = dyn_cast<Constant>(V))
275 if (!isa<GlobalValue>(C))
276 return getNodeForConstantPointer(C);
278 std::map<Value*, unsigned>::iterator I = ValueNodes.find(V);
279 if (I == ValueNodes.end()) {
283 assert(0 && "Value does not have a node in the points-to graph!");
288 /// getObject - Return the node corresponding to the memory object for the
289 /// specified global or allocation instruction.
290 unsigned getObject(Value *V) {
291 std::map<Value*, unsigned>::iterator I = ObjectNodes.find(V);
292 assert(I != ObjectNodes.end() &&
293 "Value does not have an object in the points-to graph!");
297 /// getReturnNode - Return the node representing the return value for the
298 /// specified function.
299 unsigned getReturnNode(Function *F) {
300 std::map<Function*, unsigned>::iterator I = ReturnNodes.find(F);
301 assert(I != ReturnNodes.end() && "Function does not return a value!");
305 /// getVarargNode - Return the node representing the variable arguments
306 /// formal for the specified function.
307 unsigned getVarargNode(Function *F) {
308 std::map<Function*, unsigned>::iterator I = VarargNodes.find(F);
309 assert(I != VarargNodes.end() && "Function does not take var args!");
313 /// getNodeValue - Get the node for the specified LLVM value and set the
314 /// value for it to be the specified value.
315 unsigned getNodeValue(Value &V) {
316 unsigned Index = getNode(&V);
317 GraphNodes[Index].setValue(&V);
321 unsigned UniteNodes(unsigned First, unsigned Second);
322 unsigned FindNode(unsigned Node);
324 void IdentifyObjects(Module &M);
325 void CollectConstraints(Module &M);
326 bool AnalyzeUsesOfFunction(Value *);
327 void CreateConstraintGraph();
328 void SolveConstraints();
329 void QueryNode(unsigned Node);
331 unsigned getNodeForConstantPointer(Constant *C);
332 unsigned getNodeForConstantPointerTarget(Constant *C);
333 void AddGlobalInitializerConstraints(unsigned, Constant *C);
335 void AddConstraintsForNonInternalLinkage(Function *F);
336 void AddConstraintsForCall(CallSite CS, Function *F);
337 bool AddConstraintsForExternalCall(CallSite CS, Function *F);
340 void PrintNode(Node *N);
341 void PrintConstraints();
342 void PrintPointsToGraph();
344 //===------------------------------------------------------------------===//
345 // Instruction visitation methods for adding constraints
347 friend class InstVisitor<Andersens>;
348 void visitReturnInst(ReturnInst &RI);
349 void visitInvokeInst(InvokeInst &II) { visitCallSite(CallSite(&II)); }
350 void visitCallInst(CallInst &CI) { visitCallSite(CallSite(&CI)); }
351 void visitCallSite(CallSite CS);
352 void visitAllocationInst(AllocationInst &AI);
353 void visitLoadInst(LoadInst &LI);
354 void visitStoreInst(StoreInst &SI);
355 void visitGetElementPtrInst(GetElementPtrInst &GEP);
356 void visitPHINode(PHINode &PN);
357 void visitCastInst(CastInst &CI);
358 void visitICmpInst(ICmpInst &ICI) {} // NOOP!
359 void visitFCmpInst(FCmpInst &ICI) {} // NOOP!
360 void visitSelectInst(SelectInst &SI);
361 void visitVAArg(VAArgInst &I);
362 void visitInstruction(Instruction &I);
366 char Andersens::ID = 0;
367 RegisterPass<Andersens> X("anders-aa",
368 "Andersen's Interprocedural Alias Analysis");
369 RegisterAnalysisGroup<AliasAnalysis> Y(X);
372 ModulePass *llvm::createAndersensPass() { return new Andersens(); }
374 //===----------------------------------------------------------------------===//
375 // AliasAnalysis Interface Implementation
376 //===----------------------------------------------------------------------===//
378 AliasAnalysis::AliasResult Andersens::alias(const Value *V1, unsigned V1Size,
379 const Value *V2, unsigned V2Size) {
380 Node *N1 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V1)))];
381 Node *N2 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V2)))];
383 // Check to see if the two pointers are known to not alias. They don't alias
384 // if their points-to sets do not intersect.
385 if (!N1->intersectsIgnoring(N2, NullObject))
388 return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
391 AliasAnalysis::ModRefResult
392 Andersens::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
393 // The only thing useful that we can contribute for mod/ref information is
394 // when calling external function calls: if we know that memory never escapes
395 // from the program, it cannot be modified by an external call.
397 // NOTE: This is not really safe, at least not when the entire program is not
398 // available. The deal is that the external function could call back into the
399 // program and modify stuff. We ignore this technical niggle for now. This
400 // is, after all, a "research quality" implementation of Andersen's analysis.
401 if (Function *F = CS.getCalledFunction())
402 if (F->isDeclaration()) {
403 Node *N1 = &GraphNodes[FindNode(getNode(P))];
405 if (N1->PointsTo->empty())
408 if (!N1->PointsTo->test(UniversalSet))
409 return NoModRef; // P doesn't point to the universal set.
412 return AliasAnalysis::getModRefInfo(CS, P, Size);
415 AliasAnalysis::ModRefResult
416 Andersens::getModRefInfo(CallSite CS1, CallSite CS2) {
417 return AliasAnalysis::getModRefInfo(CS1,CS2);
420 /// getMustAlias - We can provide must alias information if we know that a
421 /// pointer can only point to a specific function or the null pointer.
422 /// Unfortunately we cannot determine must-alias information for global
423 /// variables or any other memory memory objects because we do not track whether
424 /// a pointer points to the beginning of an object or a field of it.
425 void Andersens::getMustAliases(Value *P, std::vector<Value*> &RetVals) {
426 Node *N = &GraphNodes[FindNode(getNode(P))];
427 if (N->PointsTo->count() == 1) {
428 Node *Pointee = &GraphNodes[N->PointsTo->find_first()];
429 // If a function is the only object in the points-to set, then it must be
430 // the destination. Note that we can't handle global variables here,
431 // because we don't know if the pointer is actually pointing to a field of
432 // the global or to the beginning of it.
433 if (Value *V = Pointee->getValue()) {
434 if (Function *F = dyn_cast<Function>(V))
435 RetVals.push_back(F);
437 // If the object in the points-to set is the null object, then the null
438 // pointer is a must alias.
439 if (Pointee == &GraphNodes[NullObject])
440 RetVals.push_back(Constant::getNullValue(P->getType()));
443 AliasAnalysis::getMustAliases(P, RetVals);
446 /// pointsToConstantMemory - If we can determine that this pointer only points
447 /// to constant memory, return true. In practice, this means that if the
448 /// pointer can only point to constant globals, functions, or the null pointer,
451 bool Andersens::pointsToConstantMemory(const Value *P) {
452 Node *N = &GraphNodes[FindNode(getNode((Value*)P))];
455 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
456 bi != N->PointsTo->end();
459 Node *Pointee = &GraphNodes[i];
460 if (Value *V = Pointee->getValue()) {
461 if (!isa<GlobalValue>(V) || (isa<GlobalVariable>(V) &&
462 !cast<GlobalVariable>(V)->isConstant()))
463 return AliasAnalysis::pointsToConstantMemory(P);
466 return AliasAnalysis::pointsToConstantMemory(P);
473 //===----------------------------------------------------------------------===//
474 // Object Identification Phase
475 //===----------------------------------------------------------------------===//
477 /// IdentifyObjects - This stage scans the program, adding an entry to the
478 /// GraphNodes list for each memory object in the program (global stack or
479 /// heap), and populates the ValueNodes and ObjectNodes maps for these objects.
481 void Andersens::IdentifyObjects(Module &M) {
482 unsigned NumObjects = 0;
484 // Object #0 is always the universal set: the object that we don't know
486 assert(NumObjects == UniversalSet && "Something changed!");
489 // Object #1 always represents the null pointer.
490 assert(NumObjects == NullPtr && "Something changed!");
493 // Object #2 always represents the null object (the object pointed to by null)
494 assert(NumObjects == NullObject && "Something changed!");
497 // Add all the globals first.
498 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
500 ObjectNodes[I] = NumObjects++;
501 ValueNodes[I] = NumObjects++;
504 // Add nodes for all of the functions and the instructions inside of them.
505 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
506 // The function itself is a memory object.
507 unsigned First = NumObjects;
508 ValueNodes[F] = NumObjects++;
509 ObjectNodes[F] = NumObjects++;
510 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
511 ReturnNodes[F] = NumObjects++;
512 if (F->getFunctionType()->isVarArg())
513 VarargNodes[F] = NumObjects++;
516 // Add nodes for all of the incoming pointer arguments.
517 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
519 if (isa<PointerType>(I->getType()))
520 ValueNodes[I] = NumObjects++;
521 MaxK[First] = NumObjects - First;
522 MaxK[First + 1] = NumObjects - First - 1;
524 // Scan the function body, creating a memory object for each heap/stack
525 // allocation in the body of the function and a node to represent all
526 // pointer values defined by instructions and used as operands.
527 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
528 // If this is an heap or stack allocation, create a node for the memory
530 if (isa<PointerType>(II->getType())) {
531 ValueNodes[&*II] = NumObjects++;
532 if (AllocationInst *AI = dyn_cast<AllocationInst>(&*II))
533 ObjectNodes[AI] = NumObjects++;
538 // Now that we know how many objects to create, make them all now!
539 GraphNodes.resize(NumObjects);
540 NumNodes += NumObjects;
543 //===----------------------------------------------------------------------===//
544 // Constraint Identification Phase
545 //===----------------------------------------------------------------------===//
547 /// getNodeForConstantPointer - Return the node corresponding to the constant
549 unsigned Andersens::getNodeForConstantPointer(Constant *C) {
550 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
552 if (isa<ConstantPointerNull>(C) || isa<UndefValue>(C))
554 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
556 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
557 switch (CE->getOpcode()) {
558 case Instruction::GetElementPtr:
559 return getNodeForConstantPointer(CE->getOperand(0));
560 case Instruction::IntToPtr:
562 case Instruction::BitCast:
563 return getNodeForConstantPointer(CE->getOperand(0));
565 cerr << "Constant Expr not yet handled: " << *CE << "\n";
569 assert(0 && "Unknown constant pointer!");
574 /// getNodeForConstantPointerTarget - Return the node POINTED TO by the
575 /// specified constant pointer.
576 unsigned Andersens::getNodeForConstantPointerTarget(Constant *C) {
577 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
579 if (isa<ConstantPointerNull>(C))
581 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
582 return getObject(GV);
583 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
584 switch (CE->getOpcode()) {
585 case Instruction::GetElementPtr:
586 return getNodeForConstantPointerTarget(CE->getOperand(0));
587 case Instruction::IntToPtr:
589 case Instruction::BitCast:
590 return getNodeForConstantPointerTarget(CE->getOperand(0));
592 cerr << "Constant Expr not yet handled: " << *CE << "\n";
596 assert(0 && "Unknown constant pointer!");
601 /// AddGlobalInitializerConstraints - Add inclusion constraints for the memory
602 /// object N, which contains values indicated by C.
603 void Andersens::AddGlobalInitializerConstraints(unsigned NodeIndex,
605 if (C->getType()->isFirstClassType()) {
606 if (isa<PointerType>(C->getType()))
607 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
608 getNodeForConstantPointer(C)));
609 } else if (C->isNullValue()) {
610 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
613 } else if (!isa<UndefValue>(C)) {
614 // If this is an array or struct, include constraints for each element.
615 assert(isa<ConstantArray>(C) || isa<ConstantStruct>(C));
616 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
617 AddGlobalInitializerConstraints(NodeIndex,
618 cast<Constant>(C->getOperand(i)));
622 /// AddConstraintsForNonInternalLinkage - If this function does not have
623 /// internal linkage, realize that we can't trust anything passed into or
624 /// returned by this function.
625 void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
626 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
627 if (isa<PointerType>(I->getType()))
628 // If this is an argument of an externally accessible function, the
629 // incoming pointer might point to anything.
630 Constraints.push_back(Constraint(Constraint::Copy, getNode(I),
634 /// AddConstraintsForCall - If this is a call to a "known" function, add the
635 /// constraints and return true. If this is a call to an unknown function,
637 bool Andersens::AddConstraintsForExternalCall(CallSite CS, Function *F) {
638 assert(F->isDeclaration() && "Not an external function!");
640 // These functions don't induce any points-to constraints.
641 if (F->getName() == "atoi" || F->getName() == "atof" ||
642 F->getName() == "atol" || F->getName() == "atoll" ||
643 F->getName() == "remove" || F->getName() == "unlink" ||
644 F->getName() == "rename" || F->getName() == "memcmp" ||
645 F->getName() == "llvm.memset.i32" ||
646 F->getName() == "llvm.memset.i64" ||
647 F->getName() == "strcmp" || F->getName() == "strncmp" ||
648 F->getName() == "execl" || F->getName() == "execlp" ||
649 F->getName() == "execle" || F->getName() == "execv" ||
650 F->getName() == "execvp" || F->getName() == "chmod" ||
651 F->getName() == "puts" || F->getName() == "write" ||
652 F->getName() == "open" || F->getName() == "create" ||
653 F->getName() == "truncate" || F->getName() == "chdir" ||
654 F->getName() == "mkdir" || F->getName() == "rmdir" ||
655 F->getName() == "read" || F->getName() == "pipe" ||
656 F->getName() == "wait" || F->getName() == "time" ||
657 F->getName() == "stat" || F->getName() == "fstat" ||
658 F->getName() == "lstat" || F->getName() == "strtod" ||
659 F->getName() == "strtof" || F->getName() == "strtold" ||
660 F->getName() == "fopen" || F->getName() == "fdopen" ||
661 F->getName() == "freopen" ||
662 F->getName() == "fflush" || F->getName() == "feof" ||
663 F->getName() == "fileno" || F->getName() == "clearerr" ||
664 F->getName() == "rewind" || F->getName() == "ftell" ||
665 F->getName() == "ferror" || F->getName() == "fgetc" ||
666 F->getName() == "fgetc" || F->getName() == "_IO_getc" ||
667 F->getName() == "fwrite" || F->getName() == "fread" ||
668 F->getName() == "fgets" || F->getName() == "ungetc" ||
669 F->getName() == "fputc" ||
670 F->getName() == "fputs" || F->getName() == "putc" ||
671 F->getName() == "ftell" || F->getName() == "rewind" ||
672 F->getName() == "_IO_putc" || F->getName() == "fseek" ||
673 F->getName() == "fgetpos" || F->getName() == "fsetpos" ||
674 F->getName() == "printf" || F->getName() == "fprintf" ||
675 F->getName() == "sprintf" || F->getName() == "vprintf" ||
676 F->getName() == "vfprintf" || F->getName() == "vsprintf" ||
677 F->getName() == "scanf" || F->getName() == "fscanf" ||
678 F->getName() == "sscanf" || F->getName() == "__assert_fail" ||
679 F->getName() == "modf")
683 // These functions do induce points-to edges.
684 if (F->getName() == "llvm.memcpy.i32" || F->getName() == "llvm.memcpy.i64" ||
685 F->getName() == "llvm.memmove.i32" ||F->getName() == "llvm.memmove.i64" ||
686 F->getName() == "memmove") {
688 // *Dest = *Src, which requires an artificial graph node to represent the
689 // constraint. It is broken up into *Dest = temp, temp = *Src
690 unsigned FirstArg = getNode(CS.getArgument(0));
691 unsigned SecondArg = getNode(CS.getArgument(1));
692 unsigned TempArg = GraphNodes.size();
693 GraphNodes.push_back(Node());
694 Constraints.push_back(Constraint(Constraint::Store,
696 Constraints.push_back(Constraint(Constraint::Load,
697 TempArg, SecondArg));
702 if (F->getName() == "realloc" || F->getName() == "strchr" ||
703 F->getName() == "strrchr" || F->getName() == "strstr" ||
704 F->getName() == "strtok") {
705 Constraints.push_back(Constraint(Constraint::Copy,
706 getNode(CS.getInstruction()),
707 getNode(CS.getArgument(0))));
716 /// AnalyzeUsesOfFunction - Look at all of the users of the specified function.
717 /// If this is used by anything complex (i.e., the address escapes), return
719 bool Andersens::AnalyzeUsesOfFunction(Value *V) {
721 if (!isa<PointerType>(V->getType())) return true;
723 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
724 if (dyn_cast<LoadInst>(*UI)) {
726 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
727 if (V == SI->getOperand(1)) {
729 } else if (SI->getOperand(1)) {
730 return true; // Storing the pointer
732 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
733 if (AnalyzeUsesOfFunction(GEP)) return true;
734 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
735 // Make sure that this is just the function being called, not that it is
736 // passing into the function.
737 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
738 if (CI->getOperand(i) == V) return true;
739 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
740 // Make sure that this is just the function being called, not that it is
741 // passing into the function.
742 for (unsigned i = 3, e = II->getNumOperands(); i != e; ++i)
743 if (II->getOperand(i) == V) return true;
744 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
745 if (CE->getOpcode() == Instruction::GetElementPtr ||
746 CE->getOpcode() == Instruction::BitCast) {
747 if (AnalyzeUsesOfFunction(CE))
752 } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(*UI)) {
753 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
754 return true; // Allow comparison against null.
755 } else if (dyn_cast<FreeInst>(*UI)) {
763 /// CollectConstraints - This stage scans the program, adding a constraint to
764 /// the Constraints list for each instruction in the program that induces a
765 /// constraint, and setting up the initial points-to graph.
767 void Andersens::CollectConstraints(Module &M) {
768 // First, the universal set points to itself.
769 Constraints.push_back(Constraint(Constraint::AddressOf, UniversalSet,
771 Constraints.push_back(Constraint(Constraint::Store, UniversalSet,
774 // Next, the null pointer points to the null object.
775 Constraints.push_back(Constraint(Constraint::AddressOf, NullPtr, NullObject));
777 // Next, add any constraints on global variables and their initializers.
778 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
780 // Associate the address of the global object as pointing to the memory for
781 // the global: &G = <G memory>
782 unsigned ObjectIndex = getObject(I);
783 Node *Object = &GraphNodes[ObjectIndex];
785 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(*I),
788 if (I->hasInitializer()) {
789 AddGlobalInitializerConstraints(ObjectIndex, I->getInitializer());
791 // If it doesn't have an initializer (i.e. it's defined in another
792 // translation unit), it points to the universal set.
793 Constraints.push_back(Constraint(Constraint::Copy, ObjectIndex,
798 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
799 // Make the function address point to the function object.
800 unsigned ObjectIndex = getObject(F);
801 GraphNodes[ObjectIndex].setValue(F);
802 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(*F),
804 // Set up the return value node.
805 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
806 GraphNodes[getReturnNode(F)].setValue(F);
807 if (F->getFunctionType()->isVarArg())
808 GraphNodes[getVarargNode(F)].setValue(F);
810 // Set up incoming argument nodes.
811 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
813 if (isa<PointerType>(I->getType()))
816 // At some point we should just add constraints for the escaping functions
817 // at solve time, but this slows down solving. For now, we simply mark
818 // address taken functions as escaping and treat them as external.
819 if (!F->hasInternalLinkage() || AnalyzeUsesOfFunction(F))
820 AddConstraintsForNonInternalLinkage(F);
822 if (!F->isDeclaration()) {
823 // Scan the function body, creating a memory object for each heap/stack
824 // allocation in the body of the function and a node to represent all
825 // pointer values defined by instructions and used as operands.
828 // External functions that return pointers return the universal set.
829 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
830 Constraints.push_back(Constraint(Constraint::Copy,
834 // Any pointers that are passed into the function have the universal set
836 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
838 if (isa<PointerType>(I->getType())) {
839 // Pointers passed into external functions could have anything stored
841 Constraints.push_back(Constraint(Constraint::Store, getNode(I),
843 // Memory objects passed into external function calls can have the
844 // universal set point to them.
845 Constraints.push_back(Constraint(Constraint::Copy,
850 // If this is an external varargs function, it can also store pointers
851 // into any pointers passed through the varargs section.
852 if (F->getFunctionType()->isVarArg())
853 Constraints.push_back(Constraint(Constraint::Store, getVarargNode(F),
857 NumConstraints += Constraints.size();
861 void Andersens::visitInstruction(Instruction &I) {
863 return; // This function is just a big assert.
865 if (isa<BinaryOperator>(I))
867 // Most instructions don't have any effect on pointer values.
868 switch (I.getOpcode()) {
869 case Instruction::Br:
870 case Instruction::Switch:
871 case Instruction::Unwind:
872 case Instruction::Unreachable:
873 case Instruction::Free:
874 case Instruction::ICmp:
875 case Instruction::FCmp:
878 // Is this something we aren't handling yet?
879 cerr << "Unknown instruction: " << I;
884 void Andersens::visitAllocationInst(AllocationInst &AI) {
885 unsigned ObjectIndex = getObject(&AI);
886 GraphNodes[ObjectIndex].setValue(&AI);
887 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(AI),
891 void Andersens::visitReturnInst(ReturnInst &RI) {
892 if (RI.getNumOperands() && isa<PointerType>(RI.getOperand(0)->getType()))
893 // return V --> <Copy/retval{F}/v>
894 Constraints.push_back(Constraint(Constraint::Copy,
895 getReturnNode(RI.getParent()->getParent()),
896 getNode(RI.getOperand(0))));
899 void Andersens::visitLoadInst(LoadInst &LI) {
900 if (isa<PointerType>(LI.getType()))
901 // P1 = load P2 --> <Load/P1/P2>
902 Constraints.push_back(Constraint(Constraint::Load, getNodeValue(LI),
903 getNode(LI.getOperand(0))));
906 void Andersens::visitStoreInst(StoreInst &SI) {
907 if (isa<PointerType>(SI.getOperand(0)->getType()))
908 // store P1, P2 --> <Store/P2/P1>
909 Constraints.push_back(Constraint(Constraint::Store,
910 getNode(SI.getOperand(1)),
911 getNode(SI.getOperand(0))));
914 void Andersens::visitGetElementPtrInst(GetElementPtrInst &GEP) {
915 // P1 = getelementptr P2, ... --> <Copy/P1/P2>
916 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(GEP),
917 getNode(GEP.getOperand(0))));
920 void Andersens::visitPHINode(PHINode &PN) {
921 if (isa<PointerType>(PN.getType())) {
922 unsigned PNN = getNodeValue(PN);
923 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
924 // P1 = phi P2, P3 --> <Copy/P1/P2>, <Copy/P1/P3>, ...
925 Constraints.push_back(Constraint(Constraint::Copy, PNN,
926 getNode(PN.getIncomingValue(i))));
930 void Andersens::visitCastInst(CastInst &CI) {
931 Value *Op = CI.getOperand(0);
932 if (isa<PointerType>(CI.getType())) {
933 if (isa<PointerType>(Op->getType())) {
934 // P1 = cast P2 --> <Copy/P1/P2>
935 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
936 getNode(CI.getOperand(0))));
938 // P1 = cast int --> <Copy/P1/Univ>
940 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
946 } else if (isa<PointerType>(Op->getType())) {
947 // int = cast P1 --> <Copy/Univ/P1>
949 Constraints.push_back(Constraint(Constraint::Copy,
951 getNode(CI.getOperand(0))));
953 getNode(CI.getOperand(0));
958 void Andersens::visitSelectInst(SelectInst &SI) {
959 if (isa<PointerType>(SI.getType())) {
960 unsigned SIN = getNodeValue(SI);
961 // P1 = select C, P2, P3 ---> <Copy/P1/P2>, <Copy/P1/P3>
962 Constraints.push_back(Constraint(Constraint::Copy, SIN,
963 getNode(SI.getOperand(1))));
964 Constraints.push_back(Constraint(Constraint::Copy, SIN,
965 getNode(SI.getOperand(2))));
969 void Andersens::visitVAArg(VAArgInst &I) {
970 assert(0 && "vaarg not handled yet!");
973 /// AddConstraintsForCall - Add constraints for a call with actual arguments
974 /// specified by CS to the function specified by F. Note that the types of
975 /// arguments might not match up in the case where this is an indirect call and
976 /// the function pointer has been casted. If this is the case, do something
978 void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
979 Value *CallValue = CS.getCalledValue();
980 bool IsDeref = F == NULL;
982 // If this is a call to an external function, try to handle it directly to get
983 // some taste of context sensitivity.
984 if (F && F->isDeclaration() && AddConstraintsForExternalCall(CS, F))
987 if (isa<PointerType>(CS.getType())) {
988 unsigned CSN = getNode(CS.getInstruction());
989 if (!F || isa<PointerType>(F->getFunctionType()->getReturnType())) {
991 Constraints.push_back(Constraint(Constraint::Load, CSN,
992 getNode(CallValue), CallReturnPos));
994 Constraints.push_back(Constraint(Constraint::Copy, CSN,
995 getNode(CallValue) + CallReturnPos));
997 // If the function returns a non-pointer value, handle this just like we
998 // treat a nonpointer cast to pointer.
999 Constraints.push_back(Constraint(Constraint::Copy, CSN,
1002 } else if (F && isa<PointerType>(F->getFunctionType()->getReturnType())) {
1003 Constraints.push_back(Constraint(Constraint::Copy,
1005 getNode(CallValue) + CallReturnPos));
1008 CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
1011 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1012 for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI)
1013 if (isa<PointerType>(AI->getType())) {
1014 if (isa<PointerType>((*ArgI)->getType())) {
1015 // Copy the actual argument into the formal argument.
1016 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1019 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1022 } else if (isa<PointerType>((*ArgI)->getType())) {
1023 Constraints.push_back(Constraint(Constraint::Copy,
1029 unsigned ArgPos = CallFirstArgPos;
1030 for (; ArgI != ArgE; ++ArgI) {
1031 if (isa<PointerType>((*ArgI)->getType())) {
1032 // Copy the actual argument into the formal argument.
1033 Constraints.push_back(Constraint(Constraint::Store,
1035 getNode(*ArgI), ArgPos++));
1037 Constraints.push_back(Constraint(Constraint::Store,
1038 getNode (CallValue),
1039 UniversalSet, ArgPos++));
1043 // Copy all pointers passed through the varargs section to the varargs node.
1044 if (F && F->getFunctionType()->isVarArg())
1045 for (; ArgI != ArgE; ++ArgI)
1046 if (isa<PointerType>((*ArgI)->getType()))
1047 Constraints.push_back(Constraint(Constraint::Copy, getVarargNode(F),
1049 // If more arguments are passed in than we track, just drop them on the floor.
1052 void Andersens::visitCallSite(CallSite CS) {
1053 if (isa<PointerType>(CS.getType()))
1054 getNodeValue(*CS.getInstruction());
1056 if (Function *F = CS.getCalledFunction()) {
1057 AddConstraintsForCall(CS, F);
1059 AddConstraintsForCall(CS, NULL);
1063 //===----------------------------------------------------------------------===//
1064 // Constraint Solving Phase
1065 //===----------------------------------------------------------------------===//
1067 /// intersects - Return true if the points-to set of this node intersects
1068 /// with the points-to set of the specified node.
1069 bool Andersens::Node::intersects(Node *N) const {
1070 return PointsTo->intersects(N->PointsTo);
1073 /// intersectsIgnoring - Return true if the points-to set of this node
1074 /// intersects with the points-to set of the specified node on any nodes
1075 /// except for the specified node to ignore.
1076 bool Andersens::Node::intersectsIgnoring(Node *N, unsigned Ignoring) const {
1077 // TODO: If we are only going to call this with the same value for Ignoring,
1078 // we should move the special values out of the points-to bitmap.
1079 bool WeHadIt = PointsTo->test(Ignoring);
1080 bool NHadIt = N->PointsTo->test(Ignoring);
1081 bool Result = false;
1083 PointsTo->reset(Ignoring);
1085 N->PointsTo->reset(Ignoring);
1086 Result = PointsTo->intersects(N->PointsTo);
1088 PointsTo->set(Ignoring);
1090 N->PointsTo->set(Ignoring);
1094 // Create the constraint graph used for solving points-to analysis.
1096 void Andersens::CreateConstraintGraph() {
1097 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1098 Constraint &C = Constraints[i];
1099 assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
1100 if (C.Type == Constraint::AddressOf)
1101 GraphNodes[C.Dest].PointsTo->set(C.Src);
1102 else if (C.Type == Constraint::Load)
1103 GraphNodes[C.Src].Constraints.push_back(C);
1104 else if (C.Type == Constraint::Store)
1105 GraphNodes[C.Dest].Constraints.push_back(C);
1106 else if (C.Offset != 0)
1107 GraphNodes[C.Src].Constraints.push_back(C);
1109 GraphNodes[C.Src].Edges->set(C.Dest);
1113 // Perform cycle detection, DFS, and RPO finding.
1114 void Andersens::QueryNode(unsigned Node) {
1115 assert(GraphNodes[Node].NodeRep == SelfRep && "Querying a non-rep node");
1116 unsigned OurDFS = ++DFSNumber;
1117 SparseBitVector<> ToErase;
1118 SparseBitVector<> NewEdges;
1119 Node2DFS[Node] = OurDFS;
1121 for (SparseBitVector<>::iterator bi = GraphNodes[Node].Edges->begin();
1122 bi != GraphNodes[Node].Edges->end();
1124 unsigned RepNode = FindNode(*bi);
1125 // If we are going to add an edge to repnode, we have no need for the edge
1127 if (RepNode != *bi && NewEdges.test(RepNode)){
1132 // Continue about our DFS.
1133 if (!Node2Deleted[RepNode]){
1134 if (Node2DFS[RepNode] == 0) {
1136 // May have been changed by query
1137 RepNode = FindNode(RepNode);
1139 if (Node2DFS[RepNode] < Node2DFS[Node])
1140 Node2DFS[Node] = Node2DFS[RepNode];
1142 // We may have just discovered that e belongs to a cycle, in which case we
1143 // can also erase it.
1144 if (RepNode != *bi) {
1146 NewEdges.set(RepNode);
1150 GraphNodes[Node].Edges->intersectWithComplement(ToErase);
1151 GraphNodes[Node].Edges |= NewEdges;
1153 // If this node is a root of a non-trivial SCC, place it on our worklist to be
1155 if (OurDFS == Node2DFS[Node]) {
1156 bool Changed = false;
1157 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= OurDFS) {
1158 Node = UniteNodes(Node, FindNode(SCCStack.top()));
1163 Node2Deleted[Node] = true;
1166 Topo2Node.at(GraphNodes.size() - RPONumber) = Node;
1167 Node2Topo[Node] = GraphNodes.size() - RPONumber;
1169 GraphNodes[Node].Changed = true;
1171 SCCStack.push(Node);
1176 /// SolveConstraints - This stage iteratively processes the constraints list
1177 /// propagating constraints (adding edges to the Nodes in the points-to graph)
1178 /// until a fixed point is reached.
1180 void Andersens::SolveConstraints() {
1181 bool Changed = true;
1182 unsigned Iteration = 0;
1184 // We create the bitmaps here to avoid getting jerked around by the compiler
1185 // creating objects behind our back and wasting lots of memory.
1186 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1187 Node *N = &GraphNodes[i];
1188 N->PointsTo = new SparseBitVector<>;
1189 N->OldPointsTo = new SparseBitVector<>;
1190 N->Edges = new SparseBitVector<>;
1192 CreateConstraintGraph();
1194 Topo2Node.insert(Topo2Node.begin(), GraphNodes.size(), Unvisited);
1195 Node2Topo.insert(Node2Topo.begin(), GraphNodes.size(), Unvisited);
1196 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1197 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1200 // Order graph and mark starting nodes as changed.
1201 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1202 unsigned N = FindNode(i);
1203 Node *INode = &GraphNodes[i];
1204 if (Node2DFS[N] == 0) {
1206 // Mark as changed if it's a representation and can contribute to the
1207 // calculation right now.
1208 if (INode->NodeRep == SelfRep && !INode->PointsTo->empty()
1209 && (!INode->Edges->empty() || !INode->Constraints.empty()))
1210 INode->Changed = true;
1218 DOUT << "Starting iteration #" << Iteration++ << "!\n";
1219 // TODO: In the microoptimization category, we could just make Topo2Node
1220 // a fast map and thus only contain the visited nodes.
1221 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1222 unsigned CurrNodeIndex = Topo2Node[i];
1225 // We may not revisit all nodes on every iteration
1226 if (CurrNodeIndex == Unvisited)
1228 CurrNode = &GraphNodes[CurrNodeIndex];
1229 // See if this is a node we need to process on this iteration
1230 if (!CurrNode->Changed || CurrNode->NodeRep != SelfRep)
1232 CurrNode->Changed = false;
1234 // Figure out the changed points to bits
1235 SparseBitVector<> CurrPointsTo;
1236 CurrPointsTo.intersectWithComplement(CurrNode->PointsTo,
1237 CurrNode->OldPointsTo);
1238 if (CurrPointsTo.empty()){
1241 *(CurrNode->OldPointsTo) |= CurrPointsTo;
1243 /* Now process the constraints for this node. */
1244 for (std::list<Constraint>::iterator li = CurrNode->Constraints.begin();
1245 li != CurrNode->Constraints.end(); ) {
1246 li->Src = FindNode(li->Src);
1247 li->Dest = FindNode(li->Dest);
1249 // TODO: We could delete redundant constraints here.
1250 // Src and Dest will be the vars we are going to process.
1251 // This may look a bit ugly, but what it does is allow us to process
1252 // both store and load constraints with the same function.
1253 // Load constraints say that every member of our RHS solution has K
1254 // added to it, and that variable gets an edge to LHS. We also union
1255 // RHS+K's solution into the LHS solution.
1256 // Store constraints say that every member of our LHS solution has K
1257 // added to it, and that variable gets an edge from RHS. We also union
1258 // RHS's solution into the LHS+K solution.
1261 unsigned K = li->Offset;
1262 unsigned CurrMember;
1263 if (li->Type == Constraint::Load) {
1266 } else if (li->Type == Constraint::Store) {
1270 // TODO Handle offseted copy constraint
1274 // TODO: hybrid cycle detection would go here, we should check
1275 // if it was a statically detected offline equivalence that
1276 // involves pointers , and if so, remove the redundant constraints.
1278 const SparseBitVector<> &Solution = CurrPointsTo;
1280 for (SparseBitVector<>::iterator bi = Solution.begin();
1281 bi != Solution.end();
1285 // Need to increment the member by K since that is where we are
1286 // supposed to copy to/from
1287 // Node that in positive weight cycles, which occur in address taking
1288 // of fields, K can go past
1289 // MaxK[CurrMember] elements, even though that is all it could
1291 if (K > 0 && K > MaxK[CurrMember])
1294 CurrMember = FindNode(CurrMember + K);
1296 // Add an edge to the graph, so we can just do regular bitmap ior next
1297 // time. It may also let us notice a cycle.
1298 if (!GraphNodes[*Src].Edges->test_and_set(*Dest)) {
1299 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo)) {
1300 GraphNodes[*Dest].Changed = true;
1301 // If we changed a node we've already processed, we need another
1303 if (Node2Topo[*Dest] <= i)
1310 SparseBitVector<> NewEdges;
1311 SparseBitVector<> ToErase;
1313 // Now all we have left to do is propagate points-to info along the
1314 // edges, erasing the redundant edges.
1317 for (SparseBitVector<>::iterator bi = CurrNode->Edges->begin();
1318 bi != CurrNode->Edges->end();
1321 unsigned DestVar = *bi;
1322 unsigned Rep = FindNode(DestVar);
1324 // If we ended up with this node as our destination, or we've already
1325 // got an edge for the representative, delete the current edge.
1326 if (Rep == CurrNodeIndex ||
1327 (Rep != DestVar && NewEdges.test(Rep))) {
1328 ToErase.set(DestVar);
1331 // Union the points-to sets into the dest
1332 if (GraphNodes[Rep].PointsTo |= CurrPointsTo) {
1333 GraphNodes[Rep].Changed = true;
1334 if (Node2Topo[Rep] <= i)
1337 // If this edge's destination was collapsed, rewrite the edge.
1338 if (Rep != DestVar) {
1339 ToErase.set(DestVar);
1343 CurrNode->Edges->intersectWithComplement(ToErase);
1344 CurrNode->Edges |= NewEdges;
1347 DFSNumber = RPONumber = 0;
1348 Node2Deleted.clear();
1352 Topo2Node.insert(Topo2Node.begin(), GraphNodes.size(), Unvisited);
1353 Node2Topo.insert(Node2Topo.begin(), GraphNodes.size(), Unvisited);
1354 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1355 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1356 // Rediscover the DFS/Topo ordering, and cycle detect.
1357 for (unsigned j = 0; j < GraphNodes.size(); j++) {
1358 unsigned JRep = FindNode(j);
1359 if (Node2DFS[JRep] == 0)
1369 Node2Deleted.clear();
1370 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1371 Node *N = &GraphNodes[i];
1372 delete N->OldPointsTo;
1377 //===----------------------------------------------------------------------===//
1379 //===----------------------------------------------------------------------===//
1381 // Unite nodes First and Second, returning the one which is now the
1382 // representative node. First and Second are indexes into GraphNodes
1383 unsigned Andersens::UniteNodes(unsigned First, unsigned Second) {
1384 assert (First < GraphNodes.size() && Second < GraphNodes.size() &&
1385 "Attempting to merge nodes that don't exist");
1386 // TODO: implement union by rank
1387 Node *FirstNode = &GraphNodes[First];
1388 Node *SecondNode = &GraphNodes[Second];
1390 assert (SecondNode->NodeRep == SelfRep && FirstNode->NodeRep == SelfRep &&
1391 "Trying to unite two non-representative nodes!");
1392 if (First == Second)
1395 SecondNode->NodeRep = First;
1396 FirstNode->Changed |= SecondNode->Changed;
1397 FirstNode->PointsTo |= *(SecondNode->PointsTo);
1398 FirstNode->Edges |= *(SecondNode->Edges);
1399 FirstNode->Constraints.splice(FirstNode->Constraints.begin(),
1400 SecondNode->Constraints);
1401 delete FirstNode->OldPointsTo;
1402 FirstNode->OldPointsTo = new SparseBitVector<>;
1404 // Destroy interesting parts of the merged-from node.
1405 delete SecondNode->OldPointsTo;
1406 delete SecondNode->Edges;
1407 delete SecondNode->PointsTo;
1408 SecondNode->Edges = NULL;
1409 SecondNode->PointsTo = NULL;
1410 SecondNode->OldPointsTo = NULL;
1413 DOUT << "Unified Node ";
1414 DEBUG(PrintNode(FirstNode));
1415 DOUT << " and Node ";
1416 DEBUG(PrintNode(SecondNode));
1423 // Find the index into GraphNodes of the node representing Node, performing
1424 // path compression along the way
1425 unsigned Andersens::FindNode(unsigned NodeIndex) {
1426 assert (NodeIndex < GraphNodes.size()
1427 && "Attempting to find a node that can't exist");
1428 Node *N = &GraphNodes[NodeIndex];
1429 if (N->NodeRep == SelfRep)
1432 return (N->NodeRep = FindNode(N->NodeRep));
1435 //===----------------------------------------------------------------------===//
1437 //===----------------------------------------------------------------------===//
1439 void Andersens::PrintNode(Node *N) {
1440 if (N == &GraphNodes[UniversalSet]) {
1441 cerr << "<universal>";
1443 } else if (N == &GraphNodes[NullPtr]) {
1444 cerr << "<nullptr>";
1446 } else if (N == &GraphNodes[NullObject]) {
1450 if (!N->getValue()) {
1451 cerr << "artificial" << (intptr_t) N;
1455 assert(N->getValue() != 0 && "Never set node label!");
1456 Value *V = N->getValue();
1457 if (Function *F = dyn_cast<Function>(V)) {
1458 if (isa<PointerType>(F->getFunctionType()->getReturnType()) &&
1459 N == &GraphNodes[getReturnNode(F)]) {
1460 cerr << F->getName() << ":retval";
1462 } else if (F->getFunctionType()->isVarArg() &&
1463 N == &GraphNodes[getVarargNode(F)]) {
1464 cerr << F->getName() << ":vararg";
1469 if (Instruction *I = dyn_cast<Instruction>(V))
1470 cerr << I->getParent()->getParent()->getName() << ":";
1471 else if (Argument *Arg = dyn_cast<Argument>(V))
1472 cerr << Arg->getParent()->getName() << ":";
1475 cerr << V->getName();
1477 cerr << "(unnamed)";
1479 if (isa<GlobalValue>(V) || isa<AllocationInst>(V))
1480 if (N == &GraphNodes[getObject(V)])
1484 void Andersens::PrintConstraints() {
1485 cerr << "Constraints:\n";
1487 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1488 const Constraint &C = Constraints[i];
1489 if (C.Type == Constraint::Store) {
1494 PrintNode(&GraphNodes[C.Dest]);
1495 if (C.Type == Constraint::Store && C.Offset != 0)
1496 cerr << " + " << C.Offset << ")";
1498 if (C.Type == Constraint::Load) {
1503 else if (C.Type == Constraint::AddressOf)
1505 PrintNode(&GraphNodes[C.Src]);
1506 if (C.Offset != 0 && C.Type != Constraint::Store)
1507 cerr << " + " << C.Offset;
1508 if (C.Type == Constraint::Load && C.Offset != 0)
1514 void Andersens::PrintPointsToGraph() {
1515 cerr << "Points-to graph:\n";
1516 for (unsigned i = 0, e = GraphNodes.size(); i != e; ++i) {
1517 Node *N = &GraphNodes[i];
1518 if (FindNode (i) != i) {
1520 cerr << "\t--> same as ";
1521 PrintNode(&GraphNodes[FindNode(i)]);
1524 cerr << "[" << (N->PointsTo->count()) << "] ";
1529 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
1530 bi != N->PointsTo->end();
1534 PrintNode(&GraphNodes[*bi]);