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