blob: 9cfd02c02186886a3b2cc23c1eba90fe19162767 [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"
Hal Finkel60db0582014-09-07 18:57:58 +000020#include "llvm/Analysis/AssumptionTracker.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"
26#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Constants.h"
28#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000030#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000032#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/GlobalAlias.h"
34#include "llvm/IR/GlobalVariable.h"
35#include "llvm/IR/Instructions.h"
36#include "llvm/IR/IntrinsicInst.h"
37#include "llvm/IR/LLVMContext.h"
38#include "llvm/IR/Operator.h"
Chris Lattnerd82256a2004-03-15 03:36:49 +000039#include "llvm/Pass.h"
Torok Edwin56d06592009-07-11 20:10:48 +000040#include "llvm/Support/ErrorHandling.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000041#include "llvm/Target/TargetLibraryInfo.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,
199 AssumptionTracker *AT,
200 DominatorTree *DT) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000201 assert(V->getType()->isIntegerTy() && "Not an integer value");
202
203 // Limit our recursion depth.
204 if (Depth == 6) {
205 Scale = 1;
206 Offset = 0;
207 return V;
208 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000209
Chris Lattner9f7500f2010-08-18 22:07:29 +0000210 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(V)) {
211 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
212 switch (BOp->getOpcode()) {
213 default: break;
214 case Instruction::Or:
215 // X|C == X+C if all the bits in C are unset in X. Otherwise we can't
216 // analyze it.
Hal Finkel60db0582014-09-07 18:57:58 +0000217 if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), &DL, 0,
218 AT, BOp, DT))
Chris Lattner9f7500f2010-08-18 22:07:29 +0000219 break;
220 // FALL THROUGH.
221 case Instruction::Add:
Chris Lattner3decde92010-08-18 23:09:49 +0000222 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
Hal Finkel60db0582014-09-07 18:57:58 +0000223 DL, Depth+1, AT, DT);
Chris Lattner9f7500f2010-08-18 22:07:29 +0000224 Offset += RHSC->getValue();
225 return V;
226 case Instruction::Mul:
Chris Lattner3decde92010-08-18 23:09:49 +0000227 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
Hal Finkel60db0582014-09-07 18:57:58 +0000228 DL, Depth+1, AT, DT);
Chris Lattner9f7500f2010-08-18 22:07:29 +0000229 Offset *= RHSC->getValue();
230 Scale *= RHSC->getValue();
231 return V;
232 case Instruction::Shl:
Chris Lattner3decde92010-08-18 23:09:49 +0000233 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
Hal Finkel60db0582014-09-07 18:57:58 +0000234 DL, Depth+1, AT, DT);
Chris Lattner9f7500f2010-08-18 22:07:29 +0000235 Offset <<= RHSC->getValue().getLimitedValue();
236 Scale <<= RHSC->getValue().getLimitedValue();
237 return V;
238 }
239 }
240 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000241
Chris Lattner9f7500f2010-08-18 22:07:29 +0000242 // Since GEP indices are sign extended anyway, we don't care about the high
Chris Lattner3decde92010-08-18 23:09:49 +0000243 // bits of a sign or zero extended value - just scales and offsets. The
244 // extensions have to be consistent though.
245 if ((isa<SExtInst>(V) && Extension != EK_ZeroExt) ||
246 (isa<ZExtInst>(V) && Extension != EK_SignExt)) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000247 Value *CastOp = cast<CastInst>(V)->getOperand(0);
248 unsigned OldWidth = Scale.getBitWidth();
249 unsigned SmallWidth = CastOp->getType()->getPrimitiveSizeInBits();
Jay Foad583abbc2010-12-07 08:25:19 +0000250 Scale = Scale.trunc(SmallWidth);
251 Offset = Offset.trunc(SmallWidth);
Chris Lattner3decde92010-08-18 23:09:49 +0000252 Extension = isa<SExtInst>(V) ? EK_SignExt : EK_ZeroExt;
253
254 Value *Result = GetLinearExpression(CastOp, Scale, Offset, Extension,
Hal Finkel60db0582014-09-07 18:57:58 +0000255 DL, Depth+1, AT, DT);
Jay Foad583abbc2010-12-07 08:25:19 +0000256 Scale = Scale.zext(OldWidth);
257 Offset = Offset.zext(OldWidth);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000258
Chris Lattner9f7500f2010-08-18 22:07:29 +0000259 return Result;
260 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000261
Chris Lattner9f7500f2010-08-18 22:07:29 +0000262 Scale = 1;
263 Offset = 0;
264 return V;
265}
266
267/// DecomposeGEPExpression - If V is a symbolic pointer expression, decompose it
268/// into a base pointer with a constant offset and a number of scaled symbolic
269/// offsets.
270///
271/// The scaled symbolic offsets (represented by pairs of a Value* and a scale in
272/// the VarIndices vector) are Value*'s that are known to be scaled by the
273/// specified amount, but which may have other unrepresented high bits. As such,
274/// the gep cannot necessarily be reconstructed from its decomposed form.
275///
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000276/// When DataLayout is around, this function is capable of analyzing everything
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000277/// that GetUnderlyingObject can look through. To be able to do that
278/// GetUnderlyingObject and DecomposeGEPExpression must use the same search
279/// depth (MaxLookupSearchDepth).
280/// When DataLayout not is around, it just looks through pointer casts.
Chris Lattner9f7500f2010-08-18 22:07:29 +0000281///
282static const Value *
283DecomposeGEPExpression(const Value *V, int64_t &BaseOffs,
Chris Lattner1b9c3872010-08-18 22:47:56 +0000284 SmallVectorImpl<VariableGEPIndex> &VarIndices,
Hal Finkel60db0582014-09-07 18:57:58 +0000285 bool &MaxLookupReached, const DataLayout *DL,
286 AssumptionTracker *AT, DominatorTree *DT) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000287 // Limit recursion depth to limit compile time in crazy cases.
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000288 unsigned MaxLookup = MaxLookupSearchDepth;
289 MaxLookupReached = false;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000290
Chris Lattner9f7500f2010-08-18 22:07:29 +0000291 BaseOffs = 0;
292 do {
293 // See if this is a bitcast or GEP.
294 const Operator *Op = dyn_cast<Operator>(V);
Craig Topper9f008862014-04-15 04:59:12 +0000295 if (!Op) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000296 // The only non-operator case we can handle are GlobalAliases.
297 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
298 if (!GA->mayBeOverridden()) {
299 V = GA->getAliasee();
300 continue;
301 }
302 }
303 return V;
304 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000305
Matt Arsenault70f4db882014-07-15 00:56:40 +0000306 if (Op->getOpcode() == Instruction::BitCast ||
307 Op->getOpcode() == Instruction::AddrSpaceCast) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000308 V = Op->getOperand(0);
309 continue;
310 }
Dan Gohman05b18f12010-12-15 20:49:55 +0000311
Chris Lattner9f7500f2010-08-18 22:07:29 +0000312 const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
Craig Topper9f008862014-04-15 04:59:12 +0000313 if (!GEPOp) {
Dan Gohman0573b552011-05-24 18:24:08 +0000314 // If it's not a GEP, hand it off to SimplifyInstruction to see if it
315 // can come up with something. This matches what GetUnderlyingObject does.
316 if (const Instruction *I = dyn_cast<Instruction>(V))
Hal Finkel60db0582014-09-07 18:57:58 +0000317 // TODO: Get a DominatorTree and AssumptionTracker and use them here
318 // (these are both now available in this function, but this should be
319 // updated when GetUnderlyingObject is updated). TLI should be
320 // provided also.
Dan Gohman0573b552011-05-24 18:24:08 +0000321 if (const Value *Simplified =
Rafael Espindola5f57f462014-02-21 18:34:28 +0000322 SimplifyInstruction(const_cast<Instruction *>(I), DL)) {
Dan Gohman0573b552011-05-24 18:24:08 +0000323 V = Simplified;
324 continue;
325 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000326
Chris Lattner9f7500f2010-08-18 22:07:29 +0000327 return V;
Dan Gohman0573b552011-05-24 18:24:08 +0000328 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000329
Chris Lattner9f7500f2010-08-18 22:07:29 +0000330 // Don't attempt to analyze GEPs over unsized objects.
Matt Arsenaultfa252722013-09-27 22:18:51 +0000331 if (!GEPOp->getOperand(0)->getType()->getPointerElementType()->isSized())
Chris Lattner9f7500f2010-08-18 22:07:29 +0000332 return V;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000333
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000334 // If we are lacking DataLayout information, we can't compute the offets of
Chris Lattner9f7500f2010-08-18 22:07:29 +0000335 // elements computed by GEPs. However, we can handle bitcast equivalent
336 // GEPs.
Craig Topper9f008862014-04-15 04:59:12 +0000337 if (!DL) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000338 if (!GEPOp->hasAllZeroIndices())
339 return V;
340 V = GEPOp->getOperand(0);
341 continue;
342 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000343
Matt Arsenaulta8fe22b2013-11-16 00:36:43 +0000344 unsigned AS = GEPOp->getPointerAddressSpace();
Chris Lattner9f7500f2010-08-18 22:07:29 +0000345 // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
346 gep_type_iterator GTI = gep_type_begin(GEPOp);
347 for (User::const_op_iterator I = GEPOp->op_begin()+1,
348 E = GEPOp->op_end(); I != E; ++I) {
349 Value *Index = *I;
350 // Compute the (potentially symbolic) offset in bytes for this index.
Chris Lattner229907c2011-07-18 04:54:35 +0000351 if (StructType *STy = dyn_cast<StructType>(*GTI++)) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000352 // For a struct, add the member offset.
353 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
354 if (FieldNo == 0) continue;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000355
Rafael Espindola5f57f462014-02-21 18:34:28 +0000356 BaseOffs += DL->getStructLayout(STy)->getElementOffset(FieldNo);
Chris Lattner9f7500f2010-08-18 22:07:29 +0000357 continue;
358 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000359
Chris Lattner9f7500f2010-08-18 22:07:29 +0000360 // For an array/pointer, add the element offset, explicitly scaled.
361 if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
362 if (CIdx->isZero()) continue;
Rafael Espindola5f57f462014-02-21 18:34:28 +0000363 BaseOffs += DL->getTypeAllocSize(*GTI)*CIdx->getSExtValue();
Chris Lattner9f7500f2010-08-18 22:07:29 +0000364 continue;
365 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000366
Rafael Espindola5f57f462014-02-21 18:34:28 +0000367 uint64_t Scale = DL->getTypeAllocSize(*GTI);
Chris Lattner1b9c3872010-08-18 22:47:56 +0000368 ExtensionKind Extension = EK_NotExtended;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000369
Chris Lattner3decde92010-08-18 23:09:49 +0000370 // If the integer type is smaller than the pointer size, it is implicitly
371 // sign extended to pointer size.
Matt Arsenaultfa252722013-09-27 22:18:51 +0000372 unsigned Width = Index->getType()->getIntegerBitWidth();
Rafael Espindola5f57f462014-02-21 18:34:28 +0000373 if (DL->getPointerSizeInBits(AS) > Width)
Chris Lattner3decde92010-08-18 23:09:49 +0000374 Extension = EK_SignExt;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000375
Chris Lattner3decde92010-08-18 23:09:49 +0000376 // Use GetLinearExpression to decompose the index into a C1*V+C2 form.
Chris Lattner9f7500f2010-08-18 22:07:29 +0000377 APInt IndexScale(Width, 0), IndexOffset(Width, 0);
Chris Lattner3decde92010-08-18 23:09:49 +0000378 Index = GetLinearExpression(Index, IndexScale, IndexOffset, Extension,
Hal Finkel60db0582014-09-07 18:57:58 +0000379 *DL, 0, AT, DT);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000380
Chris Lattner9f7500f2010-08-18 22:07:29 +0000381 // The GEP index scale ("Scale") scales C1*V+C2, yielding (C1*V+C2)*Scale.
382 // This gives us an aggregate computation of (C1*Scale)*V + C2*Scale.
Eli Friedmanab3a1282010-09-15 20:08:03 +0000383 BaseOffs += IndexOffset.getSExtValue()*Scale;
384 Scale *= IndexScale.getSExtValue();
Jakub Staszak07f383f2013-08-24 14:16:00 +0000385
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000386 // If we already had an occurrence of this index variable, merge this
Chris Lattner9f7500f2010-08-18 22:07:29 +0000387 // scale into it. For example, we want to handle:
388 // A[x][x] -> x*16 + x*4 -> x*20
389 // This also ensures that 'x' only appears in the index list once.
390 for (unsigned i = 0, e = VarIndices.size(); i != e; ++i) {
Chris Lattner1b9c3872010-08-18 22:47:56 +0000391 if (VarIndices[i].V == Index &&
392 VarIndices[i].Extension == Extension) {
393 Scale += VarIndices[i].Scale;
Chris Lattner9f7500f2010-08-18 22:07:29 +0000394 VarIndices.erase(VarIndices.begin()+i);
395 break;
396 }
397 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000398
Chris Lattner9f7500f2010-08-18 22:07:29 +0000399 // Make sure that we have a scale that makes sense for this target's
400 // pointer size.
Rafael Espindola5f57f462014-02-21 18:34:28 +0000401 if (unsigned ShiftBits = 64 - DL->getPointerSizeInBits(AS)) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000402 Scale <<= ShiftBits;
Eli Friedmanab3a1282010-09-15 20:08:03 +0000403 Scale = (int64_t)Scale >> ShiftBits;
Chris Lattner9f7500f2010-08-18 22:07:29 +0000404 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000405
Chris Lattner1b9c3872010-08-18 22:47:56 +0000406 if (Scale) {
Jeffrey Yasskin6381c012011-07-27 06:22:51 +0000407 VariableGEPIndex Entry = {Index, Extension,
408 static_cast<int64_t>(Scale)};
Chris Lattner1b9c3872010-08-18 22:47:56 +0000409 VarIndices.push_back(Entry);
410 }
Chris Lattner9f7500f2010-08-18 22:07:29 +0000411 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000412
Chris Lattner9f7500f2010-08-18 22:07:29 +0000413 // Analyze the base pointer next.
414 V = GEPOp->getOperand(0);
415 } while (--MaxLookup);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000416
Chris Lattner9f7500f2010-08-18 22:07:29 +0000417 // If the chain of expressions is too deep, just return early.
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000418 MaxLookupReached = true;
Chris Lattner9f7500f2010-08-18 22:07:29 +0000419 return V;
420}
421
Chris Lattner9f7500f2010-08-18 22:07:29 +0000422//===----------------------------------------------------------------------===//
Dan Gohman0824aff2010-06-29 00:50:39 +0000423// BasicAliasAnalysis Pass
Chris Lattner2d332972008-06-16 06:30:22 +0000424//===----------------------------------------------------------------------===//
425
Dan Gohman00ef9322010-07-07 14:27:09 +0000426#ifndef NDEBUG
Dan Gohman0824aff2010-06-29 00:50:39 +0000427static const Function *getParent(const Value *V) {
Dan Gohman1be9e7c2010-06-29 18:12:34 +0000428 if (const Instruction *inst = dyn_cast<Instruction>(V))
Dan Gohman0824aff2010-06-29 00:50:39 +0000429 return inst->getParent()->getParent();
430
Dan Gohman1be9e7c2010-06-29 18:12:34 +0000431 if (const Argument *arg = dyn_cast<Argument>(V))
Dan Gohman0824aff2010-06-29 00:50:39 +0000432 return arg->getParent();
433
Craig Topper9f008862014-04-15 04:59:12 +0000434 return nullptr;
Dan Gohman0824aff2010-06-29 00:50:39 +0000435}
436
Dan Gohman84f90a32010-07-01 20:08:40 +0000437static bool notDifferentParent(const Value *O1, const Value *O2) {
438
439 const Function *F1 = getParent(O1);
440 const Function *F2 = getParent(O2);
441
Dan Gohman0824aff2010-06-29 00:50:39 +0000442 return !F1 || !F2 || F1 == F2;
443}
Benjamin Kramer80b7bc02010-06-29 10:03:11 +0000444#endif
Dan Gohman0824aff2010-06-29 00:50:39 +0000445
Chris Lattner2d332972008-06-16 06:30:22 +0000446namespace {
Dan Gohmanda85ed82010-10-19 23:09:08 +0000447 /// BasicAliasAnalysis - This is the primary alias analysis implementation.
448 struct BasicAliasAnalysis : public ImmutablePass, public AliasAnalysis {
Chris Lattner2d332972008-06-16 06:30:22 +0000449 static char ID; // Class identification, replacement for typeinfo
Benjamin Kramer6c2649c2012-09-05 16:49:37 +0000450 BasicAliasAnalysis() : ImmutablePass(ID) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000451 initializeBasicAliasAnalysisPass(*PassRegistry::getPassRegistry());
452 }
Dan Gohman0824aff2010-06-29 00:50:39 +0000453
Craig Toppere9ba7592014-03-05 07:30:04 +0000454 void initializePass() override {
Dan Gohman02538ac2010-10-18 18:04:47 +0000455 InitializeAliasAnalysis(this);
456 }
457
Craig Toppere9ba7592014-03-05 07:30:04 +0000458 void getAnalysisUsage(AnalysisUsage &AU) const override {
Dan Gohman02538ac2010-10-18 18:04:47 +0000459 AU.addRequired<AliasAnalysis>();
Hal Finkel60db0582014-09-07 18:57:58 +0000460 AU.addRequired<AssumptionTracker>();
Owen Anderson653cb032011-09-06 23:33:25 +0000461 AU.addRequired<TargetLibraryInfo>();
Dan Gohman02538ac2010-10-18 18:04:47 +0000462 }
463
Craig Toppere9ba7592014-03-05 07:30:04 +0000464 AliasResult alias(const Location &LocA, const Location &LocB) override {
Dan Gohmanfb02cec2011-06-04 00:31:50 +0000465 assert(AliasCache.empty() && "AliasCache must be cleared after use!");
Dan Gohman41f14cf2010-09-14 21:25:10 +0000466 assert(notDifferentParent(LocA.Ptr, LocB.Ptr) &&
Dan Gohman00ef9322010-07-07 14:27:09 +0000467 "BasicAliasAnalysis doesn't support interprocedural queries.");
Hal Finkelcc39b672014-07-24 12:16:19 +0000468 AliasResult Alias = aliasCheck(LocA.Ptr, LocA.Size, LocA.AATags,
469 LocB.Ptr, LocB.Size, LocB.AATags);
Benjamin Kramer6c2649c2012-09-05 16:49:37 +0000470 // AliasCache rarely has more than 1 or 2 elements, always use
471 // shrink_and_clear so it quickly returns to the inline capacity of the
472 // SmallDenseMap if it ever grows larger.
473 // FIXME: This should really be shrink_to_inline_capacity_and_clear().
474 AliasCache.shrink_and_clear();
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +0000475 VisitedPhiBBs.clear();
Evan Chengb3ccb642009-10-14 06:46:26 +0000476 return Alias;
Evan Chengc10e88d2009-10-13 22:02:20 +0000477 }
Chris Lattner2d332972008-06-16 06:30:22 +0000478
Craig Toppere9ba7592014-03-05 07:30:04 +0000479 ModRefResult getModRefInfo(ImmutableCallSite CS,
480 const Location &Loc) override;
Dan Gohman5f1702e2010-08-06 01:25:49 +0000481
Craig Toppere9ba7592014-03-05 07:30:04 +0000482 ModRefResult getModRefInfo(ImmutableCallSite CS1,
Hal Finkel93046912014-07-25 21:13:35 +0000483 ImmutableCallSite CS2) override;
Owen Anderson98a36172009-02-05 23:36:27 +0000484
Chris Lattner2d332972008-06-16 06:30:22 +0000485 /// pointsToConstantMemory - Chase pointers until we find a (constant
486 /// global) or not.
Craig Toppere9ba7592014-03-05 07:30:04 +0000487 bool pointsToConstantMemory(const Location &Loc, bool OrLocal) override;
Dan Gohman5f1702e2010-08-06 01:25:49 +0000488
Hal Finkel354e23b2014-07-17 01:28:25 +0000489 /// Get the location associated with a pointer argument of a callsite.
490 Location getArgLocation(ImmutableCallSite CS, unsigned ArgIdx,
491 ModRefResult &Mask) override;
492
Dan Gohman5f1702e2010-08-06 01:25:49 +0000493 /// getModRefBehavior - Return the behavior when calling the given
494 /// call site.
Craig Toppere9ba7592014-03-05 07:30:04 +0000495 ModRefBehavior getModRefBehavior(ImmutableCallSite CS) override;
Dan Gohman5f1702e2010-08-06 01:25:49 +0000496
497 /// getModRefBehavior - Return the behavior when calling the given function.
498 /// For use when the call site is not known.
Craig Toppere9ba7592014-03-05 07:30:04 +0000499 ModRefBehavior getModRefBehavior(const Function *F) override;
Chris Lattner2d332972008-06-16 06:30:22 +0000500
Chris Lattneraf362f02010-01-20 19:26:14 +0000501 /// getAdjustedAnalysisPointer - This method is used when a pass implements
Dan Gohmane0d5c452010-08-05 23:48:14 +0000502 /// an analysis interface through multiple inheritance. If needed, it
503 /// should override this to adjust the this pointer as needed for the
504 /// specified pass info.
Craig Toppere9ba7592014-03-05 07:30:04 +0000505 void *getAdjustedAnalysisPointer(const void *ID) override {
Owen Andersona7aed182010-08-06 18:33:48 +0000506 if (ID == &AliasAnalysis::ID)
Chris Lattneraf362f02010-01-20 19:26:14 +0000507 return (AliasAnalysis*)this;
508 return this;
509 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000510
Chris Lattner2d332972008-06-16 06:30:22 +0000511 private:
Dan Gohmanfb02cec2011-06-04 00:31:50 +0000512 // AliasCache - Track alias queries to guard against recursion.
513 typedef std::pair<Location, Location> LocPair;
Benjamin Kramer6c2649c2012-09-05 16:49:37 +0000514 typedef SmallDenseMap<LocPair, AliasResult, 8> AliasCacheTy;
Dan Gohmanfb02cec2011-06-04 00:31:50 +0000515 AliasCacheTy AliasCache;
516
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +0000517 /// \brief Track phi nodes we have visited. When interpret "Value" pointer
518 /// equality as value equality we need to make sure that the "Value" is not
519 /// part of a cycle. Otherwise, two uses could come from different
520 /// "iterations" of a cycle and see different values for the same "Value"
521 /// pointer.
522 /// The following example shows the problem:
523 /// %p = phi(%alloca1, %addr2)
524 /// %l = load %ptr
525 /// %addr1 = gep, %alloca2, 0, %l
526 /// %addr2 = gep %alloca2, 0, (%l + 1)
527 /// alias(%p, %addr1) -> MayAlias !
528 /// store %l, ...
529 SmallPtrSet<const BasicBlock*, 8> VisitedPhiBBs;
530
Dan Gohmanfb02cec2011-06-04 00:31:50 +0000531 // Visited - Track instructions visited by pointsToConstantMemory.
Dan Gohman7c34ece2010-06-28 21:16:52 +0000532 SmallPtrSet<const Value*, 16> Visited;
Evan Cheng31565b32009-10-14 05:05:02 +0000533
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +0000534 /// \brief Check whether two Values can be considered equivalent.
535 ///
536 /// In addition to pointer equivalence of \p V1 and \p V2 this checks
537 /// whether they can not be part of a cycle in the value graph by looking at
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +0000538 /// all visited phi nodes an making sure that the phis cannot reach the
539 /// value. We have to do this because we are looking through phi nodes (That
540 /// is we say noalias(V, phi(VA, VB)) if noalias(V, VA) and noalias(V, VB).
541 bool isValueEqualInPotentialCycles(const Value *V1, const Value *V2);
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +0000542
543 /// \brief Dest and Src are the variable indices from two decomposed
544 /// GetElementPtr instructions GEP1 and GEP2 which have common base
545 /// pointers. Subtract the GEP2 indices from GEP1 to find the symbolic
546 /// difference between the two pointers.
547 void GetIndexDifference(SmallVectorImpl<VariableGEPIndex> &Dest,
548 const SmallVectorImpl<VariableGEPIndex> &Src);
549
Chris Lattner98e253262009-11-23 16:45:27 +0000550 // aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP
551 // instruction against another.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000552 AliasResult aliasGEP(const GEPOperator *V1, uint64_t V1Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000553 const AAMDNodes &V1AAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +0000554 const Value *V2, uint64_t V2Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000555 const AAMDNodes &V2AAInfo,
Chris Lattner5341c962009-11-26 02:14:59 +0000556 const Value *UnderlyingV1, const Value *UnderlyingV2);
Evan Chengc10e88d2009-10-13 22:02:20 +0000557
Chris Lattner98e253262009-11-23 16:45:27 +0000558 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI
559 // instruction against another.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000560 AliasResult aliasPHI(const PHINode *PN, uint64_t PNSize,
Hal Finkelcc39b672014-07-24 12:16:19 +0000561 const AAMDNodes &PNAAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +0000562 const Value *V2, uint64_t V2Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000563 const AAMDNodes &V2AAInfo);
Evan Chengc10e88d2009-10-13 22:02:20 +0000564
Dan Gohman3b7ba5f2009-10-26 21:55:43 +0000565 /// aliasSelect - Disambiguate a Select instruction against another value.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000566 AliasResult aliasSelect(const SelectInst *SI, uint64_t SISize,
Hal Finkelcc39b672014-07-24 12:16:19 +0000567 const AAMDNodes &SIAAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +0000568 const Value *V2, uint64_t V2Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000569 const AAMDNodes &V2AAInfo);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +0000570
Dan Gohmanf372cf82010-10-19 22:54:46 +0000571 AliasResult aliasCheck(const Value *V1, uint64_t V1Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000572 AAMDNodes V1AATag,
Dan Gohmanf372cf82010-10-19 22:54:46 +0000573 const Value *V2, uint64_t V2Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000574 AAMDNodes V2AATag);
Chris Lattner2d332972008-06-16 06:30:22 +0000575 };
576} // End of anonymous namespace
577
578// Register this pass...
579char BasicAliasAnalysis::ID = 0;
Owen Anderson653cb032011-09-06 23:33:25 +0000580INITIALIZE_AG_PASS_BEGIN(BasicAliasAnalysis, AliasAnalysis, "basicaa",
Dan Gohmanda85ed82010-10-19 23:09:08 +0000581 "Basic Alias Analysis (stateless AA impl)",
Dan Gohman02538ac2010-10-18 18:04:47 +0000582 false, true, false)
Hal Finkel60db0582014-09-07 18:57:58 +0000583INITIALIZE_PASS_DEPENDENCY(AssumptionTracker)
Owen Anderson653cb032011-09-06 23:33:25 +0000584INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
585INITIALIZE_AG_PASS_END(BasicAliasAnalysis, AliasAnalysis, "basicaa",
586 "Basic Alias Analysis (stateless AA impl)",
587 false, true, false)
588
Chris Lattner2d332972008-06-16 06:30:22 +0000589
590ImmutablePass *llvm::createBasicAliasAnalysisPass() {
591 return new BasicAliasAnalysis();
592}
593
Dan Gohman9130bad2010-11-08 16:45:26 +0000594/// pointsToConstantMemory - Returns whether the given pointer value
595/// points to memory that is local to the function, with global constants being
596/// considered local to all functions.
597bool
598BasicAliasAnalysis::pointsToConstantMemory(const Location &Loc, bool OrLocal) {
599 assert(Visited.empty() && "Visited must be cleared after use!");
Chris Lattner2d332972008-06-16 06:30:22 +0000600
Dan Gohman142ff822010-11-08 20:26:19 +0000601 unsigned MaxLookup = 8;
Dan Gohman9130bad2010-11-08 16:45:26 +0000602 SmallVector<const Value *, 16> Worklist;
603 Worklist.push_back(Loc.Ptr);
604 do {
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000605 const Value *V = GetUnderlyingObject(Worklist.pop_back_val(), DL);
Dan Gohman9130bad2010-11-08 16:45:26 +0000606 if (!Visited.insert(V)) {
607 Visited.clear();
608 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
609 }
Dan Gohman5f1702e2010-08-06 01:25:49 +0000610
Dan Gohman9130bad2010-11-08 16:45:26 +0000611 // An alloca instruction defines local memory.
612 if (OrLocal && isa<AllocaInst>(V))
613 continue;
614
615 // A global constant counts as local memory for our purposes.
616 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
617 // Note: this doesn't require GV to be "ODR" because it isn't legal for a
618 // global to be marked constant in some modules and non-constant in
619 // others. GV may even be a declaration, not a definition.
620 if (!GV->isConstant()) {
621 Visited.clear();
622 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
623 }
624 continue;
625 }
626
627 // If both select values point to local memory, then so does the select.
628 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
629 Worklist.push_back(SI->getTrueValue());
630 Worklist.push_back(SI->getFalseValue());
631 continue;
632 }
633
634 // If all values incoming to a phi node point to local memory, then so does
635 // the phi.
636 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
Dan Gohman142ff822010-11-08 20:26:19 +0000637 // Don't bother inspecting phi nodes with many operands.
638 if (PN->getNumIncomingValues() > MaxLookup) {
639 Visited.clear();
640 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
641 }
Dan Gohman9130bad2010-11-08 16:45:26 +0000642 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
643 Worklist.push_back(PN->getIncomingValue(i));
644 continue;
645 }
646
647 // Otherwise be conservative.
648 Visited.clear();
649 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
650
Dan Gohman142ff822010-11-08 20:26:19 +0000651 } while (!Worklist.empty() && --MaxLookup);
Dan Gohman9130bad2010-11-08 16:45:26 +0000652
653 Visited.clear();
Dan Gohman142ff822010-11-08 20:26:19 +0000654 return Worklist.empty();
Chris Lattner2d332972008-06-16 06:30:22 +0000655}
656
Hal Finkel354e23b2014-07-17 01:28:25 +0000657static bool isMemsetPattern16(const Function *MS,
658 const TargetLibraryInfo &TLI) {
659 if (TLI.has(LibFunc::memset_pattern16) &&
660 MS->getName() == "memset_pattern16") {
661 FunctionType *MemsetType = MS->getFunctionType();
662 if (!MemsetType->isVarArg() && MemsetType->getNumParams() == 3 &&
663 isa<PointerType>(MemsetType->getParamType(0)) &&
664 isa<PointerType>(MemsetType->getParamType(1)) &&
665 isa<IntegerType>(MemsetType->getParamType(2)))
666 return true;
667 }
668
669 return false;
670}
671
Dan Gohman5f1702e2010-08-06 01:25:49 +0000672/// getModRefBehavior - Return the behavior when calling the given call site.
673AliasAnalysis::ModRefBehavior
674BasicAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
675 if (CS.doesNotAccessMemory())
676 // Can't do better than this.
677 return DoesNotAccessMemory;
678
679 ModRefBehavior Min = UnknownModRefBehavior;
680
681 // If the callsite knows it only reads memory, don't return worse
682 // than that.
683 if (CS.onlyReadsMemory())
684 Min = OnlyReadsMemory;
685
686 // The AliasAnalysis base class has some smarts, lets use them.
Dan Gohman2694e142010-11-10 01:02:18 +0000687 return ModRefBehavior(AliasAnalysis::getModRefBehavior(CS) & Min);
Dan Gohman5f1702e2010-08-06 01:25:49 +0000688}
689
690/// getModRefBehavior - Return the behavior when calling the given function.
691/// For use when the call site is not known.
692AliasAnalysis::ModRefBehavior
693BasicAliasAnalysis::getModRefBehavior(const Function *F) {
Dan Gohmane461d7d2010-11-08 16:08:43 +0000694 // If the function declares it doesn't access memory, we can't do better.
Dan Gohman5f1702e2010-08-06 01:25:49 +0000695 if (F->doesNotAccessMemory())
Dan Gohman5f1702e2010-08-06 01:25:49 +0000696 return DoesNotAccessMemory;
Dan Gohmane461d7d2010-11-08 16:08:43 +0000697
698 // For intrinsics, we can check the table.
699 if (unsigned iid = F->getIntrinsicID()) {
700#define GET_INTRINSIC_MODREF_BEHAVIOR
Chandler Carruthdb25c6c2013-01-02 12:09:16 +0000701#include "llvm/IR/Intrinsics.gen"
Dan Gohmane461d7d2010-11-08 16:08:43 +0000702#undef GET_INTRINSIC_MODREF_BEHAVIOR
703 }
704
Dan Gohman2694e142010-11-10 01:02:18 +0000705 ModRefBehavior Min = UnknownModRefBehavior;
706
Dan Gohmane461d7d2010-11-08 16:08:43 +0000707 // If the function declares it only reads memory, go with that.
Dan Gohman5f1702e2010-08-06 01:25:49 +0000708 if (F->onlyReadsMemory())
Dan Gohman2694e142010-11-10 01:02:18 +0000709 Min = OnlyReadsMemory;
Dan Gohman5f1702e2010-08-06 01:25:49 +0000710
Hal Finkel354e23b2014-07-17 01:28:25 +0000711 const TargetLibraryInfo &TLI = getAnalysis<TargetLibraryInfo>();
712 if (isMemsetPattern16(F, TLI))
713 Min = OnlyAccessesArgumentPointees;
714
Dan Gohmane461d7d2010-11-08 16:08:43 +0000715 // Otherwise be conservative.
Dan Gohman2694e142010-11-10 01:02:18 +0000716 return ModRefBehavior(AliasAnalysis::getModRefBehavior(F) & Min);
Dan Gohman5f1702e2010-08-06 01:25:49 +0000717}
Owen Anderson98a36172009-02-05 23:36:27 +0000718
Hal Finkel354e23b2014-07-17 01:28:25 +0000719AliasAnalysis::Location
720BasicAliasAnalysis::getArgLocation(ImmutableCallSite CS, unsigned ArgIdx,
721 ModRefResult &Mask) {
722 Location Loc = AliasAnalysis::getArgLocation(CS, ArgIdx, Mask);
723 const TargetLibraryInfo &TLI = getAnalysis<TargetLibraryInfo>();
724 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
725 if (II != nullptr)
726 switch (II->getIntrinsicID()) {
727 default: break;
728 case Intrinsic::memset:
729 case Intrinsic::memcpy:
730 case Intrinsic::memmove: {
731 assert((ArgIdx == 0 || ArgIdx == 1) &&
732 "Invalid argument index for memory intrinsic");
733 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getArgOperand(2)))
734 Loc.Size = LenCI->getZExtValue();
735 assert(Loc.Ptr == II->getArgOperand(ArgIdx) &&
736 "Memory intrinsic location pointer not argument?");
737 Mask = ArgIdx ? Ref : Mod;
738 break;
739 }
740 case Intrinsic::lifetime_start:
741 case Intrinsic::lifetime_end:
742 case Intrinsic::invariant_start: {
743 assert(ArgIdx == 1 && "Invalid argument index");
744 assert(Loc.Ptr == II->getArgOperand(ArgIdx) &&
745 "Intrinsic location pointer not argument?");
746 Loc.Size = cast<ConstantInt>(II->getArgOperand(0))->getZExtValue();
747 break;
748 }
749 case Intrinsic::invariant_end: {
750 assert(ArgIdx == 2 && "Invalid argument index");
751 assert(Loc.Ptr == II->getArgOperand(ArgIdx) &&
752 "Intrinsic location pointer not argument?");
753 Loc.Size = cast<ConstantInt>(II->getArgOperand(1))->getZExtValue();
754 break;
755 }
756 case Intrinsic::arm_neon_vld1: {
757 assert(ArgIdx == 0 && "Invalid argument index");
758 assert(Loc.Ptr == II->getArgOperand(ArgIdx) &&
759 "Intrinsic location pointer not argument?");
760 // LLVM's vld1 and vst1 intrinsics currently only support a single
761 // vector register.
762 if (DL)
763 Loc.Size = DL->getTypeStoreSize(II->getType());
764 break;
765 }
766 case Intrinsic::arm_neon_vst1: {
767 assert(ArgIdx == 0 && "Invalid argument index");
768 assert(Loc.Ptr == II->getArgOperand(ArgIdx) &&
769 "Intrinsic location pointer not argument?");
770 if (DL)
771 Loc.Size = DL->getTypeStoreSize(II->getArgOperand(1)->getType());
772 break;
773 }
774 }
775
776 // We can bound the aliasing properties of memset_pattern16 just as we can
777 // for memcpy/memset. This is particularly important because the
778 // LoopIdiomRecognizer likes to turn loops into calls to memset_pattern16
779 // whenever possible.
780 else if (CS.getCalledFunction() &&
781 isMemsetPattern16(CS.getCalledFunction(), TLI)) {
782 assert((ArgIdx == 0 || ArgIdx == 1) &&
783 "Invalid argument index for memset_pattern16");
784 if (ArgIdx == 1)
785 Loc.Size = 16;
786 else if (const ConstantInt *LenCI =
787 dyn_cast<ConstantInt>(CS.getArgument(2)))
788 Loc.Size = LenCI->getZExtValue();
789 assert(Loc.Ptr == CS.getArgument(ArgIdx) &&
790 "memset_pattern16 location pointer not argument?");
791 Mask = ArgIdx ? Ref : Mod;
792 }
793 // FIXME: Handle memset_pattern4 and memset_pattern8 also.
794
795 return Loc;
796}
797
Hal Finkel93046912014-07-25 21:13:35 +0000798static bool isAssumeIntrinsic(ImmutableCallSite CS) {
799 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
800 if (II && II->getIntrinsicID() == Intrinsic::assume)
801 return true;
802
803 return false;
804}
805
Chris Lattner98e253262009-11-23 16:45:27 +0000806/// getModRefInfo - Check to see if the specified callsite can clobber the
807/// specified memory object. Since we only look at local properties of this
808/// function, we really can't say much about this query. We do, however, use
809/// simple "address taken" analysis on local objects.
Chris Lattner2d332972008-06-16 06:30:22 +0000810AliasAnalysis::ModRefResult
Dan Gohman5442c712010-08-03 21:48:53 +0000811BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS,
Dan Gohman41f14cf2010-09-14 21:25:10 +0000812 const Location &Loc) {
813 assert(notDifferentParent(CS.getInstruction(), Loc.Ptr) &&
Dan Gohman00ef9322010-07-07 14:27:09 +0000814 "AliasAnalysis query involving multiple functions!");
815
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000816 const Value *Object = GetUnderlyingObject(Loc.Ptr, DL);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000817
Dan Gohman41f14cf2010-09-14 21:25:10 +0000818 // If this is a tail call and Loc.Ptr points to a stack location, we know that
Chris Lattnerd6a49ad2009-11-22 16:05:05 +0000819 // the tail call cannot access or modify the local stack.
820 // We cannot exclude byval arguments here; these belong to the caller of
821 // the current function not to the current function, and a tail callee
822 // may reference them.
823 if (isa<AllocaInst>(Object))
Dan Gohman5442c712010-08-03 21:48:53 +0000824 if (const CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
Chris Lattnerd6a49ad2009-11-22 16:05:05 +0000825 if (CI->isTailCall())
826 return NoModRef;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000827
Chris Lattnerd6a49ad2009-11-22 16:05:05 +0000828 // If the pointer is to a locally allocated object that does not escape,
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000829 // then the call can not mod/ref the pointer unless the call takes the pointer
830 // as an argument, and itself doesn't capture it.
Chris Lattner1e7b37e2009-11-23 16:46:41 +0000831 if (!isa<Constant>(Object) && CS.getInstruction() != Object &&
Dan Gohman84f90a32010-07-01 20:08:40 +0000832 isNonEscapingLocalObject(Object)) {
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000833 bool PassedAsArg = false;
834 unsigned ArgNo = 0;
Dan Gohman5442c712010-08-03 21:48:53 +0000835 for (ImmutableCallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000836 CI != CE; ++CI, ++ArgNo) {
Chris Lattner026f5e62011-05-23 05:15:43 +0000837 // Only look at the no-capture or byval pointer arguments. If this
838 // pointer were passed to arguments that were neither of these, then it
839 // couldn't be no-capture.
Duncan Sands19d0b472010-02-16 11:11:14 +0000840 if (!(*CI)->getType()->isPointerTy() ||
Nick Lewycky612d70b2011-11-20 19:09:04 +0000841 (!CS.doesNotCapture(ArgNo) && !CS.isByValArgument(ArgNo)))
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000842 continue;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000843
Dan Gohman41f14cf2010-09-14 21:25:10 +0000844 // If this is a no-capture pointer argument, see if we can tell that it
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000845 // is impossible to alias the pointer we're checking. If not, we have to
846 // assume that the call could touch the pointer, even though it doesn't
847 // escape.
Eli Friedman5f476dc2011-09-28 00:34:27 +0000848 if (!isNoAlias(Location(*CI), Location(Object))) {
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000849 PassedAsArg = true;
850 break;
851 }
852 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000853
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000854 if (!PassedAsArg)
Chris Lattnerd6a49ad2009-11-22 16:05:05 +0000855 return NoModRef;
856 }
857
Hal Finkel93046912014-07-25 21:13:35 +0000858 // While the assume intrinsic is marked as arbitrarily writing so that
859 // proper control dependencies will be maintained, it never aliases any
860 // particular memory location.
861 if (isAssumeIntrinsic(CS))
862 return NoModRef;
863
Chris Lattner2d332972008-06-16 06:30:22 +0000864 // The AliasAnalysis base class has some smarts, lets use them.
Hal Finkel354e23b2014-07-17 01:28:25 +0000865 return AliasAnalysis::getModRefInfo(CS, Loc);
Dan Gohman64d842e2010-09-08 01:32:20 +0000866}
Chris Lattner2d332972008-06-16 06:30:22 +0000867
Hal Finkel93046912014-07-25 21:13:35 +0000868AliasAnalysis::ModRefResult
869BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
870 ImmutableCallSite CS2) {
871 // While the assume intrinsic is marked as arbitrarily writing so that
872 // proper control dependencies will be maintained, it never aliases any
873 // particular memory location.
874 if (isAssumeIntrinsic(CS1) || isAssumeIntrinsic(CS2))
875 return NoModRef;
876
877 // The AliasAnalysis base class has some smarts, lets use them.
878 return AliasAnalysis::getModRefInfo(CS1, CS2);
879}
880
Chris Lattnera99edbe2009-11-26 02:11:08 +0000881/// aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
882/// against another pointer. We know that V1 is a GEP, but we don't know
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000883/// anything about V2. UnderlyingV1 is GetUnderlyingObject(GEP1, DL),
Chris Lattner5341c962009-11-26 02:14:59 +0000884/// UnderlyingV2 is the same for V2.
Chris Lattnera99edbe2009-11-26 02:11:08 +0000885///
Chris Lattnerd6a2a992003-02-26 19:41:54 +0000886AliasAnalysis::AliasResult
Dan Gohmanf372cf82010-10-19 22:54:46 +0000887BasicAliasAnalysis::aliasGEP(const GEPOperator *GEP1, uint64_t V1Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000888 const AAMDNodes &V1AAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +0000889 const Value *V2, uint64_t V2Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000890 const AAMDNodes &V2AAInfo,
Chris Lattner5341c962009-11-26 02:14:59 +0000891 const Value *UnderlyingV1,
892 const Value *UnderlyingV2) {
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000893 int64_t GEP1BaseOffset;
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000894 bool GEP1MaxLookupReached;
Chris Lattner1b9c3872010-08-18 22:47:56 +0000895 SmallVector<VariableGEPIndex, 4> GEP1VariableIndices;
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000896
Hal Finkel60db0582014-09-07 18:57:58 +0000897 AssumptionTracker *AT = &getAnalysis<AssumptionTracker>();
898 DominatorTreeWrapperPass *DTWP =
899 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
900 DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
901
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000902 // If we have two gep instructions with must-alias or not-alias'ing base
903 // pointers, figure out if the indexes to the GEP tell us anything about the
904 // derived pointer.
Chris Lattnera99edbe2009-11-26 02:11:08 +0000905 if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
Arnold Schwaighoferaadf1042013-03-26 18:07:53 +0000906 // Do the base pointers alias?
Craig Topper9f008862014-04-15 04:59:12 +0000907 AliasResult BaseAlias = aliasCheck(UnderlyingV1, UnknownSize, nullptr,
908 UnderlyingV2, UnknownSize, nullptr);
Arnold Schwaighoferaadf1042013-03-26 18:07:53 +0000909
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000910 // Check for geps of non-aliasing underlying pointers where the offsets are
911 // identical.
Arnold Schwaighoferaadf1042013-03-26 18:07:53 +0000912 if ((BaseAlias == MayAlias) && V1Size == V2Size) {
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000913 // Do the base pointers alias assuming type and size.
914 AliasResult PreciseBaseAlias = aliasCheck(UnderlyingV1, V1Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000915 V1AAInfo, UnderlyingV2,
916 V2Size, V2AAInfo);
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000917 if (PreciseBaseAlias == NoAlias) {
918 // See if the computed offset from the common pointer tells us about the
919 // relation of the resulting pointer.
920 int64_t GEP2BaseOffset;
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000921 bool GEP2MaxLookupReached;
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000922 SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
923 const Value *GEP2BasePtr =
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000924 DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices,
Hal Finkel60db0582014-09-07 18:57:58 +0000925 GEP2MaxLookupReached, DL, AT, DT);
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000926 const Value *GEP1BasePtr =
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000927 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
Hal Finkel60db0582014-09-07 18:57:58 +0000928 GEP1MaxLookupReached, DL, AT, DT);
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000929 // DecomposeGEPExpression and GetUnderlyingObject should return the
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000930 // same result except when DecomposeGEPExpression has no DataLayout.
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000931 if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
Craig Topper9f008862014-04-15 04:59:12 +0000932 assert(!DL &&
933 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000934 return MayAlias;
935 }
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000936 // If the max search depth is reached the result is undefined
937 if (GEP2MaxLookupReached || GEP1MaxLookupReached)
938 return MayAlias;
939
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000940 // Same offsets.
941 if (GEP1BaseOffset == GEP2BaseOffset &&
Benjamin Kramer147644d2014-04-18 19:48:03 +0000942 GEP1VariableIndices == GEP2VariableIndices)
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000943 return NoAlias;
944 GEP1VariableIndices.clear();
945 }
946 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000947
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000948 // If we get a No or May, then return it immediately, no amount of analysis
949 // will improve this situation.
950 if (BaseAlias != MustAlias) return BaseAlias;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000951
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000952 // Otherwise, we have a MustAlias. Since the base pointers alias each other
953 // exactly, see if the computed offset from the common pointer tells us
954 // about the relation of the resulting pointer.
955 const Value *GEP1BasePtr =
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000956 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
Hal Finkel60db0582014-09-07 18:57:58 +0000957 GEP1MaxLookupReached, DL, AT, DT);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000958
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000959 int64_t GEP2BaseOffset;
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000960 bool GEP2MaxLookupReached;
Chris Lattner1b9c3872010-08-18 22:47:56 +0000961 SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000962 const Value *GEP2BasePtr =
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000963 DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices,
Hal Finkel60db0582014-09-07 18:57:58 +0000964 GEP2MaxLookupReached, DL, AT, DT);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000965
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000966 // DecomposeGEPExpression and GetUnderlyingObject should return the
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000967 // same result except when DecomposeGEPExpression has no DataLayout.
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000968 if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
Craig Topper9f008862014-04-15 04:59:12 +0000969 assert(!DL &&
Dan Gohmana4fcd242010-12-15 20:02:24 +0000970 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000971 return MayAlias;
972 }
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000973 // If the max search depth is reached the result is undefined
974 if (GEP2MaxLookupReached || GEP1MaxLookupReached)
975 return MayAlias;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000976
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000977 // Subtract the GEP2 pointer from the GEP1 pointer to find out their
978 // symbolic difference.
979 GEP1BaseOffset -= GEP2BaseOffset;
Dan Gohmanad867b02010-08-03 20:23:52 +0000980 GetIndexDifference(GEP1VariableIndices, GEP2VariableIndices);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000981
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000982 } else {
983 // Check to see if these two pointers are related by the getelementptr
984 // instruction. If one pointer is a GEP with a non-zero index of the other
985 // pointer, we know they cannot alias.
Chris Lattner5c1cfc22009-11-26 16:52:32 +0000986
987 // If both accesses are unknown size, we can't do anything useful here.
Dan Gohman2a190082010-08-03 01:03:11 +0000988 if (V1Size == UnknownSize && V2Size == UnknownSize)
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000989 return MayAlias;
Chris Lattner6ea17f77f2003-12-11 22:44:13 +0000990
Craig Topper9f008862014-04-15 04:59:12 +0000991 AliasResult R = aliasCheck(UnderlyingV1, UnknownSize, nullptr,
Hal Finkelcc39b672014-07-24 12:16:19 +0000992 V2, V2Size, V2AAInfo);
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000993 if (R != MustAlias)
994 // If V2 may alias GEP base pointer, conservatively returns MayAlias.
995 // If V2 is known not to alias GEP base pointer, then the two values
996 // cannot alias per GEP semantics: "A pointer value formed from a
997 // getelementptr instruction is associated with the addresses associated
998 // with the first operand of the getelementptr".
999 return R;
Chris Lattner6ea17f77f2003-12-11 22:44:13 +00001000
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001001 const Value *GEP1BasePtr =
Arnold Schwaighofer1a444482014-03-26 21:30:19 +00001002 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
Hal Finkel60db0582014-09-07 18:57:58 +00001003 GEP1MaxLookupReached, DL, AT, DT);
Jakub Staszak07f383f2013-08-24 14:16:00 +00001004
Arnold Schwaighofer76dca582012-09-06 14:31:51 +00001005 // DecomposeGEPExpression and GetUnderlyingObject should return the
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001006 // same result except when DecomposeGEPExpression has no DataLayout.
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001007 if (GEP1BasePtr != UnderlyingV1) {
Craig Topper9f008862014-04-15 04:59:12 +00001008 assert(!DL &&
Dan Gohmana4fcd242010-12-15 20:02:24 +00001009 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001010 return MayAlias;
Chris Lattner6ea17f77f2003-12-11 22:44:13 +00001011 }
Arnold Schwaighofer1a444482014-03-26 21:30:19 +00001012 // If the max search depth is reached the result is undefined
1013 if (GEP1MaxLookupReached)
1014 return MayAlias;
Chris Lattner6ea17f77f2003-12-11 22:44:13 +00001015 }
Jakub Staszak07f383f2013-08-24 14:16:00 +00001016
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001017 // In the two GEP Case, if there is no difference in the offsets of the
1018 // computed pointers, the resultant pointers are a must alias. This
1019 // hapens when we have two lexically identical GEP's (for example).
Chris Lattnerd6a2a992003-02-26 19:41:54 +00001020 //
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001021 // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
1022 // must aliases the GEP, the end result is a must alias also.
1023 if (GEP1BaseOffset == 0 && GEP1VariableIndices.empty())
Evan Chengc1eed9d2009-10-14 06:41:49 +00001024 return MustAlias;
Evan Chengf1f3dd32009-10-13 18:42:04 +00001025
Eli Friedman3d1b3072011-09-08 02:23:31 +00001026 // If there is a constant difference between the pointers, but the difference
1027 // is less than the size of the associated memory object, then we know
1028 // that the objects are partially overlapping. If the difference is
1029 // greater, we know they do not overlap.
Dan Gohmanc4bf5ca2010-12-13 22:50:24 +00001030 if (GEP1BaseOffset != 0 && GEP1VariableIndices.empty()) {
Eli Friedman3d1b3072011-09-08 02:23:31 +00001031 if (GEP1BaseOffset >= 0) {
1032 if (V2Size != UnknownSize) {
1033 if ((uint64_t)GEP1BaseOffset < V2Size)
1034 return PartialAlias;
1035 return NoAlias;
1036 }
1037 } else {
Arnold Schwaighofere3ac0992014-01-16 04:53:18 +00001038 // We have the situation where:
1039 // + +
1040 // | BaseOffset |
1041 // ---------------->|
1042 // |-->V1Size |-------> V2Size
1043 // GEP1 V2
1044 // We need to know that V2Size is not unknown, otherwise we might have
1045 // stripped a gep with negative index ('gep <ptr>, -1, ...).
1046 if (V1Size != UnknownSize && V2Size != UnknownSize) {
Eli Friedman3d1b3072011-09-08 02:23:31 +00001047 if (-(uint64_t)GEP1BaseOffset < V1Size)
1048 return PartialAlias;
1049 return NoAlias;
1050 }
1051 }
Dan Gohmanc4bf5ca2010-12-13 22:50:24 +00001052 }
1053
Eli Friedman3d1b3072011-09-08 02:23:31 +00001054 // Try to distinguish something like &A[i][1] against &A[42][0].
1055 // Grab the least significant bit set in any of the scales.
Eli Friedmanb78ac542011-09-08 02:37:07 +00001056 if (!GEP1VariableIndices.empty()) {
1057 uint64_t Modulo = 0;
1058 for (unsigned i = 0, e = GEP1VariableIndices.size(); i != e; ++i)
1059 Modulo |= (uint64_t)GEP1VariableIndices[i].Scale;
1060 Modulo = Modulo ^ (Modulo & (Modulo - 1));
Eli Friedman3d1b3072011-09-08 02:23:31 +00001061
Eli Friedmanb78ac542011-09-08 02:37:07 +00001062 // We can compute the difference between the two addresses
1063 // mod Modulo. Check whether that difference guarantees that the
1064 // two locations do not alias.
1065 uint64_t ModOffset = (uint64_t)GEP1BaseOffset & (Modulo - 1);
1066 if (V1Size != UnknownSize && V2Size != UnknownSize &&
1067 ModOffset >= V2Size && V1Size <= Modulo - ModOffset)
1068 return NoAlias;
1069 }
Eli Friedman3d1b3072011-09-08 02:23:31 +00001070
Dan Gohmanadf80ae2011-06-04 06:50:18 +00001071 // Statically, we can see that the base objects are the same, but the
1072 // pointers have dynamic offsets which we can't resolve. And none of our
1073 // little tricks above worked.
1074 //
1075 // TODO: Returning PartialAlias instead of MayAlias is a mild hack; the
1076 // practical effect of this is protecting TBAA in the case of dynamic
Dan Gohman9017b842012-02-17 18:33:38 +00001077 // indices into arrays of unions or malloc'd memory.
Dan Gohmanadf80ae2011-06-04 06:50:18 +00001078 return PartialAlias;
Evan Chengf1f3dd32009-10-13 18:42:04 +00001079}
1080
Dan Gohman4e7e7952011-06-03 20:17:36 +00001081static AliasAnalysis::AliasResult
1082MergeAliasResults(AliasAnalysis::AliasResult A, AliasAnalysis::AliasResult B) {
1083 // If the results agree, take it.
1084 if (A == B)
1085 return A;
1086 // A mix of PartialAlias and MustAlias is PartialAlias.
1087 if ((A == AliasAnalysis::PartialAlias && B == AliasAnalysis::MustAlias) ||
1088 (B == AliasAnalysis::PartialAlias && A == AliasAnalysis::MustAlias))
1089 return AliasAnalysis::PartialAlias;
1090 // Otherwise, we don't know anything.
1091 return AliasAnalysis::MayAlias;
1092}
1093
Chris Lattner98e253262009-11-23 16:45:27 +00001094/// aliasSelect - Provide a bunch of ad-hoc rules to disambiguate a Select
1095/// instruction against another.
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001096AliasAnalysis::AliasResult
Dan Gohmanf372cf82010-10-19 22:54:46 +00001097BasicAliasAnalysis::aliasSelect(const SelectInst *SI, uint64_t SISize,
Hal Finkelcc39b672014-07-24 12:16:19 +00001098 const AAMDNodes &SIAAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +00001099 const Value *V2, uint64_t V2Size,
Hal Finkelcc39b672014-07-24 12:16:19 +00001100 const AAMDNodes &V2AAInfo) {
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001101 // If the values are Selects with the same condition, we can do a more precise
1102 // check: just check for aliases between the values on corresponding arms.
1103 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
1104 if (SI->getCondition() == SI2->getCondition()) {
1105 AliasResult Alias =
Hal Finkelcc39b672014-07-24 12:16:19 +00001106 aliasCheck(SI->getTrueValue(), SISize, SIAAInfo,
1107 SI2->getTrueValue(), V2Size, V2AAInfo);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001108 if (Alias == MayAlias)
1109 return MayAlias;
1110 AliasResult ThisAlias =
Hal Finkelcc39b672014-07-24 12:16:19 +00001111 aliasCheck(SI->getFalseValue(), SISize, SIAAInfo,
1112 SI2->getFalseValue(), V2Size, V2AAInfo);
Dan Gohman4e7e7952011-06-03 20:17:36 +00001113 return MergeAliasResults(ThisAlias, Alias);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001114 }
1115
1116 // If both arms of the Select node NoAlias or MustAlias V2, then returns
1117 // NoAlias / MustAlias. Otherwise, returns MayAlias.
1118 AliasResult Alias =
Hal Finkelcc39b672014-07-24 12:16:19 +00001119 aliasCheck(V2, V2Size, V2AAInfo, SI->getTrueValue(), SISize, SIAAInfo);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001120 if (Alias == MayAlias)
1121 return MayAlias;
Dan Gohman7c34ece2010-06-28 21:16:52 +00001122
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001123 AliasResult ThisAlias =
Hal Finkelcc39b672014-07-24 12:16:19 +00001124 aliasCheck(V2, V2Size, V2AAInfo, SI->getFalseValue(), SISize, SIAAInfo);
Dan Gohman4e7e7952011-06-03 20:17:36 +00001125 return MergeAliasResults(ThisAlias, Alias);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001126}
1127
Evan Chengf92f5552009-10-14 05:22:03 +00001128// aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
Evan Cheng31565b32009-10-14 05:05:02 +00001129// against another.
Evan Chengc10e88d2009-10-13 22:02:20 +00001130AliasAnalysis::AliasResult
Dan Gohmanf372cf82010-10-19 22:54:46 +00001131BasicAliasAnalysis::aliasPHI(const PHINode *PN, uint64_t PNSize,
Hal Finkelcc39b672014-07-24 12:16:19 +00001132 const AAMDNodes &PNAAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +00001133 const Value *V2, uint64_t V2Size,
Hal Finkelcc39b672014-07-24 12:16:19 +00001134 const AAMDNodes &V2AAInfo) {
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001135 // Track phi nodes we have visited. We use this information when we determine
1136 // value equivalence.
1137 VisitedPhiBBs.insert(PN->getParent());
1138
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001139 // If the values are PHIs in the same block, we can do a more precise
1140 // as well as efficient check: just check for aliases between the values
1141 // on corresponding edges.
1142 if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
1143 if (PN2->getParent() == PN->getParent()) {
Hal Finkelcc39b672014-07-24 12:16:19 +00001144 LocPair Locs(Location(PN, PNSize, PNAAInfo),
1145 Location(V2, V2Size, V2AAInfo));
Arnold Schwaighofer8dc34cf2012-09-06 14:41:53 +00001146 if (PN > V2)
1147 std::swap(Locs.first, Locs.second);
Arnold Schwaighoferedd62b12012-12-10 23:02:41 +00001148 // Analyse the PHIs' inputs under the assumption that the PHIs are
1149 // NoAlias.
1150 // If the PHIs are May/MustAlias there must be (recursively) an input
1151 // operand from outside the PHIs' cycle that is MayAlias/MustAlias or
1152 // there must be an operation on the PHIs within the PHIs' value cycle
1153 // that causes a MayAlias.
1154 // Pretend the phis do not alias.
1155 AliasResult Alias = NoAlias;
1156 assert(AliasCache.count(Locs) &&
1157 "There must exist an entry for the phi node");
1158 AliasResult OrigAliasResult = AliasCache[Locs];
1159 AliasCache[Locs] = NoAlias;
Arnold Schwaighofer8dc34cf2012-09-06 14:41:53 +00001160
Hal Finkela6f86fc2012-11-17 02:33:15 +00001161 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001162 AliasResult ThisAlias =
Hal Finkelcc39b672014-07-24 12:16:19 +00001163 aliasCheck(PN->getIncomingValue(i), PNSize, PNAAInfo,
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001164 PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
Hal Finkelcc39b672014-07-24 12:16:19 +00001165 V2Size, V2AAInfo);
Dan Gohman4e7e7952011-06-03 20:17:36 +00001166 Alias = MergeAliasResults(ThisAlias, Alias);
1167 if (Alias == MayAlias)
1168 break;
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001169 }
Arnold Schwaighofer8dc34cf2012-09-06 14:41:53 +00001170
1171 // Reset if speculation failed.
Arnold Schwaighoferedd62b12012-12-10 23:02:41 +00001172 if (Alias != NoAlias)
Arnold Schwaighofer8dc34cf2012-09-06 14:41:53 +00001173 AliasCache[Locs] = OrigAliasResult;
1174
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001175 return Alias;
1176 }
1177
Evan Cheng8ec25932009-10-16 00:33:09 +00001178 SmallPtrSet<Value*, 4> UniqueSrc;
Evan Chengc10e88d2009-10-13 22:02:20 +00001179 SmallVector<Value*, 4> V1Srcs;
Evan Chengc10e88d2009-10-13 22:02:20 +00001180 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1181 Value *PV1 = PN->getIncomingValue(i);
1182 if (isa<PHINode>(PV1))
1183 // If any of the source itself is a PHI, return MayAlias conservatively
Evan Chengc1eed9d2009-10-14 06:41:49 +00001184 // to avoid compile time explosion. The worst possible case is if both
1185 // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
1186 // and 'n' are the number of PHI sources.
Evan Chengc10e88d2009-10-13 22:02:20 +00001187 return MayAlias;
1188 if (UniqueSrc.insert(PV1))
1189 V1Srcs.push_back(PV1);
1190 }
1191
Hal Finkelcc39b672014-07-24 12:16:19 +00001192 AliasResult Alias = aliasCheck(V2, V2Size, V2AAInfo,
1193 V1Srcs[0], PNSize, PNAAInfo);
Evan Chengf92f5552009-10-14 05:22:03 +00001194 // Early exit if the check of the first PHI source against V2 is MayAlias.
1195 // Other results are not possible.
1196 if (Alias == MayAlias)
1197 return MayAlias;
1198
Evan Chengc10e88d2009-10-13 22:02:20 +00001199 // If all sources of the PHI node NoAlias or MustAlias V2, then returns
1200 // NoAlias / MustAlias. Otherwise, returns MayAlias.
Evan Chengc10e88d2009-10-13 22:02:20 +00001201 for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
1202 Value *V = V1Srcs[i];
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001203
Hal Finkelcc39b672014-07-24 12:16:19 +00001204 AliasResult ThisAlias = aliasCheck(V2, V2Size, V2AAInfo,
1205 V, PNSize, PNAAInfo);
Dan Gohman4e7e7952011-06-03 20:17:36 +00001206 Alias = MergeAliasResults(ThisAlias, Alias);
1207 if (Alias == MayAlias)
1208 break;
Evan Chengc10e88d2009-10-13 22:02:20 +00001209 }
1210
1211 return Alias;
1212}
1213
1214// aliasCheck - Provide a bunch of ad-hoc rules to disambiguate in common cases,
1215// such as array references.
Evan Chengf1f3dd32009-10-13 18:42:04 +00001216//
1217AliasAnalysis::AliasResult
Dan Gohmanf372cf82010-10-19 22:54:46 +00001218BasicAliasAnalysis::aliasCheck(const Value *V1, uint64_t V1Size,
Hal Finkelcc39b672014-07-24 12:16:19 +00001219 AAMDNodes V1AAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +00001220 const Value *V2, uint64_t V2Size,
Hal Finkelcc39b672014-07-24 12:16:19 +00001221 AAMDNodes V2AAInfo) {
Dan Gohmancb45bd92010-04-08 18:11:50 +00001222 // If either of the memory references is empty, it doesn't matter what the
1223 // pointer values are.
1224 if (V1Size == 0 || V2Size == 0)
1225 return NoAlias;
1226
Evan Chengf1f3dd32009-10-13 18:42:04 +00001227 // Strip off any casts if they exist.
1228 V1 = V1->stripPointerCasts();
1229 V2 = V2->stripPointerCasts();
1230
1231 // Are we checking for alias of the same value?
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001232 // Because we look 'through' phi nodes we could look at "Value" pointers from
1233 // different iterations. We must therefore make sure that this is not the
1234 // case. The function isValueEqualInPotentialCycles ensures that this cannot
1235 // happen by looking at the visited phi nodes and making sure they cannot
1236 // reach the value.
1237 if (isValueEqualInPotentialCycles(V1, V2))
1238 return MustAlias;
Evan Chengf1f3dd32009-10-13 18:42:04 +00001239
Duncan Sands19d0b472010-02-16 11:11:14 +00001240 if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
Evan Chengf1f3dd32009-10-13 18:42:04 +00001241 return NoAlias; // Scalars cannot alias each other
1242
1243 // Figure out what objects these things are pointing to if we can.
Arnold Schwaighofer1a444482014-03-26 21:30:19 +00001244 const Value *O1 = GetUnderlyingObject(V1, DL, MaxLookupSearchDepth);
1245 const Value *O2 = GetUnderlyingObject(V2, DL, MaxLookupSearchDepth);
Evan Chengf1f3dd32009-10-13 18:42:04 +00001246
Dan Gohmanccb45842009-11-09 19:29:11 +00001247 // Null values in the default address space don't point to any object, so they
1248 // don't alias any other pointer.
1249 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
1250 if (CPN->getType()->getAddressSpace() == 0)
1251 return NoAlias;
1252 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
1253 if (CPN->getType()->getAddressSpace() == 0)
1254 return NoAlias;
1255
Evan Chengf1f3dd32009-10-13 18:42:04 +00001256 if (O1 != O2) {
1257 // If V1/V2 point to two different objects we know that we have no alias.
Dan Gohman00ef9322010-07-07 14:27:09 +00001258 if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
Evan Chengf1f3dd32009-10-13 18:42:04 +00001259 return NoAlias;
Nick Lewyckyc53e2ec2009-11-14 06:15:14 +00001260
1261 // Constant pointers can't alias with non-const isIdentifiedObject objects.
Dan Gohman00ef9322010-07-07 14:27:09 +00001262 if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
1263 (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
Nick Lewyckyc53e2ec2009-11-14 06:15:14 +00001264 return NoAlias;
1265
Michael Kupersteinf3e663a2013-05-28 08:17:48 +00001266 // Function arguments can't alias with things that are known to be
1267 // unambigously identified at the function level.
1268 if ((isa<Argument>(O1) && isIdentifiedFunctionLocal(O2)) ||
1269 (isa<Argument>(O2) && isIdentifiedFunctionLocal(O1)))
Dan Gohman84f90a32010-07-01 20:08:40 +00001270 return NoAlias;
Evan Chengf1f3dd32009-10-13 18:42:04 +00001271
1272 // Most objects can't alias null.
Dan Gohman00ef9322010-07-07 14:27:09 +00001273 if ((isa<ConstantPointerNull>(O2) && isKnownNonNull(O1)) ||
1274 (isa<ConstantPointerNull>(O1) && isKnownNonNull(O2)))
Evan Chengf1f3dd32009-10-13 18:42:04 +00001275 return NoAlias;
Jakub Staszak07f383f2013-08-24 14:16:00 +00001276
Dan Gohman5b0a8a82010-07-07 14:30:04 +00001277 // If one pointer is the result of a call/invoke or load and the other is a
1278 // non-escaping local object within the same function, then we know the
1279 // object couldn't escape to a point where the call could return it.
1280 //
1281 // Note that if the pointers are in different functions, there are a
1282 // variety of complications. A call with a nocapture argument may still
1283 // temporary store the nocapture argument's value in a temporary memory
1284 // location if that memory location doesn't escape. Or it may pass a
1285 // nocapture value to other functions as long as they don't capture it.
1286 if (isEscapeSource(O1) && isNonEscapingLocalObject(O2))
1287 return NoAlias;
1288 if (isEscapeSource(O2) && isNonEscapingLocalObject(O1))
1289 return NoAlias;
1290 }
1291
Evan Chengf1f3dd32009-10-13 18:42:04 +00001292 // If the size of one access is larger than the entire object on the other
1293 // side, then we know such behavior is undefined and can assume no alias.
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001294 if (DL)
1295 if ((V1Size != UnknownSize && isObjectSmallerThan(O2, V1Size, *DL, *TLI)) ||
1296 (V2Size != UnknownSize && isObjectSmallerThan(O1, V2Size, *DL, *TLI)))
Evan Chengf1f3dd32009-10-13 18:42:04 +00001297 return NoAlias;
Jakub Staszak07f383f2013-08-24 14:16:00 +00001298
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001299 // Check the cache before climbing up use-def chains. This also terminates
1300 // otherwise infinitely recursive queries.
Hal Finkelcc39b672014-07-24 12:16:19 +00001301 LocPair Locs(Location(V1, V1Size, V1AAInfo),
1302 Location(V2, V2Size, V2AAInfo));
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001303 if (V1 > V2)
1304 std::swap(Locs.first, Locs.second);
1305 std::pair<AliasCacheTy::iterator, bool> Pair =
1306 AliasCache.insert(std::make_pair(Locs, MayAlias));
1307 if (!Pair.second)
1308 return Pair.first->second;
1309
Chris Lattner89288992009-11-26 02:13:03 +00001310 // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
1311 // GEP can't simplify, we don't even look at the PHI cases.
Chris Lattnerb2647b92009-10-17 23:48:54 +00001312 if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
Chris Lattnerd6a2a992003-02-26 19:41:54 +00001313 std::swap(V1, V2);
1314 std::swap(V1Size, V2Size);
Chris Lattner5341c962009-11-26 02:14:59 +00001315 std::swap(O1, O2);
Hal Finkelcc39b672014-07-24 12:16:19 +00001316 std::swap(V1AAInfo, V2AAInfo);
Chris Lattnerd6a2a992003-02-26 19:41:54 +00001317 }
Dan Gohman02538ac2010-10-18 18:04:47 +00001318 if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) {
Hal Finkelcc39b672014-07-24 12:16:19 +00001319 AliasResult Result = aliasGEP(GV1, V1Size, V1AAInfo, V2, V2Size, V2AAInfo, O1, O2);
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001320 if (Result != MayAlias) return AliasCache[Locs] = Result;
Dan Gohman02538ac2010-10-18 18:04:47 +00001321 }
Evan Chengc10e88d2009-10-13 22:02:20 +00001322
1323 if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
1324 std::swap(V1, V2);
1325 std::swap(V1Size, V2Size);
Hal Finkelcc39b672014-07-24 12:16:19 +00001326 std::swap(V1AAInfo, V2AAInfo);
Evan Chengc10e88d2009-10-13 22:02:20 +00001327 }
Dan Gohman02538ac2010-10-18 18:04:47 +00001328 if (const PHINode *PN = dyn_cast<PHINode>(V1)) {
Hal Finkelcc39b672014-07-24 12:16:19 +00001329 AliasResult Result = aliasPHI(PN, V1Size, V1AAInfo,
1330 V2, V2Size, V2AAInfo);
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001331 if (Result != MayAlias) return AliasCache[Locs] = Result;
Dan Gohman02538ac2010-10-18 18:04:47 +00001332 }
Misha Brukman01808ca2005-04-21 21:13:18 +00001333
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001334 if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
1335 std::swap(V1, V2);
1336 std::swap(V1Size, V2Size);
Hal Finkelcc39b672014-07-24 12:16:19 +00001337 std::swap(V1AAInfo, V2AAInfo);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001338 }
Dan Gohman02538ac2010-10-18 18:04:47 +00001339 if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) {
Hal Finkelcc39b672014-07-24 12:16:19 +00001340 AliasResult Result = aliasSelect(S1, V1Size, V1AAInfo,
1341 V2, V2Size, V2AAInfo);
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001342 if (Result != MayAlias) return AliasCache[Locs] = Result;
Dan Gohman02538ac2010-10-18 18:04:47 +00001343 }
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001344
Dan Gohman44da55b2011-01-18 21:16:06 +00001345 // If both pointers are pointing into the same object and one of them
1346 // accesses is accessing the entire object, then the accesses must
1347 // overlap in some way.
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001348 if (DL && O1 == O2)
1349 if ((V1Size != UnknownSize && isObjectSize(O1, V1Size, *DL, *TLI)) ||
1350 (V2Size != UnknownSize && isObjectSize(O2, V2Size, *DL, *TLI)))
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001351 return AliasCache[Locs] = PartialAlias;
Dan Gohman44da55b2011-01-18 21:16:06 +00001352
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001353 AliasResult Result =
Hal Finkelcc39b672014-07-24 12:16:19 +00001354 AliasAnalysis::alias(Location(V1, V1Size, V1AAInfo),
1355 Location(V2, V2Size, V2AAInfo));
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001356 return AliasCache[Locs] = Result;
Chris Lattnerd6a2a992003-02-26 19:41:54 +00001357}
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001358
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001359bool BasicAliasAnalysis::isValueEqualInPotentialCycles(const Value *V,
1360 const Value *V2) {
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001361 if (V != V2)
1362 return false;
1363
1364 const Instruction *Inst = dyn_cast<Instruction>(V);
1365 if (!Inst)
1366 return true;
1367
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001368 if (VisitedPhiBBs.size() > MaxNumPhiBBsValueReachabilityCheck)
1369 return false;
1370
1371 // Use dominance or loop info if available.
Chandler Carruth73523022014-01-13 13:07:17 +00001372 DominatorTreeWrapperPass *DTWP =
1373 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
Craig Topper9f008862014-04-15 04:59:12 +00001374 DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001375 LoopInfo *LI = getAnalysisIfAvailable<LoopInfo>();
1376
1377 // Make sure that the visited phis cannot reach the Value. This ensures that
1378 // the Values cannot come from different iterations of a potential cycle the
1379 // phi nodes could be involved in.
Craig Topper46276792014-08-24 23:23:06 +00001380 for (auto *P : VisitedPhiBBs)
1381 if (isPotentiallyReachable(P->begin(), Inst, DT, LI))
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001382 return false;
1383
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001384 return true;
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001385}
1386
1387/// GetIndexDifference - Dest and Src are the variable indices from two
1388/// decomposed GetElementPtr instructions GEP1 and GEP2 which have common base
1389/// pointers. Subtract the GEP2 indices from GEP1 to find the symbolic
1390/// difference between the two pointers.
1391void BasicAliasAnalysis::GetIndexDifference(
1392 SmallVectorImpl<VariableGEPIndex> &Dest,
1393 const SmallVectorImpl<VariableGEPIndex> &Src) {
1394 if (Src.empty())
1395 return;
1396
1397 for (unsigned i = 0, e = Src.size(); i != e; ++i) {
1398 const Value *V = Src[i].V;
1399 ExtensionKind Extension = Src[i].Extension;
1400 int64_t Scale = Src[i].Scale;
1401
1402 // Find V in Dest. This is N^2, but pointer indices almost never have more
1403 // than a few variable indexes.
1404 for (unsigned j = 0, e = Dest.size(); j != e; ++j) {
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001405 if (!isValueEqualInPotentialCycles(Dest[j].V, V) ||
1406 Dest[j].Extension != Extension)
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001407 continue;
1408
1409 // If we found it, subtract off Scale V's from the entry in Dest. If it
1410 // goes to zero, remove the entry.
1411 if (Dest[j].Scale != Scale)
1412 Dest[j].Scale -= Scale;
1413 else
1414 Dest.erase(Dest.begin() + j);
1415 Scale = 0;
1416 break;
1417 }
1418
1419 // If we didn't consume this entry, add it to the end of the Dest list.
1420 if (Scale) {
1421 VariableGEPIndex Entry = { V, Extension, -Scale };
1422 Dest.push_back(Entry);
1423 }
1424 }
1425}