blob: e942529176d84e8b6752e5cb4c8b78791ce019d6 [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"
32#include "llvm/Analysis/Passes.h"
33#include "llvm/ADT/BitVector.h"
34#include "llvm/ADT/DenseMap.h"
35#include "llvm/ADT/Optional.h"
36#include "llvm/ADT/None.h"
37#include "llvm/Analysis/AliasAnalysis.h"
38#include "llvm/IR/Constants.h"
39#include "llvm/IR/Function.h"
40#include "llvm/IR/Instructions.h"
41#include "llvm/IR/InstVisitor.h"
42#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
76namespace {
77// StratifiedInfo Attribute things.
78typedef unsigned StratifiedAttr;
Hal Finkel7d7087c2014-09-02 22:13:00 +000079LLVM_CONSTEXPR unsigned MaxStratifiedAttrIndex = NumStratifiedAttrs;
80LLVM_CONSTEXPR unsigned AttrAllIndex = 0;
81LLVM_CONSTEXPR unsigned AttrGlobalIndex = 1;
82LLVM_CONSTEXPR unsigned AttrFirstArgIndex = 2;
83LLVM_CONSTEXPR unsigned AttrLastArgIndex = MaxStratifiedAttrIndex;
84LLVM_CONSTEXPR unsigned AttrMaxNumArgs = AttrLastArgIndex - AttrFirstArgIndex;
Hal Finkel7529c552014-09-02 21:43:13 +000085
Hal Finkel7d7087c2014-09-02 22:13:00 +000086LLVM_CONSTEXPR StratifiedAttr AttrNone = 0;
87LLVM_CONSTEXPR StratifiedAttr AttrAll = ~AttrNone;
Hal Finkel7529c552014-09-02 21:43:13 +000088
89// \brief StratifiedSets call for knowledge of "direction", so this is how we
90// represent that locally.
91enum class Level { Same, Above, Below };
92
93// \brief Edges can be one of four "weights" -- each weight must have an inverse
94// weight (Assign has Assign; Reference has Dereference).
95enum class EdgeType {
96 // The weight assigned when assigning from or to a value. For example, in:
97 // %b = getelementptr %a, 0
98 // ...The relationships are %b assign %a, and %a assign %b. This used to be
99 // two edges, but having a distinction bought us nothing.
100 Assign,
101
102 // The edge used when we have an edge going from some handle to a Value.
103 // Examples of this include:
104 // %b = load %a (%b Dereference %a)
105 // %b = extractelement %a, 0 (%a Dereference %b)
106 Dereference,
107
108 // The edge used when our edge goes from a value to a handle that may have
109 // contained it at some point. Examples:
110 // %b = load %a (%a Reference %b)
111 // %b = extractelement %a, 0 (%b Reference %a)
112 Reference
113};
114
115// \brief Encodes the notion of a "use"
116struct Edge {
117 // \brief Which value the edge is coming from
118 Value *From;
119
120 // \brief Which value the edge is pointing to
121 Value *To;
122
123 // \brief Edge weight
124 EdgeType Weight;
125
126 // \brief Whether we aliased any external values along the way that may be
127 // invisible to the analysis (i.e. landingpad for exceptions, calls for
128 // interprocedural analysis, etc.)
129 StratifiedAttrs AdditionalAttrs;
130
131 Edge(Value *From, Value *To, EdgeType W, StratifiedAttrs A)
132 : From(From), To(To), Weight(W), AdditionalAttrs(A) {}
133};
134
135// \brief Information we have about a function and would like to keep around
136struct FunctionInfo {
137 StratifiedSets<Value *> Sets;
138 // Lots of functions have < 4 returns. Adjust as necessary.
139 SmallVector<Value *, 4> ReturnedValues;
140};
141
142struct CFLAliasAnalysis;
143
144struct FunctionHandle : public CallbackVH {
145 FunctionHandle(Function *Fn, CFLAliasAnalysis *CFLAA)
146 : CallbackVH(Fn), CFLAA(CFLAA) {
147 assert(Fn != nullptr);
148 assert(CFLAA != nullptr);
149 }
150
151 virtual ~FunctionHandle() {}
152
153 virtual void deleted() override { removeSelfFromCache(); }
154 virtual void allUsesReplacedWith(Value *) override { removeSelfFromCache(); }
155
156private:
157 CFLAliasAnalysis *CFLAA;
158
159 void removeSelfFromCache();
160};
161
162struct CFLAliasAnalysis : public ImmutablePass, public AliasAnalysis {
163private:
164 /// \brief Cached mapping of Functions to their StratifiedSets.
165 /// If a function's sets are currently being built, it is marked
166 /// in the cache as an Optional without a value. This way, if we
167 /// have any kind of recursion, it is discernable from a function
168 /// that simply has empty sets.
169 DenseMap<Function *, Optional<FunctionInfo>> Cache;
170 std::forward_list<FunctionHandle> Handles;
171
172public:
173 static char ID;
174
175 CFLAliasAnalysis() : ImmutablePass(ID) {
176 initializeCFLAliasAnalysisPass(*PassRegistry::getPassRegistry());
177 }
178
179 virtual ~CFLAliasAnalysis() {}
180
181 void getAnalysisUsage(AnalysisUsage &AU) const {
182 AliasAnalysis::getAnalysisUsage(AU);
183 }
184
185 void *getAdjustedAnalysisPointer(const void *ID) override {
186 if (ID == &AliasAnalysis::ID)
187 return (AliasAnalysis *)this;
188 return this;
189 }
190
191 /// \brief Inserts the given Function into the cache.
192 void scan(Function *Fn);
193
194 void evict(Function *Fn) { Cache.erase(Fn); }
195
196 /// \brief Ensures that the given function is available in the cache.
197 /// Returns the appropriate entry from the cache.
198 const Optional<FunctionInfo> &ensureCached(Function *Fn) {
199 auto Iter = Cache.find(Fn);
200 if (Iter == Cache.end()) {
201 scan(Fn);
202 Iter = Cache.find(Fn);
203 assert(Iter != Cache.end());
204 assert(Iter->second.hasValue());
205 }
206 return Iter->second;
207 }
208
209 AliasResult query(const Location &LocA, const Location &LocB);
210
211 AliasResult alias(const Location &LocA, const Location &LocB) override {
212 if (LocA.Ptr == LocB.Ptr) {
213 if (LocA.Size == LocB.Size) {
214 return MustAlias;
215 } else {
216 return PartialAlias;
217 }
218 }
219
220 // Comparisons between global variables and other constants should be
221 // handled by BasicAA.
222 if (isa<Constant>(LocA.Ptr) && isa<Constant>(LocB.Ptr)) {
223 return MayAlias;
224 }
225
226 return query(LocA, LocB);
227 }
228
229 void initializePass() override { InitializeAliasAnalysis(this); }
230};
231
232void FunctionHandle::removeSelfFromCache() {
233 assert(CFLAA != nullptr);
234 auto *Val = getValPtr();
235 CFLAA->evict(cast<Function>(Val));
236 setValPtr(nullptr);
237}
238
239// \brief Gets the edges our graph should have, based on an Instruction*
240class GetEdgesVisitor : public InstVisitor<GetEdgesVisitor, void> {
241 CFLAliasAnalysis &AA;
242 SmallVectorImpl<Edge> &Output;
243
244public:
245 GetEdgesVisitor(CFLAliasAnalysis &AA, SmallVectorImpl<Edge> &Output)
246 : AA(AA), Output(Output) {}
247
248 void visitInstruction(Instruction &) {
249 llvm_unreachable("Unsupported instruction encountered");
250 }
251
252 void visitCastInst(CastInst &Inst) {
Hal Finkel8d1590d2014-09-02 22:52:30 +0000253 Output.push_back(Edge(&Inst, Inst.getOperand(0), EdgeType::Assign,
254 AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000255 }
256
257 void visitBinaryOperator(BinaryOperator &Inst) {
258 auto *Op1 = Inst.getOperand(0);
259 auto *Op2 = Inst.getOperand(1);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000260 Output.push_back(Edge(&Inst, Op1, EdgeType::Assign, AttrNone));
261 Output.push_back(Edge(&Inst, Op2, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000262 }
263
264 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
265 auto *Ptr = Inst.getPointerOperand();
266 auto *Val = Inst.getNewValOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000267 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000268 }
269
270 void visitAtomicRMWInst(AtomicRMWInst &Inst) {
271 auto *Ptr = Inst.getPointerOperand();
272 auto *Val = Inst.getValOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000273 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000274 }
275
276 void visitPHINode(PHINode &Inst) {
277 for (unsigned I = 0, E = Inst.getNumIncomingValues(); I != E; ++I) {
278 Value *Val = Inst.getIncomingValue(I);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000279 Output.push_back(Edge(&Inst, Val, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000280 }
281 }
282
283 void visitGetElementPtrInst(GetElementPtrInst &Inst) {
284 auto *Op = Inst.getPointerOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000285 Output.push_back(Edge(&Inst, Op, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000286 for (auto I = Inst.idx_begin(), E = Inst.idx_end(); I != E; ++I)
Hal Finkel8d1590d2014-09-02 22:52:30 +0000287 Output.push_back(Edge(&Inst, *I, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000288 }
289
290 void visitSelectInst(SelectInst &Inst) {
291 auto *Condition = Inst.getCondition();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000292 Output.push_back(Edge(&Inst, Condition, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000293 auto *TrueVal = Inst.getTrueValue();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000294 Output.push_back(Edge(&Inst, TrueVal, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000295 auto *FalseVal = Inst.getFalseValue();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000296 Output.push_back(Edge(&Inst, FalseVal, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000297 }
298
299 void visitAllocaInst(AllocaInst &) {}
300
301 void visitLoadInst(LoadInst &Inst) {
302 auto *Ptr = Inst.getPointerOperand();
303 auto *Val = &Inst;
Hal Finkel8d1590d2014-09-02 22:52:30 +0000304 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000305 }
306
307 void visitStoreInst(StoreInst &Inst) {
308 auto *Ptr = Inst.getPointerOperand();
309 auto *Val = Inst.getValueOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000310 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000311 }
312
313 static bool isFunctionExternal(Function *Fn) {
314 return Fn->isDeclaration() || !Fn->hasLocalLinkage();
315 }
316
317 // Gets whether the sets at Index1 above, below, or equal to the sets at
318 // Index2. Returns None if they are not in the same set chain.
319 static Optional<Level> getIndexRelation(const StratifiedSets<Value *> &Sets,
320 StratifiedIndex Index1,
321 StratifiedIndex Index2) {
322 if (Index1 == Index2)
323 return Level::Same;
324
325 const auto *Current = &Sets.getLink(Index1);
326 while (Current->hasBelow()) {
327 if (Current->Below == Index2)
328 return Level::Below;
329 Current = &Sets.getLink(Current->Below);
330 }
331
332 Current = &Sets.getLink(Index1);
333 while (Current->hasAbove()) {
334 if (Current->Above == Index2)
335 return Level::Above;
336 Current = &Sets.getLink(Current->Above);
337 }
338
339 return NoneType();
340 }
341
342 bool
343 tryInterproceduralAnalysis(const SmallVectorImpl<Function *> &Fns,
344 Value *FuncValue,
345 const iterator_range<User::op_iterator> &Args) {
Hal Finkelca616ac2014-09-02 23:29:48 +0000346 const unsigned ExpectedMaxArgs = 8;
347 const unsigned MaxSupportedArgs = 50;
Hal Finkel7529c552014-09-02 21:43:13 +0000348 assert(Fns.size() > 0);
349
350 // I put this here to give us an upper bound on time taken by IPA. Is it
351 // really (realistically) needed? Keep in mind that we do have an n^2 algo.
Hal Finkelca616ac2014-09-02 23:29:48 +0000352 if (std::distance(Args.begin(), Args.end()) > (int) MaxSupportedArgs)
Hal Finkel7529c552014-09-02 21:43:13 +0000353 return false;
354
355 // Exit early if we'll fail anyway
356 for (auto *Fn : Fns) {
357 if (isFunctionExternal(Fn) || Fn->isVarArg())
358 return false;
359 auto &MaybeInfo = AA.ensureCached(Fn);
360 if (!MaybeInfo.hasValue())
361 return false;
362 }
363
364 SmallVector<Value *, ExpectedMaxArgs> Arguments(Args.begin(), Args.end());
365 SmallVector<StratifiedInfo, ExpectedMaxArgs> Parameters;
366 for (auto *Fn : Fns) {
367 auto &Info = *AA.ensureCached(Fn);
368 auto &Sets = Info.Sets;
369 auto &RetVals = Info.ReturnedValues;
370
371 Parameters.clear();
372 for (auto &Param : Fn->args()) {
373 auto MaybeInfo = Sets.find(&Param);
374 // Did a new parameter somehow get added to the function/slip by?
375 if (!MaybeInfo.hasValue())
376 return false;
377 Parameters.push_back(*MaybeInfo);
378 }
379
380 // Adding an edge from argument -> return value for each parameter that
381 // may alias the return value
382 for (unsigned I = 0, E = Parameters.size(); I != E; ++I) {
383 auto &ParamInfo = Parameters[I];
384 auto &ArgVal = Arguments[I];
385 bool AddEdge = false;
386 StratifiedAttrs Externals;
387 for (unsigned X = 0, XE = RetVals.size(); X != XE; ++X) {
388 auto MaybeInfo = Sets.find(RetVals[X]);
389 if (!MaybeInfo.hasValue())
390 return false;
391
392 auto &RetInfo = *MaybeInfo;
393 auto RetAttrs = Sets.getLink(RetInfo.Index).Attrs;
394 auto ParamAttrs = Sets.getLink(ParamInfo.Index).Attrs;
395 auto MaybeRelation =
396 getIndexRelation(Sets, ParamInfo.Index, RetInfo.Index);
397 if (MaybeRelation.hasValue()) {
398 AddEdge = true;
399 Externals |= RetAttrs | ParamAttrs;
400 }
401 }
402 if (AddEdge)
Hal Finkelca616ac2014-09-02 23:29:48 +0000403 Output.push_back(Edge(FuncValue, ArgVal, EdgeType::Assign,
404 StratifiedAttrs().flip()));
Hal Finkel7529c552014-09-02 21:43:13 +0000405 }
406
407 if (Parameters.size() != Arguments.size())
408 return false;
409
410 // Adding edges between arguments for arguments that may end up aliasing
411 // each other. This is necessary for functions such as
412 // void foo(int** a, int** b) { *a = *b; }
413 // (Technically, the proper sets for this would be those below
414 // Arguments[I] and Arguments[X], but our algorithm will produce
415 // extremely similar, and equally correct, results either way)
416 for (unsigned I = 0, E = Arguments.size(); I != E; ++I) {
417 auto &MainVal = Arguments[I];
418 auto &MainInfo = Parameters[I];
419 auto &MainAttrs = Sets.getLink(MainInfo.Index).Attrs;
420 for (unsigned X = I + 1; X != E; ++X) {
421 auto &SubInfo = Parameters[X];
422 auto &SubVal = Arguments[X];
423 auto &SubAttrs = Sets.getLink(SubInfo.Index).Attrs;
424 auto MaybeRelation =
425 getIndexRelation(Sets, MainInfo.Index, SubInfo.Index);
426
427 if (!MaybeRelation.hasValue())
428 continue;
429
430 auto NewAttrs = SubAttrs | MainAttrs;
Hal Finkel8d1590d2014-09-02 22:52:30 +0000431 Output.push_back(Edge(MainVal, SubVal, EdgeType::Assign, NewAttrs));
Hal Finkel7529c552014-09-02 21:43:13 +0000432 }
433 }
434 }
435 return true;
436 }
437
438 template <typename InstT> void visitCallLikeInst(InstT &Inst) {
439 SmallVector<Function *, 4> Targets;
440 if (getPossibleTargets(&Inst, Targets)) {
441 if (tryInterproceduralAnalysis(Targets, &Inst, Inst.arg_operands()))
442 return;
443 // Cleanup from interprocedural analysis
444 Output.clear();
445 }
446
447 for (Value *V : Inst.arg_operands())
Hal Finkel8d1590d2014-09-02 22:52:30 +0000448 Output.push_back(Edge(&Inst, V, EdgeType::Assign, AttrAll));
Hal Finkel7529c552014-09-02 21:43:13 +0000449 }
450
451 void visitCallInst(CallInst &Inst) { visitCallLikeInst(Inst); }
452
453 void visitInvokeInst(InvokeInst &Inst) { visitCallLikeInst(Inst); }
454
455 // Because vectors/aggregates are immutable and unaddressable,
456 // there's nothing we can do to coax a value out of them, other
457 // than calling Extract{Element,Value}. We can effectively treat
458 // them as pointers to arbitrary memory locations we can store in
459 // and load from.
460 void visitExtractElementInst(ExtractElementInst &Inst) {
461 auto *Ptr = Inst.getVectorOperand();
462 auto *Val = &Inst;
Hal Finkel8d1590d2014-09-02 22:52:30 +0000463 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000464 }
465
466 void visitInsertElementInst(InsertElementInst &Inst) {
467 auto *Vec = Inst.getOperand(0);
468 auto *Val = Inst.getOperand(1);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000469 Output.push_back(Edge(&Inst, Vec, EdgeType::Assign, AttrNone));
470 Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000471 }
472
473 void visitLandingPadInst(LandingPadInst &Inst) {
474 // Exceptions come from "nowhere", from our analysis' perspective.
475 // So we place the instruction its own group, noting that said group may
476 // alias externals
Hal Finkel8d1590d2014-09-02 22:52:30 +0000477 Output.push_back(Edge(&Inst, &Inst, EdgeType::Assign, AttrAll));
Hal Finkel7529c552014-09-02 21:43:13 +0000478 }
479
480 void visitInsertValueInst(InsertValueInst &Inst) {
481 auto *Agg = Inst.getOperand(0);
482 auto *Val = Inst.getOperand(1);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000483 Output.push_back(Edge(&Inst, Agg, EdgeType::Assign, AttrNone));
484 Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000485 }
486
487 void visitExtractValueInst(ExtractValueInst &Inst) {
488 auto *Ptr = Inst.getAggregateOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000489 Output.push_back(Edge(&Inst, Ptr, EdgeType::Reference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000490 }
491
492 void visitShuffleVectorInst(ShuffleVectorInst &Inst) {
493 auto *From1 = Inst.getOperand(0);
494 auto *From2 = Inst.getOperand(1);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000495 Output.push_back(Edge(&Inst, From1, EdgeType::Assign, AttrNone));
496 Output.push_back(Edge(&Inst, From2, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000497 }
498};
499
500// For a given instruction, we need to know which Value* to get the
501// users of in order to build our graph. In some cases (i.e. add),
502// we simply need the Instruction*. In other cases (i.e. store),
503// finding the users of the Instruction* is useless; we need to find
504// the users of the first operand. This handles determining which
505// value to follow for us.
506//
507// Note: we *need* to keep this in sync with GetEdgesVisitor. Add
508// something to GetEdgesVisitor, add it here -- remove something from
509// GetEdgesVisitor, remove it here.
510class GetTargetValueVisitor
511 : public InstVisitor<GetTargetValueVisitor, Value *> {
512public:
513 Value *visitInstruction(Instruction &Inst) { return &Inst; }
514
515 Value *visitStoreInst(StoreInst &Inst) { return Inst.getPointerOperand(); }
516
517 Value *visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
518 return Inst.getPointerOperand();
519 }
520
521 Value *visitAtomicRMWInst(AtomicRMWInst &Inst) {
522 return Inst.getPointerOperand();
523 }
524
525 Value *visitInsertElementInst(InsertElementInst &Inst) {
526 return Inst.getOperand(0);
527 }
528
529 Value *visitInsertValueInst(InsertValueInst &Inst) {
530 return Inst.getAggregateOperand();
531 }
532};
533
534// Set building requires a weighted bidirectional graph.
535template <typename EdgeTypeT> class WeightedBidirectionalGraph {
536public:
537 typedef std::size_t Node;
538
539private:
Hal Finkelca616ac2014-09-02 23:29:48 +0000540 const static Node StartNode = Node(0);
Hal Finkel7529c552014-09-02 21:43:13 +0000541
542 struct Edge {
543 EdgeTypeT Weight;
544 Node Other;
545
Hal Finkelca616ac2014-09-02 23:29:48 +0000546 Edge(const EdgeTypeT &W, const Node &N)
547 : Weight(W), Other(N) {}
548
Hal Finkel7529c552014-09-02 21:43:13 +0000549 bool operator==(const Edge &E) const {
550 return Weight == E.Weight && Other == E.Other;
551 }
552
553 bool operator!=(const Edge &E) const { return !operator==(E); }
554 };
555
556 struct NodeImpl {
557 std::vector<Edge> Edges;
558 };
559
560 std::vector<NodeImpl> NodeImpls;
561
562 bool inbounds(Node NodeIndex) const { return NodeIndex < NodeImpls.size(); }
563
564 const NodeImpl &getNode(Node N) const { return NodeImpls[N]; }
565 NodeImpl &getNode(Node N) { return NodeImpls[N]; }
566
567public:
568 // ----- Various Edge iterators for the graph ----- //
569
570 // \brief Iterator for edges. Because this graph is bidirected, we don't
571 // allow modificaiton of the edges using this iterator. Additionally, the
572 // iterator becomes invalid if you add edges to or from the node you're
573 // getting the edges of.
574 struct EdgeIterator : public std::iterator<std::forward_iterator_tag,
575 std::tuple<EdgeTypeT, Node *>> {
576 EdgeIterator(const typename std::vector<Edge>::const_iterator &Iter)
577 : Current(Iter) {}
578
579 EdgeIterator(NodeImpl &Impl) : Current(Impl.begin()) {}
580
581 EdgeIterator &operator++() {
582 ++Current;
583 return *this;
584 }
585
586 EdgeIterator operator++(int) {
587 EdgeIterator Copy(Current);
588 operator++();
589 return Copy;
590 }
591
592 std::tuple<EdgeTypeT, Node> &operator*() {
593 Store = std::make_tuple(Current->Weight, Current->Other);
594 return Store;
595 }
596
597 bool operator==(const EdgeIterator &Other) const {
598 return Current == Other.Current;
599 }
600
601 bool operator!=(const EdgeIterator &Other) const {
602 return !operator==(Other);
603 }
604
605 private:
606 typename std::vector<Edge>::const_iterator Current;
607 std::tuple<EdgeTypeT, Node> Store;
608 };
609
610 // Wrapper for EdgeIterator with begin()/end() calls.
611 struct EdgeIterable {
612 EdgeIterable(const std::vector<Edge> &Edges)
613 : BeginIter(Edges.begin()), EndIter(Edges.end()) {}
614
615 EdgeIterator begin() { return EdgeIterator(BeginIter); }
616
617 EdgeIterator end() { return EdgeIterator(EndIter); }
618
619 private:
620 typename std::vector<Edge>::const_iterator BeginIter;
621 typename std::vector<Edge>::const_iterator EndIter;
622 };
623
624 // ----- Actual graph-related things ----- //
625
Hal Finkelca616ac2014-09-02 23:29:48 +0000626 WeightedBidirectionalGraph() {}
Hal Finkel7529c552014-09-02 21:43:13 +0000627
628 WeightedBidirectionalGraph(WeightedBidirectionalGraph<EdgeTypeT> &&Other)
629 : NodeImpls(std::move(Other.NodeImpls)) {}
630
631 WeightedBidirectionalGraph<EdgeTypeT> &
632 operator=(WeightedBidirectionalGraph<EdgeTypeT> &&Other) {
633 NodeImpls = std::move(Other.NodeImpls);
634 return *this;
635 }
636
637 Node addNode() {
638 auto Index = NodeImpls.size();
639 auto NewNode = Node(Index);
640 NodeImpls.push_back(NodeImpl());
641 return NewNode;
642 }
643
644 void addEdge(Node From, Node To, const EdgeTypeT &Weight,
645 const EdgeTypeT &ReverseWeight) {
646 assert(inbounds(From));
647 assert(inbounds(To));
648 auto &FromNode = getNode(From);
649 auto &ToNode = getNode(To);
Hal Finkelca616ac2014-09-02 23:29:48 +0000650 FromNode.Edges.push_back(Edge(Weight, To));
651 ToNode.Edges.push_back(Edge(ReverseWeight, From));
Hal Finkel7529c552014-09-02 21:43:13 +0000652 }
653
654 EdgeIterable edgesFor(const Node &N) const {
655 const auto &Node = getNode(N);
656 return EdgeIterable(Node.Edges);
657 }
658
659 bool empty() const { return NodeImpls.empty(); }
660 std::size_t size() const { return NodeImpls.size(); }
661
662 // \brief Gets an arbitrary node in the graph as a starting point for
663 // traversal.
664 Node getEntryNode() {
665 assert(inbounds(StartNode));
666 return StartNode;
667 }
668};
669
670typedef WeightedBidirectionalGraph<std::pair<EdgeType, StratifiedAttrs>> GraphT;
671typedef DenseMap<Value *, GraphT::Node> NodeMapT;
672}
673
674// -- Setting up/registering CFLAA pass -- //
675char CFLAliasAnalysis::ID = 0;
676
677INITIALIZE_AG_PASS(CFLAliasAnalysis, AliasAnalysis, "cfl-aa",
678 "CFL-Based AA implementation", false, true, false)
679
680ImmutablePass *llvm::createCFLAliasAnalysisPass() {
681 return new CFLAliasAnalysis();
682}
683
684//===----------------------------------------------------------------------===//
685// Function declarations that require types defined in the namespace above
686//===----------------------------------------------------------------------===//
687
688// Given an argument number, returns the appropriate Attr index to set.
689static StratifiedAttr argNumberToAttrIndex(StratifiedAttr);
690
691// Given a Value, potentially return which AttrIndex it maps to.
692static Optional<StratifiedAttr> valueToAttrIndex(Value *Val);
693
694// Gets the inverse of a given EdgeType.
695static EdgeType flipWeight(EdgeType);
696
697// Gets edges of the given Instruction*, writing them to the SmallVector*.
698static void argsToEdges(CFLAliasAnalysis &, Instruction *,
699 SmallVectorImpl<Edge> &);
700
701// Gets the "Level" that one should travel in StratifiedSets
702// given an EdgeType.
703static Level directionOfEdgeType(EdgeType);
704
705// Builds the graph needed for constructing the StratifiedSets for the
706// given function
707static void buildGraphFrom(CFLAliasAnalysis &, Function *,
708 SmallVectorImpl<Value *> &, NodeMapT &, GraphT &);
709
710// Builds the graph + StratifiedSets for a function.
711static FunctionInfo buildSetsFrom(CFLAliasAnalysis &, Function *);
712
713static Optional<Function *> parentFunctionOfValue(Value *Val) {
714 if (auto *Inst = dyn_cast<Instruction>(Val)) {
715 auto *Bb = Inst->getParent();
716 return Bb->getParent();
717 }
718
719 if (auto *Arg = dyn_cast<Argument>(Val))
720 return Arg->getParent();
721 return NoneType();
722}
723
724template <typename Inst>
725static bool getPossibleTargets(Inst *Call,
726 SmallVectorImpl<Function *> &Output) {
727 if (auto *Fn = Call->getCalledFunction()) {
728 Output.push_back(Fn);
729 return true;
730 }
731
732 // TODO: If the call is indirect, we might be able to enumerate all potential
733 // targets of the call and return them, rather than just failing.
734 return false;
735}
736
737static Optional<Value *> getTargetValue(Instruction *Inst) {
738 GetTargetValueVisitor V;
739 return V.visit(Inst);
740}
741
742static bool hasUsefulEdges(Instruction *Inst) {
743 bool IsNonInvokeTerminator =
744 isa<TerminatorInst>(Inst) && !isa<InvokeInst>(Inst);
745 return !isa<CmpInst>(Inst) && !isa<FenceInst>(Inst) && !IsNonInvokeTerminator;
746}
747
748static Optional<StratifiedAttr> valueToAttrIndex(Value *Val) {
749 if (isa<GlobalValue>(Val))
750 return AttrGlobalIndex;
751
752 if (auto *Arg = dyn_cast<Argument>(Val))
753 if (!Arg->hasNoAliasAttr())
754 return argNumberToAttrIndex(Arg->getArgNo());
755 return NoneType();
756}
757
758static StratifiedAttr argNumberToAttrIndex(unsigned ArgNum) {
759 if (ArgNum > AttrMaxNumArgs)
760 return AttrAllIndex;
761 return ArgNum + AttrFirstArgIndex;
762}
763
764static EdgeType flipWeight(EdgeType Initial) {
765 switch (Initial) {
766 case EdgeType::Assign:
767 return EdgeType::Assign;
768 case EdgeType::Dereference:
769 return EdgeType::Reference;
770 case EdgeType::Reference:
771 return EdgeType::Dereference;
772 }
773 llvm_unreachable("Incomplete coverage of EdgeType enum");
774}
775
776static void argsToEdges(CFLAliasAnalysis &Analysis, Instruction *Inst,
777 SmallVectorImpl<Edge> &Output) {
778 GetEdgesVisitor v(Analysis, Output);
779 v.visit(Inst);
780}
781
782static Level directionOfEdgeType(EdgeType Weight) {
783 switch (Weight) {
784 case EdgeType::Reference:
785 return Level::Above;
786 case EdgeType::Dereference:
787 return Level::Below;
788 case EdgeType::Assign:
789 return Level::Same;
790 }
791 llvm_unreachable("Incomplete switch coverage");
792}
793
794// Aside: We may remove graph construction entirely, because it doesn't really
795// buy us much that we don't already have. I'd like to add interprocedural
796// analysis prior to this however, in case that somehow requires the graph
797// produced by this for efficient execution
798static void buildGraphFrom(CFLAliasAnalysis &Analysis, Function *Fn,
799 SmallVectorImpl<Value *> &ReturnedValues,
800 NodeMapT &Map, GraphT &Graph) {
801 const auto findOrInsertNode = [&Map, &Graph](Value *Val) {
802 auto Pair = Map.insert(std::make_pair(Val, GraphT::Node()));
803 auto &Iter = Pair.first;
804 if (Pair.second) {
805 auto NewNode = Graph.addNode();
806 Iter->second = NewNode;
807 }
808 return Iter->second;
809 };
810
811 SmallVector<Edge, 8> Edges;
812 for (auto &Bb : Fn->getBasicBlockList()) {
813 for (auto &Inst : Bb.getInstList()) {
814 // We don't want the edges of most "return" instructions, but we *do* want
815 // to know what can be returned.
816 if (auto *Ret = dyn_cast<ReturnInst>(&Inst))
817 ReturnedValues.push_back(Ret);
818
819 if (!hasUsefulEdges(&Inst))
820 continue;
821
822 Edges.clear();
823 argsToEdges(Analysis, &Inst, Edges);
824
825 // In the case of an unused alloca (or similar), edges may be empty. Note
826 // that it exists so we can potentially answer NoAlias.
827 if (Edges.empty()) {
828 auto MaybeVal = getTargetValue(&Inst);
829 assert(MaybeVal.hasValue());
830 auto *Target = *MaybeVal;
831 findOrInsertNode(Target);
832 continue;
833 }
834
835 for (const Edge &E : Edges) {
836 auto To = findOrInsertNode(E.To);
837 auto From = findOrInsertNode(E.From);
838 auto FlippedWeight = flipWeight(E.Weight);
839 auto Attrs = E.AdditionalAttrs;
840 Graph.addEdge(From, To, {E.Weight, Attrs}, {FlippedWeight, Attrs});
841 }
842 }
843 }
844}
845
846static FunctionInfo buildSetsFrom(CFLAliasAnalysis &Analysis, Function *Fn) {
847 NodeMapT Map;
848 GraphT Graph;
849 SmallVector<Value *, 4> ReturnedValues;
850
851 buildGraphFrom(Analysis, Fn, ReturnedValues, Map, Graph);
852
853 DenseMap<GraphT::Node, Value *> NodeValueMap;
854 NodeValueMap.resize(Map.size());
855 for (const auto &Pair : Map)
Hal Finkel8d1590d2014-09-02 22:52:30 +0000856 NodeValueMap.insert(std::make_pair(Pair.second, Pair.first));
Hal Finkel7529c552014-09-02 21:43:13 +0000857
858 const auto findValueOrDie = [&NodeValueMap](GraphT::Node Node) {
859 auto ValIter = NodeValueMap.find(Node);
860 assert(ValIter != NodeValueMap.end());
861 return ValIter->second;
862 };
863
864 StratifiedSetsBuilder<Value *> Builder;
865
866 SmallVector<GraphT::Node, 16> Worklist;
867 for (auto &Pair : Map) {
868 Worklist.clear();
869
870 auto *Value = Pair.first;
871 Builder.add(Value);
872 auto InitialNode = Pair.second;
873 Worklist.push_back(InitialNode);
874 while (!Worklist.empty()) {
875 auto Node = Worklist.pop_back_val();
876 auto *CurValue = findValueOrDie(Node);
877 if (isa<Constant>(CurValue) && !isa<GlobalValue>(CurValue))
878 continue;
879
880 for (const auto &EdgeTuple : Graph.edgesFor(Node)) {
881 auto Weight = std::get<0>(EdgeTuple);
882 auto Label = Weight.first;
883 auto &OtherNode = std::get<1>(EdgeTuple);
884 auto *OtherValue = findValueOrDie(OtherNode);
885
886 if (isa<Constant>(OtherValue) && !isa<GlobalValue>(OtherValue))
887 continue;
888
889 bool Added;
890 switch (directionOfEdgeType(Label)) {
891 case Level::Above:
892 Added = Builder.addAbove(CurValue, OtherValue);
893 break;
894 case Level::Below:
895 Added = Builder.addBelow(CurValue, OtherValue);
896 break;
897 case Level::Same:
898 Added = Builder.addWith(CurValue, OtherValue);
899 break;
900 }
901
902 if (Added) {
903 auto Aliasing = Weight.second;
904 if (auto MaybeCurIndex = valueToAttrIndex(CurValue))
905 Aliasing.set(*MaybeCurIndex);
906 if (auto MaybeOtherIndex = valueToAttrIndex(OtherValue))
907 Aliasing.set(*MaybeOtherIndex);
908 Builder.noteAttributes(CurValue, Aliasing);
909 Builder.noteAttributes(OtherValue, Aliasing);
910 Worklist.push_back(OtherNode);
911 }
912 }
913 }
914 }
915
916 // There are times when we end up with parameters not in our graph (i.e. if
917 // it's only used as the condition of a branch). Other bits of code depend on
918 // things that were present during construction being present in the graph.
919 // So, we add all present arguments here.
920 for (auto &Arg : Fn->args()) {
921 Builder.add(&Arg);
922 }
923
924 return {Builder.build(), std::move(ReturnedValues)};
925}
926
927void CFLAliasAnalysis::scan(Function *Fn) {
Hal Finkel8d1590d2014-09-02 22:52:30 +0000928 auto InsertPair = Cache.insert(std::make_pair(Fn, Optional<FunctionInfo>()));
Hal Finkel7529c552014-09-02 21:43:13 +0000929 (void)InsertPair;
930 assert(InsertPair.second &&
931 "Trying to scan a function that has already been cached");
932
933 FunctionInfo Info(buildSetsFrom(*this, Fn));
934 Cache[Fn] = std::move(Info);
935 Handles.push_front(FunctionHandle(Fn, this));
936}
937
938AliasAnalysis::AliasResult
939CFLAliasAnalysis::query(const AliasAnalysis::Location &LocA,
940 const AliasAnalysis::Location &LocB) {
941 auto *ValA = const_cast<Value *>(LocA.Ptr);
942 auto *ValB = const_cast<Value *>(LocB.Ptr);
943
944 Function *Fn = nullptr;
945 auto MaybeFnA = parentFunctionOfValue(ValA);
946 auto MaybeFnB = parentFunctionOfValue(ValB);
947 if (!MaybeFnA.hasValue() && !MaybeFnB.hasValue()) {
948 llvm_unreachable("Don't know how to extract the parent function "
949 "from values A or B");
950 }
951
952 if (MaybeFnA.hasValue()) {
953 Fn = *MaybeFnA;
954 assert((!MaybeFnB.hasValue() || *MaybeFnB == *MaybeFnA) &&
955 "Interprocedural queries not supported");
956 } else {
957 Fn = *MaybeFnB;
958 }
959
960 assert(Fn != nullptr);
961 auto &MaybeInfo = ensureCached(Fn);
962 assert(MaybeInfo.hasValue());
963
964 auto &Sets = MaybeInfo->Sets;
965 auto MaybeA = Sets.find(ValA);
966 if (!MaybeA.hasValue())
967 return AliasAnalysis::MayAlias;
968
969 auto MaybeB = Sets.find(ValB);
970 if (!MaybeB.hasValue())
971 return AliasAnalysis::MayAlias;
972
973 auto SetA = *MaybeA;
974 auto SetB = *MaybeB;
975
976 if (SetA.Index == SetB.Index)
977 return AliasAnalysis::PartialAlias;
978
979 auto AttrsA = Sets.getLink(SetA.Index).Attrs;
980 auto AttrsB = Sets.getLink(SetB.Index).Attrs;
981 auto CombinedAttrs = AttrsA | AttrsB;
982 if (CombinedAttrs.any())
983 return AliasAnalysis::PartialAlias;
984
985 return AliasAnalysis::NoAlias;
986}