blob: 46ca6ee91f5eaf84da7e2b0681267c8d18d9135d [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
Jeff Cohencede1ce2005-01-08 22:01:16 +000016#include "llvm/Analysis/Passes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/SmallPtrSet.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruth66b31302015-01-04 12:03:27 +000020#include "llvm/Analysis/AssumptionCache.h"
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +000021#include "llvm/Analysis/CFG.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000022#include "llvm/Analysis/CaptureTracking.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/Analysis/InstructionSimplify.h"
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +000024#include "llvm/Analysis/LoopInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000025#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000026#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/Constants.h"
29#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000031#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000033#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/GlobalAlias.h"
35#include "llvm/IR/GlobalVariable.h"
36#include "llvm/IR/Instructions.h"
37#include "llvm/IR/IntrinsicInst.h"
38#include "llvm/IR/LLVMContext.h"
39#include "llvm/IR/Operator.h"
Chris Lattnerd82256a2004-03-15 03:36:49 +000040#include "llvm/Pass.h"
Torok Edwin56d06592009-07-11 20:10:48 +000041#include "llvm/Support/ErrorHandling.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000042#include <algorithm>
Chris Lattner35997482003-11-25 18:33:40 +000043using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000044
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +000045/// Cutoff after which to stop analysing a set of phi nodes potentially involved
46/// in a cycle. Because we are analysing 'through' phi nodes we need to be
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +000047/// careful with value equivalence. We use reachability to make sure a value
48/// cannot be involved in a cycle.
49const unsigned MaxNumPhiBBsValueReachabilityCheck = 20;
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +000050
Arnold Schwaighofer1a444482014-03-26 21:30:19 +000051// The max limit of the search depth in DecomposeGEPExpression() and
52// GetUnderlyingObject(), both functions need to use the same search
53// depth otherwise the algorithm in aliasGEP will assert.
54static const unsigned MaxLookupSearchDepth = 6;
55
Chris Lattner2d332972008-06-16 06:30:22 +000056//===----------------------------------------------------------------------===//
57// Useful predicates
58//===----------------------------------------------------------------------===//
Devang Patel09f162c2007-05-01 21:15:47 +000059
Chris Lattnerb35d9b52008-06-16 06:19:11 +000060/// isNonEscapingLocalObject - Return true if the pointer is to a function-local
61/// object that never escapes from the function.
Dan Gohman84f90a32010-07-01 20:08:40 +000062static bool isNonEscapingLocalObject(const Value *V) {
Chris Lattnerfa482582008-06-16 06:28:01 +000063 // If this is a local allocation, check to see if it escapes.
Dan Gohman84f90a32010-07-01 20:08:40 +000064 if (isa<AllocaInst>(V) || isNoAliasCall(V))
Dan Gohman94e61762009-11-19 21:57:48 +000065 // Set StoreCaptures to True so that we can assume in our callers that the
66 // pointer is not the result of a load instruction. Currently
67 // PointerMayBeCaptured doesn't have any special analysis for the
68 // StoreCaptures=false case; if it did, our callers could be refined to be
69 // more precise.
70 return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
Duncan Sands8d65f362009-01-05 21:19:53 +000071
Chris Lattnerfa482582008-06-16 06:28:01 +000072 // If this is an argument that corresponds to a byval or noalias argument,
Duncan Sands8d65f362009-01-05 21:19:53 +000073 // then it has not escaped before entering the function. Check if it escapes
74 // inside the function.
Dan Gohman84f90a32010-07-01 20:08:40 +000075 if (const Argument *A = dyn_cast<Argument>(V))
Richard Osbornea1fffcf2012-11-05 10:48:24 +000076 if (A->hasByValAttr() || A->hasNoAliasAttr())
77 // Note even if the argument is marked nocapture we still need to check
78 // for copies made inside the function. The nocapture attribute only
79 // specifies that there are no copies made that outlive the function.
Dan Gohman84f90a32010-07-01 20:08:40 +000080 return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
Richard Osbornea1fffcf2012-11-05 10:48:24 +000081
Chris Lattnerb35d9b52008-06-16 06:19:11 +000082 return false;
83}
84
Dan Gohman0824aff2010-06-29 00:50:39 +000085/// isEscapeSource - Return true if the pointer is one which would have
86/// been considered an escape by isNonEscapingLocalObject.
Dan Gohman84f90a32010-07-01 20:08:40 +000087static bool isEscapeSource(const Value *V) {
88 if (isa<CallInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V))
89 return true;
Dan Gohman0824aff2010-06-29 00:50:39 +000090
91 // The load case works because isNonEscapingLocalObject considers all
92 // stores to be escapes (it passes true for the StoreCaptures argument
93 // to PointerMayBeCaptured).
94 if (isa<LoadInst>(V))
95 return true;
96
97 return false;
98}
Chris Lattnerb35d9b52008-06-16 06:19:11 +000099
Dan Gohman44da55b2011-01-18 21:16:06 +0000100/// getObjectSize - Return the size of the object specified by V, or
101/// UnknownSize if unknown.
Rafael Espindola5f57f462014-02-21 18:34:28 +0000102static uint64_t getObjectSize(const Value *V, const DataLayout &DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000103 const TargetLibraryInfo &TLI,
Eli Friedman8bc169c2012-02-27 20:46:07 +0000104 bool RoundToAlign = false) {
Nuno Lopes55fff832012-06-21 15:45:28 +0000105 uint64_t Size;
Rafael Espindola5f57f462014-02-21 18:34:28 +0000106 if (getObjectSize(V, Size, &DL, &TLI, RoundToAlign))
Nuno Lopes55fff832012-06-21 15:45:28 +0000107 return Size;
108 return AliasAnalysis::UnknownSize;
Dan Gohman44da55b2011-01-18 21:16:06 +0000109}
110
111/// isObjectSmallerThan - Return true if we can prove that the object specified
112/// by V is smaller than Size.
113static bool isObjectSmallerThan(const Value *V, uint64_t Size,
Rafael Espindola5f57f462014-02-21 18:34:28 +0000114 const DataLayout &DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000115 const TargetLibraryInfo &TLI) {
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000116 // Note that the meanings of the "object" are slightly different in the
117 // following contexts:
118 // c1: llvm::getObjectSize()
119 // c2: llvm.objectsize() intrinsic
120 // c3: isObjectSmallerThan()
121 // c1 and c2 share the same meaning; however, the meaning of "object" in c3
122 // refers to the "entire object".
123 //
124 // Consider this example:
125 // char *p = (char*)malloc(100)
126 // char *q = p+80;
127 //
128 // In the context of c1 and c2, the "object" pointed by q refers to the
129 // stretch of memory of q[0:19]. So, getObjectSize(q) should return 20.
130 //
131 // However, in the context of c3, the "object" refers to the chunk of memory
132 // being allocated. So, the "object" has 100 bytes, and q points to the middle
133 // the "object". In case q is passed to isObjectSmallerThan() as the 1st
134 // parameter, before the llvm::getObjectSize() is called to get the size of
135 // entire object, we should:
136 // - either rewind the pointer q to the base-address of the object in
137 // question (in this case rewind to p), or
138 // - just give up. It is up to caller to make sure the pointer is pointing
139 // to the base address the object.
Jakub Staszak07f383f2013-08-24 14:16:00 +0000140 //
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000141 // We go for 2nd option for simplicity.
142 if (!isIdentifiedObject(V))
143 return false;
144
Eli Friedman8bc169c2012-02-27 20:46:07 +0000145 // This function needs to use the aligned object size because we allow
146 // reads a bit past the end given sufficient alignment.
Rafael Espindola5f57f462014-02-21 18:34:28 +0000147 uint64_t ObjectSize = getObjectSize(V, DL, TLI, /*RoundToAlign*/true);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000148
Dan Gohman44da55b2011-01-18 21:16:06 +0000149 return ObjectSize != AliasAnalysis::UnknownSize && ObjectSize < Size;
150}
151
152/// isObjectSize - Return true if we can prove that the object specified
153/// by V has size Size.
154static bool isObjectSize(const Value *V, uint64_t Size,
Rafael Espindola5f57f462014-02-21 18:34:28 +0000155 const DataLayout &DL, const TargetLibraryInfo &TLI) {
156 uint64_t ObjectSize = getObjectSize(V, DL, TLI);
Dan Gohman44da55b2011-01-18 21:16:06 +0000157 return ObjectSize != AliasAnalysis::UnknownSize && ObjectSize == Size;
Chris Lattner98ad8162008-06-16 06:10:11 +0000158}
159
Chris Lattner2d332972008-06-16 06:30:22 +0000160//===----------------------------------------------------------------------===//
Chris Lattner9f7500f2010-08-18 22:07:29 +0000161// GetElementPtr Instruction Decomposition and Analysis
162//===----------------------------------------------------------------------===//
163
Chris Lattner1b9c3872010-08-18 22:47:56 +0000164namespace {
165 enum ExtensionKind {
166 EK_NotExtended,
167 EK_SignExt,
168 EK_ZeroExt
169 };
Jakub Staszak07f383f2013-08-24 14:16:00 +0000170
Chris Lattner1b9c3872010-08-18 22:47:56 +0000171 struct VariableGEPIndex {
172 const Value *V;
173 ExtensionKind Extension;
174 int64_t Scale;
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000175
176 bool operator==(const VariableGEPIndex &Other) const {
177 return V == Other.V && Extension == Other.Extension &&
178 Scale == Other.Scale;
179 }
180
181 bool operator!=(const VariableGEPIndex &Other) const {
182 return !operator==(Other);
183 }
Chris Lattner1b9c3872010-08-18 22:47:56 +0000184 };
185}
186
Chris Lattner9f7500f2010-08-18 22:07:29 +0000187
188/// GetLinearExpression - Analyze the specified value as a linear expression:
189/// "A*V + B", where A and B are constant integers. Return the scale and offset
Chris Lattner3decde92010-08-18 23:09:49 +0000190/// values as APInts and return V as a Value*, and return whether we looked
191/// through any sign or zero extends. The incoming Value is known to have
192/// IntegerType and it may already be sign or zero extended.
193///
194/// Note that this looks through extends, so the high bits may not be
195/// represented in the result.
Chris Lattner9f7500f2010-08-18 22:07:29 +0000196static Value *GetLinearExpression(Value *V, APInt &Scale, APInt &Offset,
Chris Lattner3decde92010-08-18 23:09:49 +0000197 ExtensionKind &Extension,
Hal Finkel60db0582014-09-07 18:57:58 +0000198 const DataLayout &DL, unsigned Depth,
Chandler Carruth66b31302015-01-04 12:03:27 +0000199 AssumptionCache *AC, DominatorTree *DT) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000200 assert(V->getType()->isIntegerTy() && "Not an integer value");
201
202 // Limit our recursion depth.
203 if (Depth == 6) {
204 Scale = 1;
205 Offset = 0;
206 return V;
207 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000208
Hal Finkel45ba2c12014-11-13 09:16:54 +0000209 if (ConstantInt *Const = dyn_cast<ConstantInt>(V)) {
210 // if it's a constant, just convert it to an offset
211 // and remove the variable.
212 Offset += Const->getValue();
213 assert(Scale == 0 && "Constant values don't have a scale");
214 return V;
215 }
216
Chris Lattner9f7500f2010-08-18 22:07:29 +0000217 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(V)) {
218 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
219 switch (BOp->getOpcode()) {
220 default: break;
221 case Instruction::Or:
222 // X|C == X+C if all the bits in C are unset in X. Otherwise we can't
223 // analyze it.
Chandler Carruth66b31302015-01-04 12:03:27 +0000224 if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), &DL, 0, AC,
225 BOp, DT))
Chris Lattner9f7500f2010-08-18 22:07:29 +0000226 break;
227 // FALL THROUGH.
228 case Instruction::Add:
Chris Lattner3decde92010-08-18 23:09:49 +0000229 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
Chandler Carruth66b31302015-01-04 12:03:27 +0000230 DL, Depth + 1, AC, DT);
Chris Lattner9f7500f2010-08-18 22:07:29 +0000231 Offset += RHSC->getValue();
232 return V;
233 case Instruction::Mul:
Chris Lattner3decde92010-08-18 23:09:49 +0000234 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
Chandler Carruth66b31302015-01-04 12:03:27 +0000235 DL, Depth + 1, AC, DT);
Chris Lattner9f7500f2010-08-18 22:07:29 +0000236 Offset *= RHSC->getValue();
237 Scale *= RHSC->getValue();
238 return V;
239 case Instruction::Shl:
Chris Lattner3decde92010-08-18 23:09:49 +0000240 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
Chandler Carruth66b31302015-01-04 12:03:27 +0000241 DL, Depth + 1, AC, DT);
Chris Lattner9f7500f2010-08-18 22:07:29 +0000242 Offset <<= RHSC->getValue().getLimitedValue();
243 Scale <<= RHSC->getValue().getLimitedValue();
244 return V;
245 }
246 }
247 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000248
Chris Lattner9f7500f2010-08-18 22:07:29 +0000249 // Since GEP indices are sign extended anyway, we don't care about the high
Chris Lattner3decde92010-08-18 23:09:49 +0000250 // bits of a sign or zero extended value - just scales and offsets. The
251 // extensions have to be consistent though.
252 if ((isa<SExtInst>(V) && Extension != EK_ZeroExt) ||
253 (isa<ZExtInst>(V) && Extension != EK_SignExt)) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000254 Value *CastOp = cast<CastInst>(V)->getOperand(0);
255 unsigned OldWidth = Scale.getBitWidth();
256 unsigned SmallWidth = CastOp->getType()->getPrimitiveSizeInBits();
Jay Foad583abbc2010-12-07 08:25:19 +0000257 Scale = Scale.trunc(SmallWidth);
258 Offset = Offset.trunc(SmallWidth);
Chris Lattner3decde92010-08-18 23:09:49 +0000259 Extension = isa<SExtInst>(V) ? EK_SignExt : EK_ZeroExt;
260
Chandler Carruth66b31302015-01-04 12:03:27 +0000261 Value *Result = GetLinearExpression(CastOp, Scale, Offset, Extension, DL,
262 Depth + 1, AC, DT);
Jay Foad583abbc2010-12-07 08:25:19 +0000263 Scale = Scale.zext(OldWidth);
Hal Finkel45ba2c12014-11-13 09:16:54 +0000264
265 // We have to sign-extend even if Extension == EK_ZeroExt as we can't
266 // decompose a sign extension (i.e. zext(x - 1) != zext(x) - zext(-1)).
267 Offset = Offset.sext(OldWidth);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000268
Chris Lattner9f7500f2010-08-18 22:07:29 +0000269 return Result;
270 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000271
Chris Lattner9f7500f2010-08-18 22:07:29 +0000272 Scale = 1;
273 Offset = 0;
274 return V;
275}
276
277/// DecomposeGEPExpression - If V is a symbolic pointer expression, decompose it
278/// into a base pointer with a constant offset and a number of scaled symbolic
279/// offsets.
280///
281/// The scaled symbolic offsets (represented by pairs of a Value* and a scale in
282/// the VarIndices vector) are Value*'s that are known to be scaled by the
283/// specified amount, but which may have other unrepresented high bits. As such,
284/// the gep cannot necessarily be reconstructed from its decomposed form.
285///
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000286/// When DataLayout is around, this function is capable of analyzing everything
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000287/// that GetUnderlyingObject can look through. To be able to do that
288/// GetUnderlyingObject and DecomposeGEPExpression must use the same search
289/// depth (MaxLookupSearchDepth).
290/// When DataLayout not is around, it just looks through pointer casts.
Chris Lattner9f7500f2010-08-18 22:07:29 +0000291///
292static const Value *
293DecomposeGEPExpression(const Value *V, int64_t &BaseOffs,
Chris Lattner1b9c3872010-08-18 22:47:56 +0000294 SmallVectorImpl<VariableGEPIndex> &VarIndices,
Hal Finkel60db0582014-09-07 18:57:58 +0000295 bool &MaxLookupReached, const DataLayout *DL,
Chandler Carruth66b31302015-01-04 12:03:27 +0000296 AssumptionCache *AC, DominatorTree *DT) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000297 // Limit recursion depth to limit compile time in crazy cases.
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000298 unsigned MaxLookup = MaxLookupSearchDepth;
299 MaxLookupReached = false;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000300
Chris Lattner9f7500f2010-08-18 22:07:29 +0000301 BaseOffs = 0;
302 do {
303 // See if this is a bitcast or GEP.
304 const Operator *Op = dyn_cast<Operator>(V);
Craig Topper9f008862014-04-15 04:59:12 +0000305 if (!Op) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000306 // The only non-operator case we can handle are GlobalAliases.
307 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
308 if (!GA->mayBeOverridden()) {
309 V = GA->getAliasee();
310 continue;
311 }
312 }
313 return V;
314 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000315
Matt Arsenault70f4db882014-07-15 00:56:40 +0000316 if (Op->getOpcode() == Instruction::BitCast ||
317 Op->getOpcode() == Instruction::AddrSpaceCast) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000318 V = Op->getOperand(0);
319 continue;
320 }
Dan Gohman05b18f12010-12-15 20:49:55 +0000321
Chris Lattner9f7500f2010-08-18 22:07:29 +0000322 const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
Craig Topper9f008862014-04-15 04:59:12 +0000323 if (!GEPOp) {
Dan Gohman0573b552011-05-24 18:24:08 +0000324 // If it's not a GEP, hand it off to SimplifyInstruction to see if it
325 // can come up with something. This matches what GetUnderlyingObject does.
326 if (const Instruction *I = dyn_cast<Instruction>(V))
Chandler Carruth66b31302015-01-04 12:03:27 +0000327 // TODO: Get a DominatorTree and AssumptionCache and use them here
Hal Finkel60db0582014-09-07 18:57:58 +0000328 // (these are both now available in this function, but this should be
329 // updated when GetUnderlyingObject is updated). TLI should be
330 // provided also.
Dan Gohman0573b552011-05-24 18:24:08 +0000331 if (const Value *Simplified =
Rafael Espindola5f57f462014-02-21 18:34:28 +0000332 SimplifyInstruction(const_cast<Instruction *>(I), DL)) {
Dan Gohman0573b552011-05-24 18:24:08 +0000333 V = Simplified;
334 continue;
335 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000336
Chris Lattner9f7500f2010-08-18 22:07:29 +0000337 return V;
Dan Gohman0573b552011-05-24 18:24:08 +0000338 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000339
Chris Lattner9f7500f2010-08-18 22:07:29 +0000340 // Don't attempt to analyze GEPs over unsized objects.
Matt Arsenaultfa252722013-09-27 22:18:51 +0000341 if (!GEPOp->getOperand(0)->getType()->getPointerElementType()->isSized())
Chris Lattner9f7500f2010-08-18 22:07:29 +0000342 return V;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000343
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000344 // If we are lacking DataLayout information, we can't compute the offets of
Chris Lattner9f7500f2010-08-18 22:07:29 +0000345 // elements computed by GEPs. However, we can handle bitcast equivalent
346 // GEPs.
Craig Topper9f008862014-04-15 04:59:12 +0000347 if (!DL) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000348 if (!GEPOp->hasAllZeroIndices())
349 return V;
350 V = GEPOp->getOperand(0);
351 continue;
352 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000353
Matt Arsenaulta8fe22b2013-11-16 00:36:43 +0000354 unsigned AS = GEPOp->getPointerAddressSpace();
Chris Lattner9f7500f2010-08-18 22:07:29 +0000355 // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
356 gep_type_iterator GTI = gep_type_begin(GEPOp);
357 for (User::const_op_iterator I = GEPOp->op_begin()+1,
358 E = GEPOp->op_end(); I != E; ++I) {
359 Value *Index = *I;
360 // Compute the (potentially symbolic) offset in bytes for this index.
Chris Lattner229907c2011-07-18 04:54:35 +0000361 if (StructType *STy = dyn_cast<StructType>(*GTI++)) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000362 // For a struct, add the member offset.
363 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
364 if (FieldNo == 0) continue;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000365
Rafael Espindola5f57f462014-02-21 18:34:28 +0000366 BaseOffs += DL->getStructLayout(STy)->getElementOffset(FieldNo);
Chris Lattner9f7500f2010-08-18 22:07:29 +0000367 continue;
368 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000369
Chris Lattner9f7500f2010-08-18 22:07:29 +0000370 // For an array/pointer, add the element offset, explicitly scaled.
371 if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
372 if (CIdx->isZero()) continue;
Rafael Espindola5f57f462014-02-21 18:34:28 +0000373 BaseOffs += DL->getTypeAllocSize(*GTI)*CIdx->getSExtValue();
Chris Lattner9f7500f2010-08-18 22:07:29 +0000374 continue;
375 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000376
Rafael Espindola5f57f462014-02-21 18:34:28 +0000377 uint64_t Scale = DL->getTypeAllocSize(*GTI);
Chris Lattner1b9c3872010-08-18 22:47:56 +0000378 ExtensionKind Extension = EK_NotExtended;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000379
Chris Lattner3decde92010-08-18 23:09:49 +0000380 // If the integer type is smaller than the pointer size, it is implicitly
381 // sign extended to pointer size.
Matt Arsenaultfa252722013-09-27 22:18:51 +0000382 unsigned Width = Index->getType()->getIntegerBitWidth();
Rafael Espindola5f57f462014-02-21 18:34:28 +0000383 if (DL->getPointerSizeInBits(AS) > Width)
Chris Lattner3decde92010-08-18 23:09:49 +0000384 Extension = EK_SignExt;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000385
Chris Lattner3decde92010-08-18 23:09:49 +0000386 // Use GetLinearExpression to decompose the index into a C1*V+C2 form.
Chris Lattner9f7500f2010-08-18 22:07:29 +0000387 APInt IndexScale(Width, 0), IndexOffset(Width, 0);
Chris Lattner3decde92010-08-18 23:09:49 +0000388 Index = GetLinearExpression(Index, IndexScale, IndexOffset, Extension,
Chandler Carruth66b31302015-01-04 12:03:27 +0000389 *DL, 0, AC, DT);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000390
Chris Lattner9f7500f2010-08-18 22:07:29 +0000391 // The GEP index scale ("Scale") scales C1*V+C2, yielding (C1*V+C2)*Scale.
392 // This gives us an aggregate computation of (C1*Scale)*V + C2*Scale.
Eli Friedmanab3a1282010-09-15 20:08:03 +0000393 BaseOffs += IndexOffset.getSExtValue()*Scale;
394 Scale *= IndexScale.getSExtValue();
Jakub Staszak07f383f2013-08-24 14:16:00 +0000395
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000396 // If we already had an occurrence of this index variable, merge this
Chris Lattner9f7500f2010-08-18 22:07:29 +0000397 // scale into it. For example, we want to handle:
398 // A[x][x] -> x*16 + x*4 -> x*20
399 // This also ensures that 'x' only appears in the index list once.
400 for (unsigned i = 0, e = VarIndices.size(); i != e; ++i) {
Chris Lattner1b9c3872010-08-18 22:47:56 +0000401 if (VarIndices[i].V == Index &&
402 VarIndices[i].Extension == Extension) {
403 Scale += VarIndices[i].Scale;
Chris Lattner9f7500f2010-08-18 22:07:29 +0000404 VarIndices.erase(VarIndices.begin()+i);
405 break;
406 }
407 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000408
Chris Lattner9f7500f2010-08-18 22:07:29 +0000409 // Make sure that we have a scale that makes sense for this target's
410 // pointer size.
Rafael Espindola5f57f462014-02-21 18:34:28 +0000411 if (unsigned ShiftBits = 64 - DL->getPointerSizeInBits(AS)) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000412 Scale <<= ShiftBits;
Eli Friedmanab3a1282010-09-15 20:08:03 +0000413 Scale = (int64_t)Scale >> ShiftBits;
Chris Lattner9f7500f2010-08-18 22:07:29 +0000414 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000415
Chris Lattner1b9c3872010-08-18 22:47:56 +0000416 if (Scale) {
Jeffrey Yasskin6381c012011-07-27 06:22:51 +0000417 VariableGEPIndex Entry = {Index, Extension,
418 static_cast<int64_t>(Scale)};
Chris Lattner1b9c3872010-08-18 22:47:56 +0000419 VarIndices.push_back(Entry);
420 }
Chris Lattner9f7500f2010-08-18 22:07:29 +0000421 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000422
Chris Lattner9f7500f2010-08-18 22:07:29 +0000423 // Analyze the base pointer next.
424 V = GEPOp->getOperand(0);
425 } while (--MaxLookup);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000426
Chris Lattner9f7500f2010-08-18 22:07:29 +0000427 // If the chain of expressions is too deep, just return early.
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000428 MaxLookupReached = true;
Chris Lattner9f7500f2010-08-18 22:07:29 +0000429 return V;
430}
431
Chris Lattner9f7500f2010-08-18 22:07:29 +0000432//===----------------------------------------------------------------------===//
Dan Gohman0824aff2010-06-29 00:50:39 +0000433// BasicAliasAnalysis Pass
Chris Lattner2d332972008-06-16 06:30:22 +0000434//===----------------------------------------------------------------------===//
435
Dan Gohman00ef9322010-07-07 14:27:09 +0000436#ifndef NDEBUG
Dan Gohman0824aff2010-06-29 00:50:39 +0000437static const Function *getParent(const Value *V) {
Dan Gohman1be9e7c2010-06-29 18:12:34 +0000438 if (const Instruction *inst = dyn_cast<Instruction>(V))
Dan Gohman0824aff2010-06-29 00:50:39 +0000439 return inst->getParent()->getParent();
440
Dan Gohman1be9e7c2010-06-29 18:12:34 +0000441 if (const Argument *arg = dyn_cast<Argument>(V))
Dan Gohman0824aff2010-06-29 00:50:39 +0000442 return arg->getParent();
443
Craig Topper9f008862014-04-15 04:59:12 +0000444 return nullptr;
Dan Gohman0824aff2010-06-29 00:50:39 +0000445}
446
Dan Gohman84f90a32010-07-01 20:08:40 +0000447static bool notDifferentParent(const Value *O1, const Value *O2) {
448
449 const Function *F1 = getParent(O1);
450 const Function *F2 = getParent(O2);
451
Dan Gohman0824aff2010-06-29 00:50:39 +0000452 return !F1 || !F2 || F1 == F2;
453}
Benjamin Kramer80b7bc02010-06-29 10:03:11 +0000454#endif
Dan Gohman0824aff2010-06-29 00:50:39 +0000455
Chris Lattner2d332972008-06-16 06:30:22 +0000456namespace {
Dan Gohmanda85ed82010-10-19 23:09:08 +0000457 /// BasicAliasAnalysis - This is the primary alias analysis implementation.
458 struct BasicAliasAnalysis : public ImmutablePass, public AliasAnalysis {
Chris Lattner2d332972008-06-16 06:30:22 +0000459 static char ID; // Class identification, replacement for typeinfo
Benjamin Kramer6c2649c2012-09-05 16:49:37 +0000460 BasicAliasAnalysis() : ImmutablePass(ID) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000461 initializeBasicAliasAnalysisPass(*PassRegistry::getPassRegistry());
462 }
Dan Gohman0824aff2010-06-29 00:50:39 +0000463
Craig Toppere9ba7592014-03-05 07:30:04 +0000464 void initializePass() override {
Dan Gohman02538ac2010-10-18 18:04:47 +0000465 InitializeAliasAnalysis(this);
466 }
467
Craig Toppere9ba7592014-03-05 07:30:04 +0000468 void getAnalysisUsage(AnalysisUsage &AU) const override {
Dan Gohman02538ac2010-10-18 18:04:47 +0000469 AU.addRequired<AliasAnalysis>();
Chandler Carruth66b31302015-01-04 12:03:27 +0000470 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000471 AU.addRequired<TargetLibraryInfoWrapperPass>();
Dan Gohman02538ac2010-10-18 18:04:47 +0000472 }
473
Craig Toppere9ba7592014-03-05 07:30:04 +0000474 AliasResult alias(const Location &LocA, const Location &LocB) override {
Dan Gohmanfb02cec2011-06-04 00:31:50 +0000475 assert(AliasCache.empty() && "AliasCache must be cleared after use!");
Dan Gohman41f14cf2010-09-14 21:25:10 +0000476 assert(notDifferentParent(LocA.Ptr, LocB.Ptr) &&
Dan Gohman00ef9322010-07-07 14:27:09 +0000477 "BasicAliasAnalysis doesn't support interprocedural queries.");
Hal Finkelcc39b672014-07-24 12:16:19 +0000478 AliasResult Alias = aliasCheck(LocA.Ptr, LocA.Size, LocA.AATags,
479 LocB.Ptr, LocB.Size, LocB.AATags);
Benjamin Kramer6c2649c2012-09-05 16:49:37 +0000480 // AliasCache rarely has more than 1 or 2 elements, always use
481 // shrink_and_clear so it quickly returns to the inline capacity of the
482 // SmallDenseMap if it ever grows larger.
483 // FIXME: This should really be shrink_to_inline_capacity_and_clear().
484 AliasCache.shrink_and_clear();
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +0000485 VisitedPhiBBs.clear();
Evan Chengb3ccb642009-10-14 06:46:26 +0000486 return Alias;
Evan Chengc10e88d2009-10-13 22:02:20 +0000487 }
Chris Lattner2d332972008-06-16 06:30:22 +0000488
Craig Toppere9ba7592014-03-05 07:30:04 +0000489 ModRefResult getModRefInfo(ImmutableCallSite CS,
490 const Location &Loc) override;
Dan Gohman5f1702e2010-08-06 01:25:49 +0000491
Craig Toppere9ba7592014-03-05 07:30:04 +0000492 ModRefResult getModRefInfo(ImmutableCallSite CS1,
Hal Finkel93046912014-07-25 21:13:35 +0000493 ImmutableCallSite CS2) override;
Owen Anderson98a36172009-02-05 23:36:27 +0000494
Chris Lattner2d332972008-06-16 06:30:22 +0000495 /// pointsToConstantMemory - Chase pointers until we find a (constant
496 /// global) or not.
Craig Toppere9ba7592014-03-05 07:30:04 +0000497 bool pointsToConstantMemory(const Location &Loc, bool OrLocal) override;
Dan Gohman5f1702e2010-08-06 01:25:49 +0000498
Hal Finkel354e23b2014-07-17 01:28:25 +0000499 /// Get the location associated with a pointer argument of a callsite.
500 Location getArgLocation(ImmutableCallSite CS, unsigned ArgIdx,
501 ModRefResult &Mask) override;
502
Dan Gohman5f1702e2010-08-06 01:25:49 +0000503 /// getModRefBehavior - Return the behavior when calling the given
504 /// call site.
Craig Toppere9ba7592014-03-05 07:30:04 +0000505 ModRefBehavior getModRefBehavior(ImmutableCallSite CS) override;
Dan Gohman5f1702e2010-08-06 01:25:49 +0000506
507 /// getModRefBehavior - Return the behavior when calling the given function.
508 /// For use when the call site is not known.
Craig Toppere9ba7592014-03-05 07:30:04 +0000509 ModRefBehavior getModRefBehavior(const Function *F) override;
Chris Lattner2d332972008-06-16 06:30:22 +0000510
Chris Lattneraf362f02010-01-20 19:26:14 +0000511 /// getAdjustedAnalysisPointer - This method is used when a pass implements
Dan Gohmane0d5c452010-08-05 23:48:14 +0000512 /// an analysis interface through multiple inheritance. If needed, it
513 /// should override this to adjust the this pointer as needed for the
514 /// specified pass info.
Craig Toppere9ba7592014-03-05 07:30:04 +0000515 void *getAdjustedAnalysisPointer(const void *ID) override {
Owen Andersona7aed182010-08-06 18:33:48 +0000516 if (ID == &AliasAnalysis::ID)
Chris Lattneraf362f02010-01-20 19:26:14 +0000517 return (AliasAnalysis*)this;
518 return this;
519 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000520
Chris Lattner2d332972008-06-16 06:30:22 +0000521 private:
Dan Gohmanfb02cec2011-06-04 00:31:50 +0000522 // AliasCache - Track alias queries to guard against recursion.
523 typedef std::pair<Location, Location> LocPair;
Benjamin Kramer6c2649c2012-09-05 16:49:37 +0000524 typedef SmallDenseMap<LocPair, AliasResult, 8> AliasCacheTy;
Dan Gohmanfb02cec2011-06-04 00:31:50 +0000525 AliasCacheTy AliasCache;
526
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +0000527 /// \brief Track phi nodes we have visited. When interpret "Value" pointer
528 /// equality as value equality we need to make sure that the "Value" is not
529 /// part of a cycle. Otherwise, two uses could come from different
530 /// "iterations" of a cycle and see different values for the same "Value"
531 /// pointer.
532 /// The following example shows the problem:
533 /// %p = phi(%alloca1, %addr2)
534 /// %l = load %ptr
535 /// %addr1 = gep, %alloca2, 0, %l
536 /// %addr2 = gep %alloca2, 0, (%l + 1)
537 /// alias(%p, %addr1) -> MayAlias !
538 /// store %l, ...
539 SmallPtrSet<const BasicBlock*, 8> VisitedPhiBBs;
540
Dan Gohmanfb02cec2011-06-04 00:31:50 +0000541 // Visited - Track instructions visited by pointsToConstantMemory.
Dan Gohman7c34ece2010-06-28 21:16:52 +0000542 SmallPtrSet<const Value*, 16> Visited;
Evan Cheng31565b32009-10-14 05:05:02 +0000543
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +0000544 /// \brief Check whether two Values can be considered equivalent.
545 ///
546 /// In addition to pointer equivalence of \p V1 and \p V2 this checks
547 /// whether they can not be part of a cycle in the value graph by looking at
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +0000548 /// all visited phi nodes an making sure that the phis cannot reach the
549 /// value. We have to do this because we are looking through phi nodes (That
550 /// is we say noalias(V, phi(VA, VB)) if noalias(V, VA) and noalias(V, VB).
551 bool isValueEqualInPotentialCycles(const Value *V1, const Value *V2);
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +0000552
553 /// \brief Dest and Src are the variable indices from two decomposed
554 /// GetElementPtr instructions GEP1 and GEP2 which have common base
555 /// pointers. Subtract the GEP2 indices from GEP1 to find the symbolic
556 /// difference between the two pointers.
557 void GetIndexDifference(SmallVectorImpl<VariableGEPIndex> &Dest,
558 const SmallVectorImpl<VariableGEPIndex> &Src);
559
Chris Lattner98e253262009-11-23 16:45:27 +0000560 // aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP
561 // instruction against another.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000562 AliasResult aliasGEP(const GEPOperator *V1, uint64_t V1Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000563 const AAMDNodes &V1AAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +0000564 const Value *V2, uint64_t V2Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000565 const AAMDNodes &V2AAInfo,
Chris Lattner5341c962009-11-26 02:14:59 +0000566 const Value *UnderlyingV1, const Value *UnderlyingV2);
Evan Chengc10e88d2009-10-13 22:02:20 +0000567
Chris Lattner98e253262009-11-23 16:45:27 +0000568 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI
569 // instruction against another.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000570 AliasResult aliasPHI(const PHINode *PN, uint64_t PNSize,
Hal Finkelcc39b672014-07-24 12:16:19 +0000571 const AAMDNodes &PNAAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +0000572 const Value *V2, uint64_t V2Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000573 const AAMDNodes &V2AAInfo);
Evan Chengc10e88d2009-10-13 22:02:20 +0000574
Dan Gohman3b7ba5f2009-10-26 21:55:43 +0000575 /// aliasSelect - Disambiguate a Select instruction against another value.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000576 AliasResult aliasSelect(const SelectInst *SI, uint64_t SISize,
Hal Finkelcc39b672014-07-24 12:16:19 +0000577 const AAMDNodes &SIAAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +0000578 const Value *V2, uint64_t V2Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000579 const AAMDNodes &V2AAInfo);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +0000580
Dan Gohmanf372cf82010-10-19 22:54:46 +0000581 AliasResult aliasCheck(const Value *V1, uint64_t V1Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000582 AAMDNodes V1AATag,
Dan Gohmanf372cf82010-10-19 22:54:46 +0000583 const Value *V2, uint64_t V2Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000584 AAMDNodes V2AATag);
Chris Lattner2d332972008-06-16 06:30:22 +0000585 };
586} // End of anonymous namespace
587
588// Register this pass...
589char BasicAliasAnalysis::ID = 0;
Owen Anderson653cb032011-09-06 23:33:25 +0000590INITIALIZE_AG_PASS_BEGIN(BasicAliasAnalysis, AliasAnalysis, "basicaa",
Dan Gohmanda85ed82010-10-19 23:09:08 +0000591 "Basic Alias Analysis (stateless AA impl)",
Dan Gohman02538ac2010-10-18 18:04:47 +0000592 false, true, false)
Chandler Carruth66b31302015-01-04 12:03:27 +0000593INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000594INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Owen Anderson653cb032011-09-06 23:33:25 +0000595INITIALIZE_AG_PASS_END(BasicAliasAnalysis, AliasAnalysis, "basicaa",
596 "Basic Alias Analysis (stateless AA impl)",
597 false, true, false)
598
Chris Lattner2d332972008-06-16 06:30:22 +0000599
600ImmutablePass *llvm::createBasicAliasAnalysisPass() {
601 return new BasicAliasAnalysis();
602}
603
Dan Gohman9130bad2010-11-08 16:45:26 +0000604/// pointsToConstantMemory - Returns whether the given pointer value
605/// points to memory that is local to the function, with global constants being
606/// considered local to all functions.
607bool
608BasicAliasAnalysis::pointsToConstantMemory(const Location &Loc, bool OrLocal) {
609 assert(Visited.empty() && "Visited must be cleared after use!");
Chris Lattner2d332972008-06-16 06:30:22 +0000610
Dan Gohman142ff822010-11-08 20:26:19 +0000611 unsigned MaxLookup = 8;
Dan Gohman9130bad2010-11-08 16:45:26 +0000612 SmallVector<const Value *, 16> Worklist;
613 Worklist.push_back(Loc.Ptr);
614 do {
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000615 const Value *V = GetUnderlyingObject(Worklist.pop_back_val(), DL);
David Blaikie70573dc2014-11-19 07:49:26 +0000616 if (!Visited.insert(V).second) {
Dan Gohman9130bad2010-11-08 16:45:26 +0000617 Visited.clear();
618 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
619 }
Dan Gohman5f1702e2010-08-06 01:25:49 +0000620
Dan Gohman9130bad2010-11-08 16:45:26 +0000621 // An alloca instruction defines local memory.
622 if (OrLocal && isa<AllocaInst>(V))
623 continue;
624
625 // A global constant counts as local memory for our purposes.
626 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
627 // Note: this doesn't require GV to be "ODR" because it isn't legal for a
628 // global to be marked constant in some modules and non-constant in
629 // others. GV may even be a declaration, not a definition.
630 if (!GV->isConstant()) {
631 Visited.clear();
632 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
633 }
634 continue;
635 }
636
637 // If both select values point to local memory, then so does the select.
638 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
639 Worklist.push_back(SI->getTrueValue());
640 Worklist.push_back(SI->getFalseValue());
641 continue;
642 }
643
644 // If all values incoming to a phi node point to local memory, then so does
645 // the phi.
646 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
Dan Gohman142ff822010-11-08 20:26:19 +0000647 // Don't bother inspecting phi nodes with many operands.
648 if (PN->getNumIncomingValues() > MaxLookup) {
649 Visited.clear();
650 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
651 }
Dan Gohman9130bad2010-11-08 16:45:26 +0000652 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
653 Worklist.push_back(PN->getIncomingValue(i));
654 continue;
655 }
656
657 // Otherwise be conservative.
658 Visited.clear();
659 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
660
Dan Gohman142ff822010-11-08 20:26:19 +0000661 } while (!Worklist.empty() && --MaxLookup);
Dan Gohman9130bad2010-11-08 16:45:26 +0000662
663 Visited.clear();
Dan Gohman142ff822010-11-08 20:26:19 +0000664 return Worklist.empty();
Chris Lattner2d332972008-06-16 06:30:22 +0000665}
666
Hal Finkel354e23b2014-07-17 01:28:25 +0000667static bool isMemsetPattern16(const Function *MS,
668 const TargetLibraryInfo &TLI) {
669 if (TLI.has(LibFunc::memset_pattern16) &&
670 MS->getName() == "memset_pattern16") {
671 FunctionType *MemsetType = MS->getFunctionType();
672 if (!MemsetType->isVarArg() && MemsetType->getNumParams() == 3 &&
673 isa<PointerType>(MemsetType->getParamType(0)) &&
674 isa<PointerType>(MemsetType->getParamType(1)) &&
675 isa<IntegerType>(MemsetType->getParamType(2)))
676 return true;
677 }
678
679 return false;
680}
681
Dan Gohman5f1702e2010-08-06 01:25:49 +0000682/// getModRefBehavior - Return the behavior when calling the given call site.
683AliasAnalysis::ModRefBehavior
684BasicAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
685 if (CS.doesNotAccessMemory())
686 // Can't do better than this.
687 return DoesNotAccessMemory;
688
689 ModRefBehavior Min = UnknownModRefBehavior;
690
691 // If the callsite knows it only reads memory, don't return worse
692 // than that.
693 if (CS.onlyReadsMemory())
694 Min = OnlyReadsMemory;
695
696 // The AliasAnalysis base class has some smarts, lets use them.
Dan Gohman2694e142010-11-10 01:02:18 +0000697 return ModRefBehavior(AliasAnalysis::getModRefBehavior(CS) & Min);
Dan Gohman5f1702e2010-08-06 01:25:49 +0000698}
699
700/// getModRefBehavior - Return the behavior when calling the given function.
701/// For use when the call site is not known.
702AliasAnalysis::ModRefBehavior
703BasicAliasAnalysis::getModRefBehavior(const Function *F) {
Dan Gohmane461d7d2010-11-08 16:08:43 +0000704 // If the function declares it doesn't access memory, we can't do better.
Dan Gohman5f1702e2010-08-06 01:25:49 +0000705 if (F->doesNotAccessMemory())
Dan Gohman5f1702e2010-08-06 01:25:49 +0000706 return DoesNotAccessMemory;
Dan Gohmane461d7d2010-11-08 16:08:43 +0000707
708 // For intrinsics, we can check the table.
709 if (unsigned iid = F->getIntrinsicID()) {
710#define GET_INTRINSIC_MODREF_BEHAVIOR
Chandler Carruthdb25c6c2013-01-02 12:09:16 +0000711#include "llvm/IR/Intrinsics.gen"
Dan Gohmane461d7d2010-11-08 16:08:43 +0000712#undef GET_INTRINSIC_MODREF_BEHAVIOR
713 }
714
Dan Gohman2694e142010-11-10 01:02:18 +0000715 ModRefBehavior Min = UnknownModRefBehavior;
716
Dan Gohmane461d7d2010-11-08 16:08:43 +0000717 // If the function declares it only reads memory, go with that.
Dan Gohman5f1702e2010-08-06 01:25:49 +0000718 if (F->onlyReadsMemory())
Dan Gohman2694e142010-11-10 01:02:18 +0000719 Min = OnlyReadsMemory;
Dan Gohman5f1702e2010-08-06 01:25:49 +0000720
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000721 const TargetLibraryInfo &TLI =
722 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Hal Finkel354e23b2014-07-17 01:28:25 +0000723 if (isMemsetPattern16(F, TLI))
724 Min = OnlyAccessesArgumentPointees;
725
Dan Gohmane461d7d2010-11-08 16:08:43 +0000726 // Otherwise be conservative.
Dan Gohman2694e142010-11-10 01:02:18 +0000727 return ModRefBehavior(AliasAnalysis::getModRefBehavior(F) & Min);
Dan Gohman5f1702e2010-08-06 01:25:49 +0000728}
Owen Anderson98a36172009-02-05 23:36:27 +0000729
Hal Finkel354e23b2014-07-17 01:28:25 +0000730AliasAnalysis::Location
731BasicAliasAnalysis::getArgLocation(ImmutableCallSite CS, unsigned ArgIdx,
732 ModRefResult &Mask) {
733 Location Loc = AliasAnalysis::getArgLocation(CS, ArgIdx, Mask);
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000734 const TargetLibraryInfo &TLI =
735 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Hal Finkel354e23b2014-07-17 01:28:25 +0000736 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
737 if (II != nullptr)
738 switch (II->getIntrinsicID()) {
739 default: break;
740 case Intrinsic::memset:
741 case Intrinsic::memcpy:
742 case Intrinsic::memmove: {
743 assert((ArgIdx == 0 || ArgIdx == 1) &&
744 "Invalid argument index for memory intrinsic");
745 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getArgOperand(2)))
746 Loc.Size = LenCI->getZExtValue();
747 assert(Loc.Ptr == II->getArgOperand(ArgIdx) &&
748 "Memory intrinsic location pointer not argument?");
749 Mask = ArgIdx ? Ref : Mod;
750 break;
751 }
752 case Intrinsic::lifetime_start:
753 case Intrinsic::lifetime_end:
754 case Intrinsic::invariant_start: {
755 assert(ArgIdx == 1 && "Invalid argument index");
756 assert(Loc.Ptr == II->getArgOperand(ArgIdx) &&
757 "Intrinsic location pointer not argument?");
758 Loc.Size = cast<ConstantInt>(II->getArgOperand(0))->getZExtValue();
759 break;
760 }
761 case Intrinsic::invariant_end: {
762 assert(ArgIdx == 2 && "Invalid argument index");
763 assert(Loc.Ptr == II->getArgOperand(ArgIdx) &&
764 "Intrinsic location pointer not argument?");
765 Loc.Size = cast<ConstantInt>(II->getArgOperand(1))->getZExtValue();
766 break;
767 }
768 case Intrinsic::arm_neon_vld1: {
769 assert(ArgIdx == 0 && "Invalid argument index");
770 assert(Loc.Ptr == II->getArgOperand(ArgIdx) &&
771 "Intrinsic location pointer not argument?");
772 // LLVM's vld1 and vst1 intrinsics currently only support a single
773 // vector register.
774 if (DL)
775 Loc.Size = DL->getTypeStoreSize(II->getType());
776 break;
777 }
778 case Intrinsic::arm_neon_vst1: {
779 assert(ArgIdx == 0 && "Invalid argument index");
780 assert(Loc.Ptr == II->getArgOperand(ArgIdx) &&
781 "Intrinsic location pointer not argument?");
782 if (DL)
783 Loc.Size = DL->getTypeStoreSize(II->getArgOperand(1)->getType());
784 break;
785 }
786 }
787
788 // We can bound the aliasing properties of memset_pattern16 just as we can
789 // for memcpy/memset. This is particularly important because the
790 // LoopIdiomRecognizer likes to turn loops into calls to memset_pattern16
791 // whenever possible.
792 else if (CS.getCalledFunction() &&
793 isMemsetPattern16(CS.getCalledFunction(), TLI)) {
794 assert((ArgIdx == 0 || ArgIdx == 1) &&
795 "Invalid argument index for memset_pattern16");
796 if (ArgIdx == 1)
797 Loc.Size = 16;
798 else if (const ConstantInt *LenCI =
799 dyn_cast<ConstantInt>(CS.getArgument(2)))
800 Loc.Size = LenCI->getZExtValue();
801 assert(Loc.Ptr == CS.getArgument(ArgIdx) &&
802 "memset_pattern16 location pointer not argument?");
803 Mask = ArgIdx ? Ref : Mod;
804 }
805 // FIXME: Handle memset_pattern4 and memset_pattern8 also.
806
807 return Loc;
808}
809
Hal Finkel93046912014-07-25 21:13:35 +0000810static bool isAssumeIntrinsic(ImmutableCallSite CS) {
811 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
812 if (II && II->getIntrinsicID() == Intrinsic::assume)
813 return true;
814
815 return false;
816}
817
Chris Lattner98e253262009-11-23 16:45:27 +0000818/// getModRefInfo - Check to see if the specified callsite can clobber the
819/// specified memory object. Since we only look at local properties of this
820/// function, we really can't say much about this query. We do, however, use
821/// simple "address taken" analysis on local objects.
Chris Lattner2d332972008-06-16 06:30:22 +0000822AliasAnalysis::ModRefResult
Dan Gohman5442c712010-08-03 21:48:53 +0000823BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS,
Dan Gohman41f14cf2010-09-14 21:25:10 +0000824 const Location &Loc) {
825 assert(notDifferentParent(CS.getInstruction(), Loc.Ptr) &&
Dan Gohman00ef9322010-07-07 14:27:09 +0000826 "AliasAnalysis query involving multiple functions!");
827
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000828 const Value *Object = GetUnderlyingObject(Loc.Ptr, DL);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000829
Dan Gohman41f14cf2010-09-14 21:25:10 +0000830 // If this is a tail call and Loc.Ptr points to a stack location, we know that
Chris Lattnerd6a49ad2009-11-22 16:05:05 +0000831 // the tail call cannot access or modify the local stack.
832 // We cannot exclude byval arguments here; these belong to the caller of
833 // the current function not to the current function, and a tail callee
834 // may reference them.
835 if (isa<AllocaInst>(Object))
Dan Gohman5442c712010-08-03 21:48:53 +0000836 if (const CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
Chris Lattnerd6a49ad2009-11-22 16:05:05 +0000837 if (CI->isTailCall())
838 return NoModRef;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000839
Chris Lattnerd6a49ad2009-11-22 16:05:05 +0000840 // If the pointer is to a locally allocated object that does not escape,
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000841 // then the call can not mod/ref the pointer unless the call takes the pointer
842 // as an argument, and itself doesn't capture it.
Chris Lattner1e7b37e2009-11-23 16:46:41 +0000843 if (!isa<Constant>(Object) && CS.getInstruction() != Object &&
Dan Gohman84f90a32010-07-01 20:08:40 +0000844 isNonEscapingLocalObject(Object)) {
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000845 bool PassedAsArg = false;
846 unsigned ArgNo = 0;
Dan Gohman5442c712010-08-03 21:48:53 +0000847 for (ImmutableCallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000848 CI != CE; ++CI, ++ArgNo) {
Chris Lattner026f5e62011-05-23 05:15:43 +0000849 // Only look at the no-capture or byval pointer arguments. If this
850 // pointer were passed to arguments that were neither of these, then it
851 // couldn't be no-capture.
Duncan Sands19d0b472010-02-16 11:11:14 +0000852 if (!(*CI)->getType()->isPointerTy() ||
Nick Lewycky612d70b2011-11-20 19:09:04 +0000853 (!CS.doesNotCapture(ArgNo) && !CS.isByValArgument(ArgNo)))
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000854 continue;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000855
Dan Gohman41f14cf2010-09-14 21:25:10 +0000856 // If this is a no-capture pointer argument, see if we can tell that it
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000857 // is impossible to alias the pointer we're checking. If not, we have to
858 // assume that the call could touch the pointer, even though it doesn't
859 // escape.
Eli Friedman5f476dc2011-09-28 00:34:27 +0000860 if (!isNoAlias(Location(*CI), Location(Object))) {
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000861 PassedAsArg = true;
862 break;
863 }
864 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000865
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000866 if (!PassedAsArg)
Chris Lattnerd6a49ad2009-11-22 16:05:05 +0000867 return NoModRef;
868 }
869
Hal Finkel93046912014-07-25 21:13:35 +0000870 // While the assume intrinsic is marked as arbitrarily writing so that
871 // proper control dependencies will be maintained, it never aliases any
872 // particular memory location.
873 if (isAssumeIntrinsic(CS))
874 return NoModRef;
875
Chris Lattner2d332972008-06-16 06:30:22 +0000876 // The AliasAnalysis base class has some smarts, lets use them.
Hal Finkel354e23b2014-07-17 01:28:25 +0000877 return AliasAnalysis::getModRefInfo(CS, Loc);
Dan Gohman64d842e2010-09-08 01:32:20 +0000878}
Chris Lattner2d332972008-06-16 06:30:22 +0000879
Hal Finkel93046912014-07-25 21:13:35 +0000880AliasAnalysis::ModRefResult
881BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
882 ImmutableCallSite CS2) {
883 // While the assume intrinsic is marked as arbitrarily writing so that
884 // proper control dependencies will be maintained, it never aliases any
885 // particular memory location.
886 if (isAssumeIntrinsic(CS1) || isAssumeIntrinsic(CS2))
887 return NoModRef;
888
889 // The AliasAnalysis base class has some smarts, lets use them.
890 return AliasAnalysis::getModRefInfo(CS1, CS2);
891}
892
Ahmed Bougacha29efe3b2015-02-07 17:04:29 +0000893/// \brief Provide ad-hoc rules to disambiguate accesses through two GEP
894/// operators, both having the exact same pointer operand.
895static AliasAnalysis::AliasResult
896aliasSameBasePointerGEPs(const GEPOperator *GEP1, uint64_t V1Size,
897 const GEPOperator *GEP2, uint64_t V2Size,
898 const DataLayout &DL) {
899
900 assert(GEP1->getPointerOperand() == GEP2->getPointerOperand() &&
901 "Expected GEPs with the same pointer operand");
902
903 // Try to determine whether GEP1 and GEP2 index through arrays, into structs,
904 // such that the struct field accesses provably cannot alias.
905 // We also need at least two indices (the pointer, and the struct field).
906 if (GEP1->getNumIndices() != GEP2->getNumIndices() ||
907 GEP1->getNumIndices() < 2)
908 return AliasAnalysis::MayAlias;
909
910 // If we don't know the size of the accesses through both GEPs, we can't
911 // determine whether the struct fields accessed can't alias.
912 if (V1Size == AliasAnalysis::UnknownSize ||
913 V2Size == AliasAnalysis::UnknownSize)
914 return AliasAnalysis::MayAlias;
915
916 ConstantInt *C1 =
917 dyn_cast<ConstantInt>(GEP1->getOperand(GEP1->getNumOperands() - 1));
918 ConstantInt *C2 =
919 dyn_cast<ConstantInt>(GEP2->getOperand(GEP2->getNumOperands() - 1));
920
921 // If the last (struct) indices aren't constants, we can't say anything.
922 // If they're identical, the other indices might be also be dynamically
923 // equal, so the GEPs can alias.
924 if (!C1 || !C2 || C1 == C2)
925 return AliasAnalysis::MayAlias;
926
927 // Find the last-indexed type of the GEP, i.e., the type you'd get if
928 // you stripped the last index.
929 // On the way, look at each indexed type. If there's something other
930 // than an array, different indices can lead to different final types.
931 SmallVector<Value *, 8> IntermediateIndices;
932
933 // Insert the first index; we don't need to check the type indexed
934 // through it as it only drops the pointer indirection.
935 assert(GEP1->getNumIndices() > 1 && "Not enough GEP indices to examine");
936 IntermediateIndices.push_back(GEP1->getOperand(1));
937
938 // Insert all the remaining indices but the last one.
939 // Also, check that they all index through arrays.
940 for (unsigned i = 1, e = GEP1->getNumIndices() - 1; i != e; ++i) {
941 if (!isa<ArrayType>(GetElementPtrInst::getIndexedType(
942 GEP1->getPointerOperandType(), IntermediateIndices)))
943 return AliasAnalysis::MayAlias;
944 IntermediateIndices.push_back(GEP1->getOperand(i + 1));
945 }
946
947 StructType *LastIndexedStruct =
948 dyn_cast<StructType>(GetElementPtrInst::getIndexedType(
949 GEP1->getPointerOperandType(), IntermediateIndices));
950
951 if (!LastIndexedStruct)
952 return AliasAnalysis::MayAlias;
953
954 // We know that:
955 // - both GEPs begin indexing from the exact same pointer;
956 // - the last indices in both GEPs are constants, indexing into a struct;
957 // - said indices are different, hence, the pointed-to fields are different;
958 // - both GEPs only index through arrays prior to that.
959 //
960 // This lets us determine that the struct that GEP1 indexes into and the
961 // struct that GEP2 indexes into must either precisely overlap or be
962 // completely disjoint. Because they cannot partially overlap, indexing into
963 // different non-overlapping fields of the struct will never alias.
964
965 // Therefore, the only remaining thing needed to show that both GEPs can't
966 // alias is that the fields are not overlapping.
967 const StructLayout *SL = DL.getStructLayout(LastIndexedStruct);
968 const uint64_t StructSize = SL->getSizeInBytes();
969 const uint64_t V1Off = SL->getElementOffset(C1->getZExtValue());
970 const uint64_t V2Off = SL->getElementOffset(C2->getZExtValue());
971
972 auto EltsDontOverlap = [StructSize](uint64_t V1Off, uint64_t V1Size,
973 uint64_t V2Off, uint64_t V2Size) {
974 return V1Off < V2Off && V1Off + V1Size <= V2Off &&
975 ((V2Off + V2Size <= StructSize) ||
976 (V2Off + V2Size - StructSize <= V1Off));
977 };
978
979 if (EltsDontOverlap(V1Off, V1Size, V2Off, V2Size) ||
980 EltsDontOverlap(V2Off, V2Size, V1Off, V1Size))
981 return AliasAnalysis::NoAlias;
982
983 return AliasAnalysis::MayAlias;
984}
985
Chris Lattnera99edbe2009-11-26 02:11:08 +0000986/// aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
987/// against another pointer. We know that V1 is a GEP, but we don't know
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000988/// anything about V2. UnderlyingV1 is GetUnderlyingObject(GEP1, DL),
Chris Lattner5341c962009-11-26 02:14:59 +0000989/// UnderlyingV2 is the same for V2.
Chris Lattnera99edbe2009-11-26 02:11:08 +0000990///
Chris Lattnerd6a2a992003-02-26 19:41:54 +0000991AliasAnalysis::AliasResult
Dan Gohmanf372cf82010-10-19 22:54:46 +0000992BasicAliasAnalysis::aliasGEP(const GEPOperator *GEP1, uint64_t V1Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000993 const AAMDNodes &V1AAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +0000994 const Value *V2, uint64_t V2Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000995 const AAMDNodes &V2AAInfo,
Chris Lattner5341c962009-11-26 02:14:59 +0000996 const Value *UnderlyingV1,
997 const Value *UnderlyingV2) {
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000998 int64_t GEP1BaseOffset;
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000999 bool GEP1MaxLookupReached;
Chris Lattner1b9c3872010-08-18 22:47:56 +00001000 SmallVector<VariableGEPIndex, 4> GEP1VariableIndices;
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001001
Chandler Carruth66b31302015-01-04 12:03:27 +00001002 // We have to get two AssumptionCaches here because GEP1 and V2 may be from
1003 // different functions.
1004 // FIXME: This really doesn't make any sense. We get a dominator tree below
1005 // that can only refer to a single function. But this function (aliasGEP) is
1006 // a method on an immutable pass that can be called when there *isn't*
1007 // a single function. The old pass management layer makes this "work", but
1008 // this isn't really a clean solution.
1009 AssumptionCacheTracker &ACT = getAnalysis<AssumptionCacheTracker>();
1010 AssumptionCache *AC1 = nullptr, *AC2 = nullptr;
1011 if (auto *GEP1I = dyn_cast<Instruction>(GEP1))
1012 AC1 = &ACT.getAssumptionCache(
1013 const_cast<Function &>(*GEP1I->getParent()->getParent()));
1014 if (auto *I2 = dyn_cast<Instruction>(V2))
1015 AC2 = &ACT.getAssumptionCache(
1016 const_cast<Function &>(*I2->getParent()->getParent()));
1017
Hal Finkel60db0582014-09-07 18:57:58 +00001018 DominatorTreeWrapperPass *DTWP =
1019 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1020 DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
1021
Arnold Schwaighofer76dca582012-09-06 14:31:51 +00001022 // If we have two gep instructions with must-alias or not-alias'ing base
1023 // pointers, figure out if the indexes to the GEP tell us anything about the
1024 // derived pointer.
Chris Lattnera99edbe2009-11-26 02:11:08 +00001025 if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
Arnold Schwaighoferaadf1042013-03-26 18:07:53 +00001026 // Do the base pointers alias?
Benjamin Kramer2e52f022014-10-04 22:44:29 +00001027 AliasResult BaseAlias = aliasCheck(UnderlyingV1, UnknownSize, AAMDNodes(),
1028 UnderlyingV2, UnknownSize, AAMDNodes());
Arnold Schwaighoferaadf1042013-03-26 18:07:53 +00001029
Arnold Schwaighofer76dca582012-09-06 14:31:51 +00001030 // Check for geps of non-aliasing underlying pointers where the offsets are
1031 // identical.
Arnold Schwaighoferaadf1042013-03-26 18:07:53 +00001032 if ((BaseAlias == MayAlias) && V1Size == V2Size) {
Arnold Schwaighofer76dca582012-09-06 14:31:51 +00001033 // Do the base pointers alias assuming type and size.
1034 AliasResult PreciseBaseAlias = aliasCheck(UnderlyingV1, V1Size,
Hal Finkelcc39b672014-07-24 12:16:19 +00001035 V1AAInfo, UnderlyingV2,
1036 V2Size, V2AAInfo);
Arnold Schwaighofer76dca582012-09-06 14:31:51 +00001037 if (PreciseBaseAlias == NoAlias) {
1038 // See if the computed offset from the common pointer tells us about the
1039 // relation of the resulting pointer.
1040 int64_t GEP2BaseOffset;
Arnold Schwaighofer1a444482014-03-26 21:30:19 +00001041 bool GEP2MaxLookupReached;
Arnold Schwaighofer76dca582012-09-06 14:31:51 +00001042 SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
1043 const Value *GEP2BasePtr =
Chandler Carruth66b31302015-01-04 12:03:27 +00001044 DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices,
1045 GEP2MaxLookupReached, DL, AC2, DT);
Arnold Schwaighofer76dca582012-09-06 14:31:51 +00001046 const Value *GEP1BasePtr =
Chandler Carruth66b31302015-01-04 12:03:27 +00001047 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
1048 GEP1MaxLookupReached, DL, AC1, DT);
Arnold Schwaighofer76dca582012-09-06 14:31:51 +00001049 // DecomposeGEPExpression and GetUnderlyingObject should return the
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001050 // same result except when DecomposeGEPExpression has no DataLayout.
Arnold Schwaighofer76dca582012-09-06 14:31:51 +00001051 if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
Craig Topper9f008862014-04-15 04:59:12 +00001052 assert(!DL &&
1053 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
Arnold Schwaighofer76dca582012-09-06 14:31:51 +00001054 return MayAlias;
1055 }
Arnold Schwaighofer1a444482014-03-26 21:30:19 +00001056 // If the max search depth is reached the result is undefined
1057 if (GEP2MaxLookupReached || GEP1MaxLookupReached)
1058 return MayAlias;
1059
Arnold Schwaighofer76dca582012-09-06 14:31:51 +00001060 // Same offsets.
1061 if (GEP1BaseOffset == GEP2BaseOffset &&
Benjamin Kramer147644d2014-04-18 19:48:03 +00001062 GEP1VariableIndices == GEP2VariableIndices)
Arnold Schwaighofer76dca582012-09-06 14:31:51 +00001063 return NoAlias;
1064 GEP1VariableIndices.clear();
1065 }
1066 }
Jakub Staszak07f383f2013-08-24 14:16:00 +00001067
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001068 // If we get a No or May, then return it immediately, no amount of analysis
1069 // will improve this situation.
1070 if (BaseAlias != MustAlias) return BaseAlias;
Jakub Staszak07f383f2013-08-24 14:16:00 +00001071
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001072 // Otherwise, we have a MustAlias. Since the base pointers alias each other
1073 // exactly, see if the computed offset from the common pointer tells us
1074 // about the relation of the resulting pointer.
1075 const Value *GEP1BasePtr =
Chandler Carruth66b31302015-01-04 12:03:27 +00001076 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
1077 GEP1MaxLookupReached, DL, AC1, DT);
Jakub Staszak07f383f2013-08-24 14:16:00 +00001078
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001079 int64_t GEP2BaseOffset;
Arnold Schwaighofer1a444482014-03-26 21:30:19 +00001080 bool GEP2MaxLookupReached;
Chris Lattner1b9c3872010-08-18 22:47:56 +00001081 SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001082 const Value *GEP2BasePtr =
Chandler Carruth66b31302015-01-04 12:03:27 +00001083 DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices,
1084 GEP2MaxLookupReached, DL, AC2, DT);
Jakub Staszak07f383f2013-08-24 14:16:00 +00001085
Arnold Schwaighofer76dca582012-09-06 14:31:51 +00001086 // DecomposeGEPExpression and GetUnderlyingObject should return the
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001087 // same result except when DecomposeGEPExpression has no DataLayout.
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001088 if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
Craig Topper9f008862014-04-15 04:59:12 +00001089 assert(!DL &&
Dan Gohmana4fcd242010-12-15 20:02:24 +00001090 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001091 return MayAlias;
1092 }
Ahmed Bougacha29efe3b2015-02-07 17:04:29 +00001093
1094 // If we know the two GEPs are based off of the exact same pointer (and not
1095 // just the same underlying object), see if that tells us anything about
1096 // the resulting pointers.
1097 if (DL && GEP1->getPointerOperand() == GEP2->getPointerOperand()) {
1098 AliasResult R = aliasSameBasePointerGEPs(GEP1, V1Size, GEP2, V2Size, *DL);
1099 // If we couldn't find anything interesting, don't abandon just yet.
1100 if (R != MayAlias)
1101 return R;
1102 }
1103
Arnold Schwaighofer1a444482014-03-26 21:30:19 +00001104 // If the max search depth is reached the result is undefined
1105 if (GEP2MaxLookupReached || GEP1MaxLookupReached)
1106 return MayAlias;
Jakub Staszak07f383f2013-08-24 14:16:00 +00001107
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001108 // Subtract the GEP2 pointer from the GEP1 pointer to find out their
1109 // symbolic difference.
1110 GEP1BaseOffset -= GEP2BaseOffset;
Dan Gohmanad867b02010-08-03 20:23:52 +00001111 GetIndexDifference(GEP1VariableIndices, GEP2VariableIndices);
Jakub Staszak07f383f2013-08-24 14:16:00 +00001112
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001113 } else {
1114 // Check to see if these two pointers are related by the getelementptr
1115 // instruction. If one pointer is a GEP with a non-zero index of the other
1116 // pointer, we know they cannot alias.
Chris Lattner5c1cfc22009-11-26 16:52:32 +00001117
1118 // If both accesses are unknown size, we can't do anything useful here.
Dan Gohman2a190082010-08-03 01:03:11 +00001119 if (V1Size == UnknownSize && V2Size == UnknownSize)
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001120 return MayAlias;
Chris Lattner6ea17f77f2003-12-11 22:44:13 +00001121
Benjamin Kramer2e52f022014-10-04 22:44:29 +00001122 AliasResult R = aliasCheck(UnderlyingV1, UnknownSize, AAMDNodes(),
Hal Finkelcc39b672014-07-24 12:16:19 +00001123 V2, V2Size, V2AAInfo);
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001124 if (R != MustAlias)
1125 // If V2 may alias GEP base pointer, conservatively returns MayAlias.
1126 // If V2 is known not to alias GEP base pointer, then the two values
1127 // cannot alias per GEP semantics: "A pointer value formed from a
1128 // getelementptr instruction is associated with the addresses associated
1129 // with the first operand of the getelementptr".
1130 return R;
Chris Lattner6ea17f77f2003-12-11 22:44:13 +00001131
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001132 const Value *GEP1BasePtr =
Chandler Carruth66b31302015-01-04 12:03:27 +00001133 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
1134 GEP1MaxLookupReached, DL, AC1, DT);
Jakub Staszak07f383f2013-08-24 14:16:00 +00001135
Arnold Schwaighofer76dca582012-09-06 14:31:51 +00001136 // DecomposeGEPExpression and GetUnderlyingObject should return the
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001137 // same result except when DecomposeGEPExpression has no DataLayout.
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001138 if (GEP1BasePtr != UnderlyingV1) {
Craig Topper9f008862014-04-15 04:59:12 +00001139 assert(!DL &&
Dan Gohmana4fcd242010-12-15 20:02:24 +00001140 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001141 return MayAlias;
Chris Lattner6ea17f77f2003-12-11 22:44:13 +00001142 }
Arnold Schwaighofer1a444482014-03-26 21:30:19 +00001143 // If the max search depth is reached the result is undefined
1144 if (GEP1MaxLookupReached)
1145 return MayAlias;
Chris Lattner6ea17f77f2003-12-11 22:44:13 +00001146 }
Jakub Staszak07f383f2013-08-24 14:16:00 +00001147
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001148 // In the two GEP Case, if there is no difference in the offsets of the
1149 // computed pointers, the resultant pointers are a must alias. This
1150 // hapens when we have two lexically identical GEP's (for example).
Chris Lattnerd6a2a992003-02-26 19:41:54 +00001151 //
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001152 // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
1153 // must aliases the GEP, the end result is a must alias also.
1154 if (GEP1BaseOffset == 0 && GEP1VariableIndices.empty())
Evan Chengc1eed9d2009-10-14 06:41:49 +00001155 return MustAlias;
Evan Chengf1f3dd32009-10-13 18:42:04 +00001156
Eli Friedman3d1b3072011-09-08 02:23:31 +00001157 // If there is a constant difference between the pointers, but the difference
1158 // is less than the size of the associated memory object, then we know
1159 // that the objects are partially overlapping. If the difference is
1160 // greater, we know they do not overlap.
Dan Gohmanc4bf5ca2010-12-13 22:50:24 +00001161 if (GEP1BaseOffset != 0 && GEP1VariableIndices.empty()) {
Eli Friedman3d1b3072011-09-08 02:23:31 +00001162 if (GEP1BaseOffset >= 0) {
1163 if (V2Size != UnknownSize) {
1164 if ((uint64_t)GEP1BaseOffset < V2Size)
1165 return PartialAlias;
1166 return NoAlias;
1167 }
1168 } else {
Arnold Schwaighofere3ac0992014-01-16 04:53:18 +00001169 // We have the situation where:
1170 // + +
1171 // | BaseOffset |
1172 // ---------------->|
1173 // |-->V1Size |-------> V2Size
1174 // GEP1 V2
1175 // We need to know that V2Size is not unknown, otherwise we might have
1176 // stripped a gep with negative index ('gep <ptr>, -1, ...).
1177 if (V1Size != UnknownSize && V2Size != UnknownSize) {
Eli Friedman3d1b3072011-09-08 02:23:31 +00001178 if (-(uint64_t)GEP1BaseOffset < V1Size)
1179 return PartialAlias;
1180 return NoAlias;
1181 }
1182 }
Dan Gohmanc4bf5ca2010-12-13 22:50:24 +00001183 }
1184
Eli Friedmanb78ac542011-09-08 02:37:07 +00001185 if (!GEP1VariableIndices.empty()) {
1186 uint64_t Modulo = 0;
Hal Finkel45ba2c12014-11-13 09:16:54 +00001187 bool AllPositive = true;
1188 for (unsigned i = 0, e = GEP1VariableIndices.size(); i != e; ++i) {
1189
1190 // Try to distinguish something like &A[i][1] against &A[42][0].
1191 // Grab the least significant bit set in any of the scales. We
1192 // don't need std::abs here (even if the scale's negative) as we'll
1193 // be ^'ing Modulo with itself later.
1194 Modulo |= (uint64_t) GEP1VariableIndices[i].Scale;
1195
1196 if (AllPositive) {
1197 // If the Value could change between cycles, then any reasoning about
1198 // the Value this cycle may not hold in the next cycle. We'll just
1199 // give up if we can't determine conditions that hold for every cycle:
1200 const Value *V = GEP1VariableIndices[i].V;
1201
1202 bool SignKnownZero, SignKnownOne;
Chandler Carruth66b31302015-01-04 12:03:27 +00001203 ComputeSignBit(const_cast<Value *>(V), SignKnownZero, SignKnownOne, DL,
1204 0, AC1, nullptr, DT);
Hal Finkel45ba2c12014-11-13 09:16:54 +00001205
1206 // Zero-extension widens the variable, and so forces the sign
1207 // bit to zero.
1208 bool IsZExt = GEP1VariableIndices[i].Extension == EK_ZeroExt;
1209 SignKnownZero |= IsZExt;
1210 SignKnownOne &= !IsZExt;
1211
1212 // If the variable begins with a zero then we know it's
1213 // positive, regardless of whether the value is signed or
1214 // unsigned.
1215 int64_t Scale = GEP1VariableIndices[i].Scale;
1216 AllPositive =
1217 (SignKnownZero && Scale >= 0) ||
1218 (SignKnownOne && Scale < 0);
1219 }
1220 }
1221
Eli Friedmanb78ac542011-09-08 02:37:07 +00001222 Modulo = Modulo ^ (Modulo & (Modulo - 1));
Eli Friedman3d1b3072011-09-08 02:23:31 +00001223
Eli Friedmanb78ac542011-09-08 02:37:07 +00001224 // We can compute the difference between the two addresses
1225 // mod Modulo. Check whether that difference guarantees that the
1226 // two locations do not alias.
1227 uint64_t ModOffset = (uint64_t)GEP1BaseOffset & (Modulo - 1);
1228 if (V1Size != UnknownSize && V2Size != UnknownSize &&
1229 ModOffset >= V2Size && V1Size <= Modulo - ModOffset)
1230 return NoAlias;
Hal Finkel45ba2c12014-11-13 09:16:54 +00001231
1232 // If we know all the variables are positive, then GEP1 >= GEP1BasePtr.
1233 // If GEP1BasePtr > V2 (GEP1BaseOffset > 0) then we know the pointers
1234 // don't alias if V2Size can fit in the gap between V2 and GEP1BasePtr.
1235 if (AllPositive && GEP1BaseOffset > 0 && V2Size <= (uint64_t) GEP1BaseOffset)
1236 return NoAlias;
Eli Friedmanb78ac542011-09-08 02:37:07 +00001237 }
Eli Friedman3d1b3072011-09-08 02:23:31 +00001238
Dan Gohmanadf80ae2011-06-04 06:50:18 +00001239 // Statically, we can see that the base objects are the same, but the
1240 // pointers have dynamic offsets which we can't resolve. And none of our
1241 // little tricks above worked.
1242 //
1243 // TODO: Returning PartialAlias instead of MayAlias is a mild hack; the
1244 // practical effect of this is protecting TBAA in the case of dynamic
Dan Gohman9017b842012-02-17 18:33:38 +00001245 // indices into arrays of unions or malloc'd memory.
Dan Gohmanadf80ae2011-06-04 06:50:18 +00001246 return PartialAlias;
Evan Chengf1f3dd32009-10-13 18:42:04 +00001247}
1248
Dan Gohman4e7e7952011-06-03 20:17:36 +00001249static AliasAnalysis::AliasResult
1250MergeAliasResults(AliasAnalysis::AliasResult A, AliasAnalysis::AliasResult B) {
1251 // If the results agree, take it.
1252 if (A == B)
1253 return A;
1254 // A mix of PartialAlias and MustAlias is PartialAlias.
1255 if ((A == AliasAnalysis::PartialAlias && B == AliasAnalysis::MustAlias) ||
1256 (B == AliasAnalysis::PartialAlias && A == AliasAnalysis::MustAlias))
1257 return AliasAnalysis::PartialAlias;
1258 // Otherwise, we don't know anything.
1259 return AliasAnalysis::MayAlias;
1260}
1261
Chris Lattner98e253262009-11-23 16:45:27 +00001262/// aliasSelect - Provide a bunch of ad-hoc rules to disambiguate a Select
1263/// instruction against another.
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001264AliasAnalysis::AliasResult
Dan Gohmanf372cf82010-10-19 22:54:46 +00001265BasicAliasAnalysis::aliasSelect(const SelectInst *SI, uint64_t SISize,
Hal Finkelcc39b672014-07-24 12:16:19 +00001266 const AAMDNodes &SIAAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +00001267 const Value *V2, uint64_t V2Size,
Hal Finkelcc39b672014-07-24 12:16:19 +00001268 const AAMDNodes &V2AAInfo) {
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001269 // If the values are Selects with the same condition, we can do a more precise
1270 // check: just check for aliases between the values on corresponding arms.
1271 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
1272 if (SI->getCondition() == SI2->getCondition()) {
1273 AliasResult Alias =
Hal Finkelcc39b672014-07-24 12:16:19 +00001274 aliasCheck(SI->getTrueValue(), SISize, SIAAInfo,
1275 SI2->getTrueValue(), V2Size, V2AAInfo);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001276 if (Alias == MayAlias)
1277 return MayAlias;
1278 AliasResult ThisAlias =
Hal Finkelcc39b672014-07-24 12:16:19 +00001279 aliasCheck(SI->getFalseValue(), SISize, SIAAInfo,
1280 SI2->getFalseValue(), V2Size, V2AAInfo);
Dan Gohman4e7e7952011-06-03 20:17:36 +00001281 return MergeAliasResults(ThisAlias, Alias);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001282 }
1283
1284 // If both arms of the Select node NoAlias or MustAlias V2, then returns
1285 // NoAlias / MustAlias. Otherwise, returns MayAlias.
1286 AliasResult Alias =
Hal Finkelcc39b672014-07-24 12:16:19 +00001287 aliasCheck(V2, V2Size, V2AAInfo, SI->getTrueValue(), SISize, SIAAInfo);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001288 if (Alias == MayAlias)
1289 return MayAlias;
Dan Gohman7c34ece2010-06-28 21:16:52 +00001290
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001291 AliasResult ThisAlias =
Hal Finkelcc39b672014-07-24 12:16:19 +00001292 aliasCheck(V2, V2Size, V2AAInfo, SI->getFalseValue(), SISize, SIAAInfo);
Dan Gohman4e7e7952011-06-03 20:17:36 +00001293 return MergeAliasResults(ThisAlias, Alias);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001294}
1295
Evan Chengf92f5552009-10-14 05:22:03 +00001296// aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
Evan Cheng31565b32009-10-14 05:05:02 +00001297// against another.
Evan Chengc10e88d2009-10-13 22:02:20 +00001298AliasAnalysis::AliasResult
Dan Gohmanf372cf82010-10-19 22:54:46 +00001299BasicAliasAnalysis::aliasPHI(const PHINode *PN, uint64_t PNSize,
Hal Finkelcc39b672014-07-24 12:16:19 +00001300 const AAMDNodes &PNAAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +00001301 const Value *V2, uint64_t V2Size,
Hal Finkelcc39b672014-07-24 12:16:19 +00001302 const AAMDNodes &V2AAInfo) {
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001303 // Track phi nodes we have visited. We use this information when we determine
1304 // value equivalence.
1305 VisitedPhiBBs.insert(PN->getParent());
1306
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001307 // If the values are PHIs in the same block, we can do a more precise
1308 // as well as efficient check: just check for aliases between the values
1309 // on corresponding edges.
1310 if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
1311 if (PN2->getParent() == PN->getParent()) {
Hal Finkelcc39b672014-07-24 12:16:19 +00001312 LocPair Locs(Location(PN, PNSize, PNAAInfo),
1313 Location(V2, V2Size, V2AAInfo));
Arnold Schwaighofer8dc34cf2012-09-06 14:41:53 +00001314 if (PN > V2)
1315 std::swap(Locs.first, Locs.second);
Arnold Schwaighoferedd62b12012-12-10 23:02:41 +00001316 // Analyse the PHIs' inputs under the assumption that the PHIs are
1317 // NoAlias.
1318 // If the PHIs are May/MustAlias there must be (recursively) an input
1319 // operand from outside the PHIs' cycle that is MayAlias/MustAlias or
1320 // there must be an operation on the PHIs within the PHIs' value cycle
1321 // that causes a MayAlias.
1322 // Pretend the phis do not alias.
1323 AliasResult Alias = NoAlias;
1324 assert(AliasCache.count(Locs) &&
1325 "There must exist an entry for the phi node");
1326 AliasResult OrigAliasResult = AliasCache[Locs];
1327 AliasCache[Locs] = NoAlias;
Arnold Schwaighofer8dc34cf2012-09-06 14:41:53 +00001328
Hal Finkela6f86fc2012-11-17 02:33:15 +00001329 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001330 AliasResult ThisAlias =
Hal Finkelcc39b672014-07-24 12:16:19 +00001331 aliasCheck(PN->getIncomingValue(i), PNSize, PNAAInfo,
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001332 PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
Hal Finkelcc39b672014-07-24 12:16:19 +00001333 V2Size, V2AAInfo);
Dan Gohman4e7e7952011-06-03 20:17:36 +00001334 Alias = MergeAliasResults(ThisAlias, Alias);
1335 if (Alias == MayAlias)
1336 break;
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001337 }
Arnold Schwaighofer8dc34cf2012-09-06 14:41:53 +00001338
1339 // Reset if speculation failed.
Arnold Schwaighoferedd62b12012-12-10 23:02:41 +00001340 if (Alias != NoAlias)
Arnold Schwaighofer8dc34cf2012-09-06 14:41:53 +00001341 AliasCache[Locs] = OrigAliasResult;
1342
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001343 return Alias;
1344 }
1345
Evan Cheng8ec25932009-10-16 00:33:09 +00001346 SmallPtrSet<Value*, 4> UniqueSrc;
Evan Chengc10e88d2009-10-13 22:02:20 +00001347 SmallVector<Value*, 4> V1Srcs;
Evan Chengc10e88d2009-10-13 22:02:20 +00001348 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1349 Value *PV1 = PN->getIncomingValue(i);
1350 if (isa<PHINode>(PV1))
1351 // If any of the source itself is a PHI, return MayAlias conservatively
Evan Chengc1eed9d2009-10-14 06:41:49 +00001352 // to avoid compile time explosion. The worst possible case is if both
1353 // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
1354 // and 'n' are the number of PHI sources.
Evan Chengc10e88d2009-10-13 22:02:20 +00001355 return MayAlias;
David Blaikie70573dc2014-11-19 07:49:26 +00001356 if (UniqueSrc.insert(PV1).second)
Evan Chengc10e88d2009-10-13 22:02:20 +00001357 V1Srcs.push_back(PV1);
1358 }
1359
Hal Finkelcc39b672014-07-24 12:16:19 +00001360 AliasResult Alias = aliasCheck(V2, V2Size, V2AAInfo,
1361 V1Srcs[0], PNSize, PNAAInfo);
Evan Chengf92f5552009-10-14 05:22:03 +00001362 // Early exit if the check of the first PHI source against V2 is MayAlias.
1363 // Other results are not possible.
1364 if (Alias == MayAlias)
1365 return MayAlias;
1366
Evan Chengc10e88d2009-10-13 22:02:20 +00001367 // If all sources of the PHI node NoAlias or MustAlias V2, then returns
1368 // NoAlias / MustAlias. Otherwise, returns MayAlias.
Evan Chengc10e88d2009-10-13 22:02:20 +00001369 for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
1370 Value *V = V1Srcs[i];
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001371
Hal Finkelcc39b672014-07-24 12:16:19 +00001372 AliasResult ThisAlias = aliasCheck(V2, V2Size, V2AAInfo,
1373 V, PNSize, PNAAInfo);
Dan Gohman4e7e7952011-06-03 20:17:36 +00001374 Alias = MergeAliasResults(ThisAlias, Alias);
1375 if (Alias == MayAlias)
1376 break;
Evan Chengc10e88d2009-10-13 22:02:20 +00001377 }
1378
1379 return Alias;
1380}
1381
1382// aliasCheck - Provide a bunch of ad-hoc rules to disambiguate in common cases,
1383// such as array references.
Evan Chengf1f3dd32009-10-13 18:42:04 +00001384//
1385AliasAnalysis::AliasResult
Dan Gohmanf372cf82010-10-19 22:54:46 +00001386BasicAliasAnalysis::aliasCheck(const Value *V1, uint64_t V1Size,
Hal Finkelcc39b672014-07-24 12:16:19 +00001387 AAMDNodes V1AAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +00001388 const Value *V2, uint64_t V2Size,
Hal Finkelcc39b672014-07-24 12:16:19 +00001389 AAMDNodes V2AAInfo) {
Dan Gohmancb45bd92010-04-08 18:11:50 +00001390 // If either of the memory references is empty, it doesn't matter what the
1391 // pointer values are.
1392 if (V1Size == 0 || V2Size == 0)
1393 return NoAlias;
1394
Evan Chengf1f3dd32009-10-13 18:42:04 +00001395 // Strip off any casts if they exist.
1396 V1 = V1->stripPointerCasts();
1397 V2 = V2->stripPointerCasts();
1398
1399 // Are we checking for alias of the same value?
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001400 // Because we look 'through' phi nodes we could look at "Value" pointers from
1401 // different iterations. We must therefore make sure that this is not the
1402 // case. The function isValueEqualInPotentialCycles ensures that this cannot
1403 // happen by looking at the visited phi nodes and making sure they cannot
1404 // reach the value.
1405 if (isValueEqualInPotentialCycles(V1, V2))
1406 return MustAlias;
Evan Chengf1f3dd32009-10-13 18:42:04 +00001407
Duncan Sands19d0b472010-02-16 11:11:14 +00001408 if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
Evan Chengf1f3dd32009-10-13 18:42:04 +00001409 return NoAlias; // Scalars cannot alias each other
1410
1411 // Figure out what objects these things are pointing to if we can.
Arnold Schwaighofer1a444482014-03-26 21:30:19 +00001412 const Value *O1 = GetUnderlyingObject(V1, DL, MaxLookupSearchDepth);
1413 const Value *O2 = GetUnderlyingObject(V2, DL, MaxLookupSearchDepth);
Evan Chengf1f3dd32009-10-13 18:42:04 +00001414
Dan Gohmanccb45842009-11-09 19:29:11 +00001415 // Null values in the default address space don't point to any object, so they
1416 // don't alias any other pointer.
1417 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
1418 if (CPN->getType()->getAddressSpace() == 0)
1419 return NoAlias;
1420 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
1421 if (CPN->getType()->getAddressSpace() == 0)
1422 return NoAlias;
1423
Evan Chengf1f3dd32009-10-13 18:42:04 +00001424 if (O1 != O2) {
1425 // If V1/V2 point to two different objects we know that we have no alias.
Dan Gohman00ef9322010-07-07 14:27:09 +00001426 if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
Evan Chengf1f3dd32009-10-13 18:42:04 +00001427 return NoAlias;
Nick Lewyckyc53e2ec2009-11-14 06:15:14 +00001428
1429 // Constant pointers can't alias with non-const isIdentifiedObject objects.
Dan Gohman00ef9322010-07-07 14:27:09 +00001430 if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
1431 (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
Nick Lewyckyc53e2ec2009-11-14 06:15:14 +00001432 return NoAlias;
1433
Michael Kupersteinf3e663a2013-05-28 08:17:48 +00001434 // Function arguments can't alias with things that are known to be
1435 // unambigously identified at the function level.
1436 if ((isa<Argument>(O1) && isIdentifiedFunctionLocal(O2)) ||
1437 (isa<Argument>(O2) && isIdentifiedFunctionLocal(O1)))
Dan Gohman84f90a32010-07-01 20:08:40 +00001438 return NoAlias;
Evan Chengf1f3dd32009-10-13 18:42:04 +00001439
1440 // Most objects can't alias null.
Dan Gohman00ef9322010-07-07 14:27:09 +00001441 if ((isa<ConstantPointerNull>(O2) && isKnownNonNull(O1)) ||
1442 (isa<ConstantPointerNull>(O1) && isKnownNonNull(O2)))
Evan Chengf1f3dd32009-10-13 18:42:04 +00001443 return NoAlias;
Jakub Staszak07f383f2013-08-24 14:16:00 +00001444
Dan Gohman5b0a8a82010-07-07 14:30:04 +00001445 // If one pointer is the result of a call/invoke or load and the other is a
1446 // non-escaping local object within the same function, then we know the
1447 // object couldn't escape to a point where the call could return it.
1448 //
1449 // Note that if the pointers are in different functions, there are a
1450 // variety of complications. A call with a nocapture argument may still
1451 // temporary store the nocapture argument's value in a temporary memory
1452 // location if that memory location doesn't escape. Or it may pass a
1453 // nocapture value to other functions as long as they don't capture it.
1454 if (isEscapeSource(O1) && isNonEscapingLocalObject(O2))
1455 return NoAlias;
1456 if (isEscapeSource(O2) && isNonEscapingLocalObject(O1))
1457 return NoAlias;
1458 }
1459
Evan Chengf1f3dd32009-10-13 18:42:04 +00001460 // If the size of one access is larger than the entire object on the other
1461 // side, then we know such behavior is undefined and can assume no alias.
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001462 if (DL)
1463 if ((V1Size != UnknownSize && isObjectSmallerThan(O2, V1Size, *DL, *TLI)) ||
1464 (V2Size != UnknownSize && isObjectSmallerThan(O1, V2Size, *DL, *TLI)))
Evan Chengf1f3dd32009-10-13 18:42:04 +00001465 return NoAlias;
Jakub Staszak07f383f2013-08-24 14:16:00 +00001466
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001467 // Check the cache before climbing up use-def chains. This also terminates
1468 // otherwise infinitely recursive queries.
Hal Finkelcc39b672014-07-24 12:16:19 +00001469 LocPair Locs(Location(V1, V1Size, V1AAInfo),
1470 Location(V2, V2Size, V2AAInfo));
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001471 if (V1 > V2)
1472 std::swap(Locs.first, Locs.second);
1473 std::pair<AliasCacheTy::iterator, bool> Pair =
1474 AliasCache.insert(std::make_pair(Locs, MayAlias));
1475 if (!Pair.second)
1476 return Pair.first->second;
1477
Chris Lattner89288992009-11-26 02:13:03 +00001478 // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
1479 // GEP can't simplify, we don't even look at the PHI cases.
Chris Lattnerb2647b92009-10-17 23:48:54 +00001480 if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
Chris Lattnerd6a2a992003-02-26 19:41:54 +00001481 std::swap(V1, V2);
1482 std::swap(V1Size, V2Size);
Chris Lattner5341c962009-11-26 02:14:59 +00001483 std::swap(O1, O2);
Hal Finkelcc39b672014-07-24 12:16:19 +00001484 std::swap(V1AAInfo, V2AAInfo);
Chris Lattnerd6a2a992003-02-26 19:41:54 +00001485 }
Dan Gohman02538ac2010-10-18 18:04:47 +00001486 if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) {
Hal Finkelcc39b672014-07-24 12:16:19 +00001487 AliasResult Result = aliasGEP(GV1, V1Size, V1AAInfo, V2, V2Size, V2AAInfo, O1, O2);
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001488 if (Result != MayAlias) return AliasCache[Locs] = Result;
Dan Gohman02538ac2010-10-18 18:04:47 +00001489 }
Evan Chengc10e88d2009-10-13 22:02:20 +00001490
1491 if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
1492 std::swap(V1, V2);
1493 std::swap(V1Size, V2Size);
Hal Finkelcc39b672014-07-24 12:16:19 +00001494 std::swap(V1AAInfo, V2AAInfo);
Evan Chengc10e88d2009-10-13 22:02:20 +00001495 }
Dan Gohman02538ac2010-10-18 18:04:47 +00001496 if (const PHINode *PN = dyn_cast<PHINode>(V1)) {
Hal Finkelcc39b672014-07-24 12:16:19 +00001497 AliasResult Result = aliasPHI(PN, V1Size, V1AAInfo,
1498 V2, V2Size, V2AAInfo);
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001499 if (Result != MayAlias) return AliasCache[Locs] = Result;
Dan Gohman02538ac2010-10-18 18:04:47 +00001500 }
Misha Brukman01808ca2005-04-21 21:13:18 +00001501
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001502 if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
1503 std::swap(V1, V2);
1504 std::swap(V1Size, V2Size);
Hal Finkelcc39b672014-07-24 12:16:19 +00001505 std::swap(V1AAInfo, V2AAInfo);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001506 }
Dan Gohman02538ac2010-10-18 18:04:47 +00001507 if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) {
Hal Finkelcc39b672014-07-24 12:16:19 +00001508 AliasResult Result = aliasSelect(S1, V1Size, V1AAInfo,
1509 V2, V2Size, V2AAInfo);
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001510 if (Result != MayAlias) return AliasCache[Locs] = Result;
Dan Gohman02538ac2010-10-18 18:04:47 +00001511 }
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001512
Dan Gohman44da55b2011-01-18 21:16:06 +00001513 // If both pointers are pointing into the same object and one of them
1514 // accesses is accessing the entire object, then the accesses must
1515 // overlap in some way.
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001516 if (DL && O1 == O2)
1517 if ((V1Size != UnknownSize && isObjectSize(O1, V1Size, *DL, *TLI)) ||
1518 (V2Size != UnknownSize && isObjectSize(O2, V2Size, *DL, *TLI)))
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001519 return AliasCache[Locs] = PartialAlias;
Dan Gohman44da55b2011-01-18 21:16:06 +00001520
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001521 AliasResult Result =
Hal Finkelcc39b672014-07-24 12:16:19 +00001522 AliasAnalysis::alias(Location(V1, V1Size, V1AAInfo),
1523 Location(V2, V2Size, V2AAInfo));
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001524 return AliasCache[Locs] = Result;
Chris Lattnerd6a2a992003-02-26 19:41:54 +00001525}
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001526
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001527bool BasicAliasAnalysis::isValueEqualInPotentialCycles(const Value *V,
1528 const Value *V2) {
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001529 if (V != V2)
1530 return false;
1531
1532 const Instruction *Inst = dyn_cast<Instruction>(V);
1533 if (!Inst)
1534 return true;
1535
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001536 if (VisitedPhiBBs.size() > MaxNumPhiBBsValueReachabilityCheck)
1537 return false;
1538
1539 // Use dominance or loop info if available.
Chandler Carruth73523022014-01-13 13:07:17 +00001540 DominatorTreeWrapperPass *DTWP =
1541 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
Craig Topper9f008862014-04-15 04:59:12 +00001542 DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
Chandler Carruth4f8f3072015-01-17 14:16:18 +00001543 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
1544 LoopInfo *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001545
1546 // Make sure that the visited phis cannot reach the Value. This ensures that
1547 // the Values cannot come from different iterations of a potential cycle the
1548 // phi nodes could be involved in.
Craig Topper46276792014-08-24 23:23:06 +00001549 for (auto *P : VisitedPhiBBs)
1550 if (isPotentiallyReachable(P->begin(), Inst, DT, LI))
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001551 return false;
1552
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001553 return true;
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001554}
1555
1556/// GetIndexDifference - Dest and Src are the variable indices from two
1557/// decomposed GetElementPtr instructions GEP1 and GEP2 which have common base
1558/// pointers. Subtract the GEP2 indices from GEP1 to find the symbolic
1559/// difference between the two pointers.
1560void BasicAliasAnalysis::GetIndexDifference(
1561 SmallVectorImpl<VariableGEPIndex> &Dest,
1562 const SmallVectorImpl<VariableGEPIndex> &Src) {
1563 if (Src.empty())
1564 return;
1565
1566 for (unsigned i = 0, e = Src.size(); i != e; ++i) {
1567 const Value *V = Src[i].V;
1568 ExtensionKind Extension = Src[i].Extension;
1569 int64_t Scale = Src[i].Scale;
1570
1571 // Find V in Dest. This is N^2, but pointer indices almost never have more
1572 // than a few variable indexes.
1573 for (unsigned j = 0, e = Dest.size(); j != e; ++j) {
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001574 if (!isValueEqualInPotentialCycles(Dest[j].V, V) ||
1575 Dest[j].Extension != Extension)
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001576 continue;
1577
1578 // If we found it, subtract off Scale V's from the entry in Dest. If it
1579 // goes to zero, remove the entry.
1580 if (Dest[j].Scale != Scale)
1581 Dest[j].Scale -= Scale;
1582 else
1583 Dest.erase(Dest.begin() + j);
1584 Scale = 0;
1585 break;
1586 }
1587
1588 // If we didn't consume this entry, add it to the end of the Dest list.
1589 if (Scale) {
1590 VariableGEPIndex Entry = { V, Extension, -Scale };
1591 Dest.push_back(Entry);
1592 }
1593 }
1594}