blob: 09dd098ba07edd970b6328b5ea704e1b85bfbfef [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 IV87b2e412016-06-20 23:10:56 +000093/// Information we have about a function and would like to keep around.
94class CFLAAResult::FunctionInfo {
95 StratifiedSets<Value *> Sets;
96
97 // RetParamRelations is a collection of ExternalRelations.
98 SmallVector<ExternalRelation, 8> RetParamRelations;
99
100public:
101 FunctionInfo(Function &Fn, const SmallVectorImpl<Value *> &RetVals,
102 StratifiedSets<Value *> S);
103
104 const StratifiedSets<Value *> &getStratifiedSets() const { return Sets; }
105 const SmallVectorImpl<ExternalRelation> &getRetParamRelations() const {
106 return RetParamRelations;
107 }
Chandler Carruth8b046a42015-08-14 02:42:20 +0000108};
109
George Burgess IVcae581d2016-04-13 23:27:37 +0000110/// Try to go from a Value* to a Function*. Never returns nullptr.
Hal Finkel7529c552014-09-02 21:43:13 +0000111static Optional<Function *> parentFunctionOfValue(Value *);
112
George Burgess IVcae581d2016-04-13 23:27:37 +0000113/// Returns possible functions called by the Inst* into the given
114/// SmallVectorImpl. Returns true if targets found, false otherwise. This is
115/// templated so we can use it with CallInsts and InvokeInsts.
George Burgess IV24eb0da2016-06-14 18:12:28 +0000116static bool getPossibleTargets(CallSite, SmallVectorImpl<Function *> &);
Hal Finkel7529c552014-09-02 21:43:13 +0000117
Hal Finkel1ae325f2014-09-02 23:50:01 +0000118const StratifiedIndex StratifiedLink::SetSentinel =
George Burgess IV11d509d2015-03-15 00:52:21 +0000119 std::numeric_limits<StratifiedIndex>::max();
Hal Finkel1ae325f2014-09-02 23:50:01 +0000120
Hal Finkel7529c552014-09-02 21:43:13 +0000121namespace {
George Burgess IVcae581d2016-04-13 23:27:37 +0000122/// StratifiedInfo Attribute things.
Hal Finkel7529c552014-09-02 21:43:13 +0000123typedef unsigned StratifiedAttr;
Hal Finkel7d7087c2014-09-02 22:13:00 +0000124LLVM_CONSTEXPR unsigned MaxStratifiedAttrIndex = NumStratifiedAttrs;
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000125LLVM_CONSTEXPR unsigned AttrEscapedIndex = 0;
126LLVM_CONSTEXPR unsigned AttrUnknownIndex = 1;
127LLVM_CONSTEXPR unsigned AttrGlobalIndex = 2;
George Burgess IVb54a8d622015-03-10 02:40:06 +0000128LLVM_CONSTEXPR unsigned AttrFirstArgIndex = 3;
Hal Finkel7d7087c2014-09-02 22:13:00 +0000129LLVM_CONSTEXPR unsigned AttrLastArgIndex = MaxStratifiedAttrIndex;
130LLVM_CONSTEXPR unsigned AttrMaxNumArgs = AttrLastArgIndex - AttrFirstArgIndex;
Hal Finkel7529c552014-09-02 21:43:13 +0000131
Hal Finkel7d7087c2014-09-02 22:13:00 +0000132LLVM_CONSTEXPR StratifiedAttr AttrNone = 0;
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000133LLVM_CONSTEXPR StratifiedAttr AttrEscaped = 1 << AttrEscapedIndex;
George Burgess IVb54a8d622015-03-10 02:40:06 +0000134LLVM_CONSTEXPR StratifiedAttr AttrUnknown = 1 << AttrUnknownIndex;
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000135LLVM_CONSTEXPR StratifiedAttr AttrGlobal = 1 << AttrGlobalIndex;
Hal Finkel7529c552014-09-02 21:43:13 +0000136
George Burgess IV87b2e412016-06-20 23:10:56 +0000137/// The maximum number of arguments we can put into a summary.
138LLVM_CONSTEXPR unsigned MaxSupportedArgsInSummary = 50;
139
George Burgess IVcae581d2016-04-13 23:27:37 +0000140/// StratifiedSets call for knowledge of "direction", so this is how we
141/// represent that locally.
Hal Finkel7529c552014-09-02 21:43:13 +0000142enum class Level { Same, Above, Below };
143
George Burgess IVcae581d2016-04-13 23:27:37 +0000144/// Edges can be one of four "weights" -- each weight must have an inverse
145/// weight (Assign has Assign; Reference has Dereference).
Hal Finkel7529c552014-09-02 21:43:13 +0000146enum class EdgeType {
George Burgess IVcae581d2016-04-13 23:27:37 +0000147 /// The weight assigned when assigning from or to a value. For example, in:
148 /// %b = getelementptr %a, 0
149 /// ...The relationships are %b assign %a, and %a assign %b. This used to be
150 /// two edges, but having a distinction bought us nothing.
Hal Finkel7529c552014-09-02 21:43:13 +0000151 Assign,
152
George Burgess IVcae581d2016-04-13 23:27:37 +0000153 /// The edge used when we have an edge going from some handle to a Value.
154 /// Examples of this include:
155 /// %b = load %a (%b Dereference %a)
156 /// %b = extractelement %a, 0 (%a Dereference %b)
Hal Finkel7529c552014-09-02 21:43:13 +0000157 Dereference,
158
George Burgess IVcae581d2016-04-13 23:27:37 +0000159 /// The edge used when our edge goes from a value to a handle that may have
160 /// contained it at some point. Examples:
161 /// %b = load %a (%a Reference %b)
162 /// %b = extractelement %a, 0 (%b Reference %a)
Hal Finkel7529c552014-09-02 21:43:13 +0000163 Reference
164};
165
George Burgess IV24eb0da2016-06-14 18:12:28 +0000166/// The Program Expression Graph (PEG) of CFL analysis
167class CFLGraph {
168 typedef Value *Node;
Hal Finkel7529c552014-09-02 21:43:13 +0000169
George Burgess IV24eb0da2016-06-14 18:12:28 +0000170 struct Edge {
George Burgess IV24eb0da2016-06-14 18:12:28 +0000171 EdgeType Type;
172 Node Other;
173 };
Hal Finkel7529c552014-09-02 21:43:13 +0000174
George Burgess IV24eb0da2016-06-14 18:12:28 +0000175 typedef std::vector<Edge> EdgeList;
George Burgess IV259d9012016-06-15 20:43:41 +0000176
177 struct NodeInfo {
178 EdgeList Edges;
179 StratifiedAttrs Attr;
180 };
181
182 typedef DenseMap<Node, NodeInfo> NodeMap;
George Burgess IV24eb0da2016-06-14 18:12:28 +0000183 NodeMap NodeImpls;
Hal Finkel7529c552014-09-02 21:43:13 +0000184
George Burgess IV24eb0da2016-06-14 18:12:28 +0000185 // Gets the inverse of a given EdgeType.
186 static EdgeType flipWeight(EdgeType Initial) {
187 switch (Initial) {
188 case EdgeType::Assign:
189 return EdgeType::Assign;
190 case EdgeType::Dereference:
191 return EdgeType::Reference;
192 case EdgeType::Reference:
193 return EdgeType::Dereference;
194 }
195 llvm_unreachable("Incomplete coverage of EdgeType enum");
196 }
Hal Finkel7529c552014-09-02 21:43:13 +0000197
George Burgess IV259d9012016-06-15 20:43:41 +0000198 const NodeInfo *getNode(Node N) const {
George Burgess IV24eb0da2016-06-14 18:12:28 +0000199 auto Itr = NodeImpls.find(N);
200 if (Itr == NodeImpls.end())
201 return nullptr;
202 return &Itr->second;
203 }
George Burgess IV259d9012016-06-15 20:43:41 +0000204 NodeInfo *getNode(Node N) {
George Burgess IV24eb0da2016-06-14 18:12:28 +0000205 auto Itr = NodeImpls.find(N);
206 if (Itr == NodeImpls.end())
207 return nullptr;
208 return &Itr->second;
209 }
210
211 static Node nodeDeref(const NodeMap::value_type &P) { return P.first; }
212 typedef std::pointer_to_unary_function<const NodeMap::value_type &, Node>
213 NodeDerefFun;
214
215public:
216 typedef EdgeList::const_iterator const_edge_iterator;
217 typedef mapped_iterator<NodeMap::const_iterator, NodeDerefFun>
218 const_node_iterator;
219
220 bool addNode(Node N) {
George Burgess IV259d9012016-06-15 20:43:41 +0000221 return NodeImpls.insert(std::make_pair(N, NodeInfo{EdgeList(), AttrNone}))
222 .second;
George Burgess IV24eb0da2016-06-14 18:12:28 +0000223 }
224
George Burgess IV259d9012016-06-15 20:43:41 +0000225 void addAttr(Node N, StratifiedAttrs Attr) {
226 auto *Info = getNode(N);
227 assert(Info != nullptr);
228 Info->Attr |= Attr;
229 }
George Burgess IV24eb0da2016-06-14 18:12:28 +0000230
George Burgess IV259d9012016-06-15 20:43:41 +0000231 void addEdge(Node From, Node To, EdgeType Type) {
232 auto *FromInfo = getNode(From);
233 assert(FromInfo != nullptr);
234 auto *ToInfo = getNode(To);
235 assert(ToInfo != nullptr);
236
237 FromInfo->Edges.push_back(Edge{Type, To});
238 ToInfo->Edges.push_back(Edge{flipWeight(Type), From});
239 }
240
241 StratifiedAttrs attrFor(Node N) const {
242 auto *Info = getNode(N);
243 assert(Info != nullptr);
244 return Info->Attr;
George Burgess IV24eb0da2016-06-14 18:12:28 +0000245 }
246
247 iterator_range<const_edge_iterator> edgesFor(Node N) const {
George Burgess IV259d9012016-06-15 20:43:41 +0000248 auto *Info = getNode(N);
249 assert(Info != nullptr);
250 auto &Edges = Info->Edges;
251 return make_range(Edges.begin(), Edges.end());
George Burgess IV24eb0da2016-06-14 18:12:28 +0000252 }
253
254 iterator_range<const_node_iterator> nodes() const {
255 return make_range<const_node_iterator>(
256 map_iterator(NodeImpls.begin(), NodeDerefFun(nodeDeref)),
257 map_iterator(NodeImpls.end(), NodeDerefFun(nodeDeref)));
258 }
259
260 bool empty() const { return NodeImpls.empty(); }
261 std::size_t size() const { return NodeImpls.size(); }
Hal Finkel7529c552014-09-02 21:43:13 +0000262};
263
George Burgess IV1f99da52016-06-23 18:55:23 +0000264// Interprocedural assignment edges that CFLGraph may not easily model
265struct InterprocEdge {
266 struct Node {
267 Value *Value;
268 unsigned DerefLevel;
269 };
270
271 Node From, To;
272};
273
George Burgess IVcae581d2016-04-13 23:27:37 +0000274/// Gets the edges our graph should have, based on an Instruction*
Hal Finkel7529c552014-09-02 21:43:13 +0000275class GetEdgesVisitor : public InstVisitor<GetEdgesVisitor, void> {
Chandler Carruth7b560d42015-09-09 17:55:00 +0000276 CFLAAResult &AA;
George Burgess IV18b83fe2016-06-01 18:39:54 +0000277 const TargetLibraryInfo &TLI;
Hal Finkel7529c552014-09-02 21:43:13 +0000278
George Burgess IV24eb0da2016-06-14 18:12:28 +0000279 CFLGraph &Graph;
280 SmallPtrSetImpl<Value *> &Externals;
281 SmallPtrSetImpl<Value *> &Escapes;
George Burgess IV1f99da52016-06-23 18:55:23 +0000282 SmallVectorImpl<InterprocEdge> &InterprocEdges;
George Burgess IV24eb0da2016-06-14 18:12:28 +0000283
284 static bool hasUsefulEdges(ConstantExpr *CE) {
285 // ConstantExpr doesn't have terminators, invokes, or fences, so only needs
286 // to check for compares.
287 return CE->getOpcode() != Instruction::ICmp &&
288 CE->getOpcode() != Instruction::FCmp;
289 }
290
291 void addNode(Value *Val) {
292 if (!Graph.addNode(Val))
293 return;
294
295 if (isa<GlobalValue>(Val))
296 Externals.insert(Val);
297 else if (auto CExpr = dyn_cast<ConstantExpr>(Val))
298 if (hasUsefulEdges(CExpr))
299 visitConstantExpr(CExpr);
300 }
301
George Burgess IV259d9012016-06-15 20:43:41 +0000302 void addNodeWithAttr(Value *Val, StratifiedAttrs Attr) {
303 addNode(Val);
304 Graph.addAttr(Val, Attr);
305 }
306
307 void addEdge(Value *From, Value *To, EdgeType Type) {
308 if (!From->getType()->isPointerTy() || !To->getType()->isPointerTy())
309 return;
George Burgess IV24eb0da2016-06-14 18:12:28 +0000310 addNode(From);
311 if (To != From)
312 addNode(To);
George Burgess IV259d9012016-06-15 20:43:41 +0000313 Graph.addEdge(From, To, Type);
George Burgess IV24eb0da2016-06-14 18:12:28 +0000314 }
315
Hal Finkel7529c552014-09-02 21:43:13 +0000316public:
George Burgess IV24eb0da2016-06-14 18:12:28 +0000317 GetEdgesVisitor(CFLAAResult &AA, const TargetLibraryInfo &TLI,
318 CFLGraph &Graph, SmallPtrSetImpl<Value *> &Externals,
George Burgess IV1f99da52016-06-23 18:55:23 +0000319 SmallPtrSetImpl<Value *> &Escapes,
320 SmallVectorImpl<InterprocEdge> &InterprocEdges)
321 : AA(AA), TLI(TLI), Graph(Graph), Externals(Externals), Escapes(Escapes),
322 InterprocEdges(InterprocEdges) {}
Hal Finkel7529c552014-09-02 21:43:13 +0000323
324 void visitInstruction(Instruction &) {
325 llvm_unreachable("Unsupported instruction encountered");
326 }
327
George Burgess IVb54a8d622015-03-10 02:40:06 +0000328 void visitPtrToIntInst(PtrToIntInst &Inst) {
329 auto *Ptr = Inst.getOperand(0);
George Burgess IV259d9012016-06-15 20:43:41 +0000330 addNodeWithAttr(Ptr, AttrEscaped);
George Burgess IVb54a8d622015-03-10 02:40:06 +0000331 }
332
333 void visitIntToPtrInst(IntToPtrInst &Inst) {
334 auto *Ptr = &Inst;
George Burgess IV259d9012016-06-15 20:43:41 +0000335 addNodeWithAttr(Ptr, AttrUnknown);
George Burgess IVb54a8d622015-03-10 02:40:06 +0000336 }
337
Hal Finkel7529c552014-09-02 21:43:13 +0000338 void visitCastInst(CastInst &Inst) {
George Burgess IV24eb0da2016-06-14 18:12:28 +0000339 auto *Src = Inst.getOperand(0);
George Burgess IV259d9012016-06-15 20:43:41 +0000340 addEdge(Src, &Inst, EdgeType::Assign);
Hal Finkel7529c552014-09-02 21:43:13 +0000341 }
342
343 void visitBinaryOperator(BinaryOperator &Inst) {
344 auto *Op1 = Inst.getOperand(0);
345 auto *Op2 = Inst.getOperand(1);
George Burgess IV259d9012016-06-15 20:43:41 +0000346 addEdge(Op1, &Inst, EdgeType::Assign);
347 addEdge(Op2, &Inst, EdgeType::Assign);
Hal Finkel7529c552014-09-02 21:43:13 +0000348 }
349
350 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
351 auto *Ptr = Inst.getPointerOperand();
352 auto *Val = Inst.getNewValOperand();
George Burgess IV259d9012016-06-15 20:43:41 +0000353 addEdge(Ptr, Val, EdgeType::Dereference);
Hal Finkel7529c552014-09-02 21:43:13 +0000354 }
355
356 void visitAtomicRMWInst(AtomicRMWInst &Inst) {
357 auto *Ptr = Inst.getPointerOperand();
358 auto *Val = Inst.getValOperand();
George Burgess IV259d9012016-06-15 20:43:41 +0000359 addEdge(Ptr, Val, EdgeType::Dereference);
Hal Finkel7529c552014-09-02 21:43:13 +0000360 }
361
362 void visitPHINode(PHINode &Inst) {
George Burgess IV77351ba32016-01-28 00:54:01 +0000363 for (Value *Val : Inst.incoming_values())
George Burgess IV259d9012016-06-15 20:43:41 +0000364 addEdge(Val, &Inst, EdgeType::Assign);
Hal Finkel7529c552014-09-02 21:43:13 +0000365 }
366
367 void visitGetElementPtrInst(GetElementPtrInst &Inst) {
368 auto *Op = Inst.getPointerOperand();
George Burgess IV259d9012016-06-15 20:43:41 +0000369 addEdge(Op, &Inst, EdgeType::Assign);
Hal Finkel7529c552014-09-02 21:43:13 +0000370 }
371
372 void visitSelectInst(SelectInst &Inst) {
Daniel Berlin16f7a522015-01-26 17:31:17 +0000373 // Condition is not processed here (The actual statement producing
374 // the condition result is processed elsewhere). For select, the
375 // condition is evaluated, but not loaded, stored, or assigned
376 // simply as a result of being the condition of a select.
377
Hal Finkel7529c552014-09-02 21:43:13 +0000378 auto *TrueVal = Inst.getTrueValue();
Hal Finkel7529c552014-09-02 21:43:13 +0000379 auto *FalseVal = Inst.getFalseValue();
George Burgess IV259d9012016-06-15 20:43:41 +0000380 addEdge(TrueVal, &Inst, EdgeType::Assign);
381 addEdge(FalseVal, &Inst, EdgeType::Assign);
Hal Finkel7529c552014-09-02 21:43:13 +0000382 }
383
George Burgess IV24eb0da2016-06-14 18:12:28 +0000384 void visitAllocaInst(AllocaInst &Inst) { Graph.addNode(&Inst); }
Hal Finkel7529c552014-09-02 21:43:13 +0000385
386 void visitLoadInst(LoadInst &Inst) {
387 auto *Ptr = Inst.getPointerOperand();
388 auto *Val = &Inst;
George Burgess IV259d9012016-06-15 20:43:41 +0000389 addEdge(Val, Ptr, EdgeType::Reference);
Hal Finkel7529c552014-09-02 21:43:13 +0000390 }
391
392 void visitStoreInst(StoreInst &Inst) {
393 auto *Ptr = Inst.getPointerOperand();
394 auto *Val = Inst.getValueOperand();
George Burgess IV259d9012016-06-15 20:43:41 +0000395 addEdge(Ptr, Val, EdgeType::Dereference);
Hal Finkel7529c552014-09-02 21:43:13 +0000396 }
397
Hal Finkeldb5f86a2014-10-14 20:51:26 +0000398 void visitVAArgInst(VAArgInst &Inst) {
399 // We can't fully model va_arg here. For *Ptr = Inst.getOperand(0), it does
400 // two things:
401 // 1. Loads a value from *((T*)*Ptr).
402 // 2. Increments (stores to) *Ptr by some target-specific amount.
403 // For now, we'll handle this like a landingpad instruction (by placing the
404 // result in its own group, and having that group alias externals).
George Burgess IV259d9012016-06-15 20:43:41 +0000405 addNodeWithAttr(&Inst, AttrUnknown);
Hal Finkeldb5f86a2014-10-14 20:51:26 +0000406 }
407
Hal Finkel7529c552014-09-02 21:43:13 +0000408 static bool isFunctionExternal(Function *Fn) {
George Burgess IV9fdbfe12016-06-21 01:42:47 +0000409 return !Fn->hasExactDefinition();
Hal Finkel7529c552014-09-02 21:43:13 +0000410 }
411
George Burgess IV87b2e412016-06-20 23:10:56 +0000412 bool tryInterproceduralAnalysis(CallSite CS,
413 const SmallVectorImpl<Function *> &Fns) {
Hal Finkel7529c552014-09-02 21:43:13 +0000414 assert(Fns.size() > 0);
415
George Burgess IV87b2e412016-06-20 23:10:56 +0000416 if (CS.arg_size() > MaxSupportedArgsInSummary)
Hal Finkel7529c552014-09-02 21:43:13 +0000417 return false;
418
419 // Exit early if we'll fail anyway
420 for (auto *Fn : Fns) {
421 if (isFunctionExternal(Fn) || Fn->isVarArg())
422 return false;
George Burgess IV87b2e412016-06-20 23:10:56 +0000423 // Fail if the caller does not provide enough arguments
424 assert(Fn->arg_size() <= CS.arg_size());
Hal Finkel7529c552014-09-02 21:43:13 +0000425 auto &MaybeInfo = AA.ensureCached(Fn);
426 if (!MaybeInfo.hasValue())
427 return false;
428 }
429
Hal Finkel7529c552014-09-02 21:43:13 +0000430 for (auto *Fn : Fns) {
George Burgess IV87b2e412016-06-20 23:10:56 +0000431 auto &FnInfo = AA.ensureCached(Fn);
432 assert(FnInfo.hasValue());
Hal Finkel7529c552014-09-02 21:43:13 +0000433
George Burgess IV87b2e412016-06-20 23:10:56 +0000434 auto &RetParamRelations = FnInfo->getRetParamRelations();
435 for (auto &Relation : RetParamRelations) {
George Burgess IV1f99da52016-06-23 18:55:23 +0000436 auto FromIndex = Relation.From.Index;
437 auto ToIndex = Relation.To.Index;
George Burgess IV87b2e412016-06-20 23:10:56 +0000438 auto FromVal = (FromIndex == 0) ? CS.getInstruction()
439 : CS.getArgument(FromIndex - 1);
440 auto ToVal =
441 (ToIndex == 0) ? CS.getInstruction() : CS.getArgument(ToIndex - 1);
442 if (FromVal->getType()->isPointerTy() &&
George Burgess IV1f99da52016-06-23 18:55:23 +0000443 ToVal->getType()->isPointerTy()) {
444 auto FromLevel = Relation.From.DerefLevel;
445 auto ToLevel = Relation.To.DerefLevel;
446 InterprocEdges.push_back(
447 InterprocEdge{InterprocEdge::Node{FromVal, FromLevel},
448 InterprocEdge::Node{ToVal, ToLevel}});
449 }
Hal Finkel7529c552014-09-02 21:43:13 +0000450 }
George Burgess IV259d9012016-06-15 20:43:41 +0000451 }
George Burgess IV24eb0da2016-06-14 18:12:28 +0000452
Hal Finkel7529c552014-09-02 21:43:13 +0000453 return true;
454 }
455
George Burgess IV24eb0da2016-06-14 18:12:28 +0000456 void visitCallSite(CallSite CS) {
457 auto Inst = CS.getInstruction();
458
459 // Make sure all arguments and return value are added to the graph first
460 for (Value *V : CS.args())
461 addNode(V);
George Burgess IV87b2e412016-06-20 23:10:56 +0000462 if (Inst->getType()->isPointerTy())
George Burgess IV24eb0da2016-06-14 18:12:28 +0000463 addNode(Inst);
464
George Burgess IV18b83fe2016-06-01 18:39:54 +0000465 // Check if Inst is a call to a library function that allocates/deallocates
466 // on the heap. Those kinds of functions do not introduce any aliases.
467 // TODO: address other common library functions such as realloc(), strdup(),
468 // etc.
George Burgess IV24eb0da2016-06-14 18:12:28 +0000469 if (isMallocLikeFn(Inst, &TLI) || isCallocLikeFn(Inst, &TLI) ||
470 isFreeCall(Inst, &TLI))
George Burgess IV18b83fe2016-06-01 18:39:54 +0000471 return;
George Burgess IV18b83fe2016-06-01 18:39:54 +0000472
George Burgess IV68b36e02015-08-28 00:16:18 +0000473 // TODO: Add support for noalias args/all the other fun function attributes
474 // that we can tack on.
Hal Finkel7529c552014-09-02 21:43:13 +0000475 SmallVector<Function *, 4> Targets;
George Burgess IV24eb0da2016-06-14 18:12:28 +0000476 if (getPossibleTargets(CS, Targets))
George Burgess IV87b2e412016-06-20 23:10:56 +0000477 if (tryInterproceduralAnalysis(CS, Targets))
Hal Finkel7529c552014-09-02 21:43:13 +0000478 return;
Hal Finkel7529c552014-09-02 21:43:13 +0000479
George Burgess IV68b36e02015-08-28 00:16:18 +0000480 // Because the function is opaque, we need to note that anything
George Burgess IV24eb0da2016-06-14 18:12:28 +0000481 // could have happened to the arguments (unless the function is marked
482 // readonly or readnone), and that the result could alias just about
483 // anything, too (unless the result is marked noalias).
484 if (!CS.onlyReadsMemory())
485 for (Value *V : CS.args()) {
George Burgess IV259d9012016-06-15 20:43:41 +0000486 if (V->getType()->isPointerTy())
487 Escapes.insert(V);
George Burgess IV24eb0da2016-06-14 18:12:28 +0000488 }
489
George Burgess IV87b2e412016-06-20 23:10:56 +0000490 if (Inst->getType()->isPointerTy()) {
George Burgess IV24eb0da2016-06-14 18:12:28 +0000491 auto *Fn = CS.getCalledFunction();
492 if (Fn == nullptr || !Fn->doesNotAlias(0))
George Burgess IV259d9012016-06-15 20:43:41 +0000493 Graph.addAttr(Inst, AttrUnknown);
George Burgess IV24eb0da2016-06-14 18:12:28 +0000494 }
Hal Finkel7529c552014-09-02 21:43:13 +0000495 }
496
George Burgess IVcae581d2016-04-13 23:27:37 +0000497 /// Because vectors/aggregates are immutable and unaddressable, there's
498 /// nothing we can do to coax a value out of them, other than calling
499 /// Extract{Element,Value}. We can effectively treat them as pointers to
500 /// arbitrary memory locations we can store in and load from.
Hal Finkel7529c552014-09-02 21:43:13 +0000501 void visitExtractElementInst(ExtractElementInst &Inst) {
502 auto *Ptr = Inst.getVectorOperand();
503 auto *Val = &Inst;
George Burgess IV259d9012016-06-15 20:43:41 +0000504 addEdge(Val, Ptr, EdgeType::Reference);
Hal Finkel7529c552014-09-02 21:43:13 +0000505 }
506
507 void visitInsertElementInst(InsertElementInst &Inst) {
508 auto *Vec = Inst.getOperand(0);
509 auto *Val = Inst.getOperand(1);
George Burgess IV259d9012016-06-15 20:43:41 +0000510 addEdge(Vec, &Inst, EdgeType::Assign);
511 addEdge(&Inst, Val, EdgeType::Dereference);
Hal Finkel7529c552014-09-02 21:43:13 +0000512 }
513
514 void visitLandingPadInst(LandingPadInst &Inst) {
515 // Exceptions come from "nowhere", from our analysis' perspective.
516 // So we place the instruction its own group, noting that said group may
517 // alias externals
George Burgess IV259d9012016-06-15 20:43:41 +0000518 addNodeWithAttr(&Inst, AttrUnknown);
Hal Finkel7529c552014-09-02 21:43:13 +0000519 }
520
521 void visitInsertValueInst(InsertValueInst &Inst) {
522 auto *Agg = Inst.getOperand(0);
523 auto *Val = Inst.getOperand(1);
George Burgess IV259d9012016-06-15 20:43:41 +0000524 addEdge(Agg, &Inst, EdgeType::Assign);
525 addEdge(&Inst, Val, EdgeType::Dereference);
Hal Finkel7529c552014-09-02 21:43:13 +0000526 }
527
528 void visitExtractValueInst(ExtractValueInst &Inst) {
529 auto *Ptr = Inst.getAggregateOperand();
George Burgess IV259d9012016-06-15 20:43:41 +0000530 addEdge(&Inst, Ptr, EdgeType::Reference);
Hal Finkel7529c552014-09-02 21:43:13 +0000531 }
532
533 void visitShuffleVectorInst(ShuffleVectorInst &Inst) {
534 auto *From1 = Inst.getOperand(0);
535 auto *From2 = Inst.getOperand(1);
George Burgess IV259d9012016-06-15 20:43:41 +0000536 addEdge(From1, &Inst, EdgeType::Assign);
537 addEdge(From2, &Inst, EdgeType::Assign);
Hal Finkel7529c552014-09-02 21:43:13 +0000538 }
Pete Cooper36642532015-06-12 16:13:54 +0000539
540 void visitConstantExpr(ConstantExpr *CE) {
541 switch (CE->getOpcode()) {
542 default:
543 llvm_unreachable("Unknown instruction type encountered!");
544// Build the switch statement using the Instruction.def file.
545#define HANDLE_INST(NUM, OPCODE, CLASS) \
546 case Instruction::OPCODE: \
547 visit##OPCODE(*(CLASS *)CE); \
548 break;
549#include "llvm/IR/Instruction.def"
550 }
551 }
Hal Finkel7529c552014-09-02 21:43:13 +0000552};
553
George Burgess IVe17756e2016-06-14 18:02:27 +0000554class CFLGraphBuilder {
555 // Input of the builder
556 CFLAAResult &Analysis;
557 const TargetLibraryInfo &TLI;
558
559 // Output of the builder
560 CFLGraph Graph;
561 SmallVector<Value *, 4> ReturnedValues;
562
563 // Auxiliary structures used by the builder
George Burgess IV24eb0da2016-06-14 18:12:28 +0000564 SmallPtrSet<Value *, 8> ExternalValues;
565 SmallPtrSet<Value *, 8> EscapedValues;
George Burgess IV1f99da52016-06-23 18:55:23 +0000566 SmallVector<InterprocEdge, 8> InterprocEdges;
George Burgess IVe17756e2016-06-14 18:02:27 +0000567
568 // Helper functions
569
570 // Determines whether or not we an instruction is useless to us (e.g.
571 // FenceInst)
572 static bool hasUsefulEdges(Instruction *Inst) {
573 bool IsNonInvokeTerminator =
574 isa<TerminatorInst>(Inst) && !isa<InvokeInst>(Inst);
575 return !isa<CmpInst>(Inst) && !isa<FenceInst>(Inst) &&
576 !IsNonInvokeTerminator;
577 }
578
George Burgess IV24eb0da2016-06-14 18:12:28 +0000579 void addArgumentToGraph(Argument &Arg) {
George Burgess IV259d9012016-06-15 20:43:41 +0000580 if (Arg.getType()->isPointerTy()) {
581 Graph.addNode(&Arg);
582 ExternalValues.insert(&Arg);
583 }
George Burgess IVe17756e2016-06-14 18:02:27 +0000584 }
585
586 // Given an Instruction, this will add it to the graph, along with any
587 // Instructions that are potentially only available from said Instruction
588 // For example, given the following line:
589 // %0 = load i16* getelementptr ([1 x i16]* @a, 0, 0), align 2
590 // addInstructionToGraph would add both the `load` and `getelementptr`
591 // instructions to the graph appropriately.
592 void addInstructionToGraph(Instruction &Inst) {
593 // We don't want the edges of most "return" instructions, but we *do* want
594 // to know what can be returned.
George Burgess IV87b2e412016-06-20 23:10:56 +0000595 if (auto RetInst = dyn_cast<ReturnInst>(&Inst))
596 if (auto RetVal = RetInst->getReturnValue())
597 if (RetVal->getType()->isPointerTy())
598 ReturnedValues.push_back(RetVal);
George Burgess IVe17756e2016-06-14 18:02:27 +0000599
600 if (!hasUsefulEdges(&Inst))
601 return;
602
George Burgess IV1f99da52016-06-23 18:55:23 +0000603 GetEdgesVisitor(Analysis, TLI, Graph, ExternalValues, EscapedValues,
604 InterprocEdges)
George Burgess IV24eb0da2016-06-14 18:12:28 +0000605 .visit(Inst);
606 }
George Burgess IVe17756e2016-06-14 18:02:27 +0000607
George Burgess IV24eb0da2016-06-14 18:12:28 +0000608 // Builds the graph needed for constructing the StratifiedSets for the given
609 // function
610 void buildGraphFrom(Function &Fn) {
611 for (auto &Bb : Fn.getBasicBlockList())
612 for (auto &Inst : Bb.getInstList())
613 addInstructionToGraph(Inst);
George Burgess IVe17756e2016-06-14 18:02:27 +0000614
George Burgess IV24eb0da2016-06-14 18:12:28 +0000615 for (auto &Arg : Fn.args())
616 addArgumentToGraph(Arg);
George Burgess IVe17756e2016-06-14 18:02:27 +0000617 }
618
619public:
620 CFLGraphBuilder(CFLAAResult &Analysis, const TargetLibraryInfo &TLI,
621 Function &Fn)
622 : Analysis(Analysis), TLI(TLI) {
623 buildGraphFrom(Fn);
624 }
625
George Burgess IV87b2e412016-06-20 23:10:56 +0000626 const CFLGraph &getCFLGraph() const { return Graph; }
627 const SmallVector<Value *, 4> &getReturnValues() const {
628 return ReturnedValues;
George Burgess IVe17756e2016-06-14 18:02:27 +0000629 }
George Burgess IV87b2e412016-06-20 23:10:56 +0000630 const SmallPtrSet<Value *, 8> &getExternalValues() const {
631 return ExternalValues;
632 }
633 const SmallPtrSet<Value *, 8> &getEscapedValues() const {
634 return EscapedValues;
635 }
George Burgess IV1f99da52016-06-23 18:55:23 +0000636 const SmallVector<InterprocEdge, 8> &getInterprocEdges() const {
637 return InterprocEdges;
638 }
George Burgess IVe17756e2016-06-14 18:02:27 +0000639};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000640}
Hal Finkel7529c552014-09-02 21:43:13 +0000641
Hal Finkel7529c552014-09-02 21:43:13 +0000642//===----------------------------------------------------------------------===//
643// Function declarations that require types defined in the namespace above
644//===----------------------------------------------------------------------===//
645
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000646/// Given a StratifiedAttrs, returns true if it marks the corresponding values
647/// as globals or arguments
648static bool isGlobalOrArgAttr(StratifiedAttrs Attr);
Hal Finkel7529c552014-09-02 21:43:13 +0000649
George Burgess IV652ec4f2016-06-09 23:15:04 +0000650/// Given a StratifiedAttrs, returns true if the corresponding values come from
651/// an unknown source (such as opaque memory or an integer cast)
652static bool isUnknownAttr(StratifiedAttrs Attr);
653
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000654/// Given an argument number, returns the appropriate StratifiedAttr to set.
655static StratifiedAttr argNumberToAttr(unsigned ArgNum);
656
657/// Given a Value, potentially return which StratifiedAttr it maps to.
658static Optional<StratifiedAttr> valueToAttr(Value *Val);
Hal Finkel7529c552014-09-02 21:43:13 +0000659
George Burgess IVcae581d2016-04-13 23:27:37 +0000660/// Gets the "Level" that one should travel in StratifiedSets
661/// given an EdgeType.
Hal Finkel7529c552014-09-02 21:43:13 +0000662static Level directionOfEdgeType(EdgeType);
663
George Burgess IVcae581d2016-04-13 23:27:37 +0000664/// Determines whether it would be pointless to add the given Value to our sets.
George Burgess IVab03af22015-03-10 02:58:15 +0000665static bool canSkipAddingToSets(Value *Val);
666
Hal Finkel7529c552014-09-02 21:43:13 +0000667static Optional<Function *> parentFunctionOfValue(Value *Val) {
668 if (auto *Inst = dyn_cast<Instruction>(Val)) {
669 auto *Bb = Inst->getParent();
670 return Bb->getParent();
671 }
672
673 if (auto *Arg = dyn_cast<Argument>(Val))
674 return Arg->getParent();
George Burgess IV77351ba32016-01-28 00:54:01 +0000675 return None;
Hal Finkel7529c552014-09-02 21:43:13 +0000676}
677
George Burgess IV24eb0da2016-06-14 18:12:28 +0000678static bool getPossibleTargets(CallSite CS,
Hal Finkel7529c552014-09-02 21:43:13 +0000679 SmallVectorImpl<Function *> &Output) {
George Burgess IV24eb0da2016-06-14 18:12:28 +0000680 if (auto *Fn = CS.getCalledFunction()) {
Hal Finkel7529c552014-09-02 21:43:13 +0000681 Output.push_back(Fn);
682 return true;
683 }
684
685 // TODO: If the call is indirect, we might be able to enumerate all potential
686 // targets of the call and return them, rather than just failing.
687 return false;
688}
689
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000690static bool isGlobalOrArgAttr(StratifiedAttrs Attr) {
691 return Attr.reset(AttrEscapedIndex).reset(AttrUnknownIndex).any();
692}
693
George Burgess IV652ec4f2016-06-09 23:15:04 +0000694static bool isUnknownAttr(StratifiedAttrs Attr) {
695 return Attr.test(AttrUnknownIndex);
696}
697
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000698static Optional<StratifiedAttr> valueToAttr(Value *Val) {
Hal Finkel7529c552014-09-02 21:43:13 +0000699 if (isa<GlobalValue>(Val))
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000700 return AttrGlobal;
Hal Finkel7529c552014-09-02 21:43:13 +0000701
702 if (auto *Arg = dyn_cast<Argument>(Val))
Daniel Berlin16f7a522015-01-26 17:31:17 +0000703 // Only pointer arguments should have the argument attribute,
704 // because things can't escape through scalars without us seeing a
705 // cast, and thus, interaction with them doesn't matter.
706 if (!Arg->hasNoAliasAttr() && Arg->getType()->isPointerTy())
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000707 return argNumberToAttr(Arg->getArgNo());
George Burgess IV77351ba32016-01-28 00:54:01 +0000708 return None;
Hal Finkel7529c552014-09-02 21:43:13 +0000709}
710
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000711static StratifiedAttr argNumberToAttr(unsigned ArgNum) {
George Burgess IV3c898c22015-01-21 16:37:21 +0000712 if (ArgNum >= AttrMaxNumArgs)
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000713 return AttrUnknown;
714 return 1 << (ArgNum + AttrFirstArgIndex);
Hal Finkel7529c552014-09-02 21:43:13 +0000715}
716
Hal Finkel7529c552014-09-02 21:43:13 +0000717static Level directionOfEdgeType(EdgeType Weight) {
718 switch (Weight) {
719 case EdgeType::Reference:
720 return Level::Above;
721 case EdgeType::Dereference:
722 return Level::Below;
723 case EdgeType::Assign:
724 return Level::Same;
725 }
726 llvm_unreachable("Incomplete switch coverage");
727}
728
George Burgess IVab03af22015-03-10 02:58:15 +0000729static bool canSkipAddingToSets(Value *Val) {
730 // Constants can share instances, which may falsely unify multiple
731 // sets, e.g. in
732 // store i32* null, i32** %ptr1
733 // store i32* null, i32** %ptr2
734 // clearly ptr1 and ptr2 should not be unified into the same set, so
735 // we should filter out the (potentially shared) instance to
736 // i32* null.
737 if (isa<Constant>(Val)) {
George Burgess IVab03af22015-03-10 02:58:15 +0000738 // TODO: Because all of these things are constant, we can determine whether
739 // the data is *actually* mutable at graph building time. This will probably
740 // come for free/cheap with offset awareness.
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +0000741 bool CanStoreMutableData = isa<GlobalValue>(Val) ||
742 isa<ConstantExpr>(Val) ||
743 isa<ConstantAggregate>(Val);
George Burgess IVab03af22015-03-10 02:58:15 +0000744 return !CanStoreMutableData;
745 }
746
747 return false;
Hal Finkel7529c552014-09-02 21:43:13 +0000748}
749
George Burgess IV87b2e412016-06-20 23:10:56 +0000750CFLAAResult::FunctionInfo::FunctionInfo(Function &Fn,
751 const SmallVectorImpl<Value *> &RetVals,
752 StratifiedSets<Value *> S)
753 : Sets(std::move(S)) {
George Burgess IV1f99da52016-06-23 18:55:23 +0000754 // Historically, an arbitrary upper-bound of 50 args was selected. We may want
755 // to remove this if it doesn't really matter in practice.
756 if (Fn.arg_size() > MaxSupportedArgsInSummary)
757 return;
George Burgess IV87b2e412016-06-20 23:10:56 +0000758
George Burgess IV1f99da52016-06-23 18:55:23 +0000759 DenseMap<StratifiedIndex, InterfaceValue> InterfaceMap;
George Burgess IV87b2e412016-06-20 23:10:56 +0000760
George Burgess IV1f99da52016-06-23 18:55:23 +0000761 // Our intention here is to record all InterfaceValues that share the same
762 // StratifiedIndex in RetParamRelations. For each valid InterfaceValue, we
763 // have its StratifiedIndex scanned here and check if the index is presented
764 // in InterfaceMap: if it is not, we add the correspondence to the map;
765 // otherwise, an aliasing relation is found and we add it to
766 // RetParamRelations.
767 auto AddToRetParamRelations = [this, &InterfaceMap](
768 unsigned InterfaceIndex, StratifiedIndex SetIndex) {
769 unsigned Level = 0;
770 while (true) {
771 InterfaceValue CurrValue{InterfaceIndex, Level};
George Burgess IV87b2e412016-06-20 23:10:56 +0000772
George Burgess IV1f99da52016-06-23 18:55:23 +0000773 auto Itr = InterfaceMap.find(SetIndex);
774 if (Itr != InterfaceMap.end()) {
775 if (CurrValue != Itr->second)
776 RetParamRelations.push_back(ExternalRelation{CurrValue, Itr->second});
777 break;
778 } else
779 InterfaceMap.insert(std::make_pair(SetIndex, CurrValue));
George Burgess IV87b2e412016-06-20 23:10:56 +0000780
George Burgess IV1f99da52016-06-23 18:55:23 +0000781 auto &Link = Sets.getLink(SetIndex);
782 if (!Link.hasBelow())
783 break;
George Burgess IV87b2e412016-06-20 23:10:56 +0000784
George Burgess IV1f99da52016-06-23 18:55:23 +0000785 ++Level;
786 SetIndex = Link.Below;
George Burgess IV87b2e412016-06-20 23:10:56 +0000787 }
George Burgess IV1f99da52016-06-23 18:55:23 +0000788 };
789
790 // Populate RetParamRelations for return values
791 for (auto *RetVal : RetVals) {
792 auto RetInfo = Sets.find(RetVal);
793 if (RetInfo.hasValue())
794 AddToRetParamRelations(0, RetInfo->Index);
795 }
796
797 // Populate RetParamRelations for parameters
798 unsigned I = 0;
799 for (auto &Param : Fn.args()) {
800 if (Param.getType()->isPointerTy()) {
801 auto ParamInfo = Sets.find(&Param);
802 if (ParamInfo.hasValue())
803 AddToRetParamRelations(I + 1, ParamInfo->Index);
804 }
805 ++I;
George Burgess IV87b2e412016-06-20 23:10:56 +0000806 }
807}
808
Chandler Carruth8b046a42015-08-14 02:42:20 +0000809// Builds the graph + StratifiedSets for a function.
Chandler Carruth7b560d42015-09-09 17:55:00 +0000810CFLAAResult::FunctionInfo CFLAAResult::buildSetsFrom(Function *Fn) {
George Burgess IVe17756e2016-06-14 18:02:27 +0000811 CFLGraphBuilder GraphBuilder(*this, TLI, *Fn);
812 StratifiedSetsBuilder<Value *> SetBuilder;
Hal Finkel7529c552014-09-02 21:43:13 +0000813
George Burgess IVe17756e2016-06-14 18:02:27 +0000814 auto &Graph = GraphBuilder.getCFLGraph();
George Burgess IVdc96feb2016-06-13 19:21:18 +0000815 SmallVector<Value *, 16> Worklist;
George Burgess IVdc96feb2016-06-13 19:21:18 +0000816 for (auto Node : Graph.nodes())
817 Worklist.push_back(Node);
818
819 while (!Worklist.empty()) {
820 auto *CurValue = Worklist.pop_back_val();
George Burgess IVe17756e2016-06-14 18:02:27 +0000821 SetBuilder.add(CurValue);
George Burgess IVdc96feb2016-06-13 19:21:18 +0000822 if (canSkipAddingToSets(CurValue))
823 continue;
824
George Burgess IV259d9012016-06-15 20:43:41 +0000825 auto Attr = Graph.attrFor(CurValue);
826 SetBuilder.noteAttributes(CurValue, Attr);
827
George Burgess IVdc96feb2016-06-13 19:21:18 +0000828 for (const auto &Edge : Graph.edgesFor(CurValue)) {
829 auto Label = Edge.Type;
830 auto *OtherValue = Edge.Other;
831
832 if (canSkipAddingToSets(OtherValue))
Hal Finkel7529c552014-09-02 21:43:13 +0000833 continue;
834
George Burgess IVdc96feb2016-06-13 19:21:18 +0000835 bool Added;
836 switch (directionOfEdgeType(Label)) {
837 case Level::Above:
George Burgess IVe17756e2016-06-14 18:02:27 +0000838 Added = SetBuilder.addAbove(CurValue, OtherValue);
George Burgess IVdc96feb2016-06-13 19:21:18 +0000839 break;
840 case Level::Below:
George Burgess IVe17756e2016-06-14 18:02:27 +0000841 Added = SetBuilder.addBelow(CurValue, OtherValue);
George Burgess IVdc96feb2016-06-13 19:21:18 +0000842 break;
843 case Level::Same:
George Burgess IVe17756e2016-06-14 18:02:27 +0000844 Added = SetBuilder.addWith(CurValue, OtherValue);
George Burgess IVdc96feb2016-06-13 19:21:18 +0000845 break;
Hal Finkel7529c552014-09-02 21:43:13 +0000846 }
George Burgess IVdc96feb2016-06-13 19:21:18 +0000847
George Burgess IVdc96feb2016-06-13 19:21:18 +0000848 if (Added)
849 Worklist.push_back(OtherValue);
Hal Finkel7529c552014-09-02 21:43:13 +0000850 }
851 }
852
George Burgess IV652ec4f2016-06-09 23:15:04 +0000853 // Special handling for globals and arguments
George Burgess IV24eb0da2016-06-14 18:12:28 +0000854 for (auto *External : GraphBuilder.getExternalValues()) {
855 SetBuilder.add(External);
856 auto Attr = valueToAttr(External);
George Burgess IV652ec4f2016-06-09 23:15:04 +0000857 if (Attr.hasValue()) {
George Burgess IV24eb0da2016-06-14 18:12:28 +0000858 SetBuilder.noteAttributes(External, *Attr);
859 SetBuilder.addAttributesBelow(External, AttrUnknown);
George Burgess IV652ec4f2016-06-09 23:15:04 +0000860 }
George Burgess IV24eb0da2016-06-14 18:12:28 +0000861 }
George Burgess IVab03af22015-03-10 02:58:15 +0000862
George Burgess IV1f99da52016-06-23 18:55:23 +0000863 // Special handling for interprocedural aliases
864 for (auto &Edge : GraphBuilder.getInterprocEdges()) {
865 auto FromVal = Edge.From.Value;
866 auto ToVal = Edge.To.Value;
867 SetBuilder.add(FromVal);
868 SetBuilder.add(ToVal);
869 SetBuilder.addBelowWith(FromVal, Edge.From.DerefLevel, ToVal,
870 Edge.To.DerefLevel);
871 }
872
873 // Special handling for opaque external functions
George Burgess IV24eb0da2016-06-14 18:12:28 +0000874 for (auto *Escape : GraphBuilder.getEscapedValues()) {
875 SetBuilder.add(Escape);
876 SetBuilder.noteAttributes(Escape, AttrEscaped);
877 SetBuilder.addAttributesBelow(Escape, AttrUnknown);
878 }
Hal Finkel7529c552014-09-02 21:43:13 +0000879
George Burgess IV87b2e412016-06-20 23:10:56 +0000880 return FunctionInfo(*Fn, GraphBuilder.getReturnValues(), SetBuilder.build());
Hal Finkel7529c552014-09-02 21:43:13 +0000881}
882
Chandler Carruth7b560d42015-09-09 17:55:00 +0000883void CFLAAResult::scan(Function *Fn) {
Hal Finkel8d1590d2014-09-02 22:52:30 +0000884 auto InsertPair = Cache.insert(std::make_pair(Fn, Optional<FunctionInfo>()));
Hal Finkel7529c552014-09-02 21:43:13 +0000885 (void)InsertPair;
886 assert(InsertPair.second &&
887 "Trying to scan a function that has already been cached");
888
George Burgess IV6edb8912016-05-02 18:09:19 +0000889 // Note that we can't do Cache[Fn] = buildSetsFrom(Fn) here: the function call
890 // may get evaluated after operator[], potentially triggering a DenseMap
891 // resize and invalidating the reference returned by operator[]
892 auto FunInfo = buildSetsFrom(Fn);
893 Cache[Fn] = std::move(FunInfo);
894
Hal Finkel7529c552014-09-02 21:43:13 +0000895 Handles.push_front(FunctionHandle(Fn, this));
896}
897
Chandler Carruth7b560d42015-09-09 17:55:00 +0000898void CFLAAResult::evict(Function *Fn) { Cache.erase(Fn); }
Chandler Carruth8b046a42015-08-14 02:42:20 +0000899
George Burgess IVcae581d2016-04-13 23:27:37 +0000900/// Ensures that the given function is available in the cache, and returns the
901/// entry.
Chandler Carruth7b560d42015-09-09 17:55:00 +0000902const Optional<CFLAAResult::FunctionInfo> &
903CFLAAResult::ensureCached(Function *Fn) {
Chandler Carruth8b046a42015-08-14 02:42:20 +0000904 auto Iter = Cache.find(Fn);
905 if (Iter == Cache.end()) {
906 scan(Fn);
907 Iter = Cache.find(Fn);
908 assert(Iter != Cache.end());
909 assert(Iter->second.hasValue());
910 }
911 return Iter->second;
912}
913
Chandler Carruth7b560d42015-09-09 17:55:00 +0000914AliasResult CFLAAResult::query(const MemoryLocation &LocA,
915 const MemoryLocation &LocB) {
Hal Finkel7529c552014-09-02 21:43:13 +0000916 auto *ValA = const_cast<Value *>(LocA.Ptr);
917 auto *ValB = const_cast<Value *>(LocB.Ptr);
918
George Burgess IV259d9012016-06-15 20:43:41 +0000919 if (!ValA->getType()->isPointerTy() || !ValB->getType()->isPointerTy())
920 return NoAlias;
921
Hal Finkel7529c552014-09-02 21:43:13 +0000922 Function *Fn = nullptr;
923 auto MaybeFnA = parentFunctionOfValue(ValA);
924 auto MaybeFnB = parentFunctionOfValue(ValB);
925 if (!MaybeFnA.hasValue() && !MaybeFnB.hasValue()) {
George Burgess IVcae581d2016-04-13 23:27:37 +0000926 // The only times this is known to happen are when globals + InlineAsm are
927 // involved
George Burgess IV33305e72015-02-12 03:07:07 +0000928 DEBUG(dbgs() << "CFLAA: could not extract parent function information.\n");
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000929 return MayAlias;
Hal Finkel7529c552014-09-02 21:43:13 +0000930 }
931
932 if (MaybeFnA.hasValue()) {
933 Fn = *MaybeFnA;
934 assert((!MaybeFnB.hasValue() || *MaybeFnB == *MaybeFnA) &&
935 "Interprocedural queries not supported");
936 } else {
937 Fn = *MaybeFnB;
938 }
939
940 assert(Fn != nullptr);
941 auto &MaybeInfo = ensureCached(Fn);
942 assert(MaybeInfo.hasValue());
943
George Burgess IV87b2e412016-06-20 23:10:56 +0000944 auto &Sets = MaybeInfo->getStratifiedSets();
Hal Finkel7529c552014-09-02 21:43:13 +0000945 auto MaybeA = Sets.find(ValA);
946 if (!MaybeA.hasValue())
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000947 return MayAlias;
Hal Finkel7529c552014-09-02 21:43:13 +0000948
949 auto MaybeB = Sets.find(ValB);
950 if (!MaybeB.hasValue())
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000951 return MayAlias;
Hal Finkel7529c552014-09-02 21:43:13 +0000952
953 auto SetA = *MaybeA;
954 auto SetB = *MaybeB;
Hal Finkel7529c552014-09-02 21:43:13 +0000955 auto AttrsA = Sets.getLink(SetA.Index).Attrs;
956 auto AttrsB = Sets.getLink(SetB.Index).Attrs;
George Burgess IV33305e72015-02-12 03:07:07 +0000957
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000958 // If both values are local (meaning the corresponding set has attribute
959 // AttrNone or AttrEscaped), then we know that CFLAA fully models them: they
960 // may-alias each other if and only if they are in the same set
961 // If at least one value is non-local (meaning it either is global/argument or
962 // it comes from unknown sources like integer cast), the situation becomes a
963 // bit more interesting. We follow three general rules described below:
964 // - Non-local values may alias each other
965 // - AttrNone values do not alias any non-local values
George Burgess IV652ec4f2016-06-09 23:15:04 +0000966 // - AttrEscaped do not alias globals/arguments, but they may alias
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000967 // AttrUnknown values
968 if (SetA.Index == SetB.Index)
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000969 return MayAlias;
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000970 if (AttrsA.none() || AttrsB.none())
971 return NoAlias;
George Burgess IV652ec4f2016-06-09 23:15:04 +0000972 if (isUnknownAttr(AttrsA) || isUnknownAttr(AttrsB))
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000973 return MayAlias;
974 if (isGlobalOrArgAttr(AttrsA) && isGlobalOrArgAttr(AttrsB))
975 return MayAlias;
976 return NoAlias;
Hal Finkel7529c552014-09-02 21:43:13 +0000977}
Mehdi Amini46a43552015-03-04 18:43:29 +0000978
Chandler Carruthb4faf132016-03-11 10:22:49 +0000979char CFLAA::PassID;
980
Chandler Carruthb47f8012016-03-11 11:05:24 +0000981CFLAAResult CFLAA::run(Function &F, AnalysisManager<Function> &AM) {
George Burgess IV18b83fe2016-06-01 18:39:54 +0000982 return CFLAAResult(AM.getResult<TargetLibraryAnalysis>(F));
Chandler Carruth7b560d42015-09-09 17:55:00 +0000983}
984
Chandler Carruth7b560d42015-09-09 17:55:00 +0000985char CFLAAWrapperPass::ID = 0;
Chandler Carruth12884f72016-03-02 15:56:53 +0000986INITIALIZE_PASS(CFLAAWrapperPass, "cfl-aa", "CFL-Based Alias Analysis", false,
987 true)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000988
989ImmutablePass *llvm::createCFLAAWrapperPass() { return new CFLAAWrapperPass(); }
990
991CFLAAWrapperPass::CFLAAWrapperPass() : ImmutablePass(ID) {
992 initializeCFLAAWrapperPassPass(*PassRegistry::getPassRegistry());
993}
994
George Burgess IV18b83fe2016-06-01 18:39:54 +0000995void CFLAAWrapperPass::initializePass() {
996 auto &TLIWP = getAnalysis<TargetLibraryInfoWrapperPass>();
997 Result.reset(new CFLAAResult(TLIWP.getTLI()));
Chandler Carruth7b560d42015-09-09 17:55:00 +0000998}
999
1000void CFLAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
1001 AU.setPreservesAll();
George Burgess IV18b83fe2016-06-01 18:39:54 +00001002 AU.addRequired<TargetLibraryInfoWrapperPass>();
Mehdi Amini46a43552015-03-04 18:43:29 +00001003}