blob: e2ace96edf75b5a40c78e0ba7eb60d7c2b5db25c [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
George Burgess IV77351ba32016-01-28 00:54:01 +000026// ~nlogn time (n = number of variables), which makes queries take constant
Hal Finkel7529c552014-09-02 21:43:13 +000027// time.
28//===----------------------------------------------------------------------===//
29
George Burgess IV77351ba32016-01-28 00:54:01 +000030// N.B. AliasAnalysis as a whole is phrased as a FunctionPass at the moment, and
31// CFLAA is interprocedural. This is *technically* A Bad Thing, because
32// FunctionPasses are only allowed to inspect the Function that they're being
33// run on. Realistically, this likely isn't a problem until we allow
34// FunctionPasses to run concurrently.
35
Chandler Carruth8b046a42015-08-14 02:42:20 +000036#include "llvm/Analysis/CFLAliasAnalysis.h"
Hal Finkel7529c552014-09-02 21:43:13 +000037#include "StratifiedSets.h"
Hal Finkel7529c552014-09-02 21:43:13 +000038#include "llvm/ADT/DenseMap.h"
Hal Finkel7529c552014-09-02 21:43:13 +000039#include "llvm/ADT/None.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000040#include "llvm/ADT/Optional.h"
George Burgess IV18b83fe2016-06-01 18:39:54 +000041#include "llvm/Analysis/MemoryBuiltins.h"
42#include "llvm/Analysis/TargetLibraryInfo.h"
Hal Finkel7529c552014-09-02 21:43:13 +000043#include "llvm/IR/Constants.h"
44#include "llvm/IR/Function.h"
Hal Finkel7529c552014-09-02 21:43:13 +000045#include "llvm/IR/InstVisitor.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000046#include "llvm/IR/Instructions.h"
Hal Finkel7529c552014-09-02 21:43:13 +000047#include "llvm/Pass.h"
Hal Finkel7d7087c2014-09-02 22:13:00 +000048#include "llvm/Support/Compiler.h"
George Burgess IV33305e72015-02-12 03:07:07 +000049#include "llvm/Support/Debug.h"
Hal Finkel7529c552014-09-02 21:43:13 +000050#include "llvm/Support/ErrorHandling.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000051#include "llvm/Support/raw_ostream.h"
Hal Finkel7529c552014-09-02 21:43:13 +000052#include <algorithm>
53#include <cassert>
Benjamin Kramer799003b2015-03-23 19:32:43 +000054#include <memory>
Hal Finkel7529c552014-09-02 21:43:13 +000055#include <tuple>
56
57using namespace llvm;
58
George Burgess IV33305e72015-02-12 03:07:07 +000059#define DEBUG_TYPE "cfl-aa"
60
George Burgess IV18b83fe2016-06-01 18:39:54 +000061CFLAAResult::CFLAAResult(const TargetLibraryInfo &TLI)
62 : AAResultBase(), TLI(TLI) {}
63CFLAAResult::CFLAAResult(CFLAAResult &&Arg)
64 : AAResultBase(std::move(Arg)), TLI(Arg.TLI) {}
Chandler Carruth342c6712016-02-20 03:52:02 +000065CFLAAResult::~CFLAAResult() {}
Chandler Carruth8b046a42015-08-14 02:42:20 +000066
George Burgess IV1f99da52016-06-23 18:55:23 +000067/// We use InterfaceValue to describe parameters/return value, as well as
68/// potential memory locations that are pointed to by parameters/return value,
69/// of a function.
70/// Index is an integer which represents a single parameter or a return value.
71/// When the index is 0, it refers to the return value. Non-zero index i refers
72/// to the i-th parameter.
73/// DerefLevel indicates the number of dereferences one must perform on the
74/// parameter/return value to get this InterfaceValue.
75struct InterfaceValue {
76 unsigned Index;
77 unsigned DerefLevel;
78};
79
80bool operator==(InterfaceValue lhs, InterfaceValue rhs) {
81 return lhs.Index == rhs.Index && lhs.DerefLevel == rhs.DerefLevel;
82}
83bool operator!=(InterfaceValue lhs, InterfaceValue rhs) {
84 return !(lhs == rhs);
85}
86
87/// We use ExternalRelation to describe an externally visible aliasing relations
George Burgess IV87b2e412016-06-20 23:10:56 +000088/// between parameters/return value of a function.
George Burgess IV87b2e412016-06-20 23:10:56 +000089struct ExternalRelation {
George Burgess IV1f99da52016-06-23 18:55:23 +000090 InterfaceValue From, To;
George Burgess IV87b2e412016-06-20 23:10:56 +000091};
Chandler Carruth8b046a42015-08-14 02:42:20 +000092
George Burgess IVa3d62be2016-06-24 01:00:03 +000093/// We use ExternalAttribute to describe an externally visible StratifiedAttrs
94/// for parameters/return value.
95struct ExternalAttribute {
96 InterfaceValue IValue;
97 StratifiedAttrs Attr;
98};
99
George Burgess IV87b2e412016-06-20 23:10:56 +0000100/// Information we have about a function and would like to keep around.
101class CFLAAResult::FunctionInfo {
102 StratifiedSets<Value *> Sets;
103
104 // RetParamRelations is a collection of ExternalRelations.
105 SmallVector<ExternalRelation, 8> RetParamRelations;
106
George Burgess IVa3d62be2016-06-24 01:00:03 +0000107 // RetParamAttributes is a collection of ExternalAttributes.
108 SmallVector<ExternalAttribute, 8> RetParamAttributes;
109
George Burgess IV87b2e412016-06-20 23:10:56 +0000110public:
111 FunctionInfo(Function &Fn, const SmallVectorImpl<Value *> &RetVals,
112 StratifiedSets<Value *> S);
113
114 const StratifiedSets<Value *> &getStratifiedSets() const { return Sets; }
115 const SmallVectorImpl<ExternalRelation> &getRetParamRelations() const {
116 return RetParamRelations;
117 }
George Burgess IVa3d62be2016-06-24 01:00:03 +0000118 const SmallVectorImpl<ExternalAttribute> &getRetParamAttributes() const {
119 return RetParamAttributes;
120 }
Chandler Carruth8b046a42015-08-14 02:42:20 +0000121};
122
George Burgess IVcae581d2016-04-13 23:27:37 +0000123/// Try to go from a Value* to a Function*. Never returns nullptr.
Hal Finkel7529c552014-09-02 21:43:13 +0000124static Optional<Function *> parentFunctionOfValue(Value *);
125
George Burgess IVcae581d2016-04-13 23:27:37 +0000126/// Returns possible functions called by the Inst* into the given
127/// SmallVectorImpl. Returns true if targets found, false otherwise. This is
128/// templated so we can use it with CallInsts and InvokeInsts.
George Burgess IV24eb0da2016-06-14 18:12:28 +0000129static bool getPossibleTargets(CallSite, SmallVectorImpl<Function *> &);
Hal Finkel7529c552014-09-02 21:43:13 +0000130
Hal Finkel1ae325f2014-09-02 23:50:01 +0000131const StratifiedIndex StratifiedLink::SetSentinel =
George Burgess IV11d509d2015-03-15 00:52:21 +0000132 std::numeric_limits<StratifiedIndex>::max();
Hal Finkel1ae325f2014-09-02 23:50:01 +0000133
Hal Finkel7529c552014-09-02 21:43:13 +0000134namespace {
George Burgess IVcae581d2016-04-13 23:27:37 +0000135/// StratifiedInfo Attribute things.
Hal Finkel7d7087c2014-09-02 22:13:00 +0000136LLVM_CONSTEXPR unsigned MaxStratifiedAttrIndex = NumStratifiedAttrs;
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000137LLVM_CONSTEXPR unsigned AttrEscapedIndex = 0;
138LLVM_CONSTEXPR unsigned AttrUnknownIndex = 1;
139LLVM_CONSTEXPR unsigned AttrGlobalIndex = 2;
George Burgess IVa3d62be2016-06-24 01:00:03 +0000140LLVM_CONSTEXPR unsigned AttrCallerIndex = 3;
141LLVM_CONSTEXPR unsigned AttrFirstArgIndex = 4;
Hal Finkel7d7087c2014-09-02 22:13:00 +0000142LLVM_CONSTEXPR unsigned AttrLastArgIndex = MaxStratifiedAttrIndex;
143LLVM_CONSTEXPR unsigned AttrMaxNumArgs = AttrLastArgIndex - AttrFirstArgIndex;
Hal Finkel7529c552014-09-02 21:43:13 +0000144
George Burgess IVd9c39fc2016-06-24 01:41:29 +0000145// NOTE: These aren't StratifiedAttrs because bitsets don't have a constexpr
146// ctor for some versions of MSVC that we support. We could maybe refactor,
147// but...
148using StratifiedAttr = unsigned;
149LLVM_CONSTEXPR StratifiedAttr AttrNone = 0;
150LLVM_CONSTEXPR StratifiedAttr AttrEscaped = 1 << AttrEscapedIndex;
151LLVM_CONSTEXPR StratifiedAttr AttrUnknown = 1 << AttrUnknownIndex;
152LLVM_CONSTEXPR StratifiedAttr AttrGlobal = 1 << AttrGlobalIndex;
153LLVM_CONSTEXPR StratifiedAttr AttrCaller = 1 << AttrCallerIndex;
154LLVM_CONSTEXPR StratifiedAttr ExternalAttrMask =
155 AttrEscaped | AttrUnknown | AttrGlobal;
Hal Finkel7529c552014-09-02 21:43:13 +0000156
George Burgess IV87b2e412016-06-20 23:10:56 +0000157/// The maximum number of arguments we can put into a summary.
158LLVM_CONSTEXPR unsigned MaxSupportedArgsInSummary = 50;
159
George Burgess IVcae581d2016-04-13 23:27:37 +0000160/// StratifiedSets call for knowledge of "direction", so this is how we
161/// represent that locally.
Hal Finkel7529c552014-09-02 21:43:13 +0000162enum class Level { Same, Above, Below };
163
George Burgess IVcae581d2016-04-13 23:27:37 +0000164/// Edges can be one of four "weights" -- each weight must have an inverse
165/// weight (Assign has Assign; Reference has Dereference).
Hal Finkel7529c552014-09-02 21:43:13 +0000166enum class EdgeType {
George Burgess IVcae581d2016-04-13 23:27:37 +0000167 /// The weight assigned when assigning from or to a value. For example, in:
168 /// %b = getelementptr %a, 0
169 /// ...The relationships are %b assign %a, and %a assign %b. This used to be
170 /// two edges, but having a distinction bought us nothing.
Hal Finkel7529c552014-09-02 21:43:13 +0000171 Assign,
172
George Burgess IVcae581d2016-04-13 23:27:37 +0000173 /// The edge used when we have an edge going from some handle to a Value.
174 /// Examples of this include:
175 /// %b = load %a (%b Dereference %a)
176 /// %b = extractelement %a, 0 (%a Dereference %b)
Hal Finkel7529c552014-09-02 21:43:13 +0000177 Dereference,
178
George Burgess IVcae581d2016-04-13 23:27:37 +0000179 /// The edge used when our edge goes from a value to a handle that may have
180 /// contained it at some point. Examples:
181 /// %b = load %a (%a Reference %b)
182 /// %b = extractelement %a, 0 (%b Reference %a)
Hal Finkel7529c552014-09-02 21:43:13 +0000183 Reference
184};
185
George Burgess IV24eb0da2016-06-14 18:12:28 +0000186/// The Program Expression Graph (PEG) of CFL analysis
187class CFLGraph {
188 typedef Value *Node;
Hal Finkel7529c552014-09-02 21:43:13 +0000189
George Burgess IV24eb0da2016-06-14 18:12:28 +0000190 struct Edge {
George Burgess IV24eb0da2016-06-14 18:12:28 +0000191 EdgeType Type;
192 Node Other;
193 };
Hal Finkel7529c552014-09-02 21:43:13 +0000194
George Burgess IV24eb0da2016-06-14 18:12:28 +0000195 typedef std::vector<Edge> EdgeList;
George Burgess IV259d9012016-06-15 20:43:41 +0000196
197 struct NodeInfo {
198 EdgeList Edges;
199 StratifiedAttrs Attr;
200 };
201
202 typedef DenseMap<Node, NodeInfo> NodeMap;
George Burgess IV24eb0da2016-06-14 18:12:28 +0000203 NodeMap NodeImpls;
Hal Finkel7529c552014-09-02 21:43:13 +0000204
George Burgess IV24eb0da2016-06-14 18:12:28 +0000205 // Gets the inverse of a given EdgeType.
206 static EdgeType flipWeight(EdgeType Initial) {
207 switch (Initial) {
208 case EdgeType::Assign:
209 return EdgeType::Assign;
210 case EdgeType::Dereference:
211 return EdgeType::Reference;
212 case EdgeType::Reference:
213 return EdgeType::Dereference;
214 }
215 llvm_unreachable("Incomplete coverage of EdgeType enum");
216 }
Hal Finkel7529c552014-09-02 21:43:13 +0000217
George Burgess IV259d9012016-06-15 20:43:41 +0000218 const NodeInfo *getNode(Node N) const {
George Burgess IV24eb0da2016-06-14 18:12:28 +0000219 auto Itr = NodeImpls.find(N);
220 if (Itr == NodeImpls.end())
221 return nullptr;
222 return &Itr->second;
223 }
George Burgess IV259d9012016-06-15 20:43:41 +0000224 NodeInfo *getNode(Node N) {
George Burgess IV24eb0da2016-06-14 18:12:28 +0000225 auto Itr = NodeImpls.find(N);
226 if (Itr == NodeImpls.end())
227 return nullptr;
228 return &Itr->second;
229 }
230
231 static Node nodeDeref(const NodeMap::value_type &P) { return P.first; }
232 typedef std::pointer_to_unary_function<const NodeMap::value_type &, Node>
233 NodeDerefFun;
234
235public:
236 typedef EdgeList::const_iterator const_edge_iterator;
237 typedef mapped_iterator<NodeMap::const_iterator, NodeDerefFun>
238 const_node_iterator;
239
240 bool addNode(Node N) {
George Burgess IV259d9012016-06-15 20:43:41 +0000241 return NodeImpls.insert(std::make_pair(N, NodeInfo{EdgeList(), AttrNone}))
242 .second;
George Burgess IV24eb0da2016-06-14 18:12:28 +0000243 }
244
George Burgess IV259d9012016-06-15 20:43:41 +0000245 void addAttr(Node N, StratifiedAttrs Attr) {
246 auto *Info = getNode(N);
247 assert(Info != nullptr);
248 Info->Attr |= Attr;
249 }
George Burgess IV24eb0da2016-06-14 18:12:28 +0000250
George Burgess IV259d9012016-06-15 20:43:41 +0000251 void addEdge(Node From, Node To, EdgeType Type) {
252 auto *FromInfo = getNode(From);
253 assert(FromInfo != nullptr);
254 auto *ToInfo = getNode(To);
255 assert(ToInfo != nullptr);
256
257 FromInfo->Edges.push_back(Edge{Type, To});
258 ToInfo->Edges.push_back(Edge{flipWeight(Type), From});
259 }
260
261 StratifiedAttrs attrFor(Node N) const {
262 auto *Info = getNode(N);
263 assert(Info != nullptr);
264 return Info->Attr;
George Burgess IV24eb0da2016-06-14 18:12:28 +0000265 }
266
267 iterator_range<const_edge_iterator> edgesFor(Node N) const {
George Burgess IV259d9012016-06-15 20:43:41 +0000268 auto *Info = getNode(N);
269 assert(Info != nullptr);
270 auto &Edges = Info->Edges;
271 return make_range(Edges.begin(), Edges.end());
George Burgess IV24eb0da2016-06-14 18:12:28 +0000272 }
273
274 iterator_range<const_node_iterator> nodes() const {
275 return make_range<const_node_iterator>(
276 map_iterator(NodeImpls.begin(), NodeDerefFun(nodeDeref)),
277 map_iterator(NodeImpls.end(), NodeDerefFun(nodeDeref)));
278 }
279
280 bool empty() const { return NodeImpls.empty(); }
281 std::size_t size() const { return NodeImpls.size(); }
Hal Finkel7529c552014-09-02 21:43:13 +0000282};
283
George Burgess IVa3d62be2016-06-24 01:00:03 +0000284// This is the result of instantiating InterfaceValue at a particular callsite
285struct InterprocNode {
286 Value *Val;
287 unsigned DerefLevel;
288};
289
George Burgess IV1f99da52016-06-23 18:55:23 +0000290// Interprocedural assignment edges that CFLGraph may not easily model
291struct InterprocEdge {
George Burgess IVa3d62be2016-06-24 01:00:03 +0000292 InterprocNode From, To;
293};
George Burgess IV1f99da52016-06-23 18:55:23 +0000294
George Burgess IVa3d62be2016-06-24 01:00:03 +0000295// Interprocedural attribute tagging that CFLGraph may not easily model
296struct InterprocAttr {
297 InterprocNode Node;
298 StratifiedAttrs Attr;
George Burgess IV1f99da52016-06-23 18:55:23 +0000299};
300
George Burgess IVcae581d2016-04-13 23:27:37 +0000301/// Gets the edges our graph should have, based on an Instruction*
Hal Finkel7529c552014-09-02 21:43:13 +0000302class GetEdgesVisitor : public InstVisitor<GetEdgesVisitor, void> {
Chandler Carruth7b560d42015-09-09 17:55:00 +0000303 CFLAAResult &AA;
George Burgess IV18b83fe2016-06-01 18:39:54 +0000304 const TargetLibraryInfo &TLI;
Hal Finkel7529c552014-09-02 21:43:13 +0000305
George Burgess IV24eb0da2016-06-14 18:12:28 +0000306 CFLGraph &Graph;
George Burgess IVa3d62be2016-06-24 01:00:03 +0000307 SmallVectorImpl<Value *> &ReturnValues;
George Burgess IV24eb0da2016-06-14 18:12:28 +0000308 SmallPtrSetImpl<Value *> &Externals;
309 SmallPtrSetImpl<Value *> &Escapes;
George Burgess IV1f99da52016-06-23 18:55:23 +0000310 SmallVectorImpl<InterprocEdge> &InterprocEdges;
George Burgess IVa3d62be2016-06-24 01:00:03 +0000311 SmallVectorImpl<InterprocAttr> &InterprocAttrs;
George Burgess IV24eb0da2016-06-14 18:12:28 +0000312
313 static bool hasUsefulEdges(ConstantExpr *CE) {
314 // ConstantExpr doesn't have terminators, invokes, or fences, so only needs
315 // to check for compares.
316 return CE->getOpcode() != Instruction::ICmp &&
317 CE->getOpcode() != Instruction::FCmp;
318 }
319
320 void addNode(Value *Val) {
321 if (!Graph.addNode(Val))
322 return;
323
324 if (isa<GlobalValue>(Val))
325 Externals.insert(Val);
326 else if (auto CExpr = dyn_cast<ConstantExpr>(Val))
327 if (hasUsefulEdges(CExpr))
328 visitConstantExpr(CExpr);
329 }
330
George Burgess IV259d9012016-06-15 20:43:41 +0000331 void addNodeWithAttr(Value *Val, StratifiedAttrs Attr) {
332 addNode(Val);
333 Graph.addAttr(Val, Attr);
334 }
335
336 void addEdge(Value *From, Value *To, EdgeType Type) {
337 if (!From->getType()->isPointerTy() || !To->getType()->isPointerTy())
338 return;
George Burgess IV24eb0da2016-06-14 18:12:28 +0000339 addNode(From);
340 if (To != From)
341 addNode(To);
George Burgess IV259d9012016-06-15 20:43:41 +0000342 Graph.addEdge(From, To, Type);
George Burgess IV24eb0da2016-06-14 18:12:28 +0000343 }
344
Hal Finkel7529c552014-09-02 21:43:13 +0000345public:
George Burgess IV24eb0da2016-06-14 18:12:28 +0000346 GetEdgesVisitor(CFLAAResult &AA, const TargetLibraryInfo &TLI,
George Burgess IVa3d62be2016-06-24 01:00:03 +0000347 CFLGraph &Graph, SmallVectorImpl<Value *> &ReturnValues,
348 SmallPtrSetImpl<Value *> &Externals,
George Burgess IV1f99da52016-06-23 18:55:23 +0000349 SmallPtrSetImpl<Value *> &Escapes,
George Burgess IVa3d62be2016-06-24 01:00:03 +0000350 SmallVectorImpl<InterprocEdge> &InterprocEdges,
351 SmallVectorImpl<InterprocAttr> &InterprocAttrs)
352 : AA(AA), TLI(TLI), Graph(Graph), ReturnValues(ReturnValues),
353 Externals(Externals), Escapes(Escapes), InterprocEdges(InterprocEdges),
354 InterprocAttrs(InterprocAttrs) {}
Hal Finkel7529c552014-09-02 21:43:13 +0000355
356 void visitInstruction(Instruction &) {
357 llvm_unreachable("Unsupported instruction encountered");
358 }
359
George Burgess IVa3d62be2016-06-24 01:00:03 +0000360 void visitReturnInst(ReturnInst &Inst) {
361 if (auto RetVal = Inst.getReturnValue()) {
362 if (RetVal->getType()->isPointerTy()) {
363 addNode(RetVal);
364 ReturnValues.push_back(RetVal);
365 }
366 }
367 }
368
George Burgess IVb54a8d622015-03-10 02:40:06 +0000369 void visitPtrToIntInst(PtrToIntInst &Inst) {
370 auto *Ptr = Inst.getOperand(0);
George Burgess IV259d9012016-06-15 20:43:41 +0000371 addNodeWithAttr(Ptr, AttrEscaped);
George Burgess IVb54a8d622015-03-10 02:40:06 +0000372 }
373
374 void visitIntToPtrInst(IntToPtrInst &Inst) {
375 auto *Ptr = &Inst;
George Burgess IV259d9012016-06-15 20:43:41 +0000376 addNodeWithAttr(Ptr, AttrUnknown);
George Burgess IVb54a8d622015-03-10 02:40:06 +0000377 }
378
Hal Finkel7529c552014-09-02 21:43:13 +0000379 void visitCastInst(CastInst &Inst) {
George Burgess IV24eb0da2016-06-14 18:12:28 +0000380 auto *Src = Inst.getOperand(0);
George Burgess IV259d9012016-06-15 20:43:41 +0000381 addEdge(Src, &Inst, EdgeType::Assign);
Hal Finkel7529c552014-09-02 21:43:13 +0000382 }
383
384 void visitBinaryOperator(BinaryOperator &Inst) {
385 auto *Op1 = Inst.getOperand(0);
386 auto *Op2 = Inst.getOperand(1);
George Burgess IV259d9012016-06-15 20:43:41 +0000387 addEdge(Op1, &Inst, EdgeType::Assign);
388 addEdge(Op2, &Inst, EdgeType::Assign);
Hal Finkel7529c552014-09-02 21:43:13 +0000389 }
390
391 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
392 auto *Ptr = Inst.getPointerOperand();
393 auto *Val = Inst.getNewValOperand();
George Burgess IV259d9012016-06-15 20:43:41 +0000394 addEdge(Ptr, Val, EdgeType::Dereference);
Hal Finkel7529c552014-09-02 21:43:13 +0000395 }
396
397 void visitAtomicRMWInst(AtomicRMWInst &Inst) {
398 auto *Ptr = Inst.getPointerOperand();
399 auto *Val = Inst.getValOperand();
George Burgess IV259d9012016-06-15 20:43:41 +0000400 addEdge(Ptr, Val, EdgeType::Dereference);
Hal Finkel7529c552014-09-02 21:43:13 +0000401 }
402
403 void visitPHINode(PHINode &Inst) {
George Burgess IV77351ba32016-01-28 00:54:01 +0000404 for (Value *Val : Inst.incoming_values())
George Burgess IV259d9012016-06-15 20:43:41 +0000405 addEdge(Val, &Inst, EdgeType::Assign);
Hal Finkel7529c552014-09-02 21:43:13 +0000406 }
407
408 void visitGetElementPtrInst(GetElementPtrInst &Inst) {
409 auto *Op = Inst.getPointerOperand();
George Burgess IV259d9012016-06-15 20:43:41 +0000410 addEdge(Op, &Inst, EdgeType::Assign);
Hal Finkel7529c552014-09-02 21:43:13 +0000411 }
412
413 void visitSelectInst(SelectInst &Inst) {
Daniel Berlin16f7a522015-01-26 17:31:17 +0000414 // Condition is not processed here (The actual statement producing
415 // the condition result is processed elsewhere). For select, the
416 // condition is evaluated, but not loaded, stored, or assigned
417 // simply as a result of being the condition of a select.
418
Hal Finkel7529c552014-09-02 21:43:13 +0000419 auto *TrueVal = Inst.getTrueValue();
Hal Finkel7529c552014-09-02 21:43:13 +0000420 auto *FalseVal = Inst.getFalseValue();
George Burgess IV259d9012016-06-15 20:43:41 +0000421 addEdge(TrueVal, &Inst, EdgeType::Assign);
422 addEdge(FalseVal, &Inst, EdgeType::Assign);
Hal Finkel7529c552014-09-02 21:43:13 +0000423 }
424
George Burgess IV24eb0da2016-06-14 18:12:28 +0000425 void visitAllocaInst(AllocaInst &Inst) { Graph.addNode(&Inst); }
Hal Finkel7529c552014-09-02 21:43:13 +0000426
427 void visitLoadInst(LoadInst &Inst) {
428 auto *Ptr = Inst.getPointerOperand();
429 auto *Val = &Inst;
George Burgess IV259d9012016-06-15 20:43:41 +0000430 addEdge(Val, Ptr, EdgeType::Reference);
Hal Finkel7529c552014-09-02 21:43:13 +0000431 }
432
433 void visitStoreInst(StoreInst &Inst) {
434 auto *Ptr = Inst.getPointerOperand();
435 auto *Val = Inst.getValueOperand();
George Burgess IV259d9012016-06-15 20:43:41 +0000436 addEdge(Ptr, Val, EdgeType::Dereference);
Hal Finkel7529c552014-09-02 21:43:13 +0000437 }
438
Hal Finkeldb5f86a2014-10-14 20:51:26 +0000439 void visitVAArgInst(VAArgInst &Inst) {
440 // We can't fully model va_arg here. For *Ptr = Inst.getOperand(0), it does
441 // two things:
442 // 1. Loads a value from *((T*)*Ptr).
443 // 2. Increments (stores to) *Ptr by some target-specific amount.
444 // For now, we'll handle this like a landingpad instruction (by placing the
445 // result in its own group, and having that group alias externals).
George Burgess IV259d9012016-06-15 20:43:41 +0000446 addNodeWithAttr(&Inst, AttrUnknown);
Hal Finkeldb5f86a2014-10-14 20:51:26 +0000447 }
448
Hal Finkel7529c552014-09-02 21:43:13 +0000449 static bool isFunctionExternal(Function *Fn) {
George Burgess IV9fdbfe12016-06-21 01:42:47 +0000450 return !Fn->hasExactDefinition();
Hal Finkel7529c552014-09-02 21:43:13 +0000451 }
452
George Burgess IV87b2e412016-06-20 23:10:56 +0000453 bool tryInterproceduralAnalysis(CallSite CS,
454 const SmallVectorImpl<Function *> &Fns) {
Hal Finkel7529c552014-09-02 21:43:13 +0000455 assert(Fns.size() > 0);
456
George Burgess IV87b2e412016-06-20 23:10:56 +0000457 if (CS.arg_size() > MaxSupportedArgsInSummary)
Hal Finkel7529c552014-09-02 21:43:13 +0000458 return false;
459
460 // Exit early if we'll fail anyway
461 for (auto *Fn : Fns) {
462 if (isFunctionExternal(Fn) || Fn->isVarArg())
463 return false;
George Burgess IV87b2e412016-06-20 23:10:56 +0000464 // Fail if the caller does not provide enough arguments
465 assert(Fn->arg_size() <= CS.arg_size());
Hal Finkel7529c552014-09-02 21:43:13 +0000466 auto &MaybeInfo = AA.ensureCached(Fn);
467 if (!MaybeInfo.hasValue())
468 return false;
469 }
470
George Burgess IVa3d62be2016-06-24 01:00:03 +0000471 auto InstantiateInterfaceIndex = [&CS](unsigned Index) {
472 auto Value =
473 (Index == 0) ? CS.getInstruction() : CS.getArgument(Index - 1);
474 return Value->getType()->isPointerTy() ? Value : nullptr;
475 };
476
Hal Finkel7529c552014-09-02 21:43:13 +0000477 for (auto *Fn : Fns) {
George Burgess IV87b2e412016-06-20 23:10:56 +0000478 auto &FnInfo = AA.ensureCached(Fn);
479 assert(FnInfo.hasValue());
Hal Finkel7529c552014-09-02 21:43:13 +0000480
George Burgess IV87b2e412016-06-20 23:10:56 +0000481 auto &RetParamRelations = FnInfo->getRetParamRelations();
482 for (auto &Relation : RetParamRelations) {
George Burgess IVa3d62be2016-06-24 01:00:03 +0000483 auto FromVal = InstantiateInterfaceIndex(Relation.From.Index);
484 auto ToVal = InstantiateInterfaceIndex(Relation.To.Index);
485 if (FromVal && ToVal) {
George Burgess IV1f99da52016-06-23 18:55:23 +0000486 auto FromLevel = Relation.From.DerefLevel;
487 auto ToLevel = Relation.To.DerefLevel;
488 InterprocEdges.push_back(
George Burgess IVa3d62be2016-06-24 01:00:03 +0000489 InterprocEdge{InterprocNode{FromVal, FromLevel},
490 InterprocNode{ToVal, ToLevel}});
491 }
492 }
493
494 auto &RetParamAttributes = FnInfo->getRetParamAttributes();
495 for (auto &Attribute : RetParamAttributes) {
496 if (auto Val = InstantiateInterfaceIndex(Attribute.IValue.Index)) {
497 InterprocAttrs.push_back(InterprocAttr{
498 InterprocNode{Val, Attribute.IValue.DerefLevel}, Attribute.Attr});
George Burgess IV1f99da52016-06-23 18:55:23 +0000499 }
Hal Finkel7529c552014-09-02 21:43:13 +0000500 }
George Burgess IV259d9012016-06-15 20:43:41 +0000501 }
George Burgess IV24eb0da2016-06-14 18:12:28 +0000502
Hal Finkel7529c552014-09-02 21:43:13 +0000503 return true;
504 }
505
George Burgess IV24eb0da2016-06-14 18:12:28 +0000506 void visitCallSite(CallSite CS) {
507 auto Inst = CS.getInstruction();
508
509 // Make sure all arguments and return value are added to the graph first
510 for (Value *V : CS.args())
511 addNode(V);
George Burgess IV87b2e412016-06-20 23:10:56 +0000512 if (Inst->getType()->isPointerTy())
George Burgess IV24eb0da2016-06-14 18:12:28 +0000513 addNode(Inst);
514
George Burgess IV18b83fe2016-06-01 18:39:54 +0000515 // Check if Inst is a call to a library function that allocates/deallocates
516 // on the heap. Those kinds of functions do not introduce any aliases.
517 // TODO: address other common library functions such as realloc(), strdup(),
518 // etc.
George Burgess IV24eb0da2016-06-14 18:12:28 +0000519 if (isMallocLikeFn(Inst, &TLI) || isCallocLikeFn(Inst, &TLI) ||
520 isFreeCall(Inst, &TLI))
George Burgess IV18b83fe2016-06-01 18:39:54 +0000521 return;
George Burgess IV18b83fe2016-06-01 18:39:54 +0000522
George Burgess IV68b36e02015-08-28 00:16:18 +0000523 // TODO: Add support for noalias args/all the other fun function attributes
524 // that we can tack on.
Hal Finkel7529c552014-09-02 21:43:13 +0000525 SmallVector<Function *, 4> Targets;
George Burgess IV24eb0da2016-06-14 18:12:28 +0000526 if (getPossibleTargets(CS, Targets))
George Burgess IV87b2e412016-06-20 23:10:56 +0000527 if (tryInterproceduralAnalysis(CS, Targets))
Hal Finkel7529c552014-09-02 21:43:13 +0000528 return;
Hal Finkel7529c552014-09-02 21:43:13 +0000529
George Burgess IV68b36e02015-08-28 00:16:18 +0000530 // Because the function is opaque, we need to note that anything
George Burgess IV24eb0da2016-06-14 18:12:28 +0000531 // could have happened to the arguments (unless the function is marked
532 // readonly or readnone), and that the result could alias just about
533 // anything, too (unless the result is marked noalias).
534 if (!CS.onlyReadsMemory())
535 for (Value *V : CS.args()) {
George Burgess IV259d9012016-06-15 20:43:41 +0000536 if (V->getType()->isPointerTy())
537 Escapes.insert(V);
George Burgess IV24eb0da2016-06-14 18:12:28 +0000538 }
539
George Burgess IV87b2e412016-06-20 23:10:56 +0000540 if (Inst->getType()->isPointerTy()) {
George Burgess IV24eb0da2016-06-14 18:12:28 +0000541 auto *Fn = CS.getCalledFunction();
542 if (Fn == nullptr || !Fn->doesNotAlias(0))
George Burgess IV259d9012016-06-15 20:43:41 +0000543 Graph.addAttr(Inst, AttrUnknown);
George Burgess IV24eb0da2016-06-14 18:12:28 +0000544 }
Hal Finkel7529c552014-09-02 21:43:13 +0000545 }
546
George Burgess IVcae581d2016-04-13 23:27:37 +0000547 /// Because vectors/aggregates are immutable and unaddressable, there's
548 /// nothing we can do to coax a value out of them, other than calling
549 /// Extract{Element,Value}. We can effectively treat them as pointers to
550 /// arbitrary memory locations we can store in and load from.
Hal Finkel7529c552014-09-02 21:43:13 +0000551 void visitExtractElementInst(ExtractElementInst &Inst) {
552 auto *Ptr = Inst.getVectorOperand();
553 auto *Val = &Inst;
George Burgess IV259d9012016-06-15 20:43:41 +0000554 addEdge(Val, Ptr, EdgeType::Reference);
Hal Finkel7529c552014-09-02 21:43:13 +0000555 }
556
557 void visitInsertElementInst(InsertElementInst &Inst) {
558 auto *Vec = Inst.getOperand(0);
559 auto *Val = Inst.getOperand(1);
George Burgess IV259d9012016-06-15 20:43:41 +0000560 addEdge(Vec, &Inst, EdgeType::Assign);
561 addEdge(&Inst, Val, EdgeType::Dereference);
Hal Finkel7529c552014-09-02 21:43:13 +0000562 }
563
564 void visitLandingPadInst(LandingPadInst &Inst) {
565 // Exceptions come from "nowhere", from our analysis' perspective.
566 // So we place the instruction its own group, noting that said group may
567 // alias externals
George Burgess IV259d9012016-06-15 20:43:41 +0000568 addNodeWithAttr(&Inst, AttrUnknown);
Hal Finkel7529c552014-09-02 21:43:13 +0000569 }
570
571 void visitInsertValueInst(InsertValueInst &Inst) {
572 auto *Agg = Inst.getOperand(0);
573 auto *Val = Inst.getOperand(1);
George Burgess IV259d9012016-06-15 20:43:41 +0000574 addEdge(Agg, &Inst, EdgeType::Assign);
575 addEdge(&Inst, Val, EdgeType::Dereference);
Hal Finkel7529c552014-09-02 21:43:13 +0000576 }
577
578 void visitExtractValueInst(ExtractValueInst &Inst) {
579 auto *Ptr = Inst.getAggregateOperand();
George Burgess IV259d9012016-06-15 20:43:41 +0000580 addEdge(&Inst, Ptr, EdgeType::Reference);
Hal Finkel7529c552014-09-02 21:43:13 +0000581 }
582
583 void visitShuffleVectorInst(ShuffleVectorInst &Inst) {
584 auto *From1 = Inst.getOperand(0);
585 auto *From2 = Inst.getOperand(1);
George Burgess IV259d9012016-06-15 20:43:41 +0000586 addEdge(From1, &Inst, EdgeType::Assign);
587 addEdge(From2, &Inst, EdgeType::Assign);
Hal Finkel7529c552014-09-02 21:43:13 +0000588 }
Pete Cooper36642532015-06-12 16:13:54 +0000589
590 void visitConstantExpr(ConstantExpr *CE) {
591 switch (CE->getOpcode()) {
592 default:
593 llvm_unreachable("Unknown instruction type encountered!");
594// Build the switch statement using the Instruction.def file.
595#define HANDLE_INST(NUM, OPCODE, CLASS) \
596 case Instruction::OPCODE: \
597 visit##OPCODE(*(CLASS *)CE); \
598 break;
599#include "llvm/IR/Instruction.def"
600 }
601 }
Hal Finkel7529c552014-09-02 21:43:13 +0000602};
603
George Burgess IVe17756e2016-06-14 18:02:27 +0000604class CFLGraphBuilder {
605 // Input of the builder
606 CFLAAResult &Analysis;
607 const TargetLibraryInfo &TLI;
608
609 // Output of the builder
610 CFLGraph Graph;
611 SmallVector<Value *, 4> ReturnedValues;
612
613 // Auxiliary structures used by the builder
George Burgess IV24eb0da2016-06-14 18:12:28 +0000614 SmallPtrSet<Value *, 8> ExternalValues;
615 SmallPtrSet<Value *, 8> EscapedValues;
George Burgess IV1f99da52016-06-23 18:55:23 +0000616 SmallVector<InterprocEdge, 8> InterprocEdges;
George Burgess IVa3d62be2016-06-24 01:00:03 +0000617 SmallVector<InterprocAttr, 8> InterprocAttrs;
George Burgess IVe17756e2016-06-14 18:02:27 +0000618
619 // Helper functions
620
621 // Determines whether or not we an instruction is useless to us (e.g.
622 // FenceInst)
623 static bool hasUsefulEdges(Instruction *Inst) {
George Burgess IVa3d62be2016-06-24 01:00:03 +0000624 bool IsNonInvokeRetTerminator = isa<TerminatorInst>(Inst) &&
625 !isa<InvokeInst>(Inst) &&
626 !isa<ReturnInst>(Inst);
George Burgess IVe17756e2016-06-14 18:02:27 +0000627 return !isa<CmpInst>(Inst) && !isa<FenceInst>(Inst) &&
George Burgess IVa3d62be2016-06-24 01:00:03 +0000628 !IsNonInvokeRetTerminator;
George Burgess IVe17756e2016-06-14 18:02:27 +0000629 }
630
George Burgess IV24eb0da2016-06-14 18:12:28 +0000631 void addArgumentToGraph(Argument &Arg) {
George Burgess IV259d9012016-06-15 20:43:41 +0000632 if (Arg.getType()->isPointerTy()) {
633 Graph.addNode(&Arg);
634 ExternalValues.insert(&Arg);
635 }
George Burgess IVe17756e2016-06-14 18:02:27 +0000636 }
637
638 // Given an Instruction, this will add it to the graph, along with any
639 // Instructions that are potentially only available from said Instruction
640 // For example, given the following line:
641 // %0 = load i16* getelementptr ([1 x i16]* @a, 0, 0), align 2
642 // addInstructionToGraph would add both the `load` and `getelementptr`
643 // instructions to the graph appropriately.
644 void addInstructionToGraph(Instruction &Inst) {
George Burgess IVe17756e2016-06-14 18:02:27 +0000645 if (!hasUsefulEdges(&Inst))
646 return;
647
George Burgess IVa3d62be2016-06-24 01:00:03 +0000648 GetEdgesVisitor(Analysis, TLI, Graph, ReturnedValues, ExternalValues,
649 EscapedValues, InterprocEdges, InterprocAttrs)
George Burgess IV24eb0da2016-06-14 18:12:28 +0000650 .visit(Inst);
651 }
George Burgess IVe17756e2016-06-14 18:02:27 +0000652
George Burgess IV24eb0da2016-06-14 18:12:28 +0000653 // Builds the graph needed for constructing the StratifiedSets for the given
654 // function
655 void buildGraphFrom(Function &Fn) {
656 for (auto &Bb : Fn.getBasicBlockList())
657 for (auto &Inst : Bb.getInstList())
658 addInstructionToGraph(Inst);
George Burgess IVe17756e2016-06-14 18:02:27 +0000659
George Burgess IV24eb0da2016-06-14 18:12:28 +0000660 for (auto &Arg : Fn.args())
661 addArgumentToGraph(Arg);
George Burgess IVe17756e2016-06-14 18:02:27 +0000662 }
663
664public:
665 CFLGraphBuilder(CFLAAResult &Analysis, const TargetLibraryInfo &TLI,
666 Function &Fn)
667 : Analysis(Analysis), TLI(TLI) {
668 buildGraphFrom(Fn);
669 }
670
George Burgess IV87b2e412016-06-20 23:10:56 +0000671 const CFLGraph &getCFLGraph() const { return Graph; }
672 const SmallVector<Value *, 4> &getReturnValues() const {
673 return ReturnedValues;
George Burgess IVe17756e2016-06-14 18:02:27 +0000674 }
George Burgess IV87b2e412016-06-20 23:10:56 +0000675 const SmallPtrSet<Value *, 8> &getExternalValues() const {
676 return ExternalValues;
677 }
678 const SmallPtrSet<Value *, 8> &getEscapedValues() const {
679 return EscapedValues;
680 }
George Burgess IV1f99da52016-06-23 18:55:23 +0000681 const SmallVector<InterprocEdge, 8> &getInterprocEdges() const {
682 return InterprocEdges;
683 }
George Burgess IVa3d62be2016-06-24 01:00:03 +0000684 const SmallVector<InterprocAttr, 8> &getInterprocAttrs() const {
685 return InterprocAttrs;
686 }
George Burgess IVe17756e2016-06-14 18:02:27 +0000687};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000688}
Hal Finkel7529c552014-09-02 21:43:13 +0000689
Hal Finkel7529c552014-09-02 21:43:13 +0000690//===----------------------------------------------------------------------===//
691// Function declarations that require types defined in the namespace above
692//===----------------------------------------------------------------------===//
693
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000694/// Given a StratifiedAttrs, returns true if it marks the corresponding values
695/// as globals or arguments
696static bool isGlobalOrArgAttr(StratifiedAttrs Attr);
Hal Finkel7529c552014-09-02 21:43:13 +0000697
George Burgess IV652ec4f2016-06-09 23:15:04 +0000698/// Given a StratifiedAttrs, returns true if the corresponding values come from
699/// an unknown source (such as opaque memory or an integer cast)
700static bool isUnknownAttr(StratifiedAttrs Attr);
701
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000702/// Given an argument number, returns the appropriate StratifiedAttr to set.
George Burgess IVa3d62be2016-06-24 01:00:03 +0000703static StratifiedAttrs argNumberToAttr(unsigned ArgNum);
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000704
705/// Given a Value, potentially return which StratifiedAttr it maps to.
George Burgess IVa3d62be2016-06-24 01:00:03 +0000706static Optional<StratifiedAttrs> valueToAttr(Value *Val);
Hal Finkel7529c552014-09-02 21:43:13 +0000707
George Burgess IVcae581d2016-04-13 23:27:37 +0000708/// Gets the "Level" that one should travel in StratifiedSets
709/// given an EdgeType.
Hal Finkel7529c552014-09-02 21:43:13 +0000710static Level directionOfEdgeType(EdgeType);
711
George Burgess IVcae581d2016-04-13 23:27:37 +0000712/// Determines whether it would be pointless to add the given Value to our sets.
George Burgess IVab03af22015-03-10 02:58:15 +0000713static bool canSkipAddingToSets(Value *Val);
714
Hal Finkel7529c552014-09-02 21:43:13 +0000715static Optional<Function *> parentFunctionOfValue(Value *Val) {
716 if (auto *Inst = dyn_cast<Instruction>(Val)) {
717 auto *Bb = Inst->getParent();
718 return Bb->getParent();
719 }
720
721 if (auto *Arg = dyn_cast<Argument>(Val))
722 return Arg->getParent();
George Burgess IV77351ba32016-01-28 00:54:01 +0000723 return None;
Hal Finkel7529c552014-09-02 21:43:13 +0000724}
725
George Burgess IV24eb0da2016-06-14 18:12:28 +0000726static bool getPossibleTargets(CallSite CS,
Hal Finkel7529c552014-09-02 21:43:13 +0000727 SmallVectorImpl<Function *> &Output) {
George Burgess IV24eb0da2016-06-14 18:12:28 +0000728 if (auto *Fn = CS.getCalledFunction()) {
Hal Finkel7529c552014-09-02 21:43:13 +0000729 Output.push_back(Fn);
730 return true;
731 }
732
733 // TODO: If the call is indirect, we might be able to enumerate all potential
734 // targets of the call and return them, rather than just failing.
735 return false;
736}
737
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000738static bool isGlobalOrArgAttr(StratifiedAttrs Attr) {
George Burgess IVa3d62be2016-06-24 01:00:03 +0000739 return Attr.reset(AttrEscapedIndex)
740 .reset(AttrUnknownIndex)
741 .reset(AttrCallerIndex)
742 .any();
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000743}
744
George Burgess IV652ec4f2016-06-09 23:15:04 +0000745static bool isUnknownAttr(StratifiedAttrs Attr) {
George Burgess IVa3d62be2016-06-24 01:00:03 +0000746 return Attr.test(AttrUnknownIndex) || Attr.test(AttrCallerIndex);
George Burgess IV652ec4f2016-06-09 23:15:04 +0000747}
748
George Burgess IVa3d62be2016-06-24 01:00:03 +0000749static Optional<StratifiedAttrs> valueToAttr(Value *Val) {
Hal Finkel7529c552014-09-02 21:43:13 +0000750 if (isa<GlobalValue>(Val))
George Burgess IVd9c39fc2016-06-24 01:41:29 +0000751 return StratifiedAttrs(AttrGlobal);
Hal Finkel7529c552014-09-02 21:43:13 +0000752
753 if (auto *Arg = dyn_cast<Argument>(Val))
Daniel Berlin16f7a522015-01-26 17:31:17 +0000754 // 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())
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000758 return argNumberToAttr(Arg->getArgNo());
George Burgess IV77351ba32016-01-28 00:54:01 +0000759 return None;
Hal Finkel7529c552014-09-02 21:43:13 +0000760}
761
George Burgess IVa3d62be2016-06-24 01:00:03 +0000762static StratifiedAttrs argNumberToAttr(unsigned ArgNum) {
George Burgess IV3c898c22015-01-21 16:37:21 +0000763 if (ArgNum >= AttrMaxNumArgs)
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000764 return AttrUnknown;
George Burgess IVf10c7fc2016-06-27 22:50:01 +0000765 // N.B. MSVC complains if we use `1U` here, since StratifiedAttrs' ctor takes
766 // an unsigned long long.
767 return StratifiedAttrs(1ULL << (ArgNum + AttrFirstArgIndex));
Hal Finkel7529c552014-09-02 21:43:13 +0000768}
769
Hal Finkel7529c552014-09-02 21:43:13 +0000770static Level directionOfEdgeType(EdgeType Weight) {
771 switch (Weight) {
772 case EdgeType::Reference:
773 return Level::Above;
774 case EdgeType::Dereference:
775 return Level::Below;
776 case EdgeType::Assign:
777 return Level::Same;
778 }
779 llvm_unreachable("Incomplete switch coverage");
780}
781
George Burgess IVab03af22015-03-10 02:58:15 +0000782static bool canSkipAddingToSets(Value *Val) {
783 // Constants can share instances, which may falsely unify multiple
784 // sets, e.g. in
785 // store i32* null, i32** %ptr1
786 // store i32* null, i32** %ptr2
787 // clearly ptr1 and ptr2 should not be unified into the same set, so
788 // we should filter out the (potentially shared) instance to
789 // i32* null.
790 if (isa<Constant>(Val)) {
George Burgess IVab03af22015-03-10 02:58:15 +0000791 // TODO: Because all of these things are constant, we can determine whether
792 // the data is *actually* mutable at graph building time. This will probably
793 // come for free/cheap with offset awareness.
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +0000794 bool CanStoreMutableData = isa<GlobalValue>(Val) ||
795 isa<ConstantExpr>(Val) ||
796 isa<ConstantAggregate>(Val);
George Burgess IVab03af22015-03-10 02:58:15 +0000797 return !CanStoreMutableData;
798 }
799
800 return false;
Hal Finkel7529c552014-09-02 21:43:13 +0000801}
802
George Burgess IV87b2e412016-06-20 23:10:56 +0000803CFLAAResult::FunctionInfo::FunctionInfo(Function &Fn,
804 const SmallVectorImpl<Value *> &RetVals,
805 StratifiedSets<Value *> S)
806 : Sets(std::move(S)) {
George Burgess IV1f99da52016-06-23 18:55:23 +0000807 // Historically, an arbitrary upper-bound of 50 args was selected. We may want
808 // to remove this if it doesn't really matter in practice.
809 if (Fn.arg_size() > MaxSupportedArgsInSummary)
810 return;
George Burgess IV87b2e412016-06-20 23:10:56 +0000811
George Burgess IV1f99da52016-06-23 18:55:23 +0000812 DenseMap<StratifiedIndex, InterfaceValue> InterfaceMap;
George Burgess IV87b2e412016-06-20 23:10:56 +0000813
George Burgess IV1f99da52016-06-23 18:55:23 +0000814 // Our intention here is to record all InterfaceValues that share the same
815 // StratifiedIndex in RetParamRelations. For each valid InterfaceValue, we
816 // have its StratifiedIndex scanned here and check if the index is presented
817 // in InterfaceMap: if it is not, we add the correspondence to the map;
818 // otherwise, an aliasing relation is found and we add it to
819 // RetParamRelations.
George Burgess IVa3d62be2016-06-24 01:00:03 +0000820
George Burgess IVd14d05a2016-06-23 20:59:13 +0000821 auto AddToRetParamRelations = [&](unsigned InterfaceIndex,
822 StratifiedIndex SetIndex) {
George Burgess IV1f99da52016-06-23 18:55:23 +0000823 unsigned Level = 0;
824 while (true) {
825 InterfaceValue CurrValue{InterfaceIndex, Level};
George Burgess IV87b2e412016-06-20 23:10:56 +0000826
George Burgess IV1f99da52016-06-23 18:55:23 +0000827 auto Itr = InterfaceMap.find(SetIndex);
828 if (Itr != InterfaceMap.end()) {
829 if (CurrValue != Itr->second)
830 RetParamRelations.push_back(ExternalRelation{CurrValue, Itr->second});
831 break;
George Burgess IVa3d62be2016-06-24 01:00:03 +0000832 }
George Burgess IV87b2e412016-06-20 23:10:56 +0000833
George Burgess IV1f99da52016-06-23 18:55:23 +0000834 auto &Link = Sets.getLink(SetIndex);
George Burgess IVa3d62be2016-06-24 01:00:03 +0000835 InterfaceMap.insert(std::make_pair(SetIndex, CurrValue));
George Burgess IVd9c39fc2016-06-24 01:41:29 +0000836 auto ExternalAttrs = Link.Attrs & StratifiedAttrs(ExternalAttrMask);
George Burgess IVa3d62be2016-06-24 01:00:03 +0000837 if (ExternalAttrs.any())
838 RetParamAttributes.push_back(
839 ExternalAttribute{CurrValue, ExternalAttrs});
840
George Burgess IV1f99da52016-06-23 18:55:23 +0000841 if (!Link.hasBelow())
842 break;
George Burgess IV87b2e412016-06-20 23:10:56 +0000843
George Burgess IV1f99da52016-06-23 18:55:23 +0000844 ++Level;
845 SetIndex = Link.Below;
George Burgess IV87b2e412016-06-20 23:10:56 +0000846 }
George Burgess IV1f99da52016-06-23 18:55:23 +0000847 };
848
849 // Populate RetParamRelations for return values
850 for (auto *RetVal : RetVals) {
George Burgess IVa3d62be2016-06-24 01:00:03 +0000851 assert(RetVal != nullptr);
852 assert(RetVal->getType()->isPointerTy());
George Burgess IV1f99da52016-06-23 18:55:23 +0000853 auto RetInfo = Sets.find(RetVal);
854 if (RetInfo.hasValue())
855 AddToRetParamRelations(0, RetInfo->Index);
856 }
857
858 // Populate RetParamRelations for parameters
859 unsigned I = 0;
860 for (auto &Param : Fn.args()) {
861 if (Param.getType()->isPointerTy()) {
862 auto ParamInfo = Sets.find(&Param);
863 if (ParamInfo.hasValue())
864 AddToRetParamRelations(I + 1, ParamInfo->Index);
865 }
866 ++I;
George Burgess IV87b2e412016-06-20 23:10:56 +0000867 }
868}
869
Chandler Carruth8b046a42015-08-14 02:42:20 +0000870// Builds the graph + StratifiedSets for a function.
Chandler Carruth7b560d42015-09-09 17:55:00 +0000871CFLAAResult::FunctionInfo CFLAAResult::buildSetsFrom(Function *Fn) {
George Burgess IVe17756e2016-06-14 18:02:27 +0000872 CFLGraphBuilder GraphBuilder(*this, TLI, *Fn);
873 StratifiedSetsBuilder<Value *> SetBuilder;
Hal Finkel7529c552014-09-02 21:43:13 +0000874
George Burgess IVe17756e2016-06-14 18:02:27 +0000875 auto &Graph = GraphBuilder.getCFLGraph();
George Burgess IVdc96feb2016-06-13 19:21:18 +0000876 SmallVector<Value *, 16> Worklist;
George Burgess IVdc96feb2016-06-13 19:21:18 +0000877 for (auto Node : Graph.nodes())
878 Worklist.push_back(Node);
879
880 while (!Worklist.empty()) {
881 auto *CurValue = Worklist.pop_back_val();
George Burgess IVe17756e2016-06-14 18:02:27 +0000882 SetBuilder.add(CurValue);
George Burgess IVdc96feb2016-06-13 19:21:18 +0000883 if (canSkipAddingToSets(CurValue))
884 continue;
885
George Burgess IV259d9012016-06-15 20:43:41 +0000886 auto Attr = Graph.attrFor(CurValue);
887 SetBuilder.noteAttributes(CurValue, Attr);
888
George Burgess IVdc96feb2016-06-13 19:21:18 +0000889 for (const auto &Edge : Graph.edgesFor(CurValue)) {
890 auto Label = Edge.Type;
891 auto *OtherValue = Edge.Other;
892
893 if (canSkipAddingToSets(OtherValue))
Hal Finkel7529c552014-09-02 21:43:13 +0000894 continue;
895
George Burgess IVdc96feb2016-06-13 19:21:18 +0000896 bool Added;
897 switch (directionOfEdgeType(Label)) {
898 case Level::Above:
George Burgess IVe17756e2016-06-14 18:02:27 +0000899 Added = SetBuilder.addAbove(CurValue, OtherValue);
George Burgess IVdc96feb2016-06-13 19:21:18 +0000900 break;
901 case Level::Below:
George Burgess IVe17756e2016-06-14 18:02:27 +0000902 Added = SetBuilder.addBelow(CurValue, OtherValue);
George Burgess IVdc96feb2016-06-13 19:21:18 +0000903 break;
904 case Level::Same:
George Burgess IVe17756e2016-06-14 18:02:27 +0000905 Added = SetBuilder.addWith(CurValue, OtherValue);
George Burgess IVdc96feb2016-06-13 19:21:18 +0000906 break;
Hal Finkel7529c552014-09-02 21:43:13 +0000907 }
George Burgess IVdc96feb2016-06-13 19:21:18 +0000908
George Burgess IVdc96feb2016-06-13 19:21:18 +0000909 if (Added)
910 Worklist.push_back(OtherValue);
Hal Finkel7529c552014-09-02 21:43:13 +0000911 }
912 }
913
George Burgess IV652ec4f2016-06-09 23:15:04 +0000914 // Special handling for globals and arguments
George Burgess IV24eb0da2016-06-14 18:12:28 +0000915 for (auto *External : GraphBuilder.getExternalValues()) {
916 SetBuilder.add(External);
917 auto Attr = valueToAttr(External);
George Burgess IV652ec4f2016-06-09 23:15:04 +0000918 if (Attr.hasValue()) {
George Burgess IV24eb0da2016-06-14 18:12:28 +0000919 SetBuilder.noteAttributes(External, *Attr);
George Burgess IVa3d62be2016-06-24 01:00:03 +0000920 if (*Attr == AttrGlobal)
921 SetBuilder.addAttributesBelow(External, 1, AttrUnknown);
922 else
923 SetBuilder.addAttributesBelow(External, 1, AttrCaller);
George Burgess IV652ec4f2016-06-09 23:15:04 +0000924 }
George Burgess IV24eb0da2016-06-14 18:12:28 +0000925 }
George Burgess IVab03af22015-03-10 02:58:15 +0000926
George Burgess IV1f99da52016-06-23 18:55:23 +0000927 // Special handling for interprocedural aliases
928 for (auto &Edge : GraphBuilder.getInterprocEdges()) {
George Burgess IVfe1397b2016-06-23 19:16:04 +0000929 auto FromVal = Edge.From.Val;
930 auto ToVal = Edge.To.Val;
George Burgess IV1f99da52016-06-23 18:55:23 +0000931 SetBuilder.add(FromVal);
932 SetBuilder.add(ToVal);
933 SetBuilder.addBelowWith(FromVal, Edge.From.DerefLevel, ToVal,
934 Edge.To.DerefLevel);
935 }
936
George Burgess IVa3d62be2016-06-24 01:00:03 +0000937 // Special handling for interprocedural attributes
938 for (auto &IPAttr : GraphBuilder.getInterprocAttrs()) {
939 auto Val = IPAttr.Node.Val;
940 SetBuilder.add(Val);
941 SetBuilder.addAttributesBelow(Val, IPAttr.Node.DerefLevel, IPAttr.Attr);
942 }
943
George Burgess IV1f99da52016-06-23 18:55:23 +0000944 // Special handling for opaque external functions
George Burgess IV24eb0da2016-06-14 18:12:28 +0000945 for (auto *Escape : GraphBuilder.getEscapedValues()) {
946 SetBuilder.add(Escape);
947 SetBuilder.noteAttributes(Escape, AttrEscaped);
George Burgess IVa3d62be2016-06-24 01:00:03 +0000948 SetBuilder.addAttributesBelow(Escape, 1, AttrUnknown);
George Burgess IV24eb0da2016-06-14 18:12:28 +0000949 }
Hal Finkel7529c552014-09-02 21:43:13 +0000950
George Burgess IV87b2e412016-06-20 23:10:56 +0000951 return FunctionInfo(*Fn, GraphBuilder.getReturnValues(), SetBuilder.build());
Hal Finkel7529c552014-09-02 21:43:13 +0000952}
953
Chandler Carruth7b560d42015-09-09 17:55:00 +0000954void CFLAAResult::scan(Function *Fn) {
Hal Finkel8d1590d2014-09-02 22:52:30 +0000955 auto InsertPair = Cache.insert(std::make_pair(Fn, Optional<FunctionInfo>()));
Hal Finkel7529c552014-09-02 21:43:13 +0000956 (void)InsertPair;
957 assert(InsertPair.second &&
958 "Trying to scan a function that has already been cached");
959
George Burgess IV6edb8912016-05-02 18:09:19 +0000960 // Note that we can't do Cache[Fn] = buildSetsFrom(Fn) here: the function call
961 // may get evaluated after operator[], potentially triggering a DenseMap
962 // resize and invalidating the reference returned by operator[]
963 auto FunInfo = buildSetsFrom(Fn);
964 Cache[Fn] = std::move(FunInfo);
965
Hal Finkel7529c552014-09-02 21:43:13 +0000966 Handles.push_front(FunctionHandle(Fn, this));
967}
968
Chandler Carruth7b560d42015-09-09 17:55:00 +0000969void CFLAAResult::evict(Function *Fn) { Cache.erase(Fn); }
Chandler Carruth8b046a42015-08-14 02:42:20 +0000970
George Burgess IVcae581d2016-04-13 23:27:37 +0000971/// Ensures that the given function is available in the cache, and returns the
972/// entry.
Chandler Carruth7b560d42015-09-09 17:55:00 +0000973const Optional<CFLAAResult::FunctionInfo> &
974CFLAAResult::ensureCached(Function *Fn) {
Chandler Carruth8b046a42015-08-14 02:42:20 +0000975 auto Iter = Cache.find(Fn);
976 if (Iter == Cache.end()) {
977 scan(Fn);
978 Iter = Cache.find(Fn);
979 assert(Iter != Cache.end());
980 assert(Iter->second.hasValue());
981 }
982 return Iter->second;
983}
984
Chandler Carruth7b560d42015-09-09 17:55:00 +0000985AliasResult CFLAAResult::query(const MemoryLocation &LocA,
986 const MemoryLocation &LocB) {
Hal Finkel7529c552014-09-02 21:43:13 +0000987 auto *ValA = const_cast<Value *>(LocA.Ptr);
988 auto *ValB = const_cast<Value *>(LocB.Ptr);
989
George Burgess IV259d9012016-06-15 20:43:41 +0000990 if (!ValA->getType()->isPointerTy() || !ValB->getType()->isPointerTy())
991 return NoAlias;
992
Hal Finkel7529c552014-09-02 21:43:13 +0000993 Function *Fn = nullptr;
994 auto MaybeFnA = parentFunctionOfValue(ValA);
995 auto MaybeFnB = parentFunctionOfValue(ValB);
996 if (!MaybeFnA.hasValue() && !MaybeFnB.hasValue()) {
George Burgess IVcae581d2016-04-13 23:27:37 +0000997 // The only times this is known to happen are when globals + InlineAsm are
998 // involved
George Burgess IV33305e72015-02-12 03:07:07 +0000999 DEBUG(dbgs() << "CFLAA: could not extract parent function information.\n");
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001000 return MayAlias;
Hal Finkel7529c552014-09-02 21:43:13 +00001001 }
1002
1003 if (MaybeFnA.hasValue()) {
1004 Fn = *MaybeFnA;
1005 assert((!MaybeFnB.hasValue() || *MaybeFnB == *MaybeFnA) &&
1006 "Interprocedural queries not supported");
1007 } else {
1008 Fn = *MaybeFnB;
1009 }
1010
1011 assert(Fn != nullptr);
1012 auto &MaybeInfo = ensureCached(Fn);
1013 assert(MaybeInfo.hasValue());
1014
George Burgess IV87b2e412016-06-20 23:10:56 +00001015 auto &Sets = MaybeInfo->getStratifiedSets();
Hal Finkel7529c552014-09-02 21:43:13 +00001016 auto MaybeA = Sets.find(ValA);
1017 if (!MaybeA.hasValue())
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001018 return MayAlias;
Hal Finkel7529c552014-09-02 21:43:13 +00001019
1020 auto MaybeB = Sets.find(ValB);
1021 if (!MaybeB.hasValue())
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001022 return MayAlias;
Hal Finkel7529c552014-09-02 21:43:13 +00001023
1024 auto SetA = *MaybeA;
1025 auto SetB = *MaybeB;
Hal Finkel7529c552014-09-02 21:43:13 +00001026 auto AttrsA = Sets.getLink(SetA.Index).Attrs;
1027 auto AttrsB = Sets.getLink(SetB.Index).Attrs;
George Burgess IV33305e72015-02-12 03:07:07 +00001028
George Burgess IVa1f9a2d2016-06-07 18:35:37 +00001029 // If both values are local (meaning the corresponding set has attribute
1030 // AttrNone or AttrEscaped), then we know that CFLAA fully models them: they
1031 // may-alias each other if and only if they are in the same set
1032 // If at least one value is non-local (meaning it either is global/argument or
1033 // it comes from unknown sources like integer cast), the situation becomes a
1034 // bit more interesting. We follow three general rules described below:
1035 // - Non-local values may alias each other
1036 // - AttrNone values do not alias any non-local values
George Burgess IV652ec4f2016-06-09 23:15:04 +00001037 // - AttrEscaped do not alias globals/arguments, but they may alias
George Burgess IVa1f9a2d2016-06-07 18:35:37 +00001038 // AttrUnknown values
1039 if (SetA.Index == SetB.Index)
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001040 return MayAlias;
George Burgess IVa1f9a2d2016-06-07 18:35:37 +00001041 if (AttrsA.none() || AttrsB.none())
1042 return NoAlias;
George Burgess IV652ec4f2016-06-09 23:15:04 +00001043 if (isUnknownAttr(AttrsA) || isUnknownAttr(AttrsB))
George Burgess IVa1f9a2d2016-06-07 18:35:37 +00001044 return MayAlias;
1045 if (isGlobalOrArgAttr(AttrsA) && isGlobalOrArgAttr(AttrsB))
1046 return MayAlias;
1047 return NoAlias;
Hal Finkel7529c552014-09-02 21:43:13 +00001048}
Mehdi Amini46a43552015-03-04 18:43:29 +00001049
Chandler Carruthb4faf132016-03-11 10:22:49 +00001050char CFLAA::PassID;
1051
Chandler Carruthb47f8012016-03-11 11:05:24 +00001052CFLAAResult CFLAA::run(Function &F, AnalysisManager<Function> &AM) {
George Burgess IV18b83fe2016-06-01 18:39:54 +00001053 return CFLAAResult(AM.getResult<TargetLibraryAnalysis>(F));
Chandler Carruth7b560d42015-09-09 17:55:00 +00001054}
1055
Chandler Carruth7b560d42015-09-09 17:55:00 +00001056char CFLAAWrapperPass::ID = 0;
Chandler Carruth12884f72016-03-02 15:56:53 +00001057INITIALIZE_PASS(CFLAAWrapperPass, "cfl-aa", "CFL-Based Alias Analysis", false,
1058 true)
Chandler Carruth7b560d42015-09-09 17:55:00 +00001059
1060ImmutablePass *llvm::createCFLAAWrapperPass() { return new CFLAAWrapperPass(); }
1061
1062CFLAAWrapperPass::CFLAAWrapperPass() : ImmutablePass(ID) {
1063 initializeCFLAAWrapperPassPass(*PassRegistry::getPassRegistry());
1064}
1065
George Burgess IV18b83fe2016-06-01 18:39:54 +00001066void CFLAAWrapperPass::initializePass() {
1067 auto &TLIWP = getAnalysis<TargetLibraryInfoWrapperPass>();
1068 Result.reset(new CFLAAResult(TLIWP.getTLI()));
Chandler Carruth7b560d42015-09-09 17:55:00 +00001069}
1070
1071void CFLAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
1072 AU.setPreservesAll();
George Burgess IV18b83fe2016-06-01 18:39:54 +00001073 AU.addRequired<TargetLibraryInfoWrapperPass>();
Mehdi Amini46a43552015-03-04 18:43:29 +00001074}