blob: 958ba95b3e6333562f67d11acff8653eccdb79b5 [file] [log] [blame]
Hal Finkel7529c552014-09-02 21:43:13 +00001//===- CFLAliasAnalysis.cpp - CFL-Based Alias Analysis Implementation ------==//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a CFL-based context-insensitive alias analysis
11// algorithm. It does not depend on types. The algorithm is a mixture of the one
12// described in "Demand-driven alias analysis for C" by Xin Zheng and Radu
13// Rugina, and "Fast algorithms for Dyck-CFL-reachability with applications to
14// Alias Analysis" by Zhang Q, Lyu M R, Yuan H, and Su Z. -- to summarize the
15// papers, we build a graph of the uses of a variable, where each node is a
16// memory location, and each edge is an action that happened on that memory
Chad Rosier38c6ad22015-06-19 17:32:57 +000017// location. The "actions" can be one of Dereference, Reference, or Assign.
Hal Finkel7529c552014-09-02 21:43:13 +000018//
19// Two variables are considered as aliasing iff you can reach one value's node
20// from the other value's node and the language formed by concatenating all of
21// the edge labels (actions) conforms to a context-free grammar.
22//
23// Because this algorithm requires a graph search on each query, we execute the
24// algorithm outlined in "Fast algorithms..." (mentioned above)
25// in order to transform the graph into sets of variables that may alias in
26// ~nlogn time (n = number of variables.), which makes queries take constant
27// time.
28//===----------------------------------------------------------------------===//
29
Chandler Carruth8b046a42015-08-14 02:42:20 +000030#include "llvm/Analysis/CFLAliasAnalysis.h"
Hal Finkel7529c552014-09-02 21:43:13 +000031#include "StratifiedSets.h"
Hal Finkel7529c552014-09-02 21:43:13 +000032#include "llvm/ADT/BitVector.h"
33#include "llvm/ADT/DenseMap.h"
Hal Finkel7529c552014-09-02 21:43:13 +000034#include "llvm/ADT/None.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000035#include "llvm/ADT/Optional.h"
Hal Finkel7529c552014-09-02 21:43:13 +000036#include "llvm/Analysis/AliasAnalysis.h"
37#include "llvm/IR/Constants.h"
38#include "llvm/IR/Function.h"
Hal Finkel7529c552014-09-02 21:43:13 +000039#include "llvm/IR/InstVisitor.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000040#include "llvm/IR/Instructions.h"
Hal Finkel7529c552014-09-02 21:43:13 +000041#include "llvm/IR/ValueHandle.h"
42#include "llvm/Pass.h"
43#include "llvm/Support/Allocator.h"
Hal Finkel7d7087c2014-09-02 22:13:00 +000044#include "llvm/Support/Compiler.h"
George Burgess IV33305e72015-02-12 03:07:07 +000045#include "llvm/Support/Debug.h"
Hal Finkel7529c552014-09-02 21:43:13 +000046#include "llvm/Support/ErrorHandling.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000047#include "llvm/Support/raw_ostream.h"
Hal Finkel7529c552014-09-02 21:43:13 +000048#include <algorithm>
49#include <cassert>
Benjamin Kramer799003b2015-03-23 19:32:43 +000050#include <memory>
Hal Finkel7529c552014-09-02 21:43:13 +000051#include <tuple>
52
53using namespace llvm;
54
George Burgess IV33305e72015-02-12 03:07:07 +000055#define DEBUG_TYPE "cfl-aa"
56
Chandler Carruth8b046a42015-08-14 02:42:20 +000057// -- Setting up/registering CFLAA pass -- //
58char CFLAliasAnalysis::ID = 0;
59
60INITIALIZE_AG_PASS(CFLAliasAnalysis, AliasAnalysis, "cfl-aa",
61 "CFL-Based AA implementation", false, true, false)
62
63ImmutablePass *llvm::createCFLAliasAnalysisPass() {
64 return new CFLAliasAnalysis();
65}
66
67// \brief Information we have about a function and would like to keep around
68struct CFLAliasAnalysis::FunctionInfo {
69 StratifiedSets<Value *> Sets;
70 // Lots of functions have < 4 returns. Adjust as necessary.
71 SmallVector<Value *, 4> ReturnedValues;
72
73 FunctionInfo(StratifiedSets<Value *> &&S, SmallVector<Value *, 4> &&RV)
74 : Sets(std::move(S)), ReturnedValues(std::move(RV)) {}
75};
76
77struct CFLAliasAnalysis::FunctionHandle final : public CallbackVH {
78 FunctionHandle(Function *Fn, CFLAliasAnalysis *CFLAA)
79 : CallbackVH(Fn), CFLAA(CFLAA) {
80 assert(Fn != nullptr);
81 assert(CFLAA != nullptr);
82 }
83
84 void deleted() override { removeSelfFromCache(); }
85 void allUsesReplacedWith(Value *) override { removeSelfFromCache(); }
86
87private:
88 CFLAliasAnalysis *CFLAA;
89
90 void removeSelfFromCache() {
91 assert(CFLAA != nullptr);
92 auto *Val = getValPtr();
93 CFLAA->evict(cast<Function>(Val));
94 setValPtr(nullptr);
95 }
96};
97
98CFLAliasAnalysis::CFLAliasAnalysis() : ImmutablePass(ID) {
99 initializeCFLAliasAnalysisPass(*PassRegistry::getPassRegistry());
100}
101
102CFLAliasAnalysis::~CFLAliasAnalysis() {}
103
104void CFLAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
105 AliasAnalysis::getAnalysisUsage(AU);
106}
107
108void *CFLAliasAnalysis::getAdjustedAnalysisPointer(const void *ID) {
109 if (ID == &AliasAnalysis::ID)
110 return (AliasAnalysis *)this;
111 return this;
112}
113
Hal Finkel7529c552014-09-02 21:43:13 +0000114// Try to go from a Value* to a Function*. Never returns nullptr.
115static Optional<Function *> parentFunctionOfValue(Value *);
116
117// Returns possible functions called by the Inst* into the given
118// SmallVectorImpl. Returns true if targets found, false otherwise.
119// This is templated because InvokeInst/CallInst give us the same
120// set of functions that we care about, and I don't like repeating
121// myself.
122template <typename Inst>
123static bool getPossibleTargets(Inst *, SmallVectorImpl<Function *> &);
124
125// Some instructions need to have their users tracked. Instructions like
126// `add` require you to get the users of the Instruction* itself, other
127// instructions like `store` require you to get the users of the first
128// operand. This function gets the "proper" value to track for each
129// type of instruction we support.
130static Optional<Value *> getTargetValue(Instruction *);
131
132// There are certain instructions (i.e. FenceInst, etc.) that we ignore.
133// This notes that we should ignore those.
134static bool hasUsefulEdges(Instruction *);
135
Hal Finkel1ae325f2014-09-02 23:50:01 +0000136const StratifiedIndex StratifiedLink::SetSentinel =
George Burgess IV11d509d2015-03-15 00:52:21 +0000137 std::numeric_limits<StratifiedIndex>::max();
Hal Finkel1ae325f2014-09-02 23:50:01 +0000138
Hal Finkel7529c552014-09-02 21:43:13 +0000139namespace {
140// StratifiedInfo Attribute things.
141typedef unsigned StratifiedAttr;
Hal Finkel7d7087c2014-09-02 22:13:00 +0000142LLVM_CONSTEXPR unsigned MaxStratifiedAttrIndex = NumStratifiedAttrs;
143LLVM_CONSTEXPR unsigned AttrAllIndex = 0;
144LLVM_CONSTEXPR unsigned AttrGlobalIndex = 1;
George Burgess IVb54a8d622015-03-10 02:40:06 +0000145LLVM_CONSTEXPR unsigned AttrUnknownIndex = 2;
146LLVM_CONSTEXPR unsigned AttrFirstArgIndex = 3;
Hal Finkel7d7087c2014-09-02 22:13:00 +0000147LLVM_CONSTEXPR unsigned AttrLastArgIndex = MaxStratifiedAttrIndex;
148LLVM_CONSTEXPR unsigned AttrMaxNumArgs = AttrLastArgIndex - AttrFirstArgIndex;
Hal Finkel7529c552014-09-02 21:43:13 +0000149
Hal Finkel7d7087c2014-09-02 22:13:00 +0000150LLVM_CONSTEXPR StratifiedAttr AttrNone = 0;
George Burgess IVb54a8d622015-03-10 02:40:06 +0000151LLVM_CONSTEXPR StratifiedAttr AttrUnknown = 1 << AttrUnknownIndex;
Hal Finkel7d7087c2014-09-02 22:13:00 +0000152LLVM_CONSTEXPR StratifiedAttr AttrAll = ~AttrNone;
Hal Finkel7529c552014-09-02 21:43:13 +0000153
154// \brief StratifiedSets call for knowledge of "direction", so this is how we
155// represent that locally.
156enum class Level { Same, Above, Below };
157
158// \brief Edges can be one of four "weights" -- each weight must have an inverse
159// weight (Assign has Assign; Reference has Dereference).
160enum class EdgeType {
161 // The weight assigned when assigning from or to a value. For example, in:
162 // %b = getelementptr %a, 0
163 // ...The relationships are %b assign %a, and %a assign %b. This used to be
164 // two edges, but having a distinction bought us nothing.
165 Assign,
166
167 // The edge used when we have an edge going from some handle to a Value.
168 // Examples of this include:
169 // %b = load %a (%b Dereference %a)
170 // %b = extractelement %a, 0 (%a Dereference %b)
171 Dereference,
172
173 // The edge used when our edge goes from a value to a handle that may have
174 // contained it at some point. Examples:
175 // %b = load %a (%a Reference %b)
176 // %b = extractelement %a, 0 (%b Reference %a)
177 Reference
178};
179
180// \brief Encodes the notion of a "use"
181struct Edge {
182 // \brief Which value the edge is coming from
183 Value *From;
184
185 // \brief Which value the edge is pointing to
186 Value *To;
187
188 // \brief Edge weight
189 EdgeType Weight;
190
191 // \brief Whether we aliased any external values along the way that may be
192 // invisible to the analysis (i.e. landingpad for exceptions, calls for
193 // interprocedural analysis, etc.)
194 StratifiedAttrs AdditionalAttrs;
195
196 Edge(Value *From, Value *To, EdgeType W, StratifiedAttrs A)
197 : From(From), To(To), Weight(W), AdditionalAttrs(A) {}
198};
199
Hal Finkel7529c552014-09-02 21:43:13 +0000200// \brief Gets the edges our graph should have, based on an Instruction*
201class GetEdgesVisitor : public InstVisitor<GetEdgesVisitor, void> {
202 CFLAliasAnalysis &AA;
203 SmallVectorImpl<Edge> &Output;
204
205public:
206 GetEdgesVisitor(CFLAliasAnalysis &AA, SmallVectorImpl<Edge> &Output)
207 : AA(AA), Output(Output) {}
208
209 void visitInstruction(Instruction &) {
210 llvm_unreachable("Unsupported instruction encountered");
211 }
212
George Burgess IVb54a8d622015-03-10 02:40:06 +0000213 void visitPtrToIntInst(PtrToIntInst &Inst) {
214 auto *Ptr = Inst.getOperand(0);
215 Output.push_back(Edge(Ptr, Ptr, EdgeType::Assign, AttrUnknown));
216 }
217
218 void visitIntToPtrInst(IntToPtrInst &Inst) {
219 auto *Ptr = &Inst;
220 Output.push_back(Edge(Ptr, Ptr, EdgeType::Assign, AttrUnknown));
221 }
222
Hal Finkel7529c552014-09-02 21:43:13 +0000223 void visitCastInst(CastInst &Inst) {
George Burgess IV11d509d2015-03-15 00:52:21 +0000224 Output.push_back(
225 Edge(&Inst, Inst.getOperand(0), EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000226 }
227
228 void visitBinaryOperator(BinaryOperator &Inst) {
229 auto *Op1 = Inst.getOperand(0);
230 auto *Op2 = Inst.getOperand(1);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000231 Output.push_back(Edge(&Inst, Op1, EdgeType::Assign, AttrNone));
232 Output.push_back(Edge(&Inst, Op2, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000233 }
234
235 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
236 auto *Ptr = Inst.getPointerOperand();
237 auto *Val = Inst.getNewValOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000238 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000239 }
240
241 void visitAtomicRMWInst(AtomicRMWInst &Inst) {
242 auto *Ptr = Inst.getPointerOperand();
243 auto *Val = Inst.getValOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000244 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000245 }
246
247 void visitPHINode(PHINode &Inst) {
Pete Cooper833f34d2015-05-12 20:05:31 +0000248 for (Value *Val : Inst.incoming_values()) {
Hal Finkel8d1590d2014-09-02 22:52:30 +0000249 Output.push_back(Edge(&Inst, Val, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000250 }
251 }
252
253 void visitGetElementPtrInst(GetElementPtrInst &Inst) {
254 auto *Op = Inst.getPointerOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000255 Output.push_back(Edge(&Inst, Op, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000256 for (auto I = Inst.idx_begin(), E = Inst.idx_end(); I != E; ++I)
Hal Finkel8d1590d2014-09-02 22:52:30 +0000257 Output.push_back(Edge(&Inst, *I, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000258 }
259
260 void visitSelectInst(SelectInst &Inst) {
Daniel Berlin16f7a522015-01-26 17:31:17 +0000261 // Condition is not processed here (The actual statement producing
262 // the condition result is processed elsewhere). For select, the
263 // condition is evaluated, but not loaded, stored, or assigned
264 // simply as a result of being the condition of a select.
265
Hal Finkel7529c552014-09-02 21:43:13 +0000266 auto *TrueVal = Inst.getTrueValue();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000267 Output.push_back(Edge(&Inst, TrueVal, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000268 auto *FalseVal = Inst.getFalseValue();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000269 Output.push_back(Edge(&Inst, FalseVal, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000270 }
271
272 void visitAllocaInst(AllocaInst &) {}
273
274 void visitLoadInst(LoadInst &Inst) {
275 auto *Ptr = Inst.getPointerOperand();
276 auto *Val = &Inst;
Hal Finkel8d1590d2014-09-02 22:52:30 +0000277 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000278 }
279
280 void visitStoreInst(StoreInst &Inst) {
281 auto *Ptr = Inst.getPointerOperand();
282 auto *Val = Inst.getValueOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000283 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000284 }
285
Hal Finkeldb5f86a2014-10-14 20:51:26 +0000286 void visitVAArgInst(VAArgInst &Inst) {
287 // We can't fully model va_arg here. For *Ptr = Inst.getOperand(0), it does
288 // two things:
289 // 1. Loads a value from *((T*)*Ptr).
290 // 2. Increments (stores to) *Ptr by some target-specific amount.
291 // For now, we'll handle this like a landingpad instruction (by placing the
292 // result in its own group, and having that group alias externals).
293 auto *Val = &Inst;
294 Output.push_back(Edge(Val, Val, EdgeType::Assign, AttrAll));
295 }
296
Hal Finkel7529c552014-09-02 21:43:13 +0000297 static bool isFunctionExternal(Function *Fn) {
298 return Fn->isDeclaration() || !Fn->hasLocalLinkage();
299 }
300
301 // Gets whether the sets at Index1 above, below, or equal to the sets at
302 // Index2. Returns None if they are not in the same set chain.
303 static Optional<Level> getIndexRelation(const StratifiedSets<Value *> &Sets,
304 StratifiedIndex Index1,
305 StratifiedIndex Index2) {
306 if (Index1 == Index2)
307 return Level::Same;
308
309 const auto *Current = &Sets.getLink(Index1);
310 while (Current->hasBelow()) {
311 if (Current->Below == Index2)
312 return Level::Below;
313 Current = &Sets.getLink(Current->Below);
314 }
315
316 Current = &Sets.getLink(Index1);
317 while (Current->hasAbove()) {
318 if (Current->Above == Index2)
319 return Level::Above;
320 Current = &Sets.getLink(Current->Above);
321 }
322
323 return NoneType();
324 }
325
326 bool
327 tryInterproceduralAnalysis(const SmallVectorImpl<Function *> &Fns,
328 Value *FuncValue,
329 const iterator_range<User::op_iterator> &Args) {
Hal Finkelca616ac2014-09-02 23:29:48 +0000330 const unsigned ExpectedMaxArgs = 8;
331 const unsigned MaxSupportedArgs = 50;
Hal Finkel7529c552014-09-02 21:43:13 +0000332 assert(Fns.size() > 0);
333
334 // I put this here to give us an upper bound on time taken by IPA. Is it
335 // really (realistically) needed? Keep in mind that we do have an n^2 algo.
George Burgess IVab03af22015-03-10 02:58:15 +0000336 if (std::distance(Args.begin(), Args.end()) > (int)MaxSupportedArgs)
Hal Finkel7529c552014-09-02 21:43:13 +0000337 return false;
338
339 // Exit early if we'll fail anyway
340 for (auto *Fn : Fns) {
341 if (isFunctionExternal(Fn) || Fn->isVarArg())
342 return false;
343 auto &MaybeInfo = AA.ensureCached(Fn);
344 if (!MaybeInfo.hasValue())
345 return false;
346 }
347
348 SmallVector<Value *, ExpectedMaxArgs> Arguments(Args.begin(), Args.end());
349 SmallVector<StratifiedInfo, ExpectedMaxArgs> Parameters;
350 for (auto *Fn : Fns) {
351 auto &Info = *AA.ensureCached(Fn);
352 auto &Sets = Info.Sets;
353 auto &RetVals = Info.ReturnedValues;
354
355 Parameters.clear();
356 for (auto &Param : Fn->args()) {
357 auto MaybeInfo = Sets.find(&Param);
358 // Did a new parameter somehow get added to the function/slip by?
359 if (!MaybeInfo.hasValue())
360 return false;
361 Parameters.push_back(*MaybeInfo);
362 }
363
364 // Adding an edge from argument -> return value for each parameter that
365 // may alias the return value
366 for (unsigned I = 0, E = Parameters.size(); I != E; ++I) {
367 auto &ParamInfo = Parameters[I];
368 auto &ArgVal = Arguments[I];
369 bool AddEdge = false;
370 StratifiedAttrs Externals;
371 for (unsigned X = 0, XE = RetVals.size(); X != XE; ++X) {
372 auto MaybeInfo = Sets.find(RetVals[X]);
373 if (!MaybeInfo.hasValue())
374 return false;
375
376 auto &RetInfo = *MaybeInfo;
377 auto RetAttrs = Sets.getLink(RetInfo.Index).Attrs;
378 auto ParamAttrs = Sets.getLink(ParamInfo.Index).Attrs;
379 auto MaybeRelation =
380 getIndexRelation(Sets, ParamInfo.Index, RetInfo.Index);
381 if (MaybeRelation.hasValue()) {
382 AddEdge = true;
383 Externals |= RetAttrs | ParamAttrs;
384 }
385 }
386 if (AddEdge)
Hal Finkelca616ac2014-09-02 23:29:48 +0000387 Output.push_back(Edge(FuncValue, ArgVal, EdgeType::Assign,
George Burgess IV11d509d2015-03-15 00:52:21 +0000388 StratifiedAttrs().flip()));
Hal Finkel7529c552014-09-02 21:43:13 +0000389 }
390
391 if (Parameters.size() != Arguments.size())
392 return false;
393
394 // Adding edges between arguments for arguments that may end up aliasing
395 // each other. This is necessary for functions such as
396 // void foo(int** a, int** b) { *a = *b; }
397 // (Technically, the proper sets for this would be those below
398 // Arguments[I] and Arguments[X], but our algorithm will produce
399 // extremely similar, and equally correct, results either way)
400 for (unsigned I = 0, E = Arguments.size(); I != E; ++I) {
401 auto &MainVal = Arguments[I];
402 auto &MainInfo = Parameters[I];
403 auto &MainAttrs = Sets.getLink(MainInfo.Index).Attrs;
404 for (unsigned X = I + 1; X != E; ++X) {
405 auto &SubInfo = Parameters[X];
406 auto &SubVal = Arguments[X];
407 auto &SubAttrs = Sets.getLink(SubInfo.Index).Attrs;
408 auto MaybeRelation =
409 getIndexRelation(Sets, MainInfo.Index, SubInfo.Index);
410
411 if (!MaybeRelation.hasValue())
412 continue;
413
414 auto NewAttrs = SubAttrs | MainAttrs;
Hal Finkel8d1590d2014-09-02 22:52:30 +0000415 Output.push_back(Edge(MainVal, SubVal, EdgeType::Assign, NewAttrs));
Hal Finkel7529c552014-09-02 21:43:13 +0000416 }
417 }
418 }
419 return true;
420 }
421
422 template <typename InstT> void visitCallLikeInst(InstT &Inst) {
423 SmallVector<Function *, 4> Targets;
424 if (getPossibleTargets(&Inst, Targets)) {
425 if (tryInterproceduralAnalysis(Targets, &Inst, Inst.arg_operands()))
426 return;
427 // Cleanup from interprocedural analysis
428 Output.clear();
429 }
430
431 for (Value *V : Inst.arg_operands())
Hal Finkel8d1590d2014-09-02 22:52:30 +0000432 Output.push_back(Edge(&Inst, V, EdgeType::Assign, AttrAll));
Hal Finkel7529c552014-09-02 21:43:13 +0000433 }
434
435 void visitCallInst(CallInst &Inst) { visitCallLikeInst(Inst); }
436
437 void visitInvokeInst(InvokeInst &Inst) { visitCallLikeInst(Inst); }
438
439 // Because vectors/aggregates are immutable and unaddressable,
440 // there's nothing we can do to coax a value out of them, other
441 // than calling Extract{Element,Value}. We can effectively treat
442 // them as pointers to arbitrary memory locations we can store in
443 // and load from.
444 void visitExtractElementInst(ExtractElementInst &Inst) {
445 auto *Ptr = Inst.getVectorOperand();
446 auto *Val = &Inst;
Hal Finkel8d1590d2014-09-02 22:52:30 +0000447 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000448 }
449
450 void visitInsertElementInst(InsertElementInst &Inst) {
451 auto *Vec = Inst.getOperand(0);
452 auto *Val = Inst.getOperand(1);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000453 Output.push_back(Edge(&Inst, Vec, EdgeType::Assign, AttrNone));
454 Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000455 }
456
457 void visitLandingPadInst(LandingPadInst &Inst) {
458 // Exceptions come from "nowhere", from our analysis' perspective.
459 // So we place the instruction its own group, noting that said group may
460 // alias externals
Hal Finkel8d1590d2014-09-02 22:52:30 +0000461 Output.push_back(Edge(&Inst, &Inst, EdgeType::Assign, AttrAll));
Hal Finkel7529c552014-09-02 21:43:13 +0000462 }
463
464 void visitInsertValueInst(InsertValueInst &Inst) {
465 auto *Agg = Inst.getOperand(0);
466 auto *Val = Inst.getOperand(1);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000467 Output.push_back(Edge(&Inst, Agg, EdgeType::Assign, AttrNone));
468 Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000469 }
470
471 void visitExtractValueInst(ExtractValueInst &Inst) {
472 auto *Ptr = Inst.getAggregateOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000473 Output.push_back(Edge(&Inst, Ptr, EdgeType::Reference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000474 }
475
476 void visitShuffleVectorInst(ShuffleVectorInst &Inst) {
477 auto *From1 = Inst.getOperand(0);
478 auto *From2 = Inst.getOperand(1);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000479 Output.push_back(Edge(&Inst, From1, EdgeType::Assign, AttrNone));
480 Output.push_back(Edge(&Inst, From2, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000481 }
Pete Cooper36642532015-06-12 16:13:54 +0000482
483 void visitConstantExpr(ConstantExpr *CE) {
484 switch (CE->getOpcode()) {
485 default:
486 llvm_unreachable("Unknown instruction type encountered!");
487// Build the switch statement using the Instruction.def file.
488#define HANDLE_INST(NUM, OPCODE, CLASS) \
489 case Instruction::OPCODE: \
490 visit##OPCODE(*(CLASS *)CE); \
491 break;
492#include "llvm/IR/Instruction.def"
493 }
494 }
Hal Finkel7529c552014-09-02 21:43:13 +0000495};
496
497// For a given instruction, we need to know which Value* to get the
498// users of in order to build our graph. In some cases (i.e. add),
499// we simply need the Instruction*. In other cases (i.e. store),
500// finding the users of the Instruction* is useless; we need to find
501// the users of the first operand. This handles determining which
502// value to follow for us.
503//
504// Note: we *need* to keep this in sync with GetEdgesVisitor. Add
505// something to GetEdgesVisitor, add it here -- remove something from
506// GetEdgesVisitor, remove it here.
507class GetTargetValueVisitor
508 : public InstVisitor<GetTargetValueVisitor, Value *> {
509public:
510 Value *visitInstruction(Instruction &Inst) { return &Inst; }
511
512 Value *visitStoreInst(StoreInst &Inst) { return Inst.getPointerOperand(); }
513
514 Value *visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
515 return Inst.getPointerOperand();
516 }
517
518 Value *visitAtomicRMWInst(AtomicRMWInst &Inst) {
519 return Inst.getPointerOperand();
520 }
521
522 Value *visitInsertElementInst(InsertElementInst &Inst) {
523 return Inst.getOperand(0);
524 }
525
526 Value *visitInsertValueInst(InsertValueInst &Inst) {
527 return Inst.getAggregateOperand();
528 }
529};
530
531// Set building requires a weighted bidirectional graph.
532template <typename EdgeTypeT> class WeightedBidirectionalGraph {
533public:
534 typedef std::size_t Node;
535
536private:
Hal Finkelca616ac2014-09-02 23:29:48 +0000537 const static Node StartNode = Node(0);
Hal Finkel7529c552014-09-02 21:43:13 +0000538
539 struct Edge {
540 EdgeTypeT Weight;
541 Node Other;
542
George Burgess IV11d509d2015-03-15 00:52:21 +0000543 Edge(const EdgeTypeT &W, const Node &N) : Weight(W), Other(N) {}
Hal Finkelca616ac2014-09-02 23:29:48 +0000544
Hal Finkel7529c552014-09-02 21:43:13 +0000545 bool operator==(const Edge &E) const {
546 return Weight == E.Weight && Other == E.Other;
547 }
548
549 bool operator!=(const Edge &E) const { return !operator==(E); }
550 };
551
552 struct NodeImpl {
553 std::vector<Edge> Edges;
554 };
555
556 std::vector<NodeImpl> NodeImpls;
557
558 bool inbounds(Node NodeIndex) const { return NodeIndex < NodeImpls.size(); }
559
560 const NodeImpl &getNode(Node N) const { return NodeImpls[N]; }
561 NodeImpl &getNode(Node N) { return NodeImpls[N]; }
562
563public:
564 // ----- Various Edge iterators for the graph ----- //
565
566 // \brief Iterator for edges. Because this graph is bidirected, we don't
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000567 // allow modification of the edges using this iterator. Additionally, the
Hal Finkel7529c552014-09-02 21:43:13 +0000568 // iterator becomes invalid if you add edges to or from the node you're
569 // getting the edges of.
570 struct EdgeIterator : public std::iterator<std::forward_iterator_tag,
571 std::tuple<EdgeTypeT, Node *>> {
572 EdgeIterator(const typename std::vector<Edge>::const_iterator &Iter)
573 : Current(Iter) {}
574
575 EdgeIterator(NodeImpl &Impl) : Current(Impl.begin()) {}
576
577 EdgeIterator &operator++() {
578 ++Current;
579 return *this;
580 }
581
582 EdgeIterator operator++(int) {
583 EdgeIterator Copy(Current);
584 operator++();
585 return Copy;
586 }
587
588 std::tuple<EdgeTypeT, Node> &operator*() {
589 Store = std::make_tuple(Current->Weight, Current->Other);
590 return Store;
591 }
592
593 bool operator==(const EdgeIterator &Other) const {
594 return Current == Other.Current;
595 }
596
597 bool operator!=(const EdgeIterator &Other) const {
598 return !operator==(Other);
599 }
600
601 private:
602 typename std::vector<Edge>::const_iterator Current;
603 std::tuple<EdgeTypeT, Node> Store;
604 };
605
606 // Wrapper for EdgeIterator with begin()/end() calls.
607 struct EdgeIterable {
608 EdgeIterable(const std::vector<Edge> &Edges)
609 : BeginIter(Edges.begin()), EndIter(Edges.end()) {}
610
611 EdgeIterator begin() { return EdgeIterator(BeginIter); }
612
613 EdgeIterator end() { return EdgeIterator(EndIter); }
614
615 private:
616 typename std::vector<Edge>::const_iterator BeginIter;
617 typename std::vector<Edge>::const_iterator EndIter;
618 };
619
620 // ----- Actual graph-related things ----- //
621
Hal Finkelca616ac2014-09-02 23:29:48 +0000622 WeightedBidirectionalGraph() {}
Hal Finkel7529c552014-09-02 21:43:13 +0000623
624 WeightedBidirectionalGraph(WeightedBidirectionalGraph<EdgeTypeT> &&Other)
625 : NodeImpls(std::move(Other.NodeImpls)) {}
626
627 WeightedBidirectionalGraph<EdgeTypeT> &
628 operator=(WeightedBidirectionalGraph<EdgeTypeT> &&Other) {
629 NodeImpls = std::move(Other.NodeImpls);
630 return *this;
631 }
632
633 Node addNode() {
634 auto Index = NodeImpls.size();
635 auto NewNode = Node(Index);
636 NodeImpls.push_back(NodeImpl());
637 return NewNode;
638 }
639
640 void addEdge(Node From, Node To, const EdgeTypeT &Weight,
641 const EdgeTypeT &ReverseWeight) {
642 assert(inbounds(From));
643 assert(inbounds(To));
644 auto &FromNode = getNode(From);
645 auto &ToNode = getNode(To);
Hal Finkelca616ac2014-09-02 23:29:48 +0000646 FromNode.Edges.push_back(Edge(Weight, To));
647 ToNode.Edges.push_back(Edge(ReverseWeight, From));
Hal Finkel7529c552014-09-02 21:43:13 +0000648 }
649
650 EdgeIterable edgesFor(const Node &N) const {
651 const auto &Node = getNode(N);
652 return EdgeIterable(Node.Edges);
653 }
654
655 bool empty() const { return NodeImpls.empty(); }
656 std::size_t size() const { return NodeImpls.size(); }
657
658 // \brief Gets an arbitrary node in the graph as a starting point for
659 // traversal.
660 Node getEntryNode() {
661 assert(inbounds(StartNode));
662 return StartNode;
663 }
664};
665
666typedef WeightedBidirectionalGraph<std::pair<EdgeType, StratifiedAttrs>> GraphT;
667typedef DenseMap<Value *, GraphT::Node> NodeMapT;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000668}
Hal Finkel7529c552014-09-02 21:43:13 +0000669
Hal Finkel7529c552014-09-02 21:43:13 +0000670//===----------------------------------------------------------------------===//
671// Function declarations that require types defined in the namespace above
672//===----------------------------------------------------------------------===//
673
674// Given an argument number, returns the appropriate Attr index to set.
675static StratifiedAttr argNumberToAttrIndex(StratifiedAttr);
676
677// Given a Value, potentially return which AttrIndex it maps to.
678static Optional<StratifiedAttr> valueToAttrIndex(Value *Val);
679
680// Gets the inverse of a given EdgeType.
681static EdgeType flipWeight(EdgeType);
682
683// Gets edges of the given Instruction*, writing them to the SmallVector*.
684static void argsToEdges(CFLAliasAnalysis &, Instruction *,
685 SmallVectorImpl<Edge> &);
686
Pete Cooper36642532015-06-12 16:13:54 +0000687// Gets edges of the given ConstantExpr*, writing them to the SmallVector*.
688static void argsToEdges(CFLAliasAnalysis &, ConstantExpr *,
689 SmallVectorImpl<Edge> &);
690
Hal Finkel7529c552014-09-02 21:43:13 +0000691// Gets the "Level" that one should travel in StratifiedSets
692// given an EdgeType.
693static Level directionOfEdgeType(EdgeType);
694
695// Builds the graph needed for constructing the StratifiedSets for the
696// given function
697static void buildGraphFrom(CFLAliasAnalysis &, Function *,
698 SmallVectorImpl<Value *> &, NodeMapT &, GraphT &);
699
George Burgess IVab03af22015-03-10 02:58:15 +0000700// Gets the edges of a ConstantExpr as if it was an Instruction. This
701// function also acts on any nested ConstantExprs, adding the edges
702// of those to the given SmallVector as well.
703static void constexprToEdges(CFLAliasAnalysis &, ConstantExpr &,
704 SmallVectorImpl<Edge> &);
705
706// Given an Instruction, this will add it to the graph, along with any
707// Instructions that are potentially only available from said Instruction
708// For example, given the following line:
709// %0 = load i16* getelementptr ([1 x i16]* @a, 0, 0), align 2
710// addInstructionToGraph would add both the `load` and `getelementptr`
711// instructions to the graph appropriately.
712static void addInstructionToGraph(CFLAliasAnalysis &, Instruction &,
713 SmallVectorImpl<Value *> &, NodeMapT &,
714 GraphT &);
715
716// Notes whether it would be pointless to add the given Value to our sets.
717static bool canSkipAddingToSets(Value *Val);
718
Hal Finkel7529c552014-09-02 21:43:13 +0000719static Optional<Function *> parentFunctionOfValue(Value *Val) {
720 if (auto *Inst = dyn_cast<Instruction>(Val)) {
721 auto *Bb = Inst->getParent();
722 return Bb->getParent();
723 }
724
725 if (auto *Arg = dyn_cast<Argument>(Val))
726 return Arg->getParent();
727 return NoneType();
728}
729
730template <typename Inst>
731static bool getPossibleTargets(Inst *Call,
732 SmallVectorImpl<Function *> &Output) {
733 if (auto *Fn = Call->getCalledFunction()) {
734 Output.push_back(Fn);
735 return true;
736 }
737
738 // TODO: If the call is indirect, we might be able to enumerate all potential
739 // targets of the call and return them, rather than just failing.
740 return false;
741}
742
743static Optional<Value *> getTargetValue(Instruction *Inst) {
744 GetTargetValueVisitor V;
745 return V.visit(Inst);
746}
747
748static bool hasUsefulEdges(Instruction *Inst) {
749 bool IsNonInvokeTerminator =
750 isa<TerminatorInst>(Inst) && !isa<InvokeInst>(Inst);
751 return !isa<CmpInst>(Inst) && !isa<FenceInst>(Inst) && !IsNonInvokeTerminator;
752}
753
Pete Cooper36642532015-06-12 16:13:54 +0000754static bool hasUsefulEdges(ConstantExpr *CE) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000755 // ConstantExpr doesn't have terminators, invokes, or fences, so only needs
Pete Cooper36642532015-06-12 16:13:54 +0000756 // to check for compares.
757 return CE->getOpcode() != Instruction::ICmp &&
758 CE->getOpcode() != Instruction::FCmp;
759}
760
Hal Finkel7529c552014-09-02 21:43:13 +0000761static Optional<StratifiedAttr> valueToAttrIndex(Value *Val) {
762 if (isa<GlobalValue>(Val))
763 return AttrGlobalIndex;
764
765 if (auto *Arg = dyn_cast<Argument>(Val))
Daniel Berlin16f7a522015-01-26 17:31:17 +0000766 // Only pointer arguments should have the argument attribute,
767 // because things can't escape through scalars without us seeing a
768 // cast, and thus, interaction with them doesn't matter.
769 if (!Arg->hasNoAliasAttr() && Arg->getType()->isPointerTy())
Hal Finkel7529c552014-09-02 21:43:13 +0000770 return argNumberToAttrIndex(Arg->getArgNo());
771 return NoneType();
772}
773
774static StratifiedAttr argNumberToAttrIndex(unsigned ArgNum) {
George Burgess IV3c898c22015-01-21 16:37:21 +0000775 if (ArgNum >= AttrMaxNumArgs)
Hal Finkel7529c552014-09-02 21:43:13 +0000776 return AttrAllIndex;
777 return ArgNum + AttrFirstArgIndex;
778}
779
780static EdgeType flipWeight(EdgeType Initial) {
781 switch (Initial) {
782 case EdgeType::Assign:
783 return EdgeType::Assign;
784 case EdgeType::Dereference:
785 return EdgeType::Reference;
786 case EdgeType::Reference:
787 return EdgeType::Dereference;
788 }
789 llvm_unreachable("Incomplete coverage of EdgeType enum");
790}
791
792static void argsToEdges(CFLAliasAnalysis &Analysis, Instruction *Inst,
793 SmallVectorImpl<Edge> &Output) {
George Burgess IVab03af22015-03-10 02:58:15 +0000794 assert(hasUsefulEdges(Inst) &&
795 "Expected instructions to have 'useful' edges");
Hal Finkel7529c552014-09-02 21:43:13 +0000796 GetEdgesVisitor v(Analysis, Output);
797 v.visit(Inst);
798}
799
Pete Cooper36642532015-06-12 16:13:54 +0000800static void argsToEdges(CFLAliasAnalysis &Analysis, ConstantExpr *CE,
801 SmallVectorImpl<Edge> &Output) {
802 assert(hasUsefulEdges(CE) && "Expected constant expr to have 'useful' edges");
803 GetEdgesVisitor v(Analysis, Output);
804 v.visitConstantExpr(CE);
805}
806
Hal Finkel7529c552014-09-02 21:43:13 +0000807static Level directionOfEdgeType(EdgeType Weight) {
808 switch (Weight) {
809 case EdgeType::Reference:
810 return Level::Above;
811 case EdgeType::Dereference:
812 return Level::Below;
813 case EdgeType::Assign:
814 return Level::Same;
815 }
816 llvm_unreachable("Incomplete switch coverage");
817}
818
George Burgess IVab03af22015-03-10 02:58:15 +0000819static void constexprToEdges(CFLAliasAnalysis &Analysis,
820 ConstantExpr &CExprToCollapse,
821 SmallVectorImpl<Edge> &Results) {
822 SmallVector<ConstantExpr *, 4> Worklist;
823 Worklist.push_back(&CExprToCollapse);
824
825 SmallVector<Edge, 8> ConstexprEdges;
Pete Cooper36642532015-06-12 16:13:54 +0000826 SmallPtrSet<ConstantExpr *, 4> Visited;
George Burgess IVab03af22015-03-10 02:58:15 +0000827 while (!Worklist.empty()) {
828 auto *CExpr = Worklist.pop_back_val();
George Burgess IVab03af22015-03-10 02:58:15 +0000829
Pete Cooper36642532015-06-12 16:13:54 +0000830 if (!hasUsefulEdges(CExpr))
George Burgess IVab03af22015-03-10 02:58:15 +0000831 continue;
832
833 ConstexprEdges.clear();
Pete Cooper36642532015-06-12 16:13:54 +0000834 argsToEdges(Analysis, CExpr, ConstexprEdges);
George Burgess IVab03af22015-03-10 02:58:15 +0000835 for (auto &Edge : ConstexprEdges) {
Pete Cooper36642532015-06-12 16:13:54 +0000836 if (auto *Nested = dyn_cast<ConstantExpr>(Edge.From))
837 if (Visited.insert(Nested).second)
838 Worklist.push_back(Nested);
George Burgess IVab03af22015-03-10 02:58:15 +0000839
Pete Cooper36642532015-06-12 16:13:54 +0000840 if (auto *Nested = dyn_cast<ConstantExpr>(Edge.To))
841 if (Visited.insert(Nested).second)
842 Worklist.push_back(Nested);
George Burgess IVab03af22015-03-10 02:58:15 +0000843 }
844
845 Results.append(ConstexprEdges.begin(), ConstexprEdges.end());
846 }
847}
848
849static void addInstructionToGraph(CFLAliasAnalysis &Analysis, Instruction &Inst,
850 SmallVectorImpl<Value *> &ReturnedValues,
851 NodeMapT &Map, GraphT &Graph) {
Hal Finkel7529c552014-09-02 21:43:13 +0000852 const auto findOrInsertNode = [&Map, &Graph](Value *Val) {
853 auto Pair = Map.insert(std::make_pair(Val, GraphT::Node()));
854 auto &Iter = Pair.first;
855 if (Pair.second) {
856 auto NewNode = Graph.addNode();
857 Iter->second = NewNode;
858 }
859 return Iter->second;
860 };
861
George Burgess IVab03af22015-03-10 02:58:15 +0000862 // We don't want the edges of most "return" instructions, but we *do* want
863 // to know what can be returned.
864 if (isa<ReturnInst>(&Inst))
865 ReturnedValues.push_back(&Inst);
866
867 if (!hasUsefulEdges(&Inst))
868 return;
869
Hal Finkel7529c552014-09-02 21:43:13 +0000870 SmallVector<Edge, 8> Edges;
George Burgess IVab03af22015-03-10 02:58:15 +0000871 argsToEdges(Analysis, &Inst, Edges);
Hal Finkel7529c552014-09-02 21:43:13 +0000872
George Burgess IVab03af22015-03-10 02:58:15 +0000873 // In the case of an unused alloca (or similar), edges may be empty. Note
874 // that it exists so we can potentially answer NoAlias.
875 if (Edges.empty()) {
876 auto MaybeVal = getTargetValue(&Inst);
877 assert(MaybeVal.hasValue());
878 auto *Target = *MaybeVal;
879 findOrInsertNode(Target);
880 return;
Hal Finkel7529c552014-09-02 21:43:13 +0000881 }
George Burgess IVab03af22015-03-10 02:58:15 +0000882
883 const auto addEdgeToGraph = [&Graph, &findOrInsertNode](const Edge &E) {
884 auto To = findOrInsertNode(E.To);
885 auto From = findOrInsertNode(E.From);
886 auto FlippedWeight = flipWeight(E.Weight);
887 auto Attrs = E.AdditionalAttrs;
888 Graph.addEdge(From, To, std::make_pair(E.Weight, Attrs),
889 std::make_pair(FlippedWeight, Attrs));
890 };
891
892 SmallVector<ConstantExpr *, 4> ConstantExprs;
893 for (const Edge &E : Edges) {
894 addEdgeToGraph(E);
895 if (auto *Constexpr = dyn_cast<ConstantExpr>(E.To))
896 ConstantExprs.push_back(Constexpr);
897 if (auto *Constexpr = dyn_cast<ConstantExpr>(E.From))
898 ConstantExprs.push_back(Constexpr);
899 }
900
901 for (ConstantExpr *CE : ConstantExprs) {
902 Edges.clear();
903 constexprToEdges(Analysis, *CE, Edges);
904 std::for_each(Edges.begin(), Edges.end(), addEdgeToGraph);
905 }
906}
907
908// Aside: We may remove graph construction entirely, because it doesn't really
909// buy us much that we don't already have. I'd like to add interprocedural
910// analysis prior to this however, in case that somehow requires the graph
911// produced by this for efficient execution
912static void buildGraphFrom(CFLAliasAnalysis &Analysis, Function *Fn,
913 SmallVectorImpl<Value *> &ReturnedValues,
914 NodeMapT &Map, GraphT &Graph) {
915 for (auto &Bb : Fn->getBasicBlockList())
916 for (auto &Inst : Bb.getInstList())
917 addInstructionToGraph(Analysis, Inst, ReturnedValues, Map, Graph);
918}
919
920static bool canSkipAddingToSets(Value *Val) {
921 // Constants can share instances, which may falsely unify multiple
922 // sets, e.g. in
923 // store i32* null, i32** %ptr1
924 // store i32* null, i32** %ptr2
925 // clearly ptr1 and ptr2 should not be unified into the same set, so
926 // we should filter out the (potentially shared) instance to
927 // i32* null.
928 if (isa<Constant>(Val)) {
929 bool Container = isa<ConstantVector>(Val) || isa<ConstantArray>(Val) ||
930 isa<ConstantStruct>(Val);
931 // TODO: Because all of these things are constant, we can determine whether
932 // the data is *actually* mutable at graph building time. This will probably
933 // come for free/cheap with offset awareness.
934 bool CanStoreMutableData =
935 isa<GlobalValue>(Val) || isa<ConstantExpr>(Val) || Container;
936 return !CanStoreMutableData;
937 }
938
939 return false;
Hal Finkel7529c552014-09-02 21:43:13 +0000940}
941
Chandler Carruth8b046a42015-08-14 02:42:20 +0000942// Builds the graph + StratifiedSets for a function.
943CFLAliasAnalysis::FunctionInfo CFLAliasAnalysis::buildSetsFrom(Function *Fn) {
Hal Finkel7529c552014-09-02 21:43:13 +0000944 NodeMapT Map;
945 GraphT Graph;
946 SmallVector<Value *, 4> ReturnedValues;
947
Chandler Carruth8b046a42015-08-14 02:42:20 +0000948 buildGraphFrom(*this, Fn, ReturnedValues, Map, Graph);
Hal Finkel7529c552014-09-02 21:43:13 +0000949
950 DenseMap<GraphT::Node, Value *> NodeValueMap;
951 NodeValueMap.resize(Map.size());
952 for (const auto &Pair : Map)
Hal Finkel8d1590d2014-09-02 22:52:30 +0000953 NodeValueMap.insert(std::make_pair(Pair.second, Pair.first));
Hal Finkel7529c552014-09-02 21:43:13 +0000954
955 const auto findValueOrDie = [&NodeValueMap](GraphT::Node Node) {
956 auto ValIter = NodeValueMap.find(Node);
957 assert(ValIter != NodeValueMap.end());
958 return ValIter->second;
959 };
960
961 StratifiedSetsBuilder<Value *> Builder;
962
963 SmallVector<GraphT::Node, 16> Worklist;
964 for (auto &Pair : Map) {
965 Worklist.clear();
966
967 auto *Value = Pair.first;
968 Builder.add(Value);
969 auto InitialNode = Pair.second;
970 Worklist.push_back(InitialNode);
971 while (!Worklist.empty()) {
972 auto Node = Worklist.pop_back_val();
973 auto *CurValue = findValueOrDie(Node);
George Burgess IVab03af22015-03-10 02:58:15 +0000974 if (canSkipAddingToSets(CurValue))
Hal Finkel7529c552014-09-02 21:43:13 +0000975 continue;
976
977 for (const auto &EdgeTuple : Graph.edgesFor(Node)) {
978 auto Weight = std::get<0>(EdgeTuple);
979 auto Label = Weight.first;
980 auto &OtherNode = std::get<1>(EdgeTuple);
981 auto *OtherValue = findValueOrDie(OtherNode);
982
George Burgess IVab03af22015-03-10 02:58:15 +0000983 if (canSkipAddingToSets(OtherValue))
Hal Finkel7529c552014-09-02 21:43:13 +0000984 continue;
985
986 bool Added;
987 switch (directionOfEdgeType(Label)) {
988 case Level::Above:
989 Added = Builder.addAbove(CurValue, OtherValue);
990 break;
991 case Level::Below:
992 Added = Builder.addBelow(CurValue, OtherValue);
993 break;
994 case Level::Same:
995 Added = Builder.addWith(CurValue, OtherValue);
996 break;
997 }
998
George Burgess IVb54a8d622015-03-10 02:40:06 +0000999 auto Aliasing = Weight.second;
1000 if (auto MaybeCurIndex = valueToAttrIndex(CurValue))
1001 Aliasing.set(*MaybeCurIndex);
1002 if (auto MaybeOtherIndex = valueToAttrIndex(OtherValue))
1003 Aliasing.set(*MaybeOtherIndex);
1004 Builder.noteAttributes(CurValue, Aliasing);
1005 Builder.noteAttributes(OtherValue, Aliasing);
1006
1007 if (Added)
Hal Finkel7529c552014-09-02 21:43:13 +00001008 Worklist.push_back(OtherNode);
Hal Finkel7529c552014-09-02 21:43:13 +00001009 }
1010 }
1011 }
1012
1013 // There are times when we end up with parameters not in our graph (i.e. if
1014 // it's only used as the condition of a branch). Other bits of code depend on
1015 // things that were present during construction being present in the graph.
1016 // So, we add all present arguments here.
1017 for (auto &Arg : Fn->args()) {
George Burgess IVab03af22015-03-10 02:58:15 +00001018 if (!Builder.add(&Arg))
1019 continue;
1020
1021 auto Attrs = valueToAttrIndex(&Arg);
1022 if (Attrs.hasValue())
1023 Builder.noteAttributes(&Arg, *Attrs);
Hal Finkel7529c552014-09-02 21:43:13 +00001024 }
1025
Hal Finkel85f26922014-09-03 00:06:47 +00001026 return FunctionInfo(Builder.build(), std::move(ReturnedValues));
Hal Finkel7529c552014-09-02 21:43:13 +00001027}
1028
1029void CFLAliasAnalysis::scan(Function *Fn) {
Hal Finkel8d1590d2014-09-02 22:52:30 +00001030 auto InsertPair = Cache.insert(std::make_pair(Fn, Optional<FunctionInfo>()));
Hal Finkel7529c552014-09-02 21:43:13 +00001031 (void)InsertPair;
1032 assert(InsertPair.second &&
1033 "Trying to scan a function that has already been cached");
1034
Chandler Carruth8b046a42015-08-14 02:42:20 +00001035 FunctionInfo Info(buildSetsFrom(Fn));
Hal Finkel7529c552014-09-02 21:43:13 +00001036 Cache[Fn] = std::move(Info);
1037 Handles.push_front(FunctionHandle(Fn, this));
1038}
1039
Chandler Carruth8b046a42015-08-14 02:42:20 +00001040void CFLAliasAnalysis::evict(Function *Fn) { Cache.erase(Fn); }
1041
1042/// \brief Ensures that the given function is available in the cache.
1043/// Returns the appropriate entry from the cache.
1044const Optional<CFLAliasAnalysis::FunctionInfo> &
1045CFLAliasAnalysis::ensureCached(Function *Fn) {
1046 auto Iter = Cache.find(Fn);
1047 if (Iter == Cache.end()) {
1048 scan(Fn);
1049 Iter = Cache.find(Fn);
1050 assert(Iter != Cache.end());
1051 assert(Iter->second.hasValue());
1052 }
1053 return Iter->second;
1054}
1055
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001056AliasResult CFLAliasAnalysis::query(const MemoryLocation &LocA,
1057 const MemoryLocation &LocB) {
Hal Finkel7529c552014-09-02 21:43:13 +00001058 auto *ValA = const_cast<Value *>(LocA.Ptr);
1059 auto *ValB = const_cast<Value *>(LocB.Ptr);
1060
1061 Function *Fn = nullptr;
1062 auto MaybeFnA = parentFunctionOfValue(ValA);
1063 auto MaybeFnB = parentFunctionOfValue(ValB);
1064 if (!MaybeFnA.hasValue() && !MaybeFnB.hasValue()) {
George Burgess IV33305e72015-02-12 03:07:07 +00001065 // The only times this is known to happen are when globals + InlineAsm
1066 // are involved
1067 DEBUG(dbgs() << "CFLAA: could not extract parent function information.\n");
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001068 return MayAlias;
Hal Finkel7529c552014-09-02 21:43:13 +00001069 }
1070
1071 if (MaybeFnA.hasValue()) {
1072 Fn = *MaybeFnA;
1073 assert((!MaybeFnB.hasValue() || *MaybeFnB == *MaybeFnA) &&
1074 "Interprocedural queries not supported");
1075 } else {
1076 Fn = *MaybeFnB;
1077 }
1078
1079 assert(Fn != nullptr);
1080 auto &MaybeInfo = ensureCached(Fn);
1081 assert(MaybeInfo.hasValue());
1082
1083 auto &Sets = MaybeInfo->Sets;
1084 auto MaybeA = Sets.find(ValA);
1085 if (!MaybeA.hasValue())
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001086 return MayAlias;
Hal Finkel7529c552014-09-02 21:43:13 +00001087
1088 auto MaybeB = Sets.find(ValB);
1089 if (!MaybeB.hasValue())
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001090 return MayAlias;
Hal Finkel7529c552014-09-02 21:43:13 +00001091
1092 auto SetA = *MaybeA;
1093 auto SetB = *MaybeB;
Hal Finkel7529c552014-09-02 21:43:13 +00001094 auto AttrsA = Sets.getLink(SetA.Index).Attrs;
1095 auto AttrsB = Sets.getLink(SetB.Index).Attrs;
George Burgess IV33305e72015-02-12 03:07:07 +00001096
Hal Finkel8eae3ad2014-10-06 14:42:56 +00001097 // Stratified set attributes are used as markets to signify whether a member
George Burgess IV33305e72015-02-12 03:07:07 +00001098 // of a StratifiedSet (or a member of a set above the current set) has
Hal Finkel8eae3ad2014-10-06 14:42:56 +00001099 // interacted with either arguments or globals. "Interacted with" meaning
George Burgess IV33305e72015-02-12 03:07:07 +00001100 // its value may be different depending on the value of an argument or
Hal Finkel8eae3ad2014-10-06 14:42:56 +00001101 // global. The thought behind this is that, because arguments and globals
1102 // may alias each other, if AttrsA and AttrsB have touched args/globals,
George Burgess IV33305e72015-02-12 03:07:07 +00001103 // we must conservatively say that they alias. However, if at least one of
1104 // the sets has no values that could legally be altered by changing the value
Hal Finkel8eae3ad2014-10-06 14:42:56 +00001105 // of an argument or global, then we don't have to be as conservative.
1106 if (AttrsA.any() && AttrsB.any())
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001107 return MayAlias;
Hal Finkel7529c552014-09-02 21:43:13 +00001108
Daniel Berlin16f7a522015-01-26 17:31:17 +00001109 // We currently unify things even if the accesses to them may not be in
1110 // bounds, so we can't return partial alias here because we don't
1111 // know whether the pointer is really within the object or not.
1112 // IE Given an out of bounds GEP and an alloca'd pointer, we may
1113 // unify the two. We can't return partial alias for this case.
1114 // Since we do not currently track enough information to
1115 // differentiate
1116
1117 if (SetA.Index == SetB.Index)
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001118 return MayAlias;
Daniel Berlin16f7a522015-01-26 17:31:17 +00001119
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001120 return NoAlias;
Hal Finkel7529c552014-09-02 21:43:13 +00001121}
Mehdi Amini46a43552015-03-04 18:43:29 +00001122
1123bool CFLAliasAnalysis::doInitialization(Module &M) {
1124 InitializeAliasAnalysis(this, &M.getDataLayout());
1125 return true;
1126}