1 //===- 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/ADT/BitVector.h"
33 #include "llvm/ADT/DenseMap.h"
34 #include "llvm/ADT/None.h"
35 #include "llvm/ADT/Optional.h"
36 #include "llvm/Analysis/AliasAnalysis.h"
37 #include "llvm/Analysis/Passes.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/InstVisitor.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/ValueHandle.h"
43 #include "llvm/Pass.h"
44 #include "llvm/Support/Allocator.h"
45 #include "llvm/Support/Compiler.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include <algorithm>
48 #include <cassert>
49 #include <forward_list>
50 #include <tuple>
51
52 using namespace llvm;
53
54 // Try to go from a Value* to a Function*. Never returns nullptr.
55 static 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.
62 template <typename Inst>
63 static 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.
70 static 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.
74 static bool hasUsefulEdges(Instruction *);
75
76 const StratifiedIndex StratifiedLink::SetSentinel =
77 std::numeric_limits<StratifiedIndex>::max();
78
79 namespace {
80 // StratifiedInfo Attribute things.
81 typedef unsigned StratifiedAttr;
82 LLVM_CONSTEXPR unsigned MaxStratifiedAttrIndex = NumStratifiedAttrs;
83 LLVM_CONSTEXPR unsigned AttrAllIndex = 0;
84 LLVM_CONSTEXPR unsigned AttrGlobalIndex = 1;
85 LLVM_CONSTEXPR unsigned AttrFirstArgIndex = 2;
86 LLVM_CONSTEXPR unsigned AttrLastArgIndex = MaxStratifiedAttrIndex;
87 LLVM_CONSTEXPR unsigned AttrMaxNumArgs = AttrLastArgIndex - AttrFirstArgIndex;
88
89 LLVM_CONSTEXPR StratifiedAttr AttrNone = 0;
90 LLVM_CONSTEXPR StratifiedAttr AttrAll = ~AttrNone;
91
92 // \brief StratifiedSets call for knowledge of "direction", so this is how we
93 // represent that locally.
94 enum 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).
98 enum 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"
119 struct 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
Edge__anon27e61d590111::Edge134 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
139 struct FunctionInfo {
140 StratifiedSets<Value *> Sets;
141 // Lots of functions have < 4 returns. Adjust as necessary.
142 SmallVector<Value *, 4> ReturnedValues;
143
FunctionInfo__anon27e61d590111::FunctionInfo144 FunctionInfo(StratifiedSets<Value *> &&S,
145 SmallVector<Value *, 4> &&RV)
146 : Sets(std::move(S)), ReturnedValues(std::move(RV)) {}
147 };
148
149 struct CFLAliasAnalysis;
150
151 struct FunctionHandle : public CallbackVH {
FunctionHandle__anon27e61d590111::FunctionHandle152 FunctionHandle(Function *Fn, CFLAliasAnalysis *CFLAA)
153 : CallbackVH(Fn), CFLAA(CFLAA) {
154 assert(Fn != nullptr);
155 assert(CFLAA != nullptr);
156 }
157
~FunctionHandle__anon27e61d590111::FunctionHandle158 virtual ~FunctionHandle() {}
159
deleted__anon27e61d590111::FunctionHandle160 void deleted() override { removeSelfFromCache(); }
allUsesReplacedWith__anon27e61d590111::FunctionHandle161 void allUsesReplacedWith(Value *) override { removeSelfFromCache(); }
162
163 private:
164 CFLAliasAnalysis *CFLAA;
165
166 void removeSelfFromCache();
167 };
168
169 struct CFLAliasAnalysis : public ImmutablePass, public AliasAnalysis {
170 private:
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
179 public:
180 static char ID;
181
CFLAliasAnalysis__anon27e61d590111::CFLAliasAnalysis182 CFLAliasAnalysis() : ImmutablePass(ID) {
183 initializeCFLAliasAnalysisPass(*PassRegistry::getPassRegistry());
184 }
185
~CFLAliasAnalysis__anon27e61d590111::CFLAliasAnalysis186 virtual ~CFLAliasAnalysis() {}
187
getAnalysisUsage__anon27e61d590111::CFLAliasAnalysis188 void getAnalysisUsage(AnalysisUsage &AU) const override {
189 AliasAnalysis::getAnalysisUsage(AU);
190 }
191
getAdjustedAnalysisPointer__anon27e61d590111::CFLAliasAnalysis192 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
evict__anon27e61d590111::CFLAliasAnalysis201 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.
ensureCached__anon27e61d590111::CFLAliasAnalysis205 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
alias__anon27e61d590111::CFLAliasAnalysis218 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)) {
230 return MayAlias;
231 }
232
233 return query(LocA, LocB);
234 }
235
initializePass__anon27e61d590111::CFLAliasAnalysis236 void initializePass() override { InitializeAliasAnalysis(this); }
237 };
238
removeSelfFromCache()239 void FunctionHandle::removeSelfFromCache() {
240 assert(CFLAA != nullptr);
241 auto *Val = getValPtr();
242 CFLAA->evict(cast<Function>(Val));
243 setValPtr(nullptr);
244 }
245
246 // \brief Gets the edges our graph should have, based on an Instruction*
247 class GetEdgesVisitor : public InstVisitor<GetEdgesVisitor, void> {
248 CFLAliasAnalysis &AA;
249 SmallVectorImpl<Edge> &Output;
250
251 public:
GetEdgesVisitor(CFLAliasAnalysis & AA,SmallVectorImpl<Edge> & Output)252 GetEdgesVisitor(CFLAliasAnalysis &AA, SmallVectorImpl<Edge> &Output)
253 : AA(AA), Output(Output) {}
254
visitInstruction(Instruction &)255 void visitInstruction(Instruction &) {
256 llvm_unreachable("Unsupported instruction encountered");
257 }
258
visitCastInst(CastInst & Inst)259 void visitCastInst(CastInst &Inst) {
260 Output.push_back(Edge(&Inst, Inst.getOperand(0), EdgeType::Assign,
261 AttrNone));
262 }
263
visitBinaryOperator(BinaryOperator & Inst)264 void visitBinaryOperator(BinaryOperator &Inst) {
265 auto *Op1 = Inst.getOperand(0);
266 auto *Op2 = Inst.getOperand(1);
267 Output.push_back(Edge(&Inst, Op1, EdgeType::Assign, AttrNone));
268 Output.push_back(Edge(&Inst, Op2, EdgeType::Assign, AttrNone));
269 }
270
visitAtomicCmpXchgInst(AtomicCmpXchgInst & Inst)271 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
272 auto *Ptr = Inst.getPointerOperand();
273 auto *Val = Inst.getNewValOperand();
274 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
275 }
276
visitAtomicRMWInst(AtomicRMWInst & Inst)277 void visitAtomicRMWInst(AtomicRMWInst &Inst) {
278 auto *Ptr = Inst.getPointerOperand();
279 auto *Val = Inst.getValOperand();
280 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
281 }
282
visitPHINode(PHINode & Inst)283 void visitPHINode(PHINode &Inst) {
284 for (unsigned I = 0, E = Inst.getNumIncomingValues(); I != E; ++I) {
285 Value *Val = Inst.getIncomingValue(I);
286 Output.push_back(Edge(&Inst, Val, EdgeType::Assign, AttrNone));
287 }
288 }
289
visitGetElementPtrInst(GetElementPtrInst & Inst)290 void visitGetElementPtrInst(GetElementPtrInst &Inst) {
291 auto *Op = Inst.getPointerOperand();
292 Output.push_back(Edge(&Inst, Op, EdgeType::Assign, AttrNone));
293 for (auto I = Inst.idx_begin(), E = Inst.idx_end(); I != E; ++I)
294 Output.push_back(Edge(&Inst, *I, EdgeType::Assign, AttrNone));
295 }
296
visitSelectInst(SelectInst & Inst)297 void visitSelectInst(SelectInst &Inst) {
298 auto *Condition = Inst.getCondition();
299 Output.push_back(Edge(&Inst, Condition, EdgeType::Assign, AttrNone));
300 auto *TrueVal = Inst.getTrueValue();
301 Output.push_back(Edge(&Inst, TrueVal, EdgeType::Assign, AttrNone));
302 auto *FalseVal = Inst.getFalseValue();
303 Output.push_back(Edge(&Inst, FalseVal, EdgeType::Assign, AttrNone));
304 }
305
visitAllocaInst(AllocaInst &)306 void visitAllocaInst(AllocaInst &) {}
307
visitLoadInst(LoadInst & Inst)308 void visitLoadInst(LoadInst &Inst) {
309 auto *Ptr = Inst.getPointerOperand();
310 auto *Val = &Inst;
311 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
312 }
313
visitStoreInst(StoreInst & Inst)314 void visitStoreInst(StoreInst &Inst) {
315 auto *Ptr = Inst.getPointerOperand();
316 auto *Val = Inst.getValueOperand();
317 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
318 }
319
visitVAArgInst(VAArgInst & Inst)320 void visitVAArgInst(VAArgInst &Inst) {
321 // We can't fully model va_arg here. For *Ptr = Inst.getOperand(0), it does
322 // two things:
323 // 1. Loads a value from *((T*)*Ptr).
324 // 2. Increments (stores to) *Ptr by some target-specific amount.
325 // For now, we'll handle this like a landingpad instruction (by placing the
326 // result in its own group, and having that group alias externals).
327 auto *Val = &Inst;
328 Output.push_back(Edge(Val, Val, EdgeType::Assign, AttrAll));
329 }
330
isFunctionExternal(Function * Fn)331 static bool isFunctionExternal(Function *Fn) {
332 return Fn->isDeclaration() || !Fn->hasLocalLinkage();
333 }
334
335 // Gets whether the sets at Index1 above, below, or equal to the sets at
336 // Index2. Returns None if they are not in the same set chain.
getIndexRelation(const StratifiedSets<Value * > & Sets,StratifiedIndex Index1,StratifiedIndex Index2)337 static Optional<Level> getIndexRelation(const StratifiedSets<Value *> &Sets,
338 StratifiedIndex Index1,
339 StratifiedIndex Index2) {
340 if (Index1 == Index2)
341 return Level::Same;
342
343 const auto *Current = &Sets.getLink(Index1);
344 while (Current->hasBelow()) {
345 if (Current->Below == Index2)
346 return Level::Below;
347 Current = &Sets.getLink(Current->Below);
348 }
349
350 Current = &Sets.getLink(Index1);
351 while (Current->hasAbove()) {
352 if (Current->Above == Index2)
353 return Level::Above;
354 Current = &Sets.getLink(Current->Above);
355 }
356
357 return NoneType();
358 }
359
360 bool
tryInterproceduralAnalysis(const SmallVectorImpl<Function * > & Fns,Value * FuncValue,const iterator_range<User::op_iterator> & Args)361 tryInterproceduralAnalysis(const SmallVectorImpl<Function *> &Fns,
362 Value *FuncValue,
363 const iterator_range<User::op_iterator> &Args) {
364 const unsigned ExpectedMaxArgs = 8;
365 const unsigned MaxSupportedArgs = 50;
366 assert(Fns.size() > 0);
367
368 // I put this here to give us an upper bound on time taken by IPA. Is it
369 // really (realistically) needed? Keep in mind that we do have an n^2 algo.
370 if (std::distance(Args.begin(), Args.end()) > (int) MaxSupportedArgs)
371 return false;
372
373 // Exit early if we'll fail anyway
374 for (auto *Fn : Fns) {
375 if (isFunctionExternal(Fn) || Fn->isVarArg())
376 return false;
377 auto &MaybeInfo = AA.ensureCached(Fn);
378 if (!MaybeInfo.hasValue())
379 return false;
380 }
381
382 SmallVector<Value *, ExpectedMaxArgs> Arguments(Args.begin(), Args.end());
383 SmallVector<StratifiedInfo, ExpectedMaxArgs> Parameters;
384 for (auto *Fn : Fns) {
385 auto &Info = *AA.ensureCached(Fn);
386 auto &Sets = Info.Sets;
387 auto &RetVals = Info.ReturnedValues;
388
389 Parameters.clear();
390 for (auto &Param : Fn->args()) {
391 auto MaybeInfo = Sets.find(&Param);
392 // Did a new parameter somehow get added to the function/slip by?
393 if (!MaybeInfo.hasValue())
394 return false;
395 Parameters.push_back(*MaybeInfo);
396 }
397
398 // Adding an edge from argument -> return value for each parameter that
399 // may alias the return value
400 for (unsigned I = 0, E = Parameters.size(); I != E; ++I) {
401 auto &ParamInfo = Parameters[I];
402 auto &ArgVal = Arguments[I];
403 bool AddEdge = false;
404 StratifiedAttrs Externals;
405 for (unsigned X = 0, XE = RetVals.size(); X != XE; ++X) {
406 auto MaybeInfo = Sets.find(RetVals[X]);
407 if (!MaybeInfo.hasValue())
408 return false;
409
410 auto &RetInfo = *MaybeInfo;
411 auto RetAttrs = Sets.getLink(RetInfo.Index).Attrs;
412 auto ParamAttrs = Sets.getLink(ParamInfo.Index).Attrs;
413 auto MaybeRelation =
414 getIndexRelation(Sets, ParamInfo.Index, RetInfo.Index);
415 if (MaybeRelation.hasValue()) {
416 AddEdge = true;
417 Externals |= RetAttrs | ParamAttrs;
418 }
419 }
420 if (AddEdge)
421 Output.push_back(Edge(FuncValue, ArgVal, EdgeType::Assign,
422 StratifiedAttrs().flip()));
423 }
424
425 if (Parameters.size() != Arguments.size())
426 return false;
427
428 // Adding edges between arguments for arguments that may end up aliasing
429 // each other. This is necessary for functions such as
430 // void foo(int** a, int** b) { *a = *b; }
431 // (Technically, the proper sets for this would be those below
432 // Arguments[I] and Arguments[X], but our algorithm will produce
433 // extremely similar, and equally correct, results either way)
434 for (unsigned I = 0, E = Arguments.size(); I != E; ++I) {
435 auto &MainVal = Arguments[I];
436 auto &MainInfo = Parameters[I];
437 auto &MainAttrs = Sets.getLink(MainInfo.Index).Attrs;
438 for (unsigned X = I + 1; X != E; ++X) {
439 auto &SubInfo = Parameters[X];
440 auto &SubVal = Arguments[X];
441 auto &SubAttrs = Sets.getLink(SubInfo.Index).Attrs;
442 auto MaybeRelation =
443 getIndexRelation(Sets, MainInfo.Index, SubInfo.Index);
444
445 if (!MaybeRelation.hasValue())
446 continue;
447
448 auto NewAttrs = SubAttrs | MainAttrs;
449 Output.push_back(Edge(MainVal, SubVal, EdgeType::Assign, NewAttrs));
450 }
451 }
452 }
453 return true;
454 }
455
visitCallLikeInst(InstT & Inst)456 template <typename InstT> void visitCallLikeInst(InstT &Inst) {
457 SmallVector<Function *, 4> Targets;
458 if (getPossibleTargets(&Inst, Targets)) {
459 if (tryInterproceduralAnalysis(Targets, &Inst, Inst.arg_operands()))
460 return;
461 // Cleanup from interprocedural analysis
462 Output.clear();
463 }
464
465 for (Value *V : Inst.arg_operands())
466 Output.push_back(Edge(&Inst, V, EdgeType::Assign, AttrAll));
467 }
468
visitCallInst(CallInst & Inst)469 void visitCallInst(CallInst &Inst) { visitCallLikeInst(Inst); }
470
visitInvokeInst(InvokeInst & Inst)471 void visitInvokeInst(InvokeInst &Inst) { visitCallLikeInst(Inst); }
472
473 // Because vectors/aggregates are immutable and unaddressable,
474 // there's nothing we can do to coax a value out of them, other
475 // than calling Extract{Element,Value}. We can effectively treat
476 // them as pointers to arbitrary memory locations we can store in
477 // and load from.
visitExtractElementInst(ExtractElementInst & Inst)478 void visitExtractElementInst(ExtractElementInst &Inst) {
479 auto *Ptr = Inst.getVectorOperand();
480 auto *Val = &Inst;
481 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
482 }
483
visitInsertElementInst(InsertElementInst & Inst)484 void visitInsertElementInst(InsertElementInst &Inst) {
485 auto *Vec = Inst.getOperand(0);
486 auto *Val = Inst.getOperand(1);
487 Output.push_back(Edge(&Inst, Vec, EdgeType::Assign, AttrNone));
488 Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
489 }
490
visitLandingPadInst(LandingPadInst & Inst)491 void visitLandingPadInst(LandingPadInst &Inst) {
492 // Exceptions come from "nowhere", from our analysis' perspective.
493 // So we place the instruction its own group, noting that said group may
494 // alias externals
495 Output.push_back(Edge(&Inst, &Inst, EdgeType::Assign, AttrAll));
496 }
497
visitInsertValueInst(InsertValueInst & Inst)498 void visitInsertValueInst(InsertValueInst &Inst) {
499 auto *Agg = Inst.getOperand(0);
500 auto *Val = Inst.getOperand(1);
501 Output.push_back(Edge(&Inst, Agg, EdgeType::Assign, AttrNone));
502 Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
503 }
504
visitExtractValueInst(ExtractValueInst & Inst)505 void visitExtractValueInst(ExtractValueInst &Inst) {
506 auto *Ptr = Inst.getAggregateOperand();
507 Output.push_back(Edge(&Inst, Ptr, EdgeType::Reference, AttrNone));
508 }
509
visitShuffleVectorInst(ShuffleVectorInst & Inst)510 void visitShuffleVectorInst(ShuffleVectorInst &Inst) {
511 auto *From1 = Inst.getOperand(0);
512 auto *From2 = Inst.getOperand(1);
513 Output.push_back(Edge(&Inst, From1, EdgeType::Assign, AttrNone));
514 Output.push_back(Edge(&Inst, From2, EdgeType::Assign, AttrNone));
515 }
516 };
517
518 // For a given instruction, we need to know which Value* to get the
519 // users of in order to build our graph. In some cases (i.e. add),
520 // we simply need the Instruction*. In other cases (i.e. store),
521 // finding the users of the Instruction* is useless; we need to find
522 // the users of the first operand. This handles determining which
523 // value to follow for us.
524 //
525 // Note: we *need* to keep this in sync with GetEdgesVisitor. Add
526 // something to GetEdgesVisitor, add it here -- remove something from
527 // GetEdgesVisitor, remove it here.
528 class GetTargetValueVisitor
529 : public InstVisitor<GetTargetValueVisitor, Value *> {
530 public:
visitInstruction(Instruction & Inst)531 Value *visitInstruction(Instruction &Inst) { return &Inst; }
532
visitStoreInst(StoreInst & Inst)533 Value *visitStoreInst(StoreInst &Inst) { return Inst.getPointerOperand(); }
534
visitAtomicCmpXchgInst(AtomicCmpXchgInst & Inst)535 Value *visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
536 return Inst.getPointerOperand();
537 }
538
visitAtomicRMWInst(AtomicRMWInst & Inst)539 Value *visitAtomicRMWInst(AtomicRMWInst &Inst) {
540 return Inst.getPointerOperand();
541 }
542
visitInsertElementInst(InsertElementInst & Inst)543 Value *visitInsertElementInst(InsertElementInst &Inst) {
544 return Inst.getOperand(0);
545 }
546
visitInsertValueInst(InsertValueInst & Inst)547 Value *visitInsertValueInst(InsertValueInst &Inst) {
548 return Inst.getAggregateOperand();
549 }
550 };
551
552 // Set building requires a weighted bidirectional graph.
553 template <typename EdgeTypeT> class WeightedBidirectionalGraph {
554 public:
555 typedef std::size_t Node;
556
557 private:
558 const static Node StartNode = Node(0);
559
560 struct Edge {
561 EdgeTypeT Weight;
562 Node Other;
563
Edge__anon27e61d590111::WeightedBidirectionalGraph::Edge564 Edge(const EdgeTypeT &W, const Node &N)
565 : Weight(W), Other(N) {}
566
operator ==__anon27e61d590111::WeightedBidirectionalGraph::Edge567 bool operator==(const Edge &E) const {
568 return Weight == E.Weight && Other == E.Other;
569 }
570
operator !=__anon27e61d590111::WeightedBidirectionalGraph::Edge571 bool operator!=(const Edge &E) const { return !operator==(E); }
572 };
573
574 struct NodeImpl {
575 std::vector<Edge> Edges;
576 };
577
578 std::vector<NodeImpl> NodeImpls;
579
inbounds(Node NodeIndex) const580 bool inbounds(Node NodeIndex) const { return NodeIndex < NodeImpls.size(); }
581
getNode(Node N) const582 const NodeImpl &getNode(Node N) const { return NodeImpls[N]; }
getNode(Node N)583 NodeImpl &getNode(Node N) { return NodeImpls[N]; }
584
585 public:
586 // ----- Various Edge iterators for the graph ----- //
587
588 // \brief Iterator for edges. Because this graph is bidirected, we don't
589 // allow modificaiton of the edges using this iterator. Additionally, the
590 // iterator becomes invalid if you add edges to or from the node you're
591 // getting the edges of.
592 struct EdgeIterator : public std::iterator<std::forward_iterator_tag,
593 std::tuple<EdgeTypeT, Node *>> {
EdgeIterator__anon27e61d590111::WeightedBidirectionalGraph::EdgeIterator594 EdgeIterator(const typename std::vector<Edge>::const_iterator &Iter)
595 : Current(Iter) {}
596
EdgeIterator__anon27e61d590111::WeightedBidirectionalGraph::EdgeIterator597 EdgeIterator(NodeImpl &Impl) : Current(Impl.begin()) {}
598
operator ++__anon27e61d590111::WeightedBidirectionalGraph::EdgeIterator599 EdgeIterator &operator++() {
600 ++Current;
601 return *this;
602 }
603
operator ++__anon27e61d590111::WeightedBidirectionalGraph::EdgeIterator604 EdgeIterator operator++(int) {
605 EdgeIterator Copy(Current);
606 operator++();
607 return Copy;
608 }
609
operator *__anon27e61d590111::WeightedBidirectionalGraph::EdgeIterator610 std::tuple<EdgeTypeT, Node> &operator*() {
611 Store = std::make_tuple(Current->Weight, Current->Other);
612 return Store;
613 }
614
operator ==__anon27e61d590111::WeightedBidirectionalGraph::EdgeIterator615 bool operator==(const EdgeIterator &Other) const {
616 return Current == Other.Current;
617 }
618
operator !=__anon27e61d590111::WeightedBidirectionalGraph::EdgeIterator619 bool operator!=(const EdgeIterator &Other) const {
620 return !operator==(Other);
621 }
622
623 private:
624 typename std::vector<Edge>::const_iterator Current;
625 std::tuple<EdgeTypeT, Node> Store;
626 };
627
628 // Wrapper for EdgeIterator with begin()/end() calls.
629 struct EdgeIterable {
EdgeIterable__anon27e61d590111::WeightedBidirectionalGraph::EdgeIterable630 EdgeIterable(const std::vector<Edge> &Edges)
631 : BeginIter(Edges.begin()), EndIter(Edges.end()) {}
632
begin__anon27e61d590111::WeightedBidirectionalGraph::EdgeIterable633 EdgeIterator begin() { return EdgeIterator(BeginIter); }
634
end__anon27e61d590111::WeightedBidirectionalGraph::EdgeIterable635 EdgeIterator end() { return EdgeIterator(EndIter); }
636
637 private:
638 typename std::vector<Edge>::const_iterator BeginIter;
639 typename std::vector<Edge>::const_iterator EndIter;
640 };
641
642 // ----- Actual graph-related things ----- //
643
WeightedBidirectionalGraph()644 WeightedBidirectionalGraph() {}
645
WeightedBidirectionalGraph(WeightedBidirectionalGraph<EdgeTypeT> && Other)646 WeightedBidirectionalGraph(WeightedBidirectionalGraph<EdgeTypeT> &&Other)
647 : NodeImpls(std::move(Other.NodeImpls)) {}
648
649 WeightedBidirectionalGraph<EdgeTypeT> &
operator =(WeightedBidirectionalGraph<EdgeTypeT> && Other)650 operator=(WeightedBidirectionalGraph<EdgeTypeT> &&Other) {
651 NodeImpls = std::move(Other.NodeImpls);
652 return *this;
653 }
654
addNode()655 Node addNode() {
656 auto Index = NodeImpls.size();
657 auto NewNode = Node(Index);
658 NodeImpls.push_back(NodeImpl());
659 return NewNode;
660 }
661
addEdge(Node From,Node To,const EdgeTypeT & Weight,const EdgeTypeT & ReverseWeight)662 void addEdge(Node From, Node To, const EdgeTypeT &Weight,
663 const EdgeTypeT &ReverseWeight) {
664 assert(inbounds(From));
665 assert(inbounds(To));
666 auto &FromNode = getNode(From);
667 auto &ToNode = getNode(To);
668 FromNode.Edges.push_back(Edge(Weight, To));
669 ToNode.Edges.push_back(Edge(ReverseWeight, From));
670 }
671
edgesFor(const Node & N) const672 EdgeIterable edgesFor(const Node &N) const {
673 const auto &Node = getNode(N);
674 return EdgeIterable(Node.Edges);
675 }
676
empty() const677 bool empty() const { return NodeImpls.empty(); }
size() const678 std::size_t size() const { return NodeImpls.size(); }
679
680 // \brief Gets an arbitrary node in the graph as a starting point for
681 // traversal.
getEntryNode()682 Node getEntryNode() {
683 assert(inbounds(StartNode));
684 return StartNode;
685 }
686 };
687
688 typedef WeightedBidirectionalGraph<std::pair<EdgeType, StratifiedAttrs>> GraphT;
689 typedef DenseMap<Value *, GraphT::Node> NodeMapT;
690 }
691
692 // -- Setting up/registering CFLAA pass -- //
693 char CFLAliasAnalysis::ID = 0;
694
695 INITIALIZE_AG_PASS(CFLAliasAnalysis, AliasAnalysis, "cfl-aa",
696 "CFL-Based AA implementation", false, true, false)
697
createCFLAliasAnalysisPass()698 ImmutablePass *llvm::createCFLAliasAnalysisPass() {
699 return new CFLAliasAnalysis();
700 }
701
702 //===----------------------------------------------------------------------===//
703 // Function declarations that require types defined in the namespace above
704 //===----------------------------------------------------------------------===//
705
706 // Given an argument number, returns the appropriate Attr index to set.
707 static StratifiedAttr argNumberToAttrIndex(StratifiedAttr);
708
709 // Given a Value, potentially return which AttrIndex it maps to.
710 static Optional<StratifiedAttr> valueToAttrIndex(Value *Val);
711
712 // Gets the inverse of a given EdgeType.
713 static EdgeType flipWeight(EdgeType);
714
715 // Gets edges of the given Instruction*, writing them to the SmallVector*.
716 static void argsToEdges(CFLAliasAnalysis &, Instruction *,
717 SmallVectorImpl<Edge> &);
718
719 // Gets the "Level" that one should travel in StratifiedSets
720 // given an EdgeType.
721 static Level directionOfEdgeType(EdgeType);
722
723 // Builds the graph needed for constructing the StratifiedSets for the
724 // given function
725 static void buildGraphFrom(CFLAliasAnalysis &, Function *,
726 SmallVectorImpl<Value *> &, NodeMapT &, GraphT &);
727
728 // Builds the graph + StratifiedSets for a function.
729 static FunctionInfo buildSetsFrom(CFLAliasAnalysis &, Function *);
730
parentFunctionOfValue(Value * Val)731 static Optional<Function *> parentFunctionOfValue(Value *Val) {
732 if (auto *Inst = dyn_cast<Instruction>(Val)) {
733 auto *Bb = Inst->getParent();
734 return Bb->getParent();
735 }
736
737 if (auto *Arg = dyn_cast<Argument>(Val))
738 return Arg->getParent();
739 return NoneType();
740 }
741
742 template <typename Inst>
getPossibleTargets(Inst * Call,SmallVectorImpl<Function * > & Output)743 static bool getPossibleTargets(Inst *Call,
744 SmallVectorImpl<Function *> &Output) {
745 if (auto *Fn = Call->getCalledFunction()) {
746 Output.push_back(Fn);
747 return true;
748 }
749
750 // TODO: If the call is indirect, we might be able to enumerate all potential
751 // targets of the call and return them, rather than just failing.
752 return false;
753 }
754
getTargetValue(Instruction * Inst)755 static Optional<Value *> getTargetValue(Instruction *Inst) {
756 GetTargetValueVisitor V;
757 return V.visit(Inst);
758 }
759
hasUsefulEdges(Instruction * Inst)760 static bool hasUsefulEdges(Instruction *Inst) {
761 bool IsNonInvokeTerminator =
762 isa<TerminatorInst>(Inst) && !isa<InvokeInst>(Inst);
763 return !isa<CmpInst>(Inst) && !isa<FenceInst>(Inst) && !IsNonInvokeTerminator;
764 }
765
valueToAttrIndex(Value * Val)766 static Optional<StratifiedAttr> valueToAttrIndex(Value *Val) {
767 if (isa<GlobalValue>(Val))
768 return AttrGlobalIndex;
769
770 if (auto *Arg = dyn_cast<Argument>(Val))
771 if (!Arg->hasNoAliasAttr())
772 return argNumberToAttrIndex(Arg->getArgNo());
773 return NoneType();
774 }
775
argNumberToAttrIndex(unsigned ArgNum)776 static StratifiedAttr argNumberToAttrIndex(unsigned ArgNum) {
777 if (ArgNum > AttrMaxNumArgs)
778 return AttrAllIndex;
779 return ArgNum + AttrFirstArgIndex;
780 }
781
flipWeight(EdgeType Initial)782 static EdgeType flipWeight(EdgeType Initial) {
783 switch (Initial) {
784 case EdgeType::Assign:
785 return EdgeType::Assign;
786 case EdgeType::Dereference:
787 return EdgeType::Reference;
788 case EdgeType::Reference:
789 return EdgeType::Dereference;
790 }
791 llvm_unreachable("Incomplete coverage of EdgeType enum");
792 }
793
argsToEdges(CFLAliasAnalysis & Analysis,Instruction * Inst,SmallVectorImpl<Edge> & Output)794 static void argsToEdges(CFLAliasAnalysis &Analysis, Instruction *Inst,
795 SmallVectorImpl<Edge> &Output) {
796 GetEdgesVisitor v(Analysis, Output);
797 v.visit(Inst);
798 }
799
directionOfEdgeType(EdgeType Weight)800 static Level directionOfEdgeType(EdgeType Weight) {
801 switch (Weight) {
802 case EdgeType::Reference:
803 return Level::Above;
804 case EdgeType::Dereference:
805 return Level::Below;
806 case EdgeType::Assign:
807 return Level::Same;
808 }
809 llvm_unreachable("Incomplete switch coverage");
810 }
811
812 // Aside: We may remove graph construction entirely, because it doesn't really
813 // buy us much that we don't already have. I'd like to add interprocedural
814 // analysis prior to this however, in case that somehow requires the graph
815 // produced by this for efficient execution
buildGraphFrom(CFLAliasAnalysis & Analysis,Function * Fn,SmallVectorImpl<Value * > & ReturnedValues,NodeMapT & Map,GraphT & Graph)816 static void buildGraphFrom(CFLAliasAnalysis &Analysis, Function *Fn,
817 SmallVectorImpl<Value *> &ReturnedValues,
818 NodeMapT &Map, GraphT &Graph) {
819 const auto findOrInsertNode = [&Map, &Graph](Value *Val) {
820 auto Pair = Map.insert(std::make_pair(Val, GraphT::Node()));
821 auto &Iter = Pair.first;
822 if (Pair.second) {
823 auto NewNode = Graph.addNode();
824 Iter->second = NewNode;
825 }
826 return Iter->second;
827 };
828
829 SmallVector<Edge, 8> Edges;
830 for (auto &Bb : Fn->getBasicBlockList()) {
831 for (auto &Inst : Bb.getInstList()) {
832 // We don't want the edges of most "return" instructions, but we *do* want
833 // to know what can be returned.
834 if (auto *Ret = dyn_cast<ReturnInst>(&Inst))
835 ReturnedValues.push_back(Ret);
836
837 if (!hasUsefulEdges(&Inst))
838 continue;
839
840 Edges.clear();
841 argsToEdges(Analysis, &Inst, Edges);
842
843 // In the case of an unused alloca (or similar), edges may be empty. Note
844 // that it exists so we can potentially answer NoAlias.
845 if (Edges.empty()) {
846 auto MaybeVal = getTargetValue(&Inst);
847 assert(MaybeVal.hasValue());
848 auto *Target = *MaybeVal;
849 findOrInsertNode(Target);
850 continue;
851 }
852
853 for (const Edge &E : Edges) {
854 auto To = findOrInsertNode(E.To);
855 auto From = findOrInsertNode(E.From);
856 auto FlippedWeight = flipWeight(E.Weight);
857 auto Attrs = E.AdditionalAttrs;
858 Graph.addEdge(From, To, std::make_pair(E.Weight, Attrs),
859 std::make_pair(FlippedWeight, Attrs));
860 }
861 }
862 }
863 }
864
buildSetsFrom(CFLAliasAnalysis & Analysis,Function * Fn)865 static FunctionInfo buildSetsFrom(CFLAliasAnalysis &Analysis, Function *Fn) {
866 NodeMapT Map;
867 GraphT Graph;
868 SmallVector<Value *, 4> ReturnedValues;
869
870 buildGraphFrom(Analysis, Fn, ReturnedValues, Map, Graph);
871
872 DenseMap<GraphT::Node, Value *> NodeValueMap;
873 NodeValueMap.resize(Map.size());
874 for (const auto &Pair : Map)
875 NodeValueMap.insert(std::make_pair(Pair.second, Pair.first));
876
877 const auto findValueOrDie = [&NodeValueMap](GraphT::Node Node) {
878 auto ValIter = NodeValueMap.find(Node);
879 assert(ValIter != NodeValueMap.end());
880 return ValIter->second;
881 };
882
883 StratifiedSetsBuilder<Value *> Builder;
884
885 SmallVector<GraphT::Node, 16> Worklist;
886 for (auto &Pair : Map) {
887 Worklist.clear();
888
889 auto *Value = Pair.first;
890 Builder.add(Value);
891 auto InitialNode = Pair.second;
892 Worklist.push_back(InitialNode);
893 while (!Worklist.empty()) {
894 auto Node = Worklist.pop_back_val();
895 auto *CurValue = findValueOrDie(Node);
896 if (isa<Constant>(CurValue) && !isa<GlobalValue>(CurValue))
897 continue;
898
899 for (const auto &EdgeTuple : Graph.edgesFor(Node)) {
900 auto Weight = std::get<0>(EdgeTuple);
901 auto Label = Weight.first;
902 auto &OtherNode = std::get<1>(EdgeTuple);
903 auto *OtherValue = findValueOrDie(OtherNode);
904
905 if (isa<Constant>(OtherValue) && !isa<GlobalValue>(OtherValue))
906 continue;
907
908 bool Added;
909 switch (directionOfEdgeType(Label)) {
910 case Level::Above:
911 Added = Builder.addAbove(CurValue, OtherValue);
912 break;
913 case Level::Below:
914 Added = Builder.addBelow(CurValue, OtherValue);
915 break;
916 case Level::Same:
917 Added = Builder.addWith(CurValue, OtherValue);
918 break;
919 }
920
921 if (Added) {
922 auto Aliasing = Weight.second;
923 if (auto MaybeCurIndex = valueToAttrIndex(CurValue))
924 Aliasing.set(*MaybeCurIndex);
925 if (auto MaybeOtherIndex = valueToAttrIndex(OtherValue))
926 Aliasing.set(*MaybeOtherIndex);
927 Builder.noteAttributes(CurValue, Aliasing);
928 Builder.noteAttributes(OtherValue, Aliasing);
929 Worklist.push_back(OtherNode);
930 }
931 }
932 }
933 }
934
935 // There are times when we end up with parameters not in our graph (i.e. if
936 // it's only used as the condition of a branch). Other bits of code depend on
937 // things that were present during construction being present in the graph.
938 // So, we add all present arguments here.
939 for (auto &Arg : Fn->args()) {
940 Builder.add(&Arg);
941 }
942
943 return FunctionInfo(Builder.build(), std::move(ReturnedValues));
944 }
945
scan(Function * Fn)946 void CFLAliasAnalysis::scan(Function *Fn) {
947 auto InsertPair = Cache.insert(std::make_pair(Fn, Optional<FunctionInfo>()));
948 (void)InsertPair;
949 assert(InsertPair.second &&
950 "Trying to scan a function that has already been cached");
951
952 FunctionInfo Info(buildSetsFrom(*this, Fn));
953 Cache[Fn] = std::move(Info);
954 Handles.push_front(FunctionHandle(Fn, this));
955 }
956
957 AliasAnalysis::AliasResult
query(const AliasAnalysis::Location & LocA,const AliasAnalysis::Location & LocB)958 CFLAliasAnalysis::query(const AliasAnalysis::Location &LocA,
959 const AliasAnalysis::Location &LocB) {
960 auto *ValA = const_cast<Value *>(LocA.Ptr);
961 auto *ValB = const_cast<Value *>(LocB.Ptr);
962
963 Function *Fn = nullptr;
964 auto MaybeFnA = parentFunctionOfValue(ValA);
965 auto MaybeFnB = parentFunctionOfValue(ValB);
966 if (!MaybeFnA.hasValue() && !MaybeFnB.hasValue()) {
967 llvm_unreachable("Don't know how to extract the parent function "
968 "from values A or B");
969 }
970
971 if (MaybeFnA.hasValue()) {
972 Fn = *MaybeFnA;
973 assert((!MaybeFnB.hasValue() || *MaybeFnB == *MaybeFnA) &&
974 "Interprocedural queries not supported");
975 } else {
976 Fn = *MaybeFnB;
977 }
978
979 assert(Fn != nullptr);
980 auto &MaybeInfo = ensureCached(Fn);
981 assert(MaybeInfo.hasValue());
982
983 auto &Sets = MaybeInfo->Sets;
984 auto MaybeA = Sets.find(ValA);
985 if (!MaybeA.hasValue())
986 return AliasAnalysis::MayAlias;
987
988 auto MaybeB = Sets.find(ValB);
989 if (!MaybeB.hasValue())
990 return AliasAnalysis::MayAlias;
991
992 auto SetA = *MaybeA;
993 auto SetB = *MaybeB;
994
995 if (SetA.Index == SetB.Index)
996 return AliasAnalysis::PartialAlias;
997
998 auto AttrsA = Sets.getLink(SetA.Index).Attrs;
999 auto AttrsB = Sets.getLink(SetB.Index).Attrs;
1000 // Stratified set attributes are used as markets to signify whether a member
1001 // of a StratifiedSet (or a member of a set above the current set) has
1002 // interacted with either arguments or globals. "Interacted with" meaning
1003 // its value may be different depending on the value of an argument or
1004 // global. The thought behind this is that, because arguments and globals
1005 // may alias each other, if AttrsA and AttrsB have touched args/globals,
1006 // we must conservatively say that they alias. However, if at least one of
1007 // the sets has no values that could legally be altered by changing the value
1008 // of an argument or global, then we don't have to be as conservative.
1009 if (AttrsA.any() && AttrsB.any())
1010 return AliasAnalysis::MayAlias;
1011
1012 return AliasAnalysis::NoAlias;
1013 }
1014