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, or Assign.
19 // Two variables are considered as aliasing iff you can reach one value's node
20 // from the other value's node and the language formed by concatenating all of
21 // the edge labels (actions) conforms to a context-free grammar.
23 // Because this algorithm requires a graph search on each query, we execute the
24 // algorithm outlined in "Fast algorithms..." (mentioned above)
25 // in order to transform the graph into sets of variables that may alias in
26 // ~nlogn time (n = number of variables.), which makes queries take constant
28 //===----------------------------------------------------------------------===//
30 #include "llvm/Analysis/CFLAliasAnalysis.h"
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/IR/Constants.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/InstVisitor.h"
40 #include "llvm/IR/Instructions.h"
41 #include "llvm/Pass.h"
42 #include "llvm/Support/Allocator.h"
43 #include "llvm/Support/Compiler.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/raw_ostream.h"
54 #define DEBUG_TYPE "cfl-aa"
56 // -- Setting up/registering CFLAA pass -- //
57 char CFLAliasAnalysis::ID = 0;
59 INITIALIZE_AG_PASS(CFLAliasAnalysis, AliasAnalysis, "cfl-aa",
60 "CFL-Based AA implementation", false, true, false)
62 ImmutablePass *llvm::createCFLAliasAnalysisPass() {
63 return new CFLAliasAnalysis();
66 // \brief Information we have about a function and would like to keep around
67 struct CFLAliasAnalysis::FunctionInfo {
68 StratifiedSets<Value *> Sets;
69 // Lots of functions have < 4 returns. Adjust as necessary.
70 SmallVector<Value *, 4> ReturnedValues;
72 FunctionInfo(StratifiedSets<Value *> &&S, SmallVector<Value *, 4> &&RV)
73 : Sets(std::move(S)), ReturnedValues(std::move(RV)) {}
76 CFLAliasAnalysis::CFLAliasAnalysis() : ImmutablePass(ID) {
77 initializeCFLAliasAnalysisPass(*PassRegistry::getPassRegistry());
80 CFLAliasAnalysis::~CFLAliasAnalysis() {}
82 void CFLAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
83 AliasAnalysis::getAnalysisUsage(AU);
86 void *CFLAliasAnalysis::getAdjustedAnalysisPointer(const void *ID) {
87 if (ID == &AliasAnalysis::ID)
88 return (AliasAnalysis *)this;
92 // Try to go from a Value* to a Function*. Never returns nullptr.
93 static Optional<Function *> parentFunctionOfValue(Value *);
95 // Returns possible functions called by the Inst* into the given
96 // SmallVectorImpl. Returns true if targets found, false otherwise.
97 // This is templated because InvokeInst/CallInst give us the same
98 // set of functions that we care about, and I don't like repeating
100 template <typename Inst>
101 static bool getPossibleTargets(Inst *, SmallVectorImpl<Function *> &);
103 // Some instructions need to have their users tracked. Instructions like
104 // `add` require you to get the users of the Instruction* itself, other
105 // instructions like `store` require you to get the users of the first
106 // operand. This function gets the "proper" value to track for each
107 // type of instruction we support.
108 static Optional<Value *> getTargetValue(Instruction *);
110 // There are certain instructions (i.e. FenceInst, etc.) that we ignore.
111 // This notes that we should ignore those.
112 static bool hasUsefulEdges(Instruction *);
114 const StratifiedIndex StratifiedLink::SetSentinel =
115 std::numeric_limits<StratifiedIndex>::max();
118 // StratifiedInfo Attribute things.
119 typedef unsigned StratifiedAttr;
120 LLVM_CONSTEXPR unsigned MaxStratifiedAttrIndex = NumStratifiedAttrs;
121 LLVM_CONSTEXPR unsigned AttrAllIndex = 0;
122 LLVM_CONSTEXPR unsigned AttrGlobalIndex = 1;
123 LLVM_CONSTEXPR unsigned AttrUnknownIndex = 2;
124 LLVM_CONSTEXPR unsigned AttrFirstArgIndex = 3;
125 LLVM_CONSTEXPR unsigned AttrLastArgIndex = MaxStratifiedAttrIndex;
126 LLVM_CONSTEXPR unsigned AttrMaxNumArgs = AttrLastArgIndex - AttrFirstArgIndex;
128 LLVM_CONSTEXPR StratifiedAttr AttrNone = 0;
129 LLVM_CONSTEXPR StratifiedAttr AttrUnknown = 1 << AttrUnknownIndex;
130 LLVM_CONSTEXPR StratifiedAttr AttrAll = ~AttrNone;
132 // \brief StratifiedSets call for knowledge of "direction", so this is how we
133 // represent that locally.
134 enum class Level { Same, Above, Below };
136 // \brief Edges can be one of four "weights" -- each weight must have an inverse
137 // weight (Assign has Assign; Reference has Dereference).
138 enum class EdgeType {
139 // The weight assigned when assigning from or to a value. For example, in:
140 // %b = getelementptr %a, 0
141 // ...The relationships are %b assign %a, and %a assign %b. This used to be
142 // two edges, but having a distinction bought us nothing.
145 // The edge used when we have an edge going from some handle to a Value.
146 // Examples of this include:
147 // %b = load %a (%b Dereference %a)
148 // %b = extractelement %a, 0 (%a Dereference %b)
151 // The edge used when our edge goes from a value to a handle that may have
152 // contained it at some point. Examples:
153 // %b = load %a (%a Reference %b)
154 // %b = extractelement %a, 0 (%b Reference %a)
158 // \brief Encodes the notion of a "use"
160 // \brief Which value the edge is coming from
163 // \brief Which value the edge is pointing to
166 // \brief Edge weight
169 // \brief Whether we aliased any external values along the way that may be
170 // invisible to the analysis (i.e. landingpad for exceptions, calls for
171 // interprocedural analysis, etc.)
172 StratifiedAttrs AdditionalAttrs;
174 Edge(Value *From, Value *To, EdgeType W, StratifiedAttrs A)
175 : From(From), To(To), Weight(W), AdditionalAttrs(A) {}
178 // \brief Gets the edges our graph should have, based on an Instruction*
179 class GetEdgesVisitor : public InstVisitor<GetEdgesVisitor, void> {
180 CFLAliasAnalysis &AA;
181 SmallVectorImpl<Edge> &Output;
184 GetEdgesVisitor(CFLAliasAnalysis &AA, SmallVectorImpl<Edge> &Output)
185 : AA(AA), Output(Output) {}
187 void visitInstruction(Instruction &) {
188 llvm_unreachable("Unsupported instruction encountered");
191 void visitPtrToIntInst(PtrToIntInst &Inst) {
192 auto *Ptr = Inst.getOperand(0);
193 Output.push_back(Edge(Ptr, Ptr, EdgeType::Assign, AttrUnknown));
196 void visitIntToPtrInst(IntToPtrInst &Inst) {
198 Output.push_back(Edge(Ptr, Ptr, EdgeType::Assign, AttrUnknown));
201 void visitCastInst(CastInst &Inst) {
203 Edge(&Inst, Inst.getOperand(0), EdgeType::Assign, AttrNone));
206 void visitBinaryOperator(BinaryOperator &Inst) {
207 auto *Op1 = Inst.getOperand(0);
208 auto *Op2 = Inst.getOperand(1);
209 Output.push_back(Edge(&Inst, Op1, EdgeType::Assign, AttrNone));
210 Output.push_back(Edge(&Inst, Op2, EdgeType::Assign, AttrNone));
213 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
214 auto *Ptr = Inst.getPointerOperand();
215 auto *Val = Inst.getNewValOperand();
216 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
219 void visitAtomicRMWInst(AtomicRMWInst &Inst) {
220 auto *Ptr = Inst.getPointerOperand();
221 auto *Val = Inst.getValOperand();
222 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
225 void visitPHINode(PHINode &Inst) {
226 for (Value *Val : Inst.incoming_values()) {
227 Output.push_back(Edge(&Inst, Val, EdgeType::Assign, AttrNone));
231 void visitGetElementPtrInst(GetElementPtrInst &Inst) {
232 auto *Op = Inst.getPointerOperand();
233 Output.push_back(Edge(&Inst, Op, EdgeType::Assign, AttrNone));
234 for (auto I = Inst.idx_begin(), E = Inst.idx_end(); I != E; ++I)
235 Output.push_back(Edge(&Inst, *I, EdgeType::Assign, AttrNone));
238 void visitSelectInst(SelectInst &Inst) {
239 // Condition is not processed here (The actual statement producing
240 // the condition result is processed elsewhere). For select, the
241 // condition is evaluated, but not loaded, stored, or assigned
242 // simply as a result of being the condition of a select.
244 auto *TrueVal = Inst.getTrueValue();
245 Output.push_back(Edge(&Inst, TrueVal, EdgeType::Assign, AttrNone));
246 auto *FalseVal = Inst.getFalseValue();
247 Output.push_back(Edge(&Inst, FalseVal, EdgeType::Assign, AttrNone));
250 void visitAllocaInst(AllocaInst &) {}
252 void visitLoadInst(LoadInst &Inst) {
253 auto *Ptr = Inst.getPointerOperand();
255 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
258 void visitStoreInst(StoreInst &Inst) {
259 auto *Ptr = Inst.getPointerOperand();
260 auto *Val = Inst.getValueOperand();
261 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
264 void visitVAArgInst(VAArgInst &Inst) {
265 // We can't fully model va_arg here. For *Ptr = Inst.getOperand(0), it does
267 // 1. Loads a value from *((T*)*Ptr).
268 // 2. Increments (stores to) *Ptr by some target-specific amount.
269 // For now, we'll handle this like a landingpad instruction (by placing the
270 // result in its own group, and having that group alias externals).
272 Output.push_back(Edge(Val, Val, EdgeType::Assign, AttrAll));
275 static bool isFunctionExternal(Function *Fn) {
276 return Fn->isDeclaration() || !Fn->hasLocalLinkage();
279 // Gets whether the sets at Index1 above, below, or equal to the sets at
280 // Index2. Returns None if they are not in the same set chain.
281 static Optional<Level> getIndexRelation(const StratifiedSets<Value *> &Sets,
282 StratifiedIndex Index1,
283 StratifiedIndex Index2) {
284 if (Index1 == Index2)
287 const auto *Current = &Sets.getLink(Index1);
288 while (Current->hasBelow()) {
289 if (Current->Below == Index2)
291 Current = &Sets.getLink(Current->Below);
294 Current = &Sets.getLink(Index1);
295 while (Current->hasAbove()) {
296 if (Current->Above == Index2)
298 Current = &Sets.getLink(Current->Above);
305 tryInterproceduralAnalysis(const SmallVectorImpl<Function *> &Fns,
307 const iterator_range<User::op_iterator> &Args) {
308 const unsigned ExpectedMaxArgs = 8;
309 const unsigned MaxSupportedArgs = 50;
310 assert(Fns.size() > 0);
312 // I put this here to give us an upper bound on time taken by IPA. Is it
313 // really (realistically) needed? Keep in mind that we do have an n^2 algo.
314 if (std::distance(Args.begin(), Args.end()) > (int)MaxSupportedArgs)
317 // Exit early if we'll fail anyway
318 for (auto *Fn : Fns) {
319 if (isFunctionExternal(Fn) || Fn->isVarArg())
321 auto &MaybeInfo = AA.ensureCached(Fn);
322 if (!MaybeInfo.hasValue())
326 SmallVector<Value *, ExpectedMaxArgs> Arguments(Args.begin(), Args.end());
327 SmallVector<StratifiedInfo, ExpectedMaxArgs> Parameters;
328 for (auto *Fn : Fns) {
329 auto &Info = *AA.ensureCached(Fn);
330 auto &Sets = Info.Sets;
331 auto &RetVals = Info.ReturnedValues;
334 for (auto &Param : Fn->args()) {
335 auto MaybeInfo = Sets.find(&Param);
336 // Did a new parameter somehow get added to the function/slip by?
337 if (!MaybeInfo.hasValue())
339 Parameters.push_back(*MaybeInfo);
342 // Adding an edge from argument -> return value for each parameter that
343 // may alias the return value
344 for (unsigned I = 0, E = Parameters.size(); I != E; ++I) {
345 auto &ParamInfo = Parameters[I];
346 auto &ArgVal = Arguments[I];
347 bool AddEdge = false;
348 StratifiedAttrs Externals;
349 for (unsigned X = 0, XE = RetVals.size(); X != XE; ++X) {
350 auto MaybeInfo = Sets.find(RetVals[X]);
351 if (!MaybeInfo.hasValue())
354 auto &RetInfo = *MaybeInfo;
355 auto RetAttrs = Sets.getLink(RetInfo.Index).Attrs;
356 auto ParamAttrs = Sets.getLink(ParamInfo.Index).Attrs;
358 getIndexRelation(Sets, ParamInfo.Index, RetInfo.Index);
359 if (MaybeRelation.hasValue()) {
361 Externals |= RetAttrs | ParamAttrs;
365 Output.push_back(Edge(FuncValue, ArgVal, EdgeType::Assign,
366 StratifiedAttrs().flip()));
369 if (Parameters.size() != Arguments.size())
372 // Adding edges between arguments for arguments that may end up aliasing
373 // each other. This is necessary for functions such as
374 // void foo(int** a, int** b) { *a = *b; }
375 // (Technically, the proper sets for this would be those below
376 // Arguments[I] and Arguments[X], but our algorithm will produce
377 // extremely similar, and equally correct, results either way)
378 for (unsigned I = 0, E = Arguments.size(); I != E; ++I) {
379 auto &MainVal = Arguments[I];
380 auto &MainInfo = Parameters[I];
381 auto &MainAttrs = Sets.getLink(MainInfo.Index).Attrs;
382 for (unsigned X = I + 1; X != E; ++X) {
383 auto &SubInfo = Parameters[X];
384 auto &SubVal = Arguments[X];
385 auto &SubAttrs = Sets.getLink(SubInfo.Index).Attrs;
387 getIndexRelation(Sets, MainInfo.Index, SubInfo.Index);
389 if (!MaybeRelation.hasValue())
392 auto NewAttrs = SubAttrs | MainAttrs;
393 Output.push_back(Edge(MainVal, SubVal, EdgeType::Assign, NewAttrs));
400 template <typename InstT> void visitCallLikeInst(InstT &Inst) {
401 // TODO: Add support for noalias args/all the other fun function attributes
402 // that we can tack on.
403 SmallVector<Function *, 4> Targets;
404 if (getPossibleTargets(&Inst, Targets)) {
405 if (tryInterproceduralAnalysis(Targets, &Inst, Inst.arg_operands()))
407 // Cleanup from interprocedural analysis
411 // Because the function is opaque, we need to note that anything
412 // could have happened to the arguments, and that the result could alias
413 // just about anything, too.
414 // The goal of the loop is in part to unify many Values into one set, so we
415 // don't care if the function is void there.
416 for (Value *V : Inst.arg_operands())
417 Output.push_back(Edge(&Inst, V, EdgeType::Assign, AttrAll));
418 if (Inst.getNumArgOperands() == 0 &&
419 Inst.getType() != Type::getVoidTy(Inst.getContext()))
420 Output.push_back(Edge(&Inst, &Inst, EdgeType::Assign, AttrAll));
423 void visitCallInst(CallInst &Inst) { visitCallLikeInst(Inst); }
425 void visitInvokeInst(InvokeInst &Inst) { visitCallLikeInst(Inst); }
427 // Because vectors/aggregates are immutable and unaddressable,
428 // there's nothing we can do to coax a value out of them, other
429 // than calling Extract{Element,Value}. We can effectively treat
430 // them as pointers to arbitrary memory locations we can store in
432 void visitExtractElementInst(ExtractElementInst &Inst) {
433 auto *Ptr = Inst.getVectorOperand();
435 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
438 void visitInsertElementInst(InsertElementInst &Inst) {
439 auto *Vec = Inst.getOperand(0);
440 auto *Val = Inst.getOperand(1);
441 Output.push_back(Edge(&Inst, Vec, EdgeType::Assign, AttrNone));
442 Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
445 void visitLandingPadInst(LandingPadInst &Inst) {
446 // Exceptions come from "nowhere", from our analysis' perspective.
447 // So we place the instruction its own group, noting that said group may
449 Output.push_back(Edge(&Inst, &Inst, EdgeType::Assign, AttrAll));
452 void visitInsertValueInst(InsertValueInst &Inst) {
453 auto *Agg = Inst.getOperand(0);
454 auto *Val = Inst.getOperand(1);
455 Output.push_back(Edge(&Inst, Agg, EdgeType::Assign, AttrNone));
456 Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
459 void visitExtractValueInst(ExtractValueInst &Inst) {
460 auto *Ptr = Inst.getAggregateOperand();
461 Output.push_back(Edge(&Inst, Ptr, EdgeType::Reference, AttrNone));
464 void visitShuffleVectorInst(ShuffleVectorInst &Inst) {
465 auto *From1 = Inst.getOperand(0);
466 auto *From2 = Inst.getOperand(1);
467 Output.push_back(Edge(&Inst, From1, EdgeType::Assign, AttrNone));
468 Output.push_back(Edge(&Inst, From2, EdgeType::Assign, AttrNone));
471 void visitConstantExpr(ConstantExpr *CE) {
472 switch (CE->getOpcode()) {
474 llvm_unreachable("Unknown instruction type encountered!");
475 // Build the switch statement using the Instruction.def file.
476 #define HANDLE_INST(NUM, OPCODE, CLASS) \
477 case Instruction::OPCODE: \
478 visit##OPCODE(*(CLASS *)CE); \
480 #include "llvm/IR/Instruction.def"
485 // For a given instruction, we need to know which Value* to get the
486 // users of in order to build our graph. In some cases (i.e. add),
487 // we simply need the Instruction*. In other cases (i.e. store),
488 // finding the users of the Instruction* is useless; we need to find
489 // the users of the first operand. This handles determining which
490 // value to follow for us.
492 // Note: we *need* to keep this in sync with GetEdgesVisitor. Add
493 // something to GetEdgesVisitor, add it here -- remove something from
494 // GetEdgesVisitor, remove it here.
495 class GetTargetValueVisitor
496 : public InstVisitor<GetTargetValueVisitor, Value *> {
498 Value *visitInstruction(Instruction &Inst) { return &Inst; }
500 Value *visitStoreInst(StoreInst &Inst) { return Inst.getPointerOperand(); }
502 Value *visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
503 return Inst.getPointerOperand();
506 Value *visitAtomicRMWInst(AtomicRMWInst &Inst) {
507 return Inst.getPointerOperand();
510 Value *visitInsertElementInst(InsertElementInst &Inst) {
511 return Inst.getOperand(0);
514 Value *visitInsertValueInst(InsertValueInst &Inst) {
515 return Inst.getAggregateOperand();
519 // Set building requires a weighted bidirectional graph.
520 template <typename EdgeTypeT> class WeightedBidirectionalGraph {
522 typedef std::size_t Node;
525 const static Node StartNode = Node(0);
531 Edge(const EdgeTypeT &W, const Node &N) : Weight(W), Other(N) {}
533 bool operator==(const Edge &E) const {
534 return Weight == E.Weight && Other == E.Other;
537 bool operator!=(const Edge &E) const { return !operator==(E); }
541 std::vector<Edge> Edges;
544 std::vector<NodeImpl> NodeImpls;
546 bool inbounds(Node NodeIndex) const { return NodeIndex < NodeImpls.size(); }
548 const NodeImpl &getNode(Node N) const { return NodeImpls[N]; }
549 NodeImpl &getNode(Node N) { return NodeImpls[N]; }
552 // ----- Various Edge iterators for the graph ----- //
554 // \brief Iterator for edges. Because this graph is bidirected, we don't
555 // allow modification of the edges using this iterator. Additionally, the
556 // iterator becomes invalid if you add edges to or from the node you're
557 // getting the edges of.
558 struct EdgeIterator : public std::iterator<std::forward_iterator_tag,
559 std::tuple<EdgeTypeT, Node *>> {
560 EdgeIterator(const typename std::vector<Edge>::const_iterator &Iter)
563 EdgeIterator(NodeImpl &Impl) : Current(Impl.begin()) {}
565 EdgeIterator &operator++() {
570 EdgeIterator operator++(int) {
571 EdgeIterator Copy(Current);
576 std::tuple<EdgeTypeT, Node> &operator*() {
577 Store = std::make_tuple(Current->Weight, Current->Other);
581 bool operator==(const EdgeIterator &Other) const {
582 return Current == Other.Current;
585 bool operator!=(const EdgeIterator &Other) const {
586 return !operator==(Other);
590 typename std::vector<Edge>::const_iterator Current;
591 std::tuple<EdgeTypeT, Node> Store;
594 // Wrapper for EdgeIterator with begin()/end() calls.
595 struct EdgeIterable {
596 EdgeIterable(const std::vector<Edge> &Edges)
597 : BeginIter(Edges.begin()), EndIter(Edges.end()) {}
599 EdgeIterator begin() { return EdgeIterator(BeginIter); }
601 EdgeIterator end() { return EdgeIterator(EndIter); }
604 typename std::vector<Edge>::const_iterator BeginIter;
605 typename std::vector<Edge>::const_iterator EndIter;
608 // ----- Actual graph-related things ----- //
610 WeightedBidirectionalGraph() {}
612 WeightedBidirectionalGraph(WeightedBidirectionalGraph<EdgeTypeT> &&Other)
613 : NodeImpls(std::move(Other.NodeImpls)) {}
615 WeightedBidirectionalGraph<EdgeTypeT> &
616 operator=(WeightedBidirectionalGraph<EdgeTypeT> &&Other) {
617 NodeImpls = std::move(Other.NodeImpls);
622 auto Index = NodeImpls.size();
623 auto NewNode = Node(Index);
624 NodeImpls.push_back(NodeImpl());
628 void addEdge(Node From, Node To, const EdgeTypeT &Weight,
629 const EdgeTypeT &ReverseWeight) {
630 assert(inbounds(From));
631 assert(inbounds(To));
632 auto &FromNode = getNode(From);
633 auto &ToNode = getNode(To);
634 FromNode.Edges.push_back(Edge(Weight, To));
635 ToNode.Edges.push_back(Edge(ReverseWeight, From));
638 EdgeIterable edgesFor(const Node &N) const {
639 const auto &Node = getNode(N);
640 return EdgeIterable(Node.Edges);
643 bool empty() const { return NodeImpls.empty(); }
644 std::size_t size() const { return NodeImpls.size(); }
646 // \brief Gets an arbitrary node in the graph as a starting point for
648 Node getEntryNode() {
649 assert(inbounds(StartNode));
654 typedef WeightedBidirectionalGraph<std::pair<EdgeType, StratifiedAttrs>> GraphT;
655 typedef DenseMap<Value *, GraphT::Node> NodeMapT;
658 //===----------------------------------------------------------------------===//
659 // Function declarations that require types defined in the namespace above
660 //===----------------------------------------------------------------------===//
662 // Given an argument number, returns the appropriate Attr index to set.
663 static StratifiedAttr argNumberToAttrIndex(StratifiedAttr);
665 // Given a Value, potentially return which AttrIndex it maps to.
666 static Optional<StratifiedAttr> valueToAttrIndex(Value *Val);
668 // Gets the inverse of a given EdgeType.
669 static EdgeType flipWeight(EdgeType);
671 // Gets edges of the given Instruction*, writing them to the SmallVector*.
672 static void argsToEdges(CFLAliasAnalysis &, Instruction *,
673 SmallVectorImpl<Edge> &);
675 // Gets edges of the given ConstantExpr*, writing them to the SmallVector*.
676 static void argsToEdges(CFLAliasAnalysis &, ConstantExpr *,
677 SmallVectorImpl<Edge> &);
679 // Gets the "Level" that one should travel in StratifiedSets
680 // given an EdgeType.
681 static Level directionOfEdgeType(EdgeType);
683 // Builds the graph needed for constructing the StratifiedSets for the
685 static void buildGraphFrom(CFLAliasAnalysis &, Function *,
686 SmallVectorImpl<Value *> &, NodeMapT &, GraphT &);
688 // Gets the edges of a ConstantExpr as if it was an Instruction. This
689 // function also acts on any nested ConstantExprs, adding the edges
690 // of those to the given SmallVector as well.
691 static void constexprToEdges(CFLAliasAnalysis &, ConstantExpr &,
692 SmallVectorImpl<Edge> &);
694 // Given an Instruction, this will add it to the graph, along with any
695 // Instructions that are potentially only available from said Instruction
696 // For example, given the following line:
697 // %0 = load i16* getelementptr ([1 x i16]* @a, 0, 0), align 2
698 // addInstructionToGraph would add both the `load` and `getelementptr`
699 // instructions to the graph appropriately.
700 static void addInstructionToGraph(CFLAliasAnalysis &, Instruction &,
701 SmallVectorImpl<Value *> &, NodeMapT &,
704 // Notes whether it would be pointless to add the given Value to our sets.
705 static bool canSkipAddingToSets(Value *Val);
707 static Optional<Function *> parentFunctionOfValue(Value *Val) {
708 if (auto *Inst = dyn_cast<Instruction>(Val)) {
709 auto *Bb = Inst->getParent();
710 return Bb->getParent();
713 if (auto *Arg = dyn_cast<Argument>(Val))
714 return Arg->getParent();
718 template <typename Inst>
719 static bool getPossibleTargets(Inst *Call,
720 SmallVectorImpl<Function *> &Output) {
721 if (auto *Fn = Call->getCalledFunction()) {
722 Output.push_back(Fn);
726 // TODO: If the call is indirect, we might be able to enumerate all potential
727 // targets of the call and return them, rather than just failing.
731 static Optional<Value *> getTargetValue(Instruction *Inst) {
732 GetTargetValueVisitor V;
733 return V.visit(Inst);
736 static bool hasUsefulEdges(Instruction *Inst) {
737 bool IsNonInvokeTerminator =
738 isa<TerminatorInst>(Inst) && !isa<InvokeInst>(Inst);
739 return !isa<CmpInst>(Inst) && !isa<FenceInst>(Inst) && !IsNonInvokeTerminator;
742 static bool hasUsefulEdges(ConstantExpr *CE) {
743 // ConstantExpr doesn't have terminators, invokes, or fences, so only needs
744 // to check for compares.
745 return CE->getOpcode() != Instruction::ICmp &&
746 CE->getOpcode() != Instruction::FCmp;
749 static Optional<StratifiedAttr> valueToAttrIndex(Value *Val) {
750 if (isa<GlobalValue>(Val))
751 return AttrGlobalIndex;
753 if (auto *Arg = dyn_cast<Argument>(Val))
754 // Only pointer arguments should have the argument attribute,
755 // because things can't escape through scalars without us seeing a
756 // cast, and thus, interaction with them doesn't matter.
757 if (!Arg->hasNoAliasAttr() && Arg->getType()->isPointerTy())
758 return argNumberToAttrIndex(Arg->getArgNo());
762 static StratifiedAttr argNumberToAttrIndex(unsigned ArgNum) {
763 if (ArgNum >= AttrMaxNumArgs)
765 return ArgNum + AttrFirstArgIndex;
768 static EdgeType flipWeight(EdgeType Initial) {
770 case EdgeType::Assign:
771 return EdgeType::Assign;
772 case EdgeType::Dereference:
773 return EdgeType::Reference;
774 case EdgeType::Reference:
775 return EdgeType::Dereference;
777 llvm_unreachable("Incomplete coverage of EdgeType enum");
780 static void argsToEdges(CFLAliasAnalysis &Analysis, Instruction *Inst,
781 SmallVectorImpl<Edge> &Output) {
782 assert(hasUsefulEdges(Inst) &&
783 "Expected instructions to have 'useful' edges");
784 GetEdgesVisitor v(Analysis, Output);
788 static void argsToEdges(CFLAliasAnalysis &Analysis, ConstantExpr *CE,
789 SmallVectorImpl<Edge> &Output) {
790 assert(hasUsefulEdges(CE) && "Expected constant expr to have 'useful' edges");
791 GetEdgesVisitor v(Analysis, Output);
792 v.visitConstantExpr(CE);
795 static Level directionOfEdgeType(EdgeType Weight) {
797 case EdgeType::Reference:
799 case EdgeType::Dereference:
801 case EdgeType::Assign:
804 llvm_unreachable("Incomplete switch coverage");
807 static void constexprToEdges(CFLAliasAnalysis &Analysis,
808 ConstantExpr &CExprToCollapse,
809 SmallVectorImpl<Edge> &Results) {
810 SmallVector<ConstantExpr *, 4> Worklist;
811 Worklist.push_back(&CExprToCollapse);
813 SmallVector<Edge, 8> ConstexprEdges;
814 SmallPtrSet<ConstantExpr *, 4> Visited;
815 while (!Worklist.empty()) {
816 auto *CExpr = Worklist.pop_back_val();
818 if (!hasUsefulEdges(CExpr))
821 ConstexprEdges.clear();
822 argsToEdges(Analysis, CExpr, ConstexprEdges);
823 for (auto &Edge : ConstexprEdges) {
824 if (auto *Nested = dyn_cast<ConstantExpr>(Edge.From))
825 if (Visited.insert(Nested).second)
826 Worklist.push_back(Nested);
828 if (auto *Nested = dyn_cast<ConstantExpr>(Edge.To))
829 if (Visited.insert(Nested).second)
830 Worklist.push_back(Nested);
833 Results.append(ConstexprEdges.begin(), ConstexprEdges.end());
837 static void addInstructionToGraph(CFLAliasAnalysis &Analysis, Instruction &Inst,
838 SmallVectorImpl<Value *> &ReturnedValues,
839 NodeMapT &Map, GraphT &Graph) {
840 const auto findOrInsertNode = [&Map, &Graph](Value *Val) {
841 auto Pair = Map.insert(std::make_pair(Val, GraphT::Node()));
842 auto &Iter = Pair.first;
844 auto NewNode = Graph.addNode();
845 Iter->second = NewNode;
850 // We don't want the edges of most "return" instructions, but we *do* want
851 // to know what can be returned.
852 if (isa<ReturnInst>(&Inst))
853 ReturnedValues.push_back(&Inst);
855 if (!hasUsefulEdges(&Inst))
858 SmallVector<Edge, 8> Edges;
859 argsToEdges(Analysis, &Inst, Edges);
861 // In the case of an unused alloca (or similar), edges may be empty. Note
862 // that it exists so we can potentially answer NoAlias.
864 auto MaybeVal = getTargetValue(&Inst);
865 assert(MaybeVal.hasValue());
866 auto *Target = *MaybeVal;
867 findOrInsertNode(Target);
871 const auto addEdgeToGraph = [&Graph, &findOrInsertNode](const Edge &E) {
872 auto To = findOrInsertNode(E.To);
873 auto From = findOrInsertNode(E.From);
874 auto FlippedWeight = flipWeight(E.Weight);
875 auto Attrs = E.AdditionalAttrs;
876 Graph.addEdge(From, To, std::make_pair(E.Weight, Attrs),
877 std::make_pair(FlippedWeight, Attrs));
880 SmallVector<ConstantExpr *, 4> ConstantExprs;
881 for (const Edge &E : Edges) {
883 if (auto *Constexpr = dyn_cast<ConstantExpr>(E.To))
884 ConstantExprs.push_back(Constexpr);
885 if (auto *Constexpr = dyn_cast<ConstantExpr>(E.From))
886 ConstantExprs.push_back(Constexpr);
889 for (ConstantExpr *CE : ConstantExprs) {
891 constexprToEdges(Analysis, *CE, Edges);
892 std::for_each(Edges.begin(), Edges.end(), addEdgeToGraph);
896 // Aside: We may remove graph construction entirely, because it doesn't really
897 // buy us much that we don't already have. I'd like to add interprocedural
898 // analysis prior to this however, in case that somehow requires the graph
899 // produced by this for efficient execution
900 static void buildGraphFrom(CFLAliasAnalysis &Analysis, Function *Fn,
901 SmallVectorImpl<Value *> &ReturnedValues,
902 NodeMapT &Map, GraphT &Graph) {
903 for (auto &Bb : Fn->getBasicBlockList())
904 for (auto &Inst : Bb.getInstList())
905 addInstructionToGraph(Analysis, Inst, ReturnedValues, Map, Graph);
908 static bool canSkipAddingToSets(Value *Val) {
909 // Constants can share instances, which may falsely unify multiple
911 // store i32* null, i32** %ptr1
912 // store i32* null, i32** %ptr2
913 // clearly ptr1 and ptr2 should not be unified into the same set, so
914 // we should filter out the (potentially shared) instance to
916 if (isa<Constant>(Val)) {
917 bool Container = isa<ConstantVector>(Val) || isa<ConstantArray>(Val) ||
918 isa<ConstantStruct>(Val);
919 // TODO: Because all of these things are constant, we can determine whether
920 // the data is *actually* mutable at graph building time. This will probably
921 // come for free/cheap with offset awareness.
922 bool CanStoreMutableData =
923 isa<GlobalValue>(Val) || isa<ConstantExpr>(Val) || Container;
924 return !CanStoreMutableData;
930 // Builds the graph + StratifiedSets for a function.
931 CFLAliasAnalysis::FunctionInfo CFLAliasAnalysis::buildSetsFrom(Function *Fn) {
934 SmallVector<Value *, 4> ReturnedValues;
936 buildGraphFrom(*this, Fn, ReturnedValues, Map, Graph);
938 DenseMap<GraphT::Node, Value *> NodeValueMap;
939 NodeValueMap.resize(Map.size());
940 for (const auto &Pair : Map)
941 NodeValueMap.insert(std::make_pair(Pair.second, Pair.first));
943 const auto findValueOrDie = [&NodeValueMap](GraphT::Node Node) {
944 auto ValIter = NodeValueMap.find(Node);
945 assert(ValIter != NodeValueMap.end());
946 return ValIter->second;
949 StratifiedSetsBuilder<Value *> Builder;
951 SmallVector<GraphT::Node, 16> Worklist;
952 for (auto &Pair : Map) {
955 auto *Value = Pair.first;
957 auto InitialNode = Pair.second;
958 Worklist.push_back(InitialNode);
959 while (!Worklist.empty()) {
960 auto Node = Worklist.pop_back_val();
961 auto *CurValue = findValueOrDie(Node);
962 if (canSkipAddingToSets(CurValue))
965 for (const auto &EdgeTuple : Graph.edgesFor(Node)) {
966 auto Weight = std::get<0>(EdgeTuple);
967 auto Label = Weight.first;
968 auto &OtherNode = std::get<1>(EdgeTuple);
969 auto *OtherValue = findValueOrDie(OtherNode);
971 if (canSkipAddingToSets(OtherValue))
975 switch (directionOfEdgeType(Label)) {
977 Added = Builder.addAbove(CurValue, OtherValue);
980 Added = Builder.addBelow(CurValue, OtherValue);
983 Added = Builder.addWith(CurValue, OtherValue);
987 auto Aliasing = Weight.second;
988 if (auto MaybeCurIndex = valueToAttrIndex(CurValue))
989 Aliasing.set(*MaybeCurIndex);
990 if (auto MaybeOtherIndex = valueToAttrIndex(OtherValue))
991 Aliasing.set(*MaybeOtherIndex);
992 Builder.noteAttributes(CurValue, Aliasing);
993 Builder.noteAttributes(OtherValue, Aliasing);
996 Worklist.push_back(OtherNode);
1001 // There are times when we end up with parameters not in our graph (i.e. if
1002 // it's only used as the condition of a branch). Other bits of code depend on
1003 // things that were present during construction being present in the graph.
1004 // So, we add all present arguments here.
1005 for (auto &Arg : Fn->args()) {
1006 if (!Builder.add(&Arg))
1009 auto Attrs = valueToAttrIndex(&Arg);
1010 if (Attrs.hasValue())
1011 Builder.noteAttributes(&Arg, *Attrs);
1014 return FunctionInfo(Builder.build(), std::move(ReturnedValues));
1017 void CFLAliasAnalysis::scan(Function *Fn) {
1018 auto InsertPair = Cache.insert(std::make_pair(Fn, Optional<FunctionInfo>()));
1020 assert(InsertPair.second &&
1021 "Trying to scan a function that has already been cached");
1023 FunctionInfo Info(buildSetsFrom(Fn));
1024 Cache[Fn] = std::move(Info);
1025 Handles.push_front(FunctionHandle(Fn, this));
1028 void CFLAliasAnalysis::evict(Function *Fn) { Cache.erase(Fn); }
1030 /// \brief Ensures that the given function is available in the cache.
1031 /// Returns the appropriate entry from the cache.
1032 const Optional<CFLAliasAnalysis::FunctionInfo> &
1033 CFLAliasAnalysis::ensureCached(Function *Fn) {
1034 auto Iter = Cache.find(Fn);
1035 if (Iter == Cache.end()) {
1037 Iter = Cache.find(Fn);
1038 assert(Iter != Cache.end());
1039 assert(Iter->second.hasValue());
1041 return Iter->second;
1044 AliasResult CFLAliasAnalysis::query(const MemoryLocation &LocA,
1045 const MemoryLocation &LocB) {
1046 auto *ValA = const_cast<Value *>(LocA.Ptr);
1047 auto *ValB = const_cast<Value *>(LocB.Ptr);
1049 Function *Fn = nullptr;
1050 auto MaybeFnA = parentFunctionOfValue(ValA);
1051 auto MaybeFnB = parentFunctionOfValue(ValB);
1052 if (!MaybeFnA.hasValue() && !MaybeFnB.hasValue()) {
1053 // The only times this is known to happen are when globals + InlineAsm
1055 DEBUG(dbgs() << "CFLAA: could not extract parent function information.\n");
1059 if (MaybeFnA.hasValue()) {
1061 assert((!MaybeFnB.hasValue() || *MaybeFnB == *MaybeFnA) &&
1062 "Interprocedural queries not supported");
1067 assert(Fn != nullptr);
1068 auto &MaybeInfo = ensureCached(Fn);
1069 assert(MaybeInfo.hasValue());
1071 auto &Sets = MaybeInfo->Sets;
1072 auto MaybeA = Sets.find(ValA);
1073 if (!MaybeA.hasValue())
1076 auto MaybeB = Sets.find(ValB);
1077 if (!MaybeB.hasValue())
1080 auto SetA = *MaybeA;
1081 auto SetB = *MaybeB;
1082 auto AttrsA = Sets.getLink(SetA.Index).Attrs;
1083 auto AttrsB = Sets.getLink(SetB.Index).Attrs;
1085 // Stratified set attributes are used as markets to signify whether a member
1086 // of a StratifiedSet (or a member of a set above the current set) has
1087 // interacted with either arguments or globals. "Interacted with" meaning
1088 // its value may be different depending on the value of an argument or
1089 // global. The thought behind this is that, because arguments and globals
1090 // may alias each other, if AttrsA and AttrsB have touched args/globals,
1091 // we must conservatively say that they alias. However, if at least one of
1092 // the sets has no values that could legally be altered by changing the value
1093 // of an argument or global, then we don't have to be as conservative.
1094 if (AttrsA.any() && AttrsB.any())
1097 // We currently unify things even if the accesses to them may not be in
1098 // bounds, so we can't return partial alias here because we don't
1099 // know whether the pointer is really within the object or not.
1100 // IE Given an out of bounds GEP and an alloca'd pointer, we may
1101 // unify the two. We can't return partial alias for this case.
1102 // Since we do not currently track enough information to
1105 if (SetA.Index == SetB.Index)
1111 bool CFLAliasAnalysis::doInitialization(Module &M) {
1112 InitializeAliasAnalysis(this, &M.getDataLayout());