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