blob: 9af904f4926941f673f3d32cf37a3596714d815e [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- Andersens.cpp - Andersen's Interprocedural Alias Analysis ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
Daniel Berlin385bda62007-09-16 21:45:02 +000010// This file defines an implementation of Andersen's interprocedural alias
11// analysis
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012//
13// In pointer analysis terms, this is a subset-based, flow-insensitive,
Daniel Berlin385bda62007-09-16 21:45:02 +000014// field-sensitive, and context-insensitive algorithm pointer algorithm.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000015//
16// This algorithm is implemented as three stages:
17// 1. Object identification.
18// 2. Inclusion constraint identification.
Daniel Berlinb53270f2007-09-24 19:45:49 +000019// 3. Offline constraint graph optimization
20// 4. Inclusion constraint solving.
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Berlin385bda62007-09-16 21:45:02 +000030// B can point to. Constraints can handle copies, loads, and stores, and
31// address taking.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000032//
Daniel Berlin122992d2007-09-24 22:20:45 +000033// The offline constraint graph optimization portion includes offline variable
Daniel Berlined95dd02008-03-05 19:31:47 +000034// substitution algorithms intended to compute pointer and location
Daniel Berlin122992d2007-09-24 22:20:45 +000035// equivalences. Pointer equivalences are those pointers that will have the
36// same points-to sets, and location equivalences are those variables that
Daniel Berlined95dd02008-03-05 19:31:47 +000037// always appear together in points-to sets. It also includes an offline
38// cycle detection algorithm that allows cycles to be collapsed sooner
39// during solving.
Daniel Berlinb53270f2007-09-24 19:45:49 +000040//
Dan Gohmanf17a25c2007-07-18 16:29:46 +000041// The inclusion constraint solving phase iteratively propagates the inclusion
42// constraints until a fixed point is reached. This is an O(N^3) algorithm.
43//
Daniel Berlin385bda62007-09-16 21:45:02 +000044// Function constraints are handled as if they were structs with X fields.
45// Thus, an access to argument X of function Y is an access to node index
46// getNode(Y) + X. This representation allows handling of indirect calls
Daniel Berlinb53270f2007-09-24 19:45:49 +000047// without any issues. To wit, an indirect call Y(a,b) is equivalent to
Daniel Berlin385bda62007-09-16 21:45:02 +000048// *(Y + 1) = a, *(Y + 2) = b.
49// The return node for a function is always located at getNode(F) +
50// CallReturnPos. The arguments start at getNode(F) + CallArgPos.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000051//
52// Future Improvements:
Daniel Berlined95dd02008-03-05 19:31:47 +000053// Use of BDD's.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000054//===----------------------------------------------------------------------===//
55
56#define DEBUG_TYPE "anders-aa"
57#include "llvm/Constants.h"
58#include "llvm/DerivedTypes.h"
59#include "llvm/Instructions.h"
60#include "llvm/Module.h"
61#include "llvm/Pass.h"
62#include "llvm/Support/Compiler.h"
63#include "llvm/Support/InstIterator.h"
64#include "llvm/Support/InstVisitor.h"
65#include "llvm/Analysis/AliasAnalysis.h"
66#include "llvm/Analysis/Passes.h"
67#include "llvm/Support/Debug.h"
68#include "llvm/ADT/Statistic.h"
Daniel Berlin385bda62007-09-16 21:45:02 +000069#include "llvm/ADT/SparseBitVector.h"
Chris Lattner4cf3c502007-09-30 00:47:20 +000070#include "llvm/ADT/DenseSet.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000071#include <algorithm>
72#include <set>
Daniel Berlin385bda62007-09-16 21:45:02 +000073#include <list>
Dan Gohman249ddbf2008-03-21 23:51:57 +000074#include <map>
Daniel Berlin385bda62007-09-16 21:45:02 +000075#include <stack>
76#include <vector>
Daniel Berlinc6fd7722007-12-12 00:37:04 +000077#include <queue>
78
79// Determining the actual set of nodes the universal set can consist of is very
80// expensive because it means propagating around very large sets. We rely on
81// other analysis being able to determine which nodes can never be pointed to in
82// order to disambiguate further than "points-to anything".
83#define FULL_UNIVERSAL 0
Dan Gohmanf17a25c2007-07-18 16:29:46 +000084
Daniel Berlin385bda62007-09-16 21:45:02 +000085using namespace llvm;
Daniel Berlinb53270f2007-09-24 19:45:49 +000086STATISTIC(NumIters , "Number of iterations to reach convergence");
87STATISTIC(NumConstraints, "Number of constraints");
88STATISTIC(NumNodes , "Number of nodes");
89STATISTIC(NumUnified , "Number of variables unified");
Daniel Berlinc6fd7722007-12-12 00:37:04 +000090STATISTIC(NumErased , "Number of redundant constraints erased");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000091
92namespace {
Daniel Berlin385bda62007-09-16 21:45:02 +000093 const unsigned SelfRep = (unsigned)-1;
94 const unsigned Unvisited = (unsigned)-1;
95 // Position of the function return node relative to the function node.
Daniel Berlinb53270f2007-09-24 19:45:49 +000096 const unsigned CallReturnPos = 1;
Daniel Berlin385bda62007-09-16 21:45:02 +000097 // Position of the function call node relative to the function node.
Daniel Berlinb53270f2007-09-24 19:45:49 +000098 const unsigned CallFirstArgPos = 2;
99
100 struct BitmapKeyInfo {
101 static inline SparseBitVector<> *getEmptyKey() {
102 return reinterpret_cast<SparseBitVector<> *>(-1);
103 }
104 static inline SparseBitVector<> *getTombstoneKey() {
105 return reinterpret_cast<SparseBitVector<> *>(-2);
106 }
107 static unsigned getHashValue(const SparseBitVector<> *bitmap) {
108 return bitmap->getHashValue();
109 }
110 static bool isEqual(const SparseBitVector<> *LHS,
111 const SparseBitVector<> *RHS) {
112 if (LHS == RHS)
113 return true;
114 else if (LHS == getEmptyKey() || RHS == getEmptyKey()
115 || LHS == getTombstoneKey() || RHS == getTombstoneKey())
116 return false;
117
118 return *LHS == *RHS;
119 }
120
121 static bool isPod() { return true; }
122 };
Daniel Berlin385bda62007-09-16 21:45:02 +0000123
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000124 class VISIBILITY_HIDDEN Andersens : public ModulePass, public AliasAnalysis,
125 private InstVisitor<Andersens> {
Hartmut Kaiserad654562007-10-25 23:49:14 +0000126 struct Node;
Daniel Berlin385bda62007-09-16 21:45:02 +0000127
128 /// Constraint - Objects of this structure are used to represent the various
129 /// constraints identified by the algorithm. The constraints are 'copy',
130 /// for statements like "A = B", 'load' for statements like "A = *B",
131 /// 'store' for statements like "*A = B", and AddressOf for statements like
132 /// A = alloca; The Offset is applied as *(A + K) = B for stores,
133 /// A = *(B + K) for loads, and A = B + K for copies. It is
Daniel Berlinb53270f2007-09-24 19:45:49 +0000134 /// illegal on addressof constraints (because it is statically
Daniel Berlin385bda62007-09-16 21:45:02 +0000135 /// resolvable to A = &C where C = B + K)
136
137 struct Constraint {
138 enum ConstraintType { Copy, Load, Store, AddressOf } Type;
139 unsigned Dest;
140 unsigned Src;
141 unsigned Offset;
142
143 Constraint(ConstraintType Ty, unsigned D, unsigned S, unsigned O = 0)
144 : Type(Ty), Dest(D), Src(S), Offset(O) {
Anton Korobeynikov357a27d2008-02-20 11:08:44 +0000145 assert((Offset == 0 || Ty != AddressOf) &&
Daniel Berlin385bda62007-09-16 21:45:02 +0000146 "Offset is illegal on addressof constraints");
147 }
Daniel Berlin158a3932007-09-29 00:50:40 +0000148
Daniel Berline87fe282007-09-27 15:42:23 +0000149 bool operator==(const Constraint &RHS) const {
150 return RHS.Type == Type
151 && RHS.Dest == Dest
152 && RHS.Src == Src
153 && RHS.Offset == Offset;
154 }
Daniel Berlin158a3932007-09-29 00:50:40 +0000155
156 bool operator!=(const Constraint &RHS) const {
157 return !(*this == RHS);
158 }
159
Daniel Berline87fe282007-09-27 15:42:23 +0000160 bool operator<(const Constraint &RHS) const {
161 if (RHS.Type != Type)
162 return RHS.Type < Type;
163 else if (RHS.Dest != Dest)
164 return RHS.Dest < Dest;
165 else if (RHS.Src != Src)
166 return RHS.Src < Src;
167 return RHS.Offset < Offset;
168 }
Daniel Berlin385bda62007-09-16 21:45:02 +0000169 };
170
Daniel Berlinc6fd7722007-12-12 00:37:04 +0000171 // Information DenseSet requires implemented in order to be able to do
172 // it's thing
173 struct PairKeyInfo {
174 static inline std::pair<unsigned, unsigned> getEmptyKey() {
Scott Michel67973e42008-03-18 16:55:06 +0000175 return std::make_pair(~0U, ~0U);
Daniel Berlinc6fd7722007-12-12 00:37:04 +0000176 }
177 static inline std::pair<unsigned, unsigned> getTombstoneKey() {
Scott Michel67973e42008-03-18 16:55:06 +0000178 return std::make_pair(~0U - 1, ~0U - 1);
Daniel Berlinc6fd7722007-12-12 00:37:04 +0000179 }
180 static unsigned getHashValue(const std::pair<unsigned, unsigned> &P) {
181 return P.first ^ P.second;
182 }
183 static unsigned isEqual(const std::pair<unsigned, unsigned> &LHS,
184 const std::pair<unsigned, unsigned> &RHS) {
185 return LHS == RHS;
186 }
187 };
188
Daniel Berlin158a3932007-09-29 00:50:40 +0000189 struct ConstraintKeyInfo {
190 static inline Constraint getEmptyKey() {
Scott Michel67973e42008-03-18 16:55:06 +0000191 return Constraint(Constraint::Copy, ~0U, ~0U, ~0U);
Daniel Berlin158a3932007-09-29 00:50:40 +0000192 }
193 static inline Constraint getTombstoneKey() {
Scott Michel67973e42008-03-18 16:55:06 +0000194 return Constraint(Constraint::Copy, ~0U - 1, ~0U - 1, ~0U - 1);
Daniel Berlin158a3932007-09-29 00:50:40 +0000195 }
196 static unsigned getHashValue(const Constraint &C) {
197 return C.Src ^ C.Dest ^ C.Type ^ C.Offset;
198 }
199 static bool isEqual(const Constraint &LHS,
200 const Constraint &RHS) {
201 return LHS.Type == RHS.Type && LHS.Dest == RHS.Dest
202 && LHS.Src == RHS.Src && LHS.Offset == RHS.Offset;
203 }
204 };
205
Daniel Berlinb53270f2007-09-24 19:45:49 +0000206 // Node class - This class is used to represent a node in the constraint
Daniel Berlin122992d2007-09-24 22:20:45 +0000207 // graph. Due to various optimizations, it is not always the case that
208 // there is a mapping from a Node to a Value. In particular, we add
209 // artificial Node's that represent the set of pointed-to variables shared
210 // for each location equivalent Node.
Daniel Berlin385bda62007-09-16 21:45:02 +0000211 struct Node {
Daniel Berlinc6fd7722007-12-12 00:37:04 +0000212 private:
213 static unsigned Counter;
214
215 public:
Daniel Berlinb53270f2007-09-24 19:45:49 +0000216 Value *Val;
Daniel Berlin385bda62007-09-16 21:45:02 +0000217 SparseBitVector<> *Edges;
218 SparseBitVector<> *PointsTo;
219 SparseBitVector<> *OldPointsTo;
Daniel Berlin385bda62007-09-16 21:45:02 +0000220 std::list<Constraint> Constraints;
221
Daniel Berlinb53270f2007-09-24 19:45:49 +0000222 // Pointer and location equivalence labels
223 unsigned PointerEquivLabel;
224 unsigned LocationEquivLabel;
225 // Predecessor edges, both real and implicit
226 SparseBitVector<> *PredEdges;
227 SparseBitVector<> *ImplicitPredEdges;
228 // Set of nodes that point to us, only use for location equivalence.
229 SparseBitVector<> *PointedToBy;
230 // Number of incoming edges, used during variable substitution to early
231 // free the points-to sets
232 unsigned NumInEdges;
Daniel Berlin122992d2007-09-24 22:20:45 +0000233 // True if our points-to set is in the Set2PEClass map
Daniel Berlinb53270f2007-09-24 19:45:49 +0000234 bool StoredInHash;
Daniel Berlin122992d2007-09-24 22:20:45 +0000235 // True if our node has no indirect constraints (complex or otherwise)
Daniel Berlinb53270f2007-09-24 19:45:49 +0000236 bool Direct;
237 // True if the node is address taken, *or* it is part of a group of nodes
238 // that must be kept together. This is set to true for functions and
239 // their arg nodes, which must be kept at the same position relative to
240 // their base function node.
Daniel Berlinb53270f2007-09-24 19:45:49 +0000241 bool AddressTaken;
Daniel Berlin385bda62007-09-16 21:45:02 +0000242
Daniel Berlinb53270f2007-09-24 19:45:49 +0000243 // Nodes in cycles (or in equivalence classes) are united together using a
244 // standard union-find representation with path compression. NodeRep
245 // gives the index into GraphNodes for the representative Node.
246 unsigned NodeRep;
Daniel Berlinc6fd7722007-12-12 00:37:04 +0000247
248 // Modification timestamp. Assigned from Counter.
249 // Used for work list prioritization.
250 unsigned Timestamp;
Daniel Berlinb53270f2007-09-24 19:45:49 +0000251
Dan Gohmanc43c7f42007-12-14 15:41:34 +0000252 explicit Node(bool direct = true) :
Daniel Berlinc6fd7722007-12-12 00:37:04 +0000253 Val(0), Edges(0), PointsTo(0), OldPointsTo(0),
Daniel Berlinb53270f2007-09-24 19:45:49 +0000254 PointerEquivLabel(0), LocationEquivLabel(0), PredEdges(0),
255 ImplicitPredEdges(0), PointedToBy(0), NumInEdges(0),
256 StoredInHash(false), Direct(direct), AddressTaken(false),
Daniel Berlinc6fd7722007-12-12 00:37:04 +0000257 NodeRep(SelfRep), Timestamp(0) { }
Daniel Berlin385bda62007-09-16 21:45:02 +0000258
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000259 Node *setValue(Value *V) {
260 assert(Val == 0 && "Value already set for this node!");
261 Val = V;
262 return this;
263 }
264
265 /// getValue - Return the LLVM value corresponding to this node.
266 ///
267 Value *getValue() const { return Val; }
268
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000269 /// addPointerTo - Add a pointer to the list of pointees of this node,
270 /// returning true if this caused a new pointer to be added, or false if
271 /// we already knew about the points-to relation.
Daniel Berlin385bda62007-09-16 21:45:02 +0000272 bool addPointerTo(unsigned Node) {
273 return PointsTo->test_and_set(Node);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000274 }
275
276 /// intersects - Return true if the points-to set of this node intersects
277 /// with the points-to set of the specified node.
278 bool intersects(Node *N) const;
279
280 /// intersectsIgnoring - Return true if the points-to set of this node
281 /// intersects with the points-to set of the specified node on any nodes
282 /// except for the specified node to ignore.
Daniel Berlin385bda62007-09-16 21:45:02 +0000283 bool intersectsIgnoring(Node *N, unsigned) const;
Daniel Berlinc6fd7722007-12-12 00:37:04 +0000284
285 // Timestamp a node (used for work list prioritization)
286 void Stamp() {
287 Timestamp = Counter++;
288 }
289
Andrew Lenharthdce39302008-03-20 15:36:44 +0000290 bool isRep() const {
Daniel Berlinc6fd7722007-12-12 00:37:04 +0000291 return( (int) NodeRep < 0 );
292 }
293 };
294
295 struct WorkListElement {
296 Node* node;
297 unsigned Timestamp;
298 WorkListElement(Node* n, unsigned t) : node(n), Timestamp(t) {}
299
300 // Note that we reverse the sense of the comparison because we
301 // actually want to give low timestamps the priority over high,
302 // whereas priority is typically interpreted as a greater value is
303 // given high priority.
304 bool operator<(const WorkListElement& that) const {
305 return( this->Timestamp > that.Timestamp );
306 }
307 };
308
309 // Priority-queue based work list specialized for Nodes.
310 class WorkList {
311 std::priority_queue<WorkListElement> Q;
312
313 public:
314 void insert(Node* n) {
315 Q.push( WorkListElement(n, n->Timestamp) );
316 }
317
318 // We automatically discard non-representative nodes and nodes
319 // that were in the work list twice (we keep a copy of the
320 // timestamp in the work list so we can detect this situation by
321 // comparing against the node's current timestamp).
322 Node* pop() {
323 while( !Q.empty() ) {
324 WorkListElement x = Q.top(); Q.pop();
325 Node* INode = x.node;
326
327 if( INode->isRep() &&
328 INode->Timestamp == x.Timestamp ) {
329 return(x.node);
330 }
331 }
332 return(0);
333 }
334
335 bool empty() {
336 return Q.empty();
337 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000338 };
339
340 /// GraphNodes - This vector is populated as part of the object
341 /// identification stage of the analysis, which populates this vector with a
342 /// node for each memory object and fills in the ValueNodes map.
343 std::vector<Node> GraphNodes;
344
345 /// ValueNodes - This map indicates the Node that a particular Value* is
346 /// represented by. This contains entries for all pointers.
Daniel Berlinb53270f2007-09-24 19:45:49 +0000347 DenseMap<Value*, unsigned> ValueNodes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000348
349 /// ObjectNodes - This map contains entries for each memory object in the
350 /// program: globals, alloca's and mallocs.
Daniel Berlinb53270f2007-09-24 19:45:49 +0000351 DenseMap<Value*, unsigned> ObjectNodes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000352
353 /// ReturnNodes - This map contains an entry for each function in the
354 /// program that returns a value.
Daniel Berlinb53270f2007-09-24 19:45:49 +0000355 DenseMap<Function*, unsigned> ReturnNodes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000356
357 /// VarargNodes - This map contains the entry used to represent all pointers
358 /// passed through the varargs portion of a function call for a particular
359 /// function. An entry is not present in this map for functions that do not
360 /// take variable arguments.
Daniel Berlinb53270f2007-09-24 19:45:49 +0000361 DenseMap<Function*, unsigned> VarargNodes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000362
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000363
364 /// Constraints - This vector contains a list of all of the constraints
365 /// identified by the program.
366 std::vector<Constraint> Constraints;
367
Daniel Berlinb53270f2007-09-24 19:45:49 +0000368 // Map from graph node to maximum K value that is allowed (for functions,
Daniel Berlin385bda62007-09-16 21:45:02 +0000369 // this is equivalent to the number of arguments + CallFirstArgPos)
370 std::map<unsigned, unsigned> MaxK;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000371
372 /// This enum defines the GraphNodes indices that correspond to important
373 /// fixed sets.
374 enum {
375 UniversalSet = 0,
376 NullPtr = 1,
Daniel Berlinb53270f2007-09-24 19:45:49 +0000377 NullObject = 2,
378 NumberSpecialNodes
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000379 };
Daniel Berlinb53270f2007-09-24 19:45:49 +0000380 // Stack for Tarjan's
Daniel Berlin385bda62007-09-16 21:45:02 +0000381 std::stack<unsigned> SCCStack;
Daniel Berlin385bda62007-09-16 21:45:02 +0000382 // Map from Graph Node to DFS number
383 std::vector<unsigned> Node2DFS;
384 // Map from Graph Node to Deleted from graph.
385 std::vector<bool> Node2Deleted;
Daniel Berlinc6fd7722007-12-12 00:37:04 +0000386 // Same as Node Maps, but implemented as std::map because it is faster to
387 // clear
388 std::map<unsigned, unsigned> Tarjan2DFS;
389 std::map<unsigned, bool> Tarjan2Deleted;
390 // Current DFS number
Daniel Berlin385bda62007-09-16 21:45:02 +0000391 unsigned DFSNumber;
Daniel Berlinc6fd7722007-12-12 00:37:04 +0000392
393 // Work lists.
394 WorkList w1, w2;
395 WorkList *CurrWL, *NextWL; // "current" and "next" work lists
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000396
Daniel Berlinb53270f2007-09-24 19:45:49 +0000397 // Offline variable substitution related things
398
399 // Temporary rep storage, used because we can't collapse SCC's in the
400 // predecessor graph by uniting the variables permanently, we can only do so
401 // for the successor graph.
402 std::vector<unsigned> VSSCCRep;
403 // Mapping from node to whether we have visited it during SCC finding yet.
404 std::vector<bool> Node2Visited;
405 // During variable substitution, we create unknowns to represent the unknown
406 // value that is a dereference of a variable. These nodes are known as
407 // "ref" nodes (since they represent the value of dereferences).
408 unsigned FirstRefNode;
409 // During HVN, we create represent address taken nodes as if they were
410 // unknown (since HVN, unlike HU, does not evaluate unions).
411 unsigned FirstAdrNode;
412 // Current pointer equivalence class number
413 unsigned PEClass;
414 // Mapping from points-to sets to equivalence classes
415 typedef DenseMap<SparseBitVector<> *, unsigned, BitmapKeyInfo> BitVectorMap;
416 BitVectorMap Set2PEClass;
417 // Mapping from pointer equivalences to the representative node. -1 if we
418 // have no representative node for this pointer equivalence class yet.
419 std::vector<int> PEClass2Node;
420 // Mapping from pointer equivalences to representative node. This includes
421 // pointer equivalent but not location equivalent variables. -1 if we have
422 // no representative node for this pointer equivalence class yet.
423 std::vector<int> PENLEClass2Node;
Daniel Berlined95dd02008-03-05 19:31:47 +0000424 // Union/Find for HCD
425 std::vector<unsigned> HCDSCCRep;
426 // HCD's offline-detected cycles; "Statically DeTected"
427 // -1 if not part of such a cycle, otherwise a representative node.
428 std::vector<int> SDT;
429 // Whether to use SDT (UniteNodes can use it during solving, but not before)
430 bool SDTActive;
Daniel Berlinb53270f2007-09-24 19:45:49 +0000431
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000432 public:
Daniel Berlin385bda62007-09-16 21:45:02 +0000433 static char ID;
Devang Patel3aab76e2008-03-19 21:56:59 +0000434 Andersens() : ModulePass((intptr_t)&ID) {}
Devang Patel2b4fa682008-03-18 00:39:19 +0000435
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000436 bool runOnModule(Module &M) {
437 InitializeAliasAnalysis(this);
438 IdentifyObjects(M);
439 CollectConstraints(M);
Daniel Berlinb53270f2007-09-24 19:45:49 +0000440#undef DEBUG_TYPE
441#define DEBUG_TYPE "anders-aa-constraints"
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000442 DEBUG(PrintConstraints());
Daniel Berlinb53270f2007-09-24 19:45:49 +0000443#undef DEBUG_TYPE
444#define DEBUG_TYPE "anders-aa"
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000445 SolveConstraints();
446 DEBUG(PrintPointsToGraph());
447
448 // Free the constraints list, as we don't need it to respond to alias
449 // requests.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000450 std::vector<Constraint>().swap(Constraints);
Andrew Lenharthdce39302008-03-20 15:36:44 +0000451 //These are needed for Print() (-analyze in opt)
452 //ObjectNodes.clear();
453 //ReturnNodes.clear();
454 //VarargNodes.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000455 return false;
456 }
457
458 void releaseMemory() {
459 // FIXME: Until we have transitively required passes working correctly,
460 // this cannot be enabled! Otherwise, using -count-aa with the pass
461 // causes memory to be freed too early. :(
462#if 0
463 // The memory objects and ValueNodes data structures at the only ones that
464 // are still live after construction.
465 std::vector<Node>().swap(GraphNodes);
466 ValueNodes.clear();
467#endif
468 }
469
470 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
471 AliasAnalysis::getAnalysisUsage(AU);
472 AU.setPreservesAll(); // Does not transform code
473 }
474
475 //------------------------------------------------
476 // Implement the AliasAnalysis API
477 //
478 AliasResult alias(const Value *V1, unsigned V1Size,
479 const Value *V2, unsigned V2Size);
480 virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
481 virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
482 void getMustAliases(Value *P, std::vector<Value*> &RetVals);
483 bool pointsToConstantMemory(const Value *P);
484
485 virtual void deleteValue(Value *V) {
486 ValueNodes.erase(V);
487 getAnalysis<AliasAnalysis>().deleteValue(V);
488 }
489
490 virtual void copyValue(Value *From, Value *To) {
491 ValueNodes[To] = ValueNodes[From];
492 getAnalysis<AliasAnalysis>().copyValue(From, To);
493 }
494
495 private:
496 /// getNode - Return the node corresponding to the specified pointer scalar.
497 ///
Daniel Berlin385bda62007-09-16 21:45:02 +0000498 unsigned getNode(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000499 if (Constant *C = dyn_cast<Constant>(V))
500 if (!isa<GlobalValue>(C))
501 return getNodeForConstantPointer(C);
502
Daniel Berlinb53270f2007-09-24 19:45:49 +0000503 DenseMap<Value*, unsigned>::iterator I = ValueNodes.find(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000504 if (I == ValueNodes.end()) {
505#ifndef NDEBUG
506 V->dump();
507#endif
508 assert(0 && "Value does not have a node in the points-to graph!");
509 }
Daniel Berlin385bda62007-09-16 21:45:02 +0000510 return I->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000511 }
512
513 /// getObject - Return the node corresponding to the memory object for the
514 /// specified global or allocation instruction.
Andrew Lenharthdce39302008-03-20 15:36:44 +0000515 unsigned getObject(Value *V) const {
Daniel Berlinb53270f2007-09-24 19:45:49 +0000516 DenseMap<Value*, unsigned>::iterator I = ObjectNodes.find(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000517 assert(I != ObjectNodes.end() &&
518 "Value does not have an object in the points-to graph!");
Daniel Berlin385bda62007-09-16 21:45:02 +0000519 return I->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000520 }
521
522 /// getReturnNode - Return the node representing the return value for the
523 /// specified function.
Andrew Lenharthdce39302008-03-20 15:36:44 +0000524 unsigned getReturnNode(Function *F) const {
Daniel Berlinb53270f2007-09-24 19:45:49 +0000525 DenseMap<Function*, unsigned>::iterator I = ReturnNodes.find(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000526 assert(I != ReturnNodes.end() && "Function does not return a value!");
Daniel Berlin385bda62007-09-16 21:45:02 +0000527 return I->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000528 }
529
530 /// getVarargNode - Return the node representing the variable arguments
531 /// formal for the specified function.
Andrew Lenharthdce39302008-03-20 15:36:44 +0000532 unsigned getVarargNode(Function *F) const {
Daniel Berlinb53270f2007-09-24 19:45:49 +0000533 DenseMap<Function*, unsigned>::iterator I = VarargNodes.find(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000534 assert(I != VarargNodes.end() && "Function does not take var args!");
Daniel Berlin385bda62007-09-16 21:45:02 +0000535 return I->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000536 }
537
538 /// getNodeValue - Get the node for the specified LLVM value and set the
539 /// value for it to be the specified value.
Daniel Berlin385bda62007-09-16 21:45:02 +0000540 unsigned getNodeValue(Value &V) {
541 unsigned Index = getNode(&V);
542 GraphNodes[Index].setValue(&V);
543 return Index;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000544 }
545
Daniel Berlinc6fd7722007-12-12 00:37:04 +0000546 unsigned UniteNodes(unsigned First, unsigned Second,
547 bool UnionByRank = true);
Daniel Berlin385bda62007-09-16 21:45:02 +0000548 unsigned FindNode(unsigned Node);
Andrew Lenharthdce39302008-03-20 15:36:44 +0000549 unsigned FindNode(unsigned Node) const;
Daniel Berlin385bda62007-09-16 21:45:02 +0000550
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000551 void IdentifyObjects(Module &M);
552 void CollectConstraints(Module &M);
Daniel Berlin385bda62007-09-16 21:45:02 +0000553 bool AnalyzeUsesOfFunction(Value *);
554 void CreateConstraintGraph();
Daniel Berlinb53270f2007-09-24 19:45:49 +0000555 void OptimizeConstraints();
556 unsigned FindEquivalentNode(unsigned, unsigned);
557 void ClumpAddressTaken();
558 void RewriteConstraints();
559 void HU();
560 void HVN();
Daniel Berlined95dd02008-03-05 19:31:47 +0000561 void HCD();
562 void Search(unsigned Node);
Daniel Berlinb53270f2007-09-24 19:45:49 +0000563 void UnitePointerEquivalences();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000564 void SolveConstraints();
Daniel Berlinc6fd7722007-12-12 00:37:04 +0000565 bool QueryNode(unsigned Node);
Daniel Berlinb53270f2007-09-24 19:45:49 +0000566 void Condense(unsigned Node);
567 void HUValNum(unsigned Node);
568 void HVNValNum(unsigned Node);
Daniel Berlin385bda62007-09-16 21:45:02 +0000569 unsigned getNodeForConstantPointer(Constant *C);
570 unsigned getNodeForConstantPointerTarget(Constant *C);
571 void AddGlobalInitializerConstraints(unsigned, Constant *C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000572
573 void AddConstraintsForNonInternalLinkage(Function *F);
574 void AddConstraintsForCall(CallSite CS, Function *F);
575 bool AddConstraintsForExternalCall(CallSite CS, Function *F);
576
577
Andrew Lenharthdce39302008-03-20 15:36:44 +0000578 void PrintNode(const Node *N) const;
579 void PrintConstraints() const ;
580 void PrintConstraint(const Constraint &) const;
581 void PrintLabels() const;
582 void PrintPointsToGraph() const;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000583
584 //===------------------------------------------------------------------===//
585 // Instruction visitation methods for adding constraints
586 //
587 friend class InstVisitor<Andersens>;
588 void visitReturnInst(ReturnInst &RI);
589 void visitInvokeInst(InvokeInst &II) { visitCallSite(CallSite(&II)); }
590 void visitCallInst(CallInst &CI) { visitCallSite(CallSite(&CI)); }
591 void visitCallSite(CallSite CS);
592 void visitAllocationInst(AllocationInst &AI);
593 void visitLoadInst(LoadInst &LI);
594 void visitStoreInst(StoreInst &SI);
595 void visitGetElementPtrInst(GetElementPtrInst &GEP);
596 void visitPHINode(PHINode &PN);
597 void visitCastInst(CastInst &CI);
598 void visitICmpInst(ICmpInst &ICI) {} // NOOP!
599 void visitFCmpInst(FCmpInst &ICI) {} // NOOP!
600 void visitSelectInst(SelectInst &SI);
601 void visitVAArg(VAArgInst &I);
602 void visitInstruction(Instruction &I);
Daniel Berlin385bda62007-09-16 21:45:02 +0000603
Andrew Lenharthdce39302008-03-20 15:36:44 +0000604 //===------------------------------------------------------------------===//
605 // Implement Analyize interface
606 //
607 void print(std::ostream &O, const Module* M) const {
608 PrintPointsToGraph();
609 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000610 };
611
612 char Andersens::ID = 0;
613 RegisterPass<Andersens> X("anders-aa",
Devang Patelbdfd1862008-03-20 02:25:21 +0000614 "Andersen's Interprocedural Alias Analysis", false,
Devang Patel3aab76e2008-03-19 21:56:59 +0000615 true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000616 RegisterAnalysisGroup<AliasAnalysis> Y(X);
Daniel Berlinc6fd7722007-12-12 00:37:04 +0000617
618 // Initialize Timestamp Counter (static).
619 unsigned Andersens::Node::Counter = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000620}
621
622ModulePass *llvm::createAndersensPass() { return new Andersens(); }
623
624//===----------------------------------------------------------------------===//
625// AliasAnalysis Interface Implementation
626//===----------------------------------------------------------------------===//
627
628AliasAnalysis::AliasResult Andersens::alias(const Value *V1, unsigned V1Size,
629 const Value *V2, unsigned V2Size) {
Daniel Berlin385bda62007-09-16 21:45:02 +0000630 Node *N1 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V1)))];
631 Node *N2 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V2)))];
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000632
633 // Check to see if the two pointers are known to not alias. They don't alias
634 // if their points-to sets do not intersect.
Daniel Berlin385bda62007-09-16 21:45:02 +0000635 if (!N1->intersectsIgnoring(N2, NullObject))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000636 return NoAlias;
637
638 return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
639}
640
641AliasAnalysis::ModRefResult
642Andersens::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
643 // The only thing useful that we can contribute for mod/ref information is
644 // when calling external function calls: if we know that memory never escapes
645 // from the program, it cannot be modified by an external call.
646 //
647 // NOTE: This is not really safe, at least not when the entire program is not
648 // available. The deal is that the external function could call back into the
649 // program and modify stuff. We ignore this technical niggle for now. This
650 // is, after all, a "research quality" implementation of Andersen's analysis.
651 if (Function *F = CS.getCalledFunction())
652 if (F->isDeclaration()) {
Daniel Berlin385bda62007-09-16 21:45:02 +0000653 Node *N1 = &GraphNodes[FindNode(getNode(P))];
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000654
Daniel Berlin385bda62007-09-16 21:45:02 +0000655 if (N1->PointsTo->empty())
656 return NoModRef;
Daniel Berlinb68539d2008-03-18 22:22:53 +0000657#if FULL_UNIVERSAL
658 if (!UniversalSet->PointsTo->test(FindNode(getNode(P))))
659 return NoModRef; // Universal set does not contain P
660#else
Daniel Berlin385bda62007-09-16 21:45:02 +0000661 if (!N1->PointsTo->test(UniversalSet))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000662 return NoModRef; // P doesn't point to the universal set.
Daniel Berlinb68539d2008-03-18 22:22:53 +0000663#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000664 }
665
666 return AliasAnalysis::getModRefInfo(CS, P, Size);
667}
668
669AliasAnalysis::ModRefResult
670Andersens::getModRefInfo(CallSite CS1, CallSite CS2) {
671 return AliasAnalysis::getModRefInfo(CS1,CS2);
672}
673
674/// getMustAlias - We can provide must alias information if we know that a
675/// pointer can only point to a specific function or the null pointer.
676/// Unfortunately we cannot determine must-alias information for global
677/// variables or any other memory memory objects because we do not track whether
678/// a pointer points to the beginning of an object or a field of it.
679void Andersens::getMustAliases(Value *P, std::vector<Value*> &RetVals) {
Daniel Berlin385bda62007-09-16 21:45:02 +0000680 Node *N = &GraphNodes[FindNode(getNode(P))];
681 if (N->PointsTo->count() == 1) {
682 Node *Pointee = &GraphNodes[N->PointsTo->find_first()];
683 // If a function is the only object in the points-to set, then it must be
684 // the destination. Note that we can't handle global variables here,
685 // because we don't know if the pointer is actually pointing to a field of
686 // the global or to the beginning of it.
687 if (Value *V = Pointee->getValue()) {
688 if (Function *F = dyn_cast<Function>(V))
689 RetVals.push_back(F);
690 } else {
691 // If the object in the points-to set is the null object, then the null
692 // pointer is a must alias.
693 if (Pointee == &GraphNodes[NullObject])
694 RetVals.push_back(Constant::getNullValue(P->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000695 }
696 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000697 AliasAnalysis::getMustAliases(P, RetVals);
698}
699
700/// pointsToConstantMemory - If we can determine that this pointer only points
701/// to constant memory, return true. In practice, this means that if the
702/// pointer can only point to constant globals, functions, or the null pointer,
703/// return true.
704///
705bool Andersens::pointsToConstantMemory(const Value *P) {
Dan Gohmandd96f722008-02-21 17:33:24 +0000706 Node *N = &GraphNodes[FindNode(getNode(const_cast<Value*>(P)))];
Daniel Berlin385bda62007-09-16 21:45:02 +0000707 unsigned i;
708
709 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
710 bi != N->PointsTo->end();
711 ++bi) {
712 i = *bi;
713 Node *Pointee = &GraphNodes[i];
714 if (Value *V = Pointee->getValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000715 if (!isa<GlobalValue>(V) || (isa<GlobalVariable>(V) &&
716 !cast<GlobalVariable>(V)->isConstant()))
717 return AliasAnalysis::pointsToConstantMemory(P);
718 } else {
Daniel Berlin385bda62007-09-16 21:45:02 +0000719 if (i != NullObject)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000720 return AliasAnalysis::pointsToConstantMemory(P);
721 }
722 }
723
724 return true;
725}
726
727//===----------------------------------------------------------------------===//
728// Object Identification Phase
729//===----------------------------------------------------------------------===//
730
731/// IdentifyObjects - This stage scans the program, adding an entry to the
732/// GraphNodes list for each memory object in the program (global stack or
733/// heap), and populates the ValueNodes and ObjectNodes maps for these objects.
734///
735void Andersens::IdentifyObjects(Module &M) {
736 unsigned NumObjects = 0;
737
738 // Object #0 is always the universal set: the object that we don't know
739 // anything about.
740 assert(NumObjects == UniversalSet && "Something changed!");
741 ++NumObjects;
742
743 // Object #1 always represents the null pointer.
744 assert(NumObjects == NullPtr && "Something changed!");
745 ++NumObjects;
746
747 // Object #2 always represents the null object (the object pointed to by null)
748 assert(NumObjects == NullObject && "Something changed!");
749 ++NumObjects;
750
751 // Add all the globals first.
752 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
753 I != E; ++I) {
754 ObjectNodes[I] = NumObjects++;
755 ValueNodes[I] = NumObjects++;
756 }
757
758 // Add nodes for all of the functions and the instructions inside of them.
759 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
760 // The function itself is a memory object.
Daniel Berlin385bda62007-09-16 21:45:02 +0000761 unsigned First = NumObjects;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000762 ValueNodes[F] = NumObjects++;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000763 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
764 ReturnNodes[F] = NumObjects++;
765 if (F->getFunctionType()->isVarArg())
766 VarargNodes[F] = NumObjects++;
767
Daniel Berlin385bda62007-09-16 21:45:02 +0000768
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000769 // Add nodes for all of the incoming pointer arguments.
770 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
771 I != E; ++I)
Daniel Berlinb53270f2007-09-24 19:45:49 +0000772 {
773 if (isa<PointerType>(I->getType()))
774 ValueNodes[I] = NumObjects++;
775 }
Daniel Berlin385bda62007-09-16 21:45:02 +0000776 MaxK[First] = NumObjects - First;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000777
778 // Scan the function body, creating a memory object for each heap/stack
779 // allocation in the body of the function and a node to represent all
780 // pointer values defined by instructions and used as operands.
781 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
782 // If this is an heap or stack allocation, create a node for the memory
783 // object.
784 if (isa<PointerType>(II->getType())) {
785 ValueNodes[&*II] = NumObjects++;
786 if (AllocationInst *AI = dyn_cast<AllocationInst>(&*II))
787 ObjectNodes[AI] = NumObjects++;
788 }
Nick Lewycky6b676da2007-11-22 03:07:37 +0000789
790 // Calls to inline asm need to be added as well because the callee isn't
791 // referenced anywhere else.
792 if (CallInst *CI = dyn_cast<CallInst>(&*II)) {
793 Value *Callee = CI->getCalledValue();
794 if (isa<InlineAsm>(Callee))
795 ValueNodes[Callee] = NumObjects++;
796 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000797 }
798 }
799
800 // Now that we know how many objects to create, make them all now!
801 GraphNodes.resize(NumObjects);
802 NumNodes += NumObjects;
803}
804
805//===----------------------------------------------------------------------===//
806// Constraint Identification Phase
807//===----------------------------------------------------------------------===//
808
809/// getNodeForConstantPointer - Return the node corresponding to the constant
810/// pointer itself.
Daniel Berlin385bda62007-09-16 21:45:02 +0000811unsigned Andersens::getNodeForConstantPointer(Constant *C) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000812 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
813
814 if (isa<ConstantPointerNull>(C) || isa<UndefValue>(C))
Daniel Berlin385bda62007-09-16 21:45:02 +0000815 return NullPtr;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000816 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
817 return getNode(GV);
818 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
819 switch (CE->getOpcode()) {
820 case Instruction::GetElementPtr:
821 return getNodeForConstantPointer(CE->getOperand(0));
822 case Instruction::IntToPtr:
Daniel Berlin385bda62007-09-16 21:45:02 +0000823 return UniversalSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000824 case Instruction::BitCast:
825 return getNodeForConstantPointer(CE->getOperand(0));
826 default:
827 cerr << "Constant Expr not yet handled: " << *CE << "\n";
828 assert(0);
829 }
830 } else {
831 assert(0 && "Unknown constant pointer!");
832 }
833 return 0;
834}
835
836/// getNodeForConstantPointerTarget - Return the node POINTED TO by the
837/// specified constant pointer.
Daniel Berlin385bda62007-09-16 21:45:02 +0000838unsigned Andersens::getNodeForConstantPointerTarget(Constant *C) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000839 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
840
841 if (isa<ConstantPointerNull>(C))
Daniel Berlin385bda62007-09-16 21:45:02 +0000842 return NullObject;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000843 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
844 return getObject(GV);
845 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
846 switch (CE->getOpcode()) {
847 case Instruction::GetElementPtr:
848 return getNodeForConstantPointerTarget(CE->getOperand(0));
849 case Instruction::IntToPtr:
Daniel Berlin385bda62007-09-16 21:45:02 +0000850 return UniversalSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000851 case Instruction::BitCast:
852 return getNodeForConstantPointerTarget(CE->getOperand(0));
853 default:
854 cerr << "Constant Expr not yet handled: " << *CE << "\n";
855 assert(0);
856 }
857 } else {
858 assert(0 && "Unknown constant pointer!");
859 }
860 return 0;
861}
862
863/// AddGlobalInitializerConstraints - Add inclusion constraints for the memory
864/// object N, which contains values indicated by C.
Daniel Berlin385bda62007-09-16 21:45:02 +0000865void Andersens::AddGlobalInitializerConstraints(unsigned NodeIndex,
866 Constant *C) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000867 if (C->getType()->isFirstClassType()) {
868 if (isa<PointerType>(C->getType()))
Daniel Berlin385bda62007-09-16 21:45:02 +0000869 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
870 getNodeForConstantPointer(C)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000871 } else if (C->isNullValue()) {
Daniel Berlin385bda62007-09-16 21:45:02 +0000872 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
873 NullObject));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000874 return;
875 } else if (!isa<UndefValue>(C)) {
876 // If this is an array or struct, include constraints for each element.
877 assert(isa<ConstantArray>(C) || isa<ConstantStruct>(C));
878 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
Daniel Berlin385bda62007-09-16 21:45:02 +0000879 AddGlobalInitializerConstraints(NodeIndex,
880 cast<Constant>(C->getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000881 }
882}
883
884/// AddConstraintsForNonInternalLinkage - If this function does not have
885/// internal linkage, realize that we can't trust anything passed into or
886/// returned by this function.
887void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
888 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
889 if (isa<PointerType>(I->getType()))
890 // If this is an argument of an externally accessible function, the
891 // incoming pointer might point to anything.
892 Constraints.push_back(Constraint(Constraint::Copy, getNode(I),
Daniel Berlin385bda62007-09-16 21:45:02 +0000893 UniversalSet));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000894}
895
896/// AddConstraintsForCall - If this is a call to a "known" function, add the
897/// constraints and return true. If this is a call to an unknown function,
898/// return false.
899bool Andersens::AddConstraintsForExternalCall(CallSite CS, Function *F) {
900 assert(F->isDeclaration() && "Not an external function!");
901
902 // These functions don't induce any points-to constraints.
903 if (F->getName() == "atoi" || F->getName() == "atof" ||
904 F->getName() == "atol" || F->getName() == "atoll" ||
905 F->getName() == "remove" || F->getName() == "unlink" ||
906 F->getName() == "rename" || F->getName() == "memcmp" ||
907 F->getName() == "llvm.memset.i32" ||
908 F->getName() == "llvm.memset.i64" ||
909 F->getName() == "strcmp" || F->getName() == "strncmp" ||
910 F->getName() == "execl" || F->getName() == "execlp" ||
911 F->getName() == "execle" || F->getName() == "execv" ||
912 F->getName() == "execvp" || F->getName() == "chmod" ||
913 F->getName() == "puts" || F->getName() == "write" ||
914 F->getName() == "open" || F->getName() == "create" ||
915 F->getName() == "truncate" || F->getName() == "chdir" ||
916 F->getName() == "mkdir" || F->getName() == "rmdir" ||
917 F->getName() == "read" || F->getName() == "pipe" ||
918 F->getName() == "wait" || F->getName() == "time" ||
919 F->getName() == "stat" || F->getName() == "fstat" ||
920 F->getName() == "lstat" || F->getName() == "strtod" ||
921 F->getName() == "strtof" || F->getName() == "strtold" ||
922 F->getName() == "fopen" || F->getName() == "fdopen" ||
923 F->getName() == "freopen" ||
924 F->getName() == "fflush" || F->getName() == "feof" ||
925 F->getName() == "fileno" || F->getName() == "clearerr" ||
926 F->getName() == "rewind" || F->getName() == "ftell" ||
927 F->getName() == "ferror" || F->getName() == "fgetc" ||
928 F->getName() == "fgetc" || F->getName() == "_IO_getc" ||
929 F->getName() == "fwrite" || F->getName() == "fread" ||
930 F->getName() == "fgets" || F->getName() == "ungetc" ||
931 F->getName() == "fputc" ||
932 F->getName() == "fputs" || F->getName() == "putc" ||
933 F->getName() == "ftell" || F->getName() == "rewind" ||
934 F->getName() == "_IO_putc" || F->getName() == "fseek" ||
935 F->getName() == "fgetpos" || F->getName() == "fsetpos" ||
936 F->getName() == "printf" || F->getName() == "fprintf" ||
937 F->getName() == "sprintf" || F->getName() == "vprintf" ||
938 F->getName() == "vfprintf" || F->getName() == "vsprintf" ||
939 F->getName() == "scanf" || F->getName() == "fscanf" ||
940 F->getName() == "sscanf" || F->getName() == "__assert_fail" ||
941 F->getName() == "modf")
942 return true;
943
944
945 // These functions do induce points-to edges.
Daniel Berlin385bda62007-09-16 21:45:02 +0000946 if (F->getName() == "llvm.memcpy.i32" || F->getName() == "llvm.memcpy.i64" ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000947 F->getName() == "llvm.memmove.i32" ||F->getName() == "llvm.memmove.i64" ||
948 F->getName() == "memmove") {
Daniel Berlin385bda62007-09-16 21:45:02 +0000949
950 // *Dest = *Src, which requires an artificial graph node to represent the
951 // constraint. It is broken up into *Dest = temp, temp = *Src
952 unsigned FirstArg = getNode(CS.getArgument(0));
953 unsigned SecondArg = getNode(CS.getArgument(1));
954 unsigned TempArg = GraphNodes.size();
955 GraphNodes.push_back(Node());
956 Constraints.push_back(Constraint(Constraint::Store,
957 FirstArg, TempArg));
958 Constraints.push_back(Constraint(Constraint::Load,
959 TempArg, SecondArg));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000960 return true;
961 }
962
963 // Result = Arg0
964 if (F->getName() == "realloc" || F->getName() == "strchr" ||
965 F->getName() == "strrchr" || F->getName() == "strstr" ||
966 F->getName() == "strtok") {
967 Constraints.push_back(Constraint(Constraint::Copy,
968 getNode(CS.getInstruction()),
969 getNode(CS.getArgument(0))));
970 return true;
971 }
972
973 return false;
974}
975
976
977
Daniel Berlin385bda62007-09-16 21:45:02 +0000978/// AnalyzeUsesOfFunction - Look at all of the users of the specified function.
979/// If this is used by anything complex (i.e., the address escapes), return
980/// true.
981bool Andersens::AnalyzeUsesOfFunction(Value *V) {
982
983 if (!isa<PointerType>(V->getType())) return true;
984
985 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
986 if (dyn_cast<LoadInst>(*UI)) {
987 return false;
988 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
989 if (V == SI->getOperand(1)) {
990 return false;
991 } else if (SI->getOperand(1)) {
992 return true; // Storing the pointer
993 }
994 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
995 if (AnalyzeUsesOfFunction(GEP)) return true;
996 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
997 // Make sure that this is just the function being called, not that it is
998 // passing into the function.
999 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
1000 if (CI->getOperand(i) == V) return true;
1001 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
1002 // Make sure that this is just the function being called, not that it is
1003 // passing into the function.
1004 for (unsigned i = 3, e = II->getNumOperands(); i != e; ++i)
1005 if (II->getOperand(i) == V) return true;
1006 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
1007 if (CE->getOpcode() == Instruction::GetElementPtr ||
1008 CE->getOpcode() == Instruction::BitCast) {
1009 if (AnalyzeUsesOfFunction(CE))
1010 return true;
1011 } else {
1012 return true;
1013 }
1014 } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(*UI)) {
1015 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1016 return true; // Allow comparison against null.
1017 } else if (dyn_cast<FreeInst>(*UI)) {
1018 return false;
1019 } else {
1020 return true;
1021 }
1022 return false;
1023}
1024
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001025/// CollectConstraints - This stage scans the program, adding a constraint to
1026/// the Constraints list for each instruction in the program that induces a
1027/// constraint, and setting up the initial points-to graph.
1028///
1029void Andersens::CollectConstraints(Module &M) {
1030 // First, the universal set points to itself.
Daniel Berlin385bda62007-09-16 21:45:02 +00001031 Constraints.push_back(Constraint(Constraint::AddressOf, UniversalSet,
1032 UniversalSet));
1033 Constraints.push_back(Constraint(Constraint::Store, UniversalSet,
1034 UniversalSet));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001035
1036 // Next, the null pointer points to the null object.
Daniel Berlin385bda62007-09-16 21:45:02 +00001037 Constraints.push_back(Constraint(Constraint::AddressOf, NullPtr, NullObject));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001038
1039 // Next, add any constraints on global variables and their initializers.
1040 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1041 I != E; ++I) {
1042 // Associate the address of the global object as pointing to the memory for
1043 // the global: &G = <G memory>
Daniel Berlin385bda62007-09-16 21:45:02 +00001044 unsigned ObjectIndex = getObject(I);
1045 Node *Object = &GraphNodes[ObjectIndex];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001046 Object->setValue(I);
Daniel Berlin385bda62007-09-16 21:45:02 +00001047 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(*I),
1048 ObjectIndex));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001049
1050 if (I->hasInitializer()) {
Daniel Berlin385bda62007-09-16 21:45:02 +00001051 AddGlobalInitializerConstraints(ObjectIndex, I->getInitializer());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001052 } else {
1053 // If it doesn't have an initializer (i.e. it's defined in another
1054 // translation unit), it points to the universal set.
Daniel Berlin385bda62007-09-16 21:45:02 +00001055 Constraints.push_back(Constraint(Constraint::Copy, ObjectIndex,
1056 UniversalSet));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001057 }
1058 }
1059
1060 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001061 // Set up the return value node.
1062 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
Daniel Berlin385bda62007-09-16 21:45:02 +00001063 GraphNodes[getReturnNode(F)].setValue(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001064 if (F->getFunctionType()->isVarArg())
Daniel Berlin385bda62007-09-16 21:45:02 +00001065 GraphNodes[getVarargNode(F)].setValue(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001066
1067 // Set up incoming argument nodes.
1068 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
1069 I != E; ++I)
1070 if (isa<PointerType>(I->getType()))
1071 getNodeValue(*I);
1072
Daniel Berlin385bda62007-09-16 21:45:02 +00001073 // At some point we should just add constraints for the escaping functions
1074 // at solve time, but this slows down solving. For now, we simply mark
1075 // address taken functions as escaping and treat them as external.
1076 if (!F->hasInternalLinkage() || AnalyzeUsesOfFunction(F))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001077 AddConstraintsForNonInternalLinkage(F);
1078
1079 if (!F->isDeclaration()) {
1080 // Scan the function body, creating a memory object for each heap/stack
1081 // allocation in the body of the function and a node to represent all
1082 // pointer values defined by instructions and used as operands.
1083 visit(F);
1084 } else {
1085 // External functions that return pointers return the universal set.
1086 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
1087 Constraints.push_back(Constraint(Constraint::Copy,
1088 getReturnNode(F),
Daniel Berlin385bda62007-09-16 21:45:02 +00001089 UniversalSet));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001090
1091 // Any pointers that are passed into the function have the universal set
1092 // stored into them.
1093 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
1094 I != E; ++I)
1095 if (isa<PointerType>(I->getType())) {
1096 // Pointers passed into external functions could have anything stored
1097 // through them.
1098 Constraints.push_back(Constraint(Constraint::Store, getNode(I),
Daniel Berlin385bda62007-09-16 21:45:02 +00001099 UniversalSet));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001100 // Memory objects passed into external function calls can have the
1101 // universal set point to them.
Daniel Berlinc6fd7722007-12-12 00:37:04 +00001102#if FULL_UNIVERSAL
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001103 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlin385bda62007-09-16 21:45:02 +00001104 UniversalSet,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001105 getNode(I)));
Daniel Berlinc6fd7722007-12-12 00:37:04 +00001106#else
1107 Constraints.push_back(Constraint(Constraint::Copy,
1108 getNode(I),
1109 UniversalSet));
1110#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001111 }
1112
1113 // If this is an external varargs function, it can also store pointers
1114 // into any pointers passed through the varargs section.
1115 if (F->getFunctionType()->isVarArg())
1116 Constraints.push_back(Constraint(Constraint::Store, getVarargNode(F),
Daniel Berlin385bda62007-09-16 21:45:02 +00001117 UniversalSet));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001118 }
1119 }
1120 NumConstraints += Constraints.size();
1121}
1122
1123
1124void Andersens::visitInstruction(Instruction &I) {
1125#ifdef NDEBUG
1126 return; // This function is just a big assert.
1127#endif
1128 if (isa<BinaryOperator>(I))
1129 return;
1130 // Most instructions don't have any effect on pointer values.
1131 switch (I.getOpcode()) {
1132 case Instruction::Br:
1133 case Instruction::Switch:
1134 case Instruction::Unwind:
1135 case Instruction::Unreachable:
1136 case Instruction::Free:
1137 case Instruction::ICmp:
1138 case Instruction::FCmp:
1139 return;
1140 default:
1141 // Is this something we aren't handling yet?
1142 cerr << "Unknown instruction: " << I;
1143 abort();
1144 }
1145}
1146
1147void Andersens::visitAllocationInst(AllocationInst &AI) {
Daniel Berlin385bda62007-09-16 21:45:02 +00001148 unsigned ObjectIndex = getObject(&AI);
1149 GraphNodes[ObjectIndex].setValue(&AI);
1150 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(AI),
1151 ObjectIndex));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001152}
1153
1154void Andersens::visitReturnInst(ReturnInst &RI) {
1155 if (RI.getNumOperands() && isa<PointerType>(RI.getOperand(0)->getType()))
1156 // return V --> <Copy/retval{F}/v>
1157 Constraints.push_back(Constraint(Constraint::Copy,
1158 getReturnNode(RI.getParent()->getParent()),
1159 getNode(RI.getOperand(0))));
1160}
1161
1162void Andersens::visitLoadInst(LoadInst &LI) {
1163 if (isa<PointerType>(LI.getType()))
1164 // P1 = load P2 --> <Load/P1/P2>
1165 Constraints.push_back(Constraint(Constraint::Load, getNodeValue(LI),
1166 getNode(LI.getOperand(0))));
1167}
1168
1169void Andersens::visitStoreInst(StoreInst &SI) {
1170 if (isa<PointerType>(SI.getOperand(0)->getType()))
1171 // store P1, P2 --> <Store/P2/P1>
1172 Constraints.push_back(Constraint(Constraint::Store,
1173 getNode(SI.getOperand(1)),
1174 getNode(SI.getOperand(0))));
1175}
1176
1177void Andersens::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1178 // P1 = getelementptr P2, ... --> <Copy/P1/P2>
1179 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(GEP),
1180 getNode(GEP.getOperand(0))));
1181}
1182
1183void Andersens::visitPHINode(PHINode &PN) {
1184 if (isa<PointerType>(PN.getType())) {
Daniel Berlin385bda62007-09-16 21:45:02 +00001185 unsigned PNN = getNodeValue(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001186 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1187 // P1 = phi P2, P3 --> <Copy/P1/P2>, <Copy/P1/P3>, ...
1188 Constraints.push_back(Constraint(Constraint::Copy, PNN,
1189 getNode(PN.getIncomingValue(i))));
1190 }
1191}
1192
1193void Andersens::visitCastInst(CastInst &CI) {
1194 Value *Op = CI.getOperand(0);
1195 if (isa<PointerType>(CI.getType())) {
1196 if (isa<PointerType>(Op->getType())) {
1197 // P1 = cast P2 --> <Copy/P1/P2>
1198 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
1199 getNode(CI.getOperand(0))));
1200 } else {
1201 // P1 = cast int --> <Copy/P1/Univ>
1202#if 0
1203 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
Daniel Berlin385bda62007-09-16 21:45:02 +00001204 UniversalSet));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001205#else
1206 getNodeValue(CI);
1207#endif
1208 }
1209 } else if (isa<PointerType>(Op->getType())) {
1210 // int = cast P1 --> <Copy/Univ/P1>
1211#if 0
1212 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlin385bda62007-09-16 21:45:02 +00001213 UniversalSet,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001214 getNode(CI.getOperand(0))));
1215#else
1216 getNode(CI.getOperand(0));
1217#endif
1218 }
1219}
1220
1221void Andersens::visitSelectInst(SelectInst &SI) {
1222 if (isa<PointerType>(SI.getType())) {
Daniel Berlin385bda62007-09-16 21:45:02 +00001223 unsigned SIN = getNodeValue(SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001224 // P1 = select C, P2, P3 ---> <Copy/P1/P2>, <Copy/P1/P3>
1225 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1226 getNode(SI.getOperand(1))));
1227 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1228 getNode(SI.getOperand(2))));
1229 }
1230}
1231
1232void Andersens::visitVAArg(VAArgInst &I) {
1233 assert(0 && "vaarg not handled yet!");
1234}
1235
1236/// AddConstraintsForCall - Add constraints for a call with actual arguments
1237/// specified by CS to the function specified by F. Note that the types of
1238/// arguments might not match up in the case where this is an indirect call and
1239/// the function pointer has been casted. If this is the case, do something
1240/// reasonable.
1241void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
Daniel Berlin385bda62007-09-16 21:45:02 +00001242 Value *CallValue = CS.getCalledValue();
1243 bool IsDeref = F == NULL;
1244
1245 // If this is a call to an external function, try to handle it directly to get
1246 // some taste of context sensitivity.
1247 if (F && F->isDeclaration() && AddConstraintsForExternalCall(CS, F))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001248 return;
1249
1250 if (isa<PointerType>(CS.getType())) {
Daniel Berlin385bda62007-09-16 21:45:02 +00001251 unsigned CSN = getNode(CS.getInstruction());
1252 if (!F || isa<PointerType>(F->getFunctionType()->getReturnType())) {
1253 if (IsDeref)
1254 Constraints.push_back(Constraint(Constraint::Load, CSN,
1255 getNode(CallValue), CallReturnPos));
1256 else
1257 Constraints.push_back(Constraint(Constraint::Copy, CSN,
1258 getNode(CallValue) + CallReturnPos));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001259 } else {
1260 // If the function returns a non-pointer value, handle this just like we
1261 // treat a nonpointer cast to pointer.
1262 Constraints.push_back(Constraint(Constraint::Copy, CSN,
Daniel Berlin385bda62007-09-16 21:45:02 +00001263 UniversalSet));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001264 }
Daniel Berlin385bda62007-09-16 21:45:02 +00001265 } else if (F && isa<PointerType>(F->getFunctionType()->getReturnType())) {
Daniel Berlinc6fd7722007-12-12 00:37:04 +00001266#if FULL_UNIVERSAL
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001267 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlin385bda62007-09-16 21:45:02 +00001268 UniversalSet,
1269 getNode(CallValue) + CallReturnPos));
Daniel Berlinc6fd7722007-12-12 00:37:04 +00001270#else
1271 Constraints.push_back(Constraint(Constraint::Copy,
1272 getNode(CallValue) + CallReturnPos,
1273 UniversalSet));
1274#endif
1275
1276
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001277 }
1278
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001279 CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
Daniel Berlinb68539d2008-03-18 22:22:53 +00001280 bool external = !F || F->isDeclaration();
Daniel Berlin385bda62007-09-16 21:45:02 +00001281 if (F) {
1282 // Direct Call
1283 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
Daniel Berlinb68539d2008-03-18 22:22:53 +00001284 for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI)
1285 {
1286#if !FULL_UNIVERSAL
1287 if (external && isa<PointerType>((*ArgI)->getType()))
1288 {
1289 // Add constraint that ArgI can now point to anything due to
1290 // escaping, as can everything it points to. The second portion of
1291 // this should be taken care of by universal = *universal
1292 Constraints.push_back(Constraint(Constraint::Copy,
1293 getNode(*ArgI),
1294 UniversalSet));
1295 }
Daniel Berlinc6fd7722007-12-12 00:37:04 +00001296#endif
Daniel Berlinb68539d2008-03-18 22:22:53 +00001297 if (isa<PointerType>(AI->getType())) {
1298 if (isa<PointerType>((*ArgI)->getType())) {
1299 // Copy the actual argument into the formal argument.
1300 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1301 getNode(*ArgI)));
1302 } else {
1303 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1304 UniversalSet));
1305 }
1306 } else if (isa<PointerType>((*ArgI)->getType())) {
1307#if FULL_UNIVERSAL
1308 Constraints.push_back(Constraint(Constraint::Copy,
1309 UniversalSet,
1310 getNode(*ArgI)));
1311#else
1312 Constraints.push_back(Constraint(Constraint::Copy,
1313 getNode(*ArgI),
1314 UniversalSet));
1315#endif
1316 }
Daniel Berlin385bda62007-09-16 21:45:02 +00001317 }
1318 } else {
1319 //Indirect Call
1320 unsigned ArgPos = CallFirstArgPos;
1321 for (; ArgI != ArgE; ++ArgI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001322 if (isa<PointerType>((*ArgI)->getType())) {
1323 // Copy the actual argument into the formal argument.
Daniel Berlin385bda62007-09-16 21:45:02 +00001324 Constraints.push_back(Constraint(Constraint::Store,
1325 getNode(CallValue),
1326 getNode(*ArgI), ArgPos++));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001327 } else {
Daniel Berlin385bda62007-09-16 21:45:02 +00001328 Constraints.push_back(Constraint(Constraint::Store,
1329 getNode (CallValue),
1330 UniversalSet, ArgPos++));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001331 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001332 }
Daniel Berlin385bda62007-09-16 21:45:02 +00001333 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001334 // Copy all pointers passed through the varargs section to the varargs node.
Daniel Berlin385bda62007-09-16 21:45:02 +00001335 if (F && F->getFunctionType()->isVarArg())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001336 for (; ArgI != ArgE; ++ArgI)
1337 if (isa<PointerType>((*ArgI)->getType()))
1338 Constraints.push_back(Constraint(Constraint::Copy, getVarargNode(F),
1339 getNode(*ArgI)));
1340 // If more arguments are passed in than we track, just drop them on the floor.
1341}
1342
1343void Andersens::visitCallSite(CallSite CS) {
1344 if (isa<PointerType>(CS.getType()))
1345 getNodeValue(*CS.getInstruction());
1346
1347 if (Function *F = CS.getCalledFunction()) {
1348 AddConstraintsForCall(CS, F);
1349 } else {
Daniel Berlin385bda62007-09-16 21:45:02 +00001350 AddConstraintsForCall(CS, NULL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001351 }
1352}
1353
1354//===----------------------------------------------------------------------===//
1355// Constraint Solving Phase
1356//===----------------------------------------------------------------------===//
1357
1358/// intersects - Return true if the points-to set of this node intersects
1359/// with the points-to set of the specified node.
1360bool Andersens::Node::intersects(Node *N) const {
Daniel Berlin385bda62007-09-16 21:45:02 +00001361 return PointsTo->intersects(N->PointsTo);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001362}
1363
1364/// intersectsIgnoring - Return true if the points-to set of this node
1365/// intersects with the points-to set of the specified node on any nodes
1366/// except for the specified node to ignore.
Daniel Berlin385bda62007-09-16 21:45:02 +00001367bool Andersens::Node::intersectsIgnoring(Node *N, unsigned Ignoring) const {
1368 // TODO: If we are only going to call this with the same value for Ignoring,
1369 // we should move the special values out of the points-to bitmap.
1370 bool WeHadIt = PointsTo->test(Ignoring);
1371 bool NHadIt = N->PointsTo->test(Ignoring);
1372 bool Result = false;
1373 if (WeHadIt)
1374 PointsTo->reset(Ignoring);
1375 if (NHadIt)
1376 N->PointsTo->reset(Ignoring);
1377 Result = PointsTo->intersects(N->PointsTo);
1378 if (WeHadIt)
1379 PointsTo->set(Ignoring);
1380 if (NHadIt)
1381 N->PointsTo->set(Ignoring);
1382 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001383}
1384
Daniel Berlinb53270f2007-09-24 19:45:49 +00001385void dumpToDOUT(SparseBitVector<> *bitmap) {
Bill Wendling38ddbac2007-09-24 22:43:48 +00001386#ifndef NDEBUG
Daniel Berlinb53270f2007-09-24 19:45:49 +00001387 dump(*bitmap, DOUT);
Bill Wendling38ddbac2007-09-24 22:43:48 +00001388#endif
Daniel Berlinb53270f2007-09-24 19:45:49 +00001389}
1390
1391
1392/// Clump together address taken variables so that the points-to sets use up
1393/// less space and can be operated on faster.
1394
1395void Andersens::ClumpAddressTaken() {
1396#undef DEBUG_TYPE
1397#define DEBUG_TYPE "anders-aa-renumber"
1398 std::vector<unsigned> Translate;
1399 std::vector<Node> NewGraphNodes;
1400
1401 Translate.resize(GraphNodes.size());
1402 unsigned NewPos = 0;
1403
1404 for (unsigned i = 0; i < Constraints.size(); ++i) {
1405 Constraint &C = Constraints[i];
1406 if (C.Type == Constraint::AddressOf) {
1407 GraphNodes[C.Src].AddressTaken = true;
1408 }
1409 }
1410 for (unsigned i = 0; i < NumberSpecialNodes; ++i) {
1411 unsigned Pos = NewPos++;
1412 Translate[i] = Pos;
1413 NewGraphNodes.push_back(GraphNodes[i]);
1414 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1415 }
1416
1417 // I believe this ends up being faster than making two vectors and splicing
1418 // them.
1419 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1420 if (GraphNodes[i].AddressTaken) {
1421 unsigned Pos = NewPos++;
1422 Translate[i] = Pos;
1423 NewGraphNodes.push_back(GraphNodes[i]);
1424 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1425 }
1426 }
1427
1428 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1429 if (!GraphNodes[i].AddressTaken) {
1430 unsigned Pos = NewPos++;
1431 Translate[i] = Pos;
1432 NewGraphNodes.push_back(GraphNodes[i]);
1433 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1434 }
1435 }
1436
1437 for (DenseMap<Value*, unsigned>::iterator Iter = ValueNodes.begin();
1438 Iter != ValueNodes.end();
1439 ++Iter)
1440 Iter->second = Translate[Iter->second];
1441
1442 for (DenseMap<Value*, unsigned>::iterator Iter = ObjectNodes.begin();
1443 Iter != ObjectNodes.end();
1444 ++Iter)
1445 Iter->second = Translate[Iter->second];
1446
1447 for (DenseMap<Function*, unsigned>::iterator Iter = ReturnNodes.begin();
1448 Iter != ReturnNodes.end();
1449 ++Iter)
1450 Iter->second = Translate[Iter->second];
1451
1452 for (DenseMap<Function*, unsigned>::iterator Iter = VarargNodes.begin();
1453 Iter != VarargNodes.end();
1454 ++Iter)
1455 Iter->second = Translate[Iter->second];
1456
1457 for (unsigned i = 0; i < Constraints.size(); ++i) {
1458 Constraint &C = Constraints[i];
1459 C.Src = Translate[C.Src];
1460 C.Dest = Translate[C.Dest];
1461 }
1462
1463 GraphNodes.swap(NewGraphNodes);
1464#undef DEBUG_TYPE
1465#define DEBUG_TYPE "anders-aa"
1466}
1467
1468/// The technique used here is described in "Exploiting Pointer and Location
1469/// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1470/// Analysis Symposium (SAS), August 2007." It is known as the "HVN" algorithm,
1471/// and is equivalent to value numbering the collapsed constraint graph without
1472/// evaluating unions. This is used as a pre-pass to HU in order to resolve
1473/// first order pointer dereferences and speed up/reduce memory usage of HU.
1474/// Running both is equivalent to HRU without the iteration
1475/// HVN in more detail:
1476/// Imagine the set of constraints was simply straight line code with no loops
1477/// (we eliminate cycles, so there are no loops), such as:
1478/// E = &D
1479/// E = &C
1480/// E = F
1481/// F = G
1482/// G = F
1483/// Applying value numbering to this code tells us:
1484/// G == F == E
1485///
1486/// For HVN, this is as far as it goes. We assign new value numbers to every
1487/// "address node", and every "reference node".
1488/// To get the optimal result for this, we use a DFS + SCC (since all nodes in a
1489/// cycle must have the same value number since the = operation is really
1490/// inclusion, not overwrite), and value number nodes we receive points-to sets
1491/// before we value our own node.
1492/// The advantage of HU over HVN is that HU considers the inclusion property, so
1493/// that if you have
1494/// E = &D
1495/// E = &C
1496/// E = F
1497/// F = G
1498/// F = &D
1499/// G = F
1500/// HU will determine that G == F == E. HVN will not, because it cannot prove
1501/// that the points to information ends up being the same because they all
1502/// receive &D from E anyway.
1503
1504void Andersens::HVN() {
1505 DOUT << "Beginning HVN\n";
1506 // Build a predecessor graph. This is like our constraint graph with the
1507 // edges going in the opposite direction, and there are edges for all the
1508 // constraints, instead of just copy constraints. We also build implicit
1509 // edges for constraints are implied but not explicit. I.E for the constraint
1510 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1511 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1512 Constraint &C = Constraints[i];
1513 if (C.Type == Constraint::AddressOf) {
1514 GraphNodes[C.Src].AddressTaken = true;
1515 GraphNodes[C.Src].Direct = false;
1516
1517 // Dest = &src edge
1518 unsigned AdrNode = C.Src + FirstAdrNode;
1519 if (!GraphNodes[C.Dest].PredEdges)
1520 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1521 GraphNodes[C.Dest].PredEdges->set(AdrNode);
1522
1523 // *Dest = src edge
1524 unsigned RefNode = C.Dest + FirstRefNode;
1525 if (!GraphNodes[RefNode].ImplicitPredEdges)
1526 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1527 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1528 } else if (C.Type == Constraint::Load) {
1529 if (C.Offset == 0) {
1530 // dest = *src edge
1531 if (!GraphNodes[C.Dest].PredEdges)
1532 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1533 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1534 } else {
1535 GraphNodes[C.Dest].Direct = false;
1536 }
1537 } else if (C.Type == Constraint::Store) {
1538 if (C.Offset == 0) {
1539 // *dest = src edge
1540 unsigned RefNode = C.Dest + FirstRefNode;
1541 if (!GraphNodes[RefNode].PredEdges)
1542 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1543 GraphNodes[RefNode].PredEdges->set(C.Src);
1544 }
1545 } else {
1546 // Dest = Src edge and *Dest = *Src edge
1547 if (!GraphNodes[C.Dest].PredEdges)
1548 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1549 GraphNodes[C.Dest].PredEdges->set(C.Src);
1550 unsigned RefNode = C.Dest + FirstRefNode;
1551 if (!GraphNodes[RefNode].ImplicitPredEdges)
1552 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1553 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1554 }
1555 }
1556 PEClass = 1;
1557 // Do SCC finding first to condense our predecessor graph
1558 DFSNumber = 0;
1559 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1560 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1561 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1562
1563 for (unsigned i = 0; i < FirstRefNode; ++i) {
1564 unsigned Node = VSSCCRep[i];
1565 if (!Node2Visited[Node])
1566 HVNValNum(Node);
1567 }
1568 for (BitVectorMap::iterator Iter = Set2PEClass.begin();
1569 Iter != Set2PEClass.end();
1570 ++Iter)
1571 delete Iter->first;
1572 Set2PEClass.clear();
1573 Node2DFS.clear();
1574 Node2Deleted.clear();
1575 Node2Visited.clear();
1576 DOUT << "Finished HVN\n";
1577
1578}
1579
1580/// This is the workhorse of HVN value numbering. We combine SCC finding at the
1581/// same time because it's easy.
1582void Andersens::HVNValNum(unsigned NodeIndex) {
1583 unsigned MyDFS = DFSNumber++;
1584 Node *N = &GraphNodes[NodeIndex];
1585 Node2Visited[NodeIndex] = true;
1586 Node2DFS[NodeIndex] = MyDFS;
1587
1588 // First process all our explicit edges
1589 if (N->PredEdges)
1590 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1591 Iter != N->PredEdges->end();
1592 ++Iter) {
1593 unsigned j = VSSCCRep[*Iter];
1594 if (!Node2Deleted[j]) {
1595 if (!Node2Visited[j])
1596 HVNValNum(j);
1597 if (Node2DFS[NodeIndex] > Node2DFS[j])
1598 Node2DFS[NodeIndex] = Node2DFS[j];
1599 }
1600 }
1601
1602 // Now process all the implicit edges
1603 if (N->ImplicitPredEdges)
1604 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1605 Iter != N->ImplicitPredEdges->end();
1606 ++Iter) {
1607 unsigned j = VSSCCRep[*Iter];
1608 if (!Node2Deleted[j]) {
1609 if (!Node2Visited[j])
1610 HVNValNum(j);
1611 if (Node2DFS[NodeIndex] > Node2DFS[j])
1612 Node2DFS[NodeIndex] = Node2DFS[j];
1613 }
1614 }
1615
1616 // See if we found any cycles
1617 if (MyDFS == Node2DFS[NodeIndex]) {
1618 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1619 unsigned CycleNodeIndex = SCCStack.top();
1620 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1621 VSSCCRep[CycleNodeIndex] = NodeIndex;
1622 // Unify the nodes
1623 N->Direct &= CycleNode->Direct;
1624
1625 if (CycleNode->PredEdges) {
1626 if (!N->PredEdges)
1627 N->PredEdges = new SparseBitVector<>;
1628 *(N->PredEdges) |= CycleNode->PredEdges;
1629 delete CycleNode->PredEdges;
1630 CycleNode->PredEdges = NULL;
1631 }
1632 if (CycleNode->ImplicitPredEdges) {
1633 if (!N->ImplicitPredEdges)
1634 N->ImplicitPredEdges = new SparseBitVector<>;
1635 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1636 delete CycleNode->ImplicitPredEdges;
1637 CycleNode->ImplicitPredEdges = NULL;
1638 }
1639
1640 SCCStack.pop();
1641 }
1642
1643 Node2Deleted[NodeIndex] = true;
1644
1645 if (!N->Direct) {
1646 GraphNodes[NodeIndex].PointerEquivLabel = PEClass++;
1647 return;
1648 }
1649
1650 // Collect labels of successor nodes
1651 bool AllSame = true;
1652 unsigned First = ~0;
1653 SparseBitVector<> *Labels = new SparseBitVector<>;
1654 bool Used = false;
1655
1656 if (N->PredEdges)
1657 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1658 Iter != N->PredEdges->end();
1659 ++Iter) {
1660 unsigned j = VSSCCRep[*Iter];
1661 unsigned Label = GraphNodes[j].PointerEquivLabel;
1662 // Ignore labels that are equal to us or non-pointers
1663 if (j == NodeIndex || Label == 0)
1664 continue;
1665 if (First == (unsigned)~0)
1666 First = Label;
1667 else if (First != Label)
1668 AllSame = false;
1669 Labels->set(Label);
1670 }
1671
1672 // We either have a non-pointer, a copy of an existing node, or a new node.
1673 // Assign the appropriate pointer equivalence label.
1674 if (Labels->empty()) {
1675 GraphNodes[NodeIndex].PointerEquivLabel = 0;
1676 } else if (AllSame) {
1677 GraphNodes[NodeIndex].PointerEquivLabel = First;
1678 } else {
1679 GraphNodes[NodeIndex].PointerEquivLabel = Set2PEClass[Labels];
1680 if (GraphNodes[NodeIndex].PointerEquivLabel == 0) {
1681 unsigned EquivClass = PEClass++;
1682 Set2PEClass[Labels] = EquivClass;
1683 GraphNodes[NodeIndex].PointerEquivLabel = EquivClass;
1684 Used = true;
1685 }
1686 }
1687 if (!Used)
1688 delete Labels;
1689 } else {
1690 SCCStack.push(NodeIndex);
1691 }
1692}
1693
1694/// The technique used here is described in "Exploiting Pointer and Location
1695/// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1696/// Analysis Symposium (SAS), August 2007." It is known as the "HU" algorithm,
1697/// and is equivalent to value numbering the collapsed constraint graph
1698/// including evaluating unions.
1699void Andersens::HU() {
1700 DOUT << "Beginning HU\n";
1701 // Build a predecessor graph. This is like our constraint graph with the
1702 // edges going in the opposite direction, and there are edges for all the
1703 // constraints, instead of just copy constraints. We also build implicit
1704 // edges for constraints are implied but not explicit. I.E for the constraint
1705 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1706 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1707 Constraint &C = Constraints[i];
1708 if (C.Type == Constraint::AddressOf) {
1709 GraphNodes[C.Src].AddressTaken = true;
1710 GraphNodes[C.Src].Direct = false;
1711
1712 GraphNodes[C.Dest].PointsTo->set(C.Src);
1713 // *Dest = src edge
1714 unsigned RefNode = C.Dest + FirstRefNode;
1715 if (!GraphNodes[RefNode].ImplicitPredEdges)
1716 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1717 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1718 GraphNodes[C.Src].PointedToBy->set(C.Dest);
1719 } else if (C.Type == Constraint::Load) {
1720 if (C.Offset == 0) {
1721 // dest = *src edge
1722 if (!GraphNodes[C.Dest].PredEdges)
1723 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1724 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1725 } else {
1726 GraphNodes[C.Dest].Direct = false;
1727 }
1728 } else if (C.Type == Constraint::Store) {
1729 if (C.Offset == 0) {
1730 // *dest = src edge
1731 unsigned RefNode = C.Dest + FirstRefNode;
1732 if (!GraphNodes[RefNode].PredEdges)
1733 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1734 GraphNodes[RefNode].PredEdges->set(C.Src);
1735 }
1736 } else {
1737 // Dest = Src edge and *Dest = *Src edg
1738 if (!GraphNodes[C.Dest].PredEdges)
1739 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1740 GraphNodes[C.Dest].PredEdges->set(C.Src);
1741 unsigned RefNode = C.Dest + FirstRefNode;
1742 if (!GraphNodes[RefNode].ImplicitPredEdges)
1743 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1744 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1745 }
1746 }
1747 PEClass = 1;
1748 // Do SCC finding first to condense our predecessor graph
1749 DFSNumber = 0;
1750 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1751 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1752 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1753
1754 for (unsigned i = 0; i < FirstRefNode; ++i) {
1755 if (FindNode(i) == i) {
1756 unsigned Node = VSSCCRep[i];
1757 if (!Node2Visited[Node])
1758 Condense(Node);
1759 }
1760 }
1761
1762 // Reset tables for actual labeling
1763 Node2DFS.clear();
1764 Node2Visited.clear();
1765 Node2Deleted.clear();
1766 // Pre-grow our densemap so that we don't get really bad behavior
1767 Set2PEClass.resize(GraphNodes.size());
1768
1769 // Visit the condensed graph and generate pointer equivalence labels.
1770 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1771 for (unsigned i = 0; i < FirstRefNode; ++i) {
1772 if (FindNode(i) == i) {
1773 unsigned Node = VSSCCRep[i];
1774 if (!Node2Visited[Node])
1775 HUValNum(Node);
1776 }
1777 }
1778 // PEClass nodes will be deleted by the deleting of N->PointsTo in our caller.
1779 Set2PEClass.clear();
1780 DOUT << "Finished HU\n";
1781}
1782
1783
1784/// Implementation of standard Tarjan SCC algorithm as modified by Nuutilla.
1785void Andersens::Condense(unsigned NodeIndex) {
1786 unsigned MyDFS = DFSNumber++;
1787 Node *N = &GraphNodes[NodeIndex];
1788 Node2Visited[NodeIndex] = true;
1789 Node2DFS[NodeIndex] = MyDFS;
1790
1791 // First process all our explicit edges
1792 if (N->PredEdges)
1793 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1794 Iter != N->PredEdges->end();
1795 ++Iter) {
1796 unsigned j = VSSCCRep[*Iter];
1797 if (!Node2Deleted[j]) {
1798 if (!Node2Visited[j])
1799 Condense(j);
1800 if (Node2DFS[NodeIndex] > Node2DFS[j])
1801 Node2DFS[NodeIndex] = Node2DFS[j];
1802 }
1803 }
1804
1805 // Now process all the implicit edges
1806 if (N->ImplicitPredEdges)
1807 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1808 Iter != N->ImplicitPredEdges->end();
1809 ++Iter) {
1810 unsigned j = VSSCCRep[*Iter];
1811 if (!Node2Deleted[j]) {
1812 if (!Node2Visited[j])
1813 Condense(j);
1814 if (Node2DFS[NodeIndex] > Node2DFS[j])
1815 Node2DFS[NodeIndex] = Node2DFS[j];
1816 }
1817 }
1818
1819 // See if we found any cycles
1820 if (MyDFS == Node2DFS[NodeIndex]) {
1821 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1822 unsigned CycleNodeIndex = SCCStack.top();
1823 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1824 VSSCCRep[CycleNodeIndex] = NodeIndex;
1825 // Unify the nodes
1826 N->Direct &= CycleNode->Direct;
1827
1828 *(N->PointsTo) |= CycleNode->PointsTo;
1829 delete CycleNode->PointsTo;
1830 CycleNode->PointsTo = NULL;
1831 if (CycleNode->PredEdges) {
1832 if (!N->PredEdges)
1833 N->PredEdges = new SparseBitVector<>;
1834 *(N->PredEdges) |= CycleNode->PredEdges;
1835 delete CycleNode->PredEdges;
1836 CycleNode->PredEdges = NULL;
1837 }
1838 if (CycleNode->ImplicitPredEdges) {
1839 if (!N->ImplicitPredEdges)
1840 N->ImplicitPredEdges = new SparseBitVector<>;
1841 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1842 delete CycleNode->ImplicitPredEdges;
1843 CycleNode->ImplicitPredEdges = NULL;
1844 }
1845 SCCStack.pop();
1846 }
1847
1848 Node2Deleted[NodeIndex] = true;
1849
1850 // Set up number of incoming edges for other nodes
1851 if (N->PredEdges)
1852 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1853 Iter != N->PredEdges->end();
1854 ++Iter)
1855 ++GraphNodes[VSSCCRep[*Iter]].NumInEdges;
1856 } else {
1857 SCCStack.push(NodeIndex);
1858 }
1859}
1860
1861void Andersens::HUValNum(unsigned NodeIndex) {
1862 Node *N = &GraphNodes[NodeIndex];
1863 Node2Visited[NodeIndex] = true;
1864
1865 // Eliminate dereferences of non-pointers for those non-pointers we have
1866 // already identified. These are ref nodes whose non-ref node:
1867 // 1. Has already been visited determined to point to nothing (and thus, a
1868 // dereference of it must point to nothing)
1869 // 2. Any direct node with no predecessor edges in our graph and with no
1870 // points-to set (since it can't point to anything either, being that it
1871 // receives no points-to sets and has none).
1872 if (NodeIndex >= FirstRefNode) {
1873 unsigned j = VSSCCRep[FindNode(NodeIndex - FirstRefNode)];
1874 if ((Node2Visited[j] && !GraphNodes[j].PointerEquivLabel)
1875 || (GraphNodes[j].Direct && !GraphNodes[j].PredEdges
1876 && GraphNodes[j].PointsTo->empty())){
1877 return;
1878 }
1879 }
1880 // Process all our explicit edges
1881 if (N->PredEdges)
1882 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1883 Iter != N->PredEdges->end();
1884 ++Iter) {
1885 unsigned j = VSSCCRep[*Iter];
1886 if (!Node2Visited[j])
1887 HUValNum(j);
1888
1889 // If this edge turned out to be the same as us, or got no pointer
1890 // equivalence label (and thus points to nothing) , just decrement our
1891 // incoming edges and continue.
1892 if (j == NodeIndex || GraphNodes[j].PointerEquivLabel == 0) {
1893 --GraphNodes[j].NumInEdges;
1894 continue;
1895 }
1896
1897 *(N->PointsTo) |= GraphNodes[j].PointsTo;
1898
1899 // If we didn't end up storing this in the hash, and we're done with all
1900 // the edges, we don't need the points-to set anymore.
1901 --GraphNodes[j].NumInEdges;
1902 if (!GraphNodes[j].NumInEdges && !GraphNodes[j].StoredInHash) {
1903 delete GraphNodes[j].PointsTo;
1904 GraphNodes[j].PointsTo = NULL;
1905 }
1906 }
1907 // If this isn't a direct node, generate a fresh variable.
1908 if (!N->Direct) {
1909 N->PointsTo->set(FirstRefNode + NodeIndex);
1910 }
1911
1912 // See If we have something equivalent to us, if not, generate a new
1913 // equivalence class.
1914 if (N->PointsTo->empty()) {
1915 delete N->PointsTo;
1916 N->PointsTo = NULL;
1917 } else {
1918 if (N->Direct) {
1919 N->PointerEquivLabel = Set2PEClass[N->PointsTo];
1920 if (N->PointerEquivLabel == 0) {
1921 unsigned EquivClass = PEClass++;
1922 N->StoredInHash = true;
1923 Set2PEClass[N->PointsTo] = EquivClass;
1924 N->PointerEquivLabel = EquivClass;
1925 }
1926 } else {
1927 N->PointerEquivLabel = PEClass++;
1928 }
1929 }
1930}
1931
1932/// Rewrite our list of constraints so that pointer equivalent nodes are
1933/// replaced by their the pointer equivalence class representative.
1934void Andersens::RewriteConstraints() {
1935 std::vector<Constraint> NewConstraints;
Chris Lattner4cf3c502007-09-30 00:47:20 +00001936 DenseSet<Constraint, ConstraintKeyInfo> Seen;
Daniel Berlinb53270f2007-09-24 19:45:49 +00001937
1938 PEClass2Node.clear();
1939 PENLEClass2Node.clear();
1940
1941 // We may have from 1 to Graphnodes + 1 equivalence classes.
1942 PEClass2Node.insert(PEClass2Node.begin(), GraphNodes.size() + 1, -1);
1943 PENLEClass2Node.insert(PENLEClass2Node.begin(), GraphNodes.size() + 1, -1);
1944
1945 // Rewrite constraints, ignoring non-pointer constraints, uniting equivalent
1946 // nodes, and rewriting constraints to use the representative nodes.
1947 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1948 Constraint &C = Constraints[i];
1949 unsigned RHSNode = FindNode(C.Src);
1950 unsigned LHSNode = FindNode(C.Dest);
1951 unsigned RHSLabel = GraphNodes[VSSCCRep[RHSNode]].PointerEquivLabel;
1952 unsigned LHSLabel = GraphNodes[VSSCCRep[LHSNode]].PointerEquivLabel;
1953
1954 // First we try to eliminate constraints for things we can prove don't point
1955 // to anything.
1956 if (LHSLabel == 0) {
1957 DEBUG(PrintNode(&GraphNodes[LHSNode]));
1958 DOUT << " is a non-pointer, ignoring constraint.\n";
1959 continue;
1960 }
1961 if (RHSLabel == 0) {
1962 DEBUG(PrintNode(&GraphNodes[RHSNode]));
1963 DOUT << " is a non-pointer, ignoring constraint.\n";
1964 continue;
1965 }
1966 // This constraint may be useless, and it may become useless as we translate
1967 // it.
1968 if (C.Src == C.Dest && C.Type == Constraint::Copy)
1969 continue;
Daniel Berline87fe282007-09-27 15:42:23 +00001970
Daniel Berlinb53270f2007-09-24 19:45:49 +00001971 C.Src = FindEquivalentNode(RHSNode, RHSLabel);
1972 C.Dest = FindEquivalentNode(FindNode(LHSNode), LHSLabel);
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00001973 if ((C.Src == C.Dest && C.Type == Constraint::Copy)
Chris Lattner4cf3c502007-09-30 00:47:20 +00001974 || Seen.count(C))
Daniel Berlinb53270f2007-09-24 19:45:49 +00001975 continue;
1976
Chris Lattner4cf3c502007-09-30 00:47:20 +00001977 Seen.insert(C);
Daniel Berlinb53270f2007-09-24 19:45:49 +00001978 NewConstraints.push_back(C);
1979 }
1980 Constraints.swap(NewConstraints);
1981 PEClass2Node.clear();
1982}
1983
1984/// See if we have a node that is pointer equivalent to the one being asked
1985/// about, and if so, unite them and return the equivalent node. Otherwise,
1986/// return the original node.
1987unsigned Andersens::FindEquivalentNode(unsigned NodeIndex,
1988 unsigned NodeLabel) {
1989 if (!GraphNodes[NodeIndex].AddressTaken) {
1990 if (PEClass2Node[NodeLabel] != -1) {
1991 // We found an existing node with the same pointer label, so unify them.
Daniel Berlinc6fd7722007-12-12 00:37:04 +00001992 // We specifically request that Union-By-Rank not be used so that
1993 // PEClass2Node[NodeLabel] U= NodeIndex and not the other way around.
1994 return UniteNodes(PEClass2Node[NodeLabel], NodeIndex, false);
Daniel Berlinb53270f2007-09-24 19:45:49 +00001995 } else {
1996 PEClass2Node[NodeLabel] = NodeIndex;
1997 PENLEClass2Node[NodeLabel] = NodeIndex;
1998 }
1999 } else if (PENLEClass2Node[NodeLabel] == -1) {
2000 PENLEClass2Node[NodeLabel] = NodeIndex;
2001 }
2002
2003 return NodeIndex;
2004}
2005
Andrew Lenharthdce39302008-03-20 15:36:44 +00002006void Andersens::PrintLabels() const {
Daniel Berlinb53270f2007-09-24 19:45:49 +00002007 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2008 if (i < FirstRefNode) {
2009 PrintNode(&GraphNodes[i]);
2010 } else if (i < FirstAdrNode) {
2011 DOUT << "REF(";
2012 PrintNode(&GraphNodes[i-FirstRefNode]);
2013 DOUT <<")";
2014 } else {
2015 DOUT << "ADR(";
2016 PrintNode(&GraphNodes[i-FirstAdrNode]);
2017 DOUT <<")";
2018 }
2019
2020 DOUT << " has pointer label " << GraphNodes[i].PointerEquivLabel
2021 << " and SCC rep " << VSSCCRep[i]
2022 << " and is " << (GraphNodes[i].Direct ? "Direct" : "Not direct")
2023 << "\n";
2024 }
2025}
2026
Daniel Berlined95dd02008-03-05 19:31:47 +00002027/// The technique used here is described in "The Ant and the
2028/// Grasshopper: Fast and Accurate Pointer Analysis for Millions of
2029/// Lines of Code. In Programming Language Design and Implementation
2030/// (PLDI), June 2007." It is known as the "HCD" (Hybrid Cycle
2031/// Detection) algorithm. It is called a hybrid because it performs an
2032/// offline analysis and uses its results during the solving (online)
2033/// phase. This is just the offline portion; the results of this
2034/// operation are stored in SDT and are later used in SolveContraints()
2035/// and UniteNodes().
2036void Andersens::HCD() {
2037 DOUT << "Starting HCD.\n";
2038 HCDSCCRep.resize(GraphNodes.size());
2039
2040 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2041 GraphNodes[i].Edges = new SparseBitVector<>;
2042 HCDSCCRep[i] = i;
2043 }
2044
2045 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2046 Constraint &C = Constraints[i];
2047 assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
2048 if (C.Type == Constraint::AddressOf) {
2049 continue;
2050 } else if (C.Type == Constraint::Load) {
2051 if( C.Offset == 0 )
2052 GraphNodes[C.Dest].Edges->set(C.Src + FirstRefNode);
2053 } else if (C.Type == Constraint::Store) {
2054 if( C.Offset == 0 )
2055 GraphNodes[C.Dest + FirstRefNode].Edges->set(C.Src);
2056 } else {
2057 GraphNodes[C.Dest].Edges->set(C.Src);
2058 }
2059 }
2060
2061 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2062 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2063 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
2064 SDT.insert(SDT.begin(), GraphNodes.size() / 2, -1);
2065
2066 DFSNumber = 0;
2067 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2068 unsigned Node = HCDSCCRep[i];
2069 if (!Node2Deleted[Node])
2070 Search(Node);
2071 }
2072
2073 for (unsigned i = 0; i < GraphNodes.size(); ++i)
2074 if (GraphNodes[i].Edges != NULL) {
2075 delete GraphNodes[i].Edges;
2076 GraphNodes[i].Edges = NULL;
2077 }
2078
2079 while( !SCCStack.empty() )
2080 SCCStack.pop();
2081
2082 Node2DFS.clear();
2083 Node2Visited.clear();
2084 Node2Deleted.clear();
2085 HCDSCCRep.clear();
2086 DOUT << "HCD complete.\n";
2087}
2088
2089// Component of HCD:
2090// Use Nuutila's variant of Tarjan's algorithm to detect
2091// Strongly-Connected Components (SCCs). For non-trivial SCCs
2092// containing ref nodes, insert the appropriate information in SDT.
2093void Andersens::Search(unsigned Node) {
2094 unsigned MyDFS = DFSNumber++;
2095
2096 Node2Visited[Node] = true;
2097 Node2DFS[Node] = MyDFS;
2098
2099 for (SparseBitVector<>::iterator Iter = GraphNodes[Node].Edges->begin(),
2100 End = GraphNodes[Node].Edges->end();
2101 Iter != End;
2102 ++Iter) {
2103 unsigned J = HCDSCCRep[*Iter];
2104 assert(GraphNodes[J].isRep() && "Debug check; must be representative");
2105 if (!Node2Deleted[J]) {
2106 if (!Node2Visited[J])
2107 Search(J);
2108 if (Node2DFS[Node] > Node2DFS[J])
2109 Node2DFS[Node] = Node2DFS[J];
2110 }
2111 }
2112
2113 if( MyDFS != Node2DFS[Node] ) {
2114 SCCStack.push(Node);
2115 return;
2116 }
2117
2118 // This node is the root of a SCC, so process it.
2119 //
2120 // If the SCC is "non-trivial" (not a singleton) and contains a reference
2121 // node, we place this SCC into SDT. We unite the nodes in any case.
2122 if (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
2123 SparseBitVector<> SCC;
2124
2125 SCC.set(Node);
2126
2127 bool Ref = (Node >= FirstRefNode);
2128
2129 Node2Deleted[Node] = true;
2130
2131 do {
2132 unsigned P = SCCStack.top(); SCCStack.pop();
2133 Ref |= (P >= FirstRefNode);
2134 SCC.set(P);
2135 HCDSCCRep[P] = Node;
2136 } while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS);
2137
2138 if (Ref) {
2139 unsigned Rep = SCC.find_first();
2140 assert(Rep < FirstRefNode && "The SCC didn't have a non-Ref node!");
2141
2142 SparseBitVector<>::iterator i = SCC.begin();
2143
2144 // Skip over the non-ref nodes
2145 while( *i < FirstRefNode )
2146 ++i;
2147
2148 while( i != SCC.end() )
2149 SDT[ (*i++) - FirstRefNode ] = Rep;
2150 }
2151 }
2152}
2153
2154
Daniel Berlinb53270f2007-09-24 19:45:49 +00002155/// Optimize the constraints by performing offline variable substitution and
2156/// other optimizations.
2157void Andersens::OptimizeConstraints() {
2158 DOUT << "Beginning constraint optimization\n";
2159
Daniel Berlined95dd02008-03-05 19:31:47 +00002160 SDTActive = false;
2161
Daniel Berlinb53270f2007-09-24 19:45:49 +00002162 // Function related nodes need to stay in the same relative position and can't
2163 // be location equivalent.
2164 for (std::map<unsigned, unsigned>::iterator Iter = MaxK.begin();
2165 Iter != MaxK.end();
2166 ++Iter) {
2167 for (unsigned i = Iter->first;
2168 i != Iter->first + Iter->second;
2169 ++i) {
2170 GraphNodes[i].AddressTaken = true;
2171 GraphNodes[i].Direct = false;
2172 }
2173 }
2174
2175 ClumpAddressTaken();
2176 FirstRefNode = GraphNodes.size();
2177 FirstAdrNode = FirstRefNode + GraphNodes.size();
2178 GraphNodes.insert(GraphNodes.end(), 2 * GraphNodes.size(),
2179 Node(false));
2180 VSSCCRep.resize(GraphNodes.size());
2181 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2182 VSSCCRep[i] = i;
2183 }
2184 HVN();
2185 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2186 Node *N = &GraphNodes[i];
2187 delete N->PredEdges;
2188 N->PredEdges = NULL;
2189 delete N->ImplicitPredEdges;
2190 N->ImplicitPredEdges = NULL;
2191 }
2192#undef DEBUG_TYPE
2193#define DEBUG_TYPE "anders-aa-labels"
2194 DEBUG(PrintLabels());
2195#undef DEBUG_TYPE
2196#define DEBUG_TYPE "anders-aa"
2197 RewriteConstraints();
2198 // Delete the adr nodes.
2199 GraphNodes.resize(FirstRefNode * 2);
2200
2201 // Now perform HU
2202 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2203 Node *N = &GraphNodes[i];
2204 if (FindNode(i) == i) {
2205 N->PointsTo = new SparseBitVector<>;
2206 N->PointedToBy = new SparseBitVector<>;
2207 // Reset our labels
2208 }
2209 VSSCCRep[i] = i;
2210 N->PointerEquivLabel = 0;
2211 }
2212 HU();
2213#undef DEBUG_TYPE
2214#define DEBUG_TYPE "anders-aa-labels"
2215 DEBUG(PrintLabels());
2216#undef DEBUG_TYPE
2217#define DEBUG_TYPE "anders-aa"
2218 RewriteConstraints();
2219 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2220 if (FindNode(i) == i) {
2221 Node *N = &GraphNodes[i];
2222 delete N->PointsTo;
Daniel Berlined95dd02008-03-05 19:31:47 +00002223 N->PointsTo = NULL;
Daniel Berlinb53270f2007-09-24 19:45:49 +00002224 delete N->PredEdges;
Daniel Berlined95dd02008-03-05 19:31:47 +00002225 N->PredEdges = NULL;
Daniel Berlinb53270f2007-09-24 19:45:49 +00002226 delete N->ImplicitPredEdges;
Daniel Berlined95dd02008-03-05 19:31:47 +00002227 N->ImplicitPredEdges = NULL;
Daniel Berlinb53270f2007-09-24 19:45:49 +00002228 delete N->PointedToBy;
Daniel Berlined95dd02008-03-05 19:31:47 +00002229 N->PointedToBy = NULL;
Daniel Berlinb53270f2007-09-24 19:45:49 +00002230 }
2231 }
Daniel Berlined95dd02008-03-05 19:31:47 +00002232
2233 // perform Hybrid Cycle Detection (HCD)
2234 HCD();
2235 SDTActive = true;
2236
2237 // No longer any need for the upper half of GraphNodes (for ref nodes).
Daniel Berlinb53270f2007-09-24 19:45:49 +00002238 GraphNodes.erase(GraphNodes.begin() + FirstRefNode, GraphNodes.end());
Daniel Berlined95dd02008-03-05 19:31:47 +00002239
2240 // HCD complete.
2241
Daniel Berlinb53270f2007-09-24 19:45:49 +00002242 DOUT << "Finished constraint optimization\n";
2243 FirstRefNode = 0;
2244 FirstAdrNode = 0;
2245}
2246
2247/// Unite pointer but not location equivalent variables, now that the constraint
2248/// graph is built.
2249void Andersens::UnitePointerEquivalences() {
2250 DOUT << "Uniting remaining pointer equivalences\n";
2251 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002252 if (GraphNodes[i].AddressTaken && GraphNodes[i].isRep()) {
Daniel Berlinb53270f2007-09-24 19:45:49 +00002253 unsigned Label = GraphNodes[i].PointerEquivLabel;
2254
2255 if (Label && PENLEClass2Node[Label] != -1)
2256 UniteNodes(i, PENLEClass2Node[Label]);
2257 }
2258 }
2259 DOUT << "Finished remaining pointer equivalences\n";
2260 PENLEClass2Node.clear();
2261}
2262
2263/// Create the constraint graph used for solving points-to analysis.
2264///
Daniel Berlin385bda62007-09-16 21:45:02 +00002265void Andersens::CreateConstraintGraph() {
2266 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2267 Constraint &C = Constraints[i];
2268 assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
2269 if (C.Type == Constraint::AddressOf)
2270 GraphNodes[C.Dest].PointsTo->set(C.Src);
2271 else if (C.Type == Constraint::Load)
2272 GraphNodes[C.Src].Constraints.push_back(C);
2273 else if (C.Type == Constraint::Store)
2274 GraphNodes[C.Dest].Constraints.push_back(C);
2275 else if (C.Offset != 0)
2276 GraphNodes[C.Src].Constraints.push_back(C);
2277 else
2278 GraphNodes[C.Src].Edges->set(C.Dest);
2279 }
2280}
2281
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002282// Perform DFS and cycle detection.
2283bool Andersens::QueryNode(unsigned Node) {
2284 assert(GraphNodes[Node].isRep() && "Querying a non-rep node");
Daniel Berlin385bda62007-09-16 21:45:02 +00002285 unsigned OurDFS = ++DFSNumber;
2286 SparseBitVector<> ToErase;
2287 SparseBitVector<> NewEdges;
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002288 Tarjan2DFS[Node] = OurDFS;
2289
2290 // Changed denotes a change from a recursive call that we will bubble up.
2291 // Merged is set if we actually merge a node ourselves.
2292 bool Changed = false, Merged = false;
Daniel Berlin385bda62007-09-16 21:45:02 +00002293
2294 for (SparseBitVector<>::iterator bi = GraphNodes[Node].Edges->begin();
2295 bi != GraphNodes[Node].Edges->end();
2296 ++bi) {
2297 unsigned RepNode = FindNode(*bi);
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002298 // If this edge points to a non-representative node but we are
2299 // already planning to add an edge to its representative, we have no
2300 // need for this edge anymore.
Daniel Berlin385bda62007-09-16 21:45:02 +00002301 if (RepNode != *bi && NewEdges.test(RepNode)){
2302 ToErase.set(*bi);
2303 continue;
2304 }
2305
2306 // Continue about our DFS.
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002307 if (!Tarjan2Deleted[RepNode]){
2308 if (Tarjan2DFS[RepNode] == 0) {
2309 Changed |= QueryNode(RepNode);
2310 // May have been changed by QueryNode
Daniel Berlin385bda62007-09-16 21:45:02 +00002311 RepNode = FindNode(RepNode);
2312 }
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002313 if (Tarjan2DFS[RepNode] < Tarjan2DFS[Node])
2314 Tarjan2DFS[Node] = Tarjan2DFS[RepNode];
Daniel Berlin385bda62007-09-16 21:45:02 +00002315 }
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002316
2317 // We may have just discovered that this node is part of a cycle, in
2318 // which case we can also erase it.
Daniel Berlin385bda62007-09-16 21:45:02 +00002319 if (RepNode != *bi) {
2320 ToErase.set(*bi);
2321 NewEdges.set(RepNode);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002322 }
2323 }
2324
Daniel Berlin385bda62007-09-16 21:45:02 +00002325 GraphNodes[Node].Edges->intersectWithComplement(ToErase);
2326 GraphNodes[Node].Edges |= NewEdges;
2327
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002328 // If this node is a root of a non-trivial SCC, place it on our
2329 // worklist to be processed.
2330 if (OurDFS == Tarjan2DFS[Node]) {
2331 while (!SCCStack.empty() && Tarjan2DFS[SCCStack.top()] >= OurDFS) {
2332 Node = UniteNodes(Node, SCCStack.top());
Daniel Berlin385bda62007-09-16 21:45:02 +00002333
2334 SCCStack.pop();
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002335 Merged = true;
Daniel Berlin385bda62007-09-16 21:45:02 +00002336 }
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002337 Tarjan2Deleted[Node] = true;
Daniel Berlin385bda62007-09-16 21:45:02 +00002338
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002339 if (Merged)
2340 NextWL->insert(&GraphNodes[Node]);
Daniel Berlin385bda62007-09-16 21:45:02 +00002341 } else {
2342 SCCStack.push(Node);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002343 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002344
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002345 return(Changed | Merged);
2346}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002347
2348/// SolveConstraints - This stage iteratively processes the constraints list
2349/// propagating constraints (adding edges to the Nodes in the points-to graph)
2350/// until a fixed point is reached.
2351///
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002352/// We use a variant of the technique called "Lazy Cycle Detection", which is
2353/// described in "The Ant and the Grasshopper: Fast and Accurate Pointer
2354/// Analysis for Millions of Lines of Code. In Programming Language Design and
2355/// Implementation (PLDI), June 2007."
2356/// The paper describes performing cycle detection one node at a time, which can
2357/// be expensive if there are no cycles, but there are long chains of nodes that
2358/// it heuristically believes are cycles (because it will DFS from each node
2359/// without state from previous nodes).
2360/// Instead, we use the heuristic to build a worklist of nodes to check, then
2361/// cycle detect them all at the same time to do this more cheaply. This
2362/// catches cycles slightly later than the original technique did, but does it
2363/// make significantly cheaper.
2364
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002365void Andersens::SolveConstraints() {
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002366 CurrWL = &w1;
2367 NextWL = &w2;
Daniel Berlin385bda62007-09-16 21:45:02 +00002368
Daniel Berlinb53270f2007-09-24 19:45:49 +00002369 OptimizeConstraints();
2370#undef DEBUG_TYPE
2371#define DEBUG_TYPE "anders-aa-constraints"
2372 DEBUG(PrintConstraints());
2373#undef DEBUG_TYPE
2374#define DEBUG_TYPE "anders-aa"
2375
Daniel Berlin385bda62007-09-16 21:45:02 +00002376 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2377 Node *N = &GraphNodes[i];
2378 N->PointsTo = new SparseBitVector<>;
2379 N->OldPointsTo = new SparseBitVector<>;
2380 N->Edges = new SparseBitVector<>;
2381 }
2382 CreateConstraintGraph();
Daniel Berlinb53270f2007-09-24 19:45:49 +00002383 UnitePointerEquivalences();
2384 assert(SCCStack.empty() && "SCC Stack should be empty by now!");
Daniel Berlinb53270f2007-09-24 19:45:49 +00002385 Node2DFS.clear();
2386 Node2Deleted.clear();
Daniel Berlin385bda62007-09-16 21:45:02 +00002387 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2388 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2389 DFSNumber = 0;
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002390 DenseSet<Constraint, ConstraintKeyInfo> Seen;
2391 DenseSet<std::pair<unsigned,unsigned>, PairKeyInfo> EdgesChecked;
2392
2393 // Order graph and add initial nodes to work list.
Daniel Berlin385bda62007-09-16 21:45:02 +00002394 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
Daniel Berlin385bda62007-09-16 21:45:02 +00002395 Node *INode = &GraphNodes[i];
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002396
2397 // Add to work list if it's a representative and can contribute to the
2398 // calculation right now.
2399 if (INode->isRep() && !INode->PointsTo->empty()
2400 && (!INode->Edges->empty() || !INode->Constraints.empty())) {
2401 INode->Stamp();
2402 CurrWL->insert(INode);
Daniel Berlin385bda62007-09-16 21:45:02 +00002403 }
2404 }
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002405 std::queue<unsigned int> TarjanWL;
Daniel Berlined95dd02008-03-05 19:31:47 +00002406#if !FULL_UNIVERSAL
2407 // "Rep and special variables" - in order for HCD to maintain conservative
2408 // results when !FULL_UNIVERSAL, we need to treat the special variables in
2409 // the same way that the !FULL_UNIVERSAL tweak does throughout the rest of
2410 // the analysis - it's ok to add edges from the special nodes, but never
2411 // *to* the special nodes.
2412 std::vector<unsigned int> RSV;
2413#endif
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002414 while( !CurrWL->empty() ) {
2415 DOUT << "Starting iteration #" << ++NumIters << "\n";
Daniel Berlin385bda62007-09-16 21:45:02 +00002416
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002417 Node* CurrNode;
2418 unsigned CurrNodeIndex;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002419
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002420 // Actual cycle checking code. We cycle check all of the lazy cycle
2421 // candidates from the last iteration in one go.
2422 if (!TarjanWL.empty()) {
2423 DFSNumber = 0;
2424
2425 Tarjan2DFS.clear();
2426 Tarjan2Deleted.clear();
2427 while (!TarjanWL.empty()) {
2428 unsigned int ToTarjan = TarjanWL.front();
2429 TarjanWL.pop();
2430 if (!Tarjan2Deleted[ToTarjan]
2431 && GraphNodes[ToTarjan].isRep()
2432 && Tarjan2DFS[ToTarjan] == 0)
2433 QueryNode(ToTarjan);
2434 }
2435 }
2436
2437 // Add to work list if it's a representative and can contribute to the
2438 // calculation right now.
2439 while( (CurrNode = CurrWL->pop()) != NULL ) {
2440 CurrNodeIndex = CurrNode - &GraphNodes[0];
2441 CurrNode->Stamp();
2442
2443
Daniel Berlin385bda62007-09-16 21:45:02 +00002444 // Figure out the changed points to bits
2445 SparseBitVector<> CurrPointsTo;
2446 CurrPointsTo.intersectWithComplement(CurrNode->PointsTo,
2447 CurrNode->OldPointsTo);
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002448 if (CurrPointsTo.empty())
Daniel Berlin385bda62007-09-16 21:45:02 +00002449 continue;
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002450
Daniel Berlin385bda62007-09-16 21:45:02 +00002451 *(CurrNode->OldPointsTo) |= CurrPointsTo;
Daniel Berlined95dd02008-03-05 19:31:47 +00002452
2453 // Check the offline-computed equivalencies from HCD.
2454 bool SCC = false;
2455 unsigned Rep;
2456
2457 if (SDT[CurrNodeIndex] >= 0) {
2458 SCC = true;
2459 Rep = FindNode(SDT[CurrNodeIndex]);
2460
2461#if !FULL_UNIVERSAL
2462 RSV.clear();
2463#endif
2464 for (SparseBitVector<>::iterator bi = CurrPointsTo.begin();
2465 bi != CurrPointsTo.end(); ++bi) {
2466 unsigned Node = FindNode(*bi);
2467#if !FULL_UNIVERSAL
2468 if (Node < NumberSpecialNodes) {
2469 RSV.push_back(Node);
2470 continue;
2471 }
2472#endif
2473 Rep = UniteNodes(Rep,Node);
2474 }
2475#if !FULL_UNIVERSAL
2476 RSV.push_back(Rep);
2477#endif
2478
2479 NextWL->insert(&GraphNodes[Rep]);
2480
2481 if ( ! CurrNode->isRep() )
2482 continue;
2483 }
2484
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002485 Seen.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002486
Daniel Berlin385bda62007-09-16 21:45:02 +00002487 /* Now process the constraints for this node. */
2488 for (std::list<Constraint>::iterator li = CurrNode->Constraints.begin();
2489 li != CurrNode->Constraints.end(); ) {
2490 li->Src = FindNode(li->Src);
2491 li->Dest = FindNode(li->Dest);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002492
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002493 // Delete redundant constraints
2494 if( Seen.count(*li) ) {
2495 std::list<Constraint>::iterator lk = li; li++;
2496
2497 CurrNode->Constraints.erase(lk);
2498 ++NumErased;
2499 continue;
2500 }
2501 Seen.insert(*li);
2502
Daniel Berlin385bda62007-09-16 21:45:02 +00002503 // Src and Dest will be the vars we are going to process.
2504 // This may look a bit ugly, but what it does is allow us to process
Daniel Berlinb53270f2007-09-24 19:45:49 +00002505 // both store and load constraints with the same code.
Daniel Berlin385bda62007-09-16 21:45:02 +00002506 // Load constraints say that every member of our RHS solution has K
2507 // added to it, and that variable gets an edge to LHS. We also union
2508 // RHS+K's solution into the LHS solution.
2509 // Store constraints say that every member of our LHS solution has K
2510 // added to it, and that variable gets an edge from RHS. We also union
2511 // RHS's solution into the LHS+K solution.
2512 unsigned *Src;
2513 unsigned *Dest;
2514 unsigned K = li->Offset;
2515 unsigned CurrMember;
2516 if (li->Type == Constraint::Load) {
2517 Src = &CurrMember;
2518 Dest = &li->Dest;
2519 } else if (li->Type == Constraint::Store) {
2520 Src = &li->Src;
2521 Dest = &CurrMember;
2522 } else {
2523 // TODO Handle offseted copy constraint
2524 li++;
2525 continue;
2526 }
Daniel Berlined95dd02008-03-05 19:31:47 +00002527
2528 // See if we can use Hybrid Cycle Detection (that is, check
Daniel Berlin385bda62007-09-16 21:45:02 +00002529 // if it was a statically detected offline equivalence that
Daniel Berlined95dd02008-03-05 19:31:47 +00002530 // involves pointers; if so, remove the redundant constraints).
2531 if( SCC && K == 0 ) {
2532#if FULL_UNIVERSAL
2533 CurrMember = Rep;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002534
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002535 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2536 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2537 NextWL->insert(&GraphNodes[*Dest]);
Daniel Berlined95dd02008-03-05 19:31:47 +00002538#else
2539 for (unsigned i=0; i < RSV.size(); ++i) {
2540 CurrMember = RSV[i];
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002541
Daniel Berlined95dd02008-03-05 19:31:47 +00002542 if (*Dest < NumberSpecialNodes)
2543 continue;
2544 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2545 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2546 NextWL->insert(&GraphNodes[*Dest]);
2547 }
2548#endif
2549 // since all future elements of the points-to set will be
2550 // equivalent to the current ones, the complex constraints
2551 // become redundant.
2552 //
2553 std::list<Constraint>::iterator lk = li; li++;
2554#if !FULL_UNIVERSAL
2555 // In this case, we can still erase the constraints when the
2556 // elements of the points-to sets are referenced by *Dest,
2557 // but not when they are referenced by *Src (i.e. for a Load
2558 // constraint). This is because if another special variable is
2559 // put into the points-to set later, we still need to add the
2560 // new edge from that special variable.
2561 if( lk->Type != Constraint::Load)
2562#endif
2563 GraphNodes[CurrNodeIndex].Constraints.erase(lk);
2564 } else {
2565 const SparseBitVector<> &Solution = CurrPointsTo;
2566
2567 for (SparseBitVector<>::iterator bi = Solution.begin();
2568 bi != Solution.end();
2569 ++bi) {
2570 CurrMember = *bi;
2571
2572 // Need to increment the member by K since that is where we are
2573 // supposed to copy to/from. Note that in positive weight cycles,
2574 // which occur in address taking of fields, K can go past
2575 // MaxK[CurrMember] elements, even though that is all it could point
2576 // to.
2577 if (K > 0 && K > MaxK[CurrMember])
2578 continue;
2579 else
2580 CurrMember = FindNode(CurrMember + K);
2581
2582 // Add an edge to the graph, so we can just do regular
2583 // bitmap ior next time. It may also let us notice a cycle.
2584#if !FULL_UNIVERSAL
2585 if (*Dest < NumberSpecialNodes)
2586 continue;
2587#endif
2588 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2589 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2590 NextWL->insert(&GraphNodes[*Dest]);
2591
2592 }
2593 li++;
Daniel Berlin385bda62007-09-16 21:45:02 +00002594 }
Daniel Berlin385bda62007-09-16 21:45:02 +00002595 }
2596 SparseBitVector<> NewEdges;
2597 SparseBitVector<> ToErase;
2598
2599 // Now all we have left to do is propagate points-to info along the
2600 // edges, erasing the redundant edges.
Daniel Berlin385bda62007-09-16 21:45:02 +00002601 for (SparseBitVector<>::iterator bi = CurrNode->Edges->begin();
2602 bi != CurrNode->Edges->end();
2603 ++bi) {
2604
2605 unsigned DestVar = *bi;
2606 unsigned Rep = FindNode(DestVar);
2607
Bill Wendling059e62c2008-02-26 10:51:52 +00002608 // If we ended up with this node as our destination, or we've already
2609 // got an edge for the representative, delete the current edge.
2610 if (Rep == CurrNodeIndex ||
2611 (Rep != DestVar && NewEdges.test(Rep))) {
Daniel Berlined95dd02008-03-05 19:31:47 +00002612 ToErase.set(DestVar);
2613 continue;
Bill Wendling059e62c2008-02-26 10:51:52 +00002614 }
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002615
Bill Wendling059e62c2008-02-26 10:51:52 +00002616 std::pair<unsigned,unsigned> edge(CurrNodeIndex,Rep);
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002617
2618 // This is where we do lazy cycle detection.
2619 // If this is a cycle candidate (equal points-to sets and this
2620 // particular edge has not been cycle-checked previously), add to the
2621 // list to check for cycles on the next iteration.
2622 if (!EdgesChecked.count(edge) &&
2623 *(GraphNodes[Rep].PointsTo) == *(CurrNode->PointsTo)) {
2624 EdgesChecked.insert(edge);
2625 TarjanWL.push(Rep);
Daniel Berlin385bda62007-09-16 21:45:02 +00002626 }
2627 // Union the points-to sets into the dest
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002628#if !FULL_UNIVERSAL
2629 if (Rep >= NumberSpecialNodes)
2630#endif
Daniel Berlin385bda62007-09-16 21:45:02 +00002631 if (GraphNodes[Rep].PointsTo |= CurrPointsTo) {
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002632 NextWL->insert(&GraphNodes[Rep]);
Daniel Berlin385bda62007-09-16 21:45:02 +00002633 }
2634 // If this edge's destination was collapsed, rewrite the edge.
2635 if (Rep != DestVar) {
2636 ToErase.set(DestVar);
2637 NewEdges.set(Rep);
2638 }
2639 }
2640 CurrNode->Edges->intersectWithComplement(ToErase);
2641 CurrNode->Edges |= NewEdges;
2642 }
Daniel Berlin385bda62007-09-16 21:45:02 +00002643
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002644 // Switch to other work list.
2645 WorkList* t = CurrWL; CurrWL = NextWL; NextWL = t;
2646 }
Daniel Berlin385bda62007-09-16 21:45:02 +00002647
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002648
Daniel Berlin385bda62007-09-16 21:45:02 +00002649 Node2DFS.clear();
2650 Node2Deleted.clear();
2651 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2652 Node *N = &GraphNodes[i];
2653 delete N->OldPointsTo;
2654 delete N->Edges;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002655 }
Daniel Berlined95dd02008-03-05 19:31:47 +00002656 SDTActive = false;
2657 SDT.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002658}
2659
Daniel Berlin385bda62007-09-16 21:45:02 +00002660//===----------------------------------------------------------------------===//
2661// Union-Find
2662//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002663
Daniel Berlin385bda62007-09-16 21:45:02 +00002664// Unite nodes First and Second, returning the one which is now the
2665// representative node. First and Second are indexes into GraphNodes
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002666unsigned Andersens::UniteNodes(unsigned First, unsigned Second,
2667 bool UnionByRank) {
Daniel Berlin385bda62007-09-16 21:45:02 +00002668 assert (First < GraphNodes.size() && Second < GraphNodes.size() &&
2669 "Attempting to merge nodes that don't exist");
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002670
Daniel Berlin385bda62007-09-16 21:45:02 +00002671 Node *FirstNode = &GraphNodes[First];
2672 Node *SecondNode = &GraphNodes[Second];
2673
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002674 assert (SecondNode->isRep() && FirstNode->isRep() &&
Daniel Berlin385bda62007-09-16 21:45:02 +00002675 "Trying to unite two non-representative nodes!");
2676 if (First == Second)
2677 return First;
2678
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002679 if (UnionByRank) {
2680 int RankFirst = (int) FirstNode ->NodeRep;
2681 int RankSecond = (int) SecondNode->NodeRep;
2682
2683 // Rank starts at -1 and gets decremented as it increases.
2684 // Translation: higher rank, lower NodeRep value, which is always negative.
2685 if (RankFirst > RankSecond) {
2686 unsigned t = First; First = Second; Second = t;
2687 Node* tp = FirstNode; FirstNode = SecondNode; SecondNode = tp;
2688 } else if (RankFirst == RankSecond) {
2689 FirstNode->NodeRep = (unsigned) (RankFirst - 1);
2690 }
2691 }
2692
Daniel Berlin385bda62007-09-16 21:45:02 +00002693 SecondNode->NodeRep = First;
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002694#if !FULL_UNIVERSAL
2695 if (First >= NumberSpecialNodes)
2696#endif
Daniel Berlinb53270f2007-09-24 19:45:49 +00002697 if (FirstNode->PointsTo && SecondNode->PointsTo)
2698 FirstNode->PointsTo |= *(SecondNode->PointsTo);
2699 if (FirstNode->Edges && SecondNode->Edges)
2700 FirstNode->Edges |= *(SecondNode->Edges);
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002701 if (!SecondNode->Constraints.empty())
Daniel Berlinb53270f2007-09-24 19:45:49 +00002702 FirstNode->Constraints.splice(FirstNode->Constraints.begin(),
2703 SecondNode->Constraints);
2704 if (FirstNode->OldPointsTo) {
2705 delete FirstNode->OldPointsTo;
2706 FirstNode->OldPointsTo = new SparseBitVector<>;
2707 }
Daniel Berlin385bda62007-09-16 21:45:02 +00002708
2709 // Destroy interesting parts of the merged-from node.
2710 delete SecondNode->OldPointsTo;
2711 delete SecondNode->Edges;
2712 delete SecondNode->PointsTo;
2713 SecondNode->Edges = NULL;
2714 SecondNode->PointsTo = NULL;
2715 SecondNode->OldPointsTo = NULL;
2716
2717 NumUnified++;
2718 DOUT << "Unified Node ";
2719 DEBUG(PrintNode(FirstNode));
2720 DOUT << " and Node ";
2721 DEBUG(PrintNode(SecondNode));
2722 DOUT << "\n";
2723
Daniel Berlined95dd02008-03-05 19:31:47 +00002724 if (SDTActive)
2725 if (SDT[Second] >= 0)
2726 if (SDT[First] < 0)
2727 SDT[First] = SDT[Second];
2728 else {
2729 UniteNodes( FindNode(SDT[First]), FindNode(SDT[Second]) );
2730 First = FindNode(First);
2731 }
2732
Daniel Berlin385bda62007-09-16 21:45:02 +00002733 return First;
2734}
2735
2736// Find the index into GraphNodes of the node representing Node, performing
2737// path compression along the way
2738unsigned Andersens::FindNode(unsigned NodeIndex) {
2739 assert (NodeIndex < GraphNodes.size()
2740 && "Attempting to find a node that can't exist");
2741 Node *N = &GraphNodes[NodeIndex];
Daniel Berlinc6fd7722007-12-12 00:37:04 +00002742 if (N->isRep())
Daniel Berlin385bda62007-09-16 21:45:02 +00002743 return NodeIndex;
2744 else
2745 return (N->NodeRep = FindNode(N->NodeRep));
2746}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002747
Andrew Lenharthdce39302008-03-20 15:36:44 +00002748// Find the index into GraphNodes of the node representing Node,
2749// don't perform path compression along the way (for Print)
2750unsigned Andersens::FindNode(unsigned NodeIndex) const {
2751 assert (NodeIndex < GraphNodes.size()
2752 && "Attempting to find a node that can't exist");
2753 const Node *N = &GraphNodes[NodeIndex];
2754 if (N->isRep())
2755 return NodeIndex;
2756 else
2757 return FindNode(N->NodeRep);
2758}
2759
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002760//===----------------------------------------------------------------------===//
2761// Debugging Output
2762//===----------------------------------------------------------------------===//
2763
Andrew Lenharthdce39302008-03-20 15:36:44 +00002764void Andersens::PrintNode(const Node *N) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002765 if (N == &GraphNodes[UniversalSet]) {
2766 cerr << "<universal>";
2767 return;
2768 } else if (N == &GraphNodes[NullPtr]) {
2769 cerr << "<nullptr>";
2770 return;
2771 } else if (N == &GraphNodes[NullObject]) {
2772 cerr << "<null>";
2773 return;
2774 }
Daniel Berlin385bda62007-09-16 21:45:02 +00002775 if (!N->getValue()) {
2776 cerr << "artificial" << (intptr_t) N;
2777 return;
2778 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002779
2780 assert(N->getValue() != 0 && "Never set node label!");
2781 Value *V = N->getValue();
2782 if (Function *F = dyn_cast<Function>(V)) {
2783 if (isa<PointerType>(F->getFunctionType()->getReturnType()) &&
Daniel Berlin385bda62007-09-16 21:45:02 +00002784 N == &GraphNodes[getReturnNode(F)]) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002785 cerr << F->getName() << ":retval";
2786 return;
Daniel Berlin385bda62007-09-16 21:45:02 +00002787 } else if (F->getFunctionType()->isVarArg() &&
2788 N == &GraphNodes[getVarargNode(F)]) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002789 cerr << F->getName() << ":vararg";
2790 return;
2791 }
2792 }
2793
2794 if (Instruction *I = dyn_cast<Instruction>(V))
2795 cerr << I->getParent()->getParent()->getName() << ":";
2796 else if (Argument *Arg = dyn_cast<Argument>(V))
2797 cerr << Arg->getParent()->getName() << ":";
2798
2799 if (V->hasName())
2800 cerr << V->getName();
2801 else
2802 cerr << "(unnamed)";
2803
2804 if (isa<GlobalValue>(V) || isa<AllocationInst>(V))
Daniel Berlin385bda62007-09-16 21:45:02 +00002805 if (N == &GraphNodes[getObject(V)])
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002806 cerr << "<mem>";
2807}
Andrew Lenharthdce39302008-03-20 15:36:44 +00002808void Andersens::PrintConstraint(const Constraint &C) const {
Daniel Berlinb53270f2007-09-24 19:45:49 +00002809 if (C.Type == Constraint::Store) {
2810 cerr << "*";
2811 if (C.Offset != 0)
2812 cerr << "(";
2813 }
2814 PrintNode(&GraphNodes[C.Dest]);
2815 if (C.Type == Constraint::Store && C.Offset != 0)
2816 cerr << " + " << C.Offset << ")";
2817 cerr << " = ";
2818 if (C.Type == Constraint::Load) {
2819 cerr << "*";
2820 if (C.Offset != 0)
2821 cerr << "(";
2822 }
2823 else if (C.Type == Constraint::AddressOf)
2824 cerr << "&";
2825 PrintNode(&GraphNodes[C.Src]);
2826 if (C.Offset != 0 && C.Type != Constraint::Store)
2827 cerr << " + " << C.Offset;
2828 if (C.Type == Constraint::Load && C.Offset != 0)
2829 cerr << ")";
2830 cerr << "\n";
2831}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002832
Andrew Lenharthdce39302008-03-20 15:36:44 +00002833void Andersens::PrintConstraints() const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002834 cerr << "Constraints:\n";
Daniel Berlin385bda62007-09-16 21:45:02 +00002835
Daniel Berlinb53270f2007-09-24 19:45:49 +00002836 for (unsigned i = 0, e = Constraints.size(); i != e; ++i)
2837 PrintConstraint(Constraints[i]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002838}
2839
Andrew Lenharthdce39302008-03-20 15:36:44 +00002840void Andersens::PrintPointsToGraph() const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002841 cerr << "Points-to graph:\n";
2842 for (unsigned i = 0, e = GraphNodes.size(); i != e; ++i) {
Andrew Lenharthdce39302008-03-20 15:36:44 +00002843 const Node *N = &GraphNodes[i];
2844 if (FindNode(i) != i) {
Daniel Berlin385bda62007-09-16 21:45:02 +00002845 PrintNode(N);
2846 cerr << "\t--> same as ";
2847 PrintNode(&GraphNodes[FindNode(i)]);
2848 cerr << "\n";
2849 } else {
2850 cerr << "[" << (N->PointsTo->count()) << "] ";
2851 PrintNode(N);
2852 cerr << "\t--> ";
2853
2854 bool first = true;
2855 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
2856 bi != N->PointsTo->end();
2857 ++bi) {
2858 if (!first)
2859 cerr << ", ";
2860 PrintNode(&GraphNodes[*bi]);
2861 first = false;
2862 }
2863 cerr << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002864 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002865 }
2866}