blob: 371a8a0deec616f7207777dfa7875f8c6e8b9ed2 [file] [log] [blame]
Chris Lattnere995a2a2004-05-23 21:00:47 +00001//===- Andersens.cpp - Andersen's Interprocedural Alias Analysis -----------==//
2//
3// The LLVM Compiler Infrastructure
4//
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.
7//
8//===----------------------------------------------------------------------===//
9//
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.
15//
16// In pointer analysis terms, this is a subset-based, flow-insensitive,
17// field-insensitive, and context-insensitive algorithm pointer algorithm.
18//
19// This algorithm is implemented as three stages:
20// 1. Object identification.
21// 2. Inclusion constraint identification.
22// 3. Inclusion constraint solving.
23//
24// The object identification stage identifies all of the memory objects in the
25// program, which includes globals, heap allocated objects, and stack allocated
26// objects.
27//
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.
33//
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.
36//
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.
43//
44//===----------------------------------------------------------------------===//
45
46#define DEBUG_TYPE "anders-aa"
47#include "llvm/Constants.h"
48#include "llvm/DerivedTypes.h"
49#include "llvm/Instructions.h"
50#include "llvm/Module.h"
51#include "llvm/Pass.h"
52#include "llvm/Support/InstIterator.h"
53#include "llvm/Support/InstVisitor.h"
54#include "llvm/Analysis/AliasAnalysis.h"
55#include "Support/Debug.h"
56#include "Support/Statistic.h"
57#include <set>
58using namespace llvm;
59
60namespace {
61 Statistic<>
62 NumIters("anders-aa", "Number of iterations to reach convergence");
63 Statistic<>
64 NumConstraints("anders-aa", "Number of constraints");
65 Statistic<>
66 NumNodes("anders-aa", "Number of nodes");
67 Statistic<>
68 NumEscapingFunctions("anders-aa", "Number of internal functions that escape");
69 Statistic<>
70 NumIndirectCallees("anders-aa", "Number of indirect callees found");
71
72 class Andersens : public Pass, public AliasAnalysis,
73 private InstVisitor<Andersens> {
74 /// Node class - This class is used to represent a memory object in the
75 /// program, and is the primitive used to build the points-to graph.
76 class Node {
77 std::vector<Node*> Pointees;
78 Value *Val;
79 public:
80 Node() : Val(0) {}
81 Node *setValue(Value *V) {
82 assert(Val == 0 && "Value already set for this node!");
83 Val = V;
84 return this;
85 }
86
87 /// getValue - Return the LLVM value corresponding to this node.
88 Value *getValue() const { return Val; }
89
90 typedef std::vector<Node*>::const_iterator iterator;
91 iterator begin() const { return Pointees.begin(); }
92 iterator end() const { return Pointees.end(); }
93
94 /// addPointerTo - Add a pointer to the list of pointees of this node,
95 /// returning true if this caused a new pointer to be added, or false if
96 /// we already knew about the points-to relation.
97 bool addPointerTo(Node *N) {
98 std::vector<Node*>::iterator I = std::lower_bound(Pointees.begin(),
99 Pointees.end(),
100 N);
101 if (I != Pointees.end() && *I == N)
102 return false;
103 Pointees.insert(I, N);
104 return true;
105 }
106
107 /// intersects - Return true if the points-to set of this node intersects
108 /// with the points-to set of the specified node.
109 bool intersects(Node *N) const;
110
111 /// intersectsIgnoring - Return true if the points-to set of this node
112 /// intersects with the points-to set of the specified node on any nodes
113 /// except for the specified node to ignore.
114 bool intersectsIgnoring(Node *N, Node *Ignoring) const;
115
116 // Constraint application methods.
117 bool copyFrom(Node *N);
118 bool loadFrom(Node *N);
119 bool storeThrough(Node *N);
120 };
121
122 /// GraphNodes - This vector is populated as part of the object
123 /// identification stage of the analysis, which populates this vector with a
124 /// node for each memory object and fills in the ValueNodes map.
125 std::vector<Node> GraphNodes;
126
127 /// ValueNodes - This map indicates the Node that a particular Value* is
128 /// represented by. This contains entries for all pointers.
129 std::map<Value*, unsigned> ValueNodes;
130
131 /// ObjectNodes - This map contains entries for each memory object in the
132 /// program: globals, alloca's and mallocs.
133 std::map<Value*, unsigned> ObjectNodes;
134
135 /// ReturnNodes - This map contains an entry for each function in the
136 /// program that returns a value.
137 std::map<Function*, unsigned> ReturnNodes;
138
139 /// VarargNodes - This map contains the entry used to represent all pointers
140 /// passed through the varargs portion of a function call for a particular
141 /// function. An entry is not present in this map for functions that do not
142 /// take variable arguments.
143 std::map<Function*, unsigned> VarargNodes;
144
145 /// Constraint - Objects of this structure are used to represent the various
146 /// constraints identified by the algorithm. The constraints are 'copy',
147 /// for statements like "A = B", 'load' for statements like "A = *B", and
148 /// 'store' for statements like "*A = B".
149 struct Constraint {
150 enum ConstraintType { Copy, Load, Store } Type;
151 Node *Dest, *Src;
152
153 Constraint(ConstraintType Ty, Node *D, Node *S)
154 : Type(Ty), Dest(D), Src(S) {}
155 };
156
157 /// Constraints - This vector contains a list of all of the constraints
158 /// identified by the program.
159 std::vector<Constraint> Constraints;
160
161 /// EscapingInternalFunctions - This set contains all of the internal
162 /// functions that are found to escape from the program. If the address of
163 /// an internal function is passed to an external function or otherwise
164 /// escapes from the analyzed portion of the program, we must assume that
165 /// any pointer arguments can alias the universal node. This set keeps
166 /// track of those functions we are assuming to escape so far.
167 std::set<Function*> EscapingInternalFunctions;
168
169 /// IndirectCalls - This contains a list of all of the indirect call sites
170 /// in the program. Since the call graph is iteratively discovered, we may
171 /// need to add constraints to our graph as we find new targets of function
172 /// pointers.
173 std::vector<CallSite> IndirectCalls;
174
175 /// IndirectCallees - For each call site in the indirect calls list, keep
176 /// track of the callees that we have discovered so far. As the analysis
177 /// proceeds, more callees are discovered, until the call graph finally
178 /// stabilizes.
179 std::map<CallSite, std::vector<Function*> > IndirectCallees;
180
181 /// This enum defines the GraphNodes indices that correspond to important
182 /// fixed sets.
183 enum {
184 UniversalSet = 0,
185 NullPtr = 1,
186 NullObject = 2,
187 };
188
189 public:
190 bool run(Module &M) {
191 InitializeAliasAnalysis(this);
192 IdentifyObjects(M);
193 CollectConstraints(M);
194 DEBUG(PrintConstraints());
195 SolveConstraints();
196 DEBUG(PrintPointsToGraph());
197
198 // Free the constraints list, as we don't need it to respond to alias
199 // requests.
200 ObjectNodes.clear();
201 ReturnNodes.clear();
202 VarargNodes.clear();
203 EscapingInternalFunctions.clear();
204 std::vector<Constraint>().swap(Constraints);
205 return false;
206 }
207
208 void releaseMemory() {
209 // FIXME: Until we have transitively required passes working correctly,
210 // this cannot be enabled! Otherwise, using -count-aa with the pass
211 // causes memory to be freed too early. :(
212#if 0
213 // The memory objects and ValueNodes data structures at the only ones that
214 // are still live after construction.
215 std::vector<Node>().swap(GraphNodes);
216 ValueNodes.clear();
217#endif
218 }
219
220 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
221 AliasAnalysis::getAnalysisUsage(AU);
222 AU.setPreservesAll(); // Does not transform code
223 }
224
225 //------------------------------------------------
226 // Implement the AliasAnalysis API
227 //
228 AliasResult alias(const Value *V1, unsigned V1Size,
229 const Value *V2, unsigned V2Size);
230 void getMustAliases(Value *P, std::vector<Value*> &RetVals);
231 bool pointsToConstantMemory(const Value *P);
232
233 virtual void deleteValue(Value *V) {
234 ValueNodes.erase(V);
235 getAnalysis<AliasAnalysis>().deleteValue(V);
236 }
237
238 virtual void copyValue(Value *From, Value *To) {
239 ValueNodes[To] = ValueNodes[From];
240 getAnalysis<AliasAnalysis>().copyValue(From, To);
241 }
242
243 private:
244 /// getNode - Return the node corresponding to the specified pointer scalar.
245 ///
246 Node *getNode(Value *V) {
247 if (Constant *C = dyn_cast<Constant>(V))
248 return getNodeForConstantPointer(C);
249
250 std::map<Value*, unsigned>::iterator I = ValueNodes.find(V);
251 if (I == ValueNodes.end()) {
252 V->dump();
253 assert(I != ValueNodes.end() &&
254 "Value does not have a node in the points-to graph!");
255 }
256 return &GraphNodes[I->second];
257 }
258
259 /// getObject - Return the node corresponding to the memory object for the
260 /// specified global or allocation instruction.
261 Node *getObject(Value *V) {
262 std::map<Value*, unsigned>::iterator I = ObjectNodes.find(V);
263 assert(I != ObjectNodes.end() &&
264 "Value does not have an object in the points-to graph!");
265 return &GraphNodes[I->second];
266 }
267
268 /// getReturnNode - Return the node representing the return value for the
269 /// specified function.
270 Node *getReturnNode(Function *F) {
271 std::map<Function*, unsigned>::iterator I = ReturnNodes.find(F);
272 assert(I != ReturnNodes.end() && "Function does not return a value!");
273 return &GraphNodes[I->second];
274 }
275
276 /// getVarargNode - Return the node representing the variable arguments
277 /// formal for the specified function.
278 Node *getVarargNode(Function *F) {
279 std::map<Function*, unsigned>::iterator I = VarargNodes.find(F);
280 assert(I != VarargNodes.end() && "Function does not take var args!");
281 return &GraphNodes[I->second];
282 }
283
284 /// getNodeValue - Get the node for the specified LLVM value and set the
285 /// value for it to be the specified value.
286 Node *getNodeValue(Value &V) {
287 return getNode(&V)->setValue(&V);
288 }
289
290 void IdentifyObjects(Module &M);
291 void CollectConstraints(Module &M);
292 void SolveConstraints();
293
294 Node *getNodeForConstantPointer(Constant *C);
295 Node *getNodeForConstantPointerTarget(Constant *C);
296 void AddGlobalInitializerConstraints(Node *N, Constant *C);
297 void AddConstraintsForNonInternalLinkage(Function *F);
298 void AddConstraintsForCall(CallSite CS, Function *F);
299
300
301 void PrintNode(Node *N);
302 void PrintConstraints();
303 void PrintPointsToGraph();
304
305 //===------------------------------------------------------------------===//
306 // Instruction visitation methods for adding constraints
307 //
308 friend class InstVisitor<Andersens>;
309 void visitReturnInst(ReturnInst &RI);
310 void visitInvokeInst(InvokeInst &II) { visitCallSite(CallSite(&II)); }
311 void visitCallInst(CallInst &CI) { visitCallSite(CallSite(&CI)); }
312 void visitCallSite(CallSite CS);
313 void visitAllocationInst(AllocationInst &AI);
314 void visitLoadInst(LoadInst &LI);
315 void visitStoreInst(StoreInst &SI);
316 void visitGetElementPtrInst(GetElementPtrInst &GEP);
317 void visitPHINode(PHINode &PN);
318 void visitCastInst(CastInst &CI);
319 void visitSelectInst(SelectInst &SI);
320 void visitVANext(VANextInst &I);
321 void visitVAArg(VAArgInst &I);
322 void visitInstruction(Instruction &I);
323 };
324
325 RegisterOpt<Andersens> X("anders-aa",
326 "Andersen's Interprocedural Alias Analysis");
327 RegisterAnalysisGroup<AliasAnalysis, Andersens> Y;
328}
329
330//===----------------------------------------------------------------------===//
331// AliasAnalysis Interface Implementation
332//===----------------------------------------------------------------------===//
333
334AliasAnalysis::AliasResult Andersens::alias(const Value *V1, unsigned V1Size,
335 const Value *V2, unsigned V2Size) {
336 Node *N1 = getNode((Value*)V1);
337 Node *N2 = getNode((Value*)V2);
338
339 // Check to see if the two pointers are known to not alias. They don't alias
340 // if their points-to sets do not intersect.
341 if (!N1->intersectsIgnoring(N2, &GraphNodes[NullObject]))
342 return NoAlias;
343
344 return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
345}
346
347/// getMustAlias - We can provide must alias information if we know that a
348/// pointer can only point to a specific function or the null pointer.
349/// Unfortunately we cannot determine must-alias information for global
350/// variables or any other memory memory objects because we do not track whether
351/// a pointer points to the beginning of an object or a field of it.
352void Andersens::getMustAliases(Value *P, std::vector<Value*> &RetVals) {
353 Node *N = getNode(P);
354 Node::iterator I = N->begin();
355 if (I != N->end()) {
356 // If there is exactly one element in the points-to set for the object...
357 ++I;
358 if (I == N->end()) {
359 Node *Pointee = *N->begin();
360
361 // If a function is the only object in the points-to set, then it must be
362 // the destination. Note that we can't handle global variables here,
363 // because we don't know if the pointer is actually pointing to a field of
364 // the global or to the beginning of it.
365 if (Value *V = Pointee->getValue()) {
366 if (Function *F = dyn_cast<Function>(V))
367 RetVals.push_back(F);
368 } else {
369 // If the object in the points-to set is the null object, then the null
370 // pointer is a must alias.
371 if (Pointee == &GraphNodes[NullObject])
372 RetVals.push_back(Constant::getNullValue(P->getType()));
373 }
374 }
375 }
376
377 AliasAnalysis::getMustAliases(P, RetVals);
378}
379
380/// pointsToConstantMemory - If we can determine that this pointer only points
381/// to constant memory, return true. In practice, this means that if the
382/// pointer can only point to constant globals, functions, or the null pointer,
383/// return true.
384///
385bool Andersens::pointsToConstantMemory(const Value *P) {
386 Node *N = getNode((Value*)P);
387 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I) {
388 if (Value *V = (*I)->getValue()) {
389 if (!isa<GlobalValue>(V) || (isa<GlobalVariable>(V) &&
390 !cast<GlobalVariable>(V)->isConstant()))
391 return AliasAnalysis::pointsToConstantMemory(P);
392 } else {
393 if (*I != &GraphNodes[NullObject])
394 return AliasAnalysis::pointsToConstantMemory(P);
395 }
396 }
397
398 return true;
399}
400
401//===----------------------------------------------------------------------===//
402// Object Identification Phase
403//===----------------------------------------------------------------------===//
404
405/// IdentifyObjects - This stage scans the program, adding an entry to the
406/// GraphNodes list for each memory object in the program (global stack or
407/// heap), and populates the ValueNodes and ObjectNodes maps for these objects.
408///
409void Andersens::IdentifyObjects(Module &M) {
410 unsigned NumObjects = 0;
411
412 // Object #0 is always the universal set: the object that we don't know
413 // anything about.
414 assert(NumObjects == UniversalSet && "Something changed!");
415 ++NumObjects;
416
417 // Object #1 always represents the null pointer.
418 assert(NumObjects == NullPtr && "Something changed!");
419 ++NumObjects;
420
421 // Object #2 always represents the null object (the object pointed to by null)
422 assert(NumObjects == NullObject && "Something changed!");
423 ++NumObjects;
424
425 // Add all the globals first.
426 for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I) {
427 ObjectNodes[I] = NumObjects++;
428 ValueNodes[I] = NumObjects++;
429 }
430
431 // Add nodes for all of the functions and the instructions inside of them.
432 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
433 // The function itself is a memory object.
434 ValueNodes[F] = NumObjects++;
435 ObjectNodes[F] = NumObjects++;
436 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
437 ReturnNodes[F] = NumObjects++;
438 if (F->getFunctionType()->isVarArg())
439 VarargNodes[F] = NumObjects++;
440
441 // Add nodes for all of the incoming pointer arguments.
442 for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
443 if (isa<PointerType>(I->getType()))
444 ValueNodes[I] = NumObjects++;
445
446 // Scan the function body, creating a memory object for each heap/stack
447 // allocation in the body of the function and a node to represent all
448 // pointer values defined by instructions and used as operands.
449 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
450 // If this is an heap or stack allocation, create a node for the memory
451 // object.
452 if (isa<PointerType>(II->getType())) {
453 ValueNodes[&*II] = NumObjects++;
454 if (AllocationInst *AI = dyn_cast<AllocationInst>(&*II))
455 ObjectNodes[AI] = NumObjects++;
456 }
457 }
458 }
459
460 // Now that we know how many objects to create, make them all now!
461 GraphNodes.resize(NumObjects);
462 NumNodes += NumObjects;
463}
464
465//===----------------------------------------------------------------------===//
466// Constraint Identification Phase
467//===----------------------------------------------------------------------===//
468
469/// getNodeForConstantPointer - Return the node corresponding to the constant
470/// pointer itself.
471Andersens::Node *Andersens::getNodeForConstantPointer(Constant *C) {
472 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
473
474 if (isa<ConstantPointerNull>(C))
475 return &GraphNodes[NullPtr];
476 else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C))
477 return getNode(CPR->getValue());
478 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
479 switch (CE->getOpcode()) {
480 case Instruction::GetElementPtr:
481 return getNodeForConstantPointer(CE->getOperand(0));
482 case Instruction::Cast:
483 if (isa<PointerType>(CE->getOperand(0)->getType()))
484 return getNodeForConstantPointer(CE->getOperand(0));
485 else
486 return &GraphNodes[UniversalSet];
487 default:
488 std::cerr << "Constant Expr not yet handled: " << *CE << "\n";
489 assert(0);
490 }
491 } else {
492 assert(0 && "Unknown constant pointer!");
493 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000494 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000495}
496
497/// getNodeForConstantPointerTarget - Return the node POINTED TO by the
498/// specified constant pointer.
499Andersens::Node *Andersens::getNodeForConstantPointerTarget(Constant *C) {
500 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
501
502 if (isa<ConstantPointerNull>(C))
503 return &GraphNodes[NullObject];
504 else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C))
505 return getObject(CPR->getValue());
506 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
507 switch (CE->getOpcode()) {
508 case Instruction::GetElementPtr:
509 return getNodeForConstantPointerTarget(CE->getOperand(0));
510 case Instruction::Cast:
511 if (isa<PointerType>(CE->getOperand(0)->getType()))
512 return getNodeForConstantPointerTarget(CE->getOperand(0));
513 else
514 return &GraphNodes[UniversalSet];
515 default:
516 std::cerr << "Constant Expr not yet handled: " << *CE << "\n";
517 assert(0);
518 }
519 } else {
520 assert(0 && "Unknown constant pointer!");
521 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000522 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000523}
524
525/// AddGlobalInitializerConstraints - Add inclusion constraints for the memory
526/// object N, which contains values indicated by C.
527void Andersens::AddGlobalInitializerConstraints(Node *N, Constant *C) {
528 if (C->getType()->isFirstClassType()) {
529 if (isa<PointerType>(C->getType()))
530 N->addPointerTo(getNodeForConstantPointer(C));
531 } else if (C->isNullValue()) {
532 N->addPointerTo(&GraphNodes[NullObject]);
533 return;
534 } else {
535 // If this is an array or struct, include constraints for each element.
536 assert(isa<ConstantArray>(C) || isa<ConstantStruct>(C));
537 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
538 AddGlobalInitializerConstraints(N, cast<Constant>(C->getOperand(i)));
539 }
540}
541
542void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
543 for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
544 if (isa<PointerType>(I->getType()))
545 // If this is an argument of an externally accessible function, the
546 // incoming pointer might point to anything.
547 Constraints.push_back(Constraint(Constraint::Copy, getNode(I),
548 &GraphNodes[UniversalSet]));
549}
550
551
552/// CollectConstraints - This stage scans the program, adding a constraint to
553/// the Constraints list for each instruction in the program that induces a
554/// constraint, and setting up the initial points-to graph.
555///
556void Andersens::CollectConstraints(Module &M) {
557 // First, the universal set points to itself.
558 GraphNodes[UniversalSet].addPointerTo(&GraphNodes[UniversalSet]);
559
560 // Next, the null pointer points to the null object.
561 GraphNodes[NullPtr].addPointerTo(&GraphNodes[NullObject]);
562
563 // Next, add any constraints on global variables and their initializers.
564 for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I) {
565 // Associate the address of the global object as pointing to the memory for
566 // the global: &G = <G memory>
567 Node *Object = getObject(I);
568 Object->setValue(I);
569 getNodeValue(*I)->addPointerTo(Object);
570
571 if (I->hasInitializer()) {
572 AddGlobalInitializerConstraints(Object, I->getInitializer());
573 } else {
574 // If it doesn't have an initializer (i.e. it's defined in another
575 // translation unit), it points to the universal set.
576 Constraints.push_back(Constraint(Constraint::Copy, Object,
577 &GraphNodes[UniversalSet]));
578 }
579 }
580
581 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
582 // Make the function address point to the function object.
583 getNodeValue(*F)->addPointerTo(getObject(F)->setValue(F));
584
585 // Set up the return value node.
586 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
587 getReturnNode(F)->setValue(F);
588 if (F->getFunctionType()->isVarArg())
589 getVarargNode(F)->setValue(F);
590
591 // Set up incoming argument nodes.
592 for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
593 if (isa<PointerType>(I->getType()))
594 getNodeValue(*I);
595
596 if (!F->hasInternalLinkage())
597 AddConstraintsForNonInternalLinkage(F);
598
599 if (!F->isExternal()) {
600 // Scan the function body, creating a memory object for each heap/stack
601 // allocation in the body of the function and a node to represent all
602 // pointer values defined by instructions and used as operands.
603 visit(F);
604 } else {
605 // External functions that return pointers return the universal set.
606 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
607 Constraints.push_back(Constraint(Constraint::Copy,
608 getReturnNode(F),
609 &GraphNodes[UniversalSet]));
610
611 // Any pointers that are passed into the function have the universal set
612 // stored into them.
613 for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
614 if (isa<PointerType>(I->getType())) {
615 // Pointers passed into external functions could have anything stored
616 // through them.
617 Constraints.push_back(Constraint(Constraint::Store, getNode(I),
618 &GraphNodes[UniversalSet]));
619 // Memory objects passed into external function calls can have the
620 // universal set point to them.
621 Constraints.push_back(Constraint(Constraint::Copy,
622 &GraphNodes[UniversalSet],
623 getNode(I)));
624 }
625
626 // If this is an external varargs function, it can also store pointers
627 // into any pointers passed through the varargs section.
628 if (F->getFunctionType()->isVarArg())
629 Constraints.push_back(Constraint(Constraint::Store, getVarargNode(F),
630 &GraphNodes[UniversalSet]));
631 }
632 }
633 NumConstraints += Constraints.size();
634}
635
636
637void Andersens::visitInstruction(Instruction &I) {
638#ifdef NDEBUG
639 return; // This function is just a big assert.
640#endif
641 if (isa<BinaryOperator>(I))
642 return;
643 // Most instructions don't have any effect on pointer values.
644 switch (I.getOpcode()) {
645 case Instruction::Br:
646 case Instruction::Switch:
647 case Instruction::Unwind:
648 case Instruction::Free:
649 case Instruction::Shl:
650 case Instruction::Shr:
651 return;
652 default:
653 // Is this something we aren't handling yet?
654 std::cerr << "Unknown instruction: " << I;
655 abort();
656 }
657}
658
659void Andersens::visitAllocationInst(AllocationInst &AI) {
660 getNodeValue(AI)->addPointerTo(getObject(&AI)->setValue(&AI));
661}
662
663void Andersens::visitReturnInst(ReturnInst &RI) {
664 if (RI.getNumOperands() && isa<PointerType>(RI.getOperand(0)->getType()))
665 // return V --> <Copy/retval{F}/v>
666 Constraints.push_back(Constraint(Constraint::Copy,
667 getReturnNode(RI.getParent()->getParent()),
668 getNode(RI.getOperand(0))));
669}
670
671void Andersens::visitLoadInst(LoadInst &LI) {
672 if (isa<PointerType>(LI.getType()))
673 // P1 = load P2 --> <Load/P1/P2>
674 Constraints.push_back(Constraint(Constraint::Load, getNodeValue(LI),
675 getNode(LI.getOperand(0))));
676}
677
678void Andersens::visitStoreInst(StoreInst &SI) {
679 if (isa<PointerType>(SI.getOperand(0)->getType()))
680 // store P1, P2 --> <Store/P2/P1>
681 Constraints.push_back(Constraint(Constraint::Store,
682 getNode(SI.getOperand(1)),
683 getNode(SI.getOperand(0))));
684}
685
686void Andersens::visitGetElementPtrInst(GetElementPtrInst &GEP) {
687 // P1 = getelementptr P2, ... --> <Copy/P1/P2>
688 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(GEP),
689 getNode(GEP.getOperand(0))));
690}
691
692void Andersens::visitPHINode(PHINode &PN) {
693 if (isa<PointerType>(PN.getType())) {
694 Node *PNN = getNodeValue(PN);
695 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
696 // P1 = phi P2, P3 --> <Copy/P1/P2>, <Copy/P1/P3>, ...
697 Constraints.push_back(Constraint(Constraint::Copy, PNN,
698 getNode(PN.getIncomingValue(i))));
699 }
700}
701
702void Andersens::visitCastInst(CastInst &CI) {
703 Value *Op = CI.getOperand(0);
704 if (isa<PointerType>(CI.getType())) {
705 if (isa<PointerType>(Op->getType())) {
706 // P1 = cast P2 --> <Copy/P1/P2>
707 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
708 getNode(CI.getOperand(0))));
709 } else {
710 // P1 = cast int --> <Copy/P1/Univ>
711 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
712 &GraphNodes[UniversalSet]));
713 }
714 } else if (isa<PointerType>(Op->getType())) {
715 // int = cast P1 --> <Copy/Univ/P1>
716 Constraints.push_back(Constraint(Constraint::Copy,
717 &GraphNodes[UniversalSet],
718 getNode(CI.getOperand(0))));
719 }
720}
721
722void Andersens::visitSelectInst(SelectInst &SI) {
723 if (isa<PointerType>(SI.getType())) {
724 Node *SIN = getNodeValue(SI);
725 // P1 = select C, P2, P3 ---> <Copy/P1/P2>, <Copy/P1/P3>
726 Constraints.push_back(Constraint(Constraint::Copy, SIN,
727 getNode(SI.getOperand(1))));
728 Constraints.push_back(Constraint(Constraint::Copy, SIN,
729 getNode(SI.getOperand(2))));
730 }
731}
732
733void Andersens::visitVANext(VANextInst &I) {
734 // FIXME: Implement
735 assert(0 && "vanext not handled yet!");
736}
737void Andersens::visitVAArg(VAArgInst &I) {
738 assert(0 && "vaarg not handled yet!");
739}
740
741/// AddConstraintsForCall - Add constraints for a call with actual arguments
742/// specified by CS to the function specified by F. Note that the types of
743/// arguments might not match up in the case where this is an indirect call and
744/// the function pointer has been casted. If this is the case, do something
745/// reasonable.
746void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
747 if (isa<PointerType>(CS.getType())) {
748 Node *CSN = getNode(CS.getInstruction());
749 if (isa<PointerType>(F->getFunctionType()->getReturnType())) {
750 Constraints.push_back(Constraint(Constraint::Copy, CSN,
751 getReturnNode(F)));
752 } else {
753 // If the function returns a non-pointer value, handle this just like we
754 // treat a nonpointer cast to pointer.
755 Constraints.push_back(Constraint(Constraint::Copy, CSN,
756 &GraphNodes[UniversalSet]));
757 }
758 } else if (isa<PointerType>(F->getFunctionType()->getReturnType())) {
759 Constraints.push_back(Constraint(Constraint::Copy,
760 &GraphNodes[UniversalSet],
761 getReturnNode(F)));
762 }
763
764 Function::aiterator AI = F->abegin(), AE = F->aend();
765 CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
766 for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI)
767 if (isa<PointerType>(AI->getType())) {
768 if (isa<PointerType>((*ArgI)->getType())) {
769 // Copy the actual argument into the formal argument.
770 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
771 getNode(*ArgI)));
772 } else {
773 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
774 &GraphNodes[UniversalSet]));
775 }
776 } else if (isa<PointerType>((*ArgI)->getType())) {
777 Constraints.push_back(Constraint(Constraint::Copy,
778 &GraphNodes[UniversalSet],
779 getNode(*ArgI)));
780 }
781
782 // Copy all pointers passed through the varargs section to the varargs node.
783 if (F->getFunctionType()->isVarArg())
784 for (; ArgI != ArgE; ++ArgI)
785 if (isa<PointerType>((*ArgI)->getType()))
786 Constraints.push_back(Constraint(Constraint::Copy, getVarargNode(F),
787 getNode(*ArgI)));
788 // If more arguments are passed in than we track, just drop them on the floor.
789}
790
791void Andersens::visitCallSite(CallSite CS) {
792 if (isa<PointerType>(CS.getType()))
793 getNodeValue(*CS.getInstruction());
794
795 if (Function *F = CS.getCalledFunction()) {
796 AddConstraintsForCall(CS, F);
797 } else {
798 // We don't handle indirect call sites yet. Keep track of them for when we
799 // discover the call graph incrementally.
800 IndirectCalls.push_back(CS);
801 }
802}
803
804//===----------------------------------------------------------------------===//
805// Constraint Solving Phase
806//===----------------------------------------------------------------------===//
807
808/// intersects - Return true if the points-to set of this node intersects
809/// with the points-to set of the specified node.
810bool Andersens::Node::intersects(Node *N) const {
811 iterator I1 = begin(), I2 = N->begin(), E1 = end(), E2 = N->end();
812 while (I1 != E1 && I2 != E2) {
813 if (*I1 == *I2) return true;
814 if (*I1 < *I2)
815 ++I1;
816 else
817 ++I2;
818 }
819 return false;
820}
821
822/// intersectsIgnoring - Return true if the points-to set of this node
823/// intersects with the points-to set of the specified node on any nodes
824/// except for the specified node to ignore.
825bool Andersens::Node::intersectsIgnoring(Node *N, Node *Ignoring) const {
826 iterator I1 = begin(), I2 = N->begin(), E1 = end(), E2 = N->end();
827 while (I1 != E1 && I2 != E2) {
828 if (*I1 == *I2) {
829 if (*I1 != Ignoring) return true;
830 ++I1; ++I2;
831 } else if (*I1 < *I2)
832 ++I1;
833 else
834 ++I2;
835 }
836 return false;
837}
838
839// Copy constraint: all edges out of the source node get copied to the
840// destination node. This returns true if a change is made.
841bool Andersens::Node::copyFrom(Node *N) {
842 // Use a mostly linear-time merge since both of the lists are sorted.
843 bool Changed = false;
844 iterator I = N->begin(), E = N->end();
845 unsigned i = 0;
846 while (I != E && i != Pointees.size()) {
847 if (Pointees[i] < *I) {
848 ++i;
849 } else if (Pointees[i] == *I) {
850 ++i; ++I;
851 } else {
852 // We found a new element to copy over.
853 Changed = true;
854 Pointees.insert(Pointees.begin()+i, *I);
855 ++i; ++I;
856 }
857 }
858
859 if (I != E) {
860 Pointees.insert(Pointees.end(), I, E);
861 Changed = true;
862 }
863
864 return Changed;
865}
866
867bool Andersens::Node::loadFrom(Node *N) {
868 bool Changed = false;
869 for (iterator I = N->begin(), E = N->end(); I != E; ++I)
870 Changed |= copyFrom(*I);
871 return Changed;
872}
873
874bool Andersens::Node::storeThrough(Node *N) {
875 bool Changed = false;
876 for (iterator I = begin(), E = end(); I != E; ++I)
877 Changed |= (*I)->copyFrom(N);
878 return Changed;
879}
880
881
882/// SolveConstraints - This stage iteratively processes the constraints list
883/// propagating constraints (adding edges to the Nodes in the points-to graph)
884/// until a fixed point is reached.
885///
886void Andersens::SolveConstraints() {
887 bool Changed = true;
888 unsigned Iteration = 0;
889 while (Changed) {
890 Changed = false;
891 ++NumIters;
892 DEBUG(std::cerr << "Starting iteration #" << Iteration++ << "!\n");
893
894 // Loop over all of the constraints, applying them in turn.
895 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
896 Constraint &C = Constraints[i];
897 switch (C.Type) {
898 case Constraint::Copy:
899 Changed |= C.Dest->copyFrom(C.Src);
900 break;
901 case Constraint::Load:
902 Changed |= C.Dest->loadFrom(C.Src);
903 break;
904 case Constraint::Store:
905 Changed |= C.Dest->storeThrough(C.Src);
906 break;
907 default:
908 assert(0 && "Unknown constraint!");
909 }
910 }
911
912 if (Changed) {
913 // Check to see if any internal function's addresses have been passed to
914 // external functions. If so, we have to assume that their incoming
915 // arguments could be anything. If there are any internal functions in
916 // the universal node that we don't know about, we must iterate.
917 for (Node::iterator I = GraphNodes[UniversalSet].begin(),
918 E = GraphNodes[UniversalSet].end(); I != E; ++I)
919 if (Function *F = dyn_cast_or_null<Function>((*I)->getValue()))
920 if (F->hasInternalLinkage() &&
921 EscapingInternalFunctions.insert(F).second) {
922 // We found a function that is just now escaping. Mark it as if it
923 // didn't have internal linkage.
924 AddConstraintsForNonInternalLinkage(F);
925 DEBUG(std::cerr << "Found escaping internal function: "
926 << F->getName() << "\n");
927 ++NumEscapingFunctions;
928 }
929
930 // Check to see if we have discovered any new callees of the indirect call
931 // sites. If so, add constraints to the analysis.
932 for (unsigned i = 0, e = IndirectCalls.size(); i != e; ++i) {
933 CallSite CS = IndirectCalls[i];
934 std::vector<Function*> &KnownCallees = IndirectCallees[CS];
935 Node *CN = getNode(CS.getCalledValue());
936
937 for (Node::iterator NI = CN->begin(), E = CN->end(); NI != E; ++NI)
938 if (Function *F = dyn_cast_or_null<Function>((*NI)->getValue())) {
939 std::vector<Function*>::iterator IP =
940 std::lower_bound(KnownCallees.begin(), KnownCallees.end(), F);
941 if (IP == KnownCallees.end() || *IP != F) {
942 // Add the constraints for the call now.
943 AddConstraintsForCall(CS, F);
944 DEBUG(std::cerr << "Found actual callee '"
945 << F->getName() << "' for call: "
946 << *CS.getInstruction() << "\n");
947 ++NumIndirectCallees;
948 KnownCallees.insert(IP, F);
949 }
950 }
951 }
952 }
953 }
954}
955
956
957
958//===----------------------------------------------------------------------===//
959// Debugging Output
960//===----------------------------------------------------------------------===//
961
962void Andersens::PrintNode(Node *N) {
963 if (N == &GraphNodes[UniversalSet]) {
964 std::cerr << "<universal>";
965 return;
966 } else if (N == &GraphNodes[NullPtr]) {
967 std::cerr << "<nullptr>";
968 return;
969 } else if (N == &GraphNodes[NullObject]) {
970 std::cerr << "<null>";
971 return;
972 }
973
974 assert(N->getValue() != 0 && "Never set node label!");
975 Value *V = N->getValue();
976 if (Function *F = dyn_cast<Function>(V)) {
977 if (isa<PointerType>(F->getFunctionType()->getReturnType()) &&
978 N == getReturnNode(F)) {
979 std::cerr << F->getName() << ":retval";
980 return;
981 } else if (F->getFunctionType()->isVarArg() && N == getVarargNode(F)) {
982 std::cerr << F->getName() << ":vararg";
983 return;
984 }
985 }
986
987 if (Instruction *I = dyn_cast<Instruction>(V))
988 std::cerr << I->getParent()->getParent()->getName() << ":";
989 else if (Argument *Arg = dyn_cast<Argument>(V))
990 std::cerr << Arg->getParent()->getName() << ":";
991
992 if (V->hasName())
993 std::cerr << V->getName();
994 else
995 std::cerr << "(unnamed)";
996
997 if (isa<GlobalValue>(V) || isa<AllocationInst>(V))
998 if (N == getObject(V))
999 std::cerr << "<mem>";
1000}
1001
1002void Andersens::PrintConstraints() {
1003 std::cerr << "Constraints:\n";
1004 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1005 std::cerr << " #" << i << ": ";
1006 Constraint &C = Constraints[i];
1007 if (C.Type == Constraint::Store)
1008 std::cerr << "*";
1009 PrintNode(C.Dest);
1010 std::cerr << " = ";
1011 if (C.Type == Constraint::Load)
1012 std::cerr << "*";
1013 PrintNode(C.Src);
1014 std::cerr << "\n";
1015 }
1016}
1017
1018void Andersens::PrintPointsToGraph() {
1019 std::cerr << "Points-to graph:\n";
1020 for (unsigned i = 0, e = GraphNodes.size(); i != e; ++i) {
1021 Node *N = &GraphNodes[i];
1022 std::cerr << "[" << (N->end() - N->begin()) << "] ";
1023 PrintNode(N);
1024 std::cerr << "\t--> ";
1025 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I) {
1026 if (I != N->begin()) std::cerr << ", ";
1027 PrintNode(*I);
1028 }
1029 std::cerr << "\n";
1030 }
1031}