blob: d77997bb3979dc3f3936a5eafc58f85c5d946adb [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>
74#include <stack>
75#include <vector>
Daniel Berlin3a3f1632007-12-12 00:37:04 +000076#include <queue>
77
78// Determining the actual set of nodes the universal set can consist of is very
79// expensive because it means propagating around very large sets. We rely on
80// other analysis being able to determine which nodes can never be pointed to in
81// order to disambiguate further than "points-to anything".
82#define FULL_UNIVERSAL 0
Chris Lattnere995a2a2004-05-23 21:00:47 +000083
Daniel Berlinaad15882007-09-16 21:45:02 +000084using namespace llvm;
Daniel Berlind81ccc22007-09-24 19:45:49 +000085STATISTIC(NumIters , "Number of iterations to reach convergence");
86STATISTIC(NumConstraints, "Number of constraints");
87STATISTIC(NumNodes , "Number of nodes");
88STATISTIC(NumUnified , "Number of variables unified");
Daniel Berlin3a3f1632007-12-12 00:37:04 +000089STATISTIC(NumErased , "Number of redundant constraints erased");
Chris Lattnere995a2a2004-05-23 21:00:47 +000090
Chris Lattner3b27d682006-12-19 22:30:33 +000091namespace {
Daniel Berlinaad15882007-09-16 21:45:02 +000092 const unsigned SelfRep = (unsigned)-1;
93 const unsigned Unvisited = (unsigned)-1;
94 // Position of the function return node relative to the function node.
Daniel Berlind81ccc22007-09-24 19:45:49 +000095 const unsigned CallReturnPos = 1;
Daniel Berlinaad15882007-09-16 21:45:02 +000096 // Position of the function call node relative to the function node.
Daniel Berlind81ccc22007-09-24 19:45:49 +000097 const unsigned CallFirstArgPos = 2;
98
99 struct BitmapKeyInfo {
100 static inline SparseBitVector<> *getEmptyKey() {
101 return reinterpret_cast<SparseBitVector<> *>(-1);
102 }
103 static inline SparseBitVector<> *getTombstoneKey() {
104 return reinterpret_cast<SparseBitVector<> *>(-2);
105 }
106 static unsigned getHashValue(const SparseBitVector<> *bitmap) {
107 return bitmap->getHashValue();
108 }
109 static bool isEqual(const SparseBitVector<> *LHS,
110 const SparseBitVector<> *RHS) {
111 if (LHS == RHS)
112 return true;
113 else if (LHS == getEmptyKey() || RHS == getEmptyKey()
114 || LHS == getTombstoneKey() || RHS == getTombstoneKey())
115 return false;
116
117 return *LHS == *RHS;
118 }
119
120 static bool isPod() { return true; }
121 };
Daniel Berlinaad15882007-09-16 21:45:02 +0000122
Reid Spencerd7d83db2007-02-05 23:42:17 +0000123 class VISIBILITY_HIDDEN Andersens : public ModulePass, public AliasAnalysis,
124 private InstVisitor<Andersens> {
Hartmut Kaiser081fdf22007-10-25 23:49:14 +0000125 struct Node;
Daniel Berlinaad15882007-09-16 21:45:02 +0000126
127 /// Constraint - Objects of this structure are used to represent the various
128 /// constraints identified by the algorithm. The constraints are 'copy',
129 /// for statements like "A = B", 'load' for statements like "A = *B",
130 /// 'store' for statements like "*A = B", and AddressOf for statements like
131 /// A = alloca; The Offset is applied as *(A + K) = B for stores,
132 /// A = *(B + K) for loads, and A = B + K for copies. It is
Daniel Berlind81ccc22007-09-24 19:45:49 +0000133 /// illegal on addressof constraints (because it is statically
Daniel Berlinaad15882007-09-16 21:45:02 +0000134 /// resolvable to A = &C where C = B + K)
135
136 struct Constraint {
137 enum ConstraintType { Copy, Load, Store, AddressOf } Type;
138 unsigned Dest;
139 unsigned Src;
140 unsigned Offset;
141
142 Constraint(ConstraintType Ty, unsigned D, unsigned S, unsigned O = 0)
143 : Type(Ty), Dest(D), Src(S), Offset(O) {
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +0000144 assert((Offset == 0 || Ty != AddressOf) &&
Daniel Berlinaad15882007-09-16 21:45:02 +0000145 "Offset is illegal on addressof constraints");
146 }
Daniel Berlin336c6c02007-09-29 00:50:40 +0000147
Daniel Berlinc7a12ae2007-09-27 15:42:23 +0000148 bool operator==(const Constraint &RHS) const {
149 return RHS.Type == Type
150 && RHS.Dest == Dest
151 && RHS.Src == Src
152 && RHS.Offset == Offset;
153 }
Daniel Berlin336c6c02007-09-29 00:50:40 +0000154
155 bool operator!=(const Constraint &RHS) const {
156 return !(*this == RHS);
157 }
158
Daniel Berlinc7a12ae2007-09-27 15:42:23 +0000159 bool operator<(const Constraint &RHS) const {
160 if (RHS.Type != Type)
161 return RHS.Type < Type;
162 else if (RHS.Dest != Dest)
163 return RHS.Dest < Dest;
164 else if (RHS.Src != Src)
165 return RHS.Src < Src;
166 return RHS.Offset < Offset;
167 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000168 };
169
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000170 // Information DenseSet requires implemented in order to be able to do
171 // it's thing
172 struct PairKeyInfo {
173 static inline std::pair<unsigned, unsigned> getEmptyKey() {
Scott Michelacddf9d2008-03-18 16:55:06 +0000174 return std::make_pair(~0U, ~0U);
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000175 }
176 static inline std::pair<unsigned, unsigned> getTombstoneKey() {
Scott Michelacddf9d2008-03-18 16:55:06 +0000177 return std::make_pair(~0U - 1, ~0U - 1);
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000178 }
179 static unsigned getHashValue(const std::pair<unsigned, unsigned> &P) {
180 return P.first ^ P.second;
181 }
182 static unsigned isEqual(const std::pair<unsigned, unsigned> &LHS,
183 const std::pair<unsigned, unsigned> &RHS) {
184 return LHS == RHS;
185 }
186 };
187
Daniel Berlin336c6c02007-09-29 00:50:40 +0000188 struct ConstraintKeyInfo {
189 static inline Constraint getEmptyKey() {
Scott Michelacddf9d2008-03-18 16:55:06 +0000190 return Constraint(Constraint::Copy, ~0U, ~0U, ~0U);
Daniel Berlin336c6c02007-09-29 00:50:40 +0000191 }
192 static inline Constraint getTombstoneKey() {
Scott Michelacddf9d2008-03-18 16:55:06 +0000193 return Constraint(Constraint::Copy, ~0U - 1, ~0U - 1, ~0U - 1);
Daniel Berlin336c6c02007-09-29 00:50:40 +0000194 }
195 static unsigned getHashValue(const Constraint &C) {
196 return C.Src ^ C.Dest ^ C.Type ^ C.Offset;
197 }
198 static bool isEqual(const Constraint &LHS,
199 const Constraint &RHS) {
200 return LHS.Type == RHS.Type && LHS.Dest == RHS.Dest
201 && LHS.Src == RHS.Src && LHS.Offset == RHS.Offset;
202 }
203 };
204
Daniel Berlind81ccc22007-09-24 19:45:49 +0000205 // Node class - This class is used to represent a node in the constraint
Daniel Berline6f04792007-09-24 22:20:45 +0000206 // graph. Due to various optimizations, it is not always the case that
207 // there is a mapping from a Node to a Value. In particular, we add
208 // artificial Node's that represent the set of pointed-to variables shared
209 // for each location equivalent Node.
Daniel Berlinaad15882007-09-16 21:45:02 +0000210 struct Node {
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000211 private:
212 static unsigned Counter;
213
214 public:
Daniel Berlind81ccc22007-09-24 19:45:49 +0000215 Value *Val;
Daniel Berlinaad15882007-09-16 21:45:02 +0000216 SparseBitVector<> *Edges;
217 SparseBitVector<> *PointsTo;
218 SparseBitVector<> *OldPointsTo;
Daniel Berlinaad15882007-09-16 21:45:02 +0000219 std::list<Constraint> Constraints;
220
Daniel Berlind81ccc22007-09-24 19:45:49 +0000221 // Pointer and location equivalence labels
222 unsigned PointerEquivLabel;
223 unsigned LocationEquivLabel;
224 // Predecessor edges, both real and implicit
225 SparseBitVector<> *PredEdges;
226 SparseBitVector<> *ImplicitPredEdges;
227 // Set of nodes that point to us, only use for location equivalence.
228 SparseBitVector<> *PointedToBy;
229 // Number of incoming edges, used during variable substitution to early
230 // free the points-to sets
231 unsigned NumInEdges;
Daniel Berline6f04792007-09-24 22:20:45 +0000232 // True if our points-to set is in the Set2PEClass map
Daniel Berlind81ccc22007-09-24 19:45:49 +0000233 bool StoredInHash;
Daniel Berline6f04792007-09-24 22:20:45 +0000234 // True if our node has no indirect constraints (complex or otherwise)
Daniel Berlind81ccc22007-09-24 19:45:49 +0000235 bool Direct;
236 // True if the node is address taken, *or* it is part of a group of nodes
237 // that must be kept together. This is set to true for functions and
238 // their arg nodes, which must be kept at the same position relative to
239 // their base function node.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000240 bool AddressTaken;
Daniel Berlinaad15882007-09-16 21:45:02 +0000241
Daniel Berlind81ccc22007-09-24 19:45:49 +0000242 // Nodes in cycles (or in equivalence classes) are united together using a
243 // standard union-find representation with path compression. NodeRep
244 // gives the index into GraphNodes for the representative Node.
245 unsigned NodeRep;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000246
247 // Modification timestamp. Assigned from Counter.
248 // Used for work list prioritization.
249 unsigned Timestamp;
Daniel Berlind81ccc22007-09-24 19:45:49 +0000250
Dan Gohmanded2b0d2007-12-14 15:41:34 +0000251 explicit Node(bool direct = true) :
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000252 Val(0), Edges(0), PointsTo(0), OldPointsTo(0),
Daniel Berlind81ccc22007-09-24 19:45:49 +0000253 PointerEquivLabel(0), LocationEquivLabel(0), PredEdges(0),
254 ImplicitPredEdges(0), PointedToBy(0), NumInEdges(0),
255 StoredInHash(false), Direct(direct), AddressTaken(false),
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000256 NodeRep(SelfRep), Timestamp(0) { }
Daniel Berlinaad15882007-09-16 21:45:02 +0000257
Chris Lattnere995a2a2004-05-23 21:00:47 +0000258 Node *setValue(Value *V) {
259 assert(Val == 0 && "Value already set for this node!");
260 Val = V;
261 return this;
262 }
263
264 /// getValue - Return the LLVM value corresponding to this node.
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000265 ///
Chris Lattnere995a2a2004-05-23 21:00:47 +0000266 Value *getValue() const { return Val; }
267
Chris Lattnere995a2a2004-05-23 21:00:47 +0000268 /// addPointerTo - Add a pointer to the list of pointees of this node,
269 /// returning true if this caused a new pointer to be added, or false if
270 /// we already knew about the points-to relation.
Daniel Berlinaad15882007-09-16 21:45:02 +0000271 bool addPointerTo(unsigned Node) {
272 return PointsTo->test_and_set(Node);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000273 }
274
275 /// intersects - Return true if the points-to set of this node intersects
276 /// with the points-to set of the specified node.
277 bool intersects(Node *N) const;
278
279 /// intersectsIgnoring - Return true if the points-to set of this node
280 /// intersects with the points-to set of the specified node on any nodes
281 /// except for the specified node to ignore.
Daniel Berlinaad15882007-09-16 21:45:02 +0000282 bool intersectsIgnoring(Node *N, unsigned) const;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000283
284 // Timestamp a node (used for work list prioritization)
285 void Stamp() {
286 Timestamp = Counter++;
287 }
288
289 bool isRep() {
290 return( (int) NodeRep < 0 );
291 }
292 };
293
294 struct WorkListElement {
295 Node* node;
296 unsigned Timestamp;
297 WorkListElement(Node* n, unsigned t) : node(n), Timestamp(t) {}
298
299 // Note that we reverse the sense of the comparison because we
300 // actually want to give low timestamps the priority over high,
301 // whereas priority is typically interpreted as a greater value is
302 // given high priority.
303 bool operator<(const WorkListElement& that) const {
304 return( this->Timestamp > that.Timestamp );
305 }
306 };
307
308 // Priority-queue based work list specialized for Nodes.
309 class WorkList {
310 std::priority_queue<WorkListElement> Q;
311
312 public:
313 void insert(Node* n) {
314 Q.push( WorkListElement(n, n->Timestamp) );
315 }
316
317 // We automatically discard non-representative nodes and nodes
318 // that were in the work list twice (we keep a copy of the
319 // timestamp in the work list so we can detect this situation by
320 // comparing against the node's current timestamp).
321 Node* pop() {
322 while( !Q.empty() ) {
323 WorkListElement x = Q.top(); Q.pop();
324 Node* INode = x.node;
325
326 if( INode->isRep() &&
327 INode->Timestamp == x.Timestamp ) {
328 return(x.node);
329 }
330 }
331 return(0);
332 }
333
334 bool empty() {
335 return Q.empty();
336 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000337 };
338
339 /// GraphNodes - This vector is populated as part of the object
340 /// identification stage of the analysis, which populates this vector with a
341 /// node for each memory object and fills in the ValueNodes map.
342 std::vector<Node> GraphNodes;
343
344 /// ValueNodes - This map indicates the Node that a particular Value* is
345 /// represented by. This contains entries for all pointers.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000346 DenseMap<Value*, unsigned> ValueNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000347
348 /// ObjectNodes - This map contains entries for each memory object in the
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000349 /// program: globals, alloca's and mallocs.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000350 DenseMap<Value*, unsigned> ObjectNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000351
352 /// ReturnNodes - This map contains an entry for each function in the
353 /// program that returns a value.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000354 DenseMap<Function*, unsigned> ReturnNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000355
356 /// VarargNodes - This map contains the entry used to represent all pointers
357 /// passed through the varargs portion of a function call for a particular
358 /// function. An entry is not present in this map for functions that do not
359 /// take variable arguments.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000360 DenseMap<Function*, unsigned> VarargNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000361
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000362
Chris Lattnere995a2a2004-05-23 21:00:47 +0000363 /// Constraints - This vector contains a list of all of the constraints
364 /// identified by the program.
365 std::vector<Constraint> Constraints;
366
Daniel Berlind81ccc22007-09-24 19:45:49 +0000367 // Map from graph node to maximum K value that is allowed (for functions,
Daniel Berlinaad15882007-09-16 21:45:02 +0000368 // this is equivalent to the number of arguments + CallFirstArgPos)
369 std::map<unsigned, unsigned> MaxK;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000370
371 /// This enum defines the GraphNodes indices that correspond to important
372 /// fixed sets.
373 enum {
374 UniversalSet = 0,
375 NullPtr = 1,
Daniel Berlind81ccc22007-09-24 19:45:49 +0000376 NullObject = 2,
377 NumberSpecialNodes
Chris Lattnere995a2a2004-05-23 21:00:47 +0000378 };
Daniel Berlind81ccc22007-09-24 19:45:49 +0000379 // Stack for Tarjan's
Daniel Berlinaad15882007-09-16 21:45:02 +0000380 std::stack<unsigned> SCCStack;
Daniel Berlinaad15882007-09-16 21:45:02 +0000381 // Map from Graph Node to DFS number
382 std::vector<unsigned> Node2DFS;
383 // Map from Graph Node to Deleted from graph.
384 std::vector<bool> Node2Deleted;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000385 // Same as Node Maps, but implemented as std::map because it is faster to
386 // clear
387 std::map<unsigned, unsigned> Tarjan2DFS;
388 std::map<unsigned, bool> Tarjan2Deleted;
389 // Current DFS number
Daniel Berlinaad15882007-09-16 21:45:02 +0000390 unsigned DFSNumber;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000391
392 // Work lists.
393 WorkList w1, w2;
394 WorkList *CurrWL, *NextWL; // "current" and "next" work lists
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000395
Daniel Berlind81ccc22007-09-24 19:45:49 +0000396 // Offline variable substitution related things
397
398 // Temporary rep storage, used because we can't collapse SCC's in the
399 // predecessor graph by uniting the variables permanently, we can only do so
400 // for the successor graph.
401 std::vector<unsigned> VSSCCRep;
402 // Mapping from node to whether we have visited it during SCC finding yet.
403 std::vector<bool> Node2Visited;
404 // During variable substitution, we create unknowns to represent the unknown
405 // value that is a dereference of a variable. These nodes are known as
406 // "ref" nodes (since they represent the value of dereferences).
407 unsigned FirstRefNode;
408 // During HVN, we create represent address taken nodes as if they were
409 // unknown (since HVN, unlike HU, does not evaluate unions).
410 unsigned FirstAdrNode;
411 // Current pointer equivalence class number
412 unsigned PEClass;
413 // Mapping from points-to sets to equivalence classes
414 typedef DenseMap<SparseBitVector<> *, unsigned, BitmapKeyInfo> BitVectorMap;
415 BitVectorMap Set2PEClass;
416 // Mapping from pointer equivalences to the representative node. -1 if we
417 // have no representative node for this pointer equivalence class yet.
418 std::vector<int> PEClass2Node;
419 // Mapping from pointer equivalences to representative node. This includes
420 // pointer equivalent but not location equivalent variables. -1 if we have
421 // no representative node for this pointer equivalence class yet.
422 std::vector<int> PENLEClass2Node;
Daniel Berlinc864edb2008-03-05 19:31:47 +0000423 // Union/Find for HCD
424 std::vector<unsigned> HCDSCCRep;
425 // HCD's offline-detected cycles; "Statically DeTected"
426 // -1 if not part of such a cycle, otherwise a representative node.
427 std::vector<int> SDT;
428 // Whether to use SDT (UniteNodes can use it during solving, but not before)
429 bool SDTActive;
Daniel Berlind81ccc22007-09-24 19:45:49 +0000430
Chris Lattnere995a2a2004-05-23 21:00:47 +0000431 public:
Daniel Berlinaad15882007-09-16 21:45:02 +0000432 static char ID;
Devang Patelc7fe32e2008-03-19 00:48:41 +0000433 Andersens() : ModulePass((intptr_t)&ID, true) {}
Devang Patel1cee94f2008-03-18 00:39:19 +0000434
Chris Lattnerb12914b2004-09-20 04:48:05 +0000435 bool runOnModule(Module &M) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000436 InitializeAliasAnalysis(this);
437 IdentifyObjects(M);
438 CollectConstraints(M);
Daniel Berlind81ccc22007-09-24 19:45:49 +0000439#undef DEBUG_TYPE
440#define DEBUG_TYPE "anders-aa-constraints"
Chris Lattnere995a2a2004-05-23 21:00:47 +0000441 DEBUG(PrintConstraints());
Daniel Berlind81ccc22007-09-24 19:45:49 +0000442#undef DEBUG_TYPE
443#define DEBUG_TYPE "anders-aa"
Chris Lattnere995a2a2004-05-23 21:00:47 +0000444 SolveConstraints();
445 DEBUG(PrintPointsToGraph());
446
447 // Free the constraints list, as we don't need it to respond to alias
448 // requests.
449 ObjectNodes.clear();
450 ReturnNodes.clear();
451 VarargNodes.clear();
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000452 std::vector<Constraint>().swap(Constraints);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000453 return false;
454 }
455
456 void releaseMemory() {
457 // FIXME: Until we have transitively required passes working correctly,
458 // this cannot be enabled! Otherwise, using -count-aa with the pass
459 // causes memory to be freed too early. :(
460#if 0
461 // The memory objects and ValueNodes data structures at the only ones that
462 // are still live after construction.
463 std::vector<Node>().swap(GraphNodes);
464 ValueNodes.clear();
465#endif
466 }
467
468 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
469 AliasAnalysis::getAnalysisUsage(AU);
470 AU.setPreservesAll(); // Does not transform code
471 }
472
473 //------------------------------------------------
474 // Implement the AliasAnalysis API
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000475 //
Chris Lattnere995a2a2004-05-23 21:00:47 +0000476 AliasResult alias(const Value *V1, unsigned V1Size,
477 const Value *V2, unsigned V2Size);
Reid Spencer3a9ec242006-08-28 01:02:49 +0000478 virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
479 virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000480 void getMustAliases(Value *P, std::vector<Value*> &RetVals);
481 bool pointsToConstantMemory(const Value *P);
482
483 virtual void deleteValue(Value *V) {
484 ValueNodes.erase(V);
485 getAnalysis<AliasAnalysis>().deleteValue(V);
486 }
487
488 virtual void copyValue(Value *From, Value *To) {
489 ValueNodes[To] = ValueNodes[From];
490 getAnalysis<AliasAnalysis>().copyValue(From, To);
491 }
492
493 private:
494 /// getNode - Return the node corresponding to the specified pointer scalar.
495 ///
Daniel Berlinaad15882007-09-16 21:45:02 +0000496 unsigned getNode(Value *V) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000497 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattnerdf9b7bc2004-08-16 05:38:02 +0000498 if (!isa<GlobalValue>(C))
499 return getNodeForConstantPointer(C);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000500
Daniel Berlind81ccc22007-09-24 19:45:49 +0000501 DenseMap<Value*, unsigned>::iterator I = ValueNodes.find(V);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000502 if (I == ValueNodes.end()) {
Jim Laskey16d42c62006-07-11 18:25:13 +0000503#ifndef NDEBUG
504 V->dump();
505#endif
Jim Laskeye37fe9b2006-07-11 17:58:07 +0000506 assert(0 && "Value does not have a node in the points-to graph!");
Chris Lattnere995a2a2004-05-23 21:00:47 +0000507 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000508 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000509 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000510
Chris Lattnere995a2a2004-05-23 21:00:47 +0000511 /// getObject - Return the node corresponding to the memory object for the
512 /// specified global or allocation instruction.
Daniel Berlinaad15882007-09-16 21:45:02 +0000513 unsigned getObject(Value *V) {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000514 DenseMap<Value*, unsigned>::iterator I = ObjectNodes.find(V);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000515 assert(I != ObjectNodes.end() &&
516 "Value does not have an object in the points-to graph!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000517 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000518 }
519
520 /// getReturnNode - Return the node representing the return value for the
521 /// specified function.
Daniel Berlinaad15882007-09-16 21:45:02 +0000522 unsigned getReturnNode(Function *F) {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000523 DenseMap<Function*, unsigned>::iterator I = ReturnNodes.find(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000524 assert(I != ReturnNodes.end() && "Function does not return a value!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000525 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000526 }
527
528 /// getVarargNode - Return the node representing the variable arguments
529 /// formal for the specified function.
Daniel Berlinaad15882007-09-16 21:45:02 +0000530 unsigned getVarargNode(Function *F) {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000531 DenseMap<Function*, unsigned>::iterator I = VarargNodes.find(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000532 assert(I != VarargNodes.end() && "Function does not take var args!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000533 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000534 }
535
536 /// getNodeValue - Get the node for the specified LLVM value and set the
537 /// value for it to be the specified value.
Daniel Berlinaad15882007-09-16 21:45:02 +0000538 unsigned getNodeValue(Value &V) {
539 unsigned Index = getNode(&V);
540 GraphNodes[Index].setValue(&V);
541 return Index;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000542 }
543
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000544 unsigned UniteNodes(unsigned First, unsigned Second,
545 bool UnionByRank = true);
Daniel Berlinaad15882007-09-16 21:45:02 +0000546 unsigned FindNode(unsigned Node);
547
Chris Lattnere995a2a2004-05-23 21:00:47 +0000548 void IdentifyObjects(Module &M);
549 void CollectConstraints(Module &M);
Daniel Berlinaad15882007-09-16 21:45:02 +0000550 bool AnalyzeUsesOfFunction(Value *);
551 void CreateConstraintGraph();
Daniel Berlind81ccc22007-09-24 19:45:49 +0000552 void OptimizeConstraints();
553 unsigned FindEquivalentNode(unsigned, unsigned);
554 void ClumpAddressTaken();
555 void RewriteConstraints();
556 void HU();
557 void HVN();
Daniel Berlinc864edb2008-03-05 19:31:47 +0000558 void HCD();
559 void Search(unsigned Node);
Daniel Berlind81ccc22007-09-24 19:45:49 +0000560 void UnitePointerEquivalences();
Chris Lattnere995a2a2004-05-23 21:00:47 +0000561 void SolveConstraints();
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000562 bool QueryNode(unsigned Node);
Daniel Berlind81ccc22007-09-24 19:45:49 +0000563 void Condense(unsigned Node);
564 void HUValNum(unsigned Node);
565 void HVNValNum(unsigned Node);
Daniel Berlinaad15882007-09-16 21:45:02 +0000566 unsigned getNodeForConstantPointer(Constant *C);
567 unsigned getNodeForConstantPointerTarget(Constant *C);
568 void AddGlobalInitializerConstraints(unsigned, Constant *C);
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000569
Chris Lattnere995a2a2004-05-23 21:00:47 +0000570 void AddConstraintsForNonInternalLinkage(Function *F);
571 void AddConstraintsForCall(CallSite CS, Function *F);
Chris Lattner8a446432005-03-29 06:09:07 +0000572 bool AddConstraintsForExternalCall(CallSite CS, Function *F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000573
574
575 void PrintNode(Node *N);
576 void PrintConstraints();
Daniel Berlind81ccc22007-09-24 19:45:49 +0000577 void PrintConstraint(const Constraint &);
578 void PrintLabels();
Chris Lattnere995a2a2004-05-23 21:00:47 +0000579 void PrintPointsToGraph();
580
581 //===------------------------------------------------------------------===//
582 // Instruction visitation methods for adding constraints
583 //
584 friend class InstVisitor<Andersens>;
585 void visitReturnInst(ReturnInst &RI);
586 void visitInvokeInst(InvokeInst &II) { visitCallSite(CallSite(&II)); }
587 void visitCallInst(CallInst &CI) { visitCallSite(CallSite(&CI)); }
588 void visitCallSite(CallSite CS);
589 void visitAllocationInst(AllocationInst &AI);
590 void visitLoadInst(LoadInst &LI);
591 void visitStoreInst(StoreInst &SI);
592 void visitGetElementPtrInst(GetElementPtrInst &GEP);
593 void visitPHINode(PHINode &PN);
594 void visitCastInst(CastInst &CI);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000595 void visitICmpInst(ICmpInst &ICI) {} // NOOP!
596 void visitFCmpInst(FCmpInst &ICI) {} // NOOP!
Chris Lattnere995a2a2004-05-23 21:00:47 +0000597 void visitSelectInst(SelectInst &SI);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000598 void visitVAArg(VAArgInst &I);
599 void visitInstruction(Instruction &I);
Daniel Berlinaad15882007-09-16 21:45:02 +0000600
Chris Lattnere995a2a2004-05-23 21:00:47 +0000601 };
602
Devang Patel19974732007-05-03 01:11:54 +0000603 char Andersens::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +0000604 RegisterPass<Andersens> X("anders-aa",
605 "Andersen's Interprocedural Alias Analysis");
Chris Lattnera5370172006-08-28 00:42:29 +0000606 RegisterAnalysisGroup<AliasAnalysis> Y(X);
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000607
608 // Initialize Timestamp Counter (static).
609 unsigned Andersens::Node::Counter = 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000610}
611
Jeff Cohen534927d2005-01-08 22:01:16 +0000612ModulePass *llvm::createAndersensPass() { return new Andersens(); }
613
Chris Lattnere995a2a2004-05-23 21:00:47 +0000614//===----------------------------------------------------------------------===//
615// AliasAnalysis Interface Implementation
616//===----------------------------------------------------------------------===//
617
618AliasAnalysis::AliasResult Andersens::alias(const Value *V1, unsigned V1Size,
619 const Value *V2, unsigned V2Size) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000620 Node *N1 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V1)))];
621 Node *N2 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V2)))];
Chris Lattnere995a2a2004-05-23 21:00:47 +0000622
623 // Check to see if the two pointers are known to not alias. They don't alias
624 // if their points-to sets do not intersect.
Daniel Berlinaad15882007-09-16 21:45:02 +0000625 if (!N1->intersectsIgnoring(N2, NullObject))
Chris Lattnere995a2a2004-05-23 21:00:47 +0000626 return NoAlias;
627
628 return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
629}
630
Chris Lattnerf392c642005-03-28 06:21:17 +0000631AliasAnalysis::ModRefResult
632Andersens::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
633 // The only thing useful that we can contribute for mod/ref information is
634 // when calling external function calls: if we know that memory never escapes
635 // from the program, it cannot be modified by an external call.
636 //
637 // NOTE: This is not really safe, at least not when the entire program is not
638 // available. The deal is that the external function could call back into the
639 // program and modify stuff. We ignore this technical niggle for now. This
640 // is, after all, a "research quality" implementation of Andersen's analysis.
641 if (Function *F = CS.getCalledFunction())
Reid Spencer5cbf9852007-01-30 20:08:39 +0000642 if (F->isDeclaration()) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000643 Node *N1 = &GraphNodes[FindNode(getNode(P))];
Chris Lattnerf392c642005-03-28 06:21:17 +0000644
Daniel Berlinaad15882007-09-16 21:45:02 +0000645 if (N1->PointsTo->empty())
646 return NoModRef;
Daniel Berlind3bf1ae2008-03-18 22:22:53 +0000647#if FULL_UNIVERSAL
648 if (!UniversalSet->PointsTo->test(FindNode(getNode(P))))
649 return NoModRef; // Universal set does not contain P
650#else
Daniel Berlinaad15882007-09-16 21:45:02 +0000651 if (!N1->PointsTo->test(UniversalSet))
Chris Lattnerf392c642005-03-28 06:21:17 +0000652 return NoModRef; // P doesn't point to the universal set.
Daniel Berlind3bf1ae2008-03-18 22:22:53 +0000653#endif
Chris Lattnerf392c642005-03-28 06:21:17 +0000654 }
655
656 return AliasAnalysis::getModRefInfo(CS, P, Size);
657}
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000658
Reid Spencer3a9ec242006-08-28 01:02:49 +0000659AliasAnalysis::ModRefResult
660Andersens::getModRefInfo(CallSite CS1, CallSite CS2) {
661 return AliasAnalysis::getModRefInfo(CS1,CS2);
662}
663
Chris Lattnere995a2a2004-05-23 21:00:47 +0000664/// getMustAlias - We can provide must alias information if we know that a
665/// pointer can only point to a specific function or the null pointer.
666/// Unfortunately we cannot determine must-alias information for global
667/// variables or any other memory memory objects because we do not track whether
668/// a pointer points to the beginning of an object or a field of it.
669void Andersens::getMustAliases(Value *P, std::vector<Value*> &RetVals) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000670 Node *N = &GraphNodes[FindNode(getNode(P))];
671 if (N->PointsTo->count() == 1) {
672 Node *Pointee = &GraphNodes[N->PointsTo->find_first()];
673 // If a function is the only object in the points-to set, then it must be
674 // the destination. Note that we can't handle global variables here,
675 // because we don't know if the pointer is actually pointing to a field of
676 // the global or to the beginning of it.
677 if (Value *V = Pointee->getValue()) {
678 if (Function *F = dyn_cast<Function>(V))
679 RetVals.push_back(F);
680 } else {
681 // If the object in the points-to set is the null object, then the null
682 // pointer is a must alias.
683 if (Pointee == &GraphNodes[NullObject])
684 RetVals.push_back(Constant::getNullValue(P->getType()));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000685 }
686 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000687 AliasAnalysis::getMustAliases(P, RetVals);
688}
689
690/// pointsToConstantMemory - If we can determine that this pointer only points
691/// to constant memory, return true. In practice, this means that if the
692/// pointer can only point to constant globals, functions, or the null pointer,
693/// return true.
694///
695bool Andersens::pointsToConstantMemory(const Value *P) {
Dan Gohman6a551e72008-02-21 17:33:24 +0000696 Node *N = &GraphNodes[FindNode(getNode(const_cast<Value*>(P)))];
Daniel Berlinaad15882007-09-16 21:45:02 +0000697 unsigned i;
698
699 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
700 bi != N->PointsTo->end();
701 ++bi) {
702 i = *bi;
703 Node *Pointee = &GraphNodes[i];
704 if (Value *V = Pointee->getValue()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000705 if (!isa<GlobalValue>(V) || (isa<GlobalVariable>(V) &&
706 !cast<GlobalVariable>(V)->isConstant()))
707 return AliasAnalysis::pointsToConstantMemory(P);
708 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +0000709 if (i != NullObject)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000710 return AliasAnalysis::pointsToConstantMemory(P);
711 }
712 }
713
714 return true;
715}
716
717//===----------------------------------------------------------------------===//
718// Object Identification Phase
719//===----------------------------------------------------------------------===//
720
721/// IdentifyObjects - This stage scans the program, adding an entry to the
722/// GraphNodes list for each memory object in the program (global stack or
723/// heap), and populates the ValueNodes and ObjectNodes maps for these objects.
724///
725void Andersens::IdentifyObjects(Module &M) {
726 unsigned NumObjects = 0;
727
728 // Object #0 is always the universal set: the object that we don't know
729 // anything about.
730 assert(NumObjects == UniversalSet && "Something changed!");
731 ++NumObjects;
732
733 // Object #1 always represents the null pointer.
734 assert(NumObjects == NullPtr && "Something changed!");
735 ++NumObjects;
736
737 // Object #2 always represents the null object (the object pointed to by null)
738 assert(NumObjects == NullObject && "Something changed!");
739 ++NumObjects;
740
741 // Add all the globals first.
Chris Lattner493f6362005-03-27 22:03:46 +0000742 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
743 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000744 ObjectNodes[I] = NumObjects++;
745 ValueNodes[I] = NumObjects++;
746 }
747
748 // Add nodes for all of the functions and the instructions inside of them.
749 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
750 // The function itself is a memory object.
Daniel Berlinaad15882007-09-16 21:45:02 +0000751 unsigned First = NumObjects;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000752 ValueNodes[F] = NumObjects++;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000753 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
754 ReturnNodes[F] = NumObjects++;
755 if (F->getFunctionType()->isVarArg())
756 VarargNodes[F] = NumObjects++;
757
Daniel Berlinaad15882007-09-16 21:45:02 +0000758
Chris Lattnere995a2a2004-05-23 21:00:47 +0000759 // Add nodes for all of the incoming pointer arguments.
Chris Lattner493f6362005-03-27 22:03:46 +0000760 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
761 I != E; ++I)
Daniel Berlind81ccc22007-09-24 19:45:49 +0000762 {
763 if (isa<PointerType>(I->getType()))
764 ValueNodes[I] = NumObjects++;
765 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000766 MaxK[First] = NumObjects - First;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000767
768 // Scan the function body, creating a memory object for each heap/stack
769 // allocation in the body of the function and a node to represent all
770 // pointer values defined by instructions and used as operands.
771 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
772 // If this is an heap or stack allocation, create a node for the memory
773 // object.
774 if (isa<PointerType>(II->getType())) {
775 ValueNodes[&*II] = NumObjects++;
776 if (AllocationInst *AI = dyn_cast<AllocationInst>(&*II))
777 ObjectNodes[AI] = NumObjects++;
778 }
Nick Lewycky4ac0e8d2007-11-22 03:07:37 +0000779
780 // Calls to inline asm need to be added as well because the callee isn't
781 // referenced anywhere else.
782 if (CallInst *CI = dyn_cast<CallInst>(&*II)) {
783 Value *Callee = CI->getCalledValue();
784 if (isa<InlineAsm>(Callee))
785 ValueNodes[Callee] = NumObjects++;
786 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000787 }
788 }
789
790 // Now that we know how many objects to create, make them all now!
791 GraphNodes.resize(NumObjects);
792 NumNodes += NumObjects;
793}
794
795//===----------------------------------------------------------------------===//
796// Constraint Identification Phase
797//===----------------------------------------------------------------------===//
798
799/// getNodeForConstantPointer - Return the node corresponding to the constant
800/// pointer itself.
Daniel Berlinaad15882007-09-16 21:45:02 +0000801unsigned Andersens::getNodeForConstantPointer(Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000802 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
803
Chris Lattner267a1b02005-03-27 18:58:23 +0000804 if (isa<ConstantPointerNull>(C) || isa<UndefValue>(C))
Daniel Berlinaad15882007-09-16 21:45:02 +0000805 return NullPtr;
Reid Spencere8404342004-07-18 00:18:30 +0000806 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
807 return getNode(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000808 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
809 switch (CE->getOpcode()) {
810 case Instruction::GetElementPtr:
811 return getNodeForConstantPointer(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000812 case Instruction::IntToPtr:
Daniel Berlinaad15882007-09-16 21:45:02 +0000813 return UniversalSet;
Reid Spencer3da59db2006-11-27 01:05:10 +0000814 case Instruction::BitCast:
815 return getNodeForConstantPointer(CE->getOperand(0));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000816 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000817 cerr << "Constant Expr not yet handled: " << *CE << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +0000818 assert(0);
819 }
820 } else {
821 assert(0 && "Unknown constant pointer!");
822 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000823 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000824}
825
826/// getNodeForConstantPointerTarget - Return the node POINTED TO by the
827/// specified constant pointer.
Daniel Berlinaad15882007-09-16 21:45:02 +0000828unsigned Andersens::getNodeForConstantPointerTarget(Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000829 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
830
831 if (isa<ConstantPointerNull>(C))
Daniel Berlinaad15882007-09-16 21:45:02 +0000832 return NullObject;
Reid Spencere8404342004-07-18 00:18:30 +0000833 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
834 return getObject(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000835 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
836 switch (CE->getOpcode()) {
837 case Instruction::GetElementPtr:
838 return getNodeForConstantPointerTarget(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000839 case Instruction::IntToPtr:
Daniel Berlinaad15882007-09-16 21:45:02 +0000840 return UniversalSet;
Reid Spencer3da59db2006-11-27 01:05:10 +0000841 case Instruction::BitCast:
842 return getNodeForConstantPointerTarget(CE->getOperand(0));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000843 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000844 cerr << "Constant Expr not yet handled: " << *CE << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +0000845 assert(0);
846 }
847 } else {
848 assert(0 && "Unknown constant pointer!");
849 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000850 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000851}
852
853/// AddGlobalInitializerConstraints - Add inclusion constraints for the memory
854/// object N, which contains values indicated by C.
Daniel Berlinaad15882007-09-16 21:45:02 +0000855void Andersens::AddGlobalInitializerConstraints(unsigned NodeIndex,
856 Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000857 if (C->getType()->isFirstClassType()) {
858 if (isa<PointerType>(C->getType()))
Daniel Berlinaad15882007-09-16 21:45:02 +0000859 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
860 getNodeForConstantPointer(C)));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000861 } else if (C->isNullValue()) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000862 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
863 NullObject));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000864 return;
Chris Lattner8a446432005-03-29 06:09:07 +0000865 } else if (!isa<UndefValue>(C)) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000866 // If this is an array or struct, include constraints for each element.
867 assert(isa<ConstantArray>(C) || isa<ConstantStruct>(C));
868 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
Daniel Berlinaad15882007-09-16 21:45:02 +0000869 AddGlobalInitializerConstraints(NodeIndex,
870 cast<Constant>(C->getOperand(i)));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000871 }
872}
873
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000874/// AddConstraintsForNonInternalLinkage - If this function does not have
875/// internal linkage, realize that we can't trust anything passed into or
876/// returned by this function.
Chris Lattnere995a2a2004-05-23 21:00:47 +0000877void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
Chris Lattnere4d5c442005-03-15 04:54:21 +0000878 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000879 if (isa<PointerType>(I->getType()))
880 // If this is an argument of an externally accessible function, the
881 // incoming pointer might point to anything.
882 Constraints.push_back(Constraint(Constraint::Copy, getNode(I),
Daniel Berlinaad15882007-09-16 21:45:02 +0000883 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000884}
885
Chris Lattner8a446432005-03-29 06:09:07 +0000886/// AddConstraintsForCall - If this is a call to a "known" function, add the
887/// constraints and return true. If this is a call to an unknown function,
888/// return false.
889bool Andersens::AddConstraintsForExternalCall(CallSite CS, Function *F) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000890 assert(F->isDeclaration() && "Not an external function!");
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000891
892 // These functions don't induce any points-to constraints.
Chris Lattner175b9632005-03-29 20:36:05 +0000893 if (F->getName() == "atoi" || F->getName() == "atof" ||
894 F->getName() == "atol" || F->getName() == "atoll" ||
895 F->getName() == "remove" || F->getName() == "unlink" ||
896 F->getName() == "rename" || F->getName() == "memcmp" ||
Chris Lattner01ac91e2006-03-03 01:21:36 +0000897 F->getName() == "llvm.memset.i32" ||
898 F->getName() == "llvm.memset.i64" ||
Chris Lattner175b9632005-03-29 20:36:05 +0000899 F->getName() == "strcmp" || F->getName() == "strncmp" ||
900 F->getName() == "execl" || F->getName() == "execlp" ||
901 F->getName() == "execle" || F->getName() == "execv" ||
902 F->getName() == "execvp" || F->getName() == "chmod" ||
903 F->getName() == "puts" || F->getName() == "write" ||
904 F->getName() == "open" || F->getName() == "create" ||
905 F->getName() == "truncate" || F->getName() == "chdir" ||
906 F->getName() == "mkdir" || F->getName() == "rmdir" ||
907 F->getName() == "read" || F->getName() == "pipe" ||
908 F->getName() == "wait" || F->getName() == "time" ||
909 F->getName() == "stat" || F->getName() == "fstat" ||
910 F->getName() == "lstat" || F->getName() == "strtod" ||
911 F->getName() == "strtof" || F->getName() == "strtold" ||
912 F->getName() == "fopen" || F->getName() == "fdopen" ||
913 F->getName() == "freopen" ||
914 F->getName() == "fflush" || F->getName() == "feof" ||
915 F->getName() == "fileno" || F->getName() == "clearerr" ||
916 F->getName() == "rewind" || F->getName() == "ftell" ||
917 F->getName() == "ferror" || F->getName() == "fgetc" ||
918 F->getName() == "fgetc" || F->getName() == "_IO_getc" ||
919 F->getName() == "fwrite" || F->getName() == "fread" ||
920 F->getName() == "fgets" || F->getName() == "ungetc" ||
921 F->getName() == "fputc" ||
922 F->getName() == "fputs" || F->getName() == "putc" ||
923 F->getName() == "ftell" || F->getName() == "rewind" ||
924 F->getName() == "_IO_putc" || F->getName() == "fseek" ||
925 F->getName() == "fgetpos" || F->getName() == "fsetpos" ||
926 F->getName() == "printf" || F->getName() == "fprintf" ||
927 F->getName() == "sprintf" || F->getName() == "vprintf" ||
928 F->getName() == "vfprintf" || F->getName() == "vsprintf" ||
929 F->getName() == "scanf" || F->getName() == "fscanf" ||
930 F->getName() == "sscanf" || F->getName() == "__assert_fail" ||
931 F->getName() == "modf")
Chris Lattner8a446432005-03-29 06:09:07 +0000932 return true;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000933
Chris Lattner175b9632005-03-29 20:36:05 +0000934
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000935 // These functions do induce points-to edges.
Daniel Berlinaad15882007-09-16 21:45:02 +0000936 if (F->getName() == "llvm.memcpy.i32" || F->getName() == "llvm.memcpy.i64" ||
Chris Lattner01ac91e2006-03-03 01:21:36 +0000937 F->getName() == "llvm.memmove.i32" ||F->getName() == "llvm.memmove.i64" ||
Chris Lattner4de57fd2005-03-29 06:52:20 +0000938 F->getName() == "memmove") {
Daniel Berlinaad15882007-09-16 21:45:02 +0000939
940 // *Dest = *Src, which requires an artificial graph node to represent the
941 // constraint. It is broken up into *Dest = temp, temp = *Src
942 unsigned FirstArg = getNode(CS.getArgument(0));
943 unsigned SecondArg = getNode(CS.getArgument(1));
944 unsigned TempArg = GraphNodes.size();
945 GraphNodes.push_back(Node());
946 Constraints.push_back(Constraint(Constraint::Store,
947 FirstArg, TempArg));
948 Constraints.push_back(Constraint(Constraint::Load,
949 TempArg, SecondArg));
Chris Lattner8a446432005-03-29 06:09:07 +0000950 return true;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000951 }
952
Chris Lattner77b50562005-03-29 20:04:24 +0000953 // Result = Arg0
954 if (F->getName() == "realloc" || F->getName() == "strchr" ||
955 F->getName() == "strrchr" || F->getName() == "strstr" ||
956 F->getName() == "strtok") {
Chris Lattner8a446432005-03-29 06:09:07 +0000957 Constraints.push_back(Constraint(Constraint::Copy,
958 getNode(CS.getInstruction()),
959 getNode(CS.getArgument(0))));
960 return true;
961 }
962
963 return false;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000964}
965
966
Chris Lattnere995a2a2004-05-23 21:00:47 +0000967
Daniel Berlinaad15882007-09-16 21:45:02 +0000968/// AnalyzeUsesOfFunction - Look at all of the users of the specified function.
969/// If this is used by anything complex (i.e., the address escapes), return
970/// true.
971bool Andersens::AnalyzeUsesOfFunction(Value *V) {
972
973 if (!isa<PointerType>(V->getType())) return true;
974
975 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
976 if (dyn_cast<LoadInst>(*UI)) {
977 return false;
978 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
979 if (V == SI->getOperand(1)) {
980 return false;
981 } else if (SI->getOperand(1)) {
982 return true; // Storing the pointer
983 }
984 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
985 if (AnalyzeUsesOfFunction(GEP)) return true;
986 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
987 // Make sure that this is just the function being called, not that it is
988 // passing into the function.
989 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
990 if (CI->getOperand(i) == V) return true;
991 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
992 // Make sure that this is just the function being called, not that it is
993 // passing into the function.
994 for (unsigned i = 3, e = II->getNumOperands(); i != e; ++i)
995 if (II->getOperand(i) == V) return true;
996 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
997 if (CE->getOpcode() == Instruction::GetElementPtr ||
998 CE->getOpcode() == Instruction::BitCast) {
999 if (AnalyzeUsesOfFunction(CE))
1000 return true;
1001 } else {
1002 return true;
1003 }
1004 } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(*UI)) {
1005 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1006 return true; // Allow comparison against null.
1007 } else if (dyn_cast<FreeInst>(*UI)) {
1008 return false;
1009 } else {
1010 return true;
1011 }
1012 return false;
1013}
1014
Chris Lattnere995a2a2004-05-23 21:00:47 +00001015/// CollectConstraints - This stage scans the program, adding a constraint to
1016/// the Constraints list for each instruction in the program that induces a
1017/// constraint, and setting up the initial points-to graph.
1018///
1019void Andersens::CollectConstraints(Module &M) {
1020 // First, the universal set points to itself.
Daniel Berlinaad15882007-09-16 21:45:02 +00001021 Constraints.push_back(Constraint(Constraint::AddressOf, UniversalSet,
1022 UniversalSet));
1023 Constraints.push_back(Constraint(Constraint::Store, UniversalSet,
1024 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001025
1026 // Next, the null pointer points to the null object.
Daniel Berlinaad15882007-09-16 21:45:02 +00001027 Constraints.push_back(Constraint(Constraint::AddressOf, NullPtr, NullObject));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001028
1029 // Next, add any constraints on global variables and their initializers.
Chris Lattner493f6362005-03-27 22:03:46 +00001030 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1031 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001032 // Associate the address of the global object as pointing to the memory for
1033 // the global: &G = <G memory>
Daniel Berlinaad15882007-09-16 21:45:02 +00001034 unsigned ObjectIndex = getObject(I);
1035 Node *Object = &GraphNodes[ObjectIndex];
Chris Lattnere995a2a2004-05-23 21:00:47 +00001036 Object->setValue(I);
Daniel Berlinaad15882007-09-16 21:45:02 +00001037 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(*I),
1038 ObjectIndex));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001039
1040 if (I->hasInitializer()) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001041 AddGlobalInitializerConstraints(ObjectIndex, I->getInitializer());
Chris Lattnere995a2a2004-05-23 21:00:47 +00001042 } else {
1043 // If it doesn't have an initializer (i.e. it's defined in another
1044 // translation unit), it points to the universal set.
Daniel Berlinaad15882007-09-16 21:45:02 +00001045 Constraints.push_back(Constraint(Constraint::Copy, ObjectIndex,
1046 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001047 }
1048 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001049
Chris Lattnere995a2a2004-05-23 21:00:47 +00001050 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001051 // Set up the return value node.
1052 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
Daniel Berlinaad15882007-09-16 21:45:02 +00001053 GraphNodes[getReturnNode(F)].setValue(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001054 if (F->getFunctionType()->isVarArg())
Daniel Berlinaad15882007-09-16 21:45:02 +00001055 GraphNodes[getVarargNode(F)].setValue(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001056
1057 // Set up incoming argument nodes.
Chris Lattner493f6362005-03-27 22:03:46 +00001058 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
1059 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +00001060 if (isa<PointerType>(I->getType()))
1061 getNodeValue(*I);
1062
Daniel Berlinaad15882007-09-16 21:45:02 +00001063 // At some point we should just add constraints for the escaping functions
1064 // at solve time, but this slows down solving. For now, we simply mark
1065 // address taken functions as escaping and treat them as external.
1066 if (!F->hasInternalLinkage() || AnalyzeUsesOfFunction(F))
Chris Lattnere995a2a2004-05-23 21:00:47 +00001067 AddConstraintsForNonInternalLinkage(F);
1068
Reid Spencer5cbf9852007-01-30 20:08:39 +00001069 if (!F->isDeclaration()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001070 // Scan the function body, creating a memory object for each heap/stack
1071 // allocation in the body of the function and a node to represent all
1072 // pointer values defined by instructions and used as operands.
1073 visit(F);
Chris Lattner8a446432005-03-29 06:09:07 +00001074 } else {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001075 // External functions that return pointers return the universal set.
1076 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
1077 Constraints.push_back(Constraint(Constraint::Copy,
1078 getReturnNode(F),
Daniel Berlinaad15882007-09-16 21:45:02 +00001079 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001080
1081 // Any pointers that are passed into the function have the universal set
1082 // stored into them.
Chris Lattner493f6362005-03-27 22:03:46 +00001083 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
1084 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +00001085 if (isa<PointerType>(I->getType())) {
1086 // Pointers passed into external functions could have anything stored
1087 // through them.
1088 Constraints.push_back(Constraint(Constraint::Store, getNode(I),
Daniel Berlinaad15882007-09-16 21:45:02 +00001089 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001090 // Memory objects passed into external function calls can have the
1091 // universal set point to them.
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001092#if FULL_UNIVERSAL
Chris Lattnere995a2a2004-05-23 21:00:47 +00001093 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001094 UniversalSet,
Chris Lattnere995a2a2004-05-23 21:00:47 +00001095 getNode(I)));
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001096#else
1097 Constraints.push_back(Constraint(Constraint::Copy,
1098 getNode(I),
1099 UniversalSet));
1100#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001101 }
1102
1103 // If this is an external varargs function, it can also store pointers
1104 // into any pointers passed through the varargs section.
1105 if (F->getFunctionType()->isVarArg())
1106 Constraints.push_back(Constraint(Constraint::Store, getVarargNode(F),
Daniel Berlinaad15882007-09-16 21:45:02 +00001107 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001108 }
1109 }
1110 NumConstraints += Constraints.size();
1111}
1112
1113
1114void Andersens::visitInstruction(Instruction &I) {
1115#ifdef NDEBUG
1116 return; // This function is just a big assert.
1117#endif
1118 if (isa<BinaryOperator>(I))
1119 return;
1120 // Most instructions don't have any effect on pointer values.
1121 switch (I.getOpcode()) {
1122 case Instruction::Br:
1123 case Instruction::Switch:
1124 case Instruction::Unwind:
Chris Lattnerc17edbd2004-10-16 18:16:19 +00001125 case Instruction::Unreachable:
Chris Lattnere995a2a2004-05-23 21:00:47 +00001126 case Instruction::Free:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001127 case Instruction::ICmp:
1128 case Instruction::FCmp:
Chris Lattnere995a2a2004-05-23 21:00:47 +00001129 return;
1130 default:
1131 // Is this something we aren't handling yet?
Bill Wendlinge8156192006-12-07 01:30:32 +00001132 cerr << "Unknown instruction: " << I;
Chris Lattnere995a2a2004-05-23 21:00:47 +00001133 abort();
1134 }
1135}
1136
1137void Andersens::visitAllocationInst(AllocationInst &AI) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001138 unsigned ObjectIndex = getObject(&AI);
1139 GraphNodes[ObjectIndex].setValue(&AI);
1140 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(AI),
1141 ObjectIndex));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001142}
1143
1144void Andersens::visitReturnInst(ReturnInst &RI) {
1145 if (RI.getNumOperands() && isa<PointerType>(RI.getOperand(0)->getType()))
1146 // return V --> <Copy/retval{F}/v>
1147 Constraints.push_back(Constraint(Constraint::Copy,
1148 getReturnNode(RI.getParent()->getParent()),
1149 getNode(RI.getOperand(0))));
1150}
1151
1152void Andersens::visitLoadInst(LoadInst &LI) {
1153 if (isa<PointerType>(LI.getType()))
1154 // P1 = load P2 --> <Load/P1/P2>
1155 Constraints.push_back(Constraint(Constraint::Load, getNodeValue(LI),
1156 getNode(LI.getOperand(0))));
1157}
1158
1159void Andersens::visitStoreInst(StoreInst &SI) {
1160 if (isa<PointerType>(SI.getOperand(0)->getType()))
1161 // store P1, P2 --> <Store/P2/P1>
1162 Constraints.push_back(Constraint(Constraint::Store,
1163 getNode(SI.getOperand(1)),
1164 getNode(SI.getOperand(0))));
1165}
1166
1167void Andersens::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1168 // P1 = getelementptr P2, ... --> <Copy/P1/P2>
1169 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(GEP),
1170 getNode(GEP.getOperand(0))));
1171}
1172
1173void Andersens::visitPHINode(PHINode &PN) {
1174 if (isa<PointerType>(PN.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001175 unsigned PNN = getNodeValue(PN);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001176 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1177 // P1 = phi P2, P3 --> <Copy/P1/P2>, <Copy/P1/P3>, ...
1178 Constraints.push_back(Constraint(Constraint::Copy, PNN,
1179 getNode(PN.getIncomingValue(i))));
1180 }
1181}
1182
1183void Andersens::visitCastInst(CastInst &CI) {
1184 Value *Op = CI.getOperand(0);
1185 if (isa<PointerType>(CI.getType())) {
1186 if (isa<PointerType>(Op->getType())) {
1187 // P1 = cast P2 --> <Copy/P1/P2>
1188 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
1189 getNode(CI.getOperand(0))));
1190 } else {
1191 // P1 = cast int --> <Copy/P1/Univ>
Chris Lattner175b9632005-03-29 20:36:05 +00001192#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +00001193 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
Daniel Berlinaad15882007-09-16 21:45:02 +00001194 UniversalSet));
Chris Lattnerbd135c72005-04-05 01:12:03 +00001195#else
1196 getNodeValue(CI);
Chris Lattner175b9632005-03-29 20:36:05 +00001197#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001198 }
1199 } else if (isa<PointerType>(Op->getType())) {
1200 // int = cast P1 --> <Copy/Univ/P1>
Chris Lattner175b9632005-03-29 20:36:05 +00001201#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +00001202 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001203 UniversalSet,
Chris Lattnere995a2a2004-05-23 21:00:47 +00001204 getNode(CI.getOperand(0))));
Chris Lattnerbd135c72005-04-05 01:12:03 +00001205#else
1206 getNode(CI.getOperand(0));
Chris Lattner175b9632005-03-29 20:36:05 +00001207#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001208 }
1209}
1210
1211void Andersens::visitSelectInst(SelectInst &SI) {
1212 if (isa<PointerType>(SI.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001213 unsigned SIN = getNodeValue(SI);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001214 // P1 = select C, P2, P3 ---> <Copy/P1/P2>, <Copy/P1/P3>
1215 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1216 getNode(SI.getOperand(1))));
1217 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1218 getNode(SI.getOperand(2))));
1219 }
1220}
1221
Chris Lattnere995a2a2004-05-23 21:00:47 +00001222void Andersens::visitVAArg(VAArgInst &I) {
1223 assert(0 && "vaarg not handled yet!");
1224}
1225
1226/// AddConstraintsForCall - Add constraints for a call with actual arguments
1227/// specified by CS to the function specified by F. Note that the types of
1228/// arguments might not match up in the case where this is an indirect call and
1229/// the function pointer has been casted. If this is the case, do something
1230/// reasonable.
1231void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001232 Value *CallValue = CS.getCalledValue();
1233 bool IsDeref = F == NULL;
1234
1235 // If this is a call to an external function, try to handle it directly to get
1236 // some taste of context sensitivity.
1237 if (F && F->isDeclaration() && AddConstraintsForExternalCall(CS, F))
Chris Lattner8a446432005-03-29 06:09:07 +00001238 return;
1239
Chris Lattnere995a2a2004-05-23 21:00:47 +00001240 if (isa<PointerType>(CS.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001241 unsigned CSN = getNode(CS.getInstruction());
1242 if (!F || isa<PointerType>(F->getFunctionType()->getReturnType())) {
1243 if (IsDeref)
1244 Constraints.push_back(Constraint(Constraint::Load, CSN,
1245 getNode(CallValue), CallReturnPos));
1246 else
1247 Constraints.push_back(Constraint(Constraint::Copy, CSN,
1248 getNode(CallValue) + CallReturnPos));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001249 } else {
1250 // If the function returns a non-pointer value, handle this just like we
1251 // treat a nonpointer cast to pointer.
1252 Constraints.push_back(Constraint(Constraint::Copy, CSN,
Daniel Berlinaad15882007-09-16 21:45:02 +00001253 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001254 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001255 } else if (F && isa<PointerType>(F->getFunctionType()->getReturnType())) {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001256#if FULL_UNIVERSAL
Chris Lattnere995a2a2004-05-23 21:00:47 +00001257 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001258 UniversalSet,
1259 getNode(CallValue) + CallReturnPos));
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001260#else
1261 Constraints.push_back(Constraint(Constraint::Copy,
1262 getNode(CallValue) + CallReturnPos,
1263 UniversalSet));
1264#endif
1265
1266
Chris Lattnere995a2a2004-05-23 21:00:47 +00001267 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001268
Chris Lattnere995a2a2004-05-23 21:00:47 +00001269 CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
Daniel Berlind3bf1ae2008-03-18 22:22:53 +00001270 bool external = !F || F->isDeclaration();
Daniel Berlinaad15882007-09-16 21:45:02 +00001271 if (F) {
1272 // Direct Call
1273 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
Daniel Berlind3bf1ae2008-03-18 22:22:53 +00001274 for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI)
1275 {
1276#if !FULL_UNIVERSAL
1277 if (external && isa<PointerType>((*ArgI)->getType()))
1278 {
1279 // Add constraint that ArgI can now point to anything due to
1280 // escaping, as can everything it points to. The second portion of
1281 // this should be taken care of by universal = *universal
1282 Constraints.push_back(Constraint(Constraint::Copy,
1283 getNode(*ArgI),
1284 UniversalSet));
1285 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001286#endif
Daniel Berlind3bf1ae2008-03-18 22:22:53 +00001287 if (isa<PointerType>(AI->getType())) {
1288 if (isa<PointerType>((*ArgI)->getType())) {
1289 // Copy the actual argument into the formal argument.
1290 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1291 getNode(*ArgI)));
1292 } else {
1293 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1294 UniversalSet));
1295 }
1296 } else if (isa<PointerType>((*ArgI)->getType())) {
1297#if FULL_UNIVERSAL
1298 Constraints.push_back(Constraint(Constraint::Copy,
1299 UniversalSet,
1300 getNode(*ArgI)));
1301#else
1302 Constraints.push_back(Constraint(Constraint::Copy,
1303 getNode(*ArgI),
1304 UniversalSet));
1305#endif
1306 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001307 }
1308 } else {
1309 //Indirect Call
1310 unsigned ArgPos = CallFirstArgPos;
1311 for (; ArgI != ArgE; ++ArgI) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001312 if (isa<PointerType>((*ArgI)->getType())) {
1313 // Copy the actual argument into the formal argument.
Daniel Berlinaad15882007-09-16 21:45:02 +00001314 Constraints.push_back(Constraint(Constraint::Store,
1315 getNode(CallValue),
1316 getNode(*ArgI), ArgPos++));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001317 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +00001318 Constraints.push_back(Constraint(Constraint::Store,
1319 getNode (CallValue),
1320 UniversalSet, ArgPos++));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001321 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00001322 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001323 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00001324 // Copy all pointers passed through the varargs section to the varargs node.
Daniel Berlinaad15882007-09-16 21:45:02 +00001325 if (F && F->getFunctionType()->isVarArg())
Chris Lattnere995a2a2004-05-23 21:00:47 +00001326 for (; ArgI != ArgE; ++ArgI)
1327 if (isa<PointerType>((*ArgI)->getType()))
1328 Constraints.push_back(Constraint(Constraint::Copy, getVarargNode(F),
1329 getNode(*ArgI)));
1330 // If more arguments are passed in than we track, just drop them on the floor.
1331}
1332
1333void Andersens::visitCallSite(CallSite CS) {
1334 if (isa<PointerType>(CS.getType()))
1335 getNodeValue(*CS.getInstruction());
1336
1337 if (Function *F = CS.getCalledFunction()) {
1338 AddConstraintsForCall(CS, F);
1339 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +00001340 AddConstraintsForCall(CS, NULL);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001341 }
1342}
1343
1344//===----------------------------------------------------------------------===//
1345// Constraint Solving Phase
1346//===----------------------------------------------------------------------===//
1347
1348/// intersects - Return true if the points-to set of this node intersects
1349/// with the points-to set of the specified node.
1350bool Andersens::Node::intersects(Node *N) const {
Daniel Berlinaad15882007-09-16 21:45:02 +00001351 return PointsTo->intersects(N->PointsTo);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001352}
1353
1354/// intersectsIgnoring - Return true if the points-to set of this node
1355/// intersects with the points-to set of the specified node on any nodes
1356/// except for the specified node to ignore.
Daniel Berlinaad15882007-09-16 21:45:02 +00001357bool Andersens::Node::intersectsIgnoring(Node *N, unsigned Ignoring) const {
1358 // TODO: If we are only going to call this with the same value for Ignoring,
1359 // we should move the special values out of the points-to bitmap.
1360 bool WeHadIt = PointsTo->test(Ignoring);
1361 bool NHadIt = N->PointsTo->test(Ignoring);
1362 bool Result = false;
1363 if (WeHadIt)
1364 PointsTo->reset(Ignoring);
1365 if (NHadIt)
1366 N->PointsTo->reset(Ignoring);
1367 Result = PointsTo->intersects(N->PointsTo);
1368 if (WeHadIt)
1369 PointsTo->set(Ignoring);
1370 if (NHadIt)
1371 N->PointsTo->set(Ignoring);
1372 return Result;
Chris Lattnere995a2a2004-05-23 21:00:47 +00001373}
1374
Daniel Berlind81ccc22007-09-24 19:45:49 +00001375void dumpToDOUT(SparseBitVector<> *bitmap) {
Bill Wendlingcab5f5d2007-09-24 22:43:48 +00001376#ifndef NDEBUG
Daniel Berlind81ccc22007-09-24 19:45:49 +00001377 dump(*bitmap, DOUT);
Bill Wendlingcab5f5d2007-09-24 22:43:48 +00001378#endif
Daniel Berlind81ccc22007-09-24 19:45:49 +00001379}
1380
1381
1382/// Clump together address taken variables so that the points-to sets use up
1383/// less space and can be operated on faster.
1384
1385void Andersens::ClumpAddressTaken() {
1386#undef DEBUG_TYPE
1387#define DEBUG_TYPE "anders-aa-renumber"
1388 std::vector<unsigned> Translate;
1389 std::vector<Node> NewGraphNodes;
1390
1391 Translate.resize(GraphNodes.size());
1392 unsigned NewPos = 0;
1393
1394 for (unsigned i = 0; i < Constraints.size(); ++i) {
1395 Constraint &C = Constraints[i];
1396 if (C.Type == Constraint::AddressOf) {
1397 GraphNodes[C.Src].AddressTaken = true;
1398 }
1399 }
1400 for (unsigned i = 0; i < NumberSpecialNodes; ++i) {
1401 unsigned Pos = NewPos++;
1402 Translate[i] = Pos;
1403 NewGraphNodes.push_back(GraphNodes[i]);
1404 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1405 }
1406
1407 // I believe this ends up being faster than making two vectors and splicing
1408 // them.
1409 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1410 if (GraphNodes[i].AddressTaken) {
1411 unsigned Pos = NewPos++;
1412 Translate[i] = Pos;
1413 NewGraphNodes.push_back(GraphNodes[i]);
1414 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1415 }
1416 }
1417
1418 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1419 if (!GraphNodes[i].AddressTaken) {
1420 unsigned Pos = NewPos++;
1421 Translate[i] = Pos;
1422 NewGraphNodes.push_back(GraphNodes[i]);
1423 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1424 }
1425 }
1426
1427 for (DenseMap<Value*, unsigned>::iterator Iter = ValueNodes.begin();
1428 Iter != ValueNodes.end();
1429 ++Iter)
1430 Iter->second = Translate[Iter->second];
1431
1432 for (DenseMap<Value*, unsigned>::iterator Iter = ObjectNodes.begin();
1433 Iter != ObjectNodes.end();
1434 ++Iter)
1435 Iter->second = Translate[Iter->second];
1436
1437 for (DenseMap<Function*, unsigned>::iterator Iter = ReturnNodes.begin();
1438 Iter != ReturnNodes.end();
1439 ++Iter)
1440 Iter->second = Translate[Iter->second];
1441
1442 for (DenseMap<Function*, unsigned>::iterator Iter = VarargNodes.begin();
1443 Iter != VarargNodes.end();
1444 ++Iter)
1445 Iter->second = Translate[Iter->second];
1446
1447 for (unsigned i = 0; i < Constraints.size(); ++i) {
1448 Constraint &C = Constraints[i];
1449 C.Src = Translate[C.Src];
1450 C.Dest = Translate[C.Dest];
1451 }
1452
1453 GraphNodes.swap(NewGraphNodes);
1454#undef DEBUG_TYPE
1455#define DEBUG_TYPE "anders-aa"
1456}
1457
1458/// The technique used here is described in "Exploiting Pointer and Location
1459/// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1460/// Analysis Symposium (SAS), August 2007." It is known as the "HVN" algorithm,
1461/// and is equivalent to value numbering the collapsed constraint graph without
1462/// evaluating unions. This is used as a pre-pass to HU in order to resolve
1463/// first order pointer dereferences and speed up/reduce memory usage of HU.
1464/// Running both is equivalent to HRU without the iteration
1465/// HVN in more detail:
1466/// Imagine the set of constraints was simply straight line code with no loops
1467/// (we eliminate cycles, so there are no loops), such as:
1468/// E = &D
1469/// E = &C
1470/// E = F
1471/// F = G
1472/// G = F
1473/// Applying value numbering to this code tells us:
1474/// G == F == E
1475///
1476/// For HVN, this is as far as it goes. We assign new value numbers to every
1477/// "address node", and every "reference node".
1478/// To get the optimal result for this, we use a DFS + SCC (since all nodes in a
1479/// cycle must have the same value number since the = operation is really
1480/// inclusion, not overwrite), and value number nodes we receive points-to sets
1481/// before we value our own node.
1482/// The advantage of HU over HVN is that HU considers the inclusion property, so
1483/// that if you have
1484/// E = &D
1485/// E = &C
1486/// E = F
1487/// F = G
1488/// F = &D
1489/// G = F
1490/// HU will determine that G == F == E. HVN will not, because it cannot prove
1491/// that the points to information ends up being the same because they all
1492/// receive &D from E anyway.
1493
1494void Andersens::HVN() {
1495 DOUT << "Beginning HVN\n";
1496 // Build a predecessor graph. This is like our constraint graph with the
1497 // edges going in the opposite direction, and there are edges for all the
1498 // constraints, instead of just copy constraints. We also build implicit
1499 // edges for constraints are implied but not explicit. I.E for the constraint
1500 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1501 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1502 Constraint &C = Constraints[i];
1503 if (C.Type == Constraint::AddressOf) {
1504 GraphNodes[C.Src].AddressTaken = true;
1505 GraphNodes[C.Src].Direct = false;
1506
1507 // Dest = &src edge
1508 unsigned AdrNode = C.Src + FirstAdrNode;
1509 if (!GraphNodes[C.Dest].PredEdges)
1510 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1511 GraphNodes[C.Dest].PredEdges->set(AdrNode);
1512
1513 // *Dest = src edge
1514 unsigned RefNode = C.Dest + FirstRefNode;
1515 if (!GraphNodes[RefNode].ImplicitPredEdges)
1516 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1517 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1518 } else if (C.Type == Constraint::Load) {
1519 if (C.Offset == 0) {
1520 // dest = *src edge
1521 if (!GraphNodes[C.Dest].PredEdges)
1522 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1523 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1524 } else {
1525 GraphNodes[C.Dest].Direct = false;
1526 }
1527 } else if (C.Type == Constraint::Store) {
1528 if (C.Offset == 0) {
1529 // *dest = src edge
1530 unsigned RefNode = C.Dest + FirstRefNode;
1531 if (!GraphNodes[RefNode].PredEdges)
1532 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1533 GraphNodes[RefNode].PredEdges->set(C.Src);
1534 }
1535 } else {
1536 // Dest = Src edge and *Dest = *Src edge
1537 if (!GraphNodes[C.Dest].PredEdges)
1538 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1539 GraphNodes[C.Dest].PredEdges->set(C.Src);
1540 unsigned RefNode = C.Dest + FirstRefNode;
1541 if (!GraphNodes[RefNode].ImplicitPredEdges)
1542 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1543 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1544 }
1545 }
1546 PEClass = 1;
1547 // Do SCC finding first to condense our predecessor graph
1548 DFSNumber = 0;
1549 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1550 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1551 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1552
1553 for (unsigned i = 0; i < FirstRefNode; ++i) {
1554 unsigned Node = VSSCCRep[i];
1555 if (!Node2Visited[Node])
1556 HVNValNum(Node);
1557 }
1558 for (BitVectorMap::iterator Iter = Set2PEClass.begin();
1559 Iter != Set2PEClass.end();
1560 ++Iter)
1561 delete Iter->first;
1562 Set2PEClass.clear();
1563 Node2DFS.clear();
1564 Node2Deleted.clear();
1565 Node2Visited.clear();
1566 DOUT << "Finished HVN\n";
1567
1568}
1569
1570/// This is the workhorse of HVN value numbering. We combine SCC finding at the
1571/// same time because it's easy.
1572void Andersens::HVNValNum(unsigned NodeIndex) {
1573 unsigned MyDFS = DFSNumber++;
1574 Node *N = &GraphNodes[NodeIndex];
1575 Node2Visited[NodeIndex] = true;
1576 Node2DFS[NodeIndex] = MyDFS;
1577
1578 // First process all our explicit edges
1579 if (N->PredEdges)
1580 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1581 Iter != N->PredEdges->end();
1582 ++Iter) {
1583 unsigned j = VSSCCRep[*Iter];
1584 if (!Node2Deleted[j]) {
1585 if (!Node2Visited[j])
1586 HVNValNum(j);
1587 if (Node2DFS[NodeIndex] > Node2DFS[j])
1588 Node2DFS[NodeIndex] = Node2DFS[j];
1589 }
1590 }
1591
1592 // Now process all the implicit edges
1593 if (N->ImplicitPredEdges)
1594 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1595 Iter != N->ImplicitPredEdges->end();
1596 ++Iter) {
1597 unsigned j = VSSCCRep[*Iter];
1598 if (!Node2Deleted[j]) {
1599 if (!Node2Visited[j])
1600 HVNValNum(j);
1601 if (Node2DFS[NodeIndex] > Node2DFS[j])
1602 Node2DFS[NodeIndex] = Node2DFS[j];
1603 }
1604 }
1605
1606 // See if we found any cycles
1607 if (MyDFS == Node2DFS[NodeIndex]) {
1608 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1609 unsigned CycleNodeIndex = SCCStack.top();
1610 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1611 VSSCCRep[CycleNodeIndex] = NodeIndex;
1612 // Unify the nodes
1613 N->Direct &= CycleNode->Direct;
1614
1615 if (CycleNode->PredEdges) {
1616 if (!N->PredEdges)
1617 N->PredEdges = new SparseBitVector<>;
1618 *(N->PredEdges) |= CycleNode->PredEdges;
1619 delete CycleNode->PredEdges;
1620 CycleNode->PredEdges = NULL;
1621 }
1622 if (CycleNode->ImplicitPredEdges) {
1623 if (!N->ImplicitPredEdges)
1624 N->ImplicitPredEdges = new SparseBitVector<>;
1625 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1626 delete CycleNode->ImplicitPredEdges;
1627 CycleNode->ImplicitPredEdges = NULL;
1628 }
1629
1630 SCCStack.pop();
1631 }
1632
1633 Node2Deleted[NodeIndex] = true;
1634
1635 if (!N->Direct) {
1636 GraphNodes[NodeIndex].PointerEquivLabel = PEClass++;
1637 return;
1638 }
1639
1640 // Collect labels of successor nodes
1641 bool AllSame = true;
1642 unsigned First = ~0;
1643 SparseBitVector<> *Labels = new SparseBitVector<>;
1644 bool Used = false;
1645
1646 if (N->PredEdges)
1647 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1648 Iter != N->PredEdges->end();
1649 ++Iter) {
1650 unsigned j = VSSCCRep[*Iter];
1651 unsigned Label = GraphNodes[j].PointerEquivLabel;
1652 // Ignore labels that are equal to us or non-pointers
1653 if (j == NodeIndex || Label == 0)
1654 continue;
1655 if (First == (unsigned)~0)
1656 First = Label;
1657 else if (First != Label)
1658 AllSame = false;
1659 Labels->set(Label);
1660 }
1661
1662 // We either have a non-pointer, a copy of an existing node, or a new node.
1663 // Assign the appropriate pointer equivalence label.
1664 if (Labels->empty()) {
1665 GraphNodes[NodeIndex].PointerEquivLabel = 0;
1666 } else if (AllSame) {
1667 GraphNodes[NodeIndex].PointerEquivLabel = First;
1668 } else {
1669 GraphNodes[NodeIndex].PointerEquivLabel = Set2PEClass[Labels];
1670 if (GraphNodes[NodeIndex].PointerEquivLabel == 0) {
1671 unsigned EquivClass = PEClass++;
1672 Set2PEClass[Labels] = EquivClass;
1673 GraphNodes[NodeIndex].PointerEquivLabel = EquivClass;
1674 Used = true;
1675 }
1676 }
1677 if (!Used)
1678 delete Labels;
1679 } else {
1680 SCCStack.push(NodeIndex);
1681 }
1682}
1683
1684/// The technique used here is described in "Exploiting Pointer and Location
1685/// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1686/// Analysis Symposium (SAS), August 2007." It is known as the "HU" algorithm,
1687/// and is equivalent to value numbering the collapsed constraint graph
1688/// including evaluating unions.
1689void Andersens::HU() {
1690 DOUT << "Beginning HU\n";
1691 // Build a predecessor graph. This is like our constraint graph with the
1692 // edges going in the opposite direction, and there are edges for all the
1693 // constraints, instead of just copy constraints. We also build implicit
1694 // edges for constraints are implied but not explicit. I.E for the constraint
1695 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1696 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1697 Constraint &C = Constraints[i];
1698 if (C.Type == Constraint::AddressOf) {
1699 GraphNodes[C.Src].AddressTaken = true;
1700 GraphNodes[C.Src].Direct = false;
1701
1702 GraphNodes[C.Dest].PointsTo->set(C.Src);
1703 // *Dest = src edge
1704 unsigned RefNode = C.Dest + FirstRefNode;
1705 if (!GraphNodes[RefNode].ImplicitPredEdges)
1706 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1707 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1708 GraphNodes[C.Src].PointedToBy->set(C.Dest);
1709 } else if (C.Type == Constraint::Load) {
1710 if (C.Offset == 0) {
1711 // dest = *src edge
1712 if (!GraphNodes[C.Dest].PredEdges)
1713 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1714 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1715 } else {
1716 GraphNodes[C.Dest].Direct = false;
1717 }
1718 } else if (C.Type == Constraint::Store) {
1719 if (C.Offset == 0) {
1720 // *dest = src edge
1721 unsigned RefNode = C.Dest + FirstRefNode;
1722 if (!GraphNodes[RefNode].PredEdges)
1723 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1724 GraphNodes[RefNode].PredEdges->set(C.Src);
1725 }
1726 } else {
1727 // Dest = Src edge and *Dest = *Src edg
1728 if (!GraphNodes[C.Dest].PredEdges)
1729 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1730 GraphNodes[C.Dest].PredEdges->set(C.Src);
1731 unsigned RefNode = C.Dest + FirstRefNode;
1732 if (!GraphNodes[RefNode].ImplicitPredEdges)
1733 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1734 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1735 }
1736 }
1737 PEClass = 1;
1738 // Do SCC finding first to condense our predecessor graph
1739 DFSNumber = 0;
1740 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1741 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1742 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1743
1744 for (unsigned i = 0; i < FirstRefNode; ++i) {
1745 if (FindNode(i) == i) {
1746 unsigned Node = VSSCCRep[i];
1747 if (!Node2Visited[Node])
1748 Condense(Node);
1749 }
1750 }
1751
1752 // Reset tables for actual labeling
1753 Node2DFS.clear();
1754 Node2Visited.clear();
1755 Node2Deleted.clear();
1756 // Pre-grow our densemap so that we don't get really bad behavior
1757 Set2PEClass.resize(GraphNodes.size());
1758
1759 // Visit the condensed graph and generate pointer equivalence labels.
1760 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1761 for (unsigned i = 0; i < FirstRefNode; ++i) {
1762 if (FindNode(i) == i) {
1763 unsigned Node = VSSCCRep[i];
1764 if (!Node2Visited[Node])
1765 HUValNum(Node);
1766 }
1767 }
1768 // PEClass nodes will be deleted by the deleting of N->PointsTo in our caller.
1769 Set2PEClass.clear();
1770 DOUT << "Finished HU\n";
1771}
1772
1773
1774/// Implementation of standard Tarjan SCC algorithm as modified by Nuutilla.
1775void Andersens::Condense(unsigned NodeIndex) {
1776 unsigned MyDFS = DFSNumber++;
1777 Node *N = &GraphNodes[NodeIndex];
1778 Node2Visited[NodeIndex] = true;
1779 Node2DFS[NodeIndex] = MyDFS;
1780
1781 // First process all our explicit edges
1782 if (N->PredEdges)
1783 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1784 Iter != N->PredEdges->end();
1785 ++Iter) {
1786 unsigned j = VSSCCRep[*Iter];
1787 if (!Node2Deleted[j]) {
1788 if (!Node2Visited[j])
1789 Condense(j);
1790 if (Node2DFS[NodeIndex] > Node2DFS[j])
1791 Node2DFS[NodeIndex] = Node2DFS[j];
1792 }
1793 }
1794
1795 // Now process all the implicit edges
1796 if (N->ImplicitPredEdges)
1797 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1798 Iter != N->ImplicitPredEdges->end();
1799 ++Iter) {
1800 unsigned j = VSSCCRep[*Iter];
1801 if (!Node2Deleted[j]) {
1802 if (!Node2Visited[j])
1803 Condense(j);
1804 if (Node2DFS[NodeIndex] > Node2DFS[j])
1805 Node2DFS[NodeIndex] = Node2DFS[j];
1806 }
1807 }
1808
1809 // See if we found any cycles
1810 if (MyDFS == Node2DFS[NodeIndex]) {
1811 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1812 unsigned CycleNodeIndex = SCCStack.top();
1813 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1814 VSSCCRep[CycleNodeIndex] = NodeIndex;
1815 // Unify the nodes
1816 N->Direct &= CycleNode->Direct;
1817
1818 *(N->PointsTo) |= CycleNode->PointsTo;
1819 delete CycleNode->PointsTo;
1820 CycleNode->PointsTo = NULL;
1821 if (CycleNode->PredEdges) {
1822 if (!N->PredEdges)
1823 N->PredEdges = new SparseBitVector<>;
1824 *(N->PredEdges) |= CycleNode->PredEdges;
1825 delete CycleNode->PredEdges;
1826 CycleNode->PredEdges = NULL;
1827 }
1828 if (CycleNode->ImplicitPredEdges) {
1829 if (!N->ImplicitPredEdges)
1830 N->ImplicitPredEdges = new SparseBitVector<>;
1831 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1832 delete CycleNode->ImplicitPredEdges;
1833 CycleNode->ImplicitPredEdges = NULL;
1834 }
1835 SCCStack.pop();
1836 }
1837
1838 Node2Deleted[NodeIndex] = true;
1839
1840 // Set up number of incoming edges for other nodes
1841 if (N->PredEdges)
1842 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1843 Iter != N->PredEdges->end();
1844 ++Iter)
1845 ++GraphNodes[VSSCCRep[*Iter]].NumInEdges;
1846 } else {
1847 SCCStack.push(NodeIndex);
1848 }
1849}
1850
1851void Andersens::HUValNum(unsigned NodeIndex) {
1852 Node *N = &GraphNodes[NodeIndex];
1853 Node2Visited[NodeIndex] = true;
1854
1855 // Eliminate dereferences of non-pointers for those non-pointers we have
1856 // already identified. These are ref nodes whose non-ref node:
1857 // 1. Has already been visited determined to point to nothing (and thus, a
1858 // dereference of it must point to nothing)
1859 // 2. Any direct node with no predecessor edges in our graph and with no
1860 // points-to set (since it can't point to anything either, being that it
1861 // receives no points-to sets and has none).
1862 if (NodeIndex >= FirstRefNode) {
1863 unsigned j = VSSCCRep[FindNode(NodeIndex - FirstRefNode)];
1864 if ((Node2Visited[j] && !GraphNodes[j].PointerEquivLabel)
1865 || (GraphNodes[j].Direct && !GraphNodes[j].PredEdges
1866 && GraphNodes[j].PointsTo->empty())){
1867 return;
1868 }
1869 }
1870 // Process all our explicit edges
1871 if (N->PredEdges)
1872 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1873 Iter != N->PredEdges->end();
1874 ++Iter) {
1875 unsigned j = VSSCCRep[*Iter];
1876 if (!Node2Visited[j])
1877 HUValNum(j);
1878
1879 // If this edge turned out to be the same as us, or got no pointer
1880 // equivalence label (and thus points to nothing) , just decrement our
1881 // incoming edges and continue.
1882 if (j == NodeIndex || GraphNodes[j].PointerEquivLabel == 0) {
1883 --GraphNodes[j].NumInEdges;
1884 continue;
1885 }
1886
1887 *(N->PointsTo) |= GraphNodes[j].PointsTo;
1888
1889 // If we didn't end up storing this in the hash, and we're done with all
1890 // the edges, we don't need the points-to set anymore.
1891 --GraphNodes[j].NumInEdges;
1892 if (!GraphNodes[j].NumInEdges && !GraphNodes[j].StoredInHash) {
1893 delete GraphNodes[j].PointsTo;
1894 GraphNodes[j].PointsTo = NULL;
1895 }
1896 }
1897 // If this isn't a direct node, generate a fresh variable.
1898 if (!N->Direct) {
1899 N->PointsTo->set(FirstRefNode + NodeIndex);
1900 }
1901
1902 // See If we have something equivalent to us, if not, generate a new
1903 // equivalence class.
1904 if (N->PointsTo->empty()) {
1905 delete N->PointsTo;
1906 N->PointsTo = NULL;
1907 } else {
1908 if (N->Direct) {
1909 N->PointerEquivLabel = Set2PEClass[N->PointsTo];
1910 if (N->PointerEquivLabel == 0) {
1911 unsigned EquivClass = PEClass++;
1912 N->StoredInHash = true;
1913 Set2PEClass[N->PointsTo] = EquivClass;
1914 N->PointerEquivLabel = EquivClass;
1915 }
1916 } else {
1917 N->PointerEquivLabel = PEClass++;
1918 }
1919 }
1920}
1921
1922/// Rewrite our list of constraints so that pointer equivalent nodes are
1923/// replaced by their the pointer equivalence class representative.
1924void Andersens::RewriteConstraints() {
1925 std::vector<Constraint> NewConstraints;
Chris Lattnerbe207732007-09-30 00:47:20 +00001926 DenseSet<Constraint, ConstraintKeyInfo> Seen;
Daniel Berlind81ccc22007-09-24 19:45:49 +00001927
1928 PEClass2Node.clear();
1929 PENLEClass2Node.clear();
1930
1931 // We may have from 1 to Graphnodes + 1 equivalence classes.
1932 PEClass2Node.insert(PEClass2Node.begin(), GraphNodes.size() + 1, -1);
1933 PENLEClass2Node.insert(PENLEClass2Node.begin(), GraphNodes.size() + 1, -1);
1934
1935 // Rewrite constraints, ignoring non-pointer constraints, uniting equivalent
1936 // nodes, and rewriting constraints to use the representative nodes.
1937 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1938 Constraint &C = Constraints[i];
1939 unsigned RHSNode = FindNode(C.Src);
1940 unsigned LHSNode = FindNode(C.Dest);
1941 unsigned RHSLabel = GraphNodes[VSSCCRep[RHSNode]].PointerEquivLabel;
1942 unsigned LHSLabel = GraphNodes[VSSCCRep[LHSNode]].PointerEquivLabel;
1943
1944 // First we try to eliminate constraints for things we can prove don't point
1945 // to anything.
1946 if (LHSLabel == 0) {
1947 DEBUG(PrintNode(&GraphNodes[LHSNode]));
1948 DOUT << " is a non-pointer, ignoring constraint.\n";
1949 continue;
1950 }
1951 if (RHSLabel == 0) {
1952 DEBUG(PrintNode(&GraphNodes[RHSNode]));
1953 DOUT << " is a non-pointer, ignoring constraint.\n";
1954 continue;
1955 }
1956 // This constraint may be useless, and it may become useless as we translate
1957 // it.
1958 if (C.Src == C.Dest && C.Type == Constraint::Copy)
1959 continue;
Daniel Berlinc7a12ae2007-09-27 15:42:23 +00001960
Daniel Berlind81ccc22007-09-24 19:45:49 +00001961 C.Src = FindEquivalentNode(RHSNode, RHSLabel);
1962 C.Dest = FindEquivalentNode(FindNode(LHSNode), LHSLabel);
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001963 if ((C.Src == C.Dest && C.Type == Constraint::Copy)
Chris Lattnerbe207732007-09-30 00:47:20 +00001964 || Seen.count(C))
Daniel Berlind81ccc22007-09-24 19:45:49 +00001965 continue;
1966
Chris Lattnerbe207732007-09-30 00:47:20 +00001967 Seen.insert(C);
Daniel Berlind81ccc22007-09-24 19:45:49 +00001968 NewConstraints.push_back(C);
1969 }
1970 Constraints.swap(NewConstraints);
1971 PEClass2Node.clear();
1972}
1973
1974/// See if we have a node that is pointer equivalent to the one being asked
1975/// about, and if so, unite them and return the equivalent node. Otherwise,
1976/// return the original node.
1977unsigned Andersens::FindEquivalentNode(unsigned NodeIndex,
1978 unsigned NodeLabel) {
1979 if (!GraphNodes[NodeIndex].AddressTaken) {
1980 if (PEClass2Node[NodeLabel] != -1) {
1981 // We found an existing node with the same pointer label, so unify them.
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001982 // We specifically request that Union-By-Rank not be used so that
1983 // PEClass2Node[NodeLabel] U= NodeIndex and not the other way around.
1984 return UniteNodes(PEClass2Node[NodeLabel], NodeIndex, false);
Daniel Berlind81ccc22007-09-24 19:45:49 +00001985 } else {
1986 PEClass2Node[NodeLabel] = NodeIndex;
1987 PENLEClass2Node[NodeLabel] = NodeIndex;
1988 }
1989 } else if (PENLEClass2Node[NodeLabel] == -1) {
1990 PENLEClass2Node[NodeLabel] = NodeIndex;
1991 }
1992
1993 return NodeIndex;
1994}
1995
1996void Andersens::PrintLabels() {
1997 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1998 if (i < FirstRefNode) {
1999 PrintNode(&GraphNodes[i]);
2000 } else if (i < FirstAdrNode) {
2001 DOUT << "REF(";
2002 PrintNode(&GraphNodes[i-FirstRefNode]);
2003 DOUT <<")";
2004 } else {
2005 DOUT << "ADR(";
2006 PrintNode(&GraphNodes[i-FirstAdrNode]);
2007 DOUT <<")";
2008 }
2009
2010 DOUT << " has pointer label " << GraphNodes[i].PointerEquivLabel
2011 << " and SCC rep " << VSSCCRep[i]
2012 << " and is " << (GraphNodes[i].Direct ? "Direct" : "Not direct")
2013 << "\n";
2014 }
2015}
2016
Daniel Berlinc864edb2008-03-05 19:31:47 +00002017/// The technique used here is described in "The Ant and the
2018/// Grasshopper: Fast and Accurate Pointer Analysis for Millions of
2019/// Lines of Code. In Programming Language Design and Implementation
2020/// (PLDI), June 2007." It is known as the "HCD" (Hybrid Cycle
2021/// Detection) algorithm. It is called a hybrid because it performs an
2022/// offline analysis and uses its results during the solving (online)
2023/// phase. This is just the offline portion; the results of this
2024/// operation are stored in SDT and are later used in SolveContraints()
2025/// and UniteNodes().
2026void Andersens::HCD() {
2027 DOUT << "Starting HCD.\n";
2028 HCDSCCRep.resize(GraphNodes.size());
2029
2030 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2031 GraphNodes[i].Edges = new SparseBitVector<>;
2032 HCDSCCRep[i] = i;
2033 }
2034
2035 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2036 Constraint &C = Constraints[i];
2037 assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
2038 if (C.Type == Constraint::AddressOf) {
2039 continue;
2040 } else if (C.Type == Constraint::Load) {
2041 if( C.Offset == 0 )
2042 GraphNodes[C.Dest].Edges->set(C.Src + FirstRefNode);
2043 } else if (C.Type == Constraint::Store) {
2044 if( C.Offset == 0 )
2045 GraphNodes[C.Dest + FirstRefNode].Edges->set(C.Src);
2046 } else {
2047 GraphNodes[C.Dest].Edges->set(C.Src);
2048 }
2049 }
2050
2051 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2052 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2053 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
2054 SDT.insert(SDT.begin(), GraphNodes.size() / 2, -1);
2055
2056 DFSNumber = 0;
2057 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2058 unsigned Node = HCDSCCRep[i];
2059 if (!Node2Deleted[Node])
2060 Search(Node);
2061 }
2062
2063 for (unsigned i = 0; i < GraphNodes.size(); ++i)
2064 if (GraphNodes[i].Edges != NULL) {
2065 delete GraphNodes[i].Edges;
2066 GraphNodes[i].Edges = NULL;
2067 }
2068
2069 while( !SCCStack.empty() )
2070 SCCStack.pop();
2071
2072 Node2DFS.clear();
2073 Node2Visited.clear();
2074 Node2Deleted.clear();
2075 HCDSCCRep.clear();
2076 DOUT << "HCD complete.\n";
2077}
2078
2079// Component of HCD:
2080// Use Nuutila's variant of Tarjan's algorithm to detect
2081// Strongly-Connected Components (SCCs). For non-trivial SCCs
2082// containing ref nodes, insert the appropriate information in SDT.
2083void Andersens::Search(unsigned Node) {
2084 unsigned MyDFS = DFSNumber++;
2085
2086 Node2Visited[Node] = true;
2087 Node2DFS[Node] = MyDFS;
2088
2089 for (SparseBitVector<>::iterator Iter = GraphNodes[Node].Edges->begin(),
2090 End = GraphNodes[Node].Edges->end();
2091 Iter != End;
2092 ++Iter) {
2093 unsigned J = HCDSCCRep[*Iter];
2094 assert(GraphNodes[J].isRep() && "Debug check; must be representative");
2095 if (!Node2Deleted[J]) {
2096 if (!Node2Visited[J])
2097 Search(J);
2098 if (Node2DFS[Node] > Node2DFS[J])
2099 Node2DFS[Node] = Node2DFS[J];
2100 }
2101 }
2102
2103 if( MyDFS != Node2DFS[Node] ) {
2104 SCCStack.push(Node);
2105 return;
2106 }
2107
2108 // This node is the root of a SCC, so process it.
2109 //
2110 // If the SCC is "non-trivial" (not a singleton) and contains a reference
2111 // node, we place this SCC into SDT. We unite the nodes in any case.
2112 if (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
2113 SparseBitVector<> SCC;
2114
2115 SCC.set(Node);
2116
2117 bool Ref = (Node >= FirstRefNode);
2118
2119 Node2Deleted[Node] = true;
2120
2121 do {
2122 unsigned P = SCCStack.top(); SCCStack.pop();
2123 Ref |= (P >= FirstRefNode);
2124 SCC.set(P);
2125 HCDSCCRep[P] = Node;
2126 } while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS);
2127
2128 if (Ref) {
2129 unsigned Rep = SCC.find_first();
2130 assert(Rep < FirstRefNode && "The SCC didn't have a non-Ref node!");
2131
2132 SparseBitVector<>::iterator i = SCC.begin();
2133
2134 // Skip over the non-ref nodes
2135 while( *i < FirstRefNode )
2136 ++i;
2137
2138 while( i != SCC.end() )
2139 SDT[ (*i++) - FirstRefNode ] = Rep;
2140 }
2141 }
2142}
2143
2144
Daniel Berlind81ccc22007-09-24 19:45:49 +00002145/// Optimize the constraints by performing offline variable substitution and
2146/// other optimizations.
2147void Andersens::OptimizeConstraints() {
2148 DOUT << "Beginning constraint optimization\n";
2149
Daniel Berlinc864edb2008-03-05 19:31:47 +00002150 SDTActive = false;
2151
Daniel Berlind81ccc22007-09-24 19:45:49 +00002152 // Function related nodes need to stay in the same relative position and can't
2153 // be location equivalent.
2154 for (std::map<unsigned, unsigned>::iterator Iter = MaxK.begin();
2155 Iter != MaxK.end();
2156 ++Iter) {
2157 for (unsigned i = Iter->first;
2158 i != Iter->first + Iter->second;
2159 ++i) {
2160 GraphNodes[i].AddressTaken = true;
2161 GraphNodes[i].Direct = false;
2162 }
2163 }
2164
2165 ClumpAddressTaken();
2166 FirstRefNode = GraphNodes.size();
2167 FirstAdrNode = FirstRefNode + GraphNodes.size();
2168 GraphNodes.insert(GraphNodes.end(), 2 * GraphNodes.size(),
2169 Node(false));
2170 VSSCCRep.resize(GraphNodes.size());
2171 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2172 VSSCCRep[i] = i;
2173 }
2174 HVN();
2175 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2176 Node *N = &GraphNodes[i];
2177 delete N->PredEdges;
2178 N->PredEdges = NULL;
2179 delete N->ImplicitPredEdges;
2180 N->ImplicitPredEdges = NULL;
2181 }
2182#undef DEBUG_TYPE
2183#define DEBUG_TYPE "anders-aa-labels"
2184 DEBUG(PrintLabels());
2185#undef DEBUG_TYPE
2186#define DEBUG_TYPE "anders-aa"
2187 RewriteConstraints();
2188 // Delete the adr nodes.
2189 GraphNodes.resize(FirstRefNode * 2);
2190
2191 // Now perform HU
2192 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2193 Node *N = &GraphNodes[i];
2194 if (FindNode(i) == i) {
2195 N->PointsTo = new SparseBitVector<>;
2196 N->PointedToBy = new SparseBitVector<>;
2197 // Reset our labels
2198 }
2199 VSSCCRep[i] = i;
2200 N->PointerEquivLabel = 0;
2201 }
2202 HU();
2203#undef DEBUG_TYPE
2204#define DEBUG_TYPE "anders-aa-labels"
2205 DEBUG(PrintLabels());
2206#undef DEBUG_TYPE
2207#define DEBUG_TYPE "anders-aa"
2208 RewriteConstraints();
2209 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2210 if (FindNode(i) == i) {
2211 Node *N = &GraphNodes[i];
2212 delete N->PointsTo;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002213 N->PointsTo = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002214 delete N->PredEdges;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002215 N->PredEdges = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002216 delete N->ImplicitPredEdges;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002217 N->ImplicitPredEdges = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002218 delete N->PointedToBy;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002219 N->PointedToBy = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002220 }
2221 }
Daniel Berlinc864edb2008-03-05 19:31:47 +00002222
2223 // perform Hybrid Cycle Detection (HCD)
2224 HCD();
2225 SDTActive = true;
2226
2227 // No longer any need for the upper half of GraphNodes (for ref nodes).
Daniel Berlind81ccc22007-09-24 19:45:49 +00002228 GraphNodes.erase(GraphNodes.begin() + FirstRefNode, GraphNodes.end());
Daniel Berlinc864edb2008-03-05 19:31:47 +00002229
2230 // HCD complete.
2231
Daniel Berlind81ccc22007-09-24 19:45:49 +00002232 DOUT << "Finished constraint optimization\n";
2233 FirstRefNode = 0;
2234 FirstAdrNode = 0;
2235}
2236
2237/// Unite pointer but not location equivalent variables, now that the constraint
2238/// graph is built.
2239void Andersens::UnitePointerEquivalences() {
2240 DOUT << "Uniting remaining pointer equivalences\n";
2241 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002242 if (GraphNodes[i].AddressTaken && GraphNodes[i].isRep()) {
Daniel Berlind81ccc22007-09-24 19:45:49 +00002243 unsigned Label = GraphNodes[i].PointerEquivLabel;
2244
2245 if (Label && PENLEClass2Node[Label] != -1)
2246 UniteNodes(i, PENLEClass2Node[Label]);
2247 }
2248 }
2249 DOUT << "Finished remaining pointer equivalences\n";
2250 PENLEClass2Node.clear();
2251}
2252
2253/// Create the constraint graph used for solving points-to analysis.
2254///
Daniel Berlinaad15882007-09-16 21:45:02 +00002255void Andersens::CreateConstraintGraph() {
2256 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2257 Constraint &C = Constraints[i];
2258 assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
2259 if (C.Type == Constraint::AddressOf)
2260 GraphNodes[C.Dest].PointsTo->set(C.Src);
2261 else if (C.Type == Constraint::Load)
2262 GraphNodes[C.Src].Constraints.push_back(C);
2263 else if (C.Type == Constraint::Store)
2264 GraphNodes[C.Dest].Constraints.push_back(C);
2265 else if (C.Offset != 0)
2266 GraphNodes[C.Src].Constraints.push_back(C);
2267 else
2268 GraphNodes[C.Src].Edges->set(C.Dest);
2269 }
2270}
2271
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002272// Perform DFS and cycle detection.
2273bool Andersens::QueryNode(unsigned Node) {
2274 assert(GraphNodes[Node].isRep() && "Querying a non-rep node");
Daniel Berlinaad15882007-09-16 21:45:02 +00002275 unsigned OurDFS = ++DFSNumber;
2276 SparseBitVector<> ToErase;
2277 SparseBitVector<> NewEdges;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002278 Tarjan2DFS[Node] = OurDFS;
2279
2280 // Changed denotes a change from a recursive call that we will bubble up.
2281 // Merged is set if we actually merge a node ourselves.
2282 bool Changed = false, Merged = false;
Daniel Berlinaad15882007-09-16 21:45:02 +00002283
2284 for (SparseBitVector<>::iterator bi = GraphNodes[Node].Edges->begin();
2285 bi != GraphNodes[Node].Edges->end();
2286 ++bi) {
2287 unsigned RepNode = FindNode(*bi);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002288 // If this edge points to a non-representative node but we are
2289 // already planning to add an edge to its representative, we have no
2290 // need for this edge anymore.
Daniel Berlinaad15882007-09-16 21:45:02 +00002291 if (RepNode != *bi && NewEdges.test(RepNode)){
2292 ToErase.set(*bi);
2293 continue;
2294 }
2295
2296 // Continue about our DFS.
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002297 if (!Tarjan2Deleted[RepNode]){
2298 if (Tarjan2DFS[RepNode] == 0) {
2299 Changed |= QueryNode(RepNode);
2300 // May have been changed by QueryNode
Daniel Berlinaad15882007-09-16 21:45:02 +00002301 RepNode = FindNode(RepNode);
2302 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002303 if (Tarjan2DFS[RepNode] < Tarjan2DFS[Node])
2304 Tarjan2DFS[Node] = Tarjan2DFS[RepNode];
Daniel Berlinaad15882007-09-16 21:45:02 +00002305 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002306
2307 // We may have just discovered that this node is part of a cycle, in
2308 // which case we can also erase it.
Daniel Berlinaad15882007-09-16 21:45:02 +00002309 if (RepNode != *bi) {
2310 ToErase.set(*bi);
2311 NewEdges.set(RepNode);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002312 }
2313 }
2314
Daniel Berlinaad15882007-09-16 21:45:02 +00002315 GraphNodes[Node].Edges->intersectWithComplement(ToErase);
2316 GraphNodes[Node].Edges |= NewEdges;
2317
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002318 // If this node is a root of a non-trivial SCC, place it on our
2319 // worklist to be processed.
2320 if (OurDFS == Tarjan2DFS[Node]) {
2321 while (!SCCStack.empty() && Tarjan2DFS[SCCStack.top()] >= OurDFS) {
2322 Node = UniteNodes(Node, SCCStack.top());
Daniel Berlinaad15882007-09-16 21:45:02 +00002323
2324 SCCStack.pop();
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002325 Merged = true;
Daniel Berlinaad15882007-09-16 21:45:02 +00002326 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002327 Tarjan2Deleted[Node] = true;
Daniel Berlinaad15882007-09-16 21:45:02 +00002328
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002329 if (Merged)
2330 NextWL->insert(&GraphNodes[Node]);
Daniel Berlinaad15882007-09-16 21:45:02 +00002331 } else {
2332 SCCStack.push(Node);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002333 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002334
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002335 return(Changed | Merged);
2336}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002337
2338/// SolveConstraints - This stage iteratively processes the constraints list
2339/// propagating constraints (adding edges to the Nodes in the points-to graph)
2340/// until a fixed point is reached.
2341///
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002342/// We use a variant of the technique called "Lazy Cycle Detection", which is
2343/// described in "The Ant and the Grasshopper: Fast and Accurate Pointer
2344/// Analysis for Millions of Lines of Code. In Programming Language Design and
2345/// Implementation (PLDI), June 2007."
2346/// The paper describes performing cycle detection one node at a time, which can
2347/// be expensive if there are no cycles, but there are long chains of nodes that
2348/// it heuristically believes are cycles (because it will DFS from each node
2349/// without state from previous nodes).
2350/// Instead, we use the heuristic to build a worklist of nodes to check, then
2351/// cycle detect them all at the same time to do this more cheaply. This
2352/// catches cycles slightly later than the original technique did, but does it
2353/// make significantly cheaper.
2354
Chris Lattnere995a2a2004-05-23 21:00:47 +00002355void Andersens::SolveConstraints() {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002356 CurrWL = &w1;
2357 NextWL = &w2;
Daniel Berlinaad15882007-09-16 21:45:02 +00002358
Daniel Berlind81ccc22007-09-24 19:45:49 +00002359 OptimizeConstraints();
2360#undef DEBUG_TYPE
2361#define DEBUG_TYPE "anders-aa-constraints"
2362 DEBUG(PrintConstraints());
2363#undef DEBUG_TYPE
2364#define DEBUG_TYPE "anders-aa"
2365
Daniel Berlinaad15882007-09-16 21:45:02 +00002366 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2367 Node *N = &GraphNodes[i];
2368 N->PointsTo = new SparseBitVector<>;
2369 N->OldPointsTo = new SparseBitVector<>;
2370 N->Edges = new SparseBitVector<>;
2371 }
2372 CreateConstraintGraph();
Daniel Berlind81ccc22007-09-24 19:45:49 +00002373 UnitePointerEquivalences();
2374 assert(SCCStack.empty() && "SCC Stack should be empty by now!");
Daniel Berlind81ccc22007-09-24 19:45:49 +00002375 Node2DFS.clear();
2376 Node2Deleted.clear();
Daniel Berlinaad15882007-09-16 21:45:02 +00002377 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2378 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2379 DFSNumber = 0;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002380 DenseSet<Constraint, ConstraintKeyInfo> Seen;
2381 DenseSet<std::pair<unsigned,unsigned>, PairKeyInfo> EdgesChecked;
2382
2383 // Order graph and add initial nodes to work list.
Daniel Berlinaad15882007-09-16 21:45:02 +00002384 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
Daniel Berlinaad15882007-09-16 21:45:02 +00002385 Node *INode = &GraphNodes[i];
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002386
2387 // Add to work list if it's a representative and can contribute to the
2388 // calculation right now.
2389 if (INode->isRep() && !INode->PointsTo->empty()
2390 && (!INode->Edges->empty() || !INode->Constraints.empty())) {
2391 INode->Stamp();
2392 CurrWL->insert(INode);
Daniel Berlinaad15882007-09-16 21:45:02 +00002393 }
2394 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002395 std::queue<unsigned int> TarjanWL;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002396#if !FULL_UNIVERSAL
2397 // "Rep and special variables" - in order for HCD to maintain conservative
2398 // results when !FULL_UNIVERSAL, we need to treat the special variables in
2399 // the same way that the !FULL_UNIVERSAL tweak does throughout the rest of
2400 // the analysis - it's ok to add edges from the special nodes, but never
2401 // *to* the special nodes.
2402 std::vector<unsigned int> RSV;
2403#endif
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002404 while( !CurrWL->empty() ) {
2405 DOUT << "Starting iteration #" << ++NumIters << "\n";
Daniel Berlinaad15882007-09-16 21:45:02 +00002406
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002407 Node* CurrNode;
2408 unsigned CurrNodeIndex;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002409
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002410 // Actual cycle checking code. We cycle check all of the lazy cycle
2411 // candidates from the last iteration in one go.
2412 if (!TarjanWL.empty()) {
2413 DFSNumber = 0;
2414
2415 Tarjan2DFS.clear();
2416 Tarjan2Deleted.clear();
2417 while (!TarjanWL.empty()) {
2418 unsigned int ToTarjan = TarjanWL.front();
2419 TarjanWL.pop();
2420 if (!Tarjan2Deleted[ToTarjan]
2421 && GraphNodes[ToTarjan].isRep()
2422 && Tarjan2DFS[ToTarjan] == 0)
2423 QueryNode(ToTarjan);
2424 }
2425 }
2426
2427 // Add to work list if it's a representative and can contribute to the
2428 // calculation right now.
2429 while( (CurrNode = CurrWL->pop()) != NULL ) {
2430 CurrNodeIndex = CurrNode - &GraphNodes[0];
2431 CurrNode->Stamp();
2432
2433
Daniel Berlinaad15882007-09-16 21:45:02 +00002434 // Figure out the changed points to bits
2435 SparseBitVector<> CurrPointsTo;
2436 CurrPointsTo.intersectWithComplement(CurrNode->PointsTo,
2437 CurrNode->OldPointsTo);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002438 if (CurrPointsTo.empty())
Daniel Berlinaad15882007-09-16 21:45:02 +00002439 continue;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002440
Daniel Berlinaad15882007-09-16 21:45:02 +00002441 *(CurrNode->OldPointsTo) |= CurrPointsTo;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002442
2443 // Check the offline-computed equivalencies from HCD.
2444 bool SCC = false;
2445 unsigned Rep;
2446
2447 if (SDT[CurrNodeIndex] >= 0) {
2448 SCC = true;
2449 Rep = FindNode(SDT[CurrNodeIndex]);
2450
2451#if !FULL_UNIVERSAL
2452 RSV.clear();
2453#endif
2454 for (SparseBitVector<>::iterator bi = CurrPointsTo.begin();
2455 bi != CurrPointsTo.end(); ++bi) {
2456 unsigned Node = FindNode(*bi);
2457#if !FULL_UNIVERSAL
2458 if (Node < NumberSpecialNodes) {
2459 RSV.push_back(Node);
2460 continue;
2461 }
2462#endif
2463 Rep = UniteNodes(Rep,Node);
2464 }
2465#if !FULL_UNIVERSAL
2466 RSV.push_back(Rep);
2467#endif
2468
2469 NextWL->insert(&GraphNodes[Rep]);
2470
2471 if ( ! CurrNode->isRep() )
2472 continue;
2473 }
2474
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002475 Seen.clear();
Chris Lattnere995a2a2004-05-23 21:00:47 +00002476
Daniel Berlinaad15882007-09-16 21:45:02 +00002477 /* Now process the constraints for this node. */
2478 for (std::list<Constraint>::iterator li = CurrNode->Constraints.begin();
2479 li != CurrNode->Constraints.end(); ) {
2480 li->Src = FindNode(li->Src);
2481 li->Dest = FindNode(li->Dest);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002482
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002483 // Delete redundant constraints
2484 if( Seen.count(*li) ) {
2485 std::list<Constraint>::iterator lk = li; li++;
2486
2487 CurrNode->Constraints.erase(lk);
2488 ++NumErased;
2489 continue;
2490 }
2491 Seen.insert(*li);
2492
Daniel Berlinaad15882007-09-16 21:45:02 +00002493 // Src and Dest will be the vars we are going to process.
2494 // This may look a bit ugly, but what it does is allow us to process
Daniel Berlind81ccc22007-09-24 19:45:49 +00002495 // both store and load constraints with the same code.
Daniel Berlinaad15882007-09-16 21:45:02 +00002496 // Load constraints say that every member of our RHS solution has K
2497 // added to it, and that variable gets an edge to LHS. We also union
2498 // RHS+K's solution into the LHS solution.
2499 // Store constraints say that every member of our LHS solution has K
2500 // added to it, and that variable gets an edge from RHS. We also union
2501 // RHS's solution into the LHS+K solution.
2502 unsigned *Src;
2503 unsigned *Dest;
2504 unsigned K = li->Offset;
2505 unsigned CurrMember;
2506 if (li->Type == Constraint::Load) {
2507 Src = &CurrMember;
2508 Dest = &li->Dest;
2509 } else if (li->Type == Constraint::Store) {
2510 Src = &li->Src;
2511 Dest = &CurrMember;
2512 } else {
2513 // TODO Handle offseted copy constraint
2514 li++;
2515 continue;
2516 }
Daniel Berlinc864edb2008-03-05 19:31:47 +00002517
2518 // See if we can use Hybrid Cycle Detection (that is, check
Daniel Berlinaad15882007-09-16 21:45:02 +00002519 // if it was a statically detected offline equivalence that
Daniel Berlinc864edb2008-03-05 19:31:47 +00002520 // involves pointers; if so, remove the redundant constraints).
2521 if( SCC && K == 0 ) {
2522#if FULL_UNIVERSAL
2523 CurrMember = Rep;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002524
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002525 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2526 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2527 NextWL->insert(&GraphNodes[*Dest]);
Daniel Berlinc864edb2008-03-05 19:31:47 +00002528#else
2529 for (unsigned i=0; i < RSV.size(); ++i) {
2530 CurrMember = RSV[i];
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002531
Daniel Berlinc864edb2008-03-05 19:31:47 +00002532 if (*Dest < NumberSpecialNodes)
2533 continue;
2534 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2535 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2536 NextWL->insert(&GraphNodes[*Dest]);
2537 }
2538#endif
2539 // since all future elements of the points-to set will be
2540 // equivalent to the current ones, the complex constraints
2541 // become redundant.
2542 //
2543 std::list<Constraint>::iterator lk = li; li++;
2544#if !FULL_UNIVERSAL
2545 // In this case, we can still erase the constraints when the
2546 // elements of the points-to sets are referenced by *Dest,
2547 // but not when they are referenced by *Src (i.e. for a Load
2548 // constraint). This is because if another special variable is
2549 // put into the points-to set later, we still need to add the
2550 // new edge from that special variable.
2551 if( lk->Type != Constraint::Load)
2552#endif
2553 GraphNodes[CurrNodeIndex].Constraints.erase(lk);
2554 } else {
2555 const SparseBitVector<> &Solution = CurrPointsTo;
2556
2557 for (SparseBitVector<>::iterator bi = Solution.begin();
2558 bi != Solution.end();
2559 ++bi) {
2560 CurrMember = *bi;
2561
2562 // Need to increment the member by K since that is where we are
2563 // supposed to copy to/from. Note that in positive weight cycles,
2564 // which occur in address taking of fields, K can go past
2565 // MaxK[CurrMember] elements, even though that is all it could point
2566 // to.
2567 if (K > 0 && K > MaxK[CurrMember])
2568 continue;
2569 else
2570 CurrMember = FindNode(CurrMember + K);
2571
2572 // Add an edge to the graph, so we can just do regular
2573 // bitmap ior next time. It may also let us notice a cycle.
2574#if !FULL_UNIVERSAL
2575 if (*Dest < NumberSpecialNodes)
2576 continue;
2577#endif
2578 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2579 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2580 NextWL->insert(&GraphNodes[*Dest]);
2581
2582 }
2583 li++;
Daniel Berlinaad15882007-09-16 21:45:02 +00002584 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002585 }
2586 SparseBitVector<> NewEdges;
2587 SparseBitVector<> ToErase;
2588
2589 // Now all we have left to do is propagate points-to info along the
2590 // edges, erasing the redundant edges.
Daniel Berlinaad15882007-09-16 21:45:02 +00002591 for (SparseBitVector<>::iterator bi = CurrNode->Edges->begin();
2592 bi != CurrNode->Edges->end();
2593 ++bi) {
2594
2595 unsigned DestVar = *bi;
2596 unsigned Rep = FindNode(DestVar);
2597
Bill Wendlingf059deb2008-02-26 10:51:52 +00002598 // If we ended up with this node as our destination, or we've already
2599 // got an edge for the representative, delete the current edge.
2600 if (Rep == CurrNodeIndex ||
2601 (Rep != DestVar && NewEdges.test(Rep))) {
Daniel Berlinc864edb2008-03-05 19:31:47 +00002602 ToErase.set(DestVar);
2603 continue;
Bill Wendlingf059deb2008-02-26 10:51:52 +00002604 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002605
Bill Wendlingf059deb2008-02-26 10:51:52 +00002606 std::pair<unsigned,unsigned> edge(CurrNodeIndex,Rep);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002607
2608 // This is where we do lazy cycle detection.
2609 // If this is a cycle candidate (equal points-to sets and this
2610 // particular edge has not been cycle-checked previously), add to the
2611 // list to check for cycles on the next iteration.
2612 if (!EdgesChecked.count(edge) &&
2613 *(GraphNodes[Rep].PointsTo) == *(CurrNode->PointsTo)) {
2614 EdgesChecked.insert(edge);
2615 TarjanWL.push(Rep);
Daniel Berlinaad15882007-09-16 21:45:02 +00002616 }
2617 // Union the points-to sets into the dest
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002618#if !FULL_UNIVERSAL
2619 if (Rep >= NumberSpecialNodes)
2620#endif
Daniel Berlinaad15882007-09-16 21:45:02 +00002621 if (GraphNodes[Rep].PointsTo |= CurrPointsTo) {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002622 NextWL->insert(&GraphNodes[Rep]);
Daniel Berlinaad15882007-09-16 21:45:02 +00002623 }
2624 // If this edge's destination was collapsed, rewrite the edge.
2625 if (Rep != DestVar) {
2626 ToErase.set(DestVar);
2627 NewEdges.set(Rep);
2628 }
2629 }
2630 CurrNode->Edges->intersectWithComplement(ToErase);
2631 CurrNode->Edges |= NewEdges;
2632 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002633
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002634 // Switch to other work list.
2635 WorkList* t = CurrWL; CurrWL = NextWL; NextWL = t;
2636 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002637
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002638
Daniel Berlinaad15882007-09-16 21:45:02 +00002639 Node2DFS.clear();
2640 Node2Deleted.clear();
2641 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2642 Node *N = &GraphNodes[i];
2643 delete N->OldPointsTo;
2644 delete N->Edges;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002645 }
Daniel Berlinc864edb2008-03-05 19:31:47 +00002646 SDTActive = false;
2647 SDT.clear();
Chris Lattnere995a2a2004-05-23 21:00:47 +00002648}
2649
Daniel Berlinaad15882007-09-16 21:45:02 +00002650//===----------------------------------------------------------------------===//
2651// Union-Find
2652//===----------------------------------------------------------------------===//
Chris Lattnere995a2a2004-05-23 21:00:47 +00002653
Daniel Berlinaad15882007-09-16 21:45:02 +00002654// Unite nodes First and Second, returning the one which is now the
2655// representative node. First and Second are indexes into GraphNodes
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002656unsigned Andersens::UniteNodes(unsigned First, unsigned Second,
2657 bool UnionByRank) {
Daniel Berlinaad15882007-09-16 21:45:02 +00002658 assert (First < GraphNodes.size() && Second < GraphNodes.size() &&
2659 "Attempting to merge nodes that don't exist");
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002660
Daniel Berlinaad15882007-09-16 21:45:02 +00002661 Node *FirstNode = &GraphNodes[First];
2662 Node *SecondNode = &GraphNodes[Second];
2663
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002664 assert (SecondNode->isRep() && FirstNode->isRep() &&
Daniel Berlinaad15882007-09-16 21:45:02 +00002665 "Trying to unite two non-representative nodes!");
2666 if (First == Second)
2667 return First;
2668
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002669 if (UnionByRank) {
2670 int RankFirst = (int) FirstNode ->NodeRep;
2671 int RankSecond = (int) SecondNode->NodeRep;
2672
2673 // Rank starts at -1 and gets decremented as it increases.
2674 // Translation: higher rank, lower NodeRep value, which is always negative.
2675 if (RankFirst > RankSecond) {
2676 unsigned t = First; First = Second; Second = t;
2677 Node* tp = FirstNode; FirstNode = SecondNode; SecondNode = tp;
2678 } else if (RankFirst == RankSecond) {
2679 FirstNode->NodeRep = (unsigned) (RankFirst - 1);
2680 }
2681 }
2682
Daniel Berlinaad15882007-09-16 21:45:02 +00002683 SecondNode->NodeRep = First;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002684#if !FULL_UNIVERSAL
2685 if (First >= NumberSpecialNodes)
2686#endif
Daniel Berlind81ccc22007-09-24 19:45:49 +00002687 if (FirstNode->PointsTo && SecondNode->PointsTo)
2688 FirstNode->PointsTo |= *(SecondNode->PointsTo);
2689 if (FirstNode->Edges && SecondNode->Edges)
2690 FirstNode->Edges |= *(SecondNode->Edges);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002691 if (!SecondNode->Constraints.empty())
Daniel Berlind81ccc22007-09-24 19:45:49 +00002692 FirstNode->Constraints.splice(FirstNode->Constraints.begin(),
2693 SecondNode->Constraints);
2694 if (FirstNode->OldPointsTo) {
2695 delete FirstNode->OldPointsTo;
2696 FirstNode->OldPointsTo = new SparseBitVector<>;
2697 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002698
2699 // Destroy interesting parts of the merged-from node.
2700 delete SecondNode->OldPointsTo;
2701 delete SecondNode->Edges;
2702 delete SecondNode->PointsTo;
2703 SecondNode->Edges = NULL;
2704 SecondNode->PointsTo = NULL;
2705 SecondNode->OldPointsTo = NULL;
2706
2707 NumUnified++;
2708 DOUT << "Unified Node ";
2709 DEBUG(PrintNode(FirstNode));
2710 DOUT << " and Node ";
2711 DEBUG(PrintNode(SecondNode));
2712 DOUT << "\n";
2713
Daniel Berlinc864edb2008-03-05 19:31:47 +00002714 if (SDTActive)
2715 if (SDT[Second] >= 0)
2716 if (SDT[First] < 0)
2717 SDT[First] = SDT[Second];
2718 else {
2719 UniteNodes( FindNode(SDT[First]), FindNode(SDT[Second]) );
2720 First = FindNode(First);
2721 }
2722
Daniel Berlinaad15882007-09-16 21:45:02 +00002723 return First;
2724}
2725
2726// Find the index into GraphNodes of the node representing Node, performing
2727// path compression along the way
2728unsigned Andersens::FindNode(unsigned NodeIndex) {
2729 assert (NodeIndex < GraphNodes.size()
2730 && "Attempting to find a node that can't exist");
2731 Node *N = &GraphNodes[NodeIndex];
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002732 if (N->isRep())
Daniel Berlinaad15882007-09-16 21:45:02 +00002733 return NodeIndex;
2734 else
2735 return (N->NodeRep = FindNode(N->NodeRep));
2736}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002737
2738//===----------------------------------------------------------------------===//
2739// Debugging Output
2740//===----------------------------------------------------------------------===//
2741
2742void Andersens::PrintNode(Node *N) {
2743 if (N == &GraphNodes[UniversalSet]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002744 cerr << "<universal>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002745 return;
2746 } else if (N == &GraphNodes[NullPtr]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002747 cerr << "<nullptr>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002748 return;
2749 } else if (N == &GraphNodes[NullObject]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002750 cerr << "<null>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002751 return;
2752 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002753 if (!N->getValue()) {
2754 cerr << "artificial" << (intptr_t) N;
2755 return;
2756 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002757
2758 assert(N->getValue() != 0 && "Never set node label!");
2759 Value *V = N->getValue();
2760 if (Function *F = dyn_cast<Function>(V)) {
2761 if (isa<PointerType>(F->getFunctionType()->getReturnType()) &&
Daniel Berlinaad15882007-09-16 21:45:02 +00002762 N == &GraphNodes[getReturnNode(F)]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002763 cerr << F->getName() << ":retval";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002764 return;
Daniel Berlinaad15882007-09-16 21:45:02 +00002765 } else if (F->getFunctionType()->isVarArg() &&
2766 N == &GraphNodes[getVarargNode(F)]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002767 cerr << F->getName() << ":vararg";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002768 return;
2769 }
2770 }
2771
2772 if (Instruction *I = dyn_cast<Instruction>(V))
Bill Wendlinge8156192006-12-07 01:30:32 +00002773 cerr << I->getParent()->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002774 else if (Argument *Arg = dyn_cast<Argument>(V))
Bill Wendlinge8156192006-12-07 01:30:32 +00002775 cerr << Arg->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002776
2777 if (V->hasName())
Bill Wendlinge8156192006-12-07 01:30:32 +00002778 cerr << V->getName();
Chris Lattnere995a2a2004-05-23 21:00:47 +00002779 else
Bill Wendlinge8156192006-12-07 01:30:32 +00002780 cerr << "(unnamed)";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002781
2782 if (isa<GlobalValue>(V) || isa<AllocationInst>(V))
Daniel Berlinaad15882007-09-16 21:45:02 +00002783 if (N == &GraphNodes[getObject(V)])
Bill Wendlinge8156192006-12-07 01:30:32 +00002784 cerr << "<mem>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002785}
Daniel Berlind81ccc22007-09-24 19:45:49 +00002786void Andersens::PrintConstraint(const Constraint &C) {
2787 if (C.Type == Constraint::Store) {
2788 cerr << "*";
2789 if (C.Offset != 0)
2790 cerr << "(";
2791 }
2792 PrintNode(&GraphNodes[C.Dest]);
2793 if (C.Type == Constraint::Store && C.Offset != 0)
2794 cerr << " + " << C.Offset << ")";
2795 cerr << " = ";
2796 if (C.Type == Constraint::Load) {
2797 cerr << "*";
2798 if (C.Offset != 0)
2799 cerr << "(";
2800 }
2801 else if (C.Type == Constraint::AddressOf)
2802 cerr << "&";
2803 PrintNode(&GraphNodes[C.Src]);
2804 if (C.Offset != 0 && C.Type != Constraint::Store)
2805 cerr << " + " << C.Offset;
2806 if (C.Type == Constraint::Load && C.Offset != 0)
2807 cerr << ")";
2808 cerr << "\n";
2809}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002810
2811void Andersens::PrintConstraints() {
Bill Wendlinge8156192006-12-07 01:30:32 +00002812 cerr << "Constraints:\n";
Daniel Berlinaad15882007-09-16 21:45:02 +00002813
Daniel Berlind81ccc22007-09-24 19:45:49 +00002814 for (unsigned i = 0, e = Constraints.size(); i != e; ++i)
2815 PrintConstraint(Constraints[i]);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002816}
2817
2818void Andersens::PrintPointsToGraph() {
Bill Wendlinge8156192006-12-07 01:30:32 +00002819 cerr << "Points-to graph:\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002820 for (unsigned i = 0, e = GraphNodes.size(); i != e; ++i) {
2821 Node *N = &GraphNodes[i];
Daniel Berlinaad15882007-09-16 21:45:02 +00002822 if (FindNode (i) != i) {
2823 PrintNode(N);
2824 cerr << "\t--> same as ";
2825 PrintNode(&GraphNodes[FindNode(i)]);
2826 cerr << "\n";
2827 } else {
2828 cerr << "[" << (N->PointsTo->count()) << "] ";
2829 PrintNode(N);
2830 cerr << "\t--> ";
2831
2832 bool first = true;
2833 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
2834 bi != N->PointsTo->end();
2835 ++bi) {
2836 if (!first)
2837 cerr << ", ";
2838 PrintNode(&GraphNodes[*bi]);
2839 first = false;
2840 }
2841 cerr << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002842 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002843 }
2844}