1 //===- CFLAliasAnalysis.cpp - CFL-Based Alias Analysis Implementation ------==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
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.
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
29 //===----------------------------------------------------------------------===//
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/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
50 #include <forward_list>
55 #define DEBUG_TYPE "cfl-aa"
57 // Try to go from a Value* to a Function*. Never returns nullptr.
58 static Optional<Function *> parentFunctionOfValue(Value *);
60 // Returns possible functions called by the Inst* into the given
61 // SmallVectorImpl. Returns true if targets found, false otherwise.
62 // This is templated because InvokeInst/CallInst give us the same
63 // set of functions that we care about, and I don't like repeating
65 template <typename Inst>
66 static bool getPossibleTargets(Inst *, SmallVectorImpl<Function *> &);
68 // Some instructions need to have their users tracked. Instructions like
69 // `add` require you to get the users of the Instruction* itself, other
70 // instructions like `store` require you to get the users of the first
71 // operand. This function gets the "proper" value to track for each
72 // type of instruction we support.
73 static Optional<Value *> getTargetValue(Instruction *);
75 // There are certain instructions (i.e. FenceInst, etc.) that we ignore.
76 // This notes that we should ignore those.
77 static bool hasUsefulEdges(Instruction *);
79 const StratifiedIndex StratifiedLink::SetSentinel =
80 std::numeric_limits<StratifiedIndex>::max();
83 // StratifiedInfo Attribute things.
84 typedef unsigned StratifiedAttr;
85 LLVM_CONSTEXPR unsigned MaxStratifiedAttrIndex = NumStratifiedAttrs;
86 LLVM_CONSTEXPR unsigned AttrAllIndex = 0;
87 LLVM_CONSTEXPR unsigned AttrGlobalIndex = 1;
88 LLVM_CONSTEXPR unsigned AttrFirstArgIndex = 2;
89 LLVM_CONSTEXPR unsigned AttrLastArgIndex = MaxStratifiedAttrIndex;
90 LLVM_CONSTEXPR unsigned AttrMaxNumArgs = AttrLastArgIndex - AttrFirstArgIndex;
92 LLVM_CONSTEXPR StratifiedAttr AttrNone = 0;
93 LLVM_CONSTEXPR StratifiedAttr AttrAll = ~AttrNone;
95 // \brief StratifiedSets call for knowledge of "direction", so this is how we
96 // represent that locally.
97 enum class Level { Same, Above, Below };
99 // \brief Edges can be one of four "weights" -- each weight must have an inverse
100 // weight (Assign has Assign; Reference has Dereference).
101 enum class EdgeType {
102 // The weight assigned when assigning from or to a value. For example, in:
103 // %b = getelementptr %a, 0
104 // ...The relationships are %b assign %a, and %a assign %b. This used to be
105 // two edges, but having a distinction bought us nothing.
108 // The edge used when we have an edge going from some handle to a Value.
109 // Examples of this include:
110 // %b = load %a (%b Dereference %a)
111 // %b = extractelement %a, 0 (%a Dereference %b)
114 // The edge used when our edge goes from a value to a handle that may have
115 // contained it at some point. Examples:
116 // %b = load %a (%a Reference %b)
117 // %b = extractelement %a, 0 (%b Reference %a)
121 // \brief Encodes the notion of a "use"
123 // \brief Which value the edge is coming from
126 // \brief Which value the edge is pointing to
129 // \brief Edge weight
132 // \brief Whether we aliased any external values along the way that may be
133 // invisible to the analysis (i.e. landingpad for exceptions, calls for
134 // interprocedural analysis, etc.)
135 StratifiedAttrs AdditionalAttrs;
137 Edge(Value *From, Value *To, EdgeType W, StratifiedAttrs A)
138 : From(From), To(To), Weight(W), AdditionalAttrs(A) {}
141 // \brief Information we have about a function and would like to keep around
142 struct FunctionInfo {
143 StratifiedSets<Value *> Sets;
144 // Lots of functions have < 4 returns. Adjust as necessary.
145 SmallVector<Value *, 4> ReturnedValues;
147 FunctionInfo(StratifiedSets<Value *> &&S,
148 SmallVector<Value *, 4> &&RV)
149 : Sets(std::move(S)), ReturnedValues(std::move(RV)) {}
152 struct CFLAliasAnalysis;
154 struct FunctionHandle : public CallbackVH {
155 FunctionHandle(Function *Fn, CFLAliasAnalysis *CFLAA)
156 : CallbackVH(Fn), CFLAA(CFLAA) {
157 assert(Fn != nullptr);
158 assert(CFLAA != nullptr);
161 virtual ~FunctionHandle() {}
163 void deleted() override { removeSelfFromCache(); }
164 void allUsesReplacedWith(Value *) override { removeSelfFromCache(); }
167 CFLAliasAnalysis *CFLAA;
169 void removeSelfFromCache();
172 struct CFLAliasAnalysis : public ImmutablePass, public AliasAnalysis {
174 /// \brief Cached mapping of Functions to their StratifiedSets.
175 /// If a function's sets are currently being built, it is marked
176 /// in the cache as an Optional without a value. This way, if we
177 /// have any kind of recursion, it is discernable from a function
178 /// that simply has empty sets.
179 DenseMap<Function *, Optional<FunctionInfo>> Cache;
180 std::forward_list<FunctionHandle> Handles;
185 CFLAliasAnalysis() : ImmutablePass(ID) {
186 initializeCFLAliasAnalysisPass(*PassRegistry::getPassRegistry());
189 virtual ~CFLAliasAnalysis() {}
191 void getAnalysisUsage(AnalysisUsage &AU) const override {
192 AliasAnalysis::getAnalysisUsage(AU);
195 void *getAdjustedAnalysisPointer(const void *ID) override {
196 if (ID == &AliasAnalysis::ID)
197 return (AliasAnalysis *)this;
201 /// \brief Inserts the given Function into the cache.
202 void scan(Function *Fn);
204 void evict(Function *Fn) { Cache.erase(Fn); }
206 /// \brief Ensures that the given function is available in the cache.
207 /// Returns the appropriate entry from the cache.
208 const Optional<FunctionInfo> &ensureCached(Function *Fn) {
209 auto Iter = Cache.find(Fn);
210 if (Iter == Cache.end()) {
212 Iter = Cache.find(Fn);
213 assert(Iter != Cache.end());
214 assert(Iter->second.hasValue());
219 AliasResult query(const Location &LocA, const Location &LocB);
221 AliasResult alias(const Location &LocA, const Location &LocB) override {
222 if (LocA.Ptr == LocB.Ptr) {
223 if (LocA.Size == LocB.Size) {
230 // Comparisons between global variables and other constants should be
231 // handled by BasicAA.
232 if (isa<Constant>(LocA.Ptr) && isa<Constant>(LocB.Ptr)) {
233 return AliasAnalysis::alias(LocA, LocB);
236 AliasResult QueryResult = query(LocA, LocB);
237 if (QueryResult == MayAlias)
238 return AliasAnalysis::alias(LocA, LocB);
243 void initializePass() override { InitializeAliasAnalysis(this); }
246 void FunctionHandle::removeSelfFromCache() {
247 assert(CFLAA != nullptr);
248 auto *Val = getValPtr();
249 CFLAA->evict(cast<Function>(Val));
253 // \brief Gets the edges our graph should have, based on an Instruction*
254 class GetEdgesVisitor : public InstVisitor<GetEdgesVisitor, void> {
255 CFLAliasAnalysis &AA;
256 SmallVectorImpl<Edge> &Output;
259 GetEdgesVisitor(CFLAliasAnalysis &AA, SmallVectorImpl<Edge> &Output)
260 : AA(AA), Output(Output) {}
262 void visitInstruction(Instruction &) {
263 llvm_unreachable("Unsupported instruction encountered");
266 void visitCastInst(CastInst &Inst) {
267 Output.push_back(Edge(&Inst, Inst.getOperand(0), EdgeType::Assign,
271 void visitBinaryOperator(BinaryOperator &Inst) {
272 auto *Op1 = Inst.getOperand(0);
273 auto *Op2 = Inst.getOperand(1);
274 Output.push_back(Edge(&Inst, Op1, EdgeType::Assign, AttrNone));
275 Output.push_back(Edge(&Inst, Op2, EdgeType::Assign, AttrNone));
278 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
279 auto *Ptr = Inst.getPointerOperand();
280 auto *Val = Inst.getNewValOperand();
281 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
284 void visitAtomicRMWInst(AtomicRMWInst &Inst) {
285 auto *Ptr = Inst.getPointerOperand();
286 auto *Val = Inst.getValOperand();
287 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
290 void visitPHINode(PHINode &Inst) {
291 for (unsigned I = 0, E = Inst.getNumIncomingValues(); I != E; ++I) {
292 Value *Val = Inst.getIncomingValue(I);
293 Output.push_back(Edge(&Inst, Val, EdgeType::Assign, AttrNone));
297 void visitGetElementPtrInst(GetElementPtrInst &Inst) {
298 auto *Op = Inst.getPointerOperand();
299 Output.push_back(Edge(&Inst, Op, EdgeType::Assign, AttrNone));
300 for (auto I = Inst.idx_begin(), E = Inst.idx_end(); I != E; ++I)
301 Output.push_back(Edge(&Inst, *I, EdgeType::Assign, AttrNone));
304 void visitSelectInst(SelectInst &Inst) {
305 // Condition is not processed here (The actual statement producing
306 // the condition result is processed elsewhere). For select, the
307 // condition is evaluated, but not loaded, stored, or assigned
308 // simply as a result of being the condition of a select.
310 auto *TrueVal = Inst.getTrueValue();
311 Output.push_back(Edge(&Inst, TrueVal, EdgeType::Assign, AttrNone));
312 auto *FalseVal = Inst.getFalseValue();
313 Output.push_back(Edge(&Inst, FalseVal, EdgeType::Assign, AttrNone));
316 void visitAllocaInst(AllocaInst &) {}
318 void visitLoadInst(LoadInst &Inst) {
319 auto *Ptr = Inst.getPointerOperand();
321 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
324 void visitStoreInst(StoreInst &Inst) {
325 auto *Ptr = Inst.getPointerOperand();
326 auto *Val = Inst.getValueOperand();
327 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
330 void visitVAArgInst(VAArgInst &Inst) {
331 // We can't fully model va_arg here. For *Ptr = Inst.getOperand(0), it does
333 // 1. Loads a value from *((T*)*Ptr).
334 // 2. Increments (stores to) *Ptr by some target-specific amount.
335 // For now, we'll handle this like a landingpad instruction (by placing the
336 // result in its own group, and having that group alias externals).
338 Output.push_back(Edge(Val, Val, EdgeType::Assign, AttrAll));
341 static bool isFunctionExternal(Function *Fn) {
342 return Fn->isDeclaration() || !Fn->hasLocalLinkage();
345 // Gets whether the sets at Index1 above, below, or equal to the sets at
346 // Index2. Returns None if they are not in the same set chain.
347 static Optional<Level> getIndexRelation(const StratifiedSets<Value *> &Sets,
348 StratifiedIndex Index1,
349 StratifiedIndex Index2) {
350 if (Index1 == Index2)
353 const auto *Current = &Sets.getLink(Index1);
354 while (Current->hasBelow()) {
355 if (Current->Below == Index2)
357 Current = &Sets.getLink(Current->Below);
360 Current = &Sets.getLink(Index1);
361 while (Current->hasAbove()) {
362 if (Current->Above == Index2)
364 Current = &Sets.getLink(Current->Above);
371 tryInterproceduralAnalysis(const SmallVectorImpl<Function *> &Fns,
373 const iterator_range<User::op_iterator> &Args) {
374 const unsigned ExpectedMaxArgs = 8;
375 const unsigned MaxSupportedArgs = 50;
376 assert(Fns.size() > 0);
378 // I put this here to give us an upper bound on time taken by IPA. Is it
379 // really (realistically) needed? Keep in mind that we do have an n^2 algo.
380 if (std::distance(Args.begin(), Args.end()) > (int) MaxSupportedArgs)
383 // Exit early if we'll fail anyway
384 for (auto *Fn : Fns) {
385 if (isFunctionExternal(Fn) || Fn->isVarArg())
387 auto &MaybeInfo = AA.ensureCached(Fn);
388 if (!MaybeInfo.hasValue())
392 SmallVector<Value *, ExpectedMaxArgs> Arguments(Args.begin(), Args.end());
393 SmallVector<StratifiedInfo, ExpectedMaxArgs> Parameters;
394 for (auto *Fn : Fns) {
395 auto &Info = *AA.ensureCached(Fn);
396 auto &Sets = Info.Sets;
397 auto &RetVals = Info.ReturnedValues;
400 for (auto &Param : Fn->args()) {
401 auto MaybeInfo = Sets.find(&Param);
402 // Did a new parameter somehow get added to the function/slip by?
403 if (!MaybeInfo.hasValue())
405 Parameters.push_back(*MaybeInfo);
408 // Adding an edge from argument -> return value for each parameter that
409 // may alias the return value
410 for (unsigned I = 0, E = Parameters.size(); I != E; ++I) {
411 auto &ParamInfo = Parameters[I];
412 auto &ArgVal = Arguments[I];
413 bool AddEdge = false;
414 StratifiedAttrs Externals;
415 for (unsigned X = 0, XE = RetVals.size(); X != XE; ++X) {
416 auto MaybeInfo = Sets.find(RetVals[X]);
417 if (!MaybeInfo.hasValue())
420 auto &RetInfo = *MaybeInfo;
421 auto RetAttrs = Sets.getLink(RetInfo.Index).Attrs;
422 auto ParamAttrs = Sets.getLink(ParamInfo.Index).Attrs;
424 getIndexRelation(Sets, ParamInfo.Index, RetInfo.Index);
425 if (MaybeRelation.hasValue()) {
427 Externals |= RetAttrs | ParamAttrs;
431 Output.push_back(Edge(FuncValue, ArgVal, EdgeType::Assign,
432 StratifiedAttrs().flip()));
435 if (Parameters.size() != Arguments.size())
438 // Adding edges between arguments for arguments that may end up aliasing
439 // each other. This is necessary for functions such as
440 // void foo(int** a, int** b) { *a = *b; }
441 // (Technically, the proper sets for this would be those below
442 // Arguments[I] and Arguments[X], but our algorithm will produce
443 // extremely similar, and equally correct, results either way)
444 for (unsigned I = 0, E = Arguments.size(); I != E; ++I) {
445 auto &MainVal = Arguments[I];
446 auto &MainInfo = Parameters[I];
447 auto &MainAttrs = Sets.getLink(MainInfo.Index).Attrs;
448 for (unsigned X = I + 1; X != E; ++X) {
449 auto &SubInfo = Parameters[X];
450 auto &SubVal = Arguments[X];
451 auto &SubAttrs = Sets.getLink(SubInfo.Index).Attrs;
453 getIndexRelation(Sets, MainInfo.Index, SubInfo.Index);
455 if (!MaybeRelation.hasValue())
458 auto NewAttrs = SubAttrs | MainAttrs;
459 Output.push_back(Edge(MainVal, SubVal, EdgeType::Assign, NewAttrs));
466 template <typename InstT> void visitCallLikeInst(InstT &Inst) {
467 SmallVector<Function *, 4> Targets;
468 if (getPossibleTargets(&Inst, Targets)) {
469 if (tryInterproceduralAnalysis(Targets, &Inst, Inst.arg_operands()))
471 // Cleanup from interprocedural analysis
475 for (Value *V : Inst.arg_operands())
476 Output.push_back(Edge(&Inst, V, EdgeType::Assign, AttrAll));
479 void visitCallInst(CallInst &Inst) { visitCallLikeInst(Inst); }
481 void visitInvokeInst(InvokeInst &Inst) { visitCallLikeInst(Inst); }
483 // Because vectors/aggregates are immutable and unaddressable,
484 // there's nothing we can do to coax a value out of them, other
485 // than calling Extract{Element,Value}. We can effectively treat
486 // them as pointers to arbitrary memory locations we can store in
488 void visitExtractElementInst(ExtractElementInst &Inst) {
489 auto *Ptr = Inst.getVectorOperand();
491 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
494 void visitInsertElementInst(InsertElementInst &Inst) {
495 auto *Vec = Inst.getOperand(0);
496 auto *Val = Inst.getOperand(1);
497 Output.push_back(Edge(&Inst, Vec, EdgeType::Assign, AttrNone));
498 Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
501 void visitLandingPadInst(LandingPadInst &Inst) {
502 // Exceptions come from "nowhere", from our analysis' perspective.
503 // So we place the instruction its own group, noting that said group may
505 Output.push_back(Edge(&Inst, &Inst, EdgeType::Assign, AttrAll));
508 void visitInsertValueInst(InsertValueInst &Inst) {
509 auto *Agg = Inst.getOperand(0);
510 auto *Val = Inst.getOperand(1);
511 Output.push_back(Edge(&Inst, Agg, EdgeType::Assign, AttrNone));
512 Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
515 void visitExtractValueInst(ExtractValueInst &Inst) {
516 auto *Ptr = Inst.getAggregateOperand();
517 Output.push_back(Edge(&Inst, Ptr, EdgeType::Reference, AttrNone));
520 void visitShuffleVectorInst(ShuffleVectorInst &Inst) {
521 auto *From1 = Inst.getOperand(0);
522 auto *From2 = Inst.getOperand(1);
523 Output.push_back(Edge(&Inst, From1, EdgeType::Assign, AttrNone));
524 Output.push_back(Edge(&Inst, From2, EdgeType::Assign, AttrNone));
528 // For a given instruction, we need to know which Value* to get the
529 // users of in order to build our graph. In some cases (i.e. add),
530 // we simply need the Instruction*. In other cases (i.e. store),
531 // finding the users of the Instruction* is useless; we need to find
532 // the users of the first operand. This handles determining which
533 // value to follow for us.
535 // Note: we *need* to keep this in sync with GetEdgesVisitor. Add
536 // something to GetEdgesVisitor, add it here -- remove something from
537 // GetEdgesVisitor, remove it here.
538 class GetTargetValueVisitor
539 : public InstVisitor<GetTargetValueVisitor, Value *> {
541 Value *visitInstruction(Instruction &Inst) { return &Inst; }
543 Value *visitStoreInst(StoreInst &Inst) { return Inst.getPointerOperand(); }
545 Value *visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
546 return Inst.getPointerOperand();
549 Value *visitAtomicRMWInst(AtomicRMWInst &Inst) {
550 return Inst.getPointerOperand();
553 Value *visitInsertElementInst(InsertElementInst &Inst) {
554 return Inst.getOperand(0);
557 Value *visitInsertValueInst(InsertValueInst &Inst) {
558 return Inst.getAggregateOperand();
562 // Set building requires a weighted bidirectional graph.
563 template <typename EdgeTypeT> class WeightedBidirectionalGraph {
565 typedef std::size_t Node;
568 const static Node StartNode = Node(0);
574 Edge(const EdgeTypeT &W, const Node &N)
575 : Weight(W), Other(N) {}
577 bool operator==(const Edge &E) const {
578 return Weight == E.Weight && Other == E.Other;
581 bool operator!=(const Edge &E) const { return !operator==(E); }
585 std::vector<Edge> Edges;
588 std::vector<NodeImpl> NodeImpls;
590 bool inbounds(Node NodeIndex) const { return NodeIndex < NodeImpls.size(); }
592 const NodeImpl &getNode(Node N) const { return NodeImpls[N]; }
593 NodeImpl &getNode(Node N) { return NodeImpls[N]; }
596 // ----- Various Edge iterators for the graph ----- //
598 // \brief Iterator for edges. Because this graph is bidirected, we don't
599 // allow modificaiton of the edges using this iterator. Additionally, the
600 // iterator becomes invalid if you add edges to or from the node you're
601 // getting the edges of.
602 struct EdgeIterator : public std::iterator<std::forward_iterator_tag,
603 std::tuple<EdgeTypeT, Node *>> {
604 EdgeIterator(const typename std::vector<Edge>::const_iterator &Iter)
607 EdgeIterator(NodeImpl &Impl) : Current(Impl.begin()) {}
609 EdgeIterator &operator++() {
614 EdgeIterator operator++(int) {
615 EdgeIterator Copy(Current);
620 std::tuple<EdgeTypeT, Node> &operator*() {
621 Store = std::make_tuple(Current->Weight, Current->Other);
625 bool operator==(const EdgeIterator &Other) const {
626 return Current == Other.Current;
629 bool operator!=(const EdgeIterator &Other) const {
630 return !operator==(Other);
634 typename std::vector<Edge>::const_iterator Current;
635 std::tuple<EdgeTypeT, Node> Store;
638 // Wrapper for EdgeIterator with begin()/end() calls.
639 struct EdgeIterable {
640 EdgeIterable(const std::vector<Edge> &Edges)
641 : BeginIter(Edges.begin()), EndIter(Edges.end()) {}
643 EdgeIterator begin() { return EdgeIterator(BeginIter); }
645 EdgeIterator end() { return EdgeIterator(EndIter); }
648 typename std::vector<Edge>::const_iterator BeginIter;
649 typename std::vector<Edge>::const_iterator EndIter;
652 // ----- Actual graph-related things ----- //
654 WeightedBidirectionalGraph() {}
656 WeightedBidirectionalGraph(WeightedBidirectionalGraph<EdgeTypeT> &&Other)
657 : NodeImpls(std::move(Other.NodeImpls)) {}
659 WeightedBidirectionalGraph<EdgeTypeT> &
660 operator=(WeightedBidirectionalGraph<EdgeTypeT> &&Other) {
661 NodeImpls = std::move(Other.NodeImpls);
666 auto Index = NodeImpls.size();
667 auto NewNode = Node(Index);
668 NodeImpls.push_back(NodeImpl());
672 void addEdge(Node From, Node To, const EdgeTypeT &Weight,
673 const EdgeTypeT &ReverseWeight) {
674 assert(inbounds(From));
675 assert(inbounds(To));
676 auto &FromNode = getNode(From);
677 auto &ToNode = getNode(To);
678 FromNode.Edges.push_back(Edge(Weight, To));
679 ToNode.Edges.push_back(Edge(ReverseWeight, From));
682 EdgeIterable edgesFor(const Node &N) const {
683 const auto &Node = getNode(N);
684 return EdgeIterable(Node.Edges);
687 bool empty() const { return NodeImpls.empty(); }
688 std::size_t size() const { return NodeImpls.size(); }
690 // \brief Gets an arbitrary node in the graph as a starting point for
692 Node getEntryNode() {
693 assert(inbounds(StartNode));
698 typedef WeightedBidirectionalGraph<std::pair<EdgeType, StratifiedAttrs>> GraphT;
699 typedef DenseMap<Value *, GraphT::Node> NodeMapT;
702 // -- Setting up/registering CFLAA pass -- //
703 char CFLAliasAnalysis::ID = 0;
705 INITIALIZE_AG_PASS(CFLAliasAnalysis, AliasAnalysis, "cfl-aa",
706 "CFL-Based AA implementation", false, true, false)
708 ImmutablePass *llvm::createCFLAliasAnalysisPass() {
709 return new CFLAliasAnalysis();
712 //===----------------------------------------------------------------------===//
713 // Function declarations that require types defined in the namespace above
714 //===----------------------------------------------------------------------===//
716 // Given an argument number, returns the appropriate Attr index to set.
717 static StratifiedAttr argNumberToAttrIndex(StratifiedAttr);
719 // Given a Value, potentially return which AttrIndex it maps to.
720 static Optional<StratifiedAttr> valueToAttrIndex(Value *Val);
722 // Gets the inverse of a given EdgeType.
723 static EdgeType flipWeight(EdgeType);
725 // Gets edges of the given Instruction*, writing them to the SmallVector*.
726 static void argsToEdges(CFLAliasAnalysis &, Instruction *,
727 SmallVectorImpl<Edge> &);
729 // Gets the "Level" that one should travel in StratifiedSets
730 // given an EdgeType.
731 static Level directionOfEdgeType(EdgeType);
733 // Builds the graph needed for constructing the StratifiedSets for the
735 static void buildGraphFrom(CFLAliasAnalysis &, Function *,
736 SmallVectorImpl<Value *> &, NodeMapT &, GraphT &);
738 // Builds the graph + StratifiedSets for a function.
739 static FunctionInfo buildSetsFrom(CFLAliasAnalysis &, Function *);
741 static Optional<Function *> parentFunctionOfValue(Value *Val) {
742 if (auto *Inst = dyn_cast<Instruction>(Val)) {
743 auto *Bb = Inst->getParent();
744 return Bb->getParent();
747 if (auto *Arg = dyn_cast<Argument>(Val))
748 return Arg->getParent();
752 template <typename Inst>
753 static bool getPossibleTargets(Inst *Call,
754 SmallVectorImpl<Function *> &Output) {
755 if (auto *Fn = Call->getCalledFunction()) {
756 Output.push_back(Fn);
760 // TODO: If the call is indirect, we might be able to enumerate all potential
761 // targets of the call and return them, rather than just failing.
765 static Optional<Value *> getTargetValue(Instruction *Inst) {
766 GetTargetValueVisitor V;
767 return V.visit(Inst);
770 static bool hasUsefulEdges(Instruction *Inst) {
771 bool IsNonInvokeTerminator =
772 isa<TerminatorInst>(Inst) && !isa<InvokeInst>(Inst);
773 return !isa<CmpInst>(Inst) && !isa<FenceInst>(Inst) && !IsNonInvokeTerminator;
776 static Optional<StratifiedAttr> valueToAttrIndex(Value *Val) {
777 if (isa<GlobalValue>(Val))
778 return AttrGlobalIndex;
780 if (auto *Arg = dyn_cast<Argument>(Val))
781 // Only pointer arguments should have the argument attribute,
782 // because things can't escape through scalars without us seeing a
783 // cast, and thus, interaction with them doesn't matter.
784 if (!Arg->hasNoAliasAttr() && Arg->getType()->isPointerTy())
785 return argNumberToAttrIndex(Arg->getArgNo());
789 static StratifiedAttr argNumberToAttrIndex(unsigned ArgNum) {
790 if (ArgNum >= AttrMaxNumArgs)
792 return ArgNum + AttrFirstArgIndex;
795 static EdgeType flipWeight(EdgeType Initial) {
797 case EdgeType::Assign:
798 return EdgeType::Assign;
799 case EdgeType::Dereference:
800 return EdgeType::Reference;
801 case EdgeType::Reference:
802 return EdgeType::Dereference;
804 llvm_unreachable("Incomplete coverage of EdgeType enum");
807 static void argsToEdges(CFLAliasAnalysis &Analysis, Instruction *Inst,
808 SmallVectorImpl<Edge> &Output) {
809 GetEdgesVisitor v(Analysis, Output);
813 static Level directionOfEdgeType(EdgeType Weight) {
815 case EdgeType::Reference:
817 case EdgeType::Dereference:
819 case EdgeType::Assign:
822 llvm_unreachable("Incomplete switch coverage");
825 // Aside: We may remove graph construction entirely, because it doesn't really
826 // buy us much that we don't already have. I'd like to add interprocedural
827 // analysis prior to this however, in case that somehow requires the graph
828 // produced by this for efficient execution
829 static void buildGraphFrom(CFLAliasAnalysis &Analysis, Function *Fn,
830 SmallVectorImpl<Value *> &ReturnedValues,
831 NodeMapT &Map, GraphT &Graph) {
832 const auto findOrInsertNode = [&Map, &Graph](Value *Val) {
833 auto Pair = Map.insert(std::make_pair(Val, GraphT::Node()));
834 auto &Iter = Pair.first;
836 auto NewNode = Graph.addNode();
837 Iter->second = NewNode;
842 SmallVector<Edge, 8> Edges;
843 for (auto &Bb : Fn->getBasicBlockList()) {
844 for (auto &Inst : Bb.getInstList()) {
845 // We don't want the edges of most "return" instructions, but we *do* want
846 // to know what can be returned.
847 if (auto *Ret = dyn_cast<ReturnInst>(&Inst))
848 ReturnedValues.push_back(Ret);
850 if (!hasUsefulEdges(&Inst))
854 argsToEdges(Analysis, &Inst, Edges);
856 // In the case of an unused alloca (or similar), edges may be empty. Note
857 // that it exists so we can potentially answer NoAlias.
859 auto MaybeVal = getTargetValue(&Inst);
860 assert(MaybeVal.hasValue());
861 auto *Target = *MaybeVal;
862 findOrInsertNode(Target);
866 for (const Edge &E : Edges) {
867 auto To = findOrInsertNode(E.To);
868 auto From = findOrInsertNode(E.From);
869 auto FlippedWeight = flipWeight(E.Weight);
870 auto Attrs = E.AdditionalAttrs;
871 Graph.addEdge(From, To, std::make_pair(E.Weight, Attrs),
872 std::make_pair(FlippedWeight, Attrs));
878 static FunctionInfo buildSetsFrom(CFLAliasAnalysis &Analysis, Function *Fn) {
881 SmallVector<Value *, 4> ReturnedValues;
883 buildGraphFrom(Analysis, Fn, ReturnedValues, Map, Graph);
885 DenseMap<GraphT::Node, Value *> NodeValueMap;
886 NodeValueMap.resize(Map.size());
887 for (const auto &Pair : Map)
888 NodeValueMap.insert(std::make_pair(Pair.second, Pair.first));
890 const auto findValueOrDie = [&NodeValueMap](GraphT::Node Node) {
891 auto ValIter = NodeValueMap.find(Node);
892 assert(ValIter != NodeValueMap.end());
893 return ValIter->second;
896 StratifiedSetsBuilder<Value *> Builder;
898 SmallVector<GraphT::Node, 16> Worklist;
899 for (auto &Pair : Map) {
902 auto *Value = Pair.first;
904 auto InitialNode = Pair.second;
905 Worklist.push_back(InitialNode);
906 while (!Worklist.empty()) {
907 auto Node = Worklist.pop_back_val();
908 auto *CurValue = findValueOrDie(Node);
909 if (isa<Constant>(CurValue) && !isa<GlobalValue>(CurValue))
912 for (const auto &EdgeTuple : Graph.edgesFor(Node)) {
913 auto Weight = std::get<0>(EdgeTuple);
914 auto Label = Weight.first;
915 auto &OtherNode = std::get<1>(EdgeTuple);
916 auto *OtherValue = findValueOrDie(OtherNode);
918 if (isa<Constant>(OtherValue) && !isa<GlobalValue>(OtherValue))
922 switch (directionOfEdgeType(Label)) {
924 Added = Builder.addAbove(CurValue, OtherValue);
927 Added = Builder.addBelow(CurValue, OtherValue);
930 Added = Builder.addWith(CurValue, OtherValue);
935 auto Aliasing = Weight.second;
936 if (auto MaybeCurIndex = valueToAttrIndex(CurValue))
937 Aliasing.set(*MaybeCurIndex);
938 if (auto MaybeOtherIndex = valueToAttrIndex(OtherValue))
939 Aliasing.set(*MaybeOtherIndex);
940 Builder.noteAttributes(CurValue, Aliasing);
941 Builder.noteAttributes(OtherValue, Aliasing);
942 Worklist.push_back(OtherNode);
948 // There are times when we end up with parameters not in our graph (i.e. if
949 // it's only used as the condition of a branch). Other bits of code depend on
950 // things that were present during construction being present in the graph.
951 // So, we add all present arguments here.
952 for (auto &Arg : Fn->args()) {
956 return FunctionInfo(Builder.build(), std::move(ReturnedValues));
959 void CFLAliasAnalysis::scan(Function *Fn) {
960 auto InsertPair = Cache.insert(std::make_pair(Fn, Optional<FunctionInfo>()));
962 assert(InsertPair.second &&
963 "Trying to scan a function that has already been cached");
965 FunctionInfo Info(buildSetsFrom(*this, Fn));
966 Cache[Fn] = std::move(Info);
967 Handles.push_front(FunctionHandle(Fn, this));
970 AliasAnalysis::AliasResult
971 CFLAliasAnalysis::query(const AliasAnalysis::Location &LocA,
972 const AliasAnalysis::Location &LocB) {
973 auto *ValA = const_cast<Value *>(LocA.Ptr);
974 auto *ValB = const_cast<Value *>(LocB.Ptr);
976 Function *Fn = nullptr;
977 auto MaybeFnA = parentFunctionOfValue(ValA);
978 auto MaybeFnB = parentFunctionOfValue(ValB);
979 if (!MaybeFnA.hasValue() && !MaybeFnB.hasValue()) {
980 // The only times this is known to happen are when globals + InlineAsm
982 DEBUG(dbgs() << "CFLAA: could not extract parent function information.\n");
983 return AliasAnalysis::MayAlias;
986 if (MaybeFnA.hasValue()) {
988 assert((!MaybeFnB.hasValue() || *MaybeFnB == *MaybeFnA) &&
989 "Interprocedural queries not supported");
994 assert(Fn != nullptr);
995 auto &MaybeInfo = ensureCached(Fn);
996 assert(MaybeInfo.hasValue());
998 auto &Sets = MaybeInfo->Sets;
999 auto MaybeA = Sets.find(ValA);
1000 if (!MaybeA.hasValue())
1001 return AliasAnalysis::MayAlias;
1003 auto MaybeB = Sets.find(ValB);
1004 if (!MaybeB.hasValue())
1005 return AliasAnalysis::MayAlias;
1007 auto SetA = *MaybeA;
1008 auto SetB = *MaybeB;
1009 auto AttrsA = Sets.getLink(SetA.Index).Attrs;
1010 auto AttrsB = Sets.getLink(SetB.Index).Attrs;
1012 // Stratified set attributes are used as markets to signify whether a member
1013 // of a StratifiedSet (or a member of a set above the current set) has
1014 // interacted with either arguments or globals. "Interacted with" meaning
1015 // its value may be different depending on the value of an argument or
1016 // global. The thought behind this is that, because arguments and globals
1017 // may alias each other, if AttrsA and AttrsB have touched args/globals,
1018 // we must conservatively say that they alias. However, if at least one of
1019 // the sets has no values that could legally be altered by changing the value
1020 // of an argument or global, then we don't have to be as conservative.
1021 if (AttrsA.any() && AttrsB.any())
1022 return AliasAnalysis::MayAlias;
1024 // We currently unify things even if the accesses to them may not be in
1025 // bounds, so we can't return partial alias here because we don't
1026 // know whether the pointer is really within the object or not.
1027 // IE Given an out of bounds GEP and an alloca'd pointer, we may
1028 // unify the two. We can't return partial alias for this case.
1029 // Since we do not currently track enough information to
1032 if (SetA.Index == SetB.Index)
1033 return AliasAnalysis::MayAlias;
1035 return AliasAnalysis::NoAlias;