blob: 8584d06f7a7b093d98576a7b4c5c6a230f42bee4 [file] [log] [blame]
Chris Lattnerd28b0d72004-06-25 04:24:22 +00001//===- Andersens.cpp - Andersen's Interprocedural Alias Analysis ----------===//
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002//
Chris Lattnere995a2a2004-05-23 21:00:47 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00007//
Chris Lattnere995a2a2004-05-23 21:00:47 +00008//===----------------------------------------------------------------------===//
9//
Daniel Berlinaad15882007-09-16 21:45:02 +000010// This file defines an implementation of Andersen's interprocedural alias
11// analysis
Chris Lattnere995a2a2004-05-23 21:00:47 +000012//
13// In pointer analysis terms, this is a subset-based, flow-insensitive,
Daniel Berlinaad15882007-09-16 21:45:02 +000014// field-sensitive, and context-insensitive algorithm pointer algorithm.
Chris Lattnere995a2a2004-05-23 21:00:47 +000015//
16// This algorithm is implemented as three stages:
17// 1. Object identification.
18// 2. Inclusion constraint identification.
Daniel Berlind81ccc22007-09-24 19:45:49 +000019// 3. Offline constraint graph optimization
20// 4. Inclusion constraint solving.
Chris Lattnere995a2a2004-05-23 21:00:47 +000021//
22// The object identification stage identifies all of the memory objects in the
23// program, which includes globals, heap allocated objects, and stack allocated
24// objects.
25//
26// The inclusion constraint identification stage finds all inclusion constraints
27// in the program by scanning the program, looking for pointer assignments and
28// other statements that effect the points-to graph. For a statement like "A =
29// B", this statement is processed to indicate that A can point to anything that
Daniel Berlinaad15882007-09-16 21:45:02 +000030// B can point to. Constraints can handle copies, loads, and stores, and
31// address taking.
Chris Lattnere995a2a2004-05-23 21:00:47 +000032//
Daniel Berline6f04792007-09-24 22:20:45 +000033// The offline constraint graph optimization portion includes offline variable
Daniel Berlinc864edb2008-03-05 19:31:47 +000034// substitution algorithms intended to compute pointer and location
Daniel Berline6f04792007-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 Berlinc864edb2008-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 Berlind81ccc22007-09-24 19:45:49 +000040//
Chris Lattnere995a2a2004-05-23 21:00:47 +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 Berlinaad15882007-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 Berlind81ccc22007-09-24 19:45:49 +000047// without any issues. To wit, an indirect call Y(a,b) is equivalent to
Daniel Berlinaad15882007-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.
Chris Lattnere995a2a2004-05-23 21:00:47 +000051//
Chris Lattnerc7ca32b2004-06-05 20:12:36 +000052// Future Improvements:
Daniel Berlinc864edb2008-03-05 19:31:47 +000053// Use of BDD's.
Chris Lattnere995a2a2004-05-23 21:00:47 +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"
Reid Spencerd7d83db2007-02-05 23:42:17 +000062#include "llvm/Support/Compiler.h"
Chris Lattnere995a2a2004-05-23 21:00:47 +000063#include "llvm/Support/InstIterator.h"
64#include "llvm/Support/InstVisitor.h"
65#include "llvm/Analysis/AliasAnalysis.h"
Jeff Cohen534927d2005-01-08 22:01:16 +000066#include "llvm/Analysis/Passes.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000067#include "llvm/Support/Debug.h"
68#include "llvm/ADT/Statistic.h"
Daniel Berlinaad15882007-09-16 21:45:02 +000069#include "llvm/ADT/SparseBitVector.h"
Chris Lattnerbe207732007-09-30 00:47:20 +000070#include "llvm/ADT/DenseSet.h"
Jeff Cohenca5183d2007-03-05 00:00:42 +000071#include <algorithm>
Chris Lattnere995a2a2004-05-23 21:00:47 +000072#include <set>
Daniel Berlinaad15882007-09-16 21:45:02 +000073#include <list>
Dan Gohmanc9235d22008-03-21 23:51:57 +000074#include <map>
Daniel Berlinaad15882007-09-16 21:45:02 +000075#include <stack>
76#include <vector>
Daniel Berlin3a3f1632007-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
Chris Lattnere995a2a2004-05-23 21:00:47 +000084
Daniel Berlinaad15882007-09-16 21:45:02 +000085using namespace llvm;
Daniel Berlind81ccc22007-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 Berlin3a3f1632007-12-12 00:37:04 +000090STATISTIC(NumErased , "Number of redundant constraints erased");
Chris Lattnere995a2a2004-05-23 21:00:47 +000091
Dan Gohman844731a2008-05-13 00:00:25 +000092static const unsigned SelfRep = (unsigned)-1;
93static const unsigned Unvisited = (unsigned)-1;
94// Position of the function return node relative to the function node.
95static const unsigned CallReturnPos = 1;
96// Position of the function call node relative to the function node.
97static const unsigned CallFirstArgPos = 2;
Daniel Berlind81ccc22007-09-24 19:45:49 +000098
Dan Gohman844731a2008-05-13 00:00:25 +000099namespace {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000100 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 Berlinaad15882007-09-16 21:45:02 +0000123
Reid Spencerd7d83db2007-02-05 23:42:17 +0000124 class VISIBILITY_HIDDEN Andersens : public ModulePass, public AliasAnalysis,
125 private InstVisitor<Andersens> {
Hartmut Kaiser081fdf22007-10-25 23:49:14 +0000126 struct Node;
Daniel Berlinaad15882007-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 Berlind81ccc22007-09-24 19:45:49 +0000134 /// illegal on addressof constraints (because it is statically
Daniel Berlinaad15882007-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 Korobeynikovae9f3a32008-02-20 11:08:44 +0000145 assert((Offset == 0 || Ty != AddressOf) &&
Daniel Berlinaad15882007-09-16 21:45:02 +0000146 "Offset is illegal on addressof constraints");
147 }
Daniel Berlin336c6c02007-09-29 00:50:40 +0000148
Daniel Berlinc7a12ae2007-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 Berlin336c6c02007-09-29 00:50:40 +0000155
156 bool operator!=(const Constraint &RHS) const {
157 return !(*this == RHS);
158 }
159
Daniel Berlinc7a12ae2007-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 Berlinaad15882007-09-16 21:45:02 +0000169 };
170
Daniel Berlin3a3f1632007-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 Michelacddf9d2008-03-18 16:55:06 +0000175 return std::make_pair(~0U, ~0U);
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000176 }
177 static inline std::pair<unsigned, unsigned> getTombstoneKey() {
Scott Michelacddf9d2008-03-18 16:55:06 +0000178 return std::make_pair(~0U - 1, ~0U - 1);
Daniel Berlin3a3f1632007-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 Berlin336c6c02007-09-29 00:50:40 +0000189 struct ConstraintKeyInfo {
190 static inline Constraint getEmptyKey() {
Scott Michelacddf9d2008-03-18 16:55:06 +0000191 return Constraint(Constraint::Copy, ~0U, ~0U, ~0U);
Daniel Berlin336c6c02007-09-29 00:50:40 +0000192 }
193 static inline Constraint getTombstoneKey() {
Scott Michelacddf9d2008-03-18 16:55:06 +0000194 return Constraint(Constraint::Copy, ~0U - 1, ~0U - 1, ~0U - 1);
Daniel Berlin336c6c02007-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 Berlind81ccc22007-09-24 19:45:49 +0000206 // Node class - This class is used to represent a node in the constraint
Daniel Berline6f04792007-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 Berlinaad15882007-09-16 21:45:02 +0000211 struct Node {
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000212 private:
213 static unsigned Counter;
214
215 public:
Daniel Berlind81ccc22007-09-24 19:45:49 +0000216 Value *Val;
Daniel Berlinaad15882007-09-16 21:45:02 +0000217 SparseBitVector<> *Edges;
218 SparseBitVector<> *PointsTo;
219 SparseBitVector<> *OldPointsTo;
Daniel Berlinaad15882007-09-16 21:45:02 +0000220 std::list<Constraint> Constraints;
221
Daniel Berlind81ccc22007-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 Berline6f04792007-09-24 22:20:45 +0000233 // True if our points-to set is in the Set2PEClass map
Daniel Berlind81ccc22007-09-24 19:45:49 +0000234 bool StoredInHash;
Daniel Berline6f04792007-09-24 22:20:45 +0000235 // True if our node has no indirect constraints (complex or otherwise)
Daniel Berlind81ccc22007-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 Berlind81ccc22007-09-24 19:45:49 +0000241 bool AddressTaken;
Daniel Berlinaad15882007-09-16 21:45:02 +0000242
Daniel Berlind81ccc22007-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 Berlin3a3f1632007-12-12 00:37:04 +0000247
248 // Modification timestamp. Assigned from Counter.
249 // Used for work list prioritization.
250 unsigned Timestamp;
Daniel Berlind81ccc22007-09-24 19:45:49 +0000251
Dan Gohmanded2b0d2007-12-14 15:41:34 +0000252 explicit Node(bool direct = true) :
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000253 Val(0), Edges(0), PointsTo(0), OldPointsTo(0),
Daniel Berlind81ccc22007-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 Berlin3a3f1632007-12-12 00:37:04 +0000257 NodeRep(SelfRep), Timestamp(0) { }
Daniel Berlinaad15882007-09-16 21:45:02 +0000258
Chris Lattnere995a2a2004-05-23 21:00:47 +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.
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000266 ///
Chris Lattnere995a2a2004-05-23 21:00:47 +0000267 Value *getValue() const { return Val; }
268
Chris Lattnere995a2a2004-05-23 21:00:47 +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 Berlinaad15882007-09-16 21:45:02 +0000272 bool addPointerTo(unsigned Node) {
273 return PointsTo->test_and_set(Node);
Chris Lattnere995a2a2004-05-23 21:00:47 +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 Berlinaad15882007-09-16 21:45:02 +0000283 bool intersectsIgnoring(Node *N, unsigned) const;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000284
285 // Timestamp a node (used for work list prioritization)
286 void Stamp() {
287 Timestamp = Counter++;
288 }
289
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000290 bool isRep() const {
Daniel Berlin3a3f1632007-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 }
Chris Lattnere995a2a2004-05-23 21:00:47 +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 Berlind81ccc22007-09-24 19:45:49 +0000347 DenseMap<Value*, unsigned> ValueNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000348
349 /// ObjectNodes - This map contains entries for each memory object in the
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000350 /// program: globals, alloca's and mallocs.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000351 DenseMap<Value*, unsigned> ObjectNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000352
353 /// ReturnNodes - This map contains an entry for each function in the
354 /// program that returns a value.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000355 DenseMap<Function*, unsigned> ReturnNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +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 Berlind81ccc22007-09-24 19:45:49 +0000361 DenseMap<Function*, unsigned> VarargNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000362
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000363
Chris Lattnere995a2a2004-05-23 21:00:47 +0000364 /// Constraints - This vector contains a list of all of the constraints
365 /// identified by the program.
366 std::vector<Constraint> Constraints;
367
Daniel Berlind81ccc22007-09-24 19:45:49 +0000368 // Map from graph node to maximum K value that is allowed (for functions,
Daniel Berlinaad15882007-09-16 21:45:02 +0000369 // this is equivalent to the number of arguments + CallFirstArgPos)
370 std::map<unsigned, unsigned> MaxK;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000371
372 /// This enum defines the GraphNodes indices that correspond to important
373 /// fixed sets.
374 enum {
375 UniversalSet = 0,
376 NullPtr = 1,
Daniel Berlind81ccc22007-09-24 19:45:49 +0000377 NullObject = 2,
378 NumberSpecialNodes
Chris Lattnere995a2a2004-05-23 21:00:47 +0000379 };
Daniel Berlind81ccc22007-09-24 19:45:49 +0000380 // Stack for Tarjan's
Daniel Berlinaad15882007-09-16 21:45:02 +0000381 std::stack<unsigned> SCCStack;
Daniel Berlinaad15882007-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 Berlin3a3f1632007-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 Berlinaad15882007-09-16 21:45:02 +0000391 unsigned DFSNumber;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000392
393 // Work lists.
394 WorkList w1, w2;
395 WorkList *CurrWL, *NextWL; // "current" and "next" work lists
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000396
Daniel Berlind81ccc22007-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 Berlinc864edb2008-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 Berlind81ccc22007-09-24 19:45:49 +0000431
Chris Lattnere995a2a2004-05-23 21:00:47 +0000432 public:
Daniel Berlinaad15882007-09-16 21:45:02 +0000433 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +0000434 Andersens() : ModulePass(&ID) {}
Devang Patel1cee94f2008-03-18 00:39:19 +0000435
Chris Lattnerb12914b2004-09-20 04:48:05 +0000436 bool runOnModule(Module &M) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000437 InitializeAliasAnalysis(this);
438 IdentifyObjects(M);
439 CollectConstraints(M);
Daniel Berlind81ccc22007-09-24 19:45:49 +0000440#undef DEBUG_TYPE
441#define DEBUG_TYPE "anders-aa-constraints"
Chris Lattnere995a2a2004-05-23 21:00:47 +0000442 DEBUG(PrintConstraints());
Daniel Berlind81ccc22007-09-24 19:45:49 +0000443#undef DEBUG_TYPE
444#define DEBUG_TYPE "anders-aa"
Chris Lattnere995a2a2004-05-23 21:00:47 +0000445 SolveConstraints();
446 DEBUG(PrintPointsToGraph());
447
448 // Free the constraints list, as we don't need it to respond to alias
449 // requests.
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000450 std::vector<Constraint>().swap(Constraints);
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000451 //These are needed for Print() (-analyze in opt)
452 //ObjectNodes.clear();
453 //ReturnNodes.clear();
454 //VarargNodes.clear();
Chris Lattnere995a2a2004-05-23 21:00:47 +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
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000477 //
Chris Lattnere995a2a2004-05-23 21:00:47 +0000478 AliasResult alias(const Value *V1, unsigned V1Size,
479 const Value *V2, unsigned V2Size);
Reid Spencer3a9ec242006-08-28 01:02:49 +0000480 virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
481 virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000482 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 Berlinaad15882007-09-16 21:45:02 +0000498 unsigned getNode(Value *V) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000499 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattnerdf9b7bc2004-08-16 05:38:02 +0000500 if (!isa<GlobalValue>(C))
501 return getNodeForConstantPointer(C);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000502
Daniel Berlind81ccc22007-09-24 19:45:49 +0000503 DenseMap<Value*, unsigned>::iterator I = ValueNodes.find(V);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000504 if (I == ValueNodes.end()) {
Jim Laskey16d42c62006-07-11 18:25:13 +0000505#ifndef NDEBUG
506 V->dump();
507#endif
Jim Laskeye37fe9b2006-07-11 17:58:07 +0000508 assert(0 && "Value does not have a node in the points-to graph!");
Chris Lattnere995a2a2004-05-23 21:00:47 +0000509 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000510 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000511 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000512
Chris Lattnere995a2a2004-05-23 21:00:47 +0000513 /// getObject - Return the node corresponding to the memory object for the
514 /// specified global or allocation instruction.
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000515 unsigned getObject(Value *V) const {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000516 DenseMap<Value*, unsigned>::iterator I = ObjectNodes.find(V);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000517 assert(I != ObjectNodes.end() &&
518 "Value does not have an object in the points-to graph!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000519 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000520 }
521
522 /// getReturnNode - Return the node representing the return value for the
523 /// specified function.
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000524 unsigned getReturnNode(Function *F) const {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000525 DenseMap<Function*, unsigned>::iterator I = ReturnNodes.find(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000526 assert(I != ReturnNodes.end() && "Function does not return a value!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000527 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000528 }
529
530 /// getVarargNode - Return the node representing the variable arguments
531 /// formal for the specified function.
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000532 unsigned getVarargNode(Function *F) const {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000533 DenseMap<Function*, unsigned>::iterator I = VarargNodes.find(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000534 assert(I != VarargNodes.end() && "Function does not take var args!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000535 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +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 Berlinaad15882007-09-16 21:45:02 +0000540 unsigned getNodeValue(Value &V) {
541 unsigned Index = getNode(&V);
542 GraphNodes[Index].setValue(&V);
543 return Index;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000544 }
545
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000546 unsigned UniteNodes(unsigned First, unsigned Second,
547 bool UnionByRank = true);
Daniel Berlinaad15882007-09-16 21:45:02 +0000548 unsigned FindNode(unsigned Node);
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000549 unsigned FindNode(unsigned Node) const;
Daniel Berlinaad15882007-09-16 21:45:02 +0000550
Chris Lattnere995a2a2004-05-23 21:00:47 +0000551 void IdentifyObjects(Module &M);
552 void CollectConstraints(Module &M);
Daniel Berlinaad15882007-09-16 21:45:02 +0000553 bool AnalyzeUsesOfFunction(Value *);
554 void CreateConstraintGraph();
Daniel Berlind81ccc22007-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 Berlinc864edb2008-03-05 19:31:47 +0000561 void HCD();
562 void Search(unsigned Node);
Daniel Berlind81ccc22007-09-24 19:45:49 +0000563 void UnitePointerEquivalences();
Chris Lattnere995a2a2004-05-23 21:00:47 +0000564 void SolveConstraints();
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000565 bool QueryNode(unsigned Node);
Daniel Berlind81ccc22007-09-24 19:45:49 +0000566 void Condense(unsigned Node);
567 void HUValNum(unsigned Node);
568 void HVNValNum(unsigned Node);
Daniel Berlinaad15882007-09-16 21:45:02 +0000569 unsigned getNodeForConstantPointer(Constant *C);
570 unsigned getNodeForConstantPointerTarget(Constant *C);
571 void AddGlobalInitializerConstraints(unsigned, Constant *C);
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000572
Chris Lattnere995a2a2004-05-23 21:00:47 +0000573 void AddConstraintsForNonInternalLinkage(Function *F);
574 void AddConstraintsForCall(CallSite CS, Function *F);
Chris Lattner8a446432005-03-29 06:09:07 +0000575 bool AddConstraintsForExternalCall(CallSite CS, Function *F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000576
577
Andrew Lenharth52d34d92008-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;
Chris Lattnere995a2a2004-05-23 21:00:47 +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);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000598 void visitICmpInst(ICmpInst &ICI) {} // NOOP!
599 void visitFCmpInst(FCmpInst &ICI) {} // NOOP!
Chris Lattnere995a2a2004-05-23 21:00:47 +0000600 void visitSelectInst(SelectInst &SI);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000601 void visitVAArg(VAArgInst &I);
602 void visitInstruction(Instruction &I);
Daniel Berlinaad15882007-09-16 21:45:02 +0000603
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000604 //===------------------------------------------------------------------===//
605 // Implement Analyize interface
606 //
607 void print(std::ostream &O, const Module* M) const {
608 PrintPointsToGraph();
609 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000610 };
Chris Lattnere995a2a2004-05-23 21:00:47 +0000611}
612
Dan Gohman844731a2008-05-13 00:00:25 +0000613char Andersens::ID = 0;
614static RegisterPass<Andersens>
615X("anders-aa", "Andersen's Interprocedural Alias Analysis", false, true);
616static RegisterAnalysisGroup<AliasAnalysis> Y(X);
617
618// Initialize Timestamp Counter (static).
619unsigned Andersens::Node::Counter = 0;
620
Jeff Cohen534927d2005-01-08 22:01:16 +0000621ModulePass *llvm::createAndersensPass() { return new Andersens(); }
622
Chris Lattnere995a2a2004-05-23 21:00:47 +0000623//===----------------------------------------------------------------------===//
624// AliasAnalysis Interface Implementation
625//===----------------------------------------------------------------------===//
626
627AliasAnalysis::AliasResult Andersens::alias(const Value *V1, unsigned V1Size,
628 const Value *V2, unsigned V2Size) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000629 Node *N1 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V1)))];
630 Node *N2 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V2)))];
Chris Lattnere995a2a2004-05-23 21:00:47 +0000631
632 // Check to see if the two pointers are known to not alias. They don't alias
633 // if their points-to sets do not intersect.
Daniel Berlinaad15882007-09-16 21:45:02 +0000634 if (!N1->intersectsIgnoring(N2, NullObject))
Chris Lattnere995a2a2004-05-23 21:00:47 +0000635 return NoAlias;
636
637 return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
638}
639
Chris Lattnerf392c642005-03-28 06:21:17 +0000640AliasAnalysis::ModRefResult
641Andersens::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
642 // The only thing useful that we can contribute for mod/ref information is
643 // when calling external function calls: if we know that memory never escapes
644 // from the program, it cannot be modified by an external call.
645 //
646 // NOTE: This is not really safe, at least not when the entire program is not
647 // available. The deal is that the external function could call back into the
648 // program and modify stuff. We ignore this technical niggle for now. This
649 // is, after all, a "research quality" implementation of Andersen's analysis.
650 if (Function *F = CS.getCalledFunction())
Reid Spencer5cbf9852007-01-30 20:08:39 +0000651 if (F->isDeclaration()) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000652 Node *N1 = &GraphNodes[FindNode(getNode(P))];
Chris Lattnerf392c642005-03-28 06:21:17 +0000653
Daniel Berlinaad15882007-09-16 21:45:02 +0000654 if (N1->PointsTo->empty())
655 return NoModRef;
Daniel Berlind3bf1ae2008-03-18 22:22:53 +0000656#if FULL_UNIVERSAL
657 if (!UniversalSet->PointsTo->test(FindNode(getNode(P))))
658 return NoModRef; // Universal set does not contain P
659#else
Daniel Berlinaad15882007-09-16 21:45:02 +0000660 if (!N1->PointsTo->test(UniversalSet))
Chris Lattnerf392c642005-03-28 06:21:17 +0000661 return NoModRef; // P doesn't point to the universal set.
Daniel Berlind3bf1ae2008-03-18 22:22:53 +0000662#endif
Chris Lattnerf392c642005-03-28 06:21:17 +0000663 }
664
665 return AliasAnalysis::getModRefInfo(CS, P, Size);
666}
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000667
Reid Spencer3a9ec242006-08-28 01:02:49 +0000668AliasAnalysis::ModRefResult
669Andersens::getModRefInfo(CallSite CS1, CallSite CS2) {
670 return AliasAnalysis::getModRefInfo(CS1,CS2);
671}
672
Chris Lattnere995a2a2004-05-23 21:00:47 +0000673/// getMustAlias - We can provide must alias information if we know that a
674/// pointer can only point to a specific function or the null pointer.
675/// Unfortunately we cannot determine must-alias information for global
676/// variables or any other memory memory objects because we do not track whether
677/// a pointer points to the beginning of an object or a field of it.
678void Andersens::getMustAliases(Value *P, std::vector<Value*> &RetVals) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000679 Node *N = &GraphNodes[FindNode(getNode(P))];
680 if (N->PointsTo->count() == 1) {
681 Node *Pointee = &GraphNodes[N->PointsTo->find_first()];
682 // If a function is the only object in the points-to set, then it must be
683 // the destination. Note that we can't handle global variables here,
684 // because we don't know if the pointer is actually pointing to a field of
685 // the global or to the beginning of it.
686 if (Value *V = Pointee->getValue()) {
687 if (Function *F = dyn_cast<Function>(V))
688 RetVals.push_back(F);
689 } else {
690 // If the object in the points-to set is the null object, then the null
691 // pointer is a must alias.
692 if (Pointee == &GraphNodes[NullObject])
693 RetVals.push_back(Constant::getNullValue(P->getType()));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000694 }
695 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000696 AliasAnalysis::getMustAliases(P, RetVals);
697}
698
699/// pointsToConstantMemory - If we can determine that this pointer only points
700/// to constant memory, return true. In practice, this means that if the
701/// pointer can only point to constant globals, functions, or the null pointer,
702/// return true.
703///
704bool Andersens::pointsToConstantMemory(const Value *P) {
Dan Gohman6a551e72008-02-21 17:33:24 +0000705 Node *N = &GraphNodes[FindNode(getNode(const_cast<Value*>(P)))];
Daniel Berlinaad15882007-09-16 21:45:02 +0000706 unsigned i;
707
708 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
709 bi != N->PointsTo->end();
710 ++bi) {
711 i = *bi;
712 Node *Pointee = &GraphNodes[i];
713 if (Value *V = Pointee->getValue()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000714 if (!isa<GlobalValue>(V) || (isa<GlobalVariable>(V) &&
715 !cast<GlobalVariable>(V)->isConstant()))
716 return AliasAnalysis::pointsToConstantMemory(P);
717 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +0000718 if (i != NullObject)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000719 return AliasAnalysis::pointsToConstantMemory(P);
720 }
721 }
722
723 return true;
724}
725
726//===----------------------------------------------------------------------===//
727// Object Identification Phase
728//===----------------------------------------------------------------------===//
729
730/// IdentifyObjects - This stage scans the program, adding an entry to the
731/// GraphNodes list for each memory object in the program (global stack or
732/// heap), and populates the ValueNodes and ObjectNodes maps for these objects.
733///
734void Andersens::IdentifyObjects(Module &M) {
735 unsigned NumObjects = 0;
736
737 // Object #0 is always the universal set: the object that we don't know
738 // anything about.
739 assert(NumObjects == UniversalSet && "Something changed!");
740 ++NumObjects;
741
742 // Object #1 always represents the null pointer.
743 assert(NumObjects == NullPtr && "Something changed!");
744 ++NumObjects;
745
746 // Object #2 always represents the null object (the object pointed to by null)
747 assert(NumObjects == NullObject && "Something changed!");
748 ++NumObjects;
749
750 // Add all the globals first.
Chris Lattner493f6362005-03-27 22:03:46 +0000751 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
752 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000753 ObjectNodes[I] = NumObjects++;
754 ValueNodes[I] = NumObjects++;
755 }
756
757 // Add nodes for all of the functions and the instructions inside of them.
758 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
759 // The function itself is a memory object.
Daniel Berlinaad15882007-09-16 21:45:02 +0000760 unsigned First = NumObjects;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000761 ValueNodes[F] = NumObjects++;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000762 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
763 ReturnNodes[F] = NumObjects++;
764 if (F->getFunctionType()->isVarArg())
765 VarargNodes[F] = NumObjects++;
766
Daniel Berlinaad15882007-09-16 21:45:02 +0000767
Chris Lattnere995a2a2004-05-23 21:00:47 +0000768 // Add nodes for all of the incoming pointer arguments.
Chris Lattner493f6362005-03-27 22:03:46 +0000769 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
770 I != E; ++I)
Daniel Berlind81ccc22007-09-24 19:45:49 +0000771 {
772 if (isa<PointerType>(I->getType()))
773 ValueNodes[I] = NumObjects++;
774 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000775 MaxK[First] = NumObjects - First;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000776
777 // Scan the function body, creating a memory object for each heap/stack
778 // allocation in the body of the function and a node to represent all
779 // pointer values defined by instructions and used as operands.
780 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
781 // If this is an heap or stack allocation, create a node for the memory
782 // object.
783 if (isa<PointerType>(II->getType())) {
784 ValueNodes[&*II] = NumObjects++;
785 if (AllocationInst *AI = dyn_cast<AllocationInst>(&*II))
786 ObjectNodes[AI] = NumObjects++;
787 }
Nick Lewycky4ac0e8d2007-11-22 03:07:37 +0000788
789 // Calls to inline asm need to be added as well because the callee isn't
790 // referenced anywhere else.
791 if (CallInst *CI = dyn_cast<CallInst>(&*II)) {
792 Value *Callee = CI->getCalledValue();
793 if (isa<InlineAsm>(Callee))
794 ValueNodes[Callee] = NumObjects++;
795 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000796 }
797 }
798
799 // Now that we know how many objects to create, make them all now!
800 GraphNodes.resize(NumObjects);
801 NumNodes += NumObjects;
802}
803
804//===----------------------------------------------------------------------===//
805// Constraint Identification Phase
806//===----------------------------------------------------------------------===//
807
808/// getNodeForConstantPointer - Return the node corresponding to the constant
809/// pointer itself.
Daniel Berlinaad15882007-09-16 21:45:02 +0000810unsigned Andersens::getNodeForConstantPointer(Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000811 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
812
Chris Lattner267a1b02005-03-27 18:58:23 +0000813 if (isa<ConstantPointerNull>(C) || isa<UndefValue>(C))
Daniel Berlinaad15882007-09-16 21:45:02 +0000814 return NullPtr;
Reid Spencere8404342004-07-18 00:18:30 +0000815 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
816 return getNode(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000817 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
818 switch (CE->getOpcode()) {
819 case Instruction::GetElementPtr:
820 return getNodeForConstantPointer(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000821 case Instruction::IntToPtr:
Daniel Berlinaad15882007-09-16 21:45:02 +0000822 return UniversalSet;
Reid Spencer3da59db2006-11-27 01:05:10 +0000823 case Instruction::BitCast:
824 return getNodeForConstantPointer(CE->getOperand(0));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000825 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000826 cerr << "Constant Expr not yet handled: " << *CE << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +0000827 assert(0);
828 }
829 } else {
830 assert(0 && "Unknown constant pointer!");
831 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000832 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000833}
834
835/// getNodeForConstantPointerTarget - Return the node POINTED TO by the
836/// specified constant pointer.
Daniel Berlinaad15882007-09-16 21:45:02 +0000837unsigned Andersens::getNodeForConstantPointerTarget(Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000838 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
839
840 if (isa<ConstantPointerNull>(C))
Daniel Berlinaad15882007-09-16 21:45:02 +0000841 return NullObject;
Reid Spencere8404342004-07-18 00:18:30 +0000842 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
843 return getObject(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000844 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
845 switch (CE->getOpcode()) {
846 case Instruction::GetElementPtr:
847 return getNodeForConstantPointerTarget(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000848 case Instruction::IntToPtr:
Daniel Berlinaad15882007-09-16 21:45:02 +0000849 return UniversalSet;
Reid Spencer3da59db2006-11-27 01:05:10 +0000850 case Instruction::BitCast:
851 return getNodeForConstantPointerTarget(CE->getOperand(0));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000852 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000853 cerr << "Constant Expr not yet handled: " << *CE << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +0000854 assert(0);
855 }
856 } else {
857 assert(0 && "Unknown constant pointer!");
858 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000859 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000860}
861
862/// AddGlobalInitializerConstraints - Add inclusion constraints for the memory
863/// object N, which contains values indicated by C.
Daniel Berlinaad15882007-09-16 21:45:02 +0000864void Andersens::AddGlobalInitializerConstraints(unsigned NodeIndex,
865 Constant *C) {
Dan Gohmanb64aa112008-05-22 23:43:22 +0000866 if (C->getType()->isSingleValueType()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000867 if (isa<PointerType>(C->getType()))
Daniel Berlinaad15882007-09-16 21:45:02 +0000868 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
869 getNodeForConstantPointer(C)));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000870 } else if (C->isNullValue()) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000871 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
872 NullObject));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000873 return;
Chris Lattner8a446432005-03-29 06:09:07 +0000874 } else if (!isa<UndefValue>(C)) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000875 // If this is an array or struct, include constraints for each element.
876 assert(isa<ConstantArray>(C) || isa<ConstantStruct>(C));
877 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
Daniel Berlinaad15882007-09-16 21:45:02 +0000878 AddGlobalInitializerConstraints(NodeIndex,
879 cast<Constant>(C->getOperand(i)));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000880 }
881}
882
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000883/// AddConstraintsForNonInternalLinkage - If this function does not have
884/// internal linkage, realize that we can't trust anything passed into or
885/// returned by this function.
Chris Lattnere995a2a2004-05-23 21:00:47 +0000886void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
Chris Lattnere4d5c442005-03-15 04:54:21 +0000887 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000888 if (isa<PointerType>(I->getType()))
889 // If this is an argument of an externally accessible function, the
890 // incoming pointer might point to anything.
891 Constraints.push_back(Constraint(Constraint::Copy, getNode(I),
Daniel Berlinaad15882007-09-16 21:45:02 +0000892 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000893}
894
Chris Lattner8a446432005-03-29 06:09:07 +0000895/// AddConstraintsForCall - If this is a call to a "known" function, add the
896/// constraints and return true. If this is a call to an unknown function,
897/// return false.
898bool Andersens::AddConstraintsForExternalCall(CallSite CS, Function *F) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000899 assert(F->isDeclaration() && "Not an external function!");
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000900
901 // These functions don't induce any points-to constraints.
Chris Lattner175b9632005-03-29 20:36:05 +0000902 if (F->getName() == "atoi" || F->getName() == "atof" ||
903 F->getName() == "atol" || F->getName() == "atoll" ||
904 F->getName() == "remove" || F->getName() == "unlink" ||
905 F->getName() == "rename" || F->getName() == "memcmp" ||
Chris Lattner824b9582008-11-21 16:42:48 +0000906 F->getName() == "llvm.memset" ||
Chris Lattner175b9632005-03-29 20:36:05 +0000907 F->getName() == "strcmp" || F->getName() == "strncmp" ||
908 F->getName() == "execl" || F->getName() == "execlp" ||
909 F->getName() == "execle" || F->getName() == "execv" ||
910 F->getName() == "execvp" || F->getName() == "chmod" ||
911 F->getName() == "puts" || F->getName() == "write" ||
912 F->getName() == "open" || F->getName() == "create" ||
913 F->getName() == "truncate" || F->getName() == "chdir" ||
914 F->getName() == "mkdir" || F->getName() == "rmdir" ||
915 F->getName() == "read" || F->getName() == "pipe" ||
916 F->getName() == "wait" || F->getName() == "time" ||
917 F->getName() == "stat" || F->getName() == "fstat" ||
918 F->getName() == "lstat" || F->getName() == "strtod" ||
919 F->getName() == "strtof" || F->getName() == "strtold" ||
920 F->getName() == "fopen" || F->getName() == "fdopen" ||
921 F->getName() == "freopen" ||
922 F->getName() == "fflush" || F->getName() == "feof" ||
923 F->getName() == "fileno" || F->getName() == "clearerr" ||
924 F->getName() == "rewind" || F->getName() == "ftell" ||
925 F->getName() == "ferror" || F->getName() == "fgetc" ||
926 F->getName() == "fgetc" || F->getName() == "_IO_getc" ||
927 F->getName() == "fwrite" || F->getName() == "fread" ||
928 F->getName() == "fgets" || F->getName() == "ungetc" ||
929 F->getName() == "fputc" ||
930 F->getName() == "fputs" || F->getName() == "putc" ||
931 F->getName() == "ftell" || F->getName() == "rewind" ||
932 F->getName() == "_IO_putc" || F->getName() == "fseek" ||
933 F->getName() == "fgetpos" || F->getName() == "fsetpos" ||
934 F->getName() == "printf" || F->getName() == "fprintf" ||
935 F->getName() == "sprintf" || F->getName() == "vprintf" ||
936 F->getName() == "vfprintf" || F->getName() == "vsprintf" ||
937 F->getName() == "scanf" || F->getName() == "fscanf" ||
938 F->getName() == "sscanf" || F->getName() == "__assert_fail" ||
939 F->getName() == "modf")
Chris Lattner8a446432005-03-29 06:09:07 +0000940 return true;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000941
Chris Lattner175b9632005-03-29 20:36:05 +0000942
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000943 // These functions do induce points-to edges.
Chris Lattner824b9582008-11-21 16:42:48 +0000944 if (F->getName() == "llvm.memcpy" ||
945 F->getName() == "llvm.memmove" ||
Chris Lattner4de57fd2005-03-29 06:52:20 +0000946 F->getName() == "memmove") {
Daniel Berlinaad15882007-09-16 21:45:02 +0000947
Nick Lewycky3037eda2008-12-27 16:20:53 +0000948 const FunctionType *FTy = F->getFunctionType();
949 if (FTy->getNumParams() > 1 &&
950 isa<PointerType>(FTy->getParamType(0)) &&
951 isa<PointerType>(FTy->getParamType(1))) {
952
953 // *Dest = *Src, which requires an artificial graph node to represent the
954 // constraint. It is broken up into *Dest = temp, temp = *Src
955 unsigned FirstArg = getNode(CS.getArgument(0));
956 unsigned SecondArg = getNode(CS.getArgument(1));
957 unsigned TempArg = GraphNodes.size();
958 GraphNodes.push_back(Node());
959 Constraints.push_back(Constraint(Constraint::Store,
960 FirstArg, TempArg));
961 Constraints.push_back(Constraint(Constraint::Load,
962 TempArg, SecondArg));
963 // In addition, Dest = Src
964 Constraints.push_back(Constraint(Constraint::Copy,
965 FirstArg, SecondArg));
966 return true;
967 }
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000968 }
969
Chris Lattner77b50562005-03-29 20:04:24 +0000970 // Result = Arg0
971 if (F->getName() == "realloc" || F->getName() == "strchr" ||
972 F->getName() == "strrchr" || F->getName() == "strstr" ||
973 F->getName() == "strtok") {
Nick Lewycky3037eda2008-12-27 16:20:53 +0000974 const FunctionType *FTy = F->getFunctionType();
975 if (FTy->getNumParams() > 0 &&
976 isa<PointerType>(FTy->getParamType(0))) {
977 Constraints.push_back(Constraint(Constraint::Copy,
978 getNode(CS.getInstruction()),
979 getNode(CS.getArgument(0))));
980 return true;
981 }
Chris Lattner8a446432005-03-29 06:09:07 +0000982 }
983
984 return false;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000985}
986
987
Chris Lattnere995a2a2004-05-23 21:00:47 +0000988
Daniel Berlinaad15882007-09-16 21:45:02 +0000989/// AnalyzeUsesOfFunction - Look at all of the users of the specified function.
990/// If this is used by anything complex (i.e., the address escapes), return
991/// true.
992bool Andersens::AnalyzeUsesOfFunction(Value *V) {
993
994 if (!isa<PointerType>(V->getType())) return true;
995
996 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
997 if (dyn_cast<LoadInst>(*UI)) {
998 return false;
999 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
1000 if (V == SI->getOperand(1)) {
1001 return false;
1002 } else if (SI->getOperand(1)) {
1003 return true; // Storing the pointer
1004 }
1005 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1006 if (AnalyzeUsesOfFunction(GEP)) return true;
1007 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
1008 // Make sure that this is just the function being called, not that it is
1009 // passing into the function.
1010 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
1011 if (CI->getOperand(i) == V) return true;
1012 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
1013 // Make sure that this is just the function being called, not that it is
1014 // passing into the function.
Bill Wendling9a507cd2009-03-13 21:15:59 +00001015 for (unsigned i = 3, e = II->getNumOperands(); i != e; ++i)
Daniel Berlinaad15882007-09-16 21:45:02 +00001016 if (II->getOperand(i) == V) return true;
1017 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
1018 if (CE->getOpcode() == Instruction::GetElementPtr ||
1019 CE->getOpcode() == Instruction::BitCast) {
1020 if (AnalyzeUsesOfFunction(CE))
1021 return true;
1022 } else {
1023 return true;
1024 }
1025 } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(*UI)) {
1026 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1027 return true; // Allow comparison against null.
1028 } else if (dyn_cast<FreeInst>(*UI)) {
1029 return false;
1030 } else {
1031 return true;
1032 }
1033 return false;
1034}
1035
Chris Lattnere995a2a2004-05-23 21:00:47 +00001036/// CollectConstraints - This stage scans the program, adding a constraint to
1037/// the Constraints list for each instruction in the program that induces a
1038/// constraint, and setting up the initial points-to graph.
1039///
1040void Andersens::CollectConstraints(Module &M) {
1041 // First, the universal set points to itself.
Daniel Berlinaad15882007-09-16 21:45:02 +00001042 Constraints.push_back(Constraint(Constraint::AddressOf, UniversalSet,
1043 UniversalSet));
1044 Constraints.push_back(Constraint(Constraint::Store, UniversalSet,
1045 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001046
1047 // Next, the null pointer points to the null object.
Daniel Berlinaad15882007-09-16 21:45:02 +00001048 Constraints.push_back(Constraint(Constraint::AddressOf, NullPtr, NullObject));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001049
1050 // Next, add any constraints on global variables and their initializers.
Chris Lattner493f6362005-03-27 22:03:46 +00001051 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1052 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001053 // Associate the address of the global object as pointing to the memory for
1054 // the global: &G = <G memory>
Daniel Berlinaad15882007-09-16 21:45:02 +00001055 unsigned ObjectIndex = getObject(I);
1056 Node *Object = &GraphNodes[ObjectIndex];
Chris Lattnere995a2a2004-05-23 21:00:47 +00001057 Object->setValue(I);
Daniel Berlinaad15882007-09-16 21:45:02 +00001058 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(*I),
1059 ObjectIndex));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001060
1061 if (I->hasInitializer()) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001062 AddGlobalInitializerConstraints(ObjectIndex, I->getInitializer());
Chris Lattnere995a2a2004-05-23 21:00:47 +00001063 } else {
1064 // If it doesn't have an initializer (i.e. it's defined in another
1065 // translation unit), it points to the universal set.
Daniel Berlinaad15882007-09-16 21:45:02 +00001066 Constraints.push_back(Constraint(Constraint::Copy, ObjectIndex,
1067 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001068 }
1069 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001070
Chris Lattnere995a2a2004-05-23 21:00:47 +00001071 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001072 // Set up the return value node.
1073 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
Daniel Berlinaad15882007-09-16 21:45:02 +00001074 GraphNodes[getReturnNode(F)].setValue(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001075 if (F->getFunctionType()->isVarArg())
Daniel Berlinaad15882007-09-16 21:45:02 +00001076 GraphNodes[getVarargNode(F)].setValue(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001077
1078 // Set up incoming argument nodes.
Chris Lattner493f6362005-03-27 22:03:46 +00001079 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
1080 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +00001081 if (isa<PointerType>(I->getType()))
1082 getNodeValue(*I);
1083
Daniel Berlinaad15882007-09-16 21:45:02 +00001084 // At some point we should just add constraints for the escaping functions
1085 // at solve time, but this slows down solving. For now, we simply mark
1086 // address taken functions as escaping and treat them as external.
Rafael Espindolabb46f522009-01-15 20:18:42 +00001087 if (!F->hasLocalLinkage() || AnalyzeUsesOfFunction(F))
Chris Lattnere995a2a2004-05-23 21:00:47 +00001088 AddConstraintsForNonInternalLinkage(F);
1089
Reid Spencer5cbf9852007-01-30 20:08:39 +00001090 if (!F->isDeclaration()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001091 // Scan the function body, creating a memory object for each heap/stack
1092 // allocation in the body of the function and a node to represent all
1093 // pointer values defined by instructions and used as operands.
1094 visit(F);
Chris Lattner8a446432005-03-29 06:09:07 +00001095 } else {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001096 // External functions that return pointers return the universal set.
1097 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
1098 Constraints.push_back(Constraint(Constraint::Copy,
1099 getReturnNode(F),
Daniel Berlinaad15882007-09-16 21:45:02 +00001100 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001101
1102 // Any pointers that are passed into the function have the universal set
1103 // stored into them.
Chris Lattner493f6362005-03-27 22:03:46 +00001104 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
1105 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +00001106 if (isa<PointerType>(I->getType())) {
1107 // Pointers passed into external functions could have anything stored
1108 // through them.
1109 Constraints.push_back(Constraint(Constraint::Store, getNode(I),
Daniel Berlinaad15882007-09-16 21:45:02 +00001110 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001111 // Memory objects passed into external function calls can have the
1112 // universal set point to them.
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001113#if FULL_UNIVERSAL
Chris Lattnere995a2a2004-05-23 21:00:47 +00001114 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001115 UniversalSet,
Chris Lattnere995a2a2004-05-23 21:00:47 +00001116 getNode(I)));
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001117#else
1118 Constraints.push_back(Constraint(Constraint::Copy,
1119 getNode(I),
1120 UniversalSet));
1121#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001122 }
1123
1124 // If this is an external varargs function, it can also store pointers
1125 // into any pointers passed through the varargs section.
1126 if (F->getFunctionType()->isVarArg())
1127 Constraints.push_back(Constraint(Constraint::Store, getVarargNode(F),
Daniel Berlinaad15882007-09-16 21:45:02 +00001128 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001129 }
1130 }
1131 NumConstraints += Constraints.size();
1132}
1133
1134
1135void Andersens::visitInstruction(Instruction &I) {
1136#ifdef NDEBUG
1137 return; // This function is just a big assert.
1138#endif
1139 if (isa<BinaryOperator>(I))
1140 return;
1141 // Most instructions don't have any effect on pointer values.
1142 switch (I.getOpcode()) {
1143 case Instruction::Br:
1144 case Instruction::Switch:
1145 case Instruction::Unwind:
Chris Lattnerc17edbd2004-10-16 18:16:19 +00001146 case Instruction::Unreachable:
Chris Lattnere995a2a2004-05-23 21:00:47 +00001147 case Instruction::Free:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001148 case Instruction::ICmp:
1149 case Instruction::FCmp:
Chris Lattnere995a2a2004-05-23 21:00:47 +00001150 return;
1151 default:
1152 // Is this something we aren't handling yet?
Bill Wendlinge8156192006-12-07 01:30:32 +00001153 cerr << "Unknown instruction: " << I;
Chris Lattnere995a2a2004-05-23 21:00:47 +00001154 abort();
1155 }
1156}
1157
1158void Andersens::visitAllocationInst(AllocationInst &AI) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001159 unsigned ObjectIndex = getObject(&AI);
1160 GraphNodes[ObjectIndex].setValue(&AI);
1161 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(AI),
1162 ObjectIndex));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001163}
1164
1165void Andersens::visitReturnInst(ReturnInst &RI) {
1166 if (RI.getNumOperands() && isa<PointerType>(RI.getOperand(0)->getType()))
1167 // return V --> <Copy/retval{F}/v>
1168 Constraints.push_back(Constraint(Constraint::Copy,
1169 getReturnNode(RI.getParent()->getParent()),
1170 getNode(RI.getOperand(0))));
1171}
1172
1173void Andersens::visitLoadInst(LoadInst &LI) {
1174 if (isa<PointerType>(LI.getType()))
1175 // P1 = load P2 --> <Load/P1/P2>
1176 Constraints.push_back(Constraint(Constraint::Load, getNodeValue(LI),
1177 getNode(LI.getOperand(0))));
1178}
1179
1180void Andersens::visitStoreInst(StoreInst &SI) {
1181 if (isa<PointerType>(SI.getOperand(0)->getType()))
1182 // store P1, P2 --> <Store/P2/P1>
1183 Constraints.push_back(Constraint(Constraint::Store,
1184 getNode(SI.getOperand(1)),
1185 getNode(SI.getOperand(0))));
1186}
1187
1188void Andersens::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1189 // P1 = getelementptr P2, ... --> <Copy/P1/P2>
1190 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(GEP),
1191 getNode(GEP.getOperand(0))));
1192}
1193
1194void Andersens::visitPHINode(PHINode &PN) {
1195 if (isa<PointerType>(PN.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001196 unsigned PNN = getNodeValue(PN);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001197 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1198 // P1 = phi P2, P3 --> <Copy/P1/P2>, <Copy/P1/P3>, ...
1199 Constraints.push_back(Constraint(Constraint::Copy, PNN,
1200 getNode(PN.getIncomingValue(i))));
1201 }
1202}
1203
1204void Andersens::visitCastInst(CastInst &CI) {
1205 Value *Op = CI.getOperand(0);
1206 if (isa<PointerType>(CI.getType())) {
1207 if (isa<PointerType>(Op->getType())) {
1208 // P1 = cast P2 --> <Copy/P1/P2>
1209 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
1210 getNode(CI.getOperand(0))));
1211 } else {
1212 // P1 = cast int --> <Copy/P1/Univ>
Chris Lattner175b9632005-03-29 20:36:05 +00001213#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +00001214 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
Daniel Berlinaad15882007-09-16 21:45:02 +00001215 UniversalSet));
Chris Lattnerbd135c72005-04-05 01:12:03 +00001216#else
1217 getNodeValue(CI);
Chris Lattner175b9632005-03-29 20:36:05 +00001218#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001219 }
1220 } else if (isa<PointerType>(Op->getType())) {
1221 // int = cast P1 --> <Copy/Univ/P1>
Chris Lattner175b9632005-03-29 20:36:05 +00001222#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +00001223 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001224 UniversalSet,
Chris Lattnere995a2a2004-05-23 21:00:47 +00001225 getNode(CI.getOperand(0))));
Chris Lattnerbd135c72005-04-05 01:12:03 +00001226#else
1227 getNode(CI.getOperand(0));
Chris Lattner175b9632005-03-29 20:36:05 +00001228#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001229 }
1230}
1231
1232void Andersens::visitSelectInst(SelectInst &SI) {
1233 if (isa<PointerType>(SI.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001234 unsigned SIN = getNodeValue(SI);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001235 // P1 = select C, P2, P3 ---> <Copy/P1/P2>, <Copy/P1/P3>
1236 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1237 getNode(SI.getOperand(1))));
1238 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1239 getNode(SI.getOperand(2))));
1240 }
1241}
1242
Chris Lattnere995a2a2004-05-23 21:00:47 +00001243void Andersens::visitVAArg(VAArgInst &I) {
1244 assert(0 && "vaarg not handled yet!");
1245}
1246
1247/// AddConstraintsForCall - Add constraints for a call with actual arguments
1248/// specified by CS to the function specified by F. Note that the types of
1249/// arguments might not match up in the case where this is an indirect call and
1250/// the function pointer has been casted. If this is the case, do something
1251/// reasonable.
1252void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001253 Value *CallValue = CS.getCalledValue();
1254 bool IsDeref = F == NULL;
1255
1256 // If this is a call to an external function, try to handle it directly to get
1257 // some taste of context sensitivity.
1258 if (F && F->isDeclaration() && AddConstraintsForExternalCall(CS, F))
Chris Lattner8a446432005-03-29 06:09:07 +00001259 return;
1260
Chris Lattnere995a2a2004-05-23 21:00:47 +00001261 if (isa<PointerType>(CS.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001262 unsigned CSN = getNode(CS.getInstruction());
1263 if (!F || isa<PointerType>(F->getFunctionType()->getReturnType())) {
1264 if (IsDeref)
1265 Constraints.push_back(Constraint(Constraint::Load, CSN,
1266 getNode(CallValue), CallReturnPos));
1267 else
1268 Constraints.push_back(Constraint(Constraint::Copy, CSN,
1269 getNode(CallValue) + CallReturnPos));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001270 } else {
1271 // If the function returns a non-pointer value, handle this just like we
1272 // treat a nonpointer cast to pointer.
1273 Constraints.push_back(Constraint(Constraint::Copy, CSN,
Daniel Berlinaad15882007-09-16 21:45:02 +00001274 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001275 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001276 } else if (F && isa<PointerType>(F->getFunctionType()->getReturnType())) {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001277#if FULL_UNIVERSAL
Chris Lattnere995a2a2004-05-23 21:00:47 +00001278 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001279 UniversalSet,
1280 getNode(CallValue) + CallReturnPos));
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001281#else
1282 Constraints.push_back(Constraint(Constraint::Copy,
1283 getNode(CallValue) + CallReturnPos,
1284 UniversalSet));
1285#endif
1286
1287
Chris Lattnere995a2a2004-05-23 21:00:47 +00001288 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001289
Chris Lattnere995a2a2004-05-23 21:00:47 +00001290 CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
Daniel Berlind3bf1ae2008-03-18 22:22:53 +00001291 bool external = !F || F->isDeclaration();
Daniel Berlinaad15882007-09-16 21:45:02 +00001292 if (F) {
1293 // Direct Call
1294 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
Daniel Berlind3bf1ae2008-03-18 22:22:53 +00001295 for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI)
1296 {
1297#if !FULL_UNIVERSAL
1298 if (external && isa<PointerType>((*ArgI)->getType()))
1299 {
1300 // Add constraint that ArgI can now point to anything due to
1301 // escaping, as can everything it points to. The second portion of
1302 // this should be taken care of by universal = *universal
1303 Constraints.push_back(Constraint(Constraint::Copy,
1304 getNode(*ArgI),
1305 UniversalSet));
1306 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001307#endif
Daniel Berlind3bf1ae2008-03-18 22:22:53 +00001308 if (isa<PointerType>(AI->getType())) {
1309 if (isa<PointerType>((*ArgI)->getType())) {
1310 // Copy the actual argument into the formal argument.
1311 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1312 getNode(*ArgI)));
1313 } else {
1314 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1315 UniversalSet));
1316 }
1317 } else if (isa<PointerType>((*ArgI)->getType())) {
1318#if FULL_UNIVERSAL
1319 Constraints.push_back(Constraint(Constraint::Copy,
1320 UniversalSet,
1321 getNode(*ArgI)));
1322#else
1323 Constraints.push_back(Constraint(Constraint::Copy,
1324 getNode(*ArgI),
1325 UniversalSet));
1326#endif
1327 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001328 }
1329 } else {
1330 //Indirect Call
1331 unsigned ArgPos = CallFirstArgPos;
1332 for (; ArgI != ArgE; ++ArgI) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001333 if (isa<PointerType>((*ArgI)->getType())) {
1334 // Copy the actual argument into the formal argument.
Daniel Berlinaad15882007-09-16 21:45:02 +00001335 Constraints.push_back(Constraint(Constraint::Store,
1336 getNode(CallValue),
1337 getNode(*ArgI), ArgPos++));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001338 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +00001339 Constraints.push_back(Constraint(Constraint::Store,
1340 getNode (CallValue),
1341 UniversalSet, ArgPos++));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001342 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00001343 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001344 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00001345 // Copy all pointers passed through the varargs section to the varargs node.
Daniel Berlinaad15882007-09-16 21:45:02 +00001346 if (F && F->getFunctionType()->isVarArg())
Chris Lattnere995a2a2004-05-23 21:00:47 +00001347 for (; ArgI != ArgE; ++ArgI)
1348 if (isa<PointerType>((*ArgI)->getType()))
1349 Constraints.push_back(Constraint(Constraint::Copy, getVarargNode(F),
1350 getNode(*ArgI)));
1351 // If more arguments are passed in than we track, just drop them on the floor.
1352}
1353
1354void Andersens::visitCallSite(CallSite CS) {
1355 if (isa<PointerType>(CS.getType()))
1356 getNodeValue(*CS.getInstruction());
1357
1358 if (Function *F = CS.getCalledFunction()) {
1359 AddConstraintsForCall(CS, F);
1360 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +00001361 AddConstraintsForCall(CS, NULL);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001362 }
1363}
1364
1365//===----------------------------------------------------------------------===//
1366// Constraint Solving Phase
1367//===----------------------------------------------------------------------===//
1368
1369/// intersects - Return true if the points-to set of this node intersects
1370/// with the points-to set of the specified node.
1371bool Andersens::Node::intersects(Node *N) const {
Daniel Berlinaad15882007-09-16 21:45:02 +00001372 return PointsTo->intersects(N->PointsTo);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001373}
1374
1375/// intersectsIgnoring - Return true if the points-to set of this node
1376/// intersects with the points-to set of the specified node on any nodes
1377/// except for the specified node to ignore.
Daniel Berlinaad15882007-09-16 21:45:02 +00001378bool Andersens::Node::intersectsIgnoring(Node *N, unsigned Ignoring) const {
1379 // TODO: If we are only going to call this with the same value for Ignoring,
1380 // we should move the special values out of the points-to bitmap.
1381 bool WeHadIt = PointsTo->test(Ignoring);
1382 bool NHadIt = N->PointsTo->test(Ignoring);
1383 bool Result = false;
1384 if (WeHadIt)
1385 PointsTo->reset(Ignoring);
1386 if (NHadIt)
1387 N->PointsTo->reset(Ignoring);
1388 Result = PointsTo->intersects(N->PointsTo);
1389 if (WeHadIt)
1390 PointsTo->set(Ignoring);
1391 if (NHadIt)
1392 N->PointsTo->set(Ignoring);
1393 return Result;
Chris Lattnere995a2a2004-05-23 21:00:47 +00001394}
1395
Daniel Berlind81ccc22007-09-24 19:45:49 +00001396void dumpToDOUT(SparseBitVector<> *bitmap) {
Bill Wendlingcab5f5d2007-09-24 22:43:48 +00001397#ifndef NDEBUG
Daniel Berlind81ccc22007-09-24 19:45:49 +00001398 dump(*bitmap, DOUT);
Bill Wendlingcab5f5d2007-09-24 22:43:48 +00001399#endif
Daniel Berlind81ccc22007-09-24 19:45:49 +00001400}
1401
1402
1403/// Clump together address taken variables so that the points-to sets use up
1404/// less space and can be operated on faster.
1405
1406void Andersens::ClumpAddressTaken() {
1407#undef DEBUG_TYPE
1408#define DEBUG_TYPE "anders-aa-renumber"
1409 std::vector<unsigned> Translate;
1410 std::vector<Node> NewGraphNodes;
1411
1412 Translate.resize(GraphNodes.size());
1413 unsigned NewPos = 0;
1414
1415 for (unsigned i = 0; i < Constraints.size(); ++i) {
1416 Constraint &C = Constraints[i];
1417 if (C.Type == Constraint::AddressOf) {
1418 GraphNodes[C.Src].AddressTaken = true;
1419 }
1420 }
1421 for (unsigned i = 0; i < NumberSpecialNodes; ++i) {
1422 unsigned Pos = NewPos++;
1423 Translate[i] = Pos;
1424 NewGraphNodes.push_back(GraphNodes[i]);
1425 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1426 }
1427
1428 // I believe this ends up being faster than making two vectors and splicing
1429 // them.
1430 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1431 if (GraphNodes[i].AddressTaken) {
1432 unsigned Pos = NewPos++;
1433 Translate[i] = Pos;
1434 NewGraphNodes.push_back(GraphNodes[i]);
1435 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1436 }
1437 }
1438
1439 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1440 if (!GraphNodes[i].AddressTaken) {
1441 unsigned Pos = NewPos++;
1442 Translate[i] = Pos;
1443 NewGraphNodes.push_back(GraphNodes[i]);
1444 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1445 }
1446 }
1447
1448 for (DenseMap<Value*, unsigned>::iterator Iter = ValueNodes.begin();
1449 Iter != ValueNodes.end();
1450 ++Iter)
1451 Iter->second = Translate[Iter->second];
1452
1453 for (DenseMap<Value*, unsigned>::iterator Iter = ObjectNodes.begin();
1454 Iter != ObjectNodes.end();
1455 ++Iter)
1456 Iter->second = Translate[Iter->second];
1457
1458 for (DenseMap<Function*, unsigned>::iterator Iter = ReturnNodes.begin();
1459 Iter != ReturnNodes.end();
1460 ++Iter)
1461 Iter->second = Translate[Iter->second];
1462
1463 for (DenseMap<Function*, unsigned>::iterator Iter = VarargNodes.begin();
1464 Iter != VarargNodes.end();
1465 ++Iter)
1466 Iter->second = Translate[Iter->second];
1467
1468 for (unsigned i = 0; i < Constraints.size(); ++i) {
1469 Constraint &C = Constraints[i];
1470 C.Src = Translate[C.Src];
1471 C.Dest = Translate[C.Dest];
1472 }
1473
1474 GraphNodes.swap(NewGraphNodes);
1475#undef DEBUG_TYPE
1476#define DEBUG_TYPE "anders-aa"
1477}
1478
1479/// The technique used here is described in "Exploiting Pointer and Location
1480/// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1481/// Analysis Symposium (SAS), August 2007." It is known as the "HVN" algorithm,
1482/// and is equivalent to value numbering the collapsed constraint graph without
1483/// evaluating unions. This is used as a pre-pass to HU in order to resolve
1484/// first order pointer dereferences and speed up/reduce memory usage of HU.
1485/// Running both is equivalent to HRU without the iteration
1486/// HVN in more detail:
1487/// Imagine the set of constraints was simply straight line code with no loops
1488/// (we eliminate cycles, so there are no loops), such as:
1489/// E = &D
1490/// E = &C
1491/// E = F
1492/// F = G
1493/// G = F
1494/// Applying value numbering to this code tells us:
1495/// G == F == E
1496///
1497/// For HVN, this is as far as it goes. We assign new value numbers to every
1498/// "address node", and every "reference node".
1499/// To get the optimal result for this, we use a DFS + SCC (since all nodes in a
1500/// cycle must have the same value number since the = operation is really
1501/// inclusion, not overwrite), and value number nodes we receive points-to sets
1502/// before we value our own node.
1503/// The advantage of HU over HVN is that HU considers the inclusion property, so
1504/// that if you have
1505/// E = &D
1506/// E = &C
1507/// E = F
1508/// F = G
1509/// F = &D
1510/// G = F
1511/// HU will determine that G == F == E. HVN will not, because it cannot prove
1512/// that the points to information ends up being the same because they all
1513/// receive &D from E anyway.
1514
1515void Andersens::HVN() {
1516 DOUT << "Beginning HVN\n";
1517 // Build a predecessor graph. This is like our constraint graph with the
1518 // edges going in the opposite direction, and there are edges for all the
1519 // constraints, instead of just copy constraints. We also build implicit
1520 // edges for constraints are implied but not explicit. I.E for the constraint
1521 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1522 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1523 Constraint &C = Constraints[i];
1524 if (C.Type == Constraint::AddressOf) {
1525 GraphNodes[C.Src].AddressTaken = true;
1526 GraphNodes[C.Src].Direct = false;
1527
1528 // Dest = &src edge
1529 unsigned AdrNode = C.Src + FirstAdrNode;
1530 if (!GraphNodes[C.Dest].PredEdges)
1531 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1532 GraphNodes[C.Dest].PredEdges->set(AdrNode);
1533
1534 // *Dest = src edge
1535 unsigned RefNode = C.Dest + FirstRefNode;
1536 if (!GraphNodes[RefNode].ImplicitPredEdges)
1537 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1538 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1539 } else if (C.Type == Constraint::Load) {
1540 if (C.Offset == 0) {
1541 // dest = *src edge
1542 if (!GraphNodes[C.Dest].PredEdges)
1543 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1544 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1545 } else {
1546 GraphNodes[C.Dest].Direct = false;
1547 }
1548 } else if (C.Type == Constraint::Store) {
1549 if (C.Offset == 0) {
1550 // *dest = src edge
1551 unsigned RefNode = C.Dest + FirstRefNode;
1552 if (!GraphNodes[RefNode].PredEdges)
1553 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1554 GraphNodes[RefNode].PredEdges->set(C.Src);
1555 }
1556 } else {
1557 // Dest = Src edge and *Dest = *Src edge
1558 if (!GraphNodes[C.Dest].PredEdges)
1559 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1560 GraphNodes[C.Dest].PredEdges->set(C.Src);
1561 unsigned RefNode = C.Dest + FirstRefNode;
1562 if (!GraphNodes[RefNode].ImplicitPredEdges)
1563 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1564 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1565 }
1566 }
1567 PEClass = 1;
1568 // Do SCC finding first to condense our predecessor graph
1569 DFSNumber = 0;
1570 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1571 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1572 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1573
1574 for (unsigned i = 0; i < FirstRefNode; ++i) {
1575 unsigned Node = VSSCCRep[i];
1576 if (!Node2Visited[Node])
1577 HVNValNum(Node);
1578 }
1579 for (BitVectorMap::iterator Iter = Set2PEClass.begin();
1580 Iter != Set2PEClass.end();
1581 ++Iter)
1582 delete Iter->first;
1583 Set2PEClass.clear();
1584 Node2DFS.clear();
1585 Node2Deleted.clear();
1586 Node2Visited.clear();
1587 DOUT << "Finished HVN\n";
1588
1589}
1590
1591/// This is the workhorse of HVN value numbering. We combine SCC finding at the
1592/// same time because it's easy.
1593void Andersens::HVNValNum(unsigned NodeIndex) {
1594 unsigned MyDFS = DFSNumber++;
1595 Node *N = &GraphNodes[NodeIndex];
1596 Node2Visited[NodeIndex] = true;
1597 Node2DFS[NodeIndex] = MyDFS;
1598
1599 // First process all our explicit edges
1600 if (N->PredEdges)
1601 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1602 Iter != N->PredEdges->end();
1603 ++Iter) {
1604 unsigned j = VSSCCRep[*Iter];
1605 if (!Node2Deleted[j]) {
1606 if (!Node2Visited[j])
1607 HVNValNum(j);
1608 if (Node2DFS[NodeIndex] > Node2DFS[j])
1609 Node2DFS[NodeIndex] = Node2DFS[j];
1610 }
1611 }
1612
1613 // Now process all the implicit edges
1614 if (N->ImplicitPredEdges)
1615 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1616 Iter != N->ImplicitPredEdges->end();
1617 ++Iter) {
1618 unsigned j = VSSCCRep[*Iter];
1619 if (!Node2Deleted[j]) {
1620 if (!Node2Visited[j])
1621 HVNValNum(j);
1622 if (Node2DFS[NodeIndex] > Node2DFS[j])
1623 Node2DFS[NodeIndex] = Node2DFS[j];
1624 }
1625 }
1626
1627 // See if we found any cycles
1628 if (MyDFS == Node2DFS[NodeIndex]) {
1629 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1630 unsigned CycleNodeIndex = SCCStack.top();
1631 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1632 VSSCCRep[CycleNodeIndex] = NodeIndex;
1633 // Unify the nodes
1634 N->Direct &= CycleNode->Direct;
1635
1636 if (CycleNode->PredEdges) {
1637 if (!N->PredEdges)
1638 N->PredEdges = new SparseBitVector<>;
1639 *(N->PredEdges) |= CycleNode->PredEdges;
1640 delete CycleNode->PredEdges;
1641 CycleNode->PredEdges = NULL;
1642 }
1643 if (CycleNode->ImplicitPredEdges) {
1644 if (!N->ImplicitPredEdges)
1645 N->ImplicitPredEdges = new SparseBitVector<>;
1646 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1647 delete CycleNode->ImplicitPredEdges;
1648 CycleNode->ImplicitPredEdges = NULL;
1649 }
1650
1651 SCCStack.pop();
1652 }
1653
1654 Node2Deleted[NodeIndex] = true;
1655
1656 if (!N->Direct) {
1657 GraphNodes[NodeIndex].PointerEquivLabel = PEClass++;
1658 return;
1659 }
1660
1661 // Collect labels of successor nodes
1662 bool AllSame = true;
1663 unsigned First = ~0;
1664 SparseBitVector<> *Labels = new SparseBitVector<>;
1665 bool Used = false;
1666
1667 if (N->PredEdges)
1668 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1669 Iter != N->PredEdges->end();
1670 ++Iter) {
1671 unsigned j = VSSCCRep[*Iter];
1672 unsigned Label = GraphNodes[j].PointerEquivLabel;
1673 // Ignore labels that are equal to us or non-pointers
1674 if (j == NodeIndex || Label == 0)
1675 continue;
1676 if (First == (unsigned)~0)
1677 First = Label;
1678 else if (First != Label)
1679 AllSame = false;
1680 Labels->set(Label);
1681 }
1682
1683 // We either have a non-pointer, a copy of an existing node, or a new node.
1684 // Assign the appropriate pointer equivalence label.
1685 if (Labels->empty()) {
1686 GraphNodes[NodeIndex].PointerEquivLabel = 0;
1687 } else if (AllSame) {
1688 GraphNodes[NodeIndex].PointerEquivLabel = First;
1689 } else {
1690 GraphNodes[NodeIndex].PointerEquivLabel = Set2PEClass[Labels];
1691 if (GraphNodes[NodeIndex].PointerEquivLabel == 0) {
1692 unsigned EquivClass = PEClass++;
1693 Set2PEClass[Labels] = EquivClass;
1694 GraphNodes[NodeIndex].PointerEquivLabel = EquivClass;
1695 Used = true;
1696 }
1697 }
1698 if (!Used)
1699 delete Labels;
1700 } else {
1701 SCCStack.push(NodeIndex);
1702 }
1703}
1704
1705/// The technique used here is described in "Exploiting Pointer and Location
1706/// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1707/// Analysis Symposium (SAS), August 2007." It is known as the "HU" algorithm,
1708/// and is equivalent to value numbering the collapsed constraint graph
1709/// including evaluating unions.
1710void Andersens::HU() {
1711 DOUT << "Beginning HU\n";
1712 // Build a predecessor graph. This is like our constraint graph with the
1713 // edges going in the opposite direction, and there are edges for all the
1714 // constraints, instead of just copy constraints. We also build implicit
1715 // edges for constraints are implied but not explicit. I.E for the constraint
1716 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1717 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1718 Constraint &C = Constraints[i];
1719 if (C.Type == Constraint::AddressOf) {
1720 GraphNodes[C.Src].AddressTaken = true;
1721 GraphNodes[C.Src].Direct = false;
1722
1723 GraphNodes[C.Dest].PointsTo->set(C.Src);
1724 // *Dest = src edge
1725 unsigned RefNode = C.Dest + FirstRefNode;
1726 if (!GraphNodes[RefNode].ImplicitPredEdges)
1727 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1728 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1729 GraphNodes[C.Src].PointedToBy->set(C.Dest);
1730 } else if (C.Type == Constraint::Load) {
1731 if (C.Offset == 0) {
1732 // dest = *src edge
1733 if (!GraphNodes[C.Dest].PredEdges)
1734 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1735 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1736 } else {
1737 GraphNodes[C.Dest].Direct = false;
1738 }
1739 } else if (C.Type == Constraint::Store) {
1740 if (C.Offset == 0) {
1741 // *dest = src edge
1742 unsigned RefNode = C.Dest + FirstRefNode;
1743 if (!GraphNodes[RefNode].PredEdges)
1744 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1745 GraphNodes[RefNode].PredEdges->set(C.Src);
1746 }
1747 } else {
1748 // Dest = Src edge and *Dest = *Src edg
1749 if (!GraphNodes[C.Dest].PredEdges)
1750 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1751 GraphNodes[C.Dest].PredEdges->set(C.Src);
1752 unsigned RefNode = C.Dest + FirstRefNode;
1753 if (!GraphNodes[RefNode].ImplicitPredEdges)
1754 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1755 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1756 }
1757 }
1758 PEClass = 1;
1759 // Do SCC finding first to condense our predecessor graph
1760 DFSNumber = 0;
1761 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1762 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1763 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1764
1765 for (unsigned i = 0; i < FirstRefNode; ++i) {
1766 if (FindNode(i) == i) {
1767 unsigned Node = VSSCCRep[i];
1768 if (!Node2Visited[Node])
1769 Condense(Node);
1770 }
1771 }
1772
1773 // Reset tables for actual labeling
1774 Node2DFS.clear();
1775 Node2Visited.clear();
1776 Node2Deleted.clear();
1777 // Pre-grow our densemap so that we don't get really bad behavior
1778 Set2PEClass.resize(GraphNodes.size());
1779
1780 // Visit the condensed graph and generate pointer equivalence labels.
1781 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1782 for (unsigned i = 0; i < FirstRefNode; ++i) {
1783 if (FindNode(i) == i) {
1784 unsigned Node = VSSCCRep[i];
1785 if (!Node2Visited[Node])
1786 HUValNum(Node);
1787 }
1788 }
1789 // PEClass nodes will be deleted by the deleting of N->PointsTo in our caller.
1790 Set2PEClass.clear();
1791 DOUT << "Finished HU\n";
1792}
1793
1794
1795/// Implementation of standard Tarjan SCC algorithm as modified by Nuutilla.
1796void Andersens::Condense(unsigned NodeIndex) {
1797 unsigned MyDFS = DFSNumber++;
1798 Node *N = &GraphNodes[NodeIndex];
1799 Node2Visited[NodeIndex] = true;
1800 Node2DFS[NodeIndex] = MyDFS;
1801
1802 // First process all our explicit edges
1803 if (N->PredEdges)
1804 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1805 Iter != N->PredEdges->end();
1806 ++Iter) {
1807 unsigned j = VSSCCRep[*Iter];
1808 if (!Node2Deleted[j]) {
1809 if (!Node2Visited[j])
1810 Condense(j);
1811 if (Node2DFS[NodeIndex] > Node2DFS[j])
1812 Node2DFS[NodeIndex] = Node2DFS[j];
1813 }
1814 }
1815
1816 // Now process all the implicit edges
1817 if (N->ImplicitPredEdges)
1818 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1819 Iter != N->ImplicitPredEdges->end();
1820 ++Iter) {
1821 unsigned j = VSSCCRep[*Iter];
1822 if (!Node2Deleted[j]) {
1823 if (!Node2Visited[j])
1824 Condense(j);
1825 if (Node2DFS[NodeIndex] > Node2DFS[j])
1826 Node2DFS[NodeIndex] = Node2DFS[j];
1827 }
1828 }
1829
1830 // See if we found any cycles
1831 if (MyDFS == Node2DFS[NodeIndex]) {
1832 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1833 unsigned CycleNodeIndex = SCCStack.top();
1834 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1835 VSSCCRep[CycleNodeIndex] = NodeIndex;
1836 // Unify the nodes
1837 N->Direct &= CycleNode->Direct;
1838
1839 *(N->PointsTo) |= CycleNode->PointsTo;
1840 delete CycleNode->PointsTo;
1841 CycleNode->PointsTo = NULL;
1842 if (CycleNode->PredEdges) {
1843 if (!N->PredEdges)
1844 N->PredEdges = new SparseBitVector<>;
1845 *(N->PredEdges) |= CycleNode->PredEdges;
1846 delete CycleNode->PredEdges;
1847 CycleNode->PredEdges = NULL;
1848 }
1849 if (CycleNode->ImplicitPredEdges) {
1850 if (!N->ImplicitPredEdges)
1851 N->ImplicitPredEdges = new SparseBitVector<>;
1852 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1853 delete CycleNode->ImplicitPredEdges;
1854 CycleNode->ImplicitPredEdges = NULL;
1855 }
1856 SCCStack.pop();
1857 }
1858
1859 Node2Deleted[NodeIndex] = true;
1860
1861 // Set up number of incoming edges for other nodes
1862 if (N->PredEdges)
1863 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1864 Iter != N->PredEdges->end();
1865 ++Iter)
1866 ++GraphNodes[VSSCCRep[*Iter]].NumInEdges;
1867 } else {
1868 SCCStack.push(NodeIndex);
1869 }
1870}
1871
1872void Andersens::HUValNum(unsigned NodeIndex) {
1873 Node *N = &GraphNodes[NodeIndex];
1874 Node2Visited[NodeIndex] = true;
1875
1876 // Eliminate dereferences of non-pointers for those non-pointers we have
1877 // already identified. These are ref nodes whose non-ref node:
1878 // 1. Has already been visited determined to point to nothing (and thus, a
1879 // dereference of it must point to nothing)
1880 // 2. Any direct node with no predecessor edges in our graph and with no
1881 // points-to set (since it can't point to anything either, being that it
1882 // receives no points-to sets and has none).
1883 if (NodeIndex >= FirstRefNode) {
1884 unsigned j = VSSCCRep[FindNode(NodeIndex - FirstRefNode)];
1885 if ((Node2Visited[j] && !GraphNodes[j].PointerEquivLabel)
1886 || (GraphNodes[j].Direct && !GraphNodes[j].PredEdges
1887 && GraphNodes[j].PointsTo->empty())){
1888 return;
1889 }
1890 }
1891 // Process all our explicit edges
1892 if (N->PredEdges)
1893 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1894 Iter != N->PredEdges->end();
1895 ++Iter) {
1896 unsigned j = VSSCCRep[*Iter];
1897 if (!Node2Visited[j])
1898 HUValNum(j);
1899
1900 // If this edge turned out to be the same as us, or got no pointer
1901 // equivalence label (and thus points to nothing) , just decrement our
1902 // incoming edges and continue.
1903 if (j == NodeIndex || GraphNodes[j].PointerEquivLabel == 0) {
1904 --GraphNodes[j].NumInEdges;
1905 continue;
1906 }
1907
1908 *(N->PointsTo) |= GraphNodes[j].PointsTo;
1909
1910 // If we didn't end up storing this in the hash, and we're done with all
1911 // the edges, we don't need the points-to set anymore.
1912 --GraphNodes[j].NumInEdges;
1913 if (!GraphNodes[j].NumInEdges && !GraphNodes[j].StoredInHash) {
1914 delete GraphNodes[j].PointsTo;
1915 GraphNodes[j].PointsTo = NULL;
1916 }
1917 }
1918 // If this isn't a direct node, generate a fresh variable.
1919 if (!N->Direct) {
1920 N->PointsTo->set(FirstRefNode + NodeIndex);
1921 }
1922
1923 // See If we have something equivalent to us, if not, generate a new
1924 // equivalence class.
1925 if (N->PointsTo->empty()) {
1926 delete N->PointsTo;
1927 N->PointsTo = NULL;
1928 } else {
1929 if (N->Direct) {
1930 N->PointerEquivLabel = Set2PEClass[N->PointsTo];
1931 if (N->PointerEquivLabel == 0) {
1932 unsigned EquivClass = PEClass++;
1933 N->StoredInHash = true;
1934 Set2PEClass[N->PointsTo] = EquivClass;
1935 N->PointerEquivLabel = EquivClass;
1936 }
1937 } else {
1938 N->PointerEquivLabel = PEClass++;
1939 }
1940 }
1941}
1942
1943/// Rewrite our list of constraints so that pointer equivalent nodes are
1944/// replaced by their the pointer equivalence class representative.
1945void Andersens::RewriteConstraints() {
1946 std::vector<Constraint> NewConstraints;
Chris Lattnerbe207732007-09-30 00:47:20 +00001947 DenseSet<Constraint, ConstraintKeyInfo> Seen;
Daniel Berlind81ccc22007-09-24 19:45:49 +00001948
1949 PEClass2Node.clear();
1950 PENLEClass2Node.clear();
1951
1952 // We may have from 1 to Graphnodes + 1 equivalence classes.
1953 PEClass2Node.insert(PEClass2Node.begin(), GraphNodes.size() + 1, -1);
1954 PENLEClass2Node.insert(PENLEClass2Node.begin(), GraphNodes.size() + 1, -1);
1955
1956 // Rewrite constraints, ignoring non-pointer constraints, uniting equivalent
1957 // nodes, and rewriting constraints to use the representative nodes.
1958 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1959 Constraint &C = Constraints[i];
1960 unsigned RHSNode = FindNode(C.Src);
1961 unsigned LHSNode = FindNode(C.Dest);
1962 unsigned RHSLabel = GraphNodes[VSSCCRep[RHSNode]].PointerEquivLabel;
1963 unsigned LHSLabel = GraphNodes[VSSCCRep[LHSNode]].PointerEquivLabel;
1964
1965 // First we try to eliminate constraints for things we can prove don't point
1966 // to anything.
1967 if (LHSLabel == 0) {
1968 DEBUG(PrintNode(&GraphNodes[LHSNode]));
1969 DOUT << " is a non-pointer, ignoring constraint.\n";
1970 continue;
1971 }
1972 if (RHSLabel == 0) {
1973 DEBUG(PrintNode(&GraphNodes[RHSNode]));
1974 DOUT << " is a non-pointer, ignoring constraint.\n";
1975 continue;
1976 }
1977 // This constraint may be useless, and it may become useless as we translate
1978 // it.
1979 if (C.Src == C.Dest && C.Type == Constraint::Copy)
1980 continue;
Daniel Berlinc7a12ae2007-09-27 15:42:23 +00001981
Daniel Berlind81ccc22007-09-24 19:45:49 +00001982 C.Src = FindEquivalentNode(RHSNode, RHSLabel);
1983 C.Dest = FindEquivalentNode(FindNode(LHSNode), LHSLabel);
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001984 if ((C.Src == C.Dest && C.Type == Constraint::Copy)
Chris Lattnerbe207732007-09-30 00:47:20 +00001985 || Seen.count(C))
Daniel Berlind81ccc22007-09-24 19:45:49 +00001986 continue;
1987
Chris Lattnerbe207732007-09-30 00:47:20 +00001988 Seen.insert(C);
Daniel Berlind81ccc22007-09-24 19:45:49 +00001989 NewConstraints.push_back(C);
1990 }
1991 Constraints.swap(NewConstraints);
1992 PEClass2Node.clear();
1993}
1994
1995/// See if we have a node that is pointer equivalent to the one being asked
1996/// about, and if so, unite them and return the equivalent node. Otherwise,
1997/// return the original node.
1998unsigned Andersens::FindEquivalentNode(unsigned NodeIndex,
1999 unsigned NodeLabel) {
2000 if (!GraphNodes[NodeIndex].AddressTaken) {
2001 if (PEClass2Node[NodeLabel] != -1) {
2002 // We found an existing node with the same pointer label, so unify them.
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002003 // We specifically request that Union-By-Rank not be used so that
2004 // PEClass2Node[NodeLabel] U= NodeIndex and not the other way around.
2005 return UniteNodes(PEClass2Node[NodeLabel], NodeIndex, false);
Daniel Berlind81ccc22007-09-24 19:45:49 +00002006 } else {
2007 PEClass2Node[NodeLabel] = NodeIndex;
2008 PENLEClass2Node[NodeLabel] = NodeIndex;
2009 }
2010 } else if (PENLEClass2Node[NodeLabel] == -1) {
2011 PENLEClass2Node[NodeLabel] = NodeIndex;
2012 }
2013
2014 return NodeIndex;
2015}
2016
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002017void Andersens::PrintLabels() const {
Daniel Berlind81ccc22007-09-24 19:45:49 +00002018 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2019 if (i < FirstRefNode) {
2020 PrintNode(&GraphNodes[i]);
2021 } else if (i < FirstAdrNode) {
2022 DOUT << "REF(";
2023 PrintNode(&GraphNodes[i-FirstRefNode]);
2024 DOUT <<")";
2025 } else {
2026 DOUT << "ADR(";
2027 PrintNode(&GraphNodes[i-FirstAdrNode]);
2028 DOUT <<")";
2029 }
2030
2031 DOUT << " has pointer label " << GraphNodes[i].PointerEquivLabel
2032 << " and SCC rep " << VSSCCRep[i]
2033 << " and is " << (GraphNodes[i].Direct ? "Direct" : "Not direct")
2034 << "\n";
2035 }
2036}
2037
Daniel Berlinc864edb2008-03-05 19:31:47 +00002038/// The technique used here is described in "The Ant and the
2039/// Grasshopper: Fast and Accurate Pointer Analysis for Millions of
2040/// Lines of Code. In Programming Language Design and Implementation
2041/// (PLDI), June 2007." It is known as the "HCD" (Hybrid Cycle
2042/// Detection) algorithm. It is called a hybrid because it performs an
2043/// offline analysis and uses its results during the solving (online)
2044/// phase. This is just the offline portion; the results of this
2045/// operation are stored in SDT and are later used in SolveContraints()
2046/// and UniteNodes().
2047void Andersens::HCD() {
2048 DOUT << "Starting HCD.\n";
2049 HCDSCCRep.resize(GraphNodes.size());
2050
2051 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2052 GraphNodes[i].Edges = new SparseBitVector<>;
2053 HCDSCCRep[i] = i;
2054 }
2055
2056 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2057 Constraint &C = Constraints[i];
2058 assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
2059 if (C.Type == Constraint::AddressOf) {
2060 continue;
2061 } else if (C.Type == Constraint::Load) {
2062 if( C.Offset == 0 )
2063 GraphNodes[C.Dest].Edges->set(C.Src + FirstRefNode);
2064 } else if (C.Type == Constraint::Store) {
2065 if( C.Offset == 0 )
2066 GraphNodes[C.Dest + FirstRefNode].Edges->set(C.Src);
2067 } else {
2068 GraphNodes[C.Dest].Edges->set(C.Src);
2069 }
2070 }
2071
2072 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2073 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2074 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
2075 SDT.insert(SDT.begin(), GraphNodes.size() / 2, -1);
2076
2077 DFSNumber = 0;
2078 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2079 unsigned Node = HCDSCCRep[i];
2080 if (!Node2Deleted[Node])
2081 Search(Node);
2082 }
2083
2084 for (unsigned i = 0; i < GraphNodes.size(); ++i)
2085 if (GraphNodes[i].Edges != NULL) {
2086 delete GraphNodes[i].Edges;
2087 GraphNodes[i].Edges = NULL;
2088 }
2089
2090 while( !SCCStack.empty() )
2091 SCCStack.pop();
2092
2093 Node2DFS.clear();
2094 Node2Visited.clear();
2095 Node2Deleted.clear();
2096 HCDSCCRep.clear();
2097 DOUT << "HCD complete.\n";
2098}
2099
2100// Component of HCD:
2101// Use Nuutila's variant of Tarjan's algorithm to detect
2102// Strongly-Connected Components (SCCs). For non-trivial SCCs
2103// containing ref nodes, insert the appropriate information in SDT.
2104void Andersens::Search(unsigned Node) {
2105 unsigned MyDFS = DFSNumber++;
2106
2107 Node2Visited[Node] = true;
2108 Node2DFS[Node] = MyDFS;
2109
2110 for (SparseBitVector<>::iterator Iter = GraphNodes[Node].Edges->begin(),
2111 End = GraphNodes[Node].Edges->end();
2112 Iter != End;
2113 ++Iter) {
2114 unsigned J = HCDSCCRep[*Iter];
2115 assert(GraphNodes[J].isRep() && "Debug check; must be representative");
2116 if (!Node2Deleted[J]) {
2117 if (!Node2Visited[J])
2118 Search(J);
2119 if (Node2DFS[Node] > Node2DFS[J])
2120 Node2DFS[Node] = Node2DFS[J];
2121 }
2122 }
2123
2124 if( MyDFS != Node2DFS[Node] ) {
2125 SCCStack.push(Node);
2126 return;
2127 }
2128
2129 // This node is the root of a SCC, so process it.
2130 //
2131 // If the SCC is "non-trivial" (not a singleton) and contains a reference
2132 // node, we place this SCC into SDT. We unite the nodes in any case.
2133 if (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
2134 SparseBitVector<> SCC;
2135
2136 SCC.set(Node);
2137
2138 bool Ref = (Node >= FirstRefNode);
2139
2140 Node2Deleted[Node] = true;
2141
2142 do {
2143 unsigned P = SCCStack.top(); SCCStack.pop();
2144 Ref |= (P >= FirstRefNode);
2145 SCC.set(P);
2146 HCDSCCRep[P] = Node;
2147 } while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS);
2148
2149 if (Ref) {
2150 unsigned Rep = SCC.find_first();
2151 assert(Rep < FirstRefNode && "The SCC didn't have a non-Ref node!");
2152
2153 SparseBitVector<>::iterator i = SCC.begin();
2154
2155 // Skip over the non-ref nodes
2156 while( *i < FirstRefNode )
2157 ++i;
2158
2159 while( i != SCC.end() )
2160 SDT[ (*i++) - FirstRefNode ] = Rep;
2161 }
2162 }
2163}
2164
2165
Daniel Berlind81ccc22007-09-24 19:45:49 +00002166/// Optimize the constraints by performing offline variable substitution and
2167/// other optimizations.
2168void Andersens::OptimizeConstraints() {
2169 DOUT << "Beginning constraint optimization\n";
2170
Daniel Berlinc864edb2008-03-05 19:31:47 +00002171 SDTActive = false;
2172
Daniel Berlind81ccc22007-09-24 19:45:49 +00002173 // Function related nodes need to stay in the same relative position and can't
2174 // be location equivalent.
2175 for (std::map<unsigned, unsigned>::iterator Iter = MaxK.begin();
2176 Iter != MaxK.end();
2177 ++Iter) {
2178 for (unsigned i = Iter->first;
2179 i != Iter->first + Iter->second;
2180 ++i) {
2181 GraphNodes[i].AddressTaken = true;
2182 GraphNodes[i].Direct = false;
2183 }
2184 }
2185
2186 ClumpAddressTaken();
2187 FirstRefNode = GraphNodes.size();
2188 FirstAdrNode = FirstRefNode + GraphNodes.size();
2189 GraphNodes.insert(GraphNodes.end(), 2 * GraphNodes.size(),
2190 Node(false));
2191 VSSCCRep.resize(GraphNodes.size());
2192 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2193 VSSCCRep[i] = i;
2194 }
2195 HVN();
2196 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2197 Node *N = &GraphNodes[i];
2198 delete N->PredEdges;
2199 N->PredEdges = NULL;
2200 delete N->ImplicitPredEdges;
2201 N->ImplicitPredEdges = NULL;
2202 }
2203#undef DEBUG_TYPE
2204#define DEBUG_TYPE "anders-aa-labels"
2205 DEBUG(PrintLabels());
2206#undef DEBUG_TYPE
2207#define DEBUG_TYPE "anders-aa"
2208 RewriteConstraints();
2209 // Delete the adr nodes.
2210 GraphNodes.resize(FirstRefNode * 2);
2211
2212 // Now perform HU
2213 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2214 Node *N = &GraphNodes[i];
2215 if (FindNode(i) == i) {
2216 N->PointsTo = new SparseBitVector<>;
2217 N->PointedToBy = new SparseBitVector<>;
2218 // Reset our labels
2219 }
2220 VSSCCRep[i] = i;
2221 N->PointerEquivLabel = 0;
2222 }
2223 HU();
2224#undef DEBUG_TYPE
2225#define DEBUG_TYPE "anders-aa-labels"
2226 DEBUG(PrintLabels());
2227#undef DEBUG_TYPE
2228#define DEBUG_TYPE "anders-aa"
2229 RewriteConstraints();
2230 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2231 if (FindNode(i) == i) {
2232 Node *N = &GraphNodes[i];
2233 delete N->PointsTo;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002234 N->PointsTo = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002235 delete N->PredEdges;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002236 N->PredEdges = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002237 delete N->ImplicitPredEdges;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002238 N->ImplicitPredEdges = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002239 delete N->PointedToBy;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002240 N->PointedToBy = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002241 }
2242 }
Daniel Berlinc864edb2008-03-05 19:31:47 +00002243
2244 // perform Hybrid Cycle Detection (HCD)
2245 HCD();
2246 SDTActive = true;
2247
2248 // No longer any need for the upper half of GraphNodes (for ref nodes).
Daniel Berlind81ccc22007-09-24 19:45:49 +00002249 GraphNodes.erase(GraphNodes.begin() + FirstRefNode, GraphNodes.end());
Daniel Berlinc864edb2008-03-05 19:31:47 +00002250
2251 // HCD complete.
2252
Daniel Berlind81ccc22007-09-24 19:45:49 +00002253 DOUT << "Finished constraint optimization\n";
2254 FirstRefNode = 0;
2255 FirstAdrNode = 0;
2256}
2257
2258/// Unite pointer but not location equivalent variables, now that the constraint
2259/// graph is built.
2260void Andersens::UnitePointerEquivalences() {
2261 DOUT << "Uniting remaining pointer equivalences\n";
2262 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002263 if (GraphNodes[i].AddressTaken && GraphNodes[i].isRep()) {
Daniel Berlind81ccc22007-09-24 19:45:49 +00002264 unsigned Label = GraphNodes[i].PointerEquivLabel;
2265
2266 if (Label && PENLEClass2Node[Label] != -1)
2267 UniteNodes(i, PENLEClass2Node[Label]);
2268 }
2269 }
2270 DOUT << "Finished remaining pointer equivalences\n";
2271 PENLEClass2Node.clear();
2272}
2273
2274/// Create the constraint graph used for solving points-to analysis.
2275///
Daniel Berlinaad15882007-09-16 21:45:02 +00002276void Andersens::CreateConstraintGraph() {
2277 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2278 Constraint &C = Constraints[i];
2279 assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
2280 if (C.Type == Constraint::AddressOf)
2281 GraphNodes[C.Dest].PointsTo->set(C.Src);
2282 else if (C.Type == Constraint::Load)
2283 GraphNodes[C.Src].Constraints.push_back(C);
2284 else if (C.Type == Constraint::Store)
2285 GraphNodes[C.Dest].Constraints.push_back(C);
2286 else if (C.Offset != 0)
2287 GraphNodes[C.Src].Constraints.push_back(C);
2288 else
2289 GraphNodes[C.Src].Edges->set(C.Dest);
2290 }
2291}
2292
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002293// Perform DFS and cycle detection.
2294bool Andersens::QueryNode(unsigned Node) {
2295 assert(GraphNodes[Node].isRep() && "Querying a non-rep node");
Daniel Berlinaad15882007-09-16 21:45:02 +00002296 unsigned OurDFS = ++DFSNumber;
2297 SparseBitVector<> ToErase;
2298 SparseBitVector<> NewEdges;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002299 Tarjan2DFS[Node] = OurDFS;
2300
2301 // Changed denotes a change from a recursive call that we will bubble up.
2302 // Merged is set if we actually merge a node ourselves.
2303 bool Changed = false, Merged = false;
Daniel Berlinaad15882007-09-16 21:45:02 +00002304
2305 for (SparseBitVector<>::iterator bi = GraphNodes[Node].Edges->begin();
2306 bi != GraphNodes[Node].Edges->end();
2307 ++bi) {
2308 unsigned RepNode = FindNode(*bi);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002309 // If this edge points to a non-representative node but we are
2310 // already planning to add an edge to its representative, we have no
2311 // need for this edge anymore.
Daniel Berlinaad15882007-09-16 21:45:02 +00002312 if (RepNode != *bi && NewEdges.test(RepNode)){
2313 ToErase.set(*bi);
2314 continue;
2315 }
2316
2317 // Continue about our DFS.
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002318 if (!Tarjan2Deleted[RepNode]){
2319 if (Tarjan2DFS[RepNode] == 0) {
2320 Changed |= QueryNode(RepNode);
2321 // May have been changed by QueryNode
Daniel Berlinaad15882007-09-16 21:45:02 +00002322 RepNode = FindNode(RepNode);
2323 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002324 if (Tarjan2DFS[RepNode] < Tarjan2DFS[Node])
2325 Tarjan2DFS[Node] = Tarjan2DFS[RepNode];
Daniel Berlinaad15882007-09-16 21:45:02 +00002326 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002327
2328 // We may have just discovered that this node is part of a cycle, in
2329 // which case we can also erase it.
Daniel Berlinaad15882007-09-16 21:45:02 +00002330 if (RepNode != *bi) {
2331 ToErase.set(*bi);
2332 NewEdges.set(RepNode);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002333 }
2334 }
2335
Daniel Berlinaad15882007-09-16 21:45:02 +00002336 GraphNodes[Node].Edges->intersectWithComplement(ToErase);
2337 GraphNodes[Node].Edges |= NewEdges;
2338
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002339 // If this node is a root of a non-trivial SCC, place it on our
2340 // worklist to be processed.
2341 if (OurDFS == Tarjan2DFS[Node]) {
2342 while (!SCCStack.empty() && Tarjan2DFS[SCCStack.top()] >= OurDFS) {
2343 Node = UniteNodes(Node, SCCStack.top());
Daniel Berlinaad15882007-09-16 21:45:02 +00002344
2345 SCCStack.pop();
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002346 Merged = true;
Daniel Berlinaad15882007-09-16 21:45:02 +00002347 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002348 Tarjan2Deleted[Node] = true;
Daniel Berlinaad15882007-09-16 21:45:02 +00002349
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002350 if (Merged)
2351 NextWL->insert(&GraphNodes[Node]);
Daniel Berlinaad15882007-09-16 21:45:02 +00002352 } else {
2353 SCCStack.push(Node);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002354 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002355
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002356 return(Changed | Merged);
2357}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002358
2359/// SolveConstraints - This stage iteratively processes the constraints list
2360/// propagating constraints (adding edges to the Nodes in the points-to graph)
2361/// until a fixed point is reached.
2362///
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002363/// We use a variant of the technique called "Lazy Cycle Detection", which is
2364/// described in "The Ant and the Grasshopper: Fast and Accurate Pointer
2365/// Analysis for Millions of Lines of Code. In Programming Language Design and
2366/// Implementation (PLDI), June 2007."
2367/// The paper describes performing cycle detection one node at a time, which can
2368/// be expensive if there are no cycles, but there are long chains of nodes that
2369/// it heuristically believes are cycles (because it will DFS from each node
2370/// without state from previous nodes).
2371/// Instead, we use the heuristic to build a worklist of nodes to check, then
2372/// cycle detect them all at the same time to do this more cheaply. This
2373/// catches cycles slightly later than the original technique did, but does it
2374/// make significantly cheaper.
2375
Chris Lattnere995a2a2004-05-23 21:00:47 +00002376void Andersens::SolveConstraints() {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002377 CurrWL = &w1;
2378 NextWL = &w2;
Daniel Berlinaad15882007-09-16 21:45:02 +00002379
Daniel Berlind81ccc22007-09-24 19:45:49 +00002380 OptimizeConstraints();
2381#undef DEBUG_TYPE
2382#define DEBUG_TYPE "anders-aa-constraints"
2383 DEBUG(PrintConstraints());
2384#undef DEBUG_TYPE
2385#define DEBUG_TYPE "anders-aa"
2386
Daniel Berlinaad15882007-09-16 21:45:02 +00002387 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2388 Node *N = &GraphNodes[i];
2389 N->PointsTo = new SparseBitVector<>;
2390 N->OldPointsTo = new SparseBitVector<>;
2391 N->Edges = new SparseBitVector<>;
2392 }
2393 CreateConstraintGraph();
Daniel Berlind81ccc22007-09-24 19:45:49 +00002394 UnitePointerEquivalences();
2395 assert(SCCStack.empty() && "SCC Stack should be empty by now!");
Daniel Berlind81ccc22007-09-24 19:45:49 +00002396 Node2DFS.clear();
2397 Node2Deleted.clear();
Daniel Berlinaad15882007-09-16 21:45:02 +00002398 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2399 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2400 DFSNumber = 0;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002401 DenseSet<Constraint, ConstraintKeyInfo> Seen;
2402 DenseSet<std::pair<unsigned,unsigned>, PairKeyInfo> EdgesChecked;
2403
2404 // Order graph and add initial nodes to work list.
Daniel Berlinaad15882007-09-16 21:45:02 +00002405 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
Daniel Berlinaad15882007-09-16 21:45:02 +00002406 Node *INode = &GraphNodes[i];
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002407
2408 // Add to work list if it's a representative and can contribute to the
2409 // calculation right now.
2410 if (INode->isRep() && !INode->PointsTo->empty()
2411 && (!INode->Edges->empty() || !INode->Constraints.empty())) {
2412 INode->Stamp();
2413 CurrWL->insert(INode);
Daniel Berlinaad15882007-09-16 21:45:02 +00002414 }
2415 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002416 std::queue<unsigned int> TarjanWL;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002417#if !FULL_UNIVERSAL
2418 // "Rep and special variables" - in order for HCD to maintain conservative
2419 // results when !FULL_UNIVERSAL, we need to treat the special variables in
2420 // the same way that the !FULL_UNIVERSAL tweak does throughout the rest of
2421 // the analysis - it's ok to add edges from the special nodes, but never
2422 // *to* the special nodes.
2423 std::vector<unsigned int> RSV;
2424#endif
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002425 while( !CurrWL->empty() ) {
2426 DOUT << "Starting iteration #" << ++NumIters << "\n";
Daniel Berlinaad15882007-09-16 21:45:02 +00002427
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002428 Node* CurrNode;
2429 unsigned CurrNodeIndex;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002430
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002431 // Actual cycle checking code. We cycle check all of the lazy cycle
2432 // candidates from the last iteration in one go.
2433 if (!TarjanWL.empty()) {
2434 DFSNumber = 0;
2435
2436 Tarjan2DFS.clear();
2437 Tarjan2Deleted.clear();
2438 while (!TarjanWL.empty()) {
2439 unsigned int ToTarjan = TarjanWL.front();
2440 TarjanWL.pop();
2441 if (!Tarjan2Deleted[ToTarjan]
2442 && GraphNodes[ToTarjan].isRep()
2443 && Tarjan2DFS[ToTarjan] == 0)
2444 QueryNode(ToTarjan);
2445 }
2446 }
2447
2448 // Add to work list if it's a representative and can contribute to the
2449 // calculation right now.
2450 while( (CurrNode = CurrWL->pop()) != NULL ) {
2451 CurrNodeIndex = CurrNode - &GraphNodes[0];
2452 CurrNode->Stamp();
2453
2454
Daniel Berlinaad15882007-09-16 21:45:02 +00002455 // Figure out the changed points to bits
2456 SparseBitVector<> CurrPointsTo;
2457 CurrPointsTo.intersectWithComplement(CurrNode->PointsTo,
2458 CurrNode->OldPointsTo);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002459 if (CurrPointsTo.empty())
Daniel Berlinaad15882007-09-16 21:45:02 +00002460 continue;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002461
Daniel Berlinaad15882007-09-16 21:45:02 +00002462 *(CurrNode->OldPointsTo) |= CurrPointsTo;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002463
2464 // Check the offline-computed equivalencies from HCD.
2465 bool SCC = false;
2466 unsigned Rep;
2467
2468 if (SDT[CurrNodeIndex] >= 0) {
2469 SCC = true;
2470 Rep = FindNode(SDT[CurrNodeIndex]);
2471
2472#if !FULL_UNIVERSAL
2473 RSV.clear();
2474#endif
2475 for (SparseBitVector<>::iterator bi = CurrPointsTo.begin();
2476 bi != CurrPointsTo.end(); ++bi) {
2477 unsigned Node = FindNode(*bi);
2478#if !FULL_UNIVERSAL
2479 if (Node < NumberSpecialNodes) {
2480 RSV.push_back(Node);
2481 continue;
2482 }
2483#endif
2484 Rep = UniteNodes(Rep,Node);
2485 }
2486#if !FULL_UNIVERSAL
2487 RSV.push_back(Rep);
2488#endif
2489
2490 NextWL->insert(&GraphNodes[Rep]);
2491
2492 if ( ! CurrNode->isRep() )
2493 continue;
2494 }
2495
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002496 Seen.clear();
Chris Lattnere995a2a2004-05-23 21:00:47 +00002497
Daniel Berlinaad15882007-09-16 21:45:02 +00002498 /* Now process the constraints for this node. */
2499 for (std::list<Constraint>::iterator li = CurrNode->Constraints.begin();
2500 li != CurrNode->Constraints.end(); ) {
2501 li->Src = FindNode(li->Src);
2502 li->Dest = FindNode(li->Dest);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002503
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002504 // Delete redundant constraints
2505 if( Seen.count(*li) ) {
2506 std::list<Constraint>::iterator lk = li; li++;
2507
2508 CurrNode->Constraints.erase(lk);
2509 ++NumErased;
2510 continue;
2511 }
2512 Seen.insert(*li);
2513
Daniel Berlinaad15882007-09-16 21:45:02 +00002514 // Src and Dest will be the vars we are going to process.
2515 // This may look a bit ugly, but what it does is allow us to process
Daniel Berlind81ccc22007-09-24 19:45:49 +00002516 // both store and load constraints with the same code.
Daniel Berlinaad15882007-09-16 21:45:02 +00002517 // Load constraints say that every member of our RHS solution has K
2518 // added to it, and that variable gets an edge to LHS. We also union
2519 // RHS+K's solution into the LHS solution.
2520 // Store constraints say that every member of our LHS solution has K
2521 // added to it, and that variable gets an edge from RHS. We also union
2522 // RHS's solution into the LHS+K solution.
2523 unsigned *Src;
2524 unsigned *Dest;
2525 unsigned K = li->Offset;
2526 unsigned CurrMember;
2527 if (li->Type == Constraint::Load) {
2528 Src = &CurrMember;
2529 Dest = &li->Dest;
2530 } else if (li->Type == Constraint::Store) {
2531 Src = &li->Src;
2532 Dest = &CurrMember;
2533 } else {
2534 // TODO Handle offseted copy constraint
2535 li++;
2536 continue;
2537 }
Daniel Berlinc864edb2008-03-05 19:31:47 +00002538
2539 // See if we can use Hybrid Cycle Detection (that is, check
Daniel Berlinaad15882007-09-16 21:45:02 +00002540 // if it was a statically detected offline equivalence that
Daniel Berlinc864edb2008-03-05 19:31:47 +00002541 // involves pointers; if so, remove the redundant constraints).
2542 if( SCC && K == 0 ) {
2543#if FULL_UNIVERSAL
2544 CurrMember = Rep;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002545
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002546 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2547 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2548 NextWL->insert(&GraphNodes[*Dest]);
Daniel Berlinc864edb2008-03-05 19:31:47 +00002549#else
2550 for (unsigned i=0; i < RSV.size(); ++i) {
2551 CurrMember = RSV[i];
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002552
Daniel Berlinc864edb2008-03-05 19:31:47 +00002553 if (*Dest < NumberSpecialNodes)
2554 continue;
2555 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2556 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2557 NextWL->insert(&GraphNodes[*Dest]);
2558 }
2559#endif
2560 // since all future elements of the points-to set will be
2561 // equivalent to the current ones, the complex constraints
2562 // become redundant.
2563 //
2564 std::list<Constraint>::iterator lk = li; li++;
2565#if !FULL_UNIVERSAL
2566 // In this case, we can still erase the constraints when the
2567 // elements of the points-to sets are referenced by *Dest,
2568 // but not when they are referenced by *Src (i.e. for a Load
2569 // constraint). This is because if another special variable is
2570 // put into the points-to set later, we still need to add the
2571 // new edge from that special variable.
2572 if( lk->Type != Constraint::Load)
2573#endif
2574 GraphNodes[CurrNodeIndex].Constraints.erase(lk);
2575 } else {
2576 const SparseBitVector<> &Solution = CurrPointsTo;
2577
2578 for (SparseBitVector<>::iterator bi = Solution.begin();
2579 bi != Solution.end();
2580 ++bi) {
2581 CurrMember = *bi;
2582
2583 // Need to increment the member by K since that is where we are
2584 // supposed to copy to/from. Note that in positive weight cycles,
2585 // which occur in address taking of fields, K can go past
2586 // MaxK[CurrMember] elements, even though that is all it could point
2587 // to.
2588 if (K > 0 && K > MaxK[CurrMember])
2589 continue;
2590 else
2591 CurrMember = FindNode(CurrMember + K);
2592
2593 // Add an edge to the graph, so we can just do regular
2594 // bitmap ior next time. It may also let us notice a cycle.
2595#if !FULL_UNIVERSAL
2596 if (*Dest < NumberSpecialNodes)
2597 continue;
2598#endif
2599 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2600 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2601 NextWL->insert(&GraphNodes[*Dest]);
2602
2603 }
2604 li++;
Daniel Berlinaad15882007-09-16 21:45:02 +00002605 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002606 }
2607 SparseBitVector<> NewEdges;
2608 SparseBitVector<> ToErase;
2609
2610 // Now all we have left to do is propagate points-to info along the
2611 // edges, erasing the redundant edges.
Daniel Berlinaad15882007-09-16 21:45:02 +00002612 for (SparseBitVector<>::iterator bi = CurrNode->Edges->begin();
2613 bi != CurrNode->Edges->end();
2614 ++bi) {
2615
2616 unsigned DestVar = *bi;
2617 unsigned Rep = FindNode(DestVar);
2618
Bill Wendlingf059deb2008-02-26 10:51:52 +00002619 // If we ended up with this node as our destination, or we've already
2620 // got an edge for the representative, delete the current edge.
2621 if (Rep == CurrNodeIndex ||
2622 (Rep != DestVar && NewEdges.test(Rep))) {
Daniel Berlinc864edb2008-03-05 19:31:47 +00002623 ToErase.set(DestVar);
2624 continue;
Bill Wendlingf059deb2008-02-26 10:51:52 +00002625 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002626
Bill Wendlingf059deb2008-02-26 10:51:52 +00002627 std::pair<unsigned,unsigned> edge(CurrNodeIndex,Rep);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002628
2629 // This is where we do lazy cycle detection.
2630 // If this is a cycle candidate (equal points-to sets and this
2631 // particular edge has not been cycle-checked previously), add to the
2632 // list to check for cycles on the next iteration.
2633 if (!EdgesChecked.count(edge) &&
2634 *(GraphNodes[Rep].PointsTo) == *(CurrNode->PointsTo)) {
2635 EdgesChecked.insert(edge);
2636 TarjanWL.push(Rep);
Daniel Berlinaad15882007-09-16 21:45:02 +00002637 }
2638 // Union the points-to sets into the dest
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002639#if !FULL_UNIVERSAL
2640 if (Rep >= NumberSpecialNodes)
2641#endif
Daniel Berlinaad15882007-09-16 21:45:02 +00002642 if (GraphNodes[Rep].PointsTo |= CurrPointsTo) {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002643 NextWL->insert(&GraphNodes[Rep]);
Daniel Berlinaad15882007-09-16 21:45:02 +00002644 }
2645 // If this edge's destination was collapsed, rewrite the edge.
2646 if (Rep != DestVar) {
2647 ToErase.set(DestVar);
2648 NewEdges.set(Rep);
2649 }
2650 }
2651 CurrNode->Edges->intersectWithComplement(ToErase);
2652 CurrNode->Edges |= NewEdges;
2653 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002654
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002655 // Switch to other work list.
2656 WorkList* t = CurrWL; CurrWL = NextWL; NextWL = t;
2657 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002658
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002659
Daniel Berlinaad15882007-09-16 21:45:02 +00002660 Node2DFS.clear();
2661 Node2Deleted.clear();
2662 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2663 Node *N = &GraphNodes[i];
2664 delete N->OldPointsTo;
2665 delete N->Edges;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002666 }
Daniel Berlinc864edb2008-03-05 19:31:47 +00002667 SDTActive = false;
2668 SDT.clear();
Chris Lattnere995a2a2004-05-23 21:00:47 +00002669}
2670
Daniel Berlinaad15882007-09-16 21:45:02 +00002671//===----------------------------------------------------------------------===//
2672// Union-Find
2673//===----------------------------------------------------------------------===//
Chris Lattnere995a2a2004-05-23 21:00:47 +00002674
Daniel Berlinaad15882007-09-16 21:45:02 +00002675// Unite nodes First and Second, returning the one which is now the
2676// representative node. First and Second are indexes into GraphNodes
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002677unsigned Andersens::UniteNodes(unsigned First, unsigned Second,
2678 bool UnionByRank) {
Daniel Berlinaad15882007-09-16 21:45:02 +00002679 assert (First < GraphNodes.size() && Second < GraphNodes.size() &&
2680 "Attempting to merge nodes that don't exist");
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002681
Daniel Berlinaad15882007-09-16 21:45:02 +00002682 Node *FirstNode = &GraphNodes[First];
2683 Node *SecondNode = &GraphNodes[Second];
2684
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002685 assert (SecondNode->isRep() && FirstNode->isRep() &&
Daniel Berlinaad15882007-09-16 21:45:02 +00002686 "Trying to unite two non-representative nodes!");
2687 if (First == Second)
2688 return First;
2689
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002690 if (UnionByRank) {
2691 int RankFirst = (int) FirstNode ->NodeRep;
2692 int RankSecond = (int) SecondNode->NodeRep;
2693
2694 // Rank starts at -1 and gets decremented as it increases.
2695 // Translation: higher rank, lower NodeRep value, which is always negative.
2696 if (RankFirst > RankSecond) {
2697 unsigned t = First; First = Second; Second = t;
2698 Node* tp = FirstNode; FirstNode = SecondNode; SecondNode = tp;
2699 } else if (RankFirst == RankSecond) {
2700 FirstNode->NodeRep = (unsigned) (RankFirst - 1);
2701 }
2702 }
2703
Daniel Berlinaad15882007-09-16 21:45:02 +00002704 SecondNode->NodeRep = First;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002705#if !FULL_UNIVERSAL
2706 if (First >= NumberSpecialNodes)
2707#endif
Daniel Berlind81ccc22007-09-24 19:45:49 +00002708 if (FirstNode->PointsTo && SecondNode->PointsTo)
2709 FirstNode->PointsTo |= *(SecondNode->PointsTo);
2710 if (FirstNode->Edges && SecondNode->Edges)
2711 FirstNode->Edges |= *(SecondNode->Edges);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002712 if (!SecondNode->Constraints.empty())
Daniel Berlind81ccc22007-09-24 19:45:49 +00002713 FirstNode->Constraints.splice(FirstNode->Constraints.begin(),
2714 SecondNode->Constraints);
2715 if (FirstNode->OldPointsTo) {
2716 delete FirstNode->OldPointsTo;
2717 FirstNode->OldPointsTo = new SparseBitVector<>;
2718 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002719
2720 // Destroy interesting parts of the merged-from node.
2721 delete SecondNode->OldPointsTo;
2722 delete SecondNode->Edges;
2723 delete SecondNode->PointsTo;
2724 SecondNode->Edges = NULL;
2725 SecondNode->PointsTo = NULL;
2726 SecondNode->OldPointsTo = NULL;
2727
2728 NumUnified++;
2729 DOUT << "Unified Node ";
2730 DEBUG(PrintNode(FirstNode));
2731 DOUT << " and Node ";
2732 DEBUG(PrintNode(SecondNode));
2733 DOUT << "\n";
2734
Daniel Berlinc864edb2008-03-05 19:31:47 +00002735 if (SDTActive)
Duncan Sands43e2a032008-05-27 11:50:51 +00002736 if (SDT[Second] >= 0) {
Daniel Berlinc864edb2008-03-05 19:31:47 +00002737 if (SDT[First] < 0)
2738 SDT[First] = SDT[Second];
2739 else {
2740 UniteNodes( FindNode(SDT[First]), FindNode(SDT[Second]) );
2741 First = FindNode(First);
2742 }
Duncan Sands43e2a032008-05-27 11:50:51 +00002743 }
Daniel Berlinc864edb2008-03-05 19:31:47 +00002744
Daniel Berlinaad15882007-09-16 21:45:02 +00002745 return First;
2746}
2747
2748// Find the index into GraphNodes of the node representing Node, performing
2749// path compression along the way
2750unsigned Andersens::FindNode(unsigned NodeIndex) {
2751 assert (NodeIndex < GraphNodes.size()
2752 && "Attempting to find a node that can't exist");
2753 Node *N = &GraphNodes[NodeIndex];
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002754 if (N->isRep())
Daniel Berlinaad15882007-09-16 21:45:02 +00002755 return NodeIndex;
2756 else
2757 return (N->NodeRep = FindNode(N->NodeRep));
2758}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002759
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002760// Find the index into GraphNodes of the node representing Node,
2761// don't perform path compression along the way (for Print)
2762unsigned Andersens::FindNode(unsigned NodeIndex) const {
2763 assert (NodeIndex < GraphNodes.size()
2764 && "Attempting to find a node that can't exist");
2765 const Node *N = &GraphNodes[NodeIndex];
2766 if (N->isRep())
2767 return NodeIndex;
2768 else
2769 return FindNode(N->NodeRep);
2770}
2771
Chris Lattnere995a2a2004-05-23 21:00:47 +00002772//===----------------------------------------------------------------------===//
2773// Debugging Output
2774//===----------------------------------------------------------------------===//
2775
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002776void Andersens::PrintNode(const Node *N) const {
Chris Lattnere995a2a2004-05-23 21:00:47 +00002777 if (N == &GraphNodes[UniversalSet]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002778 cerr << "<universal>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002779 return;
2780 } else if (N == &GraphNodes[NullPtr]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002781 cerr << "<nullptr>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002782 return;
2783 } else if (N == &GraphNodes[NullObject]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002784 cerr << "<null>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002785 return;
2786 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002787 if (!N->getValue()) {
2788 cerr << "artificial" << (intptr_t) N;
2789 return;
2790 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002791
2792 assert(N->getValue() != 0 && "Never set node label!");
2793 Value *V = N->getValue();
2794 if (Function *F = dyn_cast<Function>(V)) {
2795 if (isa<PointerType>(F->getFunctionType()->getReturnType()) &&
Daniel Berlinaad15882007-09-16 21:45:02 +00002796 N == &GraphNodes[getReturnNode(F)]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002797 cerr << F->getName() << ":retval";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002798 return;
Daniel Berlinaad15882007-09-16 21:45:02 +00002799 } else if (F->getFunctionType()->isVarArg() &&
2800 N == &GraphNodes[getVarargNode(F)]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002801 cerr << F->getName() << ":vararg";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002802 return;
2803 }
2804 }
2805
2806 if (Instruction *I = dyn_cast<Instruction>(V))
Bill Wendlinge8156192006-12-07 01:30:32 +00002807 cerr << I->getParent()->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002808 else if (Argument *Arg = dyn_cast<Argument>(V))
Bill Wendlinge8156192006-12-07 01:30:32 +00002809 cerr << Arg->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002810
2811 if (V->hasName())
Bill Wendlinge8156192006-12-07 01:30:32 +00002812 cerr << V->getName();
Chris Lattnere995a2a2004-05-23 21:00:47 +00002813 else
Bill Wendlinge8156192006-12-07 01:30:32 +00002814 cerr << "(unnamed)";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002815
2816 if (isa<GlobalValue>(V) || isa<AllocationInst>(V))
Daniel Berlinaad15882007-09-16 21:45:02 +00002817 if (N == &GraphNodes[getObject(V)])
Bill Wendlinge8156192006-12-07 01:30:32 +00002818 cerr << "<mem>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002819}
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002820void Andersens::PrintConstraint(const Constraint &C) const {
Daniel Berlind81ccc22007-09-24 19:45:49 +00002821 if (C.Type == Constraint::Store) {
2822 cerr << "*";
2823 if (C.Offset != 0)
2824 cerr << "(";
2825 }
2826 PrintNode(&GraphNodes[C.Dest]);
2827 if (C.Type == Constraint::Store && C.Offset != 0)
2828 cerr << " + " << C.Offset << ")";
2829 cerr << " = ";
2830 if (C.Type == Constraint::Load) {
2831 cerr << "*";
2832 if (C.Offset != 0)
2833 cerr << "(";
2834 }
2835 else if (C.Type == Constraint::AddressOf)
2836 cerr << "&";
2837 PrintNode(&GraphNodes[C.Src]);
2838 if (C.Offset != 0 && C.Type != Constraint::Store)
2839 cerr << " + " << C.Offset;
2840 if (C.Type == Constraint::Load && C.Offset != 0)
2841 cerr << ")";
2842 cerr << "\n";
2843}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002844
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002845void Andersens::PrintConstraints() const {
Bill Wendlinge8156192006-12-07 01:30:32 +00002846 cerr << "Constraints:\n";
Daniel Berlinaad15882007-09-16 21:45:02 +00002847
Daniel Berlind81ccc22007-09-24 19:45:49 +00002848 for (unsigned i = 0, e = Constraints.size(); i != e; ++i)
2849 PrintConstraint(Constraints[i]);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002850}
2851
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002852void Andersens::PrintPointsToGraph() const {
Bill Wendlinge8156192006-12-07 01:30:32 +00002853 cerr << "Points-to graph:\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002854 for (unsigned i = 0, e = GraphNodes.size(); i != e; ++i) {
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002855 const Node *N = &GraphNodes[i];
2856 if (FindNode(i) != i) {
Daniel Berlinaad15882007-09-16 21:45:02 +00002857 PrintNode(N);
2858 cerr << "\t--> same as ";
2859 PrintNode(&GraphNodes[FindNode(i)]);
2860 cerr << "\n";
2861 } else {
2862 cerr << "[" << (N->PointsTo->count()) << "] ";
2863 PrintNode(N);
2864 cerr << "\t--> ";
2865
2866 bool first = true;
2867 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
2868 bi != N->PointsTo->end();
2869 ++bi) {
2870 if (!first)
2871 cerr << ", ";
2872 PrintNode(&GraphNodes[*bi]);
2873 first = false;
2874 }
2875 cerr << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002876 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002877 }
2878}