blob: 247699c6b1eaf8b635433e42b6e935c26fb01a88 [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//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source 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
34// substitution algorithms intended to computer pointer and location
35// equivalences. Pointer equivalences are those pointers that will have the
36// same points-to sets, and location equivalences are those variables that
37// always appear together in points-to sets.
Daniel Berlind81ccc22007-09-24 19:45:49 +000038//
Chris Lattnere995a2a2004-05-23 21:00:47 +000039// The inclusion constraint solving phase iteratively propagates the inclusion
40// constraints until a fixed point is reached. This is an O(N^3) algorithm.
41//
Daniel Berlinaad15882007-09-16 21:45:02 +000042// Function constraints are handled as if they were structs with X fields.
43// Thus, an access to argument X of function Y is an access to node index
44// getNode(Y) + X. This representation allows handling of indirect calls
Daniel Berlind81ccc22007-09-24 19:45:49 +000045// without any issues. To wit, an indirect call Y(a,b) is equivalent to
Daniel Berlinaad15882007-09-16 21:45:02 +000046// *(Y + 1) = a, *(Y + 2) = b.
47// The return node for a function is always located at getNode(F) +
48// CallReturnPos. The arguments start at getNode(F) + CallArgPos.
Chris Lattnere995a2a2004-05-23 21:00:47 +000049//
Chris Lattnerc7ca32b2004-06-05 20:12:36 +000050// Future Improvements:
Daniel Berlind81ccc22007-09-24 19:45:49 +000051// Offline detection of online cycles. Use of BDD's.
Chris Lattnere995a2a2004-05-23 21:00:47 +000052//===----------------------------------------------------------------------===//
53
54#define DEBUG_TYPE "anders-aa"
55#include "llvm/Constants.h"
56#include "llvm/DerivedTypes.h"
57#include "llvm/Instructions.h"
58#include "llvm/Module.h"
59#include "llvm/Pass.h"
Reid Spencerd7d83db2007-02-05 23:42:17 +000060#include "llvm/Support/Compiler.h"
Chris Lattnere995a2a2004-05-23 21:00:47 +000061#include "llvm/Support/InstIterator.h"
62#include "llvm/Support/InstVisitor.h"
63#include "llvm/Analysis/AliasAnalysis.h"
Jeff Cohen534927d2005-01-08 22:01:16 +000064#include "llvm/Analysis/Passes.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000065#include "llvm/Support/Debug.h"
66#include "llvm/ADT/Statistic.h"
Daniel Berlinaad15882007-09-16 21:45:02 +000067#include "llvm/ADT/SparseBitVector.h"
Daniel Berlind81ccc22007-09-24 19:45:49 +000068#include "llvm/ADT/DenseMap.h"
Jeff Cohenca5183d2007-03-05 00:00:42 +000069#include <algorithm>
Chris Lattnere995a2a2004-05-23 21:00:47 +000070#include <set>
Daniel Berlinaad15882007-09-16 21:45:02 +000071#include <list>
72#include <stack>
73#include <vector>
Chris Lattnere995a2a2004-05-23 21:00:47 +000074
Daniel Berlinaad15882007-09-16 21:45:02 +000075using namespace llvm;
Daniel Berlind81ccc22007-09-24 19:45:49 +000076STATISTIC(NumIters , "Number of iterations to reach convergence");
77STATISTIC(NumConstraints, "Number of constraints");
78STATISTIC(NumNodes , "Number of nodes");
79STATISTIC(NumUnified , "Number of variables unified");
Chris Lattnere995a2a2004-05-23 21:00:47 +000080
Chris Lattner3b27d682006-12-19 22:30:33 +000081namespace {
Daniel Berlinaad15882007-09-16 21:45:02 +000082 const unsigned SelfRep = (unsigned)-1;
83 const unsigned Unvisited = (unsigned)-1;
84 // Position of the function return node relative to the function node.
Daniel Berlind81ccc22007-09-24 19:45:49 +000085 const unsigned CallReturnPos = 1;
Daniel Berlinaad15882007-09-16 21:45:02 +000086 // Position of the function call node relative to the function node.
Daniel Berlind81ccc22007-09-24 19:45:49 +000087 const unsigned CallFirstArgPos = 2;
88
89 struct BitmapKeyInfo {
90 static inline SparseBitVector<> *getEmptyKey() {
91 return reinterpret_cast<SparseBitVector<> *>(-1);
92 }
93 static inline SparseBitVector<> *getTombstoneKey() {
94 return reinterpret_cast<SparseBitVector<> *>(-2);
95 }
96 static unsigned getHashValue(const SparseBitVector<> *bitmap) {
97 return bitmap->getHashValue();
98 }
99 static bool isEqual(const SparseBitVector<> *LHS,
100 const SparseBitVector<> *RHS) {
101 if (LHS == RHS)
102 return true;
103 else if (LHS == getEmptyKey() || RHS == getEmptyKey()
104 || LHS == getTombstoneKey() || RHS == getTombstoneKey())
105 return false;
106
107 return *LHS == *RHS;
108 }
109
110 static bool isPod() { return true; }
111 };
Daniel Berlinaad15882007-09-16 21:45:02 +0000112
Reid Spencerd7d83db2007-02-05 23:42:17 +0000113 class VISIBILITY_HIDDEN Andersens : public ModulePass, public AliasAnalysis,
114 private InstVisitor<Andersens> {
Daniel Berlinaad15882007-09-16 21:45:02 +0000115 class Node;
116
117 /// Constraint - Objects of this structure are used to represent the various
118 /// constraints identified by the algorithm. The constraints are 'copy',
119 /// for statements like "A = B", 'load' for statements like "A = *B",
120 /// 'store' for statements like "*A = B", and AddressOf for statements like
121 /// A = alloca; The Offset is applied as *(A + K) = B for stores,
122 /// A = *(B + K) for loads, and A = B + K for copies. It is
Daniel Berlind81ccc22007-09-24 19:45:49 +0000123 /// illegal on addressof constraints (because it is statically
Daniel Berlinaad15882007-09-16 21:45:02 +0000124 /// resolvable to A = &C where C = B + K)
125
126 struct Constraint {
127 enum ConstraintType { Copy, Load, Store, AddressOf } Type;
128 unsigned Dest;
129 unsigned Src;
130 unsigned Offset;
131
132 Constraint(ConstraintType Ty, unsigned D, unsigned S, unsigned O = 0)
133 : Type(Ty), Dest(D), Src(S), Offset(O) {
134 assert(Offset == 0 || Ty != AddressOf &&
135 "Offset is illegal on addressof constraints");
136 }
137 };
138
Daniel Berlind81ccc22007-09-24 19:45:49 +0000139 // Node class - This class is used to represent a node in the constraint
Daniel Berline6f04792007-09-24 22:20:45 +0000140 // graph. Due to various optimizations, it is not always the case that
141 // there is a mapping from a Node to a Value. In particular, we add
142 // artificial Node's that represent the set of pointed-to variables shared
143 // for each location equivalent Node.
Daniel Berlinaad15882007-09-16 21:45:02 +0000144 struct Node {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000145 Value *Val;
Daniel Berlinaad15882007-09-16 21:45:02 +0000146 SparseBitVector<> *Edges;
147 SparseBitVector<> *PointsTo;
148 SparseBitVector<> *OldPointsTo;
149 bool Changed;
150 std::list<Constraint> Constraints;
151
Daniel Berlind81ccc22007-09-24 19:45:49 +0000152 // Pointer and location equivalence labels
153 unsigned PointerEquivLabel;
154 unsigned LocationEquivLabel;
155 // Predecessor edges, both real and implicit
156 SparseBitVector<> *PredEdges;
157 SparseBitVector<> *ImplicitPredEdges;
158 // Set of nodes that point to us, only use for location equivalence.
159 SparseBitVector<> *PointedToBy;
160 // Number of incoming edges, used during variable substitution to early
161 // free the points-to sets
162 unsigned NumInEdges;
Daniel Berline6f04792007-09-24 22:20:45 +0000163 // True if our points-to set is in the Set2PEClass map
Daniel Berlind81ccc22007-09-24 19:45:49 +0000164 bool StoredInHash;
Daniel Berline6f04792007-09-24 22:20:45 +0000165 // True if our node has no indirect constraints (complex or otherwise)
Daniel Berlind81ccc22007-09-24 19:45:49 +0000166 bool Direct;
167 // True if the node is address taken, *or* it is part of a group of nodes
168 // that must be kept together. This is set to true for functions and
169 // their arg nodes, which must be kept at the same position relative to
170 // their base function node.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000171 bool AddressTaken;
Daniel Berlinaad15882007-09-16 21:45:02 +0000172
Daniel Berlind81ccc22007-09-24 19:45:49 +0000173 // Nodes in cycles (or in equivalence classes) are united together using a
174 // standard union-find representation with path compression. NodeRep
175 // gives the index into GraphNodes for the representative Node.
176 unsigned NodeRep;
177 public:
178
179 Node(bool direct = true) :
180 Val(0), Edges(0), PointsTo(0), OldPointsTo(0), Changed(false),
181 PointerEquivLabel(0), LocationEquivLabel(0), PredEdges(0),
182 ImplicitPredEdges(0), PointedToBy(0), NumInEdges(0),
183 StoredInHash(false), Direct(direct), AddressTaken(false),
184 NodeRep(SelfRep) { }
Daniel Berlinaad15882007-09-16 21:45:02 +0000185
Chris Lattnere995a2a2004-05-23 21:00:47 +0000186 Node *setValue(Value *V) {
187 assert(Val == 0 && "Value already set for this node!");
188 Val = V;
189 return this;
190 }
191
192 /// getValue - Return the LLVM value corresponding to this node.
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000193 ///
Chris Lattnere995a2a2004-05-23 21:00:47 +0000194 Value *getValue() const { return Val; }
195
Chris Lattnere995a2a2004-05-23 21:00:47 +0000196 /// addPointerTo - Add a pointer to the list of pointees of this node,
197 /// returning true if this caused a new pointer to be added, or false if
198 /// we already knew about the points-to relation.
Daniel Berlinaad15882007-09-16 21:45:02 +0000199 bool addPointerTo(unsigned Node) {
200 return PointsTo->test_and_set(Node);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000201 }
202
203 /// intersects - Return true if the points-to set of this node intersects
204 /// with the points-to set of the specified node.
205 bool intersects(Node *N) const;
206
207 /// intersectsIgnoring - Return true if the points-to set of this node
208 /// intersects with the points-to set of the specified node on any nodes
209 /// except for the specified node to ignore.
Daniel Berlinaad15882007-09-16 21:45:02 +0000210 bool intersectsIgnoring(Node *N, unsigned) const;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000211 };
212
213 /// GraphNodes - This vector is populated as part of the object
214 /// identification stage of the analysis, which populates this vector with a
215 /// node for each memory object and fills in the ValueNodes map.
216 std::vector<Node> GraphNodes;
217
218 /// ValueNodes - This map indicates the Node that a particular Value* is
219 /// represented by. This contains entries for all pointers.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000220 DenseMap<Value*, unsigned> ValueNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000221
222 /// ObjectNodes - This map contains entries for each memory object in the
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000223 /// program: globals, alloca's and mallocs.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000224 DenseMap<Value*, unsigned> ObjectNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000225
226 /// ReturnNodes - This map contains an entry for each function in the
227 /// program that returns a value.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000228 DenseMap<Function*, unsigned> ReturnNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000229
230 /// VarargNodes - This map contains the entry used to represent all pointers
231 /// passed through the varargs portion of a function call for a particular
232 /// function. An entry is not present in this map for functions that do not
233 /// take variable arguments.
Daniel Berlind81ccc22007-09-24 19:45:49 +0000234 DenseMap<Function*, unsigned> VarargNodes;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000235
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000236
Chris Lattnere995a2a2004-05-23 21:00:47 +0000237 /// Constraints - This vector contains a list of all of the constraints
238 /// identified by the program.
239 std::vector<Constraint> Constraints;
240
Daniel Berlind81ccc22007-09-24 19:45:49 +0000241 // Map from graph node to maximum K value that is allowed (for functions,
Daniel Berlinaad15882007-09-16 21:45:02 +0000242 // this is equivalent to the number of arguments + CallFirstArgPos)
243 std::map<unsigned, unsigned> MaxK;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000244
245 /// This enum defines the GraphNodes indices that correspond to important
246 /// fixed sets.
247 enum {
248 UniversalSet = 0,
249 NullPtr = 1,
Daniel Berlind81ccc22007-09-24 19:45:49 +0000250 NullObject = 2,
251 NumberSpecialNodes
Chris Lattnere995a2a2004-05-23 21:00:47 +0000252 };
Daniel Berlind81ccc22007-09-24 19:45:49 +0000253 // Stack for Tarjan's
Daniel Berlinaad15882007-09-16 21:45:02 +0000254 std::stack<unsigned> SCCStack;
255 // Topological Index -> Graph node
256 std::vector<unsigned> Topo2Node;
257 // Graph Node -> Topological Index;
258 std::vector<unsigned> Node2Topo;
259 // Map from Graph Node to DFS number
260 std::vector<unsigned> Node2DFS;
261 // Map from Graph Node to Deleted from graph.
262 std::vector<bool> Node2Deleted;
263 // Current DFS and RPO numbers
264 unsigned DFSNumber;
265 unsigned RPONumber;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000266
Daniel Berlind81ccc22007-09-24 19:45:49 +0000267 // Offline variable substitution related things
268
269 // Temporary rep storage, used because we can't collapse SCC's in the
270 // predecessor graph by uniting the variables permanently, we can only do so
271 // for the successor graph.
272 std::vector<unsigned> VSSCCRep;
273 // Mapping from node to whether we have visited it during SCC finding yet.
274 std::vector<bool> Node2Visited;
275 // During variable substitution, we create unknowns to represent the unknown
276 // value that is a dereference of a variable. These nodes are known as
277 // "ref" nodes (since they represent the value of dereferences).
278 unsigned FirstRefNode;
279 // During HVN, we create represent address taken nodes as if they were
280 // unknown (since HVN, unlike HU, does not evaluate unions).
281 unsigned FirstAdrNode;
282 // Current pointer equivalence class number
283 unsigned PEClass;
284 // Mapping from points-to sets to equivalence classes
285 typedef DenseMap<SparseBitVector<> *, unsigned, BitmapKeyInfo> BitVectorMap;
286 BitVectorMap Set2PEClass;
287 // Mapping from pointer equivalences to the representative node. -1 if we
288 // have no representative node for this pointer equivalence class yet.
289 std::vector<int> PEClass2Node;
290 // Mapping from pointer equivalences to representative node. This includes
291 // pointer equivalent but not location equivalent variables. -1 if we have
292 // no representative node for this pointer equivalence class yet.
293 std::vector<int> PENLEClass2Node;
294
Chris Lattnere995a2a2004-05-23 21:00:47 +0000295 public:
Daniel Berlinaad15882007-09-16 21:45:02 +0000296 static char ID;
297 Andersens() : ModulePass((intptr_t)&ID) {}
298
Chris Lattnerb12914b2004-09-20 04:48:05 +0000299 bool runOnModule(Module &M) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000300 InitializeAliasAnalysis(this);
301 IdentifyObjects(M);
302 CollectConstraints(M);
Daniel Berlind81ccc22007-09-24 19:45:49 +0000303#undef DEBUG_TYPE
304#define DEBUG_TYPE "anders-aa-constraints"
Chris Lattnere995a2a2004-05-23 21:00:47 +0000305 DEBUG(PrintConstraints());
Daniel Berlind81ccc22007-09-24 19:45:49 +0000306#undef DEBUG_TYPE
307#define DEBUG_TYPE "anders-aa"
Chris Lattnere995a2a2004-05-23 21:00:47 +0000308 SolveConstraints();
309 DEBUG(PrintPointsToGraph());
310
311 // Free the constraints list, as we don't need it to respond to alias
312 // requests.
313 ObjectNodes.clear();
314 ReturnNodes.clear();
315 VarargNodes.clear();
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000316 std::vector<Constraint>().swap(Constraints);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000317 return false;
318 }
319
320 void releaseMemory() {
321 // FIXME: Until we have transitively required passes working correctly,
322 // this cannot be enabled! Otherwise, using -count-aa with the pass
323 // causes memory to be freed too early. :(
324#if 0
325 // The memory objects and ValueNodes data structures at the only ones that
326 // are still live after construction.
327 std::vector<Node>().swap(GraphNodes);
328 ValueNodes.clear();
329#endif
330 }
331
332 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
333 AliasAnalysis::getAnalysisUsage(AU);
334 AU.setPreservesAll(); // Does not transform code
335 }
336
337 //------------------------------------------------
338 // Implement the AliasAnalysis API
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000339 //
Chris Lattnere995a2a2004-05-23 21:00:47 +0000340 AliasResult alias(const Value *V1, unsigned V1Size,
341 const Value *V2, unsigned V2Size);
Reid Spencer3a9ec242006-08-28 01:02:49 +0000342 virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
343 virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000344 void getMustAliases(Value *P, std::vector<Value*> &RetVals);
345 bool pointsToConstantMemory(const Value *P);
346
347 virtual void deleteValue(Value *V) {
348 ValueNodes.erase(V);
349 getAnalysis<AliasAnalysis>().deleteValue(V);
350 }
351
352 virtual void copyValue(Value *From, Value *To) {
353 ValueNodes[To] = ValueNodes[From];
354 getAnalysis<AliasAnalysis>().copyValue(From, To);
355 }
356
357 private:
358 /// getNode - Return the node corresponding to the specified pointer scalar.
359 ///
Daniel Berlinaad15882007-09-16 21:45:02 +0000360 unsigned getNode(Value *V) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000361 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattnerdf9b7bc2004-08-16 05:38:02 +0000362 if (!isa<GlobalValue>(C))
363 return getNodeForConstantPointer(C);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000364
Daniel Berlind81ccc22007-09-24 19:45:49 +0000365 DenseMap<Value*, unsigned>::iterator I = ValueNodes.find(V);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000366 if (I == ValueNodes.end()) {
Jim Laskey16d42c62006-07-11 18:25:13 +0000367#ifndef NDEBUG
368 V->dump();
369#endif
Jim Laskeye37fe9b2006-07-11 17:58:07 +0000370 assert(0 && "Value does not have a node in the points-to graph!");
Chris Lattnere995a2a2004-05-23 21:00:47 +0000371 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000372 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000373 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000374
Chris Lattnere995a2a2004-05-23 21:00:47 +0000375 /// getObject - Return the node corresponding to the memory object for the
376 /// specified global or allocation instruction.
Daniel Berlinaad15882007-09-16 21:45:02 +0000377 unsigned getObject(Value *V) {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000378 DenseMap<Value*, unsigned>::iterator I = ObjectNodes.find(V);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000379 assert(I != ObjectNodes.end() &&
380 "Value does not have an object in the points-to graph!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000381 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000382 }
383
384 /// getReturnNode - Return the node representing the return value for the
385 /// specified function.
Daniel Berlinaad15882007-09-16 21:45:02 +0000386 unsigned getReturnNode(Function *F) {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000387 DenseMap<Function*, unsigned>::iterator I = ReturnNodes.find(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000388 assert(I != ReturnNodes.end() && "Function does not return a value!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000389 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000390 }
391
392 /// getVarargNode - Return the node representing the variable arguments
393 /// formal for the specified function.
Daniel Berlinaad15882007-09-16 21:45:02 +0000394 unsigned getVarargNode(Function *F) {
Daniel Berlind81ccc22007-09-24 19:45:49 +0000395 DenseMap<Function*, unsigned>::iterator I = VarargNodes.find(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000396 assert(I != VarargNodes.end() && "Function does not take var args!");
Daniel Berlinaad15882007-09-16 21:45:02 +0000397 return I->second;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000398 }
399
400 /// getNodeValue - Get the node for the specified LLVM value and set the
401 /// value for it to be the specified value.
Daniel Berlinaad15882007-09-16 21:45:02 +0000402 unsigned getNodeValue(Value &V) {
403 unsigned Index = getNode(&V);
404 GraphNodes[Index].setValue(&V);
405 return Index;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000406 }
407
Daniel Berlinaad15882007-09-16 21:45:02 +0000408 unsigned UniteNodes(unsigned First, unsigned Second);
409 unsigned FindNode(unsigned Node);
410
Chris Lattnere995a2a2004-05-23 21:00:47 +0000411 void IdentifyObjects(Module &M);
412 void CollectConstraints(Module &M);
Daniel Berlinaad15882007-09-16 21:45:02 +0000413 bool AnalyzeUsesOfFunction(Value *);
414 void CreateConstraintGraph();
Daniel Berlind81ccc22007-09-24 19:45:49 +0000415 void OptimizeConstraints();
416 unsigned FindEquivalentNode(unsigned, unsigned);
417 void ClumpAddressTaken();
418 void RewriteConstraints();
419 void HU();
420 void HVN();
421 void UnitePointerEquivalences();
Chris Lattnere995a2a2004-05-23 21:00:47 +0000422 void SolveConstraints();
Daniel Berlinaad15882007-09-16 21:45:02 +0000423 void QueryNode(unsigned Node);
Daniel Berlind81ccc22007-09-24 19:45:49 +0000424 void Condense(unsigned Node);
425 void HUValNum(unsigned Node);
426 void HVNValNum(unsigned Node);
Daniel Berlinaad15882007-09-16 21:45:02 +0000427 unsigned getNodeForConstantPointer(Constant *C);
428 unsigned getNodeForConstantPointerTarget(Constant *C);
429 void AddGlobalInitializerConstraints(unsigned, Constant *C);
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000430
Chris Lattnere995a2a2004-05-23 21:00:47 +0000431 void AddConstraintsForNonInternalLinkage(Function *F);
432 void AddConstraintsForCall(CallSite CS, Function *F);
Chris Lattner8a446432005-03-29 06:09:07 +0000433 bool AddConstraintsForExternalCall(CallSite CS, Function *F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000434
435
436 void PrintNode(Node *N);
437 void PrintConstraints();
Daniel Berlind81ccc22007-09-24 19:45:49 +0000438 void PrintConstraint(const Constraint &);
439 void PrintLabels();
Chris Lattnere995a2a2004-05-23 21:00:47 +0000440 void PrintPointsToGraph();
441
442 //===------------------------------------------------------------------===//
443 // Instruction visitation methods for adding constraints
444 //
445 friend class InstVisitor<Andersens>;
446 void visitReturnInst(ReturnInst &RI);
447 void visitInvokeInst(InvokeInst &II) { visitCallSite(CallSite(&II)); }
448 void visitCallInst(CallInst &CI) { visitCallSite(CallSite(&CI)); }
449 void visitCallSite(CallSite CS);
450 void visitAllocationInst(AllocationInst &AI);
451 void visitLoadInst(LoadInst &LI);
452 void visitStoreInst(StoreInst &SI);
453 void visitGetElementPtrInst(GetElementPtrInst &GEP);
454 void visitPHINode(PHINode &PN);
455 void visitCastInst(CastInst &CI);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000456 void visitICmpInst(ICmpInst &ICI) {} // NOOP!
457 void visitFCmpInst(FCmpInst &ICI) {} // NOOP!
Chris Lattnere995a2a2004-05-23 21:00:47 +0000458 void visitSelectInst(SelectInst &SI);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000459 void visitVAArg(VAArgInst &I);
460 void visitInstruction(Instruction &I);
Daniel Berlinaad15882007-09-16 21:45:02 +0000461
Chris Lattnere995a2a2004-05-23 21:00:47 +0000462 };
463
Devang Patel19974732007-05-03 01:11:54 +0000464 char Andersens::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +0000465 RegisterPass<Andersens> X("anders-aa",
466 "Andersen's Interprocedural Alias Analysis");
Chris Lattnera5370172006-08-28 00:42:29 +0000467 RegisterAnalysisGroup<AliasAnalysis> Y(X);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000468}
469
Jeff Cohen534927d2005-01-08 22:01:16 +0000470ModulePass *llvm::createAndersensPass() { return new Andersens(); }
471
Chris Lattnere995a2a2004-05-23 21:00:47 +0000472//===----------------------------------------------------------------------===//
473// AliasAnalysis Interface Implementation
474//===----------------------------------------------------------------------===//
475
476AliasAnalysis::AliasResult Andersens::alias(const Value *V1, unsigned V1Size,
477 const Value *V2, unsigned V2Size) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000478 Node *N1 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V1)))];
479 Node *N2 = &GraphNodes[FindNode(getNode(const_cast<Value*>(V2)))];
Chris Lattnere995a2a2004-05-23 21:00:47 +0000480
481 // Check to see if the two pointers are known to not alias. They don't alias
482 // if their points-to sets do not intersect.
Daniel Berlinaad15882007-09-16 21:45:02 +0000483 if (!N1->intersectsIgnoring(N2, NullObject))
Chris Lattnere995a2a2004-05-23 21:00:47 +0000484 return NoAlias;
485
486 return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
487}
488
Chris Lattnerf392c642005-03-28 06:21:17 +0000489AliasAnalysis::ModRefResult
490Andersens::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
491 // The only thing useful that we can contribute for mod/ref information is
492 // when calling external function calls: if we know that memory never escapes
493 // from the program, it cannot be modified by an external call.
494 //
495 // NOTE: This is not really safe, at least not when the entire program is not
496 // available. The deal is that the external function could call back into the
497 // program and modify stuff. We ignore this technical niggle for now. This
498 // is, after all, a "research quality" implementation of Andersen's analysis.
499 if (Function *F = CS.getCalledFunction())
Reid Spencer5cbf9852007-01-30 20:08:39 +0000500 if (F->isDeclaration()) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000501 Node *N1 = &GraphNodes[FindNode(getNode(P))];
Chris Lattnerf392c642005-03-28 06:21:17 +0000502
Daniel Berlinaad15882007-09-16 21:45:02 +0000503 if (N1->PointsTo->empty())
504 return NoModRef;
Chris Lattnerf392c642005-03-28 06:21:17 +0000505
Daniel Berlinaad15882007-09-16 21:45:02 +0000506 if (!N1->PointsTo->test(UniversalSet))
Chris Lattnerf392c642005-03-28 06:21:17 +0000507 return NoModRef; // P doesn't point to the universal set.
508 }
509
510 return AliasAnalysis::getModRefInfo(CS, P, Size);
511}
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000512
Reid Spencer3a9ec242006-08-28 01:02:49 +0000513AliasAnalysis::ModRefResult
514Andersens::getModRefInfo(CallSite CS1, CallSite CS2) {
515 return AliasAnalysis::getModRefInfo(CS1,CS2);
516}
517
Chris Lattnere995a2a2004-05-23 21:00:47 +0000518/// getMustAlias - We can provide must alias information if we know that a
519/// pointer can only point to a specific function or the null pointer.
520/// Unfortunately we cannot determine must-alias information for global
521/// variables or any other memory memory objects because we do not track whether
522/// a pointer points to the beginning of an object or a field of it.
523void Andersens::getMustAliases(Value *P, std::vector<Value*> &RetVals) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000524 Node *N = &GraphNodes[FindNode(getNode(P))];
525 if (N->PointsTo->count() == 1) {
526 Node *Pointee = &GraphNodes[N->PointsTo->find_first()];
527 // If a function is the only object in the points-to set, then it must be
528 // the destination. Note that we can't handle global variables here,
529 // because we don't know if the pointer is actually pointing to a field of
530 // the global or to the beginning of it.
531 if (Value *V = Pointee->getValue()) {
532 if (Function *F = dyn_cast<Function>(V))
533 RetVals.push_back(F);
534 } else {
535 // If the object in the points-to set is the null object, then the null
536 // pointer is a must alias.
537 if (Pointee == &GraphNodes[NullObject])
538 RetVals.push_back(Constant::getNullValue(P->getType()));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000539 }
540 }
Chris Lattnere995a2a2004-05-23 21:00:47 +0000541 AliasAnalysis::getMustAliases(P, RetVals);
542}
543
544/// pointsToConstantMemory - If we can determine that this pointer only points
545/// to constant memory, return true. In practice, this means that if the
546/// pointer can only point to constant globals, functions, or the null pointer,
547/// return true.
548///
549bool Andersens::pointsToConstantMemory(const Value *P) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000550 Node *N = &GraphNodes[FindNode(getNode((Value*)P))];
551 unsigned i;
552
553 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
554 bi != N->PointsTo->end();
555 ++bi) {
556 i = *bi;
557 Node *Pointee = &GraphNodes[i];
558 if (Value *V = Pointee->getValue()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000559 if (!isa<GlobalValue>(V) || (isa<GlobalVariable>(V) &&
560 !cast<GlobalVariable>(V)->isConstant()))
561 return AliasAnalysis::pointsToConstantMemory(P);
562 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +0000563 if (i != NullObject)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000564 return AliasAnalysis::pointsToConstantMemory(P);
565 }
566 }
567
568 return true;
569}
570
571//===----------------------------------------------------------------------===//
572// Object Identification Phase
573//===----------------------------------------------------------------------===//
574
575/// IdentifyObjects - This stage scans the program, adding an entry to the
576/// GraphNodes list for each memory object in the program (global stack or
577/// heap), and populates the ValueNodes and ObjectNodes maps for these objects.
578///
579void Andersens::IdentifyObjects(Module &M) {
580 unsigned NumObjects = 0;
581
582 // Object #0 is always the universal set: the object that we don't know
583 // anything about.
584 assert(NumObjects == UniversalSet && "Something changed!");
585 ++NumObjects;
586
587 // Object #1 always represents the null pointer.
588 assert(NumObjects == NullPtr && "Something changed!");
589 ++NumObjects;
590
591 // Object #2 always represents the null object (the object pointed to by null)
592 assert(NumObjects == NullObject && "Something changed!");
593 ++NumObjects;
594
595 // Add all the globals first.
Chris Lattner493f6362005-03-27 22:03:46 +0000596 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
597 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000598 ObjectNodes[I] = NumObjects++;
599 ValueNodes[I] = NumObjects++;
600 }
601
602 // Add nodes for all of the functions and the instructions inside of them.
603 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
604 // The function itself is a memory object.
Daniel Berlinaad15882007-09-16 21:45:02 +0000605 unsigned First = NumObjects;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000606 ValueNodes[F] = NumObjects++;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000607 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
608 ReturnNodes[F] = NumObjects++;
609 if (F->getFunctionType()->isVarArg())
610 VarargNodes[F] = NumObjects++;
611
Daniel Berlinaad15882007-09-16 21:45:02 +0000612
Chris Lattnere995a2a2004-05-23 21:00:47 +0000613 // Add nodes for all of the incoming pointer arguments.
Chris Lattner493f6362005-03-27 22:03:46 +0000614 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
615 I != E; ++I)
Daniel Berlind81ccc22007-09-24 19:45:49 +0000616 {
617 if (isa<PointerType>(I->getType()))
618 ValueNodes[I] = NumObjects++;
619 }
Daniel Berlinaad15882007-09-16 21:45:02 +0000620 MaxK[First] = NumObjects - First;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000621
622 // Scan the function body, creating a memory object for each heap/stack
623 // allocation in the body of the function and a node to represent all
624 // pointer values defined by instructions and used as operands.
625 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
626 // If this is an heap or stack allocation, create a node for the memory
627 // object.
628 if (isa<PointerType>(II->getType())) {
629 ValueNodes[&*II] = NumObjects++;
630 if (AllocationInst *AI = dyn_cast<AllocationInst>(&*II))
631 ObjectNodes[AI] = NumObjects++;
632 }
633 }
634 }
635
636 // Now that we know how many objects to create, make them all now!
637 GraphNodes.resize(NumObjects);
638 NumNodes += NumObjects;
639}
640
641//===----------------------------------------------------------------------===//
642// Constraint Identification Phase
643//===----------------------------------------------------------------------===//
644
645/// getNodeForConstantPointer - Return the node corresponding to the constant
646/// pointer itself.
Daniel Berlinaad15882007-09-16 21:45:02 +0000647unsigned Andersens::getNodeForConstantPointer(Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000648 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
649
Chris Lattner267a1b02005-03-27 18:58:23 +0000650 if (isa<ConstantPointerNull>(C) || isa<UndefValue>(C))
Daniel Berlinaad15882007-09-16 21:45:02 +0000651 return NullPtr;
Reid Spencere8404342004-07-18 00:18:30 +0000652 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
653 return getNode(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000654 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
655 switch (CE->getOpcode()) {
656 case Instruction::GetElementPtr:
657 return getNodeForConstantPointer(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000658 case Instruction::IntToPtr:
Daniel Berlinaad15882007-09-16 21:45:02 +0000659 return UniversalSet;
Reid Spencer3da59db2006-11-27 01:05:10 +0000660 case Instruction::BitCast:
661 return getNodeForConstantPointer(CE->getOperand(0));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000662 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000663 cerr << "Constant Expr not yet handled: " << *CE << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +0000664 assert(0);
665 }
666 } else {
667 assert(0 && "Unknown constant pointer!");
668 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000669 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000670}
671
672/// getNodeForConstantPointerTarget - Return the node POINTED TO by the
673/// specified constant pointer.
Daniel Berlinaad15882007-09-16 21:45:02 +0000674unsigned Andersens::getNodeForConstantPointerTarget(Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000675 assert(isa<PointerType>(C->getType()) && "Not a constant pointer!");
676
677 if (isa<ConstantPointerNull>(C))
Daniel Berlinaad15882007-09-16 21:45:02 +0000678 return NullObject;
Reid Spencere8404342004-07-18 00:18:30 +0000679 else if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
680 return getObject(GV);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000681 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
682 switch (CE->getOpcode()) {
683 case Instruction::GetElementPtr:
684 return getNodeForConstantPointerTarget(CE->getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +0000685 case Instruction::IntToPtr:
Daniel Berlinaad15882007-09-16 21:45:02 +0000686 return UniversalSet;
Reid Spencer3da59db2006-11-27 01:05:10 +0000687 case Instruction::BitCast:
688 return getNodeForConstantPointerTarget(CE->getOperand(0));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000689 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000690 cerr << "Constant Expr not yet handled: " << *CE << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +0000691 assert(0);
692 }
693 } else {
694 assert(0 && "Unknown constant pointer!");
695 }
Chris Lattner1fc37392004-05-27 20:57:01 +0000696 return 0;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000697}
698
699/// AddGlobalInitializerConstraints - Add inclusion constraints for the memory
700/// object N, which contains values indicated by C.
Daniel Berlinaad15882007-09-16 21:45:02 +0000701void Andersens::AddGlobalInitializerConstraints(unsigned NodeIndex,
702 Constant *C) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000703 if (C->getType()->isFirstClassType()) {
704 if (isa<PointerType>(C->getType()))
Daniel Berlinaad15882007-09-16 21:45:02 +0000705 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
706 getNodeForConstantPointer(C)));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000707 } else if (C->isNullValue()) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000708 Constraints.push_back(Constraint(Constraint::Copy, NodeIndex,
709 NullObject));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000710 return;
Chris Lattner8a446432005-03-29 06:09:07 +0000711 } else if (!isa<UndefValue>(C)) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000712 // If this is an array or struct, include constraints for each element.
713 assert(isa<ConstantArray>(C) || isa<ConstantStruct>(C));
714 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
Daniel Berlinaad15882007-09-16 21:45:02 +0000715 AddGlobalInitializerConstraints(NodeIndex,
716 cast<Constant>(C->getOperand(i)));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000717 }
718}
719
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000720/// AddConstraintsForNonInternalLinkage - If this function does not have
721/// internal linkage, realize that we can't trust anything passed into or
722/// returned by this function.
Chris Lattnere995a2a2004-05-23 21:00:47 +0000723void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
Chris Lattnere4d5c442005-03-15 04:54:21 +0000724 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000725 if (isa<PointerType>(I->getType()))
726 // If this is an argument of an externally accessible function, the
727 // incoming pointer might point to anything.
728 Constraints.push_back(Constraint(Constraint::Copy, getNode(I),
Daniel Berlinaad15882007-09-16 21:45:02 +0000729 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000730}
731
Chris Lattner8a446432005-03-29 06:09:07 +0000732/// AddConstraintsForCall - If this is a call to a "known" function, add the
733/// constraints and return true. If this is a call to an unknown function,
734/// return false.
735bool Andersens::AddConstraintsForExternalCall(CallSite CS, Function *F) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000736 assert(F->isDeclaration() && "Not an external function!");
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000737
738 // These functions don't induce any points-to constraints.
Chris Lattner175b9632005-03-29 20:36:05 +0000739 if (F->getName() == "atoi" || F->getName() == "atof" ||
740 F->getName() == "atol" || F->getName() == "atoll" ||
741 F->getName() == "remove" || F->getName() == "unlink" ||
742 F->getName() == "rename" || F->getName() == "memcmp" ||
Chris Lattner01ac91e2006-03-03 01:21:36 +0000743 F->getName() == "llvm.memset.i32" ||
744 F->getName() == "llvm.memset.i64" ||
Chris Lattner175b9632005-03-29 20:36:05 +0000745 F->getName() == "strcmp" || F->getName() == "strncmp" ||
746 F->getName() == "execl" || F->getName() == "execlp" ||
747 F->getName() == "execle" || F->getName() == "execv" ||
748 F->getName() == "execvp" || F->getName() == "chmod" ||
749 F->getName() == "puts" || F->getName() == "write" ||
750 F->getName() == "open" || F->getName() == "create" ||
751 F->getName() == "truncate" || F->getName() == "chdir" ||
752 F->getName() == "mkdir" || F->getName() == "rmdir" ||
753 F->getName() == "read" || F->getName() == "pipe" ||
754 F->getName() == "wait" || F->getName() == "time" ||
755 F->getName() == "stat" || F->getName() == "fstat" ||
756 F->getName() == "lstat" || F->getName() == "strtod" ||
757 F->getName() == "strtof" || F->getName() == "strtold" ||
758 F->getName() == "fopen" || F->getName() == "fdopen" ||
759 F->getName() == "freopen" ||
760 F->getName() == "fflush" || F->getName() == "feof" ||
761 F->getName() == "fileno" || F->getName() == "clearerr" ||
762 F->getName() == "rewind" || F->getName() == "ftell" ||
763 F->getName() == "ferror" || F->getName() == "fgetc" ||
764 F->getName() == "fgetc" || F->getName() == "_IO_getc" ||
765 F->getName() == "fwrite" || F->getName() == "fread" ||
766 F->getName() == "fgets" || F->getName() == "ungetc" ||
767 F->getName() == "fputc" ||
768 F->getName() == "fputs" || F->getName() == "putc" ||
769 F->getName() == "ftell" || F->getName() == "rewind" ||
770 F->getName() == "_IO_putc" || F->getName() == "fseek" ||
771 F->getName() == "fgetpos" || F->getName() == "fsetpos" ||
772 F->getName() == "printf" || F->getName() == "fprintf" ||
773 F->getName() == "sprintf" || F->getName() == "vprintf" ||
774 F->getName() == "vfprintf" || F->getName() == "vsprintf" ||
775 F->getName() == "scanf" || F->getName() == "fscanf" ||
776 F->getName() == "sscanf" || F->getName() == "__assert_fail" ||
777 F->getName() == "modf")
Chris Lattner8a446432005-03-29 06:09:07 +0000778 return true;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000779
Chris Lattner175b9632005-03-29 20:36:05 +0000780
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000781 // These functions do induce points-to edges.
Daniel Berlinaad15882007-09-16 21:45:02 +0000782 if (F->getName() == "llvm.memcpy.i32" || F->getName() == "llvm.memcpy.i64" ||
Chris Lattner01ac91e2006-03-03 01:21:36 +0000783 F->getName() == "llvm.memmove.i32" ||F->getName() == "llvm.memmove.i64" ||
Chris Lattner4de57fd2005-03-29 06:52:20 +0000784 F->getName() == "memmove") {
Daniel Berlinaad15882007-09-16 21:45:02 +0000785
786 // *Dest = *Src, which requires an artificial graph node to represent the
787 // constraint. It is broken up into *Dest = temp, temp = *Src
788 unsigned FirstArg = getNode(CS.getArgument(0));
789 unsigned SecondArg = getNode(CS.getArgument(1));
790 unsigned TempArg = GraphNodes.size();
791 GraphNodes.push_back(Node());
792 Constraints.push_back(Constraint(Constraint::Store,
793 FirstArg, TempArg));
794 Constraints.push_back(Constraint(Constraint::Load,
795 TempArg, SecondArg));
Chris Lattner8a446432005-03-29 06:09:07 +0000796 return true;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000797 }
798
Chris Lattner77b50562005-03-29 20:04:24 +0000799 // Result = Arg0
800 if (F->getName() == "realloc" || F->getName() == "strchr" ||
801 F->getName() == "strrchr" || F->getName() == "strstr" ||
802 F->getName() == "strtok") {
Chris Lattner8a446432005-03-29 06:09:07 +0000803 Constraints.push_back(Constraint(Constraint::Copy,
804 getNode(CS.getInstruction()),
805 getNode(CS.getArgument(0))));
806 return true;
807 }
808
809 return false;
Chris Lattnerc3c9fd02005-03-28 04:03:52 +0000810}
811
812
Chris Lattnere995a2a2004-05-23 21:00:47 +0000813
Daniel Berlinaad15882007-09-16 21:45:02 +0000814/// AnalyzeUsesOfFunction - Look at all of the users of the specified function.
815/// If this is used by anything complex (i.e., the address escapes), return
816/// true.
817bool Andersens::AnalyzeUsesOfFunction(Value *V) {
818
819 if (!isa<PointerType>(V->getType())) return true;
820
821 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
822 if (dyn_cast<LoadInst>(*UI)) {
823 return false;
824 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
825 if (V == SI->getOperand(1)) {
826 return false;
827 } else if (SI->getOperand(1)) {
828 return true; // Storing the pointer
829 }
830 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
831 if (AnalyzeUsesOfFunction(GEP)) return true;
832 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
833 // Make sure that this is just the function being called, not that it is
834 // passing into the function.
835 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
836 if (CI->getOperand(i) == V) return true;
837 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
838 // Make sure that this is just the function being called, not that it is
839 // passing into the function.
840 for (unsigned i = 3, e = II->getNumOperands(); i != e; ++i)
841 if (II->getOperand(i) == V) return true;
842 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
843 if (CE->getOpcode() == Instruction::GetElementPtr ||
844 CE->getOpcode() == Instruction::BitCast) {
845 if (AnalyzeUsesOfFunction(CE))
846 return true;
847 } else {
848 return true;
849 }
850 } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(*UI)) {
851 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
852 return true; // Allow comparison against null.
853 } else if (dyn_cast<FreeInst>(*UI)) {
854 return false;
855 } else {
856 return true;
857 }
858 return false;
859}
860
Chris Lattnere995a2a2004-05-23 21:00:47 +0000861/// CollectConstraints - This stage scans the program, adding a constraint to
862/// the Constraints list for each instruction in the program that induces a
863/// constraint, and setting up the initial points-to graph.
864///
865void Andersens::CollectConstraints(Module &M) {
866 // First, the universal set points to itself.
Daniel Berlinaad15882007-09-16 21:45:02 +0000867 Constraints.push_back(Constraint(Constraint::AddressOf, UniversalSet,
868 UniversalSet));
869 Constraints.push_back(Constraint(Constraint::Store, UniversalSet,
870 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000871
872 // Next, the null pointer points to the null object.
Daniel Berlinaad15882007-09-16 21:45:02 +0000873 Constraints.push_back(Constraint(Constraint::AddressOf, NullPtr, NullObject));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000874
875 // Next, add any constraints on global variables and their initializers.
Chris Lattner493f6362005-03-27 22:03:46 +0000876 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
877 I != E; ++I) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000878 // Associate the address of the global object as pointing to the memory for
879 // the global: &G = <G memory>
Daniel Berlinaad15882007-09-16 21:45:02 +0000880 unsigned ObjectIndex = getObject(I);
881 Node *Object = &GraphNodes[ObjectIndex];
Chris Lattnere995a2a2004-05-23 21:00:47 +0000882 Object->setValue(I);
Daniel Berlinaad15882007-09-16 21:45:02 +0000883 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(*I),
884 ObjectIndex));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000885
886 if (I->hasInitializer()) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000887 AddGlobalInitializerConstraints(ObjectIndex, I->getInitializer());
Chris Lattnere995a2a2004-05-23 21:00:47 +0000888 } else {
889 // If it doesn't have an initializer (i.e. it's defined in another
890 // translation unit), it points to the universal set.
Daniel Berlinaad15882007-09-16 21:45:02 +0000891 Constraints.push_back(Constraint(Constraint::Copy, ObjectIndex,
892 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000893 }
894 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000895
Chris Lattnere995a2a2004-05-23 21:00:47 +0000896 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000897 // Set up the return value node.
898 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
Daniel Berlinaad15882007-09-16 21:45:02 +0000899 GraphNodes[getReturnNode(F)].setValue(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000900 if (F->getFunctionType()->isVarArg())
Daniel Berlinaad15882007-09-16 21:45:02 +0000901 GraphNodes[getVarargNode(F)].setValue(F);
Chris Lattnere995a2a2004-05-23 21:00:47 +0000902
903 // Set up incoming argument nodes.
Chris Lattner493f6362005-03-27 22:03:46 +0000904 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
905 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000906 if (isa<PointerType>(I->getType()))
907 getNodeValue(*I);
908
Daniel Berlinaad15882007-09-16 21:45:02 +0000909 // At some point we should just add constraints for the escaping functions
910 // at solve time, but this slows down solving. For now, we simply mark
911 // address taken functions as escaping and treat them as external.
912 if (!F->hasInternalLinkage() || AnalyzeUsesOfFunction(F))
Chris Lattnere995a2a2004-05-23 21:00:47 +0000913 AddConstraintsForNonInternalLinkage(F);
914
Reid Spencer5cbf9852007-01-30 20:08:39 +0000915 if (!F->isDeclaration()) {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000916 // Scan the function body, creating a memory object for each heap/stack
917 // allocation in the body of the function and a node to represent all
918 // pointer values defined by instructions and used as operands.
919 visit(F);
Chris Lattner8a446432005-03-29 06:09:07 +0000920 } else {
Chris Lattnere995a2a2004-05-23 21:00:47 +0000921 // External functions that return pointers return the universal set.
922 if (isa<PointerType>(F->getFunctionType()->getReturnType()))
923 Constraints.push_back(Constraint(Constraint::Copy,
924 getReturnNode(F),
Daniel Berlinaad15882007-09-16 21:45:02 +0000925 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000926
927 // Any pointers that are passed into the function have the universal set
928 // stored into them.
Chris Lattner493f6362005-03-27 22:03:46 +0000929 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
930 I != E; ++I)
Chris Lattnere995a2a2004-05-23 21:00:47 +0000931 if (isa<PointerType>(I->getType())) {
932 // Pointers passed into external functions could have anything stored
933 // through them.
934 Constraints.push_back(Constraint(Constraint::Store, getNode(I),
Daniel Berlinaad15882007-09-16 21:45:02 +0000935 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000936 // Memory objects passed into external function calls can have the
937 // universal set point to them.
938 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +0000939 UniversalSet,
Chris Lattnere995a2a2004-05-23 21:00:47 +0000940 getNode(I)));
941 }
942
943 // If this is an external varargs function, it can also store pointers
944 // into any pointers passed through the varargs section.
945 if (F->getFunctionType()->isVarArg())
946 Constraints.push_back(Constraint(Constraint::Store, getVarargNode(F),
Daniel Berlinaad15882007-09-16 21:45:02 +0000947 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000948 }
949 }
950 NumConstraints += Constraints.size();
951}
952
953
954void Andersens::visitInstruction(Instruction &I) {
955#ifdef NDEBUG
956 return; // This function is just a big assert.
957#endif
958 if (isa<BinaryOperator>(I))
959 return;
960 // Most instructions don't have any effect on pointer values.
961 switch (I.getOpcode()) {
962 case Instruction::Br:
963 case Instruction::Switch:
964 case Instruction::Unwind:
Chris Lattnerc17edbd2004-10-16 18:16:19 +0000965 case Instruction::Unreachable:
Chris Lattnere995a2a2004-05-23 21:00:47 +0000966 case Instruction::Free:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000967 case Instruction::ICmp:
968 case Instruction::FCmp:
Chris Lattnere995a2a2004-05-23 21:00:47 +0000969 return;
970 default:
971 // Is this something we aren't handling yet?
Bill Wendlinge8156192006-12-07 01:30:32 +0000972 cerr << "Unknown instruction: " << I;
Chris Lattnere995a2a2004-05-23 21:00:47 +0000973 abort();
974 }
975}
976
977void Andersens::visitAllocationInst(AllocationInst &AI) {
Daniel Berlinaad15882007-09-16 21:45:02 +0000978 unsigned ObjectIndex = getObject(&AI);
979 GraphNodes[ObjectIndex].setValue(&AI);
980 Constraints.push_back(Constraint(Constraint::AddressOf, getNodeValue(AI),
981 ObjectIndex));
Chris Lattnere995a2a2004-05-23 21:00:47 +0000982}
983
984void Andersens::visitReturnInst(ReturnInst &RI) {
985 if (RI.getNumOperands() && isa<PointerType>(RI.getOperand(0)->getType()))
986 // return V --> <Copy/retval{F}/v>
987 Constraints.push_back(Constraint(Constraint::Copy,
988 getReturnNode(RI.getParent()->getParent()),
989 getNode(RI.getOperand(0))));
990}
991
992void Andersens::visitLoadInst(LoadInst &LI) {
993 if (isa<PointerType>(LI.getType()))
994 // P1 = load P2 --> <Load/P1/P2>
995 Constraints.push_back(Constraint(Constraint::Load, getNodeValue(LI),
996 getNode(LI.getOperand(0))));
997}
998
999void Andersens::visitStoreInst(StoreInst &SI) {
1000 if (isa<PointerType>(SI.getOperand(0)->getType()))
1001 // store P1, P2 --> <Store/P2/P1>
1002 Constraints.push_back(Constraint(Constraint::Store,
1003 getNode(SI.getOperand(1)),
1004 getNode(SI.getOperand(0))));
1005}
1006
1007void Andersens::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1008 // P1 = getelementptr P2, ... --> <Copy/P1/P2>
1009 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(GEP),
1010 getNode(GEP.getOperand(0))));
1011}
1012
1013void Andersens::visitPHINode(PHINode &PN) {
1014 if (isa<PointerType>(PN.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001015 unsigned PNN = getNodeValue(PN);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001016 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1017 // P1 = phi P2, P3 --> <Copy/P1/P2>, <Copy/P1/P3>, ...
1018 Constraints.push_back(Constraint(Constraint::Copy, PNN,
1019 getNode(PN.getIncomingValue(i))));
1020 }
1021}
1022
1023void Andersens::visitCastInst(CastInst &CI) {
1024 Value *Op = CI.getOperand(0);
1025 if (isa<PointerType>(CI.getType())) {
1026 if (isa<PointerType>(Op->getType())) {
1027 // P1 = cast P2 --> <Copy/P1/P2>
1028 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
1029 getNode(CI.getOperand(0))));
1030 } else {
1031 // P1 = cast int --> <Copy/P1/Univ>
Chris Lattner175b9632005-03-29 20:36:05 +00001032#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +00001033 Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
Daniel Berlinaad15882007-09-16 21:45:02 +00001034 UniversalSet));
Chris Lattnerbd135c72005-04-05 01:12:03 +00001035#else
1036 getNodeValue(CI);
Chris Lattner175b9632005-03-29 20:36:05 +00001037#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001038 }
1039 } else if (isa<PointerType>(Op->getType())) {
1040 // int = cast P1 --> <Copy/Univ/P1>
Chris Lattner175b9632005-03-29 20:36:05 +00001041#if 0
Chris Lattnere995a2a2004-05-23 21:00:47 +00001042 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001043 UniversalSet,
Chris Lattnere995a2a2004-05-23 21:00:47 +00001044 getNode(CI.getOperand(0))));
Chris Lattnerbd135c72005-04-05 01:12:03 +00001045#else
1046 getNode(CI.getOperand(0));
Chris Lattner175b9632005-03-29 20:36:05 +00001047#endif
Chris Lattnere995a2a2004-05-23 21:00:47 +00001048 }
1049}
1050
1051void Andersens::visitSelectInst(SelectInst &SI) {
1052 if (isa<PointerType>(SI.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001053 unsigned SIN = getNodeValue(SI);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001054 // P1 = select C, P2, P3 ---> <Copy/P1/P2>, <Copy/P1/P3>
1055 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1056 getNode(SI.getOperand(1))));
1057 Constraints.push_back(Constraint(Constraint::Copy, SIN,
1058 getNode(SI.getOperand(2))));
1059 }
1060}
1061
Chris Lattnere995a2a2004-05-23 21:00:47 +00001062void Andersens::visitVAArg(VAArgInst &I) {
1063 assert(0 && "vaarg not handled yet!");
1064}
1065
1066/// AddConstraintsForCall - Add constraints for a call with actual arguments
1067/// specified by CS to the function specified by F. Note that the types of
1068/// arguments might not match up in the case where this is an indirect call and
1069/// the function pointer has been casted. If this is the case, do something
1070/// reasonable.
1071void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001072 Value *CallValue = CS.getCalledValue();
1073 bool IsDeref = F == NULL;
1074
1075 // If this is a call to an external function, try to handle it directly to get
1076 // some taste of context sensitivity.
1077 if (F && F->isDeclaration() && AddConstraintsForExternalCall(CS, F))
Chris Lattner8a446432005-03-29 06:09:07 +00001078 return;
1079
Chris Lattnere995a2a2004-05-23 21:00:47 +00001080 if (isa<PointerType>(CS.getType())) {
Daniel Berlinaad15882007-09-16 21:45:02 +00001081 unsigned CSN = getNode(CS.getInstruction());
1082 if (!F || isa<PointerType>(F->getFunctionType()->getReturnType())) {
1083 if (IsDeref)
1084 Constraints.push_back(Constraint(Constraint::Load, CSN,
1085 getNode(CallValue), CallReturnPos));
1086 else
1087 Constraints.push_back(Constraint(Constraint::Copy, CSN,
1088 getNode(CallValue) + CallReturnPos));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001089 } else {
1090 // If the function returns a non-pointer value, handle this just like we
1091 // treat a nonpointer cast to pointer.
1092 Constraints.push_back(Constraint(Constraint::Copy, CSN,
Daniel Berlinaad15882007-09-16 21:45:02 +00001093 UniversalSet));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001094 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001095 } else if (F && isa<PointerType>(F->getFunctionType()->getReturnType())) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001096 Constraints.push_back(Constraint(Constraint::Copy,
Daniel Berlinaad15882007-09-16 21:45:02 +00001097 UniversalSet,
1098 getNode(CallValue) + CallReturnPos));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001099 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001100
Chris Lattnere995a2a2004-05-23 21:00:47 +00001101 CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
Daniel Berlinaad15882007-09-16 21:45:02 +00001102 if (F) {
1103 // Direct Call
1104 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1105 for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI)
1106 if (isa<PointerType>(AI->getType())) {
1107 if (isa<PointerType>((*ArgI)->getType())) {
1108 // Copy the actual argument into the formal argument.
1109 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1110 getNode(*ArgI)));
1111 } else {
1112 Constraints.push_back(Constraint(Constraint::Copy, getNode(AI),
1113 UniversalSet));
1114 }
1115 } else if (isa<PointerType>((*ArgI)->getType())) {
1116 Constraints.push_back(Constraint(Constraint::Copy,
1117 UniversalSet,
1118 getNode(*ArgI)));
1119 }
1120 } else {
1121 //Indirect Call
1122 unsigned ArgPos = CallFirstArgPos;
1123 for (; ArgI != ArgE; ++ArgI) {
Chris Lattnere995a2a2004-05-23 21:00:47 +00001124 if (isa<PointerType>((*ArgI)->getType())) {
1125 // Copy the actual argument into the formal argument.
Daniel Berlinaad15882007-09-16 21:45:02 +00001126 Constraints.push_back(Constraint(Constraint::Store,
1127 getNode(CallValue),
1128 getNode(*ArgI), ArgPos++));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001129 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +00001130 Constraints.push_back(Constraint(Constraint::Store,
1131 getNode (CallValue),
1132 UniversalSet, ArgPos++));
Chris Lattnere995a2a2004-05-23 21:00:47 +00001133 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00001134 }
Daniel Berlinaad15882007-09-16 21:45:02 +00001135 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00001136 // Copy all pointers passed through the varargs section to the varargs node.
Daniel Berlinaad15882007-09-16 21:45:02 +00001137 if (F && F->getFunctionType()->isVarArg())
Chris Lattnere995a2a2004-05-23 21:00:47 +00001138 for (; ArgI != ArgE; ++ArgI)
1139 if (isa<PointerType>((*ArgI)->getType()))
1140 Constraints.push_back(Constraint(Constraint::Copy, getVarargNode(F),
1141 getNode(*ArgI)));
1142 // If more arguments are passed in than we track, just drop them on the floor.
1143}
1144
1145void Andersens::visitCallSite(CallSite CS) {
1146 if (isa<PointerType>(CS.getType()))
1147 getNodeValue(*CS.getInstruction());
1148
1149 if (Function *F = CS.getCalledFunction()) {
1150 AddConstraintsForCall(CS, F);
1151 } else {
Daniel Berlinaad15882007-09-16 21:45:02 +00001152 AddConstraintsForCall(CS, NULL);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001153 }
1154}
1155
1156//===----------------------------------------------------------------------===//
1157// Constraint Solving Phase
1158//===----------------------------------------------------------------------===//
1159
1160/// intersects - Return true if the points-to set of this node intersects
1161/// with the points-to set of the specified node.
1162bool Andersens::Node::intersects(Node *N) const {
Daniel Berlinaad15882007-09-16 21:45:02 +00001163 return PointsTo->intersects(N->PointsTo);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001164}
1165
1166/// intersectsIgnoring - Return true if the points-to set of this node
1167/// intersects with the points-to set of the specified node on any nodes
1168/// except for the specified node to ignore.
Daniel Berlinaad15882007-09-16 21:45:02 +00001169bool Andersens::Node::intersectsIgnoring(Node *N, unsigned Ignoring) const {
1170 // TODO: If we are only going to call this with the same value for Ignoring,
1171 // we should move the special values out of the points-to bitmap.
1172 bool WeHadIt = PointsTo->test(Ignoring);
1173 bool NHadIt = N->PointsTo->test(Ignoring);
1174 bool Result = false;
1175 if (WeHadIt)
1176 PointsTo->reset(Ignoring);
1177 if (NHadIt)
1178 N->PointsTo->reset(Ignoring);
1179 Result = PointsTo->intersects(N->PointsTo);
1180 if (WeHadIt)
1181 PointsTo->set(Ignoring);
1182 if (NHadIt)
1183 N->PointsTo->set(Ignoring);
1184 return Result;
Chris Lattnere995a2a2004-05-23 21:00:47 +00001185}
1186
Daniel Berlind81ccc22007-09-24 19:45:49 +00001187void dumpToDOUT(SparseBitVector<> *bitmap) {
1188 dump(*bitmap, DOUT);
1189}
1190
1191
1192/// Clump together address taken variables so that the points-to sets use up
1193/// less space and can be operated on faster.
1194
1195void Andersens::ClumpAddressTaken() {
1196#undef DEBUG_TYPE
1197#define DEBUG_TYPE "anders-aa-renumber"
1198 std::vector<unsigned> Translate;
1199 std::vector<Node> NewGraphNodes;
1200
1201 Translate.resize(GraphNodes.size());
1202 unsigned NewPos = 0;
1203
1204 for (unsigned i = 0; i < Constraints.size(); ++i) {
1205 Constraint &C = Constraints[i];
1206 if (C.Type == Constraint::AddressOf) {
1207 GraphNodes[C.Src].AddressTaken = true;
1208 }
1209 }
1210 for (unsigned i = 0; i < NumberSpecialNodes; ++i) {
1211 unsigned Pos = NewPos++;
1212 Translate[i] = Pos;
1213 NewGraphNodes.push_back(GraphNodes[i]);
1214 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1215 }
1216
1217 // I believe this ends up being faster than making two vectors and splicing
1218 // them.
1219 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1220 if (GraphNodes[i].AddressTaken) {
1221 unsigned Pos = NewPos++;
1222 Translate[i] = Pos;
1223 NewGraphNodes.push_back(GraphNodes[i]);
1224 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1225 }
1226 }
1227
1228 for (unsigned i = NumberSpecialNodes; i < GraphNodes.size(); ++i) {
1229 if (!GraphNodes[i].AddressTaken) {
1230 unsigned Pos = NewPos++;
1231 Translate[i] = Pos;
1232 NewGraphNodes.push_back(GraphNodes[i]);
1233 DOUT << "Renumbering node " << i << " to node " << Pos << "\n";
1234 }
1235 }
1236
1237 for (DenseMap<Value*, unsigned>::iterator Iter = ValueNodes.begin();
1238 Iter != ValueNodes.end();
1239 ++Iter)
1240 Iter->second = Translate[Iter->second];
1241
1242 for (DenseMap<Value*, unsigned>::iterator Iter = ObjectNodes.begin();
1243 Iter != ObjectNodes.end();
1244 ++Iter)
1245 Iter->second = Translate[Iter->second];
1246
1247 for (DenseMap<Function*, unsigned>::iterator Iter = ReturnNodes.begin();
1248 Iter != ReturnNodes.end();
1249 ++Iter)
1250 Iter->second = Translate[Iter->second];
1251
1252 for (DenseMap<Function*, unsigned>::iterator Iter = VarargNodes.begin();
1253 Iter != VarargNodes.end();
1254 ++Iter)
1255 Iter->second = Translate[Iter->second];
1256
1257 for (unsigned i = 0; i < Constraints.size(); ++i) {
1258 Constraint &C = Constraints[i];
1259 C.Src = Translate[C.Src];
1260 C.Dest = Translate[C.Dest];
1261 }
1262
1263 GraphNodes.swap(NewGraphNodes);
1264#undef DEBUG_TYPE
1265#define DEBUG_TYPE "anders-aa"
1266}
1267
1268/// The technique used here is described in "Exploiting Pointer and Location
1269/// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1270/// Analysis Symposium (SAS), August 2007." It is known as the "HVN" algorithm,
1271/// and is equivalent to value numbering the collapsed constraint graph without
1272/// evaluating unions. This is used as a pre-pass to HU in order to resolve
1273/// first order pointer dereferences and speed up/reduce memory usage of HU.
1274/// Running both is equivalent to HRU without the iteration
1275/// HVN in more detail:
1276/// Imagine the set of constraints was simply straight line code with no loops
1277/// (we eliminate cycles, so there are no loops), such as:
1278/// E = &D
1279/// E = &C
1280/// E = F
1281/// F = G
1282/// G = F
1283/// Applying value numbering to this code tells us:
1284/// G == F == E
1285///
1286/// For HVN, this is as far as it goes. We assign new value numbers to every
1287/// "address node", and every "reference node".
1288/// To get the optimal result for this, we use a DFS + SCC (since all nodes in a
1289/// cycle must have the same value number since the = operation is really
1290/// inclusion, not overwrite), and value number nodes we receive points-to sets
1291/// before we value our own node.
1292/// The advantage of HU over HVN is that HU considers the inclusion property, so
1293/// that if you have
1294/// E = &D
1295/// E = &C
1296/// E = F
1297/// F = G
1298/// F = &D
1299/// G = F
1300/// HU will determine that G == F == E. HVN will not, because it cannot prove
1301/// that the points to information ends up being the same because they all
1302/// receive &D from E anyway.
1303
1304void Andersens::HVN() {
1305 DOUT << "Beginning HVN\n";
1306 // Build a predecessor graph. This is like our constraint graph with the
1307 // edges going in the opposite direction, and there are edges for all the
1308 // constraints, instead of just copy constraints. We also build implicit
1309 // edges for constraints are implied but not explicit. I.E for the constraint
1310 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1311 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1312 Constraint &C = Constraints[i];
1313 if (C.Type == Constraint::AddressOf) {
1314 GraphNodes[C.Src].AddressTaken = true;
1315 GraphNodes[C.Src].Direct = false;
1316
1317 // Dest = &src edge
1318 unsigned AdrNode = C.Src + FirstAdrNode;
1319 if (!GraphNodes[C.Dest].PredEdges)
1320 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1321 GraphNodes[C.Dest].PredEdges->set(AdrNode);
1322
1323 // *Dest = src edge
1324 unsigned RefNode = C.Dest + FirstRefNode;
1325 if (!GraphNodes[RefNode].ImplicitPredEdges)
1326 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1327 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1328 } else if (C.Type == Constraint::Load) {
1329 if (C.Offset == 0) {
1330 // dest = *src edge
1331 if (!GraphNodes[C.Dest].PredEdges)
1332 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1333 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1334 } else {
1335 GraphNodes[C.Dest].Direct = false;
1336 }
1337 } else if (C.Type == Constraint::Store) {
1338 if (C.Offset == 0) {
1339 // *dest = src edge
1340 unsigned RefNode = C.Dest + FirstRefNode;
1341 if (!GraphNodes[RefNode].PredEdges)
1342 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1343 GraphNodes[RefNode].PredEdges->set(C.Src);
1344 }
1345 } else {
1346 // Dest = Src edge and *Dest = *Src edge
1347 if (!GraphNodes[C.Dest].PredEdges)
1348 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1349 GraphNodes[C.Dest].PredEdges->set(C.Src);
1350 unsigned RefNode = C.Dest + FirstRefNode;
1351 if (!GraphNodes[RefNode].ImplicitPredEdges)
1352 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1353 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1354 }
1355 }
1356 PEClass = 1;
1357 // Do SCC finding first to condense our predecessor graph
1358 DFSNumber = 0;
1359 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1360 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1361 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1362
1363 for (unsigned i = 0; i < FirstRefNode; ++i) {
1364 unsigned Node = VSSCCRep[i];
1365 if (!Node2Visited[Node])
1366 HVNValNum(Node);
1367 }
1368 for (BitVectorMap::iterator Iter = Set2PEClass.begin();
1369 Iter != Set2PEClass.end();
1370 ++Iter)
1371 delete Iter->first;
1372 Set2PEClass.clear();
1373 Node2DFS.clear();
1374 Node2Deleted.clear();
1375 Node2Visited.clear();
1376 DOUT << "Finished HVN\n";
1377
1378}
1379
1380/// This is the workhorse of HVN value numbering. We combine SCC finding at the
1381/// same time because it's easy.
1382void Andersens::HVNValNum(unsigned NodeIndex) {
1383 unsigned MyDFS = DFSNumber++;
1384 Node *N = &GraphNodes[NodeIndex];
1385 Node2Visited[NodeIndex] = true;
1386 Node2DFS[NodeIndex] = MyDFS;
1387
1388 // First process all our explicit edges
1389 if (N->PredEdges)
1390 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1391 Iter != N->PredEdges->end();
1392 ++Iter) {
1393 unsigned j = VSSCCRep[*Iter];
1394 if (!Node2Deleted[j]) {
1395 if (!Node2Visited[j])
1396 HVNValNum(j);
1397 if (Node2DFS[NodeIndex] > Node2DFS[j])
1398 Node2DFS[NodeIndex] = Node2DFS[j];
1399 }
1400 }
1401
1402 // Now process all the implicit edges
1403 if (N->ImplicitPredEdges)
1404 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1405 Iter != N->ImplicitPredEdges->end();
1406 ++Iter) {
1407 unsigned j = VSSCCRep[*Iter];
1408 if (!Node2Deleted[j]) {
1409 if (!Node2Visited[j])
1410 HVNValNum(j);
1411 if (Node2DFS[NodeIndex] > Node2DFS[j])
1412 Node2DFS[NodeIndex] = Node2DFS[j];
1413 }
1414 }
1415
1416 // See if we found any cycles
1417 if (MyDFS == Node2DFS[NodeIndex]) {
1418 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1419 unsigned CycleNodeIndex = SCCStack.top();
1420 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1421 VSSCCRep[CycleNodeIndex] = NodeIndex;
1422 // Unify the nodes
1423 N->Direct &= CycleNode->Direct;
1424
1425 if (CycleNode->PredEdges) {
1426 if (!N->PredEdges)
1427 N->PredEdges = new SparseBitVector<>;
1428 *(N->PredEdges) |= CycleNode->PredEdges;
1429 delete CycleNode->PredEdges;
1430 CycleNode->PredEdges = NULL;
1431 }
1432 if (CycleNode->ImplicitPredEdges) {
1433 if (!N->ImplicitPredEdges)
1434 N->ImplicitPredEdges = new SparseBitVector<>;
1435 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1436 delete CycleNode->ImplicitPredEdges;
1437 CycleNode->ImplicitPredEdges = NULL;
1438 }
1439
1440 SCCStack.pop();
1441 }
1442
1443 Node2Deleted[NodeIndex] = true;
1444
1445 if (!N->Direct) {
1446 GraphNodes[NodeIndex].PointerEquivLabel = PEClass++;
1447 return;
1448 }
1449
1450 // Collect labels of successor nodes
1451 bool AllSame = true;
1452 unsigned First = ~0;
1453 SparseBitVector<> *Labels = new SparseBitVector<>;
1454 bool Used = false;
1455
1456 if (N->PredEdges)
1457 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1458 Iter != N->PredEdges->end();
1459 ++Iter) {
1460 unsigned j = VSSCCRep[*Iter];
1461 unsigned Label = GraphNodes[j].PointerEquivLabel;
1462 // Ignore labels that are equal to us or non-pointers
1463 if (j == NodeIndex || Label == 0)
1464 continue;
1465 if (First == (unsigned)~0)
1466 First = Label;
1467 else if (First != Label)
1468 AllSame = false;
1469 Labels->set(Label);
1470 }
1471
1472 // We either have a non-pointer, a copy of an existing node, or a new node.
1473 // Assign the appropriate pointer equivalence label.
1474 if (Labels->empty()) {
1475 GraphNodes[NodeIndex].PointerEquivLabel = 0;
1476 } else if (AllSame) {
1477 GraphNodes[NodeIndex].PointerEquivLabel = First;
1478 } else {
1479 GraphNodes[NodeIndex].PointerEquivLabel = Set2PEClass[Labels];
1480 if (GraphNodes[NodeIndex].PointerEquivLabel == 0) {
1481 unsigned EquivClass = PEClass++;
1482 Set2PEClass[Labels] = EquivClass;
1483 GraphNodes[NodeIndex].PointerEquivLabel = EquivClass;
1484 Used = true;
1485 }
1486 }
1487 if (!Used)
1488 delete Labels;
1489 } else {
1490 SCCStack.push(NodeIndex);
1491 }
1492}
1493
1494/// The technique used here is described in "Exploiting Pointer and Location
1495/// Equivalence to Optimize Pointer Analysis. In the 14th International Static
1496/// Analysis Symposium (SAS), August 2007." It is known as the "HU" algorithm,
1497/// and is equivalent to value numbering the collapsed constraint graph
1498/// including evaluating unions.
1499void Andersens::HU() {
1500 DOUT << "Beginning HU\n";
1501 // Build a predecessor graph. This is like our constraint graph with the
1502 // edges going in the opposite direction, and there are edges for all the
1503 // constraints, instead of just copy constraints. We also build implicit
1504 // edges for constraints are implied but not explicit. I.E for the constraint
1505 // a = &b, we add implicit edges *a = b. This helps us capture more cycles
1506 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1507 Constraint &C = Constraints[i];
1508 if (C.Type == Constraint::AddressOf) {
1509 GraphNodes[C.Src].AddressTaken = true;
1510 GraphNodes[C.Src].Direct = false;
1511
1512 GraphNodes[C.Dest].PointsTo->set(C.Src);
1513 // *Dest = src edge
1514 unsigned RefNode = C.Dest + FirstRefNode;
1515 if (!GraphNodes[RefNode].ImplicitPredEdges)
1516 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1517 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src);
1518 GraphNodes[C.Src].PointedToBy->set(C.Dest);
1519 } else if (C.Type == Constraint::Load) {
1520 if (C.Offset == 0) {
1521 // dest = *src edge
1522 if (!GraphNodes[C.Dest].PredEdges)
1523 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1524 GraphNodes[C.Dest].PredEdges->set(C.Src + FirstRefNode);
1525 } else {
1526 GraphNodes[C.Dest].Direct = false;
1527 }
1528 } else if (C.Type == Constraint::Store) {
1529 if (C.Offset == 0) {
1530 // *dest = src edge
1531 unsigned RefNode = C.Dest + FirstRefNode;
1532 if (!GraphNodes[RefNode].PredEdges)
1533 GraphNodes[RefNode].PredEdges = new SparseBitVector<>;
1534 GraphNodes[RefNode].PredEdges->set(C.Src);
1535 }
1536 } else {
1537 // Dest = Src edge and *Dest = *Src edg
1538 if (!GraphNodes[C.Dest].PredEdges)
1539 GraphNodes[C.Dest].PredEdges = new SparseBitVector<>;
1540 GraphNodes[C.Dest].PredEdges->set(C.Src);
1541 unsigned RefNode = C.Dest + FirstRefNode;
1542 if (!GraphNodes[RefNode].ImplicitPredEdges)
1543 GraphNodes[RefNode].ImplicitPredEdges = new SparseBitVector<>;
1544 GraphNodes[RefNode].ImplicitPredEdges->set(C.Src + FirstRefNode);
1545 }
1546 }
1547 PEClass = 1;
1548 // Do SCC finding first to condense our predecessor graph
1549 DFSNumber = 0;
1550 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
1551 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
1552 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1553
1554 for (unsigned i = 0; i < FirstRefNode; ++i) {
1555 if (FindNode(i) == i) {
1556 unsigned Node = VSSCCRep[i];
1557 if (!Node2Visited[Node])
1558 Condense(Node);
1559 }
1560 }
1561
1562 // Reset tables for actual labeling
1563 Node2DFS.clear();
1564 Node2Visited.clear();
1565 Node2Deleted.clear();
1566 // Pre-grow our densemap so that we don't get really bad behavior
1567 Set2PEClass.resize(GraphNodes.size());
1568
1569 // Visit the condensed graph and generate pointer equivalence labels.
1570 Node2Visited.insert(Node2Visited.begin(), GraphNodes.size(), false);
1571 for (unsigned i = 0; i < FirstRefNode; ++i) {
1572 if (FindNode(i) == i) {
1573 unsigned Node = VSSCCRep[i];
1574 if (!Node2Visited[Node])
1575 HUValNum(Node);
1576 }
1577 }
1578 // PEClass nodes will be deleted by the deleting of N->PointsTo in our caller.
1579 Set2PEClass.clear();
1580 DOUT << "Finished HU\n";
1581}
1582
1583
1584/// Implementation of standard Tarjan SCC algorithm as modified by Nuutilla.
1585void Andersens::Condense(unsigned NodeIndex) {
1586 unsigned MyDFS = DFSNumber++;
1587 Node *N = &GraphNodes[NodeIndex];
1588 Node2Visited[NodeIndex] = true;
1589 Node2DFS[NodeIndex] = MyDFS;
1590
1591 // First process all our explicit edges
1592 if (N->PredEdges)
1593 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1594 Iter != N->PredEdges->end();
1595 ++Iter) {
1596 unsigned j = VSSCCRep[*Iter];
1597 if (!Node2Deleted[j]) {
1598 if (!Node2Visited[j])
1599 Condense(j);
1600 if (Node2DFS[NodeIndex] > Node2DFS[j])
1601 Node2DFS[NodeIndex] = Node2DFS[j];
1602 }
1603 }
1604
1605 // Now process all the implicit edges
1606 if (N->ImplicitPredEdges)
1607 for (SparseBitVector<>::iterator Iter = N->ImplicitPredEdges->begin();
1608 Iter != N->ImplicitPredEdges->end();
1609 ++Iter) {
1610 unsigned j = VSSCCRep[*Iter];
1611 if (!Node2Deleted[j]) {
1612 if (!Node2Visited[j])
1613 Condense(j);
1614 if (Node2DFS[NodeIndex] > Node2DFS[j])
1615 Node2DFS[NodeIndex] = Node2DFS[j];
1616 }
1617 }
1618
1619 // See if we found any cycles
1620 if (MyDFS == Node2DFS[NodeIndex]) {
1621 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= MyDFS) {
1622 unsigned CycleNodeIndex = SCCStack.top();
1623 Node *CycleNode = &GraphNodes[CycleNodeIndex];
1624 VSSCCRep[CycleNodeIndex] = NodeIndex;
1625 // Unify the nodes
1626 N->Direct &= CycleNode->Direct;
1627
1628 *(N->PointsTo) |= CycleNode->PointsTo;
1629 delete CycleNode->PointsTo;
1630 CycleNode->PointsTo = NULL;
1631 if (CycleNode->PredEdges) {
1632 if (!N->PredEdges)
1633 N->PredEdges = new SparseBitVector<>;
1634 *(N->PredEdges) |= CycleNode->PredEdges;
1635 delete CycleNode->PredEdges;
1636 CycleNode->PredEdges = NULL;
1637 }
1638 if (CycleNode->ImplicitPredEdges) {
1639 if (!N->ImplicitPredEdges)
1640 N->ImplicitPredEdges = new SparseBitVector<>;
1641 *(N->ImplicitPredEdges) |= CycleNode->ImplicitPredEdges;
1642 delete CycleNode->ImplicitPredEdges;
1643 CycleNode->ImplicitPredEdges = NULL;
1644 }
1645 SCCStack.pop();
1646 }
1647
1648 Node2Deleted[NodeIndex] = true;
1649
1650 // Set up number of incoming edges for other nodes
1651 if (N->PredEdges)
1652 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1653 Iter != N->PredEdges->end();
1654 ++Iter)
1655 ++GraphNodes[VSSCCRep[*Iter]].NumInEdges;
1656 } else {
1657 SCCStack.push(NodeIndex);
1658 }
1659}
1660
1661void Andersens::HUValNum(unsigned NodeIndex) {
1662 Node *N = &GraphNodes[NodeIndex];
1663 Node2Visited[NodeIndex] = true;
1664
1665 // Eliminate dereferences of non-pointers for those non-pointers we have
1666 // already identified. These are ref nodes whose non-ref node:
1667 // 1. Has already been visited determined to point to nothing (and thus, a
1668 // dereference of it must point to nothing)
1669 // 2. Any direct node with no predecessor edges in our graph and with no
1670 // points-to set (since it can't point to anything either, being that it
1671 // receives no points-to sets and has none).
1672 if (NodeIndex >= FirstRefNode) {
1673 unsigned j = VSSCCRep[FindNode(NodeIndex - FirstRefNode)];
1674 if ((Node2Visited[j] && !GraphNodes[j].PointerEquivLabel)
1675 || (GraphNodes[j].Direct && !GraphNodes[j].PredEdges
1676 && GraphNodes[j].PointsTo->empty())){
1677 return;
1678 }
1679 }
1680 // Process all our explicit edges
1681 if (N->PredEdges)
1682 for (SparseBitVector<>::iterator Iter = N->PredEdges->begin();
1683 Iter != N->PredEdges->end();
1684 ++Iter) {
1685 unsigned j = VSSCCRep[*Iter];
1686 if (!Node2Visited[j])
1687 HUValNum(j);
1688
1689 // If this edge turned out to be the same as us, or got no pointer
1690 // equivalence label (and thus points to nothing) , just decrement our
1691 // incoming edges and continue.
1692 if (j == NodeIndex || GraphNodes[j].PointerEquivLabel == 0) {
1693 --GraphNodes[j].NumInEdges;
1694 continue;
1695 }
1696
1697 *(N->PointsTo) |= GraphNodes[j].PointsTo;
1698
1699 // If we didn't end up storing this in the hash, and we're done with all
1700 // the edges, we don't need the points-to set anymore.
1701 --GraphNodes[j].NumInEdges;
1702 if (!GraphNodes[j].NumInEdges && !GraphNodes[j].StoredInHash) {
1703 delete GraphNodes[j].PointsTo;
1704 GraphNodes[j].PointsTo = NULL;
1705 }
1706 }
1707 // If this isn't a direct node, generate a fresh variable.
1708 if (!N->Direct) {
1709 N->PointsTo->set(FirstRefNode + NodeIndex);
1710 }
1711
1712 // See If we have something equivalent to us, if not, generate a new
1713 // equivalence class.
1714 if (N->PointsTo->empty()) {
1715 delete N->PointsTo;
1716 N->PointsTo = NULL;
1717 } else {
1718 if (N->Direct) {
1719 N->PointerEquivLabel = Set2PEClass[N->PointsTo];
1720 if (N->PointerEquivLabel == 0) {
1721 unsigned EquivClass = PEClass++;
1722 N->StoredInHash = true;
1723 Set2PEClass[N->PointsTo] = EquivClass;
1724 N->PointerEquivLabel = EquivClass;
1725 }
1726 } else {
1727 N->PointerEquivLabel = PEClass++;
1728 }
1729 }
1730}
1731
1732/// Rewrite our list of constraints so that pointer equivalent nodes are
1733/// replaced by their the pointer equivalence class representative.
1734void Andersens::RewriteConstraints() {
1735 std::vector<Constraint> NewConstraints;
1736
1737 PEClass2Node.clear();
1738 PENLEClass2Node.clear();
1739
1740 // We may have from 1 to Graphnodes + 1 equivalence classes.
1741 PEClass2Node.insert(PEClass2Node.begin(), GraphNodes.size() + 1, -1);
1742 PENLEClass2Node.insert(PENLEClass2Node.begin(), GraphNodes.size() + 1, -1);
1743
1744 // Rewrite constraints, ignoring non-pointer constraints, uniting equivalent
1745 // nodes, and rewriting constraints to use the representative nodes.
1746 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1747 Constraint &C = Constraints[i];
1748 unsigned RHSNode = FindNode(C.Src);
1749 unsigned LHSNode = FindNode(C.Dest);
1750 unsigned RHSLabel = GraphNodes[VSSCCRep[RHSNode]].PointerEquivLabel;
1751 unsigned LHSLabel = GraphNodes[VSSCCRep[LHSNode]].PointerEquivLabel;
1752
1753 // First we try to eliminate constraints for things we can prove don't point
1754 // to anything.
1755 if (LHSLabel == 0) {
1756 DEBUG(PrintNode(&GraphNodes[LHSNode]));
1757 DOUT << " is a non-pointer, ignoring constraint.\n";
1758 continue;
1759 }
1760 if (RHSLabel == 0) {
1761 DEBUG(PrintNode(&GraphNodes[RHSNode]));
1762 DOUT << " is a non-pointer, ignoring constraint.\n";
1763 continue;
1764 }
1765 // This constraint may be useless, and it may become useless as we translate
1766 // it.
1767 if (C.Src == C.Dest && C.Type == Constraint::Copy)
1768 continue;
1769
1770 C.Src = FindEquivalentNode(RHSNode, RHSLabel);
1771 C.Dest = FindEquivalentNode(FindNode(LHSNode), LHSLabel);
1772 if (C.Src == C.Dest && C.Type == Constraint::Copy)
1773 continue;
1774
1775 NewConstraints.push_back(C);
1776 }
1777 Constraints.swap(NewConstraints);
1778 PEClass2Node.clear();
1779}
1780
1781/// See if we have a node that is pointer equivalent to the one being asked
1782/// about, and if so, unite them and return the equivalent node. Otherwise,
1783/// return the original node.
1784unsigned Andersens::FindEquivalentNode(unsigned NodeIndex,
1785 unsigned NodeLabel) {
1786 if (!GraphNodes[NodeIndex].AddressTaken) {
1787 if (PEClass2Node[NodeLabel] != -1) {
1788 // We found an existing node with the same pointer label, so unify them.
1789 return UniteNodes(PEClass2Node[NodeLabel], NodeIndex);
1790 } else {
1791 PEClass2Node[NodeLabel] = NodeIndex;
1792 PENLEClass2Node[NodeLabel] = NodeIndex;
1793 }
1794 } else if (PENLEClass2Node[NodeLabel] == -1) {
1795 PENLEClass2Node[NodeLabel] = NodeIndex;
1796 }
1797
1798 return NodeIndex;
1799}
1800
1801void Andersens::PrintLabels() {
1802 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1803 if (i < FirstRefNode) {
1804 PrintNode(&GraphNodes[i]);
1805 } else if (i < FirstAdrNode) {
1806 DOUT << "REF(";
1807 PrintNode(&GraphNodes[i-FirstRefNode]);
1808 DOUT <<")";
1809 } else {
1810 DOUT << "ADR(";
1811 PrintNode(&GraphNodes[i-FirstAdrNode]);
1812 DOUT <<")";
1813 }
1814
1815 DOUT << " has pointer label " << GraphNodes[i].PointerEquivLabel
1816 << " and SCC rep " << VSSCCRep[i]
1817 << " and is " << (GraphNodes[i].Direct ? "Direct" : "Not direct")
1818 << "\n";
1819 }
1820}
1821
1822/// Optimize the constraints by performing offline variable substitution and
1823/// other optimizations.
1824void Andersens::OptimizeConstraints() {
1825 DOUT << "Beginning constraint optimization\n";
1826
1827 // Function related nodes need to stay in the same relative position and can't
1828 // be location equivalent.
1829 for (std::map<unsigned, unsigned>::iterator Iter = MaxK.begin();
1830 Iter != MaxK.end();
1831 ++Iter) {
1832 for (unsigned i = Iter->first;
1833 i != Iter->first + Iter->second;
1834 ++i) {
1835 GraphNodes[i].AddressTaken = true;
1836 GraphNodes[i].Direct = false;
1837 }
1838 }
1839
1840 ClumpAddressTaken();
1841 FirstRefNode = GraphNodes.size();
1842 FirstAdrNode = FirstRefNode + GraphNodes.size();
1843 GraphNodes.insert(GraphNodes.end(), 2 * GraphNodes.size(),
1844 Node(false));
1845 VSSCCRep.resize(GraphNodes.size());
1846 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1847 VSSCCRep[i] = i;
1848 }
1849 HVN();
1850 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1851 Node *N = &GraphNodes[i];
1852 delete N->PredEdges;
1853 N->PredEdges = NULL;
1854 delete N->ImplicitPredEdges;
1855 N->ImplicitPredEdges = NULL;
1856 }
1857#undef DEBUG_TYPE
1858#define DEBUG_TYPE "anders-aa-labels"
1859 DEBUG(PrintLabels());
1860#undef DEBUG_TYPE
1861#define DEBUG_TYPE "anders-aa"
1862 RewriteConstraints();
1863 // Delete the adr nodes.
1864 GraphNodes.resize(FirstRefNode * 2);
1865
1866 // Now perform HU
1867 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1868 Node *N = &GraphNodes[i];
1869 if (FindNode(i) == i) {
1870 N->PointsTo = new SparseBitVector<>;
1871 N->PointedToBy = new SparseBitVector<>;
1872 // Reset our labels
1873 }
1874 VSSCCRep[i] = i;
1875 N->PointerEquivLabel = 0;
1876 }
1877 HU();
1878#undef DEBUG_TYPE
1879#define DEBUG_TYPE "anders-aa-labels"
1880 DEBUG(PrintLabels());
1881#undef DEBUG_TYPE
1882#define DEBUG_TYPE "anders-aa"
1883 RewriteConstraints();
1884 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1885 if (FindNode(i) == i) {
1886 Node *N = &GraphNodes[i];
1887 delete N->PointsTo;
1888 delete N->PredEdges;
1889 delete N->ImplicitPredEdges;
1890 delete N->PointedToBy;
1891 }
1892 }
1893 GraphNodes.erase(GraphNodes.begin() + FirstRefNode, GraphNodes.end());
1894 DOUT << "Finished constraint optimization\n";
1895 FirstRefNode = 0;
1896 FirstAdrNode = 0;
1897}
1898
1899/// Unite pointer but not location equivalent variables, now that the constraint
1900/// graph is built.
1901void Andersens::UnitePointerEquivalences() {
1902 DOUT << "Uniting remaining pointer equivalences\n";
1903 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
1904 if (GraphNodes[i].AddressTaken && GraphNodes[i].NodeRep == SelfRep) {
1905 unsigned Label = GraphNodes[i].PointerEquivLabel;
1906
1907 if (Label && PENLEClass2Node[Label] != -1)
1908 UniteNodes(i, PENLEClass2Node[Label]);
1909 }
1910 }
1911 DOUT << "Finished remaining pointer equivalences\n";
1912 PENLEClass2Node.clear();
1913}
1914
1915/// Create the constraint graph used for solving points-to analysis.
1916///
Daniel Berlinaad15882007-09-16 21:45:02 +00001917void Andersens::CreateConstraintGraph() {
1918 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1919 Constraint &C = Constraints[i];
1920 assert (C.Src < GraphNodes.size() && C.Dest < GraphNodes.size());
1921 if (C.Type == Constraint::AddressOf)
1922 GraphNodes[C.Dest].PointsTo->set(C.Src);
1923 else if (C.Type == Constraint::Load)
1924 GraphNodes[C.Src].Constraints.push_back(C);
1925 else if (C.Type == Constraint::Store)
1926 GraphNodes[C.Dest].Constraints.push_back(C);
1927 else if (C.Offset != 0)
1928 GraphNodes[C.Src].Constraints.push_back(C);
1929 else
1930 GraphNodes[C.Src].Edges->set(C.Dest);
1931 }
1932}
1933
1934// Perform cycle detection, DFS, and RPO finding.
1935void Andersens::QueryNode(unsigned Node) {
1936 assert(GraphNodes[Node].NodeRep == SelfRep && "Querying a non-rep node");
1937 unsigned OurDFS = ++DFSNumber;
1938 SparseBitVector<> ToErase;
1939 SparseBitVector<> NewEdges;
1940 Node2DFS[Node] = OurDFS;
1941
1942 for (SparseBitVector<>::iterator bi = GraphNodes[Node].Edges->begin();
1943 bi != GraphNodes[Node].Edges->end();
1944 ++bi) {
1945 unsigned RepNode = FindNode(*bi);
1946 // If we are going to add an edge to repnode, we have no need for the edge
1947 // to e anymore.
1948 if (RepNode != *bi && NewEdges.test(RepNode)){
1949 ToErase.set(*bi);
1950 continue;
1951 }
1952
1953 // Continue about our DFS.
1954 if (!Node2Deleted[RepNode]){
1955 if (Node2DFS[RepNode] == 0) {
1956 QueryNode(RepNode);
1957 // May have been changed by query
1958 RepNode = FindNode(RepNode);
1959 }
1960 if (Node2DFS[RepNode] < Node2DFS[Node])
1961 Node2DFS[Node] = Node2DFS[RepNode];
1962 }
1963 // We may have just discovered that e belongs to a cycle, in which case we
1964 // can also erase it.
1965 if (RepNode != *bi) {
1966 ToErase.set(*bi);
1967 NewEdges.set(RepNode);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001968 }
1969 }
1970
Daniel Berlinaad15882007-09-16 21:45:02 +00001971 GraphNodes[Node].Edges->intersectWithComplement(ToErase);
1972 GraphNodes[Node].Edges |= NewEdges;
1973
1974 // If this node is a root of a non-trivial SCC, place it on our worklist to be
1975 // processed
1976 if (OurDFS == Node2DFS[Node]) {
1977 bool Changed = false;
1978 while (!SCCStack.empty() && Node2DFS[SCCStack.top()] >= OurDFS) {
1979 Node = UniteNodes(Node, FindNode(SCCStack.top()));
1980
1981 SCCStack.pop();
1982 Changed = true;
1983 }
1984 Node2Deleted[Node] = true;
1985 RPONumber++;
1986
1987 Topo2Node.at(GraphNodes.size() - RPONumber) = Node;
1988 Node2Topo[Node] = GraphNodes.size() - RPONumber;
1989 if (Changed)
1990 GraphNodes[Node].Changed = true;
1991 } else {
1992 SCCStack.push(Node);
Chris Lattnere995a2a2004-05-23 21:00:47 +00001993 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00001994}
1995
1996
1997/// SolveConstraints - This stage iteratively processes the constraints list
1998/// propagating constraints (adding edges to the Nodes in the points-to graph)
1999/// until a fixed point is reached.
2000///
2001void Andersens::SolveConstraints() {
2002 bool Changed = true;
2003 unsigned Iteration = 0;
Daniel Berlinaad15882007-09-16 21:45:02 +00002004
Daniel Berlind81ccc22007-09-24 19:45:49 +00002005 OptimizeConstraints();
2006#undef DEBUG_TYPE
2007#define DEBUG_TYPE "anders-aa-constraints"
2008 DEBUG(PrintConstraints());
2009#undef DEBUG_TYPE
2010#define DEBUG_TYPE "anders-aa"
2011
Daniel Berlinaad15882007-09-16 21:45:02 +00002012 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2013 Node *N = &GraphNodes[i];
2014 N->PointsTo = new SparseBitVector<>;
2015 N->OldPointsTo = new SparseBitVector<>;
2016 N->Edges = new SparseBitVector<>;
2017 }
2018 CreateConstraintGraph();
Daniel Berlind81ccc22007-09-24 19:45:49 +00002019 UnitePointerEquivalences();
2020 assert(SCCStack.empty() && "SCC Stack should be empty by now!");
Daniel Berlinaad15882007-09-16 21:45:02 +00002021 Topo2Node.insert(Topo2Node.begin(), GraphNodes.size(), Unvisited);
2022 Node2Topo.insert(Node2Topo.begin(), GraphNodes.size(), Unvisited);
Daniel Berlind81ccc22007-09-24 19:45:49 +00002023 Node2DFS.clear();
2024 Node2Deleted.clear();
Daniel Berlinaad15882007-09-16 21:45:02 +00002025 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2026 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2027 DFSNumber = 0;
2028 RPONumber = 0;
2029 // Order graph and mark starting nodes as changed.
2030 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2031 unsigned N = FindNode(i);
2032 Node *INode = &GraphNodes[i];
2033 if (Node2DFS[N] == 0) {
2034 QueryNode(N);
2035 // Mark as changed if it's a representation and can contribute to the
2036 // calculation right now.
2037 if (INode->NodeRep == SelfRep && !INode->PointsTo->empty()
2038 && (!INode->Edges->empty() || !INode->Constraints.empty()))
2039 INode->Changed = true;
2040 }
2041 }
2042
2043 do {
Daniel Berlinc6d93982007-09-16 23:59:53 +00002044 Changed = false;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002045 ++NumIters;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002046 DOUT << "Starting iteration #" << Iteration++ << "\n";
Daniel Berlinaad15882007-09-16 21:45:02 +00002047 // TODO: In the microoptimization category, we could just make Topo2Node
2048 // a fast map and thus only contain the visited nodes.
2049 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2050 unsigned CurrNodeIndex = Topo2Node[i];
2051 Node *CurrNode;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002052
Daniel Berlinaad15882007-09-16 21:45:02 +00002053 // We may not revisit all nodes on every iteration
2054 if (CurrNodeIndex == Unvisited)
2055 continue;
2056 CurrNode = &GraphNodes[CurrNodeIndex];
2057 // See if this is a node we need to process on this iteration
2058 if (!CurrNode->Changed || CurrNode->NodeRep != SelfRep)
2059 continue;
2060 CurrNode->Changed = false;
2061
2062 // Figure out the changed points to bits
2063 SparseBitVector<> CurrPointsTo;
2064 CurrPointsTo.intersectWithComplement(CurrNode->PointsTo,
2065 CurrNode->OldPointsTo);
2066 if (CurrPointsTo.empty()){
2067 continue;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002068 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002069 *(CurrNode->OldPointsTo) |= CurrPointsTo;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002070
Daniel Berlinaad15882007-09-16 21:45:02 +00002071 /* Now process the constraints for this node. */
2072 for (std::list<Constraint>::iterator li = CurrNode->Constraints.begin();
2073 li != CurrNode->Constraints.end(); ) {
2074 li->Src = FindNode(li->Src);
2075 li->Dest = FindNode(li->Dest);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002076
Daniel Berlinaad15882007-09-16 21:45:02 +00002077 // TODO: We could delete redundant constraints here.
2078 // Src and Dest will be the vars we are going to process.
2079 // This may look a bit ugly, but what it does is allow us to process
Daniel Berlind81ccc22007-09-24 19:45:49 +00002080 // both store and load constraints with the same code.
Daniel Berlinaad15882007-09-16 21:45:02 +00002081 // Load constraints say that every member of our RHS solution has K
2082 // added to it, and that variable gets an edge to LHS. We also union
2083 // RHS+K's solution into the LHS solution.
2084 // Store constraints say that every member of our LHS solution has K
2085 // added to it, and that variable gets an edge from RHS. We also union
2086 // RHS's solution into the LHS+K solution.
2087 unsigned *Src;
2088 unsigned *Dest;
2089 unsigned K = li->Offset;
2090 unsigned CurrMember;
2091 if (li->Type == Constraint::Load) {
2092 Src = &CurrMember;
2093 Dest = &li->Dest;
2094 } else if (li->Type == Constraint::Store) {
2095 Src = &li->Src;
2096 Dest = &CurrMember;
2097 } else {
2098 // TODO Handle offseted copy constraint
2099 li++;
2100 continue;
2101 }
2102 // TODO: hybrid cycle detection would go here, we should check
2103 // if it was a statically detected offline equivalence that
2104 // involves pointers , and if so, remove the redundant constraints.
Chris Lattnere995a2a2004-05-23 21:00:47 +00002105
Daniel Berlinaad15882007-09-16 21:45:02 +00002106 const SparseBitVector<> &Solution = CurrPointsTo;
2107
2108 for (SparseBitVector<>::iterator bi = Solution.begin();
2109 bi != Solution.end();
2110 ++bi) {
2111 CurrMember = *bi;
2112
2113 // Need to increment the member by K since that is where we are
Daniel Berlind81ccc22007-09-24 19:45:49 +00002114 // supposed to copy to/from. Note that in positive weight cycles,
2115 // which occur in address taking of fields, K can go past
2116 // MaxK[CurrMember] elements, even though that is all it could point
2117 // to.
Daniel Berlinaad15882007-09-16 21:45:02 +00002118 if (K > 0 && K > MaxK[CurrMember])
2119 continue;
2120 else
2121 CurrMember = FindNode(CurrMember + K);
2122
2123 // Add an edge to the graph, so we can just do regular bitmap ior next
2124 // time. It may also let us notice a cycle.
Daniel Berlinc6d93982007-09-16 23:59:53 +00002125 if (GraphNodes[*Src].Edges->test_and_set(*Dest)) {
Daniel Berlinaad15882007-09-16 21:45:02 +00002126 if (GraphNodes[*Dest].PointsTo |= *(GraphNodes[*Src].PointsTo)) {
2127 GraphNodes[*Dest].Changed = true;
2128 // If we changed a node we've already processed, we need another
2129 // iteration.
2130 if (Node2Topo[*Dest] <= i)
2131 Changed = true;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002132 }
2133 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002134 }
2135 li++;
2136 }
2137 SparseBitVector<> NewEdges;
2138 SparseBitVector<> ToErase;
2139
2140 // Now all we have left to do is propagate points-to info along the
2141 // edges, erasing the redundant edges.
2142
2143
2144 for (SparseBitVector<>::iterator bi = CurrNode->Edges->begin();
2145 bi != CurrNode->Edges->end();
2146 ++bi) {
2147
2148 unsigned DestVar = *bi;
2149 unsigned Rep = FindNode(DestVar);
2150
2151 // If we ended up with this node as our destination, or we've already
2152 // got an edge for the representative, delete the current edge.
2153 if (Rep == CurrNodeIndex ||
2154 (Rep != DestVar && NewEdges.test(Rep))) {
2155 ToErase.set(DestVar);
2156 continue;
2157 }
2158 // Union the points-to sets into the dest
2159 if (GraphNodes[Rep].PointsTo |= CurrPointsTo) {
2160 GraphNodes[Rep].Changed = true;
2161 if (Node2Topo[Rep] <= i)
2162 Changed = true;
2163 }
2164 // If this edge's destination was collapsed, rewrite the edge.
2165 if (Rep != DestVar) {
2166 ToErase.set(DestVar);
2167 NewEdges.set(Rep);
2168 }
2169 }
2170 CurrNode->Edges->intersectWithComplement(ToErase);
2171 CurrNode->Edges |= NewEdges;
2172 }
2173 if (Changed) {
2174 DFSNumber = RPONumber = 0;
2175 Node2Deleted.clear();
2176 Topo2Node.clear();
2177 Node2Topo.clear();
2178 Node2DFS.clear();
2179 Topo2Node.insert(Topo2Node.begin(), GraphNodes.size(), Unvisited);
2180 Node2Topo.insert(Node2Topo.begin(), GraphNodes.size(), Unvisited);
2181 Node2DFS.insert(Node2DFS.begin(), GraphNodes.size(), 0);
2182 Node2Deleted.insert(Node2Deleted.begin(), GraphNodes.size(), false);
2183 // Rediscover the DFS/Topo ordering, and cycle detect.
2184 for (unsigned j = 0; j < GraphNodes.size(); j++) {
2185 unsigned JRep = FindNode(j);
2186 if (Node2DFS[JRep] == 0)
2187 QueryNode(JRep);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002188 }
2189 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002190
2191 } while (Changed);
2192
2193 Node2Topo.clear();
2194 Topo2Node.clear();
2195 Node2DFS.clear();
2196 Node2Deleted.clear();
2197 for (unsigned i = 0; i < GraphNodes.size(); ++i) {
2198 Node *N = &GraphNodes[i];
2199 delete N->OldPointsTo;
2200 delete N->Edges;
Chris Lattnere995a2a2004-05-23 21:00:47 +00002201 }
2202}
2203
Daniel Berlinaad15882007-09-16 21:45:02 +00002204//===----------------------------------------------------------------------===//
2205// Union-Find
2206//===----------------------------------------------------------------------===//
Chris Lattnere995a2a2004-05-23 21:00:47 +00002207
Daniel Berlinaad15882007-09-16 21:45:02 +00002208// Unite nodes First and Second, returning the one which is now the
2209// representative node. First and Second are indexes into GraphNodes
2210unsigned Andersens::UniteNodes(unsigned First, unsigned Second) {
2211 assert (First < GraphNodes.size() && Second < GraphNodes.size() &&
2212 "Attempting to merge nodes that don't exist");
2213 // TODO: implement union by rank
2214 Node *FirstNode = &GraphNodes[First];
2215 Node *SecondNode = &GraphNodes[Second];
2216
2217 assert (SecondNode->NodeRep == SelfRep && FirstNode->NodeRep == SelfRep &&
2218 "Trying to unite two non-representative nodes!");
2219 if (First == Second)
2220 return First;
2221
2222 SecondNode->NodeRep = First;
2223 FirstNode->Changed |= SecondNode->Changed;
Daniel Berlind81ccc22007-09-24 19:45:49 +00002224 if (FirstNode->PointsTo && SecondNode->PointsTo)
2225 FirstNode->PointsTo |= *(SecondNode->PointsTo);
2226 if (FirstNode->Edges && SecondNode->Edges)
2227 FirstNode->Edges |= *(SecondNode->Edges);
2228 if (!FirstNode->Constraints.empty() && !SecondNode->Constraints.empty())
2229 FirstNode->Constraints.splice(FirstNode->Constraints.begin(),
2230 SecondNode->Constraints);
2231 if (FirstNode->OldPointsTo) {
2232 delete FirstNode->OldPointsTo;
2233 FirstNode->OldPointsTo = new SparseBitVector<>;
2234 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002235
2236 // Destroy interesting parts of the merged-from node.
2237 delete SecondNode->OldPointsTo;
2238 delete SecondNode->Edges;
2239 delete SecondNode->PointsTo;
2240 SecondNode->Edges = NULL;
2241 SecondNode->PointsTo = NULL;
2242 SecondNode->OldPointsTo = NULL;
2243
2244 NumUnified++;
2245 DOUT << "Unified Node ";
2246 DEBUG(PrintNode(FirstNode));
2247 DOUT << " and Node ";
2248 DEBUG(PrintNode(SecondNode));
2249 DOUT << "\n";
2250
2251 // TODO: Handle SDT
2252 return First;
2253}
2254
2255// Find the index into GraphNodes of the node representing Node, performing
2256// path compression along the way
2257unsigned Andersens::FindNode(unsigned NodeIndex) {
2258 assert (NodeIndex < GraphNodes.size()
2259 && "Attempting to find a node that can't exist");
2260 Node *N = &GraphNodes[NodeIndex];
2261 if (N->NodeRep == SelfRep)
2262 return NodeIndex;
2263 else
2264 return (N->NodeRep = FindNode(N->NodeRep));
2265}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002266
2267//===----------------------------------------------------------------------===//
2268// Debugging Output
2269//===----------------------------------------------------------------------===//
2270
2271void Andersens::PrintNode(Node *N) {
2272 if (N == &GraphNodes[UniversalSet]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002273 cerr << "<universal>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002274 return;
2275 } else if (N == &GraphNodes[NullPtr]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002276 cerr << "<nullptr>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002277 return;
2278 } else if (N == &GraphNodes[NullObject]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002279 cerr << "<null>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002280 return;
2281 }
Daniel Berlinaad15882007-09-16 21:45:02 +00002282 if (!N->getValue()) {
2283 cerr << "artificial" << (intptr_t) N;
2284 return;
2285 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002286
2287 assert(N->getValue() != 0 && "Never set node label!");
2288 Value *V = N->getValue();
2289 if (Function *F = dyn_cast<Function>(V)) {
2290 if (isa<PointerType>(F->getFunctionType()->getReturnType()) &&
Daniel Berlinaad15882007-09-16 21:45:02 +00002291 N == &GraphNodes[getReturnNode(F)]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002292 cerr << F->getName() << ":retval";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002293 return;
Daniel Berlinaad15882007-09-16 21:45:02 +00002294 } else if (F->getFunctionType()->isVarArg() &&
2295 N == &GraphNodes[getVarargNode(F)]) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002296 cerr << F->getName() << ":vararg";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002297 return;
2298 }
2299 }
2300
2301 if (Instruction *I = dyn_cast<Instruction>(V))
Bill Wendlinge8156192006-12-07 01:30:32 +00002302 cerr << I->getParent()->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002303 else if (Argument *Arg = dyn_cast<Argument>(V))
Bill Wendlinge8156192006-12-07 01:30:32 +00002304 cerr << Arg->getParent()->getName() << ":";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002305
2306 if (V->hasName())
Bill Wendlinge8156192006-12-07 01:30:32 +00002307 cerr << V->getName();
Chris Lattnere995a2a2004-05-23 21:00:47 +00002308 else
Bill Wendlinge8156192006-12-07 01:30:32 +00002309 cerr << "(unnamed)";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002310
2311 if (isa<GlobalValue>(V) || isa<AllocationInst>(V))
Daniel Berlinaad15882007-09-16 21:45:02 +00002312 if (N == &GraphNodes[getObject(V)])
Bill Wendlinge8156192006-12-07 01:30:32 +00002313 cerr << "<mem>";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002314}
Daniel Berlind81ccc22007-09-24 19:45:49 +00002315void Andersens::PrintConstraint(const Constraint &C) {
2316 if (C.Type == Constraint::Store) {
2317 cerr << "*";
2318 if (C.Offset != 0)
2319 cerr << "(";
2320 }
2321 PrintNode(&GraphNodes[C.Dest]);
2322 if (C.Type == Constraint::Store && C.Offset != 0)
2323 cerr << " + " << C.Offset << ")";
2324 cerr << " = ";
2325 if (C.Type == Constraint::Load) {
2326 cerr << "*";
2327 if (C.Offset != 0)
2328 cerr << "(";
2329 }
2330 else if (C.Type == Constraint::AddressOf)
2331 cerr << "&";
2332 PrintNode(&GraphNodes[C.Src]);
2333 if (C.Offset != 0 && C.Type != Constraint::Store)
2334 cerr << " + " << C.Offset;
2335 if (C.Type == Constraint::Load && C.Offset != 0)
2336 cerr << ")";
2337 cerr << "\n";
2338}
Chris Lattnere995a2a2004-05-23 21:00:47 +00002339
2340void Andersens::PrintConstraints() {
Bill Wendlinge8156192006-12-07 01:30:32 +00002341 cerr << "Constraints:\n";
Daniel Berlinaad15882007-09-16 21:45:02 +00002342
Daniel Berlind81ccc22007-09-24 19:45:49 +00002343 for (unsigned i = 0, e = Constraints.size(); i != e; ++i)
2344 PrintConstraint(Constraints[i]);
Chris Lattnere995a2a2004-05-23 21:00:47 +00002345}
2346
2347void Andersens::PrintPointsToGraph() {
Bill Wendlinge8156192006-12-07 01:30:32 +00002348 cerr << "Points-to graph:\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002349 for (unsigned i = 0, e = GraphNodes.size(); i != e; ++i) {
2350 Node *N = &GraphNodes[i];
Daniel Berlinaad15882007-09-16 21:45:02 +00002351 if (FindNode (i) != i) {
2352 PrintNode(N);
2353 cerr << "\t--> same as ";
2354 PrintNode(&GraphNodes[FindNode(i)]);
2355 cerr << "\n";
2356 } else {
2357 cerr << "[" << (N->PointsTo->count()) << "] ";
2358 PrintNode(N);
2359 cerr << "\t--> ";
2360
2361 bool first = true;
2362 for (SparseBitVector<>::iterator bi = N->PointsTo->begin();
2363 bi != N->PointsTo->end();
2364 ++bi) {
2365 if (!first)
2366 cerr << ", ";
2367 PrintNode(&GraphNodes[*bi]);
2368 first = false;
2369 }
2370 cerr << "\n";
Chris Lattnere995a2a2004-05-23 21:00:47 +00002371 }
Chris Lattnere995a2a2004-05-23 21:00:47 +00002372 }
2373}