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/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"
45 #include "llvm/Support/Compiler.h"
46 #include "llvm/Support/ErrorHandling.h"
49 #include <forward_list>
54 // Try to go from a Value* to a Function*. Never returns nullptr.
55 static Optional<Function *> parentFunctionOfValue(Value *);
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
62 template <typename Inst>
63 static bool getPossibleTargets(Inst *, SmallVectorImpl<Function *> &);
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 *);
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 *);
77 // StratifiedInfo Attribute things.
78 typedef unsigned StratifiedAttr;
79 LLVM_CONSTEXPR unsigned MaxStratifiedAttrIndex = NumStratifiedAttrs;
80 LLVM_CONSTEXPR unsigned AttrAllIndex = 0;
81 LLVM_CONSTEXPR unsigned AttrGlobalIndex = 1;
82 LLVM_CONSTEXPR unsigned AttrFirstArgIndex = 2;
83 LLVM_CONSTEXPR unsigned AttrLastArgIndex = MaxStratifiedAttrIndex;
84 LLVM_CONSTEXPR unsigned AttrMaxNumArgs = AttrLastArgIndex - AttrFirstArgIndex;
86 LLVM_CONSTEXPR StratifiedAttr AttrNone = 0;
87 LLVM_CONSTEXPR StratifiedAttr AttrAll = ~AttrNone;
89 // \brief StratifiedSets call for knowledge of "direction", so this is how we
90 // represent that locally.
91 enum class Level { Same, Above, Below };
93 // \brief Edges can be one of four "weights" -- each weight must have an inverse
94 // weight (Assign has Assign; Reference has Dereference).
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.
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)
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)
115 // \brief Encodes the notion of a "use"
117 // \brief Which value the edge is coming from
120 // \brief Which value the edge is pointing to
123 // \brief Edge weight
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;
131 Edge(Value *From, Value *To, EdgeType W, StratifiedAttrs A)
132 : From(From), To(To), Weight(W), AdditionalAttrs(A) {}
135 // \brief Information we have about a function and would like to keep around
136 struct FunctionInfo {
137 StratifiedSets<Value *> Sets;
138 // Lots of functions have < 4 returns. Adjust as necessary.
139 SmallVector<Value *, 4> ReturnedValues;
142 struct CFLAliasAnalysis;
144 struct FunctionHandle : public CallbackVH {
145 FunctionHandle(Function *Fn, CFLAliasAnalysis *CFLAA)
146 : CallbackVH(Fn), CFLAA(CFLAA) {
147 assert(Fn != nullptr);
148 assert(CFLAA != nullptr);
151 virtual ~FunctionHandle() {}
153 virtual void deleted() override { removeSelfFromCache(); }
154 virtual void allUsesReplacedWith(Value *) override { removeSelfFromCache(); }
157 CFLAliasAnalysis *CFLAA;
159 void removeSelfFromCache();
162 struct CFLAliasAnalysis : public ImmutablePass, public AliasAnalysis {
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;
175 CFLAliasAnalysis() : ImmutablePass(ID) {
176 initializeCFLAliasAnalysisPass(*PassRegistry::getPassRegistry());
179 virtual ~CFLAliasAnalysis() {}
181 void getAnalysisUsage(AnalysisUsage &AU) const {
182 AliasAnalysis::getAnalysisUsage(AU);
185 void *getAdjustedAnalysisPointer(const void *ID) override {
186 if (ID == &AliasAnalysis::ID)
187 return (AliasAnalysis *)this;
191 /// \brief Inserts the given Function into the cache.
192 void scan(Function *Fn);
194 void evict(Function *Fn) { Cache.erase(Fn); }
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()) {
202 Iter = Cache.find(Fn);
203 assert(Iter != Cache.end());
204 assert(Iter->second.hasValue());
209 AliasResult query(const Location &LocA, const Location &LocB);
211 AliasResult alias(const Location &LocA, const Location &LocB) override {
212 if (LocA.Ptr == LocB.Ptr) {
213 if (LocA.Size == LocB.Size) {
220 // Comparisons between global variables and other constants should be
221 // handled by BasicAA.
222 if (isa<Constant>(LocA.Ptr) && isa<Constant>(LocB.Ptr)) {
226 return query(LocA, LocB);
229 void initializePass() override { InitializeAliasAnalysis(this); }
232 void FunctionHandle::removeSelfFromCache() {
233 assert(CFLAA != nullptr);
234 auto *Val = getValPtr();
235 CFLAA->evict(cast<Function>(Val));
239 // \brief Gets the edges our graph should have, based on an Instruction*
240 class GetEdgesVisitor : public InstVisitor<GetEdgesVisitor, void> {
241 CFLAliasAnalysis &AA;
242 SmallVectorImpl<Edge> &Output;
245 GetEdgesVisitor(CFLAliasAnalysis &AA, SmallVectorImpl<Edge> &Output)
246 : AA(AA), Output(Output) {}
248 void visitInstruction(Instruction &) {
249 llvm_unreachable("Unsupported instruction encountered");
252 void visitCastInst(CastInst &Inst) {
253 Output.push_back(Edge(&Inst, Inst.getOperand(0), EdgeType::Assign,
257 void visitBinaryOperator(BinaryOperator &Inst) {
258 auto *Op1 = Inst.getOperand(0);
259 auto *Op2 = Inst.getOperand(1);
260 Output.push_back(Edge(&Inst, Op1, EdgeType::Assign, AttrNone));
261 Output.push_back(Edge(&Inst, Op2, EdgeType::Assign, AttrNone));
264 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
265 auto *Ptr = Inst.getPointerOperand();
266 auto *Val = Inst.getNewValOperand();
267 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
270 void visitAtomicRMWInst(AtomicRMWInst &Inst) {
271 auto *Ptr = Inst.getPointerOperand();
272 auto *Val = Inst.getValOperand();
273 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
276 void visitPHINode(PHINode &Inst) {
277 for (unsigned I = 0, E = Inst.getNumIncomingValues(); I != E; ++I) {
278 Value *Val = Inst.getIncomingValue(I);
279 Output.push_back(Edge(&Inst, Val, EdgeType::Assign, AttrNone));
283 void visitGetElementPtrInst(GetElementPtrInst &Inst) {
284 auto *Op = Inst.getPointerOperand();
285 Output.push_back(Edge(&Inst, Op, EdgeType::Assign, AttrNone));
286 for (auto I = Inst.idx_begin(), E = Inst.idx_end(); I != E; ++I)
287 Output.push_back(Edge(&Inst, *I, EdgeType::Assign, AttrNone));
290 void visitSelectInst(SelectInst &Inst) {
291 auto *Condition = Inst.getCondition();
292 Output.push_back(Edge(&Inst, Condition, EdgeType::Assign, AttrNone));
293 auto *TrueVal = Inst.getTrueValue();
294 Output.push_back(Edge(&Inst, TrueVal, EdgeType::Assign, AttrNone));
295 auto *FalseVal = Inst.getFalseValue();
296 Output.push_back(Edge(&Inst, FalseVal, EdgeType::Assign, AttrNone));
299 void visitAllocaInst(AllocaInst &) {}
301 void visitLoadInst(LoadInst &Inst) {
302 auto *Ptr = Inst.getPointerOperand();
304 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
307 void visitStoreInst(StoreInst &Inst) {
308 auto *Ptr = Inst.getPointerOperand();
309 auto *Val = Inst.getValueOperand();
310 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
313 static bool isFunctionExternal(Function *Fn) {
314 return Fn->isDeclaration() || !Fn->hasLocalLinkage();
317 // Gets whether the sets at Index1 above, below, or equal to the sets at
318 // Index2. Returns None if they are not in the same set chain.
319 static Optional<Level> getIndexRelation(const StratifiedSets<Value *> &Sets,
320 StratifiedIndex Index1,
321 StratifiedIndex Index2) {
322 if (Index1 == Index2)
325 const auto *Current = &Sets.getLink(Index1);
326 while (Current->hasBelow()) {
327 if (Current->Below == Index2)
329 Current = &Sets.getLink(Current->Below);
332 Current = &Sets.getLink(Index1);
333 while (Current->hasAbove()) {
334 if (Current->Above == Index2)
336 Current = &Sets.getLink(Current->Above);
343 tryInterproceduralAnalysis(const SmallVectorImpl<Function *> &Fns,
345 const iterator_range<User::op_iterator> &Args) {
346 LLVM_CONSTEXPR unsigned ExpectedMaxArgs = 8;
347 LLVM_CONSTEXPR unsigned MaxSupportedArgs = 50;
348 assert(Fns.size() > 0);
350 // I put this here to give us an upper bound on time taken by IPA. Is it
351 // really (realistically) needed? Keep in mind that we do have an n^2 algo.
352 if (std::distance(Args.begin(), Args.end()) > MaxSupportedArgs)
355 // Exit early if we'll fail anyway
356 for (auto *Fn : Fns) {
357 if (isFunctionExternal(Fn) || Fn->isVarArg())
359 auto &MaybeInfo = AA.ensureCached(Fn);
360 if (!MaybeInfo.hasValue())
364 SmallVector<Value *, ExpectedMaxArgs> Arguments(Args.begin(), Args.end());
365 SmallVector<StratifiedInfo, ExpectedMaxArgs> Parameters;
366 for (auto *Fn : Fns) {
367 auto &Info = *AA.ensureCached(Fn);
368 auto &Sets = Info.Sets;
369 auto &RetVals = Info.ReturnedValues;
372 for (auto &Param : Fn->args()) {
373 auto MaybeInfo = Sets.find(&Param);
374 // Did a new parameter somehow get added to the function/slip by?
375 if (!MaybeInfo.hasValue())
377 Parameters.push_back(*MaybeInfo);
380 // Adding an edge from argument -> return value for each parameter that
381 // may alias the return value
382 for (unsigned I = 0, E = Parameters.size(); I != E; ++I) {
383 auto &ParamInfo = Parameters[I];
384 auto &ArgVal = Arguments[I];
385 bool AddEdge = false;
386 StratifiedAttrs Externals;
387 for (unsigned X = 0, XE = RetVals.size(); X != XE; ++X) {
388 auto MaybeInfo = Sets.find(RetVals[X]);
389 if (!MaybeInfo.hasValue())
392 auto &RetInfo = *MaybeInfo;
393 auto RetAttrs = Sets.getLink(RetInfo.Index).Attrs;
394 auto ParamAttrs = Sets.getLink(ParamInfo.Index).Attrs;
396 getIndexRelation(Sets, ParamInfo.Index, RetInfo.Index);
397 if (MaybeRelation.hasValue()) {
399 Externals |= RetAttrs | ParamAttrs;
403 Output.push_back({FuncValue, ArgVal, EdgeType::Assign,
404 StratifiedAttrs().flip()});
407 if (Parameters.size() != Arguments.size())
410 // Adding edges between arguments for arguments that may end up aliasing
411 // each other. This is necessary for functions such as
412 // void foo(int** a, int** b) { *a = *b; }
413 // (Technically, the proper sets for this would be those below
414 // Arguments[I] and Arguments[X], but our algorithm will produce
415 // extremely similar, and equally correct, results either way)
416 for (unsigned I = 0, E = Arguments.size(); I != E; ++I) {
417 auto &MainVal = Arguments[I];
418 auto &MainInfo = Parameters[I];
419 auto &MainAttrs = Sets.getLink(MainInfo.Index).Attrs;
420 for (unsigned X = I + 1; X != E; ++X) {
421 auto &SubInfo = Parameters[X];
422 auto &SubVal = Arguments[X];
423 auto &SubAttrs = Sets.getLink(SubInfo.Index).Attrs;
425 getIndexRelation(Sets, MainInfo.Index, SubInfo.Index);
427 if (!MaybeRelation.hasValue())
430 auto NewAttrs = SubAttrs | MainAttrs;
431 Output.push_back(Edge(MainVal, SubVal, EdgeType::Assign, NewAttrs));
438 template <typename InstT> void visitCallLikeInst(InstT &Inst) {
439 SmallVector<Function *, 4> Targets;
440 if (getPossibleTargets(&Inst, Targets)) {
441 if (tryInterproceduralAnalysis(Targets, &Inst, Inst.arg_operands()))
443 // Cleanup from interprocedural analysis
447 for (Value *V : Inst.arg_operands())
448 Output.push_back(Edge(&Inst, V, EdgeType::Assign, AttrAll));
451 void visitCallInst(CallInst &Inst) { visitCallLikeInst(Inst); }
453 void visitInvokeInst(InvokeInst &Inst) { visitCallLikeInst(Inst); }
455 // Because vectors/aggregates are immutable and unaddressable,
456 // there's nothing we can do to coax a value out of them, other
457 // than calling Extract{Element,Value}. We can effectively treat
458 // them as pointers to arbitrary memory locations we can store in
460 void visitExtractElementInst(ExtractElementInst &Inst) {
461 auto *Ptr = Inst.getVectorOperand();
463 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
466 void visitInsertElementInst(InsertElementInst &Inst) {
467 auto *Vec = Inst.getOperand(0);
468 auto *Val = Inst.getOperand(1);
469 Output.push_back(Edge(&Inst, Vec, EdgeType::Assign, AttrNone));
470 Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
473 void visitLandingPadInst(LandingPadInst &Inst) {
474 // Exceptions come from "nowhere", from our analysis' perspective.
475 // So we place the instruction its own group, noting that said group may
477 Output.push_back(Edge(&Inst, &Inst, EdgeType::Assign, AttrAll));
480 void visitInsertValueInst(InsertValueInst &Inst) {
481 auto *Agg = Inst.getOperand(0);
482 auto *Val = Inst.getOperand(1);
483 Output.push_back(Edge(&Inst, Agg, EdgeType::Assign, AttrNone));
484 Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
487 void visitExtractValueInst(ExtractValueInst &Inst) {
488 auto *Ptr = Inst.getAggregateOperand();
489 Output.push_back(Edge(&Inst, Ptr, EdgeType::Reference, AttrNone));
492 void visitShuffleVectorInst(ShuffleVectorInst &Inst) {
493 auto *From1 = Inst.getOperand(0);
494 auto *From2 = Inst.getOperand(1);
495 Output.push_back(Edge(&Inst, From1, EdgeType::Assign, AttrNone));
496 Output.push_back(Edge(&Inst, From2, EdgeType::Assign, AttrNone));
500 // For a given instruction, we need to know which Value* to get the
501 // users of in order to build our graph. In some cases (i.e. add),
502 // we simply need the Instruction*. In other cases (i.e. store),
503 // finding the users of the Instruction* is useless; we need to find
504 // the users of the first operand. This handles determining which
505 // value to follow for us.
507 // Note: we *need* to keep this in sync with GetEdgesVisitor. Add
508 // something to GetEdgesVisitor, add it here -- remove something from
509 // GetEdgesVisitor, remove it here.
510 class GetTargetValueVisitor
511 : public InstVisitor<GetTargetValueVisitor, Value *> {
513 Value *visitInstruction(Instruction &Inst) { return &Inst; }
515 Value *visitStoreInst(StoreInst &Inst) { return Inst.getPointerOperand(); }
517 Value *visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
518 return Inst.getPointerOperand();
521 Value *visitAtomicRMWInst(AtomicRMWInst &Inst) {
522 return Inst.getPointerOperand();
525 Value *visitInsertElementInst(InsertElementInst &Inst) {
526 return Inst.getOperand(0);
529 Value *visitInsertValueInst(InsertValueInst &Inst) {
530 return Inst.getAggregateOperand();
534 // Set building requires a weighted bidirectional graph.
535 template <typename EdgeTypeT> class WeightedBidirectionalGraph {
537 typedef std::size_t Node;
540 LLVM_CONSTEXPR static Node StartNode = Node(0);
546 bool operator==(const Edge &E) const {
547 return Weight == E.Weight && Other == E.Other;
550 bool operator!=(const Edge &E) const { return !operator==(E); }
554 std::vector<Edge> Edges;
557 std::vector<NodeImpl> NodeImpls;
559 bool inbounds(Node NodeIndex) const { return NodeIndex < NodeImpls.size(); }
561 const NodeImpl &getNode(Node N) const { return NodeImpls[N]; }
562 NodeImpl &getNode(Node N) { return NodeImpls[N]; }
565 // ----- Various Edge iterators for the graph ----- //
567 // \brief Iterator for edges. Because this graph is bidirected, we don't
568 // allow modificaiton of the edges using this iterator. Additionally, the
569 // iterator becomes invalid if you add edges to or from the node you're
570 // getting the edges of.
571 struct EdgeIterator : public std::iterator<std::forward_iterator_tag,
572 std::tuple<EdgeTypeT, Node *>> {
573 EdgeIterator(const typename std::vector<Edge>::const_iterator &Iter)
576 EdgeIterator(NodeImpl &Impl) : Current(Impl.begin()) {}
578 EdgeIterator &operator++() {
583 EdgeIterator operator++(int) {
584 EdgeIterator Copy(Current);
589 std::tuple<EdgeTypeT, Node> &operator*() {
590 Store = std::make_tuple(Current->Weight, Current->Other);
594 bool operator==(const EdgeIterator &Other) const {
595 return Current == Other.Current;
598 bool operator!=(const EdgeIterator &Other) const {
599 return !operator==(Other);
603 typename std::vector<Edge>::const_iterator Current;
604 std::tuple<EdgeTypeT, Node> Store;
607 // Wrapper for EdgeIterator with begin()/end() calls.
608 struct EdgeIterable {
609 EdgeIterable(const std::vector<Edge> &Edges)
610 : BeginIter(Edges.begin()), EndIter(Edges.end()) {}
612 EdgeIterator begin() { return EdgeIterator(BeginIter); }
614 EdgeIterator end() { return EdgeIterator(EndIter); }
617 typename std::vector<Edge>::const_iterator BeginIter;
618 typename std::vector<Edge>::const_iterator EndIter;
621 // ----- Actual graph-related things ----- //
623 WeightedBidirectionalGraph() = default;
625 WeightedBidirectionalGraph(WeightedBidirectionalGraph<EdgeTypeT> &&Other)
626 : NodeImpls(std::move(Other.NodeImpls)) {}
628 WeightedBidirectionalGraph<EdgeTypeT> &
629 operator=(WeightedBidirectionalGraph<EdgeTypeT> &&Other) {
630 NodeImpls = std::move(Other.NodeImpls);
635 auto Index = NodeImpls.size();
636 auto NewNode = Node(Index);
637 NodeImpls.push_back(NodeImpl());
641 void addEdge(Node From, Node To, const EdgeTypeT &Weight,
642 const EdgeTypeT &ReverseWeight) {
643 assert(inbounds(From));
644 assert(inbounds(To));
645 auto &FromNode = getNode(From);
646 auto &ToNode = getNode(To);
647 FromNode.Edges.push_back(Edge{Weight, To});
648 ToNode.Edges.push_back(Edge{ReverseWeight, From});
651 EdgeIterable edgesFor(const Node &N) const {
652 const auto &Node = getNode(N);
653 return EdgeIterable(Node.Edges);
656 bool empty() const { return NodeImpls.empty(); }
657 std::size_t size() const { return NodeImpls.size(); }
659 // \brief Gets an arbitrary node in the graph as a starting point for
661 Node getEntryNode() {
662 assert(inbounds(StartNode));
667 typedef WeightedBidirectionalGraph<std::pair<EdgeType, StratifiedAttrs>> GraphT;
668 typedef DenseMap<Value *, GraphT::Node> NodeMapT;
671 // -- Setting up/registering CFLAA pass -- //
672 char CFLAliasAnalysis::ID = 0;
674 INITIALIZE_AG_PASS(CFLAliasAnalysis, AliasAnalysis, "cfl-aa",
675 "CFL-Based AA implementation", false, true, false)
677 ImmutablePass *llvm::createCFLAliasAnalysisPass() {
678 return new CFLAliasAnalysis();
681 //===----------------------------------------------------------------------===//
682 // Function declarations that require types defined in the namespace above
683 //===----------------------------------------------------------------------===//
685 // Given an argument number, returns the appropriate Attr index to set.
686 static StratifiedAttr argNumberToAttrIndex(StratifiedAttr);
688 // Given a Value, potentially return which AttrIndex it maps to.
689 static Optional<StratifiedAttr> valueToAttrIndex(Value *Val);
691 // Gets the inverse of a given EdgeType.
692 static EdgeType flipWeight(EdgeType);
694 // Gets edges of the given Instruction*, writing them to the SmallVector*.
695 static void argsToEdges(CFLAliasAnalysis &, Instruction *,
696 SmallVectorImpl<Edge> &);
698 // Gets the "Level" that one should travel in StratifiedSets
699 // given an EdgeType.
700 static Level directionOfEdgeType(EdgeType);
702 // Builds the graph needed for constructing the StratifiedSets for the
704 static void buildGraphFrom(CFLAliasAnalysis &, Function *,
705 SmallVectorImpl<Value *> &, NodeMapT &, GraphT &);
707 // Builds the graph + StratifiedSets for a function.
708 static FunctionInfo buildSetsFrom(CFLAliasAnalysis &, Function *);
710 static Optional<Function *> parentFunctionOfValue(Value *Val) {
711 if (auto *Inst = dyn_cast<Instruction>(Val)) {
712 auto *Bb = Inst->getParent();
713 return Bb->getParent();
716 if (auto *Arg = dyn_cast<Argument>(Val))
717 return Arg->getParent();
721 template <typename Inst>
722 static bool getPossibleTargets(Inst *Call,
723 SmallVectorImpl<Function *> &Output) {
724 if (auto *Fn = Call->getCalledFunction()) {
725 Output.push_back(Fn);
729 // TODO: If the call is indirect, we might be able to enumerate all potential
730 // targets of the call and return them, rather than just failing.
734 static Optional<Value *> getTargetValue(Instruction *Inst) {
735 GetTargetValueVisitor V;
736 return V.visit(Inst);
739 static bool hasUsefulEdges(Instruction *Inst) {
740 bool IsNonInvokeTerminator =
741 isa<TerminatorInst>(Inst) && !isa<InvokeInst>(Inst);
742 return !isa<CmpInst>(Inst) && !isa<FenceInst>(Inst) && !IsNonInvokeTerminator;
745 static Optional<StratifiedAttr> valueToAttrIndex(Value *Val) {
746 if (isa<GlobalValue>(Val))
747 return AttrGlobalIndex;
749 if (auto *Arg = dyn_cast<Argument>(Val))
750 if (!Arg->hasNoAliasAttr())
751 return argNumberToAttrIndex(Arg->getArgNo());
755 static StratifiedAttr argNumberToAttrIndex(unsigned ArgNum) {
756 if (ArgNum > AttrMaxNumArgs)
758 return ArgNum + AttrFirstArgIndex;
761 static EdgeType flipWeight(EdgeType Initial) {
763 case EdgeType::Assign:
764 return EdgeType::Assign;
765 case EdgeType::Dereference:
766 return EdgeType::Reference;
767 case EdgeType::Reference:
768 return EdgeType::Dereference;
770 llvm_unreachable("Incomplete coverage of EdgeType enum");
773 static void argsToEdges(CFLAliasAnalysis &Analysis, Instruction *Inst,
774 SmallVectorImpl<Edge> &Output) {
775 GetEdgesVisitor v(Analysis, Output);
779 static Level directionOfEdgeType(EdgeType Weight) {
781 case EdgeType::Reference:
783 case EdgeType::Dereference:
785 case EdgeType::Assign:
788 llvm_unreachable("Incomplete switch coverage");
791 // Aside: We may remove graph construction entirely, because it doesn't really
792 // buy us much that we don't already have. I'd like to add interprocedural
793 // analysis prior to this however, in case that somehow requires the graph
794 // produced by this for efficient execution
795 static void buildGraphFrom(CFLAliasAnalysis &Analysis, Function *Fn,
796 SmallVectorImpl<Value *> &ReturnedValues,
797 NodeMapT &Map, GraphT &Graph) {
798 const auto findOrInsertNode = [&Map, &Graph](Value *Val) {
799 auto Pair = Map.insert(std::make_pair(Val, GraphT::Node()));
800 auto &Iter = Pair.first;
802 auto NewNode = Graph.addNode();
803 Iter->second = NewNode;
808 SmallVector<Edge, 8> Edges;
809 for (auto &Bb : Fn->getBasicBlockList()) {
810 for (auto &Inst : Bb.getInstList()) {
811 // We don't want the edges of most "return" instructions, but we *do* want
812 // to know what can be returned.
813 if (auto *Ret = dyn_cast<ReturnInst>(&Inst))
814 ReturnedValues.push_back(Ret);
816 if (!hasUsefulEdges(&Inst))
820 argsToEdges(Analysis, &Inst, Edges);
822 // In the case of an unused alloca (or similar), edges may be empty. Note
823 // that it exists so we can potentially answer NoAlias.
825 auto MaybeVal = getTargetValue(&Inst);
826 assert(MaybeVal.hasValue());
827 auto *Target = *MaybeVal;
828 findOrInsertNode(Target);
832 for (const Edge &E : Edges) {
833 auto To = findOrInsertNode(E.To);
834 auto From = findOrInsertNode(E.From);
835 auto FlippedWeight = flipWeight(E.Weight);
836 auto Attrs = E.AdditionalAttrs;
837 Graph.addEdge(From, To, {E.Weight, Attrs}, {FlippedWeight, Attrs});
843 static FunctionInfo buildSetsFrom(CFLAliasAnalysis &Analysis, Function *Fn) {
846 SmallVector<Value *, 4> ReturnedValues;
848 buildGraphFrom(Analysis, Fn, ReturnedValues, Map, Graph);
850 DenseMap<GraphT::Node, Value *> NodeValueMap;
851 NodeValueMap.resize(Map.size());
852 for (const auto &Pair : Map)
853 NodeValueMap.insert(std::make_pair(Pair.second, Pair.first));
855 const auto findValueOrDie = [&NodeValueMap](GraphT::Node Node) {
856 auto ValIter = NodeValueMap.find(Node);
857 assert(ValIter != NodeValueMap.end());
858 return ValIter->second;
861 StratifiedSetsBuilder<Value *> Builder;
863 SmallVector<GraphT::Node, 16> Worklist;
864 for (auto &Pair : Map) {
867 auto *Value = Pair.first;
869 auto InitialNode = Pair.second;
870 Worklist.push_back(InitialNode);
871 while (!Worklist.empty()) {
872 auto Node = Worklist.pop_back_val();
873 auto *CurValue = findValueOrDie(Node);
874 if (isa<Constant>(CurValue) && !isa<GlobalValue>(CurValue))
877 for (const auto &EdgeTuple : Graph.edgesFor(Node)) {
878 auto Weight = std::get<0>(EdgeTuple);
879 auto Label = Weight.first;
880 auto &OtherNode = std::get<1>(EdgeTuple);
881 auto *OtherValue = findValueOrDie(OtherNode);
883 if (isa<Constant>(OtherValue) && !isa<GlobalValue>(OtherValue))
887 switch (directionOfEdgeType(Label)) {
889 Added = Builder.addAbove(CurValue, OtherValue);
892 Added = Builder.addBelow(CurValue, OtherValue);
895 Added = Builder.addWith(CurValue, OtherValue);
900 auto Aliasing = Weight.second;
901 if (auto MaybeCurIndex = valueToAttrIndex(CurValue))
902 Aliasing.set(*MaybeCurIndex);
903 if (auto MaybeOtherIndex = valueToAttrIndex(OtherValue))
904 Aliasing.set(*MaybeOtherIndex);
905 Builder.noteAttributes(CurValue, Aliasing);
906 Builder.noteAttributes(OtherValue, Aliasing);
907 Worklist.push_back(OtherNode);
913 // There are times when we end up with parameters not in our graph (i.e. if
914 // it's only used as the condition of a branch). Other bits of code depend on
915 // things that were present during construction being present in the graph.
916 // So, we add all present arguments here.
917 for (auto &Arg : Fn->args()) {
921 return {Builder.build(), std::move(ReturnedValues)};
924 void CFLAliasAnalysis::scan(Function *Fn) {
925 auto InsertPair = Cache.insert(std::make_pair(Fn, Optional<FunctionInfo>()));
927 assert(InsertPair.second &&
928 "Trying to scan a function that has already been cached");
930 FunctionInfo Info(buildSetsFrom(*this, Fn));
931 Cache[Fn] = std::move(Info);
932 Handles.push_front(FunctionHandle(Fn, this));
935 AliasAnalysis::AliasResult
936 CFLAliasAnalysis::query(const AliasAnalysis::Location &LocA,
937 const AliasAnalysis::Location &LocB) {
938 auto *ValA = const_cast<Value *>(LocA.Ptr);
939 auto *ValB = const_cast<Value *>(LocB.Ptr);
941 Function *Fn = nullptr;
942 auto MaybeFnA = parentFunctionOfValue(ValA);
943 auto MaybeFnB = parentFunctionOfValue(ValB);
944 if (!MaybeFnA.hasValue() && !MaybeFnB.hasValue()) {
945 llvm_unreachable("Don't know how to extract the parent function "
946 "from values A or B");
949 if (MaybeFnA.hasValue()) {
951 assert((!MaybeFnB.hasValue() || *MaybeFnB == *MaybeFnA) &&
952 "Interprocedural queries not supported");
957 assert(Fn != nullptr);
958 auto &MaybeInfo = ensureCached(Fn);
959 assert(MaybeInfo.hasValue());
961 auto &Sets = MaybeInfo->Sets;
962 auto MaybeA = Sets.find(ValA);
963 if (!MaybeA.hasValue())
964 return AliasAnalysis::MayAlias;
966 auto MaybeB = Sets.find(ValB);
967 if (!MaybeB.hasValue())
968 return AliasAnalysis::MayAlias;
973 if (SetA.Index == SetB.Index)
974 return AliasAnalysis::PartialAlias;
976 auto AttrsA = Sets.getLink(SetA.Index).Attrs;
977 auto AttrsB = Sets.getLink(SetB.Index).Attrs;
978 auto CombinedAttrs = AttrsA | AttrsB;
979 if (CombinedAttrs.any())
980 return AliasAnalysis::PartialAlias;
982 return AliasAnalysis::NoAlias;