blob: 52b19194e1b0daae44b929f1218cb02b675802f4 [file] [log] [blame]
Chris Lattnerd28b0d72004-06-25 04:24:22 +00001//===- Andersens.cpp - Andersen's Interprocedural Alias Analysis ----------===//
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002//
Chris Lattnere995a2a2004-05-23 21:00:47 +00003// 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.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00007//
Chris Lattnere995a2a2004-05-23 21:00:47 +00008//===----------------------------------------------------------------------===//
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//
Chris Lattnerc7ca32b2004-06-05 20:12:36 +000044// Future Improvements:
45// This implementation of Andersen's algorithm is extremely slow. To make it
Misha Brukman2b37d7c2005-04-21 21:13:18 +000046// scale reasonably well, the inclusion constraints could be sorted (easy),
47// offline variable substitution would be a huge win (straight-forward), and
Chris Lattnerc7ca32b2004-06-05 20:12:36 +000048// online cycle elimination (trickier) might help as well.
49//
Chris Lattnere995a2a2004-05-23 21:00:47 +000050//===----------------------------------------------------------------------===//
51
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"
Reid Spencerd7d83db2007-02-05 23:42:17 +000058#include "llvm/Support/Compiler.h"
Chris Lattnere995a2a2004-05-23 21:00:47 +000059#include "llvm/Support/InstIterator.h"
60#include "llvm/Support/InstVisitor.h"
61#include "llvm/Analysis/AliasAnalysis.h"
Jeff Cohen534927d2005-01-08 22:01:16 +000062#include "llvm/Analysis/Passes.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000063#include "llvm/Support/Debug.h"
64#include "llvm/ADT/Statistic.h"
Chris Lattnere995a2a2004-05-23 21:00:47 +000065#include <set>
66using namespace llvm;
67
Chris Lattner3b27d682006-12-19 22:30:33 +000068STATISTIC(NumIters , "Number of iterations to reach convergence");
69STATISTIC(NumConstraints , "Number of constraints");
70STATISTIC(NumNodes , "Number of nodes");
71STATISTIC(NumEscapingFunctions, "Number of internal functions that escape");
72STATISTIC(NumIndirectCallees , "Number of indirect callees found");
Chris Lattnere995a2a2004-05-23 21:00:47 +000073
Chris Lattner3b27d682006-12-19 22:30:33 +000074namespace {
Reid Spencerd7d83db2007-02-05 23:42:17 +000075 class VISIBILITY_HIDDEN Andersens : public ModulePass, public AliasAnalysis,
76 private InstVisitor<Andersens> {
Chris Lattnere995a2a2004-05-23 21:00:47 +000077 /// Node class - This class is used to represent a memory object in the
78 /// program, and is the primitive used to build the points-to graph.
79 class Node {
80 std::vector<Node*> Pointees;
81 Value *Val;
82 public:
83 Node() : Val(0) {}
84 Node *setValue(Value *V) {
85 assert(Val == 0 && "Value already set for this node!");
86 Val = V;
87 return this;
88 }
89
90 /// getValue - Return the LLVM value corresponding to this node.
Chris Lattnerc3c9fd02005-03-28 04:03:52 +000091 ///
Chris Lattnere995a2a2004-05-23 21:00:47 +000092 Value *getValue() const { return Val; }
93
94 typedef std::vector<Node*>::const_iterator iterator;
95 iterator begin() const { return Pointees.begin(); }
96 iterator end() const { return Pointees.end(); }
97
98 /// addPointerTo - Add a pointer to the list of pointees of this node,
99 /// returning true if this caused a new pointer to be added, or false if
100 /// we already knew about the points-to relation.
101 bool addPointerTo(Node *N) {
102 std::vector<Node*>::iterator I = std::lower_bound(Pointees.begin(),
103 Pointees.end(),
104 N);
105 if (I != Pointees.end() && *I == N)
106 return false;
107 Pointees.insert(I, N);
108 return true;
109 }
110
111 /// intersects - Return true if the points-to set of this node intersects
112 /// with the points-to set of the specified node.
113 bool intersects(Node *N) const;
114
115 /// intersectsIgnoring - Return true if the points-to set of this node
116 /// intersects with the points-to set of the specified node on any nodes
117 /// except for the specified node to ignore.
118 bool intersectsIgnoring(Node *N, Node *Ignoring) const;
119
120 // Constraint application methods.
121 bool copyFrom(Node *N);
122 bool loadFrom(Node *N);
123 bool storeThrough(Node *N);
124 };
125
126 /// GraphNodes - This vector is populated as part of the object
127 /// identification stage of the analysis, which populates this vector with a
128 /// node for each memory object and fills in the ValueNodes map.
129 std::vector<Node> GraphNodes;
130
131 /// ValueNodes - This map indicates the Node that a particular Value* is
132 /// represented by. This contains entries for all pointers.
133 std::map<Value*, unsigned> ValueNodes;
134
135 /// ObjectNodes - This map contains entries for each memory object in the
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000136 /// program: globals, alloca's and mallocs.
Chris Lattnere995a2a2004-05-23 21:00:47 +0000137 std::map<Value*, unsigned> ObjectNodes;
138
139 /// ReturnNodes - This map contains an entry for each function in the
140 /// program that returns a value.
141 std::map<Function*, unsigned> ReturnNodes;
142
143 /// VarargNodes - This map contains the entry used to represent all pointers
144 /// passed through the varargs portion of a function call for a particular
145 /// function. An entry is not present in this map for functions that do not
146 /// take variable arguments.
147 std::map<Function*, unsigned> VarargNodes;
148
149 /// Constraint - Objects of this structure are used to represent the various
150 /// constraints identified by the algorithm. The constraints are 'copy',
151 /// for statements like "A = B", 'load' for statements like "A = *B", and
152 /// 'store' for statements like "*A = B".
153 struct Constraint {
154 enum ConstraintType { Copy, Load, Store } Type;
155 Node *Dest, *Src;
156
157 Constraint(ConstraintType Ty, Node *D, Node *S)
158 : Type(Ty), Dest(D), Src(S) {}
159 };
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000160
Chris Lattnere995a2a2004-05-23 21:00:47 +0000161 /// Constraints - This vector contains a list of all of the constraints
162 /// identified by the program.
163 std::vector<Constraint> Constraints;
164
165 /// EscapingInternalFunctions - This set contains all of the internal
166 /// functions that are found to escape from the program. If the address of
167 /// an internal function is passed to an external function or otherwise
168 /// escapes from the analyzed portion of the program, we must assume that
169 /// any pointer arguments can alias the universal node. This set keeps
170 /// track of those functions we are assuming to escape so far.
171 std::set<Function*> EscapingInternalFunctions;
172
173 /// IndirectCalls - This contains a list of all of the indirect call sites
174 /// in the program. Since the call graph is iteratively discovered, we may
175 /// need to add constraints to our graph as we find new targets of function
176 /// pointers.
177 std::vector<CallSite> IndirectCalls;
178
179 /// IndirectCallees - For each call site in the indirect calls list, keep
180 /// track of the callees that we have discovered so far. As the analysis
181 /// proceeds, more callees are discovered, until the call graph finally
182 /// stabilizes.
183 std::map<CallSite, std::vector<Function*> > IndirectCallees;
184
185 /// This enum defines the GraphNodes indices that correspond to important
186 /// fixed sets.
187 enum {
188 UniversalSet = 0,
189 NullPtr = 1,
Chris Lattnerd74ea2b2006-05-24 17:04:05 +0000190 NullObject = 2
Chris Lattnere995a2a2004-05-23 21:00:47 +0000191 };
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000192
Chris Lattnere995a2a2004-05-23 21:00:47 +0000193 public:
Chris Lattnerb12914b2004-09-20 04:48:05 +0000194 bool runOnModule(Module &M) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000195 InitializeAliasAnalysis(this);
196 IdentifyObjects(M);
197 CollectConstraints(M);
198 DEBUG(PrintConstraints());
199 SolveConstraints();
200 DEBUG(PrintPointsToGraph());
201
202 // Free the constraints list, as we don't need it to respond to alias
203 // requests.
204 ObjectNodes.clear();
205 ReturnNodes.clear();
206 VarargNodes.clear();
207 EscapingInternalFunctions.clear();
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000208 std::vector<Constraint>().swap(Constraints);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000209 return false;
210 }
211
212 void releaseMemory() {
213 // FIXME: Until we have transitively required passes working correctly,
214 // this cannot be enabled! Otherwise, using -count-aa with the pass
215 // causes memory to be freed too early. :(
216#if 0
217 // The memory objects and ValueNodes data structures at the only ones that
218 // are still live after construction.
219 std::vector<Node>().swap(GraphNodes);
220 ValueNodes.clear();
221#endif
222 }
223
224 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
225 AliasAnalysis::getAnalysisUsage(AU);
226 AU.setPreservesAll(); // Does not transform code
227 }
228
229 //------------------------------------------------
230 // Implement the AliasAnalysis API
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000231 //
Chris Lattnere995a2a2004-05-23 21:00:47 +0000232 AliasResult alias(const Value *V1, unsigned V1Size,
233 const Value *V2, unsigned V2Size);
Reid Spencer3a9ec242006-08-28 01:02:49 +0000234 virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
235 virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000236 void getMustAliases(Value *P, std::vector<Value*> &RetVals);
237 bool pointsToConstantMemory(const Value *P);
238
239 virtual void deleteValue(Value *V) {
240 ValueNodes.erase(V);
241 getAnalysis<AliasAnalysis>().deleteValue(V);
242 }
243
244 virtual void copyValue(Value *From, Value *To) {
245 ValueNodes[To] = ValueNodes[From];
246 getAnalysis<AliasAnalysis>().copyValue(From, To);
247 }
248
249 private:
250 /// getNode - Return the node corresponding to the specified pointer scalar.
251 ///
252 Node *getNode(Value *V) {
253 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattnerdf9b7bc2004-08-16 05:38:02 +0000254 if (!isa<GlobalValue>(C))
255 return getNodeForConstantPointer(C);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000256
257 std::map<Value*, unsigned>::iterator I = ValueNodes.find(V);
258 if (I == ValueNodes.end()) {
Jim Laskey16d42c62006-07-11 18:25:13 +0000259#ifndef NDEBUG
260 V->dump();
261#endif
Jim Laskeye37fe9b2006-07-11 17:58:07 +0000262 assert(0 && "Value does not have a node in the points-to graph!");
Chris Lattnere995a2a2004-05-23 21:00:47 +0000263 }
264 return &GraphNodes[I->second];
265 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000266
Chris Lattnere995a2a2004-05-23 21:00:47 +0000267 /// 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];
274 }
275
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];
282 }
283
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];
290 }
291
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);
296 }
297
298 void IdentifyObjects(Module &M);
299 void CollectConstraints(Module &M);
300 void SolveConstraints();
301
302 Node *getNodeForConstantPointer(Constant *C);
303 Node *getNodeForConstantPointerTarget(Constant *C);
304 void AddGlobalInitializerConstraints(Node *N, Constant *C);
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000305
Chris Lattnere995a2a2004-05-23 21:00:47 +0000306 void AddConstraintsForNonInternalLinkage(Function *F);
307 void AddConstraintsForCall(CallSite CS, Function *F);
Chris Lattner8a446432005-03-29 06:09:07 +0000308 bool AddConstraintsForExternalCall(CallSite CS, Function *F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000309
310
311 void PrintNode(Node *N);
312 void PrintConstraints();
313 void PrintPointsToGraph();
314
315 //===------------------------------------------------------------------===//
316 // Instruction visitation methods for adding constraints
317 //
318 friend class InstVisitor<Andersens>;
319 void visitReturnInst(ReturnInst &RI);
320 void visitInvokeInst(InvokeInst &II) { visitCallSite(CallSite(&II)); }
321 void visitCallInst(CallInst &CI) { visitCallSite(CallSite(&CI)); }
322 void visitCallSite(CallSite CS);
323 void visitAllocationInst(AllocationInst &AI);
324 void visitLoadInst(LoadInst &LI);
325 void visitStoreInst(StoreInst &SI);
326 void visitGetElementPtrInst(GetElementPtrInst &GEP);
327 void visitPHINode(PHINode &PN);
328 void visitCastInst(CastInst &CI);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000329 void visitICmpInst(ICmpInst &ICI) {} // NOOP!
330 void visitFCmpInst(FCmpInst &ICI) {} // NOOP!
Chris Lattnere995a2a2004-05-23 21:00:47 +0000331 void visitSelectInst(SelectInst &SI);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000332 void visitVAArg(VAArgInst &I);
333 void visitInstruction(Instruction &I);
334 };
335
Chris Lattner7f8897f2006-08-27 22:42:52 +0000336 RegisterPass<Andersens> X("anders-aa",
337 "Andersen's Interprocedural Alias Analysis");
Chris Lattnera5370172006-08-28 00:42:29 +0000338 RegisterAnalysisGroup<AliasAnalysis> Y(X);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000339}
340
Jeff Cohen534927d2005-01-08 22:01:16 +0000341ModulePass *llvm::createAndersensPass() { return new Andersens(); }
342
Chris Lattnere995a2a2004-05-23 21:00:47 +0000343//===----------------------------------------------------------------------===//
344// AliasAnalysis Interface Implementation
345//===----------------------------------------------------------------------===//
346
347AliasAnalysis::AliasResult Andersens::alias(const Value *V1, unsigned V1Size,
348 const Value *V2, unsigned V2Size) {
Chris Lattnerf392c642005-03-28 06:21:17 +0000349 Node *N1 = getNode(const_cast<Value*>(V1));
350 Node *N2 = getNode(const_cast<Value*>(V2));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000351
352 // Check to see if the two pointers are known to not alias. They don't alias
353 // if their points-to sets do not intersect.
354 if (!N1->intersectsIgnoring(N2, &GraphNodes[NullObject]))
355 return NoAlias;
356
357 return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
358}
359
Chris Lattnerf392c642005-03-28 06:21:17 +0000360AliasAnalysis::ModRefResult
361Andersens::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
362 // The only thing useful that we can contribute for mod/ref information is
363 // when calling external function calls: if we know that memory never escapes
364 // from the program, it cannot be modified by an external call.
365 //
366 // NOTE: This is not really safe, at least not when the entire program is not
367 // available. The deal is that the external function could call back into the
368 // program and modify stuff. We ignore this technical niggle for now. This
369 // is, after all, a "research quality" implementation of Andersen's analysis.
370 if (Function *F = CS.getCalledFunction())
Reid Spencer5cbf9852007-01-30 20:08:39 +0000371 if (F->isDeclaration()) {
Chris Lattnerf392c642005-03-28 06:21:17 +0000372 Node *N1 = getNode(P);
Chris Lattnerf392c642005-03-28 06:21:17 +0000373
Chris Lattner8a9763c2005-04-04 22:23:21 +0000374 if (N1->begin() == N1->end())
375 return NoModRef; // P doesn't point to anything.
Chris Lattnerf392c642005-03-28 06:21:17 +0000376
Chris Lattner8a9763c2005-04-04 22:23:21 +0000377 // Get the first pointee.
378 Node *FirstPointee = *N1->begin();
379 if (FirstPointee != &GraphNodes[UniversalSet])
Chris Lattnerf392c642005-03-28 06:21:17 +0000380 return NoModRef; // P doesn't point to the universal set.
381 }
382
383 return AliasAnalysis::getModRefInfo(CS, P, Size);
384}
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000385
Reid Spencer3a9ec242006-08-28 01:02:49 +0000386AliasAnalysis::ModRefResult
387Andersens::getModRefInfo(CallSite CS1, CallSite CS2) {
388 return AliasAnalysis::getModRefInfo(CS1,CS2);
389}
390
Chris Lattnere995a2a2004-05-23 21:00:47 +0000391/// getMustAlias - We can provide must alias information if we know that a
392/// pointer can only point to a specific function or the null pointer.
393/// Unfortunately we cannot determine must-alias information for global
394/// variables or any other memory memory objects because we do not track whether
395/// a pointer points to the beginning of an object or a field of it.
396void Andersens::getMustAliases(Value *P, std::vector<Value*> &RetVals) {
397 Node *N = getNode(P);
398 Node::iterator I = N->begin();
399 if (I != N->end()) {
400 // If there is exactly one element in the points-to set for the object...
401 ++I;
402 if (I == N->end()) {
403 Node *Pointee = *N->begin();
404
405 // If a function is the only object in the points-to set, then it must be
406 // the destination. Note that we can't handle global variables here,
407 // because we don't know if the pointer is actually pointing to a field of
408 // the global or to the beginning of it.
409 if (Value *V = Pointee->getValue()) {
410 if (Function *F = dyn_cast<Function>(V))
411 RetVals.push_back(F);
412 } else {
413 // If the object in the points-to set is the null object, then the null
414 // pointer is a must alias.
415 if (Pointee == &GraphNodes[NullObject])
416 RetVals.push_back(Constant::getNullValue(P->getType()));
417 }
418 }
419 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000420
Chris Lattnere995a2a2004-05-23 21:00:47 +0000421 AliasAnalysis::getMustAliases(P, RetVals);
422}
423
424/// pointsToConstantMemory - If we can determine that this pointer only points
425/// to constant memory, return true. In practice, this means that if the
426/// pointer can only point to constant globals, functions, or the null pointer,
427/// return true.
428///
429bool Andersens::pointsToConstantMemory(const Value *P) {
430 Node *N = getNode((Value*)P);
431 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I) {
432 if (Value *V = (*I)->getValue()) {
433 if (!isa<GlobalValue>(V) || (isa<GlobalVariable>(V) &&
434 !cast<GlobalVariable>(V)->isConstant()))
435 return AliasAnalysis::pointsToConstantMemory(P);
436 } else {
437 if (*I != &GraphNodes[NullObject])
438 return AliasAnalysis::pointsToConstantMemory(P);
439 }
440 }
441
442 return true;
443}
444
445//===----------------------------------------------------------------------===//
446// Object Identification Phase
447//===----------------------------------------------------------------------===//
448
449/// IdentifyObjects - This stage scans the program, adding an entry to the
450/// GraphNodes list for each memory object in the program (global stack or
451/// heap), and populates the ValueNodes and ObjectNodes maps for these objects.
452///
453void Andersens::IdentifyObjects(Module &M) {
454 unsigned NumObjects = 0;
455
456 // Object #0 is always the universal set: the object that we don't know
457 // anything about.
458 assert(NumObjects == UniversalSet && "Something changed!");
459 ++NumObjects;
460
461 // Object #1 always represents the null pointer.
462 assert(NumObjects == NullPtr && "Something changed!");
463 ++NumObjects;
464
465 // Object #2 always represents the null object (the object pointed to by null)
466 assert(NumObjects == NullObject && "Something changed!");
467 ++NumObjects;
468
469 // Add all the globals first.
Chris Lattner493f6362005-03-27 22:03:46 +0000470 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
471 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000472 ObjectNodes[I] = NumObjects++;
473 ValueNodes[I] = NumObjects++;
474 }
475
476 // Add nodes for all of the functions and the instructions inside of them.
477 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
478 // The function itself is a memory object.
479 ValueNodes[F] = NumObjects++;
480 ObjectNodes[F] = NumObjects++;
481 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
482 ReturnNodes[F] = NumObjects++;
483 if (F->getFunctionType()->isVarArg())
484 VarargNodes[F] = NumObjects++;
485
486 // Add nodes for all of the incoming pointer arguments.
Chris Lattner493f6362005-03-27 22:03:46 +0000487 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
488 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000489 if (isa<PointerType>(I->getType()))
490 ValueNodes[I] = NumObjects++;
491
492 // Scan the function body, creating a memory object for each heap/stack
493 // allocation in the body of the function and a node to represent all
494 // pointer values defined by instructions and used as operands.
495 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
496 // If this is an heap or stack allocation, create a node for the memory
497 // object.
498 if (isa<PointerType>(II->getType())) {
499 ValueNodes[&*II] = NumObjects++;
500 if (AllocationInst *AI = dyn_cast<AllocationInst>(&*II))
501 ObjectNodes[AI] = NumObjects++;
502 }
503 }
504 }
505
506 // Now that we know how many objects to create, make them all now!
507 GraphNodes.resize(NumObjects);
508 NumNodes += NumObjects;
509}
510
511//===----------------------------------------------------------------------===//
512// Constraint Identification Phase
513//===----------------------------------------------------------------------===//
514
515/// getNodeForConstantPointer - Return the node corresponding to the constant
516/// pointer itself.
517Andersens::Node *Andersens::getNodeForConstantPointer(Constant *C) {
518 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
519
Chris Lattner267a1b02005-03-27 18:58:23 +0000520 if (isa<ConstantPointerNull>(C) || isa<UndefValue>(C))
Chris Lattnere995a2a2004-05-23 21:00:47 +0000521 return &GraphNodes[NullPtr];
Reid Spencere8404342004-07-18 00:18:30 +0000522 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
523 return getNode(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000524 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
525 switch (CE->getOpcode()) {
526 case Instruction::GetElementPtr:
527 return getNodeForConstantPointer(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000528 case Instruction::IntToPtr:
529 return &GraphNodes[UniversalSet];
530 case Instruction::BitCast:
531 return getNodeForConstantPointer(CE->getOperand(0));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000532 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000533 cerr << "Constant Expr not yet handled: " << *CE << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +0000534 assert(0);
535 }
536 } else {
537 assert(0 && "Unknown constant pointer!");
538 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000539 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000540}
541
542/// getNodeForConstantPointerTarget - Return the node POINTED TO by the
543/// specified constant pointer.
544Andersens::Node *Andersens::getNodeForConstantPointerTarget(Constant *C) {
545 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
546
547 if (isa<ConstantPointerNull>(C))
548 return &GraphNodes[NullObject];
Reid Spencere8404342004-07-18 00:18:30 +0000549 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
550 return getObject(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000551 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
552 switch (CE->getOpcode()) {
553 case Instruction::GetElementPtr:
554 return getNodeForConstantPointerTarget(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000555 case Instruction::IntToPtr:
556 return &GraphNodes[UniversalSet];
557 case Instruction::BitCast:
558 return getNodeForConstantPointerTarget(CE->getOperand(0));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000559 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000560 cerr << "Constant Expr not yet handled: " << *CE << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +0000561 assert(0);
562 }
563 } else {
564 assert(0 && "Unknown constant pointer!");
565 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000566 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000567}
568
569/// AddGlobalInitializerConstraints - Add inclusion constraints for the memory
570/// object N, which contains values indicated by C.
571void Andersens::AddGlobalInitializerConstraints(Node *N, Constant *C) {
572 if (C->getType()->isFirstClassType()) {
573 if (isa<PointerType>(C->getType()))
Chris Lattner76bc5ce2005-03-29 17:21:53 +0000574 N->copyFrom(getNodeForConstantPointer(C));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000575
Chris Lattnere995a2a2004-05-23 21:00:47 +0000576 } else if (C->isNullValue()) {
577 N->addPointerTo(&GraphNodes[NullObject]);
578 return;
Chris Lattner8a446432005-03-29 06:09:07 +0000579 } else if (!isa<UndefValue>(C)) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000580 // If this is an array or struct, include constraints for each element.
581 assert(isa<ConstantArray>(C) || isa<ConstantStruct>(C));
582 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
583 AddGlobalInitializerConstraints(N, cast<Constant>(C->getOperand(i)));
584 }
585}
586
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000587/// AddConstraintsForNonInternalLinkage - If this function does not have
588/// internal linkage, realize that we can't trust anything passed into or
589/// returned by this function.
Chris Lattnere995a2a2004-05-23 21:00:47 +0000590void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
Chris Lattnere4d5c442005-03-15 04:54:21 +0000591 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000592 if (isa<PointerType>(I->getType()))
593 // If this is an argument of an externally accessible function, the
594 // incoming pointer might point to anything.
595 Constraints.push_back(Constraint(Constraint::Copy, getNode(I),
596 &GraphNodes[UniversalSet]));
597}
598
Chris Lattner8a446432005-03-29 06:09:07 +0000599/// AddConstraintsForCall - If this is a call to a "known" function, add the
600/// constraints and return true. If this is a call to an unknown function,
601/// return false.
602bool Andersens::AddConstraintsForExternalCall(CallSite CS, Function *F) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000603 assert(F->isDeclaration() && "Not an external function!");
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000604
605 // These functions don't induce any points-to constraints.
Chris Lattner175b9632005-03-29 20:36:05 +0000606 if (F->getName() == "atoi" || F->getName() == "atof" ||
607 F->getName() == "atol" || F->getName() == "atoll" ||
608 F->getName() == "remove" || F->getName() == "unlink" ||
609 F->getName() == "rename" || F->getName() == "memcmp" ||
Chris Lattner01ac91e2006-03-03 01:21:36 +0000610 F->getName() == "llvm.memset.i32" ||
611 F->getName() == "llvm.memset.i64" ||
Chris Lattner175b9632005-03-29 20:36:05 +0000612 F->getName() == "strcmp" || F->getName() == "strncmp" ||
613 F->getName() == "execl" || F->getName() == "execlp" ||
614 F->getName() == "execle" || F->getName() == "execv" ||
615 F->getName() == "execvp" || F->getName() == "chmod" ||
616 F->getName() == "puts" || F->getName() == "write" ||
617 F->getName() == "open" || F->getName() == "create" ||
618 F->getName() == "truncate" || F->getName() == "chdir" ||
619 F->getName() == "mkdir" || F->getName() == "rmdir" ||
620 F->getName() == "read" || F->getName() == "pipe" ||
621 F->getName() == "wait" || F->getName() == "time" ||
622 F->getName() == "stat" || F->getName() == "fstat" ||
623 F->getName() == "lstat" || F->getName() == "strtod" ||
624 F->getName() == "strtof" || F->getName() == "strtold" ||
625 F->getName() == "fopen" || F->getName() == "fdopen" ||
626 F->getName() == "freopen" ||
627 F->getName() == "fflush" || F->getName() == "feof" ||
628 F->getName() == "fileno" || F->getName() == "clearerr" ||
629 F->getName() == "rewind" || F->getName() == "ftell" ||
630 F->getName() == "ferror" || F->getName() == "fgetc" ||
631 F->getName() == "fgetc" || F->getName() == "_IO_getc" ||
632 F->getName() == "fwrite" || F->getName() == "fread" ||
633 F->getName() == "fgets" || F->getName() == "ungetc" ||
634 F->getName() == "fputc" ||
635 F->getName() == "fputs" || F->getName() == "putc" ||
636 F->getName() == "ftell" || F->getName() == "rewind" ||
637 F->getName() == "_IO_putc" || F->getName() == "fseek" ||
638 F->getName() == "fgetpos" || F->getName() == "fsetpos" ||
639 F->getName() == "printf" || F->getName() == "fprintf" ||
640 F->getName() == "sprintf" || F->getName() == "vprintf" ||
641 F->getName() == "vfprintf" || F->getName() == "vsprintf" ||
642 F->getName() == "scanf" || F->getName() == "fscanf" ||
643 F->getName() == "sscanf" || F->getName() == "__assert_fail" ||
644 F->getName() == "modf")
Chris Lattner8a446432005-03-29 06:09:07 +0000645 return true;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000646
Chris Lattner175b9632005-03-29 20:36:05 +0000647
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000648 // These functions do induce points-to edges.
Chris Lattner01ac91e2006-03-03 01:21:36 +0000649 if (F->getName() == "llvm.memcpy.i32" || F->getName() == "llvm.memcpy.i64" ||
650 F->getName() == "llvm.memmove.i32" ||F->getName() == "llvm.memmove.i64" ||
Chris Lattner4de57fd2005-03-29 06:52:20 +0000651 F->getName() == "memmove") {
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000652 // Note: this is a poor approximation, this says Dest = Src, instead of
653 // *Dest = *Src.
Chris Lattner8a446432005-03-29 06:09:07 +0000654 Constraints.push_back(Constraint(Constraint::Copy,
655 getNode(CS.getArgument(0)),
656 getNode(CS.getArgument(1))));
657 return true;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000658 }
659
Chris Lattner77b50562005-03-29 20:04:24 +0000660 // Result = Arg0
661 if (F->getName() == "realloc" || F->getName() == "strchr" ||
662 F->getName() == "strrchr" || F->getName() == "strstr" ||
663 F->getName() == "strtok") {
Chris Lattner8a446432005-03-29 06:09:07 +0000664 Constraints.push_back(Constraint(Constraint::Copy,
665 getNode(CS.getInstruction()),
666 getNode(CS.getArgument(0))));
667 return true;
668 }
669
670 return false;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000671}
672
673
Chris Lattnere995a2a2004-05-23 21:00:47 +0000674
675/// CollectConstraints - This stage scans the program, adding a constraint to
676/// the Constraints list for each instruction in the program that induces a
677/// constraint, and setting up the initial points-to graph.
678///
679void Andersens::CollectConstraints(Module &M) {
680 // First, the universal set points to itself.
681 GraphNodes[UniversalSet].addPointerTo(&GraphNodes[UniversalSet]);
Chris Lattner4de57fd2005-03-29 06:52:20 +0000682 //Constraints.push_back(Constraint(Constraint::Load, &GraphNodes[UniversalSet],
683 // &GraphNodes[UniversalSet]));
Chris Lattnerf392c642005-03-28 06:21:17 +0000684 Constraints.push_back(Constraint(Constraint::Store, &GraphNodes[UniversalSet],
685 &GraphNodes[UniversalSet]));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000686
687 // Next, the null pointer points to the null object.
688 GraphNodes[NullPtr].addPointerTo(&GraphNodes[NullObject]);
689
690 // Next, add any constraints on global variables and their initializers.
Chris Lattner493f6362005-03-27 22:03:46 +0000691 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
692 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000693 // Associate the address of the global object as pointing to the memory for
694 // the global: &G = <G memory>
695 Node *Object = getObject(I);
696 Object->setValue(I);
697 getNodeValue(*I)->addPointerTo(Object);
698
699 if (I->hasInitializer()) {
700 AddGlobalInitializerConstraints(Object, I->getInitializer());
701 } else {
702 // If it doesn't have an initializer (i.e. it's defined in another
703 // translation unit), it points to the universal set.
704 Constraints.push_back(Constraint(Constraint::Copy, Object,
705 &GraphNodes[UniversalSet]));
706 }
707 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000708
Chris Lattnere995a2a2004-05-23 21:00:47 +0000709 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
710 // Make the function address point to the function object.
711 getNodeValue(*F)->addPointerTo(getObject(F)->setValue(F));
712
713 // Set up the return value node.
714 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
715 getReturnNode(F)->setValue(F);
716 if (F->getFunctionType()->isVarArg())
717 getVarargNode(F)->setValue(F);
718
719 // Set up incoming argument nodes.
Chris Lattner493f6362005-03-27 22:03:46 +0000720 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
721 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000722 if (isa<PointerType>(I->getType()))
723 getNodeValue(*I);
724
725 if (!F->hasInternalLinkage())
726 AddConstraintsForNonInternalLinkage(F);
727
Reid Spencer5cbf9852007-01-30 20:08:39 +0000728 if (!F->isDeclaration()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000729 // Scan the function body, creating a memory object for each heap/stack
730 // allocation in the body of the function and a node to represent all
731 // pointer values defined by instructions and used as operands.
732 visit(F);
Chris Lattner8a446432005-03-29 06:09:07 +0000733 } else {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000734 // External functions that return pointers return the universal set.
735 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
736 Constraints.push_back(Constraint(Constraint::Copy,
737 getReturnNode(F),
738 &GraphNodes[UniversalSet]));
739
740 // Any pointers that are passed into the function have the universal set
741 // stored into them.
Chris Lattner493f6362005-03-27 22:03:46 +0000742 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
743 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000744 if (isa<PointerType>(I->getType())) {
745 // Pointers passed into external functions could have anything stored
746 // through them.
747 Constraints.push_back(Constraint(Constraint::Store, getNode(I),
748 &GraphNodes[UniversalSet]));
749 // Memory objects passed into external function calls can have the
750 // universal set point to them.
751 Constraints.push_back(Constraint(Constraint::Copy,
752 &GraphNodes[UniversalSet],
753 getNode(I)));
754 }
755
756 // If this is an external varargs function, it can also store pointers
757 // into any pointers passed through the varargs section.
758 if (F->getFunctionType()->isVarArg())
759 Constraints.push_back(Constraint(Constraint::Store, getVarargNode(F),
760 &GraphNodes[UniversalSet]));
761 }
762 }
763 NumConstraints += Constraints.size();
764}
765
766
767void Andersens::visitInstruction(Instruction &I) {
768#ifdef NDEBUG
769 return; // This function is just a big assert.
770#endif
771 if (isa<BinaryOperator>(I))
772 return;
773 // Most instructions don't have any effect on pointer values.
774 switch (I.getOpcode()) {
775 case Instruction::Br:
776 case Instruction::Switch:
777 case Instruction::Unwind:
Chris Lattnerc17edbd2004-10-16 18:16:19 +0000778 case Instruction::Unreachable:
Chris Lattnere995a2a2004-05-23 21:00:47 +0000779 case Instruction::Free:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000780 case Instruction::ICmp:
781 case Instruction::FCmp:
Chris Lattnere995a2a2004-05-23 21:00:47 +0000782 return;
783 default:
784 // Is this something we aren't handling yet?
Bill Wendlinge8156192006-12-07 01:30:32 +0000785 cerr << "Unknown instruction: " << I;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000786 abort();
787 }
788}
789
790void Andersens::visitAllocationInst(AllocationInst &AI) {
791 getNodeValue(AI)->addPointerTo(getObject(&AI)->setValue(&AI));
792}
793
794void Andersens::visitReturnInst(ReturnInst &RI) {
795 if (RI.getNumOperands() && isa<PointerType>(RI.getOperand(0)->getType()))
796 // return V --> <Copy/retval{F}/v>
797 Constraints.push_back(Constraint(Constraint::Copy,
798 getReturnNode(RI.getParent()->getParent()),
799 getNode(RI.getOperand(0))));
800}
801
802void Andersens::visitLoadInst(LoadInst &LI) {
803 if (isa<PointerType>(LI.getType()))
804 // P1 = load P2 --> <Load/P1/P2>
805 Constraints.push_back(Constraint(Constraint::Load, getNodeValue(LI),
806 getNode(LI.getOperand(0))));
807}
808
809void Andersens::visitStoreInst(StoreInst &SI) {
810 if (isa<PointerType>(SI.getOperand(0)->getType()))
811 // store P1, P2 --> <Store/P2/P1>
812 Constraints.push_back(Constraint(Constraint::Store,
813 getNode(SI.getOperand(1)),
814 getNode(SI.getOperand(0))));
815}
816
817void Andersens::visitGetElementPtrInst(GetElementPtrInst &GEP) {
818 // P1 = getelementptr P2, ... --> <Copy/P1/P2>
819 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(GEP),
820 getNode(GEP.getOperand(0))));
821}
822
823void Andersens::visitPHINode(PHINode &PN) {
824 if (isa<PointerType>(PN.getType())) {
825 Node *PNN = getNodeValue(PN);
826 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
827 // P1 = phi P2, P3 --> <Copy/P1/P2>, <Copy/P1/P3>, ...
828 Constraints.push_back(Constraint(Constraint::Copy, PNN,
829 getNode(PN.getIncomingValue(i))));
830 }
831}
832
833void Andersens::visitCastInst(CastInst &CI) {
834 Value *Op = CI.getOperand(0);
835 if (isa<PointerType>(CI.getType())) {
836 if (isa<PointerType>(Op->getType())) {
837 // P1 = cast P2 --> <Copy/P1/P2>
838 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
839 getNode(CI.getOperand(0))));
840 } else {
841 // P1 = cast int --> <Copy/P1/Univ>
Chris Lattner175b9632005-03-29 20:36:05 +0000842#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +0000843 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
844 &GraphNodes[UniversalSet]));
Chris Lattnerbd135c72005-04-05 01:12:03 +0000845#else
846 getNodeValue(CI);
Chris Lattner175b9632005-03-29 20:36:05 +0000847#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +0000848 }
849 } else if (isa<PointerType>(Op->getType())) {
850 // int = cast P1 --> <Copy/Univ/P1>
Chris Lattner175b9632005-03-29 20:36:05 +0000851#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +0000852 Constraints.push_back(Constraint(Constraint::Copy,
853 &GraphNodes[UniversalSet],
854 getNode(CI.getOperand(0))));
Chris Lattnerbd135c72005-04-05 01:12:03 +0000855#else
856 getNode(CI.getOperand(0));
Chris Lattner175b9632005-03-29 20:36:05 +0000857#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +0000858 }
859}
860
861void Andersens::visitSelectInst(SelectInst &SI) {
862 if (isa<PointerType>(SI.getType())) {
863 Node *SIN = getNodeValue(SI);
864 // P1 = select C, P2, P3 ---> <Copy/P1/P2>, <Copy/P1/P3>
865 Constraints.push_back(Constraint(Constraint::Copy, SIN,
866 getNode(SI.getOperand(1))));
867 Constraints.push_back(Constraint(Constraint::Copy, SIN,
868 getNode(SI.getOperand(2))));
869 }
870}
871
Chris Lattnere995a2a2004-05-23 21:00:47 +0000872void Andersens::visitVAArg(VAArgInst &I) {
873 assert(0 && "vaarg not handled yet!");
874}
875
876/// AddConstraintsForCall - Add constraints for a call with actual arguments
877/// specified by CS to the function specified by F. Note that the types of
878/// arguments might not match up in the case where this is an indirect call and
879/// the function pointer has been casted. If this is the case, do something
880/// reasonable.
881void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
Chris Lattner8a446432005-03-29 06:09:07 +0000882 // If this is a call to an external function, handle it directly to get some
883 // taste of context sensitivity.
Reid Spencer5cbf9852007-01-30 20:08:39 +0000884 if (F->isDeclaration() && AddConstraintsForExternalCall(CS, F))
Chris Lattner8a446432005-03-29 06:09:07 +0000885 return;
886
Chris Lattnere995a2a2004-05-23 21:00:47 +0000887 if (isa<PointerType>(CS.getType())) {
888 Node *CSN = getNode(CS.getInstruction());
889 if (isa<PointerType>(F->getFunctionType()->getReturnType())) {
890 Constraints.push_back(Constraint(Constraint::Copy, CSN,
891 getReturnNode(F)));
892 } else {
893 // If the function returns a non-pointer value, handle this just like we
894 // treat a nonpointer cast to pointer.
895 Constraints.push_back(Constraint(Constraint::Copy, CSN,
896 &GraphNodes[UniversalSet]));
897 }
898 } else if (isa<PointerType>(F->getFunctionType()->getReturnType())) {
899 Constraints.push_back(Constraint(Constraint::Copy,
900 &GraphNodes[UniversalSet],
901 getReturnNode(F)));
902 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000903
Chris Lattnere4d5c442005-03-15 04:54:21 +0000904 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
Chris Lattnere995a2a2004-05-23 21:00:47 +0000905 CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
906 for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI)
907 if (isa<PointerType>(AI->getType())) {
908 if (isa<PointerType>((*ArgI)->getType())) {
909 // Copy the actual argument into the formal argument.
910 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
911 getNode(*ArgI)));
912 } else {
913 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
914 &GraphNodes[UniversalSet]));
915 }
916 } else if (isa<PointerType>((*ArgI)->getType())) {
917 Constraints.push_back(Constraint(Constraint::Copy,
918 &GraphNodes[UniversalSet],
919 getNode(*ArgI)));
920 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000921
Chris Lattnere995a2a2004-05-23 21:00:47 +0000922 // Copy all pointers passed through the varargs section to the varargs node.
923 if (F->getFunctionType()->isVarArg())
924 for (; ArgI != ArgE; ++ArgI)
925 if (isa<PointerType>((*ArgI)->getType()))
926 Constraints.push_back(Constraint(Constraint::Copy, getVarargNode(F),
927 getNode(*ArgI)));
928 // If more arguments are passed in than we track, just drop them on the floor.
929}
930
931void Andersens::visitCallSite(CallSite CS) {
932 if (isa<PointerType>(CS.getType()))
933 getNodeValue(*CS.getInstruction());
934
935 if (Function *F = CS.getCalledFunction()) {
936 AddConstraintsForCall(CS, F);
937 } else {
938 // We don't handle indirect call sites yet. Keep track of them for when we
939 // discover the call graph incrementally.
940 IndirectCalls.push_back(CS);
941 }
942}
943
944//===----------------------------------------------------------------------===//
945// Constraint Solving Phase
946//===----------------------------------------------------------------------===//
947
948/// intersects - Return true if the points-to set of this node intersects
949/// with the points-to set of the specified node.
950bool Andersens::Node::intersects(Node *N) const {
951 iterator I1 = begin(), I2 = N->begin(), E1 = end(), E2 = N->end();
952 while (I1 != E1 && I2 != E2) {
953 if (*I1 == *I2) return true;
954 if (*I1 < *I2)
955 ++I1;
956 else
957 ++I2;
958 }
959 return false;
960}
961
962/// intersectsIgnoring - Return true if the points-to set of this node
963/// intersects with the points-to set of the specified node on any nodes
964/// except for the specified node to ignore.
965bool Andersens::Node::intersectsIgnoring(Node *N, Node *Ignoring) const {
966 iterator I1 = begin(), I2 = N->begin(), E1 = end(), E2 = N->end();
967 while (I1 != E1 && I2 != E2) {
968 if (*I1 == *I2) {
969 if (*I1 != Ignoring) return true;
970 ++I1; ++I2;
971 } else if (*I1 < *I2)
972 ++I1;
973 else
974 ++I2;
975 }
976 return false;
977}
978
979// Copy constraint: all edges out of the source node get copied to the
980// destination node. This returns true if a change is made.
981bool Andersens::Node::copyFrom(Node *N) {
982 // Use a mostly linear-time merge since both of the lists are sorted.
983 bool Changed = false;
984 iterator I = N->begin(), E = N->end();
985 unsigned i = 0;
986 while (I != E && i != Pointees.size()) {
987 if (Pointees[i] < *I) {
988 ++i;
989 } else if (Pointees[i] == *I) {
990 ++i; ++I;
991 } else {
992 // We found a new element to copy over.
993 Changed = true;
994 Pointees.insert(Pointees.begin()+i, *I);
995 ++i; ++I;
996 }
997 }
998
999 if (I != E) {
1000 Pointees.insert(Pointees.end(), I, E);
1001 Changed = true;
1002 }
1003
1004 return Changed;
1005}
1006
1007bool Andersens::Node::loadFrom(Node *N) {
1008 bool Changed = false;
1009 for (iterator I = N->begin(), E = N->end(); I != E; ++I)
1010 Changed |= copyFrom(*I);
1011 return Changed;
1012}
1013
1014bool Andersens::Node::storeThrough(Node *N) {
1015 bool Changed = false;
1016 for (iterator I = begin(), E = end(); I != E; ++I)
1017 Changed |= (*I)->copyFrom(N);
1018 return Changed;
1019}
1020
1021
1022/// SolveConstraints - This stage iteratively processes the constraints list
1023/// propagating constraints (adding edges to the Nodes in the points-to graph)
1024/// until a fixed point is reached.
1025///
1026void Andersens::SolveConstraints() {
1027 bool Changed = true;
1028 unsigned Iteration = 0;
1029 while (Changed) {
1030 Changed = false;
1031 ++NumIters;
Bill Wendling9be7ac12006-11-17 07:36:54 +00001032 DOUT << "Starting iteration #" << Iteration++ << "!\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001033
1034 // Loop over all of the constraints, applying them in turn.
1035 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1036 Constraint &C = Constraints[i];
1037 switch (C.Type) {
1038 case Constraint::Copy:
1039 Changed |= C.Dest->copyFrom(C.Src);
1040 break;
1041 case Constraint::Load:
1042 Changed |= C.Dest->loadFrom(C.Src);
1043 break;
1044 case Constraint::Store:
1045 Changed |= C.Dest->storeThrough(C.Src);
1046 break;
1047 default:
1048 assert(0 && "Unknown constraint!");
1049 }
1050 }
1051
1052 if (Changed) {
1053 // Check to see if any internal function's addresses have been passed to
1054 // external functions. If so, we have to assume that their incoming
1055 // arguments could be anything. If there are any internal functions in
1056 // the universal node that we don't know about, we must iterate.
1057 for (Node::iterator I = GraphNodes[UniversalSet].begin(),
1058 E = GraphNodes[UniversalSet].end(); I != E; ++I)
1059 if (Function *F = dyn_cast_or_null<Function>((*I)->getValue()))
1060 if (F->hasInternalLinkage() &&
1061 EscapingInternalFunctions.insert(F).second) {
1062 // We found a function that is just now escaping. Mark it as if it
1063 // didn't have internal linkage.
1064 AddConstraintsForNonInternalLinkage(F);
Bill Wendling9be7ac12006-11-17 07:36:54 +00001065 DOUT << "Found escaping internal function: " << F->getName() <<"\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001066 ++NumEscapingFunctions;
1067 }
1068
1069 // Check to see if we have discovered any new callees of the indirect call
1070 // sites. If so, add constraints to the analysis.
1071 for (unsigned i = 0, e = IndirectCalls.size(); i != e; ++i) {
1072 CallSite CS = IndirectCalls[i];
1073 std::vector<Function*> &KnownCallees = IndirectCallees[CS];
1074 Node *CN = getNode(CS.getCalledValue());
1075
1076 for (Node::iterator NI = CN->begin(), E = CN->end(); NI != E; ++NI)
1077 if (Function *F = dyn_cast_or_null<Function>((*NI)->getValue())) {
1078 std::vector<Function*>::iterator IP =
1079 std::lower_bound(KnownCallees.begin(), KnownCallees.end(), F);
1080 if (IP == KnownCallees.end() || *IP != F) {
1081 // Add the constraints for the call now.
1082 AddConstraintsForCall(CS, F);
Bill Wendling9be7ac12006-11-17 07:36:54 +00001083 DOUT << "Found actual callee '"
1084 << F->getName() << "' for call: "
1085 << *CS.getInstruction() << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001086 ++NumIndirectCallees;
1087 KnownCallees.insert(IP, F);
1088 }
1089 }
1090 }
1091 }
1092 }
1093}
1094
1095
1096
1097//===----------------------------------------------------------------------===//
1098// Debugging Output
1099//===----------------------------------------------------------------------===//
1100
1101void Andersens::PrintNode(Node *N) {
1102 if (N == &GraphNodes[UniversalSet]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00001103 cerr << "<universal>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001104 return;
1105 } else if (N == &GraphNodes[NullPtr]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00001106 cerr << "<nullptr>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001107 return;
1108 } else if (N == &GraphNodes[NullObject]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00001109 cerr << "<null>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001110 return;
1111 }
1112
1113 assert(N->getValue() != 0 && "Never set node label!");
1114 Value *V = N->getValue();
1115 if (Function *F = dyn_cast<Function>(V)) {
1116 if (isa<PointerType>(F->getFunctionType()->getReturnType()) &&
1117 N == getReturnNode(F)) {
Bill Wendlinge8156192006-12-07 01:30:32 +00001118 cerr << F->getName() << ":retval";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001119 return;
1120 } else if (F->getFunctionType()->isVarArg() && N == getVarargNode(F)) {
Bill Wendlinge8156192006-12-07 01:30:32 +00001121 cerr << F->getName() << ":vararg";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001122 return;
1123 }
1124 }
1125
1126 if (Instruction *I = dyn_cast<Instruction>(V))
Bill Wendlinge8156192006-12-07 01:30:32 +00001127 cerr << I->getParent()->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001128 else if (Argument *Arg = dyn_cast<Argument>(V))
Bill Wendlinge8156192006-12-07 01:30:32 +00001129 cerr << Arg->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001130
1131 if (V->hasName())
Bill Wendlinge8156192006-12-07 01:30:32 +00001132 cerr << V->getName();
Chris Lattnere995a2a2004-05-23 21:00:47 +00001133 else
Bill Wendlinge8156192006-12-07 01:30:32 +00001134 cerr << "(unnamed)";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001135
1136 if (isa<GlobalValue>(V) || isa<AllocationInst>(V))
1137 if (N == getObject(V))
Bill Wendlinge8156192006-12-07 01:30:32 +00001138 cerr << "<mem>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001139}
1140
1141void Andersens::PrintConstraints() {
Bill Wendlinge8156192006-12-07 01:30:32 +00001142 cerr << "Constraints:\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001143 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Bill Wendlinge8156192006-12-07 01:30:32 +00001144 cerr << " #" << i << ": ";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001145 Constraint &C = Constraints[i];
1146 if (C.Type == Constraint::Store)
Bill Wendlinge8156192006-12-07 01:30:32 +00001147 cerr << "*";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001148 PrintNode(C.Dest);
Bill Wendlinge8156192006-12-07 01:30:32 +00001149 cerr << " = ";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001150 if (C.Type == Constraint::Load)
Bill Wendlinge8156192006-12-07 01:30:32 +00001151 cerr << "*";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001152 PrintNode(C.Src);
Bill Wendlinge8156192006-12-07 01:30:32 +00001153 cerr << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001154 }
1155}
1156
1157void Andersens::PrintPointsToGraph() {
Bill Wendlinge8156192006-12-07 01:30:32 +00001158 cerr << "Points-to graph:\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001159 for (unsigned i = 0, e = GraphNodes.size(); i != e; ++i) {
1160 Node *N = &GraphNodes[i];
Bill Wendlinge8156192006-12-07 01:30:32 +00001161 cerr << "[" << (N->end() - N->begin()) << "] ";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001162 PrintNode(N);
Bill Wendlinge8156192006-12-07 01:30:32 +00001163 cerr << "\t--> ";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001164 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I) {
Bill Wendlinge8156192006-12-07 01:30:32 +00001165 if (I != N->begin()) cerr << ", ";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001166 PrintNode(*I);
1167 }
Bill Wendlinge8156192006-12-07 01:30:32 +00001168 cerr << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001169 }
1170}