Remove trailing whitespace
[oota-llvm.git] / lib / Analysis / IPA / Andersens.cpp
1 //===- Andersens.cpp - Andersen's Interprocedural Alias Analysis ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines a very simple implementation of Andersen's interprocedural
11 // alias analysis.  This implementation does not include any of the fancy
12 // features that make Andersen's reasonably efficient (like cycle elimination or
13 // variable substitution), but it should be useful for getting precision
14 // numbers and can be extended in the future.
15 //
16 // In pointer analysis terms, this is a subset-based, flow-insensitive,
17 // field-insensitive, and context-insensitive algorithm pointer algorithm.
18 //
19 // This algorithm is implemented as three stages:
20 //   1. Object identification.
21 //   2. Inclusion constraint identification.
22 //   3. Inclusion constraint solving.
23 //
24 // The object identification stage identifies all of the memory objects in the
25 // program, which includes globals, heap allocated objects, and stack allocated
26 // objects.
27 //
28 // The inclusion constraint identification stage finds all inclusion constraints
29 // in the program by scanning the program, looking for pointer assignments and
30 // other statements that effect the points-to graph.  For a statement like "A =
31 // B", this statement is processed to indicate that A can point to anything that
32 // B can point to.  Constraints can handle copies, loads, and stores.
33 //
34 // The inclusion constraint solving phase iteratively propagates the inclusion
35 // constraints until a fixed point is reached.  This is an O(N^3) algorithm.
36 //
37 // In the initial pass, all indirect function calls are completely ignored.  As
38 // the analysis discovers new targets of function pointers, it iteratively
39 // resolves a precise (and conservative) call graph.  Also related, this
40 // analysis initially assumes that all internal functions have known incoming
41 // pointers.  If we find that an internal function's address escapes outside of
42 // the program, we update this assumption.
43 //
44 // Future Improvements:
45 //   This implementation of Andersen's algorithm is extremely slow.  To make it
46 //   scale reasonably well, the inclusion constraints could be sorted (easy),
47 //   offline variable substitution would be a huge win (straight-forward), and
48 //   online cycle elimination (trickier) might help as well.
49 //
50 //===----------------------------------------------------------------------===//
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"
58 #include "llvm/Support/InstIterator.h"
59 #include "llvm/Support/InstVisitor.h"
60 #include "llvm/Analysis/AliasAnalysis.h"
61 #include "llvm/Analysis/Passes.h"
62 #include "llvm/Support/Debug.h"
63 #include "llvm/ADT/Statistic.h"
64 #include <set>
65 using namespace llvm;
66
67 namespace {
68   Statistic<>
69   NumIters("anders-aa", "Number of iterations to reach convergence");
70   Statistic<>
71   NumConstraints("anders-aa", "Number of constraints");
72   Statistic<>
73   NumNodes("anders-aa", "Number of nodes");
74   Statistic<>
75   NumEscapingFunctions("anders-aa", "Number of internal functions that escape");
76   Statistic<>
77   NumIndirectCallees("anders-aa", "Number of indirect callees found");
78
79   class Andersens : public ModulePass, public AliasAnalysis,
80                     private InstVisitor<Andersens> {
81     /// Node class - This class is used to represent a memory object in the
82     /// program, and is the primitive used to build the points-to graph.
83     class Node {
84       std::vector<Node*> Pointees;
85       Value *Val;
86     public:
87       Node() : Val(0) {}
88       Node *setValue(Value *V) {
89         assert(Val == 0 && "Value already set for this node!");
90         Val = V;
91         return this;
92       }
93
94       /// getValue - Return the LLVM value corresponding to this node.
95       ///
96       Value *getValue() const { return Val; }
97
98       typedef std::vector<Node*>::const_iterator iterator;
99       iterator begin() const { return Pointees.begin(); }
100       iterator end() const { return Pointees.end(); }
101
102       /// addPointerTo - Add a pointer to the list of pointees of this node,
103       /// returning true if this caused a new pointer to be added, or false if
104       /// we already knew about the points-to relation.
105       bool addPointerTo(Node *N) {
106         std::vector<Node*>::iterator I = std::lower_bound(Pointees.begin(),
107                                                           Pointees.end(),
108                                                           N);
109         if (I != Pointees.end() && *I == N)
110           return false;
111         Pointees.insert(I, N);
112         return true;
113       }
114
115       /// intersects - Return true if the points-to set of this node intersects
116       /// with the points-to set of the specified node.
117       bool intersects(Node *N) const;
118
119       /// intersectsIgnoring - Return true if the points-to set of this node
120       /// intersects with the points-to set of the specified node on any nodes
121       /// except for the specified node to ignore.
122       bool intersectsIgnoring(Node *N, Node *Ignoring) const;
123
124       // Constraint application methods.
125       bool copyFrom(Node *N);
126       bool loadFrom(Node *N);
127       bool storeThrough(Node *N);
128     };
129
130     /// GraphNodes - This vector is populated as part of the object
131     /// identification stage of the analysis, which populates this vector with a
132     /// node for each memory object and fills in the ValueNodes map.
133     std::vector<Node> GraphNodes;
134
135     /// ValueNodes - This map indicates the Node that a particular Value* is
136     /// represented by.  This contains entries for all pointers.
137     std::map<Value*, unsigned> ValueNodes;
138
139     /// ObjectNodes - This map contains entries for each memory object in the
140     /// program: globals, alloca's and mallocs.
141     std::map<Value*, unsigned> ObjectNodes;
142
143     /// ReturnNodes - This map contains an entry for each function in the
144     /// program that returns a value.
145     std::map<Function*, unsigned> ReturnNodes;
146
147     /// VarargNodes - This map contains the entry used to represent all pointers
148     /// passed through the varargs portion of a function call for a particular
149     /// function.  An entry is not present in this map for functions that do not
150     /// take variable arguments.
151     std::map<Function*, unsigned> VarargNodes;
152
153     /// Constraint - Objects of this structure are used to represent the various
154     /// constraints identified by the algorithm.  The constraints are 'copy',
155     /// for statements like "A = B", 'load' for statements like "A = *B", and
156     /// 'store' for statements like "*A = B".
157     struct Constraint {
158       enum ConstraintType { Copy, Load, Store } Type;
159       Node *Dest, *Src;
160
161       Constraint(ConstraintType Ty, Node *D, Node *S)
162         : Type(Ty), Dest(D), Src(S) {}
163     };
164
165     /// Constraints - This vector contains a list of all of the constraints
166     /// identified by the program.
167     std::vector<Constraint> Constraints;
168
169     /// EscapingInternalFunctions - This set contains all of the internal
170     /// functions that are found to escape from the program.  If the address of
171     /// an internal function is passed to an external function or otherwise
172     /// escapes from the analyzed portion of the program, we must assume that
173     /// any pointer arguments can alias the universal node.  This set keeps
174     /// track of those functions we are assuming to escape so far.
175     std::set<Function*> EscapingInternalFunctions;
176
177     /// IndirectCalls - This contains a list of all of the indirect call sites
178     /// in the program.  Since the call graph is iteratively discovered, we may
179     /// need to add constraints to our graph as we find new targets of function
180     /// pointers.
181     std::vector<CallSite> IndirectCalls;
182
183     /// IndirectCallees - For each call site in the indirect calls list, keep
184     /// track of the callees that we have discovered so far.  As the analysis
185     /// proceeds, more callees are discovered, until the call graph finally
186     /// stabilizes.
187     std::map<CallSite, std::vector<Function*> > IndirectCallees;
188
189     /// This enum defines the GraphNodes indices that correspond to important
190     /// fixed sets.
191     enum {
192       UniversalSet = 0,
193       NullPtr      = 1,
194       NullObject   = 2,
195     };
196
197   public:
198     bool runOnModule(Module &M) {
199       InitializeAliasAnalysis(this);
200       IdentifyObjects(M);
201       CollectConstraints(M);
202       DEBUG(PrintConstraints());
203       SolveConstraints();
204       DEBUG(PrintPointsToGraph());
205
206       // Free the constraints list, as we don't need it to respond to alias
207       // requests.
208       ObjectNodes.clear();
209       ReturnNodes.clear();
210       VarargNodes.clear();
211       EscapingInternalFunctions.clear();
212       std::vector<Constraint>().swap(Constraints);
213       return false;
214     }
215
216     void releaseMemory() {
217       // FIXME: Until we have transitively required passes working correctly,
218       // this cannot be enabled!  Otherwise, using -count-aa with the pass
219       // causes memory to be freed too early. :(
220 #if 0
221       // The memory objects and ValueNodes data structures at the only ones that
222       // are still live after construction.
223       std::vector<Node>().swap(GraphNodes);
224       ValueNodes.clear();
225 #endif
226     }
227
228     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
229       AliasAnalysis::getAnalysisUsage(AU);
230       AU.setPreservesAll();                         // Does not transform code
231     }
232
233     //------------------------------------------------
234     // Implement the AliasAnalysis API
235     //
236     AliasResult alias(const Value *V1, unsigned V1Size,
237                       const Value *V2, unsigned V2Size);
238     ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
239     void getMustAliases(Value *P, std::vector<Value*> &RetVals);
240     bool pointsToConstantMemory(const Value *P);
241
242     virtual void deleteValue(Value *V) {
243       ValueNodes.erase(V);
244       getAnalysis<AliasAnalysis>().deleteValue(V);
245     }
246
247     virtual void copyValue(Value *From, Value *To) {
248       ValueNodes[To] = ValueNodes[From];
249       getAnalysis<AliasAnalysis>().copyValue(From, To);
250     }
251
252   private:
253     /// getNode - Return the node corresponding to the specified pointer scalar.
254     ///
255     Node *getNode(Value *V) {
256       if (Constant *C = dyn_cast<Constant>(V))
257         if (!isa<GlobalValue>(C))
258           return getNodeForConstantPointer(C);
259
260       std::map<Value*, unsigned>::iterator I = ValueNodes.find(V);
261       if (I == ValueNodes.end()) {
262         V->dump();
263         assert(I != ValueNodes.end() &&
264                "Value does not have a node in the points-to graph!");
265       }
266       return &GraphNodes[I->second];
267     }
268
269     /// getObject - Return the node corresponding to the memory object for the
270     /// specified global or allocation instruction.
271     Node *getObject(Value *V) {
272       std::map<Value*, unsigned>::iterator I = ObjectNodes.find(V);
273       assert(I != ObjectNodes.end() &&
274              "Value does not have an object in the points-to graph!");
275       return &GraphNodes[I->second];
276     }
277
278     /// getReturnNode - Return the node representing the return value for the
279     /// specified function.
280     Node *getReturnNode(Function *F) {
281       std::map<Function*, unsigned>::iterator I = ReturnNodes.find(F);
282       assert(I != ReturnNodes.end() && "Function does not return a value!");
283       return &GraphNodes[I->second];
284     }
285
286     /// getVarargNode - Return the node representing the variable arguments
287     /// formal for the specified function.
288     Node *getVarargNode(Function *F) {
289       std::map<Function*, unsigned>::iterator I = VarargNodes.find(F);
290       assert(I != VarargNodes.end() && "Function does not take var args!");
291       return &GraphNodes[I->second];
292     }
293
294     /// getNodeValue - Get the node for the specified LLVM value and set the
295     /// value for it to be the specified value.
296     Node *getNodeValue(Value &V) {
297       return getNode(&V)->setValue(&V);
298     }
299
300     void IdentifyObjects(Module &M);
301     void CollectConstraints(Module &M);
302     void SolveConstraints();
303
304     Node *getNodeForConstantPointer(Constant *C);
305     Node *getNodeForConstantPointerTarget(Constant *C);
306     void AddGlobalInitializerConstraints(Node *N, Constant *C);
307
308     void AddConstraintsForNonInternalLinkage(Function *F);
309     void AddConstraintsForCall(CallSite CS, Function *F);
310     bool AddConstraintsForExternalCall(CallSite CS, Function *F);
311
312
313     void PrintNode(Node *N);
314     void PrintConstraints();
315     void PrintPointsToGraph();
316
317     //===------------------------------------------------------------------===//
318     // Instruction visitation methods for adding constraints
319     //
320     friend class InstVisitor<Andersens>;
321     void visitReturnInst(ReturnInst &RI);
322     void visitInvokeInst(InvokeInst &II) { visitCallSite(CallSite(&II)); }
323     void visitCallInst(CallInst &CI) { visitCallSite(CallSite(&CI)); }
324     void visitCallSite(CallSite CS);
325     void visitAllocationInst(AllocationInst &AI);
326     void visitLoadInst(LoadInst &LI);
327     void visitStoreInst(StoreInst &SI);
328     void visitGetElementPtrInst(GetElementPtrInst &GEP);
329     void visitPHINode(PHINode &PN);
330     void visitCastInst(CastInst &CI);
331     void visitSetCondInst(SetCondInst &SCI) {} // NOOP!
332     void visitSelectInst(SelectInst &SI);
333     void visitVANext(VANextInst &I);
334     void visitVAArg(VAArgInst &I);
335     void visitInstruction(Instruction &I);
336   };
337
338   RegisterOpt<Andersens> X("anders-aa",
339                            "Andersen's Interprocedural Alias Analysis");
340   RegisterAnalysisGroup<AliasAnalysis, Andersens> Y;
341 }
342
343 ModulePass *llvm::createAndersensPass() { return new Andersens(); }
344
345 //===----------------------------------------------------------------------===//
346 //                  AliasAnalysis Interface Implementation
347 //===----------------------------------------------------------------------===//
348
349 AliasAnalysis::AliasResult Andersens::alias(const Value *V1, unsigned V1Size,
350                                             const Value *V2, unsigned V2Size) {
351   Node *N1 = getNode(const_cast<Value*>(V1));
352   Node *N2 = getNode(const_cast<Value*>(V2));
353
354   // Check to see if the two pointers are known to not alias.  They don't alias
355   // if their points-to sets do not intersect.
356   if (!N1->intersectsIgnoring(N2, &GraphNodes[NullObject]))
357     return NoAlias;
358
359   return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
360 }
361
362 AliasAnalysis::ModRefResult
363 Andersens::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
364   // The only thing useful that we can contribute for mod/ref information is
365   // when calling external function calls: if we know that memory never escapes
366   // from the program, it cannot be modified by an external call.
367   //
368   // NOTE: This is not really safe, at least not when the entire program is not
369   // available.  The deal is that the external function could call back into the
370   // program and modify stuff.  We ignore this technical niggle for now.  This
371   // is, after all, a "research quality" implementation of Andersen's analysis.
372   if (Function *F = CS.getCalledFunction())
373     if (F->isExternal()) {
374       Node *N1 = getNode(P);
375       bool PointsToUniversalSet = false;
376
377       if (N1->begin() == N1->end())
378         return NoModRef;  // P doesn't point to anything.
379
380       // Get the first pointee.
381       Node *FirstPointee = *N1->begin();
382       if (FirstPointee != &GraphNodes[UniversalSet])
383         return NoModRef;  // P doesn't point to the universal set.
384     }
385
386   return AliasAnalysis::getModRefInfo(CS, P, Size);
387 }
388
389 /// getMustAlias - We can provide must alias information if we know that a
390 /// pointer can only point to a specific function or the null pointer.
391 /// Unfortunately we cannot determine must-alias information for global
392 /// variables or any other memory memory objects because we do not track whether
393 /// a pointer points to the beginning of an object or a field of it.
394 void Andersens::getMustAliases(Value *P, std::vector<Value*> &RetVals) {
395   Node *N = getNode(P);
396   Node::iterator I = N->begin();
397   if (I != N->end()) {
398     // If there is exactly one element in the points-to set for the object...
399     ++I;
400     if (I == N->end()) {
401       Node *Pointee = *N->begin();
402
403       // If a function is the only object in the points-to set, then it must be
404       // the destination.  Note that we can't handle global variables here,
405       // because we don't know if the pointer is actually pointing to a field of
406       // the global or to the beginning of it.
407       if (Value *V = Pointee->getValue()) {
408         if (Function *F = dyn_cast<Function>(V))
409           RetVals.push_back(F);
410       } else {
411         // If the object in the points-to set is the null object, then the null
412         // pointer is a must alias.
413         if (Pointee == &GraphNodes[NullObject])
414           RetVals.push_back(Constant::getNullValue(P->getType()));
415       }
416     }
417   }
418
419   AliasAnalysis::getMustAliases(P, RetVals);
420 }
421
422 /// pointsToConstantMemory - If we can determine that this pointer only points
423 /// to constant memory, return true.  In practice, this means that if the
424 /// pointer can only point to constant globals, functions, or the null pointer,
425 /// return true.
426 ///
427 bool Andersens::pointsToConstantMemory(const Value *P) {
428   Node *N = getNode((Value*)P);
429   for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I) {
430     if (Value *V = (*I)->getValue()) {
431       if (!isa<GlobalValue>(V) || (isa<GlobalVariable>(V) &&
432                                    !cast<GlobalVariable>(V)->isConstant()))
433         return AliasAnalysis::pointsToConstantMemory(P);
434     } else {
435       if (*I != &GraphNodes[NullObject])
436         return AliasAnalysis::pointsToConstantMemory(P);
437     }
438   }
439
440   return true;
441 }
442
443 //===----------------------------------------------------------------------===//
444 //                       Object Identification Phase
445 //===----------------------------------------------------------------------===//
446
447 /// IdentifyObjects - This stage scans the program, adding an entry to the
448 /// GraphNodes list for each memory object in the program (global stack or
449 /// heap), and populates the ValueNodes and ObjectNodes maps for these objects.
450 ///
451 void Andersens::IdentifyObjects(Module &M) {
452   unsigned NumObjects = 0;
453
454   // Object #0 is always the universal set: the object that we don't know
455   // anything about.
456   assert(NumObjects == UniversalSet && "Something changed!");
457   ++NumObjects;
458
459   // Object #1 always represents the null pointer.
460   assert(NumObjects == NullPtr && "Something changed!");
461   ++NumObjects;
462
463   // Object #2 always represents the null object (the object pointed to by null)
464   assert(NumObjects == NullObject && "Something changed!");
465   ++NumObjects;
466
467   // Add all the globals first.
468   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
469        I != E; ++I) {
470     ObjectNodes[I] = NumObjects++;
471     ValueNodes[I] = NumObjects++;
472   }
473
474   // Add nodes for all of the functions and the instructions inside of them.
475   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
476     // The function itself is a memory object.
477     ValueNodes[F] = NumObjects++;
478     ObjectNodes[F] = NumObjects++;
479     if (isa<PointerType>(F->getFunctionType()->getReturnType()))
480       ReturnNodes[F] = NumObjects++;
481     if (F->getFunctionType()->isVarArg())
482       VarargNodes[F] = NumObjects++;
483
484     // Add nodes for all of the incoming pointer arguments.
485     for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
486          I != E; ++I)
487       if (isa<PointerType>(I->getType()))
488         ValueNodes[I] = NumObjects++;
489
490     // Scan the function body, creating a memory object for each heap/stack
491     // allocation in the body of the function and a node to represent all
492     // pointer values defined by instructions and used as operands.
493     for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
494       // If this is an heap or stack allocation, create a node for the memory
495       // object.
496       if (isa<PointerType>(II->getType())) {
497         ValueNodes[&*II] = NumObjects++;
498         if (AllocationInst *AI = dyn_cast<AllocationInst>(&*II))
499           ObjectNodes[AI] = NumObjects++;
500       }
501     }
502   }
503
504   // Now that we know how many objects to create, make them all now!
505   GraphNodes.resize(NumObjects);
506   NumNodes += NumObjects;
507 }
508
509 //===----------------------------------------------------------------------===//
510 //                     Constraint Identification Phase
511 //===----------------------------------------------------------------------===//
512
513 /// getNodeForConstantPointer - Return the node corresponding to the constant
514 /// pointer itself.
515 Andersens::Node *Andersens::getNodeForConstantPointer(Constant *C) {
516   assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
517
518   if (isa<ConstantPointerNull>(C) || isa<UndefValue>(C))
519     return &GraphNodes[NullPtr];
520   else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
521     return getNode(GV);
522   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
523     switch (CE->getOpcode()) {
524     case Instruction::GetElementPtr:
525       return getNodeForConstantPointer(CE->getOperand(0));
526     case Instruction::Cast:
527       if (isa<PointerType>(CE->getOperand(0)->getType()))
528         return getNodeForConstantPointer(CE->getOperand(0));
529       else
530         return &GraphNodes[UniversalSet];
531     default:
532       std::cerr << "Constant Expr not yet handled: " << *CE << "\n";
533       assert(0);
534     }
535   } else {
536     assert(0 && "Unknown constant pointer!");
537   }
538   return 0;
539 }
540
541 /// getNodeForConstantPointerTarget - Return the node POINTED TO by the
542 /// specified constant pointer.
543 Andersens::Node *Andersens::getNodeForConstantPointerTarget(Constant *C) {
544   assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
545
546   if (isa<ConstantPointerNull>(C))
547     return &GraphNodes[NullObject];
548   else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
549     return getObject(GV);
550   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
551     switch (CE->getOpcode()) {
552     case Instruction::GetElementPtr:
553       return getNodeForConstantPointerTarget(CE->getOperand(0));
554     case Instruction::Cast:
555       if (isa<PointerType>(CE->getOperand(0)->getType()))
556         return getNodeForConstantPointerTarget(CE->getOperand(0));
557       else
558         return &GraphNodes[UniversalSet];
559     default:
560       std::cerr << "Constant Expr not yet handled: " << *CE << "\n";
561       assert(0);
562     }
563   } else {
564     assert(0 && "Unknown constant pointer!");
565   }
566   return 0;
567 }
568
569 /// AddGlobalInitializerConstraints - Add inclusion constraints for the memory
570 /// object N, which contains values indicated by C.
571 void Andersens::AddGlobalInitializerConstraints(Node *N, Constant *C) {
572   if (C->getType()->isFirstClassType()) {
573     if (isa<PointerType>(C->getType()))
574       N->copyFrom(getNodeForConstantPointer(C));
575
576   } else if (C->isNullValue()) {
577     N->addPointerTo(&GraphNodes[NullObject]);
578     return;
579   } else if (!isa<UndefValue>(C)) {
580     // 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
587 /// 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.
590 void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
591   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
592     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
599 /// 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.
602 bool Andersens::AddConstraintsForExternalCall(CallSite CS, Function *F) {
603   assert(F->isExternal() && "Not an external function!");
604
605   // These functions don't induce any points-to constraints.
606   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" ||
610       F->getName() == "llvm.memset" ||
611       F->getName() == "strcmp" || F->getName() == "strncmp" ||
612       F->getName() == "execl" || F->getName() == "execlp" ||
613       F->getName() == "execle" || F->getName() == "execv" ||
614       F->getName() == "execvp" || F->getName() == "chmod" ||
615       F->getName() == "puts" || F->getName() == "write" ||
616       F->getName() == "open" || F->getName() == "create" ||
617       F->getName() == "truncate" || F->getName() == "chdir" ||
618       F->getName() == "mkdir" || F->getName() == "rmdir" ||
619       F->getName() == "read" || F->getName() == "pipe" ||
620       F->getName() == "wait" || F->getName() == "time" ||
621       F->getName() == "stat" || F->getName() == "fstat" ||
622       F->getName() == "lstat" || F->getName() == "strtod" ||
623       F->getName() == "strtof" || F->getName() == "strtold" ||
624       F->getName() == "fopen" || F->getName() == "fdopen" ||
625       F->getName() == "freopen" ||
626       F->getName() == "fflush" || F->getName() == "feof" ||
627       F->getName() == "fileno" || F->getName() == "clearerr" ||
628       F->getName() == "rewind" || F->getName() == "ftell" ||
629       F->getName() == "ferror" || F->getName() == "fgetc" ||
630       F->getName() == "fgetc" || F->getName() == "_IO_getc" ||
631       F->getName() == "fwrite" || F->getName() == "fread" ||
632       F->getName() == "fgets" || F->getName() == "ungetc" ||
633       F->getName() == "fputc" ||
634       F->getName() == "fputs" || F->getName() == "putc" ||
635       F->getName() == "ftell" || F->getName() == "rewind" ||
636       F->getName() == "_IO_putc" || F->getName() == "fseek" ||
637       F->getName() == "fgetpos" || F->getName() == "fsetpos" ||
638       F->getName() == "printf" || F->getName() == "fprintf" ||
639       F->getName() == "sprintf" || F->getName() == "vprintf" ||
640       F->getName() == "vfprintf" || F->getName() == "vsprintf" ||
641       F->getName() == "scanf" || F->getName() == "fscanf" ||
642       F->getName() == "sscanf" || F->getName() == "__assert_fail" ||
643       F->getName() == "modf")
644     return true;
645
646
647   // These functions do induce points-to edges.
648   if (F->getName() == "llvm.memcpy" || F->getName() == "llvm.memmove" ||
649       F->getName() == "memmove") {
650     // Note: this is a poor approximation, this says Dest = Src, instead of
651     // *Dest = *Src.
652     Constraints.push_back(Constraint(Constraint::Copy,
653                                      getNode(CS.getArgument(0)),
654                                      getNode(CS.getArgument(1))));
655     return true;
656   }
657
658   // Result = Arg0
659   if (F->getName() == "realloc" || F->getName() == "strchr" ||
660       F->getName() == "strrchr" || F->getName() == "strstr" ||
661       F->getName() == "strtok") {
662     Constraints.push_back(Constraint(Constraint::Copy,
663                                      getNode(CS.getInstruction()),
664                                      getNode(CS.getArgument(0))));
665     return true;
666   }
667
668   return false;
669 }
670
671
672
673 /// CollectConstraints - This stage scans the program, adding a constraint to
674 /// the Constraints list for each instruction in the program that induces a
675 /// constraint, and setting up the initial points-to graph.
676 ///
677 void Andersens::CollectConstraints(Module &M) {
678   // First, the universal set points to itself.
679   GraphNodes[UniversalSet].addPointerTo(&GraphNodes[UniversalSet]);
680   //Constraints.push_back(Constraint(Constraint::Load, &GraphNodes[UniversalSet],
681   //                                 &GraphNodes[UniversalSet]));
682   Constraints.push_back(Constraint(Constraint::Store, &GraphNodes[UniversalSet],
683                                    &GraphNodes[UniversalSet]));
684
685   // Next, the null pointer points to the null object.
686   GraphNodes[NullPtr].addPointerTo(&GraphNodes[NullObject]);
687
688   // Next, add any constraints on global variables and their initializers.
689   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
690        I != E; ++I) {
691     // Associate the address of the global object as pointing to the memory for
692     // the global: &G = <G memory>
693     Node *Object = getObject(I);
694     Object->setValue(I);
695     getNodeValue(*I)->addPointerTo(Object);
696
697     if (I->hasInitializer()) {
698       AddGlobalInitializerConstraints(Object, I->getInitializer());
699     } else {
700       // If it doesn't have an initializer (i.e. it's defined in another
701       // translation unit), it points to the universal set.
702       Constraints.push_back(Constraint(Constraint::Copy, Object,
703                                        &GraphNodes[UniversalSet]));
704     }
705   }
706
707   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
708     // Make the function address point to the function object.
709     getNodeValue(*F)->addPointerTo(getObject(F)->setValue(F));
710
711     // Set up the return value node.
712     if (isa<PointerType>(F->getFunctionType()->getReturnType()))
713       getReturnNode(F)->setValue(F);
714     if (F->getFunctionType()->isVarArg())
715       getVarargNode(F)->setValue(F);
716
717     // Set up incoming argument nodes.
718     for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
719          I != E; ++I)
720       if (isa<PointerType>(I->getType()))
721         getNodeValue(*I);
722
723     if (!F->hasInternalLinkage())
724       AddConstraintsForNonInternalLinkage(F);
725
726     if (!F->isExternal()) {
727       // Scan the function body, creating a memory object for each heap/stack
728       // allocation in the body of the function and a node to represent all
729       // pointer values defined by instructions and used as operands.
730       visit(F);
731     } else {
732       // External functions that return pointers return the universal set.
733       if (isa<PointerType>(F->getFunctionType()->getReturnType()))
734         Constraints.push_back(Constraint(Constraint::Copy,
735                                          getReturnNode(F),
736                                          &GraphNodes[UniversalSet]));
737
738       // Any pointers that are passed into the function have the universal set
739       // stored into them.
740       for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
741            I != E; ++I)
742         if (isa<PointerType>(I->getType())) {
743           // Pointers passed into external functions could have anything stored
744           // through them.
745           Constraints.push_back(Constraint(Constraint::Store, getNode(I),
746                                            &GraphNodes[UniversalSet]));
747           // Memory objects passed into external function calls can have the
748           // universal set point to them.
749           Constraints.push_back(Constraint(Constraint::Copy,
750                                            &GraphNodes[UniversalSet],
751                                            getNode(I)));
752         }
753
754       // If this is an external varargs function, it can also store pointers
755       // into any pointers passed through the varargs section.
756       if (F->getFunctionType()->isVarArg())
757         Constraints.push_back(Constraint(Constraint::Store, getVarargNode(F),
758                                          &GraphNodes[UniversalSet]));
759     }
760   }
761   NumConstraints += Constraints.size();
762 }
763
764
765 void Andersens::visitInstruction(Instruction &I) {
766 #ifdef NDEBUG
767   return;          // This function is just a big assert.
768 #endif
769   if (isa<BinaryOperator>(I))
770     return;
771   // Most instructions don't have any effect on pointer values.
772   switch (I.getOpcode()) {
773   case Instruction::Br:
774   case Instruction::Switch:
775   case Instruction::Unwind:
776   case Instruction::Unreachable:
777   case Instruction::Free:
778   case Instruction::Shl:
779   case Instruction::Shr:
780     return;
781   default:
782     // Is this something we aren't handling yet?
783     std::cerr << "Unknown instruction: " << I;
784     abort();
785   }
786 }
787
788 void Andersens::visitAllocationInst(AllocationInst &AI) {
789   getNodeValue(AI)->addPointerTo(getObject(&AI)->setValue(&AI));
790 }
791
792 void Andersens::visitReturnInst(ReturnInst &RI) {
793   if (RI.getNumOperands() && isa<PointerType>(RI.getOperand(0)->getType()))
794     // return V   -->   <Copy/retval{F}/v>
795     Constraints.push_back(Constraint(Constraint::Copy,
796                                      getReturnNode(RI.getParent()->getParent()),
797                                      getNode(RI.getOperand(0))));
798 }
799
800 void Andersens::visitLoadInst(LoadInst &LI) {
801   if (isa<PointerType>(LI.getType()))
802     // P1 = load P2  -->  <Load/P1/P2>
803     Constraints.push_back(Constraint(Constraint::Load, getNodeValue(LI),
804                                      getNode(LI.getOperand(0))));
805 }
806
807 void Andersens::visitStoreInst(StoreInst &SI) {
808   if (isa<PointerType>(SI.getOperand(0)->getType()))
809     // store P1, P2  -->  <Store/P2/P1>
810     Constraints.push_back(Constraint(Constraint::Store,
811                                      getNode(SI.getOperand(1)),
812                                      getNode(SI.getOperand(0))));
813 }
814
815 void Andersens::visitGetElementPtrInst(GetElementPtrInst &GEP) {
816   // P1 = getelementptr P2, ... --> <Copy/P1/P2>
817   Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(GEP),
818                                    getNode(GEP.getOperand(0))));
819 }
820
821 void Andersens::visitPHINode(PHINode &PN) {
822   if (isa<PointerType>(PN.getType())) {
823     Node *PNN = getNodeValue(PN);
824     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
825       // P1 = phi P2, P3  -->  <Copy/P1/P2>, <Copy/P1/P3>, ...
826       Constraints.push_back(Constraint(Constraint::Copy, PNN,
827                                        getNode(PN.getIncomingValue(i))));
828   }
829 }
830
831 void Andersens::visitCastInst(CastInst &CI) {
832   Value *Op = CI.getOperand(0);
833   if (isa<PointerType>(CI.getType())) {
834     if (isa<PointerType>(Op->getType())) {
835       // P1 = cast P2  --> <Copy/P1/P2>
836       Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
837                                        getNode(CI.getOperand(0))));
838     } else {
839       // P1 = cast int --> <Copy/P1/Univ>
840 #if 0
841       Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
842                                        &GraphNodes[UniversalSet]));
843 #else
844       getNodeValue(CI);
845 #endif
846     }
847   } else if (isa<PointerType>(Op->getType())) {
848     // int = cast P1 --> <Copy/Univ/P1>
849 #if 0
850     Constraints.push_back(Constraint(Constraint::Copy,
851                                      &GraphNodes[UniversalSet],
852                                      getNode(CI.getOperand(0))));
853 #else
854     getNode(CI.getOperand(0));
855 #endif
856   }
857 }
858
859 void Andersens::visitSelectInst(SelectInst &SI) {
860   if (isa<PointerType>(SI.getType())) {
861     Node *SIN = getNodeValue(SI);
862     // P1 = select C, P2, P3   ---> <Copy/P1/P2>, <Copy/P1/P3>
863     Constraints.push_back(Constraint(Constraint::Copy, SIN,
864                                      getNode(SI.getOperand(1))));
865     Constraints.push_back(Constraint(Constraint::Copy, SIN,
866                                      getNode(SI.getOperand(2))));
867   }
868 }
869
870 void Andersens::visitVANext(VANextInst &I) {
871   // FIXME: Implement
872   assert(0 && "vanext not handled yet!");
873 }
874 void Andersens::visitVAArg(VAArgInst &I) {
875   assert(0 && "vaarg not handled yet!");
876 }
877
878 /// AddConstraintsForCall - Add constraints for a call with actual arguments
879 /// specified by CS to the function specified by F.  Note that the types of
880 /// arguments might not match up in the case where this is an indirect call and
881 /// the function pointer has been casted.  If this is the case, do something
882 /// reasonable.
883 void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
884   // If this is a call to an external function, handle it directly to get some
885   // taste of context sensitivity.
886   if (F->isExternal() && AddConstraintsForExternalCall(CS, F))
887     return;
888
889   if (isa<PointerType>(CS.getType())) {
890     Node *CSN = getNode(CS.getInstruction());
891     if (isa<PointerType>(F->getFunctionType()->getReturnType())) {
892       Constraints.push_back(Constraint(Constraint::Copy, CSN,
893                                        getReturnNode(F)));
894     } else {
895       // If the function returns a non-pointer value, handle this just like we
896       // treat a nonpointer cast to pointer.
897       Constraints.push_back(Constraint(Constraint::Copy, CSN,
898                                        &GraphNodes[UniversalSet]));
899     }
900   } else if (isa<PointerType>(F->getFunctionType()->getReturnType())) {
901     Constraints.push_back(Constraint(Constraint::Copy,
902                                      &GraphNodes[UniversalSet],
903                                      getReturnNode(F)));
904   }
905
906   Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
907   CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
908   for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI)
909     if (isa<PointerType>(AI->getType())) {
910       if (isa<PointerType>((*ArgI)->getType())) {
911         // Copy the actual argument into the formal argument.
912         Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
913                                          getNode(*ArgI)));
914       } else {
915         Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
916                                          &GraphNodes[UniversalSet]));
917       }
918     } else if (isa<PointerType>((*ArgI)->getType())) {
919       Constraints.push_back(Constraint(Constraint::Copy,
920                                        &GraphNodes[UniversalSet],
921                                        getNode(*ArgI)));
922     }
923
924   // Copy all pointers passed through the varargs section to the varargs node.
925   if (F->getFunctionType()->isVarArg())
926     for (; ArgI != ArgE; ++ArgI)
927       if (isa<PointerType>((*ArgI)->getType()))
928         Constraints.push_back(Constraint(Constraint::Copy, getVarargNode(F),
929                                          getNode(*ArgI)));
930   // If more arguments are passed in than we track, just drop them on the floor.
931 }
932
933 void Andersens::visitCallSite(CallSite CS) {
934   if (isa<PointerType>(CS.getType()))
935     getNodeValue(*CS.getInstruction());
936
937   if (Function *F = CS.getCalledFunction()) {
938     AddConstraintsForCall(CS, F);
939   } else {
940     // We don't handle indirect call sites yet.  Keep track of them for when we
941     // discover the call graph incrementally.
942     IndirectCalls.push_back(CS);
943   }
944 }
945
946 //===----------------------------------------------------------------------===//
947 //                         Constraint Solving Phase
948 //===----------------------------------------------------------------------===//
949
950 /// intersects - Return true if the points-to set of this node intersects
951 /// with the points-to set of the specified node.
952 bool Andersens::Node::intersects(Node *N) const {
953   iterator I1 = begin(), I2 = N->begin(), E1 = end(), E2 = N->end();
954   while (I1 != E1 && I2 != E2) {
955     if (*I1 == *I2) return true;
956     if (*I1 < *I2)
957       ++I1;
958     else
959       ++I2;
960   }
961   return false;
962 }
963
964 /// intersectsIgnoring - Return true if the points-to set of this node
965 /// intersects with the points-to set of the specified node on any nodes
966 /// except for the specified node to ignore.
967 bool Andersens::Node::intersectsIgnoring(Node *N, Node *Ignoring) const {
968   iterator I1 = begin(), I2 = N->begin(), E1 = end(), E2 = N->end();
969   while (I1 != E1 && I2 != E2) {
970     if (*I1 == *I2) {
971       if (*I1 != Ignoring) return true;
972       ++I1; ++I2;
973     } else if (*I1 < *I2)
974       ++I1;
975     else
976       ++I2;
977   }
978   return false;
979 }
980
981 // Copy constraint: all edges out of the source node get copied to the
982 // destination node.  This returns true if a change is made.
983 bool Andersens::Node::copyFrom(Node *N) {
984   // Use a mostly linear-time merge since both of the lists are sorted.
985   bool Changed = false;
986   iterator I = N->begin(), E = N->end();
987   unsigned i = 0;
988   while (I != E && i != Pointees.size()) {
989     if (Pointees[i] < *I) {
990       ++i;
991     } else if (Pointees[i] == *I) {
992       ++i; ++I;
993     } else {
994       // We found a new element to copy over.
995       Changed = true;
996       Pointees.insert(Pointees.begin()+i, *I);
997        ++i; ++I;
998     }
999   }
1000
1001   if (I != E) {
1002     Pointees.insert(Pointees.end(), I, E);
1003     Changed = true;
1004   }
1005
1006   return Changed;
1007 }
1008
1009 bool Andersens::Node::loadFrom(Node *N) {
1010   bool Changed = false;
1011   for (iterator I = N->begin(), E = N->end(); I != E; ++I)
1012     Changed |= copyFrom(*I);
1013   return Changed;
1014 }
1015
1016 bool Andersens::Node::storeThrough(Node *N) {
1017   bool Changed = false;
1018   for (iterator I = begin(), E = end(); I != E; ++I)
1019     Changed |= (*I)->copyFrom(N);
1020   return Changed;
1021 }
1022
1023
1024 /// SolveConstraints - This stage iteratively processes the constraints list
1025 /// propagating constraints (adding edges to the Nodes in the points-to graph)
1026 /// until a fixed point is reached.
1027 ///
1028 void Andersens::SolveConstraints() {
1029   bool Changed = true;
1030   unsigned Iteration = 0;
1031   while (Changed) {
1032     Changed = false;
1033     ++NumIters;
1034     DEBUG(std::cerr << "Starting iteration #" << Iteration++ << "!\n");
1035
1036     // Loop over all of the constraints, applying them in turn.
1037     for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1038       Constraint &C = Constraints[i];
1039       switch (C.Type) {
1040       case Constraint::Copy:
1041         Changed |= C.Dest->copyFrom(C.Src);
1042         break;
1043       case Constraint::Load:
1044         Changed |= C.Dest->loadFrom(C.Src);
1045         break;
1046       case Constraint::Store:
1047         Changed |= C.Dest->storeThrough(C.Src);
1048         break;
1049       default:
1050         assert(0 && "Unknown constraint!");
1051       }
1052     }
1053
1054     if (Changed) {
1055       // Check to see if any internal function's addresses have been passed to
1056       // external functions.  If so, we have to assume that their incoming
1057       // arguments could be anything.  If there are any internal functions in
1058       // the universal node that we don't know about, we must iterate.
1059       for (Node::iterator I = GraphNodes[UniversalSet].begin(),
1060              E = GraphNodes[UniversalSet].end(); I != E; ++I)
1061         if (Function *F = dyn_cast_or_null<Function>((*I)->getValue()))
1062           if (F->hasInternalLinkage() &&
1063               EscapingInternalFunctions.insert(F).second) {
1064             // We found a function that is just now escaping.  Mark it as if it
1065             // didn't have internal linkage.
1066             AddConstraintsForNonInternalLinkage(F);
1067             DEBUG(std::cerr << "Found escaping internal function: "
1068                             << F->getName() << "\n");
1069             ++NumEscapingFunctions;
1070           }
1071
1072       // Check to see if we have discovered any new callees of the indirect call
1073       // sites.  If so, add constraints to the analysis.
1074       for (unsigned i = 0, e = IndirectCalls.size(); i != e; ++i) {
1075         CallSite CS = IndirectCalls[i];
1076         std::vector<Function*> &KnownCallees = IndirectCallees[CS];
1077         Node *CN = getNode(CS.getCalledValue());
1078
1079         for (Node::iterator NI = CN->begin(), E = CN->end(); NI != E; ++NI)
1080           if (Function *F = dyn_cast_or_null<Function>((*NI)->getValue())) {
1081             std::vector<Function*>::iterator IP =
1082               std::lower_bound(KnownCallees.begin(), KnownCallees.end(), F);
1083             if (IP == KnownCallees.end() || *IP != F) {
1084               // Add the constraints for the call now.
1085               AddConstraintsForCall(CS, F);
1086               DEBUG(std::cerr << "Found actual callee '"
1087                               << F->getName() << "' for call: "
1088                               << *CS.getInstruction() << "\n");
1089               ++NumIndirectCallees;
1090               KnownCallees.insert(IP, F);
1091             }
1092           }
1093       }
1094     }
1095   }
1096 }
1097
1098
1099
1100 //===----------------------------------------------------------------------===//
1101 //                               Debugging Output
1102 //===----------------------------------------------------------------------===//
1103
1104 void Andersens::PrintNode(Node *N) {
1105   if (N == &GraphNodes[UniversalSet]) {
1106     std::cerr << "<universal>";
1107     return;
1108   } else if (N == &GraphNodes[NullPtr]) {
1109     std::cerr << "<nullptr>";
1110     return;
1111   } else if (N == &GraphNodes[NullObject]) {
1112     std::cerr << "<null>";
1113     return;
1114   }
1115
1116   assert(N->getValue() != 0 && "Never set node label!");
1117   Value *V = N->getValue();
1118   if (Function *F = dyn_cast<Function>(V)) {
1119     if (isa<PointerType>(F->getFunctionType()->getReturnType()) &&
1120         N == getReturnNode(F)) {
1121       std::cerr << F->getName() << ":retval";
1122       return;
1123     } else if (F->getFunctionType()->isVarArg() && N == getVarargNode(F)) {
1124       std::cerr << F->getName() << ":vararg";
1125       return;
1126     }
1127   }
1128
1129   if (Instruction *I = dyn_cast<Instruction>(V))
1130     std::cerr << I->getParent()->getParent()->getName() << ":";
1131   else if (Argument *Arg = dyn_cast<Argument>(V))
1132     std::cerr << Arg->getParent()->getName() << ":";
1133
1134   if (V->hasName())
1135     std::cerr << V->getName();
1136   else
1137     std::cerr << "(unnamed)";
1138
1139   if (isa<GlobalValue>(V) || isa<AllocationInst>(V))
1140     if (N == getObject(V))
1141       std::cerr << "<mem>";
1142 }
1143
1144 void Andersens::PrintConstraints() {
1145   std::cerr << "Constraints:\n";
1146   for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1147     std::cerr << "  #" << i << ":  ";
1148     Constraint &C = Constraints[i];
1149     if (C.Type == Constraint::Store)
1150       std::cerr << "*";
1151     PrintNode(C.Dest);
1152     std::cerr << " = ";
1153     if (C.Type == Constraint::Load)
1154       std::cerr << "*";
1155     PrintNode(C.Src);
1156     std::cerr << "\n";
1157   }
1158 }
1159
1160 void Andersens::PrintPointsToGraph() {
1161   std::cerr << "Points-to graph:\n";
1162   for (unsigned i = 0, e = GraphNodes.size(); i != e; ++i) {
1163     Node *N = &GraphNodes[i];
1164     std::cerr << "[" << (N->end() - N->begin()) << "] ";
1165     PrintNode(N);
1166     std::cerr << "\t--> ";
1167     for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I) {
1168       if (I != N->begin()) std::cerr << ", ";
1169       PrintNode(*I);
1170     }
1171     std::cerr << "\n";
1172   }
1173 }