[PM/AA] Extract a minimal interface for CFLAA to its own header file.
[oota-llvm.git] / lib / Analysis / CFLAliasAnalysis.cpp
1 //===- CFLAliasAnalysis.cpp - CFL-Based Alias Analysis Implementation ------==//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements a CFL-based context-insensitive alias analysis
11 // algorithm. It does not depend on types. The algorithm is a mixture of the one
12 // described in "Demand-driven alias analysis for C" by Xin Zheng and Radu
13 // Rugina, and "Fast algorithms for Dyck-CFL-reachability with applications to
14 // Alias Analysis" by Zhang Q, Lyu M R, Yuan H, and Su Z. -- to summarize the
15 // papers, we build a graph of the uses of a variable, where each node is a
16 // memory location, and each edge is an action that happened on that memory
17 // location.  The "actions" can be one of Dereference, Reference, or Assign.
18 //
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.
22 //
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
27 // time.
28 //===----------------------------------------------------------------------===//
29
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/IR/ValueHandle.h"
42 #include "llvm/Pass.h"
43 #include "llvm/Support/Allocator.h"
44 #include "llvm/Support/Compiler.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include <algorithm>
49 #include <cassert>
50 #include <memory>
51 #include <tuple>
52
53 using namespace llvm;
54
55 #define DEBUG_TYPE "cfl-aa"
56
57 // -- Setting up/registering CFLAA pass -- //
58 char CFLAliasAnalysis::ID = 0;
59
60 INITIALIZE_AG_PASS(CFLAliasAnalysis, AliasAnalysis, "cfl-aa",
61                    "CFL-Based AA implementation", false, true, false)
62
63 ImmutablePass *llvm::createCFLAliasAnalysisPass() {
64   return new CFLAliasAnalysis();
65 }
66
67 // \brief Information we have about a function and would like to keep around
68 struct CFLAliasAnalysis::FunctionInfo {
69   StratifiedSets<Value *> Sets;
70   // Lots of functions have < 4 returns. Adjust as necessary.
71   SmallVector<Value *, 4> ReturnedValues;
72
73   FunctionInfo(StratifiedSets<Value *> &&S, SmallVector<Value *, 4> &&RV)
74       : Sets(std::move(S)), ReturnedValues(std::move(RV)) {}
75 };
76
77 struct CFLAliasAnalysis::FunctionHandle final : public CallbackVH {
78   FunctionHandle(Function *Fn, CFLAliasAnalysis *CFLAA)
79       : CallbackVH(Fn), CFLAA(CFLAA) {
80     assert(Fn != nullptr);
81     assert(CFLAA != nullptr);
82   }
83
84   void deleted() override { removeSelfFromCache(); }
85   void allUsesReplacedWith(Value *) override { removeSelfFromCache(); }
86
87 private:
88   CFLAliasAnalysis *CFLAA;
89
90   void removeSelfFromCache() {
91     assert(CFLAA != nullptr);
92     auto *Val = getValPtr();
93     CFLAA->evict(cast<Function>(Val));
94     setValPtr(nullptr);
95   }
96 };
97
98 CFLAliasAnalysis::CFLAliasAnalysis() : ImmutablePass(ID) {
99   initializeCFLAliasAnalysisPass(*PassRegistry::getPassRegistry());
100 }
101
102 CFLAliasAnalysis::~CFLAliasAnalysis() {}
103
104 void CFLAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
105   AliasAnalysis::getAnalysisUsage(AU);
106 }
107
108 void *CFLAliasAnalysis::getAdjustedAnalysisPointer(const void *ID) {
109   if (ID == &AliasAnalysis::ID)
110     return (AliasAnalysis *)this;
111   return this;
112 }
113
114 // Try to go from a Value* to a Function*. Never returns nullptr.
115 static Optional<Function *> parentFunctionOfValue(Value *);
116
117 // Returns possible functions called by the Inst* into the given
118 // SmallVectorImpl. Returns true if targets found, false otherwise.
119 // This is templated because InvokeInst/CallInst give us the same
120 // set of functions that we care about, and I don't like repeating
121 // myself.
122 template <typename Inst>
123 static bool getPossibleTargets(Inst *, SmallVectorImpl<Function *> &);
124
125 // Some instructions need to have their users tracked. Instructions like
126 // `add` require you to get the users of the Instruction* itself, other
127 // instructions like `store` require you to get the users of the first
128 // operand. This function gets the "proper" value to track for each
129 // type of instruction we support.
130 static Optional<Value *> getTargetValue(Instruction *);
131
132 // There are certain instructions (i.e. FenceInst, etc.) that we ignore.
133 // This notes that we should ignore those.
134 static bool hasUsefulEdges(Instruction *);
135
136 const StratifiedIndex StratifiedLink::SetSentinel =
137     std::numeric_limits<StratifiedIndex>::max();
138
139 namespace {
140 // StratifiedInfo Attribute things.
141 typedef unsigned StratifiedAttr;
142 LLVM_CONSTEXPR unsigned MaxStratifiedAttrIndex = NumStratifiedAttrs;
143 LLVM_CONSTEXPR unsigned AttrAllIndex = 0;
144 LLVM_CONSTEXPR unsigned AttrGlobalIndex = 1;
145 LLVM_CONSTEXPR unsigned AttrUnknownIndex = 2;
146 LLVM_CONSTEXPR unsigned AttrFirstArgIndex = 3;
147 LLVM_CONSTEXPR unsigned AttrLastArgIndex = MaxStratifiedAttrIndex;
148 LLVM_CONSTEXPR unsigned AttrMaxNumArgs = AttrLastArgIndex - AttrFirstArgIndex;
149
150 LLVM_CONSTEXPR StratifiedAttr AttrNone = 0;
151 LLVM_CONSTEXPR StratifiedAttr AttrUnknown = 1 << AttrUnknownIndex;
152 LLVM_CONSTEXPR StratifiedAttr AttrAll = ~AttrNone;
153
154 // \brief StratifiedSets call for knowledge of "direction", so this is how we
155 // represent that locally.
156 enum class Level { Same, Above, Below };
157
158 // \brief Edges can be one of four "weights" -- each weight must have an inverse
159 // weight (Assign has Assign; Reference has Dereference).
160 enum class EdgeType {
161   // The weight assigned when assigning from or to a value. For example, in:
162   // %b = getelementptr %a, 0
163   // ...The relationships are %b assign %a, and %a assign %b. This used to be
164   // two edges, but having a distinction bought us nothing.
165   Assign,
166
167   // The edge used when we have an edge going from some handle to a Value.
168   // Examples of this include:
169   // %b = load %a              (%b Dereference %a)
170   // %b = extractelement %a, 0 (%a Dereference %b)
171   Dereference,
172
173   // The edge used when our edge goes from a value to a handle that may have
174   // contained it at some point. Examples:
175   // %b = load %a              (%a Reference %b)
176   // %b = extractelement %a, 0 (%b Reference %a)
177   Reference
178 };
179
180 // \brief Encodes the notion of a "use"
181 struct Edge {
182   // \brief Which value the edge is coming from
183   Value *From;
184
185   // \brief Which value the edge is pointing to
186   Value *To;
187
188   // \brief Edge weight
189   EdgeType Weight;
190
191   // \brief Whether we aliased any external values along the way that may be
192   // invisible to the analysis (i.e. landingpad for exceptions, calls for
193   // interprocedural analysis, etc.)
194   StratifiedAttrs AdditionalAttrs;
195
196   Edge(Value *From, Value *To, EdgeType W, StratifiedAttrs A)
197       : From(From), To(To), Weight(W), AdditionalAttrs(A) {}
198 };
199
200 // \brief Gets the edges our graph should have, based on an Instruction*
201 class GetEdgesVisitor : public InstVisitor<GetEdgesVisitor, void> {
202   CFLAliasAnalysis &AA;
203   SmallVectorImpl<Edge> &Output;
204
205 public:
206   GetEdgesVisitor(CFLAliasAnalysis &AA, SmallVectorImpl<Edge> &Output)
207       : AA(AA), Output(Output) {}
208
209   void visitInstruction(Instruction &) {
210     llvm_unreachable("Unsupported instruction encountered");
211   }
212
213   void visitPtrToIntInst(PtrToIntInst &Inst) {
214     auto *Ptr = Inst.getOperand(0);
215     Output.push_back(Edge(Ptr, Ptr, EdgeType::Assign, AttrUnknown));
216   }
217
218   void visitIntToPtrInst(IntToPtrInst &Inst) {
219     auto *Ptr = &Inst;
220     Output.push_back(Edge(Ptr, Ptr, EdgeType::Assign, AttrUnknown));
221   }
222
223   void visitCastInst(CastInst &Inst) {
224     Output.push_back(
225         Edge(&Inst, Inst.getOperand(0), EdgeType::Assign, AttrNone));
226   }
227
228   void visitBinaryOperator(BinaryOperator &Inst) {
229     auto *Op1 = Inst.getOperand(0);
230     auto *Op2 = Inst.getOperand(1);
231     Output.push_back(Edge(&Inst, Op1, EdgeType::Assign, AttrNone));
232     Output.push_back(Edge(&Inst, Op2, EdgeType::Assign, AttrNone));
233   }
234
235   void visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
236     auto *Ptr = Inst.getPointerOperand();
237     auto *Val = Inst.getNewValOperand();
238     Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
239   }
240
241   void visitAtomicRMWInst(AtomicRMWInst &Inst) {
242     auto *Ptr = Inst.getPointerOperand();
243     auto *Val = Inst.getValOperand();
244     Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
245   }
246
247   void visitPHINode(PHINode &Inst) {
248     for (Value *Val : Inst.incoming_values()) {
249       Output.push_back(Edge(&Inst, Val, EdgeType::Assign, AttrNone));
250     }
251   }
252
253   void visitGetElementPtrInst(GetElementPtrInst &Inst) {
254     auto *Op = Inst.getPointerOperand();
255     Output.push_back(Edge(&Inst, Op, EdgeType::Assign, AttrNone));
256     for (auto I = Inst.idx_begin(), E = Inst.idx_end(); I != E; ++I)
257       Output.push_back(Edge(&Inst, *I, EdgeType::Assign, AttrNone));
258   }
259
260   void visitSelectInst(SelectInst &Inst) {
261     // Condition is not processed here (The actual statement producing
262     // the condition result is processed elsewhere). For select, the
263     // condition is evaluated, but not loaded, stored, or assigned
264     // simply as a result of being the condition of a select.
265
266     auto *TrueVal = Inst.getTrueValue();
267     Output.push_back(Edge(&Inst, TrueVal, EdgeType::Assign, AttrNone));
268     auto *FalseVal = Inst.getFalseValue();
269     Output.push_back(Edge(&Inst, FalseVal, EdgeType::Assign, AttrNone));
270   }
271
272   void visitAllocaInst(AllocaInst &) {}
273
274   void visitLoadInst(LoadInst &Inst) {
275     auto *Ptr = Inst.getPointerOperand();
276     auto *Val = &Inst;
277     Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
278   }
279
280   void visitStoreInst(StoreInst &Inst) {
281     auto *Ptr = Inst.getPointerOperand();
282     auto *Val = Inst.getValueOperand();
283     Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
284   }
285
286   void visitVAArgInst(VAArgInst &Inst) {
287     // We can't fully model va_arg here. For *Ptr = Inst.getOperand(0), it does
288     // two things:
289     //  1. Loads a value from *((T*)*Ptr).
290     //  2. Increments (stores to) *Ptr by some target-specific amount.
291     // For now, we'll handle this like a landingpad instruction (by placing the
292     // result in its own group, and having that group alias externals).
293     auto *Val = &Inst;
294     Output.push_back(Edge(Val, Val, EdgeType::Assign, AttrAll));
295   }
296
297   static bool isFunctionExternal(Function *Fn) {
298     return Fn->isDeclaration() || !Fn->hasLocalLinkage();
299   }
300
301   // Gets whether the sets at Index1 above, below, or equal to the sets at
302   // Index2. Returns None if they are not in the same set chain.
303   static Optional<Level> getIndexRelation(const StratifiedSets<Value *> &Sets,
304                                           StratifiedIndex Index1,
305                                           StratifiedIndex Index2) {
306     if (Index1 == Index2)
307       return Level::Same;
308
309     const auto *Current = &Sets.getLink(Index1);
310     while (Current->hasBelow()) {
311       if (Current->Below == Index2)
312         return Level::Below;
313       Current = &Sets.getLink(Current->Below);
314     }
315
316     Current = &Sets.getLink(Index1);
317     while (Current->hasAbove()) {
318       if (Current->Above == Index2)
319         return Level::Above;
320       Current = &Sets.getLink(Current->Above);
321     }
322
323     return NoneType();
324   }
325
326   bool
327   tryInterproceduralAnalysis(const SmallVectorImpl<Function *> &Fns,
328                              Value *FuncValue,
329                              const iterator_range<User::op_iterator> &Args) {
330     const unsigned ExpectedMaxArgs = 8;
331     const unsigned MaxSupportedArgs = 50;
332     assert(Fns.size() > 0);
333
334     // I put this here to give us an upper bound on time taken by IPA. Is it
335     // really (realistically) needed? Keep in mind that we do have an n^2 algo.
336     if (std::distance(Args.begin(), Args.end()) > (int)MaxSupportedArgs)
337       return false;
338
339     // Exit early if we'll fail anyway
340     for (auto *Fn : Fns) {
341       if (isFunctionExternal(Fn) || Fn->isVarArg())
342         return false;
343       auto &MaybeInfo = AA.ensureCached(Fn);
344       if (!MaybeInfo.hasValue())
345         return false;
346     }
347
348     SmallVector<Value *, ExpectedMaxArgs> Arguments(Args.begin(), Args.end());
349     SmallVector<StratifiedInfo, ExpectedMaxArgs> Parameters;
350     for (auto *Fn : Fns) {
351       auto &Info = *AA.ensureCached(Fn);
352       auto &Sets = Info.Sets;
353       auto &RetVals = Info.ReturnedValues;
354
355       Parameters.clear();
356       for (auto &Param : Fn->args()) {
357         auto MaybeInfo = Sets.find(&Param);
358         // Did a new parameter somehow get added to the function/slip by?
359         if (!MaybeInfo.hasValue())
360           return false;
361         Parameters.push_back(*MaybeInfo);
362       }
363
364       // Adding an edge from argument -> return value for each parameter that
365       // may alias the return value
366       for (unsigned I = 0, E = Parameters.size(); I != E; ++I) {
367         auto &ParamInfo = Parameters[I];
368         auto &ArgVal = Arguments[I];
369         bool AddEdge = false;
370         StratifiedAttrs Externals;
371         for (unsigned X = 0, XE = RetVals.size(); X != XE; ++X) {
372           auto MaybeInfo = Sets.find(RetVals[X]);
373           if (!MaybeInfo.hasValue())
374             return false;
375
376           auto &RetInfo = *MaybeInfo;
377           auto RetAttrs = Sets.getLink(RetInfo.Index).Attrs;
378           auto ParamAttrs = Sets.getLink(ParamInfo.Index).Attrs;
379           auto MaybeRelation =
380               getIndexRelation(Sets, ParamInfo.Index, RetInfo.Index);
381           if (MaybeRelation.hasValue()) {
382             AddEdge = true;
383             Externals |= RetAttrs | ParamAttrs;
384           }
385         }
386         if (AddEdge)
387           Output.push_back(Edge(FuncValue, ArgVal, EdgeType::Assign,
388                                 StratifiedAttrs().flip()));
389       }
390
391       if (Parameters.size() != Arguments.size())
392         return false;
393
394       // Adding edges between arguments for arguments that may end up aliasing
395       // each other. This is necessary for functions such as
396       // void foo(int** a, int** b) { *a = *b; }
397       // (Technically, the proper sets for this would be those below
398       // Arguments[I] and Arguments[X], but our algorithm will produce
399       // extremely similar, and equally correct, results either way)
400       for (unsigned I = 0, E = Arguments.size(); I != E; ++I) {
401         auto &MainVal = Arguments[I];
402         auto &MainInfo = Parameters[I];
403         auto &MainAttrs = Sets.getLink(MainInfo.Index).Attrs;
404         for (unsigned X = I + 1; X != E; ++X) {
405           auto &SubInfo = Parameters[X];
406           auto &SubVal = Arguments[X];
407           auto &SubAttrs = Sets.getLink(SubInfo.Index).Attrs;
408           auto MaybeRelation =
409               getIndexRelation(Sets, MainInfo.Index, SubInfo.Index);
410
411           if (!MaybeRelation.hasValue())
412             continue;
413
414           auto NewAttrs = SubAttrs | MainAttrs;
415           Output.push_back(Edge(MainVal, SubVal, EdgeType::Assign, NewAttrs));
416         }
417       }
418     }
419     return true;
420   }
421
422   template <typename InstT> void visitCallLikeInst(InstT &Inst) {
423     SmallVector<Function *, 4> Targets;
424     if (getPossibleTargets(&Inst, Targets)) {
425       if (tryInterproceduralAnalysis(Targets, &Inst, Inst.arg_operands()))
426         return;
427       // Cleanup from interprocedural analysis
428       Output.clear();
429     }
430
431     for (Value *V : Inst.arg_operands())
432       Output.push_back(Edge(&Inst, V, EdgeType::Assign, AttrAll));
433   }
434
435   void visitCallInst(CallInst &Inst) { visitCallLikeInst(Inst); }
436
437   void visitInvokeInst(InvokeInst &Inst) { visitCallLikeInst(Inst); }
438
439   // Because vectors/aggregates are immutable and unaddressable,
440   // there's nothing we can do to coax a value out of them, other
441   // than calling Extract{Element,Value}. We can effectively treat
442   // them as pointers to arbitrary memory locations we can store in
443   // and load from.
444   void visitExtractElementInst(ExtractElementInst &Inst) {
445     auto *Ptr = Inst.getVectorOperand();
446     auto *Val = &Inst;
447     Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
448   }
449
450   void visitInsertElementInst(InsertElementInst &Inst) {
451     auto *Vec = Inst.getOperand(0);
452     auto *Val = Inst.getOperand(1);
453     Output.push_back(Edge(&Inst, Vec, EdgeType::Assign, AttrNone));
454     Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
455   }
456
457   void visitLandingPadInst(LandingPadInst &Inst) {
458     // Exceptions come from "nowhere", from our analysis' perspective.
459     // So we place the instruction its own group, noting that said group may
460     // alias externals
461     Output.push_back(Edge(&Inst, &Inst, EdgeType::Assign, AttrAll));
462   }
463
464   void visitInsertValueInst(InsertValueInst &Inst) {
465     auto *Agg = Inst.getOperand(0);
466     auto *Val = Inst.getOperand(1);
467     Output.push_back(Edge(&Inst, Agg, EdgeType::Assign, AttrNone));
468     Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
469   }
470
471   void visitExtractValueInst(ExtractValueInst &Inst) {
472     auto *Ptr = Inst.getAggregateOperand();
473     Output.push_back(Edge(&Inst, Ptr, EdgeType::Reference, AttrNone));
474   }
475
476   void visitShuffleVectorInst(ShuffleVectorInst &Inst) {
477     auto *From1 = Inst.getOperand(0);
478     auto *From2 = Inst.getOperand(1);
479     Output.push_back(Edge(&Inst, From1, EdgeType::Assign, AttrNone));
480     Output.push_back(Edge(&Inst, From2, EdgeType::Assign, AttrNone));
481   }
482
483   void visitConstantExpr(ConstantExpr *CE) {
484     switch (CE->getOpcode()) {
485     default:
486       llvm_unreachable("Unknown instruction type encountered!");
487 // Build the switch statement using the Instruction.def file.
488 #define HANDLE_INST(NUM, OPCODE, CLASS)                                        \
489   case Instruction::OPCODE:                                                    \
490     visit##OPCODE(*(CLASS *)CE);                                               \
491     break;
492 #include "llvm/IR/Instruction.def"
493     }
494   }
495 };
496
497 // For a given instruction, we need to know which Value* to get the
498 // users of in order to build our graph. In some cases (i.e. add),
499 // we simply need the Instruction*. In other cases (i.e. store),
500 // finding the users of the Instruction* is useless; we need to find
501 // the users of the first operand. This handles determining which
502 // value to follow for us.
503 //
504 // Note: we *need* to keep this in sync with GetEdgesVisitor. Add
505 // something to GetEdgesVisitor, add it here -- remove something from
506 // GetEdgesVisitor, remove it here.
507 class GetTargetValueVisitor
508     : public InstVisitor<GetTargetValueVisitor, Value *> {
509 public:
510   Value *visitInstruction(Instruction &Inst) { return &Inst; }
511
512   Value *visitStoreInst(StoreInst &Inst) { return Inst.getPointerOperand(); }
513
514   Value *visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
515     return Inst.getPointerOperand();
516   }
517
518   Value *visitAtomicRMWInst(AtomicRMWInst &Inst) {
519     return Inst.getPointerOperand();
520   }
521
522   Value *visitInsertElementInst(InsertElementInst &Inst) {
523     return Inst.getOperand(0);
524   }
525
526   Value *visitInsertValueInst(InsertValueInst &Inst) {
527     return Inst.getAggregateOperand();
528   }
529 };
530
531 // Set building requires a weighted bidirectional graph.
532 template <typename EdgeTypeT> class WeightedBidirectionalGraph {
533 public:
534   typedef std::size_t Node;
535
536 private:
537   const static Node StartNode = Node(0);
538
539   struct Edge {
540     EdgeTypeT Weight;
541     Node Other;
542
543     Edge(const EdgeTypeT &W, const Node &N) : Weight(W), Other(N) {}
544
545     bool operator==(const Edge &E) const {
546       return Weight == E.Weight && Other == E.Other;
547     }
548
549     bool operator!=(const Edge &E) const { return !operator==(E); }
550   };
551
552   struct NodeImpl {
553     std::vector<Edge> Edges;
554   };
555
556   std::vector<NodeImpl> NodeImpls;
557
558   bool inbounds(Node NodeIndex) const { return NodeIndex < NodeImpls.size(); }
559
560   const NodeImpl &getNode(Node N) const { return NodeImpls[N]; }
561   NodeImpl &getNode(Node N) { return NodeImpls[N]; }
562
563 public:
564   // ----- Various Edge iterators for the graph ----- //
565
566   // \brief Iterator for edges. Because this graph is bidirected, we don't
567   // allow modification of the edges using this iterator. Additionally, the
568   // iterator becomes invalid if you add edges to or from the node you're
569   // getting the edges of.
570   struct EdgeIterator : public std::iterator<std::forward_iterator_tag,
571                                              std::tuple<EdgeTypeT, Node *>> {
572     EdgeIterator(const typename std::vector<Edge>::const_iterator &Iter)
573         : Current(Iter) {}
574
575     EdgeIterator(NodeImpl &Impl) : Current(Impl.begin()) {}
576
577     EdgeIterator &operator++() {
578       ++Current;
579       return *this;
580     }
581
582     EdgeIterator operator++(int) {
583       EdgeIterator Copy(Current);
584       operator++();
585       return Copy;
586     }
587
588     std::tuple<EdgeTypeT, Node> &operator*() {
589       Store = std::make_tuple(Current->Weight, Current->Other);
590       return Store;
591     }
592
593     bool operator==(const EdgeIterator &Other) const {
594       return Current == Other.Current;
595     }
596
597     bool operator!=(const EdgeIterator &Other) const {
598       return !operator==(Other);
599     }
600
601   private:
602     typename std::vector<Edge>::const_iterator Current;
603     std::tuple<EdgeTypeT, Node> Store;
604   };
605
606   // Wrapper for EdgeIterator with begin()/end() calls.
607   struct EdgeIterable {
608     EdgeIterable(const std::vector<Edge> &Edges)
609         : BeginIter(Edges.begin()), EndIter(Edges.end()) {}
610
611     EdgeIterator begin() { return EdgeIterator(BeginIter); }
612
613     EdgeIterator end() { return EdgeIterator(EndIter); }
614
615   private:
616     typename std::vector<Edge>::const_iterator BeginIter;
617     typename std::vector<Edge>::const_iterator EndIter;
618   };
619
620   // ----- Actual graph-related things ----- //
621
622   WeightedBidirectionalGraph() {}
623
624   WeightedBidirectionalGraph(WeightedBidirectionalGraph<EdgeTypeT> &&Other)
625       : NodeImpls(std::move(Other.NodeImpls)) {}
626
627   WeightedBidirectionalGraph<EdgeTypeT> &
628   operator=(WeightedBidirectionalGraph<EdgeTypeT> &&Other) {
629     NodeImpls = std::move(Other.NodeImpls);
630     return *this;
631   }
632
633   Node addNode() {
634     auto Index = NodeImpls.size();
635     auto NewNode = Node(Index);
636     NodeImpls.push_back(NodeImpl());
637     return NewNode;
638   }
639
640   void addEdge(Node From, Node To, const EdgeTypeT &Weight,
641                const EdgeTypeT &ReverseWeight) {
642     assert(inbounds(From));
643     assert(inbounds(To));
644     auto &FromNode = getNode(From);
645     auto &ToNode = getNode(To);
646     FromNode.Edges.push_back(Edge(Weight, To));
647     ToNode.Edges.push_back(Edge(ReverseWeight, From));
648   }
649
650   EdgeIterable edgesFor(const Node &N) const {
651     const auto &Node = getNode(N);
652     return EdgeIterable(Node.Edges);
653   }
654
655   bool empty() const { return NodeImpls.empty(); }
656   std::size_t size() const { return NodeImpls.size(); }
657
658   // \brief Gets an arbitrary node in the graph as a starting point for
659   // traversal.
660   Node getEntryNode() {
661     assert(inbounds(StartNode));
662     return StartNode;
663   }
664 };
665
666 typedef WeightedBidirectionalGraph<std::pair<EdgeType, StratifiedAttrs>> GraphT;
667 typedef DenseMap<Value *, GraphT::Node> NodeMapT;
668 }
669
670 //===----------------------------------------------------------------------===//
671 // Function declarations that require types defined in the namespace above
672 //===----------------------------------------------------------------------===//
673
674 // Given an argument number, returns the appropriate Attr index to set.
675 static StratifiedAttr argNumberToAttrIndex(StratifiedAttr);
676
677 // Given a Value, potentially return which AttrIndex it maps to.
678 static Optional<StratifiedAttr> valueToAttrIndex(Value *Val);
679
680 // Gets the inverse of a given EdgeType.
681 static EdgeType flipWeight(EdgeType);
682
683 // Gets edges of the given Instruction*, writing them to the SmallVector*.
684 static void argsToEdges(CFLAliasAnalysis &, Instruction *,
685                         SmallVectorImpl<Edge> &);
686
687 // Gets edges of the given ConstantExpr*, writing them to the SmallVector*.
688 static void argsToEdges(CFLAliasAnalysis &, ConstantExpr *,
689                         SmallVectorImpl<Edge> &);
690
691 // Gets the "Level" that one should travel in StratifiedSets
692 // given an EdgeType.
693 static Level directionOfEdgeType(EdgeType);
694
695 // Builds the graph needed for constructing the StratifiedSets for the
696 // given function
697 static void buildGraphFrom(CFLAliasAnalysis &, Function *,
698                            SmallVectorImpl<Value *> &, NodeMapT &, GraphT &);
699
700 // Gets the edges of a ConstantExpr as if it was an Instruction. This
701 // function also acts on any nested ConstantExprs, adding the edges
702 // of those to the given SmallVector as well.
703 static void constexprToEdges(CFLAliasAnalysis &, ConstantExpr &,
704                              SmallVectorImpl<Edge> &);
705
706 // Given an Instruction, this will add it to the graph, along with any
707 // Instructions that are potentially only available from said Instruction
708 // For example, given the following line:
709 //   %0 = load i16* getelementptr ([1 x i16]* @a, 0, 0), align 2
710 // addInstructionToGraph would add both the `load` and `getelementptr`
711 // instructions to the graph appropriately.
712 static void addInstructionToGraph(CFLAliasAnalysis &, Instruction &,
713                                   SmallVectorImpl<Value *> &, NodeMapT &,
714                                   GraphT &);
715
716 // Notes whether it would be pointless to add the given Value to our sets.
717 static bool canSkipAddingToSets(Value *Val);
718
719 static Optional<Function *> parentFunctionOfValue(Value *Val) {
720   if (auto *Inst = dyn_cast<Instruction>(Val)) {
721     auto *Bb = Inst->getParent();
722     return Bb->getParent();
723   }
724
725   if (auto *Arg = dyn_cast<Argument>(Val))
726     return Arg->getParent();
727   return NoneType();
728 }
729
730 template <typename Inst>
731 static bool getPossibleTargets(Inst *Call,
732                                SmallVectorImpl<Function *> &Output) {
733   if (auto *Fn = Call->getCalledFunction()) {
734     Output.push_back(Fn);
735     return true;
736   }
737
738   // TODO: If the call is indirect, we might be able to enumerate all potential
739   // targets of the call and return them, rather than just failing.
740   return false;
741 }
742
743 static Optional<Value *> getTargetValue(Instruction *Inst) {
744   GetTargetValueVisitor V;
745   return V.visit(Inst);
746 }
747
748 static bool hasUsefulEdges(Instruction *Inst) {
749   bool IsNonInvokeTerminator =
750       isa<TerminatorInst>(Inst) && !isa<InvokeInst>(Inst);
751   return !isa<CmpInst>(Inst) && !isa<FenceInst>(Inst) && !IsNonInvokeTerminator;
752 }
753
754 static bool hasUsefulEdges(ConstantExpr *CE) {
755   // ConstantExpr doesn't have terminators, invokes, or fences, so only needs
756   // to check for compares.
757   return CE->getOpcode() != Instruction::ICmp &&
758          CE->getOpcode() != Instruction::FCmp;
759 }
760
761 static Optional<StratifiedAttr> valueToAttrIndex(Value *Val) {
762   if (isa<GlobalValue>(Val))
763     return AttrGlobalIndex;
764
765   if (auto *Arg = dyn_cast<Argument>(Val))
766     // Only pointer arguments should have the argument attribute,
767     // because things can't escape through scalars without us seeing a
768     // cast, and thus, interaction with them doesn't matter.
769     if (!Arg->hasNoAliasAttr() && Arg->getType()->isPointerTy())
770       return argNumberToAttrIndex(Arg->getArgNo());
771   return NoneType();
772 }
773
774 static StratifiedAttr argNumberToAttrIndex(unsigned ArgNum) {
775   if (ArgNum >= AttrMaxNumArgs)
776     return AttrAllIndex;
777   return ArgNum + AttrFirstArgIndex;
778 }
779
780 static EdgeType flipWeight(EdgeType Initial) {
781   switch (Initial) {
782   case EdgeType::Assign:
783     return EdgeType::Assign;
784   case EdgeType::Dereference:
785     return EdgeType::Reference;
786   case EdgeType::Reference:
787     return EdgeType::Dereference;
788   }
789   llvm_unreachable("Incomplete coverage of EdgeType enum");
790 }
791
792 static void argsToEdges(CFLAliasAnalysis &Analysis, Instruction *Inst,
793                         SmallVectorImpl<Edge> &Output) {
794   assert(hasUsefulEdges(Inst) &&
795          "Expected instructions to have 'useful' edges");
796   GetEdgesVisitor v(Analysis, Output);
797   v.visit(Inst);
798 }
799
800 static void argsToEdges(CFLAliasAnalysis &Analysis, ConstantExpr *CE,
801                         SmallVectorImpl<Edge> &Output) {
802   assert(hasUsefulEdges(CE) && "Expected constant expr to have 'useful' edges");
803   GetEdgesVisitor v(Analysis, Output);
804   v.visitConstantExpr(CE);
805 }
806
807 static Level directionOfEdgeType(EdgeType Weight) {
808   switch (Weight) {
809   case EdgeType::Reference:
810     return Level::Above;
811   case EdgeType::Dereference:
812     return Level::Below;
813   case EdgeType::Assign:
814     return Level::Same;
815   }
816   llvm_unreachable("Incomplete switch coverage");
817 }
818
819 static void constexprToEdges(CFLAliasAnalysis &Analysis,
820                              ConstantExpr &CExprToCollapse,
821                              SmallVectorImpl<Edge> &Results) {
822   SmallVector<ConstantExpr *, 4> Worklist;
823   Worklist.push_back(&CExprToCollapse);
824
825   SmallVector<Edge, 8> ConstexprEdges;
826   SmallPtrSet<ConstantExpr *, 4> Visited;
827   while (!Worklist.empty()) {
828     auto *CExpr = Worklist.pop_back_val();
829
830     if (!hasUsefulEdges(CExpr))
831       continue;
832
833     ConstexprEdges.clear();
834     argsToEdges(Analysis, CExpr, ConstexprEdges);
835     for (auto &Edge : ConstexprEdges) {
836       if (auto *Nested = dyn_cast<ConstantExpr>(Edge.From))
837         if (Visited.insert(Nested).second)
838           Worklist.push_back(Nested);
839
840       if (auto *Nested = dyn_cast<ConstantExpr>(Edge.To))
841         if (Visited.insert(Nested).second)
842           Worklist.push_back(Nested);
843     }
844
845     Results.append(ConstexprEdges.begin(), ConstexprEdges.end());
846   }
847 }
848
849 static void addInstructionToGraph(CFLAliasAnalysis &Analysis, Instruction &Inst,
850                                   SmallVectorImpl<Value *> &ReturnedValues,
851                                   NodeMapT &Map, GraphT &Graph) {
852   const auto findOrInsertNode = [&Map, &Graph](Value *Val) {
853     auto Pair = Map.insert(std::make_pair(Val, GraphT::Node()));
854     auto &Iter = Pair.first;
855     if (Pair.second) {
856       auto NewNode = Graph.addNode();
857       Iter->second = NewNode;
858     }
859     return Iter->second;
860   };
861
862   // We don't want the edges of most "return" instructions, but we *do* want
863   // to know what can be returned.
864   if (isa<ReturnInst>(&Inst))
865     ReturnedValues.push_back(&Inst);
866
867   if (!hasUsefulEdges(&Inst))
868     return;
869
870   SmallVector<Edge, 8> Edges;
871   argsToEdges(Analysis, &Inst, Edges);
872
873   // In the case of an unused alloca (or similar), edges may be empty. Note
874   // that it exists so we can potentially answer NoAlias.
875   if (Edges.empty()) {
876     auto MaybeVal = getTargetValue(&Inst);
877     assert(MaybeVal.hasValue());
878     auto *Target = *MaybeVal;
879     findOrInsertNode(Target);
880     return;
881   }
882
883   const auto addEdgeToGraph = [&Graph, &findOrInsertNode](const Edge &E) {
884     auto To = findOrInsertNode(E.To);
885     auto From = findOrInsertNode(E.From);
886     auto FlippedWeight = flipWeight(E.Weight);
887     auto Attrs = E.AdditionalAttrs;
888     Graph.addEdge(From, To, std::make_pair(E.Weight, Attrs),
889                   std::make_pair(FlippedWeight, Attrs));
890   };
891
892   SmallVector<ConstantExpr *, 4> ConstantExprs;
893   for (const Edge &E : Edges) {
894     addEdgeToGraph(E);
895     if (auto *Constexpr = dyn_cast<ConstantExpr>(E.To))
896       ConstantExprs.push_back(Constexpr);
897     if (auto *Constexpr = dyn_cast<ConstantExpr>(E.From))
898       ConstantExprs.push_back(Constexpr);
899   }
900
901   for (ConstantExpr *CE : ConstantExprs) {
902     Edges.clear();
903     constexprToEdges(Analysis, *CE, Edges);
904     std::for_each(Edges.begin(), Edges.end(), addEdgeToGraph);
905   }
906 }
907
908 // Aside: We may remove graph construction entirely, because it doesn't really
909 // buy us much that we don't already have. I'd like to add interprocedural
910 // analysis prior to this however, in case that somehow requires the graph
911 // produced by this for efficient execution
912 static void buildGraphFrom(CFLAliasAnalysis &Analysis, Function *Fn,
913                            SmallVectorImpl<Value *> &ReturnedValues,
914                            NodeMapT &Map, GraphT &Graph) {
915   for (auto &Bb : Fn->getBasicBlockList())
916     for (auto &Inst : Bb.getInstList())
917       addInstructionToGraph(Analysis, Inst, ReturnedValues, Map, Graph);
918 }
919
920 static bool canSkipAddingToSets(Value *Val) {
921   // Constants can share instances, which may falsely unify multiple
922   // sets, e.g. in
923   // store i32* null, i32** %ptr1
924   // store i32* null, i32** %ptr2
925   // clearly ptr1 and ptr2 should not be unified into the same set, so
926   // we should filter out the (potentially shared) instance to
927   // i32* null.
928   if (isa<Constant>(Val)) {
929     bool Container = isa<ConstantVector>(Val) || isa<ConstantArray>(Val) ||
930                      isa<ConstantStruct>(Val);
931     // TODO: Because all of these things are constant, we can determine whether
932     // the data is *actually* mutable at graph building time. This will probably
933     // come for free/cheap with offset awareness.
934     bool CanStoreMutableData =
935         isa<GlobalValue>(Val) || isa<ConstantExpr>(Val) || Container;
936     return !CanStoreMutableData;
937   }
938
939   return false;
940 }
941
942 // Builds the graph + StratifiedSets for a function.
943 CFLAliasAnalysis::FunctionInfo CFLAliasAnalysis::buildSetsFrom(Function *Fn) {
944   NodeMapT Map;
945   GraphT Graph;
946   SmallVector<Value *, 4> ReturnedValues;
947
948   buildGraphFrom(*this, Fn, ReturnedValues, Map, Graph);
949
950   DenseMap<GraphT::Node, Value *> NodeValueMap;
951   NodeValueMap.resize(Map.size());
952   for (const auto &Pair : Map)
953     NodeValueMap.insert(std::make_pair(Pair.second, Pair.first));
954
955   const auto findValueOrDie = [&NodeValueMap](GraphT::Node Node) {
956     auto ValIter = NodeValueMap.find(Node);
957     assert(ValIter != NodeValueMap.end());
958     return ValIter->second;
959   };
960
961   StratifiedSetsBuilder<Value *> Builder;
962
963   SmallVector<GraphT::Node, 16> Worklist;
964   for (auto &Pair : Map) {
965     Worklist.clear();
966
967     auto *Value = Pair.first;
968     Builder.add(Value);
969     auto InitialNode = Pair.second;
970     Worklist.push_back(InitialNode);
971     while (!Worklist.empty()) {
972       auto Node = Worklist.pop_back_val();
973       auto *CurValue = findValueOrDie(Node);
974       if (canSkipAddingToSets(CurValue))
975         continue;
976
977       for (const auto &EdgeTuple : Graph.edgesFor(Node)) {
978         auto Weight = std::get<0>(EdgeTuple);
979         auto Label = Weight.first;
980         auto &OtherNode = std::get<1>(EdgeTuple);
981         auto *OtherValue = findValueOrDie(OtherNode);
982
983         if (canSkipAddingToSets(OtherValue))
984           continue;
985
986         bool Added;
987         switch (directionOfEdgeType(Label)) {
988         case Level::Above:
989           Added = Builder.addAbove(CurValue, OtherValue);
990           break;
991         case Level::Below:
992           Added = Builder.addBelow(CurValue, OtherValue);
993           break;
994         case Level::Same:
995           Added = Builder.addWith(CurValue, OtherValue);
996           break;
997         }
998
999         auto Aliasing = Weight.second;
1000         if (auto MaybeCurIndex = valueToAttrIndex(CurValue))
1001           Aliasing.set(*MaybeCurIndex);
1002         if (auto MaybeOtherIndex = valueToAttrIndex(OtherValue))
1003           Aliasing.set(*MaybeOtherIndex);
1004         Builder.noteAttributes(CurValue, Aliasing);
1005         Builder.noteAttributes(OtherValue, Aliasing);
1006
1007         if (Added)
1008           Worklist.push_back(OtherNode);
1009       }
1010     }
1011   }
1012
1013   // There are times when we end up with parameters not in our graph (i.e. if
1014   // it's only used as the condition of a branch). Other bits of code depend on
1015   // things that were present during construction being present in the graph.
1016   // So, we add all present arguments here.
1017   for (auto &Arg : Fn->args()) {
1018     if (!Builder.add(&Arg))
1019       continue;
1020
1021     auto Attrs = valueToAttrIndex(&Arg);
1022     if (Attrs.hasValue())
1023       Builder.noteAttributes(&Arg, *Attrs);
1024   }
1025
1026   return FunctionInfo(Builder.build(), std::move(ReturnedValues));
1027 }
1028
1029 void CFLAliasAnalysis::scan(Function *Fn) {
1030   auto InsertPair = Cache.insert(std::make_pair(Fn, Optional<FunctionInfo>()));
1031   (void)InsertPair;
1032   assert(InsertPair.second &&
1033          "Trying to scan a function that has already been cached");
1034
1035   FunctionInfo Info(buildSetsFrom(Fn));
1036   Cache[Fn] = std::move(Info);
1037   Handles.push_front(FunctionHandle(Fn, this));
1038 }
1039
1040 void CFLAliasAnalysis::evict(Function *Fn) { Cache.erase(Fn); }
1041
1042 /// \brief Ensures that the given function is available in the cache.
1043 /// Returns the appropriate entry from the cache.
1044 const Optional<CFLAliasAnalysis::FunctionInfo> &
1045 CFLAliasAnalysis::ensureCached(Function *Fn) {
1046   auto Iter = Cache.find(Fn);
1047   if (Iter == Cache.end()) {
1048     scan(Fn);
1049     Iter = Cache.find(Fn);
1050     assert(Iter != Cache.end());
1051     assert(Iter->second.hasValue());
1052   }
1053   return Iter->second;
1054 }
1055
1056 AliasResult CFLAliasAnalysis::query(const MemoryLocation &LocA,
1057                                     const MemoryLocation &LocB) {
1058   auto *ValA = const_cast<Value *>(LocA.Ptr);
1059   auto *ValB = const_cast<Value *>(LocB.Ptr);
1060
1061   Function *Fn = nullptr;
1062   auto MaybeFnA = parentFunctionOfValue(ValA);
1063   auto MaybeFnB = parentFunctionOfValue(ValB);
1064   if (!MaybeFnA.hasValue() && !MaybeFnB.hasValue()) {
1065     // The only times this is known to happen are when globals + InlineAsm
1066     // are involved
1067     DEBUG(dbgs() << "CFLAA: could not extract parent function information.\n");
1068     return MayAlias;
1069   }
1070
1071   if (MaybeFnA.hasValue()) {
1072     Fn = *MaybeFnA;
1073     assert((!MaybeFnB.hasValue() || *MaybeFnB == *MaybeFnA) &&
1074            "Interprocedural queries not supported");
1075   } else {
1076     Fn = *MaybeFnB;
1077   }
1078
1079   assert(Fn != nullptr);
1080   auto &MaybeInfo = ensureCached(Fn);
1081   assert(MaybeInfo.hasValue());
1082
1083   auto &Sets = MaybeInfo->Sets;
1084   auto MaybeA = Sets.find(ValA);
1085   if (!MaybeA.hasValue())
1086     return MayAlias;
1087
1088   auto MaybeB = Sets.find(ValB);
1089   if (!MaybeB.hasValue())
1090     return MayAlias;
1091
1092   auto SetA = *MaybeA;
1093   auto SetB = *MaybeB;
1094   auto AttrsA = Sets.getLink(SetA.Index).Attrs;
1095   auto AttrsB = Sets.getLink(SetB.Index).Attrs;
1096
1097   // Stratified set attributes are used as markets to signify whether a member
1098   // of a StratifiedSet (or a member of a set above the current set) has
1099   // interacted with either arguments or globals. "Interacted with" meaning
1100   // its value may be different depending on the value of an argument or
1101   // global. The thought behind this is that, because arguments and globals
1102   // may alias each other, if AttrsA and AttrsB have touched args/globals,
1103   // we must conservatively say that they alias. However, if at least one of
1104   // the sets has no values that could legally be altered by changing the value
1105   // of an argument or global, then we don't have to be as conservative.
1106   if (AttrsA.any() && AttrsB.any())
1107     return MayAlias;
1108
1109   // We currently unify things even if the accesses to them may not be in
1110   // bounds, so we can't return partial alias here because we don't
1111   // know whether the pointer is really within the object or not.
1112   // IE Given an out of bounds GEP and an alloca'd pointer, we may
1113   // unify the two. We can't return partial alias for this case.
1114   // Since we do not currently track enough information to
1115   // differentiate
1116
1117   if (SetA.Index == SetB.Index)
1118     return MayAlias;
1119
1120   return NoAlias;
1121 }
1122
1123 bool CFLAliasAnalysis::doInitialization(Module &M) {
1124   InitializeAliasAnalysis(this, &M.getDataLayout());
1125   return true;
1126 }