blob: 037f33145a22ce8fa9bab4958638c430a6852efd [file] [log] [blame]
Chris Lattnerd28b0d72004-06-25 04:24:22 +00001//===- Andersens.cpp - Andersen's Interprocedural Alias Analysis ----------===//
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002//
Chris Lattnere995a2a2004-05-23 21:00:47 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00007//
Chris Lattnere995a2a2004-05-23 21:00:47 +00008//===----------------------------------------------------------------------===//
9//
Daniel Berlinaad15882007-09-16 21:45:02 +000010// This file defines an implementation of Andersen's interprocedural alias
11// analysis
Chris Lattnere995a2a2004-05-23 21:00:47 +000012//
13// In pointer analysis terms, this is a subset-based, flow-insensitive,
Daniel Berlinaad15882007-09-16 21:45:02 +000014// field-sensitive, and context-insensitive algorithm pointer algorithm.
Chris Lattnere995a2a2004-05-23 21:00:47 +000015//
16// This algorithm is implemented as three stages:
17// 1. Object identification.
18// 2. Inclusion constraint identification.
Daniel Berlind81ccc22007-09-24 19:45:49 +000019// 3. Offline constraint graph optimization
20// 4. Inclusion constraint solving.
Chris Lattnere995a2a2004-05-23 21:00:47 +000021//
22// The object identification stage identifies all of the memory objects in the
23// program, which includes globals, heap allocated objects, and stack allocated
24// objects.
25//
26// The inclusion constraint identification stage finds all inclusion constraints
27// in the program by scanning the program, looking for pointer assignments and
28// other statements that effect the points-to graph. For a statement like "A =
29// B", this statement is processed to indicate that A can point to anything that
Daniel Berlinaad15882007-09-16 21:45:02 +000030// B can point to. Constraints can handle copies, loads, and stores, and
31// address taking.
Chris Lattnere995a2a2004-05-23 21:00:47 +000032//
Daniel Berline6f04792007-09-24 22:20:45 +000033// The offline constraint graph optimization portion includes offline variable
34// substitution algorithms intended to computer pointer and location
35// equivalences. Pointer equivalences are those pointers that will have the
36// same points-to sets, and location equivalences are those variables that
37// always appear together in points-to sets.
Daniel Berlind81ccc22007-09-24 19:45:49 +000038//
Chris Lattnere995a2a2004-05-23 21:00:47 +000039// The inclusion constraint solving phase iteratively propagates the inclusion
40// constraints until a fixed point is reached. This is an O(N^3) algorithm.
41//
Daniel Berlinaad15882007-09-16 21:45:02 +000042// Function constraints are handled as if they were structs with X fields.
43// Thus, an access to argument X of function Y is an access to node index
44// getNode(Y) + X. This representation allows handling of indirect calls
Daniel Berlind81ccc22007-09-24 19:45:49 +000045// without any issues. To wit, an indirect call Y(a,b) is equivalent to
Daniel Berlinaad15882007-09-16 21:45:02 +000046// *(Y + 1) = a, *(Y + 2) = b.
47// The return node for a function is always located at getNode(F) +
48// CallReturnPos. The arguments start at getNode(F) + CallArgPos.
Chris Lattnere995a2a2004-05-23 21:00:47 +000049//
Chris Lattnerc7ca32b2004-06-05 20:12:36 +000050// Future Improvements:
Daniel Berlind81ccc22007-09-24 19:45:49 +000051// Offline detection of online cycles. Use of BDD's.
Chris Lattnere995a2a2004-05-23 21:00:47 +000052//===----------------------------------------------------------------------===//
53
54#define DEBUG_TYPE "anders-aa"
55#include "llvm/Constants.h"
56#include "llvm/DerivedTypes.h"
57#include "llvm/Instructions.h"
58#include "llvm/Module.h"
59#include "llvm/Pass.h"
Reid Spencerd7d83db2007-02-05 23:42:17 +000060#include "llvm/Support/Compiler.h"
Chris Lattnere995a2a2004-05-23 21:00:47 +000061#include "llvm/Support/InstIterator.h"
62#include "llvm/Support/InstVisitor.h"
63#include "llvm/Analysis/AliasAnalysis.h"
Jeff Cohen534927d2005-01-08 22:01:16 +000064#include "llvm/Analysis/Passes.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000065#include "llvm/Support/Debug.h"
66#include "llvm/ADT/Statistic.h"
Daniel Berlinaad15882007-09-16 21:45:02 +000067#include "llvm/ADT/SparseBitVector.h"
Chris Lattnerbe207732007-09-30 00:47:20 +000068#include "llvm/ADT/DenseSet.h"
Jeff Cohenca5183d2007-03-05 00:00:42 +000069#include <algorithm>
Chris Lattnere995a2a2004-05-23 21:00:47 +000070#include <set>
Daniel Berlinaad15882007-09-16 21:45:02 +000071#include <list>
72#include <stack>
73#include <vector>
Daniel Berlin3a3f1632007-12-12 00:37:04 +000074#include <queue>
75
76// Determining the actual set of nodes the universal set can consist of is very
77// expensive because it means propagating around very large sets. We rely on
78// other analysis being able to determine which nodes can never be pointed to in
79// order to disambiguate further than "points-to anything".
80#define FULL_UNIVERSAL 0
Chris Lattnere995a2a2004-05-23 21:00:47 +000081
Daniel Berlinaad15882007-09-16 21:45:02 +000082using namespace llvm;
Daniel Berlind81ccc22007-09-24 19:45:49 +000083STATISTIC(NumIters , "Number of iterations to reach convergence");
84STATISTIC(NumConstraints, "Number of constraints");
85STATISTIC(NumNodes , "Number of nodes");
86STATISTIC(NumUnified , "Number of variables unified");
Daniel Berlin3a3f1632007-12-12 00:37:04 +000087STATISTIC(NumErased , "Number of redundant constraints erased");
Chris Lattnere995a2a2004-05-23 21:00:47 +000088
Chris Lattner3b27d682006-12-19 22:30:33 +000089namespace {
Daniel Berlinaad15882007-09-16 21:45:02 +000090 const unsigned SelfRep = (unsigned)-1;
91 const unsigned Unvisited = (unsigned)-1;
92 // Position of the function return node relative to the function node.
Daniel Berlind81ccc22007-09-24 19:45:49 +000093 const unsigned CallReturnPos = 1;
Daniel Berlinaad15882007-09-16 21:45:02 +000094 // Position of the function call node relative to the function node.
Daniel Berlind81ccc22007-09-24 19:45:49 +000095 const unsigned CallFirstArgPos = 2;
96
97 struct BitmapKeyInfo {
98 static inline SparseBitVector<> *getEmptyKey() {
99 return reinterpret_cast<SparseBitVector<> *>(-1);
100 }
101 static inline SparseBitVector<> *getTombstoneKey() {
102 return reinterpret_cast<SparseBitVector<> *>(-2);
103 }
104 static unsigned getHashValue(const SparseBitVector<> *bitmap) {
105 return bitmap->getHashValue();
106 }
107 static bool isEqual(const SparseBitVector<> *LHS,
108 const SparseBitVector<> *RHS) {
109 if (LHS == RHS)
110 return true;
111 else if (LHS == getEmptyKey() || RHS == getEmptyKey()
112 || LHS == getTombstoneKey() || RHS == getTombstoneKey())
113 return false;
114
115 return *LHS == *RHS;
116 }
117
118 static bool isPod() { return true; }
119 };
Daniel Berlinaad15882007-09-16 21:45:02 +0000120
Reid Spencerd7d83db2007-02-05 23:42:17 +0000121 class VISIBILITY_HIDDEN Andersens : public ModulePass, public AliasAnalysis,
122 private InstVisitor<Andersens> {
Hartmut Kaiser081fdf22007-10-25 23:49:14 +0000123 struct Node;
Daniel Berlinaad15882007-09-16 21:45:02 +0000124
125 /// Constraint - Objects of this structure are used to represent the various
126 /// constraints identified by the algorithm. The constraints are 'copy',
127 /// for statements like "A = B", 'load' for statements like "A = *B",
128 /// 'store' for statements like "*A = B", and AddressOf for statements like
129 /// A = alloca; The Offset is applied as *(A + K) = B for stores,
130 /// A = *(B + K) for loads, and A = B + K for copies. It is
Daniel Berlind81ccc22007-09-24 19:45:49 +0000131 /// illegal on addressof constraints (because it is statically
Daniel Berlinaad15882007-09-16 21:45:02 +0000132 /// resolvable to A = &C where C = B + K)
133
134 struct Constraint {
135 enum ConstraintType { Copy, Load, Store, AddressOf } Type;
136 unsigned Dest;
137 unsigned Src;
138 unsigned Offset;
139
140 Constraint(ConstraintType Ty, unsigned D, unsigned S, unsigned O = 0)
141 : Type(Ty), Dest(D), Src(S), Offset(O) {
142 assert(Offset == 0 || Ty != AddressOf &&
143 "Offset is illegal on addressof constraints");
144 }
Daniel Berlin336c6c02007-09-29 00:50:40 +0000145
Daniel Berlinc7a12ae2007-09-27 15:42:23 +0000146 bool operator==(const Constraint &RHS) const {
147 return RHS.Type == Type
148 && RHS.Dest == Dest
149 && RHS.Src == Src
150 && RHS.Offset == Offset;
151 }
Daniel Berlin336c6c02007-09-29 00:50:40 +0000152
153 bool operator!=(const Constraint &RHS) const {
154 return !(*this == RHS);
155 }
156
Daniel Berlinc7a12ae2007-09-27 15:42:23 +0000157 bool operator<(const Constraint &RHS) const {
158 if (RHS.Type != Type)
159 return RHS.Type < Type;
160 else if (RHS.Dest != Dest)
161 return RHS.Dest < Dest;
162 else if (RHS.Src != Src)
163 return RHS.Src < Src;
164 return RHS.Offset < Offset;
165 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000166 };
167
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000168 // Information DenseSet requires implemented in order to be able to do
169 // it's thing
170 struct PairKeyInfo {
171 static inline std::pair<unsigned, unsigned> getEmptyKey() {
172 return std::make_pair(~0UL, ~0UL);
173 }
174 static inline std::pair<unsigned, unsigned> getTombstoneKey() {
175 return std::make_pair(~0UL - 1, ~0UL - 1);
176 }
177 static unsigned getHashValue(const std::pair<unsigned, unsigned> &P) {
178 return P.first ^ P.second;
179 }
180 static unsigned isEqual(const std::pair<unsigned, unsigned> &LHS,
181 const std::pair<unsigned, unsigned> &RHS) {
182 return LHS == RHS;
183 }
184 };
185
Daniel Berlin336c6c02007-09-29 00:50:40 +0000186 struct ConstraintKeyInfo {
187 static inline Constraint getEmptyKey() {
188 return Constraint(Constraint::Copy, ~0UL, ~0UL, ~0UL);
189 }
190 static inline Constraint getTombstoneKey() {
191 return Constraint(Constraint::Copy, ~0UL - 1, ~0UL - 1, ~0UL - 1);
192 }
193 static unsigned getHashValue(const Constraint &C) {
194 return C.Src ^ C.Dest ^ C.Type ^ C.Offset;
195 }
196 static bool isEqual(const Constraint &LHS,
197 const Constraint &RHS) {
198 return LHS.Type == RHS.Type && LHS.Dest == RHS.Dest
199 && LHS.Src == RHS.Src && LHS.Offset == RHS.Offset;
200 }
201 };
202
Daniel Berlind81ccc22007-09-24 19:45:49 +0000203 // Node class - This class is used to represent a node in the constraint
Daniel Berline6f04792007-09-24 22:20:45 +0000204 // graph. Due to various optimizations, it is not always the case that
205 // there is a mapping from a Node to a Value. In particular, we add
206 // artificial Node's that represent the set of pointed-to variables shared
207 // for each location equivalent Node.
Daniel Berlinaad15882007-09-16 21:45:02 +0000208 struct Node {
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000209 private:
210 static unsigned Counter;
211
212 public:
Daniel Berlind81ccc22007-09-24 19:45:49 +0000213 Value *Val;
Daniel Berlinaad15882007-09-16 21:45:02 +0000214 SparseBitVector<> *Edges;
215 SparseBitVector<> *PointsTo;
216 SparseBitVector<> *OldPointsTo;
Daniel Berlinaad15882007-09-16 21:45:02 +0000217 std::list<Constraint> Constraints;
218
Daniel Berlind81ccc22007-09-24 19:45:49 +0000219 // Pointer and location equivalence labels
220 unsigned PointerEquivLabel;
221 unsigned LocationEquivLabel;
222 // Predecessor edges, both real and implicit
223 SparseBitVector<> *PredEdges;
224 SparseBitVector<> *ImplicitPredEdges;
225 // Set of nodes that point to us, only use for location equivalence.
226 SparseBitVector<> *PointedToBy;
227 // Number of incoming edges, used during variable substitution to early
228 // free the points-to sets
229 unsigned NumInEdges;
Daniel Berline6f04792007-09-24 22:20:45 +0000230 // True if our points-to set is in the Set2PEClass map
Daniel Berlind81ccc22007-09-24 19:45:49 +0000231 bool StoredInHash;
Daniel Berline6f04792007-09-24 22:20:45 +0000232 // True if our node has no indirect constraints (complex or otherwise)
Daniel Berlind81ccc22007-09-24 19:45:49 +0000233 bool Direct;
234 // True if the node is address taken, *or* it is part of a group of nodes
235 // that must be kept together. This is set to true for functions and
236 // their arg nodes, which must be kept at the same position relative to
237 // their base function node.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000238 bool AddressTaken;
Daniel Berlinaad15882007-09-16 21:45:02 +0000239
Daniel Berlind81ccc22007-09-24 19:45:49 +0000240 // Nodes in cycles (or in equivalence classes) are united together using a
241 // standard union-find representation with path compression. NodeRep
242 // gives the index into GraphNodes for the representative Node.
243 unsigned NodeRep;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000244
245 // Modification timestamp. Assigned from Counter.
246 // Used for work list prioritization.
247 unsigned Timestamp;
Daniel Berlind81ccc22007-09-24 19:45:49 +0000248
Dan Gohmanded2b0d2007-12-14 15:41:34 +0000249 explicit Node(bool direct = true) :
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000250 Val(0), Edges(0), PointsTo(0), OldPointsTo(0),
Daniel Berlind81ccc22007-09-24 19:45:49 +0000251 PointerEquivLabel(0), LocationEquivLabel(0), PredEdges(0),
252 ImplicitPredEdges(0), PointedToBy(0), NumInEdges(0),
253 StoredInHash(false), Direct(direct), AddressTaken(false),
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000254 NodeRep(SelfRep), Timestamp(0) { }
Daniel Berlinaad15882007-09-16 21:45:02 +0000255
Chris Lattnere995a2a2004-05-23 21:00:47 +0000256 Node *setValue(Value *V) {
257 assert(Val == 0 && "Value already set for this node!");
258 Val = V;
259 return this;
260 }
261
262 /// getValue - Return the LLVM value corresponding to this node.
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000263 ///
Chris Lattnere995a2a2004-05-23 21:00:47 +0000264 Value *getValue() const { return Val; }
265
Chris Lattnere995a2a2004-05-23 21:00:47 +0000266 /// addPointerTo - Add a pointer to the list of pointees of this node,
267 /// returning true if this caused a new pointer to be added, or false if
268 /// we already knew about the points-to relation.
Daniel Berlinaad15882007-09-16 21:45:02 +0000269 bool addPointerTo(unsigned Node) {
270 return PointsTo->test_and_set(Node);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000271 }
272
273 /// intersects - Return true if the points-to set of this node intersects
274 /// with the points-to set of the specified node.
275 bool intersects(Node *N) const;
276
277 /// intersectsIgnoring - Return true if the points-to set of this node
278 /// intersects with the points-to set of the specified node on any nodes
279 /// except for the specified node to ignore.
Daniel Berlinaad15882007-09-16 21:45:02 +0000280 bool intersectsIgnoring(Node *N, unsigned) const;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000281
282 // Timestamp a node (used for work list prioritization)
283 void Stamp() {
284 Timestamp = Counter++;
285 }
286
287 bool isRep() {
288 return( (int) NodeRep < 0 );
289 }
290 };
291
292 struct WorkListElement {
293 Node* node;
294 unsigned Timestamp;
295 WorkListElement(Node* n, unsigned t) : node(n), Timestamp(t) {}
296
297 // Note that we reverse the sense of the comparison because we
298 // actually want to give low timestamps the priority over high,
299 // whereas priority is typically interpreted as a greater value is
300 // given high priority.
301 bool operator<(const WorkListElement& that) const {
302 return( this->Timestamp > that.Timestamp );
303 }
304 };
305
306 // Priority-queue based work list specialized for Nodes.
307 class WorkList {
308 std::priority_queue<WorkListElement> Q;
309
310 public:
311 void insert(Node* n) {
312 Q.push( WorkListElement(n, n->Timestamp) );
313 }
314
315 // We automatically discard non-representative nodes and nodes
316 // that were in the work list twice (we keep a copy of the
317 // timestamp in the work list so we can detect this situation by
318 // comparing against the node's current timestamp).
319 Node* pop() {
320 while( !Q.empty() ) {
321 WorkListElement x = Q.top(); Q.pop();
322 Node* INode = x.node;
323
324 if( INode->isRep() &&
325 INode->Timestamp == x.Timestamp ) {
326 return(x.node);
327 }
328 }
329 return(0);
330 }
331
332 bool empty() {
333 return Q.empty();
334 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000335 };
336
337 /// GraphNodes - This vector is populated as part of the object
338 /// identification stage of the analysis, which populates this vector with a
339 /// node for each memory object and fills in the ValueNodes map.
340 std::vector<Node> GraphNodes;
341
342 /// ValueNodes - This map indicates the Node that a particular Value* is
343 /// represented by. This contains entries for all pointers.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000344 DenseMap<Value*, unsigned> ValueNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000345
346 /// ObjectNodes - This map contains entries for each memory object in the
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000347 /// program: globals, alloca's and mallocs.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000348 DenseMap<Value*, unsigned> ObjectNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000349
350 /// ReturnNodes - This map contains an entry for each function in the
351 /// program that returns a value.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000352 DenseMap<Function*, unsigned> ReturnNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000353
354 /// VarargNodes - This map contains the entry used to represent all pointers
355 /// passed through the varargs portion of a function call for a particular
356 /// function. An entry is not present in this map for functions that do not
357 /// take variable arguments.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000358 DenseMap<Function*, unsigned> VarargNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000359
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000360
Chris Lattnere995a2a2004-05-23 21:00:47 +0000361 /// Constraints - This vector contains a list of all of the constraints
362 /// identified by the program.
363 std::vector<Constraint> Constraints;
364
Daniel Berlind81ccc22007-09-24 19:45:49 +0000365 // Map from graph node to maximum K value that is allowed (for functions,
Daniel Berlinaad15882007-09-16 21:45:02 +0000366 // this is equivalent to the number of arguments + CallFirstArgPos)
367 std::map<unsigned, unsigned> MaxK;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000368
369 /// This enum defines the GraphNodes indices that correspond to important
370 /// fixed sets.
371 enum {
372 UniversalSet = 0,
373 NullPtr = 1,
Daniel Berlind81ccc22007-09-24 19:45:49 +0000374 NullObject = 2,
375 NumberSpecialNodes
Chris Lattnere995a2a2004-05-23 21:00:47 +0000376 };
Daniel Berlind81ccc22007-09-24 19:45:49 +0000377 // Stack for Tarjan's
Daniel Berlinaad15882007-09-16 21:45:02 +0000378 std::stack<unsigned> SCCStack;
Daniel Berlinaad15882007-09-16 21:45:02 +0000379 // Map from Graph Node to DFS number
380 std::vector<unsigned> Node2DFS;
381 // Map from Graph Node to Deleted from graph.
382 std::vector<bool> Node2Deleted;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000383 // Same as Node Maps, but implemented as std::map because it is faster to
384 // clear
385 std::map<unsigned, unsigned> Tarjan2DFS;
386 std::map<unsigned, bool> Tarjan2Deleted;
387 // Current DFS number
Daniel Berlinaad15882007-09-16 21:45:02 +0000388 unsigned DFSNumber;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000389
390 // Work lists.
391 WorkList w1, w2;
392 WorkList *CurrWL, *NextWL; // "current" and "next" work lists
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000393
Daniel Berlind81ccc22007-09-24 19:45:49 +0000394 // Offline variable substitution related things
395
396 // Temporary rep storage, used because we can't collapse SCC's in the
397 // predecessor graph by uniting the variables permanently, we can only do so
398 // for the successor graph.
399 std::vector<unsigned> VSSCCRep;
400 // Mapping from node to whether we have visited it during SCC finding yet.
401 std::vector<bool> Node2Visited;
402 // During variable substitution, we create unknowns to represent the unknown
403 // value that is a dereference of a variable. These nodes are known as
404 // "ref" nodes (since they represent the value of dereferences).
405 unsigned FirstRefNode;
406 // During HVN, we create represent address taken nodes as if they were
407 // unknown (since HVN, unlike HU, does not evaluate unions).
408 unsigned FirstAdrNode;
409 // Current pointer equivalence class number
410 unsigned PEClass;
411 // Mapping from points-to sets to equivalence classes
412 typedef DenseMap<SparseBitVector<> *, unsigned, BitmapKeyInfo> BitVectorMap;
413 BitVectorMap Set2PEClass;
414 // Mapping from pointer equivalences to the representative node. -1 if we
415 // have no representative node for this pointer equivalence class yet.
416 std::vector<int> PEClass2Node;
417 // Mapping from pointer equivalences to representative node. This includes
418 // pointer equivalent but not location equivalent variables. -1 if we have
419 // no representative node for this pointer equivalence class yet.
420 std::vector<int> PENLEClass2Node;
421
Chris Lattnere995a2a2004-05-23 21:00:47 +0000422 public:
Daniel Berlinaad15882007-09-16 21:45:02 +0000423 static char ID;
424 Andersens() : ModulePass((intptr_t)&ID) {}
425
Chris Lattnerb12914b2004-09-20 04:48:05 +0000426 bool runOnModule(Module &M) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000427 InitializeAliasAnalysis(this);
428 IdentifyObjects(M);
429 CollectConstraints(M);
Daniel Berlind81ccc22007-09-24 19:45:49 +0000430#undef DEBUG_TYPE
431#define DEBUG_TYPE "anders-aa-constraints"
Chris Lattnere995a2a2004-05-23 21:00:47 +0000432 DEBUG(PrintConstraints());
Daniel Berlind81ccc22007-09-24 19:45:49 +0000433#undef DEBUG_TYPE
434#define DEBUG_TYPE "anders-aa"
Chris Lattnere995a2a2004-05-23 21:00:47 +0000435 SolveConstraints();
436 DEBUG(PrintPointsToGraph());
437
438 // Free the constraints list, as we don't need it to respond to alias
439 // requests.
440 ObjectNodes.clear();
441 ReturnNodes.clear();
442 VarargNodes.clear();
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000443 std::vector<Constraint>().swap(Constraints);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000444 return false;
445 }
446
447 void releaseMemory() {
448 // FIXME: Until we have transitively required passes working correctly,
449 // this cannot be enabled! Otherwise, using -count-aa with the pass
450 // causes memory to be freed too early. :(
451#if 0
452 // The memory objects and ValueNodes data structures at the only ones that
453 // are still live after construction.
454 std::vector<Node>().swap(GraphNodes);
455 ValueNodes.clear();
456#endif
457 }
458
459 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
460 AliasAnalysis::getAnalysisUsage(AU);
461 AU.setPreservesAll(); // Does not transform code
462 }
463
464 //------------------------------------------------
465 // Implement the AliasAnalysis API
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000466 //
Chris Lattnere995a2a2004-05-23 21:00:47 +0000467 AliasResult alias(const Value *V1, unsigned V1Size,
468 const Value *V2, unsigned V2Size);
Reid Spencer3a9ec242006-08-28 01:02:49 +0000469 virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
470 virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000471 void getMustAliases(Value *P, std::vector<Value*> &RetVals);
472 bool pointsToConstantMemory(const Value *P);
473
474 virtual void deleteValue(Value *V) {
475 ValueNodes.erase(V);
476 getAnalysis<AliasAnalysis>().deleteValue(V);
477 }
478
479 virtual void copyValue(Value *From, Value *To) {
480 ValueNodes[To] = ValueNodes[From];
481 getAnalysis<AliasAnalysis>().copyValue(From, To);
482 }
483
484 private:
485 /// getNode - Return the node corresponding to the specified pointer scalar.
486 ///
Daniel Berlinaad15882007-09-16 21:45:02 +0000487 unsigned getNode(Value *V) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000488 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattnerdf9b7bc2004-08-16 05:38:02 +0000489 if (!isa<GlobalValue>(C))
490 return getNodeForConstantPointer(C);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000491
Daniel Berlind81ccc22007-09-24 19:45:49 +0000492 DenseMap<Value*, unsigned>::iterator I = ValueNodes.find(V);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000493 if (I == ValueNodes.end()) {
Jim Laskey16d42c62006-07-11 18:25:13 +0000494#ifndef NDEBUG
495 V->dump();
496#endif
Jim Laskeye37fe9b2006-07-11 17:58:07 +0000497 assert(0 && "Value does not have a node in the points-to graph!");
Chris Lattnere995a2a2004-05-23 21:00:47 +0000498 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000499 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000500 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000501
Chris Lattnere995a2a2004-05-23 21:00:47 +0000502 /// getObject - Return the node corresponding to the memory object for the
503 /// specified global or allocation instruction.
Daniel Berlinaad15882007-09-16 21:45:02 +0000504 unsigned getObject(Value *V) {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000505 DenseMap<Value*, unsigned>::iterator I = ObjectNodes.find(V);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000506 assert(I != ObjectNodes.end() &&
507 "Value does not have an object in the points-to graph!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000508 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000509 }
510
511 /// getReturnNode - Return the node representing the return value for the
512 /// specified function.
Daniel Berlinaad15882007-09-16 21:45:02 +0000513 unsigned getReturnNode(Function *F) {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000514 DenseMap<Function*, unsigned>::iterator I = ReturnNodes.find(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000515 assert(I != ReturnNodes.end() && "Function does not return a value!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000516 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000517 }
518
519 /// getVarargNode - Return the node representing the variable arguments
520 /// formal for the specified function.
Daniel Berlinaad15882007-09-16 21:45:02 +0000521 unsigned getVarargNode(Function *F) {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000522 DenseMap<Function*, unsigned>::iterator I = VarargNodes.find(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000523 assert(I != VarargNodes.end() && "Function does not take var args!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000524 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000525 }
526
527 /// getNodeValue - Get the node for the specified LLVM value and set the
528 /// value for it to be the specified value.
Daniel Berlinaad15882007-09-16 21:45:02 +0000529 unsigned getNodeValue(Value &V) {
530 unsigned Index = getNode(&V);
531 GraphNodes[Index].setValue(&V);
532 return Index;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000533 }
534
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000535 unsigned UniteNodes(unsigned First, unsigned Second,
536 bool UnionByRank = true);
Daniel Berlinaad15882007-09-16 21:45:02 +0000537 unsigned FindNode(unsigned Node);
538
Chris Lattnere995a2a2004-05-23 21:00:47 +0000539 void IdentifyObjects(Module &M);
540 void CollectConstraints(Module &M);
Daniel Berlinaad15882007-09-16 21:45:02 +0000541 bool AnalyzeUsesOfFunction(Value *);
542 void CreateConstraintGraph();
Daniel Berlind81ccc22007-09-24 19:45:49 +0000543 void OptimizeConstraints();
544 unsigned FindEquivalentNode(unsigned, unsigned);
545 void ClumpAddressTaken();
546 void RewriteConstraints();
547 void HU();
548 void HVN();
549 void UnitePointerEquivalences();
Chris Lattnere995a2a2004-05-23 21:00:47 +0000550 void SolveConstraints();
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000551 bool QueryNode(unsigned Node);
Daniel Berlind81ccc22007-09-24 19:45:49 +0000552 void Condense(unsigned Node);
553 void HUValNum(unsigned Node);
554 void HVNValNum(unsigned Node);
Daniel Berlinaad15882007-09-16 21:45:02 +0000555 unsigned getNodeForConstantPointer(Constant *C);
556 unsigned getNodeForConstantPointerTarget(Constant *C);
557 void AddGlobalInitializerConstraints(unsigned, Constant *C);
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000558
Chris Lattnere995a2a2004-05-23 21:00:47 +0000559 void AddConstraintsForNonInternalLinkage(Function *F);
560 void AddConstraintsForCall(CallSite CS, Function *F);
Chris Lattner8a446432005-03-29 06:09:07 +0000561 bool AddConstraintsForExternalCall(CallSite CS, Function *F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000562
563
564 void PrintNode(Node *N);
565 void PrintConstraints();
Daniel Berlind81ccc22007-09-24 19:45:49 +0000566 void PrintConstraint(const Constraint &);
567 void PrintLabels();
Chris Lattnere995a2a2004-05-23 21:00:47 +0000568 void PrintPointsToGraph();
569
570 //===------------------------------------------------------------------===//
571 // Instruction visitation methods for adding constraints
572 //
573 friend class InstVisitor<Andersens>;
574 void visitReturnInst(ReturnInst &RI);
575 void visitInvokeInst(InvokeInst &II) { visitCallSite(CallSite(&II)); }
576 void visitCallInst(CallInst &CI) { visitCallSite(CallSite(&CI)); }
577 void visitCallSite(CallSite CS);
578 void visitAllocationInst(AllocationInst &AI);
579 void visitLoadInst(LoadInst &LI);
580 void visitStoreInst(StoreInst &SI);
581 void visitGetElementPtrInst(GetElementPtrInst &GEP);
582 void visitPHINode(PHINode &PN);
583 void visitCastInst(CastInst &CI);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000584 void visitICmpInst(ICmpInst &ICI) {} // NOOP!
585 void visitFCmpInst(FCmpInst &ICI) {} // NOOP!
Chris Lattnere995a2a2004-05-23 21:00:47 +0000586 void visitSelectInst(SelectInst &SI);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000587 void visitVAArg(VAArgInst &I);
588 void visitInstruction(Instruction &I);
Daniel Berlinaad15882007-09-16 21:45:02 +0000589
Chris Lattnere995a2a2004-05-23 21:00:47 +0000590 };
591
Devang Patel19974732007-05-03 01:11:54 +0000592 char Andersens::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +0000593 RegisterPass<Andersens> X("anders-aa",
594 "Andersen's Interprocedural Alias Analysis");
Chris Lattnera5370172006-08-28 00:42:29 +0000595 RegisterAnalysisGroup<AliasAnalysis> Y(X);
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000596
597 // Initialize Timestamp Counter (static).
598 unsigned Andersens::Node::Counter = 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000599}
600
Jeff Cohen534927d2005-01-08 22:01:16 +0000601ModulePass *llvm::createAndersensPass() { return new Andersens(); }
602
Chris Lattnere995a2a2004-05-23 21:00:47 +0000603//===----------------------------------------------------------------------===//
604// AliasAnalysis Interface Implementation
605//===----------------------------------------------------------------------===//
606
607AliasAnalysis::AliasResult Andersens::alias(const Value *V1, unsigned V1Size,
608 const Value *V2, unsigned V2Size) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000609 Node *N1 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V1)))];
610 Node *N2 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V2)))];
Chris Lattnere995a2a2004-05-23 21:00:47 +0000611
612 // Check to see if the two pointers are known to not alias. They don't alias
613 // if their points-to sets do not intersect.
Daniel Berlinaad15882007-09-16 21:45:02 +0000614 if (!N1->intersectsIgnoring(N2, NullObject))
Chris Lattnere995a2a2004-05-23 21:00:47 +0000615 return NoAlias;
616
617 return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
618}
619
Chris Lattnerf392c642005-03-28 06:21:17 +0000620AliasAnalysis::ModRefResult
621Andersens::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
622 // The only thing useful that we can contribute for mod/ref information is
623 // when calling external function calls: if we know that memory never escapes
624 // from the program, it cannot be modified by an external call.
625 //
626 // NOTE: This is not really safe, at least not when the entire program is not
627 // available. The deal is that the external function could call back into the
628 // program and modify stuff. We ignore this technical niggle for now. This
629 // is, after all, a "research quality" implementation of Andersen's analysis.
630 if (Function *F = CS.getCalledFunction())
Reid Spencer5cbf9852007-01-30 20:08:39 +0000631 if (F->isDeclaration()) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000632 Node *N1 = &GraphNodes[FindNode(getNode(P))];
Chris Lattnerf392c642005-03-28 06:21:17 +0000633
Daniel Berlinaad15882007-09-16 21:45:02 +0000634 if (N1->PointsTo->empty())
635 return NoModRef;
Chris Lattnerf392c642005-03-28 06:21:17 +0000636
Daniel Berlinaad15882007-09-16 21:45:02 +0000637 if (!N1->PointsTo->test(UniversalSet))
Chris Lattnerf392c642005-03-28 06:21:17 +0000638 return NoModRef; // P doesn't point to the universal set.
639 }
640
641 return AliasAnalysis::getModRefInfo(CS, P, Size);
642}
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000643
Reid Spencer3a9ec242006-08-28 01:02:49 +0000644AliasAnalysis::ModRefResult
645Andersens::getModRefInfo(CallSite CS1, CallSite CS2) {
646 return AliasAnalysis::getModRefInfo(CS1,CS2);
647}
648
Chris Lattnere995a2a2004-05-23 21:00:47 +0000649/// getMustAlias - We can provide must alias information if we know that a
650/// pointer can only point to a specific function or the null pointer.
651/// Unfortunately we cannot determine must-alias information for global
652/// variables or any other memory memory objects because we do not track whether
653/// a pointer points to the beginning of an object or a field of it.
654void Andersens::getMustAliases(Value *P, std::vector<Value*> &RetVals) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000655 Node *N = &GraphNodes[FindNode(getNode(P))];
656 if (N->PointsTo->count() == 1) {
657 Node *Pointee = &GraphNodes[N->PointsTo->find_first()];
658 // If a function is the only object in the points-to set, then it must be
659 // the destination. Note that we can't handle global variables here,
660 // because we don't know if the pointer is actually pointing to a field of
661 // the global or to the beginning of it.
662 if (Value *V = Pointee->getValue()) {
663 if (Function *F = dyn_cast<Function>(V))
664 RetVals.push_back(F);
665 } else {
666 // If the object in the points-to set is the null object, then the null
667 // pointer is a must alias.
668 if (Pointee == &GraphNodes[NullObject])
669 RetVals.push_back(Constant::getNullValue(P->getType()));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000670 }
671 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000672 AliasAnalysis::getMustAliases(P, RetVals);
673}
674
675/// pointsToConstantMemory - If we can determine that this pointer only points
676/// to constant memory, return true. In practice, this means that if the
677/// pointer can only point to constant globals, functions, or the null pointer,
678/// return true.
679///
680bool Andersens::pointsToConstantMemory(const Value *P) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000681 Node *N = &GraphNodes[FindNode(getNode((Value*)P))];
682 unsigned i;
683
684 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
685 bi != N->PointsTo->end();
686 ++bi) {
687 i = *bi;
688 Node *Pointee = &GraphNodes[i];
689 if (Value *V = Pointee->getValue()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000690 if (!isa<GlobalValue>(V) || (isa<GlobalVariable>(V) &&
691 !cast<GlobalVariable>(V)->isConstant()))
692 return AliasAnalysis::pointsToConstantMemory(P);
693 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +0000694 if (i != NullObject)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000695 return AliasAnalysis::pointsToConstantMemory(P);
696 }
697 }
698
699 return true;
700}
701
702//===----------------------------------------------------------------------===//
703// Object Identification Phase
704//===----------------------------------------------------------------------===//
705
706/// IdentifyObjects - This stage scans the program, adding an entry to the
707/// GraphNodes list for each memory object in the program (global stack or
708/// heap), and populates the ValueNodes and ObjectNodes maps for these objects.
709///
710void Andersens::IdentifyObjects(Module &M) {
711 unsigned NumObjects = 0;
712
713 // Object #0 is always the universal set: the object that we don't know
714 // anything about.
715 assert(NumObjects == UniversalSet && "Something changed!");
716 ++NumObjects;
717
718 // Object #1 always represents the null pointer.
719 assert(NumObjects == NullPtr && "Something changed!");
720 ++NumObjects;
721
722 // Object #2 always represents the null object (the object pointed to by null)
723 assert(NumObjects == NullObject && "Something changed!");
724 ++NumObjects;
725
726 // Add all the globals first.
Chris Lattner493f6362005-03-27 22:03:46 +0000727 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
728 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000729 ObjectNodes[I] = NumObjects++;
730 ValueNodes[I] = NumObjects++;
731 }
732
733 // Add nodes for all of the functions and the instructions inside of them.
734 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
735 // The function itself is a memory object.
Daniel Berlinaad15882007-09-16 21:45:02 +0000736 unsigned First = NumObjects;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000737 ValueNodes[F] = NumObjects++;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000738 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
739 ReturnNodes[F] = NumObjects++;
740 if (F->getFunctionType()->isVarArg())
741 VarargNodes[F] = NumObjects++;
742
Daniel Berlinaad15882007-09-16 21:45:02 +0000743
Chris Lattnere995a2a2004-05-23 21:00:47 +0000744 // Add nodes for all of the incoming pointer arguments.
Chris Lattner493f6362005-03-27 22:03:46 +0000745 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
746 I != E; ++I)
Daniel Berlind81ccc22007-09-24 19:45:49 +0000747 {
748 if (isa<PointerType>(I->getType()))
749 ValueNodes[I] = NumObjects++;
750 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000751 MaxK[First] = NumObjects - First;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000752
753 // Scan the function body, creating a memory object for each heap/stack
754 // allocation in the body of the function and a node to represent all
755 // pointer values defined by instructions and used as operands.
756 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
757 // If this is an heap or stack allocation, create a node for the memory
758 // object.
759 if (isa<PointerType>(II->getType())) {
760 ValueNodes[&*II] = NumObjects++;
761 if (AllocationInst *AI = dyn_cast<AllocationInst>(&*II))
762 ObjectNodes[AI] = NumObjects++;
763 }
Nick Lewycky4ac0e8d2007-11-22 03:07:37 +0000764
765 // Calls to inline asm need to be added as well because the callee isn't
766 // referenced anywhere else.
767 if (CallInst *CI = dyn_cast<CallInst>(&*II)) {
768 Value *Callee = CI->getCalledValue();
769 if (isa<InlineAsm>(Callee))
770 ValueNodes[Callee] = NumObjects++;
771 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000772 }
773 }
774
775 // Now that we know how many objects to create, make them all now!
776 GraphNodes.resize(NumObjects);
777 NumNodes += NumObjects;
778}
779
780//===----------------------------------------------------------------------===//
781// Constraint Identification Phase
782//===----------------------------------------------------------------------===//
783
784/// getNodeForConstantPointer - Return the node corresponding to the constant
785/// pointer itself.
Daniel Berlinaad15882007-09-16 21:45:02 +0000786unsigned Andersens::getNodeForConstantPointer(Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000787 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
788
Chris Lattner267a1b02005-03-27 18:58:23 +0000789 if (isa<ConstantPointerNull>(C) || isa<UndefValue>(C))
Daniel Berlinaad15882007-09-16 21:45:02 +0000790 return NullPtr;
Reid Spencere8404342004-07-18 00:18:30 +0000791 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
792 return getNode(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000793 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
794 switch (CE->getOpcode()) {
795 case Instruction::GetElementPtr:
796 return getNodeForConstantPointer(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000797 case Instruction::IntToPtr:
Daniel Berlinaad15882007-09-16 21:45:02 +0000798 return UniversalSet;
Reid Spencer3da59db2006-11-27 01:05:10 +0000799 case Instruction::BitCast:
800 return getNodeForConstantPointer(CE->getOperand(0));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000801 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000802 cerr << "Constant Expr not yet handled: " << *CE << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +0000803 assert(0);
804 }
805 } else {
806 assert(0 && "Unknown constant pointer!");
807 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000808 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000809}
810
811/// getNodeForConstantPointerTarget - Return the node POINTED TO by the
812/// specified constant pointer.
Daniel Berlinaad15882007-09-16 21:45:02 +0000813unsigned Andersens::getNodeForConstantPointerTarget(Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000814 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
815
816 if (isa<ConstantPointerNull>(C))
Daniel Berlinaad15882007-09-16 21:45:02 +0000817 return NullObject;
Reid Spencere8404342004-07-18 00:18:30 +0000818 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
819 return getObject(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000820 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
821 switch (CE->getOpcode()) {
822 case Instruction::GetElementPtr:
823 return getNodeForConstantPointerTarget(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000824 case Instruction::IntToPtr:
Daniel Berlinaad15882007-09-16 21:45:02 +0000825 return UniversalSet;
Reid Spencer3da59db2006-11-27 01:05:10 +0000826 case Instruction::BitCast:
827 return getNodeForConstantPointerTarget(CE->getOperand(0));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000828 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000829 cerr << "Constant Expr not yet handled: " << *CE << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +0000830 assert(0);
831 }
832 } else {
833 assert(0 && "Unknown constant pointer!");
834 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000835 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000836}
837
838/// AddGlobalInitializerConstraints - Add inclusion constraints for the memory
839/// object N, which contains values indicated by C.
Daniel Berlinaad15882007-09-16 21:45:02 +0000840void Andersens::AddGlobalInitializerConstraints(unsigned NodeIndex,
841 Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000842 if (C->getType()->isFirstClassType()) {
843 if (isa<PointerType>(C->getType()))
Daniel Berlinaad15882007-09-16 21:45:02 +0000844 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
845 getNodeForConstantPointer(C)));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000846 } else if (C->isNullValue()) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000847 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
848 NullObject));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000849 return;
Chris Lattner8a446432005-03-29 06:09:07 +0000850 } else if (!isa<UndefValue>(C)) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000851 // If this is an array or struct, include constraints for each element.
852 assert(isa<ConstantArray>(C) || isa<ConstantStruct>(C));
853 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
Daniel Berlinaad15882007-09-16 21:45:02 +0000854 AddGlobalInitializerConstraints(NodeIndex,
855 cast<Constant>(C->getOperand(i)));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000856 }
857}
858
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000859/// AddConstraintsForNonInternalLinkage - If this function does not have
860/// internal linkage, realize that we can't trust anything passed into or
861/// returned by this function.
Chris Lattnere995a2a2004-05-23 21:00:47 +0000862void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
Chris Lattnere4d5c442005-03-15 04:54:21 +0000863 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000864 if (isa<PointerType>(I->getType()))
865 // If this is an argument of an externally accessible function, the
866 // incoming pointer might point to anything.
867 Constraints.push_back(Constraint(Constraint::Copy, getNode(I),
Daniel Berlinaad15882007-09-16 21:45:02 +0000868 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000869}
870
Chris Lattner8a446432005-03-29 06:09:07 +0000871/// AddConstraintsForCall - If this is a call to a "known" function, add the
872/// constraints and return true. If this is a call to an unknown function,
873/// return false.
874bool Andersens::AddConstraintsForExternalCall(CallSite CS, Function *F) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000875 assert(F->isDeclaration() && "Not an external function!");
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000876
877 // These functions don't induce any points-to constraints.
Chris Lattner175b9632005-03-29 20:36:05 +0000878 if (F->getName() == "atoi" || F->getName() == "atof" ||
879 F->getName() == "atol" || F->getName() == "atoll" ||
880 F->getName() == "remove" || F->getName() == "unlink" ||
881 F->getName() == "rename" || F->getName() == "memcmp" ||
Chris Lattner01ac91e2006-03-03 01:21:36 +0000882 F->getName() == "llvm.memset.i32" ||
883 F->getName() == "llvm.memset.i64" ||
Chris Lattner175b9632005-03-29 20:36:05 +0000884 F->getName() == "strcmp" || F->getName() == "strncmp" ||
885 F->getName() == "execl" || F->getName() == "execlp" ||
886 F->getName() == "execle" || F->getName() == "execv" ||
887 F->getName() == "execvp" || F->getName() == "chmod" ||
888 F->getName() == "puts" || F->getName() == "write" ||
889 F->getName() == "open" || F->getName() == "create" ||
890 F->getName() == "truncate" || F->getName() == "chdir" ||
891 F->getName() == "mkdir" || F->getName() == "rmdir" ||
892 F->getName() == "read" || F->getName() == "pipe" ||
893 F->getName() == "wait" || F->getName() == "time" ||
894 F->getName() == "stat" || F->getName() == "fstat" ||
895 F->getName() == "lstat" || F->getName() == "strtod" ||
896 F->getName() == "strtof" || F->getName() == "strtold" ||
897 F->getName() == "fopen" || F->getName() == "fdopen" ||
898 F->getName() == "freopen" ||
899 F->getName() == "fflush" || F->getName() == "feof" ||
900 F->getName() == "fileno" || F->getName() == "clearerr" ||
901 F->getName() == "rewind" || F->getName() == "ftell" ||
902 F->getName() == "ferror" || F->getName() == "fgetc" ||
903 F->getName() == "fgetc" || F->getName() == "_IO_getc" ||
904 F->getName() == "fwrite" || F->getName() == "fread" ||
905 F->getName() == "fgets" || F->getName() == "ungetc" ||
906 F->getName() == "fputc" ||
907 F->getName() == "fputs" || F->getName() == "putc" ||
908 F->getName() == "ftell" || F->getName() == "rewind" ||
909 F->getName() == "_IO_putc" || F->getName() == "fseek" ||
910 F->getName() == "fgetpos" || F->getName() == "fsetpos" ||
911 F->getName() == "printf" || F->getName() == "fprintf" ||
912 F->getName() == "sprintf" || F->getName() == "vprintf" ||
913 F->getName() == "vfprintf" || F->getName() == "vsprintf" ||
914 F->getName() == "scanf" || F->getName() == "fscanf" ||
915 F->getName() == "sscanf" || F->getName() == "__assert_fail" ||
916 F->getName() == "modf")
Chris Lattner8a446432005-03-29 06:09:07 +0000917 return true;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000918
Chris Lattner175b9632005-03-29 20:36:05 +0000919
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000920 // These functions do induce points-to edges.
Daniel Berlinaad15882007-09-16 21:45:02 +0000921 if (F->getName() == "llvm.memcpy.i32" || F->getName() == "llvm.memcpy.i64" ||
Chris Lattner01ac91e2006-03-03 01:21:36 +0000922 F->getName() == "llvm.memmove.i32" ||F->getName() == "llvm.memmove.i64" ||
Chris Lattner4de57fd2005-03-29 06:52:20 +0000923 F->getName() == "memmove") {
Daniel Berlinaad15882007-09-16 21:45:02 +0000924
925 // *Dest = *Src, which requires an artificial graph node to represent the
926 // constraint. It is broken up into *Dest = temp, temp = *Src
927 unsigned FirstArg = getNode(CS.getArgument(0));
928 unsigned SecondArg = getNode(CS.getArgument(1));
929 unsigned TempArg = GraphNodes.size();
930 GraphNodes.push_back(Node());
931 Constraints.push_back(Constraint(Constraint::Store,
932 FirstArg, TempArg));
933 Constraints.push_back(Constraint(Constraint::Load,
934 TempArg, SecondArg));
Chris Lattner8a446432005-03-29 06:09:07 +0000935 return true;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000936 }
937
Chris Lattner77b50562005-03-29 20:04:24 +0000938 // Result = Arg0
939 if (F->getName() == "realloc" || F->getName() == "strchr" ||
940 F->getName() == "strrchr" || F->getName() == "strstr" ||
941 F->getName() == "strtok") {
Chris Lattner8a446432005-03-29 06:09:07 +0000942 Constraints.push_back(Constraint(Constraint::Copy,
943 getNode(CS.getInstruction()),
944 getNode(CS.getArgument(0))));
945 return true;
946 }
947
948 return false;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000949}
950
951
Chris Lattnere995a2a2004-05-23 21:00:47 +0000952
Daniel Berlinaad15882007-09-16 21:45:02 +0000953/// AnalyzeUsesOfFunction - Look at all of the users of the specified function.
954/// If this is used by anything complex (i.e., the address escapes), return
955/// true.
956bool Andersens::AnalyzeUsesOfFunction(Value *V) {
957
958 if (!isa<PointerType>(V->getType())) return true;
959
960 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
961 if (dyn_cast<LoadInst>(*UI)) {
962 return false;
963 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
964 if (V == SI->getOperand(1)) {
965 return false;
966 } else if (SI->getOperand(1)) {
967 return true; // Storing the pointer
968 }
969 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
970 if (AnalyzeUsesOfFunction(GEP)) return true;
971 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
972 // Make sure that this is just the function being called, not that it is
973 // passing into the function.
974 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
975 if (CI->getOperand(i) == V) return true;
976 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
977 // Make sure that this is just the function being called, not that it is
978 // passing into the function.
979 for (unsigned i = 3, e = II->getNumOperands(); i != e; ++i)
980 if (II->getOperand(i) == V) return true;
981 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
982 if (CE->getOpcode() == Instruction::GetElementPtr ||
983 CE->getOpcode() == Instruction::BitCast) {
984 if (AnalyzeUsesOfFunction(CE))
985 return true;
986 } else {
987 return true;
988 }
989 } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(*UI)) {
990 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
991 return true; // Allow comparison against null.
992 } else if (dyn_cast<FreeInst>(*UI)) {
993 return false;
994 } else {
995 return true;
996 }
997 return false;
998}
999
Chris Lattnere995a2a2004-05-23 21:00:47 +00001000/// CollectConstraints - This stage scans the program, adding a constraint to
1001/// the Constraints list for each instruction in the program that induces a
1002/// constraint, and setting up the initial points-to graph.
1003///
1004void Andersens::CollectConstraints(Module &M) {
1005 // First, the universal set points to itself.
Daniel Berlinaad15882007-09-16 21:45:02 +00001006 Constraints.push_back(Constraint(Constraint::AddressOf, UniversalSet,
1007 UniversalSet));
1008 Constraints.push_back(Constraint(Constraint::Store, UniversalSet,
1009 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001010
1011 // Next, the null pointer points to the null object.
Daniel Berlinaad15882007-09-16 21:45:02 +00001012 Constraints.push_back(Constraint(Constraint::AddressOf, NullPtr, NullObject));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001013
1014 // Next, add any constraints on global variables and their initializers.
Chris Lattner493f6362005-03-27 22:03:46 +00001015 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1016 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001017 // Associate the address of the global object as pointing to the memory for
1018 // the global: &G = <G memory>
Daniel Berlinaad15882007-09-16 21:45:02 +00001019 unsigned ObjectIndex = getObject(I);
1020 Node *Object = &GraphNodes[ObjectIndex];
Chris Lattnere995a2a2004-05-23 21:00:47 +00001021 Object->setValue(I);
Daniel Berlinaad15882007-09-16 21:45:02 +00001022 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(*I),
1023 ObjectIndex));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001024
1025 if (I->hasInitializer()) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001026 AddGlobalInitializerConstraints(ObjectIndex, I->getInitializer());
Chris Lattnere995a2a2004-05-23 21:00:47 +00001027 } else {
1028 // If it doesn't have an initializer (i.e. it's defined in another
1029 // translation unit), it points to the universal set.
Daniel Berlinaad15882007-09-16 21:45:02 +00001030 Constraints.push_back(Constraint(Constraint::Copy, ObjectIndex,
1031 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001032 }
1033 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001034
Chris Lattnere995a2a2004-05-23 21:00:47 +00001035 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001036 // Set up the return value node.
1037 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
Daniel Berlinaad15882007-09-16 21:45:02 +00001038 GraphNodes[getReturnNode(F)].setValue(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001039 if (F->getFunctionType()->isVarArg())
Daniel Berlinaad15882007-09-16 21:45:02 +00001040 GraphNodes[getVarargNode(F)].setValue(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001041
1042 // Set up incoming argument nodes.
Chris Lattner493f6362005-03-27 22:03:46 +00001043 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
1044 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +00001045 if (isa<PointerType>(I->getType()))
1046 getNodeValue(*I);
1047
Daniel Berlinaad15882007-09-16 21:45:02 +00001048 // At some point we should just add constraints for the escaping functions
1049 // at solve time, but this slows down solving. For now, we simply mark
1050 // address taken functions as escaping and treat them as external.
1051 if (!F->hasInternalLinkage() || AnalyzeUsesOfFunction(F))
Chris Lattnere995a2a2004-05-23 21:00:47 +00001052 AddConstraintsForNonInternalLinkage(F);
1053
Reid Spencer5cbf9852007-01-30 20:08:39 +00001054 if (!F->isDeclaration()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001055 // Scan the function body, creating a memory object for each heap/stack
1056 // allocation in the body of the function and a node to represent all
1057 // pointer values defined by instructions and used as operands.
1058 visit(F);
Chris Lattner8a446432005-03-29 06:09:07 +00001059 } else {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001060 // External functions that return pointers return the universal set.
1061 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
1062 Constraints.push_back(Constraint(Constraint::Copy,
1063 getReturnNode(F),
Daniel Berlinaad15882007-09-16 21:45:02 +00001064 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001065
1066 // Any pointers that are passed into the function have the universal set
1067 // stored into them.
Chris Lattner493f6362005-03-27 22:03:46 +00001068 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
1069 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +00001070 if (isa<PointerType>(I->getType())) {
1071 // Pointers passed into external functions could have anything stored
1072 // through them.
1073 Constraints.push_back(Constraint(Constraint::Store, getNode(I),
Daniel Berlinaad15882007-09-16 21:45:02 +00001074 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001075 // Memory objects passed into external function calls can have the
1076 // universal set point to them.
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001077#if FULL_UNIVERSAL
Chris Lattnere995a2a2004-05-23 21:00:47 +00001078 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001079 UniversalSet,
Chris Lattnere995a2a2004-05-23 21:00:47 +00001080 getNode(I)));
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001081#else
1082 Constraints.push_back(Constraint(Constraint::Copy,
1083 getNode(I),
1084 UniversalSet));
1085#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001086 }
1087
1088 // If this is an external varargs function, it can also store pointers
1089 // into any pointers passed through the varargs section.
1090 if (F->getFunctionType()->isVarArg())
1091 Constraints.push_back(Constraint(Constraint::Store, getVarargNode(F),
Daniel Berlinaad15882007-09-16 21:45:02 +00001092 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001093 }
1094 }
1095 NumConstraints += Constraints.size();
1096}
1097
1098
1099void Andersens::visitInstruction(Instruction &I) {
1100#ifdef NDEBUG
1101 return; // This function is just a big assert.
1102#endif
1103 if (isa<BinaryOperator>(I))
1104 return;
1105 // Most instructions don't have any effect on pointer values.
1106 switch (I.getOpcode()) {
1107 case Instruction::Br:
1108 case Instruction::Switch:
1109 case Instruction::Unwind:
Chris Lattnerc17edbd2004-10-16 18:16:19 +00001110 case Instruction::Unreachable:
Chris Lattnere995a2a2004-05-23 21:00:47 +00001111 case Instruction::Free:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001112 case Instruction::ICmp:
1113 case Instruction::FCmp:
Chris Lattnere995a2a2004-05-23 21:00:47 +00001114 return;
1115 default:
1116 // Is this something we aren't handling yet?
Bill Wendlinge8156192006-12-07 01:30:32 +00001117 cerr << "Unknown instruction: " << I;
Chris Lattnere995a2a2004-05-23 21:00:47 +00001118 abort();
1119 }
1120}
1121
1122void Andersens::visitAllocationInst(AllocationInst &AI) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001123 unsigned ObjectIndex = getObject(&AI);
1124 GraphNodes[ObjectIndex].setValue(&AI);
1125 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(AI),
1126 ObjectIndex));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001127}
1128
1129void Andersens::visitReturnInst(ReturnInst &RI) {
1130 if (RI.getNumOperands() && isa<PointerType>(RI.getOperand(0)->getType()))
1131 // return V --> <Copy/retval{F}/v>
1132 Constraints.push_back(Constraint(Constraint::Copy,
1133 getReturnNode(RI.getParent()->getParent()),
1134 getNode(RI.getOperand(0))));
1135}
1136
1137void Andersens::visitLoadInst(LoadInst &LI) {
1138 if (isa<PointerType>(LI.getType()))
1139 // P1 = load P2 --> <Load/P1/P2>
1140 Constraints.push_back(Constraint(Constraint::Load, getNodeValue(LI),
1141 getNode(LI.getOperand(0))));
1142}
1143
1144void Andersens::visitStoreInst(StoreInst &SI) {
1145 if (isa<PointerType>(SI.getOperand(0)->getType()))
1146 // store P1, P2 --> <Store/P2/P1>
1147 Constraints.push_back(Constraint(Constraint::Store,
1148 getNode(SI.getOperand(1)),
1149 getNode(SI.getOperand(0))));
1150}
1151
1152void Andersens::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1153 // P1 = getelementptr P2, ... --> <Copy/P1/P2>
1154 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(GEP),
1155 getNode(GEP.getOperand(0))));
1156}
1157
1158void Andersens::visitPHINode(PHINode &PN) {
1159 if (isa<PointerType>(PN.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001160 unsigned PNN = getNodeValue(PN);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001161 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1162 // P1 = phi P2, P3 --> <Copy/P1/P2>, <Copy/P1/P3>, ...
1163 Constraints.push_back(Constraint(Constraint::Copy, PNN,
1164 getNode(PN.getIncomingValue(i))));
1165 }
1166}
1167
1168void Andersens::visitCastInst(CastInst &CI) {
1169 Value *Op = CI.getOperand(0);
1170 if (isa<PointerType>(CI.getType())) {
1171 if (isa<PointerType>(Op->getType())) {
1172 // P1 = cast P2 --> <Copy/P1/P2>
1173 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
1174 getNode(CI.getOperand(0))));
1175 } else {
1176 // P1 = cast int --> <Copy/P1/Univ>
Chris Lattner175b9632005-03-29 20:36:05 +00001177#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +00001178 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
Daniel Berlinaad15882007-09-16 21:45:02 +00001179 UniversalSet));
Chris Lattnerbd135c72005-04-05 01:12:03 +00001180#else
1181 getNodeValue(CI);
Chris Lattner175b9632005-03-29 20:36:05 +00001182#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001183 }
1184 } else if (isa<PointerType>(Op->getType())) {
1185 // int = cast P1 --> <Copy/Univ/P1>
Chris Lattner175b9632005-03-29 20:36:05 +00001186#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +00001187 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001188 UniversalSet,
Chris Lattnere995a2a2004-05-23 21:00:47 +00001189 getNode(CI.getOperand(0))));
Chris Lattnerbd135c72005-04-05 01:12:03 +00001190#else
1191 getNode(CI.getOperand(0));
Chris Lattner175b9632005-03-29 20:36:05 +00001192#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001193 }
1194}
1195
1196void Andersens::visitSelectInst(SelectInst &SI) {
1197 if (isa<PointerType>(SI.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001198 unsigned SIN = getNodeValue(SI);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001199 // P1 = select C, P2, P3 ---> <Copy/P1/P2>, <Copy/P1/P3>
1200 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1201 getNode(SI.getOperand(1))));
1202 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1203 getNode(SI.getOperand(2))));
1204 }
1205}
1206
Chris Lattnere995a2a2004-05-23 21:00:47 +00001207void Andersens::visitVAArg(VAArgInst &I) {
1208 assert(0 && "vaarg not handled yet!");
1209}
1210
1211/// AddConstraintsForCall - Add constraints for a call with actual arguments
1212/// specified by CS to the function specified by F. Note that the types of
1213/// arguments might not match up in the case where this is an indirect call and
1214/// the function pointer has been casted. If this is the case, do something
1215/// reasonable.
1216void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001217 Value *CallValue = CS.getCalledValue();
1218 bool IsDeref = F == NULL;
1219
1220 // If this is a call to an external function, try to handle it directly to get
1221 // some taste of context sensitivity.
1222 if (F && F->isDeclaration() && AddConstraintsForExternalCall(CS, F))
Chris Lattner8a446432005-03-29 06:09:07 +00001223 return;
1224
Chris Lattnere995a2a2004-05-23 21:00:47 +00001225 if (isa<PointerType>(CS.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001226 unsigned CSN = getNode(CS.getInstruction());
1227 if (!F || isa<PointerType>(F->getFunctionType()->getReturnType())) {
1228 if (IsDeref)
1229 Constraints.push_back(Constraint(Constraint::Load, CSN,
1230 getNode(CallValue), CallReturnPos));
1231 else
1232 Constraints.push_back(Constraint(Constraint::Copy, CSN,
1233 getNode(CallValue) + CallReturnPos));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001234 } else {
1235 // If the function returns a non-pointer value, handle this just like we
1236 // treat a nonpointer cast to pointer.
1237 Constraints.push_back(Constraint(Constraint::Copy, CSN,
Daniel Berlinaad15882007-09-16 21:45:02 +00001238 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001239 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001240 } else if (F && isa<PointerType>(F->getFunctionType()->getReturnType())) {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001241#if FULL_UNIVERSAL
Chris Lattnere995a2a2004-05-23 21:00:47 +00001242 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001243 UniversalSet,
1244 getNode(CallValue) + CallReturnPos));
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001245#else
1246 Constraints.push_back(Constraint(Constraint::Copy,
1247 getNode(CallValue) + CallReturnPos,
1248 UniversalSet));
1249#endif
1250
1251
Chris Lattnere995a2a2004-05-23 21:00:47 +00001252 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001253
Chris Lattnere995a2a2004-05-23 21:00:47 +00001254 CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
Daniel Berlinaad15882007-09-16 21:45:02 +00001255 if (F) {
1256 // Direct Call
1257 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1258 for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI)
1259 if (isa<PointerType>(AI->getType())) {
1260 if (isa<PointerType>((*ArgI)->getType())) {
1261 // Copy the actual argument into the formal argument.
1262 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1263 getNode(*ArgI)));
1264 } else {
1265 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1266 UniversalSet));
1267 }
1268 } else if (isa<PointerType>((*ArgI)->getType())) {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001269#if FULL_UNIVERSAL
Daniel Berlinaad15882007-09-16 21:45:02 +00001270 Constraints.push_back(Constraint(Constraint::Copy,
1271 UniversalSet,
1272 getNode(*ArgI)));
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001273#else
1274 Constraints.push_back(Constraint(Constraint::Copy,
1275 getNode(*ArgI),
1276 UniversalSet));
1277#endif
Daniel Berlinaad15882007-09-16 21:45:02 +00001278 }
1279 } else {
1280 //Indirect Call
1281 unsigned ArgPos = CallFirstArgPos;
1282 for (; ArgI != ArgE; ++ArgI) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001283 if (isa<PointerType>((*ArgI)->getType())) {
1284 // Copy the actual argument into the formal argument.
Daniel Berlinaad15882007-09-16 21:45:02 +00001285 Constraints.push_back(Constraint(Constraint::Store,
1286 getNode(CallValue),
1287 getNode(*ArgI), ArgPos++));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001288 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +00001289 Constraints.push_back(Constraint(Constraint::Store,
1290 getNode (CallValue),
1291 UniversalSet, ArgPos++));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001292 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00001293 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001294 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00001295 // Copy all pointers passed through the varargs section to the varargs node.
Daniel Berlinaad15882007-09-16 21:45:02 +00001296 if (F && F->getFunctionType()->isVarArg())
Chris Lattnere995a2a2004-05-23 21:00:47 +00001297 for (; ArgI != ArgE; ++ArgI)
1298 if (isa<PointerType>((*ArgI)->getType()))
1299 Constraints.push_back(Constraint(Constraint::Copy, getVarargNode(F),
1300 getNode(*ArgI)));
1301 // If more arguments are passed in than we track, just drop them on the floor.
1302}
1303
1304void Andersens::visitCallSite(CallSite CS) {
1305 if (isa<PointerType>(CS.getType()))
1306 getNodeValue(*CS.getInstruction());
1307
1308 if (Function *F = CS.getCalledFunction()) {
1309 AddConstraintsForCall(CS, F);
1310 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +00001311 AddConstraintsForCall(CS, NULL);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001312 }
1313}
1314
1315//===----------------------------------------------------------------------===//
1316// Constraint Solving Phase
1317//===----------------------------------------------------------------------===//
1318
1319/// intersects - Return true if the points-to set of this node intersects
1320/// with the points-to set of the specified node.
1321bool Andersens::Node::intersects(Node *N) const {
Daniel Berlinaad15882007-09-16 21:45:02 +00001322 return PointsTo->intersects(N->PointsTo);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001323}
1324
1325/// intersectsIgnoring - Return true if the points-to set of this node
1326/// intersects with the points-to set of the specified node on any nodes
1327/// except for the specified node to ignore.
Daniel Berlinaad15882007-09-16 21:45:02 +00001328bool Andersens::Node::intersectsIgnoring(Node *N, unsigned Ignoring) const {
1329 // TODO: If we are only going to call this with the same value for Ignoring,
1330 // we should move the special values out of the points-to bitmap.
1331 bool WeHadIt = PointsTo->test(Ignoring);
1332 bool NHadIt = N->PointsTo->test(Ignoring);
1333 bool Result = false;
1334 if (WeHadIt)
1335 PointsTo->reset(Ignoring);
1336 if (NHadIt)
1337 N->PointsTo->reset(Ignoring);
1338 Result = PointsTo->intersects(N->PointsTo);
1339 if (WeHadIt)
1340 PointsTo->set(Ignoring);
1341 if (NHadIt)
1342 N->PointsTo->set(Ignoring);
1343 return Result;
Chris Lattnere995a2a2004-05-23 21:00:47 +00001344}
1345
Daniel Berlind81ccc22007-09-24 19:45:49 +00001346void dumpToDOUT(SparseBitVector<> *bitmap) {
Bill Wendlingcab5f5d2007-09-24 22:43:48 +00001347#ifndef NDEBUG
Daniel Berlind81ccc22007-09-24 19:45:49 +00001348 dump(*bitmap, DOUT);
Bill Wendlingcab5f5d2007-09-24 22:43:48 +00001349#endif
Daniel Berlind81ccc22007-09-24 19:45:49 +00001350}
1351
1352
1353/// Clump together address taken variables so that the points-to sets use up
1354/// less space and can be operated on faster.
1355
1356void Andersens::ClumpAddressTaken() {
1357#undef DEBUG_TYPE
1358#define DEBUG_TYPE "anders-aa-renumber"
1359 std::vector<unsigned> Translate;
1360 std::vector<Node> NewGraphNodes;
1361
1362 Translate.resize(GraphNodes.size());
1363 unsigned NewPos = 0;
1364
1365 for (unsigned i = 0; i < Constraints.size(); ++i) {
1366 Constraint &C = Constraints[i];
1367 if (C.Type == Constraint::AddressOf) {
1368 GraphNodes[C.Src].AddressTaken = true;
1369 }
1370 }
1371 for (unsigned i = 0; i < NumberSpecialNodes; ++i) {
1372 unsigned Pos = NewPos++;
1373 Translate[i] = Pos;
1374 NewGraphNodes.push_back(GraphNodes[i]);
1375 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1376 }
1377
1378 // I believe this ends up being faster than making two vectors and splicing
1379 // them.
1380 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1381 if (GraphNodes[i].AddressTaken) {
1382 unsigned Pos = NewPos++;
1383 Translate[i] = Pos;
1384 NewGraphNodes.push_back(GraphNodes[i]);
1385 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1386 }
1387 }
1388
1389 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1390 if (!GraphNodes[i].AddressTaken) {
1391 unsigned Pos = NewPos++;
1392 Translate[i] = Pos;
1393 NewGraphNodes.push_back(GraphNodes[i]);
1394 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1395 }
1396 }
1397
1398 for (DenseMap<Value*, unsigned>::iterator Iter = ValueNodes.begin();
1399 Iter != ValueNodes.end();
1400 ++Iter)
1401 Iter->second = Translate[Iter->second];
1402
1403 for (DenseMap<Value*, unsigned>::iterator Iter = ObjectNodes.begin();
1404 Iter != ObjectNodes.end();
1405 ++Iter)
1406 Iter->second = Translate[Iter->second];
1407
1408 for (DenseMap<Function*, unsigned>::iterator Iter = ReturnNodes.begin();
1409 Iter != ReturnNodes.end();
1410 ++Iter)
1411 Iter->second = Translate[Iter->second];
1412
1413 for (DenseMap<Function*, unsigned>::iterator Iter = VarargNodes.begin();
1414 Iter != VarargNodes.end();
1415 ++Iter)
1416 Iter->second = Translate[Iter->second];
1417
1418 for (unsigned i = 0; i < Constraints.size(); ++i) {
1419 Constraint &C = Constraints[i];
1420 C.Src = Translate[C.Src];
1421 C.Dest = Translate[C.Dest];
1422 }
1423
1424 GraphNodes.swap(NewGraphNodes);
1425#undef DEBUG_TYPE
1426#define DEBUG_TYPE "anders-aa"
1427}
1428
1429/// The technique used here is described in "Exploiting Pointer and Location
1430/// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1431/// Analysis Symposium (SAS), August 2007." It is known as the "HVN" algorithm,
1432/// and is equivalent to value numbering the collapsed constraint graph without
1433/// evaluating unions. This is used as a pre-pass to HU in order to resolve
1434/// first order pointer dereferences and speed up/reduce memory usage of HU.
1435/// Running both is equivalent to HRU without the iteration
1436/// HVN in more detail:
1437/// Imagine the set of constraints was simply straight line code with no loops
1438/// (we eliminate cycles, so there are no loops), such as:
1439/// E = &D
1440/// E = &C
1441/// E = F
1442/// F = G
1443/// G = F
1444/// Applying value numbering to this code tells us:
1445/// G == F == E
1446///
1447/// For HVN, this is as far as it goes. We assign new value numbers to every
1448/// "address node", and every "reference node".
1449/// To get the optimal result for this, we use a DFS + SCC (since all nodes in a
1450/// cycle must have the same value number since the = operation is really
1451/// inclusion, not overwrite), and value number nodes we receive points-to sets
1452/// before we value our own node.
1453/// The advantage of HU over HVN is that HU considers the inclusion property, so
1454/// that if you have
1455/// E = &D
1456/// E = &C
1457/// E = F
1458/// F = G
1459/// F = &D
1460/// G = F
1461/// HU will determine that G == F == E. HVN will not, because it cannot prove
1462/// that the points to information ends up being the same because they all
1463/// receive &D from E anyway.
1464
1465void Andersens::HVN() {
1466 DOUT << "Beginning HVN\n";
1467 // Build a predecessor graph. This is like our constraint graph with the
1468 // edges going in the opposite direction, and there are edges for all the
1469 // constraints, instead of just copy constraints. We also build implicit
1470 // edges for constraints are implied but not explicit. I.E for the constraint
1471 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1472 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1473 Constraint &C = Constraints[i];
1474 if (C.Type == Constraint::AddressOf) {
1475 GraphNodes[C.Src].AddressTaken = true;
1476 GraphNodes[C.Src].Direct = false;
1477
1478 // Dest = &src edge
1479 unsigned AdrNode = C.Src + FirstAdrNode;
1480 if (!GraphNodes[C.Dest].PredEdges)
1481 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1482 GraphNodes[C.Dest].PredEdges->set(AdrNode);
1483
1484 // *Dest = src edge
1485 unsigned RefNode = C.Dest + FirstRefNode;
1486 if (!GraphNodes[RefNode].ImplicitPredEdges)
1487 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1488 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1489 } else if (C.Type == Constraint::Load) {
1490 if (C.Offset == 0) {
1491 // dest = *src edge
1492 if (!GraphNodes[C.Dest].PredEdges)
1493 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1494 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1495 } else {
1496 GraphNodes[C.Dest].Direct = false;
1497 }
1498 } else if (C.Type == Constraint::Store) {
1499 if (C.Offset == 0) {
1500 // *dest = src edge
1501 unsigned RefNode = C.Dest + FirstRefNode;
1502 if (!GraphNodes[RefNode].PredEdges)
1503 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1504 GraphNodes[RefNode].PredEdges->set(C.Src);
1505 }
1506 } else {
1507 // Dest = Src edge and *Dest = *Src edge
1508 if (!GraphNodes[C.Dest].PredEdges)
1509 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1510 GraphNodes[C.Dest].PredEdges->set(C.Src);
1511 unsigned RefNode = C.Dest + FirstRefNode;
1512 if (!GraphNodes[RefNode].ImplicitPredEdges)
1513 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1514 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1515 }
1516 }
1517 PEClass = 1;
1518 // Do SCC finding first to condense our predecessor graph
1519 DFSNumber = 0;
1520 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1521 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1522 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1523
1524 for (unsigned i = 0; i < FirstRefNode; ++i) {
1525 unsigned Node = VSSCCRep[i];
1526 if (!Node2Visited[Node])
1527 HVNValNum(Node);
1528 }
1529 for (BitVectorMap::iterator Iter = Set2PEClass.begin();
1530 Iter != Set2PEClass.end();
1531 ++Iter)
1532 delete Iter->first;
1533 Set2PEClass.clear();
1534 Node2DFS.clear();
1535 Node2Deleted.clear();
1536 Node2Visited.clear();
1537 DOUT << "Finished HVN\n";
1538
1539}
1540
1541/// This is the workhorse of HVN value numbering. We combine SCC finding at the
1542/// same time because it's easy.
1543void Andersens::HVNValNum(unsigned NodeIndex) {
1544 unsigned MyDFS = DFSNumber++;
1545 Node *N = &GraphNodes[NodeIndex];
1546 Node2Visited[NodeIndex] = true;
1547 Node2DFS[NodeIndex] = MyDFS;
1548
1549 // First process all our explicit edges
1550 if (N->PredEdges)
1551 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1552 Iter != N->PredEdges->end();
1553 ++Iter) {
1554 unsigned j = VSSCCRep[*Iter];
1555 if (!Node2Deleted[j]) {
1556 if (!Node2Visited[j])
1557 HVNValNum(j);
1558 if (Node2DFS[NodeIndex] > Node2DFS[j])
1559 Node2DFS[NodeIndex] = Node2DFS[j];
1560 }
1561 }
1562
1563 // Now process all the implicit edges
1564 if (N->ImplicitPredEdges)
1565 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1566 Iter != N->ImplicitPredEdges->end();
1567 ++Iter) {
1568 unsigned j = VSSCCRep[*Iter];
1569 if (!Node2Deleted[j]) {
1570 if (!Node2Visited[j])
1571 HVNValNum(j);
1572 if (Node2DFS[NodeIndex] > Node2DFS[j])
1573 Node2DFS[NodeIndex] = Node2DFS[j];
1574 }
1575 }
1576
1577 // See if we found any cycles
1578 if (MyDFS == Node2DFS[NodeIndex]) {
1579 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1580 unsigned CycleNodeIndex = SCCStack.top();
1581 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1582 VSSCCRep[CycleNodeIndex] = NodeIndex;
1583 // Unify the nodes
1584 N->Direct &= CycleNode->Direct;
1585
1586 if (CycleNode->PredEdges) {
1587 if (!N->PredEdges)
1588 N->PredEdges = new SparseBitVector<>;
1589 *(N->PredEdges) |= CycleNode->PredEdges;
1590 delete CycleNode->PredEdges;
1591 CycleNode->PredEdges = NULL;
1592 }
1593 if (CycleNode->ImplicitPredEdges) {
1594 if (!N->ImplicitPredEdges)
1595 N->ImplicitPredEdges = new SparseBitVector<>;
1596 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1597 delete CycleNode->ImplicitPredEdges;
1598 CycleNode->ImplicitPredEdges = NULL;
1599 }
1600
1601 SCCStack.pop();
1602 }
1603
1604 Node2Deleted[NodeIndex] = true;
1605
1606 if (!N->Direct) {
1607 GraphNodes[NodeIndex].PointerEquivLabel = PEClass++;
1608 return;
1609 }
1610
1611 // Collect labels of successor nodes
1612 bool AllSame = true;
1613 unsigned First = ~0;
1614 SparseBitVector<> *Labels = new SparseBitVector<>;
1615 bool Used = false;
1616
1617 if (N->PredEdges)
1618 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1619 Iter != N->PredEdges->end();
1620 ++Iter) {
1621 unsigned j = VSSCCRep[*Iter];
1622 unsigned Label = GraphNodes[j].PointerEquivLabel;
1623 // Ignore labels that are equal to us or non-pointers
1624 if (j == NodeIndex || Label == 0)
1625 continue;
1626 if (First == (unsigned)~0)
1627 First = Label;
1628 else if (First != Label)
1629 AllSame = false;
1630 Labels->set(Label);
1631 }
1632
1633 // We either have a non-pointer, a copy of an existing node, or a new node.
1634 // Assign the appropriate pointer equivalence label.
1635 if (Labels->empty()) {
1636 GraphNodes[NodeIndex].PointerEquivLabel = 0;
1637 } else if (AllSame) {
1638 GraphNodes[NodeIndex].PointerEquivLabel = First;
1639 } else {
1640 GraphNodes[NodeIndex].PointerEquivLabel = Set2PEClass[Labels];
1641 if (GraphNodes[NodeIndex].PointerEquivLabel == 0) {
1642 unsigned EquivClass = PEClass++;
1643 Set2PEClass[Labels] = EquivClass;
1644 GraphNodes[NodeIndex].PointerEquivLabel = EquivClass;
1645 Used = true;
1646 }
1647 }
1648 if (!Used)
1649 delete Labels;
1650 } else {
1651 SCCStack.push(NodeIndex);
1652 }
1653}
1654
1655/// The technique used here is described in "Exploiting Pointer and Location
1656/// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1657/// Analysis Symposium (SAS), August 2007." It is known as the "HU" algorithm,
1658/// and is equivalent to value numbering the collapsed constraint graph
1659/// including evaluating unions.
1660void Andersens::HU() {
1661 DOUT << "Beginning HU\n";
1662 // Build a predecessor graph. This is like our constraint graph with the
1663 // edges going in the opposite direction, and there are edges for all the
1664 // constraints, instead of just copy constraints. We also build implicit
1665 // edges for constraints are implied but not explicit. I.E for the constraint
1666 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1667 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1668 Constraint &C = Constraints[i];
1669 if (C.Type == Constraint::AddressOf) {
1670 GraphNodes[C.Src].AddressTaken = true;
1671 GraphNodes[C.Src].Direct = false;
1672
1673 GraphNodes[C.Dest].PointsTo->set(C.Src);
1674 // *Dest = src edge
1675 unsigned RefNode = C.Dest + FirstRefNode;
1676 if (!GraphNodes[RefNode].ImplicitPredEdges)
1677 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1678 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1679 GraphNodes[C.Src].PointedToBy->set(C.Dest);
1680 } else if (C.Type == Constraint::Load) {
1681 if (C.Offset == 0) {
1682 // dest = *src edge
1683 if (!GraphNodes[C.Dest].PredEdges)
1684 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1685 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1686 } else {
1687 GraphNodes[C.Dest].Direct = false;
1688 }
1689 } else if (C.Type == Constraint::Store) {
1690 if (C.Offset == 0) {
1691 // *dest = src edge
1692 unsigned RefNode = C.Dest + FirstRefNode;
1693 if (!GraphNodes[RefNode].PredEdges)
1694 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1695 GraphNodes[RefNode].PredEdges->set(C.Src);
1696 }
1697 } else {
1698 // Dest = Src edge and *Dest = *Src edg
1699 if (!GraphNodes[C.Dest].PredEdges)
1700 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1701 GraphNodes[C.Dest].PredEdges->set(C.Src);
1702 unsigned RefNode = C.Dest + FirstRefNode;
1703 if (!GraphNodes[RefNode].ImplicitPredEdges)
1704 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1705 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1706 }
1707 }
1708 PEClass = 1;
1709 // Do SCC finding first to condense our predecessor graph
1710 DFSNumber = 0;
1711 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1712 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1713 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1714
1715 for (unsigned i = 0; i < FirstRefNode; ++i) {
1716 if (FindNode(i) == i) {
1717 unsigned Node = VSSCCRep[i];
1718 if (!Node2Visited[Node])
1719 Condense(Node);
1720 }
1721 }
1722
1723 // Reset tables for actual labeling
1724 Node2DFS.clear();
1725 Node2Visited.clear();
1726 Node2Deleted.clear();
1727 // Pre-grow our densemap so that we don't get really bad behavior
1728 Set2PEClass.resize(GraphNodes.size());
1729
1730 // Visit the condensed graph and generate pointer equivalence labels.
1731 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1732 for (unsigned i = 0; i < FirstRefNode; ++i) {
1733 if (FindNode(i) == i) {
1734 unsigned Node = VSSCCRep[i];
1735 if (!Node2Visited[Node])
1736 HUValNum(Node);
1737 }
1738 }
1739 // PEClass nodes will be deleted by the deleting of N->PointsTo in our caller.
1740 Set2PEClass.clear();
1741 DOUT << "Finished HU\n";
1742}
1743
1744
1745/// Implementation of standard Tarjan SCC algorithm as modified by Nuutilla.
1746void Andersens::Condense(unsigned NodeIndex) {
1747 unsigned MyDFS = DFSNumber++;
1748 Node *N = &GraphNodes[NodeIndex];
1749 Node2Visited[NodeIndex] = true;
1750 Node2DFS[NodeIndex] = MyDFS;
1751
1752 // First process all our explicit edges
1753 if (N->PredEdges)
1754 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1755 Iter != N->PredEdges->end();
1756 ++Iter) {
1757 unsigned j = VSSCCRep[*Iter];
1758 if (!Node2Deleted[j]) {
1759 if (!Node2Visited[j])
1760 Condense(j);
1761 if (Node2DFS[NodeIndex] > Node2DFS[j])
1762 Node2DFS[NodeIndex] = Node2DFS[j];
1763 }
1764 }
1765
1766 // Now process all the implicit edges
1767 if (N->ImplicitPredEdges)
1768 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1769 Iter != N->ImplicitPredEdges->end();
1770 ++Iter) {
1771 unsigned j = VSSCCRep[*Iter];
1772 if (!Node2Deleted[j]) {
1773 if (!Node2Visited[j])
1774 Condense(j);
1775 if (Node2DFS[NodeIndex] > Node2DFS[j])
1776 Node2DFS[NodeIndex] = Node2DFS[j];
1777 }
1778 }
1779
1780 // See if we found any cycles
1781 if (MyDFS == Node2DFS[NodeIndex]) {
1782 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1783 unsigned CycleNodeIndex = SCCStack.top();
1784 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1785 VSSCCRep[CycleNodeIndex] = NodeIndex;
1786 // Unify the nodes
1787 N->Direct &= CycleNode->Direct;
1788
1789 *(N->PointsTo) |= CycleNode->PointsTo;
1790 delete CycleNode->PointsTo;
1791 CycleNode->PointsTo = NULL;
1792 if (CycleNode->PredEdges) {
1793 if (!N->PredEdges)
1794 N->PredEdges = new SparseBitVector<>;
1795 *(N->PredEdges) |= CycleNode->PredEdges;
1796 delete CycleNode->PredEdges;
1797 CycleNode->PredEdges = NULL;
1798 }
1799 if (CycleNode->ImplicitPredEdges) {
1800 if (!N->ImplicitPredEdges)
1801 N->ImplicitPredEdges = new SparseBitVector<>;
1802 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1803 delete CycleNode->ImplicitPredEdges;
1804 CycleNode->ImplicitPredEdges = NULL;
1805 }
1806 SCCStack.pop();
1807 }
1808
1809 Node2Deleted[NodeIndex] = true;
1810
1811 // Set up number of incoming edges for other nodes
1812 if (N->PredEdges)
1813 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1814 Iter != N->PredEdges->end();
1815 ++Iter)
1816 ++GraphNodes[VSSCCRep[*Iter]].NumInEdges;
1817 } else {
1818 SCCStack.push(NodeIndex);
1819 }
1820}
1821
1822void Andersens::HUValNum(unsigned NodeIndex) {
1823 Node *N = &GraphNodes[NodeIndex];
1824 Node2Visited[NodeIndex] = true;
1825
1826 // Eliminate dereferences of non-pointers for those non-pointers we have
1827 // already identified. These are ref nodes whose non-ref node:
1828 // 1. Has already been visited determined to point to nothing (and thus, a
1829 // dereference of it must point to nothing)
1830 // 2. Any direct node with no predecessor edges in our graph and with no
1831 // points-to set (since it can't point to anything either, being that it
1832 // receives no points-to sets and has none).
1833 if (NodeIndex >= FirstRefNode) {
1834 unsigned j = VSSCCRep[FindNode(NodeIndex - FirstRefNode)];
1835 if ((Node2Visited[j] && !GraphNodes[j].PointerEquivLabel)
1836 || (GraphNodes[j].Direct && !GraphNodes[j].PredEdges
1837 && GraphNodes[j].PointsTo->empty())){
1838 return;
1839 }
1840 }
1841 // Process all our explicit edges
1842 if (N->PredEdges)
1843 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1844 Iter != N->PredEdges->end();
1845 ++Iter) {
1846 unsigned j = VSSCCRep[*Iter];
1847 if (!Node2Visited[j])
1848 HUValNum(j);
1849
1850 // If this edge turned out to be the same as us, or got no pointer
1851 // equivalence label (and thus points to nothing) , just decrement our
1852 // incoming edges and continue.
1853 if (j == NodeIndex || GraphNodes[j].PointerEquivLabel == 0) {
1854 --GraphNodes[j].NumInEdges;
1855 continue;
1856 }
1857
1858 *(N->PointsTo) |= GraphNodes[j].PointsTo;
1859
1860 // If we didn't end up storing this in the hash, and we're done with all
1861 // the edges, we don't need the points-to set anymore.
1862 --GraphNodes[j].NumInEdges;
1863 if (!GraphNodes[j].NumInEdges && !GraphNodes[j].StoredInHash) {
1864 delete GraphNodes[j].PointsTo;
1865 GraphNodes[j].PointsTo = NULL;
1866 }
1867 }
1868 // If this isn't a direct node, generate a fresh variable.
1869 if (!N->Direct) {
1870 N->PointsTo->set(FirstRefNode + NodeIndex);
1871 }
1872
1873 // See If we have something equivalent to us, if not, generate a new
1874 // equivalence class.
1875 if (N->PointsTo->empty()) {
1876 delete N->PointsTo;
1877 N->PointsTo = NULL;
1878 } else {
1879 if (N->Direct) {
1880 N->PointerEquivLabel = Set2PEClass[N->PointsTo];
1881 if (N->PointerEquivLabel == 0) {
1882 unsigned EquivClass = PEClass++;
1883 N->StoredInHash = true;
1884 Set2PEClass[N->PointsTo] = EquivClass;
1885 N->PointerEquivLabel = EquivClass;
1886 }
1887 } else {
1888 N->PointerEquivLabel = PEClass++;
1889 }
1890 }
1891}
1892
1893/// Rewrite our list of constraints so that pointer equivalent nodes are
1894/// replaced by their the pointer equivalence class representative.
1895void Andersens::RewriteConstraints() {
1896 std::vector<Constraint> NewConstraints;
Chris Lattnerbe207732007-09-30 00:47:20 +00001897 DenseSet<Constraint, ConstraintKeyInfo> Seen;
Daniel Berlind81ccc22007-09-24 19:45:49 +00001898
1899 PEClass2Node.clear();
1900 PENLEClass2Node.clear();
1901
1902 // We may have from 1 to Graphnodes + 1 equivalence classes.
1903 PEClass2Node.insert(PEClass2Node.begin(), GraphNodes.size() + 1, -1);
1904 PENLEClass2Node.insert(PENLEClass2Node.begin(), GraphNodes.size() + 1, -1);
1905
1906 // Rewrite constraints, ignoring non-pointer constraints, uniting equivalent
1907 // nodes, and rewriting constraints to use the representative nodes.
1908 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1909 Constraint &C = Constraints[i];
1910 unsigned RHSNode = FindNode(C.Src);
1911 unsigned LHSNode = FindNode(C.Dest);
1912 unsigned RHSLabel = GraphNodes[VSSCCRep[RHSNode]].PointerEquivLabel;
1913 unsigned LHSLabel = GraphNodes[VSSCCRep[LHSNode]].PointerEquivLabel;
1914
1915 // First we try to eliminate constraints for things we can prove don't point
1916 // to anything.
1917 if (LHSLabel == 0) {
1918 DEBUG(PrintNode(&GraphNodes[LHSNode]));
1919 DOUT << " is a non-pointer, ignoring constraint.\n";
1920 continue;
1921 }
1922 if (RHSLabel == 0) {
1923 DEBUG(PrintNode(&GraphNodes[RHSNode]));
1924 DOUT << " is a non-pointer, ignoring constraint.\n";
1925 continue;
1926 }
1927 // This constraint may be useless, and it may become useless as we translate
1928 // it.
1929 if (C.Src == C.Dest && C.Type == Constraint::Copy)
1930 continue;
Daniel Berlinc7a12ae2007-09-27 15:42:23 +00001931
Daniel Berlind81ccc22007-09-24 19:45:49 +00001932 C.Src = FindEquivalentNode(RHSNode, RHSLabel);
1933 C.Dest = FindEquivalentNode(FindNode(LHSNode), LHSLabel);
Daniel Berlinc7a12ae2007-09-27 15:42:23 +00001934 if (C.Src == C.Dest && C.Type == Constraint::Copy
Chris Lattnerbe207732007-09-30 00:47:20 +00001935 || Seen.count(C))
Daniel Berlind81ccc22007-09-24 19:45:49 +00001936 continue;
1937
Chris Lattnerbe207732007-09-30 00:47:20 +00001938 Seen.insert(C);
Daniel Berlind81ccc22007-09-24 19:45:49 +00001939 NewConstraints.push_back(C);
1940 }
1941 Constraints.swap(NewConstraints);
1942 PEClass2Node.clear();
1943}
1944
1945/// See if we have a node that is pointer equivalent to the one being asked
1946/// about, and if so, unite them and return the equivalent node. Otherwise,
1947/// return the original node.
1948unsigned Andersens::FindEquivalentNode(unsigned NodeIndex,
1949 unsigned NodeLabel) {
1950 if (!GraphNodes[NodeIndex].AddressTaken) {
1951 if (PEClass2Node[NodeLabel] != -1) {
1952 // We found an existing node with the same pointer label, so unify them.
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001953 // We specifically request that Union-By-Rank not be used so that
1954 // PEClass2Node[NodeLabel] U= NodeIndex and not the other way around.
1955 return UniteNodes(PEClass2Node[NodeLabel], NodeIndex, false);
Daniel Berlind81ccc22007-09-24 19:45:49 +00001956 } else {
1957 PEClass2Node[NodeLabel] = NodeIndex;
1958 PENLEClass2Node[NodeLabel] = NodeIndex;
1959 }
1960 } else if (PENLEClass2Node[NodeLabel] == -1) {
1961 PENLEClass2Node[NodeLabel] = NodeIndex;
1962 }
1963
1964 return NodeIndex;
1965}
1966
1967void Andersens::PrintLabels() {
1968 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1969 if (i < FirstRefNode) {
1970 PrintNode(&GraphNodes[i]);
1971 } else if (i < FirstAdrNode) {
1972 DOUT << "REF(";
1973 PrintNode(&GraphNodes[i-FirstRefNode]);
1974 DOUT <<")";
1975 } else {
1976 DOUT << "ADR(";
1977 PrintNode(&GraphNodes[i-FirstAdrNode]);
1978 DOUT <<")";
1979 }
1980
1981 DOUT << " has pointer label " << GraphNodes[i].PointerEquivLabel
1982 << " and SCC rep " << VSSCCRep[i]
1983 << " and is " << (GraphNodes[i].Direct ? "Direct" : "Not direct")
1984 << "\n";
1985 }
1986}
1987
1988/// Optimize the constraints by performing offline variable substitution and
1989/// other optimizations.
1990void Andersens::OptimizeConstraints() {
1991 DOUT << "Beginning constraint optimization\n";
1992
1993 // Function related nodes need to stay in the same relative position and can't
1994 // be location equivalent.
1995 for (std::map<unsigned, unsigned>::iterator Iter = MaxK.begin();
1996 Iter != MaxK.end();
1997 ++Iter) {
1998 for (unsigned i = Iter->first;
1999 i != Iter->first + Iter->second;
2000 ++i) {
2001 GraphNodes[i].AddressTaken = true;
2002 GraphNodes[i].Direct = false;
2003 }
2004 }
2005
2006 ClumpAddressTaken();
2007 FirstRefNode = GraphNodes.size();
2008 FirstAdrNode = FirstRefNode + GraphNodes.size();
2009 GraphNodes.insert(GraphNodes.end(), 2 * GraphNodes.size(),
2010 Node(false));
2011 VSSCCRep.resize(GraphNodes.size());
2012 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2013 VSSCCRep[i] = i;
2014 }
2015 HVN();
2016 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2017 Node *N = &GraphNodes[i];
2018 delete N->PredEdges;
2019 N->PredEdges = NULL;
2020 delete N->ImplicitPredEdges;
2021 N->ImplicitPredEdges = NULL;
2022 }
2023#undef DEBUG_TYPE
2024#define DEBUG_TYPE "anders-aa-labels"
2025 DEBUG(PrintLabels());
2026#undef DEBUG_TYPE
2027#define DEBUG_TYPE "anders-aa"
2028 RewriteConstraints();
2029 // Delete the adr nodes.
2030 GraphNodes.resize(FirstRefNode * 2);
2031
2032 // Now perform HU
2033 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2034 Node *N = &GraphNodes[i];
2035 if (FindNode(i) == i) {
2036 N->PointsTo = new SparseBitVector<>;
2037 N->PointedToBy = new SparseBitVector<>;
2038 // Reset our labels
2039 }
2040 VSSCCRep[i] = i;
2041 N->PointerEquivLabel = 0;
2042 }
2043 HU();
2044#undef DEBUG_TYPE
2045#define DEBUG_TYPE "anders-aa-labels"
2046 DEBUG(PrintLabels());
2047#undef DEBUG_TYPE
2048#define DEBUG_TYPE "anders-aa"
2049 RewriteConstraints();
2050 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2051 if (FindNode(i) == i) {
2052 Node *N = &GraphNodes[i];
2053 delete N->PointsTo;
2054 delete N->PredEdges;
2055 delete N->ImplicitPredEdges;
2056 delete N->PointedToBy;
2057 }
2058 }
2059 GraphNodes.erase(GraphNodes.begin() + FirstRefNode, GraphNodes.end());
2060 DOUT << "Finished constraint optimization\n";
2061 FirstRefNode = 0;
2062 FirstAdrNode = 0;
2063}
2064
2065/// Unite pointer but not location equivalent variables, now that the constraint
2066/// graph is built.
2067void Andersens::UnitePointerEquivalences() {
2068 DOUT << "Uniting remaining pointer equivalences\n";
2069 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002070 if (GraphNodes[i].AddressTaken && GraphNodes[i].isRep()) {
Daniel Berlind81ccc22007-09-24 19:45:49 +00002071 unsigned Label = GraphNodes[i].PointerEquivLabel;
2072
2073 if (Label && PENLEClass2Node[Label] != -1)
2074 UniteNodes(i, PENLEClass2Node[Label]);
2075 }
2076 }
2077 DOUT << "Finished remaining pointer equivalences\n";
2078 PENLEClass2Node.clear();
2079}
2080
2081/// Create the constraint graph used for solving points-to analysis.
2082///
Daniel Berlinaad15882007-09-16 21:45:02 +00002083void Andersens::CreateConstraintGraph() {
2084 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2085 Constraint &C = Constraints[i];
2086 assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
2087 if (C.Type == Constraint::AddressOf)
2088 GraphNodes[C.Dest].PointsTo->set(C.Src);
2089 else if (C.Type == Constraint::Load)
2090 GraphNodes[C.Src].Constraints.push_back(C);
2091 else if (C.Type == Constraint::Store)
2092 GraphNodes[C.Dest].Constraints.push_back(C);
2093 else if (C.Offset != 0)
2094 GraphNodes[C.Src].Constraints.push_back(C);
2095 else
2096 GraphNodes[C.Src].Edges->set(C.Dest);
2097 }
2098}
2099
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002100// Perform DFS and cycle detection.
2101bool Andersens::QueryNode(unsigned Node) {
2102 assert(GraphNodes[Node].isRep() && "Querying a non-rep node");
Daniel Berlinaad15882007-09-16 21:45:02 +00002103 unsigned OurDFS = ++DFSNumber;
2104 SparseBitVector<> ToErase;
2105 SparseBitVector<> NewEdges;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002106 Tarjan2DFS[Node] = OurDFS;
2107
2108 // Changed denotes a change from a recursive call that we will bubble up.
2109 // Merged is set if we actually merge a node ourselves.
2110 bool Changed = false, Merged = false;
Daniel Berlinaad15882007-09-16 21:45:02 +00002111
2112 for (SparseBitVector<>::iterator bi = GraphNodes[Node].Edges->begin();
2113 bi != GraphNodes[Node].Edges->end();
2114 ++bi) {
2115 unsigned RepNode = FindNode(*bi);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002116 // If this edge points to a non-representative node but we are
2117 // already planning to add an edge to its representative, we have no
2118 // need for this edge anymore.
Daniel Berlinaad15882007-09-16 21:45:02 +00002119 if (RepNode != *bi && NewEdges.test(RepNode)){
2120 ToErase.set(*bi);
2121 continue;
2122 }
2123
2124 // Continue about our DFS.
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002125 if (!Tarjan2Deleted[RepNode]){
2126 if (Tarjan2DFS[RepNode] == 0) {
2127 Changed |= QueryNode(RepNode);
2128 // May have been changed by QueryNode
Daniel Berlinaad15882007-09-16 21:45:02 +00002129 RepNode = FindNode(RepNode);
2130 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002131 if (Tarjan2DFS[RepNode] < Tarjan2DFS[Node])
2132 Tarjan2DFS[Node] = Tarjan2DFS[RepNode];
Daniel Berlinaad15882007-09-16 21:45:02 +00002133 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002134
2135 // We may have just discovered that this node is part of a cycle, in
2136 // which case we can also erase it.
Daniel Berlinaad15882007-09-16 21:45:02 +00002137 if (RepNode != *bi) {
2138 ToErase.set(*bi);
2139 NewEdges.set(RepNode);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002140 }
2141 }
2142
Daniel Berlinaad15882007-09-16 21:45:02 +00002143 GraphNodes[Node].Edges->intersectWithComplement(ToErase);
2144 GraphNodes[Node].Edges |= NewEdges;
2145
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002146 // If this node is a root of a non-trivial SCC, place it on our
2147 // worklist to be processed.
2148 if (OurDFS == Tarjan2DFS[Node]) {
2149 while (!SCCStack.empty() && Tarjan2DFS[SCCStack.top()] >= OurDFS) {
2150 Node = UniteNodes(Node, SCCStack.top());
Daniel Berlinaad15882007-09-16 21:45:02 +00002151
2152 SCCStack.pop();
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002153 Merged = true;
Daniel Berlinaad15882007-09-16 21:45:02 +00002154 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002155 Tarjan2Deleted[Node] = true;
Daniel Berlinaad15882007-09-16 21:45:02 +00002156
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002157 if (Merged)
2158 NextWL->insert(&GraphNodes[Node]);
Daniel Berlinaad15882007-09-16 21:45:02 +00002159 } else {
2160 SCCStack.push(Node);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002161 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002162
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002163 return(Changed | Merged);
2164}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002165
2166/// SolveConstraints - This stage iteratively processes the constraints list
2167/// propagating constraints (adding edges to the Nodes in the points-to graph)
2168/// until a fixed point is reached.
2169///
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002170/// We use a variant of the technique called "Lazy Cycle Detection", which is
2171/// described in "The Ant and the Grasshopper: Fast and Accurate Pointer
2172/// Analysis for Millions of Lines of Code. In Programming Language Design and
2173/// Implementation (PLDI), June 2007."
2174/// The paper describes performing cycle detection one node at a time, which can
2175/// be expensive if there are no cycles, but there are long chains of nodes that
2176/// it heuristically believes are cycles (because it will DFS from each node
2177/// without state from previous nodes).
2178/// Instead, we use the heuristic to build a worklist of nodes to check, then
2179/// cycle detect them all at the same time to do this more cheaply. This
2180/// catches cycles slightly later than the original technique did, but does it
2181/// make significantly cheaper.
2182
Chris Lattnere995a2a2004-05-23 21:00:47 +00002183void Andersens::SolveConstraints() {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002184 CurrWL = &w1;
2185 NextWL = &w2;
Daniel Berlinaad15882007-09-16 21:45:02 +00002186
Daniel Berlind81ccc22007-09-24 19:45:49 +00002187 OptimizeConstraints();
2188#undef DEBUG_TYPE
2189#define DEBUG_TYPE "anders-aa-constraints"
2190 DEBUG(PrintConstraints());
2191#undef DEBUG_TYPE
2192#define DEBUG_TYPE "anders-aa"
2193
Daniel Berlinaad15882007-09-16 21:45:02 +00002194 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2195 Node *N = &GraphNodes[i];
2196 N->PointsTo = new SparseBitVector<>;
2197 N->OldPointsTo = new SparseBitVector<>;
2198 N->Edges = new SparseBitVector<>;
2199 }
2200 CreateConstraintGraph();
Daniel Berlind81ccc22007-09-24 19:45:49 +00002201 UnitePointerEquivalences();
2202 assert(SCCStack.empty() && "SCC Stack should be empty by now!");
Daniel Berlind81ccc22007-09-24 19:45:49 +00002203 Node2DFS.clear();
2204 Node2Deleted.clear();
Daniel Berlinaad15882007-09-16 21:45:02 +00002205 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2206 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2207 DFSNumber = 0;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002208 DenseSet<Constraint, ConstraintKeyInfo> Seen;
2209 DenseSet<std::pair<unsigned,unsigned>, PairKeyInfo> EdgesChecked;
2210
2211 // Order graph and add initial nodes to work list.
Daniel Berlinaad15882007-09-16 21:45:02 +00002212 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
Daniel Berlinaad15882007-09-16 21:45:02 +00002213 Node *INode = &GraphNodes[i];
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002214
2215 // Add to work list if it's a representative and can contribute to the
2216 // calculation right now.
2217 if (INode->isRep() && !INode->PointsTo->empty()
2218 && (!INode->Edges->empty() || !INode->Constraints.empty())) {
2219 INode->Stamp();
2220 CurrWL->insert(INode);
Daniel Berlinaad15882007-09-16 21:45:02 +00002221 }
2222 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002223 std::queue<unsigned int> TarjanWL;
2224 while( !CurrWL->empty() ) {
2225 DOUT << "Starting iteration #" << ++NumIters << "\n";
Daniel Berlinaad15882007-09-16 21:45:02 +00002226
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002227 Node* CurrNode;
2228 unsigned CurrNodeIndex;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002229
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002230 // Actual cycle checking code. We cycle check all of the lazy cycle
2231 // candidates from the last iteration in one go.
2232 if (!TarjanWL.empty()) {
2233 DFSNumber = 0;
2234
2235 Tarjan2DFS.clear();
2236 Tarjan2Deleted.clear();
2237 while (!TarjanWL.empty()) {
2238 unsigned int ToTarjan = TarjanWL.front();
2239 TarjanWL.pop();
2240 if (!Tarjan2Deleted[ToTarjan]
2241 && GraphNodes[ToTarjan].isRep()
2242 && Tarjan2DFS[ToTarjan] == 0)
2243 QueryNode(ToTarjan);
2244 }
2245 }
2246
2247 // Add to work list if it's a representative and can contribute to the
2248 // calculation right now.
2249 while( (CurrNode = CurrWL->pop()) != NULL ) {
2250 CurrNodeIndex = CurrNode - &GraphNodes[0];
2251 CurrNode->Stamp();
2252
2253
Daniel Berlinaad15882007-09-16 21:45:02 +00002254 // Figure out the changed points to bits
2255 SparseBitVector<> CurrPointsTo;
2256 CurrPointsTo.intersectWithComplement(CurrNode->PointsTo,
2257 CurrNode->OldPointsTo);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002258 if (CurrPointsTo.empty())
Daniel Berlinaad15882007-09-16 21:45:02 +00002259 continue;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002260
Daniel Berlinaad15882007-09-16 21:45:02 +00002261 *(CurrNode->OldPointsTo) |= CurrPointsTo;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002262 Seen.clear();
Chris Lattnere995a2a2004-05-23 21:00:47 +00002263
Daniel Berlinaad15882007-09-16 21:45:02 +00002264 /* Now process the constraints for this node. */
2265 for (std::list<Constraint>::iterator li = CurrNode->Constraints.begin();
2266 li != CurrNode->Constraints.end(); ) {
2267 li->Src = FindNode(li->Src);
2268 li->Dest = FindNode(li->Dest);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002269
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002270 // Delete redundant constraints
2271 if( Seen.count(*li) ) {
2272 std::list<Constraint>::iterator lk = li; li++;
2273
2274 CurrNode->Constraints.erase(lk);
2275 ++NumErased;
2276 continue;
2277 }
2278 Seen.insert(*li);
2279
Daniel Berlinaad15882007-09-16 21:45:02 +00002280 // Src and Dest will be the vars we are going to process.
2281 // This may look a bit ugly, but what it does is allow us to process
Daniel Berlind81ccc22007-09-24 19:45:49 +00002282 // both store and load constraints with the same code.
Daniel Berlinaad15882007-09-16 21:45:02 +00002283 // Load constraints say that every member of our RHS solution has K
2284 // added to it, and that variable gets an edge to LHS. We also union
2285 // RHS+K's solution into the LHS solution.
2286 // Store constraints say that every member of our LHS solution has K
2287 // added to it, and that variable gets an edge from RHS. We also union
2288 // RHS's solution into the LHS+K solution.
2289 unsigned *Src;
2290 unsigned *Dest;
2291 unsigned K = li->Offset;
2292 unsigned CurrMember;
2293 if (li->Type == Constraint::Load) {
2294 Src = &CurrMember;
2295 Dest = &li->Dest;
2296 } else if (li->Type == Constraint::Store) {
2297 Src = &li->Src;
2298 Dest = &CurrMember;
2299 } else {
2300 // TODO Handle offseted copy constraint
2301 li++;
2302 continue;
2303 }
2304 // TODO: hybrid cycle detection would go here, we should check
2305 // if it was a statically detected offline equivalence that
2306 // involves pointers , and if so, remove the redundant constraints.
Chris Lattnere995a2a2004-05-23 21:00:47 +00002307
Daniel Berlinaad15882007-09-16 21:45:02 +00002308 const SparseBitVector<> &Solution = CurrPointsTo;
2309
2310 for (SparseBitVector<>::iterator bi = Solution.begin();
2311 bi != Solution.end();
2312 ++bi) {
2313 CurrMember = *bi;
2314
2315 // Need to increment the member by K since that is where we are
Daniel Berlind81ccc22007-09-24 19:45:49 +00002316 // supposed to copy to/from. Note that in positive weight cycles,
2317 // which occur in address taking of fields, K can go past
2318 // MaxK[CurrMember] elements, even though that is all it could point
2319 // to.
Daniel Berlinaad15882007-09-16 21:45:02 +00002320 if (K > 0 && K > MaxK[CurrMember])
2321 continue;
2322 else
2323 CurrMember = FindNode(CurrMember + K);
2324
2325 // Add an edge to the graph, so we can just do regular bitmap ior next
2326 // time. It may also let us notice a cycle.
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002327#if !FULL_UNIVERSAL
2328 if (*Dest < NumberSpecialNodes)
2329 continue;
2330#endif
2331 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2332 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2333 NextWL->insert(&GraphNodes[*Dest]);
2334
Daniel Berlinaad15882007-09-16 21:45:02 +00002335 }
2336 li++;
2337 }
2338 SparseBitVector<> NewEdges;
2339 SparseBitVector<> ToErase;
2340
2341 // Now all we have left to do is propagate points-to info along the
2342 // edges, erasing the redundant edges.
Daniel Berlinaad15882007-09-16 21:45:02 +00002343 for (SparseBitVector<>::iterator bi = CurrNode->Edges->begin();
2344 bi != CurrNode->Edges->end();
2345 ++bi) {
2346
2347 unsigned DestVar = *bi;
2348 unsigned Rep = FindNode(DestVar);
2349
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002350 // If we ended up with this node as our destination, or we've already
2351 // got an edge for the representative, delete the current edge.
2352 if (Rep == CurrNodeIndex ||
2353 (Rep != DestVar && NewEdges.test(Rep))) {
2354 ToErase.set(DestVar);
2355 continue;
2356 }
2357
2358 std::pair<unsigned,unsigned> edge(CurrNodeIndex,Rep);
2359
2360 // This is where we do lazy cycle detection.
2361 // If this is a cycle candidate (equal points-to sets and this
2362 // particular edge has not been cycle-checked previously), add to the
2363 // list to check for cycles on the next iteration.
2364 if (!EdgesChecked.count(edge) &&
2365 *(GraphNodes[Rep].PointsTo) == *(CurrNode->PointsTo)) {
2366 EdgesChecked.insert(edge);
2367 TarjanWL.push(Rep);
Daniel Berlinaad15882007-09-16 21:45:02 +00002368 }
2369 // Union the points-to sets into the dest
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002370#if !FULL_UNIVERSAL
2371 if (Rep >= NumberSpecialNodes)
2372#endif
Daniel Berlinaad15882007-09-16 21:45:02 +00002373 if (GraphNodes[Rep].PointsTo |= CurrPointsTo) {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002374 NextWL->insert(&GraphNodes[Rep]);
Daniel Berlinaad15882007-09-16 21:45:02 +00002375 }
2376 // If this edge's destination was collapsed, rewrite the edge.
2377 if (Rep != DestVar) {
2378 ToErase.set(DestVar);
2379 NewEdges.set(Rep);
2380 }
2381 }
2382 CurrNode->Edges->intersectWithComplement(ToErase);
2383 CurrNode->Edges |= NewEdges;
2384 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002385
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002386 // Switch to other work list.
2387 WorkList* t = CurrWL; CurrWL = NextWL; NextWL = t;
2388 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002389
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002390
Daniel Berlinaad15882007-09-16 21:45:02 +00002391 Node2DFS.clear();
2392 Node2Deleted.clear();
2393 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2394 Node *N = &GraphNodes[i];
2395 delete N->OldPointsTo;
2396 delete N->Edges;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002397 }
2398}
2399
Daniel Berlinaad15882007-09-16 21:45:02 +00002400//===----------------------------------------------------------------------===//
2401// Union-Find
2402//===----------------------------------------------------------------------===//
Chris Lattnere995a2a2004-05-23 21:00:47 +00002403
Daniel Berlinaad15882007-09-16 21:45:02 +00002404// Unite nodes First and Second, returning the one which is now the
2405// representative node. First and Second are indexes into GraphNodes
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002406unsigned Andersens::UniteNodes(unsigned First, unsigned Second,
2407 bool UnionByRank) {
Daniel Berlinaad15882007-09-16 21:45:02 +00002408 assert (First < GraphNodes.size() && Second < GraphNodes.size() &&
2409 "Attempting to merge nodes that don't exist");
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002410
Daniel Berlinaad15882007-09-16 21:45:02 +00002411 Node *FirstNode = &GraphNodes[First];
2412 Node *SecondNode = &GraphNodes[Second];
2413
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002414 assert (SecondNode->isRep() && FirstNode->isRep() &&
Daniel Berlinaad15882007-09-16 21:45:02 +00002415 "Trying to unite two non-representative nodes!");
2416 if (First == Second)
2417 return First;
2418
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002419 if (UnionByRank) {
2420 int RankFirst = (int) FirstNode ->NodeRep;
2421 int RankSecond = (int) SecondNode->NodeRep;
2422
2423 // Rank starts at -1 and gets decremented as it increases.
2424 // Translation: higher rank, lower NodeRep value, which is always negative.
2425 if (RankFirst > RankSecond) {
2426 unsigned t = First; First = Second; Second = t;
2427 Node* tp = FirstNode; FirstNode = SecondNode; SecondNode = tp;
2428 } else if (RankFirst == RankSecond) {
2429 FirstNode->NodeRep = (unsigned) (RankFirst - 1);
2430 }
2431 }
2432
Daniel Berlinaad15882007-09-16 21:45:02 +00002433 SecondNode->NodeRep = First;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002434#if !FULL_UNIVERSAL
2435 if (First >= NumberSpecialNodes)
2436#endif
Daniel Berlind81ccc22007-09-24 19:45:49 +00002437 if (FirstNode->PointsTo && SecondNode->PointsTo)
2438 FirstNode->PointsTo |= *(SecondNode->PointsTo);
2439 if (FirstNode->Edges && SecondNode->Edges)
2440 FirstNode->Edges |= *(SecondNode->Edges);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002441 if (!SecondNode->Constraints.empty())
Daniel Berlind81ccc22007-09-24 19:45:49 +00002442 FirstNode->Constraints.splice(FirstNode->Constraints.begin(),
2443 SecondNode->Constraints);
2444 if (FirstNode->OldPointsTo) {
2445 delete FirstNode->OldPointsTo;
2446 FirstNode->OldPointsTo = new SparseBitVector<>;
2447 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002448
2449 // Destroy interesting parts of the merged-from node.
2450 delete SecondNode->OldPointsTo;
2451 delete SecondNode->Edges;
2452 delete SecondNode->PointsTo;
2453 SecondNode->Edges = NULL;
2454 SecondNode->PointsTo = NULL;
2455 SecondNode->OldPointsTo = NULL;
2456
2457 NumUnified++;
2458 DOUT << "Unified Node ";
2459 DEBUG(PrintNode(FirstNode));
2460 DOUT << " and Node ";
2461 DEBUG(PrintNode(SecondNode));
2462 DOUT << "\n";
2463
2464 // TODO: Handle SDT
2465 return First;
2466}
2467
2468// Find the index into GraphNodes of the node representing Node, performing
2469// path compression along the way
2470unsigned Andersens::FindNode(unsigned NodeIndex) {
2471 assert (NodeIndex < GraphNodes.size()
2472 && "Attempting to find a node that can't exist");
2473 Node *N = &GraphNodes[NodeIndex];
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002474 if (N->isRep())
Daniel Berlinaad15882007-09-16 21:45:02 +00002475 return NodeIndex;
2476 else
2477 return (N->NodeRep = FindNode(N->NodeRep));
2478}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002479
2480//===----------------------------------------------------------------------===//
2481// Debugging Output
2482//===----------------------------------------------------------------------===//
2483
2484void Andersens::PrintNode(Node *N) {
2485 if (N == &GraphNodes[UniversalSet]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002486 cerr << "<universal>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002487 return;
2488 } else if (N == &GraphNodes[NullPtr]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002489 cerr << "<nullptr>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002490 return;
2491 } else if (N == &GraphNodes[NullObject]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002492 cerr << "<null>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002493 return;
2494 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002495 if (!N->getValue()) {
2496 cerr << "artificial" << (intptr_t) N;
2497 return;
2498 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002499
2500 assert(N->getValue() != 0 && "Never set node label!");
2501 Value *V = N->getValue();
2502 if (Function *F = dyn_cast<Function>(V)) {
2503 if (isa<PointerType>(F->getFunctionType()->getReturnType()) &&
Daniel Berlinaad15882007-09-16 21:45:02 +00002504 N == &GraphNodes[getReturnNode(F)]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002505 cerr << F->getName() << ":retval";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002506 return;
Daniel Berlinaad15882007-09-16 21:45:02 +00002507 } else if (F->getFunctionType()->isVarArg() &&
2508 N == &GraphNodes[getVarargNode(F)]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002509 cerr << F->getName() << ":vararg";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002510 return;
2511 }
2512 }
2513
2514 if (Instruction *I = dyn_cast<Instruction>(V))
Bill Wendlinge8156192006-12-07 01:30:32 +00002515 cerr << I->getParent()->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002516 else if (Argument *Arg = dyn_cast<Argument>(V))
Bill Wendlinge8156192006-12-07 01:30:32 +00002517 cerr << Arg->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002518
2519 if (V->hasName())
Bill Wendlinge8156192006-12-07 01:30:32 +00002520 cerr << V->getName();
Chris Lattnere995a2a2004-05-23 21:00:47 +00002521 else
Bill Wendlinge8156192006-12-07 01:30:32 +00002522 cerr << "(unnamed)";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002523
2524 if (isa<GlobalValue>(V) || isa<AllocationInst>(V))
Daniel Berlinaad15882007-09-16 21:45:02 +00002525 if (N == &GraphNodes[getObject(V)])
Bill Wendlinge8156192006-12-07 01:30:32 +00002526 cerr << "<mem>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002527}
Daniel Berlind81ccc22007-09-24 19:45:49 +00002528void Andersens::PrintConstraint(const Constraint &C) {
2529 if (C.Type == Constraint::Store) {
2530 cerr << "*";
2531 if (C.Offset != 0)
2532 cerr << "(";
2533 }
2534 PrintNode(&GraphNodes[C.Dest]);
2535 if (C.Type == Constraint::Store && C.Offset != 0)
2536 cerr << " + " << C.Offset << ")";
2537 cerr << " = ";
2538 if (C.Type == Constraint::Load) {
2539 cerr << "*";
2540 if (C.Offset != 0)
2541 cerr << "(";
2542 }
2543 else if (C.Type == Constraint::AddressOf)
2544 cerr << "&";
2545 PrintNode(&GraphNodes[C.Src]);
2546 if (C.Offset != 0 && C.Type != Constraint::Store)
2547 cerr << " + " << C.Offset;
2548 if (C.Type == Constraint::Load && C.Offset != 0)
2549 cerr << ")";
2550 cerr << "\n";
2551}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002552
2553void Andersens::PrintConstraints() {
Bill Wendlinge8156192006-12-07 01:30:32 +00002554 cerr << "Constraints:\n";
Daniel Berlinaad15882007-09-16 21:45:02 +00002555
Daniel Berlind81ccc22007-09-24 19:45:49 +00002556 for (unsigned i = 0, e = Constraints.size(); i != e; ++i)
2557 PrintConstraint(Constraints[i]);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002558}
2559
2560void Andersens::PrintPointsToGraph() {
Bill Wendlinge8156192006-12-07 01:30:32 +00002561 cerr << "Points-to graph:\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002562 for (unsigned i = 0, e = GraphNodes.size(); i != e; ++i) {
2563 Node *N = &GraphNodes[i];
Daniel Berlinaad15882007-09-16 21:45:02 +00002564 if (FindNode (i) != i) {
2565 PrintNode(N);
2566 cerr << "\t--> same as ";
2567 PrintNode(&GraphNodes[FindNode(i)]);
2568 cerr << "\n";
2569 } else {
2570 cerr << "[" << (N->PointsTo->count()) << "] ";
2571 PrintNode(N);
2572 cerr << "\t--> ";
2573
2574 bool first = true;
2575 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
2576 bi != N->PointsTo->end();
2577 ++bi) {
2578 if (!first)
2579 cerr << ", ";
2580 PrintNode(&GraphNodes[*bi]);
2581 first = false;
2582 }
2583 cerr << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002584 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002585 }
2586}