blob: 676b6161d0a379cffc4f987edf99a44306497030 [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
17// location. The "actions" can be one of Dereference, Reference, Assign, or
18// Assign.
19//
20// Two variables are considered as aliasing iff you can reach one value's node
21// from the other value's node and the language formed by concatenating all of
22// the edge labels (actions) conforms to a context-free grammar.
23//
24// Because this algorithm requires a graph search on each query, we execute the
25// algorithm outlined in "Fast algorithms..." (mentioned above)
26// in order to transform the graph into sets of variables that may alias in
27// ~nlogn time (n = number of variables.), which makes queries take constant
28// time.
29//===----------------------------------------------------------------------===//
30
31#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"
Chandler Carruthd9903882015-01-14 11:23:27 +000037#include "llvm/Analysis/Passes.h"
Hal Finkel7529c552014-09-02 21:43:13 +000038#include "llvm/IR/Constants.h"
39#include "llvm/IR/Function.h"
Hal Finkel7529c552014-09-02 21:43:13 +000040#include "llvm/IR/InstVisitor.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000041#include "llvm/IR/Instructions.h"
Hal Finkel7529c552014-09-02 21:43:13 +000042#include "llvm/IR/ValueHandle.h"
43#include "llvm/Pass.h"
44#include "llvm/Support/Allocator.h"
Hal Finkel7d7087c2014-09-02 22:13:00 +000045#include "llvm/Support/Compiler.h"
Hal Finkel7529c552014-09-02 21:43:13 +000046#include "llvm/Support/ErrorHandling.h"
47#include <algorithm>
48#include <cassert>
49#include <forward_list>
50#include <tuple>
51
52using namespace llvm;
53
54// Try to go from a Value* to a Function*. Never returns nullptr.
55static Optional<Function *> parentFunctionOfValue(Value *);
56
57// Returns possible functions called by the Inst* into the given
58// SmallVectorImpl. Returns true if targets found, false otherwise.
59// This is templated because InvokeInst/CallInst give us the same
60// set of functions that we care about, and I don't like repeating
61// myself.
62template <typename Inst>
63static bool getPossibleTargets(Inst *, SmallVectorImpl<Function *> &);
64
65// Some instructions need to have their users tracked. Instructions like
66// `add` require you to get the users of the Instruction* itself, other
67// instructions like `store` require you to get the users of the first
68// operand. This function gets the "proper" value to track for each
69// type of instruction we support.
70static Optional<Value *> getTargetValue(Instruction *);
71
72// There are certain instructions (i.e. FenceInst, etc.) that we ignore.
73// This notes that we should ignore those.
74static bool hasUsefulEdges(Instruction *);
75
Hal Finkel1ae325f2014-09-02 23:50:01 +000076const StratifiedIndex StratifiedLink::SetSentinel =
77 std::numeric_limits<StratifiedIndex>::max();
78
Hal Finkel7529c552014-09-02 21:43:13 +000079namespace {
80// StratifiedInfo Attribute things.
81typedef unsigned StratifiedAttr;
Hal Finkel7d7087c2014-09-02 22:13:00 +000082LLVM_CONSTEXPR unsigned MaxStratifiedAttrIndex = NumStratifiedAttrs;
83LLVM_CONSTEXPR unsigned AttrAllIndex = 0;
84LLVM_CONSTEXPR unsigned AttrGlobalIndex = 1;
85LLVM_CONSTEXPR unsigned AttrFirstArgIndex = 2;
86LLVM_CONSTEXPR unsigned AttrLastArgIndex = MaxStratifiedAttrIndex;
87LLVM_CONSTEXPR unsigned AttrMaxNumArgs = AttrLastArgIndex - AttrFirstArgIndex;
Hal Finkel7529c552014-09-02 21:43:13 +000088
Hal Finkel7d7087c2014-09-02 22:13:00 +000089LLVM_CONSTEXPR StratifiedAttr AttrNone = 0;
90LLVM_CONSTEXPR StratifiedAttr AttrAll = ~AttrNone;
Hal Finkel7529c552014-09-02 21:43:13 +000091
92// \brief StratifiedSets call for knowledge of "direction", so this is how we
93// represent that locally.
94enum class Level { Same, Above, Below };
95
96// \brief Edges can be one of four "weights" -- each weight must have an inverse
97// weight (Assign has Assign; Reference has Dereference).
98enum class EdgeType {
99 // The weight assigned when assigning from or to a value. For example, in:
100 // %b = getelementptr %a, 0
101 // ...The relationships are %b assign %a, and %a assign %b. This used to be
102 // two edges, but having a distinction bought us nothing.
103 Assign,
104
105 // The edge used when we have an edge going from some handle to a Value.
106 // Examples of this include:
107 // %b = load %a (%b Dereference %a)
108 // %b = extractelement %a, 0 (%a Dereference %b)
109 Dereference,
110
111 // The edge used when our edge goes from a value to a handle that may have
112 // contained it at some point. Examples:
113 // %b = load %a (%a Reference %b)
114 // %b = extractelement %a, 0 (%b Reference %a)
115 Reference
116};
117
118// \brief Encodes the notion of a "use"
119struct Edge {
120 // \brief Which value the edge is coming from
121 Value *From;
122
123 // \brief Which value the edge is pointing to
124 Value *To;
125
126 // \brief Edge weight
127 EdgeType Weight;
128
129 // \brief Whether we aliased any external values along the way that may be
130 // invisible to the analysis (i.e. landingpad for exceptions, calls for
131 // interprocedural analysis, etc.)
132 StratifiedAttrs AdditionalAttrs;
133
134 Edge(Value *From, Value *To, EdgeType W, StratifiedAttrs A)
135 : From(From), To(To), Weight(W), AdditionalAttrs(A) {}
136};
137
138// \brief Information we have about a function and would like to keep around
139struct FunctionInfo {
140 StratifiedSets<Value *> Sets;
141 // Lots of functions have < 4 returns. Adjust as necessary.
142 SmallVector<Value *, 4> ReturnedValues;
Hal Finkel85f26922014-09-03 00:06:47 +0000143
144 FunctionInfo(StratifiedSets<Value *> &&S,
145 SmallVector<Value *, 4> &&RV)
146 : Sets(std::move(S)), ReturnedValues(std::move(RV)) {}
Hal Finkel7529c552014-09-02 21:43:13 +0000147};
148
149struct CFLAliasAnalysis;
150
151struct FunctionHandle : public CallbackVH {
152 FunctionHandle(Function *Fn, CFLAliasAnalysis *CFLAA)
153 : CallbackVH(Fn), CFLAA(CFLAA) {
154 assert(Fn != nullptr);
155 assert(CFLAA != nullptr);
156 }
157
158 virtual ~FunctionHandle() {}
159
David Blaikie711cd9c2014-11-14 19:06:36 +0000160 void deleted() override { removeSelfFromCache(); }
161 void allUsesReplacedWith(Value *) override { removeSelfFromCache(); }
Hal Finkel7529c552014-09-02 21:43:13 +0000162
163private:
164 CFLAliasAnalysis *CFLAA;
165
166 void removeSelfFromCache();
167};
168
169struct CFLAliasAnalysis : public ImmutablePass, public AliasAnalysis {
170private:
171 /// \brief Cached mapping of Functions to their StratifiedSets.
172 /// If a function's sets are currently being built, it is marked
173 /// in the cache as an Optional without a value. This way, if we
174 /// have any kind of recursion, it is discernable from a function
175 /// that simply has empty sets.
176 DenseMap<Function *, Optional<FunctionInfo>> Cache;
177 std::forward_list<FunctionHandle> Handles;
178
179public:
180 static char ID;
181
182 CFLAliasAnalysis() : ImmutablePass(ID) {
183 initializeCFLAliasAnalysisPass(*PassRegistry::getPassRegistry());
184 }
185
186 virtual ~CFLAliasAnalysis() {}
187
Argyrios Kyrtzidis0b9f5502014-10-01 21:00:44 +0000188 void getAnalysisUsage(AnalysisUsage &AU) const override {
Hal Finkel7529c552014-09-02 21:43:13 +0000189 AliasAnalysis::getAnalysisUsage(AU);
190 }
191
192 void *getAdjustedAnalysisPointer(const void *ID) override {
193 if (ID == &AliasAnalysis::ID)
194 return (AliasAnalysis *)this;
195 return this;
196 }
197
198 /// \brief Inserts the given Function into the cache.
199 void scan(Function *Fn);
200
201 void evict(Function *Fn) { Cache.erase(Fn); }
202
203 /// \brief Ensures that the given function is available in the cache.
204 /// Returns the appropriate entry from the cache.
205 const Optional<FunctionInfo> &ensureCached(Function *Fn) {
206 auto Iter = Cache.find(Fn);
207 if (Iter == Cache.end()) {
208 scan(Fn);
209 Iter = Cache.find(Fn);
210 assert(Iter != Cache.end());
211 assert(Iter->second.hasValue());
212 }
213 return Iter->second;
214 }
215
216 AliasResult query(const Location &LocA, const Location &LocB);
217
218 AliasResult alias(const Location &LocA, const Location &LocB) override {
219 if (LocA.Ptr == LocB.Ptr) {
220 if (LocA.Size == LocB.Size) {
221 return MustAlias;
222 } else {
223 return PartialAlias;
224 }
225 }
226
227 // Comparisons between global variables and other constants should be
228 // handled by BasicAA.
229 if (isa<Constant>(LocA.Ptr) && isa<Constant>(LocB.Ptr)) {
Daniel Berlin8f10e382015-01-26 17:30:39 +0000230 return AliasAnalysis::alias(LocA, LocB);
Hal Finkel7529c552014-09-02 21:43:13 +0000231 }
Daniel Berlin8f10e382015-01-26 17:30:39 +0000232 AliasResult QueryResult = query(LocA, LocB);
233 if (QueryResult == MayAlias)
234 return AliasAnalysis::alias(LocA, LocB);
Hal Finkel7529c552014-09-02 21:43:13 +0000235
Daniel Berlin8f10e382015-01-26 17:30:39 +0000236 return QueryResult;
Hal Finkel7529c552014-09-02 21:43:13 +0000237 }
238
239 void initializePass() override { InitializeAliasAnalysis(this); }
240};
241
242void FunctionHandle::removeSelfFromCache() {
243 assert(CFLAA != nullptr);
244 auto *Val = getValPtr();
245 CFLAA->evict(cast<Function>(Val));
246 setValPtr(nullptr);
247}
248
249// \brief Gets the edges our graph should have, based on an Instruction*
250class GetEdgesVisitor : public InstVisitor<GetEdgesVisitor, void> {
251 CFLAliasAnalysis &AA;
252 SmallVectorImpl<Edge> &Output;
253
254public:
255 GetEdgesVisitor(CFLAliasAnalysis &AA, SmallVectorImpl<Edge> &Output)
256 : AA(AA), Output(Output) {}
257
258 void visitInstruction(Instruction &) {
259 llvm_unreachable("Unsupported instruction encountered");
260 }
261
262 void visitCastInst(CastInst &Inst) {
Hal Finkel8d1590d2014-09-02 22:52:30 +0000263 Output.push_back(Edge(&Inst, Inst.getOperand(0), EdgeType::Assign,
264 AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000265 }
266
267 void visitBinaryOperator(BinaryOperator &Inst) {
268 auto *Op1 = Inst.getOperand(0);
269 auto *Op2 = Inst.getOperand(1);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000270 Output.push_back(Edge(&Inst, Op1, EdgeType::Assign, AttrNone));
271 Output.push_back(Edge(&Inst, Op2, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000272 }
273
274 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
275 auto *Ptr = Inst.getPointerOperand();
276 auto *Val = Inst.getNewValOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000277 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000278 }
279
280 void visitAtomicRMWInst(AtomicRMWInst &Inst) {
281 auto *Ptr = Inst.getPointerOperand();
282 auto *Val = Inst.getValOperand();
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
286 void visitPHINode(PHINode &Inst) {
287 for (unsigned I = 0, E = Inst.getNumIncomingValues(); I != E; ++I) {
288 Value *Val = Inst.getIncomingValue(I);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000289 Output.push_back(Edge(&Inst, Val, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000290 }
291 }
292
293 void visitGetElementPtrInst(GetElementPtrInst &Inst) {
294 auto *Op = Inst.getPointerOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000295 Output.push_back(Edge(&Inst, Op, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000296 for (auto I = Inst.idx_begin(), E = Inst.idx_end(); I != E; ++I)
Hal Finkel8d1590d2014-09-02 22:52:30 +0000297 Output.push_back(Edge(&Inst, *I, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000298 }
299
300 void visitSelectInst(SelectInst &Inst) {
Daniel Berlin16f7a522015-01-26 17:31:17 +0000301 // Condition is not processed here (The actual statement producing
302 // the condition result is processed elsewhere). For select, the
303 // condition is evaluated, but not loaded, stored, or assigned
304 // simply as a result of being the condition of a select.
305
Hal Finkel7529c552014-09-02 21:43:13 +0000306 auto *TrueVal = Inst.getTrueValue();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000307 Output.push_back(Edge(&Inst, TrueVal, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000308 auto *FalseVal = Inst.getFalseValue();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000309 Output.push_back(Edge(&Inst, FalseVal, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000310 }
311
312 void visitAllocaInst(AllocaInst &) {}
313
314 void visitLoadInst(LoadInst &Inst) {
315 auto *Ptr = Inst.getPointerOperand();
316 auto *Val = &Inst;
Hal Finkel8d1590d2014-09-02 22:52:30 +0000317 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000318 }
319
320 void visitStoreInst(StoreInst &Inst) {
321 auto *Ptr = Inst.getPointerOperand();
322 auto *Val = Inst.getValueOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000323 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000324 }
325
Hal Finkeldb5f86a2014-10-14 20:51:26 +0000326 void visitVAArgInst(VAArgInst &Inst) {
327 // We can't fully model va_arg here. For *Ptr = Inst.getOperand(0), it does
328 // two things:
329 // 1. Loads a value from *((T*)*Ptr).
330 // 2. Increments (stores to) *Ptr by some target-specific amount.
331 // For now, we'll handle this like a landingpad instruction (by placing the
332 // result in its own group, and having that group alias externals).
333 auto *Val = &Inst;
334 Output.push_back(Edge(Val, Val, EdgeType::Assign, AttrAll));
335 }
336
Hal Finkel7529c552014-09-02 21:43:13 +0000337 static bool isFunctionExternal(Function *Fn) {
338 return Fn->isDeclaration() || !Fn->hasLocalLinkage();
339 }
340
341 // Gets whether the sets at Index1 above, below, or equal to the sets at
342 // Index2. Returns None if they are not in the same set chain.
343 static Optional<Level> getIndexRelation(const StratifiedSets<Value *> &Sets,
344 StratifiedIndex Index1,
345 StratifiedIndex Index2) {
346 if (Index1 == Index2)
347 return Level::Same;
348
349 const auto *Current = &Sets.getLink(Index1);
350 while (Current->hasBelow()) {
351 if (Current->Below == Index2)
352 return Level::Below;
353 Current = &Sets.getLink(Current->Below);
354 }
355
356 Current = &Sets.getLink(Index1);
357 while (Current->hasAbove()) {
358 if (Current->Above == Index2)
359 return Level::Above;
360 Current = &Sets.getLink(Current->Above);
361 }
362
363 return NoneType();
364 }
365
366 bool
367 tryInterproceduralAnalysis(const SmallVectorImpl<Function *> &Fns,
368 Value *FuncValue,
369 const iterator_range<User::op_iterator> &Args) {
Hal Finkelca616ac2014-09-02 23:29:48 +0000370 const unsigned ExpectedMaxArgs = 8;
371 const unsigned MaxSupportedArgs = 50;
Hal Finkel7529c552014-09-02 21:43:13 +0000372 assert(Fns.size() > 0);
373
374 // I put this here to give us an upper bound on time taken by IPA. Is it
375 // really (realistically) needed? Keep in mind that we do have an n^2 algo.
Hal Finkelca616ac2014-09-02 23:29:48 +0000376 if (std::distance(Args.begin(), Args.end()) > (int) MaxSupportedArgs)
Hal Finkel7529c552014-09-02 21:43:13 +0000377 return false;
378
379 // Exit early if we'll fail anyway
380 for (auto *Fn : Fns) {
381 if (isFunctionExternal(Fn) || Fn->isVarArg())
382 return false;
383 auto &MaybeInfo = AA.ensureCached(Fn);
384 if (!MaybeInfo.hasValue())
385 return false;
386 }
387
388 SmallVector<Value *, ExpectedMaxArgs> Arguments(Args.begin(), Args.end());
389 SmallVector<StratifiedInfo, ExpectedMaxArgs> Parameters;
390 for (auto *Fn : Fns) {
391 auto &Info = *AA.ensureCached(Fn);
392 auto &Sets = Info.Sets;
393 auto &RetVals = Info.ReturnedValues;
394
395 Parameters.clear();
396 for (auto &Param : Fn->args()) {
397 auto MaybeInfo = Sets.find(&Param);
398 // Did a new parameter somehow get added to the function/slip by?
399 if (!MaybeInfo.hasValue())
400 return false;
401 Parameters.push_back(*MaybeInfo);
402 }
403
404 // Adding an edge from argument -> return value for each parameter that
405 // may alias the return value
406 for (unsigned I = 0, E = Parameters.size(); I != E; ++I) {
407 auto &ParamInfo = Parameters[I];
408 auto &ArgVal = Arguments[I];
409 bool AddEdge = false;
410 StratifiedAttrs Externals;
411 for (unsigned X = 0, XE = RetVals.size(); X != XE; ++X) {
412 auto MaybeInfo = Sets.find(RetVals[X]);
413 if (!MaybeInfo.hasValue())
414 return false;
415
416 auto &RetInfo = *MaybeInfo;
417 auto RetAttrs = Sets.getLink(RetInfo.Index).Attrs;
418 auto ParamAttrs = Sets.getLink(ParamInfo.Index).Attrs;
419 auto MaybeRelation =
420 getIndexRelation(Sets, ParamInfo.Index, RetInfo.Index);
421 if (MaybeRelation.hasValue()) {
422 AddEdge = true;
423 Externals |= RetAttrs | ParamAttrs;
424 }
425 }
426 if (AddEdge)
Hal Finkelca616ac2014-09-02 23:29:48 +0000427 Output.push_back(Edge(FuncValue, ArgVal, EdgeType::Assign,
428 StratifiedAttrs().flip()));
Hal Finkel7529c552014-09-02 21:43:13 +0000429 }
430
431 if (Parameters.size() != Arguments.size())
432 return false;
433
434 // Adding edges between arguments for arguments that may end up aliasing
435 // each other. This is necessary for functions such as
436 // void foo(int** a, int** b) { *a = *b; }
437 // (Technically, the proper sets for this would be those below
438 // Arguments[I] and Arguments[X], but our algorithm will produce
439 // extremely similar, and equally correct, results either way)
440 for (unsigned I = 0, E = Arguments.size(); I != E; ++I) {
441 auto &MainVal = Arguments[I];
442 auto &MainInfo = Parameters[I];
443 auto &MainAttrs = Sets.getLink(MainInfo.Index).Attrs;
444 for (unsigned X = I + 1; X != E; ++X) {
445 auto &SubInfo = Parameters[X];
446 auto &SubVal = Arguments[X];
447 auto &SubAttrs = Sets.getLink(SubInfo.Index).Attrs;
448 auto MaybeRelation =
449 getIndexRelation(Sets, MainInfo.Index, SubInfo.Index);
450
451 if (!MaybeRelation.hasValue())
452 continue;
453
454 auto NewAttrs = SubAttrs | MainAttrs;
Hal Finkel8d1590d2014-09-02 22:52:30 +0000455 Output.push_back(Edge(MainVal, SubVal, EdgeType::Assign, NewAttrs));
Hal Finkel7529c552014-09-02 21:43:13 +0000456 }
457 }
458 }
459 return true;
460 }
461
462 template <typename InstT> void visitCallLikeInst(InstT &Inst) {
463 SmallVector<Function *, 4> Targets;
464 if (getPossibleTargets(&Inst, Targets)) {
465 if (tryInterproceduralAnalysis(Targets, &Inst, Inst.arg_operands()))
466 return;
467 // Cleanup from interprocedural analysis
468 Output.clear();
469 }
470
471 for (Value *V : Inst.arg_operands())
Hal Finkel8d1590d2014-09-02 22:52:30 +0000472 Output.push_back(Edge(&Inst, V, EdgeType::Assign, AttrAll));
Hal Finkel7529c552014-09-02 21:43:13 +0000473 }
474
475 void visitCallInst(CallInst &Inst) { visitCallLikeInst(Inst); }
476
477 void visitInvokeInst(InvokeInst &Inst) { visitCallLikeInst(Inst); }
478
479 // Because vectors/aggregates are immutable and unaddressable,
480 // there's nothing we can do to coax a value out of them, other
481 // than calling Extract{Element,Value}. We can effectively treat
482 // them as pointers to arbitrary memory locations we can store in
483 // and load from.
484 void visitExtractElementInst(ExtractElementInst &Inst) {
485 auto *Ptr = Inst.getVectorOperand();
486 auto *Val = &Inst;
Hal Finkel8d1590d2014-09-02 22:52:30 +0000487 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000488 }
489
490 void visitInsertElementInst(InsertElementInst &Inst) {
491 auto *Vec = Inst.getOperand(0);
492 auto *Val = Inst.getOperand(1);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000493 Output.push_back(Edge(&Inst, Vec, EdgeType::Assign, AttrNone));
494 Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000495 }
496
497 void visitLandingPadInst(LandingPadInst &Inst) {
498 // Exceptions come from "nowhere", from our analysis' perspective.
499 // So we place the instruction its own group, noting that said group may
500 // alias externals
Hal Finkel8d1590d2014-09-02 22:52:30 +0000501 Output.push_back(Edge(&Inst, &Inst, EdgeType::Assign, AttrAll));
Hal Finkel7529c552014-09-02 21:43:13 +0000502 }
503
504 void visitInsertValueInst(InsertValueInst &Inst) {
505 auto *Agg = Inst.getOperand(0);
506 auto *Val = Inst.getOperand(1);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000507 Output.push_back(Edge(&Inst, Agg, EdgeType::Assign, AttrNone));
508 Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000509 }
510
511 void visitExtractValueInst(ExtractValueInst &Inst) {
512 auto *Ptr = Inst.getAggregateOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000513 Output.push_back(Edge(&Inst, Ptr, EdgeType::Reference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000514 }
515
516 void visitShuffleVectorInst(ShuffleVectorInst &Inst) {
517 auto *From1 = Inst.getOperand(0);
518 auto *From2 = Inst.getOperand(1);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000519 Output.push_back(Edge(&Inst, From1, EdgeType::Assign, AttrNone));
520 Output.push_back(Edge(&Inst, From2, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000521 }
522};
523
524// For a given instruction, we need to know which Value* to get the
525// users of in order to build our graph. In some cases (i.e. add),
526// we simply need the Instruction*. In other cases (i.e. store),
527// finding the users of the Instruction* is useless; we need to find
528// the users of the first operand. This handles determining which
529// value to follow for us.
530//
531// Note: we *need* to keep this in sync with GetEdgesVisitor. Add
532// something to GetEdgesVisitor, add it here -- remove something from
533// GetEdgesVisitor, remove it here.
534class GetTargetValueVisitor
535 : public InstVisitor<GetTargetValueVisitor, Value *> {
536public:
537 Value *visitInstruction(Instruction &Inst) { return &Inst; }
538
539 Value *visitStoreInst(StoreInst &Inst) { return Inst.getPointerOperand(); }
540
541 Value *visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
542 return Inst.getPointerOperand();
543 }
544
545 Value *visitAtomicRMWInst(AtomicRMWInst &Inst) {
546 return Inst.getPointerOperand();
547 }
548
549 Value *visitInsertElementInst(InsertElementInst &Inst) {
550 return Inst.getOperand(0);
551 }
552
553 Value *visitInsertValueInst(InsertValueInst &Inst) {
554 return Inst.getAggregateOperand();
555 }
556};
557
558// Set building requires a weighted bidirectional graph.
559template <typename EdgeTypeT> class WeightedBidirectionalGraph {
560public:
561 typedef std::size_t Node;
562
563private:
Hal Finkelca616ac2014-09-02 23:29:48 +0000564 const static Node StartNode = Node(0);
Hal Finkel7529c552014-09-02 21:43:13 +0000565
566 struct Edge {
567 EdgeTypeT Weight;
568 Node Other;
569
Hal Finkelca616ac2014-09-02 23:29:48 +0000570 Edge(const EdgeTypeT &W, const Node &N)
571 : Weight(W), Other(N) {}
572
Hal Finkel7529c552014-09-02 21:43:13 +0000573 bool operator==(const Edge &E) const {
574 return Weight == E.Weight && Other == E.Other;
575 }
576
577 bool operator!=(const Edge &E) const { return !operator==(E); }
578 };
579
580 struct NodeImpl {
581 std::vector<Edge> Edges;
582 };
583
584 std::vector<NodeImpl> NodeImpls;
585
586 bool inbounds(Node NodeIndex) const { return NodeIndex < NodeImpls.size(); }
587
588 const NodeImpl &getNode(Node N) const { return NodeImpls[N]; }
589 NodeImpl &getNode(Node N) { return NodeImpls[N]; }
590
591public:
592 // ----- Various Edge iterators for the graph ----- //
593
594 // \brief Iterator for edges. Because this graph is bidirected, we don't
595 // allow modificaiton of the edges using this iterator. Additionally, the
596 // iterator becomes invalid if you add edges to or from the node you're
597 // getting the edges of.
598 struct EdgeIterator : public std::iterator<std::forward_iterator_tag,
599 std::tuple<EdgeTypeT, Node *>> {
600 EdgeIterator(const typename std::vector<Edge>::const_iterator &Iter)
601 : Current(Iter) {}
602
603 EdgeIterator(NodeImpl &Impl) : Current(Impl.begin()) {}
604
605 EdgeIterator &operator++() {
606 ++Current;
607 return *this;
608 }
609
610 EdgeIterator operator++(int) {
611 EdgeIterator Copy(Current);
612 operator++();
613 return Copy;
614 }
615
616 std::tuple<EdgeTypeT, Node> &operator*() {
617 Store = std::make_tuple(Current->Weight, Current->Other);
618 return Store;
619 }
620
621 bool operator==(const EdgeIterator &Other) const {
622 return Current == Other.Current;
623 }
624
625 bool operator!=(const EdgeIterator &Other) const {
626 return !operator==(Other);
627 }
628
629 private:
630 typename std::vector<Edge>::const_iterator Current;
631 std::tuple<EdgeTypeT, Node> Store;
632 };
633
634 // Wrapper for EdgeIterator with begin()/end() calls.
635 struct EdgeIterable {
636 EdgeIterable(const std::vector<Edge> &Edges)
637 : BeginIter(Edges.begin()), EndIter(Edges.end()) {}
638
639 EdgeIterator begin() { return EdgeIterator(BeginIter); }
640
641 EdgeIterator end() { return EdgeIterator(EndIter); }
642
643 private:
644 typename std::vector<Edge>::const_iterator BeginIter;
645 typename std::vector<Edge>::const_iterator EndIter;
646 };
647
648 // ----- Actual graph-related things ----- //
649
Hal Finkelca616ac2014-09-02 23:29:48 +0000650 WeightedBidirectionalGraph() {}
Hal Finkel7529c552014-09-02 21:43:13 +0000651
652 WeightedBidirectionalGraph(WeightedBidirectionalGraph<EdgeTypeT> &&Other)
653 : NodeImpls(std::move(Other.NodeImpls)) {}
654
655 WeightedBidirectionalGraph<EdgeTypeT> &
656 operator=(WeightedBidirectionalGraph<EdgeTypeT> &&Other) {
657 NodeImpls = std::move(Other.NodeImpls);
658 return *this;
659 }
660
661 Node addNode() {
662 auto Index = NodeImpls.size();
663 auto NewNode = Node(Index);
664 NodeImpls.push_back(NodeImpl());
665 return NewNode;
666 }
667
668 void addEdge(Node From, Node To, const EdgeTypeT &Weight,
669 const EdgeTypeT &ReverseWeight) {
670 assert(inbounds(From));
671 assert(inbounds(To));
672 auto &FromNode = getNode(From);
673 auto &ToNode = getNode(To);
Hal Finkelca616ac2014-09-02 23:29:48 +0000674 FromNode.Edges.push_back(Edge(Weight, To));
675 ToNode.Edges.push_back(Edge(ReverseWeight, From));
Hal Finkel7529c552014-09-02 21:43:13 +0000676 }
677
678 EdgeIterable edgesFor(const Node &N) const {
679 const auto &Node = getNode(N);
680 return EdgeIterable(Node.Edges);
681 }
682
683 bool empty() const { return NodeImpls.empty(); }
684 std::size_t size() const { return NodeImpls.size(); }
685
686 // \brief Gets an arbitrary node in the graph as a starting point for
687 // traversal.
688 Node getEntryNode() {
689 assert(inbounds(StartNode));
690 return StartNode;
691 }
692};
693
694typedef WeightedBidirectionalGraph<std::pair<EdgeType, StratifiedAttrs>> GraphT;
695typedef DenseMap<Value *, GraphT::Node> NodeMapT;
696}
697
698// -- Setting up/registering CFLAA pass -- //
699char CFLAliasAnalysis::ID = 0;
700
701INITIALIZE_AG_PASS(CFLAliasAnalysis, AliasAnalysis, "cfl-aa",
702 "CFL-Based AA implementation", false, true, false)
703
704ImmutablePass *llvm::createCFLAliasAnalysisPass() {
705 return new CFLAliasAnalysis();
706}
707
708//===----------------------------------------------------------------------===//
709// Function declarations that require types defined in the namespace above
710//===----------------------------------------------------------------------===//
711
712// Given an argument number, returns the appropriate Attr index to set.
713static StratifiedAttr argNumberToAttrIndex(StratifiedAttr);
714
715// Given a Value, potentially return which AttrIndex it maps to.
716static Optional<StratifiedAttr> valueToAttrIndex(Value *Val);
717
718// Gets the inverse of a given EdgeType.
719static EdgeType flipWeight(EdgeType);
720
721// Gets edges of the given Instruction*, writing them to the SmallVector*.
722static void argsToEdges(CFLAliasAnalysis &, Instruction *,
723 SmallVectorImpl<Edge> &);
724
725// Gets the "Level" that one should travel in StratifiedSets
726// given an EdgeType.
727static Level directionOfEdgeType(EdgeType);
728
729// Builds the graph needed for constructing the StratifiedSets for the
730// given function
731static void buildGraphFrom(CFLAliasAnalysis &, Function *,
732 SmallVectorImpl<Value *> &, NodeMapT &, GraphT &);
733
734// Builds the graph + StratifiedSets for a function.
735static FunctionInfo buildSetsFrom(CFLAliasAnalysis &, Function *);
736
737static Optional<Function *> parentFunctionOfValue(Value *Val) {
738 if (auto *Inst = dyn_cast<Instruction>(Val)) {
739 auto *Bb = Inst->getParent();
740 return Bb->getParent();
741 }
742
743 if (auto *Arg = dyn_cast<Argument>(Val))
744 return Arg->getParent();
745 return NoneType();
746}
747
748template <typename Inst>
749static bool getPossibleTargets(Inst *Call,
750 SmallVectorImpl<Function *> &Output) {
751 if (auto *Fn = Call->getCalledFunction()) {
752 Output.push_back(Fn);
753 return true;
754 }
755
756 // TODO: If the call is indirect, we might be able to enumerate all potential
757 // targets of the call and return them, rather than just failing.
758 return false;
759}
760
761static Optional<Value *> getTargetValue(Instruction *Inst) {
762 GetTargetValueVisitor V;
763 return V.visit(Inst);
764}
765
766static bool hasUsefulEdges(Instruction *Inst) {
767 bool IsNonInvokeTerminator =
768 isa<TerminatorInst>(Inst) && !isa<InvokeInst>(Inst);
769 return !isa<CmpInst>(Inst) && !isa<FenceInst>(Inst) && !IsNonInvokeTerminator;
770}
771
772static Optional<StratifiedAttr> valueToAttrIndex(Value *Val) {
773 if (isa<GlobalValue>(Val))
774 return AttrGlobalIndex;
775
776 if (auto *Arg = dyn_cast<Argument>(Val))
Daniel Berlin16f7a522015-01-26 17:31:17 +0000777 // Only pointer arguments should have the argument attribute,
778 // because things can't escape through scalars without us seeing a
779 // cast, and thus, interaction with them doesn't matter.
780 if (!Arg->hasNoAliasAttr() && Arg->getType()->isPointerTy())
Hal Finkel7529c552014-09-02 21:43:13 +0000781 return argNumberToAttrIndex(Arg->getArgNo());
782 return NoneType();
783}
784
785static StratifiedAttr argNumberToAttrIndex(unsigned ArgNum) {
George Burgess IV3c898c22015-01-21 16:37:21 +0000786 if (ArgNum >= AttrMaxNumArgs)
Hal Finkel7529c552014-09-02 21:43:13 +0000787 return AttrAllIndex;
788 return ArgNum + AttrFirstArgIndex;
789}
790
791static EdgeType flipWeight(EdgeType Initial) {
792 switch (Initial) {
793 case EdgeType::Assign:
794 return EdgeType::Assign;
795 case EdgeType::Dereference:
796 return EdgeType::Reference;
797 case EdgeType::Reference:
798 return EdgeType::Dereference;
799 }
800 llvm_unreachable("Incomplete coverage of EdgeType enum");
801}
802
803static void argsToEdges(CFLAliasAnalysis &Analysis, Instruction *Inst,
804 SmallVectorImpl<Edge> &Output) {
805 GetEdgesVisitor v(Analysis, Output);
806 v.visit(Inst);
807}
808
809static Level directionOfEdgeType(EdgeType Weight) {
810 switch (Weight) {
811 case EdgeType::Reference:
812 return Level::Above;
813 case EdgeType::Dereference:
814 return Level::Below;
815 case EdgeType::Assign:
816 return Level::Same;
817 }
818 llvm_unreachable("Incomplete switch coverage");
819}
820
821// Aside: We may remove graph construction entirely, because it doesn't really
822// buy us much that we don't already have. I'd like to add interprocedural
823// analysis prior to this however, in case that somehow requires the graph
824// produced by this for efficient execution
825static void buildGraphFrom(CFLAliasAnalysis &Analysis, Function *Fn,
826 SmallVectorImpl<Value *> &ReturnedValues,
827 NodeMapT &Map, GraphT &Graph) {
828 const auto findOrInsertNode = [&Map, &Graph](Value *Val) {
829 auto Pair = Map.insert(std::make_pair(Val, GraphT::Node()));
830 auto &Iter = Pair.first;
831 if (Pair.second) {
832 auto NewNode = Graph.addNode();
833 Iter->second = NewNode;
834 }
835 return Iter->second;
836 };
837
838 SmallVector<Edge, 8> Edges;
839 for (auto &Bb : Fn->getBasicBlockList()) {
840 for (auto &Inst : Bb.getInstList()) {
841 // We don't want the edges of most "return" instructions, but we *do* want
842 // to know what can be returned.
843 if (auto *Ret = dyn_cast<ReturnInst>(&Inst))
844 ReturnedValues.push_back(Ret);
845
846 if (!hasUsefulEdges(&Inst))
847 continue;
848
849 Edges.clear();
850 argsToEdges(Analysis, &Inst, Edges);
851
852 // In the case of an unused alloca (or similar), edges may be empty. Note
853 // that it exists so we can potentially answer NoAlias.
854 if (Edges.empty()) {
855 auto MaybeVal = getTargetValue(&Inst);
856 assert(MaybeVal.hasValue());
857 auto *Target = *MaybeVal;
858 findOrInsertNode(Target);
859 continue;
860 }
861
862 for (const Edge &E : Edges) {
863 auto To = findOrInsertNode(E.To);
864 auto From = findOrInsertNode(E.From);
865 auto FlippedWeight = flipWeight(E.Weight);
866 auto Attrs = E.AdditionalAttrs;
Hal Finkel1ae325f2014-09-02 23:50:01 +0000867 Graph.addEdge(From, To, std::make_pair(E.Weight, Attrs),
868 std::make_pair(FlippedWeight, Attrs));
Hal Finkel7529c552014-09-02 21:43:13 +0000869 }
870 }
871 }
872}
873
874static FunctionInfo buildSetsFrom(CFLAliasAnalysis &Analysis, Function *Fn) {
875 NodeMapT Map;
876 GraphT Graph;
877 SmallVector<Value *, 4> ReturnedValues;
878
879 buildGraphFrom(Analysis, Fn, ReturnedValues, Map, Graph);
880
881 DenseMap<GraphT::Node, Value *> NodeValueMap;
882 NodeValueMap.resize(Map.size());
883 for (const auto &Pair : Map)
Hal Finkel8d1590d2014-09-02 22:52:30 +0000884 NodeValueMap.insert(std::make_pair(Pair.second, Pair.first));
Hal Finkel7529c552014-09-02 21:43:13 +0000885
886 const auto findValueOrDie = [&NodeValueMap](GraphT::Node Node) {
887 auto ValIter = NodeValueMap.find(Node);
888 assert(ValIter != NodeValueMap.end());
889 return ValIter->second;
890 };
891
892 StratifiedSetsBuilder<Value *> Builder;
893
894 SmallVector<GraphT::Node, 16> Worklist;
895 for (auto &Pair : Map) {
896 Worklist.clear();
897
898 auto *Value = Pair.first;
899 Builder.add(Value);
900 auto InitialNode = Pair.second;
901 Worklist.push_back(InitialNode);
902 while (!Worklist.empty()) {
903 auto Node = Worklist.pop_back_val();
904 auto *CurValue = findValueOrDie(Node);
905 if (isa<Constant>(CurValue) && !isa<GlobalValue>(CurValue))
906 continue;
907
908 for (const auto &EdgeTuple : Graph.edgesFor(Node)) {
909 auto Weight = std::get<0>(EdgeTuple);
910 auto Label = Weight.first;
911 auto &OtherNode = std::get<1>(EdgeTuple);
912 auto *OtherValue = findValueOrDie(OtherNode);
913
914 if (isa<Constant>(OtherValue) && !isa<GlobalValue>(OtherValue))
915 continue;
916
917 bool Added;
918 switch (directionOfEdgeType(Label)) {
919 case Level::Above:
920 Added = Builder.addAbove(CurValue, OtherValue);
921 break;
922 case Level::Below:
923 Added = Builder.addBelow(CurValue, OtherValue);
924 break;
925 case Level::Same:
926 Added = Builder.addWith(CurValue, OtherValue);
927 break;
928 }
929
930 if (Added) {
931 auto Aliasing = Weight.second;
932 if (auto MaybeCurIndex = valueToAttrIndex(CurValue))
933 Aliasing.set(*MaybeCurIndex);
934 if (auto MaybeOtherIndex = valueToAttrIndex(OtherValue))
935 Aliasing.set(*MaybeOtherIndex);
936 Builder.noteAttributes(CurValue, Aliasing);
937 Builder.noteAttributes(OtherValue, Aliasing);
938 Worklist.push_back(OtherNode);
939 }
940 }
941 }
942 }
943
944 // There are times when we end up with parameters not in our graph (i.e. if
945 // it's only used as the condition of a branch). Other bits of code depend on
946 // things that were present during construction being present in the graph.
947 // So, we add all present arguments here.
948 for (auto &Arg : Fn->args()) {
949 Builder.add(&Arg);
950 }
951
Hal Finkel85f26922014-09-03 00:06:47 +0000952 return FunctionInfo(Builder.build(), std::move(ReturnedValues));
Hal Finkel7529c552014-09-02 21:43:13 +0000953}
954
955void CFLAliasAnalysis::scan(Function *Fn) {
Hal Finkel8d1590d2014-09-02 22:52:30 +0000956 auto InsertPair = Cache.insert(std::make_pair(Fn, Optional<FunctionInfo>()));
Hal Finkel7529c552014-09-02 21:43:13 +0000957 (void)InsertPair;
958 assert(InsertPair.second &&
959 "Trying to scan a function that has already been cached");
960
961 FunctionInfo Info(buildSetsFrom(*this, Fn));
962 Cache[Fn] = std::move(Info);
963 Handles.push_front(FunctionHandle(Fn, this));
964}
965
966AliasAnalysis::AliasResult
967CFLAliasAnalysis::query(const AliasAnalysis::Location &LocA,
968 const AliasAnalysis::Location &LocB) {
969 auto *ValA = const_cast<Value *>(LocA.Ptr);
970 auto *ValB = const_cast<Value *>(LocB.Ptr);
971
972 Function *Fn = nullptr;
973 auto MaybeFnA = parentFunctionOfValue(ValA);
974 auto MaybeFnB = parentFunctionOfValue(ValB);
975 if (!MaybeFnA.hasValue() && !MaybeFnB.hasValue()) {
976 llvm_unreachable("Don't know how to extract the parent function "
977 "from values A or B");
978 }
979
980 if (MaybeFnA.hasValue()) {
981 Fn = *MaybeFnA;
982 assert((!MaybeFnB.hasValue() || *MaybeFnB == *MaybeFnA) &&
983 "Interprocedural queries not supported");
984 } else {
985 Fn = *MaybeFnB;
986 }
987
988 assert(Fn != nullptr);
989 auto &MaybeInfo = ensureCached(Fn);
990 assert(MaybeInfo.hasValue());
991
992 auto &Sets = MaybeInfo->Sets;
993 auto MaybeA = Sets.find(ValA);
994 if (!MaybeA.hasValue())
995 return AliasAnalysis::MayAlias;
996
997 auto MaybeB = Sets.find(ValB);
998 if (!MaybeB.hasValue())
999 return AliasAnalysis::MayAlias;
1000
1001 auto SetA = *MaybeA;
1002 auto SetB = *MaybeB;
Hal Finkel7529c552014-09-02 21:43:13 +00001003 auto AttrsA = Sets.getLink(SetA.Index).Attrs;
1004 auto AttrsB = Sets.getLink(SetB.Index).Attrs;
Hal Finkel8eae3ad2014-10-06 14:42:56 +00001005 // Stratified set attributes are used as markets to signify whether a member
1006 // of a StratifiedSet (or a member of a set above the current set) has
1007 // interacted with either arguments or globals. "Interacted with" meaning
1008 // its value may be different depending on the value of an argument or
1009 // global. The thought behind this is that, because arguments and globals
1010 // may alias each other, if AttrsA and AttrsB have touched args/globals,
1011 // we must conservatively say that they alias. However, if at least one of
1012 // the sets has no values that could legally be altered by changing the value
1013 // of an argument or global, then we don't have to be as conservative.
1014 if (AttrsA.any() && AttrsB.any())
1015 return AliasAnalysis::MayAlias;
Hal Finkel7529c552014-09-02 21:43:13 +00001016
Daniel Berlin16f7a522015-01-26 17:31:17 +00001017 // We currently unify things even if the accesses to them may not be in
1018 // bounds, so we can't return partial alias here because we don't
1019 // know whether the pointer is really within the object or not.
1020 // IE Given an out of bounds GEP and an alloca'd pointer, we may
1021 // unify the two. We can't return partial alias for this case.
1022 // Since we do not currently track enough information to
1023 // differentiate
1024
1025 if (SetA.Index == SetB.Index)
1026 return AliasAnalysis::MayAlias;
1027
Hal Finkel7529c552014-09-02 21:43:13 +00001028 return AliasAnalysis::NoAlias;
1029}