Ensure that dump calls that are associated with asserts are removed from
[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 #include <iostream>
66 using namespace llvm;
67
68 namespace {
69   Statistic<>
70   NumIters("anders-aa", "Number of iterations to reach convergence");
71   Statistic<>
72   NumConstraints("anders-aa", "Number of constraints");
73   Statistic<>
74   NumNodes("anders-aa", "Number of nodes");
75   Statistic<>
76   NumEscapingFunctions("anders-aa", "Number of internal functions that escape");
77   Statistic<>
78   NumIndirectCallees("anders-aa", "Number of indirect callees found");
79
80   class Andersens : public ModulePass, public AliasAnalysis,
81                     private InstVisitor<Andersens> {
82     /// Node class - This class is used to represent a memory object in the
83     /// program, and is the primitive used to build the points-to graph.
84     class Node {
85       std::vector<Node*> Pointees;
86       Value *Val;
87     public:
88       Node() : Val(0) {}
89       Node *setValue(Value *V) {
90         assert(Val == 0 && "Value already set for this node!");
91         Val = V;
92         return this;
93       }
94
95       /// getValue - Return the LLVM value corresponding to this node.
96       ///
97       Value *getValue() const { return Val; }
98
99       typedef std::vector<Node*>::const_iterator iterator;
100       iterator begin() const { return Pointees.begin(); }
101       iterator end() const { return Pointees.end(); }
102
103       /// addPointerTo - Add a pointer to the list of pointees of this node,
104       /// returning true if this caused a new pointer to be added, or false if
105       /// we already knew about the points-to relation.
106       bool addPointerTo(Node *N) {
107         std::vector<Node*>::iterator I = std::lower_bound(Pointees.begin(),
108                                                           Pointees.end(),
109                                                           N);
110         if (I != Pointees.end() && *I == N)
111           return false;
112         Pointees.insert(I, N);
113         return true;
114       }
115
116       /// intersects - Return true if the points-to set of this node intersects
117       /// with the points-to set of the specified node.
118       bool intersects(Node *N) const;
119
120       /// intersectsIgnoring - Return true if the points-to set of this node
121       /// intersects with the points-to set of the specified node on any nodes
122       /// except for the specified node to ignore.
123       bool intersectsIgnoring(Node *N, Node *Ignoring) const;
124
125       // Constraint application methods.
126       bool copyFrom(Node *N);
127       bool loadFrom(Node *N);
128       bool storeThrough(Node *N);
129     };
130
131     /// GraphNodes - This vector is populated as part of the object
132     /// identification stage of the analysis, which populates this vector with a
133     /// node for each memory object and fills in the ValueNodes map.
134     std::vector<Node> GraphNodes;
135
136     /// ValueNodes - This map indicates the Node that a particular Value* is
137     /// represented by.  This contains entries for all pointers.
138     std::map<Value*, unsigned> ValueNodes;
139
140     /// ObjectNodes - This map contains entries for each memory object in the
141     /// program: globals, alloca's and mallocs.
142     std::map<Value*, unsigned> ObjectNodes;
143
144     /// ReturnNodes - This map contains an entry for each function in the
145     /// program that returns a value.
146     std::map<Function*, unsigned> ReturnNodes;
147
148     /// VarargNodes - This map contains the entry used to represent all pointers
149     /// passed through the varargs portion of a function call for a particular
150     /// function.  An entry is not present in this map for functions that do not
151     /// take variable arguments.
152     std::map<Function*, unsigned> VarargNodes;
153
154     /// Constraint - Objects of this structure are used to represent the various
155     /// constraints identified by the algorithm.  The constraints are 'copy',
156     /// for statements like "A = B", 'load' for statements like "A = *B", and
157     /// 'store' for statements like "*A = B".
158     struct Constraint {
159       enum ConstraintType { Copy, Load, Store } Type;
160       Node *Dest, *Src;
161
162       Constraint(ConstraintType Ty, Node *D, Node *S)
163         : Type(Ty), Dest(D), Src(S) {}
164     };
165
166     /// Constraints - This vector contains a list of all of the constraints
167     /// identified by the program.
168     std::vector<Constraint> Constraints;
169
170     /// EscapingInternalFunctions - This set contains all of the internal
171     /// functions that are found to escape from the program.  If the address of
172     /// an internal function is passed to an external function or otherwise
173     /// escapes from the analyzed portion of the program, we must assume that
174     /// any pointer arguments can alias the universal node.  This set keeps
175     /// track of those functions we are assuming to escape so far.
176     std::set<Function*> EscapingInternalFunctions;
177
178     /// IndirectCalls - This contains a list of all of the indirect call sites
179     /// in the program.  Since the call graph is iteratively discovered, we may
180     /// need to add constraints to our graph as we find new targets of function
181     /// pointers.
182     std::vector<CallSite> IndirectCalls;
183
184     /// IndirectCallees - For each call site in the indirect calls list, keep
185     /// track of the callees that we have discovered so far.  As the analysis
186     /// proceeds, more callees are discovered, until the call graph finally
187     /// stabilizes.
188     std::map<CallSite, std::vector<Function*> > IndirectCallees;
189
190     /// This enum defines the GraphNodes indices that correspond to important
191     /// fixed sets.
192     enum {
193       UniversalSet = 0,
194       NullPtr      = 1,
195       NullObject   = 2
196     };
197
198   public:
199     bool runOnModule(Module &M) {
200       InitializeAliasAnalysis(this);
201       IdentifyObjects(M);
202       CollectConstraints(M);
203       DEBUG(PrintConstraints());
204       SolveConstraints();
205       DEBUG(PrintPointsToGraph());
206
207       // Free the constraints list, as we don't need it to respond to alias
208       // requests.
209       ObjectNodes.clear();
210       ReturnNodes.clear();
211       VarargNodes.clear();
212       EscapingInternalFunctions.clear();
213       std::vector<Constraint>().swap(Constraints);
214       return false;
215     }
216
217     void releaseMemory() {
218       // FIXME: Until we have transitively required passes working correctly,
219       // this cannot be enabled!  Otherwise, using -count-aa with the pass
220       // causes memory to be freed too early. :(
221 #if 0
222       // The memory objects and ValueNodes data structures at the only ones that
223       // are still live after construction.
224       std::vector<Node>().swap(GraphNodes);
225       ValueNodes.clear();
226 #endif
227     }
228
229     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
230       AliasAnalysis::getAnalysisUsage(AU);
231       AU.setPreservesAll();                         // Does not transform code
232     }
233
234     //------------------------------------------------
235     // Implement the AliasAnalysis API
236     //
237     AliasResult alias(const Value *V1, unsigned V1Size,
238                       const Value *V2, unsigned V2Size);
239     ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
240     void getMustAliases(Value *P, std::vector<Value*> &RetVals);
241     bool pointsToConstantMemory(const Value *P);
242
243     virtual void deleteValue(Value *V) {
244       ValueNodes.erase(V);
245       getAnalysis<AliasAnalysis>().deleteValue(V);
246     }
247
248     virtual void copyValue(Value *From, Value *To) {
249       ValueNodes[To] = ValueNodes[From];
250       getAnalysis<AliasAnalysis>().copyValue(From, To);
251     }
252
253   private:
254     /// getNode - Return the node corresponding to the specified pointer scalar.
255     ///
256     Node *getNode(Value *V) {
257       if (Constant *C = dyn_cast<Constant>(V))
258         if (!isa<GlobalValue>(C))
259           return getNodeForConstantPointer(C);
260
261       std::map<Value*, unsigned>::iterator I = ValueNodes.find(V);
262       if (I == ValueNodes.end()) {
263         DEBUG(V->dump());
264         assert(0 && "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 visitVAArg(VAArgInst &I);
334     void visitInstruction(Instruction &I);
335   };
336
337   RegisterOpt<Andersens> X("anders-aa",
338                            "Andersen's Interprocedural Alias Analysis");
339   RegisterAnalysisGroup<AliasAnalysis, Andersens> Y;
340 }
341
342 ModulePass *llvm::createAndersensPass() { return new Andersens(); }
343
344 //===----------------------------------------------------------------------===//
345 //                  AliasAnalysis Interface Implementation
346 //===----------------------------------------------------------------------===//
347
348 AliasAnalysis::AliasResult Andersens::alias(const Value *V1, unsigned V1Size,
349                                             const Value *V2, unsigned V2Size) {
350   Node *N1 = getNode(const_cast<Value*>(V1));
351   Node *N2 = getNode(const_cast<Value*>(V2));
352
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
361 AliasAnalysis::ModRefResult
362 Andersens::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())
372     if (F->isExternal()) {
373       Node *N1 = getNode(P);
374       bool PointsToUniversalSet = false;
375
376       if (N1->begin() == N1->end())
377         return NoModRef;  // P doesn't point to anything.
378
379       // Get the first pointee.
380       Node *FirstPointee = *N1->begin();
381       if (FirstPointee != &GraphNodes[UniversalSet])
382         return NoModRef;  // P doesn't point to the universal set.
383     }
384
385   return AliasAnalysis::getModRefInfo(CS, P, Size);
386 }
387
388 /// getMustAlias - We can provide must alias information if we know that a
389 /// pointer can only point to a specific function or the null pointer.
390 /// Unfortunately we cannot determine must-alias information for global
391 /// variables or any other memory memory objects because we do not track whether
392 /// a pointer points to the beginning of an object or a field of it.
393 void Andersens::getMustAliases(Value *P, std::vector<Value*> &RetVals) {
394   Node *N = getNode(P);
395   Node::iterator I = N->begin();
396   if (I != N->end()) {
397     // If there is exactly one element in the points-to set for the object...
398     ++I;
399     if (I == N->end()) {
400       Node *Pointee = *N->begin();
401
402       // If a function is the only object in the points-to set, then it must be
403       // the destination.  Note that we can't handle global variables here,
404       // because we don't know if the pointer is actually pointing to a field of
405       // the global or to the beginning of it.
406       if (Value *V = Pointee->getValue()) {
407         if (Function *F = dyn_cast<Function>(V))
408           RetVals.push_back(F);
409       } else {
410         // If the object in the points-to set is the null object, then the null
411         // pointer is a must alias.
412         if (Pointee == &GraphNodes[NullObject])
413           RetVals.push_back(Constant::getNullValue(P->getType()));
414       }
415     }
416   }
417
418   AliasAnalysis::getMustAliases(P, RetVals);
419 }
420
421 /// pointsToConstantMemory - If we can determine that this pointer only points
422 /// to constant memory, return true.  In practice, this means that if the
423 /// pointer can only point to constant globals, functions, or the null pointer,
424 /// return true.
425 ///
426 bool Andersens::pointsToConstantMemory(const Value *P) {
427   Node *N = getNode((Value*)P);
428   for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I) {
429     if (Value *V = (*I)->getValue()) {
430       if (!isa<GlobalValue>(V) || (isa<GlobalVariable>(V) &&
431                                    !cast<GlobalVariable>(V)->isConstant()))
432         return AliasAnalysis::pointsToConstantMemory(P);
433     } else {
434       if (*I != &GraphNodes[NullObject])
435         return AliasAnalysis::pointsToConstantMemory(P);
436     }
437   }
438
439   return true;
440 }
441
442 //===----------------------------------------------------------------------===//
443 //                       Object Identification Phase
444 //===----------------------------------------------------------------------===//
445
446 /// IdentifyObjects - This stage scans the program, adding an entry to the
447 /// GraphNodes list for each memory object in the program (global stack or
448 /// heap), and populates the ValueNodes and ObjectNodes maps for these objects.
449 ///
450 void Andersens::IdentifyObjects(Module &M) {
451   unsigned NumObjects = 0;
452
453   // Object #0 is always the universal set: the object that we don't know
454   // anything about.
455   assert(NumObjects == UniversalSet && "Something changed!");
456   ++NumObjects;
457
458   // Object #1 always represents the null pointer.
459   assert(NumObjects == NullPtr && "Something changed!");
460   ++NumObjects;
461
462   // Object #2 always represents the null object (the object pointed to by null)
463   assert(NumObjects == NullObject && "Something changed!");
464   ++NumObjects;
465
466   // Add all the globals first.
467   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
468        I != E; ++I) {
469     ObjectNodes[I] = NumObjects++;
470     ValueNodes[I] = NumObjects++;
471   }
472
473   // Add nodes for all of the functions and the instructions inside of them.
474   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
475     // The function itself is a memory object.
476     ValueNodes[F] = NumObjects++;
477     ObjectNodes[F] = NumObjects++;
478     if (isa<PointerType>(F->getFunctionType()->getReturnType()))
479       ReturnNodes[F] = NumObjects++;
480     if (F->getFunctionType()->isVarArg())
481       VarargNodes[F] = NumObjects++;
482
483     // Add nodes for all of the incoming pointer arguments.
484     for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
485          I != E; ++I)
486       if (isa<PointerType>(I->getType()))
487         ValueNodes[I] = NumObjects++;
488
489     // Scan the function body, creating a memory object for each heap/stack
490     // allocation in the body of the function and a node to represent all
491     // pointer values defined by instructions and used as operands.
492     for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
493       // If this is an heap or stack allocation, create a node for the memory
494       // object.
495       if (isa<PointerType>(II->getType())) {
496         ValueNodes[&*II] = NumObjects++;
497         if (AllocationInst *AI = dyn_cast<AllocationInst>(&*II))
498           ObjectNodes[AI] = NumObjects++;
499       }
500     }
501   }
502
503   // Now that we know how many objects to create, make them all now!
504   GraphNodes.resize(NumObjects);
505   NumNodes += NumObjects;
506 }
507
508 //===----------------------------------------------------------------------===//
509 //                     Constraint Identification Phase
510 //===----------------------------------------------------------------------===//
511
512 /// getNodeForConstantPointer - Return the node corresponding to the constant
513 /// pointer itself.
514 Andersens::Node *Andersens::getNodeForConstantPointer(Constant *C) {
515   assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
516
517   if (isa<ConstantPointerNull>(C) || isa<UndefValue>(C))
518     return &GraphNodes[NullPtr];
519   else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
520     return getNode(GV);
521   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
522     switch (CE->getOpcode()) {
523     case Instruction::GetElementPtr:
524       return getNodeForConstantPointer(CE->getOperand(0));
525     case Instruction::Cast:
526       if (isa<PointerType>(CE->getOperand(0)->getType()))
527         return getNodeForConstantPointer(CE->getOperand(0));
528       else
529         return &GraphNodes[UniversalSet];
530     default:
531       std::cerr << "Constant Expr not yet handled: " << *CE << "\n";
532       assert(0);
533     }
534   } else {
535     assert(0 && "Unknown constant pointer!");
536   }
537   return 0;
538 }
539
540 /// getNodeForConstantPointerTarget - Return the node POINTED TO by the
541 /// specified constant pointer.
542 Andersens::Node *Andersens::getNodeForConstantPointerTarget(Constant *C) {
543   assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
544
545   if (isa<ConstantPointerNull>(C))
546     return &GraphNodes[NullObject];
547   else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
548     return getObject(GV);
549   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
550     switch (CE->getOpcode()) {
551     case Instruction::GetElementPtr:
552       return getNodeForConstantPointerTarget(CE->getOperand(0));
553     case Instruction::Cast:
554       if (isa<PointerType>(CE->getOperand(0)->getType()))
555         return getNodeForConstantPointerTarget(CE->getOperand(0));
556       else
557         return &GraphNodes[UniversalSet];
558     default:
559       std::cerr << "Constant Expr not yet handled: " << *CE << "\n";
560       assert(0);
561     }
562   } else {
563     assert(0 && "Unknown constant pointer!");
564   }
565   return 0;
566 }
567
568 /// AddGlobalInitializerConstraints - Add inclusion constraints for the memory
569 /// object N, which contains values indicated by C.
570 void Andersens::AddGlobalInitializerConstraints(Node *N, Constant *C) {
571   if (C->getType()->isFirstClassType()) {
572     if (isa<PointerType>(C->getType()))
573       N->copyFrom(getNodeForConstantPointer(C));
574
575   } else if (C->isNullValue()) {
576     N->addPointerTo(&GraphNodes[NullObject]);
577     return;
578   } else if (!isa<UndefValue>(C)) {
579     // If this is an array or struct, include constraints for each element.
580     assert(isa<ConstantArray>(C) || isa<ConstantStruct>(C));
581     for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
582       AddGlobalInitializerConstraints(N, cast<Constant>(C->getOperand(i)));
583   }
584 }
585
586 /// AddConstraintsForNonInternalLinkage - If this function does not have
587 /// internal linkage, realize that we can't trust anything passed into or
588 /// returned by this function.
589 void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
590   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
591     if (isa<PointerType>(I->getType()))
592       // If this is an argument of an externally accessible function, the
593       // incoming pointer might point to anything.
594       Constraints.push_back(Constraint(Constraint::Copy, getNode(I),
595                                        &GraphNodes[UniversalSet]));
596 }
597
598 /// AddConstraintsForCall - If this is a call to a "known" function, add the
599 /// constraints and return true.  If this is a call to an unknown function,
600 /// return false.
601 bool Andersens::AddConstraintsForExternalCall(CallSite CS, Function *F) {
602   assert(F->isExternal() && "Not an external function!");
603
604   // These functions don't induce any points-to constraints.
605   if (F->getName() == "atoi" || F->getName() == "atof" ||
606       F->getName() == "atol" || F->getName() == "atoll" ||
607       F->getName() == "remove" || F->getName() == "unlink" ||
608       F->getName() == "rename" || F->getName() == "memcmp" ||
609       F->getName() == "llvm.memset.i32" ||
610       F->getName() == "llvm.memset.i64" ||
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.i32" || F->getName() == "llvm.memcpy.i64" || 
649       F->getName() == "llvm.memmove.i32" ||F->getName() == "llvm.memmove.i64" ||
650       F->getName() == "memmove") {
651     // Note: this is a poor approximation, this says Dest = Src, instead of
652     // *Dest = *Src.
653     Constraints.push_back(Constraint(Constraint::Copy,
654                                      getNode(CS.getArgument(0)),
655                                      getNode(CS.getArgument(1))));
656     return true;
657   }
658
659   // Result = Arg0
660   if (F->getName() == "realloc" || F->getName() == "strchr" ||
661       F->getName() == "strrchr" || F->getName() == "strstr" ||
662       F->getName() == "strtok") {
663     Constraints.push_back(Constraint(Constraint::Copy,
664                                      getNode(CS.getInstruction()),
665                                      getNode(CS.getArgument(0))));
666     return true;
667   }
668
669   return false;
670 }
671
672
673
674 /// CollectConstraints - This stage scans the program, adding a constraint to
675 /// the Constraints list for each instruction in the program that induces a
676 /// constraint, and setting up the initial points-to graph.
677 ///
678 void Andersens::CollectConstraints(Module &M) {
679   // First, the universal set points to itself.
680   GraphNodes[UniversalSet].addPointerTo(&GraphNodes[UniversalSet]);
681   //Constraints.push_back(Constraint(Constraint::Load, &GraphNodes[UniversalSet],
682   //                                 &GraphNodes[UniversalSet]));
683   Constraints.push_back(Constraint(Constraint::Store, &GraphNodes[UniversalSet],
684                                    &GraphNodes[UniversalSet]));
685
686   // Next, the null pointer points to the null object.
687   GraphNodes[NullPtr].addPointerTo(&GraphNodes[NullObject]);
688
689   // Next, add any constraints on global variables and their initializers.
690   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
691        I != E; ++I) {
692     // Associate the address of the global object as pointing to the memory for
693     // the global: &G = <G memory>
694     Node *Object = getObject(I);
695     Object->setValue(I);
696     getNodeValue(*I)->addPointerTo(Object);
697
698     if (I->hasInitializer()) {
699       AddGlobalInitializerConstraints(Object, I->getInitializer());
700     } else {
701       // If it doesn't have an initializer (i.e. it's defined in another
702       // translation unit), it points to the universal set.
703       Constraints.push_back(Constraint(Constraint::Copy, Object,
704                                        &GraphNodes[UniversalSet]));
705     }
706   }
707
708   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
709     // Make the function address point to the function object.
710     getNodeValue(*F)->addPointerTo(getObject(F)->setValue(F));
711
712     // Set up the return value node.
713     if (isa<PointerType>(F->getFunctionType()->getReturnType()))
714       getReturnNode(F)->setValue(F);
715     if (F->getFunctionType()->isVarArg())
716       getVarargNode(F)->setValue(F);
717
718     // Set up incoming argument nodes.
719     for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
720          I != E; ++I)
721       if (isa<PointerType>(I->getType()))
722         getNodeValue(*I);
723
724     if (!F->hasInternalLinkage())
725       AddConstraintsForNonInternalLinkage(F);
726
727     if (!F->isExternal()) {
728       // Scan the function body, creating a memory object for each heap/stack
729       // allocation in the body of the function and a node to represent all
730       // pointer values defined by instructions and used as operands.
731       visit(F);
732     } else {
733       // External functions that return pointers return the universal set.
734       if (isa<PointerType>(F->getFunctionType()->getReturnType()))
735         Constraints.push_back(Constraint(Constraint::Copy,
736                                          getReturnNode(F),
737                                          &GraphNodes[UniversalSet]));
738
739       // Any pointers that are passed into the function have the universal set
740       // stored into them.
741       for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
742            I != E; ++I)
743         if (isa<PointerType>(I->getType())) {
744           // Pointers passed into external functions could have anything stored
745           // through them.
746           Constraints.push_back(Constraint(Constraint::Store, getNode(I),
747                                            &GraphNodes[UniversalSet]));
748           // Memory objects passed into external function calls can have the
749           // universal set point to them.
750           Constraints.push_back(Constraint(Constraint::Copy,
751                                            &GraphNodes[UniversalSet],
752                                            getNode(I)));
753         }
754
755       // If this is an external varargs function, it can also store pointers
756       // into any pointers passed through the varargs section.
757       if (F->getFunctionType()->isVarArg())
758         Constraints.push_back(Constraint(Constraint::Store, getVarargNode(F),
759                                          &GraphNodes[UniversalSet]));
760     }
761   }
762   NumConstraints += Constraints.size();
763 }
764
765
766 void Andersens::visitInstruction(Instruction &I) {
767 #ifdef NDEBUG
768   return;          // This function is just a big assert.
769 #endif
770   if (isa<BinaryOperator>(I))
771     return;
772   // Most instructions don't have any effect on pointer values.
773   switch (I.getOpcode()) {
774   case Instruction::Br:
775   case Instruction::Switch:
776   case Instruction::Unwind:
777   case Instruction::Unreachable:
778   case Instruction::Free:
779   case Instruction::Shl:
780   case Instruction::Shr:
781     return;
782   default:
783     // Is this something we aren't handling yet?
784     std::cerr << "Unknown instruction: " << I;
785     abort();
786   }
787 }
788
789 void Andersens::visitAllocationInst(AllocationInst &AI) {
790   getNodeValue(AI)->addPointerTo(getObject(&AI)->setValue(&AI));
791 }
792
793 void Andersens::visitReturnInst(ReturnInst &RI) {
794   if (RI.getNumOperands() && isa<PointerType>(RI.getOperand(0)->getType()))
795     // return V   -->   <Copy/retval{F}/v>
796     Constraints.push_back(Constraint(Constraint::Copy,
797                                      getReturnNode(RI.getParent()->getParent()),
798                                      getNode(RI.getOperand(0))));
799 }
800
801 void Andersens::visitLoadInst(LoadInst &LI) {
802   if (isa<PointerType>(LI.getType()))
803     // P1 = load P2  -->  <Load/P1/P2>
804     Constraints.push_back(Constraint(Constraint::Load, getNodeValue(LI),
805                                      getNode(LI.getOperand(0))));
806 }
807
808 void Andersens::visitStoreInst(StoreInst &SI) {
809   if (isa<PointerType>(SI.getOperand(0)->getType()))
810     // store P1, P2  -->  <Store/P2/P1>
811     Constraints.push_back(Constraint(Constraint::Store,
812                                      getNode(SI.getOperand(1)),
813                                      getNode(SI.getOperand(0))));
814 }
815
816 void Andersens::visitGetElementPtrInst(GetElementPtrInst &GEP) {
817   // P1 = getelementptr P2, ... --> <Copy/P1/P2>
818   Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(GEP),
819                                    getNode(GEP.getOperand(0))));
820 }
821
822 void Andersens::visitPHINode(PHINode &PN) {
823   if (isa<PointerType>(PN.getType())) {
824     Node *PNN = getNodeValue(PN);
825     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
826       // P1 = phi P2, P3  -->  <Copy/P1/P2>, <Copy/P1/P3>, ...
827       Constraints.push_back(Constraint(Constraint::Copy, PNN,
828                                        getNode(PN.getIncomingValue(i))));
829   }
830 }
831
832 void Andersens::visitCastInst(CastInst &CI) {
833   Value *Op = CI.getOperand(0);
834   if (isa<PointerType>(CI.getType())) {
835     if (isa<PointerType>(Op->getType())) {
836       // P1 = cast P2  --> <Copy/P1/P2>
837       Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
838                                        getNode(CI.getOperand(0))));
839     } else {
840       // P1 = cast int --> <Copy/P1/Univ>
841 #if 0
842       Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
843                                        &GraphNodes[UniversalSet]));
844 #else
845       getNodeValue(CI);
846 #endif
847     }
848   } else if (isa<PointerType>(Op->getType())) {
849     // int = cast P1 --> <Copy/Univ/P1>
850 #if 0
851     Constraints.push_back(Constraint(Constraint::Copy,
852                                      &GraphNodes[UniversalSet],
853                                      getNode(CI.getOperand(0))));
854 #else
855     getNode(CI.getOperand(0));
856 #endif
857   }
858 }
859
860 void Andersens::visitSelectInst(SelectInst &SI) {
861   if (isa<PointerType>(SI.getType())) {
862     Node *SIN = getNodeValue(SI);
863     // P1 = select C, P2, P3   ---> <Copy/P1/P2>, <Copy/P1/P3>
864     Constraints.push_back(Constraint(Constraint::Copy, SIN,
865                                      getNode(SI.getOperand(1))));
866     Constraints.push_back(Constraint(Constraint::Copy, SIN,
867                                      getNode(SI.getOperand(2))));
868   }
869 }
870
871 void Andersens::visitVAArg(VAArgInst &I) {
872   assert(0 && "vaarg not handled yet!");
873 }
874
875 /// AddConstraintsForCall - Add constraints for a call with actual arguments
876 /// specified by CS to the function specified by F.  Note that the types of
877 /// arguments might not match up in the case where this is an indirect call and
878 /// the function pointer has been casted.  If this is the case, do something
879 /// reasonable.
880 void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
881   // If this is a call to an external function, handle it directly to get some
882   // taste of context sensitivity.
883   if (F->isExternal() && AddConstraintsForExternalCall(CS, F))
884     return;
885
886   if (isa<PointerType>(CS.getType())) {
887     Node *CSN = getNode(CS.getInstruction());
888     if (isa<PointerType>(F->getFunctionType()->getReturnType())) {
889       Constraints.push_back(Constraint(Constraint::Copy, CSN,
890                                        getReturnNode(F)));
891     } else {
892       // If the function returns a non-pointer value, handle this just like we
893       // treat a nonpointer cast to pointer.
894       Constraints.push_back(Constraint(Constraint::Copy, CSN,
895                                        &GraphNodes[UniversalSet]));
896     }
897   } else if (isa<PointerType>(F->getFunctionType()->getReturnType())) {
898     Constraints.push_back(Constraint(Constraint::Copy,
899                                      &GraphNodes[UniversalSet],
900                                      getReturnNode(F)));
901   }
902
903   Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
904   CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
905   for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI)
906     if (isa<PointerType>(AI->getType())) {
907       if (isa<PointerType>((*ArgI)->getType())) {
908         // Copy the actual argument into the formal argument.
909         Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
910                                          getNode(*ArgI)));
911       } else {
912         Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
913                                          &GraphNodes[UniversalSet]));
914       }
915     } else if (isa<PointerType>((*ArgI)->getType())) {
916       Constraints.push_back(Constraint(Constraint::Copy,
917                                        &GraphNodes[UniversalSet],
918                                        getNode(*ArgI)));
919     }
920
921   // Copy all pointers passed through the varargs section to the varargs node.
922   if (F->getFunctionType()->isVarArg())
923     for (; ArgI != ArgE; ++ArgI)
924       if (isa<PointerType>((*ArgI)->getType()))
925         Constraints.push_back(Constraint(Constraint::Copy, getVarargNode(F),
926                                          getNode(*ArgI)));
927   // If more arguments are passed in than we track, just drop them on the floor.
928 }
929
930 void Andersens::visitCallSite(CallSite CS) {
931   if (isa<PointerType>(CS.getType()))
932     getNodeValue(*CS.getInstruction());
933
934   if (Function *F = CS.getCalledFunction()) {
935     AddConstraintsForCall(CS, F);
936   } else {
937     // We don't handle indirect call sites yet.  Keep track of them for when we
938     // discover the call graph incrementally.
939     IndirectCalls.push_back(CS);
940   }
941 }
942
943 //===----------------------------------------------------------------------===//
944 //                         Constraint Solving Phase
945 //===----------------------------------------------------------------------===//
946
947 /// intersects - Return true if the points-to set of this node intersects
948 /// with the points-to set of the specified node.
949 bool Andersens::Node::intersects(Node *N) const {
950   iterator I1 = begin(), I2 = N->begin(), E1 = end(), E2 = N->end();
951   while (I1 != E1 && I2 != E2) {
952     if (*I1 == *I2) return true;
953     if (*I1 < *I2)
954       ++I1;
955     else
956       ++I2;
957   }
958   return false;
959 }
960
961 /// intersectsIgnoring - Return true if the points-to set of this node
962 /// intersects with the points-to set of the specified node on any nodes
963 /// except for the specified node to ignore.
964 bool Andersens::Node::intersectsIgnoring(Node *N, Node *Ignoring) const {
965   iterator I1 = begin(), I2 = N->begin(), E1 = end(), E2 = N->end();
966   while (I1 != E1 && I2 != E2) {
967     if (*I1 == *I2) {
968       if (*I1 != Ignoring) return true;
969       ++I1; ++I2;
970     } else if (*I1 < *I2)
971       ++I1;
972     else
973       ++I2;
974   }
975   return false;
976 }
977
978 // Copy constraint: all edges out of the source node get copied to the
979 // destination node.  This returns true if a change is made.
980 bool Andersens::Node::copyFrom(Node *N) {
981   // Use a mostly linear-time merge since both of the lists are sorted.
982   bool Changed = false;
983   iterator I = N->begin(), E = N->end();
984   unsigned i = 0;
985   while (I != E && i != Pointees.size()) {
986     if (Pointees[i] < *I) {
987       ++i;
988     } else if (Pointees[i] == *I) {
989       ++i; ++I;
990     } else {
991       // We found a new element to copy over.
992       Changed = true;
993       Pointees.insert(Pointees.begin()+i, *I);
994        ++i; ++I;
995     }
996   }
997
998   if (I != E) {
999     Pointees.insert(Pointees.end(), I, E);
1000     Changed = true;
1001   }
1002
1003   return Changed;
1004 }
1005
1006 bool Andersens::Node::loadFrom(Node *N) {
1007   bool Changed = false;
1008   for (iterator I = N->begin(), E = N->end(); I != E; ++I)
1009     Changed |= copyFrom(*I);
1010   return Changed;
1011 }
1012
1013 bool Andersens::Node::storeThrough(Node *N) {
1014   bool Changed = false;
1015   for (iterator I = begin(), E = end(); I != E; ++I)
1016     Changed |= (*I)->copyFrom(N);
1017   return Changed;
1018 }
1019
1020
1021 /// SolveConstraints - This stage iteratively processes the constraints list
1022 /// propagating constraints (adding edges to the Nodes in the points-to graph)
1023 /// until a fixed point is reached.
1024 ///
1025 void Andersens::SolveConstraints() {
1026   bool Changed = true;
1027   unsigned Iteration = 0;
1028   while (Changed) {
1029     Changed = false;
1030     ++NumIters;
1031     DEBUG(std::cerr << "Starting iteration #" << Iteration++ << "!\n");
1032
1033     // Loop over all of the constraints, applying them in turn.
1034     for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1035       Constraint &C = Constraints[i];
1036       switch (C.Type) {
1037       case Constraint::Copy:
1038         Changed |= C.Dest->copyFrom(C.Src);
1039         break;
1040       case Constraint::Load:
1041         Changed |= C.Dest->loadFrom(C.Src);
1042         break;
1043       case Constraint::Store:
1044         Changed |= C.Dest->storeThrough(C.Src);
1045         break;
1046       default:
1047         assert(0 && "Unknown constraint!");
1048       }
1049     }
1050
1051     if (Changed) {
1052       // Check to see if any internal function's addresses have been passed to
1053       // external functions.  If so, we have to assume that their incoming
1054       // arguments could be anything.  If there are any internal functions in
1055       // the universal node that we don't know about, we must iterate.
1056       for (Node::iterator I = GraphNodes[UniversalSet].begin(),
1057              E = GraphNodes[UniversalSet].end(); I != E; ++I)
1058         if (Function *F = dyn_cast_or_null<Function>((*I)->getValue()))
1059           if (F->hasInternalLinkage() &&
1060               EscapingInternalFunctions.insert(F).second) {
1061             // We found a function that is just now escaping.  Mark it as if it
1062             // didn't have internal linkage.
1063             AddConstraintsForNonInternalLinkage(F);
1064             DEBUG(std::cerr << "Found escaping internal function: "
1065                             << F->getName() << "\n");
1066             ++NumEscapingFunctions;
1067           }
1068
1069       // Check to see if we have discovered any new callees of the indirect call
1070       // sites.  If so, add constraints to the analysis.
1071       for (unsigned i = 0, e = IndirectCalls.size(); i != e; ++i) {
1072         CallSite CS = IndirectCalls[i];
1073         std::vector<Function*> &KnownCallees = IndirectCallees[CS];
1074         Node *CN = getNode(CS.getCalledValue());
1075
1076         for (Node::iterator NI = CN->begin(), E = CN->end(); NI != E; ++NI)
1077           if (Function *F = dyn_cast_or_null<Function>((*NI)->getValue())) {
1078             std::vector<Function*>::iterator IP =
1079               std::lower_bound(KnownCallees.begin(), KnownCallees.end(), F);
1080             if (IP == KnownCallees.end() || *IP != F) {
1081               // Add the constraints for the call now.
1082               AddConstraintsForCall(CS, F);
1083               DEBUG(std::cerr << "Found actual callee '"
1084                               << F->getName() << "' for call: "
1085                               << *CS.getInstruction() << "\n");
1086               ++NumIndirectCallees;
1087               KnownCallees.insert(IP, F);
1088             }
1089           }
1090       }
1091     }
1092   }
1093 }
1094
1095
1096
1097 //===----------------------------------------------------------------------===//
1098 //                               Debugging Output
1099 //===----------------------------------------------------------------------===//
1100
1101 void Andersens::PrintNode(Node *N) {
1102   if (N == &GraphNodes[UniversalSet]) {
1103     std::cerr << "<universal>";
1104     return;
1105   } else if (N == &GraphNodes[NullPtr]) {
1106     std::cerr << "<nullptr>";
1107     return;
1108   } else if (N == &GraphNodes[NullObject]) {
1109     std::cerr << "<null>";
1110     return;
1111   }
1112
1113   assert(N->getValue() != 0 && "Never set node label!");
1114   Value *V = N->getValue();
1115   if (Function *F = dyn_cast<Function>(V)) {
1116     if (isa<PointerType>(F->getFunctionType()->getReturnType()) &&
1117         N == getReturnNode(F)) {
1118       std::cerr << F->getName() << ":retval";
1119       return;
1120     } else if (F->getFunctionType()->isVarArg() && N == getVarargNode(F)) {
1121       std::cerr << F->getName() << ":vararg";
1122       return;
1123     }
1124   }
1125
1126   if (Instruction *I = dyn_cast<Instruction>(V))
1127     std::cerr << I->getParent()->getParent()->getName() << ":";
1128   else if (Argument *Arg = dyn_cast<Argument>(V))
1129     std::cerr << Arg->getParent()->getName() << ":";
1130
1131   if (V->hasName())
1132     std::cerr << V->getName();
1133   else
1134     std::cerr << "(unnamed)";
1135
1136   if (isa<GlobalValue>(V) || isa<AllocationInst>(V))
1137     if (N == getObject(V))
1138       std::cerr << "<mem>";
1139 }
1140
1141 void Andersens::PrintConstraints() {
1142   std::cerr << "Constraints:\n";
1143   for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1144     std::cerr << "  #" << i << ":  ";
1145     Constraint &C = Constraints[i];
1146     if (C.Type == Constraint::Store)
1147       std::cerr << "*";
1148     PrintNode(C.Dest);
1149     std::cerr << " = ";
1150     if (C.Type == Constraint::Load)
1151       std::cerr << "*";
1152     PrintNode(C.Src);
1153     std::cerr << "\n";
1154   }
1155 }
1156
1157 void Andersens::PrintPointsToGraph() {
1158   std::cerr << "Points-to graph:\n";
1159   for (unsigned i = 0, e = GraphNodes.size(); i != e; ++i) {
1160     Node *N = &GraphNodes[i];
1161     std::cerr << "[" << (N->end() - N->begin()) << "] ";
1162     PrintNode(N);
1163     std::cerr << "\t--> ";
1164     for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I) {
1165       if (I != N->begin()) std::cerr << ", ";
1166       PrintNode(*I);
1167     }
1168     std::cerr << "\n";
1169   }
1170 }