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