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.
95 Value *getValue() const { return Val; }
97 typedef std::vector<Node*>::const_iterator iterator;
98 iterator begin() const { return Pointees.begin(); }
99 iterator end() const { return Pointees.end(); }
101 /// addPointerTo - Add a pointer to the list of pointees of this node,
102 /// returning true if this caused a new pointer to be added, or false if
103 /// we already knew about the points-to relation.
104 bool addPointerTo(Node *N) {
105 std::vector<Node*>::iterator I = std::lower_bound(Pointees.begin(),
108 if (I != Pointees.end() && *I == N)
110 Pointees.insert(I, N);
114 /// intersects - Return true if the points-to set of this node intersects
115 /// with the points-to set of the specified node.
116 bool intersects(Node *N) const;
118 /// intersectsIgnoring - Return true if the points-to set of this node
119 /// intersects with the points-to set of the specified node on any nodes
120 /// except for the specified node to ignore.
121 bool intersectsIgnoring(Node *N, Node *Ignoring) const;
123 // Constraint application methods.
124 bool copyFrom(Node *N);
125 bool loadFrom(Node *N);
126 bool storeThrough(Node *N);
129 /// GraphNodes - This vector is populated as part of the object
130 /// identification stage of the analysis, which populates this vector with a
131 /// node for each memory object and fills in the ValueNodes map.
132 std::vector<Node> GraphNodes;
134 /// ValueNodes - This map indicates the Node that a particular Value* is
135 /// represented by. This contains entries for all pointers.
136 std::map<Value*, unsigned> ValueNodes;
138 /// ObjectNodes - This map contains entries for each memory object in the
139 /// program: globals, alloca's and mallocs.
140 std::map<Value*, unsigned> ObjectNodes;
142 /// ReturnNodes - This map contains an entry for each function in the
143 /// program that returns a value.
144 std::map<Function*, unsigned> ReturnNodes;
146 /// VarargNodes - This map contains the entry used to represent all pointers
147 /// passed through the varargs portion of a function call for a particular
148 /// function. An entry is not present in this map for functions that do not
149 /// take variable arguments.
150 std::map<Function*, unsigned> VarargNodes;
152 /// Constraint - Objects of this structure are used to represent the various
153 /// constraints identified by the algorithm. The constraints are 'copy',
154 /// for statements like "A = B", 'load' for statements like "A = *B", and
155 /// 'store' for statements like "*A = B".
157 enum ConstraintType { Copy, Load, Store } Type;
160 Constraint(ConstraintType Ty, Node *D, Node *S)
161 : Type(Ty), Dest(D), Src(S) {}
164 /// Constraints - This vector contains a list of all of the constraints
165 /// identified by the program.
166 std::vector<Constraint> Constraints;
168 /// EscapingInternalFunctions - This set contains all of the internal
169 /// functions that are found to escape from the program. If the address of
170 /// an internal function is passed to an external function or otherwise
171 /// escapes from the analyzed portion of the program, we must assume that
172 /// any pointer arguments can alias the universal node. This set keeps
173 /// track of those functions we are assuming to escape so far.
174 std::set<Function*> EscapingInternalFunctions;
176 /// IndirectCalls - This contains a list of all of the indirect call sites
177 /// in the program. Since the call graph is iteratively discovered, we may
178 /// need to add constraints to our graph as we find new targets of function
180 std::vector<CallSite> IndirectCalls;
182 /// IndirectCallees - For each call site in the indirect calls list, keep
183 /// track of the callees that we have discovered so far. As the analysis
184 /// proceeds, more callees are discovered, until the call graph finally
186 std::map<CallSite, std::vector<Function*> > IndirectCallees;
188 /// This enum defines the GraphNodes indices that correspond to important
197 bool runOnModule(Module &M) {
198 InitializeAliasAnalysis(this);
200 CollectConstraints(M);
201 DEBUG(PrintConstraints());
203 DEBUG(PrintPointsToGraph());
205 // Free the constraints list, as we don't need it to respond to alias
210 EscapingInternalFunctions.clear();
211 std::vector<Constraint>().swap(Constraints);
215 void releaseMemory() {
216 // FIXME: Until we have transitively required passes working correctly,
217 // this cannot be enabled! Otherwise, using -count-aa with the pass
218 // causes memory to be freed too early. :(
220 // The memory objects and ValueNodes data structures at the only ones that
221 // are still live after construction.
222 std::vector<Node>().swap(GraphNodes);
227 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
228 AliasAnalysis::getAnalysisUsage(AU);
229 AU.setPreservesAll(); // Does not transform code
232 //------------------------------------------------
233 // Implement the AliasAnalysis API
235 AliasResult alias(const Value *V1, unsigned V1Size,
236 const Value *V2, unsigned V2Size);
237 void getMustAliases(Value *P, std::vector<Value*> &RetVals);
238 bool pointsToConstantMemory(const Value *P);
240 virtual void deleteValue(Value *V) {
242 getAnalysis<AliasAnalysis>().deleteValue(V);
245 virtual void copyValue(Value *From, Value *To) {
246 ValueNodes[To] = ValueNodes[From];
247 getAnalysis<AliasAnalysis>().copyValue(From, To);
251 /// getNode - Return the node corresponding to the specified pointer scalar.
253 Node *getNode(Value *V) {
254 if (Constant *C = dyn_cast<Constant>(V))
255 if (!isa<GlobalValue>(C))
256 return getNodeForConstantPointer(C);
258 std::map<Value*, unsigned>::iterator I = ValueNodes.find(V);
259 if (I == ValueNodes.end()) {
261 assert(I != ValueNodes.end() &&
262 "Value does not have a node in the points-to graph!");
264 return &GraphNodes[I->second];
267 /// getObject - Return the node corresponding to the memory object for the
268 /// specified global or allocation instruction.
269 Node *getObject(Value *V) {
270 std::map<Value*, unsigned>::iterator I = ObjectNodes.find(V);
271 assert(I != ObjectNodes.end() &&
272 "Value does not have an object in the points-to graph!");
273 return &GraphNodes[I->second];
276 /// getReturnNode - Return the node representing the return value for the
277 /// specified function.
278 Node *getReturnNode(Function *F) {
279 std::map<Function*, unsigned>::iterator I = ReturnNodes.find(F);
280 assert(I != ReturnNodes.end() && "Function does not return a value!");
281 return &GraphNodes[I->second];
284 /// getVarargNode - Return the node representing the variable arguments
285 /// formal for the specified function.
286 Node *getVarargNode(Function *F) {
287 std::map<Function*, unsigned>::iterator I = VarargNodes.find(F);
288 assert(I != VarargNodes.end() && "Function does not take var args!");
289 return &GraphNodes[I->second];
292 /// getNodeValue - Get the node for the specified LLVM value and set the
293 /// value for it to be the specified value.
294 Node *getNodeValue(Value &V) {
295 return getNode(&V)->setValue(&V);
298 void IdentifyObjects(Module &M);
299 void CollectConstraints(Module &M);
300 void SolveConstraints();
302 Node *getNodeForConstantPointer(Constant *C);
303 Node *getNodeForConstantPointerTarget(Constant *C);
304 void AddGlobalInitializerConstraints(Node *N, Constant *C);
305 void AddConstraintsForNonInternalLinkage(Function *F);
306 void AddConstraintsForCall(CallSite CS, Function *F);
309 void PrintNode(Node *N);
310 void PrintConstraints();
311 void PrintPointsToGraph();
313 //===------------------------------------------------------------------===//
314 // Instruction visitation methods for adding constraints
316 friend class InstVisitor<Andersens>;
317 void visitReturnInst(ReturnInst &RI);
318 void visitInvokeInst(InvokeInst &II) { visitCallSite(CallSite(&II)); }
319 void visitCallInst(CallInst &CI) { visitCallSite(CallSite(&CI)); }
320 void visitCallSite(CallSite CS);
321 void visitAllocationInst(AllocationInst &AI);
322 void visitLoadInst(LoadInst &LI);
323 void visitStoreInst(StoreInst &SI);
324 void visitGetElementPtrInst(GetElementPtrInst &GEP);
325 void visitPHINode(PHINode &PN);
326 void visitCastInst(CastInst &CI);
327 void visitSelectInst(SelectInst &SI);
328 void visitVANext(VANextInst &I);
329 void visitVAArg(VAArgInst &I);
330 void visitInstruction(Instruction &I);
333 RegisterOpt<Andersens> X("anders-aa",
334 "Andersen's Interprocedural Alias Analysis");
335 RegisterAnalysisGroup<AliasAnalysis, Andersens> Y;
338 ModulePass *llvm::createAndersensPass() { return new Andersens(); }
340 //===----------------------------------------------------------------------===//
341 // AliasAnalysis Interface Implementation
342 //===----------------------------------------------------------------------===//
344 AliasAnalysis::AliasResult Andersens::alias(const Value *V1, unsigned V1Size,
345 const Value *V2, unsigned V2Size) {
346 Node *N1 = getNode((Value*)V1);
347 Node *N2 = getNode((Value*)V2);
349 // Check to see if the two pointers are known to not alias. They don't alias
350 // if their points-to sets do not intersect.
351 if (!N1->intersectsIgnoring(N2, &GraphNodes[NullObject]))
354 return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
357 /// getMustAlias - We can provide must alias information if we know that a
358 /// pointer can only point to a specific function or the null pointer.
359 /// Unfortunately we cannot determine must-alias information for global
360 /// variables or any other memory memory objects because we do not track whether
361 /// a pointer points to the beginning of an object or a field of it.
362 void Andersens::getMustAliases(Value *P, std::vector<Value*> &RetVals) {
363 Node *N = getNode(P);
364 Node::iterator I = N->begin();
366 // If there is exactly one element in the points-to set for the object...
369 Node *Pointee = *N->begin();
371 // If a function is the only object in the points-to set, then it must be
372 // the destination. Note that we can't handle global variables here,
373 // because we don't know if the pointer is actually pointing to a field of
374 // the global or to the beginning of it.
375 if (Value *V = Pointee->getValue()) {
376 if (Function *F = dyn_cast<Function>(V))
377 RetVals.push_back(F);
379 // If the object in the points-to set is the null object, then the null
380 // pointer is a must alias.
381 if (Pointee == &GraphNodes[NullObject])
382 RetVals.push_back(Constant::getNullValue(P->getType()));
387 AliasAnalysis::getMustAliases(P, RetVals);
390 /// pointsToConstantMemory - If we can determine that this pointer only points
391 /// to constant memory, return true. In practice, this means that if the
392 /// pointer can only point to constant globals, functions, or the null pointer,
395 bool Andersens::pointsToConstantMemory(const Value *P) {
396 Node *N = getNode((Value*)P);
397 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I) {
398 if (Value *V = (*I)->getValue()) {
399 if (!isa<GlobalValue>(V) || (isa<GlobalVariable>(V) &&
400 !cast<GlobalVariable>(V)->isConstant()))
401 return AliasAnalysis::pointsToConstantMemory(P);
403 if (*I != &GraphNodes[NullObject])
404 return AliasAnalysis::pointsToConstantMemory(P);
411 //===----------------------------------------------------------------------===//
412 // Object Identification Phase
413 //===----------------------------------------------------------------------===//
415 /// IdentifyObjects - This stage scans the program, adding an entry to the
416 /// GraphNodes list for each memory object in the program (global stack or
417 /// heap), and populates the ValueNodes and ObjectNodes maps for these objects.
419 void Andersens::IdentifyObjects(Module &M) {
420 unsigned NumObjects = 0;
422 // Object #0 is always the universal set: the object that we don't know
424 assert(NumObjects == UniversalSet && "Something changed!");
427 // Object #1 always represents the null pointer.
428 assert(NumObjects == NullPtr && "Something changed!");
431 // Object #2 always represents the null object (the object pointed to by null)
432 assert(NumObjects == NullObject && "Something changed!");
435 // Add all the globals first.
436 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
438 ObjectNodes[I] = NumObjects++;
439 ValueNodes[I] = NumObjects++;
442 // Add nodes for all of the functions and the instructions inside of them.
443 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
444 // The function itself is a memory object.
445 ValueNodes[F] = NumObjects++;
446 ObjectNodes[F] = NumObjects++;
447 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
448 ReturnNodes[F] = NumObjects++;
449 if (F->getFunctionType()->isVarArg())
450 VarargNodes[F] = NumObjects++;
452 // Add nodes for all of the incoming pointer arguments.
453 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
455 if (isa<PointerType>(I->getType()))
456 ValueNodes[I] = NumObjects++;
458 // Scan the function body, creating a memory object for each heap/stack
459 // allocation in the body of the function and a node to represent all
460 // pointer values defined by instructions and used as operands.
461 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
462 // If this is an heap or stack allocation, create a node for the memory
464 if (isa<PointerType>(II->getType())) {
465 ValueNodes[&*II] = NumObjects++;
466 if (AllocationInst *AI = dyn_cast<AllocationInst>(&*II))
467 ObjectNodes[AI] = NumObjects++;
472 // Now that we know how many objects to create, make them all now!
473 GraphNodes.resize(NumObjects);
474 NumNodes += NumObjects;
477 //===----------------------------------------------------------------------===//
478 // Constraint Identification Phase
479 //===----------------------------------------------------------------------===//
481 /// getNodeForConstantPointer - Return the node corresponding to the constant
483 Andersens::Node *Andersens::getNodeForConstantPointer(Constant *C) {
484 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
486 if (isa<ConstantPointerNull>(C) || isa<UndefValue>(C))
487 return &GraphNodes[NullPtr];
488 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
490 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
491 switch (CE->getOpcode()) {
492 case Instruction::GetElementPtr:
493 return getNodeForConstantPointer(CE->getOperand(0));
494 case Instruction::Cast:
495 if (isa<PointerType>(CE->getOperand(0)->getType()))
496 return getNodeForConstantPointer(CE->getOperand(0));
498 return &GraphNodes[UniversalSet];
500 std::cerr << "Constant Expr not yet handled: " << *CE << "\n";
504 assert(0 && "Unknown constant pointer!");
509 /// getNodeForConstantPointerTarget - Return the node POINTED TO by the
510 /// specified constant pointer.
511 Andersens::Node *Andersens::getNodeForConstantPointerTarget(Constant *C) {
512 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
514 if (isa<ConstantPointerNull>(C))
515 return &GraphNodes[NullObject];
516 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
517 return getObject(GV);
518 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
519 switch (CE->getOpcode()) {
520 case Instruction::GetElementPtr:
521 return getNodeForConstantPointerTarget(CE->getOperand(0));
522 case Instruction::Cast:
523 if (isa<PointerType>(CE->getOperand(0)->getType()))
524 return getNodeForConstantPointerTarget(CE->getOperand(0));
526 return &GraphNodes[UniversalSet];
528 std::cerr << "Constant Expr not yet handled: " << *CE << "\n";
532 assert(0 && "Unknown constant pointer!");
537 /// AddGlobalInitializerConstraints - Add inclusion constraints for the memory
538 /// object N, which contains values indicated by C.
539 void Andersens::AddGlobalInitializerConstraints(Node *N, Constant *C) {
540 if (C->getType()->isFirstClassType()) {
541 if (isa<PointerType>(C->getType()))
542 N->addPointerTo(getNodeForConstantPointer(C));
543 } else if (C->isNullValue()) {
544 N->addPointerTo(&GraphNodes[NullObject]);
547 // If this is an array or struct, include constraints for each element.
548 assert(isa<ConstantArray>(C) || isa<ConstantStruct>(C));
549 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
550 AddGlobalInitializerConstraints(N, cast<Constant>(C->getOperand(i)));
554 void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
555 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
556 if (isa<PointerType>(I->getType()))
557 // If this is an argument of an externally accessible function, the
558 // incoming pointer might point to anything.
559 Constraints.push_back(Constraint(Constraint::Copy, getNode(I),
560 &GraphNodes[UniversalSet]));
564 /// CollectConstraints - This stage scans the program, adding a constraint to
565 /// the Constraints list for each instruction in the program that induces a
566 /// constraint, and setting up the initial points-to graph.
568 void Andersens::CollectConstraints(Module &M) {
569 // First, the universal set points to itself.
570 GraphNodes[UniversalSet].addPointerTo(&GraphNodes[UniversalSet]);
572 // Next, the null pointer points to the null object.
573 GraphNodes[NullPtr].addPointerTo(&GraphNodes[NullObject]);
575 // Next, add any constraints on global variables and their initializers.
576 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
578 // Associate the address of the global object as pointing to the memory for
579 // the global: &G = <G memory>
580 Node *Object = getObject(I);
582 getNodeValue(*I)->addPointerTo(Object);
584 if (I->hasInitializer()) {
585 AddGlobalInitializerConstraints(Object, I->getInitializer());
587 // If it doesn't have an initializer (i.e. it's defined in another
588 // translation unit), it points to the universal set.
589 Constraints.push_back(Constraint(Constraint::Copy, Object,
590 &GraphNodes[UniversalSet]));
594 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
595 // Make the function address point to the function object.
596 getNodeValue(*F)->addPointerTo(getObject(F)->setValue(F));
598 // Set up the return value node.
599 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
600 getReturnNode(F)->setValue(F);
601 if (F->getFunctionType()->isVarArg())
602 getVarargNode(F)->setValue(F);
604 // Set up incoming argument nodes.
605 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
607 if (isa<PointerType>(I->getType()))
610 if (!F->hasInternalLinkage())
611 AddConstraintsForNonInternalLinkage(F);
613 if (!F->isExternal()) {
614 // Scan the function body, creating a memory object for each heap/stack
615 // allocation in the body of the function and a node to represent all
616 // pointer values defined by instructions and used as operands.
619 // External functions that return pointers return the universal set.
620 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
621 Constraints.push_back(Constraint(Constraint::Copy,
623 &GraphNodes[UniversalSet]));
625 // Any pointers that are passed into the function have the universal set
627 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
629 if (isa<PointerType>(I->getType())) {
630 // Pointers passed into external functions could have anything stored
632 Constraints.push_back(Constraint(Constraint::Store, getNode(I),
633 &GraphNodes[UniversalSet]));
634 // Memory objects passed into external function calls can have the
635 // universal set point to them.
636 Constraints.push_back(Constraint(Constraint::Copy,
637 &GraphNodes[UniversalSet],
641 // If this is an external varargs function, it can also store pointers
642 // into any pointers passed through the varargs section.
643 if (F->getFunctionType()->isVarArg())
644 Constraints.push_back(Constraint(Constraint::Store, getVarargNode(F),
645 &GraphNodes[UniversalSet]));
648 NumConstraints += Constraints.size();
652 void Andersens::visitInstruction(Instruction &I) {
654 return; // This function is just a big assert.
656 if (isa<BinaryOperator>(I))
658 // Most instructions don't have any effect on pointer values.
659 switch (I.getOpcode()) {
660 case Instruction::Br:
661 case Instruction::Switch:
662 case Instruction::Unwind:
663 case Instruction::Unreachable:
664 case Instruction::Free:
665 case Instruction::Shl:
666 case Instruction::Shr:
669 // Is this something we aren't handling yet?
670 std::cerr << "Unknown instruction: " << I;
675 void Andersens::visitAllocationInst(AllocationInst &AI) {
676 getNodeValue(AI)->addPointerTo(getObject(&AI)->setValue(&AI));
679 void Andersens::visitReturnInst(ReturnInst &RI) {
680 if (RI.getNumOperands() && isa<PointerType>(RI.getOperand(0)->getType()))
681 // return V --> <Copy/retval{F}/v>
682 Constraints.push_back(Constraint(Constraint::Copy,
683 getReturnNode(RI.getParent()->getParent()),
684 getNode(RI.getOperand(0))));
687 void Andersens::visitLoadInst(LoadInst &LI) {
688 if (isa<PointerType>(LI.getType()))
689 // P1 = load P2 --> <Load/P1/P2>
690 Constraints.push_back(Constraint(Constraint::Load, getNodeValue(LI),
691 getNode(LI.getOperand(0))));
694 void Andersens::visitStoreInst(StoreInst &SI) {
695 if (isa<PointerType>(SI.getOperand(0)->getType()))
696 // store P1, P2 --> <Store/P2/P1>
697 Constraints.push_back(Constraint(Constraint::Store,
698 getNode(SI.getOperand(1)),
699 getNode(SI.getOperand(0))));
702 void Andersens::visitGetElementPtrInst(GetElementPtrInst &GEP) {
703 // P1 = getelementptr P2, ... --> <Copy/P1/P2>
704 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(GEP),
705 getNode(GEP.getOperand(0))));
708 void Andersens::visitPHINode(PHINode &PN) {
709 if (isa<PointerType>(PN.getType())) {
710 Node *PNN = getNodeValue(PN);
711 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
712 // P1 = phi P2, P3 --> <Copy/P1/P2>, <Copy/P1/P3>, ...
713 Constraints.push_back(Constraint(Constraint::Copy, PNN,
714 getNode(PN.getIncomingValue(i))));
718 void Andersens::visitCastInst(CastInst &CI) {
719 Value *Op = CI.getOperand(0);
720 if (isa<PointerType>(CI.getType())) {
721 if (isa<PointerType>(Op->getType())) {
722 // P1 = cast P2 --> <Copy/P1/P2>
723 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
724 getNode(CI.getOperand(0))));
726 // P1 = cast int --> <Copy/P1/Univ>
727 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
728 &GraphNodes[UniversalSet]));
730 } else if (isa<PointerType>(Op->getType())) {
731 // int = cast P1 --> <Copy/Univ/P1>
732 Constraints.push_back(Constraint(Constraint::Copy,
733 &GraphNodes[UniversalSet],
734 getNode(CI.getOperand(0))));
738 void Andersens::visitSelectInst(SelectInst &SI) {
739 if (isa<PointerType>(SI.getType())) {
740 Node *SIN = getNodeValue(SI);
741 // P1 = select C, P2, P3 ---> <Copy/P1/P2>, <Copy/P1/P3>
742 Constraints.push_back(Constraint(Constraint::Copy, SIN,
743 getNode(SI.getOperand(1))));
744 Constraints.push_back(Constraint(Constraint::Copy, SIN,
745 getNode(SI.getOperand(2))));
749 void Andersens::visitVANext(VANextInst &I) {
751 assert(0 && "vanext not handled yet!");
753 void Andersens::visitVAArg(VAArgInst &I) {
754 assert(0 && "vaarg not handled yet!");
757 /// AddConstraintsForCall - Add constraints for a call with actual arguments
758 /// specified by CS to the function specified by F. Note that the types of
759 /// arguments might not match up in the case where this is an indirect call and
760 /// the function pointer has been casted. If this is the case, do something
762 void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
763 if (isa<PointerType>(CS.getType())) {
764 Node *CSN = getNode(CS.getInstruction());
765 if (isa<PointerType>(F->getFunctionType()->getReturnType())) {
766 Constraints.push_back(Constraint(Constraint::Copy, CSN,
769 // If the function returns a non-pointer value, handle this just like we
770 // treat a nonpointer cast to pointer.
771 Constraints.push_back(Constraint(Constraint::Copy, CSN,
772 &GraphNodes[UniversalSet]));
774 } else if (isa<PointerType>(F->getFunctionType()->getReturnType())) {
775 Constraints.push_back(Constraint(Constraint::Copy,
776 &GraphNodes[UniversalSet],
780 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
781 CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
782 for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI)
783 if (isa<PointerType>(AI->getType())) {
784 if (isa<PointerType>((*ArgI)->getType())) {
785 // Copy the actual argument into the formal argument.
786 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
789 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
790 &GraphNodes[UniversalSet]));
792 } else if (isa<PointerType>((*ArgI)->getType())) {
793 Constraints.push_back(Constraint(Constraint::Copy,
794 &GraphNodes[UniversalSet],
798 // Copy all pointers passed through the varargs section to the varargs node.
799 if (F->getFunctionType()->isVarArg())
800 for (; ArgI != ArgE; ++ArgI)
801 if (isa<PointerType>((*ArgI)->getType()))
802 Constraints.push_back(Constraint(Constraint::Copy, getVarargNode(F),
804 // If more arguments are passed in than we track, just drop them on the floor.
807 void Andersens::visitCallSite(CallSite CS) {
808 if (isa<PointerType>(CS.getType()))
809 getNodeValue(*CS.getInstruction());
811 if (Function *F = CS.getCalledFunction()) {
812 AddConstraintsForCall(CS, F);
814 // We don't handle indirect call sites yet. Keep track of them for when we
815 // discover the call graph incrementally.
816 IndirectCalls.push_back(CS);
820 //===----------------------------------------------------------------------===//
821 // Constraint Solving Phase
822 //===----------------------------------------------------------------------===//
824 /// intersects - Return true if the points-to set of this node intersects
825 /// with the points-to set of the specified node.
826 bool Andersens::Node::intersects(Node *N) const {
827 iterator I1 = begin(), I2 = N->begin(), E1 = end(), E2 = N->end();
828 while (I1 != E1 && I2 != E2) {
829 if (*I1 == *I2) return true;
838 /// intersectsIgnoring - Return true if the points-to set of this node
839 /// intersects with the points-to set of the specified node on any nodes
840 /// except for the specified node to ignore.
841 bool Andersens::Node::intersectsIgnoring(Node *N, Node *Ignoring) const {
842 iterator I1 = begin(), I2 = N->begin(), E1 = end(), E2 = N->end();
843 while (I1 != E1 && I2 != E2) {
845 if (*I1 != Ignoring) return true;
847 } else if (*I1 < *I2)
855 // Copy constraint: all edges out of the source node get copied to the
856 // destination node. This returns true if a change is made.
857 bool Andersens::Node::copyFrom(Node *N) {
858 // Use a mostly linear-time merge since both of the lists are sorted.
859 bool Changed = false;
860 iterator I = N->begin(), E = N->end();
862 while (I != E && i != Pointees.size()) {
863 if (Pointees[i] < *I) {
865 } else if (Pointees[i] == *I) {
868 // We found a new element to copy over.
870 Pointees.insert(Pointees.begin()+i, *I);
876 Pointees.insert(Pointees.end(), I, E);
883 bool Andersens::Node::loadFrom(Node *N) {
884 bool Changed = false;
885 for (iterator I = N->begin(), E = N->end(); I != E; ++I)
886 Changed |= copyFrom(*I);
890 bool Andersens::Node::storeThrough(Node *N) {
891 bool Changed = false;
892 for (iterator I = begin(), E = end(); I != E; ++I)
893 Changed |= (*I)->copyFrom(N);
898 /// SolveConstraints - This stage iteratively processes the constraints list
899 /// propagating constraints (adding edges to the Nodes in the points-to graph)
900 /// until a fixed point is reached.
902 void Andersens::SolveConstraints() {
904 unsigned Iteration = 0;
908 DEBUG(std::cerr << "Starting iteration #" << Iteration++ << "!\n");
910 // Loop over all of the constraints, applying them in turn.
911 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
912 Constraint &C = Constraints[i];
914 case Constraint::Copy:
915 Changed |= C.Dest->copyFrom(C.Src);
917 case Constraint::Load:
918 Changed |= C.Dest->loadFrom(C.Src);
920 case Constraint::Store:
921 Changed |= C.Dest->storeThrough(C.Src);
924 assert(0 && "Unknown constraint!");
929 // Check to see if any internal function's addresses have been passed to
930 // external functions. If so, we have to assume that their incoming
931 // arguments could be anything. If there are any internal functions in
932 // the universal node that we don't know about, we must iterate.
933 for (Node::iterator I = GraphNodes[UniversalSet].begin(),
934 E = GraphNodes[UniversalSet].end(); I != E; ++I)
935 if (Function *F = dyn_cast_or_null<Function>((*I)->getValue()))
936 if (F->hasInternalLinkage() &&
937 EscapingInternalFunctions.insert(F).second) {
938 // We found a function that is just now escaping. Mark it as if it
939 // didn't have internal linkage.
940 AddConstraintsForNonInternalLinkage(F);
941 DEBUG(std::cerr << "Found escaping internal function: "
942 << F->getName() << "\n");
943 ++NumEscapingFunctions;
946 // Check to see if we have discovered any new callees of the indirect call
947 // sites. If so, add constraints to the analysis.
948 for (unsigned i = 0, e = IndirectCalls.size(); i != e; ++i) {
949 CallSite CS = IndirectCalls[i];
950 std::vector<Function*> &KnownCallees = IndirectCallees[CS];
951 Node *CN = getNode(CS.getCalledValue());
953 for (Node::iterator NI = CN->begin(), E = CN->end(); NI != E; ++NI)
954 if (Function *F = dyn_cast_or_null<Function>((*NI)->getValue())) {
955 std::vector<Function*>::iterator IP =
956 std::lower_bound(KnownCallees.begin(), KnownCallees.end(), F);
957 if (IP == KnownCallees.end() || *IP != F) {
958 // Add the constraints for the call now.
959 AddConstraintsForCall(CS, F);
960 DEBUG(std::cerr << "Found actual callee '"
961 << F->getName() << "' for call: "
962 << *CS.getInstruction() << "\n");
963 ++NumIndirectCallees;
964 KnownCallees.insert(IP, F);
974 //===----------------------------------------------------------------------===//
976 //===----------------------------------------------------------------------===//
978 void Andersens::PrintNode(Node *N) {
979 if (N == &GraphNodes[UniversalSet]) {
980 std::cerr << "<universal>";
982 } else if (N == &GraphNodes[NullPtr]) {
983 std::cerr << "<nullptr>";
985 } else if (N == &GraphNodes[NullObject]) {
986 std::cerr << "<null>";
990 assert(N->getValue() != 0 && "Never set node label!");
991 Value *V = N->getValue();
992 if (Function *F = dyn_cast<Function>(V)) {
993 if (isa<PointerType>(F->getFunctionType()->getReturnType()) &&
994 N == getReturnNode(F)) {
995 std::cerr << F->getName() << ":retval";
997 } else if (F->getFunctionType()->isVarArg() && N == getVarargNode(F)) {
998 std::cerr << F->getName() << ":vararg";
1003 if (Instruction *I = dyn_cast<Instruction>(V))
1004 std::cerr << I->getParent()->getParent()->getName() << ":";
1005 else if (Argument *Arg = dyn_cast<Argument>(V))
1006 std::cerr << Arg->getParent()->getName() << ":";
1009 std::cerr << V->getName();
1011 std::cerr << "(unnamed)";
1013 if (isa<GlobalValue>(V) || isa<AllocationInst>(V))
1014 if (N == getObject(V))
1015 std::cerr << "<mem>";
1018 void Andersens::PrintConstraints() {
1019 std::cerr << "Constraints:\n";
1020 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1021 std::cerr << " #" << i << ": ";
1022 Constraint &C = Constraints[i];
1023 if (C.Type == Constraint::Store)
1027 if (C.Type == Constraint::Load)
1034 void Andersens::PrintPointsToGraph() {
1035 std::cerr << "Points-to graph:\n";
1036 for (unsigned i = 0, e = GraphNodes.size(); i != e; ++i) {
1037 Node *N = &GraphNodes[i];
1038 std::cerr << "[" << (N->end() - N->begin()) << "] ";
1040 std::cerr << "\t--> ";
1041 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I) {
1042 if (I != N->begin()) std::cerr << ", ";