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 AttrUnknownIndex = 2;
89 LLVM_CONSTEXPR unsigned AttrFirstArgIndex = 3;
90 LLVM_CONSTEXPR unsigned AttrLastArgIndex = MaxStratifiedAttrIndex;
91 LLVM_CONSTEXPR unsigned AttrMaxNumArgs = AttrLastArgIndex - AttrFirstArgIndex;
93 LLVM_CONSTEXPR StratifiedAttr AttrNone = 0;
94 LLVM_CONSTEXPR StratifiedAttr AttrUnknown = 1 << AttrUnknownIndex;
95 LLVM_CONSTEXPR StratifiedAttr AttrAll = ~AttrNone;
97 // \brief StratifiedSets call for knowledge of "direction", so this is how we
98 // represent that locally.
99 enum class Level { Same, Above, Below };
101 // \brief Edges can be one of four "weights" -- each weight must have an inverse
102 // weight (Assign has Assign; Reference has Dereference).
103 enum class EdgeType {
104 // The weight assigned when assigning from or to a value. For example, in:
105 // %b = getelementptr %a, 0
106 // ...The relationships are %b assign %a, and %a assign %b. This used to be
107 // two edges, but having a distinction bought us nothing.
110 // The edge used when we have an edge going from some handle to a Value.
111 // Examples of this include:
112 // %b = load %a (%b Dereference %a)
113 // %b = extractelement %a, 0 (%a Dereference %b)
116 // The edge used when our edge goes from a value to a handle that may have
117 // contained it at some point. Examples:
118 // %b = load %a (%a Reference %b)
119 // %b = extractelement %a, 0 (%b Reference %a)
123 // \brief Encodes the notion of a "use"
125 // \brief Which value the edge is coming from
128 // \brief Which value the edge is pointing to
131 // \brief Edge weight
134 // \brief Whether we aliased any external values along the way that may be
135 // invisible to the analysis (i.e. landingpad for exceptions, calls for
136 // interprocedural analysis, etc.)
137 StratifiedAttrs AdditionalAttrs;
139 Edge(Value *From, Value *To, EdgeType W, StratifiedAttrs A)
140 : From(From), To(To), Weight(W), AdditionalAttrs(A) {}
143 // \brief Information we have about a function and would like to keep around
144 struct FunctionInfo {
145 StratifiedSets<Value *> Sets;
146 // Lots of functions have < 4 returns. Adjust as necessary.
147 SmallVector<Value *, 4> ReturnedValues;
149 FunctionInfo(StratifiedSets<Value *> &&S,
150 SmallVector<Value *, 4> &&RV)
151 : Sets(std::move(S)), ReturnedValues(std::move(RV)) {}
154 struct CFLAliasAnalysis;
156 struct FunctionHandle : public CallbackVH {
157 FunctionHandle(Function *Fn, CFLAliasAnalysis *CFLAA)
158 : CallbackVH(Fn), CFLAA(CFLAA) {
159 assert(Fn != nullptr);
160 assert(CFLAA != nullptr);
163 virtual ~FunctionHandle() {}
165 void deleted() override { removeSelfFromCache(); }
166 void allUsesReplacedWith(Value *) override { removeSelfFromCache(); }
169 CFLAliasAnalysis *CFLAA;
171 void removeSelfFromCache();
174 struct CFLAliasAnalysis : public ImmutablePass, public AliasAnalysis {
176 /// \brief Cached mapping of Functions to their StratifiedSets.
177 /// If a function's sets are currently being built, it is marked
178 /// in the cache as an Optional without a value. This way, if we
179 /// have any kind of recursion, it is discernable from a function
180 /// that simply has empty sets.
181 DenseMap<Function *, Optional<FunctionInfo>> Cache;
182 std::forward_list<FunctionHandle> Handles;
187 CFLAliasAnalysis() : ImmutablePass(ID) {
188 initializeCFLAliasAnalysisPass(*PassRegistry::getPassRegistry());
191 virtual ~CFLAliasAnalysis() {}
193 void getAnalysisUsage(AnalysisUsage &AU) const override {
194 AliasAnalysis::getAnalysisUsage(AU);
197 void *getAdjustedAnalysisPointer(const void *ID) override {
198 if (ID == &AliasAnalysis::ID)
199 return (AliasAnalysis *)this;
203 /// \brief Inserts the given Function into the cache.
204 void scan(Function *Fn);
206 void evict(Function *Fn) { Cache.erase(Fn); }
208 /// \brief Ensures that the given function is available in the cache.
209 /// Returns the appropriate entry from the cache.
210 const Optional<FunctionInfo> &ensureCached(Function *Fn) {
211 auto Iter = Cache.find(Fn);
212 if (Iter == Cache.end()) {
214 Iter = Cache.find(Fn);
215 assert(Iter != Cache.end());
216 assert(Iter->second.hasValue());
221 AliasResult query(const Location &LocA, const Location &LocB);
223 AliasResult alias(const Location &LocA, const Location &LocB) override {
224 if (LocA.Ptr == LocB.Ptr) {
225 if (LocA.Size == LocB.Size) {
232 // Comparisons between global variables and other constants should be
233 // handled by BasicAA.
234 if (isa<Constant>(LocA.Ptr) && isa<Constant>(LocB.Ptr)) {
235 return AliasAnalysis::alias(LocA, LocB);
238 AliasResult QueryResult = query(LocA, LocB);
239 if (QueryResult == MayAlias)
240 return AliasAnalysis::alias(LocA, LocB);
245 bool doInitialization(Module &M) override;
248 void FunctionHandle::removeSelfFromCache() {
249 assert(CFLAA != nullptr);
250 auto *Val = getValPtr();
251 CFLAA->evict(cast<Function>(Val));
255 // \brief Gets the edges our graph should have, based on an Instruction*
256 class GetEdgesVisitor : public InstVisitor<GetEdgesVisitor, void> {
257 CFLAliasAnalysis &AA;
258 SmallVectorImpl<Edge> &Output;
261 GetEdgesVisitor(CFLAliasAnalysis &AA, SmallVectorImpl<Edge> &Output)
262 : AA(AA), Output(Output) {}
264 void visitInstruction(Instruction &) {
265 llvm_unreachable("Unsupported instruction encountered");
268 void visitPtrToIntInst(PtrToIntInst &Inst) {
269 auto *Ptr = Inst.getOperand(0);
270 Output.push_back(Edge(Ptr, Ptr, EdgeType::Assign, AttrUnknown));
273 void visitIntToPtrInst(IntToPtrInst &Inst) {
275 Output.push_back(Edge(Ptr, Ptr, EdgeType::Assign, AttrUnknown));
278 void visitCastInst(CastInst &Inst) {
279 Output.push_back(Edge(&Inst, Inst.getOperand(0), EdgeType::Assign,
283 void visitBinaryOperator(BinaryOperator &Inst) {
284 auto *Op1 = Inst.getOperand(0);
285 auto *Op2 = Inst.getOperand(1);
286 Output.push_back(Edge(&Inst, Op1, EdgeType::Assign, AttrNone));
287 Output.push_back(Edge(&Inst, Op2, EdgeType::Assign, AttrNone));
290 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
291 auto *Ptr = Inst.getPointerOperand();
292 auto *Val = Inst.getNewValOperand();
293 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
296 void visitAtomicRMWInst(AtomicRMWInst &Inst) {
297 auto *Ptr = Inst.getPointerOperand();
298 auto *Val = Inst.getValOperand();
299 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
302 void visitPHINode(PHINode &Inst) {
303 for (unsigned I = 0, E = Inst.getNumIncomingValues(); I != E; ++I) {
304 Value *Val = Inst.getIncomingValue(I);
305 Output.push_back(Edge(&Inst, Val, EdgeType::Assign, AttrNone));
309 void visitGetElementPtrInst(GetElementPtrInst &Inst) {
310 auto *Op = Inst.getPointerOperand();
311 Output.push_back(Edge(&Inst, Op, EdgeType::Assign, AttrNone));
312 for (auto I = Inst.idx_begin(), E = Inst.idx_end(); I != E; ++I)
313 Output.push_back(Edge(&Inst, *I, EdgeType::Assign, AttrNone));
316 void visitSelectInst(SelectInst &Inst) {
317 // Condition is not processed here (The actual statement producing
318 // the condition result is processed elsewhere). For select, the
319 // condition is evaluated, but not loaded, stored, or assigned
320 // simply as a result of being the condition of a select.
322 auto *TrueVal = Inst.getTrueValue();
323 Output.push_back(Edge(&Inst, TrueVal, EdgeType::Assign, AttrNone));
324 auto *FalseVal = Inst.getFalseValue();
325 Output.push_back(Edge(&Inst, FalseVal, EdgeType::Assign, AttrNone));
328 void visitAllocaInst(AllocaInst &) {}
330 void visitLoadInst(LoadInst &Inst) {
331 auto *Ptr = Inst.getPointerOperand();
333 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
336 void visitStoreInst(StoreInst &Inst) {
337 auto *Ptr = Inst.getPointerOperand();
338 auto *Val = Inst.getValueOperand();
339 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
342 void visitVAArgInst(VAArgInst &Inst) {
343 // We can't fully model va_arg here. For *Ptr = Inst.getOperand(0), it does
345 // 1. Loads a value from *((T*)*Ptr).
346 // 2. Increments (stores to) *Ptr by some target-specific amount.
347 // For now, we'll handle this like a landingpad instruction (by placing the
348 // result in its own group, and having that group alias externals).
350 Output.push_back(Edge(Val, Val, EdgeType::Assign, AttrAll));
353 static bool isFunctionExternal(Function *Fn) {
354 return Fn->isDeclaration() || !Fn->hasLocalLinkage();
357 // Gets whether the sets at Index1 above, below, or equal to the sets at
358 // Index2. Returns None if they are not in the same set chain.
359 static Optional<Level> getIndexRelation(const StratifiedSets<Value *> &Sets,
360 StratifiedIndex Index1,
361 StratifiedIndex Index2) {
362 if (Index1 == Index2)
365 const auto *Current = &Sets.getLink(Index1);
366 while (Current->hasBelow()) {
367 if (Current->Below == Index2)
369 Current = &Sets.getLink(Current->Below);
372 Current = &Sets.getLink(Index1);
373 while (Current->hasAbove()) {
374 if (Current->Above == Index2)
376 Current = &Sets.getLink(Current->Above);
383 tryInterproceduralAnalysis(const SmallVectorImpl<Function *> &Fns,
385 const iterator_range<User::op_iterator> &Args) {
386 const unsigned ExpectedMaxArgs = 8;
387 const unsigned MaxSupportedArgs = 50;
388 assert(Fns.size() > 0);
390 // I put this here to give us an upper bound on time taken by IPA. Is it
391 // really (realistically) needed? Keep in mind that we do have an n^2 algo.
392 if (std::distance(Args.begin(), Args.end()) > (int) MaxSupportedArgs)
395 // Exit early if we'll fail anyway
396 for (auto *Fn : Fns) {
397 if (isFunctionExternal(Fn) || Fn->isVarArg())
399 auto &MaybeInfo = AA.ensureCached(Fn);
400 if (!MaybeInfo.hasValue())
404 SmallVector<Value *, ExpectedMaxArgs> Arguments(Args.begin(), Args.end());
405 SmallVector<StratifiedInfo, ExpectedMaxArgs> Parameters;
406 for (auto *Fn : Fns) {
407 auto &Info = *AA.ensureCached(Fn);
408 auto &Sets = Info.Sets;
409 auto &RetVals = Info.ReturnedValues;
412 for (auto &Param : Fn->args()) {
413 auto MaybeInfo = Sets.find(&Param);
414 // Did a new parameter somehow get added to the function/slip by?
415 if (!MaybeInfo.hasValue())
417 Parameters.push_back(*MaybeInfo);
420 // Adding an edge from argument -> return value for each parameter that
421 // may alias the return value
422 for (unsigned I = 0, E = Parameters.size(); I != E; ++I) {
423 auto &ParamInfo = Parameters[I];
424 auto &ArgVal = Arguments[I];
425 bool AddEdge = false;
426 StratifiedAttrs Externals;
427 for (unsigned X = 0, XE = RetVals.size(); X != XE; ++X) {
428 auto MaybeInfo = Sets.find(RetVals[X]);
429 if (!MaybeInfo.hasValue())
432 auto &RetInfo = *MaybeInfo;
433 auto RetAttrs = Sets.getLink(RetInfo.Index).Attrs;
434 auto ParamAttrs = Sets.getLink(ParamInfo.Index).Attrs;
436 getIndexRelation(Sets, ParamInfo.Index, RetInfo.Index);
437 if (MaybeRelation.hasValue()) {
439 Externals |= RetAttrs | ParamAttrs;
443 Output.push_back(Edge(FuncValue, ArgVal, EdgeType::Assign,
444 StratifiedAttrs().flip()));
447 if (Parameters.size() != Arguments.size())
450 // Adding edges between arguments for arguments that may end up aliasing
451 // each other. This is necessary for functions such as
452 // void foo(int** a, int** b) { *a = *b; }
453 // (Technically, the proper sets for this would be those below
454 // Arguments[I] and Arguments[X], but our algorithm will produce
455 // extremely similar, and equally correct, results either way)
456 for (unsigned I = 0, E = Arguments.size(); I != E; ++I) {
457 auto &MainVal = Arguments[I];
458 auto &MainInfo = Parameters[I];
459 auto &MainAttrs = Sets.getLink(MainInfo.Index).Attrs;
460 for (unsigned X = I + 1; X != E; ++X) {
461 auto &SubInfo = Parameters[X];
462 auto &SubVal = Arguments[X];
463 auto &SubAttrs = Sets.getLink(SubInfo.Index).Attrs;
465 getIndexRelation(Sets, MainInfo.Index, SubInfo.Index);
467 if (!MaybeRelation.hasValue())
470 auto NewAttrs = SubAttrs | MainAttrs;
471 Output.push_back(Edge(MainVal, SubVal, EdgeType::Assign, NewAttrs));
478 template <typename InstT> void visitCallLikeInst(InstT &Inst) {
479 SmallVector<Function *, 4> Targets;
480 if (getPossibleTargets(&Inst, Targets)) {
481 if (tryInterproceduralAnalysis(Targets, &Inst, Inst.arg_operands()))
483 // Cleanup from interprocedural analysis
487 for (Value *V : Inst.arg_operands())
488 Output.push_back(Edge(&Inst, V, EdgeType::Assign, AttrAll));
491 void visitCallInst(CallInst &Inst) { visitCallLikeInst(Inst); }
493 void visitInvokeInst(InvokeInst &Inst) { visitCallLikeInst(Inst); }
495 // Because vectors/aggregates are immutable and unaddressable,
496 // there's nothing we can do to coax a value out of them, other
497 // than calling Extract{Element,Value}. We can effectively treat
498 // them as pointers to arbitrary memory locations we can store in
500 void visitExtractElementInst(ExtractElementInst &Inst) {
501 auto *Ptr = Inst.getVectorOperand();
503 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
506 void visitInsertElementInst(InsertElementInst &Inst) {
507 auto *Vec = Inst.getOperand(0);
508 auto *Val = Inst.getOperand(1);
509 Output.push_back(Edge(&Inst, Vec, EdgeType::Assign, AttrNone));
510 Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
513 void visitLandingPadInst(LandingPadInst &Inst) {
514 // Exceptions come from "nowhere", from our analysis' perspective.
515 // So we place the instruction its own group, noting that said group may
517 Output.push_back(Edge(&Inst, &Inst, EdgeType::Assign, AttrAll));
520 void visitInsertValueInst(InsertValueInst &Inst) {
521 auto *Agg = Inst.getOperand(0);
522 auto *Val = Inst.getOperand(1);
523 Output.push_back(Edge(&Inst, Agg, EdgeType::Assign, AttrNone));
524 Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
527 void visitExtractValueInst(ExtractValueInst &Inst) {
528 auto *Ptr = Inst.getAggregateOperand();
529 Output.push_back(Edge(&Inst, Ptr, EdgeType::Reference, AttrNone));
532 void visitShuffleVectorInst(ShuffleVectorInst &Inst) {
533 auto *From1 = Inst.getOperand(0);
534 auto *From2 = Inst.getOperand(1);
535 Output.push_back(Edge(&Inst, From1, EdgeType::Assign, AttrNone));
536 Output.push_back(Edge(&Inst, From2, EdgeType::Assign, AttrNone));
540 // For a given instruction, we need to know which Value* to get the
541 // users of in order to build our graph. In some cases (i.e. add),
542 // we simply need the Instruction*. In other cases (i.e. store),
543 // finding the users of the Instruction* is useless; we need to find
544 // the users of the first operand. This handles determining which
545 // value to follow for us.
547 // Note: we *need* to keep this in sync with GetEdgesVisitor. Add
548 // something to GetEdgesVisitor, add it here -- remove something from
549 // GetEdgesVisitor, remove it here.
550 class GetTargetValueVisitor
551 : public InstVisitor<GetTargetValueVisitor, Value *> {
553 Value *visitInstruction(Instruction &Inst) { return &Inst; }
555 Value *visitStoreInst(StoreInst &Inst) { return Inst.getPointerOperand(); }
557 Value *visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
558 return Inst.getPointerOperand();
561 Value *visitAtomicRMWInst(AtomicRMWInst &Inst) {
562 return Inst.getPointerOperand();
565 Value *visitInsertElementInst(InsertElementInst &Inst) {
566 return Inst.getOperand(0);
569 Value *visitInsertValueInst(InsertValueInst &Inst) {
570 return Inst.getAggregateOperand();
574 // Set building requires a weighted bidirectional graph.
575 template <typename EdgeTypeT> class WeightedBidirectionalGraph {
577 typedef std::size_t Node;
580 const static Node StartNode = Node(0);
586 Edge(const EdgeTypeT &W, const Node &N)
587 : Weight(W), Other(N) {}
589 bool operator==(const Edge &E) const {
590 return Weight == E.Weight && Other == E.Other;
593 bool operator!=(const Edge &E) const { return !operator==(E); }
597 std::vector<Edge> Edges;
600 std::vector<NodeImpl> NodeImpls;
602 bool inbounds(Node NodeIndex) const { return NodeIndex < NodeImpls.size(); }
604 const NodeImpl &getNode(Node N) const { return NodeImpls[N]; }
605 NodeImpl &getNode(Node N) { return NodeImpls[N]; }
608 // ----- Various Edge iterators for the graph ----- //
610 // \brief Iterator for edges. Because this graph is bidirected, we don't
611 // allow modificaiton of the edges using this iterator. Additionally, the
612 // iterator becomes invalid if you add edges to or from the node you're
613 // getting the edges of.
614 struct EdgeIterator : public std::iterator<std::forward_iterator_tag,
615 std::tuple<EdgeTypeT, Node *>> {
616 EdgeIterator(const typename std::vector<Edge>::const_iterator &Iter)
619 EdgeIterator(NodeImpl &Impl) : Current(Impl.begin()) {}
621 EdgeIterator &operator++() {
626 EdgeIterator operator++(int) {
627 EdgeIterator Copy(Current);
632 std::tuple<EdgeTypeT, Node> &operator*() {
633 Store = std::make_tuple(Current->Weight, Current->Other);
637 bool operator==(const EdgeIterator &Other) const {
638 return Current == Other.Current;
641 bool operator!=(const EdgeIterator &Other) const {
642 return !operator==(Other);
646 typename std::vector<Edge>::const_iterator Current;
647 std::tuple<EdgeTypeT, Node> Store;
650 // Wrapper for EdgeIterator with begin()/end() calls.
651 struct EdgeIterable {
652 EdgeIterable(const std::vector<Edge> &Edges)
653 : BeginIter(Edges.begin()), EndIter(Edges.end()) {}
655 EdgeIterator begin() { return EdgeIterator(BeginIter); }
657 EdgeIterator end() { return EdgeIterator(EndIter); }
660 typename std::vector<Edge>::const_iterator BeginIter;
661 typename std::vector<Edge>::const_iterator EndIter;
664 // ----- Actual graph-related things ----- //
666 WeightedBidirectionalGraph() {}
668 WeightedBidirectionalGraph(WeightedBidirectionalGraph<EdgeTypeT> &&Other)
669 : NodeImpls(std::move(Other.NodeImpls)) {}
671 WeightedBidirectionalGraph<EdgeTypeT> &
672 operator=(WeightedBidirectionalGraph<EdgeTypeT> &&Other) {
673 NodeImpls = std::move(Other.NodeImpls);
678 auto Index = NodeImpls.size();
679 auto NewNode = Node(Index);
680 NodeImpls.push_back(NodeImpl());
684 void addEdge(Node From, Node To, const EdgeTypeT &Weight,
685 const EdgeTypeT &ReverseWeight) {
686 assert(inbounds(From));
687 assert(inbounds(To));
688 auto &FromNode = getNode(From);
689 auto &ToNode = getNode(To);
690 FromNode.Edges.push_back(Edge(Weight, To));
691 ToNode.Edges.push_back(Edge(ReverseWeight, From));
694 EdgeIterable edgesFor(const Node &N) const {
695 const auto &Node = getNode(N);
696 return EdgeIterable(Node.Edges);
699 bool empty() const { return NodeImpls.empty(); }
700 std::size_t size() const { return NodeImpls.size(); }
702 // \brief Gets an arbitrary node in the graph as a starting point for
704 Node getEntryNode() {
705 assert(inbounds(StartNode));
710 typedef WeightedBidirectionalGraph<std::pair<EdgeType, StratifiedAttrs>> GraphT;
711 typedef DenseMap<Value *, GraphT::Node> NodeMapT;
714 // -- Setting up/registering CFLAA pass -- //
715 char CFLAliasAnalysis::ID = 0;
717 INITIALIZE_AG_PASS(CFLAliasAnalysis, AliasAnalysis, "cfl-aa",
718 "CFL-Based AA implementation", false, true, false)
720 ImmutablePass *llvm::createCFLAliasAnalysisPass() {
721 return new CFLAliasAnalysis();
724 //===----------------------------------------------------------------------===//
725 // Function declarations that require types defined in the namespace above
726 //===----------------------------------------------------------------------===//
728 // Given an argument number, returns the appropriate Attr index to set.
729 static StratifiedAttr argNumberToAttrIndex(StratifiedAttr);
731 // Given a Value, potentially return which AttrIndex it maps to.
732 static Optional<StratifiedAttr> valueToAttrIndex(Value *Val);
734 // Gets the inverse of a given EdgeType.
735 static EdgeType flipWeight(EdgeType);
737 // Gets edges of the given Instruction*, writing them to the SmallVector*.
738 static void argsToEdges(CFLAliasAnalysis &, Instruction *,
739 SmallVectorImpl<Edge> &);
741 // Gets the "Level" that one should travel in StratifiedSets
742 // given an EdgeType.
743 static Level directionOfEdgeType(EdgeType);
745 // Builds the graph needed for constructing the StratifiedSets for the
747 static void buildGraphFrom(CFLAliasAnalysis &, Function *,
748 SmallVectorImpl<Value *> &, NodeMapT &, GraphT &);
750 // Builds the graph + StratifiedSets for a function.
751 static FunctionInfo buildSetsFrom(CFLAliasAnalysis &, Function *);
753 static Optional<Function *> parentFunctionOfValue(Value *Val) {
754 if (auto *Inst = dyn_cast<Instruction>(Val)) {
755 auto *Bb = Inst->getParent();
756 return Bb->getParent();
759 if (auto *Arg = dyn_cast<Argument>(Val))
760 return Arg->getParent();
764 template <typename Inst>
765 static bool getPossibleTargets(Inst *Call,
766 SmallVectorImpl<Function *> &Output) {
767 if (auto *Fn = Call->getCalledFunction()) {
768 Output.push_back(Fn);
772 // TODO: If the call is indirect, we might be able to enumerate all potential
773 // targets of the call and return them, rather than just failing.
777 static Optional<Value *> getTargetValue(Instruction *Inst) {
778 GetTargetValueVisitor V;
779 return V.visit(Inst);
782 static bool hasUsefulEdges(Instruction *Inst) {
783 bool IsNonInvokeTerminator =
784 isa<TerminatorInst>(Inst) && !isa<InvokeInst>(Inst);
785 return !isa<CmpInst>(Inst) && !isa<FenceInst>(Inst) && !IsNonInvokeTerminator;
788 static Optional<StratifiedAttr> valueToAttrIndex(Value *Val) {
789 if (isa<GlobalValue>(Val))
790 return AttrGlobalIndex;
792 if (auto *Arg = dyn_cast<Argument>(Val))
793 // Only pointer arguments should have the argument attribute,
794 // because things can't escape through scalars without us seeing a
795 // cast, and thus, interaction with them doesn't matter.
796 if (!Arg->hasNoAliasAttr() && Arg->getType()->isPointerTy())
797 return argNumberToAttrIndex(Arg->getArgNo());
801 static StratifiedAttr argNumberToAttrIndex(unsigned ArgNum) {
802 if (ArgNum >= AttrMaxNumArgs)
804 return ArgNum + AttrFirstArgIndex;
807 static EdgeType flipWeight(EdgeType Initial) {
809 case EdgeType::Assign:
810 return EdgeType::Assign;
811 case EdgeType::Dereference:
812 return EdgeType::Reference;
813 case EdgeType::Reference:
814 return EdgeType::Dereference;
816 llvm_unreachable("Incomplete coverage of EdgeType enum");
819 static void argsToEdges(CFLAliasAnalysis &Analysis, Instruction *Inst,
820 SmallVectorImpl<Edge> &Output) {
821 GetEdgesVisitor v(Analysis, Output);
825 static Level directionOfEdgeType(EdgeType Weight) {
827 case EdgeType::Reference:
829 case EdgeType::Dereference:
831 case EdgeType::Assign:
834 llvm_unreachable("Incomplete switch coverage");
837 // Aside: We may remove graph construction entirely, because it doesn't really
838 // buy us much that we don't already have. I'd like to add interprocedural
839 // analysis prior to this however, in case that somehow requires the graph
840 // produced by this for efficient execution
841 static void buildGraphFrom(CFLAliasAnalysis &Analysis, Function *Fn,
842 SmallVectorImpl<Value *> &ReturnedValues,
843 NodeMapT &Map, GraphT &Graph) {
844 const auto findOrInsertNode = [&Map, &Graph](Value *Val) {
845 auto Pair = Map.insert(std::make_pair(Val, GraphT::Node()));
846 auto &Iter = Pair.first;
848 auto NewNode = Graph.addNode();
849 Iter->second = NewNode;
854 SmallVector<Edge, 8> Edges;
855 for (auto &Bb : Fn->getBasicBlockList()) {
856 for (auto &Inst : Bb.getInstList()) {
857 // We don't want the edges of most "return" instructions, but we *do* want
858 // to know what can be returned.
859 if (auto *Ret = dyn_cast<ReturnInst>(&Inst))
860 ReturnedValues.push_back(Ret);
862 if (!hasUsefulEdges(&Inst))
866 argsToEdges(Analysis, &Inst, Edges);
868 // In the case of an unused alloca (or similar), edges may be empty. Note
869 // that it exists so we can potentially answer NoAlias.
871 auto MaybeVal = getTargetValue(&Inst);
872 assert(MaybeVal.hasValue());
873 auto *Target = *MaybeVal;
874 findOrInsertNode(Target);
878 for (const Edge &E : Edges) {
879 auto To = findOrInsertNode(E.To);
880 auto From = findOrInsertNode(E.From);
881 auto FlippedWeight = flipWeight(E.Weight);
882 auto Attrs = E.AdditionalAttrs;
883 Graph.addEdge(From, To, std::make_pair(E.Weight, Attrs),
884 std::make_pair(FlippedWeight, Attrs));
890 static FunctionInfo buildSetsFrom(CFLAliasAnalysis &Analysis, Function *Fn) {
893 SmallVector<Value *, 4> ReturnedValues;
895 buildGraphFrom(Analysis, Fn, ReturnedValues, Map, Graph);
897 DenseMap<GraphT::Node, Value *> NodeValueMap;
898 NodeValueMap.resize(Map.size());
899 for (const auto &Pair : Map)
900 NodeValueMap.insert(std::make_pair(Pair.second, Pair.first));
902 const auto findValueOrDie = [&NodeValueMap](GraphT::Node Node) {
903 auto ValIter = NodeValueMap.find(Node);
904 assert(ValIter != NodeValueMap.end());
905 return ValIter->second;
908 StratifiedSetsBuilder<Value *> Builder;
910 SmallVector<GraphT::Node, 16> Worklist;
911 for (auto &Pair : Map) {
914 auto *Value = Pair.first;
916 auto InitialNode = Pair.second;
917 Worklist.push_back(InitialNode);
918 while (!Worklist.empty()) {
919 auto Node = Worklist.pop_back_val();
920 auto *CurValue = findValueOrDie(Node);
921 if (isa<Constant>(CurValue) && !isa<GlobalValue>(CurValue))
924 for (const auto &EdgeTuple : Graph.edgesFor(Node)) {
925 auto Weight = std::get<0>(EdgeTuple);
926 auto Label = Weight.first;
927 auto &OtherNode = std::get<1>(EdgeTuple);
928 auto *OtherValue = findValueOrDie(OtherNode);
930 if (isa<Constant>(OtherValue) && !isa<GlobalValue>(OtherValue))
934 switch (directionOfEdgeType(Label)) {
936 Added = Builder.addAbove(CurValue, OtherValue);
939 Added = Builder.addBelow(CurValue, OtherValue);
942 Added = Builder.addWith(CurValue, OtherValue);
946 auto Aliasing = Weight.second;
947 if (auto MaybeCurIndex = valueToAttrIndex(CurValue))
948 Aliasing.set(*MaybeCurIndex);
949 if (auto MaybeOtherIndex = valueToAttrIndex(OtherValue))
950 Aliasing.set(*MaybeOtherIndex);
951 Builder.noteAttributes(CurValue, Aliasing);
952 Builder.noteAttributes(OtherValue, Aliasing);
955 Worklist.push_back(OtherNode);
960 // There are times when we end up with parameters not in our graph (i.e. if
961 // it's only used as the condition of a branch). Other bits of code depend on
962 // things that were present during construction being present in the graph.
963 // So, we add all present arguments here.
964 for (auto &Arg : Fn->args()) {
968 return FunctionInfo(Builder.build(), std::move(ReturnedValues));
971 void CFLAliasAnalysis::scan(Function *Fn) {
972 auto InsertPair = Cache.insert(std::make_pair(Fn, Optional<FunctionInfo>()));
974 assert(InsertPair.second &&
975 "Trying to scan a function that has already been cached");
977 FunctionInfo Info(buildSetsFrom(*this, Fn));
978 Cache[Fn] = std::move(Info);
979 Handles.push_front(FunctionHandle(Fn, this));
982 AliasAnalysis::AliasResult
983 CFLAliasAnalysis::query(const AliasAnalysis::Location &LocA,
984 const AliasAnalysis::Location &LocB) {
985 auto *ValA = const_cast<Value *>(LocA.Ptr);
986 auto *ValB = const_cast<Value *>(LocB.Ptr);
988 Function *Fn = nullptr;
989 auto MaybeFnA = parentFunctionOfValue(ValA);
990 auto MaybeFnB = parentFunctionOfValue(ValB);
991 if (!MaybeFnA.hasValue() && !MaybeFnB.hasValue()) {
992 // The only times this is known to happen are when globals + InlineAsm
994 DEBUG(dbgs() << "CFLAA: could not extract parent function information.\n");
995 return AliasAnalysis::MayAlias;
998 if (MaybeFnA.hasValue()) {
1000 assert((!MaybeFnB.hasValue() || *MaybeFnB == *MaybeFnA) &&
1001 "Interprocedural queries not supported");
1006 assert(Fn != nullptr);
1007 auto &MaybeInfo = ensureCached(Fn);
1008 assert(MaybeInfo.hasValue());
1010 auto &Sets = MaybeInfo->Sets;
1011 auto MaybeA = Sets.find(ValA);
1012 if (!MaybeA.hasValue())
1013 return AliasAnalysis::MayAlias;
1015 auto MaybeB = Sets.find(ValB);
1016 if (!MaybeB.hasValue())
1017 return AliasAnalysis::MayAlias;
1019 auto SetA = *MaybeA;
1020 auto SetB = *MaybeB;
1021 auto AttrsA = Sets.getLink(SetA.Index).Attrs;
1022 auto AttrsB = Sets.getLink(SetB.Index).Attrs;
1024 // Stratified set attributes are used as markets to signify whether a member
1025 // of a StratifiedSet (or a member of a set above the current set) has
1026 // interacted with either arguments or globals. "Interacted with" meaning
1027 // its value may be different depending on the value of an argument or
1028 // global. The thought behind this is that, because arguments and globals
1029 // may alias each other, if AttrsA and AttrsB have touched args/globals,
1030 // we must conservatively say that they alias. However, if at least one of
1031 // the sets has no values that could legally be altered by changing the value
1032 // of an argument or global, then we don't have to be as conservative.
1033 if (AttrsA.any() && AttrsB.any())
1034 return AliasAnalysis::MayAlias;
1036 // We currently unify things even if the accesses to them may not be in
1037 // bounds, so we can't return partial alias here because we don't
1038 // know whether the pointer is really within the object or not.
1039 // IE Given an out of bounds GEP and an alloca'd pointer, we may
1040 // unify the two. We can't return partial alias for this case.
1041 // Since we do not currently track enough information to
1044 if (SetA.Index == SetB.Index)
1045 return AliasAnalysis::MayAlias;
1047 return AliasAnalysis::NoAlias;
1050 bool CFLAliasAnalysis::doInitialization(Module &M) {
1051 InitializeAliasAnalysis(this, &M.getDataLayout());