blob: c6075e1c6106c2c799af952ddaf17c9ad5c468ca [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;
Devang Patelc7582092008-03-19 21:56:59 +0000434 Andersens() : ModulePass((intptr_t)&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 Lattner01ac91e2006-03-03 01:21:36 +0000906 F->getName() == "llvm.memset.i32" ||
907 F->getName() == "llvm.memset.i64" ||
Chris Lattner175b9632005-03-29 20:36:05 +0000908 F->getName() == "strcmp" || F->getName() == "strncmp" ||
909 F->getName() == "execl" || F->getName() == "execlp" ||
910 F->getName() == "execle" || F->getName() == "execv" ||
911 F->getName() == "execvp" || F->getName() == "chmod" ||
912 F->getName() == "puts" || F->getName() == "write" ||
913 F->getName() == "open" || F->getName() == "create" ||
914 F->getName() == "truncate" || F->getName() == "chdir" ||
915 F->getName() == "mkdir" || F->getName() == "rmdir" ||
916 F->getName() == "read" || F->getName() == "pipe" ||
917 F->getName() == "wait" || F->getName() == "time" ||
918 F->getName() == "stat" || F->getName() == "fstat" ||
919 F->getName() == "lstat" || F->getName() == "strtod" ||
920 F->getName() == "strtof" || F->getName() == "strtold" ||
921 F->getName() == "fopen" || F->getName() == "fdopen" ||
922 F->getName() == "freopen" ||
923 F->getName() == "fflush" || F->getName() == "feof" ||
924 F->getName() == "fileno" || F->getName() == "clearerr" ||
925 F->getName() == "rewind" || F->getName() == "ftell" ||
926 F->getName() == "ferror" || F->getName() == "fgetc" ||
927 F->getName() == "fgetc" || F->getName() == "_IO_getc" ||
928 F->getName() == "fwrite" || F->getName() == "fread" ||
929 F->getName() == "fgets" || F->getName() == "ungetc" ||
930 F->getName() == "fputc" ||
931 F->getName() == "fputs" || F->getName() == "putc" ||
932 F->getName() == "ftell" || F->getName() == "rewind" ||
933 F->getName() == "_IO_putc" || F->getName() == "fseek" ||
934 F->getName() == "fgetpos" || F->getName() == "fsetpos" ||
935 F->getName() == "printf" || F->getName() == "fprintf" ||
936 F->getName() == "sprintf" || F->getName() == "vprintf" ||
937 F->getName() == "vfprintf" || F->getName() == "vsprintf" ||
938 F->getName() == "scanf" || F->getName() == "fscanf" ||
939 F->getName() == "sscanf" || F->getName() == "__assert_fail" ||
940 F->getName() == "modf")
Chris Lattner8a446432005-03-29 06:09:07 +0000941 return true;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000942
Chris Lattner175b9632005-03-29 20:36:05 +0000943
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000944 // These functions do induce points-to edges.
Daniel Berlinaad15882007-09-16 21:45:02 +0000945 if (F->getName() == "llvm.memcpy.i32" || F->getName() == "llvm.memcpy.i64" ||
Chris Lattner01ac91e2006-03-03 01:21:36 +0000946 F->getName() == "llvm.memmove.i32" ||F->getName() == "llvm.memmove.i64" ||
Chris Lattner4de57fd2005-03-29 06:52:20 +0000947 F->getName() == "memmove") {
Daniel Berlinaad15882007-09-16 21:45:02 +0000948
949 // *Dest = *Src, which requires an artificial graph node to represent the
950 // constraint. It is broken up into *Dest = temp, temp = *Src
951 unsigned FirstArg = getNode(CS.getArgument(0));
952 unsigned SecondArg = getNode(CS.getArgument(1));
953 unsigned TempArg = GraphNodes.size();
954 GraphNodes.push_back(Node());
955 Constraints.push_back(Constraint(Constraint::Store,
956 FirstArg, TempArg));
957 Constraints.push_back(Constraint(Constraint::Load,
958 TempArg, SecondArg));
Daniel Berlina2ce2e32008-04-07 14:20:50 +0000959 // In addition, Dest = Src
960 Constraints.push_back(Constraint(Constraint::Copy,
961 FirstArg, SecondArg));
Chris Lattner8a446432005-03-29 06:09:07 +0000962 return true;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000963 }
964
Chris Lattner77b50562005-03-29 20:04:24 +0000965 // Result = Arg0
966 if (F->getName() == "realloc" || F->getName() == "strchr" ||
967 F->getName() == "strrchr" || F->getName() == "strstr" ||
968 F->getName() == "strtok") {
Chris Lattner8a446432005-03-29 06:09:07 +0000969 Constraints.push_back(Constraint(Constraint::Copy,
970 getNode(CS.getInstruction()),
971 getNode(CS.getArgument(0))));
972 return true;
973 }
974
975 return false;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000976}
977
978
Chris Lattnere995a2a2004-05-23 21:00:47 +0000979
Daniel Berlinaad15882007-09-16 21:45:02 +0000980/// AnalyzeUsesOfFunction - Look at all of the users of the specified function.
981/// If this is used by anything complex (i.e., the address escapes), return
982/// true.
983bool Andersens::AnalyzeUsesOfFunction(Value *V) {
984
985 if (!isa<PointerType>(V->getType())) return true;
986
987 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
988 if (dyn_cast<LoadInst>(*UI)) {
989 return false;
990 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
991 if (V == SI->getOperand(1)) {
992 return false;
993 } else if (SI->getOperand(1)) {
994 return true; // Storing the pointer
995 }
996 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
997 if (AnalyzeUsesOfFunction(GEP)) return true;
998 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
999 // Make sure that this is just the function being called, not that it is
1000 // passing into the function.
1001 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
1002 if (CI->getOperand(i) == V) return true;
1003 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
1004 // Make sure that this is just the function being called, not that it is
1005 // passing into the function.
1006 for (unsigned i = 3, e = II->getNumOperands(); i != e; ++i)
1007 if (II->getOperand(i) == V) return true;
1008 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
1009 if (CE->getOpcode() == Instruction::GetElementPtr ||
1010 CE->getOpcode() == Instruction::BitCast) {
1011 if (AnalyzeUsesOfFunction(CE))
1012 return true;
1013 } else {
1014 return true;
1015 }
1016 } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(*UI)) {
1017 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1018 return true; // Allow comparison against null.
1019 } else if (dyn_cast<FreeInst>(*UI)) {
1020 return false;
1021 } else {
1022 return true;
1023 }
1024 return false;
1025}
1026
Chris Lattnere995a2a2004-05-23 21:00:47 +00001027/// CollectConstraints - This stage scans the program, adding a constraint to
1028/// the Constraints list for each instruction in the program that induces a
1029/// constraint, and setting up the initial points-to graph.
1030///
1031void Andersens::CollectConstraints(Module &M) {
1032 // First, the universal set points to itself.
Daniel Berlinaad15882007-09-16 21:45:02 +00001033 Constraints.push_back(Constraint(Constraint::AddressOf, UniversalSet,
1034 UniversalSet));
1035 Constraints.push_back(Constraint(Constraint::Store, UniversalSet,
1036 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001037
1038 // Next, the null pointer points to the null object.
Daniel Berlinaad15882007-09-16 21:45:02 +00001039 Constraints.push_back(Constraint(Constraint::AddressOf, NullPtr, NullObject));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001040
1041 // Next, add any constraints on global variables and their initializers.
Chris Lattner493f6362005-03-27 22:03:46 +00001042 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1043 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001044 // Associate the address of the global object as pointing to the memory for
1045 // the global: &G = <G memory>
Daniel Berlinaad15882007-09-16 21:45:02 +00001046 unsigned ObjectIndex = getObject(I);
1047 Node *Object = &GraphNodes[ObjectIndex];
Chris Lattnere995a2a2004-05-23 21:00:47 +00001048 Object->setValue(I);
Daniel Berlinaad15882007-09-16 21:45:02 +00001049 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(*I),
1050 ObjectIndex));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001051
1052 if (I->hasInitializer()) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001053 AddGlobalInitializerConstraints(ObjectIndex, I->getInitializer());
Chris Lattnere995a2a2004-05-23 21:00:47 +00001054 } else {
1055 // If it doesn't have an initializer (i.e. it's defined in another
1056 // translation unit), it points to the universal set.
Daniel Berlinaad15882007-09-16 21:45:02 +00001057 Constraints.push_back(Constraint(Constraint::Copy, ObjectIndex,
1058 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001059 }
1060 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001061
Chris Lattnere995a2a2004-05-23 21:00:47 +00001062 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001063 // Set up the return value node.
1064 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
Daniel Berlinaad15882007-09-16 21:45:02 +00001065 GraphNodes[getReturnNode(F)].setValue(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001066 if (F->getFunctionType()->isVarArg())
Daniel Berlinaad15882007-09-16 21:45:02 +00001067 GraphNodes[getVarargNode(F)].setValue(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001068
1069 // Set up incoming argument nodes.
Chris Lattner493f6362005-03-27 22:03:46 +00001070 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
1071 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +00001072 if (isa<PointerType>(I->getType()))
1073 getNodeValue(*I);
1074
Daniel Berlinaad15882007-09-16 21:45:02 +00001075 // At some point we should just add constraints for the escaping functions
1076 // at solve time, but this slows down solving. For now, we simply mark
1077 // address taken functions as escaping and treat them as external.
1078 if (!F->hasInternalLinkage() || AnalyzeUsesOfFunction(F))
Chris Lattnere995a2a2004-05-23 21:00:47 +00001079 AddConstraintsForNonInternalLinkage(F);
1080
Reid Spencer5cbf9852007-01-30 20:08:39 +00001081 if (!F->isDeclaration()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001082 // Scan the function body, creating a memory object for each heap/stack
1083 // allocation in the body of the function and a node to represent all
1084 // pointer values defined by instructions and used as operands.
1085 visit(F);
Chris Lattner8a446432005-03-29 06:09:07 +00001086 } else {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001087 // External functions that return pointers return the universal set.
1088 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
1089 Constraints.push_back(Constraint(Constraint::Copy,
1090 getReturnNode(F),
Daniel Berlinaad15882007-09-16 21:45:02 +00001091 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001092
1093 // Any pointers that are passed into the function have the universal set
1094 // stored into them.
Chris Lattner493f6362005-03-27 22:03:46 +00001095 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
1096 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +00001097 if (isa<PointerType>(I->getType())) {
1098 // Pointers passed into external functions could have anything stored
1099 // through them.
1100 Constraints.push_back(Constraint(Constraint::Store, getNode(I),
Daniel Berlinaad15882007-09-16 21:45:02 +00001101 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001102 // Memory objects passed into external function calls can have the
1103 // universal set point to them.
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001104#if FULL_UNIVERSAL
Chris Lattnere995a2a2004-05-23 21:00:47 +00001105 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001106 UniversalSet,
Chris Lattnere995a2a2004-05-23 21:00:47 +00001107 getNode(I)));
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001108#else
1109 Constraints.push_back(Constraint(Constraint::Copy,
1110 getNode(I),
1111 UniversalSet));
1112#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001113 }
1114
1115 // If this is an external varargs function, it can also store pointers
1116 // into any pointers passed through the varargs section.
1117 if (F->getFunctionType()->isVarArg())
1118 Constraints.push_back(Constraint(Constraint::Store, getVarargNode(F),
Daniel Berlinaad15882007-09-16 21:45:02 +00001119 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001120 }
1121 }
1122 NumConstraints += Constraints.size();
1123}
1124
1125
1126void Andersens::visitInstruction(Instruction &I) {
1127#ifdef NDEBUG
1128 return; // This function is just a big assert.
1129#endif
1130 if (isa<BinaryOperator>(I))
1131 return;
1132 // Most instructions don't have any effect on pointer values.
1133 switch (I.getOpcode()) {
1134 case Instruction::Br:
1135 case Instruction::Switch:
1136 case Instruction::Unwind:
Chris Lattnerc17edbd2004-10-16 18:16:19 +00001137 case Instruction::Unreachable:
Chris Lattnere995a2a2004-05-23 21:00:47 +00001138 case Instruction::Free:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001139 case Instruction::ICmp:
1140 case Instruction::FCmp:
Chris Lattnere995a2a2004-05-23 21:00:47 +00001141 return;
1142 default:
1143 // Is this something we aren't handling yet?
Bill Wendlinge8156192006-12-07 01:30:32 +00001144 cerr << "Unknown instruction: " << I;
Chris Lattnere995a2a2004-05-23 21:00:47 +00001145 abort();
1146 }
1147}
1148
1149void Andersens::visitAllocationInst(AllocationInst &AI) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001150 unsigned ObjectIndex = getObject(&AI);
1151 GraphNodes[ObjectIndex].setValue(&AI);
1152 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(AI),
1153 ObjectIndex));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001154}
1155
1156void Andersens::visitReturnInst(ReturnInst &RI) {
1157 if (RI.getNumOperands() && isa<PointerType>(RI.getOperand(0)->getType()))
1158 // return V --> <Copy/retval{F}/v>
1159 Constraints.push_back(Constraint(Constraint::Copy,
1160 getReturnNode(RI.getParent()->getParent()),
1161 getNode(RI.getOperand(0))));
1162}
1163
1164void Andersens::visitLoadInst(LoadInst &LI) {
1165 if (isa<PointerType>(LI.getType()))
1166 // P1 = load P2 --> <Load/P1/P2>
1167 Constraints.push_back(Constraint(Constraint::Load, getNodeValue(LI),
1168 getNode(LI.getOperand(0))));
1169}
1170
1171void Andersens::visitStoreInst(StoreInst &SI) {
1172 if (isa<PointerType>(SI.getOperand(0)->getType()))
1173 // store P1, P2 --> <Store/P2/P1>
1174 Constraints.push_back(Constraint(Constraint::Store,
1175 getNode(SI.getOperand(1)),
1176 getNode(SI.getOperand(0))));
1177}
1178
1179void Andersens::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1180 // P1 = getelementptr P2, ... --> <Copy/P1/P2>
1181 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(GEP),
1182 getNode(GEP.getOperand(0))));
1183}
1184
1185void Andersens::visitPHINode(PHINode &PN) {
1186 if (isa<PointerType>(PN.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001187 unsigned PNN = getNodeValue(PN);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001188 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1189 // P1 = phi P2, P3 --> <Copy/P1/P2>, <Copy/P1/P3>, ...
1190 Constraints.push_back(Constraint(Constraint::Copy, PNN,
1191 getNode(PN.getIncomingValue(i))));
1192 }
1193}
1194
1195void Andersens::visitCastInst(CastInst &CI) {
1196 Value *Op = CI.getOperand(0);
1197 if (isa<PointerType>(CI.getType())) {
1198 if (isa<PointerType>(Op->getType())) {
1199 // P1 = cast P2 --> <Copy/P1/P2>
1200 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
1201 getNode(CI.getOperand(0))));
1202 } else {
1203 // P1 = cast int --> <Copy/P1/Univ>
Chris Lattner175b9632005-03-29 20:36:05 +00001204#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +00001205 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
Daniel Berlinaad15882007-09-16 21:45:02 +00001206 UniversalSet));
Chris Lattnerbd135c72005-04-05 01:12:03 +00001207#else
1208 getNodeValue(CI);
Chris Lattner175b9632005-03-29 20:36:05 +00001209#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001210 }
1211 } else if (isa<PointerType>(Op->getType())) {
1212 // int = cast P1 --> <Copy/Univ/P1>
Chris Lattner175b9632005-03-29 20:36:05 +00001213#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +00001214 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001215 UniversalSet,
Chris Lattnere995a2a2004-05-23 21:00:47 +00001216 getNode(CI.getOperand(0))));
Chris Lattnerbd135c72005-04-05 01:12:03 +00001217#else
1218 getNode(CI.getOperand(0));
Chris Lattner175b9632005-03-29 20:36:05 +00001219#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001220 }
1221}
1222
1223void Andersens::visitSelectInst(SelectInst &SI) {
1224 if (isa<PointerType>(SI.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001225 unsigned SIN = getNodeValue(SI);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001226 // P1 = select C, P2, P3 ---> <Copy/P1/P2>, <Copy/P1/P3>
1227 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1228 getNode(SI.getOperand(1))));
1229 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1230 getNode(SI.getOperand(2))));
1231 }
1232}
1233
Chris Lattnere995a2a2004-05-23 21:00:47 +00001234void Andersens::visitVAArg(VAArgInst &I) {
1235 assert(0 && "vaarg not handled yet!");
1236}
1237
1238/// AddConstraintsForCall - Add constraints for a call with actual arguments
1239/// specified by CS to the function specified by F. Note that the types of
1240/// arguments might not match up in the case where this is an indirect call and
1241/// the function pointer has been casted. If this is the case, do something
1242/// reasonable.
1243void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001244 Value *CallValue = CS.getCalledValue();
1245 bool IsDeref = F == NULL;
1246
1247 // If this is a call to an external function, try to handle it directly to get
1248 // some taste of context sensitivity.
1249 if (F && F->isDeclaration() && AddConstraintsForExternalCall(CS, F))
Chris Lattner8a446432005-03-29 06:09:07 +00001250 return;
1251
Chris Lattnere995a2a2004-05-23 21:00:47 +00001252 if (isa<PointerType>(CS.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001253 unsigned CSN = getNode(CS.getInstruction());
1254 if (!F || isa<PointerType>(F->getFunctionType()->getReturnType())) {
1255 if (IsDeref)
1256 Constraints.push_back(Constraint(Constraint::Load, CSN,
1257 getNode(CallValue), CallReturnPos));
1258 else
1259 Constraints.push_back(Constraint(Constraint::Copy, CSN,
1260 getNode(CallValue) + CallReturnPos));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001261 } else {
1262 // If the function returns a non-pointer value, handle this just like we
1263 // treat a nonpointer cast to pointer.
1264 Constraints.push_back(Constraint(Constraint::Copy, CSN,
Daniel Berlinaad15882007-09-16 21:45:02 +00001265 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001266 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001267 } else if (F && isa<PointerType>(F->getFunctionType()->getReturnType())) {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001268#if FULL_UNIVERSAL
Chris Lattnere995a2a2004-05-23 21:00:47 +00001269 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001270 UniversalSet,
1271 getNode(CallValue) + CallReturnPos));
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001272#else
1273 Constraints.push_back(Constraint(Constraint::Copy,
1274 getNode(CallValue) + CallReturnPos,
1275 UniversalSet));
1276#endif
1277
1278
Chris Lattnere995a2a2004-05-23 21:00:47 +00001279 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001280
Chris Lattnere995a2a2004-05-23 21:00:47 +00001281 CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
Daniel Berlind3bf1ae2008-03-18 22:22:53 +00001282 bool external = !F || F->isDeclaration();
Daniel Berlinaad15882007-09-16 21:45:02 +00001283 if (F) {
1284 // Direct Call
1285 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
Daniel Berlind3bf1ae2008-03-18 22:22:53 +00001286 for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI)
1287 {
1288#if !FULL_UNIVERSAL
1289 if (external && isa<PointerType>((*ArgI)->getType()))
1290 {
1291 // Add constraint that ArgI can now point to anything due to
1292 // escaping, as can everything it points to. The second portion of
1293 // this should be taken care of by universal = *universal
1294 Constraints.push_back(Constraint(Constraint::Copy,
1295 getNode(*ArgI),
1296 UniversalSet));
1297 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001298#endif
Daniel Berlind3bf1ae2008-03-18 22:22:53 +00001299 if (isa<PointerType>(AI->getType())) {
1300 if (isa<PointerType>((*ArgI)->getType())) {
1301 // Copy the actual argument into the formal argument.
1302 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1303 getNode(*ArgI)));
1304 } else {
1305 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1306 UniversalSet));
1307 }
1308 } else if (isa<PointerType>((*ArgI)->getType())) {
1309#if FULL_UNIVERSAL
1310 Constraints.push_back(Constraint(Constraint::Copy,
1311 UniversalSet,
1312 getNode(*ArgI)));
1313#else
1314 Constraints.push_back(Constraint(Constraint::Copy,
1315 getNode(*ArgI),
1316 UniversalSet));
1317#endif
1318 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001319 }
1320 } else {
1321 //Indirect Call
1322 unsigned ArgPos = CallFirstArgPos;
1323 for (; ArgI != ArgE; ++ArgI) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001324 if (isa<PointerType>((*ArgI)->getType())) {
1325 // Copy the actual argument into the formal argument.
Daniel Berlinaad15882007-09-16 21:45:02 +00001326 Constraints.push_back(Constraint(Constraint::Store,
1327 getNode(CallValue),
1328 getNode(*ArgI), ArgPos++));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001329 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +00001330 Constraints.push_back(Constraint(Constraint::Store,
1331 getNode (CallValue),
1332 UniversalSet, ArgPos++));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001333 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00001334 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001335 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00001336 // Copy all pointers passed through the varargs section to the varargs node.
Daniel Berlinaad15882007-09-16 21:45:02 +00001337 if (F && F->getFunctionType()->isVarArg())
Chris Lattnere995a2a2004-05-23 21:00:47 +00001338 for (; ArgI != ArgE; ++ArgI)
1339 if (isa<PointerType>((*ArgI)->getType()))
1340 Constraints.push_back(Constraint(Constraint::Copy, getVarargNode(F),
1341 getNode(*ArgI)));
1342 // If more arguments are passed in than we track, just drop them on the floor.
1343}
1344
1345void Andersens::visitCallSite(CallSite CS) {
1346 if (isa<PointerType>(CS.getType()))
1347 getNodeValue(*CS.getInstruction());
1348
1349 if (Function *F = CS.getCalledFunction()) {
1350 AddConstraintsForCall(CS, F);
1351 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +00001352 AddConstraintsForCall(CS, NULL);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001353 }
1354}
1355
1356//===----------------------------------------------------------------------===//
1357// Constraint Solving Phase
1358//===----------------------------------------------------------------------===//
1359
1360/// intersects - Return true if the points-to set of this node intersects
1361/// with the points-to set of the specified node.
1362bool Andersens::Node::intersects(Node *N) const {
Daniel Berlinaad15882007-09-16 21:45:02 +00001363 return PointsTo->intersects(N->PointsTo);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001364}
1365
1366/// intersectsIgnoring - Return true if the points-to set of this node
1367/// intersects with the points-to set of the specified node on any nodes
1368/// except for the specified node to ignore.
Daniel Berlinaad15882007-09-16 21:45:02 +00001369bool Andersens::Node::intersectsIgnoring(Node *N, unsigned Ignoring) const {
1370 // TODO: If we are only going to call this with the same value for Ignoring,
1371 // we should move the special values out of the points-to bitmap.
1372 bool WeHadIt = PointsTo->test(Ignoring);
1373 bool NHadIt = N->PointsTo->test(Ignoring);
1374 bool Result = false;
1375 if (WeHadIt)
1376 PointsTo->reset(Ignoring);
1377 if (NHadIt)
1378 N->PointsTo->reset(Ignoring);
1379 Result = PointsTo->intersects(N->PointsTo);
1380 if (WeHadIt)
1381 PointsTo->set(Ignoring);
1382 if (NHadIt)
1383 N->PointsTo->set(Ignoring);
1384 return Result;
Chris Lattnere995a2a2004-05-23 21:00:47 +00001385}
1386
Daniel Berlind81ccc22007-09-24 19:45:49 +00001387void dumpToDOUT(SparseBitVector<> *bitmap) {
Bill Wendlingcab5f5d2007-09-24 22:43:48 +00001388#ifndef NDEBUG
Daniel Berlind81ccc22007-09-24 19:45:49 +00001389 dump(*bitmap, DOUT);
Bill Wendlingcab5f5d2007-09-24 22:43:48 +00001390#endif
Daniel Berlind81ccc22007-09-24 19:45:49 +00001391}
1392
1393
1394/// Clump together address taken variables so that the points-to sets use up
1395/// less space and can be operated on faster.
1396
1397void Andersens::ClumpAddressTaken() {
1398#undef DEBUG_TYPE
1399#define DEBUG_TYPE "anders-aa-renumber"
1400 std::vector<unsigned> Translate;
1401 std::vector<Node> NewGraphNodes;
1402
1403 Translate.resize(GraphNodes.size());
1404 unsigned NewPos = 0;
1405
1406 for (unsigned i = 0; i < Constraints.size(); ++i) {
1407 Constraint &C = Constraints[i];
1408 if (C.Type == Constraint::AddressOf) {
1409 GraphNodes[C.Src].AddressTaken = true;
1410 }
1411 }
1412 for (unsigned i = 0; i < NumberSpecialNodes; ++i) {
1413 unsigned Pos = NewPos++;
1414 Translate[i] = Pos;
1415 NewGraphNodes.push_back(GraphNodes[i]);
1416 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1417 }
1418
1419 // I believe this ends up being faster than making two vectors and splicing
1420 // them.
1421 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1422 if (GraphNodes[i].AddressTaken) {
1423 unsigned Pos = NewPos++;
1424 Translate[i] = Pos;
1425 NewGraphNodes.push_back(GraphNodes[i]);
1426 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1427 }
1428 }
1429
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 (DenseMap<Value*, unsigned>::iterator Iter = ValueNodes.begin();
1440 Iter != ValueNodes.end();
1441 ++Iter)
1442 Iter->second = Translate[Iter->second];
1443
1444 for (DenseMap<Value*, unsigned>::iterator Iter = ObjectNodes.begin();
1445 Iter != ObjectNodes.end();
1446 ++Iter)
1447 Iter->second = Translate[Iter->second];
1448
1449 for (DenseMap<Function*, unsigned>::iterator Iter = ReturnNodes.begin();
1450 Iter != ReturnNodes.end();
1451 ++Iter)
1452 Iter->second = Translate[Iter->second];
1453
1454 for (DenseMap<Function*, unsigned>::iterator Iter = VarargNodes.begin();
1455 Iter != VarargNodes.end();
1456 ++Iter)
1457 Iter->second = Translate[Iter->second];
1458
1459 for (unsigned i = 0; i < Constraints.size(); ++i) {
1460 Constraint &C = Constraints[i];
1461 C.Src = Translate[C.Src];
1462 C.Dest = Translate[C.Dest];
1463 }
1464
1465 GraphNodes.swap(NewGraphNodes);
1466#undef DEBUG_TYPE
1467#define DEBUG_TYPE "anders-aa"
1468}
1469
1470/// The technique used here is described in "Exploiting Pointer and Location
1471/// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1472/// Analysis Symposium (SAS), August 2007." It is known as the "HVN" algorithm,
1473/// and is equivalent to value numbering the collapsed constraint graph without
1474/// evaluating unions. This is used as a pre-pass to HU in order to resolve
1475/// first order pointer dereferences and speed up/reduce memory usage of HU.
1476/// Running both is equivalent to HRU without the iteration
1477/// HVN in more detail:
1478/// Imagine the set of constraints was simply straight line code with no loops
1479/// (we eliminate cycles, so there are no loops), such as:
1480/// E = &D
1481/// E = &C
1482/// E = F
1483/// F = G
1484/// G = F
1485/// Applying value numbering to this code tells us:
1486/// G == F == E
1487///
1488/// For HVN, this is as far as it goes. We assign new value numbers to every
1489/// "address node", and every "reference node".
1490/// To get the optimal result for this, we use a DFS + SCC (since all nodes in a
1491/// cycle must have the same value number since the = operation is really
1492/// inclusion, not overwrite), and value number nodes we receive points-to sets
1493/// before we value our own node.
1494/// The advantage of HU over HVN is that HU considers the inclusion property, so
1495/// that if you have
1496/// E = &D
1497/// E = &C
1498/// E = F
1499/// F = G
1500/// F = &D
1501/// G = F
1502/// HU will determine that G == F == E. HVN will not, because it cannot prove
1503/// that the points to information ends up being the same because they all
1504/// receive &D from E anyway.
1505
1506void Andersens::HVN() {
1507 DOUT << "Beginning HVN\n";
1508 // Build a predecessor graph. This is like our constraint graph with the
1509 // edges going in the opposite direction, and there are edges for all the
1510 // constraints, instead of just copy constraints. We also build implicit
1511 // edges for constraints are implied but not explicit. I.E for the constraint
1512 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1513 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1514 Constraint &C = Constraints[i];
1515 if (C.Type == Constraint::AddressOf) {
1516 GraphNodes[C.Src].AddressTaken = true;
1517 GraphNodes[C.Src].Direct = false;
1518
1519 // Dest = &src edge
1520 unsigned AdrNode = C.Src + FirstAdrNode;
1521 if (!GraphNodes[C.Dest].PredEdges)
1522 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1523 GraphNodes[C.Dest].PredEdges->set(AdrNode);
1524
1525 // *Dest = src edge
1526 unsigned RefNode = C.Dest + FirstRefNode;
1527 if (!GraphNodes[RefNode].ImplicitPredEdges)
1528 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1529 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1530 } else if (C.Type == Constraint::Load) {
1531 if (C.Offset == 0) {
1532 // dest = *src edge
1533 if (!GraphNodes[C.Dest].PredEdges)
1534 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1535 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1536 } else {
1537 GraphNodes[C.Dest].Direct = false;
1538 }
1539 } else if (C.Type == Constraint::Store) {
1540 if (C.Offset == 0) {
1541 // *dest = src edge
1542 unsigned RefNode = C.Dest + FirstRefNode;
1543 if (!GraphNodes[RefNode].PredEdges)
1544 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1545 GraphNodes[RefNode].PredEdges->set(C.Src);
1546 }
1547 } else {
1548 // Dest = Src edge and *Dest = *Src edge
1549 if (!GraphNodes[C.Dest].PredEdges)
1550 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1551 GraphNodes[C.Dest].PredEdges->set(C.Src);
1552 unsigned RefNode = C.Dest + FirstRefNode;
1553 if (!GraphNodes[RefNode].ImplicitPredEdges)
1554 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1555 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1556 }
1557 }
1558 PEClass = 1;
1559 // Do SCC finding first to condense our predecessor graph
1560 DFSNumber = 0;
1561 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1562 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1563 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1564
1565 for (unsigned i = 0; i < FirstRefNode; ++i) {
1566 unsigned Node = VSSCCRep[i];
1567 if (!Node2Visited[Node])
1568 HVNValNum(Node);
1569 }
1570 for (BitVectorMap::iterator Iter = Set2PEClass.begin();
1571 Iter != Set2PEClass.end();
1572 ++Iter)
1573 delete Iter->first;
1574 Set2PEClass.clear();
1575 Node2DFS.clear();
1576 Node2Deleted.clear();
1577 Node2Visited.clear();
1578 DOUT << "Finished HVN\n";
1579
1580}
1581
1582/// This is the workhorse of HVN value numbering. We combine SCC finding at the
1583/// same time because it's easy.
1584void Andersens::HVNValNum(unsigned NodeIndex) {
1585 unsigned MyDFS = DFSNumber++;
1586 Node *N = &GraphNodes[NodeIndex];
1587 Node2Visited[NodeIndex] = true;
1588 Node2DFS[NodeIndex] = MyDFS;
1589
1590 // First process all our explicit edges
1591 if (N->PredEdges)
1592 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1593 Iter != N->PredEdges->end();
1594 ++Iter) {
1595 unsigned j = VSSCCRep[*Iter];
1596 if (!Node2Deleted[j]) {
1597 if (!Node2Visited[j])
1598 HVNValNum(j);
1599 if (Node2DFS[NodeIndex] > Node2DFS[j])
1600 Node2DFS[NodeIndex] = Node2DFS[j];
1601 }
1602 }
1603
1604 // Now process all the implicit edges
1605 if (N->ImplicitPredEdges)
1606 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1607 Iter != N->ImplicitPredEdges->end();
1608 ++Iter) {
1609 unsigned j = VSSCCRep[*Iter];
1610 if (!Node2Deleted[j]) {
1611 if (!Node2Visited[j])
1612 HVNValNum(j);
1613 if (Node2DFS[NodeIndex] > Node2DFS[j])
1614 Node2DFS[NodeIndex] = Node2DFS[j];
1615 }
1616 }
1617
1618 // See if we found any cycles
1619 if (MyDFS == Node2DFS[NodeIndex]) {
1620 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1621 unsigned CycleNodeIndex = SCCStack.top();
1622 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1623 VSSCCRep[CycleNodeIndex] = NodeIndex;
1624 // Unify the nodes
1625 N->Direct &= CycleNode->Direct;
1626
1627 if (CycleNode->PredEdges) {
1628 if (!N->PredEdges)
1629 N->PredEdges = new SparseBitVector<>;
1630 *(N->PredEdges) |= CycleNode->PredEdges;
1631 delete CycleNode->PredEdges;
1632 CycleNode->PredEdges = NULL;
1633 }
1634 if (CycleNode->ImplicitPredEdges) {
1635 if (!N->ImplicitPredEdges)
1636 N->ImplicitPredEdges = new SparseBitVector<>;
1637 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1638 delete CycleNode->ImplicitPredEdges;
1639 CycleNode->ImplicitPredEdges = NULL;
1640 }
1641
1642 SCCStack.pop();
1643 }
1644
1645 Node2Deleted[NodeIndex] = true;
1646
1647 if (!N->Direct) {
1648 GraphNodes[NodeIndex].PointerEquivLabel = PEClass++;
1649 return;
1650 }
1651
1652 // Collect labels of successor nodes
1653 bool AllSame = true;
1654 unsigned First = ~0;
1655 SparseBitVector<> *Labels = new SparseBitVector<>;
1656 bool Used = false;
1657
1658 if (N->PredEdges)
1659 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1660 Iter != N->PredEdges->end();
1661 ++Iter) {
1662 unsigned j = VSSCCRep[*Iter];
1663 unsigned Label = GraphNodes[j].PointerEquivLabel;
1664 // Ignore labels that are equal to us or non-pointers
1665 if (j == NodeIndex || Label == 0)
1666 continue;
1667 if (First == (unsigned)~0)
1668 First = Label;
1669 else if (First != Label)
1670 AllSame = false;
1671 Labels->set(Label);
1672 }
1673
1674 // We either have a non-pointer, a copy of an existing node, or a new node.
1675 // Assign the appropriate pointer equivalence label.
1676 if (Labels->empty()) {
1677 GraphNodes[NodeIndex].PointerEquivLabel = 0;
1678 } else if (AllSame) {
1679 GraphNodes[NodeIndex].PointerEquivLabel = First;
1680 } else {
1681 GraphNodes[NodeIndex].PointerEquivLabel = Set2PEClass[Labels];
1682 if (GraphNodes[NodeIndex].PointerEquivLabel == 0) {
1683 unsigned EquivClass = PEClass++;
1684 Set2PEClass[Labels] = EquivClass;
1685 GraphNodes[NodeIndex].PointerEquivLabel = EquivClass;
1686 Used = true;
1687 }
1688 }
1689 if (!Used)
1690 delete Labels;
1691 } else {
1692 SCCStack.push(NodeIndex);
1693 }
1694}
1695
1696/// The technique used here is described in "Exploiting Pointer and Location
1697/// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1698/// Analysis Symposium (SAS), August 2007." It is known as the "HU" algorithm,
1699/// and is equivalent to value numbering the collapsed constraint graph
1700/// including evaluating unions.
1701void Andersens::HU() {
1702 DOUT << "Beginning HU\n";
1703 // Build a predecessor graph. This is like our constraint graph with the
1704 // edges going in the opposite direction, and there are edges for all the
1705 // constraints, instead of just copy constraints. We also build implicit
1706 // edges for constraints are implied but not explicit. I.E for the constraint
1707 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1708 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1709 Constraint &C = Constraints[i];
1710 if (C.Type == Constraint::AddressOf) {
1711 GraphNodes[C.Src].AddressTaken = true;
1712 GraphNodes[C.Src].Direct = false;
1713
1714 GraphNodes[C.Dest].PointsTo->set(C.Src);
1715 // *Dest = src edge
1716 unsigned RefNode = C.Dest + FirstRefNode;
1717 if (!GraphNodes[RefNode].ImplicitPredEdges)
1718 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1719 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1720 GraphNodes[C.Src].PointedToBy->set(C.Dest);
1721 } else if (C.Type == Constraint::Load) {
1722 if (C.Offset == 0) {
1723 // dest = *src edge
1724 if (!GraphNodes[C.Dest].PredEdges)
1725 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1726 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1727 } else {
1728 GraphNodes[C.Dest].Direct = false;
1729 }
1730 } else if (C.Type == Constraint::Store) {
1731 if (C.Offset == 0) {
1732 // *dest = src edge
1733 unsigned RefNode = C.Dest + FirstRefNode;
1734 if (!GraphNodes[RefNode].PredEdges)
1735 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1736 GraphNodes[RefNode].PredEdges->set(C.Src);
1737 }
1738 } else {
1739 // Dest = Src edge and *Dest = *Src edg
1740 if (!GraphNodes[C.Dest].PredEdges)
1741 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1742 GraphNodes[C.Dest].PredEdges->set(C.Src);
1743 unsigned RefNode = C.Dest + FirstRefNode;
1744 if (!GraphNodes[RefNode].ImplicitPredEdges)
1745 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1746 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1747 }
1748 }
1749 PEClass = 1;
1750 // Do SCC finding first to condense our predecessor graph
1751 DFSNumber = 0;
1752 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1753 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1754 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1755
1756 for (unsigned i = 0; i < FirstRefNode; ++i) {
1757 if (FindNode(i) == i) {
1758 unsigned Node = VSSCCRep[i];
1759 if (!Node2Visited[Node])
1760 Condense(Node);
1761 }
1762 }
1763
1764 // Reset tables for actual labeling
1765 Node2DFS.clear();
1766 Node2Visited.clear();
1767 Node2Deleted.clear();
1768 // Pre-grow our densemap so that we don't get really bad behavior
1769 Set2PEClass.resize(GraphNodes.size());
1770
1771 // Visit the condensed graph and generate pointer equivalence labels.
1772 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1773 for (unsigned i = 0; i < FirstRefNode; ++i) {
1774 if (FindNode(i) == i) {
1775 unsigned Node = VSSCCRep[i];
1776 if (!Node2Visited[Node])
1777 HUValNum(Node);
1778 }
1779 }
1780 // PEClass nodes will be deleted by the deleting of N->PointsTo in our caller.
1781 Set2PEClass.clear();
1782 DOUT << "Finished HU\n";
1783}
1784
1785
1786/// Implementation of standard Tarjan SCC algorithm as modified by Nuutilla.
1787void Andersens::Condense(unsigned NodeIndex) {
1788 unsigned MyDFS = DFSNumber++;
1789 Node *N = &GraphNodes[NodeIndex];
1790 Node2Visited[NodeIndex] = true;
1791 Node2DFS[NodeIndex] = MyDFS;
1792
1793 // First process all our explicit edges
1794 if (N->PredEdges)
1795 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1796 Iter != N->PredEdges->end();
1797 ++Iter) {
1798 unsigned j = VSSCCRep[*Iter];
1799 if (!Node2Deleted[j]) {
1800 if (!Node2Visited[j])
1801 Condense(j);
1802 if (Node2DFS[NodeIndex] > Node2DFS[j])
1803 Node2DFS[NodeIndex] = Node2DFS[j];
1804 }
1805 }
1806
1807 // Now process all the implicit edges
1808 if (N->ImplicitPredEdges)
1809 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1810 Iter != N->ImplicitPredEdges->end();
1811 ++Iter) {
1812 unsigned j = VSSCCRep[*Iter];
1813 if (!Node2Deleted[j]) {
1814 if (!Node2Visited[j])
1815 Condense(j);
1816 if (Node2DFS[NodeIndex] > Node2DFS[j])
1817 Node2DFS[NodeIndex] = Node2DFS[j];
1818 }
1819 }
1820
1821 // See if we found any cycles
1822 if (MyDFS == Node2DFS[NodeIndex]) {
1823 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1824 unsigned CycleNodeIndex = SCCStack.top();
1825 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1826 VSSCCRep[CycleNodeIndex] = NodeIndex;
1827 // Unify the nodes
1828 N->Direct &= CycleNode->Direct;
1829
1830 *(N->PointsTo) |= CycleNode->PointsTo;
1831 delete CycleNode->PointsTo;
1832 CycleNode->PointsTo = NULL;
1833 if (CycleNode->PredEdges) {
1834 if (!N->PredEdges)
1835 N->PredEdges = new SparseBitVector<>;
1836 *(N->PredEdges) |= CycleNode->PredEdges;
1837 delete CycleNode->PredEdges;
1838 CycleNode->PredEdges = NULL;
1839 }
1840 if (CycleNode->ImplicitPredEdges) {
1841 if (!N->ImplicitPredEdges)
1842 N->ImplicitPredEdges = new SparseBitVector<>;
1843 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1844 delete CycleNode->ImplicitPredEdges;
1845 CycleNode->ImplicitPredEdges = NULL;
1846 }
1847 SCCStack.pop();
1848 }
1849
1850 Node2Deleted[NodeIndex] = true;
1851
1852 // Set up number of incoming edges for other nodes
1853 if (N->PredEdges)
1854 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1855 Iter != N->PredEdges->end();
1856 ++Iter)
1857 ++GraphNodes[VSSCCRep[*Iter]].NumInEdges;
1858 } else {
1859 SCCStack.push(NodeIndex);
1860 }
1861}
1862
1863void Andersens::HUValNum(unsigned NodeIndex) {
1864 Node *N = &GraphNodes[NodeIndex];
1865 Node2Visited[NodeIndex] = true;
1866
1867 // Eliminate dereferences of non-pointers for those non-pointers we have
1868 // already identified. These are ref nodes whose non-ref node:
1869 // 1. Has already been visited determined to point to nothing (and thus, a
1870 // dereference of it must point to nothing)
1871 // 2. Any direct node with no predecessor edges in our graph and with no
1872 // points-to set (since it can't point to anything either, being that it
1873 // receives no points-to sets and has none).
1874 if (NodeIndex >= FirstRefNode) {
1875 unsigned j = VSSCCRep[FindNode(NodeIndex - FirstRefNode)];
1876 if ((Node2Visited[j] && !GraphNodes[j].PointerEquivLabel)
1877 || (GraphNodes[j].Direct && !GraphNodes[j].PredEdges
1878 && GraphNodes[j].PointsTo->empty())){
1879 return;
1880 }
1881 }
1882 // Process all our explicit edges
1883 if (N->PredEdges)
1884 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1885 Iter != N->PredEdges->end();
1886 ++Iter) {
1887 unsigned j = VSSCCRep[*Iter];
1888 if (!Node2Visited[j])
1889 HUValNum(j);
1890
1891 // If this edge turned out to be the same as us, or got no pointer
1892 // equivalence label (and thus points to nothing) , just decrement our
1893 // incoming edges and continue.
1894 if (j == NodeIndex || GraphNodes[j].PointerEquivLabel == 0) {
1895 --GraphNodes[j].NumInEdges;
1896 continue;
1897 }
1898
1899 *(N->PointsTo) |= GraphNodes[j].PointsTo;
1900
1901 // If we didn't end up storing this in the hash, and we're done with all
1902 // the edges, we don't need the points-to set anymore.
1903 --GraphNodes[j].NumInEdges;
1904 if (!GraphNodes[j].NumInEdges && !GraphNodes[j].StoredInHash) {
1905 delete GraphNodes[j].PointsTo;
1906 GraphNodes[j].PointsTo = NULL;
1907 }
1908 }
1909 // If this isn't a direct node, generate a fresh variable.
1910 if (!N->Direct) {
1911 N->PointsTo->set(FirstRefNode + NodeIndex);
1912 }
1913
1914 // See If we have something equivalent to us, if not, generate a new
1915 // equivalence class.
1916 if (N->PointsTo->empty()) {
1917 delete N->PointsTo;
1918 N->PointsTo = NULL;
1919 } else {
1920 if (N->Direct) {
1921 N->PointerEquivLabel = Set2PEClass[N->PointsTo];
1922 if (N->PointerEquivLabel == 0) {
1923 unsigned EquivClass = PEClass++;
1924 N->StoredInHash = true;
1925 Set2PEClass[N->PointsTo] = EquivClass;
1926 N->PointerEquivLabel = EquivClass;
1927 }
1928 } else {
1929 N->PointerEquivLabel = PEClass++;
1930 }
1931 }
1932}
1933
1934/// Rewrite our list of constraints so that pointer equivalent nodes are
1935/// replaced by their the pointer equivalence class representative.
1936void Andersens::RewriteConstraints() {
1937 std::vector<Constraint> NewConstraints;
Chris Lattnerbe207732007-09-30 00:47:20 +00001938 DenseSet<Constraint, ConstraintKeyInfo> Seen;
Daniel Berlind81ccc22007-09-24 19:45:49 +00001939
1940 PEClass2Node.clear();
1941 PENLEClass2Node.clear();
1942
1943 // We may have from 1 to Graphnodes + 1 equivalence classes.
1944 PEClass2Node.insert(PEClass2Node.begin(), GraphNodes.size() + 1, -1);
1945 PENLEClass2Node.insert(PENLEClass2Node.begin(), GraphNodes.size() + 1, -1);
1946
1947 // Rewrite constraints, ignoring non-pointer constraints, uniting equivalent
1948 // nodes, and rewriting constraints to use the representative nodes.
1949 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1950 Constraint &C = Constraints[i];
1951 unsigned RHSNode = FindNode(C.Src);
1952 unsigned LHSNode = FindNode(C.Dest);
1953 unsigned RHSLabel = GraphNodes[VSSCCRep[RHSNode]].PointerEquivLabel;
1954 unsigned LHSLabel = GraphNodes[VSSCCRep[LHSNode]].PointerEquivLabel;
1955
1956 // First we try to eliminate constraints for things we can prove don't point
1957 // to anything.
1958 if (LHSLabel == 0) {
1959 DEBUG(PrintNode(&GraphNodes[LHSNode]));
1960 DOUT << " is a non-pointer, ignoring constraint.\n";
1961 continue;
1962 }
1963 if (RHSLabel == 0) {
1964 DEBUG(PrintNode(&GraphNodes[RHSNode]));
1965 DOUT << " is a non-pointer, ignoring constraint.\n";
1966 continue;
1967 }
1968 // This constraint may be useless, and it may become useless as we translate
1969 // it.
1970 if (C.Src == C.Dest && C.Type == Constraint::Copy)
1971 continue;
Daniel Berlinc7a12ae2007-09-27 15:42:23 +00001972
Daniel Berlind81ccc22007-09-24 19:45:49 +00001973 C.Src = FindEquivalentNode(RHSNode, RHSLabel);
1974 C.Dest = FindEquivalentNode(FindNode(LHSNode), LHSLabel);
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001975 if ((C.Src == C.Dest && C.Type == Constraint::Copy)
Chris Lattnerbe207732007-09-30 00:47:20 +00001976 || Seen.count(C))
Daniel Berlind81ccc22007-09-24 19:45:49 +00001977 continue;
1978
Chris Lattnerbe207732007-09-30 00:47:20 +00001979 Seen.insert(C);
Daniel Berlind81ccc22007-09-24 19:45:49 +00001980 NewConstraints.push_back(C);
1981 }
1982 Constraints.swap(NewConstraints);
1983 PEClass2Node.clear();
1984}
1985
1986/// See if we have a node that is pointer equivalent to the one being asked
1987/// about, and if so, unite them and return the equivalent node. Otherwise,
1988/// return the original node.
1989unsigned Andersens::FindEquivalentNode(unsigned NodeIndex,
1990 unsigned NodeLabel) {
1991 if (!GraphNodes[NodeIndex].AddressTaken) {
1992 if (PEClass2Node[NodeLabel] != -1) {
1993 // We found an existing node with the same pointer label, so unify them.
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001994 // We specifically request that Union-By-Rank not be used so that
1995 // PEClass2Node[NodeLabel] U= NodeIndex and not the other way around.
1996 return UniteNodes(PEClass2Node[NodeLabel], NodeIndex, false);
Daniel Berlind81ccc22007-09-24 19:45:49 +00001997 } else {
1998 PEClass2Node[NodeLabel] = NodeIndex;
1999 PENLEClass2Node[NodeLabel] = NodeIndex;
2000 }
2001 } else if (PENLEClass2Node[NodeLabel] == -1) {
2002 PENLEClass2Node[NodeLabel] = NodeIndex;
2003 }
2004
2005 return NodeIndex;
2006}
2007
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002008void Andersens::PrintLabels() const {
Daniel Berlind81ccc22007-09-24 19:45:49 +00002009 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2010 if (i < FirstRefNode) {
2011 PrintNode(&GraphNodes[i]);
2012 } else if (i < FirstAdrNode) {
2013 DOUT << "REF(";
2014 PrintNode(&GraphNodes[i-FirstRefNode]);
2015 DOUT <<")";
2016 } else {
2017 DOUT << "ADR(";
2018 PrintNode(&GraphNodes[i-FirstAdrNode]);
2019 DOUT <<")";
2020 }
2021
2022 DOUT << " has pointer label " << GraphNodes[i].PointerEquivLabel
2023 << " and SCC rep " << VSSCCRep[i]
2024 << " and is " << (GraphNodes[i].Direct ? "Direct" : "Not direct")
2025 << "\n";
2026 }
2027}
2028
Daniel Berlinc864edb2008-03-05 19:31:47 +00002029/// The technique used here is described in "The Ant and the
2030/// Grasshopper: Fast and Accurate Pointer Analysis for Millions of
2031/// Lines of Code. In Programming Language Design and Implementation
2032/// (PLDI), June 2007." It is known as the "HCD" (Hybrid Cycle
2033/// Detection) algorithm. It is called a hybrid because it performs an
2034/// offline analysis and uses its results during the solving (online)
2035/// phase. This is just the offline portion; the results of this
2036/// operation are stored in SDT and are later used in SolveContraints()
2037/// and UniteNodes().
2038void Andersens::HCD() {
2039 DOUT << "Starting HCD.\n";
2040 HCDSCCRep.resize(GraphNodes.size());
2041
2042 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2043 GraphNodes[i].Edges = new SparseBitVector<>;
2044 HCDSCCRep[i] = i;
2045 }
2046
2047 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2048 Constraint &C = Constraints[i];
2049 assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
2050 if (C.Type == Constraint::AddressOf) {
2051 continue;
2052 } else if (C.Type == Constraint::Load) {
2053 if( C.Offset == 0 )
2054 GraphNodes[C.Dest].Edges->set(C.Src + FirstRefNode);
2055 } else if (C.Type == Constraint::Store) {
2056 if( C.Offset == 0 )
2057 GraphNodes[C.Dest + FirstRefNode].Edges->set(C.Src);
2058 } else {
2059 GraphNodes[C.Dest].Edges->set(C.Src);
2060 }
2061 }
2062
2063 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2064 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2065 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
2066 SDT.insert(SDT.begin(), GraphNodes.size() / 2, -1);
2067
2068 DFSNumber = 0;
2069 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2070 unsigned Node = HCDSCCRep[i];
2071 if (!Node2Deleted[Node])
2072 Search(Node);
2073 }
2074
2075 for (unsigned i = 0; i < GraphNodes.size(); ++i)
2076 if (GraphNodes[i].Edges != NULL) {
2077 delete GraphNodes[i].Edges;
2078 GraphNodes[i].Edges = NULL;
2079 }
2080
2081 while( !SCCStack.empty() )
2082 SCCStack.pop();
2083
2084 Node2DFS.clear();
2085 Node2Visited.clear();
2086 Node2Deleted.clear();
2087 HCDSCCRep.clear();
2088 DOUT << "HCD complete.\n";
2089}
2090
2091// Component of HCD:
2092// Use Nuutila's variant of Tarjan's algorithm to detect
2093// Strongly-Connected Components (SCCs). For non-trivial SCCs
2094// containing ref nodes, insert the appropriate information in SDT.
2095void Andersens::Search(unsigned Node) {
2096 unsigned MyDFS = DFSNumber++;
2097
2098 Node2Visited[Node] = true;
2099 Node2DFS[Node] = MyDFS;
2100
2101 for (SparseBitVector<>::iterator Iter = GraphNodes[Node].Edges->begin(),
2102 End = GraphNodes[Node].Edges->end();
2103 Iter != End;
2104 ++Iter) {
2105 unsigned J = HCDSCCRep[*Iter];
2106 assert(GraphNodes[J].isRep() && "Debug check; must be representative");
2107 if (!Node2Deleted[J]) {
2108 if (!Node2Visited[J])
2109 Search(J);
2110 if (Node2DFS[Node] > Node2DFS[J])
2111 Node2DFS[Node] = Node2DFS[J];
2112 }
2113 }
2114
2115 if( MyDFS != Node2DFS[Node] ) {
2116 SCCStack.push(Node);
2117 return;
2118 }
2119
2120 // This node is the root of a SCC, so process it.
2121 //
2122 // If the SCC is "non-trivial" (not a singleton) and contains a reference
2123 // node, we place this SCC into SDT. We unite the nodes in any case.
2124 if (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
2125 SparseBitVector<> SCC;
2126
2127 SCC.set(Node);
2128
2129 bool Ref = (Node >= FirstRefNode);
2130
2131 Node2Deleted[Node] = true;
2132
2133 do {
2134 unsigned P = SCCStack.top(); SCCStack.pop();
2135 Ref |= (P >= FirstRefNode);
2136 SCC.set(P);
2137 HCDSCCRep[P] = Node;
2138 } while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS);
2139
2140 if (Ref) {
2141 unsigned Rep = SCC.find_first();
2142 assert(Rep < FirstRefNode && "The SCC didn't have a non-Ref node!");
2143
2144 SparseBitVector<>::iterator i = SCC.begin();
2145
2146 // Skip over the non-ref nodes
2147 while( *i < FirstRefNode )
2148 ++i;
2149
2150 while( i != SCC.end() )
2151 SDT[ (*i++) - FirstRefNode ] = Rep;
2152 }
2153 }
2154}
2155
2156
Daniel Berlind81ccc22007-09-24 19:45:49 +00002157/// Optimize the constraints by performing offline variable substitution and
2158/// other optimizations.
2159void Andersens::OptimizeConstraints() {
2160 DOUT << "Beginning constraint optimization\n";
2161
Daniel Berlinc864edb2008-03-05 19:31:47 +00002162 SDTActive = false;
2163
Daniel Berlind81ccc22007-09-24 19:45:49 +00002164 // Function related nodes need to stay in the same relative position and can't
2165 // be location equivalent.
2166 for (std::map<unsigned, unsigned>::iterator Iter = MaxK.begin();
2167 Iter != MaxK.end();
2168 ++Iter) {
2169 for (unsigned i = Iter->first;
2170 i != Iter->first + Iter->second;
2171 ++i) {
2172 GraphNodes[i].AddressTaken = true;
2173 GraphNodes[i].Direct = false;
2174 }
2175 }
2176
2177 ClumpAddressTaken();
2178 FirstRefNode = GraphNodes.size();
2179 FirstAdrNode = FirstRefNode + GraphNodes.size();
2180 GraphNodes.insert(GraphNodes.end(), 2 * GraphNodes.size(),
2181 Node(false));
2182 VSSCCRep.resize(GraphNodes.size());
2183 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2184 VSSCCRep[i] = i;
2185 }
2186 HVN();
2187 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2188 Node *N = &GraphNodes[i];
2189 delete N->PredEdges;
2190 N->PredEdges = NULL;
2191 delete N->ImplicitPredEdges;
2192 N->ImplicitPredEdges = NULL;
2193 }
2194#undef DEBUG_TYPE
2195#define DEBUG_TYPE "anders-aa-labels"
2196 DEBUG(PrintLabels());
2197#undef DEBUG_TYPE
2198#define DEBUG_TYPE "anders-aa"
2199 RewriteConstraints();
2200 // Delete the adr nodes.
2201 GraphNodes.resize(FirstRefNode * 2);
2202
2203 // Now perform HU
2204 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2205 Node *N = &GraphNodes[i];
2206 if (FindNode(i) == i) {
2207 N->PointsTo = new SparseBitVector<>;
2208 N->PointedToBy = new SparseBitVector<>;
2209 // Reset our labels
2210 }
2211 VSSCCRep[i] = i;
2212 N->PointerEquivLabel = 0;
2213 }
2214 HU();
2215#undef DEBUG_TYPE
2216#define DEBUG_TYPE "anders-aa-labels"
2217 DEBUG(PrintLabels());
2218#undef DEBUG_TYPE
2219#define DEBUG_TYPE "anders-aa"
2220 RewriteConstraints();
2221 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2222 if (FindNode(i) == i) {
2223 Node *N = &GraphNodes[i];
2224 delete N->PointsTo;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002225 N->PointsTo = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002226 delete N->PredEdges;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002227 N->PredEdges = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002228 delete N->ImplicitPredEdges;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002229 N->ImplicitPredEdges = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002230 delete N->PointedToBy;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002231 N->PointedToBy = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002232 }
2233 }
Daniel Berlinc864edb2008-03-05 19:31:47 +00002234
2235 // perform Hybrid Cycle Detection (HCD)
2236 HCD();
2237 SDTActive = true;
2238
2239 // No longer any need for the upper half of GraphNodes (for ref nodes).
Daniel Berlind81ccc22007-09-24 19:45:49 +00002240 GraphNodes.erase(GraphNodes.begin() + FirstRefNode, GraphNodes.end());
Daniel Berlinc864edb2008-03-05 19:31:47 +00002241
2242 // HCD complete.
2243
Daniel Berlind81ccc22007-09-24 19:45:49 +00002244 DOUT << "Finished constraint optimization\n";
2245 FirstRefNode = 0;
2246 FirstAdrNode = 0;
2247}
2248
2249/// Unite pointer but not location equivalent variables, now that the constraint
2250/// graph is built.
2251void Andersens::UnitePointerEquivalences() {
2252 DOUT << "Uniting remaining pointer equivalences\n";
2253 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002254 if (GraphNodes[i].AddressTaken && GraphNodes[i].isRep()) {
Daniel Berlind81ccc22007-09-24 19:45:49 +00002255 unsigned Label = GraphNodes[i].PointerEquivLabel;
2256
2257 if (Label && PENLEClass2Node[Label] != -1)
2258 UniteNodes(i, PENLEClass2Node[Label]);
2259 }
2260 }
2261 DOUT << "Finished remaining pointer equivalences\n";
2262 PENLEClass2Node.clear();
2263}
2264
2265/// Create the constraint graph used for solving points-to analysis.
2266///
Daniel Berlinaad15882007-09-16 21:45:02 +00002267void Andersens::CreateConstraintGraph() {
2268 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2269 Constraint &C = Constraints[i];
2270 assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
2271 if (C.Type == Constraint::AddressOf)
2272 GraphNodes[C.Dest].PointsTo->set(C.Src);
2273 else if (C.Type == Constraint::Load)
2274 GraphNodes[C.Src].Constraints.push_back(C);
2275 else if (C.Type == Constraint::Store)
2276 GraphNodes[C.Dest].Constraints.push_back(C);
2277 else if (C.Offset != 0)
2278 GraphNodes[C.Src].Constraints.push_back(C);
2279 else
2280 GraphNodes[C.Src].Edges->set(C.Dest);
2281 }
2282}
2283
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002284// Perform DFS and cycle detection.
2285bool Andersens::QueryNode(unsigned Node) {
2286 assert(GraphNodes[Node].isRep() && "Querying a non-rep node");
Daniel Berlinaad15882007-09-16 21:45:02 +00002287 unsigned OurDFS = ++DFSNumber;
2288 SparseBitVector<> ToErase;
2289 SparseBitVector<> NewEdges;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002290 Tarjan2DFS[Node] = OurDFS;
2291
2292 // Changed denotes a change from a recursive call that we will bubble up.
2293 // Merged is set if we actually merge a node ourselves.
2294 bool Changed = false, Merged = false;
Daniel Berlinaad15882007-09-16 21:45:02 +00002295
2296 for (SparseBitVector<>::iterator bi = GraphNodes[Node].Edges->begin();
2297 bi != GraphNodes[Node].Edges->end();
2298 ++bi) {
2299 unsigned RepNode = FindNode(*bi);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002300 // If this edge points to a non-representative node but we are
2301 // already planning to add an edge to its representative, we have no
2302 // need for this edge anymore.
Daniel Berlinaad15882007-09-16 21:45:02 +00002303 if (RepNode != *bi && NewEdges.test(RepNode)){
2304 ToErase.set(*bi);
2305 continue;
2306 }
2307
2308 // Continue about our DFS.
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002309 if (!Tarjan2Deleted[RepNode]){
2310 if (Tarjan2DFS[RepNode] == 0) {
2311 Changed |= QueryNode(RepNode);
2312 // May have been changed by QueryNode
Daniel Berlinaad15882007-09-16 21:45:02 +00002313 RepNode = FindNode(RepNode);
2314 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002315 if (Tarjan2DFS[RepNode] < Tarjan2DFS[Node])
2316 Tarjan2DFS[Node] = Tarjan2DFS[RepNode];
Daniel Berlinaad15882007-09-16 21:45:02 +00002317 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002318
2319 // We may have just discovered that this node is part of a cycle, in
2320 // which case we can also erase it.
Daniel Berlinaad15882007-09-16 21:45:02 +00002321 if (RepNode != *bi) {
2322 ToErase.set(*bi);
2323 NewEdges.set(RepNode);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002324 }
2325 }
2326
Daniel Berlinaad15882007-09-16 21:45:02 +00002327 GraphNodes[Node].Edges->intersectWithComplement(ToErase);
2328 GraphNodes[Node].Edges |= NewEdges;
2329
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002330 // If this node is a root of a non-trivial SCC, place it on our
2331 // worklist to be processed.
2332 if (OurDFS == Tarjan2DFS[Node]) {
2333 while (!SCCStack.empty() && Tarjan2DFS[SCCStack.top()] >= OurDFS) {
2334 Node = UniteNodes(Node, SCCStack.top());
Daniel Berlinaad15882007-09-16 21:45:02 +00002335
2336 SCCStack.pop();
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002337 Merged = true;
Daniel Berlinaad15882007-09-16 21:45:02 +00002338 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002339 Tarjan2Deleted[Node] = true;
Daniel Berlinaad15882007-09-16 21:45:02 +00002340
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002341 if (Merged)
2342 NextWL->insert(&GraphNodes[Node]);
Daniel Berlinaad15882007-09-16 21:45:02 +00002343 } else {
2344 SCCStack.push(Node);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002345 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002346
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002347 return(Changed | Merged);
2348}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002349
2350/// SolveConstraints - This stage iteratively processes the constraints list
2351/// propagating constraints (adding edges to the Nodes in the points-to graph)
2352/// until a fixed point is reached.
2353///
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002354/// We use a variant of the technique called "Lazy Cycle Detection", which is
2355/// described in "The Ant and the Grasshopper: Fast and Accurate Pointer
2356/// Analysis for Millions of Lines of Code. In Programming Language Design and
2357/// Implementation (PLDI), June 2007."
2358/// The paper describes performing cycle detection one node at a time, which can
2359/// be expensive if there are no cycles, but there are long chains of nodes that
2360/// it heuristically believes are cycles (because it will DFS from each node
2361/// without state from previous nodes).
2362/// Instead, we use the heuristic to build a worklist of nodes to check, then
2363/// cycle detect them all at the same time to do this more cheaply. This
2364/// catches cycles slightly later than the original technique did, but does it
2365/// make significantly cheaper.
2366
Chris Lattnere995a2a2004-05-23 21:00:47 +00002367void Andersens::SolveConstraints() {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002368 CurrWL = &w1;
2369 NextWL = &w2;
Daniel Berlinaad15882007-09-16 21:45:02 +00002370
Daniel Berlind81ccc22007-09-24 19:45:49 +00002371 OptimizeConstraints();
2372#undef DEBUG_TYPE
2373#define DEBUG_TYPE "anders-aa-constraints"
2374 DEBUG(PrintConstraints());
2375#undef DEBUG_TYPE
2376#define DEBUG_TYPE "anders-aa"
2377
Daniel Berlinaad15882007-09-16 21:45:02 +00002378 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2379 Node *N = &GraphNodes[i];
2380 N->PointsTo = new SparseBitVector<>;
2381 N->OldPointsTo = new SparseBitVector<>;
2382 N->Edges = new SparseBitVector<>;
2383 }
2384 CreateConstraintGraph();
Daniel Berlind81ccc22007-09-24 19:45:49 +00002385 UnitePointerEquivalences();
2386 assert(SCCStack.empty() && "SCC Stack should be empty by now!");
Daniel Berlind81ccc22007-09-24 19:45:49 +00002387 Node2DFS.clear();
2388 Node2Deleted.clear();
Daniel Berlinaad15882007-09-16 21:45:02 +00002389 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2390 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2391 DFSNumber = 0;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002392 DenseSet<Constraint, ConstraintKeyInfo> Seen;
2393 DenseSet<std::pair<unsigned,unsigned>, PairKeyInfo> EdgesChecked;
2394
2395 // Order graph and add initial nodes to work list.
Daniel Berlinaad15882007-09-16 21:45:02 +00002396 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
Daniel Berlinaad15882007-09-16 21:45:02 +00002397 Node *INode = &GraphNodes[i];
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002398
2399 // Add to work list if it's a representative and can contribute to the
2400 // calculation right now.
2401 if (INode->isRep() && !INode->PointsTo->empty()
2402 && (!INode->Edges->empty() || !INode->Constraints.empty())) {
2403 INode->Stamp();
2404 CurrWL->insert(INode);
Daniel Berlinaad15882007-09-16 21:45:02 +00002405 }
2406 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002407 std::queue<unsigned int> TarjanWL;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002408#if !FULL_UNIVERSAL
2409 // "Rep and special variables" - in order for HCD to maintain conservative
2410 // results when !FULL_UNIVERSAL, we need to treat the special variables in
2411 // the same way that the !FULL_UNIVERSAL tweak does throughout the rest of
2412 // the analysis - it's ok to add edges from the special nodes, but never
2413 // *to* the special nodes.
2414 std::vector<unsigned int> RSV;
2415#endif
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002416 while( !CurrWL->empty() ) {
2417 DOUT << "Starting iteration #" << ++NumIters << "\n";
Daniel Berlinaad15882007-09-16 21:45:02 +00002418
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002419 Node* CurrNode;
2420 unsigned CurrNodeIndex;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002421
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002422 // Actual cycle checking code. We cycle check all of the lazy cycle
2423 // candidates from the last iteration in one go.
2424 if (!TarjanWL.empty()) {
2425 DFSNumber = 0;
2426
2427 Tarjan2DFS.clear();
2428 Tarjan2Deleted.clear();
2429 while (!TarjanWL.empty()) {
2430 unsigned int ToTarjan = TarjanWL.front();
2431 TarjanWL.pop();
2432 if (!Tarjan2Deleted[ToTarjan]
2433 && GraphNodes[ToTarjan].isRep()
2434 && Tarjan2DFS[ToTarjan] == 0)
2435 QueryNode(ToTarjan);
2436 }
2437 }
2438
2439 // Add to work list if it's a representative and can contribute to the
2440 // calculation right now.
2441 while( (CurrNode = CurrWL->pop()) != NULL ) {
2442 CurrNodeIndex = CurrNode - &GraphNodes[0];
2443 CurrNode->Stamp();
2444
2445
Daniel Berlinaad15882007-09-16 21:45:02 +00002446 // Figure out the changed points to bits
2447 SparseBitVector<> CurrPointsTo;
2448 CurrPointsTo.intersectWithComplement(CurrNode->PointsTo,
2449 CurrNode->OldPointsTo);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002450 if (CurrPointsTo.empty())
Daniel Berlinaad15882007-09-16 21:45:02 +00002451 continue;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002452
Daniel Berlinaad15882007-09-16 21:45:02 +00002453 *(CurrNode->OldPointsTo) |= CurrPointsTo;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002454
2455 // Check the offline-computed equivalencies from HCD.
2456 bool SCC = false;
2457 unsigned Rep;
2458
2459 if (SDT[CurrNodeIndex] >= 0) {
2460 SCC = true;
2461 Rep = FindNode(SDT[CurrNodeIndex]);
2462
2463#if !FULL_UNIVERSAL
2464 RSV.clear();
2465#endif
2466 for (SparseBitVector<>::iterator bi = CurrPointsTo.begin();
2467 bi != CurrPointsTo.end(); ++bi) {
2468 unsigned Node = FindNode(*bi);
2469#if !FULL_UNIVERSAL
2470 if (Node < NumberSpecialNodes) {
2471 RSV.push_back(Node);
2472 continue;
2473 }
2474#endif
2475 Rep = UniteNodes(Rep,Node);
2476 }
2477#if !FULL_UNIVERSAL
2478 RSV.push_back(Rep);
2479#endif
2480
2481 NextWL->insert(&GraphNodes[Rep]);
2482
2483 if ( ! CurrNode->isRep() )
2484 continue;
2485 }
2486
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002487 Seen.clear();
Chris Lattnere995a2a2004-05-23 21:00:47 +00002488
Daniel Berlinaad15882007-09-16 21:45:02 +00002489 /* Now process the constraints for this node. */
2490 for (std::list<Constraint>::iterator li = CurrNode->Constraints.begin();
2491 li != CurrNode->Constraints.end(); ) {
2492 li->Src = FindNode(li->Src);
2493 li->Dest = FindNode(li->Dest);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002494
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002495 // Delete redundant constraints
2496 if( Seen.count(*li) ) {
2497 std::list<Constraint>::iterator lk = li; li++;
2498
2499 CurrNode->Constraints.erase(lk);
2500 ++NumErased;
2501 continue;
2502 }
2503 Seen.insert(*li);
2504
Daniel Berlinaad15882007-09-16 21:45:02 +00002505 // Src and Dest will be the vars we are going to process.
2506 // This may look a bit ugly, but what it does is allow us to process
Daniel Berlind81ccc22007-09-24 19:45:49 +00002507 // both store and load constraints with the same code.
Daniel Berlinaad15882007-09-16 21:45:02 +00002508 // Load constraints say that every member of our RHS solution has K
2509 // added to it, and that variable gets an edge to LHS. We also union
2510 // RHS+K's solution into the LHS solution.
2511 // Store constraints say that every member of our LHS solution has K
2512 // added to it, and that variable gets an edge from RHS. We also union
2513 // RHS's solution into the LHS+K solution.
2514 unsigned *Src;
2515 unsigned *Dest;
2516 unsigned K = li->Offset;
2517 unsigned CurrMember;
2518 if (li->Type == Constraint::Load) {
2519 Src = &CurrMember;
2520 Dest = &li->Dest;
2521 } else if (li->Type == Constraint::Store) {
2522 Src = &li->Src;
2523 Dest = &CurrMember;
2524 } else {
2525 // TODO Handle offseted copy constraint
2526 li++;
2527 continue;
2528 }
Daniel Berlinc864edb2008-03-05 19:31:47 +00002529
2530 // See if we can use Hybrid Cycle Detection (that is, check
Daniel Berlinaad15882007-09-16 21:45:02 +00002531 // if it was a statically detected offline equivalence that
Daniel Berlinc864edb2008-03-05 19:31:47 +00002532 // involves pointers; if so, remove the redundant constraints).
2533 if( SCC && K == 0 ) {
2534#if FULL_UNIVERSAL
2535 CurrMember = Rep;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002536
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002537 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2538 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2539 NextWL->insert(&GraphNodes[*Dest]);
Daniel Berlinc864edb2008-03-05 19:31:47 +00002540#else
2541 for (unsigned i=0; i < RSV.size(); ++i) {
2542 CurrMember = RSV[i];
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002543
Daniel Berlinc864edb2008-03-05 19:31:47 +00002544 if (*Dest < NumberSpecialNodes)
2545 continue;
2546 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2547 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2548 NextWL->insert(&GraphNodes[*Dest]);
2549 }
2550#endif
2551 // since all future elements of the points-to set will be
2552 // equivalent to the current ones, the complex constraints
2553 // become redundant.
2554 //
2555 std::list<Constraint>::iterator lk = li; li++;
2556#if !FULL_UNIVERSAL
2557 // In this case, we can still erase the constraints when the
2558 // elements of the points-to sets are referenced by *Dest,
2559 // but not when they are referenced by *Src (i.e. for a Load
2560 // constraint). This is because if another special variable is
2561 // put into the points-to set later, we still need to add the
2562 // new edge from that special variable.
2563 if( lk->Type != Constraint::Load)
2564#endif
2565 GraphNodes[CurrNodeIndex].Constraints.erase(lk);
2566 } else {
2567 const SparseBitVector<> &Solution = CurrPointsTo;
2568
2569 for (SparseBitVector<>::iterator bi = Solution.begin();
2570 bi != Solution.end();
2571 ++bi) {
2572 CurrMember = *bi;
2573
2574 // Need to increment the member by K since that is where we are
2575 // supposed to copy to/from. Note that in positive weight cycles,
2576 // which occur in address taking of fields, K can go past
2577 // MaxK[CurrMember] elements, even though that is all it could point
2578 // to.
2579 if (K > 0 && K > MaxK[CurrMember])
2580 continue;
2581 else
2582 CurrMember = FindNode(CurrMember + K);
2583
2584 // Add an edge to the graph, so we can just do regular
2585 // bitmap ior next time. It may also let us notice a cycle.
2586#if !FULL_UNIVERSAL
2587 if (*Dest < NumberSpecialNodes)
2588 continue;
2589#endif
2590 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2591 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2592 NextWL->insert(&GraphNodes[*Dest]);
2593
2594 }
2595 li++;
Daniel Berlinaad15882007-09-16 21:45:02 +00002596 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002597 }
2598 SparseBitVector<> NewEdges;
2599 SparseBitVector<> ToErase;
2600
2601 // Now all we have left to do is propagate points-to info along the
2602 // edges, erasing the redundant edges.
Daniel Berlinaad15882007-09-16 21:45:02 +00002603 for (SparseBitVector<>::iterator bi = CurrNode->Edges->begin();
2604 bi != CurrNode->Edges->end();
2605 ++bi) {
2606
2607 unsigned DestVar = *bi;
2608 unsigned Rep = FindNode(DestVar);
2609
Bill Wendlingf059deb2008-02-26 10:51:52 +00002610 // If we ended up with this node as our destination, or we've already
2611 // got an edge for the representative, delete the current edge.
2612 if (Rep == CurrNodeIndex ||
2613 (Rep != DestVar && NewEdges.test(Rep))) {
Daniel Berlinc864edb2008-03-05 19:31:47 +00002614 ToErase.set(DestVar);
2615 continue;
Bill Wendlingf059deb2008-02-26 10:51:52 +00002616 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002617
Bill Wendlingf059deb2008-02-26 10:51:52 +00002618 std::pair<unsigned,unsigned> edge(CurrNodeIndex,Rep);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002619
2620 // This is where we do lazy cycle detection.
2621 // If this is a cycle candidate (equal points-to sets and this
2622 // particular edge has not been cycle-checked previously), add to the
2623 // list to check for cycles on the next iteration.
2624 if (!EdgesChecked.count(edge) &&
2625 *(GraphNodes[Rep].PointsTo) == *(CurrNode->PointsTo)) {
2626 EdgesChecked.insert(edge);
2627 TarjanWL.push(Rep);
Daniel Berlinaad15882007-09-16 21:45:02 +00002628 }
2629 // Union the points-to sets into the dest
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002630#if !FULL_UNIVERSAL
2631 if (Rep >= NumberSpecialNodes)
2632#endif
Daniel Berlinaad15882007-09-16 21:45:02 +00002633 if (GraphNodes[Rep].PointsTo |= CurrPointsTo) {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002634 NextWL->insert(&GraphNodes[Rep]);
Daniel Berlinaad15882007-09-16 21:45:02 +00002635 }
2636 // If this edge's destination was collapsed, rewrite the edge.
2637 if (Rep != DestVar) {
2638 ToErase.set(DestVar);
2639 NewEdges.set(Rep);
2640 }
2641 }
2642 CurrNode->Edges->intersectWithComplement(ToErase);
2643 CurrNode->Edges |= NewEdges;
2644 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002645
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002646 // Switch to other work list.
2647 WorkList* t = CurrWL; CurrWL = NextWL; NextWL = t;
2648 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002649
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002650
Daniel Berlinaad15882007-09-16 21:45:02 +00002651 Node2DFS.clear();
2652 Node2Deleted.clear();
2653 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2654 Node *N = &GraphNodes[i];
2655 delete N->OldPointsTo;
2656 delete N->Edges;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002657 }
Daniel Berlinc864edb2008-03-05 19:31:47 +00002658 SDTActive = false;
2659 SDT.clear();
Chris Lattnere995a2a2004-05-23 21:00:47 +00002660}
2661
Daniel Berlinaad15882007-09-16 21:45:02 +00002662//===----------------------------------------------------------------------===//
2663// Union-Find
2664//===----------------------------------------------------------------------===//
Chris Lattnere995a2a2004-05-23 21:00:47 +00002665
Daniel Berlinaad15882007-09-16 21:45:02 +00002666// Unite nodes First and Second, returning the one which is now the
2667// representative node. First and Second are indexes into GraphNodes
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002668unsigned Andersens::UniteNodes(unsigned First, unsigned Second,
2669 bool UnionByRank) {
Daniel Berlinaad15882007-09-16 21:45:02 +00002670 assert (First < GraphNodes.size() && Second < GraphNodes.size() &&
2671 "Attempting to merge nodes that don't exist");
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002672
Daniel Berlinaad15882007-09-16 21:45:02 +00002673 Node *FirstNode = &GraphNodes[First];
2674 Node *SecondNode = &GraphNodes[Second];
2675
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002676 assert (SecondNode->isRep() && FirstNode->isRep() &&
Daniel Berlinaad15882007-09-16 21:45:02 +00002677 "Trying to unite two non-representative nodes!");
2678 if (First == Second)
2679 return First;
2680
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002681 if (UnionByRank) {
2682 int RankFirst = (int) FirstNode ->NodeRep;
2683 int RankSecond = (int) SecondNode->NodeRep;
2684
2685 // Rank starts at -1 and gets decremented as it increases.
2686 // Translation: higher rank, lower NodeRep value, which is always negative.
2687 if (RankFirst > RankSecond) {
2688 unsigned t = First; First = Second; Second = t;
2689 Node* tp = FirstNode; FirstNode = SecondNode; SecondNode = tp;
2690 } else if (RankFirst == RankSecond) {
2691 FirstNode->NodeRep = (unsigned) (RankFirst - 1);
2692 }
2693 }
2694
Daniel Berlinaad15882007-09-16 21:45:02 +00002695 SecondNode->NodeRep = First;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002696#if !FULL_UNIVERSAL
2697 if (First >= NumberSpecialNodes)
2698#endif
Daniel Berlind81ccc22007-09-24 19:45:49 +00002699 if (FirstNode->PointsTo && SecondNode->PointsTo)
2700 FirstNode->PointsTo |= *(SecondNode->PointsTo);
2701 if (FirstNode->Edges && SecondNode->Edges)
2702 FirstNode->Edges |= *(SecondNode->Edges);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002703 if (!SecondNode->Constraints.empty())
Daniel Berlind81ccc22007-09-24 19:45:49 +00002704 FirstNode->Constraints.splice(FirstNode->Constraints.begin(),
2705 SecondNode->Constraints);
2706 if (FirstNode->OldPointsTo) {
2707 delete FirstNode->OldPointsTo;
2708 FirstNode->OldPointsTo = new SparseBitVector<>;
2709 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002710
2711 // Destroy interesting parts of the merged-from node.
2712 delete SecondNode->OldPointsTo;
2713 delete SecondNode->Edges;
2714 delete SecondNode->PointsTo;
2715 SecondNode->Edges = NULL;
2716 SecondNode->PointsTo = NULL;
2717 SecondNode->OldPointsTo = NULL;
2718
2719 NumUnified++;
2720 DOUT << "Unified Node ";
2721 DEBUG(PrintNode(FirstNode));
2722 DOUT << " and Node ";
2723 DEBUG(PrintNode(SecondNode));
2724 DOUT << "\n";
2725
Daniel Berlinc864edb2008-03-05 19:31:47 +00002726 if (SDTActive)
Duncan Sands43e2a032008-05-27 11:50:51 +00002727 if (SDT[Second] >= 0) {
Daniel Berlinc864edb2008-03-05 19:31:47 +00002728 if (SDT[First] < 0)
2729 SDT[First] = SDT[Second];
2730 else {
2731 UniteNodes( FindNode(SDT[First]), FindNode(SDT[Second]) );
2732 First = FindNode(First);
2733 }
Duncan Sands43e2a032008-05-27 11:50:51 +00002734 }
Daniel Berlinc864edb2008-03-05 19:31:47 +00002735
Daniel Berlinaad15882007-09-16 21:45:02 +00002736 return First;
2737}
2738
2739// Find the index into GraphNodes of the node representing Node, performing
2740// path compression along the way
2741unsigned Andersens::FindNode(unsigned NodeIndex) {
2742 assert (NodeIndex < GraphNodes.size()
2743 && "Attempting to find a node that can't exist");
2744 Node *N = &GraphNodes[NodeIndex];
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002745 if (N->isRep())
Daniel Berlinaad15882007-09-16 21:45:02 +00002746 return NodeIndex;
2747 else
2748 return (N->NodeRep = FindNode(N->NodeRep));
2749}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002750
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002751// Find the index into GraphNodes of the node representing Node,
2752// don't perform path compression along the way (for Print)
2753unsigned Andersens::FindNode(unsigned NodeIndex) const {
2754 assert (NodeIndex < GraphNodes.size()
2755 && "Attempting to find a node that can't exist");
2756 const Node *N = &GraphNodes[NodeIndex];
2757 if (N->isRep())
2758 return NodeIndex;
2759 else
2760 return FindNode(N->NodeRep);
2761}
2762
Chris Lattnere995a2a2004-05-23 21:00:47 +00002763//===----------------------------------------------------------------------===//
2764// Debugging Output
2765//===----------------------------------------------------------------------===//
2766
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002767void Andersens::PrintNode(const Node *N) const {
Chris Lattnere995a2a2004-05-23 21:00:47 +00002768 if (N == &GraphNodes[UniversalSet]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002769 cerr << "<universal>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002770 return;
2771 } else if (N == &GraphNodes[NullPtr]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002772 cerr << "<nullptr>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002773 return;
2774 } else if (N == &GraphNodes[NullObject]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002775 cerr << "<null>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002776 return;
2777 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002778 if (!N->getValue()) {
2779 cerr << "artificial" << (intptr_t) N;
2780 return;
2781 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002782
2783 assert(N->getValue() != 0 && "Never set node label!");
2784 Value *V = N->getValue();
2785 if (Function *F = dyn_cast<Function>(V)) {
2786 if (isa<PointerType>(F->getFunctionType()->getReturnType()) &&
Daniel Berlinaad15882007-09-16 21:45:02 +00002787 N == &GraphNodes[getReturnNode(F)]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002788 cerr << F->getName() << ":retval";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002789 return;
Daniel Berlinaad15882007-09-16 21:45:02 +00002790 } else if (F->getFunctionType()->isVarArg() &&
2791 N == &GraphNodes[getVarargNode(F)]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002792 cerr << F->getName() << ":vararg";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002793 return;
2794 }
2795 }
2796
2797 if (Instruction *I = dyn_cast<Instruction>(V))
Bill Wendlinge8156192006-12-07 01:30:32 +00002798 cerr << I->getParent()->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002799 else if (Argument *Arg = dyn_cast<Argument>(V))
Bill Wendlinge8156192006-12-07 01:30:32 +00002800 cerr << Arg->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002801
2802 if (V->hasName())
Bill Wendlinge8156192006-12-07 01:30:32 +00002803 cerr << V->getName();
Chris Lattnere995a2a2004-05-23 21:00:47 +00002804 else
Bill Wendlinge8156192006-12-07 01:30:32 +00002805 cerr << "(unnamed)";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002806
2807 if (isa<GlobalValue>(V) || isa<AllocationInst>(V))
Daniel Berlinaad15882007-09-16 21:45:02 +00002808 if (N == &GraphNodes[getObject(V)])
Bill Wendlinge8156192006-12-07 01:30:32 +00002809 cerr << "<mem>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002810}
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002811void Andersens::PrintConstraint(const Constraint &C) const {
Daniel Berlind81ccc22007-09-24 19:45:49 +00002812 if (C.Type == Constraint::Store) {
2813 cerr << "*";
2814 if (C.Offset != 0)
2815 cerr << "(";
2816 }
2817 PrintNode(&GraphNodes[C.Dest]);
2818 if (C.Type == Constraint::Store && C.Offset != 0)
2819 cerr << " + " << C.Offset << ")";
2820 cerr << " = ";
2821 if (C.Type == Constraint::Load) {
2822 cerr << "*";
2823 if (C.Offset != 0)
2824 cerr << "(";
2825 }
2826 else if (C.Type == Constraint::AddressOf)
2827 cerr << "&";
2828 PrintNode(&GraphNodes[C.Src]);
2829 if (C.Offset != 0 && C.Type != Constraint::Store)
2830 cerr << " + " << C.Offset;
2831 if (C.Type == Constraint::Load && C.Offset != 0)
2832 cerr << ")";
2833 cerr << "\n";
2834}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002835
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002836void Andersens::PrintConstraints() const {
Bill Wendlinge8156192006-12-07 01:30:32 +00002837 cerr << "Constraints:\n";
Daniel Berlinaad15882007-09-16 21:45:02 +00002838
Daniel Berlind81ccc22007-09-24 19:45:49 +00002839 for (unsigned i = 0, e = Constraints.size(); i != e; ++i)
2840 PrintConstraint(Constraints[i]);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002841}
2842
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002843void Andersens::PrintPointsToGraph() const {
Bill Wendlinge8156192006-12-07 01:30:32 +00002844 cerr << "Points-to graph:\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002845 for (unsigned i = 0, e = GraphNodes.size(); i != e; ++i) {
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002846 const Node *N = &GraphNodes[i];
2847 if (FindNode(i) != i) {
Daniel Berlinaad15882007-09-16 21:45:02 +00002848 PrintNode(N);
2849 cerr << "\t--> same as ";
2850 PrintNode(&GraphNodes[FindNode(i)]);
2851 cerr << "\n";
2852 } else {
2853 cerr << "[" << (N->PointsTo->count()) << "] ";
2854 PrintNode(N);
2855 cerr << "\t--> ";
2856
2857 bool first = true;
2858 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
2859 bi != N->PointsTo->end();
2860 ++bi) {
2861 if (!first)
2862 cerr << ", ";
2863 PrintNode(&GraphNodes[*bi]);
2864 first = false;
2865 }
2866 cerr << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002867 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002868 }
2869}