blob: 17f304c021193f0aca5d61653db2db31f8bed2c8 [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"
Torok Edwin7d696d82009-07-11 13:10:19 +000062#include "llvm/Support/ErrorHandling.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"
Victor Hernandezf006b182009-10-27 20:05:49 +000066#include "llvm/Analysis/MemoryBuiltins.h"
Jeff Cohen534927d2005-01-08 22:01:16 +000067#include "llvm/Analysis/Passes.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000068#include "llvm/Support/Debug.h"
Owen Anderson2e693102009-06-24 22:16:52 +000069#include "llvm/System/Atomic.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000070#include "llvm/ADT/Statistic.h"
Daniel Berlinaad15882007-09-16 21:45:02 +000071#include "llvm/ADT/SparseBitVector.h"
Chris Lattnerbe207732007-09-30 00:47:20 +000072#include "llvm/ADT/DenseSet.h"
Jeff Cohenca5183d2007-03-05 00:00:42 +000073#include <algorithm>
Chris Lattnere995a2a2004-05-23 21:00:47 +000074#include <set>
Daniel Berlinaad15882007-09-16 21:45:02 +000075#include <list>
Dan Gohmanc9235d22008-03-21 23:51:57 +000076#include <map>
Daniel Berlinaad15882007-09-16 21:45:02 +000077#include <stack>
78#include <vector>
Daniel Berlin3a3f1632007-12-12 00:37:04 +000079#include <queue>
80
81// Determining the actual set of nodes the universal set can consist of is very
82// expensive because it means propagating around very large sets. We rely on
83// other analysis being able to determine which nodes can never be pointed to in
84// order to disambiguate further than "points-to anything".
85#define FULL_UNIVERSAL 0
Chris Lattnere995a2a2004-05-23 21:00:47 +000086
Daniel Berlinaad15882007-09-16 21:45:02 +000087using namespace llvm;
Daniel Dunbare317bcc2009-08-23 10:29:55 +000088#ifndef NDEBUG
Daniel Berlind81ccc22007-09-24 19:45:49 +000089STATISTIC(NumIters , "Number of iterations to reach convergence");
Daniel Dunbare317bcc2009-08-23 10:29:55 +000090#endif
Daniel Berlind81ccc22007-09-24 19:45:49 +000091STATISTIC(NumConstraints, "Number of constraints");
92STATISTIC(NumNodes , "Number of nodes");
93STATISTIC(NumUnified , "Number of variables unified");
Daniel Berlin3a3f1632007-12-12 00:37:04 +000094STATISTIC(NumErased , "Number of redundant constraints erased");
Chris Lattnere995a2a2004-05-23 21:00:47 +000095
Dan Gohman844731a2008-05-13 00:00:25 +000096static const unsigned SelfRep = (unsigned)-1;
97static const unsigned Unvisited = (unsigned)-1;
98// Position of the function return node relative to the function node.
99static const unsigned CallReturnPos = 1;
100// Position of the function call node relative to the function node.
101static const unsigned CallFirstArgPos = 2;
Daniel Berlind81ccc22007-09-24 19:45:49 +0000102
Dan Gohman844731a2008-05-13 00:00:25 +0000103namespace {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000104 struct BitmapKeyInfo {
105 static inline SparseBitVector<> *getEmptyKey() {
106 return reinterpret_cast<SparseBitVector<> *>(-1);
107 }
108 static inline SparseBitVector<> *getTombstoneKey() {
109 return reinterpret_cast<SparseBitVector<> *>(-2);
110 }
111 static unsigned getHashValue(const SparseBitVector<> *bitmap) {
112 return bitmap->getHashValue();
113 }
114 static bool isEqual(const SparseBitVector<> *LHS,
115 const SparseBitVector<> *RHS) {
116 if (LHS == RHS)
117 return true;
118 else if (LHS == getEmptyKey() || RHS == getEmptyKey()
119 || LHS == getTombstoneKey() || RHS == getTombstoneKey())
120 return false;
121
122 return *LHS == *RHS;
123 }
124
125 static bool isPod() { return true; }
126 };
Daniel Berlinaad15882007-09-16 21:45:02 +0000127
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000128 class Andersens : public ModulePass, public AliasAnalysis,
129 private InstVisitor<Andersens> {
Hartmut Kaiser081fdf22007-10-25 23:49:14 +0000130 struct Node;
Daniel Berlinaad15882007-09-16 21:45:02 +0000131
132 /// Constraint - Objects of this structure are used to represent the various
133 /// constraints identified by the algorithm. The constraints are 'copy',
134 /// for statements like "A = B", 'load' for statements like "A = *B",
135 /// 'store' for statements like "*A = B", and AddressOf for statements like
136 /// A = alloca; The Offset is applied as *(A + K) = B for stores,
137 /// A = *(B + K) for loads, and A = B + K for copies. It is
Daniel Berlind81ccc22007-09-24 19:45:49 +0000138 /// illegal on addressof constraints (because it is statically
Daniel Berlinaad15882007-09-16 21:45:02 +0000139 /// resolvable to A = &C where C = B + K)
140
141 struct Constraint {
142 enum ConstraintType { Copy, Load, Store, AddressOf } Type;
143 unsigned Dest;
144 unsigned Src;
145 unsigned Offset;
146
147 Constraint(ConstraintType Ty, unsigned D, unsigned S, unsigned O = 0)
148 : Type(Ty), Dest(D), Src(S), Offset(O) {
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +0000149 assert((Offset == 0 || Ty != AddressOf) &&
Daniel Berlinaad15882007-09-16 21:45:02 +0000150 "Offset is illegal on addressof constraints");
151 }
Daniel Berlin336c6c02007-09-29 00:50:40 +0000152
Daniel Berlinc7a12ae2007-09-27 15:42:23 +0000153 bool operator==(const Constraint &RHS) const {
154 return RHS.Type == Type
155 && RHS.Dest == Dest
156 && RHS.Src == Src
157 && RHS.Offset == Offset;
158 }
Daniel Berlin336c6c02007-09-29 00:50:40 +0000159
160 bool operator!=(const Constraint &RHS) const {
161 return !(*this == RHS);
162 }
163
Daniel Berlinc7a12ae2007-09-27 15:42:23 +0000164 bool operator<(const Constraint &RHS) const {
165 if (RHS.Type != Type)
166 return RHS.Type < Type;
167 else if (RHS.Dest != Dest)
168 return RHS.Dest < Dest;
169 else if (RHS.Src != Src)
170 return RHS.Src < Src;
171 return RHS.Offset < Offset;
172 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000173 };
174
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000175 // Information DenseSet requires implemented in order to be able to do
176 // it's thing
177 struct PairKeyInfo {
178 static inline std::pair<unsigned, unsigned> getEmptyKey() {
Scott Michelacddf9d2008-03-18 16:55:06 +0000179 return std::make_pair(~0U, ~0U);
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000180 }
181 static inline std::pair<unsigned, unsigned> getTombstoneKey() {
Scott Michelacddf9d2008-03-18 16:55:06 +0000182 return std::make_pair(~0U - 1, ~0U - 1);
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000183 }
184 static unsigned getHashValue(const std::pair<unsigned, unsigned> &P) {
185 return P.first ^ P.second;
186 }
187 static unsigned isEqual(const std::pair<unsigned, unsigned> &LHS,
188 const std::pair<unsigned, unsigned> &RHS) {
189 return LHS == RHS;
190 }
191 };
192
Daniel Berlin336c6c02007-09-29 00:50:40 +0000193 struct ConstraintKeyInfo {
194 static inline Constraint getEmptyKey() {
Scott Michelacddf9d2008-03-18 16:55:06 +0000195 return Constraint(Constraint::Copy, ~0U, ~0U, ~0U);
Daniel Berlin336c6c02007-09-29 00:50:40 +0000196 }
197 static inline Constraint getTombstoneKey() {
Scott Michelacddf9d2008-03-18 16:55:06 +0000198 return Constraint(Constraint::Copy, ~0U - 1, ~0U - 1, ~0U - 1);
Daniel Berlin336c6c02007-09-29 00:50:40 +0000199 }
200 static unsigned getHashValue(const Constraint &C) {
201 return C.Src ^ C.Dest ^ C.Type ^ C.Offset;
202 }
203 static bool isEqual(const Constraint &LHS,
204 const Constraint &RHS) {
205 return LHS.Type == RHS.Type && LHS.Dest == RHS.Dest
206 && LHS.Src == RHS.Src && LHS.Offset == RHS.Offset;
207 }
208 };
209
Daniel Berlind81ccc22007-09-24 19:45:49 +0000210 // Node class - This class is used to represent a node in the constraint
Daniel Berline6f04792007-09-24 22:20:45 +0000211 // graph. Due to various optimizations, it is not always the case that
212 // there is a mapping from a Node to a Value. In particular, we add
213 // artificial Node's that represent the set of pointed-to variables shared
214 // for each location equivalent Node.
Daniel Berlinaad15882007-09-16 21:45:02 +0000215 struct Node {
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000216 private:
Owen Anderson5ec56cc2009-06-30 05:33:46 +0000217 static volatile sys::cas_flag Counter;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000218
219 public:
Daniel Berlind81ccc22007-09-24 19:45:49 +0000220 Value *Val;
Daniel Berlinaad15882007-09-16 21:45:02 +0000221 SparseBitVector<> *Edges;
222 SparseBitVector<> *PointsTo;
223 SparseBitVector<> *OldPointsTo;
Daniel Berlinaad15882007-09-16 21:45:02 +0000224 std::list<Constraint> Constraints;
225
Daniel Berlind81ccc22007-09-24 19:45:49 +0000226 // Pointer and location equivalence labels
227 unsigned PointerEquivLabel;
228 unsigned LocationEquivLabel;
229 // Predecessor edges, both real and implicit
230 SparseBitVector<> *PredEdges;
231 SparseBitVector<> *ImplicitPredEdges;
232 // Set of nodes that point to us, only use for location equivalence.
233 SparseBitVector<> *PointedToBy;
234 // Number of incoming edges, used during variable substitution to early
235 // free the points-to sets
236 unsigned NumInEdges;
Daniel Berline6f04792007-09-24 22:20:45 +0000237 // True if our points-to set is in the Set2PEClass map
Daniel Berlind81ccc22007-09-24 19:45:49 +0000238 bool StoredInHash;
Daniel Berline6f04792007-09-24 22:20:45 +0000239 // True if our node has no indirect constraints (complex or otherwise)
Daniel Berlind81ccc22007-09-24 19:45:49 +0000240 bool Direct;
241 // True if the node is address taken, *or* it is part of a group of nodes
242 // that must be kept together. This is set to true for functions and
243 // their arg nodes, which must be kept at the same position relative to
244 // their base function node.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000245 bool AddressTaken;
Daniel Berlinaad15882007-09-16 21:45:02 +0000246
Daniel Berlind81ccc22007-09-24 19:45:49 +0000247 // Nodes in cycles (or in equivalence classes) are united together using a
248 // standard union-find representation with path compression. NodeRep
249 // gives the index into GraphNodes for the representative Node.
250 unsigned NodeRep;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000251
252 // Modification timestamp. Assigned from Counter.
253 // Used for work list prioritization.
254 unsigned Timestamp;
Daniel Berlind81ccc22007-09-24 19:45:49 +0000255
Dan Gohmanded2b0d2007-12-14 15:41:34 +0000256 explicit Node(bool direct = true) :
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000257 Val(0), Edges(0), PointsTo(0), OldPointsTo(0),
Daniel Berlind81ccc22007-09-24 19:45:49 +0000258 PointerEquivLabel(0), LocationEquivLabel(0), PredEdges(0),
259 ImplicitPredEdges(0), PointedToBy(0), NumInEdges(0),
260 StoredInHash(false), Direct(direct), AddressTaken(false),
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000261 NodeRep(SelfRep), Timestamp(0) { }
Daniel Berlinaad15882007-09-16 21:45:02 +0000262
Chris Lattnere995a2a2004-05-23 21:00:47 +0000263 Node *setValue(Value *V) {
264 assert(Val == 0 && "Value already set for this node!");
265 Val = V;
266 return this;
267 }
268
269 /// getValue - Return the LLVM value corresponding to this node.
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000270 ///
Chris Lattnere995a2a2004-05-23 21:00:47 +0000271 Value *getValue() const { return Val; }
272
Chris Lattnere995a2a2004-05-23 21:00:47 +0000273 /// addPointerTo - Add a pointer to the list of pointees of this node,
274 /// returning true if this caused a new pointer to be added, or false if
275 /// we already knew about the points-to relation.
Daniel Berlinaad15882007-09-16 21:45:02 +0000276 bool addPointerTo(unsigned Node) {
277 return PointsTo->test_and_set(Node);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000278 }
279
280 /// intersects - Return true if the points-to set of this node intersects
281 /// with the points-to set of the specified node.
282 bool intersects(Node *N) const;
283
284 /// intersectsIgnoring - Return true if the points-to set of this node
285 /// intersects with the points-to set of the specified node on any nodes
286 /// except for the specified node to ignore.
Daniel Berlinaad15882007-09-16 21:45:02 +0000287 bool intersectsIgnoring(Node *N, unsigned) const;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000288
289 // Timestamp a node (used for work list prioritization)
290 void Stamp() {
Owen Anderson2d7f78e2009-06-25 16:32:45 +0000291 Timestamp = sys::AtomicIncrement(&Counter);
292 --Timestamp;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000293 }
294
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000295 bool isRep() const {
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000296 return( (int) NodeRep < 0 );
297 }
298 };
299
300 struct WorkListElement {
301 Node* node;
302 unsigned Timestamp;
303 WorkListElement(Node* n, unsigned t) : node(n), Timestamp(t) {}
304
305 // Note that we reverse the sense of the comparison because we
306 // actually want to give low timestamps the priority over high,
307 // whereas priority is typically interpreted as a greater value is
308 // given high priority.
309 bool operator<(const WorkListElement& that) const {
310 return( this->Timestamp > that.Timestamp );
311 }
312 };
313
314 // Priority-queue based work list specialized for Nodes.
315 class WorkList {
316 std::priority_queue<WorkListElement> Q;
317
318 public:
319 void insert(Node* n) {
320 Q.push( WorkListElement(n, n->Timestamp) );
321 }
322
323 // We automatically discard non-representative nodes and nodes
324 // that were in the work list twice (we keep a copy of the
325 // timestamp in the work list so we can detect this situation by
326 // comparing against the node's current timestamp).
327 Node* pop() {
328 while( !Q.empty() ) {
329 WorkListElement x = Q.top(); Q.pop();
330 Node* INode = x.node;
331
332 if( INode->isRep() &&
333 INode->Timestamp == x.Timestamp ) {
334 return(x.node);
335 }
336 }
337 return(0);
338 }
339
340 bool empty() {
341 return Q.empty();
342 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000343 };
344
345 /// GraphNodes - This vector is populated as part of the object
346 /// identification stage of the analysis, which populates this vector with a
347 /// node for each memory object and fills in the ValueNodes map.
348 std::vector<Node> GraphNodes;
349
350 /// ValueNodes - This map indicates the Node that a particular Value* is
351 /// represented by. This contains entries for all pointers.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000352 DenseMap<Value*, unsigned> ValueNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000353
354 /// ObjectNodes - This map contains entries for each memory object in the
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000355 /// program: globals, alloca's and mallocs.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000356 DenseMap<Value*, unsigned> ObjectNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000357
358 /// ReturnNodes - This map contains an entry for each function in the
359 /// program that returns a value.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000360 DenseMap<Function*, unsigned> ReturnNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000361
362 /// VarargNodes - This map contains the entry used to represent all pointers
363 /// passed through the varargs portion of a function call for a particular
364 /// function. An entry is not present in this map for functions that do not
365 /// take variable arguments.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000366 DenseMap<Function*, unsigned> VarargNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000367
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000368
Chris Lattnere995a2a2004-05-23 21:00:47 +0000369 /// Constraints - This vector contains a list of all of the constraints
370 /// identified by the program.
371 std::vector<Constraint> Constraints;
372
Daniel Berlind81ccc22007-09-24 19:45:49 +0000373 // Map from graph node to maximum K value that is allowed (for functions,
Daniel Berlinaad15882007-09-16 21:45:02 +0000374 // this is equivalent to the number of arguments + CallFirstArgPos)
375 std::map<unsigned, unsigned> MaxK;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000376
377 /// This enum defines the GraphNodes indices that correspond to important
378 /// fixed sets.
379 enum {
380 UniversalSet = 0,
381 NullPtr = 1,
Daniel Berlind81ccc22007-09-24 19:45:49 +0000382 NullObject = 2,
383 NumberSpecialNodes
Chris Lattnere995a2a2004-05-23 21:00:47 +0000384 };
Daniel Berlind81ccc22007-09-24 19:45:49 +0000385 // Stack for Tarjan's
Daniel Berlinaad15882007-09-16 21:45:02 +0000386 std::stack<unsigned> SCCStack;
Daniel Berlinaad15882007-09-16 21:45:02 +0000387 // Map from Graph Node to DFS number
388 std::vector<unsigned> Node2DFS;
389 // Map from Graph Node to Deleted from graph.
390 std::vector<bool> Node2Deleted;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000391 // Same as Node Maps, but implemented as std::map because it is faster to
392 // clear
393 std::map<unsigned, unsigned> Tarjan2DFS;
394 std::map<unsigned, bool> Tarjan2Deleted;
395 // Current DFS number
Daniel Berlinaad15882007-09-16 21:45:02 +0000396 unsigned DFSNumber;
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000397
398 // Work lists.
399 WorkList w1, w2;
400 WorkList *CurrWL, *NextWL; // "current" and "next" work lists
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000401
Daniel Berlind81ccc22007-09-24 19:45:49 +0000402 // Offline variable substitution related things
403
404 // Temporary rep storage, used because we can't collapse SCC's in the
405 // predecessor graph by uniting the variables permanently, we can only do so
406 // for the successor graph.
407 std::vector<unsigned> VSSCCRep;
408 // Mapping from node to whether we have visited it during SCC finding yet.
409 std::vector<bool> Node2Visited;
410 // During variable substitution, we create unknowns to represent the unknown
411 // value that is a dereference of a variable. These nodes are known as
412 // "ref" nodes (since they represent the value of dereferences).
413 unsigned FirstRefNode;
414 // During HVN, we create represent address taken nodes as if they were
415 // unknown (since HVN, unlike HU, does not evaluate unions).
416 unsigned FirstAdrNode;
417 // Current pointer equivalence class number
418 unsigned PEClass;
419 // Mapping from points-to sets to equivalence classes
420 typedef DenseMap<SparseBitVector<> *, unsigned, BitmapKeyInfo> BitVectorMap;
421 BitVectorMap Set2PEClass;
422 // Mapping from pointer equivalences to the representative node. -1 if we
423 // have no representative node for this pointer equivalence class yet.
424 std::vector<int> PEClass2Node;
425 // Mapping from pointer equivalences to representative node. This includes
426 // pointer equivalent but not location equivalent variables. -1 if we have
427 // no representative node for this pointer equivalence class yet.
428 std::vector<int> PENLEClass2Node;
Daniel Berlinc864edb2008-03-05 19:31:47 +0000429 // Union/Find for HCD
430 std::vector<unsigned> HCDSCCRep;
431 // HCD's offline-detected cycles; "Statically DeTected"
432 // -1 if not part of such a cycle, otherwise a representative node.
433 std::vector<int> SDT;
434 // Whether to use SDT (UniteNodes can use it during solving, but not before)
435 bool SDTActive;
Daniel Berlind81ccc22007-09-24 19:45:49 +0000436
Chris Lattnere995a2a2004-05-23 21:00:47 +0000437 public:
Daniel Berlinaad15882007-09-16 21:45:02 +0000438 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +0000439 Andersens() : ModulePass(&ID) {}
Devang Patel1cee94f2008-03-18 00:39:19 +0000440
Chris Lattnerb12914b2004-09-20 04:48:05 +0000441 bool runOnModule(Module &M) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000442 InitializeAliasAnalysis(this);
443 IdentifyObjects(M);
444 CollectConstraints(M);
Daniel Berlind81ccc22007-09-24 19:45:49 +0000445#undef DEBUG_TYPE
446#define DEBUG_TYPE "anders-aa-constraints"
Chris Lattnere995a2a2004-05-23 21:00:47 +0000447 DEBUG(PrintConstraints());
Daniel Berlind81ccc22007-09-24 19:45:49 +0000448#undef DEBUG_TYPE
449#define DEBUG_TYPE "anders-aa"
Chris Lattnere995a2a2004-05-23 21:00:47 +0000450 SolveConstraints();
451 DEBUG(PrintPointsToGraph());
452
453 // Free the constraints list, as we don't need it to respond to alias
454 // requests.
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000455 std::vector<Constraint>().swap(Constraints);
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000456 //These are needed for Print() (-analyze in opt)
457 //ObjectNodes.clear();
458 //ReturnNodes.clear();
459 //VarargNodes.clear();
Chris Lattnere995a2a2004-05-23 21:00:47 +0000460 return false;
461 }
462
463 void releaseMemory() {
464 // FIXME: Until we have transitively required passes working correctly,
465 // this cannot be enabled! Otherwise, using -count-aa with the pass
466 // causes memory to be freed too early. :(
467#if 0
468 // The memory objects and ValueNodes data structures at the only ones that
469 // are still live after construction.
470 std::vector<Node>().swap(GraphNodes);
471 ValueNodes.clear();
472#endif
473 }
474
475 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
476 AliasAnalysis::getAnalysisUsage(AU);
477 AU.setPreservesAll(); // Does not transform code
478 }
479
480 //------------------------------------------------
481 // Implement the AliasAnalysis API
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000482 //
Chris Lattnere995a2a2004-05-23 21:00:47 +0000483 AliasResult alias(const Value *V1, unsigned V1Size,
484 const Value *V2, unsigned V2Size);
Reid Spencer3a9ec242006-08-28 01:02:49 +0000485 virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
486 virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000487 void getMustAliases(Value *P, std::vector<Value*> &RetVals);
488 bool pointsToConstantMemory(const Value *P);
489
490 virtual void deleteValue(Value *V) {
491 ValueNodes.erase(V);
492 getAnalysis<AliasAnalysis>().deleteValue(V);
493 }
494
495 virtual void copyValue(Value *From, Value *To) {
496 ValueNodes[To] = ValueNodes[From];
497 getAnalysis<AliasAnalysis>().copyValue(From, To);
498 }
499
500 private:
501 /// getNode - Return the node corresponding to the specified pointer scalar.
502 ///
Daniel Berlinaad15882007-09-16 21:45:02 +0000503 unsigned getNode(Value *V) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000504 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattnerdf9b7bc2004-08-16 05:38:02 +0000505 if (!isa<GlobalValue>(C))
506 return getNodeForConstantPointer(C);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000507
Daniel Berlind81ccc22007-09-24 19:45:49 +0000508 DenseMap<Value*, unsigned>::iterator I = ValueNodes.find(V);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000509 if (I == ValueNodes.end()) {
Jim Laskey16d42c62006-07-11 18:25:13 +0000510#ifndef NDEBUG
511 V->dump();
512#endif
Torok Edwinc23197a2009-07-14 16:55:14 +0000513 llvm_unreachable("Value does not have a node in the points-to graph!");
Chris Lattnere995a2a2004-05-23 21:00:47 +0000514 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000515 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000516 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000517
Chris Lattnere995a2a2004-05-23 21:00:47 +0000518 /// getObject - Return the node corresponding to the memory object for the
519 /// specified global or allocation instruction.
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000520 unsigned getObject(Value *V) const {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000521 DenseMap<Value*, unsigned>::iterator I = ObjectNodes.find(V);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000522 assert(I != ObjectNodes.end() &&
523 "Value does not have an object in the points-to graph!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000524 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000525 }
526
527 /// getReturnNode - Return the node representing the return value for the
528 /// specified function.
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000529 unsigned getReturnNode(Function *F) const {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000530 DenseMap<Function*, unsigned>::iterator I = ReturnNodes.find(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000531 assert(I != ReturnNodes.end() && "Function does not return a value!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000532 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000533 }
534
535 /// getVarargNode - Return the node representing the variable arguments
536 /// formal for the specified function.
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000537 unsigned getVarargNode(Function *F) const {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000538 DenseMap<Function*, unsigned>::iterator I = VarargNodes.find(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000539 assert(I != VarargNodes.end() && "Function does not take var args!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000540 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000541 }
542
543 /// getNodeValue - Get the node for the specified LLVM value and set the
544 /// value for it to be the specified value.
Daniel Berlinaad15882007-09-16 21:45:02 +0000545 unsigned getNodeValue(Value &V) {
546 unsigned Index = getNode(&V);
547 GraphNodes[Index].setValue(&V);
548 return Index;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000549 }
550
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000551 unsigned UniteNodes(unsigned First, unsigned Second,
552 bool UnionByRank = true);
Daniel Berlinaad15882007-09-16 21:45:02 +0000553 unsigned FindNode(unsigned Node);
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000554 unsigned FindNode(unsigned Node) const;
Daniel Berlinaad15882007-09-16 21:45:02 +0000555
Chris Lattnere995a2a2004-05-23 21:00:47 +0000556 void IdentifyObjects(Module &M);
557 void CollectConstraints(Module &M);
Daniel Berlinaad15882007-09-16 21:45:02 +0000558 bool AnalyzeUsesOfFunction(Value *);
559 void CreateConstraintGraph();
Daniel Berlind81ccc22007-09-24 19:45:49 +0000560 void OptimizeConstraints();
561 unsigned FindEquivalentNode(unsigned, unsigned);
562 void ClumpAddressTaken();
563 void RewriteConstraints();
564 void HU();
565 void HVN();
Daniel Berlinc864edb2008-03-05 19:31:47 +0000566 void HCD();
567 void Search(unsigned Node);
Daniel Berlind81ccc22007-09-24 19:45:49 +0000568 void UnitePointerEquivalences();
Chris Lattnere995a2a2004-05-23 21:00:47 +0000569 void SolveConstraints();
Daniel Berlin3a3f1632007-12-12 00:37:04 +0000570 bool QueryNode(unsigned Node);
Daniel Berlind81ccc22007-09-24 19:45:49 +0000571 void Condense(unsigned Node);
572 void HUValNum(unsigned Node);
573 void HVNValNum(unsigned Node);
Daniel Berlinaad15882007-09-16 21:45:02 +0000574 unsigned getNodeForConstantPointer(Constant *C);
575 unsigned getNodeForConstantPointerTarget(Constant *C);
576 void AddGlobalInitializerConstraints(unsigned, Constant *C);
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000577
Chris Lattnere995a2a2004-05-23 21:00:47 +0000578 void AddConstraintsForNonInternalLinkage(Function *F);
579 void AddConstraintsForCall(CallSite CS, Function *F);
Chris Lattner8a446432005-03-29 06:09:07 +0000580 bool AddConstraintsForExternalCall(CallSite CS, Function *F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000581
582
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000583 void PrintNode(const Node *N) const;
584 void PrintConstraints() const ;
585 void PrintConstraint(const Constraint &) const;
586 void PrintLabels() const;
587 void PrintPointsToGraph() const;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000588
589 //===------------------------------------------------------------------===//
590 // Instruction visitation methods for adding constraints
591 //
592 friend class InstVisitor<Andersens>;
593 void visitReturnInst(ReturnInst &RI);
594 void visitInvokeInst(InvokeInst &II) { visitCallSite(CallSite(&II)); }
Victor Hernandez46e83122009-09-18 21:34:51 +0000595 void visitCallInst(CallInst &CI) {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000596 if (isMalloc(&CI)) visitAlloc(CI);
Victor Hernandez46e83122009-09-18 21:34:51 +0000597 else visitCallSite(CallSite(&CI));
598 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000599 void visitCallSite(CallSite CS);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000600 void visitAllocaInst(AllocaInst &I);
601 void visitAlloc(Instruction &I);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000602 void visitLoadInst(LoadInst &LI);
603 void visitStoreInst(StoreInst &SI);
604 void visitGetElementPtrInst(GetElementPtrInst &GEP);
605 void visitPHINode(PHINode &PN);
606 void visitCastInst(CastInst &CI);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000607 void visitICmpInst(ICmpInst &ICI) {} // NOOP!
608 void visitFCmpInst(FCmpInst &ICI) {} // NOOP!
Chris Lattnere995a2a2004-05-23 21:00:47 +0000609 void visitSelectInst(SelectInst &SI);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000610 void visitVAArg(VAArgInst &I);
611 void visitInstruction(Instruction &I);
Daniel Berlinaad15882007-09-16 21:45:02 +0000612
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000613 //===------------------------------------------------------------------===//
614 // Implement Analyize interface
615 //
Chris Lattner45cfe542009-08-23 06:03:38 +0000616 void print(raw_ostream &O, const Module*) const {
Andrew Lenharth52d34d92008-03-20 15:36:44 +0000617 PrintPointsToGraph();
618 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000619 };
Chris Lattnere995a2a2004-05-23 21:00:47 +0000620}
621
Dan Gohman844731a2008-05-13 00:00:25 +0000622char Andersens::ID = 0;
623static RegisterPass<Andersens>
Chris Lattnerb80e1ab2009-08-28 00:45:47 +0000624X("anders-aa", "Andersen's Interprocedural Alias Analysis (experimental)",
625 false, true);
Dan Gohman844731a2008-05-13 00:00:25 +0000626static RegisterAnalysisGroup<AliasAnalysis> Y(X);
627
628// Initialize Timestamp Counter (static).
Owen Anderson5ec56cc2009-06-30 05:33:46 +0000629volatile llvm::sys::cas_flag Andersens::Node::Counter = 0;
Dan Gohman844731a2008-05-13 00:00:25 +0000630
Jeff Cohen534927d2005-01-08 22:01:16 +0000631ModulePass *llvm::createAndersensPass() { return new Andersens(); }
632
Chris Lattnere995a2a2004-05-23 21:00:47 +0000633//===----------------------------------------------------------------------===//
634// AliasAnalysis Interface Implementation
635//===----------------------------------------------------------------------===//
636
637AliasAnalysis::AliasResult Andersens::alias(const Value *V1, unsigned V1Size,
638 const Value *V2, unsigned V2Size) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000639 Node *N1 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V1)))];
640 Node *N2 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V2)))];
Chris Lattnere995a2a2004-05-23 21:00:47 +0000641
642 // Check to see if the two pointers are known to not alias. They don't alias
643 // if their points-to sets do not intersect.
Daniel Berlinaad15882007-09-16 21:45:02 +0000644 if (!N1->intersectsIgnoring(N2, NullObject))
Chris Lattnere995a2a2004-05-23 21:00:47 +0000645 return NoAlias;
646
647 return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
648}
649
Chris Lattnerf392c642005-03-28 06:21:17 +0000650AliasAnalysis::ModRefResult
651Andersens::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
652 // The only thing useful that we can contribute for mod/ref information is
653 // when calling external function calls: if we know that memory never escapes
654 // from the program, it cannot be modified by an external call.
655 //
656 // NOTE: This is not really safe, at least not when the entire program is not
657 // available. The deal is that the external function could call back into the
658 // program and modify stuff. We ignore this technical niggle for now. This
659 // is, after all, a "research quality" implementation of Andersen's analysis.
660 if (Function *F = CS.getCalledFunction())
Reid Spencer5cbf9852007-01-30 20:08:39 +0000661 if (F->isDeclaration()) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000662 Node *N1 = &GraphNodes[FindNode(getNode(P))];
Chris Lattnerf392c642005-03-28 06:21:17 +0000663
Daniel Berlinaad15882007-09-16 21:45:02 +0000664 if (N1->PointsTo->empty())
665 return NoModRef;
Daniel Berlind3bf1ae2008-03-18 22:22:53 +0000666#if FULL_UNIVERSAL
667 if (!UniversalSet->PointsTo->test(FindNode(getNode(P))))
668 return NoModRef; // Universal set does not contain P
669#else
Daniel Berlinaad15882007-09-16 21:45:02 +0000670 if (!N1->PointsTo->test(UniversalSet))
Chris Lattnerf392c642005-03-28 06:21:17 +0000671 return NoModRef; // P doesn't point to the universal set.
Daniel Berlind3bf1ae2008-03-18 22:22:53 +0000672#endif
Chris Lattnerf392c642005-03-28 06:21:17 +0000673 }
674
675 return AliasAnalysis::getModRefInfo(CS, P, Size);
676}
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000677
Reid Spencer3a9ec242006-08-28 01:02:49 +0000678AliasAnalysis::ModRefResult
679Andersens::getModRefInfo(CallSite CS1, CallSite CS2) {
680 return AliasAnalysis::getModRefInfo(CS1,CS2);
681}
682
Chris Lattnere995a2a2004-05-23 21:00:47 +0000683/// getMustAlias - We can provide must alias information if we know that a
684/// pointer can only point to a specific function or the null pointer.
685/// Unfortunately we cannot determine must-alias information for global
686/// variables or any other memory memory objects because we do not track whether
687/// a pointer points to the beginning of an object or a field of it.
688void Andersens::getMustAliases(Value *P, std::vector<Value*> &RetVals) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000689 Node *N = &GraphNodes[FindNode(getNode(P))];
690 if (N->PointsTo->count() == 1) {
691 Node *Pointee = &GraphNodes[N->PointsTo->find_first()];
692 // If a function is the only object in the points-to set, then it must be
693 // the destination. Note that we can't handle global variables here,
694 // because we don't know if the pointer is actually pointing to a field of
695 // the global or to the beginning of it.
696 if (Value *V = Pointee->getValue()) {
697 if (Function *F = dyn_cast<Function>(V))
698 RetVals.push_back(F);
699 } else {
700 // If the object in the points-to set is the null object, then the null
701 // pointer is a must alias.
702 if (Pointee == &GraphNodes[NullObject])
Owen Andersona7235ea2009-07-31 20:28:14 +0000703 RetVals.push_back(Constant::getNullValue(P->getType()));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000704 }
705 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000706 AliasAnalysis::getMustAliases(P, RetVals);
707}
708
709/// pointsToConstantMemory - If we can determine that this pointer only points
710/// to constant memory, return true. In practice, this means that if the
711/// pointer can only point to constant globals, functions, or the null pointer,
712/// return true.
713///
714bool Andersens::pointsToConstantMemory(const Value *P) {
Dan Gohman6a551e72008-02-21 17:33:24 +0000715 Node *N = &GraphNodes[FindNode(getNode(const_cast<Value*>(P)))];
Daniel Berlinaad15882007-09-16 21:45:02 +0000716 unsigned i;
717
718 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
719 bi != N->PointsTo->end();
720 ++bi) {
721 i = *bi;
722 Node *Pointee = &GraphNodes[i];
723 if (Value *V = Pointee->getValue()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000724 if (!isa<GlobalValue>(V) || (isa<GlobalVariable>(V) &&
725 !cast<GlobalVariable>(V)->isConstant()))
726 return AliasAnalysis::pointsToConstantMemory(P);
727 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +0000728 if (i != NullObject)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000729 return AliasAnalysis::pointsToConstantMemory(P);
730 }
731 }
732
733 return true;
734}
735
736//===----------------------------------------------------------------------===//
737// Object Identification Phase
738//===----------------------------------------------------------------------===//
739
740/// IdentifyObjects - This stage scans the program, adding an entry to the
741/// GraphNodes list for each memory object in the program (global stack or
742/// heap), and populates the ValueNodes and ObjectNodes maps for these objects.
743///
744void Andersens::IdentifyObjects(Module &M) {
745 unsigned NumObjects = 0;
746
747 // Object #0 is always the universal set: the object that we don't know
748 // anything about.
749 assert(NumObjects == UniversalSet && "Something changed!");
750 ++NumObjects;
751
752 // Object #1 always represents the null pointer.
753 assert(NumObjects == NullPtr && "Something changed!");
754 ++NumObjects;
755
756 // Object #2 always represents the null object (the object pointed to by null)
757 assert(NumObjects == NullObject && "Something changed!");
758 ++NumObjects;
759
760 // Add all the globals first.
Chris Lattner493f6362005-03-27 22:03:46 +0000761 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
762 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000763 ObjectNodes[I] = NumObjects++;
764 ValueNodes[I] = NumObjects++;
765 }
766
767 // Add nodes for all of the functions and the instructions inside of them.
768 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
769 // The function itself is a memory object.
Daniel Berlinaad15882007-09-16 21:45:02 +0000770 unsigned First = NumObjects;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000771 ValueNodes[F] = NumObjects++;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000772 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
773 ReturnNodes[F] = NumObjects++;
774 if (F->getFunctionType()->isVarArg())
775 VarargNodes[F] = NumObjects++;
776
Daniel Berlinaad15882007-09-16 21:45:02 +0000777
Chris Lattnere995a2a2004-05-23 21:00:47 +0000778 // Add nodes for all of the incoming pointer arguments.
Chris Lattner493f6362005-03-27 22:03:46 +0000779 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
780 I != E; ++I)
Daniel Berlind81ccc22007-09-24 19:45:49 +0000781 {
782 if (isa<PointerType>(I->getType()))
783 ValueNodes[I] = NumObjects++;
784 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000785 MaxK[First] = NumObjects - First;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000786
787 // Scan the function body, creating a memory object for each heap/stack
788 // allocation in the body of the function and a node to represent all
789 // pointer values defined by instructions and used as operands.
790 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
791 // If this is an heap or stack allocation, create a node for the memory
792 // object.
793 if (isa<PointerType>(II->getType())) {
794 ValueNodes[&*II] = NumObjects++;
Victor Hernandez7b929da2009-10-23 21:09:37 +0000795 if (AllocaInst *AI = dyn_cast<AllocaInst>(&*II))
Chris Lattnere995a2a2004-05-23 21:00:47 +0000796 ObjectNodes[AI] = NumObjects++;
Victor Hernandez46e83122009-09-18 21:34:51 +0000797 else if (isMalloc(&*II))
798 ObjectNodes[&*II] = NumObjects++;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000799 }
Nick Lewycky4ac0e8d2007-11-22 03:07:37 +0000800
801 // Calls to inline asm need to be added as well because the callee isn't
802 // referenced anywhere else.
803 if (CallInst *CI = dyn_cast<CallInst>(&*II)) {
804 Value *Callee = CI->getCalledValue();
805 if (isa<InlineAsm>(Callee))
806 ValueNodes[Callee] = NumObjects++;
807 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000808 }
809 }
810
811 // Now that we know how many objects to create, make them all now!
812 GraphNodes.resize(NumObjects);
813 NumNodes += NumObjects;
814}
815
816//===----------------------------------------------------------------------===//
817// Constraint Identification Phase
818//===----------------------------------------------------------------------===//
819
820/// getNodeForConstantPointer - Return the node corresponding to the constant
821/// pointer itself.
Daniel Berlinaad15882007-09-16 21:45:02 +0000822unsigned Andersens::getNodeForConstantPointer(Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000823 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
824
Chris Lattner267a1b02005-03-27 18:58:23 +0000825 if (isa<ConstantPointerNull>(C) || isa<UndefValue>(C))
Daniel Berlinaad15882007-09-16 21:45:02 +0000826 return NullPtr;
Reid Spencere8404342004-07-18 00:18:30 +0000827 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
828 return getNode(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000829 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
830 switch (CE->getOpcode()) {
831 case Instruction::GetElementPtr:
832 return getNodeForConstantPointer(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000833 case Instruction::IntToPtr:
Daniel Berlinaad15882007-09-16 21:45:02 +0000834 return UniversalSet;
Reid Spencer3da59db2006-11-27 01:05:10 +0000835 case Instruction::BitCast:
836 return getNodeForConstantPointer(CE->getOperand(0));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000837 default:
Daniel Dunbar3f0e8302009-07-24 09:53:24 +0000838 errs() << "Constant Expr not yet handled: " << *CE << "\n";
Torok Edwinc23197a2009-07-14 16:55:14 +0000839 llvm_unreachable(0);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000840 }
841 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +0000842 llvm_unreachable("Unknown constant pointer!");
Chris Lattnere995a2a2004-05-23 21:00:47 +0000843 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000844 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000845}
846
847/// getNodeForConstantPointerTarget - Return the node POINTED TO by the
848/// specified constant pointer.
Daniel Berlinaad15882007-09-16 21:45:02 +0000849unsigned Andersens::getNodeForConstantPointerTarget(Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000850 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
851
852 if (isa<ConstantPointerNull>(C))
Daniel Berlinaad15882007-09-16 21:45:02 +0000853 return NullObject;
Reid Spencere8404342004-07-18 00:18:30 +0000854 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
855 return getObject(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000856 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
857 switch (CE->getOpcode()) {
858 case Instruction::GetElementPtr:
859 return getNodeForConstantPointerTarget(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000860 case Instruction::IntToPtr:
Daniel Berlinaad15882007-09-16 21:45:02 +0000861 return UniversalSet;
Reid Spencer3da59db2006-11-27 01:05:10 +0000862 case Instruction::BitCast:
863 return getNodeForConstantPointerTarget(CE->getOperand(0));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000864 default:
Daniel Dunbar3f0e8302009-07-24 09:53:24 +0000865 errs() << "Constant Expr not yet handled: " << *CE << "\n";
Torok Edwinc23197a2009-07-14 16:55:14 +0000866 llvm_unreachable(0);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000867 }
868 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +0000869 llvm_unreachable("Unknown constant pointer!");
Chris Lattnere995a2a2004-05-23 21:00:47 +0000870 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000871 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000872}
873
874/// AddGlobalInitializerConstraints - Add inclusion constraints for the memory
875/// object N, which contains values indicated by C.
Daniel Berlinaad15882007-09-16 21:45:02 +0000876void Andersens::AddGlobalInitializerConstraints(unsigned NodeIndex,
877 Constant *C) {
Dan Gohmanb64aa112008-05-22 23:43:22 +0000878 if (C->getType()->isSingleValueType()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000879 if (isa<PointerType>(C->getType()))
Daniel Berlinaad15882007-09-16 21:45:02 +0000880 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
881 getNodeForConstantPointer(C)));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000882 } else if (C->isNullValue()) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000883 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
884 NullObject));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000885 return;
Chris Lattner8a446432005-03-29 06:09:07 +0000886 } else if (!isa<UndefValue>(C)) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000887 // If this is an array or struct, include constraints for each element.
888 assert(isa<ConstantArray>(C) || isa<ConstantStruct>(C));
889 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
Daniel Berlinaad15882007-09-16 21:45:02 +0000890 AddGlobalInitializerConstraints(NodeIndex,
891 cast<Constant>(C->getOperand(i)));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000892 }
893}
894
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000895/// AddConstraintsForNonInternalLinkage - If this function does not have
896/// internal linkage, realize that we can't trust anything passed into or
897/// returned by this function.
Chris Lattnere995a2a2004-05-23 21:00:47 +0000898void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
Chris Lattnere4d5c442005-03-15 04:54:21 +0000899 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000900 if (isa<PointerType>(I->getType()))
901 // If this is an argument of an externally accessible function, the
902 // incoming pointer might point to anything.
903 Constraints.push_back(Constraint(Constraint::Copy, getNode(I),
Daniel Berlinaad15882007-09-16 21:45:02 +0000904 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000905}
906
Chris Lattner8a446432005-03-29 06:09:07 +0000907/// AddConstraintsForCall - If this is a call to a "known" function, add the
908/// constraints and return true. If this is a call to an unknown function,
909/// return false.
910bool Andersens::AddConstraintsForExternalCall(CallSite CS, Function *F) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000911 assert(F->isDeclaration() && "Not an external function!");
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000912
913 // These functions don't induce any points-to constraints.
Chris Lattner175b9632005-03-29 20:36:05 +0000914 if (F->getName() == "atoi" || F->getName() == "atof" ||
915 F->getName() == "atol" || F->getName() == "atoll" ||
916 F->getName() == "remove" || F->getName() == "unlink" ||
917 F->getName() == "rename" || F->getName() == "memcmp" ||
Chris Lattner824b9582008-11-21 16:42:48 +0000918 F->getName() == "llvm.memset" ||
Chris Lattner175b9632005-03-29 20:36:05 +0000919 F->getName() == "strcmp" || F->getName() == "strncmp" ||
920 F->getName() == "execl" || F->getName() == "execlp" ||
921 F->getName() == "execle" || F->getName() == "execv" ||
922 F->getName() == "execvp" || F->getName() == "chmod" ||
923 F->getName() == "puts" || F->getName() == "write" ||
924 F->getName() == "open" || F->getName() == "create" ||
925 F->getName() == "truncate" || F->getName() == "chdir" ||
926 F->getName() == "mkdir" || F->getName() == "rmdir" ||
927 F->getName() == "read" || F->getName() == "pipe" ||
928 F->getName() == "wait" || F->getName() == "time" ||
929 F->getName() == "stat" || F->getName() == "fstat" ||
930 F->getName() == "lstat" || F->getName() == "strtod" ||
931 F->getName() == "strtof" || F->getName() == "strtold" ||
932 F->getName() == "fopen" || F->getName() == "fdopen" ||
933 F->getName() == "freopen" ||
934 F->getName() == "fflush" || F->getName() == "feof" ||
935 F->getName() == "fileno" || F->getName() == "clearerr" ||
936 F->getName() == "rewind" || F->getName() == "ftell" ||
937 F->getName() == "ferror" || F->getName() == "fgetc" ||
938 F->getName() == "fgetc" || F->getName() == "_IO_getc" ||
939 F->getName() == "fwrite" || F->getName() == "fread" ||
940 F->getName() == "fgets" || F->getName() == "ungetc" ||
941 F->getName() == "fputc" ||
942 F->getName() == "fputs" || F->getName() == "putc" ||
943 F->getName() == "ftell" || F->getName() == "rewind" ||
944 F->getName() == "_IO_putc" || F->getName() == "fseek" ||
945 F->getName() == "fgetpos" || F->getName() == "fsetpos" ||
946 F->getName() == "printf" || F->getName() == "fprintf" ||
947 F->getName() == "sprintf" || F->getName() == "vprintf" ||
948 F->getName() == "vfprintf" || F->getName() == "vsprintf" ||
949 F->getName() == "scanf" || F->getName() == "fscanf" ||
950 F->getName() == "sscanf" || F->getName() == "__assert_fail" ||
951 F->getName() == "modf")
Chris Lattner8a446432005-03-29 06:09:07 +0000952 return true;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000953
Chris Lattner175b9632005-03-29 20:36:05 +0000954
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000955 // These functions do induce points-to edges.
Chris Lattner824b9582008-11-21 16:42:48 +0000956 if (F->getName() == "llvm.memcpy" ||
957 F->getName() == "llvm.memmove" ||
Chris Lattner4de57fd2005-03-29 06:52:20 +0000958 F->getName() == "memmove") {
Daniel Berlinaad15882007-09-16 21:45:02 +0000959
Nick Lewycky3037eda2008-12-27 16:20:53 +0000960 const FunctionType *FTy = F->getFunctionType();
961 if (FTy->getNumParams() > 1 &&
962 isa<PointerType>(FTy->getParamType(0)) &&
963 isa<PointerType>(FTy->getParamType(1))) {
964
965 // *Dest = *Src, which requires an artificial graph node to represent the
966 // constraint. It is broken up into *Dest = temp, temp = *Src
967 unsigned FirstArg = getNode(CS.getArgument(0));
968 unsigned SecondArg = getNode(CS.getArgument(1));
969 unsigned TempArg = GraphNodes.size();
970 GraphNodes.push_back(Node());
971 Constraints.push_back(Constraint(Constraint::Store,
972 FirstArg, TempArg));
973 Constraints.push_back(Constraint(Constraint::Load,
974 TempArg, SecondArg));
975 // In addition, Dest = Src
976 Constraints.push_back(Constraint(Constraint::Copy,
977 FirstArg, SecondArg));
978 return true;
979 }
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000980 }
981
Chris Lattner77b50562005-03-29 20:04:24 +0000982 // Result = Arg0
983 if (F->getName() == "realloc" || F->getName() == "strchr" ||
984 F->getName() == "strrchr" || F->getName() == "strstr" ||
985 F->getName() == "strtok") {
Nick Lewycky3037eda2008-12-27 16:20:53 +0000986 const FunctionType *FTy = F->getFunctionType();
987 if (FTy->getNumParams() > 0 &&
988 isa<PointerType>(FTy->getParamType(0))) {
989 Constraints.push_back(Constraint(Constraint::Copy,
990 getNode(CS.getInstruction()),
991 getNode(CS.getArgument(0))));
992 return true;
993 }
Chris Lattner8a446432005-03-29 06:09:07 +0000994 }
995
996 return false;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000997}
998
999
Chris Lattnere995a2a2004-05-23 21:00:47 +00001000
Daniel Berlinaad15882007-09-16 21:45:02 +00001001/// AnalyzeUsesOfFunction - Look at all of the users of the specified function.
1002/// If this is used by anything complex (i.e., the address escapes), return
1003/// true.
1004bool Andersens::AnalyzeUsesOfFunction(Value *V) {
1005
1006 if (!isa<PointerType>(V->getType())) return true;
1007
1008 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
Dan Gohman104eac12009-08-11 17:20:16 +00001009 if (isa<LoadInst>(*UI)) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001010 return false;
1011 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
1012 if (V == SI->getOperand(1)) {
1013 return false;
1014 } else if (SI->getOperand(1)) {
1015 return true; // Storing the pointer
1016 }
1017 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1018 if (AnalyzeUsesOfFunction(GEP)) return true;
Victor Hernandez046e78c2009-10-26 23:43:48 +00001019 } else if (isFreeCall(*UI)) {
Victor Hernandez66284e02009-10-24 04:23:03 +00001020 return false;
Daniel Berlinaad15882007-09-16 21:45:02 +00001021 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
1022 // Make sure that this is just the function being called, not that it is
1023 // passing into the function.
1024 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
1025 if (CI->getOperand(i) == V) return true;
1026 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
1027 // Make sure that this is just the function being called, not that it is
1028 // passing into the function.
Gabor Greif03a5f132009-09-03 02:02:59 +00001029 for (unsigned i = 3, e = II->getNumOperands(); i != e; ++i)
Daniel Berlinaad15882007-09-16 21:45:02 +00001030 if (II->getOperand(i) == V) return true;
1031 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
1032 if (CE->getOpcode() == Instruction::GetElementPtr ||
1033 CE->getOpcode() == Instruction::BitCast) {
1034 if (AnalyzeUsesOfFunction(CE))
1035 return true;
1036 } else {
1037 return true;
1038 }
1039 } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(*UI)) {
1040 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1041 return true; // Allow comparison against null.
Daniel Berlinaad15882007-09-16 21:45:02 +00001042 } else {
1043 return true;
1044 }
1045 return false;
1046}
1047
Chris Lattnere995a2a2004-05-23 21:00:47 +00001048/// CollectConstraints - This stage scans the program, adding a constraint to
1049/// the Constraints list for each instruction in the program that induces a
1050/// constraint, and setting up the initial points-to graph.
1051///
1052void Andersens::CollectConstraints(Module &M) {
1053 // First, the universal set points to itself.
Daniel Berlinaad15882007-09-16 21:45:02 +00001054 Constraints.push_back(Constraint(Constraint::AddressOf, UniversalSet,
1055 UniversalSet));
1056 Constraints.push_back(Constraint(Constraint::Store, UniversalSet,
1057 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001058
1059 // Next, the null pointer points to the null object.
Daniel Berlinaad15882007-09-16 21:45:02 +00001060 Constraints.push_back(Constraint(Constraint::AddressOf, NullPtr, NullObject));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001061
1062 // Next, add any constraints on global variables and their initializers.
Chris Lattner493f6362005-03-27 22:03:46 +00001063 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1064 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001065 // Associate the address of the global object as pointing to the memory for
1066 // the global: &G = <G memory>
Daniel Berlinaad15882007-09-16 21:45:02 +00001067 unsigned ObjectIndex = getObject(I);
1068 Node *Object = &GraphNodes[ObjectIndex];
Chris Lattnere995a2a2004-05-23 21:00:47 +00001069 Object->setValue(I);
Daniel Berlinaad15882007-09-16 21:45:02 +00001070 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(*I),
1071 ObjectIndex));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001072
Dan Gohman82555732009-08-19 18:20:44 +00001073 if (I->hasDefinitiveInitializer()) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001074 AddGlobalInitializerConstraints(ObjectIndex, I->getInitializer());
Chris Lattnere995a2a2004-05-23 21:00:47 +00001075 } else {
1076 // If it doesn't have an initializer (i.e. it's defined in another
1077 // translation unit), it points to the universal set.
Daniel Berlinaad15882007-09-16 21:45:02 +00001078 Constraints.push_back(Constraint(Constraint::Copy, ObjectIndex,
1079 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001080 }
1081 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001082
Chris Lattnere995a2a2004-05-23 21:00:47 +00001083 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001084 // Set up the return value node.
1085 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
Daniel Berlinaad15882007-09-16 21:45:02 +00001086 GraphNodes[getReturnNode(F)].setValue(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001087 if (F->getFunctionType()->isVarArg())
Daniel Berlinaad15882007-09-16 21:45:02 +00001088 GraphNodes[getVarargNode(F)].setValue(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001089
1090 // Set up incoming argument nodes.
Chris Lattner493f6362005-03-27 22:03:46 +00001091 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
1092 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +00001093 if (isa<PointerType>(I->getType()))
1094 getNodeValue(*I);
1095
Daniel Berlinaad15882007-09-16 21:45:02 +00001096 // At some point we should just add constraints for the escaping functions
1097 // at solve time, but this slows down solving. For now, we simply mark
1098 // address taken functions as escaping and treat them as external.
Rafael Espindolabb46f522009-01-15 20:18:42 +00001099 if (!F->hasLocalLinkage() || AnalyzeUsesOfFunction(F))
Chris Lattnere995a2a2004-05-23 21:00:47 +00001100 AddConstraintsForNonInternalLinkage(F);
1101
Reid Spencer5cbf9852007-01-30 20:08:39 +00001102 if (!F->isDeclaration()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001103 // Scan the function body, creating a memory object for each heap/stack
1104 // allocation in the body of the function and a node to represent all
1105 // pointer values defined by instructions and used as operands.
1106 visit(F);
Chris Lattner8a446432005-03-29 06:09:07 +00001107 } else {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001108 // External functions that return pointers return the universal set.
1109 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
1110 Constraints.push_back(Constraint(Constraint::Copy,
1111 getReturnNode(F),
Daniel Berlinaad15882007-09-16 21:45:02 +00001112 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001113
1114 // Any pointers that are passed into the function have the universal set
1115 // stored into them.
Chris Lattner493f6362005-03-27 22:03:46 +00001116 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
1117 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +00001118 if (isa<PointerType>(I->getType())) {
1119 // Pointers passed into external functions could have anything stored
1120 // through them.
1121 Constraints.push_back(Constraint(Constraint::Store, getNode(I),
Daniel Berlinaad15882007-09-16 21:45:02 +00001122 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001123 // Memory objects passed into external function calls can have the
1124 // universal set point to them.
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001125#if FULL_UNIVERSAL
Chris Lattnere995a2a2004-05-23 21:00:47 +00001126 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001127 UniversalSet,
Chris Lattnere995a2a2004-05-23 21:00:47 +00001128 getNode(I)));
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001129#else
1130 Constraints.push_back(Constraint(Constraint::Copy,
1131 getNode(I),
1132 UniversalSet));
1133#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001134 }
1135
1136 // If this is an external varargs function, it can also store pointers
1137 // into any pointers passed through the varargs section.
1138 if (F->getFunctionType()->isVarArg())
1139 Constraints.push_back(Constraint(Constraint::Store, getVarargNode(F),
Daniel Berlinaad15882007-09-16 21:45:02 +00001140 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001141 }
1142 }
1143 NumConstraints += Constraints.size();
1144}
1145
1146
1147void Andersens::visitInstruction(Instruction &I) {
1148#ifdef NDEBUG
1149 return; // This function is just a big assert.
1150#endif
1151 if (isa<BinaryOperator>(I))
1152 return;
1153 // Most instructions don't have any effect on pointer values.
1154 switch (I.getOpcode()) {
1155 case Instruction::Br:
1156 case Instruction::Switch:
1157 case Instruction::Unwind:
Chris Lattnerc17edbd2004-10-16 18:16:19 +00001158 case Instruction::Unreachable:
Reid Spencere4d87aa2006-12-23 06:05:41 +00001159 case Instruction::ICmp:
1160 case Instruction::FCmp:
Chris Lattnere995a2a2004-05-23 21:00:47 +00001161 return;
1162 default:
1163 // Is this something we aren't handling yet?
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00001164 errs() << "Unknown instruction: " << I;
Torok Edwinc23197a2009-07-14 16:55:14 +00001165 llvm_unreachable(0);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001166 }
1167}
1168
Victor Hernandez7b929da2009-10-23 21:09:37 +00001169void Andersens::visitAllocaInst(AllocaInst &I) {
1170 visitAlloc(I);
1171}
1172
1173void Andersens::visitAlloc(Instruction &I) {
Victor Hernandez46e83122009-09-18 21:34:51 +00001174 unsigned ObjectIndex = getObject(&I);
1175 GraphNodes[ObjectIndex].setValue(&I);
1176 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(I),
Daniel Berlinaad15882007-09-16 21:45:02 +00001177 ObjectIndex));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001178}
1179
1180void Andersens::visitReturnInst(ReturnInst &RI) {
1181 if (RI.getNumOperands() && isa<PointerType>(RI.getOperand(0)->getType()))
1182 // return V --> <Copy/retval{F}/v>
1183 Constraints.push_back(Constraint(Constraint::Copy,
1184 getReturnNode(RI.getParent()->getParent()),
1185 getNode(RI.getOperand(0))));
1186}
1187
1188void Andersens::visitLoadInst(LoadInst &LI) {
1189 if (isa<PointerType>(LI.getType()))
1190 // P1 = load P2 --> <Load/P1/P2>
1191 Constraints.push_back(Constraint(Constraint::Load, getNodeValue(LI),
1192 getNode(LI.getOperand(0))));
1193}
1194
1195void Andersens::visitStoreInst(StoreInst &SI) {
1196 if (isa<PointerType>(SI.getOperand(0)->getType()))
1197 // store P1, P2 --> <Store/P2/P1>
1198 Constraints.push_back(Constraint(Constraint::Store,
1199 getNode(SI.getOperand(1)),
1200 getNode(SI.getOperand(0))));
1201}
1202
1203void Andersens::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1204 // P1 = getelementptr P2, ... --> <Copy/P1/P2>
1205 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(GEP),
1206 getNode(GEP.getOperand(0))));
1207}
1208
1209void Andersens::visitPHINode(PHINode &PN) {
1210 if (isa<PointerType>(PN.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001211 unsigned PNN = getNodeValue(PN);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001212 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1213 // P1 = phi P2, P3 --> <Copy/P1/P2>, <Copy/P1/P3>, ...
1214 Constraints.push_back(Constraint(Constraint::Copy, PNN,
1215 getNode(PN.getIncomingValue(i))));
1216 }
1217}
1218
1219void Andersens::visitCastInst(CastInst &CI) {
1220 Value *Op = CI.getOperand(0);
1221 if (isa<PointerType>(CI.getType())) {
1222 if (isa<PointerType>(Op->getType())) {
1223 // P1 = cast P2 --> <Copy/P1/P2>
1224 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
1225 getNode(CI.getOperand(0))));
1226 } else {
1227 // P1 = cast int --> <Copy/P1/Univ>
Chris Lattner175b9632005-03-29 20:36:05 +00001228#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +00001229 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
Daniel Berlinaad15882007-09-16 21:45:02 +00001230 UniversalSet));
Chris Lattnerbd135c72005-04-05 01:12:03 +00001231#else
1232 getNodeValue(CI);
Chris Lattner175b9632005-03-29 20:36:05 +00001233#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001234 }
1235 } else if (isa<PointerType>(Op->getType())) {
1236 // int = cast P1 --> <Copy/Univ/P1>
Chris Lattner175b9632005-03-29 20:36:05 +00001237#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +00001238 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001239 UniversalSet,
Chris Lattnere995a2a2004-05-23 21:00:47 +00001240 getNode(CI.getOperand(0))));
Chris Lattnerbd135c72005-04-05 01:12:03 +00001241#else
1242 getNode(CI.getOperand(0));
Chris Lattner175b9632005-03-29 20:36:05 +00001243#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001244 }
1245}
1246
1247void Andersens::visitSelectInst(SelectInst &SI) {
1248 if (isa<PointerType>(SI.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001249 unsigned SIN = getNodeValue(SI);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001250 // P1 = select C, P2, P3 ---> <Copy/P1/P2>, <Copy/P1/P3>
1251 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1252 getNode(SI.getOperand(1))));
1253 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1254 getNode(SI.getOperand(2))));
1255 }
1256}
1257
Chris Lattnere995a2a2004-05-23 21:00:47 +00001258void Andersens::visitVAArg(VAArgInst &I) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001259 llvm_unreachable("vaarg not handled yet!");
Chris Lattnere995a2a2004-05-23 21:00:47 +00001260}
1261
1262/// AddConstraintsForCall - Add constraints for a call with actual arguments
1263/// specified by CS to the function specified by F. Note that the types of
1264/// arguments might not match up in the case where this is an indirect call and
1265/// the function pointer has been casted. If this is the case, do something
1266/// reasonable.
1267void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001268 Value *CallValue = CS.getCalledValue();
1269 bool IsDeref = F == NULL;
1270
1271 // If this is a call to an external function, try to handle it directly to get
1272 // some taste of context sensitivity.
1273 if (F && F->isDeclaration() && AddConstraintsForExternalCall(CS, F))
Chris Lattner8a446432005-03-29 06:09:07 +00001274 return;
1275
Chris Lattnere995a2a2004-05-23 21:00:47 +00001276 if (isa<PointerType>(CS.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001277 unsigned CSN = getNode(CS.getInstruction());
1278 if (!F || isa<PointerType>(F->getFunctionType()->getReturnType())) {
1279 if (IsDeref)
1280 Constraints.push_back(Constraint(Constraint::Load, CSN,
1281 getNode(CallValue), CallReturnPos));
1282 else
1283 Constraints.push_back(Constraint(Constraint::Copy, CSN,
1284 getNode(CallValue) + CallReturnPos));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001285 } else {
1286 // If the function returns a non-pointer value, handle this just like we
1287 // treat a nonpointer cast to pointer.
1288 Constraints.push_back(Constraint(Constraint::Copy, CSN,
Daniel Berlinaad15882007-09-16 21:45:02 +00001289 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001290 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001291 } else if (F && isa<PointerType>(F->getFunctionType()->getReturnType())) {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001292#if FULL_UNIVERSAL
Chris Lattnere995a2a2004-05-23 21:00:47 +00001293 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001294 UniversalSet,
1295 getNode(CallValue) + CallReturnPos));
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001296#else
1297 Constraints.push_back(Constraint(Constraint::Copy,
1298 getNode(CallValue) + CallReturnPos,
1299 UniversalSet));
1300#endif
1301
1302
Chris Lattnere995a2a2004-05-23 21:00:47 +00001303 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001304
Chris Lattnere995a2a2004-05-23 21:00:47 +00001305 CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
Daniel Berlind3bf1ae2008-03-18 22:22:53 +00001306 bool external = !F || F->isDeclaration();
Daniel Berlinaad15882007-09-16 21:45:02 +00001307 if (F) {
1308 // Direct Call
1309 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
Daniel Berlind3bf1ae2008-03-18 22:22:53 +00001310 for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI)
1311 {
1312#if !FULL_UNIVERSAL
1313 if (external && isa<PointerType>((*ArgI)->getType()))
1314 {
1315 // Add constraint that ArgI can now point to anything due to
1316 // escaping, as can everything it points to. The second portion of
1317 // this should be taken care of by universal = *universal
1318 Constraints.push_back(Constraint(Constraint::Copy,
1319 getNode(*ArgI),
1320 UniversalSet));
1321 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00001322#endif
Daniel Berlind3bf1ae2008-03-18 22:22:53 +00001323 if (isa<PointerType>(AI->getType())) {
1324 if (isa<PointerType>((*ArgI)->getType())) {
1325 // Copy the actual argument into the formal argument.
1326 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1327 getNode(*ArgI)));
1328 } else {
1329 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1330 UniversalSet));
1331 }
1332 } else if (isa<PointerType>((*ArgI)->getType())) {
1333#if FULL_UNIVERSAL
1334 Constraints.push_back(Constraint(Constraint::Copy,
1335 UniversalSet,
1336 getNode(*ArgI)));
1337#else
1338 Constraints.push_back(Constraint(Constraint::Copy,
1339 getNode(*ArgI),
1340 UniversalSet));
1341#endif
1342 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001343 }
1344 } else {
1345 //Indirect Call
1346 unsigned ArgPos = CallFirstArgPos;
1347 for (; ArgI != ArgE; ++ArgI) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001348 if (isa<PointerType>((*ArgI)->getType())) {
1349 // Copy the actual argument into the formal argument.
Daniel Berlinaad15882007-09-16 21:45:02 +00001350 Constraints.push_back(Constraint(Constraint::Store,
1351 getNode(CallValue),
1352 getNode(*ArgI), ArgPos++));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001353 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +00001354 Constraints.push_back(Constraint(Constraint::Store,
1355 getNode (CallValue),
1356 UniversalSet, ArgPos++));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001357 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00001358 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001359 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00001360 // Copy all pointers passed through the varargs section to the varargs node.
Daniel Berlinaad15882007-09-16 21:45:02 +00001361 if (F && F->getFunctionType()->isVarArg())
Chris Lattnere995a2a2004-05-23 21:00:47 +00001362 for (; ArgI != ArgE; ++ArgI)
1363 if (isa<PointerType>((*ArgI)->getType()))
1364 Constraints.push_back(Constraint(Constraint::Copy, getVarargNode(F),
1365 getNode(*ArgI)));
1366 // If more arguments are passed in than we track, just drop them on the floor.
1367}
1368
1369void Andersens::visitCallSite(CallSite CS) {
1370 if (isa<PointerType>(CS.getType()))
1371 getNodeValue(*CS.getInstruction());
1372
1373 if (Function *F = CS.getCalledFunction()) {
1374 AddConstraintsForCall(CS, F);
1375 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +00001376 AddConstraintsForCall(CS, NULL);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001377 }
1378}
1379
1380//===----------------------------------------------------------------------===//
1381// Constraint Solving Phase
1382//===----------------------------------------------------------------------===//
1383
1384/// intersects - Return true if the points-to set of this node intersects
1385/// with the points-to set of the specified node.
1386bool Andersens::Node::intersects(Node *N) const {
Daniel Berlinaad15882007-09-16 21:45:02 +00001387 return PointsTo->intersects(N->PointsTo);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001388}
1389
1390/// intersectsIgnoring - Return true if the points-to set of this node
1391/// intersects with the points-to set of the specified node on any nodes
1392/// except for the specified node to ignore.
Daniel Berlinaad15882007-09-16 21:45:02 +00001393bool Andersens::Node::intersectsIgnoring(Node *N, unsigned Ignoring) const {
1394 // TODO: If we are only going to call this with the same value for Ignoring,
1395 // we should move the special values out of the points-to bitmap.
1396 bool WeHadIt = PointsTo->test(Ignoring);
1397 bool NHadIt = N->PointsTo->test(Ignoring);
1398 bool Result = false;
1399 if (WeHadIt)
1400 PointsTo->reset(Ignoring);
1401 if (NHadIt)
1402 N->PointsTo->reset(Ignoring);
1403 Result = PointsTo->intersects(N->PointsTo);
1404 if (WeHadIt)
1405 PointsTo->set(Ignoring);
1406 if (NHadIt)
1407 N->PointsTo->set(Ignoring);
1408 return Result;
Chris Lattnere995a2a2004-05-23 21:00:47 +00001409}
1410
Daniel Berlind81ccc22007-09-24 19:45:49 +00001411
1412/// Clump together address taken variables so that the points-to sets use up
1413/// less space and can be operated on faster.
1414
1415void Andersens::ClumpAddressTaken() {
1416#undef DEBUG_TYPE
1417#define DEBUG_TYPE "anders-aa-renumber"
1418 std::vector<unsigned> Translate;
1419 std::vector<Node> NewGraphNodes;
1420
1421 Translate.resize(GraphNodes.size());
1422 unsigned NewPos = 0;
1423
1424 for (unsigned i = 0; i < Constraints.size(); ++i) {
1425 Constraint &C = Constraints[i];
1426 if (C.Type == Constraint::AddressOf) {
1427 GraphNodes[C.Src].AddressTaken = true;
1428 }
1429 }
1430 for (unsigned i = 0; i < NumberSpecialNodes; ++i) {
1431 unsigned Pos = NewPos++;
1432 Translate[i] = Pos;
1433 NewGraphNodes.push_back(GraphNodes[i]);
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001434 DEBUG(errs() << "Renumbering node " << i << " to node " << Pos << "\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00001435 }
1436
1437 // I believe this ends up being faster than making two vectors and splicing
1438 // them.
1439 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1440 if (GraphNodes[i].AddressTaken) {
1441 unsigned Pos = NewPos++;
1442 Translate[i] = Pos;
1443 NewGraphNodes.push_back(GraphNodes[i]);
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001444 DEBUG(errs() << "Renumbering node " << i << " to node " << Pos << "\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00001445 }
1446 }
1447
1448 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1449 if (!GraphNodes[i].AddressTaken) {
1450 unsigned Pos = NewPos++;
1451 Translate[i] = Pos;
1452 NewGraphNodes.push_back(GraphNodes[i]);
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001453 DEBUG(errs() << "Renumbering node " << i << " to node " << Pos << "\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00001454 }
1455 }
1456
1457 for (DenseMap<Value*, unsigned>::iterator Iter = ValueNodes.begin();
1458 Iter != ValueNodes.end();
1459 ++Iter)
1460 Iter->second = Translate[Iter->second];
1461
1462 for (DenseMap<Value*, unsigned>::iterator Iter = ObjectNodes.begin();
1463 Iter != ObjectNodes.end();
1464 ++Iter)
1465 Iter->second = Translate[Iter->second];
1466
1467 for (DenseMap<Function*, unsigned>::iterator Iter = ReturnNodes.begin();
1468 Iter != ReturnNodes.end();
1469 ++Iter)
1470 Iter->second = Translate[Iter->second];
1471
1472 for (DenseMap<Function*, unsigned>::iterator Iter = VarargNodes.begin();
1473 Iter != VarargNodes.end();
1474 ++Iter)
1475 Iter->second = Translate[Iter->second];
1476
1477 for (unsigned i = 0; i < Constraints.size(); ++i) {
1478 Constraint &C = Constraints[i];
1479 C.Src = Translate[C.Src];
1480 C.Dest = Translate[C.Dest];
1481 }
1482
1483 GraphNodes.swap(NewGraphNodes);
1484#undef DEBUG_TYPE
1485#define DEBUG_TYPE "anders-aa"
1486}
1487
1488/// The technique used here is described in "Exploiting Pointer and Location
1489/// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1490/// Analysis Symposium (SAS), August 2007." It is known as the "HVN" algorithm,
1491/// and is equivalent to value numbering the collapsed constraint graph without
1492/// evaluating unions. This is used as a pre-pass to HU in order to resolve
1493/// first order pointer dereferences and speed up/reduce memory usage of HU.
1494/// Running both is equivalent to HRU without the iteration
1495/// HVN in more detail:
1496/// Imagine the set of constraints was simply straight line code with no loops
1497/// (we eliminate cycles, so there are no loops), such as:
1498/// E = &D
1499/// E = &C
1500/// E = F
1501/// F = G
1502/// G = F
1503/// Applying value numbering to this code tells us:
1504/// G == F == E
1505///
1506/// For HVN, this is as far as it goes. We assign new value numbers to every
1507/// "address node", and every "reference node".
1508/// To get the optimal result for this, we use a DFS + SCC (since all nodes in a
1509/// cycle must have the same value number since the = operation is really
1510/// inclusion, not overwrite), and value number nodes we receive points-to sets
1511/// before we value our own node.
1512/// The advantage of HU over HVN is that HU considers the inclusion property, so
1513/// that if you have
1514/// E = &D
1515/// E = &C
1516/// E = F
1517/// F = G
1518/// F = &D
1519/// G = F
1520/// HU will determine that G == F == E. HVN will not, because it cannot prove
1521/// that the points to information ends up being the same because they all
1522/// receive &D from E anyway.
1523
1524void Andersens::HVN() {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001525 DEBUG(errs() << "Beginning HVN\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00001526 // Build a predecessor graph. This is like our constraint graph with the
1527 // edges going in the opposite direction, and there are edges for all the
1528 // constraints, instead of just copy constraints. We also build implicit
1529 // edges for constraints are implied but not explicit. I.E for the constraint
1530 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1531 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1532 Constraint &C = Constraints[i];
1533 if (C.Type == Constraint::AddressOf) {
1534 GraphNodes[C.Src].AddressTaken = true;
1535 GraphNodes[C.Src].Direct = false;
1536
1537 // Dest = &src edge
1538 unsigned AdrNode = C.Src + FirstAdrNode;
1539 if (!GraphNodes[C.Dest].PredEdges)
1540 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1541 GraphNodes[C.Dest].PredEdges->set(AdrNode);
1542
1543 // *Dest = src edge
1544 unsigned RefNode = C.Dest + FirstRefNode;
1545 if (!GraphNodes[RefNode].ImplicitPredEdges)
1546 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1547 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1548 } else if (C.Type == Constraint::Load) {
1549 if (C.Offset == 0) {
1550 // dest = *src edge
1551 if (!GraphNodes[C.Dest].PredEdges)
1552 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1553 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1554 } else {
1555 GraphNodes[C.Dest].Direct = false;
1556 }
1557 } else if (C.Type == Constraint::Store) {
1558 if (C.Offset == 0) {
1559 // *dest = src edge
1560 unsigned RefNode = C.Dest + FirstRefNode;
1561 if (!GraphNodes[RefNode].PredEdges)
1562 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1563 GraphNodes[RefNode].PredEdges->set(C.Src);
1564 }
1565 } else {
1566 // Dest = Src edge and *Dest = *Src edge
1567 if (!GraphNodes[C.Dest].PredEdges)
1568 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1569 GraphNodes[C.Dest].PredEdges->set(C.Src);
1570 unsigned RefNode = C.Dest + FirstRefNode;
1571 if (!GraphNodes[RefNode].ImplicitPredEdges)
1572 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1573 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1574 }
1575 }
1576 PEClass = 1;
1577 // Do SCC finding first to condense our predecessor graph
1578 DFSNumber = 0;
1579 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1580 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1581 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1582
1583 for (unsigned i = 0; i < FirstRefNode; ++i) {
1584 unsigned Node = VSSCCRep[i];
1585 if (!Node2Visited[Node])
1586 HVNValNum(Node);
1587 }
1588 for (BitVectorMap::iterator Iter = Set2PEClass.begin();
1589 Iter != Set2PEClass.end();
1590 ++Iter)
1591 delete Iter->first;
1592 Set2PEClass.clear();
1593 Node2DFS.clear();
1594 Node2Deleted.clear();
1595 Node2Visited.clear();
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001596 DEBUG(errs() << "Finished HVN\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00001597
1598}
1599
1600/// This is the workhorse of HVN value numbering. We combine SCC finding at the
1601/// same time because it's easy.
1602void Andersens::HVNValNum(unsigned NodeIndex) {
1603 unsigned MyDFS = DFSNumber++;
1604 Node *N = &GraphNodes[NodeIndex];
1605 Node2Visited[NodeIndex] = true;
1606 Node2DFS[NodeIndex] = MyDFS;
1607
1608 // First process all our explicit edges
1609 if (N->PredEdges)
1610 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1611 Iter != N->PredEdges->end();
1612 ++Iter) {
1613 unsigned j = VSSCCRep[*Iter];
1614 if (!Node2Deleted[j]) {
1615 if (!Node2Visited[j])
1616 HVNValNum(j);
1617 if (Node2DFS[NodeIndex] > Node2DFS[j])
1618 Node2DFS[NodeIndex] = Node2DFS[j];
1619 }
1620 }
1621
1622 // Now process all the implicit edges
1623 if (N->ImplicitPredEdges)
1624 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1625 Iter != N->ImplicitPredEdges->end();
1626 ++Iter) {
1627 unsigned j = VSSCCRep[*Iter];
1628 if (!Node2Deleted[j]) {
1629 if (!Node2Visited[j])
1630 HVNValNum(j);
1631 if (Node2DFS[NodeIndex] > Node2DFS[j])
1632 Node2DFS[NodeIndex] = Node2DFS[j];
1633 }
1634 }
1635
1636 // See if we found any cycles
1637 if (MyDFS == Node2DFS[NodeIndex]) {
1638 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1639 unsigned CycleNodeIndex = SCCStack.top();
1640 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1641 VSSCCRep[CycleNodeIndex] = NodeIndex;
1642 // Unify the nodes
1643 N->Direct &= CycleNode->Direct;
1644
1645 if (CycleNode->PredEdges) {
1646 if (!N->PredEdges)
1647 N->PredEdges = new SparseBitVector<>;
1648 *(N->PredEdges) |= CycleNode->PredEdges;
1649 delete CycleNode->PredEdges;
1650 CycleNode->PredEdges = NULL;
1651 }
1652 if (CycleNode->ImplicitPredEdges) {
1653 if (!N->ImplicitPredEdges)
1654 N->ImplicitPredEdges = new SparseBitVector<>;
1655 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1656 delete CycleNode->ImplicitPredEdges;
1657 CycleNode->ImplicitPredEdges = NULL;
1658 }
1659
1660 SCCStack.pop();
1661 }
1662
1663 Node2Deleted[NodeIndex] = true;
1664
1665 if (!N->Direct) {
1666 GraphNodes[NodeIndex].PointerEquivLabel = PEClass++;
1667 return;
1668 }
1669
1670 // Collect labels of successor nodes
1671 bool AllSame = true;
1672 unsigned First = ~0;
1673 SparseBitVector<> *Labels = new SparseBitVector<>;
1674 bool Used = false;
1675
1676 if (N->PredEdges)
1677 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1678 Iter != N->PredEdges->end();
1679 ++Iter) {
1680 unsigned j = VSSCCRep[*Iter];
1681 unsigned Label = GraphNodes[j].PointerEquivLabel;
1682 // Ignore labels that are equal to us or non-pointers
1683 if (j == NodeIndex || Label == 0)
1684 continue;
1685 if (First == (unsigned)~0)
1686 First = Label;
1687 else if (First != Label)
1688 AllSame = false;
1689 Labels->set(Label);
1690 }
1691
1692 // We either have a non-pointer, a copy of an existing node, or a new node.
1693 // Assign the appropriate pointer equivalence label.
1694 if (Labels->empty()) {
1695 GraphNodes[NodeIndex].PointerEquivLabel = 0;
1696 } else if (AllSame) {
1697 GraphNodes[NodeIndex].PointerEquivLabel = First;
1698 } else {
1699 GraphNodes[NodeIndex].PointerEquivLabel = Set2PEClass[Labels];
1700 if (GraphNodes[NodeIndex].PointerEquivLabel == 0) {
1701 unsigned EquivClass = PEClass++;
1702 Set2PEClass[Labels] = EquivClass;
1703 GraphNodes[NodeIndex].PointerEquivLabel = EquivClass;
1704 Used = true;
1705 }
1706 }
1707 if (!Used)
1708 delete Labels;
1709 } else {
1710 SCCStack.push(NodeIndex);
1711 }
1712}
1713
1714/// The technique used here is described in "Exploiting Pointer and Location
1715/// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1716/// Analysis Symposium (SAS), August 2007." It is known as the "HU" algorithm,
1717/// and is equivalent to value numbering the collapsed constraint graph
1718/// including evaluating unions.
1719void Andersens::HU() {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001720 DEBUG(errs() << "Beginning HU\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00001721 // Build a predecessor graph. This is like our constraint graph with the
1722 // edges going in the opposite direction, and there are edges for all the
1723 // constraints, instead of just copy constraints. We also build implicit
1724 // edges for constraints are implied but not explicit. I.E for the constraint
1725 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1726 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1727 Constraint &C = Constraints[i];
1728 if (C.Type == Constraint::AddressOf) {
1729 GraphNodes[C.Src].AddressTaken = true;
1730 GraphNodes[C.Src].Direct = false;
1731
1732 GraphNodes[C.Dest].PointsTo->set(C.Src);
1733 // *Dest = src edge
1734 unsigned RefNode = C.Dest + FirstRefNode;
1735 if (!GraphNodes[RefNode].ImplicitPredEdges)
1736 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1737 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1738 GraphNodes[C.Src].PointedToBy->set(C.Dest);
1739 } else if (C.Type == Constraint::Load) {
1740 if (C.Offset == 0) {
1741 // dest = *src edge
1742 if (!GraphNodes[C.Dest].PredEdges)
1743 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1744 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1745 } else {
1746 GraphNodes[C.Dest].Direct = false;
1747 }
1748 } else if (C.Type == Constraint::Store) {
1749 if (C.Offset == 0) {
1750 // *dest = src edge
1751 unsigned RefNode = C.Dest + FirstRefNode;
1752 if (!GraphNodes[RefNode].PredEdges)
1753 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1754 GraphNodes[RefNode].PredEdges->set(C.Src);
1755 }
1756 } else {
1757 // Dest = Src edge and *Dest = *Src edg
1758 if (!GraphNodes[C.Dest].PredEdges)
1759 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1760 GraphNodes[C.Dest].PredEdges->set(C.Src);
1761 unsigned RefNode = C.Dest + FirstRefNode;
1762 if (!GraphNodes[RefNode].ImplicitPredEdges)
1763 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1764 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1765 }
1766 }
1767 PEClass = 1;
1768 // Do SCC finding first to condense our predecessor graph
1769 DFSNumber = 0;
1770 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1771 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1772 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1773
1774 for (unsigned i = 0; i < FirstRefNode; ++i) {
1775 if (FindNode(i) == i) {
1776 unsigned Node = VSSCCRep[i];
1777 if (!Node2Visited[Node])
1778 Condense(Node);
1779 }
1780 }
1781
1782 // Reset tables for actual labeling
1783 Node2DFS.clear();
1784 Node2Visited.clear();
1785 Node2Deleted.clear();
1786 // Pre-grow our densemap so that we don't get really bad behavior
1787 Set2PEClass.resize(GraphNodes.size());
1788
1789 // Visit the condensed graph and generate pointer equivalence labels.
1790 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1791 for (unsigned i = 0; i < FirstRefNode; ++i) {
1792 if (FindNode(i) == i) {
1793 unsigned Node = VSSCCRep[i];
1794 if (!Node2Visited[Node])
1795 HUValNum(Node);
1796 }
1797 }
1798 // PEClass nodes will be deleted by the deleting of N->PointsTo in our caller.
1799 Set2PEClass.clear();
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001800 DEBUG(errs() << "Finished HU\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00001801}
1802
1803
1804/// Implementation of standard Tarjan SCC algorithm as modified by Nuutilla.
1805void Andersens::Condense(unsigned NodeIndex) {
1806 unsigned MyDFS = DFSNumber++;
1807 Node *N = &GraphNodes[NodeIndex];
1808 Node2Visited[NodeIndex] = true;
1809 Node2DFS[NodeIndex] = MyDFS;
1810
1811 // First process all our explicit edges
1812 if (N->PredEdges)
1813 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1814 Iter != N->PredEdges->end();
1815 ++Iter) {
1816 unsigned j = VSSCCRep[*Iter];
1817 if (!Node2Deleted[j]) {
1818 if (!Node2Visited[j])
1819 Condense(j);
1820 if (Node2DFS[NodeIndex] > Node2DFS[j])
1821 Node2DFS[NodeIndex] = Node2DFS[j];
1822 }
1823 }
1824
1825 // Now process all the implicit edges
1826 if (N->ImplicitPredEdges)
1827 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1828 Iter != N->ImplicitPredEdges->end();
1829 ++Iter) {
1830 unsigned j = VSSCCRep[*Iter];
1831 if (!Node2Deleted[j]) {
1832 if (!Node2Visited[j])
1833 Condense(j);
1834 if (Node2DFS[NodeIndex] > Node2DFS[j])
1835 Node2DFS[NodeIndex] = Node2DFS[j];
1836 }
1837 }
1838
1839 // See if we found any cycles
1840 if (MyDFS == Node2DFS[NodeIndex]) {
1841 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1842 unsigned CycleNodeIndex = SCCStack.top();
1843 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1844 VSSCCRep[CycleNodeIndex] = NodeIndex;
1845 // Unify the nodes
1846 N->Direct &= CycleNode->Direct;
1847
1848 *(N->PointsTo) |= CycleNode->PointsTo;
1849 delete CycleNode->PointsTo;
1850 CycleNode->PointsTo = NULL;
1851 if (CycleNode->PredEdges) {
1852 if (!N->PredEdges)
1853 N->PredEdges = new SparseBitVector<>;
1854 *(N->PredEdges) |= CycleNode->PredEdges;
1855 delete CycleNode->PredEdges;
1856 CycleNode->PredEdges = NULL;
1857 }
1858 if (CycleNode->ImplicitPredEdges) {
1859 if (!N->ImplicitPredEdges)
1860 N->ImplicitPredEdges = new SparseBitVector<>;
1861 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1862 delete CycleNode->ImplicitPredEdges;
1863 CycleNode->ImplicitPredEdges = NULL;
1864 }
1865 SCCStack.pop();
1866 }
1867
1868 Node2Deleted[NodeIndex] = true;
1869
1870 // Set up number of incoming edges for other nodes
1871 if (N->PredEdges)
1872 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1873 Iter != N->PredEdges->end();
1874 ++Iter)
1875 ++GraphNodes[VSSCCRep[*Iter]].NumInEdges;
1876 } else {
1877 SCCStack.push(NodeIndex);
1878 }
1879}
1880
1881void Andersens::HUValNum(unsigned NodeIndex) {
1882 Node *N = &GraphNodes[NodeIndex];
1883 Node2Visited[NodeIndex] = true;
1884
1885 // Eliminate dereferences of non-pointers for those non-pointers we have
1886 // already identified. These are ref nodes whose non-ref node:
1887 // 1. Has already been visited determined to point to nothing (and thus, a
1888 // dereference of it must point to nothing)
1889 // 2. Any direct node with no predecessor edges in our graph and with no
1890 // points-to set (since it can't point to anything either, being that it
1891 // receives no points-to sets and has none).
1892 if (NodeIndex >= FirstRefNode) {
1893 unsigned j = VSSCCRep[FindNode(NodeIndex - FirstRefNode)];
1894 if ((Node2Visited[j] && !GraphNodes[j].PointerEquivLabel)
1895 || (GraphNodes[j].Direct && !GraphNodes[j].PredEdges
1896 && GraphNodes[j].PointsTo->empty())){
1897 return;
1898 }
1899 }
1900 // Process all our explicit edges
1901 if (N->PredEdges)
1902 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1903 Iter != N->PredEdges->end();
1904 ++Iter) {
1905 unsigned j = VSSCCRep[*Iter];
1906 if (!Node2Visited[j])
1907 HUValNum(j);
1908
1909 // If this edge turned out to be the same as us, or got no pointer
1910 // equivalence label (and thus points to nothing) , just decrement our
1911 // incoming edges and continue.
1912 if (j == NodeIndex || GraphNodes[j].PointerEquivLabel == 0) {
1913 --GraphNodes[j].NumInEdges;
1914 continue;
1915 }
1916
1917 *(N->PointsTo) |= GraphNodes[j].PointsTo;
1918
1919 // If we didn't end up storing this in the hash, and we're done with all
1920 // the edges, we don't need the points-to set anymore.
1921 --GraphNodes[j].NumInEdges;
1922 if (!GraphNodes[j].NumInEdges && !GraphNodes[j].StoredInHash) {
1923 delete GraphNodes[j].PointsTo;
1924 GraphNodes[j].PointsTo = NULL;
1925 }
1926 }
1927 // If this isn't a direct node, generate a fresh variable.
1928 if (!N->Direct) {
1929 N->PointsTo->set(FirstRefNode + NodeIndex);
1930 }
1931
1932 // See If we have something equivalent to us, if not, generate a new
1933 // equivalence class.
1934 if (N->PointsTo->empty()) {
1935 delete N->PointsTo;
1936 N->PointsTo = NULL;
1937 } else {
1938 if (N->Direct) {
1939 N->PointerEquivLabel = Set2PEClass[N->PointsTo];
1940 if (N->PointerEquivLabel == 0) {
1941 unsigned EquivClass = PEClass++;
1942 N->StoredInHash = true;
1943 Set2PEClass[N->PointsTo] = EquivClass;
1944 N->PointerEquivLabel = EquivClass;
1945 }
1946 } else {
1947 N->PointerEquivLabel = PEClass++;
1948 }
1949 }
1950}
1951
1952/// Rewrite our list of constraints so that pointer equivalent nodes are
1953/// replaced by their the pointer equivalence class representative.
1954void Andersens::RewriteConstraints() {
1955 std::vector<Constraint> NewConstraints;
Chris Lattnerbe207732007-09-30 00:47:20 +00001956 DenseSet<Constraint, ConstraintKeyInfo> Seen;
Daniel Berlind81ccc22007-09-24 19:45:49 +00001957
1958 PEClass2Node.clear();
1959 PENLEClass2Node.clear();
1960
1961 // We may have from 1 to Graphnodes + 1 equivalence classes.
1962 PEClass2Node.insert(PEClass2Node.begin(), GraphNodes.size() + 1, -1);
1963 PENLEClass2Node.insert(PENLEClass2Node.begin(), GraphNodes.size() + 1, -1);
1964
1965 // Rewrite constraints, ignoring non-pointer constraints, uniting equivalent
1966 // nodes, and rewriting constraints to use the representative nodes.
1967 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1968 Constraint &C = Constraints[i];
1969 unsigned RHSNode = FindNode(C.Src);
1970 unsigned LHSNode = FindNode(C.Dest);
1971 unsigned RHSLabel = GraphNodes[VSSCCRep[RHSNode]].PointerEquivLabel;
1972 unsigned LHSLabel = GraphNodes[VSSCCRep[LHSNode]].PointerEquivLabel;
1973
1974 // First we try to eliminate constraints for things we can prove don't point
1975 // to anything.
1976 if (LHSLabel == 0) {
1977 DEBUG(PrintNode(&GraphNodes[LHSNode]));
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001978 DEBUG(errs() << " is a non-pointer, ignoring constraint.\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00001979 continue;
1980 }
1981 if (RHSLabel == 0) {
1982 DEBUG(PrintNode(&GraphNodes[RHSNode]));
Chris Lattnerbbbfa992009-08-23 06:35:02 +00001983 DEBUG(errs() << " is a non-pointer, ignoring constraint.\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00001984 continue;
1985 }
1986 // This constraint may be useless, and it may become useless as we translate
1987 // it.
1988 if (C.Src == C.Dest && C.Type == Constraint::Copy)
1989 continue;
Daniel Berlinc7a12ae2007-09-27 15:42:23 +00001990
Daniel Berlind81ccc22007-09-24 19:45:49 +00001991 C.Src = FindEquivalentNode(RHSNode, RHSLabel);
1992 C.Dest = FindEquivalentNode(FindNode(LHSNode), LHSLabel);
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001993 if ((C.Src == C.Dest && C.Type == Constraint::Copy)
Chris Lattnerbe207732007-09-30 00:47:20 +00001994 || Seen.count(C))
Daniel Berlind81ccc22007-09-24 19:45:49 +00001995 continue;
1996
Chris Lattnerbe207732007-09-30 00:47:20 +00001997 Seen.insert(C);
Daniel Berlind81ccc22007-09-24 19:45:49 +00001998 NewConstraints.push_back(C);
1999 }
2000 Constraints.swap(NewConstraints);
2001 PEClass2Node.clear();
2002}
2003
2004/// See if we have a node that is pointer equivalent to the one being asked
2005/// about, and if so, unite them and return the equivalent node. Otherwise,
2006/// return the original node.
2007unsigned Andersens::FindEquivalentNode(unsigned NodeIndex,
2008 unsigned NodeLabel) {
2009 if (!GraphNodes[NodeIndex].AddressTaken) {
2010 if (PEClass2Node[NodeLabel] != -1) {
2011 // We found an existing node with the same pointer label, so unify them.
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002012 // We specifically request that Union-By-Rank not be used so that
2013 // PEClass2Node[NodeLabel] U= NodeIndex and not the other way around.
2014 return UniteNodes(PEClass2Node[NodeLabel], NodeIndex, false);
Daniel Berlind81ccc22007-09-24 19:45:49 +00002015 } else {
2016 PEClass2Node[NodeLabel] = NodeIndex;
2017 PENLEClass2Node[NodeLabel] = NodeIndex;
2018 }
2019 } else if (PENLEClass2Node[NodeLabel] == -1) {
2020 PENLEClass2Node[NodeLabel] = NodeIndex;
2021 }
2022
2023 return NodeIndex;
2024}
2025
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002026void Andersens::PrintLabels() const {
Daniel Berlind81ccc22007-09-24 19:45:49 +00002027 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2028 if (i < FirstRefNode) {
2029 PrintNode(&GraphNodes[i]);
2030 } else if (i < FirstAdrNode) {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002031 DEBUG(errs() << "REF(");
Daniel Berlind81ccc22007-09-24 19:45:49 +00002032 PrintNode(&GraphNodes[i-FirstRefNode]);
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002033 DEBUG(errs() <<")");
Daniel Berlind81ccc22007-09-24 19:45:49 +00002034 } else {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002035 DEBUG(errs() << "ADR(");
Daniel Berlind81ccc22007-09-24 19:45:49 +00002036 PrintNode(&GraphNodes[i-FirstAdrNode]);
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002037 DEBUG(errs() <<")");
Daniel Berlind81ccc22007-09-24 19:45:49 +00002038 }
2039
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002040 DEBUG(errs() << " has pointer label " << GraphNodes[i].PointerEquivLabel
Daniel Berlind81ccc22007-09-24 19:45:49 +00002041 << " and SCC rep " << VSSCCRep[i]
2042 << " and is " << (GraphNodes[i].Direct ? "Direct" : "Not direct")
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002043 << "\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00002044 }
2045}
2046
Daniel Berlinc864edb2008-03-05 19:31:47 +00002047/// The technique used here is described in "The Ant and the
2048/// Grasshopper: Fast and Accurate Pointer Analysis for Millions of
2049/// Lines of Code. In Programming Language Design and Implementation
2050/// (PLDI), June 2007." It is known as the "HCD" (Hybrid Cycle
2051/// Detection) algorithm. It is called a hybrid because it performs an
2052/// offline analysis and uses its results during the solving (online)
2053/// phase. This is just the offline portion; the results of this
2054/// operation are stored in SDT and are later used in SolveContraints()
2055/// and UniteNodes().
2056void Andersens::HCD() {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002057 DEBUG(errs() << "Starting HCD.\n");
Daniel Berlinc864edb2008-03-05 19:31:47 +00002058 HCDSCCRep.resize(GraphNodes.size());
2059
2060 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2061 GraphNodes[i].Edges = new SparseBitVector<>;
2062 HCDSCCRep[i] = i;
2063 }
2064
2065 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2066 Constraint &C = Constraints[i];
2067 assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
2068 if (C.Type == Constraint::AddressOf) {
2069 continue;
2070 } else if (C.Type == Constraint::Load) {
2071 if( C.Offset == 0 )
2072 GraphNodes[C.Dest].Edges->set(C.Src + FirstRefNode);
2073 } else if (C.Type == Constraint::Store) {
2074 if( C.Offset == 0 )
2075 GraphNodes[C.Dest + FirstRefNode].Edges->set(C.Src);
2076 } else {
2077 GraphNodes[C.Dest].Edges->set(C.Src);
2078 }
2079 }
2080
2081 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2082 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2083 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
2084 SDT.insert(SDT.begin(), GraphNodes.size() / 2, -1);
2085
2086 DFSNumber = 0;
2087 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2088 unsigned Node = HCDSCCRep[i];
2089 if (!Node2Deleted[Node])
2090 Search(Node);
2091 }
2092
2093 for (unsigned i = 0; i < GraphNodes.size(); ++i)
2094 if (GraphNodes[i].Edges != NULL) {
2095 delete GraphNodes[i].Edges;
2096 GraphNodes[i].Edges = NULL;
2097 }
2098
2099 while( !SCCStack.empty() )
2100 SCCStack.pop();
2101
2102 Node2DFS.clear();
2103 Node2Visited.clear();
2104 Node2Deleted.clear();
2105 HCDSCCRep.clear();
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002106 DEBUG(errs() << "HCD complete.\n");
Daniel Berlinc864edb2008-03-05 19:31:47 +00002107}
2108
2109// Component of HCD:
2110// Use Nuutila's variant of Tarjan's algorithm to detect
2111// Strongly-Connected Components (SCCs). For non-trivial SCCs
2112// containing ref nodes, insert the appropriate information in SDT.
2113void Andersens::Search(unsigned Node) {
2114 unsigned MyDFS = DFSNumber++;
2115
2116 Node2Visited[Node] = true;
2117 Node2DFS[Node] = MyDFS;
2118
2119 for (SparseBitVector<>::iterator Iter = GraphNodes[Node].Edges->begin(),
2120 End = GraphNodes[Node].Edges->end();
2121 Iter != End;
2122 ++Iter) {
2123 unsigned J = HCDSCCRep[*Iter];
2124 assert(GraphNodes[J].isRep() && "Debug check; must be representative");
2125 if (!Node2Deleted[J]) {
2126 if (!Node2Visited[J])
2127 Search(J);
2128 if (Node2DFS[Node] > Node2DFS[J])
2129 Node2DFS[Node] = Node2DFS[J];
2130 }
2131 }
2132
2133 if( MyDFS != Node2DFS[Node] ) {
2134 SCCStack.push(Node);
2135 return;
2136 }
2137
2138 // This node is the root of a SCC, so process it.
2139 //
2140 // If the SCC is "non-trivial" (not a singleton) and contains a reference
2141 // node, we place this SCC into SDT. We unite the nodes in any case.
2142 if (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
2143 SparseBitVector<> SCC;
2144
2145 SCC.set(Node);
2146
2147 bool Ref = (Node >= FirstRefNode);
2148
2149 Node2Deleted[Node] = true;
2150
2151 do {
2152 unsigned P = SCCStack.top(); SCCStack.pop();
2153 Ref |= (P >= FirstRefNode);
2154 SCC.set(P);
2155 HCDSCCRep[P] = Node;
2156 } while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS);
2157
2158 if (Ref) {
2159 unsigned Rep = SCC.find_first();
2160 assert(Rep < FirstRefNode && "The SCC didn't have a non-Ref node!");
2161
2162 SparseBitVector<>::iterator i = SCC.begin();
2163
2164 // Skip over the non-ref nodes
2165 while( *i < FirstRefNode )
2166 ++i;
2167
2168 while( i != SCC.end() )
2169 SDT[ (*i++) - FirstRefNode ] = Rep;
2170 }
2171 }
2172}
2173
2174
Daniel Berlind81ccc22007-09-24 19:45:49 +00002175/// Optimize the constraints by performing offline variable substitution and
2176/// other optimizations.
2177void Andersens::OptimizeConstraints() {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002178 DEBUG(errs() << "Beginning constraint optimization\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00002179
Daniel Berlinc864edb2008-03-05 19:31:47 +00002180 SDTActive = false;
2181
Daniel Berlind81ccc22007-09-24 19:45:49 +00002182 // Function related nodes need to stay in the same relative position and can't
2183 // be location equivalent.
2184 for (std::map<unsigned, unsigned>::iterator Iter = MaxK.begin();
2185 Iter != MaxK.end();
2186 ++Iter) {
2187 for (unsigned i = Iter->first;
2188 i != Iter->first + Iter->second;
2189 ++i) {
2190 GraphNodes[i].AddressTaken = true;
2191 GraphNodes[i].Direct = false;
2192 }
2193 }
2194
2195 ClumpAddressTaken();
2196 FirstRefNode = GraphNodes.size();
2197 FirstAdrNode = FirstRefNode + GraphNodes.size();
2198 GraphNodes.insert(GraphNodes.end(), 2 * GraphNodes.size(),
2199 Node(false));
2200 VSSCCRep.resize(GraphNodes.size());
2201 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2202 VSSCCRep[i] = i;
2203 }
2204 HVN();
2205 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2206 Node *N = &GraphNodes[i];
2207 delete N->PredEdges;
2208 N->PredEdges = NULL;
2209 delete N->ImplicitPredEdges;
2210 N->ImplicitPredEdges = NULL;
2211 }
2212#undef DEBUG_TYPE
2213#define DEBUG_TYPE "anders-aa-labels"
2214 DEBUG(PrintLabels());
2215#undef DEBUG_TYPE
2216#define DEBUG_TYPE "anders-aa"
2217 RewriteConstraints();
2218 // Delete the adr nodes.
2219 GraphNodes.resize(FirstRefNode * 2);
2220
2221 // Now perform HU
2222 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2223 Node *N = &GraphNodes[i];
2224 if (FindNode(i) == i) {
2225 N->PointsTo = new SparseBitVector<>;
2226 N->PointedToBy = new SparseBitVector<>;
2227 // Reset our labels
2228 }
2229 VSSCCRep[i] = i;
2230 N->PointerEquivLabel = 0;
2231 }
2232 HU();
2233#undef DEBUG_TYPE
2234#define DEBUG_TYPE "anders-aa-labels"
2235 DEBUG(PrintLabels());
2236#undef DEBUG_TYPE
2237#define DEBUG_TYPE "anders-aa"
2238 RewriteConstraints();
2239 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2240 if (FindNode(i) == i) {
2241 Node *N = &GraphNodes[i];
2242 delete N->PointsTo;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002243 N->PointsTo = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002244 delete N->PredEdges;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002245 N->PredEdges = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002246 delete N->ImplicitPredEdges;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002247 N->ImplicitPredEdges = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002248 delete N->PointedToBy;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002249 N->PointedToBy = NULL;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002250 }
2251 }
Daniel Berlinc864edb2008-03-05 19:31:47 +00002252
2253 // perform Hybrid Cycle Detection (HCD)
2254 HCD();
2255 SDTActive = true;
2256
2257 // No longer any need for the upper half of GraphNodes (for ref nodes).
Daniel Berlind81ccc22007-09-24 19:45:49 +00002258 GraphNodes.erase(GraphNodes.begin() + FirstRefNode, GraphNodes.end());
Daniel Berlinc864edb2008-03-05 19:31:47 +00002259
2260 // HCD complete.
2261
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002262 DEBUG(errs() << "Finished constraint optimization\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00002263 FirstRefNode = 0;
2264 FirstAdrNode = 0;
2265}
2266
2267/// Unite pointer but not location equivalent variables, now that the constraint
2268/// graph is built.
2269void Andersens::UnitePointerEquivalences() {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002270 DEBUG(errs() << "Uniting remaining pointer equivalences\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00002271 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002272 if (GraphNodes[i].AddressTaken && GraphNodes[i].isRep()) {
Daniel Berlind81ccc22007-09-24 19:45:49 +00002273 unsigned Label = GraphNodes[i].PointerEquivLabel;
2274
2275 if (Label && PENLEClass2Node[Label] != -1)
2276 UniteNodes(i, PENLEClass2Node[Label]);
2277 }
2278 }
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002279 DEBUG(errs() << "Finished remaining pointer equivalences\n");
Daniel Berlind81ccc22007-09-24 19:45:49 +00002280 PENLEClass2Node.clear();
2281}
2282
2283/// Create the constraint graph used for solving points-to analysis.
2284///
Daniel Berlinaad15882007-09-16 21:45:02 +00002285void Andersens::CreateConstraintGraph() {
2286 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2287 Constraint &C = Constraints[i];
2288 assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
2289 if (C.Type == Constraint::AddressOf)
2290 GraphNodes[C.Dest].PointsTo->set(C.Src);
2291 else if (C.Type == Constraint::Load)
2292 GraphNodes[C.Src].Constraints.push_back(C);
2293 else if (C.Type == Constraint::Store)
2294 GraphNodes[C.Dest].Constraints.push_back(C);
2295 else if (C.Offset != 0)
2296 GraphNodes[C.Src].Constraints.push_back(C);
2297 else
2298 GraphNodes[C.Src].Edges->set(C.Dest);
2299 }
2300}
2301
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002302// Perform DFS and cycle detection.
2303bool Andersens::QueryNode(unsigned Node) {
2304 assert(GraphNodes[Node].isRep() && "Querying a non-rep node");
Daniel Berlinaad15882007-09-16 21:45:02 +00002305 unsigned OurDFS = ++DFSNumber;
2306 SparseBitVector<> ToErase;
2307 SparseBitVector<> NewEdges;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002308 Tarjan2DFS[Node] = OurDFS;
2309
2310 // Changed denotes a change from a recursive call that we will bubble up.
2311 // Merged is set if we actually merge a node ourselves.
2312 bool Changed = false, Merged = false;
Daniel Berlinaad15882007-09-16 21:45:02 +00002313
2314 for (SparseBitVector<>::iterator bi = GraphNodes[Node].Edges->begin();
2315 bi != GraphNodes[Node].Edges->end();
2316 ++bi) {
2317 unsigned RepNode = FindNode(*bi);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002318 // If this edge points to a non-representative node but we are
2319 // already planning to add an edge to its representative, we have no
2320 // need for this edge anymore.
Daniel Berlinaad15882007-09-16 21:45:02 +00002321 if (RepNode != *bi && NewEdges.test(RepNode)){
2322 ToErase.set(*bi);
2323 continue;
2324 }
2325
2326 // Continue about our DFS.
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002327 if (!Tarjan2Deleted[RepNode]){
2328 if (Tarjan2DFS[RepNode] == 0) {
2329 Changed |= QueryNode(RepNode);
2330 // May have been changed by QueryNode
Daniel Berlinaad15882007-09-16 21:45:02 +00002331 RepNode = FindNode(RepNode);
2332 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002333 if (Tarjan2DFS[RepNode] < Tarjan2DFS[Node])
2334 Tarjan2DFS[Node] = Tarjan2DFS[RepNode];
Daniel Berlinaad15882007-09-16 21:45:02 +00002335 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002336
2337 // We may have just discovered that this node is part of a cycle, in
2338 // which case we can also erase it.
Daniel Berlinaad15882007-09-16 21:45:02 +00002339 if (RepNode != *bi) {
2340 ToErase.set(*bi);
2341 NewEdges.set(RepNode);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002342 }
2343 }
2344
Daniel Berlinaad15882007-09-16 21:45:02 +00002345 GraphNodes[Node].Edges->intersectWithComplement(ToErase);
2346 GraphNodes[Node].Edges |= NewEdges;
2347
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002348 // If this node is a root of a non-trivial SCC, place it on our
2349 // worklist to be processed.
2350 if (OurDFS == Tarjan2DFS[Node]) {
2351 while (!SCCStack.empty() && Tarjan2DFS[SCCStack.top()] >= OurDFS) {
2352 Node = UniteNodes(Node, SCCStack.top());
Daniel Berlinaad15882007-09-16 21:45:02 +00002353
2354 SCCStack.pop();
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002355 Merged = true;
Daniel Berlinaad15882007-09-16 21:45:02 +00002356 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002357 Tarjan2Deleted[Node] = true;
Daniel Berlinaad15882007-09-16 21:45:02 +00002358
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002359 if (Merged)
2360 NextWL->insert(&GraphNodes[Node]);
Daniel Berlinaad15882007-09-16 21:45:02 +00002361 } else {
2362 SCCStack.push(Node);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002363 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002364
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002365 return(Changed | Merged);
2366}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002367
2368/// SolveConstraints - This stage iteratively processes the constraints list
2369/// propagating constraints (adding edges to the Nodes in the points-to graph)
2370/// until a fixed point is reached.
2371///
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002372/// We use a variant of the technique called "Lazy Cycle Detection", which is
2373/// described in "The Ant and the Grasshopper: Fast and Accurate Pointer
2374/// Analysis for Millions of Lines of Code. In Programming Language Design and
2375/// Implementation (PLDI), June 2007."
2376/// The paper describes performing cycle detection one node at a time, which can
2377/// be expensive if there are no cycles, but there are long chains of nodes that
2378/// it heuristically believes are cycles (because it will DFS from each node
2379/// without state from previous nodes).
2380/// Instead, we use the heuristic to build a worklist of nodes to check, then
2381/// cycle detect them all at the same time to do this more cheaply. This
2382/// catches cycles slightly later than the original technique did, but does it
2383/// make significantly cheaper.
2384
Chris Lattnere995a2a2004-05-23 21:00:47 +00002385void Andersens::SolveConstraints() {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002386 CurrWL = &w1;
2387 NextWL = &w2;
Daniel Berlinaad15882007-09-16 21:45:02 +00002388
Daniel Berlind81ccc22007-09-24 19:45:49 +00002389 OptimizeConstraints();
2390#undef DEBUG_TYPE
2391#define DEBUG_TYPE "anders-aa-constraints"
2392 DEBUG(PrintConstraints());
2393#undef DEBUG_TYPE
2394#define DEBUG_TYPE "anders-aa"
2395
Daniel Berlinaad15882007-09-16 21:45:02 +00002396 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2397 Node *N = &GraphNodes[i];
2398 N->PointsTo = new SparseBitVector<>;
2399 N->OldPointsTo = new SparseBitVector<>;
2400 N->Edges = new SparseBitVector<>;
2401 }
2402 CreateConstraintGraph();
Daniel Berlind81ccc22007-09-24 19:45:49 +00002403 UnitePointerEquivalences();
2404 assert(SCCStack.empty() && "SCC Stack should be empty by now!");
Daniel Berlind81ccc22007-09-24 19:45:49 +00002405 Node2DFS.clear();
2406 Node2Deleted.clear();
Daniel Berlinaad15882007-09-16 21:45:02 +00002407 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2408 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2409 DFSNumber = 0;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002410 DenseSet<Constraint, ConstraintKeyInfo> Seen;
2411 DenseSet<std::pair<unsigned,unsigned>, PairKeyInfo> EdgesChecked;
2412
2413 // Order graph and add initial nodes to work list.
Daniel Berlinaad15882007-09-16 21:45:02 +00002414 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
Daniel Berlinaad15882007-09-16 21:45:02 +00002415 Node *INode = &GraphNodes[i];
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002416
2417 // Add to work list if it's a representative and can contribute to the
2418 // calculation right now.
2419 if (INode->isRep() && !INode->PointsTo->empty()
2420 && (!INode->Edges->empty() || !INode->Constraints.empty())) {
2421 INode->Stamp();
2422 CurrWL->insert(INode);
Daniel Berlinaad15882007-09-16 21:45:02 +00002423 }
2424 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002425 std::queue<unsigned int> TarjanWL;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002426#if !FULL_UNIVERSAL
2427 // "Rep and special variables" - in order for HCD to maintain conservative
2428 // results when !FULL_UNIVERSAL, we need to treat the special variables in
2429 // the same way that the !FULL_UNIVERSAL tweak does throughout the rest of
2430 // the analysis - it's ok to add edges from the special nodes, but never
2431 // *to* the special nodes.
2432 std::vector<unsigned int> RSV;
2433#endif
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002434 while( !CurrWL->empty() ) {
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002435 DEBUG(errs() << "Starting iteration #" << ++NumIters << "\n");
Daniel Berlinaad15882007-09-16 21:45:02 +00002436
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002437 Node* CurrNode;
2438 unsigned CurrNodeIndex;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002439
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002440 // Actual cycle checking code. We cycle check all of the lazy cycle
2441 // candidates from the last iteration in one go.
2442 if (!TarjanWL.empty()) {
2443 DFSNumber = 0;
2444
2445 Tarjan2DFS.clear();
2446 Tarjan2Deleted.clear();
2447 while (!TarjanWL.empty()) {
2448 unsigned int ToTarjan = TarjanWL.front();
2449 TarjanWL.pop();
2450 if (!Tarjan2Deleted[ToTarjan]
2451 && GraphNodes[ToTarjan].isRep()
2452 && Tarjan2DFS[ToTarjan] == 0)
2453 QueryNode(ToTarjan);
2454 }
2455 }
2456
2457 // Add to work list if it's a representative and can contribute to the
2458 // calculation right now.
2459 while( (CurrNode = CurrWL->pop()) != NULL ) {
2460 CurrNodeIndex = CurrNode - &GraphNodes[0];
2461 CurrNode->Stamp();
2462
2463
Daniel Berlinaad15882007-09-16 21:45:02 +00002464 // Figure out the changed points to bits
2465 SparseBitVector<> CurrPointsTo;
2466 CurrPointsTo.intersectWithComplement(CurrNode->PointsTo,
2467 CurrNode->OldPointsTo);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002468 if (CurrPointsTo.empty())
Daniel Berlinaad15882007-09-16 21:45:02 +00002469 continue;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002470
Daniel Berlinaad15882007-09-16 21:45:02 +00002471 *(CurrNode->OldPointsTo) |= CurrPointsTo;
Daniel Berlinc864edb2008-03-05 19:31:47 +00002472
2473 // Check the offline-computed equivalencies from HCD.
2474 bool SCC = false;
2475 unsigned Rep;
2476
2477 if (SDT[CurrNodeIndex] >= 0) {
2478 SCC = true;
2479 Rep = FindNode(SDT[CurrNodeIndex]);
2480
2481#if !FULL_UNIVERSAL
2482 RSV.clear();
2483#endif
2484 for (SparseBitVector<>::iterator bi = CurrPointsTo.begin();
2485 bi != CurrPointsTo.end(); ++bi) {
2486 unsigned Node = FindNode(*bi);
2487#if !FULL_UNIVERSAL
2488 if (Node < NumberSpecialNodes) {
2489 RSV.push_back(Node);
2490 continue;
2491 }
2492#endif
2493 Rep = UniteNodes(Rep,Node);
2494 }
2495#if !FULL_UNIVERSAL
2496 RSV.push_back(Rep);
2497#endif
2498
2499 NextWL->insert(&GraphNodes[Rep]);
2500
2501 if ( ! CurrNode->isRep() )
2502 continue;
2503 }
2504
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002505 Seen.clear();
Chris Lattnere995a2a2004-05-23 21:00:47 +00002506
Daniel Berlinaad15882007-09-16 21:45:02 +00002507 /* Now process the constraints for this node. */
2508 for (std::list<Constraint>::iterator li = CurrNode->Constraints.begin();
2509 li != CurrNode->Constraints.end(); ) {
2510 li->Src = FindNode(li->Src);
2511 li->Dest = FindNode(li->Dest);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002512
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002513 // Delete redundant constraints
2514 if( Seen.count(*li) ) {
2515 std::list<Constraint>::iterator lk = li; li++;
2516
2517 CurrNode->Constraints.erase(lk);
2518 ++NumErased;
2519 continue;
2520 }
2521 Seen.insert(*li);
2522
Daniel Berlinaad15882007-09-16 21:45:02 +00002523 // Src and Dest will be the vars we are going to process.
2524 // This may look a bit ugly, but what it does is allow us to process
Daniel Berlind81ccc22007-09-24 19:45:49 +00002525 // both store and load constraints with the same code.
Daniel Berlinaad15882007-09-16 21:45:02 +00002526 // Load constraints say that every member of our RHS solution has K
2527 // added to it, and that variable gets an edge to LHS. We also union
2528 // RHS+K's solution into the LHS solution.
2529 // Store constraints say that every member of our LHS solution has K
2530 // added to it, and that variable gets an edge from RHS. We also union
2531 // RHS's solution into the LHS+K solution.
2532 unsigned *Src;
2533 unsigned *Dest;
2534 unsigned K = li->Offset;
2535 unsigned CurrMember;
2536 if (li->Type == Constraint::Load) {
2537 Src = &CurrMember;
2538 Dest = &li->Dest;
2539 } else if (li->Type == Constraint::Store) {
2540 Src = &li->Src;
2541 Dest = &CurrMember;
2542 } else {
2543 // TODO Handle offseted copy constraint
2544 li++;
2545 continue;
2546 }
Daniel Berlinc864edb2008-03-05 19:31:47 +00002547
2548 // See if we can use Hybrid Cycle Detection (that is, check
Daniel Berlinaad15882007-09-16 21:45:02 +00002549 // if it was a statically detected offline equivalence that
Daniel Berlinc864edb2008-03-05 19:31:47 +00002550 // involves pointers; if so, remove the redundant constraints).
2551 if( SCC && K == 0 ) {
2552#if FULL_UNIVERSAL
2553 CurrMember = Rep;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002554
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002555 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2556 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2557 NextWL->insert(&GraphNodes[*Dest]);
Daniel Berlinc864edb2008-03-05 19:31:47 +00002558#else
2559 for (unsigned i=0; i < RSV.size(); ++i) {
2560 CurrMember = RSV[i];
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002561
Daniel Berlinc864edb2008-03-05 19:31:47 +00002562 if (*Dest < NumberSpecialNodes)
2563 continue;
2564 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2565 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2566 NextWL->insert(&GraphNodes[*Dest]);
2567 }
2568#endif
2569 // since all future elements of the points-to set will be
2570 // equivalent to the current ones, the complex constraints
2571 // become redundant.
2572 //
2573 std::list<Constraint>::iterator lk = li; li++;
2574#if !FULL_UNIVERSAL
2575 // In this case, we can still erase the constraints when the
2576 // elements of the points-to sets are referenced by *Dest,
2577 // but not when they are referenced by *Src (i.e. for a Load
2578 // constraint). This is because if another special variable is
2579 // put into the points-to set later, we still need to add the
2580 // new edge from that special variable.
2581 if( lk->Type != Constraint::Load)
2582#endif
2583 GraphNodes[CurrNodeIndex].Constraints.erase(lk);
2584 } else {
2585 const SparseBitVector<> &Solution = CurrPointsTo;
2586
2587 for (SparseBitVector<>::iterator bi = Solution.begin();
2588 bi != Solution.end();
2589 ++bi) {
2590 CurrMember = *bi;
2591
2592 // Need to increment the member by K since that is where we are
2593 // supposed to copy to/from. Note that in positive weight cycles,
2594 // which occur in address taking of fields, K can go past
2595 // MaxK[CurrMember] elements, even though that is all it could point
2596 // to.
2597 if (K > 0 && K > MaxK[CurrMember])
2598 continue;
2599 else
2600 CurrMember = FindNode(CurrMember + K);
2601
2602 // Add an edge to the graph, so we can just do regular
2603 // bitmap ior next time. It may also let us notice a cycle.
2604#if !FULL_UNIVERSAL
2605 if (*Dest < NumberSpecialNodes)
2606 continue;
2607#endif
2608 if (GraphNodes[*Src].Edges->test_and_set(*Dest))
2609 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo))
2610 NextWL->insert(&GraphNodes[*Dest]);
2611
2612 }
2613 li++;
Daniel Berlinaad15882007-09-16 21:45:02 +00002614 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002615 }
2616 SparseBitVector<> NewEdges;
2617 SparseBitVector<> ToErase;
2618
2619 // Now all we have left to do is propagate points-to info along the
2620 // edges, erasing the redundant edges.
Daniel Berlinaad15882007-09-16 21:45:02 +00002621 for (SparseBitVector<>::iterator bi = CurrNode->Edges->begin();
2622 bi != CurrNode->Edges->end();
2623 ++bi) {
2624
2625 unsigned DestVar = *bi;
2626 unsigned Rep = FindNode(DestVar);
2627
Bill Wendlingf059deb2008-02-26 10:51:52 +00002628 // If we ended up with this node as our destination, or we've already
2629 // got an edge for the representative, delete the current edge.
2630 if (Rep == CurrNodeIndex ||
2631 (Rep != DestVar && NewEdges.test(Rep))) {
Daniel Berlinc864edb2008-03-05 19:31:47 +00002632 ToErase.set(DestVar);
2633 continue;
Bill Wendlingf059deb2008-02-26 10:51:52 +00002634 }
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002635
Bill Wendlingf059deb2008-02-26 10:51:52 +00002636 std::pair<unsigned,unsigned> edge(CurrNodeIndex,Rep);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002637
2638 // This is where we do lazy cycle detection.
2639 // If this is a cycle candidate (equal points-to sets and this
2640 // particular edge has not been cycle-checked previously), add to the
2641 // list to check for cycles on the next iteration.
2642 if (!EdgesChecked.count(edge) &&
2643 *(GraphNodes[Rep].PointsTo) == *(CurrNode->PointsTo)) {
2644 EdgesChecked.insert(edge);
2645 TarjanWL.push(Rep);
Daniel Berlinaad15882007-09-16 21:45:02 +00002646 }
2647 // Union the points-to sets into the dest
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002648#if !FULL_UNIVERSAL
2649 if (Rep >= NumberSpecialNodes)
2650#endif
Daniel Berlinaad15882007-09-16 21:45:02 +00002651 if (GraphNodes[Rep].PointsTo |= CurrPointsTo) {
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002652 NextWL->insert(&GraphNodes[Rep]);
Daniel Berlinaad15882007-09-16 21:45:02 +00002653 }
2654 // If this edge's destination was collapsed, rewrite the edge.
2655 if (Rep != DestVar) {
2656 ToErase.set(DestVar);
2657 NewEdges.set(Rep);
2658 }
2659 }
2660 CurrNode->Edges->intersectWithComplement(ToErase);
2661 CurrNode->Edges |= NewEdges;
2662 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002663
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002664 // Switch to other work list.
2665 WorkList* t = CurrWL; CurrWL = NextWL; NextWL = t;
2666 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002667
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002668
Daniel Berlinaad15882007-09-16 21:45:02 +00002669 Node2DFS.clear();
2670 Node2Deleted.clear();
2671 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2672 Node *N = &GraphNodes[i];
2673 delete N->OldPointsTo;
2674 delete N->Edges;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002675 }
Daniel Berlinc864edb2008-03-05 19:31:47 +00002676 SDTActive = false;
2677 SDT.clear();
Chris Lattnere995a2a2004-05-23 21:00:47 +00002678}
2679
Daniel Berlinaad15882007-09-16 21:45:02 +00002680//===----------------------------------------------------------------------===//
2681// Union-Find
2682//===----------------------------------------------------------------------===//
Chris Lattnere995a2a2004-05-23 21:00:47 +00002683
Daniel Berlinaad15882007-09-16 21:45:02 +00002684// Unite nodes First and Second, returning the one which is now the
2685// representative node. First and Second are indexes into GraphNodes
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002686unsigned Andersens::UniteNodes(unsigned First, unsigned Second,
2687 bool UnionByRank) {
Daniel Berlinaad15882007-09-16 21:45:02 +00002688 assert (First < GraphNodes.size() && Second < GraphNodes.size() &&
2689 "Attempting to merge nodes that don't exist");
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002690
Daniel Berlinaad15882007-09-16 21:45:02 +00002691 Node *FirstNode = &GraphNodes[First];
2692 Node *SecondNode = &GraphNodes[Second];
2693
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002694 assert (SecondNode->isRep() && FirstNode->isRep() &&
Daniel Berlinaad15882007-09-16 21:45:02 +00002695 "Trying to unite two non-representative nodes!");
2696 if (First == Second)
2697 return First;
2698
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002699 if (UnionByRank) {
2700 int RankFirst = (int) FirstNode ->NodeRep;
2701 int RankSecond = (int) SecondNode->NodeRep;
2702
2703 // Rank starts at -1 and gets decremented as it increases.
2704 // Translation: higher rank, lower NodeRep value, which is always negative.
2705 if (RankFirst > RankSecond) {
2706 unsigned t = First; First = Second; Second = t;
2707 Node* tp = FirstNode; FirstNode = SecondNode; SecondNode = tp;
2708 } else if (RankFirst == RankSecond) {
2709 FirstNode->NodeRep = (unsigned) (RankFirst - 1);
2710 }
2711 }
2712
Daniel Berlinaad15882007-09-16 21:45:02 +00002713 SecondNode->NodeRep = First;
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002714#if !FULL_UNIVERSAL
2715 if (First >= NumberSpecialNodes)
2716#endif
Daniel Berlind81ccc22007-09-24 19:45:49 +00002717 if (FirstNode->PointsTo && SecondNode->PointsTo)
2718 FirstNode->PointsTo |= *(SecondNode->PointsTo);
2719 if (FirstNode->Edges && SecondNode->Edges)
2720 FirstNode->Edges |= *(SecondNode->Edges);
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002721 if (!SecondNode->Constraints.empty())
Daniel Berlind81ccc22007-09-24 19:45:49 +00002722 FirstNode->Constraints.splice(FirstNode->Constraints.begin(),
2723 SecondNode->Constraints);
2724 if (FirstNode->OldPointsTo) {
2725 delete FirstNode->OldPointsTo;
2726 FirstNode->OldPointsTo = new SparseBitVector<>;
2727 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002728
2729 // Destroy interesting parts of the merged-from node.
2730 delete SecondNode->OldPointsTo;
2731 delete SecondNode->Edges;
2732 delete SecondNode->PointsTo;
2733 SecondNode->Edges = NULL;
2734 SecondNode->PointsTo = NULL;
2735 SecondNode->OldPointsTo = NULL;
2736
2737 NumUnified++;
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002738 DEBUG(errs() << "Unified Node ");
Daniel Berlinaad15882007-09-16 21:45:02 +00002739 DEBUG(PrintNode(FirstNode));
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002740 DEBUG(errs() << " and Node ");
Daniel Berlinaad15882007-09-16 21:45:02 +00002741 DEBUG(PrintNode(SecondNode));
Chris Lattnerbbbfa992009-08-23 06:35:02 +00002742 DEBUG(errs() << "\n");
Daniel Berlinaad15882007-09-16 21:45:02 +00002743
Daniel Berlinc864edb2008-03-05 19:31:47 +00002744 if (SDTActive)
Duncan Sands43e2a032008-05-27 11:50:51 +00002745 if (SDT[Second] >= 0) {
Daniel Berlinc864edb2008-03-05 19:31:47 +00002746 if (SDT[First] < 0)
2747 SDT[First] = SDT[Second];
2748 else {
2749 UniteNodes( FindNode(SDT[First]), FindNode(SDT[Second]) );
2750 First = FindNode(First);
2751 }
Duncan Sands43e2a032008-05-27 11:50:51 +00002752 }
Daniel Berlinc864edb2008-03-05 19:31:47 +00002753
Daniel Berlinaad15882007-09-16 21:45:02 +00002754 return First;
2755}
2756
2757// Find the index into GraphNodes of the node representing Node, performing
2758// path compression along the way
2759unsigned Andersens::FindNode(unsigned NodeIndex) {
2760 assert (NodeIndex < GraphNodes.size()
2761 && "Attempting to find a node that can't exist");
2762 Node *N = &GraphNodes[NodeIndex];
Daniel Berlin3a3f1632007-12-12 00:37:04 +00002763 if (N->isRep())
Daniel Berlinaad15882007-09-16 21:45:02 +00002764 return NodeIndex;
2765 else
2766 return (N->NodeRep = FindNode(N->NodeRep));
2767}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002768
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002769// Find the index into GraphNodes of the node representing Node,
2770// don't perform path compression along the way (for Print)
2771unsigned Andersens::FindNode(unsigned NodeIndex) const {
2772 assert (NodeIndex < GraphNodes.size()
2773 && "Attempting to find a node that can't exist");
2774 const Node *N = &GraphNodes[NodeIndex];
2775 if (N->isRep())
2776 return NodeIndex;
2777 else
2778 return FindNode(N->NodeRep);
2779}
2780
Chris Lattnere995a2a2004-05-23 21:00:47 +00002781//===----------------------------------------------------------------------===//
2782// Debugging Output
2783//===----------------------------------------------------------------------===//
2784
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002785void Andersens::PrintNode(const Node *N) const {
Chris Lattnere995a2a2004-05-23 21:00:47 +00002786 if (N == &GraphNodes[UniversalSet]) {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002787 errs() << "<universal>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002788 return;
2789 } else if (N == &GraphNodes[NullPtr]) {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002790 errs() << "<nullptr>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002791 return;
2792 } else if (N == &GraphNodes[NullObject]) {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002793 errs() << "<null>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002794 return;
2795 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002796 if (!N->getValue()) {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002797 errs() << "artificial" << (intptr_t) N;
Daniel Berlinaad15882007-09-16 21:45:02 +00002798 return;
2799 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002800
2801 assert(N->getValue() != 0 && "Never set node label!");
2802 Value *V = N->getValue();
2803 if (Function *F = dyn_cast<Function>(V)) {
2804 if (isa<PointerType>(F->getFunctionType()->getReturnType()) &&
Daniel Berlinaad15882007-09-16 21:45:02 +00002805 N == &GraphNodes[getReturnNode(F)]) {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002806 errs() << F->getName() << ":retval";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002807 return;
Daniel Berlinaad15882007-09-16 21:45:02 +00002808 } else if (F->getFunctionType()->isVarArg() &&
2809 N == &GraphNodes[getVarargNode(F)]) {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002810 errs() << F->getName() << ":vararg";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002811 return;
2812 }
2813 }
2814
2815 if (Instruction *I = dyn_cast<Instruction>(V))
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002816 errs() << I->getParent()->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002817 else if (Argument *Arg = dyn_cast<Argument>(V))
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002818 errs() << Arg->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002819
2820 if (V->hasName())
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002821 errs() << V->getName();
Chris Lattnere995a2a2004-05-23 21:00:47 +00002822 else
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002823 errs() << "(unnamed)";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002824
Victor Hernandez7b929da2009-10-23 21:09:37 +00002825 if (isa<GlobalValue>(V) || isa<AllocaInst>(V) || isMalloc(V))
Daniel Berlinaad15882007-09-16 21:45:02 +00002826 if (N == &GraphNodes[getObject(V)])
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002827 errs() << "<mem>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002828}
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002829void Andersens::PrintConstraint(const Constraint &C) const {
Daniel Berlind81ccc22007-09-24 19:45:49 +00002830 if (C.Type == Constraint::Store) {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002831 errs() << "*";
Daniel Berlind81ccc22007-09-24 19:45:49 +00002832 if (C.Offset != 0)
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002833 errs() << "(";
Daniel Berlind81ccc22007-09-24 19:45:49 +00002834 }
2835 PrintNode(&GraphNodes[C.Dest]);
2836 if (C.Type == Constraint::Store && C.Offset != 0)
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002837 errs() << " + " << C.Offset << ")";
2838 errs() << " = ";
Daniel Berlind81ccc22007-09-24 19:45:49 +00002839 if (C.Type == Constraint::Load) {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002840 errs() << "*";
Daniel Berlind81ccc22007-09-24 19:45:49 +00002841 if (C.Offset != 0)
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002842 errs() << "(";
Daniel Berlind81ccc22007-09-24 19:45:49 +00002843 }
2844 else if (C.Type == Constraint::AddressOf)
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002845 errs() << "&";
Daniel Berlind81ccc22007-09-24 19:45:49 +00002846 PrintNode(&GraphNodes[C.Src]);
2847 if (C.Offset != 0 && C.Type != Constraint::Store)
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002848 errs() << " + " << C.Offset;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002849 if (C.Type == Constraint::Load && C.Offset != 0)
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002850 errs() << ")";
2851 errs() << "\n";
Daniel Berlind81ccc22007-09-24 19:45:49 +00002852}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002853
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002854void Andersens::PrintConstraints() const {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002855 errs() << "Constraints:\n";
Daniel Berlinaad15882007-09-16 21:45:02 +00002856
Daniel Berlind81ccc22007-09-24 19:45:49 +00002857 for (unsigned i = 0, e = Constraints.size(); i != e; ++i)
2858 PrintConstraint(Constraints[i]);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002859}
2860
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002861void Andersens::PrintPointsToGraph() const {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002862 errs() << "Points-to graph:\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002863 for (unsigned i = 0, e = GraphNodes.size(); i != e; ++i) {
Andrew Lenharth52d34d92008-03-20 15:36:44 +00002864 const Node *N = &GraphNodes[i];
2865 if (FindNode(i) != i) {
Daniel Berlinaad15882007-09-16 21:45:02 +00002866 PrintNode(N);
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002867 errs() << "\t--> same as ";
Daniel Berlinaad15882007-09-16 21:45:02 +00002868 PrintNode(&GraphNodes[FindNode(i)]);
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002869 errs() << "\n";
Daniel Berlinaad15882007-09-16 21:45:02 +00002870 } else {
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002871 errs() << "[" << (N->PointsTo->count()) << "] ";
Daniel Berlinaad15882007-09-16 21:45:02 +00002872 PrintNode(N);
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002873 errs() << "\t--> ";
Daniel Berlinaad15882007-09-16 21:45:02 +00002874
2875 bool first = true;
2876 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
2877 bi != N->PointsTo->end();
2878 ++bi) {
2879 if (!first)
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002880 errs() << ", ";
Daniel Berlinaad15882007-09-16 21:45:02 +00002881 PrintNode(&GraphNodes[*bi]);
2882 first = false;
2883 }
Daniel Dunbar3f0e8302009-07-24 09:53:24 +00002884 errs() << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002885 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002886 }
2887}