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