blob: e87adf142851aed8d73ffd270723d6d5b924d6f9 [file] [log] [blame]
Hal Finkel7529c552014-09-02 21:43:13 +00001//===- 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
Chad Rosier38c6ad22015-06-19 17:32:57 +000017// location. The "actions" can be one of Dereference, Reference, or Assign.
Hal Finkel7529c552014-09-02 21:43:13 +000018//
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 "StratifiedSets.h"
Hal Finkel7529c552014-09-02 21:43:13 +000031#include "llvm/ADT/BitVector.h"
32#include "llvm/ADT/DenseMap.h"
Hal Finkel7529c552014-09-02 21:43:13 +000033#include "llvm/ADT/None.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000034#include "llvm/ADT/Optional.h"
Hal Finkel7529c552014-09-02 21:43:13 +000035#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000036#include "llvm/Analysis/Passes.h"
Hal Finkel7529c552014-09-02 21:43:13 +000037#include "llvm/IR/Constants.h"
38#include "llvm/IR/Function.h"
Hal Finkel7529c552014-09-02 21:43:13 +000039#include "llvm/IR/InstVisitor.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000040#include "llvm/IR/Instructions.h"
Hal Finkel7529c552014-09-02 21:43:13 +000041#include "llvm/IR/ValueHandle.h"
42#include "llvm/Pass.h"
43#include "llvm/Support/Allocator.h"
Hal Finkel7d7087c2014-09-02 22:13:00 +000044#include "llvm/Support/Compiler.h"
George Burgess IV33305e72015-02-12 03:07:07 +000045#include "llvm/Support/Debug.h"
Hal Finkel7529c552014-09-02 21:43:13 +000046#include "llvm/Support/ErrorHandling.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000047#include "llvm/Support/raw_ostream.h"
Hal Finkel7529c552014-09-02 21:43:13 +000048#include <algorithm>
49#include <cassert>
50#include <forward_list>
Benjamin Kramer799003b2015-03-23 19:32:43 +000051#include <memory>
Hal Finkel7529c552014-09-02 21:43:13 +000052#include <tuple>
53
54using namespace llvm;
55
George Burgess IV33305e72015-02-12 03:07:07 +000056#define DEBUG_TYPE "cfl-aa"
57
Hal Finkel7529c552014-09-02 21:43:13 +000058// Try to go from a Value* to a Function*. Never returns nullptr.
59static Optional<Function *> parentFunctionOfValue(Value *);
60
61// Returns possible functions called by the Inst* into the given
62// SmallVectorImpl. Returns true if targets found, false otherwise.
63// This is templated because InvokeInst/CallInst give us the same
64// set of functions that we care about, and I don't like repeating
65// myself.
66template <typename Inst>
67static bool getPossibleTargets(Inst *, SmallVectorImpl<Function *> &);
68
69// Some instructions need to have their users tracked. Instructions like
70// `add` require you to get the users of the Instruction* itself, other
71// instructions like `store` require you to get the users of the first
72// operand. This function gets the "proper" value to track for each
73// type of instruction we support.
74static Optional<Value *> getTargetValue(Instruction *);
75
76// There are certain instructions (i.e. FenceInst, etc.) that we ignore.
77// This notes that we should ignore those.
78static bool hasUsefulEdges(Instruction *);
79
Hal Finkel1ae325f2014-09-02 23:50:01 +000080const StratifiedIndex StratifiedLink::SetSentinel =
George Burgess IV11d509d2015-03-15 00:52:21 +000081 std::numeric_limits<StratifiedIndex>::max();
Hal Finkel1ae325f2014-09-02 23:50:01 +000082
Hal Finkel7529c552014-09-02 21:43:13 +000083namespace {
84// StratifiedInfo Attribute things.
85typedef unsigned StratifiedAttr;
Hal Finkel7d7087c2014-09-02 22:13:00 +000086LLVM_CONSTEXPR unsigned MaxStratifiedAttrIndex = NumStratifiedAttrs;
87LLVM_CONSTEXPR unsigned AttrAllIndex = 0;
88LLVM_CONSTEXPR unsigned AttrGlobalIndex = 1;
George Burgess IVb54a8d622015-03-10 02:40:06 +000089LLVM_CONSTEXPR unsigned AttrUnknownIndex = 2;
90LLVM_CONSTEXPR unsigned AttrFirstArgIndex = 3;
Hal Finkel7d7087c2014-09-02 22:13:00 +000091LLVM_CONSTEXPR unsigned AttrLastArgIndex = MaxStratifiedAttrIndex;
92LLVM_CONSTEXPR unsigned AttrMaxNumArgs = AttrLastArgIndex - AttrFirstArgIndex;
Hal Finkel7529c552014-09-02 21:43:13 +000093
Hal Finkel7d7087c2014-09-02 22:13:00 +000094LLVM_CONSTEXPR StratifiedAttr AttrNone = 0;
George Burgess IVb54a8d622015-03-10 02:40:06 +000095LLVM_CONSTEXPR StratifiedAttr AttrUnknown = 1 << AttrUnknownIndex;
Hal Finkel7d7087c2014-09-02 22:13:00 +000096LLVM_CONSTEXPR StratifiedAttr AttrAll = ~AttrNone;
Hal Finkel7529c552014-09-02 21:43:13 +000097
98// \brief StratifiedSets call for knowledge of "direction", so this is how we
99// represent that locally.
100enum class Level { Same, Above, Below };
101
102// \brief Edges can be one of four "weights" -- each weight must have an inverse
103// weight (Assign has Assign; Reference has Dereference).
104enum class EdgeType {
105 // The weight assigned when assigning from or to a value. For example, in:
106 // %b = getelementptr %a, 0
107 // ...The relationships are %b assign %a, and %a assign %b. This used to be
108 // two edges, but having a distinction bought us nothing.
109 Assign,
110
111 // The edge used when we have an edge going from some handle to a Value.
112 // Examples of this include:
113 // %b = load %a (%b Dereference %a)
114 // %b = extractelement %a, 0 (%a Dereference %b)
115 Dereference,
116
117 // The edge used when our edge goes from a value to a handle that may have
118 // contained it at some point. Examples:
119 // %b = load %a (%a Reference %b)
120 // %b = extractelement %a, 0 (%b Reference %a)
121 Reference
122};
123
124// \brief Encodes the notion of a "use"
125struct Edge {
126 // \brief Which value the edge is coming from
127 Value *From;
128
129 // \brief Which value the edge is pointing to
130 Value *To;
131
132 // \brief Edge weight
133 EdgeType Weight;
134
135 // \brief Whether we aliased any external values along the way that may be
136 // invisible to the analysis (i.e. landingpad for exceptions, calls for
137 // interprocedural analysis, etc.)
138 StratifiedAttrs AdditionalAttrs;
139
140 Edge(Value *From, Value *To, EdgeType W, StratifiedAttrs A)
141 : From(From), To(To), Weight(W), AdditionalAttrs(A) {}
142};
143
144// \brief Information we have about a function and would like to keep around
145struct FunctionInfo {
146 StratifiedSets<Value *> Sets;
147 // Lots of functions have < 4 returns. Adjust as necessary.
148 SmallVector<Value *, 4> ReturnedValues;
Hal Finkel85f26922014-09-03 00:06:47 +0000149
George Burgess IV11d509d2015-03-15 00:52:21 +0000150 FunctionInfo(StratifiedSets<Value *> &&S, SmallVector<Value *, 4> &&RV)
151 : Sets(std::move(S)), ReturnedValues(std::move(RV)) {}
Hal Finkel7529c552014-09-02 21:43:13 +0000152};
153
154struct CFLAliasAnalysis;
155
David Blaikie774b5842015-08-03 22:30:24 +0000156struct FunctionHandle final : public CallbackVH {
Hal Finkel7529c552014-09-02 21:43:13 +0000157 FunctionHandle(Function *Fn, CFLAliasAnalysis *CFLAA)
158 : CallbackVH(Fn), CFLAA(CFLAA) {
159 assert(Fn != nullptr);
160 assert(CFLAA != nullptr);
161 }
162
David Blaikie711cd9c2014-11-14 19:06:36 +0000163 void deleted() override { removeSelfFromCache(); }
164 void allUsesReplacedWith(Value *) override { removeSelfFromCache(); }
Hal Finkel7529c552014-09-02 21:43:13 +0000165
166private:
167 CFLAliasAnalysis *CFLAA;
168
169 void removeSelfFromCache();
170};
171
172struct CFLAliasAnalysis : public ImmutablePass, public AliasAnalysis {
173private:
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
182public:
183 static char ID;
184
185 CFLAliasAnalysis() : ImmutablePass(ID) {
186 initializeCFLAliasAnalysisPass(*PassRegistry::getPassRegistry());
187 }
188
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000189 ~CFLAliasAnalysis() override {}
Hal Finkel7529c552014-09-02 21:43:13 +0000190
Argyrios Kyrtzidis0b9f5502014-10-01 21:00:44 +0000191 void getAnalysisUsage(AnalysisUsage &AU) const override {
Hal Finkel7529c552014-09-02 21:43:13 +0000192 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
Chandler Carruthac80dc72015-06-17 07:18:54 +0000219 AliasResult query(const MemoryLocation &LocA, const MemoryLocation &LocB);
Hal Finkel7529c552014-09-02 21:43:13 +0000220
Chandler Carruthac80dc72015-06-17 07:18:54 +0000221 AliasResult alias(const MemoryLocation &LocA,
222 const MemoryLocation &LocB) override {
Hal Finkel7529c552014-09-02 21:43:13 +0000223 if (LocA.Ptr == LocB.Ptr) {
224 if (LocA.Size == LocB.Size) {
225 return MustAlias;
226 } else {
227 return PartialAlias;
228 }
229 }
230
231 // Comparisons between global variables and other constants should be
232 // handled by BasicAA.
George Burgess IVab03af22015-03-10 02:58:15 +0000233 // TODO: ConstantExpr handling -- CFLAA may report NoAlias when comparing
234 // a GlobalValue and ConstantExpr, but every query needs to have at least
235 // one Value tied to a Function, and neither GlobalValues nor ConstantExprs
236 // are.
Hal Finkel7529c552014-09-02 21:43:13 +0000237 if (isa<Constant>(LocA.Ptr) && isa<Constant>(LocB.Ptr)) {
Daniel Berlin8f10e382015-01-26 17:30:39 +0000238 return AliasAnalysis::alias(LocA, LocB);
Hal Finkel7529c552014-09-02 21:43:13 +0000239 }
George Burgess IV33305e72015-02-12 03:07:07 +0000240
Daniel Berlin8f10e382015-01-26 17:30:39 +0000241 AliasResult QueryResult = query(LocA, LocB);
242 if (QueryResult == MayAlias)
243 return AliasAnalysis::alias(LocA, LocB);
Hal Finkel7529c552014-09-02 21:43:13 +0000244
Daniel Berlin8f10e382015-01-26 17:30:39 +0000245 return QueryResult;
Hal Finkel7529c552014-09-02 21:43:13 +0000246 }
247
Mehdi Amini46a43552015-03-04 18:43:29 +0000248 bool doInitialization(Module &M) override;
Hal Finkel7529c552014-09-02 21:43:13 +0000249};
250
251void FunctionHandle::removeSelfFromCache() {
252 assert(CFLAA != nullptr);
253 auto *Val = getValPtr();
254 CFLAA->evict(cast<Function>(Val));
255 setValPtr(nullptr);
256}
257
258// \brief Gets the edges our graph should have, based on an Instruction*
259class GetEdgesVisitor : public InstVisitor<GetEdgesVisitor, void> {
260 CFLAliasAnalysis &AA;
261 SmallVectorImpl<Edge> &Output;
262
263public:
264 GetEdgesVisitor(CFLAliasAnalysis &AA, SmallVectorImpl<Edge> &Output)
265 : AA(AA), Output(Output) {}
266
267 void visitInstruction(Instruction &) {
268 llvm_unreachable("Unsupported instruction encountered");
269 }
270
George Burgess IVb54a8d622015-03-10 02:40:06 +0000271 void visitPtrToIntInst(PtrToIntInst &Inst) {
272 auto *Ptr = Inst.getOperand(0);
273 Output.push_back(Edge(Ptr, Ptr, EdgeType::Assign, AttrUnknown));
274 }
275
276 void visitIntToPtrInst(IntToPtrInst &Inst) {
277 auto *Ptr = &Inst;
278 Output.push_back(Edge(Ptr, Ptr, EdgeType::Assign, AttrUnknown));
279 }
280
Hal Finkel7529c552014-09-02 21:43:13 +0000281 void visitCastInst(CastInst &Inst) {
George Burgess IV11d509d2015-03-15 00:52:21 +0000282 Output.push_back(
283 Edge(&Inst, Inst.getOperand(0), EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000284 }
285
286 void visitBinaryOperator(BinaryOperator &Inst) {
287 auto *Op1 = Inst.getOperand(0);
288 auto *Op2 = Inst.getOperand(1);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000289 Output.push_back(Edge(&Inst, Op1, EdgeType::Assign, AttrNone));
290 Output.push_back(Edge(&Inst, Op2, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000291 }
292
293 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
294 auto *Ptr = Inst.getPointerOperand();
295 auto *Val = Inst.getNewValOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000296 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000297 }
298
299 void visitAtomicRMWInst(AtomicRMWInst &Inst) {
300 auto *Ptr = Inst.getPointerOperand();
301 auto *Val = Inst.getValOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000302 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000303 }
304
305 void visitPHINode(PHINode &Inst) {
Pete Cooper833f34d2015-05-12 20:05:31 +0000306 for (Value *Val : Inst.incoming_values()) {
Hal Finkel8d1590d2014-09-02 22:52:30 +0000307 Output.push_back(Edge(&Inst, Val, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000308 }
309 }
310
311 void visitGetElementPtrInst(GetElementPtrInst &Inst) {
312 auto *Op = Inst.getPointerOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000313 Output.push_back(Edge(&Inst, Op, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000314 for (auto I = Inst.idx_begin(), E = Inst.idx_end(); I != E; ++I)
Hal Finkel8d1590d2014-09-02 22:52:30 +0000315 Output.push_back(Edge(&Inst, *I, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000316 }
317
318 void visitSelectInst(SelectInst &Inst) {
Daniel Berlin16f7a522015-01-26 17:31:17 +0000319 // Condition is not processed here (The actual statement producing
320 // the condition result is processed elsewhere). For select, the
321 // condition is evaluated, but not loaded, stored, or assigned
322 // simply as a result of being the condition of a select.
323
Hal Finkel7529c552014-09-02 21:43:13 +0000324 auto *TrueVal = Inst.getTrueValue();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000325 Output.push_back(Edge(&Inst, TrueVal, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000326 auto *FalseVal = Inst.getFalseValue();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000327 Output.push_back(Edge(&Inst, FalseVal, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000328 }
329
330 void visitAllocaInst(AllocaInst &) {}
331
332 void visitLoadInst(LoadInst &Inst) {
333 auto *Ptr = Inst.getPointerOperand();
334 auto *Val = &Inst;
Hal Finkel8d1590d2014-09-02 22:52:30 +0000335 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000336 }
337
338 void visitStoreInst(StoreInst &Inst) {
339 auto *Ptr = Inst.getPointerOperand();
340 auto *Val = Inst.getValueOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000341 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000342 }
343
Hal Finkeldb5f86a2014-10-14 20:51:26 +0000344 void visitVAArgInst(VAArgInst &Inst) {
345 // We can't fully model va_arg here. For *Ptr = Inst.getOperand(0), it does
346 // two things:
347 // 1. Loads a value from *((T*)*Ptr).
348 // 2. Increments (stores to) *Ptr by some target-specific amount.
349 // For now, we'll handle this like a landingpad instruction (by placing the
350 // result in its own group, and having that group alias externals).
351 auto *Val = &Inst;
352 Output.push_back(Edge(Val, Val, EdgeType::Assign, AttrAll));
353 }
354
Hal Finkel7529c552014-09-02 21:43:13 +0000355 static bool isFunctionExternal(Function *Fn) {
356 return Fn->isDeclaration() || !Fn->hasLocalLinkage();
357 }
358
359 // Gets whether the sets at Index1 above, below, or equal to the sets at
360 // Index2. Returns None if they are not in the same set chain.
361 static Optional<Level> getIndexRelation(const StratifiedSets<Value *> &Sets,
362 StratifiedIndex Index1,
363 StratifiedIndex Index2) {
364 if (Index1 == Index2)
365 return Level::Same;
366
367 const auto *Current = &Sets.getLink(Index1);
368 while (Current->hasBelow()) {
369 if (Current->Below == Index2)
370 return Level::Below;
371 Current = &Sets.getLink(Current->Below);
372 }
373
374 Current = &Sets.getLink(Index1);
375 while (Current->hasAbove()) {
376 if (Current->Above == Index2)
377 return Level::Above;
378 Current = &Sets.getLink(Current->Above);
379 }
380
381 return NoneType();
382 }
383
384 bool
385 tryInterproceduralAnalysis(const SmallVectorImpl<Function *> &Fns,
386 Value *FuncValue,
387 const iterator_range<User::op_iterator> &Args) {
Hal Finkelca616ac2014-09-02 23:29:48 +0000388 const unsigned ExpectedMaxArgs = 8;
389 const unsigned MaxSupportedArgs = 50;
Hal Finkel7529c552014-09-02 21:43:13 +0000390 assert(Fns.size() > 0);
391
392 // I put this here to give us an upper bound on time taken by IPA. Is it
393 // really (realistically) needed? Keep in mind that we do have an n^2 algo.
George Burgess IVab03af22015-03-10 02:58:15 +0000394 if (std::distance(Args.begin(), Args.end()) > (int)MaxSupportedArgs)
Hal Finkel7529c552014-09-02 21:43:13 +0000395 return false;
396
397 // Exit early if we'll fail anyway
398 for (auto *Fn : Fns) {
399 if (isFunctionExternal(Fn) || Fn->isVarArg())
400 return false;
401 auto &MaybeInfo = AA.ensureCached(Fn);
402 if (!MaybeInfo.hasValue())
403 return false;
404 }
405
406 SmallVector<Value *, ExpectedMaxArgs> Arguments(Args.begin(), Args.end());
407 SmallVector<StratifiedInfo, ExpectedMaxArgs> Parameters;
408 for (auto *Fn : Fns) {
409 auto &Info = *AA.ensureCached(Fn);
410 auto &Sets = Info.Sets;
411 auto &RetVals = Info.ReturnedValues;
412
413 Parameters.clear();
414 for (auto &Param : Fn->args()) {
415 auto MaybeInfo = Sets.find(&Param);
416 // Did a new parameter somehow get added to the function/slip by?
417 if (!MaybeInfo.hasValue())
418 return false;
419 Parameters.push_back(*MaybeInfo);
420 }
421
422 // Adding an edge from argument -> return value for each parameter that
423 // may alias the return value
424 for (unsigned I = 0, E = Parameters.size(); I != E; ++I) {
425 auto &ParamInfo = Parameters[I];
426 auto &ArgVal = Arguments[I];
427 bool AddEdge = false;
428 StratifiedAttrs Externals;
429 for (unsigned X = 0, XE = RetVals.size(); X != XE; ++X) {
430 auto MaybeInfo = Sets.find(RetVals[X]);
431 if (!MaybeInfo.hasValue())
432 return false;
433
434 auto &RetInfo = *MaybeInfo;
435 auto RetAttrs = Sets.getLink(RetInfo.Index).Attrs;
436 auto ParamAttrs = Sets.getLink(ParamInfo.Index).Attrs;
437 auto MaybeRelation =
438 getIndexRelation(Sets, ParamInfo.Index, RetInfo.Index);
439 if (MaybeRelation.hasValue()) {
440 AddEdge = true;
441 Externals |= RetAttrs | ParamAttrs;
442 }
443 }
444 if (AddEdge)
Hal Finkelca616ac2014-09-02 23:29:48 +0000445 Output.push_back(Edge(FuncValue, ArgVal, EdgeType::Assign,
George Burgess IV11d509d2015-03-15 00:52:21 +0000446 StratifiedAttrs().flip()));
Hal Finkel7529c552014-09-02 21:43:13 +0000447 }
448
449 if (Parameters.size() != Arguments.size())
450 return false;
451
452 // Adding edges between arguments for arguments that may end up aliasing
453 // each other. This is necessary for functions such as
454 // void foo(int** a, int** b) { *a = *b; }
455 // (Technically, the proper sets for this would be those below
456 // Arguments[I] and Arguments[X], but our algorithm will produce
457 // extremely similar, and equally correct, results either way)
458 for (unsigned I = 0, E = Arguments.size(); I != E; ++I) {
459 auto &MainVal = Arguments[I];
460 auto &MainInfo = Parameters[I];
461 auto &MainAttrs = Sets.getLink(MainInfo.Index).Attrs;
462 for (unsigned X = I + 1; X != E; ++X) {
463 auto &SubInfo = Parameters[X];
464 auto &SubVal = Arguments[X];
465 auto &SubAttrs = Sets.getLink(SubInfo.Index).Attrs;
466 auto MaybeRelation =
467 getIndexRelation(Sets, MainInfo.Index, SubInfo.Index);
468
469 if (!MaybeRelation.hasValue())
470 continue;
471
472 auto NewAttrs = SubAttrs | MainAttrs;
Hal Finkel8d1590d2014-09-02 22:52:30 +0000473 Output.push_back(Edge(MainVal, SubVal, EdgeType::Assign, NewAttrs));
Hal Finkel7529c552014-09-02 21:43:13 +0000474 }
475 }
476 }
477 return true;
478 }
479
480 template <typename InstT> void visitCallLikeInst(InstT &Inst) {
481 SmallVector<Function *, 4> Targets;
482 if (getPossibleTargets(&Inst, Targets)) {
483 if (tryInterproceduralAnalysis(Targets, &Inst, Inst.arg_operands()))
484 return;
485 // Cleanup from interprocedural analysis
486 Output.clear();
487 }
488
489 for (Value *V : Inst.arg_operands())
Hal Finkel8d1590d2014-09-02 22:52:30 +0000490 Output.push_back(Edge(&Inst, V, EdgeType::Assign, AttrAll));
Hal Finkel7529c552014-09-02 21:43:13 +0000491 }
492
493 void visitCallInst(CallInst &Inst) { visitCallLikeInst(Inst); }
494
495 void visitInvokeInst(InvokeInst &Inst) { visitCallLikeInst(Inst); }
496
497 // Because vectors/aggregates are immutable and unaddressable,
498 // there's nothing we can do to coax a value out of them, other
499 // than calling Extract{Element,Value}. We can effectively treat
500 // them as pointers to arbitrary memory locations we can store in
501 // and load from.
502 void visitExtractElementInst(ExtractElementInst &Inst) {
503 auto *Ptr = Inst.getVectorOperand();
504 auto *Val = &Inst;
Hal Finkel8d1590d2014-09-02 22:52:30 +0000505 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000506 }
507
508 void visitInsertElementInst(InsertElementInst &Inst) {
509 auto *Vec = Inst.getOperand(0);
510 auto *Val = Inst.getOperand(1);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000511 Output.push_back(Edge(&Inst, Vec, EdgeType::Assign, AttrNone));
512 Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000513 }
514
515 void visitLandingPadInst(LandingPadInst &Inst) {
516 // Exceptions come from "nowhere", from our analysis' perspective.
517 // So we place the instruction its own group, noting that said group may
518 // alias externals
Hal Finkel8d1590d2014-09-02 22:52:30 +0000519 Output.push_back(Edge(&Inst, &Inst, EdgeType::Assign, AttrAll));
Hal Finkel7529c552014-09-02 21:43:13 +0000520 }
521
522 void visitInsertValueInst(InsertValueInst &Inst) {
523 auto *Agg = Inst.getOperand(0);
524 auto *Val = Inst.getOperand(1);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000525 Output.push_back(Edge(&Inst, Agg, EdgeType::Assign, AttrNone));
526 Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000527 }
528
529 void visitExtractValueInst(ExtractValueInst &Inst) {
530 auto *Ptr = Inst.getAggregateOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000531 Output.push_back(Edge(&Inst, Ptr, EdgeType::Reference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000532 }
533
534 void visitShuffleVectorInst(ShuffleVectorInst &Inst) {
535 auto *From1 = Inst.getOperand(0);
536 auto *From2 = Inst.getOperand(1);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000537 Output.push_back(Edge(&Inst, From1, EdgeType::Assign, AttrNone));
538 Output.push_back(Edge(&Inst, From2, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000539 }
Pete Cooper36642532015-06-12 16:13:54 +0000540
541 void visitConstantExpr(ConstantExpr *CE) {
542 switch (CE->getOpcode()) {
543 default:
544 llvm_unreachable("Unknown instruction type encountered!");
545// Build the switch statement using the Instruction.def file.
546#define HANDLE_INST(NUM, OPCODE, CLASS) \
547 case Instruction::OPCODE: \
548 visit##OPCODE(*(CLASS *)CE); \
549 break;
550#include "llvm/IR/Instruction.def"
551 }
552 }
Hal Finkel7529c552014-09-02 21:43:13 +0000553};
554
555// For a given instruction, we need to know which Value* to get the
556// users of in order to build our graph. In some cases (i.e. add),
557// we simply need the Instruction*. In other cases (i.e. store),
558// finding the users of the Instruction* is useless; we need to find
559// the users of the first operand. This handles determining which
560// value to follow for us.
561//
562// Note: we *need* to keep this in sync with GetEdgesVisitor. Add
563// something to GetEdgesVisitor, add it here -- remove something from
564// GetEdgesVisitor, remove it here.
565class GetTargetValueVisitor
566 : public InstVisitor<GetTargetValueVisitor, Value *> {
567public:
568 Value *visitInstruction(Instruction &Inst) { return &Inst; }
569
570 Value *visitStoreInst(StoreInst &Inst) { return Inst.getPointerOperand(); }
571
572 Value *visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
573 return Inst.getPointerOperand();
574 }
575
576 Value *visitAtomicRMWInst(AtomicRMWInst &Inst) {
577 return Inst.getPointerOperand();
578 }
579
580 Value *visitInsertElementInst(InsertElementInst &Inst) {
581 return Inst.getOperand(0);
582 }
583
584 Value *visitInsertValueInst(InsertValueInst &Inst) {
585 return Inst.getAggregateOperand();
586 }
587};
588
589// Set building requires a weighted bidirectional graph.
590template <typename EdgeTypeT> class WeightedBidirectionalGraph {
591public:
592 typedef std::size_t Node;
593
594private:
Hal Finkelca616ac2014-09-02 23:29:48 +0000595 const static Node StartNode = Node(0);
Hal Finkel7529c552014-09-02 21:43:13 +0000596
597 struct Edge {
598 EdgeTypeT Weight;
599 Node Other;
600
George Burgess IV11d509d2015-03-15 00:52:21 +0000601 Edge(const EdgeTypeT &W, const Node &N) : Weight(W), Other(N) {}
Hal Finkelca616ac2014-09-02 23:29:48 +0000602
Hal Finkel7529c552014-09-02 21:43:13 +0000603 bool operator==(const Edge &E) const {
604 return Weight == E.Weight && Other == E.Other;
605 }
606
607 bool operator!=(const Edge &E) const { return !operator==(E); }
608 };
609
610 struct NodeImpl {
611 std::vector<Edge> Edges;
612 };
613
614 std::vector<NodeImpl> NodeImpls;
615
616 bool inbounds(Node NodeIndex) const { return NodeIndex < NodeImpls.size(); }
617
618 const NodeImpl &getNode(Node N) const { return NodeImpls[N]; }
619 NodeImpl &getNode(Node N) { return NodeImpls[N]; }
620
621public:
622 // ----- Various Edge iterators for the graph ----- //
623
624 // \brief Iterator for edges. Because this graph is bidirected, we don't
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000625 // allow modification of the edges using this iterator. Additionally, the
Hal Finkel7529c552014-09-02 21:43:13 +0000626 // iterator becomes invalid if you add edges to or from the node you're
627 // getting the edges of.
628 struct EdgeIterator : public std::iterator<std::forward_iterator_tag,
629 std::tuple<EdgeTypeT, Node *>> {
630 EdgeIterator(const typename std::vector<Edge>::const_iterator &Iter)
631 : Current(Iter) {}
632
633 EdgeIterator(NodeImpl &Impl) : Current(Impl.begin()) {}
634
635 EdgeIterator &operator++() {
636 ++Current;
637 return *this;
638 }
639
640 EdgeIterator operator++(int) {
641 EdgeIterator Copy(Current);
642 operator++();
643 return Copy;
644 }
645
646 std::tuple<EdgeTypeT, Node> &operator*() {
647 Store = std::make_tuple(Current->Weight, Current->Other);
648 return Store;
649 }
650
651 bool operator==(const EdgeIterator &Other) const {
652 return Current == Other.Current;
653 }
654
655 bool operator!=(const EdgeIterator &Other) const {
656 return !operator==(Other);
657 }
658
659 private:
660 typename std::vector<Edge>::const_iterator Current;
661 std::tuple<EdgeTypeT, Node> Store;
662 };
663
664 // Wrapper for EdgeIterator with begin()/end() calls.
665 struct EdgeIterable {
666 EdgeIterable(const std::vector<Edge> &Edges)
667 : BeginIter(Edges.begin()), EndIter(Edges.end()) {}
668
669 EdgeIterator begin() { return EdgeIterator(BeginIter); }
670
671 EdgeIterator end() { return EdgeIterator(EndIter); }
672
673 private:
674 typename std::vector<Edge>::const_iterator BeginIter;
675 typename std::vector<Edge>::const_iterator EndIter;
676 };
677
678 // ----- Actual graph-related things ----- //
679
Hal Finkelca616ac2014-09-02 23:29:48 +0000680 WeightedBidirectionalGraph() {}
Hal Finkel7529c552014-09-02 21:43:13 +0000681
682 WeightedBidirectionalGraph(WeightedBidirectionalGraph<EdgeTypeT> &&Other)
683 : NodeImpls(std::move(Other.NodeImpls)) {}
684
685 WeightedBidirectionalGraph<EdgeTypeT> &
686 operator=(WeightedBidirectionalGraph<EdgeTypeT> &&Other) {
687 NodeImpls = std::move(Other.NodeImpls);
688 return *this;
689 }
690
691 Node addNode() {
692 auto Index = NodeImpls.size();
693 auto NewNode = Node(Index);
694 NodeImpls.push_back(NodeImpl());
695 return NewNode;
696 }
697
698 void addEdge(Node From, Node To, const EdgeTypeT &Weight,
699 const EdgeTypeT &ReverseWeight) {
700 assert(inbounds(From));
701 assert(inbounds(To));
702 auto &FromNode = getNode(From);
703 auto &ToNode = getNode(To);
Hal Finkelca616ac2014-09-02 23:29:48 +0000704 FromNode.Edges.push_back(Edge(Weight, To));
705 ToNode.Edges.push_back(Edge(ReverseWeight, From));
Hal Finkel7529c552014-09-02 21:43:13 +0000706 }
707
708 EdgeIterable edgesFor(const Node &N) const {
709 const auto &Node = getNode(N);
710 return EdgeIterable(Node.Edges);
711 }
712
713 bool empty() const { return NodeImpls.empty(); }
714 std::size_t size() const { return NodeImpls.size(); }
715
716 // \brief Gets an arbitrary node in the graph as a starting point for
717 // traversal.
718 Node getEntryNode() {
719 assert(inbounds(StartNode));
720 return StartNode;
721 }
722};
723
724typedef WeightedBidirectionalGraph<std::pair<EdgeType, StratifiedAttrs>> GraphT;
725typedef DenseMap<Value *, GraphT::Node> NodeMapT;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000726}
Hal Finkel7529c552014-09-02 21:43:13 +0000727
728// -- Setting up/registering CFLAA pass -- //
729char CFLAliasAnalysis::ID = 0;
730
731INITIALIZE_AG_PASS(CFLAliasAnalysis, AliasAnalysis, "cfl-aa",
732 "CFL-Based AA implementation", false, true, false)
733
734ImmutablePass *llvm::createCFLAliasAnalysisPass() {
735 return new CFLAliasAnalysis();
736}
737
738//===----------------------------------------------------------------------===//
739// Function declarations that require types defined in the namespace above
740//===----------------------------------------------------------------------===//
741
742// Given an argument number, returns the appropriate Attr index to set.
743static StratifiedAttr argNumberToAttrIndex(StratifiedAttr);
744
745// Given a Value, potentially return which AttrIndex it maps to.
746static Optional<StratifiedAttr> valueToAttrIndex(Value *Val);
747
748// Gets the inverse of a given EdgeType.
749static EdgeType flipWeight(EdgeType);
750
751// Gets edges of the given Instruction*, writing them to the SmallVector*.
752static void argsToEdges(CFLAliasAnalysis &, Instruction *,
753 SmallVectorImpl<Edge> &);
754
Pete Cooper36642532015-06-12 16:13:54 +0000755// Gets edges of the given ConstantExpr*, writing them to the SmallVector*.
756static void argsToEdges(CFLAliasAnalysis &, ConstantExpr *,
757 SmallVectorImpl<Edge> &);
758
Hal Finkel7529c552014-09-02 21:43:13 +0000759// Gets the "Level" that one should travel in StratifiedSets
760// given an EdgeType.
761static Level directionOfEdgeType(EdgeType);
762
763// Builds the graph needed for constructing the StratifiedSets for the
764// given function
765static void buildGraphFrom(CFLAliasAnalysis &, Function *,
766 SmallVectorImpl<Value *> &, NodeMapT &, GraphT &);
767
George Burgess IVab03af22015-03-10 02:58:15 +0000768// Gets the edges of a ConstantExpr as if it was an Instruction. This
769// function also acts on any nested ConstantExprs, adding the edges
770// of those to the given SmallVector as well.
771static void constexprToEdges(CFLAliasAnalysis &, ConstantExpr &,
772 SmallVectorImpl<Edge> &);
773
774// Given an Instruction, this will add it to the graph, along with any
775// Instructions that are potentially only available from said Instruction
776// For example, given the following line:
777// %0 = load i16* getelementptr ([1 x i16]* @a, 0, 0), align 2
778// addInstructionToGraph would add both the `load` and `getelementptr`
779// instructions to the graph appropriately.
780static void addInstructionToGraph(CFLAliasAnalysis &, Instruction &,
781 SmallVectorImpl<Value *> &, NodeMapT &,
782 GraphT &);
783
784// Notes whether it would be pointless to add the given Value to our sets.
785static bool canSkipAddingToSets(Value *Val);
786
Hal Finkel7529c552014-09-02 21:43:13 +0000787// Builds the graph + StratifiedSets for a function.
788static FunctionInfo buildSetsFrom(CFLAliasAnalysis &, Function *);
789
790static Optional<Function *> parentFunctionOfValue(Value *Val) {
791 if (auto *Inst = dyn_cast<Instruction>(Val)) {
792 auto *Bb = Inst->getParent();
793 return Bb->getParent();
794 }
795
796 if (auto *Arg = dyn_cast<Argument>(Val))
797 return Arg->getParent();
798 return NoneType();
799}
800
801template <typename Inst>
802static bool getPossibleTargets(Inst *Call,
803 SmallVectorImpl<Function *> &Output) {
804 if (auto *Fn = Call->getCalledFunction()) {
805 Output.push_back(Fn);
806 return true;
807 }
808
809 // TODO: If the call is indirect, we might be able to enumerate all potential
810 // targets of the call and return them, rather than just failing.
811 return false;
812}
813
814static Optional<Value *> getTargetValue(Instruction *Inst) {
815 GetTargetValueVisitor V;
816 return V.visit(Inst);
817}
818
819static bool hasUsefulEdges(Instruction *Inst) {
820 bool IsNonInvokeTerminator =
821 isa<TerminatorInst>(Inst) && !isa<InvokeInst>(Inst);
822 return !isa<CmpInst>(Inst) && !isa<FenceInst>(Inst) && !IsNonInvokeTerminator;
823}
824
Pete Cooper36642532015-06-12 16:13:54 +0000825static bool hasUsefulEdges(ConstantExpr *CE) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000826 // ConstantExpr doesn't have terminators, invokes, or fences, so only needs
Pete Cooper36642532015-06-12 16:13:54 +0000827 // to check for compares.
828 return CE->getOpcode() != Instruction::ICmp &&
829 CE->getOpcode() != Instruction::FCmp;
830}
831
Hal Finkel7529c552014-09-02 21:43:13 +0000832static Optional<StratifiedAttr> valueToAttrIndex(Value *Val) {
833 if (isa<GlobalValue>(Val))
834 return AttrGlobalIndex;
835
836 if (auto *Arg = dyn_cast<Argument>(Val))
Daniel Berlin16f7a522015-01-26 17:31:17 +0000837 // Only pointer arguments should have the argument attribute,
838 // because things can't escape through scalars without us seeing a
839 // cast, and thus, interaction with them doesn't matter.
840 if (!Arg->hasNoAliasAttr() && Arg->getType()->isPointerTy())
Hal Finkel7529c552014-09-02 21:43:13 +0000841 return argNumberToAttrIndex(Arg->getArgNo());
842 return NoneType();
843}
844
845static StratifiedAttr argNumberToAttrIndex(unsigned ArgNum) {
George Burgess IV3c898c22015-01-21 16:37:21 +0000846 if (ArgNum >= AttrMaxNumArgs)
Hal Finkel7529c552014-09-02 21:43:13 +0000847 return AttrAllIndex;
848 return ArgNum + AttrFirstArgIndex;
849}
850
851static EdgeType flipWeight(EdgeType Initial) {
852 switch (Initial) {
853 case EdgeType::Assign:
854 return EdgeType::Assign;
855 case EdgeType::Dereference:
856 return EdgeType::Reference;
857 case EdgeType::Reference:
858 return EdgeType::Dereference;
859 }
860 llvm_unreachable("Incomplete coverage of EdgeType enum");
861}
862
863static void argsToEdges(CFLAliasAnalysis &Analysis, Instruction *Inst,
864 SmallVectorImpl<Edge> &Output) {
George Burgess IVab03af22015-03-10 02:58:15 +0000865 assert(hasUsefulEdges(Inst) &&
866 "Expected instructions to have 'useful' edges");
Hal Finkel7529c552014-09-02 21:43:13 +0000867 GetEdgesVisitor v(Analysis, Output);
868 v.visit(Inst);
869}
870
Pete Cooper36642532015-06-12 16:13:54 +0000871static void argsToEdges(CFLAliasAnalysis &Analysis, ConstantExpr *CE,
872 SmallVectorImpl<Edge> &Output) {
873 assert(hasUsefulEdges(CE) && "Expected constant expr to have 'useful' edges");
874 GetEdgesVisitor v(Analysis, Output);
875 v.visitConstantExpr(CE);
876}
877
Hal Finkel7529c552014-09-02 21:43:13 +0000878static Level directionOfEdgeType(EdgeType Weight) {
879 switch (Weight) {
880 case EdgeType::Reference:
881 return Level::Above;
882 case EdgeType::Dereference:
883 return Level::Below;
884 case EdgeType::Assign:
885 return Level::Same;
886 }
887 llvm_unreachable("Incomplete switch coverage");
888}
889
George Burgess IVab03af22015-03-10 02:58:15 +0000890static void constexprToEdges(CFLAliasAnalysis &Analysis,
891 ConstantExpr &CExprToCollapse,
892 SmallVectorImpl<Edge> &Results) {
893 SmallVector<ConstantExpr *, 4> Worklist;
894 Worklist.push_back(&CExprToCollapse);
895
896 SmallVector<Edge, 8> ConstexprEdges;
Pete Cooper36642532015-06-12 16:13:54 +0000897 SmallPtrSet<ConstantExpr *, 4> Visited;
George Burgess IVab03af22015-03-10 02:58:15 +0000898 while (!Worklist.empty()) {
899 auto *CExpr = Worklist.pop_back_val();
George Burgess IVab03af22015-03-10 02:58:15 +0000900
Pete Cooper36642532015-06-12 16:13:54 +0000901 if (!hasUsefulEdges(CExpr))
George Burgess IVab03af22015-03-10 02:58:15 +0000902 continue;
903
904 ConstexprEdges.clear();
Pete Cooper36642532015-06-12 16:13:54 +0000905 argsToEdges(Analysis, CExpr, ConstexprEdges);
George Burgess IVab03af22015-03-10 02:58:15 +0000906 for (auto &Edge : ConstexprEdges) {
Pete Cooper36642532015-06-12 16:13:54 +0000907 if (auto *Nested = dyn_cast<ConstantExpr>(Edge.From))
908 if (Visited.insert(Nested).second)
909 Worklist.push_back(Nested);
George Burgess IVab03af22015-03-10 02:58:15 +0000910
Pete Cooper36642532015-06-12 16:13:54 +0000911 if (auto *Nested = dyn_cast<ConstantExpr>(Edge.To))
912 if (Visited.insert(Nested).second)
913 Worklist.push_back(Nested);
George Burgess IVab03af22015-03-10 02:58:15 +0000914 }
915
916 Results.append(ConstexprEdges.begin(), ConstexprEdges.end());
917 }
918}
919
920static void addInstructionToGraph(CFLAliasAnalysis &Analysis, Instruction &Inst,
921 SmallVectorImpl<Value *> &ReturnedValues,
922 NodeMapT &Map, GraphT &Graph) {
Hal Finkel7529c552014-09-02 21:43:13 +0000923 const auto findOrInsertNode = [&Map, &Graph](Value *Val) {
924 auto Pair = Map.insert(std::make_pair(Val, GraphT::Node()));
925 auto &Iter = Pair.first;
926 if (Pair.second) {
927 auto NewNode = Graph.addNode();
928 Iter->second = NewNode;
929 }
930 return Iter->second;
931 };
932
George Burgess IVab03af22015-03-10 02:58:15 +0000933 // We don't want the edges of most "return" instructions, but we *do* want
934 // to know what can be returned.
935 if (isa<ReturnInst>(&Inst))
936 ReturnedValues.push_back(&Inst);
937
938 if (!hasUsefulEdges(&Inst))
939 return;
940
Hal Finkel7529c552014-09-02 21:43:13 +0000941 SmallVector<Edge, 8> Edges;
George Burgess IVab03af22015-03-10 02:58:15 +0000942 argsToEdges(Analysis, &Inst, Edges);
Hal Finkel7529c552014-09-02 21:43:13 +0000943
George Burgess IVab03af22015-03-10 02:58:15 +0000944 // In the case of an unused alloca (or similar), edges may be empty. Note
945 // that it exists so we can potentially answer NoAlias.
946 if (Edges.empty()) {
947 auto MaybeVal = getTargetValue(&Inst);
948 assert(MaybeVal.hasValue());
949 auto *Target = *MaybeVal;
950 findOrInsertNode(Target);
951 return;
Hal Finkel7529c552014-09-02 21:43:13 +0000952 }
George Burgess IVab03af22015-03-10 02:58:15 +0000953
954 const auto addEdgeToGraph = [&Graph, &findOrInsertNode](const Edge &E) {
955 auto To = findOrInsertNode(E.To);
956 auto From = findOrInsertNode(E.From);
957 auto FlippedWeight = flipWeight(E.Weight);
958 auto Attrs = E.AdditionalAttrs;
959 Graph.addEdge(From, To, std::make_pair(E.Weight, Attrs),
960 std::make_pair(FlippedWeight, Attrs));
961 };
962
963 SmallVector<ConstantExpr *, 4> ConstantExprs;
964 for (const Edge &E : Edges) {
965 addEdgeToGraph(E);
966 if (auto *Constexpr = dyn_cast<ConstantExpr>(E.To))
967 ConstantExprs.push_back(Constexpr);
968 if (auto *Constexpr = dyn_cast<ConstantExpr>(E.From))
969 ConstantExprs.push_back(Constexpr);
970 }
971
972 for (ConstantExpr *CE : ConstantExprs) {
973 Edges.clear();
974 constexprToEdges(Analysis, *CE, Edges);
975 std::for_each(Edges.begin(), Edges.end(), addEdgeToGraph);
976 }
977}
978
979// Aside: We may remove graph construction entirely, because it doesn't really
980// buy us much that we don't already have. I'd like to add interprocedural
981// analysis prior to this however, in case that somehow requires the graph
982// produced by this for efficient execution
983static void buildGraphFrom(CFLAliasAnalysis &Analysis, Function *Fn,
984 SmallVectorImpl<Value *> &ReturnedValues,
985 NodeMapT &Map, GraphT &Graph) {
986 for (auto &Bb : Fn->getBasicBlockList())
987 for (auto &Inst : Bb.getInstList())
988 addInstructionToGraph(Analysis, Inst, ReturnedValues, Map, Graph);
989}
990
991static bool canSkipAddingToSets(Value *Val) {
992 // Constants can share instances, which may falsely unify multiple
993 // sets, e.g. in
994 // store i32* null, i32** %ptr1
995 // store i32* null, i32** %ptr2
996 // clearly ptr1 and ptr2 should not be unified into the same set, so
997 // we should filter out the (potentially shared) instance to
998 // i32* null.
999 if (isa<Constant>(Val)) {
1000 bool Container = isa<ConstantVector>(Val) || isa<ConstantArray>(Val) ||
1001 isa<ConstantStruct>(Val);
1002 // TODO: Because all of these things are constant, we can determine whether
1003 // the data is *actually* mutable at graph building time. This will probably
1004 // come for free/cheap with offset awareness.
1005 bool CanStoreMutableData =
1006 isa<GlobalValue>(Val) || isa<ConstantExpr>(Val) || Container;
1007 return !CanStoreMutableData;
1008 }
1009
1010 return false;
Hal Finkel7529c552014-09-02 21:43:13 +00001011}
1012
1013static FunctionInfo buildSetsFrom(CFLAliasAnalysis &Analysis, Function *Fn) {
1014 NodeMapT Map;
1015 GraphT Graph;
1016 SmallVector<Value *, 4> ReturnedValues;
1017
1018 buildGraphFrom(Analysis, Fn, ReturnedValues, Map, Graph);
1019
1020 DenseMap<GraphT::Node, Value *> NodeValueMap;
1021 NodeValueMap.resize(Map.size());
1022 for (const auto &Pair : Map)
Hal Finkel8d1590d2014-09-02 22:52:30 +00001023 NodeValueMap.insert(std::make_pair(Pair.second, Pair.first));
Hal Finkel7529c552014-09-02 21:43:13 +00001024
1025 const auto findValueOrDie = [&NodeValueMap](GraphT::Node Node) {
1026 auto ValIter = NodeValueMap.find(Node);
1027 assert(ValIter != NodeValueMap.end());
1028 return ValIter->second;
1029 };
1030
1031 StratifiedSetsBuilder<Value *> Builder;
1032
1033 SmallVector<GraphT::Node, 16> Worklist;
1034 for (auto &Pair : Map) {
1035 Worklist.clear();
1036
1037 auto *Value = Pair.first;
1038 Builder.add(Value);
1039 auto InitialNode = Pair.second;
1040 Worklist.push_back(InitialNode);
1041 while (!Worklist.empty()) {
1042 auto Node = Worklist.pop_back_val();
1043 auto *CurValue = findValueOrDie(Node);
George Burgess IVab03af22015-03-10 02:58:15 +00001044 if (canSkipAddingToSets(CurValue))
Hal Finkel7529c552014-09-02 21:43:13 +00001045 continue;
1046
1047 for (const auto &EdgeTuple : Graph.edgesFor(Node)) {
1048 auto Weight = std::get<0>(EdgeTuple);
1049 auto Label = Weight.first;
1050 auto &OtherNode = std::get<1>(EdgeTuple);
1051 auto *OtherValue = findValueOrDie(OtherNode);
1052
George Burgess IVab03af22015-03-10 02:58:15 +00001053 if (canSkipAddingToSets(OtherValue))
Hal Finkel7529c552014-09-02 21:43:13 +00001054 continue;
1055
1056 bool Added;
1057 switch (directionOfEdgeType(Label)) {
1058 case Level::Above:
1059 Added = Builder.addAbove(CurValue, OtherValue);
1060 break;
1061 case Level::Below:
1062 Added = Builder.addBelow(CurValue, OtherValue);
1063 break;
1064 case Level::Same:
1065 Added = Builder.addWith(CurValue, OtherValue);
1066 break;
1067 }
1068
George Burgess IVb54a8d622015-03-10 02:40:06 +00001069 auto Aliasing = Weight.second;
1070 if (auto MaybeCurIndex = valueToAttrIndex(CurValue))
1071 Aliasing.set(*MaybeCurIndex);
1072 if (auto MaybeOtherIndex = valueToAttrIndex(OtherValue))
1073 Aliasing.set(*MaybeOtherIndex);
1074 Builder.noteAttributes(CurValue, Aliasing);
1075 Builder.noteAttributes(OtherValue, Aliasing);
1076
1077 if (Added)
Hal Finkel7529c552014-09-02 21:43:13 +00001078 Worklist.push_back(OtherNode);
Hal Finkel7529c552014-09-02 21:43:13 +00001079 }
1080 }
1081 }
1082
1083 // There are times when we end up with parameters not in our graph (i.e. if
1084 // it's only used as the condition of a branch). Other bits of code depend on
1085 // things that were present during construction being present in the graph.
1086 // So, we add all present arguments here.
1087 for (auto &Arg : Fn->args()) {
George Burgess IVab03af22015-03-10 02:58:15 +00001088 if (!Builder.add(&Arg))
1089 continue;
1090
1091 auto Attrs = valueToAttrIndex(&Arg);
1092 if (Attrs.hasValue())
1093 Builder.noteAttributes(&Arg, *Attrs);
Hal Finkel7529c552014-09-02 21:43:13 +00001094 }
1095
Hal Finkel85f26922014-09-03 00:06:47 +00001096 return FunctionInfo(Builder.build(), std::move(ReturnedValues));
Hal Finkel7529c552014-09-02 21:43:13 +00001097}
1098
1099void CFLAliasAnalysis::scan(Function *Fn) {
Hal Finkel8d1590d2014-09-02 22:52:30 +00001100 auto InsertPair = Cache.insert(std::make_pair(Fn, Optional<FunctionInfo>()));
Hal Finkel7529c552014-09-02 21:43:13 +00001101 (void)InsertPair;
1102 assert(InsertPair.second &&
1103 "Trying to scan a function that has already been cached");
1104
1105 FunctionInfo Info(buildSetsFrom(*this, Fn));
1106 Cache[Fn] = std::move(Info);
1107 Handles.push_front(FunctionHandle(Fn, this));
1108}
1109
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001110AliasResult CFLAliasAnalysis::query(const MemoryLocation &LocA,
1111 const MemoryLocation &LocB) {
Hal Finkel7529c552014-09-02 21:43:13 +00001112 auto *ValA = const_cast<Value *>(LocA.Ptr);
1113 auto *ValB = const_cast<Value *>(LocB.Ptr);
1114
1115 Function *Fn = nullptr;
1116 auto MaybeFnA = parentFunctionOfValue(ValA);
1117 auto MaybeFnB = parentFunctionOfValue(ValB);
1118 if (!MaybeFnA.hasValue() && !MaybeFnB.hasValue()) {
George Burgess IV33305e72015-02-12 03:07:07 +00001119 // The only times this is known to happen are when globals + InlineAsm
1120 // are involved
1121 DEBUG(dbgs() << "CFLAA: could not extract parent function information.\n");
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001122 return MayAlias;
Hal Finkel7529c552014-09-02 21:43:13 +00001123 }
1124
1125 if (MaybeFnA.hasValue()) {
1126 Fn = *MaybeFnA;
1127 assert((!MaybeFnB.hasValue() || *MaybeFnB == *MaybeFnA) &&
1128 "Interprocedural queries not supported");
1129 } else {
1130 Fn = *MaybeFnB;
1131 }
1132
1133 assert(Fn != nullptr);
1134 auto &MaybeInfo = ensureCached(Fn);
1135 assert(MaybeInfo.hasValue());
1136
1137 auto &Sets = MaybeInfo->Sets;
1138 auto MaybeA = Sets.find(ValA);
1139 if (!MaybeA.hasValue())
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001140 return MayAlias;
Hal Finkel7529c552014-09-02 21:43:13 +00001141
1142 auto MaybeB = Sets.find(ValB);
1143 if (!MaybeB.hasValue())
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001144 return MayAlias;
Hal Finkel7529c552014-09-02 21:43:13 +00001145
1146 auto SetA = *MaybeA;
1147 auto SetB = *MaybeB;
Hal Finkel7529c552014-09-02 21:43:13 +00001148 auto AttrsA = Sets.getLink(SetA.Index).Attrs;
1149 auto AttrsB = Sets.getLink(SetB.Index).Attrs;
George Burgess IV33305e72015-02-12 03:07:07 +00001150
Hal Finkel8eae3ad2014-10-06 14:42:56 +00001151 // Stratified set attributes are used as markets to signify whether a member
George Burgess IV33305e72015-02-12 03:07:07 +00001152 // of a StratifiedSet (or a member of a set above the current set) has
Hal Finkel8eae3ad2014-10-06 14:42:56 +00001153 // interacted with either arguments or globals. "Interacted with" meaning
George Burgess IV33305e72015-02-12 03:07:07 +00001154 // its value may be different depending on the value of an argument or
Hal Finkel8eae3ad2014-10-06 14:42:56 +00001155 // global. The thought behind this is that, because arguments and globals
1156 // may alias each other, if AttrsA and AttrsB have touched args/globals,
George Burgess IV33305e72015-02-12 03:07:07 +00001157 // we must conservatively say that they alias. However, if at least one of
1158 // the sets has no values that could legally be altered by changing the value
Hal Finkel8eae3ad2014-10-06 14:42:56 +00001159 // of an argument or global, then we don't have to be as conservative.
1160 if (AttrsA.any() && AttrsB.any())
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001161 return MayAlias;
Hal Finkel7529c552014-09-02 21:43:13 +00001162
Daniel Berlin16f7a522015-01-26 17:31:17 +00001163 // We currently unify things even if the accesses to them may not be in
1164 // bounds, so we can't return partial alias here because we don't
1165 // know whether the pointer is really within the object or not.
1166 // IE Given an out of bounds GEP and an alloca'd pointer, we may
1167 // unify the two. We can't return partial alias for this case.
1168 // Since we do not currently track enough information to
1169 // differentiate
1170
1171 if (SetA.Index == SetB.Index)
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001172 return MayAlias;
Daniel Berlin16f7a522015-01-26 17:31:17 +00001173
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001174 return NoAlias;
Hal Finkel7529c552014-09-02 21:43:13 +00001175}
Mehdi Amini46a43552015-03-04 18:43:29 +00001176
1177bool CFLAliasAnalysis::doInitialization(Module &M) {
1178 InitializeAliasAnalysis(this, &M.getDataLayout());
1179 return true;
1180}