blob: 0a281c89458325f5df60af05f5cacc7f16757919 [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"
Jeff Cohenca5183d2007-03-05 00:00:42 +000065#include <algorithm>
Chris Lattnere995a2a2004-05-23 21:00:47 +000066#include <set>
67using namespace llvm;
68
Chris Lattner3b27d682006-12-19 22:30:33 +000069STATISTIC(NumIters , "Number of iterations to reach convergence");
70STATISTIC(NumConstraints , "Number of constraints");
71STATISTIC(NumNodes , "Number of nodes");
72STATISTIC(NumEscapingFunctions, "Number of internal functions that escape");
73STATISTIC(NumIndirectCallees , "Number of indirect callees found");
Chris Lattnere995a2a2004-05-23 21:00:47 +000074
Chris Lattner3b27d682006-12-19 22:30:33 +000075namespace {
Reid Spencerd7d83db2007-02-05 23:42:17 +000076 class VISIBILITY_HIDDEN Andersens : public ModulePass, public AliasAnalysis,
77 private InstVisitor<Andersens> {
Chris Lattnere995a2a2004-05-23 21:00:47 +000078 /// Node class - This class is used to represent a memory object in the
79 /// program, and is the primitive used to build the points-to graph.
80 class Node {
81 std::vector<Node*> Pointees;
82 Value *Val;
83 public:
84 Node() : Val(0) {}
85 Node *setValue(Value *V) {
86 assert(Val == 0 && "Value already set for this node!");
87 Val = V;
88 return this;
89 }
90
91 /// getValue - Return the LLVM value corresponding to this node.
Chris Lattnerc3c9fd02005-03-28 04:03:52 +000092 ///
Chris Lattnere995a2a2004-05-23 21:00:47 +000093 Value *getValue() const { return Val; }
94
95 typedef std::vector<Node*>::const_iterator iterator;
96 iterator begin() const { return Pointees.begin(); }
97 iterator end() const { return Pointees.end(); }
98
99 /// addPointerTo - Add a pointer to the list of pointees of this node,
100 /// returning true if this caused a new pointer to be added, or false if
101 /// we already knew about the points-to relation.
102 bool addPointerTo(Node *N) {
103 std::vector<Node*>::iterator I = std::lower_bound(Pointees.begin(),
104 Pointees.end(),
105 N);
106 if (I != Pointees.end() && *I == N)
107 return false;
108 Pointees.insert(I, N);
109 return true;
110 }
111
112 /// intersects - Return true if the points-to set of this node intersects
113 /// with the points-to set of the specified node.
114 bool intersects(Node *N) const;
115
116 /// intersectsIgnoring - Return true if the points-to set of this node
117 /// intersects with the points-to set of the specified node on any nodes
118 /// except for the specified node to ignore.
119 bool intersectsIgnoring(Node *N, Node *Ignoring) const;
120
121 // Constraint application methods.
122 bool copyFrom(Node *N);
123 bool loadFrom(Node *N);
124 bool storeThrough(Node *N);
125 };
126
127 /// GraphNodes - This vector is populated as part of the object
128 /// identification stage of the analysis, which populates this vector with a
129 /// node for each memory object and fills in the ValueNodes map.
130 std::vector<Node> GraphNodes;
131
132 /// ValueNodes - This map indicates the Node that a particular Value* is
133 /// represented by. This contains entries for all pointers.
134 std::map<Value*, unsigned> ValueNodes;
135
136 /// ObjectNodes - This map contains entries for each memory object in the
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000137 /// program: globals, alloca's and mallocs.
Chris Lattnere995a2a2004-05-23 21:00:47 +0000138 std::map<Value*, unsigned> ObjectNodes;
139
140 /// ReturnNodes - This map contains an entry for each function in the
141 /// program that returns a value.
142 std::map<Function*, unsigned> ReturnNodes;
143
144 /// VarargNodes - This map contains the entry used to represent all pointers
145 /// passed through the varargs portion of a function call for a particular
146 /// function. An entry is not present in this map for functions that do not
147 /// take variable arguments.
148 std::map<Function*, unsigned> VarargNodes;
149
150 /// Constraint - Objects of this structure are used to represent the various
151 /// constraints identified by the algorithm. The constraints are 'copy',
152 /// for statements like "A = B", 'load' for statements like "A = *B", and
153 /// 'store' for statements like "*A = B".
154 struct Constraint {
155 enum ConstraintType { Copy, Load, Store } Type;
156 Node *Dest, *Src;
157
158 Constraint(ConstraintType Ty, Node *D, Node *S)
159 : Type(Ty), Dest(D), Src(S) {}
160 };
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000161
Chris Lattnere995a2a2004-05-23 21:00:47 +0000162 /// Constraints - This vector contains a list of all of the constraints
163 /// identified by the program.
164 std::vector<Constraint> Constraints;
165
166 /// EscapingInternalFunctions - This set contains all of the internal
167 /// functions that are found to escape from the program. If the address of
168 /// an internal function is passed to an external function or otherwise
169 /// escapes from the analyzed portion of the program, we must assume that
170 /// any pointer arguments can alias the universal node. This set keeps
171 /// track of those functions we are assuming to escape so far.
172 std::set<Function*> EscapingInternalFunctions;
173
174 /// IndirectCalls - This contains a list of all of the indirect call sites
175 /// in the program. Since the call graph is iteratively discovered, we may
176 /// need to add constraints to our graph as we find new targets of function
177 /// pointers.
178 std::vector<CallSite> IndirectCalls;
179
180 /// IndirectCallees - For each call site in the indirect calls list, keep
181 /// track of the callees that we have discovered so far. As the analysis
182 /// proceeds, more callees are discovered, until the call graph finally
183 /// stabilizes.
184 std::map<CallSite, std::vector<Function*> > IndirectCallees;
185
186 /// This enum defines the GraphNodes indices that correspond to important
187 /// fixed sets.
188 enum {
189 UniversalSet = 0,
190 NullPtr = 1,
Chris Lattnerd74ea2b2006-05-24 17:04:05 +0000191 NullObject = 2
Chris Lattnere995a2a2004-05-23 21:00:47 +0000192 };
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000193
Chris Lattnere995a2a2004-05-23 21:00:47 +0000194 public:
Chris Lattnerb12914b2004-09-20 04:48:05 +0000195 bool runOnModule(Module &M) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000196 InitializeAliasAnalysis(this);
197 IdentifyObjects(M);
198 CollectConstraints(M);
199 DEBUG(PrintConstraints());
200 SolveConstraints();
201 DEBUG(PrintPointsToGraph());
202
203 // Free the constraints list, as we don't need it to respond to alias
204 // requests.
205 ObjectNodes.clear();
206 ReturnNodes.clear();
207 VarargNodes.clear();
208 EscapingInternalFunctions.clear();
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000209 std::vector<Constraint>().swap(Constraints);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000210 return false;
211 }
212
213 void releaseMemory() {
214 // FIXME: Until we have transitively required passes working correctly,
215 // this cannot be enabled! Otherwise, using -count-aa with the pass
216 // causes memory to be freed too early. :(
217#if 0
218 // The memory objects and ValueNodes data structures at the only ones that
219 // are still live after construction.
220 std::vector<Node>().swap(GraphNodes);
221 ValueNodes.clear();
222#endif
223 }
224
225 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
226 AliasAnalysis::getAnalysisUsage(AU);
227 AU.setPreservesAll(); // Does not transform code
228 }
229
230 //------------------------------------------------
231 // Implement the AliasAnalysis API
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000232 //
Chris Lattnere995a2a2004-05-23 21:00:47 +0000233 AliasResult alias(const Value *V1, unsigned V1Size,
234 const Value *V2, unsigned V2Size);
Reid Spencer3a9ec242006-08-28 01:02:49 +0000235 virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
236 virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000237 void getMustAliases(Value *P, std::vector<Value*> &RetVals);
238 bool pointsToConstantMemory(const Value *P);
239
240 virtual void deleteValue(Value *V) {
241 ValueNodes.erase(V);
242 getAnalysis<AliasAnalysis>().deleteValue(V);
243 }
244
245 virtual void copyValue(Value *From, Value *To) {
246 ValueNodes[To] = ValueNodes[From];
247 getAnalysis<AliasAnalysis>().copyValue(From, To);
248 }
249
250 private:
251 /// getNode - Return the node corresponding to the specified pointer scalar.
252 ///
253 Node *getNode(Value *V) {
254 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattnerdf9b7bc2004-08-16 05:38:02 +0000255 if (!isa<GlobalValue>(C))
256 return getNodeForConstantPointer(C);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000257
258 std::map<Value*, unsigned>::iterator I = ValueNodes.find(V);
259 if (I == ValueNodes.end()) {
Jim Laskey16d42c62006-07-11 18:25:13 +0000260#ifndef NDEBUG
261 V->dump();
262#endif
Jim Laskeye37fe9b2006-07-11 17:58:07 +0000263 assert(0 && "Value does not have a node in the points-to graph!");
Chris Lattnere995a2a2004-05-23 21:00:47 +0000264 }
265 return &GraphNodes[I->second];
266 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000267
Chris Lattnere995a2a2004-05-23 21:00:47 +0000268 /// getObject - Return the node corresponding to the memory object for the
269 /// specified global or allocation instruction.
270 Node *getObject(Value *V) {
271 std::map<Value*, unsigned>::iterator I = ObjectNodes.find(V);
272 assert(I != ObjectNodes.end() &&
273 "Value does not have an object in the points-to graph!");
274 return &GraphNodes[I->second];
275 }
276
277 /// getReturnNode - Return the node representing the return value for the
278 /// specified function.
279 Node *getReturnNode(Function *F) {
280 std::map<Function*, unsigned>::iterator I = ReturnNodes.find(F);
281 assert(I != ReturnNodes.end() && "Function does not return a value!");
282 return &GraphNodes[I->second];
283 }
284
285 /// getVarargNode - Return the node representing the variable arguments
286 /// formal for the specified function.
287 Node *getVarargNode(Function *F) {
288 std::map<Function*, unsigned>::iterator I = VarargNodes.find(F);
289 assert(I != VarargNodes.end() && "Function does not take var args!");
290 return &GraphNodes[I->second];
291 }
292
293 /// getNodeValue - Get the node for the specified LLVM value and set the
294 /// value for it to be the specified value.
295 Node *getNodeValue(Value &V) {
296 return getNode(&V)->setValue(&V);
297 }
298
299 void IdentifyObjects(Module &M);
300 void CollectConstraints(Module &M);
301 void SolveConstraints();
302
303 Node *getNodeForConstantPointer(Constant *C);
304 Node *getNodeForConstantPointerTarget(Constant *C);
305 void AddGlobalInitializerConstraints(Node *N, Constant *C);
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000306
Chris Lattnere995a2a2004-05-23 21:00:47 +0000307 void AddConstraintsForNonInternalLinkage(Function *F);
308 void AddConstraintsForCall(CallSite CS, Function *F);
Chris Lattner8a446432005-03-29 06:09:07 +0000309 bool AddConstraintsForExternalCall(CallSite CS, Function *F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000310
311
312 void PrintNode(Node *N);
313 void PrintConstraints();
314 void PrintPointsToGraph();
315
316 //===------------------------------------------------------------------===//
317 // Instruction visitation methods for adding constraints
318 //
319 friend class InstVisitor<Andersens>;
320 void visitReturnInst(ReturnInst &RI);
321 void visitInvokeInst(InvokeInst &II) { visitCallSite(CallSite(&II)); }
322 void visitCallInst(CallInst &CI) { visitCallSite(CallSite(&CI)); }
323 void visitCallSite(CallSite CS);
324 void visitAllocationInst(AllocationInst &AI);
325 void visitLoadInst(LoadInst &LI);
326 void visitStoreInst(StoreInst &SI);
327 void visitGetElementPtrInst(GetElementPtrInst &GEP);
328 void visitPHINode(PHINode &PN);
329 void visitCastInst(CastInst &CI);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000330 void visitICmpInst(ICmpInst &ICI) {} // NOOP!
331 void visitFCmpInst(FCmpInst &ICI) {} // NOOP!
Chris Lattnere995a2a2004-05-23 21:00:47 +0000332 void visitSelectInst(SelectInst &SI);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000333 void visitVAArg(VAArgInst &I);
334 void visitInstruction(Instruction &I);
335 };
336
Chris Lattner7f8897f2006-08-27 22:42:52 +0000337 RegisterPass<Andersens> X("anders-aa",
338 "Andersen's Interprocedural Alias Analysis");
Chris Lattnera5370172006-08-28 00:42:29 +0000339 RegisterAnalysisGroup<AliasAnalysis> Y(X);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000340}
341
Jeff Cohen534927d2005-01-08 22:01:16 +0000342ModulePass *llvm::createAndersensPass() { return new Andersens(); }
343
Chris Lattnere995a2a2004-05-23 21:00:47 +0000344//===----------------------------------------------------------------------===//
345// AliasAnalysis Interface Implementation
346//===----------------------------------------------------------------------===//
347
348AliasAnalysis::AliasResult Andersens::alias(const Value *V1, unsigned V1Size,
349 const Value *V2, unsigned V2Size) {
Chris Lattnerf392c642005-03-28 06:21:17 +0000350 Node *N1 = getNode(const_cast<Value*>(V1));
351 Node *N2 = getNode(const_cast<Value*>(V2));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000352
353 // Check to see if the two pointers are known to not alias. They don't alias
354 // if their points-to sets do not intersect.
355 if (!N1->intersectsIgnoring(N2, &GraphNodes[NullObject]))
356 return NoAlias;
357
358 return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
359}
360
Chris Lattnerf392c642005-03-28 06:21:17 +0000361AliasAnalysis::ModRefResult
362Andersens::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
363 // The only thing useful that we can contribute for mod/ref information is
364 // when calling external function calls: if we know that memory never escapes
365 // from the program, it cannot be modified by an external call.
366 //
367 // NOTE: This is not really safe, at least not when the entire program is not
368 // available. The deal is that the external function could call back into the
369 // program and modify stuff. We ignore this technical niggle for now. This
370 // is, after all, a "research quality" implementation of Andersen's analysis.
371 if (Function *F = CS.getCalledFunction())
Reid Spencer5cbf9852007-01-30 20:08:39 +0000372 if (F->isDeclaration()) {
Chris Lattnerf392c642005-03-28 06:21:17 +0000373 Node *N1 = getNode(P);
Chris Lattnerf392c642005-03-28 06:21:17 +0000374
Chris Lattner8a9763c2005-04-04 22:23:21 +0000375 if (N1->begin() == N1->end())
376 return NoModRef; // P doesn't point to anything.
Chris Lattnerf392c642005-03-28 06:21:17 +0000377
Chris Lattner8a9763c2005-04-04 22:23:21 +0000378 // Get the first pointee.
379 Node *FirstPointee = *N1->begin();
380 if (FirstPointee != &GraphNodes[UniversalSet])
Chris Lattnerf392c642005-03-28 06:21:17 +0000381 return NoModRef; // P doesn't point to the universal set.
382 }
383
384 return AliasAnalysis::getModRefInfo(CS, P, Size);
385}
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000386
Reid Spencer3a9ec242006-08-28 01:02:49 +0000387AliasAnalysis::ModRefResult
388Andersens::getModRefInfo(CallSite CS1, CallSite CS2) {
389 return AliasAnalysis::getModRefInfo(CS1,CS2);
390}
391
Chris Lattnere995a2a2004-05-23 21:00:47 +0000392/// getMustAlias - We can provide must alias information if we know that a
393/// pointer can only point to a specific function or the null pointer.
394/// Unfortunately we cannot determine must-alias information for global
395/// variables or any other memory memory objects because we do not track whether
396/// a pointer points to the beginning of an object or a field of it.
397void Andersens::getMustAliases(Value *P, std::vector<Value*> &RetVals) {
398 Node *N = getNode(P);
399 Node::iterator I = N->begin();
400 if (I != N->end()) {
401 // If there is exactly one element in the points-to set for the object...
402 ++I;
403 if (I == N->end()) {
404 Node *Pointee = *N->begin();
405
406 // If a function is the only object in the points-to set, then it must be
407 // the destination. Note that we can't handle global variables here,
408 // because we don't know if the pointer is actually pointing to a field of
409 // the global or to the beginning of it.
410 if (Value *V = Pointee->getValue()) {
411 if (Function *F = dyn_cast<Function>(V))
412 RetVals.push_back(F);
413 } else {
414 // If the object in the points-to set is the null object, then the null
415 // pointer is a must alias.
416 if (Pointee == &GraphNodes[NullObject])
417 RetVals.push_back(Constant::getNullValue(P->getType()));
418 }
419 }
420 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000421
Chris Lattnere995a2a2004-05-23 21:00:47 +0000422 AliasAnalysis::getMustAliases(P, RetVals);
423}
424
425/// pointsToConstantMemory - If we can determine that this pointer only points
426/// to constant memory, return true. In practice, this means that if the
427/// pointer can only point to constant globals, functions, or the null pointer,
428/// return true.
429///
430bool Andersens::pointsToConstantMemory(const Value *P) {
431 Node *N = getNode((Value*)P);
432 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I) {
433 if (Value *V = (*I)->getValue()) {
434 if (!isa<GlobalValue>(V) || (isa<GlobalVariable>(V) &&
435 !cast<GlobalVariable>(V)->isConstant()))
436 return AliasAnalysis::pointsToConstantMemory(P);
437 } else {
438 if (*I != &GraphNodes[NullObject])
439 return AliasAnalysis::pointsToConstantMemory(P);
440 }
441 }
442
443 return true;
444}
445
446//===----------------------------------------------------------------------===//
447// Object Identification Phase
448//===----------------------------------------------------------------------===//
449
450/// IdentifyObjects - This stage scans the program, adding an entry to the
451/// GraphNodes list for each memory object in the program (global stack or
452/// heap), and populates the ValueNodes and ObjectNodes maps for these objects.
453///
454void Andersens::IdentifyObjects(Module &M) {
455 unsigned NumObjects = 0;
456
457 // Object #0 is always the universal set: the object that we don't know
458 // anything about.
459 assert(NumObjects == UniversalSet && "Something changed!");
460 ++NumObjects;
461
462 // Object #1 always represents the null pointer.
463 assert(NumObjects == NullPtr && "Something changed!");
464 ++NumObjects;
465
466 // Object #2 always represents the null object (the object pointed to by null)
467 assert(NumObjects == NullObject && "Something changed!");
468 ++NumObjects;
469
470 // Add all the globals first.
Chris Lattner493f6362005-03-27 22:03:46 +0000471 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
472 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000473 ObjectNodes[I] = NumObjects++;
474 ValueNodes[I] = NumObjects++;
475 }
476
477 // Add nodes for all of the functions and the instructions inside of them.
478 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
479 // The function itself is a memory object.
480 ValueNodes[F] = NumObjects++;
481 ObjectNodes[F] = NumObjects++;
482 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
483 ReturnNodes[F] = NumObjects++;
484 if (F->getFunctionType()->isVarArg())
485 VarargNodes[F] = NumObjects++;
486
487 // Add nodes for all of the incoming pointer arguments.
Chris Lattner493f6362005-03-27 22:03:46 +0000488 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
489 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000490 if (isa<PointerType>(I->getType()))
491 ValueNodes[I] = NumObjects++;
492
493 // Scan the function body, creating a memory object for each heap/stack
494 // allocation in the body of the function and a node to represent all
495 // pointer values defined by instructions and used as operands.
496 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
497 // If this is an heap or stack allocation, create a node for the memory
498 // object.
499 if (isa<PointerType>(II->getType())) {
500 ValueNodes[&*II] = NumObjects++;
501 if (AllocationInst *AI = dyn_cast<AllocationInst>(&*II))
502 ObjectNodes[AI] = NumObjects++;
503 }
504 }
505 }
506
507 // Now that we know how many objects to create, make them all now!
508 GraphNodes.resize(NumObjects);
509 NumNodes += NumObjects;
510}
511
512//===----------------------------------------------------------------------===//
513// Constraint Identification Phase
514//===----------------------------------------------------------------------===//
515
516/// getNodeForConstantPointer - Return the node corresponding to the constant
517/// pointer itself.
518Andersens::Node *Andersens::getNodeForConstantPointer(Constant *C) {
519 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
520
Chris Lattner267a1b02005-03-27 18:58:23 +0000521 if (isa<ConstantPointerNull>(C) || isa<UndefValue>(C))
Chris Lattnere995a2a2004-05-23 21:00:47 +0000522 return &GraphNodes[NullPtr];
Reid Spencere8404342004-07-18 00:18:30 +0000523 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
524 return getNode(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000525 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
526 switch (CE->getOpcode()) {
527 case Instruction::GetElementPtr:
528 return getNodeForConstantPointer(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000529 case Instruction::IntToPtr:
530 return &GraphNodes[UniversalSet];
531 case Instruction::BitCast:
532 return getNodeForConstantPointer(CE->getOperand(0));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000533 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000534 cerr << "Constant Expr not yet handled: " << *CE << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +0000535 assert(0);
536 }
537 } else {
538 assert(0 && "Unknown constant pointer!");
539 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000540 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000541}
542
543/// getNodeForConstantPointerTarget - Return the node POINTED TO by the
544/// specified constant pointer.
545Andersens::Node *Andersens::getNodeForConstantPointerTarget(Constant *C) {
546 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
547
548 if (isa<ConstantPointerNull>(C))
549 return &GraphNodes[NullObject];
Reid Spencere8404342004-07-18 00:18:30 +0000550 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
551 return getObject(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000552 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
553 switch (CE->getOpcode()) {
554 case Instruction::GetElementPtr:
555 return getNodeForConstantPointerTarget(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000556 case Instruction::IntToPtr:
557 return &GraphNodes[UniversalSet];
558 case Instruction::BitCast:
559 return getNodeForConstantPointerTarget(CE->getOperand(0));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000560 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000561 cerr << "Constant Expr not yet handled: " << *CE << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +0000562 assert(0);
563 }
564 } else {
565 assert(0 && "Unknown constant pointer!");
566 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000567 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000568}
569
570/// AddGlobalInitializerConstraints - Add inclusion constraints for the memory
571/// object N, which contains values indicated by C.
572void Andersens::AddGlobalInitializerConstraints(Node *N, Constant *C) {
573 if (C->getType()->isFirstClassType()) {
574 if (isa<PointerType>(C->getType()))
Chris Lattner76bc5ce2005-03-29 17:21:53 +0000575 N->copyFrom(getNodeForConstantPointer(C));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000576
Chris Lattnere995a2a2004-05-23 21:00:47 +0000577 } else if (C->isNullValue()) {
578 N->addPointerTo(&GraphNodes[NullObject]);
579 return;
Chris Lattner8a446432005-03-29 06:09:07 +0000580 } else if (!isa<UndefValue>(C)) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000581 // If this is an array or struct, include constraints for each element.
582 assert(isa<ConstantArray>(C) || isa<ConstantStruct>(C));
583 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
584 AddGlobalInitializerConstraints(N, cast<Constant>(C->getOperand(i)));
585 }
586}
587
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000588/// AddConstraintsForNonInternalLinkage - If this function does not have
589/// internal linkage, realize that we can't trust anything passed into or
590/// returned by this function.
Chris Lattnere995a2a2004-05-23 21:00:47 +0000591void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
Chris Lattnere4d5c442005-03-15 04:54:21 +0000592 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000593 if (isa<PointerType>(I->getType()))
594 // If this is an argument of an externally accessible function, the
595 // incoming pointer might point to anything.
596 Constraints.push_back(Constraint(Constraint::Copy, getNode(I),
597 &GraphNodes[UniversalSet]));
598}
599
Chris Lattner8a446432005-03-29 06:09:07 +0000600/// AddConstraintsForCall - If this is a call to a "known" function, add the
601/// constraints and return true. If this is a call to an unknown function,
602/// return false.
603bool Andersens::AddConstraintsForExternalCall(CallSite CS, Function *F) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000604 assert(F->isDeclaration() && "Not an external function!");
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000605
606 // These functions don't induce any points-to constraints.
Chris Lattner175b9632005-03-29 20:36:05 +0000607 if (F->getName() == "atoi" || F->getName() == "atof" ||
608 F->getName() == "atol" || F->getName() == "atoll" ||
609 F->getName() == "remove" || F->getName() == "unlink" ||
610 F->getName() == "rename" || F->getName() == "memcmp" ||
Chris Lattner01ac91e2006-03-03 01:21:36 +0000611 F->getName() == "llvm.memset.i32" ||
612 F->getName() == "llvm.memset.i64" ||
Chris Lattner175b9632005-03-29 20:36:05 +0000613 F->getName() == "strcmp" || F->getName() == "strncmp" ||
614 F->getName() == "execl" || F->getName() == "execlp" ||
615 F->getName() == "execle" || F->getName() == "execv" ||
616 F->getName() == "execvp" || F->getName() == "chmod" ||
617 F->getName() == "puts" || F->getName() == "write" ||
618 F->getName() == "open" || F->getName() == "create" ||
619 F->getName() == "truncate" || F->getName() == "chdir" ||
620 F->getName() == "mkdir" || F->getName() == "rmdir" ||
621 F->getName() == "read" || F->getName() == "pipe" ||
622 F->getName() == "wait" || F->getName() == "time" ||
623 F->getName() == "stat" || F->getName() == "fstat" ||
624 F->getName() == "lstat" || F->getName() == "strtod" ||
625 F->getName() == "strtof" || F->getName() == "strtold" ||
626 F->getName() == "fopen" || F->getName() == "fdopen" ||
627 F->getName() == "freopen" ||
628 F->getName() == "fflush" || F->getName() == "feof" ||
629 F->getName() == "fileno" || F->getName() == "clearerr" ||
630 F->getName() == "rewind" || F->getName() == "ftell" ||
631 F->getName() == "ferror" || F->getName() == "fgetc" ||
632 F->getName() == "fgetc" || F->getName() == "_IO_getc" ||
633 F->getName() == "fwrite" || F->getName() == "fread" ||
634 F->getName() == "fgets" || F->getName() == "ungetc" ||
635 F->getName() == "fputc" ||
636 F->getName() == "fputs" || F->getName() == "putc" ||
637 F->getName() == "ftell" || F->getName() == "rewind" ||
638 F->getName() == "_IO_putc" || F->getName() == "fseek" ||
639 F->getName() == "fgetpos" || F->getName() == "fsetpos" ||
640 F->getName() == "printf" || F->getName() == "fprintf" ||
641 F->getName() == "sprintf" || F->getName() == "vprintf" ||
642 F->getName() == "vfprintf" || F->getName() == "vsprintf" ||
643 F->getName() == "scanf" || F->getName() == "fscanf" ||
644 F->getName() == "sscanf" || F->getName() == "__assert_fail" ||
645 F->getName() == "modf")
Chris Lattner8a446432005-03-29 06:09:07 +0000646 return true;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000647
Chris Lattner175b9632005-03-29 20:36:05 +0000648
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000649 // These functions do induce points-to edges.
Chris Lattner01ac91e2006-03-03 01:21:36 +0000650 if (F->getName() == "llvm.memcpy.i32" || F->getName() == "llvm.memcpy.i64" ||
651 F->getName() == "llvm.memmove.i32" ||F->getName() == "llvm.memmove.i64" ||
Chris Lattner4de57fd2005-03-29 06:52:20 +0000652 F->getName() == "memmove") {
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000653 // Note: this is a poor approximation, this says Dest = Src, instead of
654 // *Dest = *Src.
Chris Lattner8a446432005-03-29 06:09:07 +0000655 Constraints.push_back(Constraint(Constraint::Copy,
656 getNode(CS.getArgument(0)),
657 getNode(CS.getArgument(1))));
658 return true;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000659 }
660
Chris Lattner77b50562005-03-29 20:04:24 +0000661 // Result = Arg0
662 if (F->getName() == "realloc" || F->getName() == "strchr" ||
663 F->getName() == "strrchr" || F->getName() == "strstr" ||
664 F->getName() == "strtok") {
Chris Lattner8a446432005-03-29 06:09:07 +0000665 Constraints.push_back(Constraint(Constraint::Copy,
666 getNode(CS.getInstruction()),
667 getNode(CS.getArgument(0))));
668 return true;
669 }
670
671 return false;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000672}
673
674
Chris Lattnere995a2a2004-05-23 21:00:47 +0000675
676/// CollectConstraints - This stage scans the program, adding a constraint to
677/// the Constraints list for each instruction in the program that induces a
678/// constraint, and setting up the initial points-to graph.
679///
680void Andersens::CollectConstraints(Module &M) {
681 // First, the universal set points to itself.
682 GraphNodes[UniversalSet].addPointerTo(&GraphNodes[UniversalSet]);
Chris Lattner4de57fd2005-03-29 06:52:20 +0000683 //Constraints.push_back(Constraint(Constraint::Load, &GraphNodes[UniversalSet],
684 // &GraphNodes[UniversalSet]));
Chris Lattnerf392c642005-03-28 06:21:17 +0000685 Constraints.push_back(Constraint(Constraint::Store, &GraphNodes[UniversalSet],
686 &GraphNodes[UniversalSet]));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000687
688 // Next, the null pointer points to the null object.
689 GraphNodes[NullPtr].addPointerTo(&GraphNodes[NullObject]);
690
691 // Next, add any constraints on global variables and their initializers.
Chris Lattner493f6362005-03-27 22:03:46 +0000692 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
693 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000694 // Associate the address of the global object as pointing to the memory for
695 // the global: &G = <G memory>
696 Node *Object = getObject(I);
697 Object->setValue(I);
698 getNodeValue(*I)->addPointerTo(Object);
699
700 if (I->hasInitializer()) {
701 AddGlobalInitializerConstraints(Object, I->getInitializer());
702 } else {
703 // If it doesn't have an initializer (i.e. it's defined in another
704 // translation unit), it points to the universal set.
705 Constraints.push_back(Constraint(Constraint::Copy, Object,
706 &GraphNodes[UniversalSet]));
707 }
708 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000709
Chris Lattnere995a2a2004-05-23 21:00:47 +0000710 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
711 // Make the function address point to the function object.
712 getNodeValue(*F)->addPointerTo(getObject(F)->setValue(F));
713
714 // Set up the return value node.
715 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
716 getReturnNode(F)->setValue(F);
717 if (F->getFunctionType()->isVarArg())
718 getVarargNode(F)->setValue(F);
719
720 // Set up incoming argument nodes.
Chris Lattner493f6362005-03-27 22:03:46 +0000721 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
722 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000723 if (isa<PointerType>(I->getType()))
724 getNodeValue(*I);
725
726 if (!F->hasInternalLinkage())
727 AddConstraintsForNonInternalLinkage(F);
728
Reid Spencer5cbf9852007-01-30 20:08:39 +0000729 if (!F->isDeclaration()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000730 // Scan the function body, creating a memory object for each heap/stack
731 // allocation in the body of the function and a node to represent all
732 // pointer values defined by instructions and used as operands.
733 visit(F);
Chris Lattner8a446432005-03-29 06:09:07 +0000734 } else {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000735 // External functions that return pointers return the universal set.
736 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
737 Constraints.push_back(Constraint(Constraint::Copy,
738 getReturnNode(F),
739 &GraphNodes[UniversalSet]));
740
741 // Any pointers that are passed into the function have the universal set
742 // stored into them.
Chris Lattner493f6362005-03-27 22:03:46 +0000743 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
744 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000745 if (isa<PointerType>(I->getType())) {
746 // Pointers passed into external functions could have anything stored
747 // through them.
748 Constraints.push_back(Constraint(Constraint::Store, getNode(I),
749 &GraphNodes[UniversalSet]));
750 // Memory objects passed into external function calls can have the
751 // universal set point to them.
752 Constraints.push_back(Constraint(Constraint::Copy,
753 &GraphNodes[UniversalSet],
754 getNode(I)));
755 }
756
757 // If this is an external varargs function, it can also store pointers
758 // into any pointers passed through the varargs section.
759 if (F->getFunctionType()->isVarArg())
760 Constraints.push_back(Constraint(Constraint::Store, getVarargNode(F),
761 &GraphNodes[UniversalSet]));
762 }
763 }
764 NumConstraints += Constraints.size();
765}
766
767
768void Andersens::visitInstruction(Instruction &I) {
769#ifdef NDEBUG
770 return; // This function is just a big assert.
771#endif
772 if (isa<BinaryOperator>(I))
773 return;
774 // Most instructions don't have any effect on pointer values.
775 switch (I.getOpcode()) {
776 case Instruction::Br:
777 case Instruction::Switch:
778 case Instruction::Unwind:
Chris Lattnerc17edbd2004-10-16 18:16:19 +0000779 case Instruction::Unreachable:
Chris Lattnere995a2a2004-05-23 21:00:47 +0000780 case Instruction::Free:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000781 case Instruction::ICmp:
782 case Instruction::FCmp:
Chris Lattnere995a2a2004-05-23 21:00:47 +0000783 return;
784 default:
785 // Is this something we aren't handling yet?
Bill Wendlinge8156192006-12-07 01:30:32 +0000786 cerr << "Unknown instruction: " << I;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000787 abort();
788 }
789}
790
791void Andersens::visitAllocationInst(AllocationInst &AI) {
792 getNodeValue(AI)->addPointerTo(getObject(&AI)->setValue(&AI));
793}
794
795void Andersens::visitReturnInst(ReturnInst &RI) {
796 if (RI.getNumOperands() && isa<PointerType>(RI.getOperand(0)->getType()))
797 // return V --> <Copy/retval{F}/v>
798 Constraints.push_back(Constraint(Constraint::Copy,
799 getReturnNode(RI.getParent()->getParent()),
800 getNode(RI.getOperand(0))));
801}
802
803void Andersens::visitLoadInst(LoadInst &LI) {
804 if (isa<PointerType>(LI.getType()))
805 // P1 = load P2 --> <Load/P1/P2>
806 Constraints.push_back(Constraint(Constraint::Load, getNodeValue(LI),
807 getNode(LI.getOperand(0))));
808}
809
810void Andersens::visitStoreInst(StoreInst &SI) {
811 if (isa<PointerType>(SI.getOperand(0)->getType()))
812 // store P1, P2 --> <Store/P2/P1>
813 Constraints.push_back(Constraint(Constraint::Store,
814 getNode(SI.getOperand(1)),
815 getNode(SI.getOperand(0))));
816}
817
818void Andersens::visitGetElementPtrInst(GetElementPtrInst &GEP) {
819 // P1 = getelementptr P2, ... --> <Copy/P1/P2>
820 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(GEP),
821 getNode(GEP.getOperand(0))));
822}
823
824void Andersens::visitPHINode(PHINode &PN) {
825 if (isa<PointerType>(PN.getType())) {
826 Node *PNN = getNodeValue(PN);
827 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
828 // P1 = phi P2, P3 --> <Copy/P1/P2>, <Copy/P1/P3>, ...
829 Constraints.push_back(Constraint(Constraint::Copy, PNN,
830 getNode(PN.getIncomingValue(i))));
831 }
832}
833
834void Andersens::visitCastInst(CastInst &CI) {
835 Value *Op = CI.getOperand(0);
836 if (isa<PointerType>(CI.getType())) {
837 if (isa<PointerType>(Op->getType())) {
838 // P1 = cast P2 --> <Copy/P1/P2>
839 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
840 getNode(CI.getOperand(0))));
841 } else {
842 // P1 = cast int --> <Copy/P1/Univ>
Chris Lattner175b9632005-03-29 20:36:05 +0000843#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +0000844 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
845 &GraphNodes[UniversalSet]));
Chris Lattnerbd135c72005-04-05 01:12:03 +0000846#else
847 getNodeValue(CI);
Chris Lattner175b9632005-03-29 20:36:05 +0000848#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +0000849 }
850 } else if (isa<PointerType>(Op->getType())) {
851 // int = cast P1 --> <Copy/Univ/P1>
Chris Lattner175b9632005-03-29 20:36:05 +0000852#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +0000853 Constraints.push_back(Constraint(Constraint::Copy,
854 &GraphNodes[UniversalSet],
855 getNode(CI.getOperand(0))));
Chris Lattnerbd135c72005-04-05 01:12:03 +0000856#else
857 getNode(CI.getOperand(0));
Chris Lattner175b9632005-03-29 20:36:05 +0000858#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +0000859 }
860}
861
862void Andersens::visitSelectInst(SelectInst &SI) {
863 if (isa<PointerType>(SI.getType())) {
864 Node *SIN = getNodeValue(SI);
865 // P1 = select C, P2, P3 ---> <Copy/P1/P2>, <Copy/P1/P3>
866 Constraints.push_back(Constraint(Constraint::Copy, SIN,
867 getNode(SI.getOperand(1))));
868 Constraints.push_back(Constraint(Constraint::Copy, SIN,
869 getNode(SI.getOperand(2))));
870 }
871}
872
Chris Lattnere995a2a2004-05-23 21:00:47 +0000873void Andersens::visitVAArg(VAArgInst &I) {
874 assert(0 && "vaarg not handled yet!");
875}
876
877/// AddConstraintsForCall - Add constraints for a call with actual arguments
878/// specified by CS to the function specified by F. Note that the types of
879/// arguments might not match up in the case where this is an indirect call and
880/// the function pointer has been casted. If this is the case, do something
881/// reasonable.
882void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
Chris Lattner8a446432005-03-29 06:09:07 +0000883 // If this is a call to an external function, handle it directly to get some
884 // taste of context sensitivity.
Reid Spencer5cbf9852007-01-30 20:08:39 +0000885 if (F->isDeclaration() && AddConstraintsForExternalCall(CS, F))
Chris Lattner8a446432005-03-29 06:09:07 +0000886 return;
887
Chris Lattnere995a2a2004-05-23 21:00:47 +0000888 if (isa<PointerType>(CS.getType())) {
889 Node *CSN = getNode(CS.getInstruction());
890 if (isa<PointerType>(F->getFunctionType()->getReturnType())) {
891 Constraints.push_back(Constraint(Constraint::Copy, CSN,
892 getReturnNode(F)));
893 } else {
894 // If the function returns a non-pointer value, handle this just like we
895 // treat a nonpointer cast to pointer.
896 Constraints.push_back(Constraint(Constraint::Copy, CSN,
897 &GraphNodes[UniversalSet]));
898 }
899 } else if (isa<PointerType>(F->getFunctionType()->getReturnType())) {
900 Constraints.push_back(Constraint(Constraint::Copy,
901 &GraphNodes[UniversalSet],
902 getReturnNode(F)));
903 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000904
Chris Lattnere4d5c442005-03-15 04:54:21 +0000905 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
Chris Lattnere995a2a2004-05-23 21:00:47 +0000906 CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
907 for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI)
908 if (isa<PointerType>(AI->getType())) {
909 if (isa<PointerType>((*ArgI)->getType())) {
910 // Copy the actual argument into the formal argument.
911 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
912 getNode(*ArgI)));
913 } else {
914 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
915 &GraphNodes[UniversalSet]));
916 }
917 } else if (isa<PointerType>((*ArgI)->getType())) {
918 Constraints.push_back(Constraint(Constraint::Copy,
919 &GraphNodes[UniversalSet],
920 getNode(*ArgI)));
921 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000922
Chris Lattnere995a2a2004-05-23 21:00:47 +0000923 // Copy all pointers passed through the varargs section to the varargs node.
924 if (F->getFunctionType()->isVarArg())
925 for (; ArgI != ArgE; ++ArgI)
926 if (isa<PointerType>((*ArgI)->getType()))
927 Constraints.push_back(Constraint(Constraint::Copy, getVarargNode(F),
928 getNode(*ArgI)));
929 // If more arguments are passed in than we track, just drop them on the floor.
930}
931
932void Andersens::visitCallSite(CallSite CS) {
933 if (isa<PointerType>(CS.getType()))
934 getNodeValue(*CS.getInstruction());
935
936 if (Function *F = CS.getCalledFunction()) {
937 AddConstraintsForCall(CS, F);
938 } else {
939 // We don't handle indirect call sites yet. Keep track of them for when we
940 // discover the call graph incrementally.
941 IndirectCalls.push_back(CS);
942 }
943}
944
945//===----------------------------------------------------------------------===//
946// Constraint Solving Phase
947//===----------------------------------------------------------------------===//
948
949/// intersects - Return true if the points-to set of this node intersects
950/// with the points-to set of the specified node.
951bool Andersens::Node::intersects(Node *N) const {
952 iterator I1 = begin(), I2 = N->begin(), E1 = end(), E2 = N->end();
953 while (I1 != E1 && I2 != E2) {
954 if (*I1 == *I2) return true;
955 if (*I1 < *I2)
956 ++I1;
957 else
958 ++I2;
959 }
960 return false;
961}
962
963/// intersectsIgnoring - Return true if the points-to set of this node
964/// intersects with the points-to set of the specified node on any nodes
965/// except for the specified node to ignore.
966bool Andersens::Node::intersectsIgnoring(Node *N, Node *Ignoring) const {
967 iterator I1 = begin(), I2 = N->begin(), E1 = end(), E2 = N->end();
968 while (I1 != E1 && I2 != E2) {
969 if (*I1 == *I2) {
970 if (*I1 != Ignoring) return true;
971 ++I1; ++I2;
972 } else if (*I1 < *I2)
973 ++I1;
974 else
975 ++I2;
976 }
977 return false;
978}
979
980// Copy constraint: all edges out of the source node get copied to the
981// destination node. This returns true if a change is made.
982bool Andersens::Node::copyFrom(Node *N) {
983 // Use a mostly linear-time merge since both of the lists are sorted.
984 bool Changed = false;
985 iterator I = N->begin(), E = N->end();
986 unsigned i = 0;
987 while (I != E && i != Pointees.size()) {
988 if (Pointees[i] < *I) {
989 ++i;
990 } else if (Pointees[i] == *I) {
991 ++i; ++I;
992 } else {
993 // We found a new element to copy over.
994 Changed = true;
995 Pointees.insert(Pointees.begin()+i, *I);
996 ++i; ++I;
997 }
998 }
999
1000 if (I != E) {
1001 Pointees.insert(Pointees.end(), I, E);
1002 Changed = true;
1003 }
1004
1005 return Changed;
1006}
1007
1008bool Andersens::Node::loadFrom(Node *N) {
1009 bool Changed = false;
1010 for (iterator I = N->begin(), E = N->end(); I != E; ++I)
1011 Changed |= copyFrom(*I);
1012 return Changed;
1013}
1014
1015bool Andersens::Node::storeThrough(Node *N) {
1016 bool Changed = false;
1017 for (iterator I = begin(), E = end(); I != E; ++I)
1018 Changed |= (*I)->copyFrom(N);
1019 return Changed;
1020}
1021
1022
1023/// SolveConstraints - This stage iteratively processes the constraints list
1024/// propagating constraints (adding edges to the Nodes in the points-to graph)
1025/// until a fixed point is reached.
1026///
1027void Andersens::SolveConstraints() {
1028 bool Changed = true;
1029 unsigned Iteration = 0;
1030 while (Changed) {
1031 Changed = false;
1032 ++NumIters;
Bill Wendling9be7ac12006-11-17 07:36:54 +00001033 DOUT << "Starting iteration #" << Iteration++ << "!\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001034
1035 // Loop over all of the constraints, applying them in turn.
1036 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1037 Constraint &C = Constraints[i];
1038 switch (C.Type) {
1039 case Constraint::Copy:
1040 Changed |= C.Dest->copyFrom(C.Src);
1041 break;
1042 case Constraint::Load:
1043 Changed |= C.Dest->loadFrom(C.Src);
1044 break;
1045 case Constraint::Store:
1046 Changed |= C.Dest->storeThrough(C.Src);
1047 break;
1048 default:
1049 assert(0 && "Unknown constraint!");
1050 }
1051 }
1052
1053 if (Changed) {
1054 // Check to see if any internal function's addresses have been passed to
1055 // external functions. If so, we have to assume that their incoming
1056 // arguments could be anything. If there are any internal functions in
1057 // the universal node that we don't know about, we must iterate.
1058 for (Node::iterator I = GraphNodes[UniversalSet].begin(),
1059 E = GraphNodes[UniversalSet].end(); I != E; ++I)
1060 if (Function *F = dyn_cast_or_null<Function>((*I)->getValue()))
1061 if (F->hasInternalLinkage() &&
1062 EscapingInternalFunctions.insert(F).second) {
1063 // We found a function that is just now escaping. Mark it as if it
1064 // didn't have internal linkage.
1065 AddConstraintsForNonInternalLinkage(F);
Bill Wendling9be7ac12006-11-17 07:36:54 +00001066 DOUT << "Found escaping internal function: " << F->getName() <<"\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001067 ++NumEscapingFunctions;
1068 }
1069
1070 // Check to see if we have discovered any new callees of the indirect call
1071 // sites. If so, add constraints to the analysis.
1072 for (unsigned i = 0, e = IndirectCalls.size(); i != e; ++i) {
1073 CallSite CS = IndirectCalls[i];
1074 std::vector<Function*> &KnownCallees = IndirectCallees[CS];
1075 Node *CN = getNode(CS.getCalledValue());
1076
1077 for (Node::iterator NI = CN->begin(), E = CN->end(); NI != E; ++NI)
1078 if (Function *F = dyn_cast_or_null<Function>((*NI)->getValue())) {
1079 std::vector<Function*>::iterator IP =
1080 std::lower_bound(KnownCallees.begin(), KnownCallees.end(), F);
1081 if (IP == KnownCallees.end() || *IP != F) {
1082 // Add the constraints for the call now.
1083 AddConstraintsForCall(CS, F);
Bill Wendling9be7ac12006-11-17 07:36:54 +00001084 DOUT << "Found actual callee '"
1085 << F->getName() << "' for call: "
1086 << *CS.getInstruction() << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001087 ++NumIndirectCallees;
1088 KnownCallees.insert(IP, F);
1089 }
1090 }
1091 }
1092 }
1093 }
1094}
1095
1096
1097
1098//===----------------------------------------------------------------------===//
1099// Debugging Output
1100//===----------------------------------------------------------------------===//
1101
1102void Andersens::PrintNode(Node *N) {
1103 if (N == &GraphNodes[UniversalSet]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00001104 cerr << "<universal>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001105 return;
1106 } else if (N == &GraphNodes[NullPtr]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00001107 cerr << "<nullptr>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001108 return;
1109 } else if (N == &GraphNodes[NullObject]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00001110 cerr << "<null>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001111 return;
1112 }
1113
1114 assert(N->getValue() != 0 && "Never set node label!");
1115 Value *V = N->getValue();
1116 if (Function *F = dyn_cast<Function>(V)) {
1117 if (isa<PointerType>(F->getFunctionType()->getReturnType()) &&
1118 N == getReturnNode(F)) {
Bill Wendlinge8156192006-12-07 01:30:32 +00001119 cerr << F->getName() << ":retval";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001120 return;
1121 } else if (F->getFunctionType()->isVarArg() && N == getVarargNode(F)) {
Bill Wendlinge8156192006-12-07 01:30:32 +00001122 cerr << F->getName() << ":vararg";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001123 return;
1124 }
1125 }
1126
1127 if (Instruction *I = dyn_cast<Instruction>(V))
Bill Wendlinge8156192006-12-07 01:30:32 +00001128 cerr << I->getParent()->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001129 else if (Argument *Arg = dyn_cast<Argument>(V))
Bill Wendlinge8156192006-12-07 01:30:32 +00001130 cerr << Arg->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001131
1132 if (V->hasName())
Bill Wendlinge8156192006-12-07 01:30:32 +00001133 cerr << V->getName();
Chris Lattnere995a2a2004-05-23 21:00:47 +00001134 else
Bill Wendlinge8156192006-12-07 01:30:32 +00001135 cerr << "(unnamed)";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001136
1137 if (isa<GlobalValue>(V) || isa<AllocationInst>(V))
1138 if (N == getObject(V))
Bill Wendlinge8156192006-12-07 01:30:32 +00001139 cerr << "<mem>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001140}
1141
1142void Andersens::PrintConstraints() {
Bill Wendlinge8156192006-12-07 01:30:32 +00001143 cerr << "Constraints:\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001144 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Bill Wendlinge8156192006-12-07 01:30:32 +00001145 cerr << " #" << i << ": ";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001146 Constraint &C = Constraints[i];
1147 if (C.Type == Constraint::Store)
Bill Wendlinge8156192006-12-07 01:30:32 +00001148 cerr << "*";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001149 PrintNode(C.Dest);
Bill Wendlinge8156192006-12-07 01:30:32 +00001150 cerr << " = ";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001151 if (C.Type == Constraint::Load)
Bill Wendlinge8156192006-12-07 01:30:32 +00001152 cerr << "*";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001153 PrintNode(C.Src);
Bill Wendlinge8156192006-12-07 01:30:32 +00001154 cerr << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001155 }
1156}
1157
1158void Andersens::PrintPointsToGraph() {
Bill Wendlinge8156192006-12-07 01:30:32 +00001159 cerr << "Points-to graph:\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001160 for (unsigned i = 0, e = GraphNodes.size(); i != e; ++i) {
1161 Node *N = &GraphNodes[i];
Bill Wendlinge8156192006-12-07 01:30:32 +00001162 cerr << "[" << (N->end() - N->begin()) << "] ";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001163 PrintNode(N);
Bill Wendlinge8156192006-12-07 01:30:32 +00001164 cerr << "\t--> ";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001165 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I) {
Bill Wendlinge8156192006-12-07 01:30:32 +00001166 if (I != N->begin()) cerr << ", ";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001167 PrintNode(*I);
1168 }
Bill Wendlinge8156192006-12-07 01:30:32 +00001169 cerr << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00001170 }
1171}