[CFLAA] And even more MSVC fixes
[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, Assign, or
18 // Assign.
19 //
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.
23 //
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
28 // time.
29 //===----------------------------------------------------------------------===//
30
31 #include "StratifiedSets.h"
32 #include "llvm/Analysis/Passes.h"
33 #include "llvm/ADT/BitVector.h"
34 #include "llvm/ADT/DenseMap.h"
35 #include "llvm/ADT/Optional.h"
36 #include "llvm/ADT/None.h"
37 #include "llvm/Analysis/AliasAnalysis.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/Instructions.h"
41 #include "llvm/IR/InstVisitor.h"
42 #include "llvm/IR/ValueHandle.h"
43 #include "llvm/Pass.h"
44 #include "llvm/Support/Allocator.h"
45 #include "llvm/Support/Compiler.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include <algorithm>
48 #include <cassert>
49 #include <forward_list>
50 #include <tuple>
51
52 using namespace llvm;
53
54 // Try to go from a Value* to a Function*. Never returns nullptr.
55 static Optional<Function *> parentFunctionOfValue(Value *);
56
57 // Returns possible functions called by the Inst* into the given
58 // SmallVectorImpl. Returns true if targets found, false otherwise.
59 // This is templated because InvokeInst/CallInst give us the same
60 // set of functions that we care about, and I don't like repeating
61 // myself.
62 template <typename Inst>
63 static bool getPossibleTargets(Inst *, SmallVectorImpl<Function *> &);
64
65 // Some instructions need to have their users tracked. Instructions like
66 // `add` require you to get the users of the Instruction* itself, other
67 // instructions like `store` require you to get the users of the first
68 // operand. This function gets the "proper" value to track for each
69 // type of instruction we support.
70 static Optional<Value *> getTargetValue(Instruction *);
71
72 // There are certain instructions (i.e. FenceInst, etc.) that we ignore.
73 // This notes that we should ignore those.
74 static bool hasUsefulEdges(Instruction *);
75
76 const StratifiedIndex StratifiedLink::SetSentinel =
77   std::numeric_limits<StratifiedIndex>::max();
78
79 namespace {
80 // StratifiedInfo Attribute things.
81 typedef unsigned StratifiedAttr;
82 LLVM_CONSTEXPR unsigned MaxStratifiedAttrIndex = NumStratifiedAttrs;
83 LLVM_CONSTEXPR unsigned AttrAllIndex = 0;
84 LLVM_CONSTEXPR unsigned AttrGlobalIndex = 1;
85 LLVM_CONSTEXPR unsigned AttrFirstArgIndex = 2;
86 LLVM_CONSTEXPR unsigned AttrLastArgIndex = MaxStratifiedAttrIndex;
87 LLVM_CONSTEXPR unsigned AttrMaxNumArgs = AttrLastArgIndex - AttrFirstArgIndex;
88
89 LLVM_CONSTEXPR StratifiedAttr AttrNone = 0;
90 LLVM_CONSTEXPR StratifiedAttr AttrAll = ~AttrNone;
91
92 // \brief StratifiedSets call for knowledge of "direction", so this is how we
93 // represent that locally.
94 enum class Level { Same, Above, Below };
95
96 // \brief Edges can be one of four "weights" -- each weight must have an inverse
97 // weight (Assign has Assign; Reference has Dereference).
98 enum class EdgeType {
99   // The weight assigned when assigning from or to a value. For example, in:
100   // %b = getelementptr %a, 0
101   // ...The relationships are %b assign %a, and %a assign %b. This used to be
102   // two edges, but having a distinction bought us nothing.
103   Assign,
104
105   // The edge used when we have an edge going from some handle to a Value.
106   // Examples of this include:
107   // %b = load %a              (%b Dereference %a)
108   // %b = extractelement %a, 0 (%a Dereference %b)
109   Dereference,
110
111   // The edge used when our edge goes from a value to a handle that may have
112   // contained it at some point. Examples:
113   // %b = load %a              (%a Reference %b)
114   // %b = extractelement %a, 0 (%b Reference %a)
115   Reference
116 };
117
118 // \brief Encodes the notion of a "use"
119 struct Edge {
120   // \brief Which value the edge is coming from
121   Value *From;
122
123   // \brief Which value the edge is pointing to
124   Value *To;
125
126   // \brief Edge weight
127   EdgeType Weight;
128
129   // \brief Whether we aliased any external values along the way that may be
130   // invisible to the analysis (i.e. landingpad for exceptions, calls for
131   // interprocedural analysis, etc.)
132   StratifiedAttrs AdditionalAttrs;
133
134   Edge(Value *From, Value *To, EdgeType W, StratifiedAttrs A)
135       : From(From), To(To), Weight(W), AdditionalAttrs(A) {}
136 };
137
138 // \brief Information we have about a function and would like to keep around
139 struct FunctionInfo {
140   StratifiedSets<Value *> Sets;
141   // Lots of functions have < 4 returns. Adjust as necessary.
142   SmallVector<Value *, 4> ReturnedValues;
143 };
144
145 struct CFLAliasAnalysis;
146
147 struct FunctionHandle : public CallbackVH {
148   FunctionHandle(Function *Fn, CFLAliasAnalysis *CFLAA)
149       : CallbackVH(Fn), CFLAA(CFLAA) {
150     assert(Fn != nullptr);
151     assert(CFLAA != nullptr);
152   }
153
154   virtual ~FunctionHandle() {}
155
156   virtual void deleted() override { removeSelfFromCache(); }
157   virtual void allUsesReplacedWith(Value *) override { removeSelfFromCache(); }
158
159 private:
160   CFLAliasAnalysis *CFLAA;
161
162   void removeSelfFromCache();
163 };
164
165 struct CFLAliasAnalysis : public ImmutablePass, public AliasAnalysis {
166 private:
167   /// \brief Cached mapping of Functions to their StratifiedSets.
168   /// If a function's sets are currently being built, it is marked
169   /// in the cache as an Optional without a value. This way, if we
170   /// have any kind of recursion, it is discernable from a function
171   /// that simply has empty sets.
172   DenseMap<Function *, Optional<FunctionInfo>> Cache;
173   std::forward_list<FunctionHandle> Handles;
174
175 public:
176   static char ID;
177
178   CFLAliasAnalysis() : ImmutablePass(ID) {
179     initializeCFLAliasAnalysisPass(*PassRegistry::getPassRegistry());
180   }
181
182   virtual ~CFLAliasAnalysis() {}
183
184   void getAnalysisUsage(AnalysisUsage &AU) const {
185     AliasAnalysis::getAnalysisUsage(AU);
186   }
187
188   void *getAdjustedAnalysisPointer(const void *ID) override {
189     if (ID == &AliasAnalysis::ID)
190       return (AliasAnalysis *)this;
191     return this;
192   }
193
194   /// \brief Inserts the given Function into the cache.
195   void scan(Function *Fn);
196
197   void evict(Function *Fn) { Cache.erase(Fn); }
198
199   /// \brief Ensures that the given function is available in the cache.
200   /// Returns the appropriate entry from the cache.
201   const Optional<FunctionInfo> &ensureCached(Function *Fn) {
202     auto Iter = Cache.find(Fn);
203     if (Iter == Cache.end()) {
204       scan(Fn);
205       Iter = Cache.find(Fn);
206       assert(Iter != Cache.end());
207       assert(Iter->second.hasValue());
208     }
209     return Iter->second;
210   }
211
212   AliasResult query(const Location &LocA, const Location &LocB);
213
214   AliasResult alias(const Location &LocA, const Location &LocB) override {
215     if (LocA.Ptr == LocB.Ptr) {
216       if (LocA.Size == LocB.Size) {
217         return MustAlias;
218       } else {
219         return PartialAlias;
220       }
221     }
222
223     // Comparisons between global variables and other constants should be
224     // handled by BasicAA.
225     if (isa<Constant>(LocA.Ptr) && isa<Constant>(LocB.Ptr)) {
226       return MayAlias;
227     }
228
229     return query(LocA, LocB);
230   }
231
232   void initializePass() override { InitializeAliasAnalysis(this); }
233 };
234
235 void FunctionHandle::removeSelfFromCache() {
236   assert(CFLAA != nullptr);
237   auto *Val = getValPtr();
238   CFLAA->evict(cast<Function>(Val));
239   setValPtr(nullptr);
240 }
241
242 // \brief Gets the edges our graph should have, based on an Instruction*
243 class GetEdgesVisitor : public InstVisitor<GetEdgesVisitor, void> {
244   CFLAliasAnalysis &AA;
245   SmallVectorImpl<Edge> &Output;
246
247 public:
248   GetEdgesVisitor(CFLAliasAnalysis &AA, SmallVectorImpl<Edge> &Output)
249       : AA(AA), Output(Output) {}
250
251   void visitInstruction(Instruction &) {
252     llvm_unreachable("Unsupported instruction encountered");
253   }
254
255   void visitCastInst(CastInst &Inst) {
256     Output.push_back(Edge(&Inst, Inst.getOperand(0), EdgeType::Assign,
257                           AttrNone));
258   }
259
260   void visitBinaryOperator(BinaryOperator &Inst) {
261     auto *Op1 = Inst.getOperand(0);
262     auto *Op2 = Inst.getOperand(1);
263     Output.push_back(Edge(&Inst, Op1, EdgeType::Assign, AttrNone));
264     Output.push_back(Edge(&Inst, Op2, EdgeType::Assign, AttrNone));
265   }
266
267   void visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
268     auto *Ptr = Inst.getPointerOperand();
269     auto *Val = Inst.getNewValOperand();
270     Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
271   }
272
273   void visitAtomicRMWInst(AtomicRMWInst &Inst) {
274     auto *Ptr = Inst.getPointerOperand();
275     auto *Val = Inst.getValOperand();
276     Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
277   }
278
279   void visitPHINode(PHINode &Inst) {
280     for (unsigned I = 0, E = Inst.getNumIncomingValues(); I != E; ++I) {
281       Value *Val = Inst.getIncomingValue(I);
282       Output.push_back(Edge(&Inst, Val, EdgeType::Assign, AttrNone));
283     }
284   }
285
286   void visitGetElementPtrInst(GetElementPtrInst &Inst) {
287     auto *Op = Inst.getPointerOperand();
288     Output.push_back(Edge(&Inst, Op, EdgeType::Assign, AttrNone));
289     for (auto I = Inst.idx_begin(), E = Inst.idx_end(); I != E; ++I)
290       Output.push_back(Edge(&Inst, *I, EdgeType::Assign, AttrNone));
291   }
292
293   void visitSelectInst(SelectInst &Inst) {
294     auto *Condition = Inst.getCondition();
295     Output.push_back(Edge(&Inst, Condition, EdgeType::Assign, AttrNone));
296     auto *TrueVal = Inst.getTrueValue();
297     Output.push_back(Edge(&Inst, TrueVal, EdgeType::Assign, AttrNone));
298     auto *FalseVal = Inst.getFalseValue();
299     Output.push_back(Edge(&Inst, FalseVal, EdgeType::Assign, AttrNone));
300   }
301
302   void visitAllocaInst(AllocaInst &) {}
303
304   void visitLoadInst(LoadInst &Inst) {
305     auto *Ptr = Inst.getPointerOperand();
306     auto *Val = &Inst;
307     Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
308   }
309
310   void visitStoreInst(StoreInst &Inst) {
311     auto *Ptr = Inst.getPointerOperand();
312     auto *Val = Inst.getValueOperand();
313     Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
314   }
315
316   static bool isFunctionExternal(Function *Fn) {
317     return Fn->isDeclaration() || !Fn->hasLocalLinkage();
318   }
319
320   // Gets whether the sets at Index1 above, below, or equal to the sets at
321   // Index2. Returns None if they are not in the same set chain.
322   static Optional<Level> getIndexRelation(const StratifiedSets<Value *> &Sets,
323                                           StratifiedIndex Index1,
324                                           StratifiedIndex Index2) {
325     if (Index1 == Index2)
326       return Level::Same;
327
328     const auto *Current = &Sets.getLink(Index1);
329     while (Current->hasBelow()) {
330       if (Current->Below == Index2)
331         return Level::Below;
332       Current = &Sets.getLink(Current->Below);
333     }
334
335     Current = &Sets.getLink(Index1);
336     while (Current->hasAbove()) {
337       if (Current->Above == Index2)
338         return Level::Above;
339       Current = &Sets.getLink(Current->Above);
340     }
341
342     return NoneType();
343   }
344
345   bool
346   tryInterproceduralAnalysis(const SmallVectorImpl<Function *> &Fns,
347                              Value *FuncValue,
348                              const iterator_range<User::op_iterator> &Args) {
349     const unsigned ExpectedMaxArgs = 8;
350     const unsigned MaxSupportedArgs = 50;
351     assert(Fns.size() > 0);
352
353     // I put this here to give us an upper bound on time taken by IPA. Is it
354     // really (realistically) needed? Keep in mind that we do have an n^2 algo.
355     if (std::distance(Args.begin(), Args.end()) > (int) MaxSupportedArgs)
356       return false;
357
358     // Exit early if we'll fail anyway
359     for (auto *Fn : Fns) {
360       if (isFunctionExternal(Fn) || Fn->isVarArg())
361         return false;
362       auto &MaybeInfo = AA.ensureCached(Fn);
363       if (!MaybeInfo.hasValue())
364         return false;
365     }
366
367     SmallVector<Value *, ExpectedMaxArgs> Arguments(Args.begin(), Args.end());
368     SmallVector<StratifiedInfo, ExpectedMaxArgs> Parameters;
369     for (auto *Fn : Fns) {
370       auto &Info = *AA.ensureCached(Fn);
371       auto &Sets = Info.Sets;
372       auto &RetVals = Info.ReturnedValues;
373
374       Parameters.clear();
375       for (auto &Param : Fn->args()) {
376         auto MaybeInfo = Sets.find(&Param);
377         // Did a new parameter somehow get added to the function/slip by?
378         if (!MaybeInfo.hasValue())
379           return false;
380         Parameters.push_back(*MaybeInfo);
381       }
382
383       // Adding an edge from argument -> return value for each parameter that
384       // may alias the return value
385       for (unsigned I = 0, E = Parameters.size(); I != E; ++I) {
386         auto &ParamInfo = Parameters[I];
387         auto &ArgVal = Arguments[I];
388         bool AddEdge = false;
389         StratifiedAttrs Externals;
390         for (unsigned X = 0, XE = RetVals.size(); X != XE; ++X) {
391           auto MaybeInfo = Sets.find(RetVals[X]);
392           if (!MaybeInfo.hasValue())
393             return false;
394
395           auto &RetInfo = *MaybeInfo;
396           auto RetAttrs = Sets.getLink(RetInfo.Index).Attrs;
397           auto ParamAttrs = Sets.getLink(ParamInfo.Index).Attrs;
398           auto MaybeRelation =
399               getIndexRelation(Sets, ParamInfo.Index, RetInfo.Index);
400           if (MaybeRelation.hasValue()) {
401             AddEdge = true;
402             Externals |= RetAttrs | ParamAttrs;
403           }
404         }
405         if (AddEdge)
406           Output.push_back(Edge(FuncValue, ArgVal, EdgeType::Assign,
407                             StratifiedAttrs().flip()));
408       }
409
410       if (Parameters.size() != Arguments.size())
411         return false;
412
413       // Adding edges between arguments for arguments that may end up aliasing
414       // each other. This is necessary for functions such as
415       // void foo(int** a, int** b) { *a = *b; }
416       // (Technically, the proper sets for this would be those below
417       // Arguments[I] and Arguments[X], but our algorithm will produce
418       // extremely similar, and equally correct, results either way)
419       for (unsigned I = 0, E = Arguments.size(); I != E; ++I) {
420         auto &MainVal = Arguments[I];
421         auto &MainInfo = Parameters[I];
422         auto &MainAttrs = Sets.getLink(MainInfo.Index).Attrs;
423         for (unsigned X = I + 1; X != E; ++X) {
424           auto &SubInfo = Parameters[X];
425           auto &SubVal = Arguments[X];
426           auto &SubAttrs = Sets.getLink(SubInfo.Index).Attrs;
427           auto MaybeRelation =
428               getIndexRelation(Sets, MainInfo.Index, SubInfo.Index);
429
430           if (!MaybeRelation.hasValue())
431             continue;
432
433           auto NewAttrs = SubAttrs | MainAttrs;
434           Output.push_back(Edge(MainVal, SubVal, EdgeType::Assign, NewAttrs));
435         }
436       }
437     }
438     return true;
439   }
440
441   template <typename InstT> void visitCallLikeInst(InstT &Inst) {
442     SmallVector<Function *, 4> Targets;
443     if (getPossibleTargets(&Inst, Targets)) {
444       if (tryInterproceduralAnalysis(Targets, &Inst, Inst.arg_operands()))
445         return;
446       // Cleanup from interprocedural analysis
447       Output.clear();
448     }
449
450     for (Value *V : Inst.arg_operands())
451       Output.push_back(Edge(&Inst, V, EdgeType::Assign, AttrAll));
452   }
453
454   void visitCallInst(CallInst &Inst) { visitCallLikeInst(Inst); }
455
456   void visitInvokeInst(InvokeInst &Inst) { visitCallLikeInst(Inst); }
457
458   // Because vectors/aggregates are immutable and unaddressable,
459   // there's nothing we can do to coax a value out of them, other
460   // than calling Extract{Element,Value}. We can effectively treat
461   // them as pointers to arbitrary memory locations we can store in
462   // and load from.
463   void visitExtractElementInst(ExtractElementInst &Inst) {
464     auto *Ptr = Inst.getVectorOperand();
465     auto *Val = &Inst;
466     Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
467   }
468
469   void visitInsertElementInst(InsertElementInst &Inst) {
470     auto *Vec = Inst.getOperand(0);
471     auto *Val = Inst.getOperand(1);
472     Output.push_back(Edge(&Inst, Vec, EdgeType::Assign, AttrNone));
473     Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
474   }
475
476   void visitLandingPadInst(LandingPadInst &Inst) {
477     // Exceptions come from "nowhere", from our analysis' perspective.
478     // So we place the instruction its own group, noting that said group may
479     // alias externals
480     Output.push_back(Edge(&Inst, &Inst, EdgeType::Assign, AttrAll));
481   }
482
483   void visitInsertValueInst(InsertValueInst &Inst) {
484     auto *Agg = Inst.getOperand(0);
485     auto *Val = Inst.getOperand(1);
486     Output.push_back(Edge(&Inst, Agg, EdgeType::Assign, AttrNone));
487     Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
488   }
489
490   void visitExtractValueInst(ExtractValueInst &Inst) {
491     auto *Ptr = Inst.getAggregateOperand();
492     Output.push_back(Edge(&Inst, Ptr, EdgeType::Reference, AttrNone));
493   }
494
495   void visitShuffleVectorInst(ShuffleVectorInst &Inst) {
496     auto *From1 = Inst.getOperand(0);
497     auto *From2 = Inst.getOperand(1);
498     Output.push_back(Edge(&Inst, From1, EdgeType::Assign, AttrNone));
499     Output.push_back(Edge(&Inst, From2, EdgeType::Assign, AttrNone));
500   }
501 };
502
503 // For a given instruction, we need to know which Value* to get the
504 // users of in order to build our graph. In some cases (i.e. add),
505 // we simply need the Instruction*. In other cases (i.e. store),
506 // finding the users of the Instruction* is useless; we need to find
507 // the users of the first operand. This handles determining which
508 // value to follow for us.
509 //
510 // Note: we *need* to keep this in sync with GetEdgesVisitor. Add
511 // something to GetEdgesVisitor, add it here -- remove something from
512 // GetEdgesVisitor, remove it here.
513 class GetTargetValueVisitor
514     : public InstVisitor<GetTargetValueVisitor, Value *> {
515 public:
516   Value *visitInstruction(Instruction &Inst) { return &Inst; }
517
518   Value *visitStoreInst(StoreInst &Inst) { return Inst.getPointerOperand(); }
519
520   Value *visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
521     return Inst.getPointerOperand();
522   }
523
524   Value *visitAtomicRMWInst(AtomicRMWInst &Inst) {
525     return Inst.getPointerOperand();
526   }
527
528   Value *visitInsertElementInst(InsertElementInst &Inst) {
529     return Inst.getOperand(0);
530   }
531
532   Value *visitInsertValueInst(InsertValueInst &Inst) {
533     return Inst.getAggregateOperand();
534   }
535 };
536
537 // Set building requires a weighted bidirectional graph.
538 template <typename EdgeTypeT> class WeightedBidirectionalGraph {
539 public:
540   typedef std::size_t Node;
541
542 private:
543   const static Node StartNode = Node(0);
544
545   struct Edge {
546     EdgeTypeT Weight;
547     Node Other;
548
549     Edge(const EdgeTypeT &W, const Node &N)
550       : Weight(W), Other(N) {}
551
552     bool operator==(const Edge &E) const {
553       return Weight == E.Weight && Other == E.Other;
554     }
555
556     bool operator!=(const Edge &E) const { return !operator==(E); }
557   };
558
559   struct NodeImpl {
560     std::vector<Edge> Edges;
561   };
562
563   std::vector<NodeImpl> NodeImpls;
564
565   bool inbounds(Node NodeIndex) const { return NodeIndex < NodeImpls.size(); }
566
567   const NodeImpl &getNode(Node N) const { return NodeImpls[N]; }
568   NodeImpl &getNode(Node N) { return NodeImpls[N]; }
569
570 public:
571   // ----- Various Edge iterators for the graph ----- //
572
573   // \brief Iterator for edges. Because this graph is bidirected, we don't
574   // allow modificaiton of the edges using this iterator. Additionally, the
575   // iterator becomes invalid if you add edges to or from the node you're
576   // getting the edges of.
577   struct EdgeIterator : public std::iterator<std::forward_iterator_tag,
578                                              std::tuple<EdgeTypeT, Node *>> {
579     EdgeIterator(const typename std::vector<Edge>::const_iterator &Iter)
580         : Current(Iter) {}
581
582     EdgeIterator(NodeImpl &Impl) : Current(Impl.begin()) {}
583
584     EdgeIterator &operator++() {
585       ++Current;
586       return *this;
587     }
588
589     EdgeIterator operator++(int) {
590       EdgeIterator Copy(Current);
591       operator++();
592       return Copy;
593     }
594
595     std::tuple<EdgeTypeT, Node> &operator*() {
596       Store = std::make_tuple(Current->Weight, Current->Other);
597       return Store;
598     }
599
600     bool operator==(const EdgeIterator &Other) const {
601       return Current == Other.Current;
602     }
603
604     bool operator!=(const EdgeIterator &Other) const {
605       return !operator==(Other);
606     }
607
608   private:
609     typename std::vector<Edge>::const_iterator Current;
610     std::tuple<EdgeTypeT, Node> Store;
611   };
612
613   // Wrapper for EdgeIterator with begin()/end() calls.
614   struct EdgeIterable {
615     EdgeIterable(const std::vector<Edge> &Edges)
616         : BeginIter(Edges.begin()), EndIter(Edges.end()) {}
617
618     EdgeIterator begin() { return EdgeIterator(BeginIter); }
619
620     EdgeIterator end() { return EdgeIterator(EndIter); }
621
622   private:
623     typename std::vector<Edge>::const_iterator BeginIter;
624     typename std::vector<Edge>::const_iterator EndIter;
625   };
626
627   // ----- Actual graph-related things ----- //
628
629   WeightedBidirectionalGraph() {}
630
631   WeightedBidirectionalGraph(WeightedBidirectionalGraph<EdgeTypeT> &&Other)
632       : NodeImpls(std::move(Other.NodeImpls)) {}
633
634   WeightedBidirectionalGraph<EdgeTypeT> &
635   operator=(WeightedBidirectionalGraph<EdgeTypeT> &&Other) {
636     NodeImpls = std::move(Other.NodeImpls);
637     return *this;
638   }
639
640   Node addNode() {
641     auto Index = NodeImpls.size();
642     auto NewNode = Node(Index);
643     NodeImpls.push_back(NodeImpl());
644     return NewNode;
645   }
646
647   void addEdge(Node From, Node To, const EdgeTypeT &Weight,
648                const EdgeTypeT &ReverseWeight) {
649     assert(inbounds(From));
650     assert(inbounds(To));
651     auto &FromNode = getNode(From);
652     auto &ToNode = getNode(To);
653     FromNode.Edges.push_back(Edge(Weight, To));
654     ToNode.Edges.push_back(Edge(ReverseWeight, From));
655   }
656
657   EdgeIterable edgesFor(const Node &N) const {
658     const auto &Node = getNode(N);
659     return EdgeIterable(Node.Edges);
660   }
661
662   bool empty() const { return NodeImpls.empty(); }
663   std::size_t size() const { return NodeImpls.size(); }
664
665   // \brief Gets an arbitrary node in the graph as a starting point for
666   // traversal.
667   Node getEntryNode() {
668     assert(inbounds(StartNode));
669     return StartNode;
670   }
671 };
672
673 typedef WeightedBidirectionalGraph<std::pair<EdgeType, StratifiedAttrs>> GraphT;
674 typedef DenseMap<Value *, GraphT::Node> NodeMapT;
675 }
676
677 // -- Setting up/registering CFLAA pass -- //
678 char CFLAliasAnalysis::ID = 0;
679
680 INITIALIZE_AG_PASS(CFLAliasAnalysis, AliasAnalysis, "cfl-aa",
681                    "CFL-Based AA implementation", false, true, false)
682
683 ImmutablePass *llvm::createCFLAliasAnalysisPass() {
684   return new CFLAliasAnalysis();
685 }
686
687 //===----------------------------------------------------------------------===//
688 // Function declarations that require types defined in the namespace above
689 //===----------------------------------------------------------------------===//
690
691 // Given an argument number, returns the appropriate Attr index to set.
692 static StratifiedAttr argNumberToAttrIndex(StratifiedAttr);
693
694 // Given a Value, potentially return which AttrIndex it maps to.
695 static Optional<StratifiedAttr> valueToAttrIndex(Value *Val);
696
697 // Gets the inverse of a given EdgeType.
698 static EdgeType flipWeight(EdgeType);
699
700 // Gets edges of the given Instruction*, writing them to the SmallVector*.
701 static void argsToEdges(CFLAliasAnalysis &, Instruction *,
702                         SmallVectorImpl<Edge> &);
703
704 // Gets the "Level" that one should travel in StratifiedSets
705 // given an EdgeType.
706 static Level directionOfEdgeType(EdgeType);
707
708 // Builds the graph needed for constructing the StratifiedSets for the
709 // given function
710 static void buildGraphFrom(CFLAliasAnalysis &, Function *,
711                            SmallVectorImpl<Value *> &, NodeMapT &, GraphT &);
712
713 // Builds the graph + StratifiedSets for a function.
714 static FunctionInfo buildSetsFrom(CFLAliasAnalysis &, Function *);
715
716 static Optional<Function *> parentFunctionOfValue(Value *Val) {
717   if (auto *Inst = dyn_cast<Instruction>(Val)) {
718     auto *Bb = Inst->getParent();
719     return Bb->getParent();
720   }
721
722   if (auto *Arg = dyn_cast<Argument>(Val))
723     return Arg->getParent();
724   return NoneType();
725 }
726
727 template <typename Inst>
728 static bool getPossibleTargets(Inst *Call,
729                                SmallVectorImpl<Function *> &Output) {
730   if (auto *Fn = Call->getCalledFunction()) {
731     Output.push_back(Fn);
732     return true;
733   }
734
735   // TODO: If the call is indirect, we might be able to enumerate all potential
736   // targets of the call and return them, rather than just failing.
737   return false;
738 }
739
740 static Optional<Value *> getTargetValue(Instruction *Inst) {
741   GetTargetValueVisitor V;
742   return V.visit(Inst);
743 }
744
745 static bool hasUsefulEdges(Instruction *Inst) {
746   bool IsNonInvokeTerminator =
747       isa<TerminatorInst>(Inst) && !isa<InvokeInst>(Inst);
748   return !isa<CmpInst>(Inst) && !isa<FenceInst>(Inst) && !IsNonInvokeTerminator;
749 }
750
751 static Optional<StratifiedAttr> valueToAttrIndex(Value *Val) {
752   if (isa<GlobalValue>(Val))
753     return AttrGlobalIndex;
754
755   if (auto *Arg = dyn_cast<Argument>(Val))
756     if (!Arg->hasNoAliasAttr())
757       return argNumberToAttrIndex(Arg->getArgNo());
758   return NoneType();
759 }
760
761 static StratifiedAttr argNumberToAttrIndex(unsigned ArgNum) {
762   if (ArgNum > AttrMaxNumArgs)
763     return AttrAllIndex;
764   return ArgNum + AttrFirstArgIndex;
765 }
766
767 static EdgeType flipWeight(EdgeType Initial) {
768   switch (Initial) {
769   case EdgeType::Assign:
770     return EdgeType::Assign;
771   case EdgeType::Dereference:
772     return EdgeType::Reference;
773   case EdgeType::Reference:
774     return EdgeType::Dereference;
775   }
776   llvm_unreachable("Incomplete coverage of EdgeType enum");
777 }
778
779 static void argsToEdges(CFLAliasAnalysis &Analysis, Instruction *Inst,
780                         SmallVectorImpl<Edge> &Output) {
781   GetEdgesVisitor v(Analysis, Output);
782   v.visit(Inst);
783 }
784
785 static Level directionOfEdgeType(EdgeType Weight) {
786   switch (Weight) {
787   case EdgeType::Reference:
788     return Level::Above;
789   case EdgeType::Dereference:
790     return Level::Below;
791   case EdgeType::Assign:
792     return Level::Same;
793   }
794   llvm_unreachable("Incomplete switch coverage");
795 }
796
797 // Aside: We may remove graph construction entirely, because it doesn't really
798 // buy us much that we don't already have. I'd like to add interprocedural
799 // analysis prior to this however, in case that somehow requires the graph
800 // produced by this for efficient execution
801 static void buildGraphFrom(CFLAliasAnalysis &Analysis, Function *Fn,
802                            SmallVectorImpl<Value *> &ReturnedValues,
803                            NodeMapT &Map, GraphT &Graph) {
804   const auto findOrInsertNode = [&Map, &Graph](Value *Val) {
805     auto Pair = Map.insert(std::make_pair(Val, GraphT::Node()));
806     auto &Iter = Pair.first;
807     if (Pair.second) {
808       auto NewNode = Graph.addNode();
809       Iter->second = NewNode;
810     }
811     return Iter->second;
812   };
813
814   SmallVector<Edge, 8> Edges;
815   for (auto &Bb : Fn->getBasicBlockList()) {
816     for (auto &Inst : Bb.getInstList()) {
817       // We don't want the edges of most "return" instructions, but we *do* want
818       // to know what can be returned.
819       if (auto *Ret = dyn_cast<ReturnInst>(&Inst))
820         ReturnedValues.push_back(Ret);
821
822       if (!hasUsefulEdges(&Inst))
823         continue;
824
825       Edges.clear();
826       argsToEdges(Analysis, &Inst, Edges);
827
828       // In the case of an unused alloca (or similar), edges may be empty. Note
829       // that it exists so we can potentially answer NoAlias.
830       if (Edges.empty()) {
831         auto MaybeVal = getTargetValue(&Inst);
832         assert(MaybeVal.hasValue());
833         auto *Target = *MaybeVal;
834         findOrInsertNode(Target);
835         continue;
836       }
837
838       for (const Edge &E : Edges) {
839         auto To = findOrInsertNode(E.To);
840         auto From = findOrInsertNode(E.From);
841         auto FlippedWeight = flipWeight(E.Weight);
842         auto Attrs = E.AdditionalAttrs;
843         Graph.addEdge(From, To, std::make_pair(E.Weight, Attrs),
844                                 std::make_pair(FlippedWeight, Attrs));
845       }
846     }
847   }
848 }
849
850 static FunctionInfo buildSetsFrom(CFLAliasAnalysis &Analysis, Function *Fn) {
851   NodeMapT Map;
852   GraphT Graph;
853   SmallVector<Value *, 4> ReturnedValues;
854
855   buildGraphFrom(Analysis, Fn, ReturnedValues, Map, Graph);
856
857   DenseMap<GraphT::Node, Value *> NodeValueMap;
858   NodeValueMap.resize(Map.size());
859   for (const auto &Pair : Map)
860     NodeValueMap.insert(std::make_pair(Pair.second, Pair.first));
861
862   const auto findValueOrDie = [&NodeValueMap](GraphT::Node Node) {
863     auto ValIter = NodeValueMap.find(Node);
864     assert(ValIter != NodeValueMap.end());
865     return ValIter->second;
866   };
867
868   StratifiedSetsBuilder<Value *> Builder;
869
870   SmallVector<GraphT::Node, 16> Worklist;
871   for (auto &Pair : Map) {
872     Worklist.clear();
873
874     auto *Value = Pair.first;
875     Builder.add(Value);
876     auto InitialNode = Pair.second;
877     Worklist.push_back(InitialNode);
878     while (!Worklist.empty()) {
879       auto Node = Worklist.pop_back_val();
880       auto *CurValue = findValueOrDie(Node);
881       if (isa<Constant>(CurValue) && !isa<GlobalValue>(CurValue))
882         continue;
883
884       for (const auto &EdgeTuple : Graph.edgesFor(Node)) {
885         auto Weight = std::get<0>(EdgeTuple);
886         auto Label = Weight.first;
887         auto &OtherNode = std::get<1>(EdgeTuple);
888         auto *OtherValue = findValueOrDie(OtherNode);
889
890         if (isa<Constant>(OtherValue) && !isa<GlobalValue>(OtherValue))
891           continue;
892
893         bool Added;
894         switch (directionOfEdgeType(Label)) {
895         case Level::Above:
896           Added = Builder.addAbove(CurValue, OtherValue);
897           break;
898         case Level::Below:
899           Added = Builder.addBelow(CurValue, OtherValue);
900           break;
901         case Level::Same:
902           Added = Builder.addWith(CurValue, OtherValue);
903           break;
904         }
905
906         if (Added) {
907           auto Aliasing = Weight.second;
908           if (auto MaybeCurIndex = valueToAttrIndex(CurValue))
909             Aliasing.set(*MaybeCurIndex);
910           if (auto MaybeOtherIndex = valueToAttrIndex(OtherValue))
911             Aliasing.set(*MaybeOtherIndex);
912           Builder.noteAttributes(CurValue, Aliasing);
913           Builder.noteAttributes(OtherValue, Aliasing);
914           Worklist.push_back(OtherNode);
915         }
916       }
917     }
918   }
919
920   // There are times when we end up with parameters not in our graph (i.e. if
921   // it's only used as the condition of a branch). Other bits of code depend on
922   // things that were present during construction being present in the graph.
923   // So, we add all present arguments here.
924   for (auto &Arg : Fn->args()) {
925     Builder.add(&Arg);
926   }
927
928   return {Builder.build(), std::move(ReturnedValues)};
929 }
930
931 void CFLAliasAnalysis::scan(Function *Fn) {
932   auto InsertPair = Cache.insert(std::make_pair(Fn, Optional<FunctionInfo>()));
933   (void)InsertPair;
934   assert(InsertPair.second &&
935          "Trying to scan a function that has already been cached");
936
937   FunctionInfo Info(buildSetsFrom(*this, Fn));
938   Cache[Fn] = std::move(Info);
939   Handles.push_front(FunctionHandle(Fn, this));
940 }
941
942 AliasAnalysis::AliasResult
943 CFLAliasAnalysis::query(const AliasAnalysis::Location &LocA,
944                         const AliasAnalysis::Location &LocB) {
945   auto *ValA = const_cast<Value *>(LocA.Ptr);
946   auto *ValB = const_cast<Value *>(LocB.Ptr);
947
948   Function *Fn = nullptr;
949   auto MaybeFnA = parentFunctionOfValue(ValA);
950   auto MaybeFnB = parentFunctionOfValue(ValB);
951   if (!MaybeFnA.hasValue() && !MaybeFnB.hasValue()) {
952     llvm_unreachable("Don't know how to extract the parent function "
953                      "from values A or B");
954   }
955
956   if (MaybeFnA.hasValue()) {
957     Fn = *MaybeFnA;
958     assert((!MaybeFnB.hasValue() || *MaybeFnB == *MaybeFnA) &&
959            "Interprocedural queries not supported");
960   } else {
961     Fn = *MaybeFnB;
962   }
963
964   assert(Fn != nullptr);
965   auto &MaybeInfo = ensureCached(Fn);
966   assert(MaybeInfo.hasValue());
967
968   auto &Sets = MaybeInfo->Sets;
969   auto MaybeA = Sets.find(ValA);
970   if (!MaybeA.hasValue())
971     return AliasAnalysis::MayAlias;
972
973   auto MaybeB = Sets.find(ValB);
974   if (!MaybeB.hasValue())
975     return AliasAnalysis::MayAlias;
976
977   auto SetA = *MaybeA;
978   auto SetB = *MaybeB;
979
980   if (SetA.Index == SetB.Index)
981     return AliasAnalysis::PartialAlias;
982
983   auto AttrsA = Sets.getLink(SetA.Index).Attrs;
984   auto AttrsB = Sets.getLink(SetB.Index).Attrs;
985   auto CombinedAttrs = AttrsA | AttrsB;
986   if (CombinedAttrs.any())
987     return AliasAnalysis::PartialAlias;
988
989   return AliasAnalysis::NoAlias;
990 }