blob: a66a6faf1c5dc209e049dcf32f3e19259eb1f437 [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;
433 Andersens() : ModulePass((intptr_t)&ID) {}
434
Devang Patel1cee94f2008-03-18 00:39:19 +0000435 /// isAnalysis - Return true if this pass is implementing an analysis pass.
436 virtual bool isAnalysis() const { return true; }
437
Chris Lattnerb12914b2004-09-20 04:48:05 +0000438 bool runOnModule(Module &M) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000439 InitializeAliasAnalysis(this);
440 IdentifyObjects(M);
441 CollectConstraints(M);
Daniel Berlind81ccc22007-09-24 19:45:49 +0000442#undef DEBUG_TYPE
443#define DEBUG_TYPE "anders-aa-constraints"
Chris Lattnere995a2a2004-05-23 21:00:47 +0000444 DEBUG(PrintConstraints());
Daniel Berlind81ccc22007-09-24 19:45:49 +0000445#undef DEBUG_TYPE
446#define DEBUG_TYPE "anders-aa"
Chris Lattnere995a2a2004-05-23 21:00:47 +0000447 SolveConstraints();
448 DEBUG(PrintPointsToGraph());
449
450 // Free the constraints list, as we don't need it to respond to alias
451 // requests.
452 ObjectNodes.clear();
453 ReturnNodes.clear();
454 VarargNodes.clear();
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000455 std::vector<Constraint>().swap(Constraints);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000456 return false;
457 }
458
459 void releaseMemory() {
460 // FIXME: Until we have transitively required passes working correctly,
461 // this cannot be enabled! Otherwise, using -count-aa with the pass
462 // causes memory to be freed too early. :(
463#if 0
464 // The memory objects and ValueNodes data structures at the only ones that
465 // are still live after construction.
466 std::vector<Node>().swap(GraphNodes);
467 ValueNodes.clear();
468#endif
469 }
470
471 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
472 AliasAnalysis::getAnalysisUsage(AU);
473 AU.setPreservesAll(); // Does not transform code
474 }
475
476 //------------------------------------------------
477 // Implement the AliasAnalysis API
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000478 //
Chris Lattnere995a2a2004-05-23 21:00:47 +0000479 AliasResult alias(const Value *V1, unsigned V1Size,
480 const Value *V2, unsigned V2Size);
Reid Spencer3a9ec242006-08-28 01:02:49 +0000481 virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
482 virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000483 void getMustAliases(Value *P, std::vector<Value*> &RetVals);
484 bool pointsToConstantMemory(const Value *P);
485
486 virtual void deleteValue(Value *V) {
487 ValueNodes.erase(V);
488 getAnalysis<AliasAnalysis>().deleteValue(V);
489 }
490
491 virtual void copyValue(Value *From, Value *To) {
492 ValueNodes[To] = ValueNodes[From];
493 getAnalysis<AliasAnalysis>().copyValue(From, To);
494 }
495
496 private:
497 /// getNode - Return the node corresponding to the specified pointer scalar.
498 ///
Daniel Berlinaad15882007-09-16 21:45:02 +0000499 unsigned getNode(Value *V) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000500 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattnerdf9b7bc2004-08-16 05:38:02 +0000501 if (!isa<GlobalValue>(C))
502 return getNodeForConstantPointer(C);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000503
Daniel Berlind81ccc22007-09-24 19:45:49 +0000504 DenseMap<Value*, unsigned>::iterator I = ValueNodes.find(V);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000505 if (I == ValueNodes.end()) {
Jim Laskey16d42c62006-07-11 18:25:13 +0000506#ifndef NDEBUG
507 V->dump();
508#endif
Jim Laskeye37fe9b2006-07-11 17:58:07 +0000509 assert(0 && "Value does not have a node in the points-to graph!");
Chris Lattnere995a2a2004-05-23 21:00:47 +0000510 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000511 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000512 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000513
Chris Lattnere995a2a2004-05-23 21:00:47 +0000514 /// getObject - Return the node corresponding to the memory object for the
515 /// specified global or allocation instruction.
Daniel Berlinaad15882007-09-16 21:45:02 +0000516 unsigned getObject(Value *V) {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000517 DenseMap<Value*, unsigned>::iterator I = ObjectNodes.find(V);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000518 assert(I != ObjectNodes.end() &&
519 "Value does not have an object in the points-to graph!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000520 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000521 }
522
523 /// getReturnNode - Return the node representing the return value for the
524 /// specified function.
Daniel Berlinaad15882007-09-16 21:45:02 +0000525 unsigned getReturnNode(Function *F) {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000526 DenseMap<Function*, unsigned>::iterator I = ReturnNodes.find(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000527 assert(I != ReturnNodes.end() && "Function does not return a value!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000528 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000529 }
530
531 /// getVarargNode - Return the node representing the variable arguments
532 /// formal for the specified function.
Daniel Berlinaad15882007-09-16 21:45:02 +0000533 unsigned getVarargNode(Function *F) {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000534 DenseMap<Function*, unsigned>::iterator I = VarargNodes.find(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000535 assert(I != VarargNodes.end() && "Function does not take var args!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000536 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000537 }
538
539 /// getNodeValue - Get the node for the specified LLVM value and set the
540 /// value for it to be the specified value.
Daniel Berlinaad15882007-09-16 21:45:02 +0000541 unsigned getNodeValue(Value &V) {
542 unsigned Index = getNode(&V);
543 GraphNodes[Index].setValue(&V);
544 return Index;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000545 }
546
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000547 unsigned UniteNodes(unsigned First, unsigned Second,
548 bool UnionByRank = true);
Daniel Berlinaad15882007-09-16 21:45:02 +0000549 unsigned FindNode(unsigned Node);
550
Chris Lattnere995a2a2004-05-23 21:00:47 +0000551 void IdentifyObjects(Module &M);
552 void CollectConstraints(Module &M);
Daniel Berlinaad15882007-09-16 21:45:02 +0000553 bool AnalyzeUsesOfFunction(Value *);
554 void CreateConstraintGraph();
Daniel Berlind81ccc22007-09-24 19:45:49 +0000555 void OptimizeConstraints();
556 unsigned FindEquivalentNode(unsigned, unsigned);
557 void ClumpAddressTaken();
558 void RewriteConstraints();
559 void HU();
560 void HVN();
Daniel Berlinc864edb2008-03-05 19:31:47 +0000561 void HCD();
562 void Search(unsigned Node);
Daniel Berlind81ccc22007-09-24 19:45:49 +0000563 void UnitePointerEquivalences();
Chris Lattnere995a2a2004-05-23 21:00:47 +0000564 void SolveConstraints();
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000565 bool QueryNode(unsigned Node);
Daniel Berlind81ccc22007-09-24 19:45:49 +0000566 void Condense(unsigned Node);
567 void HUValNum(unsigned Node);
568 void HVNValNum(unsigned Node);
Daniel Berlinaad15882007-09-16 21:45:02 +0000569 unsigned getNodeForConstantPointer(Constant *C);
570 unsigned getNodeForConstantPointerTarget(Constant *C);
571 void AddGlobalInitializerConstraints(unsigned, Constant *C);
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000572
Chris Lattnere995a2a2004-05-23 21:00:47 +0000573 void AddConstraintsForNonInternalLinkage(Function *F);
574 void AddConstraintsForCall(CallSite CS, Function *F);
Chris Lattner8a446432005-03-29 06:09:07 +0000575 bool AddConstraintsForExternalCall(CallSite CS, Function *F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000576
577
578 void PrintNode(Node *N);
579 void PrintConstraints();
Daniel Berlind81ccc22007-09-24 19:45:49 +0000580 void PrintConstraint(const Constraint &);
581 void PrintLabels();
Chris Lattnere995a2a2004-05-23 21:00:47 +0000582 void PrintPointsToGraph();
583
584 //===------------------------------------------------------------------===//
585 // Instruction visitation methods for adding constraints
586 //
587 friend class InstVisitor<Andersens>;
588 void visitReturnInst(ReturnInst &RI);
589 void visitInvokeInst(InvokeInst &II) { visitCallSite(CallSite(&II)); }
590 void visitCallInst(CallInst &CI) { visitCallSite(CallSite(&CI)); }
591 void visitCallSite(CallSite CS);
592 void visitAllocationInst(AllocationInst &AI);
593 void visitLoadInst(LoadInst &LI);
594 void visitStoreInst(StoreInst &SI);
595 void visitGetElementPtrInst(GetElementPtrInst &GEP);
596 void visitPHINode(PHINode &PN);
597 void visitCastInst(CastInst &CI);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000598 void visitICmpInst(ICmpInst &ICI) {} // NOOP!
599 void visitFCmpInst(FCmpInst &ICI) {} // NOOP!
Chris Lattnere995a2a2004-05-23 21:00:47 +0000600 void visitSelectInst(SelectInst &SI);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000601 void visitVAArg(VAArgInst &I);
602 void visitInstruction(Instruction &I);
Daniel Berlinaad15882007-09-16 21:45:02 +0000603
Chris Lattnere995a2a2004-05-23 21:00:47 +0000604 };
605
Devang Patel19974732007-05-03 01:11:54 +0000606 char Andersens::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +0000607 RegisterPass<Andersens> X("anders-aa",
608 "Andersen's Interprocedural Alias Analysis");
Chris Lattnera5370172006-08-28 00:42:29 +0000609 RegisterAnalysisGroup<AliasAnalysis> Y(X);
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000610
611 // Initialize Timestamp Counter (static).
612 unsigned Andersens::Node::Counter = 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000613}
614
Jeff Cohen534927d2005-01-08 22:01:16 +0000615ModulePass *llvm::createAndersensPass() { return new Andersens(); }
616
Chris Lattnere995a2a2004-05-23 21:00:47 +0000617//===----------------------------------------------------------------------===//
618// AliasAnalysis Interface Implementation
619//===----------------------------------------------------------------------===//
620
621AliasAnalysis::AliasResult Andersens::alias(const Value *V1, unsigned V1Size,
622 const Value *V2, unsigned V2Size) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000623 Node *N1 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V1)))];
624 Node *N2 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V2)))];
Chris Lattnere995a2a2004-05-23 21:00:47 +0000625
626 // Check to see if the two pointers are known to not alias. They don't alias
627 // if their points-to sets do not intersect.
Daniel Berlinaad15882007-09-16 21:45:02 +0000628 if (!N1->intersectsIgnoring(N2, NullObject))
Chris Lattnere995a2a2004-05-23 21:00:47 +0000629 return NoAlias;
630
631 return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
632}
633
Chris Lattnerf392c642005-03-28 06:21:17 +0000634AliasAnalysis::ModRefResult
635Andersens::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
636 // The only thing useful that we can contribute for mod/ref information is
637 // when calling external function calls: if we know that memory never escapes
638 // from the program, it cannot be modified by an external call.
639 //
640 // NOTE: This is not really safe, at least not when the entire program is not
641 // available. The deal is that the external function could call back into the
642 // program and modify stuff. We ignore this technical niggle for now. This
643 // is, after all, a "research quality" implementation of Andersen's analysis.
644 if (Function *F = CS.getCalledFunction())
Reid Spencer5cbf9852007-01-30 20:08:39 +0000645 if (F->isDeclaration()) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000646 Node *N1 = &GraphNodes[FindNode(getNode(P))];
Chris Lattnerf392c642005-03-28 06:21:17 +0000647
Daniel Berlinaad15882007-09-16 21:45:02 +0000648 if (N1->PointsTo->empty())
649 return NoModRef;
Chris Lattnerf392c642005-03-28 06:21:17 +0000650
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.
653 }
654
655 return AliasAnalysis::getModRefInfo(CS, P, Size);
656}
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000657
Reid Spencer3a9ec242006-08-28 01:02:49 +0000658AliasAnalysis::ModRefResult
659Andersens::getModRefInfo(CallSite CS1, CallSite CS2) {
660 return AliasAnalysis::getModRefInfo(CS1,CS2);
661}
662
Chris Lattnere995a2a2004-05-23 21:00:47 +0000663/// getMustAlias - We can provide must alias information if we know that a
664/// pointer can only point to a specific function or the null pointer.
665/// Unfortunately we cannot determine must-alias information for global
666/// variables or any other memory memory objects because we do not track whether
667/// a pointer points to the beginning of an object or a field of it.
668void Andersens::getMustAliases(Value *P, std::vector<Value*> &RetVals) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000669 Node *N = &GraphNodes[FindNode(getNode(P))];
670 if (N->PointsTo->count() == 1) {
671 Node *Pointee = &GraphNodes[N->PointsTo->find_first()];
672 // If a function is the only object in the points-to set, then it must be
673 // the destination. Note that we can't handle global variables here,
674 // because we don't know if the pointer is actually pointing to a field of
675 // the global or to the beginning of it.
676 if (Value *V = Pointee->getValue()) {
677 if (Function *F = dyn_cast<Function>(V))
678 RetVals.push_back(F);
679 } else {
680 // If the object in the points-to set is the null object, then the null
681 // pointer is a must alias.
682 if (Pointee == &GraphNodes[NullObject])
683 RetVals.push_back(Constant::getNullValue(P->getType()));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000684 }
685 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000686 AliasAnalysis::getMustAliases(P, RetVals);
687}
688
689/// pointsToConstantMemory - If we can determine that this pointer only points
690/// to constant memory, return true. In practice, this means that if the
691/// pointer can only point to constant globals, functions, or the null pointer,
692/// return true.
693///
694bool Andersens::pointsToConstantMemory(const Value *P) {
Dan Gohman6a551e72008-02-21 17:33:24 +0000695 Node *N = &GraphNodes[FindNode(getNode(const_cast<Value*>(P)))];
Daniel Berlinaad15882007-09-16 21:45:02 +0000696 unsigned i;
697
698 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
699 bi != N->PointsTo->end();
700 ++bi) {
701 i = *bi;
702 Node *Pointee = &GraphNodes[i];
703 if (Value *V = Pointee->getValue()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000704 if (!isa<GlobalValue>(V) || (isa<GlobalVariable>(V) &&
705 !cast<GlobalVariable>(V)->isConstant()))
706 return AliasAnalysis::pointsToConstantMemory(P);
707 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +0000708 if (i != NullObject)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000709 return AliasAnalysis::pointsToConstantMemory(P);
710 }
711 }
712
713 return true;
714}
715
716//===----------------------------------------------------------------------===//
717// Object Identification Phase
718//===----------------------------------------------------------------------===//
719
720/// IdentifyObjects - This stage scans the program, adding an entry to the
721/// GraphNodes list for each memory object in the program (global stack or
722/// heap), and populates the ValueNodes and ObjectNodes maps for these objects.
723///
724void Andersens::IdentifyObjects(Module &M) {
725 unsigned NumObjects = 0;
726
727 // Object #0 is always the universal set: the object that we don't know
728 // anything about.
729 assert(NumObjects == UniversalSet && "Something changed!");
730 ++NumObjects;
731
732 // Object #1 always represents the null pointer.
733 assert(NumObjects == NullPtr && "Something changed!");
734 ++NumObjects;
735
736 // Object #2 always represents the null object (the object pointed to by null)
737 assert(NumObjects == NullObject && "Something changed!");
738 ++NumObjects;
739
740 // Add all the globals first.
Chris Lattner493f6362005-03-27 22:03:46 +0000741 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
742 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000743 ObjectNodes[I] = NumObjects++;
744 ValueNodes[I] = NumObjects++;
745 }
746
747 // Add nodes for all of the functions and the instructions inside of them.
748 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
749 // The function itself is a memory object.
Daniel Berlinaad15882007-09-16 21:45:02 +0000750 unsigned First = NumObjects;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000751 ValueNodes[F] = NumObjects++;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000752 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
753 ReturnNodes[F] = NumObjects++;
754 if (F->getFunctionType()->isVarArg())
755 VarargNodes[F] = NumObjects++;
756
Daniel Berlinaad15882007-09-16 21:45:02 +0000757
Chris Lattnere995a2a2004-05-23 21:00:47 +0000758 // Add nodes for all of the incoming pointer arguments.
Chris Lattner493f6362005-03-27 22:03:46 +0000759 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
760 I != E; ++I)
Daniel Berlind81ccc22007-09-24 19:45:49 +0000761 {
762 if (isa<PointerType>(I->getType()))
763 ValueNodes[I] = NumObjects++;
764 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000765 MaxK[First] = NumObjects - First;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000766
767 // Scan the function body, creating a memory object for each heap/stack
768 // allocation in the body of the function and a node to represent all
769 // pointer values defined by instructions and used as operands.
770 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
771 // If this is an heap or stack allocation, create a node for the memory
772 // object.
773 if (isa<PointerType>(II->getType())) {
774 ValueNodes[&*II] = NumObjects++;
775 if (AllocationInst *AI = dyn_cast<AllocationInst>(&*II))
776 ObjectNodes[AI] = NumObjects++;
777 }
Nick Lewycky4ac0e8d2007-11-22 03:07:37 +0000778
779 // Calls to inline asm need to be added as well because the callee isn't
780 // referenced anywhere else.
781 if (CallInst *CI = dyn_cast<CallInst>(&*II)) {
782 Value *Callee = CI->getCalledValue();
783 if (isa<InlineAsm>(Callee))
784 ValueNodes[Callee] = NumObjects++;
785 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000786 }
787 }
788
789 // Now that we know how many objects to create, make them all now!
790 GraphNodes.resize(NumObjects);
791 NumNodes += NumObjects;
792}
793
794//===----------------------------------------------------------------------===//
795// Constraint Identification Phase
796//===----------------------------------------------------------------------===//
797
798/// getNodeForConstantPointer - Return the node corresponding to the constant
799/// pointer itself.
Daniel Berlinaad15882007-09-16 21:45:02 +0000800unsigned Andersens::getNodeForConstantPointer(Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000801 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
802
Chris Lattner267a1b02005-03-27 18:58:23 +0000803 if (isa<ConstantPointerNull>(C) || isa<UndefValue>(C))
Daniel Berlinaad15882007-09-16 21:45:02 +0000804 return NullPtr;
Reid Spencere8404342004-07-18 00:18:30 +0000805 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
806 return getNode(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000807 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
808 switch (CE->getOpcode()) {
809 case Instruction::GetElementPtr:
810 return getNodeForConstantPointer(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000811 case Instruction::IntToPtr:
Daniel Berlinaad15882007-09-16 21:45:02 +0000812 return UniversalSet;
Reid Spencer3da59db2006-11-27 01:05:10 +0000813 case Instruction::BitCast:
814 return getNodeForConstantPointer(CE->getOperand(0));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000815 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000816 cerr << "Constant Expr not yet handled: " << *CE << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +0000817 assert(0);
818 }
819 } else {
820 assert(0 && "Unknown constant pointer!");
821 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000822 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000823}
824
825/// getNodeForConstantPointerTarget - Return the node POINTED TO by the
826/// specified constant pointer.
Daniel Berlinaad15882007-09-16 21:45:02 +0000827unsigned Andersens::getNodeForConstantPointerTarget(Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000828 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
829
830 if (isa<ConstantPointerNull>(C))
Daniel Berlinaad15882007-09-16 21:45:02 +0000831 return NullObject;
Reid Spencere8404342004-07-18 00:18:30 +0000832 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
833 return getObject(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000834 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
835 switch (CE->getOpcode()) {
836 case Instruction::GetElementPtr:
837 return getNodeForConstantPointerTarget(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000838 case Instruction::IntToPtr:
Daniel Berlinaad15882007-09-16 21:45:02 +0000839 return UniversalSet;
Reid Spencer3da59db2006-11-27 01:05:10 +0000840 case Instruction::BitCast:
841 return getNodeForConstantPointerTarget(CE->getOperand(0));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000842 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000843 cerr << "Constant Expr not yet handled: " << *CE << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +0000844 assert(0);
845 }
846 } else {
847 assert(0 && "Unknown constant pointer!");
848 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000849 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000850}
851
852/// AddGlobalInitializerConstraints - Add inclusion constraints for the memory
853/// object N, which contains values indicated by C.
Daniel Berlinaad15882007-09-16 21:45:02 +0000854void Andersens::AddGlobalInitializerConstraints(unsigned NodeIndex,
855 Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000856 if (C->getType()->isFirstClassType()) {
857 if (isa<PointerType>(C->getType()))
Daniel Berlinaad15882007-09-16 21:45:02 +0000858 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
859 getNodeForConstantPointer(C)));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000860 } else if (C->isNullValue()) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000861 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
862 NullObject));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000863 return;
Chris Lattner8a446432005-03-29 06:09:07 +0000864 } else if (!isa<UndefValue>(C)) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000865 // If this is an array or struct, include constraints for each element.
866 assert(isa<ConstantArray>(C) || isa<ConstantStruct>(C));
867 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
Daniel Berlinaad15882007-09-16 21:45:02 +0000868 AddGlobalInitializerConstraints(NodeIndex,
869 cast<Constant>(C->getOperand(i)));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000870 }
871}
872
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000873/// AddConstraintsForNonInternalLinkage - If this function does not have
874/// internal linkage, realize that we can't trust anything passed into or
875/// returned by this function.
Chris Lattnere995a2a2004-05-23 21:00:47 +0000876void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
Chris Lattnere4d5c442005-03-15 04:54:21 +0000877 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000878 if (isa<PointerType>(I->getType()))
879 // If this is an argument of an externally accessible function, the
880 // incoming pointer might point to anything.
881 Constraints.push_back(Constraint(Constraint::Copy, getNode(I),
Daniel Berlinaad15882007-09-16 21:45:02 +0000882 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000883}
884
Chris Lattner8a446432005-03-29 06:09:07 +0000885/// AddConstraintsForCall - If this is a call to a "known" function, add the
886/// constraints and return true. If this is a call to an unknown function,
887/// return false.
888bool Andersens::AddConstraintsForExternalCall(CallSite CS, Function *F) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000889 assert(F->isDeclaration() && "Not an external function!");
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000890
891 // These functions don't induce any points-to constraints.
Chris Lattner175b9632005-03-29 20:36:05 +0000892 if (F->getName() == "atoi" || F->getName() == "atof" ||
893 F->getName() == "atol" || F->getName() == "atoll" ||
894 F->getName() == "remove" || F->getName() == "unlink" ||
895 F->getName() == "rename" || F->getName() == "memcmp" ||
Chris Lattner01ac91e2006-03-03 01:21:36 +0000896 F->getName() == "llvm.memset.i32" ||
897 F->getName() == "llvm.memset.i64" ||
Chris Lattner175b9632005-03-29 20:36:05 +0000898 F->getName() == "strcmp" || F->getName() == "strncmp" ||
899 F->getName() == "execl" || F->getName() == "execlp" ||
900 F->getName() == "execle" || F->getName() == "execv" ||
901 F->getName() == "execvp" || F->getName() == "chmod" ||
902 F->getName() == "puts" || F->getName() == "write" ||
903 F->getName() == "open" || F->getName() == "create" ||
904 F->getName() == "truncate" || F->getName() == "chdir" ||
905 F->getName() == "mkdir" || F->getName() == "rmdir" ||
906 F->getName() == "read" || F->getName() == "pipe" ||
907 F->getName() == "wait" || F->getName() == "time" ||
908 F->getName() == "stat" || F->getName() == "fstat" ||
909 F->getName() == "lstat" || F->getName() == "strtod" ||
910 F->getName() == "strtof" || F->getName() == "strtold" ||
911 F->getName() == "fopen" || F->getName() == "fdopen" ||
912 F->getName() == "freopen" ||
913 F->getName() == "fflush" || F->getName() == "feof" ||
914 F->getName() == "fileno" || F->getName() == "clearerr" ||
915 F->getName() == "rewind" || F->getName() == "ftell" ||
916 F->getName() == "ferror" || F->getName() == "fgetc" ||
917 F->getName() == "fgetc" || F->getName() == "_IO_getc" ||
918 F->getName() == "fwrite" || F->getName() == "fread" ||
919 F->getName() == "fgets" || F->getName() == "ungetc" ||
920 F->getName() == "fputc" ||
921 F->getName() == "fputs" || F->getName() == "putc" ||
922 F->getName() == "ftell" || F->getName() == "rewind" ||
923 F->getName() == "_IO_putc" || F->getName() == "fseek" ||
924 F->getName() == "fgetpos" || F->getName() == "fsetpos" ||
925 F->getName() == "printf" || F->getName() == "fprintf" ||
926 F->getName() == "sprintf" || F->getName() == "vprintf" ||
927 F->getName() == "vfprintf" || F->getName() == "vsprintf" ||
928 F->getName() == "scanf" || F->getName() == "fscanf" ||
929 F->getName() == "sscanf" || F->getName() == "__assert_fail" ||
930 F->getName() == "modf")
Chris Lattner8a446432005-03-29 06:09:07 +0000931 return true;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000932
Chris Lattner175b9632005-03-29 20:36:05 +0000933
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000934 // These functions do induce points-to edges.
Daniel Berlinaad15882007-09-16 21:45:02 +0000935 if (F->getName() == "llvm.memcpy.i32" || F->getName() == "llvm.memcpy.i64" ||
Chris Lattner01ac91e2006-03-03 01:21:36 +0000936 F->getName() == "llvm.memmove.i32" ||F->getName() == "llvm.memmove.i64" ||
Chris Lattner4de57fd2005-03-29 06:52:20 +0000937 F->getName() == "memmove") {
Daniel Berlinaad15882007-09-16 21:45:02 +0000938
939 // *Dest = *Src, which requires an artificial graph node to represent the
940 // constraint. It is broken up into *Dest = temp, temp = *Src
941 unsigned FirstArg = getNode(CS.getArgument(0));
942 unsigned SecondArg = getNode(CS.getArgument(1));
943 unsigned TempArg = GraphNodes.size();
944 GraphNodes.push_back(Node());
945 Constraints.push_back(Constraint(Constraint::Store,
946 FirstArg, TempArg));
947 Constraints.push_back(Constraint(Constraint::Load,
948 TempArg, SecondArg));
Chris Lattner8a446432005-03-29 06:09:07 +0000949 return true;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000950 }
951
Chris Lattner77b50562005-03-29 20:04:24 +0000952 // Result = Arg0
953 if (F->getName() == "realloc" || F->getName() == "strchr" ||
954 F->getName() == "strrchr" || F->getName() == "strstr" ||
955 F->getName() == "strtok") {
Chris Lattner8a446432005-03-29 06:09:07 +0000956 Constraints.push_back(Constraint(Constraint::Copy,
957 getNode(CS.getInstruction()),
958 getNode(CS.getArgument(0))));
959 return true;
960 }
961
962 return false;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000963}
964
965
Chris Lattnere995a2a2004-05-23 21:00:47 +0000966
Daniel Berlinaad15882007-09-16 21:45:02 +0000967/// AnalyzeUsesOfFunction - Look at all of the users of the specified function.
968/// If this is used by anything complex (i.e., the address escapes), return
969/// true.
970bool Andersens::AnalyzeUsesOfFunction(Value *V) {
971
972 if (!isa<PointerType>(V->getType())) return true;
973
974 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
975 if (dyn_cast<LoadInst>(*UI)) {
976 return false;
977 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
978 if (V == SI->getOperand(1)) {
979 return false;
980 } else if (SI->getOperand(1)) {
981 return true; // Storing the pointer
982 }
983 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
984 if (AnalyzeUsesOfFunction(GEP)) return true;
985 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
986 // Make sure that this is just the function being called, not that it is
987 // passing into the function.
988 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
989 if (CI->getOperand(i) == V) return true;
990 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
991 // Make sure that this is just the function being called, not that it is
992 // passing into the function.
993 for (unsigned i = 3, e = II->getNumOperands(); i != e; ++i)
994 if (II->getOperand(i) == V) return true;
995 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
996 if (CE->getOpcode() == Instruction::GetElementPtr ||
997 CE->getOpcode() == Instruction::BitCast) {
998 if (AnalyzeUsesOfFunction(CE))
999 return true;
1000 } else {
1001 return true;
1002 }
1003 } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(*UI)) {
1004 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1005 return true; // Allow comparison against null.
1006 } else if (dyn_cast<FreeInst>(*UI)) {
1007 return false;
1008 } else {
1009 return true;
1010 }
1011 return false;
1012}
1013
Chris Lattnere995a2a2004-05-23 21:00:47 +00001014/// CollectConstraints - This stage scans the program, adding a constraint to
1015/// the Constraints list for each instruction in the program that induces a
1016/// constraint, and setting up the initial points-to graph.
1017///
1018void Andersens::CollectConstraints(Module &M) {
1019 // First, the universal set points to itself.
Daniel Berlinaad15882007-09-16 21:45:02 +00001020 Constraints.push_back(Constraint(Constraint::AddressOf, UniversalSet,
1021 UniversalSet));
1022 Constraints.push_back(Constraint(Constraint::Store, UniversalSet,
1023 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001024
1025 // Next, the null pointer points to the null object.
Daniel Berlinaad15882007-09-16 21:45:02 +00001026 Constraints.push_back(Constraint(Constraint::AddressOf, NullPtr, NullObject));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001027
1028 // Next, add any constraints on global variables and their initializers.
Chris Lattner493f6362005-03-27 22:03:46 +00001029 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1030 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001031 // Associate the address of the global object as pointing to the memory for
1032 // the global: &G = <G memory>
Daniel Berlinaad15882007-09-16 21:45:02 +00001033 unsigned ObjectIndex = getObject(I);
1034 Node *Object = &GraphNodes[ObjectIndex];
Chris Lattnere995a2a2004-05-23 21:00:47 +00001035 Object->setValue(I);
Daniel Berlinaad15882007-09-16 21:45:02 +00001036 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(*I),
1037 ObjectIndex));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001038
1039 if (I->hasInitializer()) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001040 AddGlobalInitializerConstraints(ObjectIndex, I->getInitializer());
Chris Lattnere995a2a2004-05-23 21:00:47 +00001041 } else {
1042 // If it doesn't have an initializer (i.e. it's defined in another
1043 // translation unit), it points to the universal set.
Daniel Berlinaad15882007-09-16 21:45:02 +00001044 Constraints.push_back(Constraint(Constraint::Copy, ObjectIndex,
1045 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001046 }
1047 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001048
Chris Lattnere995a2a2004-05-23 21:00:47 +00001049 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001050 // Set up the return value node.
1051 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
Daniel Berlinaad15882007-09-16 21:45:02 +00001052 GraphNodes[getReturnNode(F)].setValue(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001053 if (F->getFunctionType()->isVarArg())
Daniel Berlinaad15882007-09-16 21:45:02 +00001054 GraphNodes[getVarargNode(F)].setValue(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001055
1056 // Set up incoming argument nodes.
Chris Lattner493f6362005-03-27 22:03:46 +00001057 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
1058 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +00001059 if (isa<PointerType>(I->getType()))
1060 getNodeValue(*I);
1061
Daniel Berlinaad15882007-09-16 21:45:02 +00001062 // At some point we should just add constraints for the escaping functions
1063 // at solve time, but this slows down solving. For now, we simply mark
1064 // address taken functions as escaping and treat them as external.
1065 if (!F->hasInternalLinkage() || AnalyzeUsesOfFunction(F))
Chris Lattnere995a2a2004-05-23 21:00:47 +00001066 AddConstraintsForNonInternalLinkage(F);
1067
Reid Spencer5cbf9852007-01-30 20:08:39 +00001068 if (!F->isDeclaration()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001069 // Scan the function body, creating a memory object for each heap/stack
1070 // allocation in the body of the function and a node to represent all
1071 // pointer values defined by instructions and used as operands.
1072 visit(F);
Chris Lattner8a446432005-03-29 06:09:07 +00001073 } else {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001074 // External functions that return pointers return the universal set.
1075 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
1076 Constraints.push_back(Constraint(Constraint::Copy,
1077 getReturnNode(F),
Daniel Berlinaad15882007-09-16 21:45:02 +00001078 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001079
1080 // Any pointers that are passed into the function have the universal set
1081 // stored into them.
Chris Lattner493f6362005-03-27 22:03:46 +00001082 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
1083 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +00001084 if (isa<PointerType>(I->getType())) {
1085 // Pointers passed into external functions could have anything stored
1086 // through them.
1087 Constraints.push_back(Constraint(Constraint::Store, getNode(I),
Daniel Berlinaad15882007-09-16 21:45:02 +00001088 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001089 // Memory objects passed into external function calls can have the
1090 // universal set point to them.
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001091#if FULL_UNIVERSAL
Chris Lattnere995a2a2004-05-23 21:00:47 +00001092 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001093 UniversalSet,
Chris Lattnere995a2a2004-05-23 21:00:47 +00001094 getNode(I)));
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001095#else
1096 Constraints.push_back(Constraint(Constraint::Copy,
1097 getNode(I),
1098 UniversalSet));
1099#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001100 }
1101
1102 // If this is an external varargs function, it can also store pointers
1103 // into any pointers passed through the varargs section.
1104 if (F->getFunctionType()->isVarArg())
1105 Constraints.push_back(Constraint(Constraint::Store, getVarargNode(F),
Daniel Berlinaad15882007-09-16 21:45:02 +00001106 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001107 }
1108 }
1109 NumConstraints += Constraints.size();
1110}
1111
1112
1113void Andersens::visitInstruction(Instruction &I) {
1114#ifdef NDEBUG
1115 return; // This function is just a big assert.
1116#endif
1117 if (isa<BinaryOperator>(I))
1118 return;
1119 // Most instructions don't have any effect on pointer values.
1120 switch (I.getOpcode()) {
1121 case Instruction::Br:
1122 case Instruction::Switch:
1123 case Instruction::Unwind:
Chris Lattnerc17edbd2004-10-16 18:16:19 +00001124 case Instruction::Unreachable:
Chris Lattnere995a2a2004-05-23 21:00:47 +00001125 case Instruction::Free:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001126 case Instruction::ICmp:
1127 case Instruction::FCmp:
Chris Lattnere995a2a2004-05-23 21:00:47 +00001128 return;
1129 default:
1130 // Is this something we aren't handling yet?
Bill Wendlinge8156192006-12-07 01:30:32 +00001131 cerr << "Unknown instruction: " << I;
Chris Lattnere995a2a2004-05-23 21:00:47 +00001132 abort();
1133 }
1134}
1135
1136void Andersens::visitAllocationInst(AllocationInst &AI) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001137 unsigned ObjectIndex = getObject(&AI);
1138 GraphNodes[ObjectIndex].setValue(&AI);
1139 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(AI),
1140 ObjectIndex));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001141}
1142
1143void Andersens::visitReturnInst(ReturnInst &RI) {
1144 if (RI.getNumOperands() && isa<PointerType>(RI.getOperand(0)->getType()))
1145 // return V --> <Copy/retval{F}/v>
1146 Constraints.push_back(Constraint(Constraint::Copy,
1147 getReturnNode(RI.getParent()->getParent()),
1148 getNode(RI.getOperand(0))));
1149}
1150
1151void Andersens::visitLoadInst(LoadInst &LI) {
1152 if (isa<PointerType>(LI.getType()))
1153 // P1 = load P2 --> <Load/P1/P2>
1154 Constraints.push_back(Constraint(Constraint::Load, getNodeValue(LI),
1155 getNode(LI.getOperand(0))));
1156}
1157
1158void Andersens::visitStoreInst(StoreInst &SI) {
1159 if (isa<PointerType>(SI.getOperand(0)->getType()))
1160 // store P1, P2 --> <Store/P2/P1>
1161 Constraints.push_back(Constraint(Constraint::Store,
1162 getNode(SI.getOperand(1)),
1163 getNode(SI.getOperand(0))));
1164}
1165
1166void Andersens::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1167 // P1 = getelementptr P2, ... --> <Copy/P1/P2>
1168 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(GEP),
1169 getNode(GEP.getOperand(0))));
1170}
1171
1172void Andersens::visitPHINode(PHINode &PN) {
1173 if (isa<PointerType>(PN.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001174 unsigned PNN = getNodeValue(PN);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001175 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1176 // P1 = phi P2, P3 --> <Copy/P1/P2>, <Copy/P1/P3>, ...
1177 Constraints.push_back(Constraint(Constraint::Copy, PNN,
1178 getNode(PN.getIncomingValue(i))));
1179 }
1180}
1181
1182void Andersens::visitCastInst(CastInst &CI) {
1183 Value *Op = CI.getOperand(0);
1184 if (isa<PointerType>(CI.getType())) {
1185 if (isa<PointerType>(Op->getType())) {
1186 // P1 = cast P2 --> <Copy/P1/P2>
1187 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
1188 getNode(CI.getOperand(0))));
1189 } else {
1190 // P1 = cast int --> <Copy/P1/Univ>
Chris Lattner175b9632005-03-29 20:36:05 +00001191#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +00001192 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
Daniel Berlinaad15882007-09-16 21:45:02 +00001193 UniversalSet));
Chris Lattnerbd135c72005-04-05 01:12:03 +00001194#else
1195 getNodeValue(CI);
Chris Lattner175b9632005-03-29 20:36:05 +00001196#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001197 }
1198 } else if (isa<PointerType>(Op->getType())) {
1199 // int = cast P1 --> <Copy/Univ/P1>
Chris Lattner175b9632005-03-29 20:36:05 +00001200#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +00001201 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001202 UniversalSet,
Chris Lattnere995a2a2004-05-23 21:00:47 +00001203 getNode(CI.getOperand(0))));
Chris Lattnerbd135c72005-04-05 01:12:03 +00001204#else
1205 getNode(CI.getOperand(0));
Chris Lattner175b9632005-03-29 20:36:05 +00001206#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001207 }
1208}
1209
1210void Andersens::visitSelectInst(SelectInst &SI) {
1211 if (isa<PointerType>(SI.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001212 unsigned SIN = getNodeValue(SI);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001213 // P1 = select C, P2, P3 ---> <Copy/P1/P2>, <Copy/P1/P3>
1214 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1215 getNode(SI.getOperand(1))));
1216 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1217 getNode(SI.getOperand(2))));
1218 }
1219}
1220
Chris Lattnere995a2a2004-05-23 21:00:47 +00001221void Andersens::visitVAArg(VAArgInst &I) {
1222 assert(0 && "vaarg not handled yet!");
1223}
1224
1225/// AddConstraintsForCall - Add constraints for a call with actual arguments
1226/// specified by CS to the function specified by F. Note that the types of
1227/// arguments might not match up in the case where this is an indirect call and
1228/// the function pointer has been casted. If this is the case, do something
1229/// reasonable.
1230void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001231 Value *CallValue = CS.getCalledValue();
1232 bool IsDeref = F == NULL;
1233
1234 // If this is a call to an external function, try to handle it directly to get
1235 // some taste of context sensitivity.
1236 if (F && F->isDeclaration() && AddConstraintsForExternalCall(CS, F))
Chris Lattner8a446432005-03-29 06:09:07 +00001237 return;
1238
Chris Lattnere995a2a2004-05-23 21:00:47 +00001239 if (isa<PointerType>(CS.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001240 unsigned CSN = getNode(CS.getInstruction());
1241 if (!F || isa<PointerType>(F->getFunctionType()->getReturnType())) {
1242 if (IsDeref)
1243 Constraints.push_back(Constraint(Constraint::Load, CSN,
1244 getNode(CallValue), CallReturnPos));
1245 else
1246 Constraints.push_back(Constraint(Constraint::Copy, CSN,
1247 getNode(CallValue) + CallReturnPos));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001248 } else {
1249 // If the function returns a non-pointer value, handle this just like we
1250 // treat a nonpointer cast to pointer.
1251 Constraints.push_back(Constraint(Constraint::Copy, CSN,
Daniel Berlinaad15882007-09-16 21:45:02 +00001252 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001253 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001254 } else if (F && isa<PointerType>(F->getFunctionType()->getReturnType())) {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001255#if FULL_UNIVERSAL
Chris Lattnere995a2a2004-05-23 21:00:47 +00001256 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001257 UniversalSet,
1258 getNode(CallValue) + CallReturnPos));
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001259#else
1260 Constraints.push_back(Constraint(Constraint::Copy,
1261 getNode(CallValue) + CallReturnPos,
1262 UniversalSet));
1263#endif
1264
1265
Chris Lattnere995a2a2004-05-23 21:00:47 +00001266 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001267
Chris Lattnere995a2a2004-05-23 21:00:47 +00001268 CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
Daniel Berlinaad15882007-09-16 21:45:02 +00001269 if (F) {
1270 // Direct Call
1271 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1272 for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI)
1273 if (isa<PointerType>(AI->getType())) {
1274 if (isa<PointerType>((*ArgI)->getType())) {
1275 // Copy the actual argument into the formal argument.
1276 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1277 getNode(*ArgI)));
1278 } else {
1279 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1280 UniversalSet));
1281 }
1282 } else if (isa<PointerType>((*ArgI)->getType())) {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001283#if FULL_UNIVERSAL
Daniel Berlinaad15882007-09-16 21:45:02 +00001284 Constraints.push_back(Constraint(Constraint::Copy,
1285 UniversalSet,
1286 getNode(*ArgI)));
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001287#else
1288 Constraints.push_back(Constraint(Constraint::Copy,
1289 getNode(*ArgI),
1290 UniversalSet));
1291#endif
Daniel Berlinaad15882007-09-16 21:45:02 +00001292 }
1293 } else {
1294 //Indirect Call
1295 unsigned ArgPos = CallFirstArgPos;
1296 for (; ArgI != ArgE; ++ArgI) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001297 if (isa<PointerType>((*ArgI)->getType())) {
1298 // Copy the actual argument into the formal argument.
Daniel Berlinaad15882007-09-16 21:45:02 +00001299 Constraints.push_back(Constraint(Constraint::Store,
1300 getNode(CallValue),
1301 getNode(*ArgI), ArgPos++));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001302 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +00001303 Constraints.push_back(Constraint(Constraint::Store,
1304 getNode (CallValue),
1305 UniversalSet, ArgPos++));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001306 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00001307 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001308 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00001309 // Copy all pointers passed through the varargs section to the varargs node.
Daniel Berlinaad15882007-09-16 21:45:02 +00001310 if (F && F->getFunctionType()->isVarArg())
Chris Lattnere995a2a2004-05-23 21:00:47 +00001311 for (; ArgI != ArgE; ++ArgI)
1312 if (isa<PointerType>((*ArgI)->getType()))
1313 Constraints.push_back(Constraint(Constraint::Copy, getVarargNode(F),
1314 getNode(*ArgI)));
1315 // If more arguments are passed in than we track, just drop them on the floor.
1316}
1317
1318void Andersens::visitCallSite(CallSite CS) {
1319 if (isa<PointerType>(CS.getType()))
1320 getNodeValue(*CS.getInstruction());
1321
1322 if (Function *F = CS.getCalledFunction()) {
1323 AddConstraintsForCall(CS, F);
1324 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +00001325 AddConstraintsForCall(CS, NULL);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001326 }
1327}
1328
1329//===----------------------------------------------------------------------===//
1330// Constraint Solving Phase
1331//===----------------------------------------------------------------------===//
1332
1333/// intersects - Return true if the points-to set of this node intersects
1334/// with the points-to set of the specified node.
1335bool Andersens::Node::intersects(Node *N) const {
Daniel Berlinaad15882007-09-16 21:45:02 +00001336 return PointsTo->intersects(N->PointsTo);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001337}
1338
1339/// intersectsIgnoring - Return true if the points-to set of this node
1340/// intersects with the points-to set of the specified node on any nodes
1341/// except for the specified node to ignore.
Daniel Berlinaad15882007-09-16 21:45:02 +00001342bool Andersens::Node::intersectsIgnoring(Node *N, unsigned Ignoring) const {
1343 // TODO: If we are only going to call this with the same value for Ignoring,
1344 // we should move the special values out of the points-to bitmap.
1345 bool WeHadIt = PointsTo->test(Ignoring);
1346 bool NHadIt = N->PointsTo->test(Ignoring);
1347 bool Result = false;
1348 if (WeHadIt)
1349 PointsTo->reset(Ignoring);
1350 if (NHadIt)
1351 N->PointsTo->reset(Ignoring);
1352 Result = PointsTo->intersects(N->PointsTo);
1353 if (WeHadIt)
1354 PointsTo->set(Ignoring);
1355 if (NHadIt)
1356 N->PointsTo->set(Ignoring);
1357 return Result;
Chris Lattnere995a2a2004-05-23 21:00:47 +00001358}
1359
Daniel Berlind81ccc22007-09-24 19:45:49 +00001360void dumpToDOUT(SparseBitVector<> *bitmap) {
Bill Wendlingcab5f5d2007-09-24 22:43:48 +00001361#ifndef NDEBUG
Daniel Berlind81ccc22007-09-24 19:45:49 +00001362 dump(*bitmap, DOUT);
Bill Wendlingcab5f5d2007-09-24 22:43:48 +00001363#endif
Daniel Berlind81ccc22007-09-24 19:45:49 +00001364}
1365
1366
1367/// Clump together address taken variables so that the points-to sets use up
1368/// less space and can be operated on faster.
1369
1370void Andersens::ClumpAddressTaken() {
1371#undef DEBUG_TYPE
1372#define DEBUG_TYPE "anders-aa-renumber"
1373 std::vector<unsigned> Translate;
1374 std::vector<Node> NewGraphNodes;
1375
1376 Translate.resize(GraphNodes.size());
1377 unsigned NewPos = 0;
1378
1379 for (unsigned i = 0; i < Constraints.size(); ++i) {
1380 Constraint &C = Constraints[i];
1381 if (C.Type == Constraint::AddressOf) {
1382 GraphNodes[C.Src].AddressTaken = true;
1383 }
1384 }
1385 for (unsigned i = 0; i < NumberSpecialNodes; ++i) {
1386 unsigned Pos = NewPos++;
1387 Translate[i] = Pos;
1388 NewGraphNodes.push_back(GraphNodes[i]);
1389 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1390 }
1391
1392 // I believe this ends up being faster than making two vectors and splicing
1393 // them.
1394 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1395 if (GraphNodes[i].AddressTaken) {
1396 unsigned Pos = NewPos++;
1397 Translate[i] = Pos;
1398 NewGraphNodes.push_back(GraphNodes[i]);
1399 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1400 }
1401 }
1402
1403 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1404 if (!GraphNodes[i].AddressTaken) {
1405 unsigned Pos = NewPos++;
1406 Translate[i] = Pos;
1407 NewGraphNodes.push_back(GraphNodes[i]);
1408 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1409 }
1410 }
1411
1412 for (DenseMap<Value*, unsigned>::iterator Iter = ValueNodes.begin();
1413 Iter != ValueNodes.end();
1414 ++Iter)
1415 Iter->second = Translate[Iter->second];
1416
1417 for (DenseMap<Value*, unsigned>::iterator Iter = ObjectNodes.begin();
1418 Iter != ObjectNodes.end();
1419 ++Iter)
1420 Iter->second = Translate[Iter->second];
1421
1422 for (DenseMap<Function*, unsigned>::iterator Iter = ReturnNodes.begin();
1423 Iter != ReturnNodes.end();
1424 ++Iter)
1425 Iter->second = Translate[Iter->second];
1426
1427 for (DenseMap<Function*, unsigned>::iterator Iter = VarargNodes.begin();
1428 Iter != VarargNodes.end();
1429 ++Iter)
1430 Iter->second = Translate[Iter->second];
1431
1432 for (unsigned i = 0; i < Constraints.size(); ++i) {
1433 Constraint &C = Constraints[i];
1434 C.Src = Translate[C.Src];
1435 C.Dest = Translate[C.Dest];
1436 }
1437
1438 GraphNodes.swap(NewGraphNodes);
1439#undef DEBUG_TYPE
1440#define DEBUG_TYPE "anders-aa"
1441}
1442
1443/// The technique used here is described in "Exploiting Pointer and Location
1444/// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1445/// Analysis Symposium (SAS), August 2007." It is known as the "HVN" algorithm,
1446/// and is equivalent to value numbering the collapsed constraint graph without
1447/// evaluating unions. This is used as a pre-pass to HU in order to resolve
1448/// first order pointer dereferences and speed up/reduce memory usage of HU.
1449/// Running both is equivalent to HRU without the iteration
1450/// HVN in more detail:
1451/// Imagine the set of constraints was simply straight line code with no loops
1452/// (we eliminate cycles, so there are no loops), such as:
1453/// E = &D
1454/// E = &C
1455/// E = F
1456/// F = G
1457/// G = F
1458/// Applying value numbering to this code tells us:
1459/// G == F == E
1460///
1461/// For HVN, this is as far as it goes. We assign new value numbers to every
1462/// "address node", and every "reference node".
1463/// To get the optimal result for this, we use a DFS + SCC (since all nodes in a
1464/// cycle must have the same value number since the = operation is really
1465/// inclusion, not overwrite), and value number nodes we receive points-to sets
1466/// before we value our own node.
1467/// The advantage of HU over HVN is that HU considers the inclusion property, so
1468/// that if you have
1469/// E = &D
1470/// E = &C
1471/// E = F
1472/// F = G
1473/// F = &D
1474/// G = F
1475/// HU will determine that G == F == E. HVN will not, because it cannot prove
1476/// that the points to information ends up being the same because they all
1477/// receive &D from E anyway.
1478
1479void Andersens::HVN() {
1480 DOUT << "Beginning HVN\n";
1481 // Build a predecessor graph. This is like our constraint graph with the
1482 // edges going in the opposite direction, and there are edges for all the
1483 // constraints, instead of just copy constraints. We also build implicit
1484 // edges for constraints are implied but not explicit. I.E for the constraint
1485 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1486 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1487 Constraint &C = Constraints[i];
1488 if (C.Type == Constraint::AddressOf) {
1489 GraphNodes[C.Src].AddressTaken = true;
1490 GraphNodes[C.Src].Direct = false;
1491
1492 // Dest = &src edge
1493 unsigned AdrNode = C.Src + FirstAdrNode;
1494 if (!GraphNodes[C.Dest].PredEdges)
1495 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1496 GraphNodes[C.Dest].PredEdges->set(AdrNode);
1497
1498 // *Dest = src edge
1499 unsigned RefNode = C.Dest + FirstRefNode;
1500 if (!GraphNodes[RefNode].ImplicitPredEdges)
1501 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1502 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1503 } else if (C.Type == Constraint::Load) {
1504 if (C.Offset == 0) {
1505 // dest = *src edge
1506 if (!GraphNodes[C.Dest].PredEdges)
1507 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1508 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1509 } else {
1510 GraphNodes[C.Dest].Direct = false;
1511 }
1512 } else if (C.Type == Constraint::Store) {
1513 if (C.Offset == 0) {
1514 // *dest = src edge
1515 unsigned RefNode = C.Dest + FirstRefNode;
1516 if (!GraphNodes[RefNode].PredEdges)
1517 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1518 GraphNodes[RefNode].PredEdges->set(C.Src);
1519 }
1520 } else {
1521 // Dest = Src edge and *Dest = *Src edge
1522 if (!GraphNodes[C.Dest].PredEdges)
1523 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1524 GraphNodes[C.Dest].PredEdges->set(C.Src);
1525 unsigned RefNode = C.Dest + FirstRefNode;
1526 if (!GraphNodes[RefNode].ImplicitPredEdges)
1527 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1528 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1529 }
1530 }
1531 PEClass = 1;
1532 // Do SCC finding first to condense our predecessor graph
1533 DFSNumber = 0;
1534 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1535 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1536 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1537
1538 for (unsigned i = 0; i < FirstRefNode; ++i) {
1539 unsigned Node = VSSCCRep[i];
1540 if (!Node2Visited[Node])
1541 HVNValNum(Node);
1542 }
1543 for (BitVectorMap::iterator Iter = Set2PEClass.begin();
1544 Iter != Set2PEClass.end();
1545 ++Iter)
1546 delete Iter->first;
1547 Set2PEClass.clear();
1548 Node2DFS.clear();
1549 Node2Deleted.clear();
1550 Node2Visited.clear();
1551 DOUT << "Finished HVN\n";
1552
1553}
1554
1555/// This is the workhorse of HVN value numbering. We combine SCC finding at the
1556/// same time because it's easy.
1557void Andersens::HVNValNum(unsigned NodeIndex) {
1558 unsigned MyDFS = DFSNumber++;
1559 Node *N = &GraphNodes[NodeIndex];
1560 Node2Visited[NodeIndex] = true;
1561 Node2DFS[NodeIndex] = MyDFS;
1562
1563 // First process all our explicit edges
1564 if (N->PredEdges)
1565 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1566 Iter != N->PredEdges->end();
1567 ++Iter) {
1568 unsigned j = VSSCCRep[*Iter];
1569 if (!Node2Deleted[j]) {
1570 if (!Node2Visited[j])
1571 HVNValNum(j);
1572 if (Node2DFS[NodeIndex] > Node2DFS[j])
1573 Node2DFS[NodeIndex] = Node2DFS[j];
1574 }
1575 }
1576
1577 // Now process all the implicit edges
1578 if (N->ImplicitPredEdges)
1579 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1580 Iter != N->ImplicitPredEdges->end();
1581 ++Iter) {
1582 unsigned j = VSSCCRep[*Iter];
1583 if (!Node2Deleted[j]) {
1584 if (!Node2Visited[j])
1585 HVNValNum(j);
1586 if (Node2DFS[NodeIndex] > Node2DFS[j])
1587 Node2DFS[NodeIndex] = Node2DFS[j];
1588 }
1589 }
1590
1591 // See if we found any cycles
1592 if (MyDFS == Node2DFS[NodeIndex]) {
1593 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1594 unsigned CycleNodeIndex = SCCStack.top();
1595 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1596 VSSCCRep[CycleNodeIndex] = NodeIndex;
1597 // Unify the nodes
1598 N->Direct &= CycleNode->Direct;
1599
1600 if (CycleNode->PredEdges) {
1601 if (!N->PredEdges)
1602 N->PredEdges = new SparseBitVector<>;
1603 *(N->PredEdges) |= CycleNode->PredEdges;
1604 delete CycleNode->PredEdges;
1605 CycleNode->PredEdges = NULL;
1606 }
1607 if (CycleNode->ImplicitPredEdges) {
1608 if (!N->ImplicitPredEdges)
1609 N->ImplicitPredEdges = new SparseBitVector<>;
1610 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1611 delete CycleNode->ImplicitPredEdges;
1612 CycleNode->ImplicitPredEdges = NULL;
1613 }
1614
1615 SCCStack.pop();
1616 }
1617
1618 Node2Deleted[NodeIndex] = true;
1619
1620 if (!N->Direct) {
1621 GraphNodes[NodeIndex].PointerEquivLabel = PEClass++;
1622 return;
1623 }
1624
1625 // Collect labels of successor nodes
1626 bool AllSame = true;
1627 unsigned First = ~0;
1628 SparseBitVector<> *Labels = new SparseBitVector<>;
1629 bool Used = false;
1630
1631 if (N->PredEdges)
1632 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1633 Iter != N->PredEdges->end();
1634 ++Iter) {
1635 unsigned j = VSSCCRep[*Iter];
1636 unsigned Label = GraphNodes[j].PointerEquivLabel;
1637 // Ignore labels that are equal to us or non-pointers
1638 if (j == NodeIndex || Label == 0)
1639 continue;
1640 if (First == (unsigned)~0)
1641 First = Label;
1642 else if (First != Label)
1643 AllSame = false;
1644 Labels->set(Label);
1645 }
1646
1647 // We either have a non-pointer, a copy of an existing node, or a new node.
1648 // Assign the appropriate pointer equivalence label.
1649 if (Labels->empty()) {
1650 GraphNodes[NodeIndex].PointerEquivLabel = 0;
1651 } else if (AllSame) {
1652 GraphNodes[NodeIndex].PointerEquivLabel = First;
1653 } else {
1654 GraphNodes[NodeIndex].PointerEquivLabel = Set2PEClass[Labels];
1655 if (GraphNodes[NodeIndex].PointerEquivLabel == 0) {
1656 unsigned EquivClass = PEClass++;
1657 Set2PEClass[Labels] = EquivClass;
1658 GraphNodes[NodeIndex].PointerEquivLabel = EquivClass;
1659 Used = true;
1660 }
1661 }
1662 if (!Used)
1663 delete Labels;
1664 } else {
1665 SCCStack.push(NodeIndex);
1666 }
1667}
1668
1669/// The technique used here is described in "Exploiting Pointer and Location
1670/// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1671/// Analysis Symposium (SAS), August 2007." It is known as the "HU" algorithm,
1672/// and is equivalent to value numbering the collapsed constraint graph
1673/// including evaluating unions.
1674void Andersens::HU() {
1675 DOUT << "Beginning HU\n";
1676 // Build a predecessor graph. This is like our constraint graph with the
1677 // edges going in the opposite direction, and there are edges for all the
1678 // constraints, instead of just copy constraints. We also build implicit
1679 // edges for constraints are implied but not explicit. I.E for the constraint
1680 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1681 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1682 Constraint &C = Constraints[i];
1683 if (C.Type == Constraint::AddressOf) {
1684 GraphNodes[C.Src].AddressTaken = true;
1685 GraphNodes[C.Src].Direct = false;
1686
1687 GraphNodes[C.Dest].PointsTo->set(C.Src);
1688 // *Dest = src edge
1689 unsigned RefNode = C.Dest + FirstRefNode;
1690 if (!GraphNodes[RefNode].ImplicitPredEdges)
1691 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1692 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1693 GraphNodes[C.Src].PointedToBy->set(C.Dest);
1694 } else if (C.Type == Constraint::Load) {
1695 if (C.Offset == 0) {
1696 // dest = *src edge
1697 if (!GraphNodes[C.Dest].PredEdges)
1698 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1699 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1700 } else {
1701 GraphNodes[C.Dest].Direct = false;
1702 }
1703 } else if (C.Type == Constraint::Store) {
1704 if (C.Offset == 0) {
1705 // *dest = src edge
1706 unsigned RefNode = C.Dest + FirstRefNode;
1707 if (!GraphNodes[RefNode].PredEdges)
1708 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1709 GraphNodes[RefNode].PredEdges->set(C.Src);
1710 }
1711 } else {
1712 // Dest = Src edge and *Dest = *Src edg
1713 if (!GraphNodes[C.Dest].PredEdges)
1714 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1715 GraphNodes[C.Dest].PredEdges->set(C.Src);
1716 unsigned RefNode = C.Dest + FirstRefNode;
1717 if (!GraphNodes[RefNode].ImplicitPredEdges)
1718 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1719 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1720 }
1721 }
1722 PEClass = 1;
1723 // Do SCC finding first to condense our predecessor graph
1724 DFSNumber = 0;
1725 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1726 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1727 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1728
1729 for (unsigned i = 0; i < FirstRefNode; ++i) {
1730 if (FindNode(i) == i) {
1731 unsigned Node = VSSCCRep[i];
1732 if (!Node2Visited[Node])
1733 Condense(Node);
1734 }
1735 }
1736
1737 // Reset tables for actual labeling
1738 Node2DFS.clear();
1739 Node2Visited.clear();
1740 Node2Deleted.clear();
1741 // Pre-grow our densemap so that we don't get really bad behavior
1742 Set2PEClass.resize(GraphNodes.size());
1743
1744 // Visit the condensed graph and generate pointer equivalence labels.
1745 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1746 for (unsigned i = 0; i < FirstRefNode; ++i) {
1747 if (FindNode(i) == i) {
1748 unsigned Node = VSSCCRep[i];
1749 if (!Node2Visited[Node])
1750 HUValNum(Node);
1751 }
1752 }
1753 // PEClass nodes will be deleted by the deleting of N->PointsTo in our caller.
1754 Set2PEClass.clear();
1755 DOUT << "Finished HU\n";
1756}
1757
1758
1759/// Implementation of standard Tarjan SCC algorithm as modified by Nuutilla.
1760void Andersens::Condense(unsigned NodeIndex) {
1761 unsigned MyDFS = DFSNumber++;
1762 Node *N = &GraphNodes[NodeIndex];
1763 Node2Visited[NodeIndex] = true;
1764 Node2DFS[NodeIndex] = MyDFS;
1765
1766 // First process all our explicit edges
1767 if (N->PredEdges)
1768 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1769 Iter != N->PredEdges->end();
1770 ++Iter) {
1771 unsigned j = VSSCCRep[*Iter];
1772 if (!Node2Deleted[j]) {
1773 if (!Node2Visited[j])
1774 Condense(j);
1775 if (Node2DFS[NodeIndex] > Node2DFS[j])
1776 Node2DFS[NodeIndex] = Node2DFS[j];
1777 }
1778 }
1779
1780 // Now process all the implicit edges
1781 if (N->ImplicitPredEdges)
1782 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1783 Iter != N->ImplicitPredEdges->end();
1784 ++Iter) {
1785 unsigned j = VSSCCRep[*Iter];
1786 if (!Node2Deleted[j]) {
1787 if (!Node2Visited[j])
1788 Condense(j);
1789 if (Node2DFS[NodeIndex] > Node2DFS[j])
1790 Node2DFS[NodeIndex] = Node2DFS[j];
1791 }
1792 }
1793
1794 // See if we found any cycles
1795 if (MyDFS == Node2DFS[NodeIndex]) {
1796 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1797 unsigned CycleNodeIndex = SCCStack.top();
1798 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1799 VSSCCRep[CycleNodeIndex] = NodeIndex;
1800 // Unify the nodes
1801 N->Direct &= CycleNode->Direct;
1802
1803 *(N->PointsTo) |= CycleNode->PointsTo;
1804 delete CycleNode->PointsTo;
1805 CycleNode->PointsTo = NULL;
1806 if (CycleNode->PredEdges) {
1807 if (!N->PredEdges)
1808 N->PredEdges = new SparseBitVector<>;
1809 *(N->PredEdges) |= CycleNode->PredEdges;
1810 delete CycleNode->PredEdges;
1811 CycleNode->PredEdges = NULL;
1812 }
1813 if (CycleNode->ImplicitPredEdges) {
1814 if (!N->ImplicitPredEdges)
1815 N->ImplicitPredEdges = new SparseBitVector<>;
1816 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1817 delete CycleNode->ImplicitPredEdges;
1818 CycleNode->ImplicitPredEdges = NULL;
1819 }
1820 SCCStack.pop();
1821 }
1822
1823 Node2Deleted[NodeIndex] = true;
1824
1825 // Set up number of incoming edges for other nodes
1826 if (N->PredEdges)
1827 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1828 Iter != N->PredEdges->end();
1829 ++Iter)
1830 ++GraphNodes[VSSCCRep[*Iter]].NumInEdges;
1831 } else {
1832 SCCStack.push(NodeIndex);
1833 }
1834}
1835
1836void Andersens::HUValNum(unsigned NodeIndex) {
1837 Node *N = &GraphNodes[NodeIndex];
1838 Node2Visited[NodeIndex] = true;
1839
1840 // Eliminate dereferences of non-pointers for those non-pointers we have
1841 // already identified. These are ref nodes whose non-ref node:
1842 // 1. Has already been visited determined to point to nothing (and thus, a
1843 // dereference of it must point to nothing)
1844 // 2. Any direct node with no predecessor edges in our graph and with no
1845 // points-to set (since it can't point to anything either, being that it
1846 // receives no points-to sets and has none).
1847 if (NodeIndex >= FirstRefNode) {
1848 unsigned j = VSSCCRep[FindNode(NodeIndex - FirstRefNode)];
1849 if ((Node2Visited[j] && !GraphNodes[j].PointerEquivLabel)
1850 || (GraphNodes[j].Direct && !GraphNodes[j].PredEdges
1851 && GraphNodes[j].PointsTo->empty())){
1852 return;
1853 }
1854 }
1855 // Process all our explicit edges
1856 if (N->PredEdges)
1857 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1858 Iter != N->PredEdges->end();
1859 ++Iter) {
1860 unsigned j = VSSCCRep[*Iter];
1861 if (!Node2Visited[j])
1862 HUValNum(j);
1863
1864 // If this edge turned out to be the same as us, or got no pointer
1865 // equivalence label (and thus points to nothing) , just decrement our
1866 // incoming edges and continue.
1867 if (j == NodeIndex || GraphNodes[j].PointerEquivLabel == 0) {
1868 --GraphNodes[j].NumInEdges;
1869 continue;
1870 }
1871
1872 *(N->PointsTo) |= GraphNodes[j].PointsTo;
1873
1874 // If we didn't end up storing this in the hash, and we're done with all
1875 // the edges, we don't need the points-to set anymore.
1876 --GraphNodes[j].NumInEdges;
1877 if (!GraphNodes[j].NumInEdges && !GraphNodes[j].StoredInHash) {
1878 delete GraphNodes[j].PointsTo;
1879 GraphNodes[j].PointsTo = NULL;
1880 }
1881 }
1882 // If this isn't a direct node, generate a fresh variable.
1883 if (!N->Direct) {
1884 N->PointsTo->set(FirstRefNode + NodeIndex);
1885 }
1886
1887 // See If we have something equivalent to us, if not, generate a new
1888 // equivalence class.
1889 if (N->PointsTo->empty()) {
1890 delete N->PointsTo;
1891 N->PointsTo = NULL;
1892 } else {
1893 if (N->Direct) {
1894 N->PointerEquivLabel = Set2PEClass[N->PointsTo];
1895 if (N->PointerEquivLabel == 0) {
1896 unsigned EquivClass = PEClass++;
1897 N->StoredInHash = true;
1898 Set2PEClass[N->PointsTo] = EquivClass;
1899 N->PointerEquivLabel = EquivClass;
1900 }
1901 } else {
1902 N->PointerEquivLabel = PEClass++;
1903 }
1904 }
1905}
1906
1907/// Rewrite our list of constraints so that pointer equivalent nodes are
1908/// replaced by their the pointer equivalence class representative.
1909void Andersens::RewriteConstraints() {
1910 std::vector<Constraint> NewConstraints;
Chris Lattnerbe207732007-09-30 00:47:20 +00001911 DenseSet<Constraint, ConstraintKeyInfo> Seen;
Daniel Berlind81ccc22007-09-24 19:45:49 +00001912
1913 PEClass2Node.clear();
1914 PENLEClass2Node.clear();
1915
1916 // We may have from 1 to Graphnodes + 1 equivalence classes.
1917 PEClass2Node.insert(PEClass2Node.begin(), GraphNodes.size() + 1, -1);
1918 PENLEClass2Node.insert(PENLEClass2Node.begin(), GraphNodes.size() + 1, -1);
1919
1920 // Rewrite constraints, ignoring non-pointer constraints, uniting equivalent
1921 // nodes, and rewriting constraints to use the representative nodes.
1922 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1923 Constraint &C = Constraints[i];
1924 unsigned RHSNode = FindNode(C.Src);
1925 unsigned LHSNode = FindNode(C.Dest);
1926 unsigned RHSLabel = GraphNodes[VSSCCRep[RHSNode]].PointerEquivLabel;
1927 unsigned LHSLabel = GraphNodes[VSSCCRep[LHSNode]].PointerEquivLabel;
1928
1929 // First we try to eliminate constraints for things we can prove don't point
1930 // to anything.
1931 if (LHSLabel == 0) {
1932 DEBUG(PrintNode(&GraphNodes[LHSNode]));
1933 DOUT << " is a non-pointer, ignoring constraint.\n";
1934 continue;
1935 }
1936 if (RHSLabel == 0) {
1937 DEBUG(PrintNode(&GraphNodes[RHSNode]));
1938 DOUT << " is a non-pointer, ignoring constraint.\n";
1939 continue;
1940 }
1941 // This constraint may be useless, and it may become useless as we translate
1942 // it.
1943 if (C.Src == C.Dest && C.Type == Constraint::Copy)
1944 continue;
Daniel Berlinc7a12ae2007-09-27 15:42:23 +00001945
Daniel Berlind81ccc22007-09-24 19:45:49 +00001946 C.Src = FindEquivalentNode(RHSNode, RHSLabel);
1947 C.Dest = FindEquivalentNode(FindNode(LHSNode), LHSLabel);
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001948 if ((C.Src == C.Dest && C.Type == Constraint::Copy)
Chris Lattnerbe207732007-09-30 00:47:20 +00001949 || Seen.count(C))
Daniel Berlind81ccc22007-09-24 19:45:49 +00001950 continue;
1951
Chris Lattnerbe207732007-09-30 00:47:20 +00001952 Seen.insert(C);
Daniel Berlind81ccc22007-09-24 19:45:49 +00001953 NewConstraints.push_back(C);
1954 }
1955 Constraints.swap(NewConstraints);
1956 PEClass2Node.clear();
1957}
1958
1959/// See if we have a node that is pointer equivalent to the one being asked
1960/// about, and if so, unite them and return the equivalent node. Otherwise,
1961/// return the original node.
1962unsigned Andersens::FindEquivalentNode(unsigned NodeIndex,
1963 unsigned NodeLabel) {
1964 if (!GraphNodes[NodeIndex].AddressTaken) {
1965 if (PEClass2Node[NodeLabel] != -1) {
1966 // We found an existing node with the same pointer label, so unify them.
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001967 // We specifically request that Union-By-Rank not be used so that
1968 // PEClass2Node[NodeLabel] U= NodeIndex and not the other way around.
1969 return UniteNodes(PEClass2Node[NodeLabel], NodeIndex, false);
Daniel Berlind81ccc22007-09-24 19:45:49 +00001970 } else {
1971 PEClass2Node[NodeLabel] = NodeIndex;
1972 PENLEClass2Node[NodeLabel] = NodeIndex;
1973 }
1974 } else if (PENLEClass2Node[NodeLabel] == -1) {
1975 PENLEClass2Node[NodeLabel] = NodeIndex;
1976 }
1977
1978 return NodeIndex;
1979}
1980
1981void Andersens::PrintLabels() {
1982 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1983 if (i < FirstRefNode) {
1984 PrintNode(&GraphNodes[i]);
1985 } else if (i < FirstAdrNode) {
1986 DOUT << "REF(";
1987 PrintNode(&GraphNodes[i-FirstRefNode]);
1988 DOUT <<")";
1989 } else {
1990 DOUT << "ADR(";
1991 PrintNode(&GraphNodes[i-FirstAdrNode]);
1992 DOUT <<")";
1993 }
1994
1995 DOUT << " has pointer label " << GraphNodes[i].PointerEquivLabel
1996 << " and SCC rep " << VSSCCRep[i]
1997 << " and is " << (GraphNodes[i].Direct ? "Direct" : "Not direct")
1998 << "\n";
1999 }
2000}
2001
Daniel Berlinc864edb2008-03-05 19:31:47 +00002002/// The technique used here is described in "The Ant and the
2003/// Grasshopper: Fast and Accurate Pointer Analysis for Millions of
2004/// Lines of Code. In Programming Language Design and Implementation
2005/// (PLDI), June 2007." It is known as the "HCD" (Hybrid Cycle
2006/// Detection) algorithm. It is called a hybrid because it performs an
2007/// offline analysis and uses its results during the solving (online)
2008/// phase. This is just the offline portion; the results of this
2009/// operation are stored in SDT and are later used in SolveContraints()
2010/// and UniteNodes().
2011void Andersens::HCD() {
2012 DOUT << "Starting HCD.\n";
2013 HCDSCCRep.resize(GraphNodes.size());
2014
2015 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2016 GraphNodes[i].Edges = new SparseBitVector<>;
2017 HCDSCCRep[i] = i;
2018 }
2019
2020 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2021 Constraint &C = Constraints[i];
2022 assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
2023 if (C.Type == Constraint::AddressOf) {
2024 continue;
2025 } else if (C.Type == Constraint::Load) {
2026 if( C.Offset == 0 )
2027 GraphNodes[C.Dest].Edges->set(C.Src + FirstRefNode);
2028 } else if (C.Type == Constraint::Store) {
2029 if( C.Offset == 0 )
2030 GraphNodes[C.Dest + FirstRefNode].Edges->set(C.Src);
2031 } else {
2032 GraphNodes[C.Dest].Edges->set(C.Src);
2033 }
2034 }
2035
2036 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2037 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2038 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
2039 SDT.insert(SDT.begin(), GraphNodes.size() / 2, -1);
2040
2041 DFSNumber = 0;
2042 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2043 unsigned Node = HCDSCCRep[i];
2044 if (!Node2Deleted[Node])
2045 Search(Node);
2046 }
2047
2048 for (unsigned i = 0; i < GraphNodes.size(); ++i)
2049 if (GraphNodes[i].Edges != NULL) {
2050 delete GraphNodes[i].Edges;
2051 GraphNodes[i].Edges = NULL;
2052 }
2053
2054 while( !SCCStack.empty() )
2055 SCCStack.pop();
2056
2057 Node2DFS.clear();
2058 Node2Visited.clear();
2059 Node2Deleted.clear();
2060 HCDSCCRep.clear();
2061 DOUT << "HCD complete.\n";
2062}
2063
2064// Component of HCD:
2065// Use Nuutila's variant of Tarjan's algorithm to detect
2066// Strongly-Connected Components (SCCs). For non-trivial SCCs
2067// containing ref nodes, insert the appropriate information in SDT.
2068void Andersens::Search(unsigned Node) {
2069 unsigned MyDFS = DFSNumber++;
2070
2071 Node2Visited[Node] = true;
2072 Node2DFS[Node] = MyDFS;
2073
2074 for (SparseBitVector<>::iterator Iter = GraphNodes[Node].Edges->begin(),
2075 End = GraphNodes[Node].Edges->end();
2076 Iter != End;
2077 ++Iter) {
2078 unsigned J = HCDSCCRep[*Iter];
2079 assert(GraphNodes[J].isRep() && "Debug check; must be representative");
2080 if (!Node2Deleted[J]) {
2081 if (!Node2Visited[J])
2082 Search(J);
2083 if (Node2DFS[Node] > Node2DFS[J])
2084 Node2DFS[Node] = Node2DFS[J];
2085 }
2086 }
2087
2088 if( MyDFS != Node2DFS[Node] ) {
2089 SCCStack.push(Node);
2090 return;
2091 }
2092
2093 // This node is the root of a SCC, so process it.
2094 //
2095 // If the SCC is "non-trivial" (not a singleton) and contains a reference
2096 // node, we place this SCC into SDT. We unite the nodes in any case.
2097 if (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
2098 SparseBitVector<> SCC;
2099
2100 SCC.set(Node);
2101
2102 bool Ref = (Node >= FirstRefNode);
2103
2104 Node2Deleted[Node] = true;
2105
2106 do {
2107 unsigned P = SCCStack.top(); SCCStack.pop();
2108 Ref |= (P >= FirstRefNode);
2109 SCC.set(P);
2110 HCDSCCRep[P] = Node;
2111 } while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS);
2112
2113 if (Ref) {
2114 unsigned Rep = SCC.find_first();
2115 assert(Rep < FirstRefNode && "The SCC didn't have a non-Ref node!");
2116
2117 SparseBitVector<>::iterator i = SCC.begin();
2118
2119 // Skip over the non-ref nodes
2120 while( *i < FirstRefNode )
2121 ++i;
2122
2123 while( i != SCC.end() )
2124 SDT[ (*i++) - FirstRefNode ] = Rep;
2125 }
2126 }
2127}
2128
2129
Daniel Berlind81ccc22007-09-24 19:45:49 +00002130/// Optimize the constraints by performing offline variable substitution and
2131/// other optimizations.
2132void Andersens::OptimizeConstraints() {
2133 DOUT << "Beginning constraint optimization\n";
2134
Daniel Berlinc864edb2008-03-05 19:31:47 +00002135 SDTActive = false;
2136
Daniel Berlind81ccc22007-09-24 19:45:49 +00002137 // Function related nodes need to stay in the same relative position and can't
2138 // be location equivalent.
2139 for (std::map<unsigned, unsigned>::iterator Iter = MaxK.begin();
2140 Iter != MaxK.end();
2141 ++Iter) {
2142 for (unsigned i = Iter->first;
2143 i != Iter->first + Iter->second;
2144 ++i) {
2145 GraphNodes[i].AddressTaken = true;
2146 GraphNodes[i].Direct = false;
2147 }
2148 }
2149
2150 ClumpAddressTaken();
2151 FirstRefNode = GraphNodes.size();
2152 FirstAdrNode = FirstRefNode + GraphNodes.size();
2153 GraphNodes.insert(GraphNodes.end(), 2 * GraphNodes.size(),
2154 Node(false));
2155 VSSCCRep.resize(GraphNodes.size());
2156 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2157 VSSCCRep[i] = i;
2158 }
2159 HVN();
2160 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2161 Node *N = &GraphNodes[i];
2162 delete N->PredEdges;
2163 N->PredEdges = NULL;
2164 delete N->ImplicitPredEdges;
2165 N->ImplicitPredEdges = NULL;
2166 }
2167#undef DEBUG_TYPE
2168#define DEBUG_TYPE "anders-aa-labels"
2169 DEBUG(PrintLabels());
2170#undef DEBUG_TYPE
2171#define DEBUG_TYPE "anders-aa"
2172 RewriteConstraints();
2173 // Delete the adr nodes.
2174 GraphNodes.resize(FirstRefNode * 2);
2175
2176 // Now perform HU
2177 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2178 Node *N = &GraphNodes[i];
2179 if (FindNode(i) == i) {
2180 N->PointsTo = new SparseBitVector<>;
2181 N->PointedToBy = new SparseBitVector<>;
2182 // Reset our labels
2183 }
2184 VSSCCRep[i] = i;
2185 N->PointerEquivLabel = 0;
2186 }
2187 HU();
2188#undef DEBUG_TYPE
2189#define DEBUG_TYPE "anders-aa-labels"
2190 DEBUG(PrintLabels());
2191#undef DEBUG_TYPE
2192#define DEBUG_TYPE "anders-aa"
2193 RewriteConstraints();
2194 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2195 if (FindNode(i) == i) {
2196 Node *N = &GraphNodes[i];
2197 delete N->PointsTo;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002198 N->PointsTo = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002199 delete N->PredEdges;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002200 N->PredEdges = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002201 delete N->ImplicitPredEdges;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002202 N->ImplicitPredEdges = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002203 delete N->PointedToBy;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002204 N->PointedToBy = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002205 }
2206 }
Daniel Berlinc864edb2008-03-05 19:31:47 +00002207
2208 // perform Hybrid Cycle Detection (HCD)
2209 HCD();
2210 SDTActive = true;
2211
2212 // No longer any need for the upper half of GraphNodes (for ref nodes).
Daniel Berlind81ccc22007-09-24 19:45:49 +00002213 GraphNodes.erase(GraphNodes.begin() + FirstRefNode, GraphNodes.end());
Daniel Berlinc864edb2008-03-05 19:31:47 +00002214
2215 // HCD complete.
2216
Daniel Berlind81ccc22007-09-24 19:45:49 +00002217 DOUT << "Finished constraint optimization\n";
2218 FirstRefNode = 0;
2219 FirstAdrNode = 0;
2220}
2221
2222/// Unite pointer but not location equivalent variables, now that the constraint
2223/// graph is built.
2224void Andersens::UnitePointerEquivalences() {
2225 DOUT << "Uniting remaining pointer equivalences\n";
2226 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002227 if (GraphNodes[i].AddressTaken && GraphNodes[i].isRep()) {
Daniel Berlind81ccc22007-09-24 19:45:49 +00002228 unsigned Label = GraphNodes[i].PointerEquivLabel;
2229
2230 if (Label && PENLEClass2Node[Label] != -1)
2231 UniteNodes(i, PENLEClass2Node[Label]);
2232 }
2233 }
2234 DOUT << "Finished remaining pointer equivalences\n";
2235 PENLEClass2Node.clear();
2236}
2237
2238/// Create the constraint graph used for solving points-to analysis.
2239///
Daniel Berlinaad15882007-09-16 21:45:02 +00002240void Andersens::CreateConstraintGraph() {
2241 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2242 Constraint &C = Constraints[i];
2243 assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
2244 if (C.Type == Constraint::AddressOf)
2245 GraphNodes[C.Dest].PointsTo->set(C.Src);
2246 else if (C.Type == Constraint::Load)
2247 GraphNodes[C.Src].Constraints.push_back(C);
2248 else if (C.Type == Constraint::Store)
2249 GraphNodes[C.Dest].Constraints.push_back(C);
2250 else if (C.Offset != 0)
2251 GraphNodes[C.Src].Constraints.push_back(C);
2252 else
2253 GraphNodes[C.Src].Edges->set(C.Dest);
2254 }
2255}
2256
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002257// Perform DFS and cycle detection.
2258bool Andersens::QueryNode(unsigned Node) {
2259 assert(GraphNodes[Node].isRep() && "Querying a non-rep node");
Daniel Berlinaad15882007-09-16 21:45:02 +00002260 unsigned OurDFS = ++DFSNumber;
2261 SparseBitVector<> ToErase;
2262 SparseBitVector<> NewEdges;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002263 Tarjan2DFS[Node] = OurDFS;
2264
2265 // Changed denotes a change from a recursive call that we will bubble up.
2266 // Merged is set if we actually merge a node ourselves.
2267 bool Changed = false, Merged = false;
Daniel Berlinaad15882007-09-16 21:45:02 +00002268
2269 for (SparseBitVector<>::iterator bi = GraphNodes[Node].Edges->begin();
2270 bi != GraphNodes[Node].Edges->end();
2271 ++bi) {
2272 unsigned RepNode = FindNode(*bi);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002273 // If this edge points to a non-representative node but we are
2274 // already planning to add an edge to its representative, we have no
2275 // need for this edge anymore.
Daniel Berlinaad15882007-09-16 21:45:02 +00002276 if (RepNode != *bi && NewEdges.test(RepNode)){
2277 ToErase.set(*bi);
2278 continue;
2279 }
2280
2281 // Continue about our DFS.
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002282 if (!Tarjan2Deleted[RepNode]){
2283 if (Tarjan2DFS[RepNode] == 0) {
2284 Changed |= QueryNode(RepNode);
2285 // May have been changed by QueryNode
Daniel Berlinaad15882007-09-16 21:45:02 +00002286 RepNode = FindNode(RepNode);
2287 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002288 if (Tarjan2DFS[RepNode] < Tarjan2DFS[Node])
2289 Tarjan2DFS[Node] = Tarjan2DFS[RepNode];
Daniel Berlinaad15882007-09-16 21:45:02 +00002290 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002291
2292 // We may have just discovered that this node is part of a cycle, in
2293 // which case we can also erase it.
Daniel Berlinaad15882007-09-16 21:45:02 +00002294 if (RepNode != *bi) {
2295 ToErase.set(*bi);
2296 NewEdges.set(RepNode);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002297 }
2298 }
2299
Daniel Berlinaad15882007-09-16 21:45:02 +00002300 GraphNodes[Node].Edges->intersectWithComplement(ToErase);
2301 GraphNodes[Node].Edges |= NewEdges;
2302
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002303 // If this node is a root of a non-trivial SCC, place it on our
2304 // worklist to be processed.
2305 if (OurDFS == Tarjan2DFS[Node]) {
2306 while (!SCCStack.empty() && Tarjan2DFS[SCCStack.top()] >= OurDFS) {
2307 Node = UniteNodes(Node, SCCStack.top());
Daniel Berlinaad15882007-09-16 21:45:02 +00002308
2309 SCCStack.pop();
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002310 Merged = true;
Daniel Berlinaad15882007-09-16 21:45:02 +00002311 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002312 Tarjan2Deleted[Node] = true;
Daniel Berlinaad15882007-09-16 21:45:02 +00002313
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002314 if (Merged)
2315 NextWL->insert(&GraphNodes[Node]);
Daniel Berlinaad15882007-09-16 21:45:02 +00002316 } else {
2317 SCCStack.push(Node);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002318 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002319
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002320 return(Changed | Merged);
2321}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002322
2323/// SolveConstraints - This stage iteratively processes the constraints list
2324/// propagating constraints (adding edges to the Nodes in the points-to graph)
2325/// until a fixed point is reached.
2326///
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002327/// We use a variant of the technique called "Lazy Cycle Detection", which is
2328/// described in "The Ant and the Grasshopper: Fast and Accurate Pointer
2329/// Analysis for Millions of Lines of Code. In Programming Language Design and
2330/// Implementation (PLDI), June 2007."
2331/// The paper describes performing cycle detection one node at a time, which can
2332/// be expensive if there are no cycles, but there are long chains of nodes that
2333/// it heuristically believes are cycles (because it will DFS from each node
2334/// without state from previous nodes).
2335/// Instead, we use the heuristic to build a worklist of nodes to check, then
2336/// cycle detect them all at the same time to do this more cheaply. This
2337/// catches cycles slightly later than the original technique did, but does it
2338/// make significantly cheaper.
2339
Chris Lattnere995a2a2004-05-23 21:00:47 +00002340void Andersens::SolveConstraints() {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002341 CurrWL = &w1;
2342 NextWL = &w2;
Daniel Berlinaad15882007-09-16 21:45:02 +00002343
Daniel Berlind81ccc22007-09-24 19:45:49 +00002344 OptimizeConstraints();
2345#undef DEBUG_TYPE
2346#define DEBUG_TYPE "anders-aa-constraints"
2347 DEBUG(PrintConstraints());
2348#undef DEBUG_TYPE
2349#define DEBUG_TYPE "anders-aa"
2350
Daniel Berlinaad15882007-09-16 21:45:02 +00002351 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2352 Node *N = &GraphNodes[i];
2353 N->PointsTo = new SparseBitVector<>;
2354 N->OldPointsTo = new SparseBitVector<>;
2355 N->Edges = new SparseBitVector<>;
2356 }
2357 CreateConstraintGraph();
Daniel Berlind81ccc22007-09-24 19:45:49 +00002358 UnitePointerEquivalences();
2359 assert(SCCStack.empty() && "SCC Stack should be empty by now!");
Daniel Berlind81ccc22007-09-24 19:45:49 +00002360 Node2DFS.clear();
2361 Node2Deleted.clear();
Daniel Berlinaad15882007-09-16 21:45:02 +00002362 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2363 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2364 DFSNumber = 0;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002365 DenseSet<Constraint, ConstraintKeyInfo> Seen;
2366 DenseSet<std::pair<unsigned,unsigned>, PairKeyInfo> EdgesChecked;
2367
2368 // Order graph and add initial nodes to work list.
Daniel Berlinaad15882007-09-16 21:45:02 +00002369 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
Daniel Berlinaad15882007-09-16 21:45:02 +00002370 Node *INode = &GraphNodes[i];
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002371
2372 // Add to work list if it's a representative and can contribute to the
2373 // calculation right now.
2374 if (INode->isRep() && !INode->PointsTo->empty()
2375 && (!INode->Edges->empty() || !INode->Constraints.empty())) {
2376 INode->Stamp();
2377 CurrWL->insert(INode);
Daniel Berlinaad15882007-09-16 21:45:02 +00002378 }
2379 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002380 std::queue<unsigned int> TarjanWL;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002381#if !FULL_UNIVERSAL
2382 // "Rep and special variables" - in order for HCD to maintain conservative
2383 // results when !FULL_UNIVERSAL, we need to treat the special variables in
2384 // the same way that the !FULL_UNIVERSAL tweak does throughout the rest of
2385 // the analysis - it's ok to add edges from the special nodes, but never
2386 // *to* the special nodes.
2387 std::vector<unsigned int> RSV;
2388#endif
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002389 while( !CurrWL->empty() ) {
2390 DOUT << "Starting iteration #" << ++NumIters << "\n";
Daniel Berlinaad15882007-09-16 21:45:02 +00002391
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002392 Node* CurrNode;
2393 unsigned CurrNodeIndex;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002394
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002395 // Actual cycle checking code. We cycle check all of the lazy cycle
2396 // candidates from the last iteration in one go.
2397 if (!TarjanWL.empty()) {
2398 DFSNumber = 0;
2399
2400 Tarjan2DFS.clear();
2401 Tarjan2Deleted.clear();
2402 while (!TarjanWL.empty()) {
2403 unsigned int ToTarjan = TarjanWL.front();
2404 TarjanWL.pop();
2405 if (!Tarjan2Deleted[ToTarjan]
2406 && GraphNodes[ToTarjan].isRep()
2407 && Tarjan2DFS[ToTarjan] == 0)
2408 QueryNode(ToTarjan);
2409 }
2410 }
2411
2412 // Add to work list if it's a representative and can contribute to the
2413 // calculation right now.
2414 while( (CurrNode = CurrWL->pop()) != NULL ) {
2415 CurrNodeIndex = CurrNode - &GraphNodes[0];
2416 CurrNode->Stamp();
2417
2418
Daniel Berlinaad15882007-09-16 21:45:02 +00002419 // Figure out the changed points to bits
2420 SparseBitVector<> CurrPointsTo;
2421 CurrPointsTo.intersectWithComplement(CurrNode->PointsTo,
2422 CurrNode->OldPointsTo);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002423 if (CurrPointsTo.empty())
Daniel Berlinaad15882007-09-16 21:45:02 +00002424 continue;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002425
Daniel Berlinaad15882007-09-16 21:45:02 +00002426 *(CurrNode->OldPointsTo) |= CurrPointsTo;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002427
2428 // Check the offline-computed equivalencies from HCD.
2429 bool SCC = false;
2430 unsigned Rep;
2431
2432 if (SDT[CurrNodeIndex] >= 0) {
2433 SCC = true;
2434 Rep = FindNode(SDT[CurrNodeIndex]);
2435
2436#if !FULL_UNIVERSAL
2437 RSV.clear();
2438#endif
2439 for (SparseBitVector<>::iterator bi = CurrPointsTo.begin();
2440 bi != CurrPointsTo.end(); ++bi) {
2441 unsigned Node = FindNode(*bi);
2442#if !FULL_UNIVERSAL
2443 if (Node < NumberSpecialNodes) {
2444 RSV.push_back(Node);
2445 continue;
2446 }
2447#endif
2448 Rep = UniteNodes(Rep,Node);
2449 }
2450#if !FULL_UNIVERSAL
2451 RSV.push_back(Rep);
2452#endif
2453
2454 NextWL->insert(&GraphNodes[Rep]);
2455
2456 if ( ! CurrNode->isRep() )
2457 continue;
2458 }
2459
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002460 Seen.clear();
Chris Lattnere995a2a2004-05-23 21:00:47 +00002461
Daniel Berlinaad15882007-09-16 21:45:02 +00002462 /* Now process the constraints for this node. */
2463 for (std::list<Constraint>::iterator li = CurrNode->Constraints.begin();
2464 li != CurrNode->Constraints.end(); ) {
2465 li->Src = FindNode(li->Src);
2466 li->Dest = FindNode(li->Dest);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002467
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002468 // Delete redundant constraints
2469 if( Seen.count(*li) ) {
2470 std::list<Constraint>::iterator lk = li; li++;
2471
2472 CurrNode->Constraints.erase(lk);
2473 ++NumErased;
2474 continue;
2475 }
2476 Seen.insert(*li);
2477
Daniel Berlinaad15882007-09-16 21:45:02 +00002478 // Src and Dest will be the vars we are going to process.
2479 // This may look a bit ugly, but what it does is allow us to process
Daniel Berlind81ccc22007-09-24 19:45:49 +00002480 // both store and load constraints with the same code.
Daniel Berlinaad15882007-09-16 21:45:02 +00002481 // Load constraints say that every member of our RHS solution has K
2482 // added to it, and that variable gets an edge to LHS. We also union
2483 // RHS+K's solution into the LHS solution.
2484 // Store constraints say that every member of our LHS solution has K
2485 // added to it, and that variable gets an edge from RHS. We also union
2486 // RHS's solution into the LHS+K solution.
2487 unsigned *Src;
2488 unsigned *Dest;
2489 unsigned K = li->Offset;
2490 unsigned CurrMember;
2491 if (li->Type == Constraint::Load) {
2492 Src = &CurrMember;
2493 Dest = &li->Dest;
2494 } else if (li->Type == Constraint::Store) {
2495 Src = &li->Src;
2496 Dest = &CurrMember;
2497 } else {
2498 // TODO Handle offseted copy constraint
2499 li++;
2500 continue;
2501 }
Daniel Berlinc864edb2008-03-05 19:31:47 +00002502
2503 // See if we can use Hybrid Cycle Detection (that is, check
Daniel Berlinaad15882007-09-16 21:45:02 +00002504 // if it was a statically detected offline equivalence that
Daniel Berlinc864edb2008-03-05 19:31:47 +00002505 // involves pointers; if so, remove the redundant constraints).
2506 if( SCC && K == 0 ) {
2507#if FULL_UNIVERSAL
2508 CurrMember = Rep;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002509
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002510 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2511 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2512 NextWL->insert(&GraphNodes[*Dest]);
Daniel Berlinc864edb2008-03-05 19:31:47 +00002513#else
2514 for (unsigned i=0; i < RSV.size(); ++i) {
2515 CurrMember = RSV[i];
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002516
Daniel Berlinc864edb2008-03-05 19:31:47 +00002517 if (*Dest < NumberSpecialNodes)
2518 continue;
2519 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2520 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2521 NextWL->insert(&GraphNodes[*Dest]);
2522 }
2523#endif
2524 // since all future elements of the points-to set will be
2525 // equivalent to the current ones, the complex constraints
2526 // become redundant.
2527 //
2528 std::list<Constraint>::iterator lk = li; li++;
2529#if !FULL_UNIVERSAL
2530 // In this case, we can still erase the constraints when the
2531 // elements of the points-to sets are referenced by *Dest,
2532 // but not when they are referenced by *Src (i.e. for a Load
2533 // constraint). This is because if another special variable is
2534 // put into the points-to set later, we still need to add the
2535 // new edge from that special variable.
2536 if( lk->Type != Constraint::Load)
2537#endif
2538 GraphNodes[CurrNodeIndex].Constraints.erase(lk);
2539 } else {
2540 const SparseBitVector<> &Solution = CurrPointsTo;
2541
2542 for (SparseBitVector<>::iterator bi = Solution.begin();
2543 bi != Solution.end();
2544 ++bi) {
2545 CurrMember = *bi;
2546
2547 // Need to increment the member by K since that is where we are
2548 // supposed to copy to/from. Note that in positive weight cycles,
2549 // which occur in address taking of fields, K can go past
2550 // MaxK[CurrMember] elements, even though that is all it could point
2551 // to.
2552 if (K > 0 && K > MaxK[CurrMember])
2553 continue;
2554 else
2555 CurrMember = FindNode(CurrMember + K);
2556
2557 // Add an edge to the graph, so we can just do regular
2558 // bitmap ior next time. It may also let us notice a cycle.
2559#if !FULL_UNIVERSAL
2560 if (*Dest < NumberSpecialNodes)
2561 continue;
2562#endif
2563 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2564 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2565 NextWL->insert(&GraphNodes[*Dest]);
2566
2567 }
2568 li++;
Daniel Berlinaad15882007-09-16 21:45:02 +00002569 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002570 }
2571 SparseBitVector<> NewEdges;
2572 SparseBitVector<> ToErase;
2573
2574 // Now all we have left to do is propagate points-to info along the
2575 // edges, erasing the redundant edges.
Daniel Berlinaad15882007-09-16 21:45:02 +00002576 for (SparseBitVector<>::iterator bi = CurrNode->Edges->begin();
2577 bi != CurrNode->Edges->end();
2578 ++bi) {
2579
2580 unsigned DestVar = *bi;
2581 unsigned Rep = FindNode(DestVar);
2582
Bill Wendlingf059deb2008-02-26 10:51:52 +00002583 // If we ended up with this node as our destination, or we've already
2584 // got an edge for the representative, delete the current edge.
2585 if (Rep == CurrNodeIndex ||
2586 (Rep != DestVar && NewEdges.test(Rep))) {
Daniel Berlinc864edb2008-03-05 19:31:47 +00002587 ToErase.set(DestVar);
2588 continue;
Bill Wendlingf059deb2008-02-26 10:51:52 +00002589 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002590
Bill Wendlingf059deb2008-02-26 10:51:52 +00002591 std::pair<unsigned,unsigned> edge(CurrNodeIndex,Rep);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002592
2593 // This is where we do lazy cycle detection.
2594 // If this is a cycle candidate (equal points-to sets and this
2595 // particular edge has not been cycle-checked previously), add to the
2596 // list to check for cycles on the next iteration.
2597 if (!EdgesChecked.count(edge) &&
2598 *(GraphNodes[Rep].PointsTo) == *(CurrNode->PointsTo)) {
2599 EdgesChecked.insert(edge);
2600 TarjanWL.push(Rep);
Daniel Berlinaad15882007-09-16 21:45:02 +00002601 }
2602 // Union the points-to sets into the dest
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002603#if !FULL_UNIVERSAL
2604 if (Rep >= NumberSpecialNodes)
2605#endif
Daniel Berlinaad15882007-09-16 21:45:02 +00002606 if (GraphNodes[Rep].PointsTo |= CurrPointsTo) {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002607 NextWL->insert(&GraphNodes[Rep]);
Daniel Berlinaad15882007-09-16 21:45:02 +00002608 }
2609 // If this edge's destination was collapsed, rewrite the edge.
2610 if (Rep != DestVar) {
2611 ToErase.set(DestVar);
2612 NewEdges.set(Rep);
2613 }
2614 }
2615 CurrNode->Edges->intersectWithComplement(ToErase);
2616 CurrNode->Edges |= NewEdges;
2617 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002618
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002619 // Switch to other work list.
2620 WorkList* t = CurrWL; CurrWL = NextWL; NextWL = t;
2621 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002622
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002623
Daniel Berlinaad15882007-09-16 21:45:02 +00002624 Node2DFS.clear();
2625 Node2Deleted.clear();
2626 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2627 Node *N = &GraphNodes[i];
2628 delete N->OldPointsTo;
2629 delete N->Edges;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002630 }
Daniel Berlinc864edb2008-03-05 19:31:47 +00002631 SDTActive = false;
2632 SDT.clear();
Chris Lattnere995a2a2004-05-23 21:00:47 +00002633}
2634
Daniel Berlinaad15882007-09-16 21:45:02 +00002635//===----------------------------------------------------------------------===//
2636// Union-Find
2637//===----------------------------------------------------------------------===//
Chris Lattnere995a2a2004-05-23 21:00:47 +00002638
Daniel Berlinaad15882007-09-16 21:45:02 +00002639// Unite nodes First and Second, returning the one which is now the
2640// representative node. First and Second are indexes into GraphNodes
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002641unsigned Andersens::UniteNodes(unsigned First, unsigned Second,
2642 bool UnionByRank) {
Daniel Berlinaad15882007-09-16 21:45:02 +00002643 assert (First < GraphNodes.size() && Second < GraphNodes.size() &&
2644 "Attempting to merge nodes that don't exist");
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002645
Daniel Berlinaad15882007-09-16 21:45:02 +00002646 Node *FirstNode = &GraphNodes[First];
2647 Node *SecondNode = &GraphNodes[Second];
2648
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002649 assert (SecondNode->isRep() && FirstNode->isRep() &&
Daniel Berlinaad15882007-09-16 21:45:02 +00002650 "Trying to unite two non-representative nodes!");
2651 if (First == Second)
2652 return First;
2653
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002654 if (UnionByRank) {
2655 int RankFirst = (int) FirstNode ->NodeRep;
2656 int RankSecond = (int) SecondNode->NodeRep;
2657
2658 // Rank starts at -1 and gets decremented as it increases.
2659 // Translation: higher rank, lower NodeRep value, which is always negative.
2660 if (RankFirst > RankSecond) {
2661 unsigned t = First; First = Second; Second = t;
2662 Node* tp = FirstNode; FirstNode = SecondNode; SecondNode = tp;
2663 } else if (RankFirst == RankSecond) {
2664 FirstNode->NodeRep = (unsigned) (RankFirst - 1);
2665 }
2666 }
2667
Daniel Berlinaad15882007-09-16 21:45:02 +00002668 SecondNode->NodeRep = First;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002669#if !FULL_UNIVERSAL
2670 if (First >= NumberSpecialNodes)
2671#endif
Daniel Berlind81ccc22007-09-24 19:45:49 +00002672 if (FirstNode->PointsTo && SecondNode->PointsTo)
2673 FirstNode->PointsTo |= *(SecondNode->PointsTo);
2674 if (FirstNode->Edges && SecondNode->Edges)
2675 FirstNode->Edges |= *(SecondNode->Edges);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002676 if (!SecondNode->Constraints.empty())
Daniel Berlind81ccc22007-09-24 19:45:49 +00002677 FirstNode->Constraints.splice(FirstNode->Constraints.begin(),
2678 SecondNode->Constraints);
2679 if (FirstNode->OldPointsTo) {
2680 delete FirstNode->OldPointsTo;
2681 FirstNode->OldPointsTo = new SparseBitVector<>;
2682 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002683
2684 // Destroy interesting parts of the merged-from node.
2685 delete SecondNode->OldPointsTo;
2686 delete SecondNode->Edges;
2687 delete SecondNode->PointsTo;
2688 SecondNode->Edges = NULL;
2689 SecondNode->PointsTo = NULL;
2690 SecondNode->OldPointsTo = NULL;
2691
2692 NumUnified++;
2693 DOUT << "Unified Node ";
2694 DEBUG(PrintNode(FirstNode));
2695 DOUT << " and Node ";
2696 DEBUG(PrintNode(SecondNode));
2697 DOUT << "\n";
2698
Daniel Berlinc864edb2008-03-05 19:31:47 +00002699 if (SDTActive)
2700 if (SDT[Second] >= 0)
2701 if (SDT[First] < 0)
2702 SDT[First] = SDT[Second];
2703 else {
2704 UniteNodes( FindNode(SDT[First]), FindNode(SDT[Second]) );
2705 First = FindNode(First);
2706 }
2707
Daniel Berlinaad15882007-09-16 21:45:02 +00002708 return First;
2709}
2710
2711// Find the index into GraphNodes of the node representing Node, performing
2712// path compression along the way
2713unsigned Andersens::FindNode(unsigned NodeIndex) {
2714 assert (NodeIndex < GraphNodes.size()
2715 && "Attempting to find a node that can't exist");
2716 Node *N = &GraphNodes[NodeIndex];
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002717 if (N->isRep())
Daniel Berlinaad15882007-09-16 21:45:02 +00002718 return NodeIndex;
2719 else
2720 return (N->NodeRep = FindNode(N->NodeRep));
2721}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002722
2723//===----------------------------------------------------------------------===//
2724// Debugging Output
2725//===----------------------------------------------------------------------===//
2726
2727void Andersens::PrintNode(Node *N) {
2728 if (N == &GraphNodes[UniversalSet]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002729 cerr << "<universal>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002730 return;
2731 } else if (N == &GraphNodes[NullPtr]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002732 cerr << "<nullptr>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002733 return;
2734 } else if (N == &GraphNodes[NullObject]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002735 cerr << "<null>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002736 return;
2737 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002738 if (!N->getValue()) {
2739 cerr << "artificial" << (intptr_t) N;
2740 return;
2741 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002742
2743 assert(N->getValue() != 0 && "Never set node label!");
2744 Value *V = N->getValue();
2745 if (Function *F = dyn_cast<Function>(V)) {
2746 if (isa<PointerType>(F->getFunctionType()->getReturnType()) &&
Daniel Berlinaad15882007-09-16 21:45:02 +00002747 N == &GraphNodes[getReturnNode(F)]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002748 cerr << F->getName() << ":retval";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002749 return;
Daniel Berlinaad15882007-09-16 21:45:02 +00002750 } else if (F->getFunctionType()->isVarArg() &&
2751 N == &GraphNodes[getVarargNode(F)]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002752 cerr << F->getName() << ":vararg";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002753 return;
2754 }
2755 }
2756
2757 if (Instruction *I = dyn_cast<Instruction>(V))
Bill Wendlinge8156192006-12-07 01:30:32 +00002758 cerr << I->getParent()->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002759 else if (Argument *Arg = dyn_cast<Argument>(V))
Bill Wendlinge8156192006-12-07 01:30:32 +00002760 cerr << Arg->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002761
2762 if (V->hasName())
Bill Wendlinge8156192006-12-07 01:30:32 +00002763 cerr << V->getName();
Chris Lattnere995a2a2004-05-23 21:00:47 +00002764 else
Bill Wendlinge8156192006-12-07 01:30:32 +00002765 cerr << "(unnamed)";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002766
2767 if (isa<GlobalValue>(V) || isa<AllocationInst>(V))
Daniel Berlinaad15882007-09-16 21:45:02 +00002768 if (N == &GraphNodes[getObject(V)])
Bill Wendlinge8156192006-12-07 01:30:32 +00002769 cerr << "<mem>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002770}
Daniel Berlind81ccc22007-09-24 19:45:49 +00002771void Andersens::PrintConstraint(const Constraint &C) {
2772 if (C.Type == Constraint::Store) {
2773 cerr << "*";
2774 if (C.Offset != 0)
2775 cerr << "(";
2776 }
2777 PrintNode(&GraphNodes[C.Dest]);
2778 if (C.Type == Constraint::Store && C.Offset != 0)
2779 cerr << " + " << C.Offset << ")";
2780 cerr << " = ";
2781 if (C.Type == Constraint::Load) {
2782 cerr << "*";
2783 if (C.Offset != 0)
2784 cerr << "(";
2785 }
2786 else if (C.Type == Constraint::AddressOf)
2787 cerr << "&";
2788 PrintNode(&GraphNodes[C.Src]);
2789 if (C.Offset != 0 && C.Type != Constraint::Store)
2790 cerr << " + " << C.Offset;
2791 if (C.Type == Constraint::Load && C.Offset != 0)
2792 cerr << ")";
2793 cerr << "\n";
2794}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002795
2796void Andersens::PrintConstraints() {
Bill Wendlinge8156192006-12-07 01:30:32 +00002797 cerr << "Constraints:\n";
Daniel Berlinaad15882007-09-16 21:45:02 +00002798
Daniel Berlind81ccc22007-09-24 19:45:49 +00002799 for (unsigned i = 0, e = Constraints.size(); i != e; ++i)
2800 PrintConstraint(Constraints[i]);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002801}
2802
2803void Andersens::PrintPointsToGraph() {
Bill Wendlinge8156192006-12-07 01:30:32 +00002804 cerr << "Points-to graph:\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002805 for (unsigned i = 0, e = GraphNodes.size(); i != e; ++i) {
2806 Node *N = &GraphNodes[i];
Daniel Berlinaad15882007-09-16 21:45:02 +00002807 if (FindNode (i) != i) {
2808 PrintNode(N);
2809 cerr << "\t--> same as ";
2810 PrintNode(&GraphNodes[FindNode(i)]);
2811 cerr << "\n";
2812 } else {
2813 cerr << "[" << (N->PointsTo->count()) << "] ";
2814 PrintNode(N);
2815 cerr << "\t--> ";
2816
2817 bool first = true;
2818 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
2819 bi != N->PointsTo->end();
2820 ++bi) {
2821 if (!first)
2822 cerr << ", ";
2823 PrintNode(&GraphNodes[*bi]);
2824 first = false;
2825 }
2826 cerr << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002827 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002828 }
2829}