blob: 15d09ab4b9f6f924aecd7cc098d23b90077edc3a [file] [log] [blame]
Dan Gohmanda85ed82010-10-19 23:09:08 +00001//===- BasicAliasAnalysis.cpp - Stateless Alias Analysis Impl -------------===//
Misha Brukman01808ca2005-04-21 21:13:18 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman01808ca2005-04-21 21:13:18 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerd6a2a992003-02-26 19:41:54 +00009//
Dan Gohmanda85ed82010-10-19 23:09:08 +000010// This file defines the primary stateless implementation of the
11// Alias Analysis interface that implements identities (two different
12// globals cannot alias, etc), but does no stateful analysis.
Chris Lattnerd6a2a992003-02-26 19:41:54 +000013//
14//===----------------------------------------------------------------------===//
15
Chandler Carruth17e0bc32015-08-06 07:33:15 +000016#include "llvm/Analysis/BasicAliasAnalysis.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/SmallVector.h"
Wei Mid67daae2015-08-05 23:40:30 +000018#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/Analysis/AliasAnalysis.h"
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +000020#include "llvm/Analysis/CFG.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000021#include "llvm/Analysis/CaptureTracking.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/Analysis/InstructionSimplify.h"
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +000023#include "llvm/Analysis/LoopInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/Analysis/MemoryBuiltins.h"
25#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Constants.h"
27#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000029#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/GlobalAlias.h"
31#include "llvm/IR/GlobalVariable.h"
32#include "llvm/IR/Instructions.h"
33#include "llvm/IR/IntrinsicInst.h"
34#include "llvm/IR/LLVMContext.h"
35#include "llvm/IR/Operator.h"
Chris Lattnerd82256a2004-03-15 03:36:49 +000036#include "llvm/Pass.h"
Torok Edwin56d06592009-07-11 20:10:48 +000037#include "llvm/Support/ErrorHandling.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000038#include <algorithm>
Chris Lattner35997482003-11-25 18:33:40 +000039using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000040
Tobias Edler von Kochd8ce16b2015-07-15 19:32:22 +000041/// Enable analysis of recursive PHI nodes.
42static cl::opt<bool> EnableRecPhiAnalysis("basicaa-recphi",
43 cl::Hidden, cl::init(false));
44
Wei Mid67daae2015-08-05 23:40:30 +000045/// SearchLimitReached / SearchTimes shows how often the limit of
46/// to decompose GEPs is reached. It will affect the precision
47/// of basic alias analysis.
48#define DEBUG_TYPE "basicaa"
49STATISTIC(SearchLimitReached, "Number of times the limit to "
50 "decompose GEPs is reached");
51STATISTIC(SearchTimes, "Number of times a GEP is decomposed");
52
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +000053/// Cutoff after which to stop analysing a set of phi nodes potentially involved
54/// in a cycle. Because we are analysing 'through' phi nodes we need to be
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +000055/// careful with value equivalence. We use reachability to make sure a value
56/// cannot be involved in a cycle.
57const unsigned MaxNumPhiBBsValueReachabilityCheck = 20;
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +000058
Arnold Schwaighofer1a444482014-03-26 21:30:19 +000059// The max limit of the search depth in DecomposeGEPExpression() and
60// GetUnderlyingObject(), both functions need to use the same search
61// depth otherwise the algorithm in aliasGEP will assert.
62static const unsigned MaxLookupSearchDepth = 6;
63
Chris Lattner2d332972008-06-16 06:30:22 +000064//===----------------------------------------------------------------------===//
65// Useful predicates
66//===----------------------------------------------------------------------===//
Devang Patel09f162c2007-05-01 21:15:47 +000067
Chris Lattnerb35d9b52008-06-16 06:19:11 +000068/// isNonEscapingLocalObject - Return true if the pointer is to a function-local
69/// object that never escapes from the function.
Dan Gohman84f90a32010-07-01 20:08:40 +000070static bool isNonEscapingLocalObject(const Value *V) {
Chris Lattnerfa482582008-06-16 06:28:01 +000071 // If this is a local allocation, check to see if it escapes.
Dan Gohman84f90a32010-07-01 20:08:40 +000072 if (isa<AllocaInst>(V) || isNoAliasCall(V))
Dan Gohman94e61762009-11-19 21:57:48 +000073 // Set StoreCaptures to True so that we can assume in our callers that the
74 // pointer is not the result of a load instruction. Currently
75 // PointerMayBeCaptured doesn't have any special analysis for the
76 // StoreCaptures=false case; if it did, our callers could be refined to be
77 // more precise.
78 return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
Duncan Sands8d65f362009-01-05 21:19:53 +000079
Chris Lattnerfa482582008-06-16 06:28:01 +000080 // If this is an argument that corresponds to a byval or noalias argument,
Duncan Sands8d65f362009-01-05 21:19:53 +000081 // then it has not escaped before entering the function. Check if it escapes
82 // inside the function.
Dan Gohman84f90a32010-07-01 20:08:40 +000083 if (const Argument *A = dyn_cast<Argument>(V))
Richard Osbornea1fffcf2012-11-05 10:48:24 +000084 if (A->hasByValAttr() || A->hasNoAliasAttr())
85 // Note even if the argument is marked nocapture we still need to check
86 // for copies made inside the function. The nocapture attribute only
87 // specifies that there are no copies made that outlive the function.
Dan Gohman84f90a32010-07-01 20:08:40 +000088 return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
Richard Osbornea1fffcf2012-11-05 10:48:24 +000089
Chris Lattnerb35d9b52008-06-16 06:19:11 +000090 return false;
91}
92
Dan Gohman0824aff2010-06-29 00:50:39 +000093/// isEscapeSource - Return true if the pointer is one which would have
94/// been considered an escape by isNonEscapingLocalObject.
Dan Gohman84f90a32010-07-01 20:08:40 +000095static bool isEscapeSource(const Value *V) {
96 if (isa<CallInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V))
97 return true;
Dan Gohman0824aff2010-06-29 00:50:39 +000098
99 // The load case works because isNonEscapingLocalObject considers all
100 // stores to be escapes (it passes true for the StoreCaptures argument
101 // to PointerMayBeCaptured).
102 if (isa<LoadInst>(V))
103 return true;
104
105 return false;
106}
Chris Lattnerb35d9b52008-06-16 06:19:11 +0000107
Dan Gohman44da55b2011-01-18 21:16:06 +0000108/// getObjectSize - Return the size of the object specified by V, or
109/// UnknownSize if unknown.
Rafael Espindola5f57f462014-02-21 18:34:28 +0000110static uint64_t getObjectSize(const Value *V, const DataLayout &DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000111 const TargetLibraryInfo &TLI,
Eli Friedman8bc169c2012-02-27 20:46:07 +0000112 bool RoundToAlign = false) {
Nuno Lopes55fff832012-06-21 15:45:28 +0000113 uint64_t Size;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000114 if (getObjectSize(V, Size, DL, &TLI, RoundToAlign))
Nuno Lopes55fff832012-06-21 15:45:28 +0000115 return Size;
Chandler Carruthecbd1682015-06-17 07:21:38 +0000116 return MemoryLocation::UnknownSize;
Dan Gohman44da55b2011-01-18 21:16:06 +0000117}
118
119/// isObjectSmallerThan - Return true if we can prove that the object specified
120/// by V is smaller than Size.
121static bool isObjectSmallerThan(const Value *V, uint64_t Size,
Rafael Espindola5f57f462014-02-21 18:34:28 +0000122 const DataLayout &DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000123 const TargetLibraryInfo &TLI) {
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000124 // Note that the meanings of the "object" are slightly different in the
125 // following contexts:
126 // c1: llvm::getObjectSize()
127 // c2: llvm.objectsize() intrinsic
128 // c3: isObjectSmallerThan()
129 // c1 and c2 share the same meaning; however, the meaning of "object" in c3
130 // refers to the "entire object".
131 //
132 // Consider this example:
133 // char *p = (char*)malloc(100)
134 // char *q = p+80;
135 //
136 // In the context of c1 and c2, the "object" pointed by q refers to the
137 // stretch of memory of q[0:19]. So, getObjectSize(q) should return 20.
138 //
139 // However, in the context of c3, the "object" refers to the chunk of memory
140 // being allocated. So, the "object" has 100 bytes, and q points to the middle
141 // the "object". In case q is passed to isObjectSmallerThan() as the 1st
142 // parameter, before the llvm::getObjectSize() is called to get the size of
143 // entire object, we should:
144 // - either rewind the pointer q to the base-address of the object in
145 // question (in this case rewind to p), or
146 // - just give up. It is up to caller to make sure the pointer is pointing
147 // to the base address the object.
Jakub Staszak07f383f2013-08-24 14:16:00 +0000148 //
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000149 // We go for 2nd option for simplicity.
150 if (!isIdentifiedObject(V))
151 return false;
152
Eli Friedman8bc169c2012-02-27 20:46:07 +0000153 // This function needs to use the aligned object size because we allow
154 // reads a bit past the end given sufficient alignment.
Rafael Espindola5f57f462014-02-21 18:34:28 +0000155 uint64_t ObjectSize = getObjectSize(V, DL, TLI, /*RoundToAlign*/true);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000156
Chandler Carruthecbd1682015-06-17 07:21:38 +0000157 return ObjectSize != MemoryLocation::UnknownSize && ObjectSize < Size;
Dan Gohman44da55b2011-01-18 21:16:06 +0000158}
159
160/// isObjectSize - Return true if we can prove that the object specified
161/// by V has size Size.
162static bool isObjectSize(const Value *V, uint64_t Size,
Rafael Espindola5f57f462014-02-21 18:34:28 +0000163 const DataLayout &DL, const TargetLibraryInfo &TLI) {
164 uint64_t ObjectSize = getObjectSize(V, DL, TLI);
Chandler Carruthecbd1682015-06-17 07:21:38 +0000165 return ObjectSize != MemoryLocation::UnknownSize && ObjectSize == Size;
Chris Lattner98ad8162008-06-16 06:10:11 +0000166}
167
Chris Lattner2d332972008-06-16 06:30:22 +0000168//===----------------------------------------------------------------------===//
Chris Lattner9f7500f2010-08-18 22:07:29 +0000169// GetElementPtr Instruction Decomposition and Analysis
170//===----------------------------------------------------------------------===//
171
Chris Lattner9f7500f2010-08-18 22:07:29 +0000172/// GetLinearExpression - Analyze the specified value as a linear expression:
173/// "A*V + B", where A and B are constant integers. Return the scale and offset
Chris Lattner3decde92010-08-18 23:09:49 +0000174/// values as APInts and return V as a Value*, and return whether we looked
175/// through any sign or zero extends. The incoming Value is known to have
176/// IntegerType and it may already be sign or zero extended.
177///
178/// Note that this looks through extends, so the high bits may not be
179/// represented in the result.
Chandler Carruth17e0bc32015-08-06 07:33:15 +0000180/*static*/ Value *BasicAliasAnalysis::GetLinearExpression(
181 Value *V, APInt &Scale, APInt &Offset, ExtensionKind &Extension,
182 const DataLayout &DL, unsigned Depth, AssumptionCache *AC,
183 DominatorTree *DT) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000184 assert(V->getType()->isIntegerTy() && "Not an integer value");
185
186 // Limit our recursion depth.
187 if (Depth == 6) {
188 Scale = 1;
189 Offset = 0;
190 return V;
191 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000192
Manuel Klimek779cf852015-07-13 13:50:55 +0000193 if (ConstantInt *Const = dyn_cast<ConstantInt>(V)) {
194 // if it's a constant, just convert it to an offset
195 // and remove the variable.
196 Offset += Const->getValue();
Hal Finkel45ba2c12014-11-13 09:16:54 +0000197 assert(Scale == 0 && "Constant values don't have a scale");
198 return V;
199 }
200
Manuel Klimek779cf852015-07-13 13:50:55 +0000201 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(V)) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000202 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
203 switch (BOp->getOpcode()) {
Manuel Klimek779cf852015-07-13 13:50:55 +0000204 default: break;
Chris Lattner9f7500f2010-08-18 22:07:29 +0000205 case Instruction::Or:
206 // X|C == X+C if all the bits in C are unset in X. Otherwise we can't
207 // analyze it.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000208 if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), DL, 0, AC,
Chandler Carruth66b31302015-01-04 12:03:27 +0000209 BOp, DT))
Chris Lattner9f7500f2010-08-18 22:07:29 +0000210 break;
211 // FALL THROUGH.
212 case Instruction::Add:
Manuel Klimek779cf852015-07-13 13:50:55 +0000213 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
214 DL, Depth + 1, AC, DT);
215 Offset += RHSC->getValue();
216 return V;
Chris Lattner9f7500f2010-08-18 22:07:29 +0000217 case Instruction::Mul:
Manuel Klimek779cf852015-07-13 13:50:55 +0000218 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
219 DL, Depth + 1, AC, DT);
220 Offset *= RHSC->getValue();
221 Scale *= RHSC->getValue();
222 return V;
Chris Lattner9f7500f2010-08-18 22:07:29 +0000223 case Instruction::Shl:
Manuel Klimek779cf852015-07-13 13:50:55 +0000224 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
225 DL, Depth + 1, AC, DT);
226 Offset <<= RHSC->getValue().getLimitedValue();
227 Scale <<= RHSC->getValue().getLimitedValue();
Chris Lattner9f7500f2010-08-18 22:07:29 +0000228 return V;
229 }
230 }
231 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000232
Chris Lattner9f7500f2010-08-18 22:07:29 +0000233 // Since GEP indices are sign extended anyway, we don't care about the high
Chris Lattner3decde92010-08-18 23:09:49 +0000234 // bits of a sign or zero extended value - just scales and offsets. The
235 // extensions have to be consistent though.
Manuel Klimek779cf852015-07-13 13:50:55 +0000236 if ((isa<SExtInst>(V) && Extension != EK_ZeroExt) ||
237 (isa<ZExtInst>(V) && Extension != EK_SignExt)) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000238 Value *CastOp = cast<CastInst>(V)->getOperand(0);
Manuel Klimek779cf852015-07-13 13:50:55 +0000239 unsigned OldWidth = Scale.getBitWidth();
Chris Lattner9f7500f2010-08-18 22:07:29 +0000240 unsigned SmallWidth = CastOp->getType()->getPrimitiveSizeInBits();
Manuel Klimek779cf852015-07-13 13:50:55 +0000241 Scale = Scale.trunc(SmallWidth);
242 Offset = Offset.trunc(SmallWidth);
243 Extension = isa<SExtInst>(V) ? EK_SignExt : EK_ZeroExt;
Chris Lattner3decde92010-08-18 23:09:49 +0000244
Manuel Klimek779cf852015-07-13 13:50:55 +0000245 Value *Result = GetLinearExpression(CastOp, Scale, Offset, Extension, DL,
246 Depth + 1, AC, DT);
247 Scale = Scale.zext(OldWidth);
Hal Finkel45ba2c12014-11-13 09:16:54 +0000248
Manuel Klimek779cf852015-07-13 13:50:55 +0000249 // We have to sign-extend even if Extension == EK_ZeroExt as we can't
250 // decompose a sign extension (i.e. zext(x - 1) != zext(x) - zext(-1)).
251 Offset = Offset.sext(OldWidth);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000252
Chris Lattner9f7500f2010-08-18 22:07:29 +0000253 return Result;
254 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000255
Chris Lattner9f7500f2010-08-18 22:07:29 +0000256 Scale = 1;
257 Offset = 0;
258 return V;
259}
260
261/// DecomposeGEPExpression - If V is a symbolic pointer expression, decompose it
262/// into a base pointer with a constant offset and a number of scaled symbolic
263/// offsets.
264///
265/// The scaled symbolic offsets (represented by pairs of a Value* and a scale in
266/// the VarIndices vector) are Value*'s that are known to be scaled by the
267/// specified amount, but which may have other unrepresented high bits. As such,
268/// the gep cannot necessarily be reconstructed from its decomposed form.
269///
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000270/// When DataLayout is around, this function is capable of analyzing everything
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000271/// that GetUnderlyingObject can look through. To be able to do that
272/// GetUnderlyingObject and DecomposeGEPExpression must use the same search
273/// depth (MaxLookupSearchDepth).
274/// When DataLayout not is around, it just looks through pointer casts.
Chris Lattner9f7500f2010-08-18 22:07:29 +0000275///
Chandler Carruth17e0bc32015-08-06 07:33:15 +0000276/*static*/ const Value *BasicAliasAnalysis::DecomposeGEPExpression(
277 const Value *V, int64_t &BaseOffs,
278 SmallVectorImpl<VariableGEPIndex> &VarIndices, bool &MaxLookupReached,
279 const DataLayout &DL, AssumptionCache *AC, DominatorTree *DT) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000280 // Limit recursion depth to limit compile time in crazy cases.
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000281 unsigned MaxLookup = MaxLookupSearchDepth;
282 MaxLookupReached = false;
Wei Mid67daae2015-08-05 23:40:30 +0000283 SearchTimes++;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000284
Chris Lattner9f7500f2010-08-18 22:07:29 +0000285 BaseOffs = 0;
286 do {
287 // See if this is a bitcast or GEP.
288 const Operator *Op = dyn_cast<Operator>(V);
Craig Topper9f008862014-04-15 04:59:12 +0000289 if (!Op) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000290 // The only non-operator case we can handle are GlobalAliases.
291 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
292 if (!GA->mayBeOverridden()) {
293 V = GA->getAliasee();
294 continue;
295 }
296 }
297 return V;
298 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000299
Matt Arsenault70f4db882014-07-15 00:56:40 +0000300 if (Op->getOpcode() == Instruction::BitCast ||
301 Op->getOpcode() == Instruction::AddrSpaceCast) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000302 V = Op->getOperand(0);
303 continue;
304 }
Dan Gohman05b18f12010-12-15 20:49:55 +0000305
Chris Lattner9f7500f2010-08-18 22:07:29 +0000306 const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
Craig Topper9f008862014-04-15 04:59:12 +0000307 if (!GEPOp) {
Dan Gohman0573b552011-05-24 18:24:08 +0000308 // If it's not a GEP, hand it off to SimplifyInstruction to see if it
309 // can come up with something. This matches what GetUnderlyingObject does.
310 if (const Instruction *I = dyn_cast<Instruction>(V))
Chandler Carruth66b31302015-01-04 12:03:27 +0000311 // TODO: Get a DominatorTree and AssumptionCache and use them here
Hal Finkel60db0582014-09-07 18:57:58 +0000312 // (these are both now available in this function, but this should be
313 // updated when GetUnderlyingObject is updated). TLI should be
314 // provided also.
Dan Gohman0573b552011-05-24 18:24:08 +0000315 if (const Value *Simplified =
Rafael Espindola5f57f462014-02-21 18:34:28 +0000316 SimplifyInstruction(const_cast<Instruction *>(I), DL)) {
Dan Gohman0573b552011-05-24 18:24:08 +0000317 V = Simplified;
318 continue;
319 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000320
Chris Lattner9f7500f2010-08-18 22:07:29 +0000321 return V;
Dan Gohman0573b552011-05-24 18:24:08 +0000322 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000323
Chris Lattner9f7500f2010-08-18 22:07:29 +0000324 // Don't attempt to analyze GEPs over unsized objects.
Matt Arsenaultfa252722013-09-27 22:18:51 +0000325 if (!GEPOp->getOperand(0)->getType()->getPointerElementType()->isSized())
Chris Lattner9f7500f2010-08-18 22:07:29 +0000326 return V;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000327
Matt Arsenaulta8fe22b2013-11-16 00:36:43 +0000328 unsigned AS = GEPOp->getPointerAddressSpace();
Chris Lattner9f7500f2010-08-18 22:07:29 +0000329 // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
330 gep_type_iterator GTI = gep_type_begin(GEPOp);
331 for (User::const_op_iterator I = GEPOp->op_begin()+1,
332 E = GEPOp->op_end(); I != E; ++I) {
Manuel Klimek779cf852015-07-13 13:50:55 +0000333 Value *Index = *I;
Chris Lattner9f7500f2010-08-18 22:07:29 +0000334 // Compute the (potentially symbolic) offset in bytes for this index.
Chris Lattner229907c2011-07-18 04:54:35 +0000335 if (StructType *STy = dyn_cast<StructType>(*GTI++)) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000336 // For a struct, add the member offset.
337 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
338 if (FieldNo == 0) continue;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000339
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000340 BaseOffs += DL.getStructLayout(STy)->getElementOffset(FieldNo);
Chris Lattner9f7500f2010-08-18 22:07:29 +0000341 continue;
342 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000343
Chris Lattner9f7500f2010-08-18 22:07:29 +0000344 // For an array/pointer, add the element offset, explicitly scaled.
Manuel Klimek779cf852015-07-13 13:50:55 +0000345 if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000346 if (CIdx->isZero()) continue;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000347 BaseOffs += DL.getTypeAllocSize(*GTI) * CIdx->getSExtValue();
Chris Lattner9f7500f2010-08-18 22:07:29 +0000348 continue;
349 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000350
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000351 uint64_t Scale = DL.getTypeAllocSize(*GTI);
Manuel Klimek779cf852015-07-13 13:50:55 +0000352 ExtensionKind Extension = EK_NotExtended;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000353
Chris Lattner3decde92010-08-18 23:09:49 +0000354 // If the integer type is smaller than the pointer size, it is implicitly
355 // sign extended to pointer size.
Matt Arsenaultfa252722013-09-27 22:18:51 +0000356 unsigned Width = Index->getType()->getIntegerBitWidth();
Manuel Klimek779cf852015-07-13 13:50:55 +0000357 if (DL.getPointerSizeInBits(AS) > Width)
358 Extension = EK_SignExt;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000359
Chris Lattner3decde92010-08-18 23:09:49 +0000360 // Use GetLinearExpression to decompose the index into a C1*V+C2 form.
Chris Lattner9f7500f2010-08-18 22:07:29 +0000361 APInt IndexScale(Width, 0), IndexOffset(Width, 0);
Manuel Klimek779cf852015-07-13 13:50:55 +0000362 Index = GetLinearExpression(Index, IndexScale, IndexOffset, Extension, DL,
363 0, AC, DT);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000364
Chris Lattner9f7500f2010-08-18 22:07:29 +0000365 // The GEP index scale ("Scale") scales C1*V+C2, yielding (C1*V+C2)*Scale.
366 // This gives us an aggregate computation of (C1*Scale)*V + C2*Scale.
Eli Friedmanab3a1282010-09-15 20:08:03 +0000367 BaseOffs += IndexOffset.getSExtValue()*Scale;
368 Scale *= IndexScale.getSExtValue();
Jakub Staszak07f383f2013-08-24 14:16:00 +0000369
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000370 // If we already had an occurrence of this index variable, merge this
Chris Lattner9f7500f2010-08-18 22:07:29 +0000371 // scale into it. For example, we want to handle:
372 // A[x][x] -> x*16 + x*4 -> x*20
373 // This also ensures that 'x' only appears in the index list once.
374 for (unsigned i = 0, e = VarIndices.size(); i != e; ++i) {
Manuel Klimek779cf852015-07-13 13:50:55 +0000375 if (VarIndices[i].V == Index &&
376 VarIndices[i].Extension == Extension) {
Chris Lattner1b9c3872010-08-18 22:47:56 +0000377 Scale += VarIndices[i].Scale;
Chris Lattner9f7500f2010-08-18 22:07:29 +0000378 VarIndices.erase(VarIndices.begin()+i);
379 break;
380 }
381 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000382
Chris Lattner9f7500f2010-08-18 22:07:29 +0000383 // Make sure that we have a scale that makes sense for this target's
384 // pointer size.
Manuel Klimek779cf852015-07-13 13:50:55 +0000385 if (unsigned ShiftBits = 64 - DL.getPointerSizeInBits(AS)) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000386 Scale <<= ShiftBits;
Eli Friedmanab3a1282010-09-15 20:08:03 +0000387 Scale = (int64_t)Scale >> ShiftBits;
Chris Lattner9f7500f2010-08-18 22:07:29 +0000388 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000389
Chris Lattner1b9c3872010-08-18 22:47:56 +0000390 if (Scale) {
Manuel Klimek779cf852015-07-13 13:50:55 +0000391 VariableGEPIndex Entry = {Index, Extension,
Jeffrey Yasskin6381c012011-07-27 06:22:51 +0000392 static_cast<int64_t>(Scale)};
Chris Lattner1b9c3872010-08-18 22:47:56 +0000393 VarIndices.push_back(Entry);
394 }
Chris Lattner9f7500f2010-08-18 22:07:29 +0000395 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000396
Chris Lattner9f7500f2010-08-18 22:07:29 +0000397 // Analyze the base pointer next.
398 V = GEPOp->getOperand(0);
399 } while (--MaxLookup);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000400
Chris Lattner9f7500f2010-08-18 22:07:29 +0000401 // If the chain of expressions is too deep, just return early.
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000402 MaxLookupReached = true;
Wei Mid67daae2015-08-05 23:40:30 +0000403 SearchLimitReached++;
Chris Lattner9f7500f2010-08-18 22:07:29 +0000404 return V;
405}
406
Chris Lattner9f7500f2010-08-18 22:07:29 +0000407//===----------------------------------------------------------------------===//
Dan Gohman0824aff2010-06-29 00:50:39 +0000408// BasicAliasAnalysis Pass
Chris Lattner2d332972008-06-16 06:30:22 +0000409//===----------------------------------------------------------------------===//
410
Chandler Carruth17e0bc32015-08-06 07:33:15 +0000411// Register the pass...
Chris Lattner2d332972008-06-16 06:30:22 +0000412char BasicAliasAnalysis::ID = 0;
Owen Anderson653cb032011-09-06 23:33:25 +0000413INITIALIZE_AG_PASS_BEGIN(BasicAliasAnalysis, AliasAnalysis, "basicaa",
Dan Gohmanda85ed82010-10-19 23:09:08 +0000414 "Basic Alias Analysis (stateless AA impl)",
Dan Gohman02538ac2010-10-18 18:04:47 +0000415 false, true, false)
Chandler Carruth66b31302015-01-04 12:03:27 +0000416INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000417INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Owen Anderson653cb032011-09-06 23:33:25 +0000418INITIALIZE_AG_PASS_END(BasicAliasAnalysis, AliasAnalysis, "basicaa",
419 "Basic Alias Analysis (stateless AA impl)",
420 false, true, false)
421
Chris Lattner2d332972008-06-16 06:30:22 +0000422ImmutablePass *llvm::createBasicAliasAnalysisPass() {
423 return new BasicAliasAnalysis();
424}
425
Dan Gohman9130bad2010-11-08 16:45:26 +0000426/// pointsToConstantMemory - Returns whether the given pointer value
427/// points to memory that is local to the function, with global constants being
428/// considered local to all functions.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000429bool BasicAliasAnalysis::pointsToConstantMemory(const MemoryLocation &Loc,
430 bool OrLocal) {
Dan Gohman9130bad2010-11-08 16:45:26 +0000431 assert(Visited.empty() && "Visited must be cleared after use!");
Chris Lattner2d332972008-06-16 06:30:22 +0000432
Dan Gohman142ff822010-11-08 20:26:19 +0000433 unsigned MaxLookup = 8;
Dan Gohman9130bad2010-11-08 16:45:26 +0000434 SmallVector<const Value *, 16> Worklist;
435 Worklist.push_back(Loc.Ptr);
436 do {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000437 const Value *V = GetUnderlyingObject(Worklist.pop_back_val(), *DL);
David Blaikie70573dc2014-11-19 07:49:26 +0000438 if (!Visited.insert(V).second) {
Dan Gohman9130bad2010-11-08 16:45:26 +0000439 Visited.clear();
440 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
441 }
Dan Gohman5f1702e2010-08-06 01:25:49 +0000442
Dan Gohman9130bad2010-11-08 16:45:26 +0000443 // An alloca instruction defines local memory.
444 if (OrLocal && isa<AllocaInst>(V))
445 continue;
446
447 // A global constant counts as local memory for our purposes.
448 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
449 // Note: this doesn't require GV to be "ODR" because it isn't legal for a
450 // global to be marked constant in some modules and non-constant in
451 // others. GV may even be a declaration, not a definition.
452 if (!GV->isConstant()) {
453 Visited.clear();
454 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
455 }
456 continue;
457 }
458
459 // If both select values point to local memory, then so does the select.
460 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
461 Worklist.push_back(SI->getTrueValue());
462 Worklist.push_back(SI->getFalseValue());
463 continue;
464 }
465
466 // If all values incoming to a phi node point to local memory, then so does
467 // the phi.
468 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
Dan Gohman142ff822010-11-08 20:26:19 +0000469 // Don't bother inspecting phi nodes with many operands.
470 if (PN->getNumIncomingValues() > MaxLookup) {
471 Visited.clear();
472 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
473 }
Pete Cooper833f34d2015-05-12 20:05:31 +0000474 for (Value *IncValue : PN->incoming_values())
475 Worklist.push_back(IncValue);
Dan Gohman9130bad2010-11-08 16:45:26 +0000476 continue;
477 }
478
479 // Otherwise be conservative.
480 Visited.clear();
481 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
482
Dan Gohman142ff822010-11-08 20:26:19 +0000483 } while (!Worklist.empty() && --MaxLookup);
Dan Gohman9130bad2010-11-08 16:45:26 +0000484
485 Visited.clear();
Dan Gohman142ff822010-11-08 20:26:19 +0000486 return Worklist.empty();
Chris Lattner2d332972008-06-16 06:30:22 +0000487}
488
Chandler Carruthc41404a2015-06-17 07:12:40 +0000489// FIXME: This code is duplicated with MemoryLocation and should be hoisted to
490// some common utility location.
Hal Finkel354e23b2014-07-17 01:28:25 +0000491static bool isMemsetPattern16(const Function *MS,
492 const TargetLibraryInfo &TLI) {
493 if (TLI.has(LibFunc::memset_pattern16) &&
494 MS->getName() == "memset_pattern16") {
495 FunctionType *MemsetType = MS->getFunctionType();
496 if (!MemsetType->isVarArg() && MemsetType->getNumParams() == 3 &&
497 isa<PointerType>(MemsetType->getParamType(0)) &&
498 isa<PointerType>(MemsetType->getParamType(1)) &&
499 isa<IntegerType>(MemsetType->getParamType(2)))
500 return true;
501 }
502
503 return false;
504}
505
Dan Gohman5f1702e2010-08-06 01:25:49 +0000506/// getModRefBehavior - Return the behavior when calling the given call site.
Chandler Carruth194f59c2015-07-22 23:15:57 +0000507FunctionModRefBehavior
Dan Gohman5f1702e2010-08-06 01:25:49 +0000508BasicAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
509 if (CS.doesNotAccessMemory())
510 // Can't do better than this.
Chandler Carruth194f59c2015-07-22 23:15:57 +0000511 return FMRB_DoesNotAccessMemory;
Dan Gohman5f1702e2010-08-06 01:25:49 +0000512
Chandler Carruth194f59c2015-07-22 23:15:57 +0000513 FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
Dan Gohman5f1702e2010-08-06 01:25:49 +0000514
515 // If the callsite knows it only reads memory, don't return worse
516 // than that.
517 if (CS.onlyReadsMemory())
Chandler Carruth194f59c2015-07-22 23:15:57 +0000518 Min = FMRB_OnlyReadsMemory;
Dan Gohman5f1702e2010-08-06 01:25:49 +0000519
Igor Laevsky39d662f2015-07-11 10:30:36 +0000520 if (CS.onlyAccessesArgMemory())
Chandler Carruth194f59c2015-07-22 23:15:57 +0000521 Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesArgumentPointees);
Igor Laevsky39d662f2015-07-11 10:30:36 +0000522
Dan Gohman5f1702e2010-08-06 01:25:49 +0000523 // The AliasAnalysis base class has some smarts, lets use them.
Chandler Carruth194f59c2015-07-22 23:15:57 +0000524 return FunctionModRefBehavior(AliasAnalysis::getModRefBehavior(CS) & Min);
Dan Gohman5f1702e2010-08-06 01:25:49 +0000525}
526
527/// getModRefBehavior - Return the behavior when calling the given function.
528/// For use when the call site is not known.
Chandler Carruth194f59c2015-07-22 23:15:57 +0000529FunctionModRefBehavior
Dan Gohman5f1702e2010-08-06 01:25:49 +0000530BasicAliasAnalysis::getModRefBehavior(const Function *F) {
Dan Gohmane461d7d2010-11-08 16:08:43 +0000531 // If the function declares it doesn't access memory, we can't do better.
Dan Gohman5f1702e2010-08-06 01:25:49 +0000532 if (F->doesNotAccessMemory())
Chandler Carruth194f59c2015-07-22 23:15:57 +0000533 return FMRB_DoesNotAccessMemory;
Dan Gohmane461d7d2010-11-08 16:08:43 +0000534
535 // For intrinsics, we can check the table.
Pete Cooper9e1d3352015-05-20 17:16:39 +0000536 if (Intrinsic::ID iid = F->getIntrinsicID()) {
Dan Gohmane461d7d2010-11-08 16:08:43 +0000537#define GET_INTRINSIC_MODREF_BEHAVIOR
Chandler Carruthdb25c6c2013-01-02 12:09:16 +0000538#include "llvm/IR/Intrinsics.gen"
Dan Gohmane461d7d2010-11-08 16:08:43 +0000539#undef GET_INTRINSIC_MODREF_BEHAVIOR
540 }
541
Chandler Carruth194f59c2015-07-22 23:15:57 +0000542 FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
Dan Gohman2694e142010-11-10 01:02:18 +0000543
Dan Gohmane461d7d2010-11-08 16:08:43 +0000544 // If the function declares it only reads memory, go with that.
Dan Gohman5f1702e2010-08-06 01:25:49 +0000545 if (F->onlyReadsMemory())
Chandler Carruth194f59c2015-07-22 23:15:57 +0000546 Min = FMRB_OnlyReadsMemory;
Dan Gohman5f1702e2010-08-06 01:25:49 +0000547
Igor Laevsky39d662f2015-07-11 10:30:36 +0000548 if (F->onlyAccessesArgMemory())
Chandler Carruth194f59c2015-07-22 23:15:57 +0000549 Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesArgumentPointees);
Igor Laevsky39d662f2015-07-11 10:30:36 +0000550
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000551 const TargetLibraryInfo &TLI =
552 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Hal Finkel354e23b2014-07-17 01:28:25 +0000553 if (isMemsetPattern16(F, TLI))
Chandler Carruth194f59c2015-07-22 23:15:57 +0000554 Min = FMRB_OnlyAccessesArgumentPointees;
Hal Finkel354e23b2014-07-17 01:28:25 +0000555
Dan Gohmane461d7d2010-11-08 16:08:43 +0000556 // Otherwise be conservative.
Chandler Carruth194f59c2015-07-22 23:15:57 +0000557 return FunctionModRefBehavior(AliasAnalysis::getModRefBehavior(F) & Min);
Dan Gohman5f1702e2010-08-06 01:25:49 +0000558}
Owen Anderson98a36172009-02-05 23:36:27 +0000559
Chandler Carruth194f59c2015-07-22 23:15:57 +0000560ModRefInfo BasicAliasAnalysis::getArgModRefInfo(ImmutableCallSite CS,
561 unsigned ArgIdx) {
Chandler Carruthc41404a2015-06-17 07:12:40 +0000562 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction()))
Hal Finkel354e23b2014-07-17 01:28:25 +0000563 switch (II->getIntrinsicID()) {
Chandler Carruthc41404a2015-06-17 07:12:40 +0000564 default:
565 break;
Hal Finkel354e23b2014-07-17 01:28:25 +0000566 case Intrinsic::memset:
567 case Intrinsic::memcpy:
Chandler Carruthc41404a2015-06-17 07:12:40 +0000568 case Intrinsic::memmove:
Hal Finkel354e23b2014-07-17 01:28:25 +0000569 assert((ArgIdx == 0 || ArgIdx == 1) &&
570 "Invalid argument index for memory intrinsic");
Chandler Carruth194f59c2015-07-22 23:15:57 +0000571 return ArgIdx ? MRI_Ref : MRI_Mod;
Hal Finkel354e23b2014-07-17 01:28:25 +0000572 }
573
574 // We can bound the aliasing properties of memset_pattern16 just as we can
575 // for memcpy/memset. This is particularly important because the
576 // LoopIdiomRecognizer likes to turn loops into calls to memset_pattern16
577 // whenever possible.
Chandler Carruthc41404a2015-06-17 07:12:40 +0000578 if (CS.getCalledFunction() &&
579 isMemsetPattern16(CS.getCalledFunction(), *TLI)) {
Hal Finkel354e23b2014-07-17 01:28:25 +0000580 assert((ArgIdx == 0 || ArgIdx == 1) &&
581 "Invalid argument index for memset_pattern16");
Chandler Carruth194f59c2015-07-22 23:15:57 +0000582 return ArgIdx ? MRI_Ref : MRI_Mod;
Hal Finkel354e23b2014-07-17 01:28:25 +0000583 }
584 // FIXME: Handle memset_pattern4 and memset_pattern8 also.
585
Chandler Carruthc41404a2015-06-17 07:12:40 +0000586 return AliasAnalysis::getArgModRefInfo(CS, ArgIdx);
Hal Finkel354e23b2014-07-17 01:28:25 +0000587}
588
Hal Finkel93046912014-07-25 21:13:35 +0000589static bool isAssumeIntrinsic(ImmutableCallSite CS) {
590 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
591 if (II && II->getIntrinsicID() == Intrinsic::assume)
592 return true;
593
594 return false;
595}
596
Mehdi Amini46a43552015-03-04 18:43:29 +0000597bool BasicAliasAnalysis::doInitialization(Module &M) {
598 InitializeAliasAnalysis(this, &M.getDataLayout());
599 return true;
600}
601
Chris Lattner98e253262009-11-23 16:45:27 +0000602/// getModRefInfo - Check to see if the specified callsite can clobber the
603/// specified memory object. Since we only look at local properties of this
604/// function, we really can't say much about this query. We do, however, use
605/// simple "address taken" analysis on local objects.
Chandler Carruth194f59c2015-07-22 23:15:57 +0000606ModRefInfo BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS,
607 const MemoryLocation &Loc) {
Dan Gohman41f14cf2010-09-14 21:25:10 +0000608 assert(notDifferentParent(CS.getInstruction(), Loc.Ptr) &&
Dan Gohman00ef9322010-07-07 14:27:09 +0000609 "AliasAnalysis query involving multiple functions!");
610
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000611 const Value *Object = GetUnderlyingObject(Loc.Ptr, *DL);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000612
Dan Gohman41f14cf2010-09-14 21:25:10 +0000613 // If this is a tail call and Loc.Ptr points to a stack location, we know that
Chris Lattnerd6a49ad2009-11-22 16:05:05 +0000614 // the tail call cannot access or modify the local stack.
615 // We cannot exclude byval arguments here; these belong to the caller of
616 // the current function not to the current function, and a tail callee
617 // may reference them.
618 if (isa<AllocaInst>(Object))
Dan Gohman5442c712010-08-03 21:48:53 +0000619 if (const CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
Chris Lattnerd6a49ad2009-11-22 16:05:05 +0000620 if (CI->isTailCall())
Chandler Carruth194f59c2015-07-22 23:15:57 +0000621 return MRI_NoModRef;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000622
Chris Lattnerd6a49ad2009-11-22 16:05:05 +0000623 // If the pointer is to a locally allocated object that does not escape,
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000624 // then the call can not mod/ref the pointer unless the call takes the pointer
625 // as an argument, and itself doesn't capture it.
Chris Lattner1e7b37e2009-11-23 16:46:41 +0000626 if (!isa<Constant>(Object) && CS.getInstruction() != Object &&
Dan Gohman84f90a32010-07-01 20:08:40 +0000627 isNonEscapingLocalObject(Object)) {
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000628 bool PassedAsArg = false;
629 unsigned ArgNo = 0;
Dan Gohman5442c712010-08-03 21:48:53 +0000630 for (ImmutableCallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000631 CI != CE; ++CI, ++ArgNo) {
Chris Lattner026f5e62011-05-23 05:15:43 +0000632 // Only look at the no-capture or byval pointer arguments. If this
633 // pointer were passed to arguments that were neither of these, then it
634 // couldn't be no-capture.
Duncan Sands19d0b472010-02-16 11:11:14 +0000635 if (!(*CI)->getType()->isPointerTy() ||
Nick Lewycky612d70b2011-11-20 19:09:04 +0000636 (!CS.doesNotCapture(ArgNo) && !CS.isByValArgument(ArgNo)))
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000637 continue;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000638
Dan Gohman41f14cf2010-09-14 21:25:10 +0000639 // If this is a no-capture pointer argument, see if we can tell that it
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000640 // is impossible to alias the pointer we're checking. If not, we have to
641 // assume that the call could touch the pointer, even though it doesn't
642 // escape.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000643 if (!isNoAlias(MemoryLocation(*CI), MemoryLocation(Object))) {
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000644 PassedAsArg = true;
645 break;
646 }
647 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000648
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000649 if (!PassedAsArg)
Chandler Carruth194f59c2015-07-22 23:15:57 +0000650 return MRI_NoModRef;
Chris Lattnerd6a49ad2009-11-22 16:05:05 +0000651 }
652
Hal Finkel93046912014-07-25 21:13:35 +0000653 // While the assume intrinsic is marked as arbitrarily writing so that
654 // proper control dependencies will be maintained, it never aliases any
655 // particular memory location.
656 if (isAssumeIntrinsic(CS))
Chandler Carruth194f59c2015-07-22 23:15:57 +0000657 return MRI_NoModRef;
Hal Finkel93046912014-07-25 21:13:35 +0000658
Chris Lattner2d332972008-06-16 06:30:22 +0000659 // The AliasAnalysis base class has some smarts, lets use them.
Hal Finkel354e23b2014-07-17 01:28:25 +0000660 return AliasAnalysis::getModRefInfo(CS, Loc);
Dan Gohman64d842e2010-09-08 01:32:20 +0000661}
Chris Lattner2d332972008-06-16 06:30:22 +0000662
Chandler Carruth194f59c2015-07-22 23:15:57 +0000663ModRefInfo BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
664 ImmutableCallSite CS2) {
Hal Finkel93046912014-07-25 21:13:35 +0000665 // While the assume intrinsic is marked as arbitrarily writing so that
666 // proper control dependencies will be maintained, it never aliases any
667 // particular memory location.
668 if (isAssumeIntrinsic(CS1) || isAssumeIntrinsic(CS2))
Chandler Carruth194f59c2015-07-22 23:15:57 +0000669 return MRI_NoModRef;
Hal Finkel93046912014-07-25 21:13:35 +0000670
671 // The AliasAnalysis base class has some smarts, lets use them.
672 return AliasAnalysis::getModRefInfo(CS1, CS2);
673}
674
Ahmed Bougacha29efe3b2015-02-07 17:04:29 +0000675/// \brief Provide ad-hoc rules to disambiguate accesses through two GEP
676/// operators, both having the exact same pointer operand.
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000677static AliasResult aliasSameBasePointerGEPs(const GEPOperator *GEP1,
678 uint64_t V1Size,
679 const GEPOperator *GEP2,
680 uint64_t V2Size,
681 const DataLayout &DL) {
Ahmed Bougacha29efe3b2015-02-07 17:04:29 +0000682
683 assert(GEP1->getPointerOperand() == GEP2->getPointerOperand() &&
684 "Expected GEPs with the same pointer operand");
685
686 // Try to determine whether GEP1 and GEP2 index through arrays, into structs,
687 // such that the struct field accesses provably cannot alias.
688 // We also need at least two indices (the pointer, and the struct field).
689 if (GEP1->getNumIndices() != GEP2->getNumIndices() ||
690 GEP1->getNumIndices() < 2)
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000691 return MayAlias;
Ahmed Bougacha29efe3b2015-02-07 17:04:29 +0000692
693 // If we don't know the size of the accesses through both GEPs, we can't
694 // determine whether the struct fields accessed can't alias.
Chandler Carruthecbd1682015-06-17 07:21:38 +0000695 if (V1Size == MemoryLocation::UnknownSize ||
696 V2Size == MemoryLocation::UnknownSize)
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000697 return MayAlias;
Ahmed Bougacha29efe3b2015-02-07 17:04:29 +0000698
699 ConstantInt *C1 =
700 dyn_cast<ConstantInt>(GEP1->getOperand(GEP1->getNumOperands() - 1));
701 ConstantInt *C2 =
702 dyn_cast<ConstantInt>(GEP2->getOperand(GEP2->getNumOperands() - 1));
703
704 // If the last (struct) indices aren't constants, we can't say anything.
705 // If they're identical, the other indices might be also be dynamically
706 // equal, so the GEPs can alias.
707 if (!C1 || !C2 || C1 == C2)
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000708 return MayAlias;
Ahmed Bougacha29efe3b2015-02-07 17:04:29 +0000709
710 // Find the last-indexed type of the GEP, i.e., the type you'd get if
711 // you stripped the last index.
712 // On the way, look at each indexed type. If there's something other
713 // than an array, different indices can lead to different final types.
714 SmallVector<Value *, 8> IntermediateIndices;
715
716 // Insert the first index; we don't need to check the type indexed
717 // through it as it only drops the pointer indirection.
718 assert(GEP1->getNumIndices() > 1 && "Not enough GEP indices to examine");
719 IntermediateIndices.push_back(GEP1->getOperand(1));
720
721 // Insert all the remaining indices but the last one.
722 // Also, check that they all index through arrays.
723 for (unsigned i = 1, e = GEP1->getNumIndices() - 1; i != e; ++i) {
724 if (!isa<ArrayType>(GetElementPtrInst::getIndexedType(
David Blaikied288fb82015-03-30 21:41:43 +0000725 GEP1->getSourceElementType(), IntermediateIndices)))
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000726 return MayAlias;
Ahmed Bougacha29efe3b2015-02-07 17:04:29 +0000727 IntermediateIndices.push_back(GEP1->getOperand(i + 1));
728 }
729
730 StructType *LastIndexedStruct =
731 dyn_cast<StructType>(GetElementPtrInst::getIndexedType(
David Blaikied288fb82015-03-30 21:41:43 +0000732 GEP1->getSourceElementType(), IntermediateIndices));
Ahmed Bougacha29efe3b2015-02-07 17:04:29 +0000733
734 if (!LastIndexedStruct)
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000735 return MayAlias;
Ahmed Bougacha29efe3b2015-02-07 17:04:29 +0000736
737 // We know that:
738 // - both GEPs begin indexing from the exact same pointer;
739 // - the last indices in both GEPs are constants, indexing into a struct;
740 // - said indices are different, hence, the pointed-to fields are different;
741 // - both GEPs only index through arrays prior to that.
742 //
743 // This lets us determine that the struct that GEP1 indexes into and the
744 // struct that GEP2 indexes into must either precisely overlap or be
745 // completely disjoint. Because they cannot partially overlap, indexing into
746 // different non-overlapping fields of the struct will never alias.
747
748 // Therefore, the only remaining thing needed to show that both GEPs can't
749 // alias is that the fields are not overlapping.
750 const StructLayout *SL = DL.getStructLayout(LastIndexedStruct);
751 const uint64_t StructSize = SL->getSizeInBytes();
752 const uint64_t V1Off = SL->getElementOffset(C1->getZExtValue());
753 const uint64_t V2Off = SL->getElementOffset(C2->getZExtValue());
754
755 auto EltsDontOverlap = [StructSize](uint64_t V1Off, uint64_t V1Size,
756 uint64_t V2Off, uint64_t V2Size) {
757 return V1Off < V2Off && V1Off + V1Size <= V2Off &&
758 ((V2Off + V2Size <= StructSize) ||
759 (V2Off + V2Size - StructSize <= V1Off));
760 };
761
762 if (EltsDontOverlap(V1Off, V1Size, V2Off, V2Size) ||
763 EltsDontOverlap(V2Off, V2Size, V1Off, V1Size))
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000764 return NoAlias;
Ahmed Bougacha29efe3b2015-02-07 17:04:29 +0000765
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000766 return MayAlias;
Ahmed Bougacha29efe3b2015-02-07 17:04:29 +0000767}
768
Chris Lattnera99edbe2009-11-26 02:11:08 +0000769/// aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
770/// against another pointer. We know that V1 is a GEP, but we don't know
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000771/// anything about V2. UnderlyingV1 is GetUnderlyingObject(GEP1, DL),
Chris Lattner5341c962009-11-26 02:14:59 +0000772/// UnderlyingV2 is the same for V2.
Chris Lattnera99edbe2009-11-26 02:11:08 +0000773///
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000774AliasResult BasicAliasAnalysis::aliasGEP(
775 const GEPOperator *GEP1, uint64_t V1Size, const AAMDNodes &V1AAInfo,
776 const Value *V2, uint64_t V2Size, const AAMDNodes &V2AAInfo,
777 const Value *UnderlyingV1, const Value *UnderlyingV2) {
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000778 int64_t GEP1BaseOffset;
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000779 bool GEP1MaxLookupReached;
Chris Lattner1b9c3872010-08-18 22:47:56 +0000780 SmallVector<VariableGEPIndex, 4> GEP1VariableIndices;
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000781
Chandler Carruth66b31302015-01-04 12:03:27 +0000782 // We have to get two AssumptionCaches here because GEP1 and V2 may be from
783 // different functions.
784 // FIXME: This really doesn't make any sense. We get a dominator tree below
785 // that can only refer to a single function. But this function (aliasGEP) is
786 // a method on an immutable pass that can be called when there *isn't*
787 // a single function. The old pass management layer makes this "work", but
788 // this isn't really a clean solution.
789 AssumptionCacheTracker &ACT = getAnalysis<AssumptionCacheTracker>();
790 AssumptionCache *AC1 = nullptr, *AC2 = nullptr;
791 if (auto *GEP1I = dyn_cast<Instruction>(GEP1))
792 AC1 = &ACT.getAssumptionCache(
793 const_cast<Function &>(*GEP1I->getParent()->getParent()));
794 if (auto *I2 = dyn_cast<Instruction>(V2))
795 AC2 = &ACT.getAssumptionCache(
796 const_cast<Function &>(*I2->getParent()->getParent()));
797
Hal Finkel60db0582014-09-07 18:57:58 +0000798 DominatorTreeWrapperPass *DTWP =
799 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
800 DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
801
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000802 // If we have two gep instructions with must-alias or not-alias'ing base
803 // pointers, figure out if the indexes to the GEP tell us anything about the
804 // derived pointer.
Chris Lattnera99edbe2009-11-26 02:11:08 +0000805 if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
Arnold Schwaighoferaadf1042013-03-26 18:07:53 +0000806 // Do the base pointers alias?
Chandler Carruthecbd1682015-06-17 07:21:38 +0000807 AliasResult BaseAlias =
808 aliasCheck(UnderlyingV1, MemoryLocation::UnknownSize, AAMDNodes(),
809 UnderlyingV2, MemoryLocation::UnknownSize, AAMDNodes());
Arnold Schwaighoferaadf1042013-03-26 18:07:53 +0000810
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000811 // Check for geps of non-aliasing underlying pointers where the offsets are
812 // identical.
Arnold Schwaighoferaadf1042013-03-26 18:07:53 +0000813 if ((BaseAlias == MayAlias) && V1Size == V2Size) {
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000814 // Do the base pointers alias assuming type and size.
815 AliasResult PreciseBaseAlias = aliasCheck(UnderlyingV1, V1Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000816 V1AAInfo, UnderlyingV2,
817 V2Size, V2AAInfo);
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000818 if (PreciseBaseAlias == NoAlias) {
819 // See if the computed offset from the common pointer tells us about the
820 // relation of the resulting pointer.
821 int64_t GEP2BaseOffset;
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000822 bool GEP2MaxLookupReached;
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000823 SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
824 const Value *GEP2BasePtr =
Chandler Carruth66b31302015-01-04 12:03:27 +0000825 DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000826 GEP2MaxLookupReached, *DL, AC2, DT);
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000827 const Value *GEP1BasePtr =
Chandler Carruth66b31302015-01-04 12:03:27 +0000828 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000829 GEP1MaxLookupReached, *DL, AC1, DT);
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000830 // DecomposeGEPExpression and GetUnderlyingObject should return the
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000831 // same result except when DecomposeGEPExpression has no DataLayout.
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000832 if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
Craig Topper9f008862014-04-15 04:59:12 +0000833 assert(!DL &&
834 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000835 return MayAlias;
836 }
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000837 // If the max search depth is reached the result is undefined
838 if (GEP2MaxLookupReached || GEP1MaxLookupReached)
839 return MayAlias;
840
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000841 // Same offsets.
842 if (GEP1BaseOffset == GEP2BaseOffset &&
Benjamin Kramer147644d2014-04-18 19:48:03 +0000843 GEP1VariableIndices == GEP2VariableIndices)
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000844 return NoAlias;
845 GEP1VariableIndices.clear();
846 }
847 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000848
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000849 // If we get a No or May, then return it immediately, no amount of analysis
850 // will improve this situation.
851 if (BaseAlias != MustAlias) return BaseAlias;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000852
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000853 // Otherwise, we have a MustAlias. Since the base pointers alias each other
854 // exactly, see if the computed offset from the common pointer tells us
855 // about the relation of the resulting pointer.
856 const Value *GEP1BasePtr =
Chandler Carruth66b31302015-01-04 12:03:27 +0000857 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000858 GEP1MaxLookupReached, *DL, AC1, DT);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000859
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000860 int64_t GEP2BaseOffset;
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000861 bool GEP2MaxLookupReached;
Chris Lattner1b9c3872010-08-18 22:47:56 +0000862 SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000863 const Value *GEP2BasePtr =
Chandler Carruth66b31302015-01-04 12:03:27 +0000864 DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000865 GEP2MaxLookupReached, *DL, AC2, DT);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000866
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000867 // DecomposeGEPExpression and GetUnderlyingObject should return the
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000868 // same result except when DecomposeGEPExpression has no DataLayout.
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000869 if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
Craig Topper9f008862014-04-15 04:59:12 +0000870 assert(!DL &&
Dan Gohmana4fcd242010-12-15 20:02:24 +0000871 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000872 return MayAlias;
873 }
Ahmed Bougacha29efe3b2015-02-07 17:04:29 +0000874
875 // If we know the two GEPs are based off of the exact same pointer (and not
876 // just the same underlying object), see if that tells us anything about
877 // the resulting pointers.
878 if (DL && GEP1->getPointerOperand() == GEP2->getPointerOperand()) {
879 AliasResult R = aliasSameBasePointerGEPs(GEP1, V1Size, GEP2, V2Size, *DL);
880 // If we couldn't find anything interesting, don't abandon just yet.
881 if (R != MayAlias)
882 return R;
883 }
884
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000885 // If the max search depth is reached the result is undefined
886 if (GEP2MaxLookupReached || GEP1MaxLookupReached)
887 return MayAlias;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000888
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000889 // Subtract the GEP2 pointer from the GEP1 pointer to find out their
890 // symbolic difference.
891 GEP1BaseOffset -= GEP2BaseOffset;
Dan Gohmanad867b02010-08-03 20:23:52 +0000892 GetIndexDifference(GEP1VariableIndices, GEP2VariableIndices);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000893
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000894 } else {
895 // Check to see if these two pointers are related by the getelementptr
896 // instruction. If one pointer is a GEP with a non-zero index of the other
897 // pointer, we know they cannot alias.
Chris Lattner5c1cfc22009-11-26 16:52:32 +0000898
899 // If both accesses are unknown size, we can't do anything useful here.
Chandler Carruthecbd1682015-06-17 07:21:38 +0000900 if (V1Size == MemoryLocation::UnknownSize &&
901 V2Size == MemoryLocation::UnknownSize)
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000902 return MayAlias;
Chris Lattner6ea17f77f2003-12-11 22:44:13 +0000903
Chandler Carruthecbd1682015-06-17 07:21:38 +0000904 AliasResult R = aliasCheck(UnderlyingV1, MemoryLocation::UnknownSize,
905 AAMDNodes(), V2, V2Size, V2AAInfo);
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000906 if (R != MustAlias)
907 // If V2 may alias GEP base pointer, conservatively returns MayAlias.
908 // If V2 is known not to alias GEP base pointer, then the two values
909 // cannot alias per GEP semantics: "A pointer value formed from a
910 // getelementptr instruction is associated with the addresses associated
911 // with the first operand of the getelementptr".
912 return R;
Chris Lattner6ea17f77f2003-12-11 22:44:13 +0000913
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000914 const Value *GEP1BasePtr =
Chandler Carruth66b31302015-01-04 12:03:27 +0000915 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000916 GEP1MaxLookupReached, *DL, AC1, DT);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000917
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000918 // DecomposeGEPExpression and GetUnderlyingObject should return the
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000919 // same result except when DecomposeGEPExpression has no DataLayout.
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000920 if (GEP1BasePtr != UnderlyingV1) {
Craig Topper9f008862014-04-15 04:59:12 +0000921 assert(!DL &&
Dan Gohmana4fcd242010-12-15 20:02:24 +0000922 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000923 return MayAlias;
Chris Lattner6ea17f77f2003-12-11 22:44:13 +0000924 }
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000925 // If the max search depth is reached the result is undefined
926 if (GEP1MaxLookupReached)
927 return MayAlias;
Chris Lattner6ea17f77f2003-12-11 22:44:13 +0000928 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000929
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000930 // In the two GEP Case, if there is no difference in the offsets of the
931 // computed pointers, the resultant pointers are a must alias. This
932 // hapens when we have two lexically identical GEP's (for example).
Chris Lattnerd6a2a992003-02-26 19:41:54 +0000933 //
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000934 // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
935 // must aliases the GEP, the end result is a must alias also.
936 if (GEP1BaseOffset == 0 && GEP1VariableIndices.empty())
Evan Chengc1eed9d2009-10-14 06:41:49 +0000937 return MustAlias;
Evan Chengf1f3dd32009-10-13 18:42:04 +0000938
Eli Friedman3d1b3072011-09-08 02:23:31 +0000939 // If there is a constant difference between the pointers, but the difference
940 // is less than the size of the associated memory object, then we know
941 // that the objects are partially overlapping. If the difference is
942 // greater, we know they do not overlap.
Dan Gohmanc4bf5ca2010-12-13 22:50:24 +0000943 if (GEP1BaseOffset != 0 && GEP1VariableIndices.empty()) {
Eli Friedman3d1b3072011-09-08 02:23:31 +0000944 if (GEP1BaseOffset >= 0) {
Chandler Carruthecbd1682015-06-17 07:21:38 +0000945 if (V2Size != MemoryLocation::UnknownSize) {
Eli Friedman3d1b3072011-09-08 02:23:31 +0000946 if ((uint64_t)GEP1BaseOffset < V2Size)
947 return PartialAlias;
948 return NoAlias;
949 }
950 } else {
Arnold Schwaighofere3ac0992014-01-16 04:53:18 +0000951 // We have the situation where:
952 // + +
953 // | BaseOffset |
954 // ---------------->|
955 // |-->V1Size |-------> V2Size
956 // GEP1 V2
957 // We need to know that V2Size is not unknown, otherwise we might have
958 // stripped a gep with negative index ('gep <ptr>, -1, ...).
Chandler Carruthecbd1682015-06-17 07:21:38 +0000959 if (V1Size != MemoryLocation::UnknownSize &&
960 V2Size != MemoryLocation::UnknownSize) {
Eli Friedman3d1b3072011-09-08 02:23:31 +0000961 if (-(uint64_t)GEP1BaseOffset < V1Size)
962 return PartialAlias;
963 return NoAlias;
964 }
965 }
Dan Gohmanc4bf5ca2010-12-13 22:50:24 +0000966 }
967
Eli Friedmanb78ac542011-09-08 02:37:07 +0000968 if (!GEP1VariableIndices.empty()) {
969 uint64_t Modulo = 0;
Hal Finkel45ba2c12014-11-13 09:16:54 +0000970 bool AllPositive = true;
971 for (unsigned i = 0, e = GEP1VariableIndices.size(); i != e; ++i) {
972
973 // Try to distinguish something like &A[i][1] against &A[42][0].
974 // Grab the least significant bit set in any of the scales. We
975 // don't need std::abs here (even if the scale's negative) as we'll
976 // be ^'ing Modulo with itself later.
977 Modulo |= (uint64_t) GEP1VariableIndices[i].Scale;
978
979 if (AllPositive) {
980 // If the Value could change between cycles, then any reasoning about
981 // the Value this cycle may not hold in the next cycle. We'll just
982 // give up if we can't determine conditions that hold for every cycle:
983 const Value *V = GEP1VariableIndices[i].V;
984
985 bool SignKnownZero, SignKnownOne;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000986 ComputeSignBit(const_cast<Value *>(V), SignKnownZero, SignKnownOne, *DL,
Chandler Carruth66b31302015-01-04 12:03:27 +0000987 0, AC1, nullptr, DT);
Hal Finkel45ba2c12014-11-13 09:16:54 +0000988
989 // Zero-extension widens the variable, and so forces the sign
990 // bit to zero.
Manuel Klimek779cf852015-07-13 13:50:55 +0000991 bool IsZExt = GEP1VariableIndices[i].Extension == EK_ZeroExt;
Hal Finkel45ba2c12014-11-13 09:16:54 +0000992 SignKnownZero |= IsZExt;
993 SignKnownOne &= !IsZExt;
994
995 // If the variable begins with a zero then we know it's
996 // positive, regardless of whether the value is signed or
997 // unsigned.
998 int64_t Scale = GEP1VariableIndices[i].Scale;
999 AllPositive =
1000 (SignKnownZero && Scale >= 0) ||
1001 (SignKnownOne && Scale < 0);
1002 }
1003 }
1004
Eli Friedmanb78ac542011-09-08 02:37:07 +00001005 Modulo = Modulo ^ (Modulo & (Modulo - 1));
Eli Friedman3d1b3072011-09-08 02:23:31 +00001006
Eli Friedmanb78ac542011-09-08 02:37:07 +00001007 // We can compute the difference between the two addresses
1008 // mod Modulo. Check whether that difference guarantees that the
1009 // two locations do not alias.
1010 uint64_t ModOffset = (uint64_t)GEP1BaseOffset & (Modulo - 1);
Chandler Carruthecbd1682015-06-17 07:21:38 +00001011 if (V1Size != MemoryLocation::UnknownSize &&
1012 V2Size != MemoryLocation::UnknownSize && ModOffset >= V2Size &&
1013 V1Size <= Modulo - ModOffset)
Eli Friedmanb78ac542011-09-08 02:37:07 +00001014 return NoAlias;
Hal Finkel45ba2c12014-11-13 09:16:54 +00001015
1016 // If we know all the variables are positive, then GEP1 >= GEP1BasePtr.
1017 // If GEP1BasePtr > V2 (GEP1BaseOffset > 0) then we know the pointers
1018 // don't alias if V2Size can fit in the gap between V2 and GEP1BasePtr.
1019 if (AllPositive && GEP1BaseOffset > 0 && V2Size <= (uint64_t) GEP1BaseOffset)
1020 return NoAlias;
Eli Friedmanb78ac542011-09-08 02:37:07 +00001021 }
Eli Friedman3d1b3072011-09-08 02:23:31 +00001022
Dan Gohmanadf80ae2011-06-04 06:50:18 +00001023 // Statically, we can see that the base objects are the same, but the
1024 // pointers have dynamic offsets which we can't resolve. And none of our
1025 // little tricks above worked.
1026 //
1027 // TODO: Returning PartialAlias instead of MayAlias is a mild hack; the
1028 // practical effect of this is protecting TBAA in the case of dynamic
Dan Gohman9017b842012-02-17 18:33:38 +00001029 // indices into arrays of unions or malloc'd memory.
Dan Gohmanadf80ae2011-06-04 06:50:18 +00001030 return PartialAlias;
Evan Chengf1f3dd32009-10-13 18:42:04 +00001031}
1032
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001033static AliasResult MergeAliasResults(AliasResult A, AliasResult B) {
Dan Gohman4e7e7952011-06-03 20:17:36 +00001034 // If the results agree, take it.
1035 if (A == B)
1036 return A;
1037 // A mix of PartialAlias and MustAlias is PartialAlias.
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001038 if ((A == PartialAlias && B == MustAlias) ||
1039 (B == PartialAlias && A == MustAlias))
1040 return PartialAlias;
Dan Gohman4e7e7952011-06-03 20:17:36 +00001041 // Otherwise, we don't know anything.
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001042 return MayAlias;
Dan Gohman4e7e7952011-06-03 20:17:36 +00001043}
1044
Chris Lattner98e253262009-11-23 16:45:27 +00001045/// aliasSelect - Provide a bunch of ad-hoc rules to disambiguate a Select
1046/// instruction against another.
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001047AliasResult BasicAliasAnalysis::aliasSelect(const SelectInst *SI,
1048 uint64_t SISize,
1049 const AAMDNodes &SIAAInfo,
1050 const Value *V2, uint64_t V2Size,
1051 const AAMDNodes &V2AAInfo) {
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001052 // If the values are Selects with the same condition, we can do a more precise
1053 // check: just check for aliases between the values on corresponding arms.
1054 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
1055 if (SI->getCondition() == SI2->getCondition()) {
1056 AliasResult Alias =
Hal Finkelcc39b672014-07-24 12:16:19 +00001057 aliasCheck(SI->getTrueValue(), SISize, SIAAInfo,
1058 SI2->getTrueValue(), V2Size, V2AAInfo);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001059 if (Alias == MayAlias)
1060 return MayAlias;
1061 AliasResult ThisAlias =
Hal Finkelcc39b672014-07-24 12:16:19 +00001062 aliasCheck(SI->getFalseValue(), SISize, SIAAInfo,
1063 SI2->getFalseValue(), V2Size, V2AAInfo);
Dan Gohman4e7e7952011-06-03 20:17:36 +00001064 return MergeAliasResults(ThisAlias, Alias);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001065 }
1066
1067 // If both arms of the Select node NoAlias or MustAlias V2, then returns
1068 // NoAlias / MustAlias. Otherwise, returns MayAlias.
1069 AliasResult Alias =
Hal Finkelcc39b672014-07-24 12:16:19 +00001070 aliasCheck(V2, V2Size, V2AAInfo, SI->getTrueValue(), SISize, SIAAInfo);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001071 if (Alias == MayAlias)
1072 return MayAlias;
Dan Gohman7c34ece2010-06-28 21:16:52 +00001073
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001074 AliasResult ThisAlias =
Hal Finkelcc39b672014-07-24 12:16:19 +00001075 aliasCheck(V2, V2Size, V2AAInfo, SI->getFalseValue(), SISize, SIAAInfo);
Dan Gohman4e7e7952011-06-03 20:17:36 +00001076 return MergeAliasResults(ThisAlias, Alias);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001077}
1078
Evan Chengf92f5552009-10-14 05:22:03 +00001079// aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
Evan Cheng31565b32009-10-14 05:05:02 +00001080// against another.
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001081AliasResult BasicAliasAnalysis::aliasPHI(const PHINode *PN, uint64_t PNSize,
1082 const AAMDNodes &PNAAInfo,
1083 const Value *V2, uint64_t V2Size,
1084 const AAMDNodes &V2AAInfo) {
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001085 // Track phi nodes we have visited. We use this information when we determine
1086 // value equivalence.
1087 VisitedPhiBBs.insert(PN->getParent());
1088
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001089 // If the values are PHIs in the same block, we can do a more precise
1090 // as well as efficient check: just check for aliases between the values
1091 // on corresponding edges.
1092 if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
1093 if (PN2->getParent() == PN->getParent()) {
Chandler Carruthac80dc72015-06-17 07:18:54 +00001094 LocPair Locs(MemoryLocation(PN, PNSize, PNAAInfo),
1095 MemoryLocation(V2, V2Size, V2AAInfo));
Arnold Schwaighofer8dc34cf2012-09-06 14:41:53 +00001096 if (PN > V2)
1097 std::swap(Locs.first, Locs.second);
Arnold Schwaighoferedd62b12012-12-10 23:02:41 +00001098 // Analyse the PHIs' inputs under the assumption that the PHIs are
1099 // NoAlias.
1100 // If the PHIs are May/MustAlias there must be (recursively) an input
1101 // operand from outside the PHIs' cycle that is MayAlias/MustAlias or
1102 // there must be an operation on the PHIs within the PHIs' value cycle
1103 // that causes a MayAlias.
1104 // Pretend the phis do not alias.
1105 AliasResult Alias = NoAlias;
1106 assert(AliasCache.count(Locs) &&
1107 "There must exist an entry for the phi node");
1108 AliasResult OrigAliasResult = AliasCache[Locs];
1109 AliasCache[Locs] = NoAlias;
Arnold Schwaighofer8dc34cf2012-09-06 14:41:53 +00001110
Hal Finkela6f86fc2012-11-17 02:33:15 +00001111 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001112 AliasResult ThisAlias =
Hal Finkelcc39b672014-07-24 12:16:19 +00001113 aliasCheck(PN->getIncomingValue(i), PNSize, PNAAInfo,
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001114 PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
Hal Finkelcc39b672014-07-24 12:16:19 +00001115 V2Size, V2AAInfo);
Dan Gohman4e7e7952011-06-03 20:17:36 +00001116 Alias = MergeAliasResults(ThisAlias, Alias);
1117 if (Alias == MayAlias)
1118 break;
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001119 }
Arnold Schwaighofer8dc34cf2012-09-06 14:41:53 +00001120
1121 // Reset if speculation failed.
Arnold Schwaighoferedd62b12012-12-10 23:02:41 +00001122 if (Alias != NoAlias)
Arnold Schwaighofer8dc34cf2012-09-06 14:41:53 +00001123 AliasCache[Locs] = OrigAliasResult;
1124
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001125 return Alias;
1126 }
1127
Evan Cheng8ec25932009-10-16 00:33:09 +00001128 SmallPtrSet<Value*, 4> UniqueSrc;
Evan Chengc10e88d2009-10-13 22:02:20 +00001129 SmallVector<Value*, 4> V1Srcs;
Tobias Edler von Kochd8ce16b2015-07-15 19:32:22 +00001130 bool isRecursive = false;
Pete Cooper833f34d2015-05-12 20:05:31 +00001131 for (Value *PV1 : PN->incoming_values()) {
Evan Chengc10e88d2009-10-13 22:02:20 +00001132 if (isa<PHINode>(PV1))
1133 // If any of the source itself is a PHI, return MayAlias conservatively
Evan Chengc1eed9d2009-10-14 06:41:49 +00001134 // to avoid compile time explosion. The worst possible case is if both
1135 // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
1136 // and 'n' are the number of PHI sources.
Evan Chengc10e88d2009-10-13 22:02:20 +00001137 return MayAlias;
Tobias Edler von Kochd8ce16b2015-07-15 19:32:22 +00001138
1139 if (EnableRecPhiAnalysis)
1140 if (GEPOperator *PV1GEP = dyn_cast<GEPOperator>(PV1)) {
1141 // Check whether the incoming value is a GEP that advances the pointer
1142 // result of this PHI node (e.g. in a loop). If this is the case, we
1143 // would recurse and always get a MayAlias. Handle this case specially
1144 // below.
1145 if (PV1GEP->getPointerOperand() == PN && PV1GEP->getNumIndices() == 1 &&
1146 isa<ConstantInt>(PV1GEP->idx_begin())) {
1147 isRecursive = true;
1148 continue;
1149 }
1150 }
1151
David Blaikie70573dc2014-11-19 07:49:26 +00001152 if (UniqueSrc.insert(PV1).second)
Evan Chengc10e88d2009-10-13 22:02:20 +00001153 V1Srcs.push_back(PV1);
1154 }
1155
Tobias Edler von Kochd8ce16b2015-07-15 19:32:22 +00001156 // If this PHI node is recursive, set the size of the accessed memory to
1157 // unknown to represent all the possible values the GEP could advance the
1158 // pointer to.
1159 if (isRecursive)
1160 PNSize = MemoryLocation::UnknownSize;
1161
Hal Finkelcc39b672014-07-24 12:16:19 +00001162 AliasResult Alias = aliasCheck(V2, V2Size, V2AAInfo,
1163 V1Srcs[0], PNSize, PNAAInfo);
Tobias Edler von Kochd8ce16b2015-07-15 19:32:22 +00001164
Evan Chengf92f5552009-10-14 05:22:03 +00001165 // Early exit if the check of the first PHI source against V2 is MayAlias.
1166 // Other results are not possible.
1167 if (Alias == MayAlias)
1168 return MayAlias;
1169
Evan Chengc10e88d2009-10-13 22:02:20 +00001170 // If all sources of the PHI node NoAlias or MustAlias V2, then returns
1171 // NoAlias / MustAlias. Otherwise, returns MayAlias.
Evan Chengc10e88d2009-10-13 22:02:20 +00001172 for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
1173 Value *V = V1Srcs[i];
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001174
Hal Finkelcc39b672014-07-24 12:16:19 +00001175 AliasResult ThisAlias = aliasCheck(V2, V2Size, V2AAInfo,
1176 V, PNSize, PNAAInfo);
Dan Gohman4e7e7952011-06-03 20:17:36 +00001177 Alias = MergeAliasResults(ThisAlias, Alias);
1178 if (Alias == MayAlias)
1179 break;
Evan Chengc10e88d2009-10-13 22:02:20 +00001180 }
1181
1182 return Alias;
1183}
1184
1185// aliasCheck - Provide a bunch of ad-hoc rules to disambiguate in common cases,
1186// such as array references.
Evan Chengf1f3dd32009-10-13 18:42:04 +00001187//
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001188AliasResult BasicAliasAnalysis::aliasCheck(const Value *V1, uint64_t V1Size,
1189 AAMDNodes V1AAInfo, const Value *V2,
1190 uint64_t V2Size,
1191 AAMDNodes V2AAInfo) {
Dan Gohmancb45bd92010-04-08 18:11:50 +00001192 // If either of the memory references is empty, it doesn't matter what the
1193 // pointer values are.
1194 if (V1Size == 0 || V2Size == 0)
1195 return NoAlias;
1196
Evan Chengf1f3dd32009-10-13 18:42:04 +00001197 // Strip off any casts if they exist.
1198 V1 = V1->stripPointerCasts();
1199 V2 = V2->stripPointerCasts();
1200
Daniel Berlin3459d6e2015-05-05 18:10:49 +00001201 // If V1 or V2 is undef, the result is NoAlias because we can always pick a
1202 // value for undef that aliases nothing in the program.
1203 if (isa<UndefValue>(V1) || isa<UndefValue>(V2))
1204 return NoAlias;
1205
Evan Chengf1f3dd32009-10-13 18:42:04 +00001206 // Are we checking for alias of the same value?
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001207 // Because we look 'through' phi nodes we could look at "Value" pointers from
1208 // different iterations. We must therefore make sure that this is not the
1209 // case. The function isValueEqualInPotentialCycles ensures that this cannot
1210 // happen by looking at the visited phi nodes and making sure they cannot
1211 // reach the value.
1212 if (isValueEqualInPotentialCycles(V1, V2))
1213 return MustAlias;
Evan Chengf1f3dd32009-10-13 18:42:04 +00001214
Duncan Sands19d0b472010-02-16 11:11:14 +00001215 if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
Evan Chengf1f3dd32009-10-13 18:42:04 +00001216 return NoAlias; // Scalars cannot alias each other
1217
1218 // Figure out what objects these things are pointing to if we can.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001219 const Value *O1 = GetUnderlyingObject(V1, *DL, MaxLookupSearchDepth);
1220 const Value *O2 = GetUnderlyingObject(V2, *DL, MaxLookupSearchDepth);
Evan Chengf1f3dd32009-10-13 18:42:04 +00001221
Dan Gohmanccb45842009-11-09 19:29:11 +00001222 // Null values in the default address space don't point to any object, so they
1223 // don't alias any other pointer.
1224 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
1225 if (CPN->getType()->getAddressSpace() == 0)
1226 return NoAlias;
1227 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
1228 if (CPN->getType()->getAddressSpace() == 0)
1229 return NoAlias;
1230
Evan Chengf1f3dd32009-10-13 18:42:04 +00001231 if (O1 != O2) {
1232 // If V1/V2 point to two different objects we know that we have no alias.
Dan Gohman00ef9322010-07-07 14:27:09 +00001233 if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
Evan Chengf1f3dd32009-10-13 18:42:04 +00001234 return NoAlias;
Nick Lewyckyc53e2ec2009-11-14 06:15:14 +00001235
1236 // Constant pointers can't alias with non-const isIdentifiedObject objects.
Dan Gohman00ef9322010-07-07 14:27:09 +00001237 if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
1238 (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
Nick Lewyckyc53e2ec2009-11-14 06:15:14 +00001239 return NoAlias;
1240
Michael Kupersteinf3e663a2013-05-28 08:17:48 +00001241 // Function arguments can't alias with things that are known to be
1242 // unambigously identified at the function level.
1243 if ((isa<Argument>(O1) && isIdentifiedFunctionLocal(O2)) ||
1244 (isa<Argument>(O2) && isIdentifiedFunctionLocal(O1)))
Dan Gohman84f90a32010-07-01 20:08:40 +00001245 return NoAlias;
Evan Chengf1f3dd32009-10-13 18:42:04 +00001246
1247 // Most objects can't alias null.
Dan Gohman00ef9322010-07-07 14:27:09 +00001248 if ((isa<ConstantPointerNull>(O2) && isKnownNonNull(O1)) ||
1249 (isa<ConstantPointerNull>(O1) && isKnownNonNull(O2)))
Evan Chengf1f3dd32009-10-13 18:42:04 +00001250 return NoAlias;
Jakub Staszak07f383f2013-08-24 14:16:00 +00001251
Dan Gohman5b0a8a82010-07-07 14:30:04 +00001252 // If one pointer is the result of a call/invoke or load and the other is a
1253 // non-escaping local object within the same function, then we know the
1254 // object couldn't escape to a point where the call could return it.
1255 //
1256 // Note that if the pointers are in different functions, there are a
1257 // variety of complications. A call with a nocapture argument may still
1258 // temporary store the nocapture argument's value in a temporary memory
1259 // location if that memory location doesn't escape. Or it may pass a
1260 // nocapture value to other functions as long as they don't capture it.
1261 if (isEscapeSource(O1) && isNonEscapingLocalObject(O2))
1262 return NoAlias;
1263 if (isEscapeSource(O2) && isNonEscapingLocalObject(O1))
1264 return NoAlias;
1265 }
1266
Evan Chengf1f3dd32009-10-13 18:42:04 +00001267 // If the size of one access is larger than the entire object on the other
1268 // side, then we know such behavior is undefined and can assume no alias.
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001269 if (DL)
Chandler Carruthecbd1682015-06-17 07:21:38 +00001270 if ((V1Size != MemoryLocation::UnknownSize &&
1271 isObjectSmallerThan(O2, V1Size, *DL, *TLI)) ||
1272 (V2Size != MemoryLocation::UnknownSize &&
1273 isObjectSmallerThan(O1, V2Size, *DL, *TLI)))
Evan Chengf1f3dd32009-10-13 18:42:04 +00001274 return NoAlias;
Jakub Staszak07f383f2013-08-24 14:16:00 +00001275
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001276 // Check the cache before climbing up use-def chains. This also terminates
1277 // otherwise infinitely recursive queries.
Chandler Carruthac80dc72015-06-17 07:18:54 +00001278 LocPair Locs(MemoryLocation(V1, V1Size, V1AAInfo),
1279 MemoryLocation(V2, V2Size, V2AAInfo));
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001280 if (V1 > V2)
1281 std::swap(Locs.first, Locs.second);
1282 std::pair<AliasCacheTy::iterator, bool> Pair =
1283 AliasCache.insert(std::make_pair(Locs, MayAlias));
1284 if (!Pair.second)
1285 return Pair.first->second;
1286
Chris Lattner89288992009-11-26 02:13:03 +00001287 // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
1288 // GEP can't simplify, we don't even look at the PHI cases.
Chris Lattnerb2647b92009-10-17 23:48:54 +00001289 if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
Chris Lattnerd6a2a992003-02-26 19:41:54 +00001290 std::swap(V1, V2);
1291 std::swap(V1Size, V2Size);
Chris Lattner5341c962009-11-26 02:14:59 +00001292 std::swap(O1, O2);
Hal Finkelcc39b672014-07-24 12:16:19 +00001293 std::swap(V1AAInfo, V2AAInfo);
Chris Lattnerd6a2a992003-02-26 19:41:54 +00001294 }
Dan Gohman02538ac2010-10-18 18:04:47 +00001295 if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) {
Hal Finkelcc39b672014-07-24 12:16:19 +00001296 AliasResult Result = aliasGEP(GV1, V1Size, V1AAInfo, V2, V2Size, V2AAInfo, O1, O2);
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001297 if (Result != MayAlias) return AliasCache[Locs] = Result;
Dan Gohman02538ac2010-10-18 18:04:47 +00001298 }
Evan Chengc10e88d2009-10-13 22:02:20 +00001299
1300 if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
1301 std::swap(V1, V2);
1302 std::swap(V1Size, V2Size);
Hal Finkelcc39b672014-07-24 12:16:19 +00001303 std::swap(V1AAInfo, V2AAInfo);
Evan Chengc10e88d2009-10-13 22:02:20 +00001304 }
Dan Gohman02538ac2010-10-18 18:04:47 +00001305 if (const PHINode *PN = dyn_cast<PHINode>(V1)) {
Hal Finkelcc39b672014-07-24 12:16:19 +00001306 AliasResult Result = aliasPHI(PN, V1Size, V1AAInfo,
1307 V2, V2Size, V2AAInfo);
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001308 if (Result != MayAlias) return AliasCache[Locs] = Result;
Dan Gohman02538ac2010-10-18 18:04:47 +00001309 }
Misha Brukman01808ca2005-04-21 21:13:18 +00001310
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001311 if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
1312 std::swap(V1, V2);
1313 std::swap(V1Size, V2Size);
Hal Finkelcc39b672014-07-24 12:16:19 +00001314 std::swap(V1AAInfo, V2AAInfo);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001315 }
Dan Gohman02538ac2010-10-18 18:04:47 +00001316 if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) {
Hal Finkelcc39b672014-07-24 12:16:19 +00001317 AliasResult Result = aliasSelect(S1, V1Size, V1AAInfo,
1318 V2, V2Size, V2AAInfo);
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001319 if (Result != MayAlias) return AliasCache[Locs] = Result;
Dan Gohman02538ac2010-10-18 18:04:47 +00001320 }
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001321
Dan Gohman44da55b2011-01-18 21:16:06 +00001322 // If both pointers are pointing into the same object and one of them
1323 // accesses is accessing the entire object, then the accesses must
1324 // overlap in some way.
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001325 if (DL && O1 == O2)
Chandler Carruthecbd1682015-06-17 07:21:38 +00001326 if ((V1Size != MemoryLocation::UnknownSize &&
1327 isObjectSize(O1, V1Size, *DL, *TLI)) ||
1328 (V2Size != MemoryLocation::UnknownSize &&
1329 isObjectSize(O2, V2Size, *DL, *TLI)))
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001330 return AliasCache[Locs] = PartialAlias;
Dan Gohman44da55b2011-01-18 21:16:06 +00001331
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001332 AliasResult Result =
Chandler Carruthac80dc72015-06-17 07:18:54 +00001333 AliasAnalysis::alias(MemoryLocation(V1, V1Size, V1AAInfo),
1334 MemoryLocation(V2, V2Size, V2AAInfo));
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001335 return AliasCache[Locs] = Result;
Chris Lattnerd6a2a992003-02-26 19:41:54 +00001336}
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001337
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001338bool BasicAliasAnalysis::isValueEqualInPotentialCycles(const Value *V,
1339 const Value *V2) {
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001340 if (V != V2)
1341 return false;
1342
1343 const Instruction *Inst = dyn_cast<Instruction>(V);
1344 if (!Inst)
1345 return true;
1346
Daniel Berlin9e77de22015-03-20 18:05:49 +00001347 if (VisitedPhiBBs.empty())
1348 return true;
1349
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001350 if (VisitedPhiBBs.size() > MaxNumPhiBBsValueReachabilityCheck)
1351 return false;
1352
1353 // Use dominance or loop info if available.
Chandler Carruth73523022014-01-13 13:07:17 +00001354 DominatorTreeWrapperPass *DTWP =
1355 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
Craig Topper9f008862014-04-15 04:59:12 +00001356 DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
Chandler Carruth4f8f3072015-01-17 14:16:18 +00001357 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
1358 LoopInfo *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001359
1360 // Make sure that the visited phis cannot reach the Value. This ensures that
1361 // the Values cannot come from different iterations of a potential cycle the
1362 // phi nodes could be involved in.
Craig Topper46276792014-08-24 23:23:06 +00001363 for (auto *P : VisitedPhiBBs)
1364 if (isPotentiallyReachable(P->begin(), Inst, DT, LI))
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001365 return false;
1366
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001367 return true;
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001368}
1369
1370/// GetIndexDifference - Dest and Src are the variable indices from two
1371/// decomposed GetElementPtr instructions GEP1 and GEP2 which have common base
1372/// pointers. Subtract the GEP2 indices from GEP1 to find the symbolic
1373/// difference between the two pointers.
1374void BasicAliasAnalysis::GetIndexDifference(
1375 SmallVectorImpl<VariableGEPIndex> &Dest,
1376 const SmallVectorImpl<VariableGEPIndex> &Src) {
1377 if (Src.empty())
1378 return;
1379
1380 for (unsigned i = 0, e = Src.size(); i != e; ++i) {
1381 const Value *V = Src[i].V;
Manuel Klimek779cf852015-07-13 13:50:55 +00001382 ExtensionKind Extension = Src[i].Extension;
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001383 int64_t Scale = Src[i].Scale;
1384
1385 // Find V in Dest. This is N^2, but pointer indices almost never have more
1386 // than a few variable indexes.
1387 for (unsigned j = 0, e = Dest.size(); j != e; ++j) {
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001388 if (!isValueEqualInPotentialCycles(Dest[j].V, V) ||
Manuel Klimek779cf852015-07-13 13:50:55 +00001389 Dest[j].Extension != Extension)
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001390 continue;
1391
1392 // If we found it, subtract off Scale V's from the entry in Dest. If it
1393 // goes to zero, remove the entry.
1394 if (Dest[j].Scale != Scale)
1395 Dest[j].Scale -= Scale;
1396 else
1397 Dest.erase(Dest.begin() + j);
1398 Scale = 0;
1399 break;
1400 }
1401
1402 // If we didn't consume this entry, add it to the end of the Dest list.
1403 if (Scale) {
Manuel Klimek779cf852015-07-13 13:50:55 +00001404 VariableGEPIndex Entry = { V, Extension, -Scale };
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001405 Dest.push_back(Entry);
1406 }
1407 }
1408}