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