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