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