wrap some long lines
[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();
437        I != E; ++I) {
438     ObjectNodes[I] = NumObjects++;
439     ValueNodes[I] = NumObjects++;
440   }
441
442   // Add nodes for all of the functions and the instructions inside of them.
443   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
444     // The function itself is a memory object.
445     ValueNodes[F] = NumObjects++;
446     ObjectNodes[F] = NumObjects++;
447     if (isa<PointerType>(F->getFunctionType()->getReturnType()))
448       ReturnNodes[F] = NumObjects++;
449     if (F->getFunctionType()->isVarArg())
450       VarargNodes[F] = NumObjects++;
451
452     // Add nodes for all of the incoming pointer arguments.
453     for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
454          I != E; ++I)
455       if (isa<PointerType>(I->getType()))
456         ValueNodes[I] = NumObjects++;
457
458     // Scan the function body, creating a memory object for each heap/stack
459     // allocation in the body of the function and a node to represent all
460     // pointer values defined by instructions and used as operands.
461     for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
462       // If this is an heap or stack allocation, create a node for the memory
463       // object.
464       if (isa<PointerType>(II->getType())) {
465         ValueNodes[&*II] = NumObjects++;
466         if (AllocationInst *AI = dyn_cast<AllocationInst>(&*II))
467           ObjectNodes[AI] = NumObjects++;
468       }
469     }
470   }
471
472   // Now that we know how many objects to create, make them all now!
473   GraphNodes.resize(NumObjects);
474   NumNodes += NumObjects;
475 }
476
477 //===----------------------------------------------------------------------===//
478 //                     Constraint Identification Phase
479 //===----------------------------------------------------------------------===//
480
481 /// getNodeForConstantPointer - Return the node corresponding to the constant
482 /// pointer itself.
483 Andersens::Node *Andersens::getNodeForConstantPointer(Constant *C) {
484   assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
485
486   if (isa<ConstantPointerNull>(C) || isa<UndefValue>(C))
487     return &GraphNodes[NullPtr];
488   else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
489     return getNode(GV);
490   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
491     switch (CE->getOpcode()) {
492     case Instruction::GetElementPtr:
493       return getNodeForConstantPointer(CE->getOperand(0));
494     case Instruction::Cast:
495       if (isa<PointerType>(CE->getOperand(0)->getType()))
496         return getNodeForConstantPointer(CE->getOperand(0));
497       else
498         return &GraphNodes[UniversalSet];
499     default:
500       std::cerr << "Constant Expr not yet handled: " << *CE << "\n";
501       assert(0);
502     }
503   } else {
504     assert(0 && "Unknown constant pointer!");
505   }
506   return 0;
507 }
508
509 /// getNodeForConstantPointerTarget - Return the node POINTED TO by the
510 /// specified constant pointer.
511 Andersens::Node *Andersens::getNodeForConstantPointerTarget(Constant *C) {
512   assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
513
514   if (isa<ConstantPointerNull>(C))
515     return &GraphNodes[NullObject];
516   else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
517     return getObject(GV);
518   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
519     switch (CE->getOpcode()) {
520     case Instruction::GetElementPtr:
521       return getNodeForConstantPointerTarget(CE->getOperand(0));
522     case Instruction::Cast:
523       if (isa<PointerType>(CE->getOperand(0)->getType()))
524         return getNodeForConstantPointerTarget(CE->getOperand(0));
525       else
526         return &GraphNodes[UniversalSet];
527     default:
528       std::cerr << "Constant Expr not yet handled: " << *CE << "\n";
529       assert(0);
530     }
531   } else {
532     assert(0 && "Unknown constant pointer!");
533   }
534   return 0;
535 }
536
537 /// AddGlobalInitializerConstraints - Add inclusion constraints for the memory
538 /// object N, which contains values indicated by C.
539 void Andersens::AddGlobalInitializerConstraints(Node *N, Constant *C) {
540   if (C->getType()->isFirstClassType()) {
541     if (isa<PointerType>(C->getType()))
542       N->addPointerTo(getNodeForConstantPointer(C));
543   } else if (C->isNullValue()) {
544     N->addPointerTo(&GraphNodes[NullObject]);
545     return;
546   } else {
547     // If this is an array or struct, include constraints for each element.
548     assert(isa<ConstantArray>(C) || isa<ConstantStruct>(C));
549     for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
550       AddGlobalInitializerConstraints(N, cast<Constant>(C->getOperand(i)));
551   }
552 }
553
554 void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
555   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
556     if (isa<PointerType>(I->getType()))
557       // If this is an argument of an externally accessible function, the
558       // incoming pointer might point to anything.
559       Constraints.push_back(Constraint(Constraint::Copy, getNode(I),
560                                        &GraphNodes[UniversalSet]));
561 }
562
563
564 /// CollectConstraints - This stage scans the program, adding a constraint to
565 /// the Constraints list for each instruction in the program that induces a
566 /// constraint, and setting up the initial points-to graph.
567 ///
568 void Andersens::CollectConstraints(Module &M) {
569   // First, the universal set points to itself.
570   GraphNodes[UniversalSet].addPointerTo(&GraphNodes[UniversalSet]);
571
572   // Next, the null pointer points to the null object.
573   GraphNodes[NullPtr].addPointerTo(&GraphNodes[NullObject]);
574
575   // Next, add any constraints on global variables and their initializers.
576   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
577        I != E; ++I) {
578     // Associate the address of the global object as pointing to the memory for
579     // the global: &G = <G memory>
580     Node *Object = getObject(I);
581     Object->setValue(I);
582     getNodeValue(*I)->addPointerTo(Object);
583
584     if (I->hasInitializer()) {
585       AddGlobalInitializerConstraints(Object, I->getInitializer());
586     } else {
587       // If it doesn't have an initializer (i.e. it's defined in another
588       // translation unit), it points to the universal set.
589       Constraints.push_back(Constraint(Constraint::Copy, Object,
590                                        &GraphNodes[UniversalSet]));
591     }
592   }
593   
594   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
595     // Make the function address point to the function object.
596     getNodeValue(*F)->addPointerTo(getObject(F)->setValue(F));
597
598     // Set up the return value node.
599     if (isa<PointerType>(F->getFunctionType()->getReturnType()))
600       getReturnNode(F)->setValue(F);
601     if (F->getFunctionType()->isVarArg())
602       getVarargNode(F)->setValue(F);
603
604     // Set up incoming argument nodes.
605     for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
606          I != E; ++I)
607       if (isa<PointerType>(I->getType()))
608         getNodeValue(*I);
609
610     if (!F->hasInternalLinkage())
611       AddConstraintsForNonInternalLinkage(F);
612
613     if (!F->isExternal()) {
614       // Scan the function body, creating a memory object for each heap/stack
615       // allocation in the body of the function and a node to represent all
616       // pointer values defined by instructions and used as operands.
617       visit(F);
618     } else {
619       // External functions that return pointers return the universal set.
620       if (isa<PointerType>(F->getFunctionType()->getReturnType()))
621         Constraints.push_back(Constraint(Constraint::Copy,
622                                          getReturnNode(F),
623                                          &GraphNodes[UniversalSet]));
624
625       // Any pointers that are passed into the function have the universal set
626       // stored into them.
627       for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
628            I != E; ++I)
629         if (isa<PointerType>(I->getType())) {
630           // Pointers passed into external functions could have anything stored
631           // through them.
632           Constraints.push_back(Constraint(Constraint::Store, getNode(I),
633                                            &GraphNodes[UniversalSet]));
634           // Memory objects passed into external function calls can have the
635           // universal set point to them.
636           Constraints.push_back(Constraint(Constraint::Copy,
637                                            &GraphNodes[UniversalSet],
638                                            getNode(I)));
639         }
640
641       // If this is an external varargs function, it can also store pointers
642       // into any pointers passed through the varargs section.
643       if (F->getFunctionType()->isVarArg())
644         Constraints.push_back(Constraint(Constraint::Store, getVarargNode(F),
645                                          &GraphNodes[UniversalSet]));
646     }
647   }
648   NumConstraints += Constraints.size();
649 }
650
651
652 void Andersens::visitInstruction(Instruction &I) {
653 #ifdef NDEBUG
654   return;          // This function is just a big assert.
655 #endif
656   if (isa<BinaryOperator>(I))
657     return;
658   // Most instructions don't have any effect on pointer values.
659   switch (I.getOpcode()) {
660   case Instruction::Br:
661   case Instruction::Switch:
662   case Instruction::Unwind:
663   case Instruction::Unreachable:
664   case Instruction::Free:
665   case Instruction::Shl:
666   case Instruction::Shr:
667     return;
668   default:
669     // Is this something we aren't handling yet?
670     std::cerr << "Unknown instruction: " << I;
671     abort();
672   }
673 }
674
675 void Andersens::visitAllocationInst(AllocationInst &AI) {
676   getNodeValue(AI)->addPointerTo(getObject(&AI)->setValue(&AI));
677 }
678
679 void Andersens::visitReturnInst(ReturnInst &RI) {
680   if (RI.getNumOperands() && isa<PointerType>(RI.getOperand(0)->getType()))
681     // return V   -->   <Copy/retval{F}/v>
682     Constraints.push_back(Constraint(Constraint::Copy,
683                                      getReturnNode(RI.getParent()->getParent()),
684                                      getNode(RI.getOperand(0))));
685 }
686
687 void Andersens::visitLoadInst(LoadInst &LI) {
688   if (isa<PointerType>(LI.getType()))
689     // P1 = load P2  -->  <Load/P1/P2>
690     Constraints.push_back(Constraint(Constraint::Load, getNodeValue(LI),
691                                      getNode(LI.getOperand(0))));
692 }
693
694 void Andersens::visitStoreInst(StoreInst &SI) {
695   if (isa<PointerType>(SI.getOperand(0)->getType()))
696     // store P1, P2  -->  <Store/P2/P1>
697     Constraints.push_back(Constraint(Constraint::Store,
698                                      getNode(SI.getOperand(1)),
699                                      getNode(SI.getOperand(0))));
700 }
701
702 void Andersens::visitGetElementPtrInst(GetElementPtrInst &GEP) {
703   // P1 = getelementptr P2, ... --> <Copy/P1/P2>
704   Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(GEP),
705                                    getNode(GEP.getOperand(0))));
706 }
707
708 void Andersens::visitPHINode(PHINode &PN) {
709   if (isa<PointerType>(PN.getType())) {
710     Node *PNN = getNodeValue(PN);
711     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
712       // P1 = phi P2, P3  -->  <Copy/P1/P2>, <Copy/P1/P3>, ...
713       Constraints.push_back(Constraint(Constraint::Copy, PNN,
714                                        getNode(PN.getIncomingValue(i))));
715   }
716 }
717
718 void Andersens::visitCastInst(CastInst &CI) {
719   Value *Op = CI.getOperand(0);
720   if (isa<PointerType>(CI.getType())) {
721     if (isa<PointerType>(Op->getType())) {
722       // P1 = cast P2  --> <Copy/P1/P2>
723       Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
724                                        getNode(CI.getOperand(0))));
725     } else {
726       // P1 = cast int --> <Copy/P1/Univ>
727       Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
728                                        &GraphNodes[UniversalSet]));
729     }
730   } else if (isa<PointerType>(Op->getType())) {
731     // int = cast P1 --> <Copy/Univ/P1>
732     Constraints.push_back(Constraint(Constraint::Copy,
733                                      &GraphNodes[UniversalSet],
734                                      getNode(CI.getOperand(0))));
735   }
736 }
737
738 void Andersens::visitSelectInst(SelectInst &SI) {
739   if (isa<PointerType>(SI.getType())) {
740     Node *SIN = getNodeValue(SI);
741     // P1 = select C, P2, P3   ---> <Copy/P1/P2>, <Copy/P1/P3>
742     Constraints.push_back(Constraint(Constraint::Copy, SIN,
743                                      getNode(SI.getOperand(1))));
744     Constraints.push_back(Constraint(Constraint::Copy, SIN,
745                                      getNode(SI.getOperand(2))));
746   }
747 }
748
749 void Andersens::visitVANext(VANextInst &I) {
750   // FIXME: Implement
751   assert(0 && "vanext not handled yet!");
752 }
753 void Andersens::visitVAArg(VAArgInst &I) {
754   assert(0 && "vaarg not handled yet!");
755 }
756
757 /// AddConstraintsForCall - Add constraints for a call with actual arguments
758 /// specified by CS to the function specified by F.  Note that the types of
759 /// arguments might not match up in the case where this is an indirect call and
760 /// the function pointer has been casted.  If this is the case, do something
761 /// reasonable.
762 void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
763   if (isa<PointerType>(CS.getType())) {
764     Node *CSN = getNode(CS.getInstruction());
765     if (isa<PointerType>(F->getFunctionType()->getReturnType())) {
766       Constraints.push_back(Constraint(Constraint::Copy, CSN,
767                                        getReturnNode(F)));
768     } else {
769       // If the function returns a non-pointer value, handle this just like we
770       // treat a nonpointer cast to pointer.
771       Constraints.push_back(Constraint(Constraint::Copy, CSN,
772                                        &GraphNodes[UniversalSet]));
773     }
774   } else if (isa<PointerType>(F->getFunctionType()->getReturnType())) {
775     Constraints.push_back(Constraint(Constraint::Copy,
776                                      &GraphNodes[UniversalSet],
777                                      getReturnNode(F)));
778   }
779   
780   Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
781   CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
782   for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI)
783     if (isa<PointerType>(AI->getType())) {
784       if (isa<PointerType>((*ArgI)->getType())) {
785         // Copy the actual argument into the formal argument.
786         Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
787                                          getNode(*ArgI)));
788       } else {
789         Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
790                                          &GraphNodes[UniversalSet]));
791       }
792     } else if (isa<PointerType>((*ArgI)->getType())) {
793       Constraints.push_back(Constraint(Constraint::Copy,
794                                        &GraphNodes[UniversalSet],
795                                        getNode(*ArgI)));
796     }
797   
798   // Copy all pointers passed through the varargs section to the varargs node.
799   if (F->getFunctionType()->isVarArg())
800     for (; ArgI != ArgE; ++ArgI)
801       if (isa<PointerType>((*ArgI)->getType()))
802         Constraints.push_back(Constraint(Constraint::Copy, getVarargNode(F),
803                                          getNode(*ArgI)));
804   // If more arguments are passed in than we track, just drop them on the floor.
805 }
806
807 void Andersens::visitCallSite(CallSite CS) {
808   if (isa<PointerType>(CS.getType()))
809     getNodeValue(*CS.getInstruction());
810
811   if (Function *F = CS.getCalledFunction()) {
812     AddConstraintsForCall(CS, F);
813   } else {
814     // We don't handle indirect call sites yet.  Keep track of them for when we
815     // discover the call graph incrementally.
816     IndirectCalls.push_back(CS);
817   }
818 }
819
820 //===----------------------------------------------------------------------===//
821 //                         Constraint Solving Phase
822 //===----------------------------------------------------------------------===//
823
824 /// intersects - Return true if the points-to set of this node intersects
825 /// with the points-to set of the specified node.
826 bool Andersens::Node::intersects(Node *N) const {
827   iterator I1 = begin(), I2 = N->begin(), E1 = end(), E2 = N->end();
828   while (I1 != E1 && I2 != E2) {
829     if (*I1 == *I2) return true;
830     if (*I1 < *I2)
831       ++I1;
832     else
833       ++I2;
834   }
835   return false;
836 }
837
838 /// intersectsIgnoring - Return true if the points-to set of this node
839 /// intersects with the points-to set of the specified node on any nodes
840 /// except for the specified node to ignore.
841 bool Andersens::Node::intersectsIgnoring(Node *N, Node *Ignoring) const {
842   iterator I1 = begin(), I2 = N->begin(), E1 = end(), E2 = N->end();
843   while (I1 != E1 && I2 != E2) {
844     if (*I1 == *I2) {
845       if (*I1 != Ignoring) return true;
846       ++I1; ++I2;
847     } else if (*I1 < *I2)
848       ++I1;
849     else
850       ++I2;
851   }
852   return false;
853 }
854
855 // Copy constraint: all edges out of the source node get copied to the
856 // destination node.  This returns true if a change is made.
857 bool Andersens::Node::copyFrom(Node *N) {
858   // Use a mostly linear-time merge since both of the lists are sorted.
859   bool Changed = false;
860   iterator I = N->begin(), E = N->end();
861   unsigned i = 0;
862   while (I != E && i != Pointees.size()) {
863     if (Pointees[i] < *I) {
864       ++i;
865     } else if (Pointees[i] == *I) {
866       ++i; ++I;
867     } else {
868       // We found a new element to copy over.
869       Changed = true;
870       Pointees.insert(Pointees.begin()+i, *I);
871        ++i; ++I;
872     }
873   }
874
875   if (I != E) {
876     Pointees.insert(Pointees.end(), I, E);
877     Changed = true;
878   }
879
880   return Changed;
881 }
882
883 bool Andersens::Node::loadFrom(Node *N) {
884   bool Changed = false;
885   for (iterator I = N->begin(), E = N->end(); I != E; ++I)
886     Changed |= copyFrom(*I);
887   return Changed;
888 }
889
890 bool Andersens::Node::storeThrough(Node *N) {
891   bool Changed = false;
892   for (iterator I = begin(), E = end(); I != E; ++I)
893     Changed |= (*I)->copyFrom(N);
894   return Changed;
895 }
896
897
898 /// SolveConstraints - This stage iteratively processes the constraints list
899 /// propagating constraints (adding edges to the Nodes in the points-to graph)
900 /// until a fixed point is reached.
901 ///
902 void Andersens::SolveConstraints() {
903   bool Changed = true;
904   unsigned Iteration = 0;
905   while (Changed) {
906     Changed = false;
907     ++NumIters;
908     DEBUG(std::cerr << "Starting iteration #" << Iteration++ << "!\n");
909
910     // Loop over all of the constraints, applying them in turn.
911     for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
912       Constraint &C = Constraints[i];
913       switch (C.Type) {
914       case Constraint::Copy:
915         Changed |= C.Dest->copyFrom(C.Src);
916         break;
917       case Constraint::Load:
918         Changed |= C.Dest->loadFrom(C.Src);
919         break;
920       case Constraint::Store:
921         Changed |= C.Dest->storeThrough(C.Src);
922         break;
923       default:
924         assert(0 && "Unknown constraint!");
925       }
926     }
927
928     if (Changed) {
929       // Check to see if any internal function's addresses have been passed to
930       // external functions.  If so, we have to assume that their incoming
931       // arguments could be anything.  If there are any internal functions in
932       // the universal node that we don't know about, we must iterate.
933       for (Node::iterator I = GraphNodes[UniversalSet].begin(),
934              E = GraphNodes[UniversalSet].end(); I != E; ++I)
935         if (Function *F = dyn_cast_or_null<Function>((*I)->getValue()))
936           if (F->hasInternalLinkage() &&
937               EscapingInternalFunctions.insert(F).second) {
938             // We found a function that is just now escaping.  Mark it as if it
939             // didn't have internal linkage.
940             AddConstraintsForNonInternalLinkage(F);
941             DEBUG(std::cerr << "Found escaping internal function: "
942                             << F->getName() << "\n");
943             ++NumEscapingFunctions;
944           }
945
946       // Check to see if we have discovered any new callees of the indirect call
947       // sites.  If so, add constraints to the analysis.
948       for (unsigned i = 0, e = IndirectCalls.size(); i != e; ++i) {
949         CallSite CS = IndirectCalls[i];
950         std::vector<Function*> &KnownCallees = IndirectCallees[CS];
951         Node *CN = getNode(CS.getCalledValue());
952
953         for (Node::iterator NI = CN->begin(), E = CN->end(); NI != E; ++NI)
954           if (Function *F = dyn_cast_or_null<Function>((*NI)->getValue())) {
955             std::vector<Function*>::iterator IP =
956               std::lower_bound(KnownCallees.begin(), KnownCallees.end(), F);
957             if (IP == KnownCallees.end() || *IP != F) {
958               // Add the constraints for the call now.
959               AddConstraintsForCall(CS, F);
960               DEBUG(std::cerr << "Found actual callee '"
961                               << F->getName() << "' for call: "
962                               << *CS.getInstruction() << "\n");
963               ++NumIndirectCallees;
964               KnownCallees.insert(IP, F);
965             }
966           }
967       }
968     }
969   }
970 }
971
972
973
974 //===----------------------------------------------------------------------===//
975 //                               Debugging Output
976 //===----------------------------------------------------------------------===//
977
978 void Andersens::PrintNode(Node *N) {
979   if (N == &GraphNodes[UniversalSet]) {
980     std::cerr << "<universal>";
981     return;
982   } else if (N == &GraphNodes[NullPtr]) {
983     std::cerr << "<nullptr>";
984     return;
985   } else if (N == &GraphNodes[NullObject]) {
986     std::cerr << "<null>";
987     return;
988   }
989
990   assert(N->getValue() != 0 && "Never set node label!");
991   Value *V = N->getValue();
992   if (Function *F = dyn_cast<Function>(V)) {
993     if (isa<PointerType>(F->getFunctionType()->getReturnType()) &&
994         N == getReturnNode(F)) {
995       std::cerr << F->getName() << ":retval";
996       return;
997     } else if (F->getFunctionType()->isVarArg() && N == getVarargNode(F)) {
998       std::cerr << F->getName() << ":vararg";
999       return;
1000     }
1001   }
1002
1003   if (Instruction *I = dyn_cast<Instruction>(V))
1004     std::cerr << I->getParent()->getParent()->getName() << ":";
1005   else if (Argument *Arg = dyn_cast<Argument>(V))
1006     std::cerr << Arg->getParent()->getName() << ":";
1007
1008   if (V->hasName())
1009     std::cerr << V->getName();
1010   else
1011     std::cerr << "(unnamed)";
1012
1013   if (isa<GlobalValue>(V) || isa<AllocationInst>(V))
1014     if (N == getObject(V))
1015       std::cerr << "<mem>";
1016 }
1017
1018 void Andersens::PrintConstraints() {
1019   std::cerr << "Constraints:\n";
1020   for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1021     std::cerr << "  #" << i << ":  ";
1022     Constraint &C = Constraints[i];
1023     if (C.Type == Constraint::Store)
1024       std::cerr << "*";
1025     PrintNode(C.Dest);
1026     std::cerr << " = ";
1027     if (C.Type == Constraint::Load)
1028       std::cerr << "*";
1029     PrintNode(C.Src);
1030     std::cerr << "\n";
1031   }
1032 }
1033
1034 void Andersens::PrintPointsToGraph() {
1035   std::cerr << "Points-to graph:\n";
1036   for (unsigned i = 0, e = GraphNodes.size(); i != e; ++i) {
1037     Node *N = &GraphNodes[i];
1038     std::cerr << "[" << (N->end() - N->begin()) << "] ";
1039     PrintNode(N);
1040     std::cerr << "\t--> ";
1041     for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I) {
1042       if (I != N->begin()) std::cerr << ", ";
1043       PrintNode(*I);
1044     }
1045     std::cerr << "\n";
1046   }
1047 }