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 a very simple implementation of Andersen's interprocedural
11 // alias analysis. This implementation does not include any of the fancy
12 // features that make Andersen's reasonably efficient (like cycle elimination or
13 // variable substitution), but it should be useful for getting precision
14 // numbers and can be extended in the future.
16 // In pointer analysis terms, this is a subset-based, flow-insensitive,
17 // field-insensitive, and context-insensitive algorithm pointer algorithm.
19 // This algorithm is implemented as three stages:
20 // 1. Object identification.
21 // 2. Inclusion constraint identification.
22 // 3. Inclusion constraint solving.
24 // The object identification stage identifies all of the memory objects in the
25 // program, which includes globals, heap allocated objects, and stack allocated
28 // The inclusion constraint identification stage finds all inclusion constraints
29 // in the program by scanning the program, looking for pointer assignments and
30 // other statements that effect the points-to graph. For a statement like "A =
31 // B", this statement is processed to indicate that A can point to anything that
32 // B can point to. Constraints can handle copies, loads, and stores.
34 // The inclusion constraint solving phase iteratively propagates the inclusion
35 // constraints until a fixed point is reached. This is an O(N^3) algorithm.
37 // In the initial pass, all indirect function calls are completely ignored. As
38 // the analysis discovers new targets of function pointers, it iteratively
39 // resolves a precise (and conservative) call graph. Also related, this
40 // analysis initially assumes that all internal functions have known incoming
41 // pointers. If we find that an internal function's address escapes outside of
42 // the program, we update this assumption.
44 // Future Improvements:
45 // This implementation of Andersen's algorithm is extremely slow. To make it
46 // scale reasonably well, the inclusion constraints could be sorted (easy),
47 // offline variable substitution would be a huge win (straight-forward), and
48 // online cycle elimination (trickier) might help as well.
50 //===----------------------------------------------------------------------===//
52 #define DEBUG_TYPE "anders-aa"
53 #include "llvm/Constants.h"
54 #include "llvm/DerivedTypes.h"
55 #include "llvm/Instructions.h"
56 #include "llvm/Module.h"
57 #include "llvm/Pass.h"
58 #include "llvm/Support/InstIterator.h"
59 #include "llvm/Support/InstVisitor.h"
60 #include "llvm/Analysis/AliasAnalysis.h"
61 #include "llvm/Analysis/Passes.h"
62 #include "llvm/Support/Debug.h"
63 #include "llvm/ADT/Statistic.h"
69 NumIters("anders-aa", "Number of iterations to reach convergence");
71 NumConstraints("anders-aa", "Number of constraints");
73 NumNodes("anders-aa", "Number of nodes");
75 NumEscapingFunctions("anders-aa", "Number of internal functions that escape");
77 NumIndirectCallees("anders-aa", "Number of indirect callees found");
79 class Andersens : public ModulePass, public AliasAnalysis,
80 private InstVisitor<Andersens> {
81 /// Node class - This class is used to represent a memory object in the
82 /// program, and is the primitive used to build the points-to graph.
84 std::vector<Node*> Pointees;
88 Node *setValue(Value *V) {
89 assert(Val == 0 && "Value already set for this node!");
94 /// getValue - Return the LLVM value corresponding to this node.
96 Value *getValue() const { return Val; }
98 typedef std::vector<Node*>::const_iterator iterator;
99 iterator begin() const { return Pointees.begin(); }
100 iterator end() const { return Pointees.end(); }
102 /// addPointerTo - Add a pointer to the list of pointees of this node,
103 /// returning true if this caused a new pointer to be added, or false if
104 /// we already knew about the points-to relation.
105 bool addPointerTo(Node *N) {
106 std::vector<Node*>::iterator I = std::lower_bound(Pointees.begin(),
109 if (I != Pointees.end() && *I == N)
111 Pointees.insert(I, N);
115 /// intersects - Return true if the points-to set of this node intersects
116 /// with the points-to set of the specified node.
117 bool intersects(Node *N) const;
119 /// intersectsIgnoring - Return true if the points-to set of this node
120 /// intersects with the points-to set of the specified node on any nodes
121 /// except for the specified node to ignore.
122 bool intersectsIgnoring(Node *N, Node *Ignoring) const;
124 // Constraint application methods.
125 bool copyFrom(Node *N);
126 bool loadFrom(Node *N);
127 bool storeThrough(Node *N);
130 /// GraphNodes - This vector is populated as part of the object
131 /// identification stage of the analysis, which populates this vector with a
132 /// node for each memory object and fills in the ValueNodes map.
133 std::vector<Node> GraphNodes;
135 /// ValueNodes - This map indicates the Node that a particular Value* is
136 /// represented by. This contains entries for all pointers.
137 std::map<Value*, unsigned> ValueNodes;
139 /// ObjectNodes - This map contains entries for each memory object in the
140 /// program: globals, alloca's and mallocs.
141 std::map<Value*, unsigned> ObjectNodes;
143 /// ReturnNodes - This map contains an entry for each function in the
144 /// program that returns a value.
145 std::map<Function*, unsigned> ReturnNodes;
147 /// VarargNodes - This map contains the entry used to represent all pointers
148 /// passed through the varargs portion of a function call for a particular
149 /// function. An entry is not present in this map for functions that do not
150 /// take variable arguments.
151 std::map<Function*, unsigned> VarargNodes;
153 /// Constraint - Objects of this structure are used to represent the various
154 /// constraints identified by the algorithm. The constraints are 'copy',
155 /// for statements like "A = B", 'load' for statements like "A = *B", and
156 /// 'store' for statements like "*A = B".
158 enum ConstraintType { Copy, Load, Store } Type;
161 Constraint(ConstraintType Ty, Node *D, Node *S)
162 : Type(Ty), Dest(D), Src(S) {}
165 /// Constraints - This vector contains a list of all of the constraints
166 /// identified by the program.
167 std::vector<Constraint> Constraints;
169 /// EscapingInternalFunctions - This set contains all of the internal
170 /// functions that are found to escape from the program. If the address of
171 /// an internal function is passed to an external function or otherwise
172 /// escapes from the analyzed portion of the program, we must assume that
173 /// any pointer arguments can alias the universal node. This set keeps
174 /// track of those functions we are assuming to escape so far.
175 std::set<Function*> EscapingInternalFunctions;
177 /// IndirectCalls - This contains a list of all of the indirect call sites
178 /// in the program. Since the call graph is iteratively discovered, we may
179 /// need to add constraints to our graph as we find new targets of function
181 std::vector<CallSite> IndirectCalls;
183 /// IndirectCallees - For each call site in the indirect calls list, keep
184 /// track of the callees that we have discovered so far. As the analysis
185 /// proceeds, more callees are discovered, until the call graph finally
187 std::map<CallSite, std::vector<Function*> > IndirectCallees;
189 /// This enum defines the GraphNodes indices that correspond to important
198 bool runOnModule(Module &M) {
199 InitializeAliasAnalysis(this);
201 CollectConstraints(M);
202 DEBUG(PrintConstraints());
204 DEBUG(PrintPointsToGraph());
206 // Free the constraints list, as we don't need it to respond to alias
211 EscapingInternalFunctions.clear();
212 std::vector<Constraint>().swap(Constraints);
216 void releaseMemory() {
217 // FIXME: Until we have transitively required passes working correctly,
218 // this cannot be enabled! Otherwise, using -count-aa with the pass
219 // causes memory to be freed too early. :(
221 // The memory objects and ValueNodes data structures at the only ones that
222 // are still live after construction.
223 std::vector<Node>().swap(GraphNodes);
228 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
229 AliasAnalysis::getAnalysisUsage(AU);
230 AU.setPreservesAll(); // Does not transform code
233 //------------------------------------------------
234 // Implement the AliasAnalysis API
236 AliasResult alias(const Value *V1, unsigned V1Size,
237 const Value *V2, unsigned V2Size);
238 ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
239 void getMustAliases(Value *P, std::vector<Value*> &RetVals);
240 bool pointsToConstantMemory(const Value *P);
242 virtual void deleteValue(Value *V) {
244 getAnalysis<AliasAnalysis>().deleteValue(V);
247 virtual void copyValue(Value *From, Value *To) {
248 ValueNodes[To] = ValueNodes[From];
249 getAnalysis<AliasAnalysis>().copyValue(From, To);
253 /// getNode - Return the node corresponding to the specified pointer scalar.
255 Node *getNode(Value *V) {
256 if (Constant *C = dyn_cast<Constant>(V))
257 if (!isa<GlobalValue>(C))
258 return getNodeForConstantPointer(C);
260 std::map<Value*, unsigned>::iterator I = ValueNodes.find(V);
261 if (I == ValueNodes.end()) {
263 assert(I != ValueNodes.end() &&
264 "Value does not have a node in the points-to graph!");
266 return &GraphNodes[I->second];
269 /// getObject - Return the node corresponding to the memory object for the
270 /// specified global or allocation instruction.
271 Node *getObject(Value *V) {
272 std::map<Value*, unsigned>::iterator I = ObjectNodes.find(V);
273 assert(I != ObjectNodes.end() &&
274 "Value does not have an object in the points-to graph!");
275 return &GraphNodes[I->second];
278 /// getReturnNode - Return the node representing the return value for the
279 /// specified function.
280 Node *getReturnNode(Function *F) {
281 std::map<Function*, unsigned>::iterator I = ReturnNodes.find(F);
282 assert(I != ReturnNodes.end() && "Function does not return a value!");
283 return &GraphNodes[I->second];
286 /// getVarargNode - Return the node representing the variable arguments
287 /// formal for the specified function.
288 Node *getVarargNode(Function *F) {
289 std::map<Function*, unsigned>::iterator I = VarargNodes.find(F);
290 assert(I != VarargNodes.end() && "Function does not take var args!");
291 return &GraphNodes[I->second];
294 /// getNodeValue - Get the node for the specified LLVM value and set the
295 /// value for it to be the specified value.
296 Node *getNodeValue(Value &V) {
297 return getNode(&V)->setValue(&V);
300 void IdentifyObjects(Module &M);
301 void CollectConstraints(Module &M);
302 void SolveConstraints();
304 Node *getNodeForConstantPointer(Constant *C);
305 Node *getNodeForConstantPointerTarget(Constant *C);
306 void AddGlobalInitializerConstraints(Node *N, Constant *C);
308 void AddConstraintsForNonInternalLinkage(Function *F);
309 void AddConstraintsForCall(CallSite CS, Function *F);
310 bool AddConstraintsForExternalCall(CallSite CS, Function *F);
313 void PrintNode(Node *N);
314 void PrintConstraints();
315 void PrintPointsToGraph();
317 //===------------------------------------------------------------------===//
318 // Instruction visitation methods for adding constraints
320 friend class InstVisitor<Andersens>;
321 void visitReturnInst(ReturnInst &RI);
322 void visitInvokeInst(InvokeInst &II) { visitCallSite(CallSite(&II)); }
323 void visitCallInst(CallInst &CI) { visitCallSite(CallSite(&CI)); }
324 void visitCallSite(CallSite CS);
325 void visitAllocationInst(AllocationInst &AI);
326 void visitLoadInst(LoadInst &LI);
327 void visitStoreInst(StoreInst &SI);
328 void visitGetElementPtrInst(GetElementPtrInst &GEP);
329 void visitPHINode(PHINode &PN);
330 void visitCastInst(CastInst &CI);
331 void visitSelectInst(SelectInst &SI);
332 void visitVANext(VANextInst &I);
333 void visitVAArg(VAArgInst &I);
334 void visitInstruction(Instruction &I);
337 RegisterOpt<Andersens> X("anders-aa",
338 "Andersen's Interprocedural Alias Analysis");
339 RegisterAnalysisGroup<AliasAnalysis, Andersens> Y;
342 ModulePass *llvm::createAndersensPass() { return new Andersens(); }
344 //===----------------------------------------------------------------------===//
345 // AliasAnalysis Interface Implementation
346 //===----------------------------------------------------------------------===//
348 AliasAnalysis::AliasResult Andersens::alias(const Value *V1, unsigned V1Size,
349 const Value *V2, unsigned V2Size) {
350 Node *N1 = getNode(const_cast<Value*>(V1));
351 Node *N2 = getNode(const_cast<Value*>(V2));
353 // Check to see if the two pointers are known to not alias. They don't alias
354 // if their points-to sets do not intersect.
355 if (!N1->intersectsIgnoring(N2, &GraphNodes[NullObject]))
358 return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
361 AliasAnalysis::ModRefResult
362 Andersens::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
363 // The only thing useful that we can contribute for mod/ref information is
364 // when calling external function calls: if we know that memory never escapes
365 // from the program, it cannot be modified by an external call.
367 // NOTE: This is not really safe, at least not when the entire program is not
368 // available. The deal is that the external function could call back into the
369 // program and modify stuff. We ignore this technical niggle for now. This
370 // is, after all, a "research quality" implementation of Andersen's analysis.
371 if (Function *F = CS.getCalledFunction())
372 if (F->isExternal()) {
373 Node *N1 = getNode(P);
374 bool PointsToUniversalSet = false;
376 for (Node::iterator NI = N1->begin(), E = N1->end(); NI != E; ++NI) {
378 if (PN->begin() == PN->end())
379 continue; // P doesn't point to anything.
380 // Get the first pointee.
381 Node *FirstPointee = *PN->begin();
382 if (FirstPointee == &GraphNodes[UniversalSet]) {
383 PointsToUniversalSet = true;
388 if (!PointsToUniversalSet)
389 return NoModRef; // P doesn't point to the universal set.
392 return AliasAnalysis::getModRefInfo(CS, P, Size);
395 /// getMustAlias - We can provide must alias information if we know that a
396 /// pointer can only point to a specific function or the null pointer.
397 /// Unfortunately we cannot determine must-alias information for global
398 /// variables or any other memory memory objects because we do not track whether
399 /// a pointer points to the beginning of an object or a field of it.
400 void Andersens::getMustAliases(Value *P, std::vector<Value*> &RetVals) {
401 Node *N = getNode(P);
402 Node::iterator I = N->begin();
404 // If there is exactly one element in the points-to set for the object...
407 Node *Pointee = *N->begin();
409 // If a function is the only object in the points-to set, then it must be
410 // the destination. Note that we can't handle global variables here,
411 // because we don't know if the pointer is actually pointing to a field of
412 // the global or to the beginning of it.
413 if (Value *V = Pointee->getValue()) {
414 if (Function *F = dyn_cast<Function>(V))
415 RetVals.push_back(F);
417 // If the object in the points-to set is the null object, then the null
418 // pointer is a must alias.
419 if (Pointee == &GraphNodes[NullObject])
420 RetVals.push_back(Constant::getNullValue(P->getType()));
425 AliasAnalysis::getMustAliases(P, RetVals);
428 /// pointsToConstantMemory - If we can determine that this pointer only points
429 /// to constant memory, return true. In practice, this means that if the
430 /// pointer can only point to constant globals, functions, or the null pointer,
433 bool Andersens::pointsToConstantMemory(const Value *P) {
434 Node *N = getNode((Value*)P);
435 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I) {
436 if (Value *V = (*I)->getValue()) {
437 if (!isa<GlobalValue>(V) || (isa<GlobalVariable>(V) &&
438 !cast<GlobalVariable>(V)->isConstant()))
439 return AliasAnalysis::pointsToConstantMemory(P);
441 if (*I != &GraphNodes[NullObject])
442 return AliasAnalysis::pointsToConstantMemory(P);
449 //===----------------------------------------------------------------------===//
450 // Object Identification Phase
451 //===----------------------------------------------------------------------===//
453 /// IdentifyObjects - This stage scans the program, adding an entry to the
454 /// GraphNodes list for each memory object in the program (global stack or
455 /// heap), and populates the ValueNodes and ObjectNodes maps for these objects.
457 void Andersens::IdentifyObjects(Module &M) {
458 unsigned NumObjects = 0;
460 // Object #0 is always the universal set: the object that we don't know
462 assert(NumObjects == UniversalSet && "Something changed!");
465 // Object #1 always represents the null pointer.
466 assert(NumObjects == NullPtr && "Something changed!");
469 // Object #2 always represents the null object (the object pointed to by null)
470 assert(NumObjects == NullObject && "Something changed!");
473 // Add all the globals first.
474 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
476 ObjectNodes[I] = NumObjects++;
477 ValueNodes[I] = NumObjects++;
480 // Add nodes for all of the functions and the instructions inside of them.
481 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
482 // The function itself is a memory object.
483 ValueNodes[F] = NumObjects++;
484 ObjectNodes[F] = NumObjects++;
485 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
486 ReturnNodes[F] = NumObjects++;
487 if (F->getFunctionType()->isVarArg())
488 VarargNodes[F] = NumObjects++;
490 // Add nodes for all of the incoming pointer arguments.
491 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
493 if (isa<PointerType>(I->getType()))
494 ValueNodes[I] = NumObjects++;
496 // Scan the function body, creating a memory object for each heap/stack
497 // allocation in the body of the function and a node to represent all
498 // pointer values defined by instructions and used as operands.
499 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
500 // If this is an heap or stack allocation, create a node for the memory
502 if (isa<PointerType>(II->getType())) {
503 ValueNodes[&*II] = NumObjects++;
504 if (AllocationInst *AI = dyn_cast<AllocationInst>(&*II))
505 ObjectNodes[AI] = NumObjects++;
510 // Now that we know how many objects to create, make them all now!
511 GraphNodes.resize(NumObjects);
512 NumNodes += NumObjects;
515 //===----------------------------------------------------------------------===//
516 // Constraint Identification Phase
517 //===----------------------------------------------------------------------===//
519 /// getNodeForConstantPointer - Return the node corresponding to the constant
521 Andersens::Node *Andersens::getNodeForConstantPointer(Constant *C) {
522 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
524 if (isa<ConstantPointerNull>(C) || isa<UndefValue>(C))
525 return &GraphNodes[NullPtr];
526 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
528 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
529 switch (CE->getOpcode()) {
530 case Instruction::GetElementPtr:
531 return getNodeForConstantPointer(CE->getOperand(0));
532 case Instruction::Cast:
533 if (isa<PointerType>(CE->getOperand(0)->getType()))
534 return getNodeForConstantPointer(CE->getOperand(0));
536 return &GraphNodes[UniversalSet];
538 std::cerr << "Constant Expr not yet handled: " << *CE << "\n";
542 assert(0 && "Unknown constant pointer!");
547 /// getNodeForConstantPointerTarget - Return the node POINTED TO by the
548 /// specified constant pointer.
549 Andersens::Node *Andersens::getNodeForConstantPointerTarget(Constant *C) {
550 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
552 if (isa<ConstantPointerNull>(C))
553 return &GraphNodes[NullObject];
554 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
555 return getObject(GV);
556 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
557 switch (CE->getOpcode()) {
558 case Instruction::GetElementPtr:
559 return getNodeForConstantPointerTarget(CE->getOperand(0));
560 case Instruction::Cast:
561 if (isa<PointerType>(CE->getOperand(0)->getType()))
562 return getNodeForConstantPointerTarget(CE->getOperand(0));
564 return &GraphNodes[UniversalSet];
566 std::cerr << "Constant Expr not yet handled: " << *CE << "\n";
570 assert(0 && "Unknown constant pointer!");
575 /// AddGlobalInitializerConstraints - Add inclusion constraints for the memory
576 /// object N, which contains values indicated by C.
577 void Andersens::AddGlobalInitializerConstraints(Node *N, Constant *C) {
578 if (C->getType()->isFirstClassType()) {
579 if (isa<PointerType>(C->getType()))
580 N->addPointerTo(getNodeForConstantPointer(C));
581 } else if (C->isNullValue()) {
582 N->addPointerTo(&GraphNodes[NullObject]);
584 } else if (!isa<UndefValue>(C)) {
585 // If this is an array or struct, include constraints for each element.
586 assert(isa<ConstantArray>(C) || isa<ConstantStruct>(C));
587 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
588 AddGlobalInitializerConstraints(N, cast<Constant>(C->getOperand(i)));
592 /// AddConstraintsForNonInternalLinkage - If this function does not have
593 /// internal linkage, realize that we can't trust anything passed into or
594 /// returned by this function.
595 void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
596 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
597 if (isa<PointerType>(I->getType()))
598 // If this is an argument of an externally accessible function, the
599 // incoming pointer might point to anything.
600 Constraints.push_back(Constraint(Constraint::Copy, getNode(I),
601 &GraphNodes[UniversalSet]));
604 /// AddConstraintsForCall - If this is a call to a "known" function, add the
605 /// constraints and return true. If this is a call to an unknown function,
607 bool Andersens::AddConstraintsForExternalCall(CallSite CS, Function *F) {
608 assert(F->isExternal() && "Not an external function!");
610 // These functions don't induce any points-to constraints.
611 if (F->getName() == "printf" || F->getName() == "fprintf" ||
612 F->getName() == "fgets" ||
613 F->getName() == "open" || F->getName() == "fopen" ||
614 F->getName() == "fclose" || F->getName() == "fflush" ||
615 F->getName() == "atoi" || F->getName() == "sscanf" ||
616 F->getName() == "llvm.memset" || F->getName() == "memcmp" ||
617 F->getName() == "read" || F->getName() == "write")
620 // These functions do induce points-to edges.
621 if (F->getName() == "llvm.memcpy" || F->getName() == "llvm.memmove") {
622 // Note: this is a poor approximation, this says Dest = Src, instead of
624 Constraints.push_back(Constraint(Constraint::Copy,
625 getNode(CS.getArgument(0)),
626 getNode(CS.getArgument(1))));
630 if (F->getName() == "realloc") {
632 Constraints.push_back(Constraint(Constraint::Copy,
633 getNode(CS.getInstruction()),
634 getNode(CS.getArgument(0))));
643 /// CollectConstraints - This stage scans the program, adding a constraint to
644 /// the Constraints list for each instruction in the program that induces a
645 /// constraint, and setting up the initial points-to graph.
647 void Andersens::CollectConstraints(Module &M) {
648 // First, the universal set points to itself.
649 GraphNodes[UniversalSet].addPointerTo(&GraphNodes[UniversalSet]);
650 Constraints.push_back(Constraint(Constraint::Load, &GraphNodes[UniversalSet],
651 &GraphNodes[UniversalSet]));
652 Constraints.push_back(Constraint(Constraint::Store, &GraphNodes[UniversalSet],
653 &GraphNodes[UniversalSet]));
655 // Next, the null pointer points to the null object.
656 GraphNodes[NullPtr].addPointerTo(&GraphNodes[NullObject]);
658 // Next, add any constraints on global variables and their initializers.
659 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
661 // Associate the address of the global object as pointing to the memory for
662 // the global: &G = <G memory>
663 Node *Object = getObject(I);
665 getNodeValue(*I)->addPointerTo(Object);
667 if (I->hasInitializer()) {
668 AddGlobalInitializerConstraints(Object, I->getInitializer());
670 // If it doesn't have an initializer (i.e. it's defined in another
671 // translation unit), it points to the universal set.
672 Constraints.push_back(Constraint(Constraint::Copy, Object,
673 &GraphNodes[UniversalSet]));
677 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
678 // Make the function address point to the function object.
679 getNodeValue(*F)->addPointerTo(getObject(F)->setValue(F));
681 // Set up the return value node.
682 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
683 getReturnNode(F)->setValue(F);
684 if (F->getFunctionType()->isVarArg())
685 getVarargNode(F)->setValue(F);
687 // Set up incoming argument nodes.
688 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
690 if (isa<PointerType>(I->getType()))
693 if (!F->hasInternalLinkage())
694 AddConstraintsForNonInternalLinkage(F);
696 if (!F->isExternal()) {
697 // Scan the function body, creating a memory object for each heap/stack
698 // allocation in the body of the function and a node to represent all
699 // pointer values defined by instructions and used as operands.
702 // External functions that return pointers return the universal set.
703 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
704 Constraints.push_back(Constraint(Constraint::Copy,
706 &GraphNodes[UniversalSet]));
708 // Any pointers that are passed into the function have the universal set
710 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
712 if (isa<PointerType>(I->getType())) {
713 // Pointers passed into external functions could have anything stored
715 Constraints.push_back(Constraint(Constraint::Store, getNode(I),
716 &GraphNodes[UniversalSet]));
717 // Memory objects passed into external function calls can have the
718 // universal set point to them.
719 Constraints.push_back(Constraint(Constraint::Copy,
720 &GraphNodes[UniversalSet],
724 // If this is an external varargs function, it can also store pointers
725 // into any pointers passed through the varargs section.
726 if (F->getFunctionType()->isVarArg())
727 Constraints.push_back(Constraint(Constraint::Store, getVarargNode(F),
728 &GraphNodes[UniversalSet]));
731 NumConstraints += Constraints.size();
735 void Andersens::visitInstruction(Instruction &I) {
737 return; // This function is just a big assert.
739 if (isa<BinaryOperator>(I))
741 // Most instructions don't have any effect on pointer values.
742 switch (I.getOpcode()) {
743 case Instruction::Br:
744 case Instruction::Switch:
745 case Instruction::Unwind:
746 case Instruction::Unreachable:
747 case Instruction::Free:
748 case Instruction::Shl:
749 case Instruction::Shr:
752 // Is this something we aren't handling yet?
753 std::cerr << "Unknown instruction: " << I;
758 void Andersens::visitAllocationInst(AllocationInst &AI) {
759 getNodeValue(AI)->addPointerTo(getObject(&AI)->setValue(&AI));
762 void Andersens::visitReturnInst(ReturnInst &RI) {
763 if (RI.getNumOperands() && isa<PointerType>(RI.getOperand(0)->getType()))
764 // return V --> <Copy/retval{F}/v>
765 Constraints.push_back(Constraint(Constraint::Copy,
766 getReturnNode(RI.getParent()->getParent()),
767 getNode(RI.getOperand(0))));
770 void Andersens::visitLoadInst(LoadInst &LI) {
771 if (isa<PointerType>(LI.getType()))
772 // P1 = load P2 --> <Load/P1/P2>
773 Constraints.push_back(Constraint(Constraint::Load, getNodeValue(LI),
774 getNode(LI.getOperand(0))));
777 void Andersens::visitStoreInst(StoreInst &SI) {
778 if (isa<PointerType>(SI.getOperand(0)->getType()))
779 // store P1, P2 --> <Store/P2/P1>
780 Constraints.push_back(Constraint(Constraint::Store,
781 getNode(SI.getOperand(1)),
782 getNode(SI.getOperand(0))));
785 void Andersens::visitGetElementPtrInst(GetElementPtrInst &GEP) {
786 // P1 = getelementptr P2, ... --> <Copy/P1/P2>
787 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(GEP),
788 getNode(GEP.getOperand(0))));
791 void Andersens::visitPHINode(PHINode &PN) {
792 if (isa<PointerType>(PN.getType())) {
793 Node *PNN = getNodeValue(PN);
794 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
795 // P1 = phi P2, P3 --> <Copy/P1/P2>, <Copy/P1/P3>, ...
796 Constraints.push_back(Constraint(Constraint::Copy, PNN,
797 getNode(PN.getIncomingValue(i))));
801 void Andersens::visitCastInst(CastInst &CI) {
802 Value *Op = CI.getOperand(0);
803 if (isa<PointerType>(CI.getType())) {
804 if (isa<PointerType>(Op->getType())) {
805 // P1 = cast P2 --> <Copy/P1/P2>
806 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
807 getNode(CI.getOperand(0))));
809 // P1 = cast int --> <Copy/P1/Univ>
810 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
811 &GraphNodes[UniversalSet]));
813 } else if (isa<PointerType>(Op->getType())) {
814 // int = cast P1 --> <Copy/Univ/P1>
815 Constraints.push_back(Constraint(Constraint::Copy,
816 &GraphNodes[UniversalSet],
817 getNode(CI.getOperand(0))));
821 void Andersens::visitSelectInst(SelectInst &SI) {
822 if (isa<PointerType>(SI.getType())) {
823 Node *SIN = getNodeValue(SI);
824 // P1 = select C, P2, P3 ---> <Copy/P1/P2>, <Copy/P1/P3>
825 Constraints.push_back(Constraint(Constraint::Copy, SIN,
826 getNode(SI.getOperand(1))));
827 Constraints.push_back(Constraint(Constraint::Copy, SIN,
828 getNode(SI.getOperand(2))));
832 void Andersens::visitVANext(VANextInst &I) {
834 assert(0 && "vanext not handled yet!");
836 void Andersens::visitVAArg(VAArgInst &I) {
837 assert(0 && "vaarg not handled yet!");
840 /// AddConstraintsForCall - Add constraints for a call with actual arguments
841 /// specified by CS to the function specified by F. Note that the types of
842 /// arguments might not match up in the case where this is an indirect call and
843 /// the function pointer has been casted. If this is the case, do something
845 void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
846 // If this is a call to an external function, handle it directly to get some
847 // taste of context sensitivity.
848 if (F->isExternal() && AddConstraintsForExternalCall(CS, F))
851 if (isa<PointerType>(CS.getType())) {
852 Node *CSN = getNode(CS.getInstruction());
853 if (isa<PointerType>(F->getFunctionType()->getReturnType())) {
854 Constraints.push_back(Constraint(Constraint::Copy, CSN,
857 // If the function returns a non-pointer value, handle this just like we
858 // treat a nonpointer cast to pointer.
859 Constraints.push_back(Constraint(Constraint::Copy, CSN,
860 &GraphNodes[UniversalSet]));
862 } else if (isa<PointerType>(F->getFunctionType()->getReturnType())) {
863 Constraints.push_back(Constraint(Constraint::Copy,
864 &GraphNodes[UniversalSet],
868 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
869 CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
870 for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI)
871 if (isa<PointerType>(AI->getType())) {
872 if (isa<PointerType>((*ArgI)->getType())) {
873 // Copy the actual argument into the formal argument.
874 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
877 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
878 &GraphNodes[UniversalSet]));
880 } else if (isa<PointerType>((*ArgI)->getType())) {
881 Constraints.push_back(Constraint(Constraint::Copy,
882 &GraphNodes[UniversalSet],
886 // Copy all pointers passed through the varargs section to the varargs node.
887 if (F->getFunctionType()->isVarArg())
888 for (; ArgI != ArgE; ++ArgI)
889 if (isa<PointerType>((*ArgI)->getType()))
890 Constraints.push_back(Constraint(Constraint::Copy, getVarargNode(F),
892 // If more arguments are passed in than we track, just drop them on the floor.
895 void Andersens::visitCallSite(CallSite CS) {
896 if (isa<PointerType>(CS.getType()))
897 getNodeValue(*CS.getInstruction());
899 if (Function *F = CS.getCalledFunction()) {
900 AddConstraintsForCall(CS, F);
902 // We don't handle indirect call sites yet. Keep track of them for when we
903 // discover the call graph incrementally.
904 IndirectCalls.push_back(CS);
908 //===----------------------------------------------------------------------===//
909 // Constraint Solving Phase
910 //===----------------------------------------------------------------------===//
912 /// intersects - Return true if the points-to set of this node intersects
913 /// with the points-to set of the specified node.
914 bool Andersens::Node::intersects(Node *N) const {
915 iterator I1 = begin(), I2 = N->begin(), E1 = end(), E2 = N->end();
916 while (I1 != E1 && I2 != E2) {
917 if (*I1 == *I2) return true;
926 /// intersectsIgnoring - Return true if the points-to set of this node
927 /// intersects with the points-to set of the specified node on any nodes
928 /// except for the specified node to ignore.
929 bool Andersens::Node::intersectsIgnoring(Node *N, Node *Ignoring) const {
930 iterator I1 = begin(), I2 = N->begin(), E1 = end(), E2 = N->end();
931 while (I1 != E1 && I2 != E2) {
933 if (*I1 != Ignoring) return true;
935 } else if (*I1 < *I2)
943 // Copy constraint: all edges out of the source node get copied to the
944 // destination node. This returns true if a change is made.
945 bool Andersens::Node::copyFrom(Node *N) {
946 // Use a mostly linear-time merge since both of the lists are sorted.
947 bool Changed = false;
948 iterator I = N->begin(), E = N->end();
950 while (I != E && i != Pointees.size()) {
951 if (Pointees[i] < *I) {
953 } else if (Pointees[i] == *I) {
956 // We found a new element to copy over.
958 Pointees.insert(Pointees.begin()+i, *I);
964 Pointees.insert(Pointees.end(), I, E);
971 bool Andersens::Node::loadFrom(Node *N) {
972 bool Changed = false;
973 for (iterator I = N->begin(), E = N->end(); I != E; ++I)
974 Changed |= copyFrom(*I);
978 bool Andersens::Node::storeThrough(Node *N) {
979 bool Changed = false;
980 for (iterator I = begin(), E = end(); I != E; ++I)
981 Changed |= (*I)->copyFrom(N);
986 /// SolveConstraints - This stage iteratively processes the constraints list
987 /// propagating constraints (adding edges to the Nodes in the points-to graph)
988 /// until a fixed point is reached.
990 void Andersens::SolveConstraints() {
992 unsigned Iteration = 0;
996 DEBUG(std::cerr << "Starting iteration #" << Iteration++ << "!\n");
998 // Loop over all of the constraints, applying them in turn.
999 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1000 Constraint &C = Constraints[i];
1002 case Constraint::Copy:
1003 Changed |= C.Dest->copyFrom(C.Src);
1005 case Constraint::Load:
1006 Changed |= C.Dest->loadFrom(C.Src);
1008 case Constraint::Store:
1009 Changed |= C.Dest->storeThrough(C.Src);
1012 assert(0 && "Unknown constraint!");
1017 // Check to see if any internal function's addresses have been passed to
1018 // external functions. If so, we have to assume that their incoming
1019 // arguments could be anything. If there are any internal functions in
1020 // the universal node that we don't know about, we must iterate.
1021 for (Node::iterator I = GraphNodes[UniversalSet].begin(),
1022 E = GraphNodes[UniversalSet].end(); I != E; ++I)
1023 if (Function *F = dyn_cast_or_null<Function>((*I)->getValue()))
1024 if (F->hasInternalLinkage() &&
1025 EscapingInternalFunctions.insert(F).second) {
1026 // We found a function that is just now escaping. Mark it as if it
1027 // didn't have internal linkage.
1028 AddConstraintsForNonInternalLinkage(F);
1029 DEBUG(std::cerr << "Found escaping internal function: "
1030 << F->getName() << "\n");
1031 ++NumEscapingFunctions;
1034 // Check to see if we have discovered any new callees of the indirect call
1035 // sites. If so, add constraints to the analysis.
1036 for (unsigned i = 0, e = IndirectCalls.size(); i != e; ++i) {
1037 CallSite CS = IndirectCalls[i];
1038 std::vector<Function*> &KnownCallees = IndirectCallees[CS];
1039 Node *CN = getNode(CS.getCalledValue());
1041 for (Node::iterator NI = CN->begin(), E = CN->end(); NI != E; ++NI)
1042 if (Function *F = dyn_cast_or_null<Function>((*NI)->getValue())) {
1043 std::vector<Function*>::iterator IP =
1044 std::lower_bound(KnownCallees.begin(), KnownCallees.end(), F);
1045 if (IP == KnownCallees.end() || *IP != F) {
1046 // Add the constraints for the call now.
1047 AddConstraintsForCall(CS, F);
1048 DEBUG(std::cerr << "Found actual callee '"
1049 << F->getName() << "' for call: "
1050 << *CS.getInstruction() << "\n");
1051 ++NumIndirectCallees;
1052 KnownCallees.insert(IP, F);
1062 //===----------------------------------------------------------------------===//
1064 //===----------------------------------------------------------------------===//
1066 void Andersens::PrintNode(Node *N) {
1067 if (N == &GraphNodes[UniversalSet]) {
1068 std::cerr << "<universal>";
1070 } else if (N == &GraphNodes[NullPtr]) {
1071 std::cerr << "<nullptr>";
1073 } else if (N == &GraphNodes[NullObject]) {
1074 std::cerr << "<null>";
1078 assert(N->getValue() != 0 && "Never set node label!");
1079 Value *V = N->getValue();
1080 if (Function *F = dyn_cast<Function>(V)) {
1081 if (isa<PointerType>(F->getFunctionType()->getReturnType()) &&
1082 N == getReturnNode(F)) {
1083 std::cerr << F->getName() << ":retval";
1085 } else if (F->getFunctionType()->isVarArg() && N == getVarargNode(F)) {
1086 std::cerr << F->getName() << ":vararg";
1091 if (Instruction *I = dyn_cast<Instruction>(V))
1092 std::cerr << I->getParent()->getParent()->getName() << ":";
1093 else if (Argument *Arg = dyn_cast<Argument>(V))
1094 std::cerr << Arg->getParent()->getName() << ":";
1097 std::cerr << V->getName();
1099 std::cerr << "(unnamed)";
1101 if (isa<GlobalValue>(V) || isa<AllocationInst>(V))
1102 if (N == getObject(V))
1103 std::cerr << "<mem>";
1106 void Andersens::PrintConstraints() {
1107 std::cerr << "Constraints:\n";
1108 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1109 std::cerr << " #" << i << ": ";
1110 Constraint &C = Constraints[i];
1111 if (C.Type == Constraint::Store)
1115 if (C.Type == Constraint::Load)
1122 void Andersens::PrintPointsToGraph() {
1123 std::cerr << "Points-to graph:\n";
1124 for (unsigned i = 0, e = GraphNodes.size(); i != e; ++i) {
1125 Node *N = &GraphNodes[i];
1126 std::cerr << "[" << (N->end() - N->begin()) << "] ";
1128 std::cerr << "\t--> ";
1129 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I) {
1130 if (I != N->begin()) std::cerr << ", ";