blob: 9a7d312c65c6256710a95f53a34d772730ada8a6 [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
Hal Finkel45ba2c12014-11-13 09:16:54 +0000210 if (ConstantInt *Const = dyn_cast<ConstantInt>(V)) {
211 // if it's a constant, just convert it to an offset
212 // and remove the variable.
213 Offset += Const->getValue();
214 assert(Scale == 0 && "Constant values don't have a scale");
215 return V;
216 }
217
Chris Lattner9f7500f2010-08-18 22:07:29 +0000218 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(V)) {
219 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
220 switch (BOp->getOpcode()) {
221 default: break;
222 case Instruction::Or:
223 // X|C == X+C if all the bits in C are unset in X. Otherwise we can't
224 // analyze it.
Hal Finkel60db0582014-09-07 18:57:58 +0000225 if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), &DL, 0,
226 AT, BOp, DT))
Chris Lattner9f7500f2010-08-18 22:07:29 +0000227 break;
228 // FALL THROUGH.
229 case Instruction::Add:
Chris Lattner3decde92010-08-18 23:09:49 +0000230 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
Hal Finkel60db0582014-09-07 18:57:58 +0000231 DL, Depth+1, AT, DT);
Chris Lattner9f7500f2010-08-18 22:07:29 +0000232 Offset += RHSC->getValue();
233 return V;
234 case Instruction::Mul:
Chris Lattner3decde92010-08-18 23:09:49 +0000235 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
Hal Finkel60db0582014-09-07 18:57:58 +0000236 DL, Depth+1, AT, DT);
Chris Lattner9f7500f2010-08-18 22:07:29 +0000237 Offset *= RHSC->getValue();
238 Scale *= RHSC->getValue();
239 return V;
240 case Instruction::Shl:
Chris Lattner3decde92010-08-18 23:09:49 +0000241 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
Hal Finkel60db0582014-09-07 18:57:58 +0000242 DL, Depth+1, AT, DT);
Chris Lattner9f7500f2010-08-18 22:07:29 +0000243 Offset <<= RHSC->getValue().getLimitedValue();
244 Scale <<= RHSC->getValue().getLimitedValue();
245 return V;
246 }
247 }
248 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000249
Chris Lattner9f7500f2010-08-18 22:07:29 +0000250 // Since GEP indices are sign extended anyway, we don't care about the high
Chris Lattner3decde92010-08-18 23:09:49 +0000251 // bits of a sign or zero extended value - just scales and offsets. The
252 // extensions have to be consistent though.
253 if ((isa<SExtInst>(V) && Extension != EK_ZeroExt) ||
254 (isa<ZExtInst>(V) && Extension != EK_SignExt)) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000255 Value *CastOp = cast<CastInst>(V)->getOperand(0);
256 unsigned OldWidth = Scale.getBitWidth();
257 unsigned SmallWidth = CastOp->getType()->getPrimitiveSizeInBits();
Jay Foad583abbc2010-12-07 08:25:19 +0000258 Scale = Scale.trunc(SmallWidth);
259 Offset = Offset.trunc(SmallWidth);
Chris Lattner3decde92010-08-18 23:09:49 +0000260 Extension = isa<SExtInst>(V) ? EK_SignExt : EK_ZeroExt;
261
262 Value *Result = GetLinearExpression(CastOp, Scale, Offset, Extension,
Hal Finkel60db0582014-09-07 18:57:58 +0000263 DL, Depth+1, AT, DT);
Jay Foad583abbc2010-12-07 08:25:19 +0000264 Scale = Scale.zext(OldWidth);
Hal Finkel45ba2c12014-11-13 09:16:54 +0000265
266 // We have to sign-extend even if Extension == EK_ZeroExt as we can't
267 // decompose a sign extension (i.e. zext(x - 1) != zext(x) - zext(-1)).
268 Offset = Offset.sext(OldWidth);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000269
Chris Lattner9f7500f2010-08-18 22:07:29 +0000270 return Result;
271 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000272
Chris Lattner9f7500f2010-08-18 22:07:29 +0000273 Scale = 1;
274 Offset = 0;
275 return V;
276}
277
278/// DecomposeGEPExpression - If V is a symbolic pointer expression, decompose it
279/// into a base pointer with a constant offset and a number of scaled symbolic
280/// offsets.
281///
282/// The scaled symbolic offsets (represented by pairs of a Value* and a scale in
283/// the VarIndices vector) are Value*'s that are known to be scaled by the
284/// specified amount, but which may have other unrepresented high bits. As such,
285/// the gep cannot necessarily be reconstructed from its decomposed form.
286///
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000287/// When DataLayout is around, this function is capable of analyzing everything
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000288/// that GetUnderlyingObject can look through. To be able to do that
289/// GetUnderlyingObject and DecomposeGEPExpression must use the same search
290/// depth (MaxLookupSearchDepth).
291/// When DataLayout not is around, it just looks through pointer casts.
Chris Lattner9f7500f2010-08-18 22:07:29 +0000292///
293static const Value *
294DecomposeGEPExpression(const Value *V, int64_t &BaseOffs,
Chris Lattner1b9c3872010-08-18 22:47:56 +0000295 SmallVectorImpl<VariableGEPIndex> &VarIndices,
Hal Finkel60db0582014-09-07 18:57:58 +0000296 bool &MaxLookupReached, const DataLayout *DL,
297 AssumptionTracker *AT, DominatorTree *DT) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000298 // Limit recursion depth to limit compile time in crazy cases.
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000299 unsigned MaxLookup = MaxLookupSearchDepth;
300 MaxLookupReached = false;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000301
Chris Lattner9f7500f2010-08-18 22:07:29 +0000302 BaseOffs = 0;
303 do {
304 // See if this is a bitcast or GEP.
305 const Operator *Op = dyn_cast<Operator>(V);
Craig Topper9f008862014-04-15 04:59:12 +0000306 if (!Op) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000307 // The only non-operator case we can handle are GlobalAliases.
308 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
309 if (!GA->mayBeOverridden()) {
310 V = GA->getAliasee();
311 continue;
312 }
313 }
314 return V;
315 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000316
Matt Arsenault70f4db882014-07-15 00:56:40 +0000317 if (Op->getOpcode() == Instruction::BitCast ||
318 Op->getOpcode() == Instruction::AddrSpaceCast) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000319 V = Op->getOperand(0);
320 continue;
321 }
Dan Gohman05b18f12010-12-15 20:49:55 +0000322
Chris Lattner9f7500f2010-08-18 22:07:29 +0000323 const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
Craig Topper9f008862014-04-15 04:59:12 +0000324 if (!GEPOp) {
Dan Gohman0573b552011-05-24 18:24:08 +0000325 // If it's not a GEP, hand it off to SimplifyInstruction to see if it
326 // can come up with something. This matches what GetUnderlyingObject does.
327 if (const Instruction *I = dyn_cast<Instruction>(V))
Hal Finkel60db0582014-09-07 18:57:58 +0000328 // TODO: Get a DominatorTree and AssumptionTracker and use them here
329 // (these are both now available in this function, but this should be
330 // updated when GetUnderlyingObject is updated). TLI should be
331 // provided also.
Dan Gohman0573b552011-05-24 18:24:08 +0000332 if (const Value *Simplified =
Rafael Espindola5f57f462014-02-21 18:34:28 +0000333 SimplifyInstruction(const_cast<Instruction *>(I), DL)) {
Dan Gohman0573b552011-05-24 18:24:08 +0000334 V = Simplified;
335 continue;
336 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000337
Chris Lattner9f7500f2010-08-18 22:07:29 +0000338 return V;
Dan Gohman0573b552011-05-24 18:24:08 +0000339 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000340
Chris Lattner9f7500f2010-08-18 22:07:29 +0000341 // Don't attempt to analyze GEPs over unsized objects.
Matt Arsenaultfa252722013-09-27 22:18:51 +0000342 if (!GEPOp->getOperand(0)->getType()->getPointerElementType()->isSized())
Chris Lattner9f7500f2010-08-18 22:07:29 +0000343 return V;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000344
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000345 // If we are lacking DataLayout information, we can't compute the offets of
Chris Lattner9f7500f2010-08-18 22:07:29 +0000346 // elements computed by GEPs. However, we can handle bitcast equivalent
347 // GEPs.
Craig Topper9f008862014-04-15 04:59:12 +0000348 if (!DL) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000349 if (!GEPOp->hasAllZeroIndices())
350 return V;
351 V = GEPOp->getOperand(0);
352 continue;
353 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000354
Matt Arsenaulta8fe22b2013-11-16 00:36:43 +0000355 unsigned AS = GEPOp->getPointerAddressSpace();
Chris Lattner9f7500f2010-08-18 22:07:29 +0000356 // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
357 gep_type_iterator GTI = gep_type_begin(GEPOp);
358 for (User::const_op_iterator I = GEPOp->op_begin()+1,
359 E = GEPOp->op_end(); I != E; ++I) {
360 Value *Index = *I;
361 // Compute the (potentially symbolic) offset in bytes for this index.
Chris Lattner229907c2011-07-18 04:54:35 +0000362 if (StructType *STy = dyn_cast<StructType>(*GTI++)) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000363 // For a struct, add the member offset.
364 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
365 if (FieldNo == 0) continue;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000366
Rafael Espindola5f57f462014-02-21 18:34:28 +0000367 BaseOffs += DL->getStructLayout(STy)->getElementOffset(FieldNo);
Chris Lattner9f7500f2010-08-18 22:07:29 +0000368 continue;
369 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000370
Chris Lattner9f7500f2010-08-18 22:07:29 +0000371 // For an array/pointer, add the element offset, explicitly scaled.
372 if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
373 if (CIdx->isZero()) continue;
Rafael Espindola5f57f462014-02-21 18:34:28 +0000374 BaseOffs += DL->getTypeAllocSize(*GTI)*CIdx->getSExtValue();
Chris Lattner9f7500f2010-08-18 22:07:29 +0000375 continue;
376 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000377
Rafael Espindola5f57f462014-02-21 18:34:28 +0000378 uint64_t Scale = DL->getTypeAllocSize(*GTI);
Chris Lattner1b9c3872010-08-18 22:47:56 +0000379 ExtensionKind Extension = EK_NotExtended;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000380
Chris Lattner3decde92010-08-18 23:09:49 +0000381 // If the integer type is smaller than the pointer size, it is implicitly
382 // sign extended to pointer size.
Matt Arsenaultfa252722013-09-27 22:18:51 +0000383 unsigned Width = Index->getType()->getIntegerBitWidth();
Rafael Espindola5f57f462014-02-21 18:34:28 +0000384 if (DL->getPointerSizeInBits(AS) > Width)
Chris Lattner3decde92010-08-18 23:09:49 +0000385 Extension = EK_SignExt;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000386
Chris Lattner3decde92010-08-18 23:09:49 +0000387 // Use GetLinearExpression to decompose the index into a C1*V+C2 form.
Chris Lattner9f7500f2010-08-18 22:07:29 +0000388 APInt IndexScale(Width, 0), IndexOffset(Width, 0);
Chris Lattner3decde92010-08-18 23:09:49 +0000389 Index = GetLinearExpression(Index, IndexScale, IndexOffset, Extension,
Hal Finkel60db0582014-09-07 18:57:58 +0000390 *DL, 0, AT, DT);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000391
Chris Lattner9f7500f2010-08-18 22:07:29 +0000392 // The GEP index scale ("Scale") scales C1*V+C2, yielding (C1*V+C2)*Scale.
393 // This gives us an aggregate computation of (C1*Scale)*V + C2*Scale.
Eli Friedmanab3a1282010-09-15 20:08:03 +0000394 BaseOffs += IndexOffset.getSExtValue()*Scale;
395 Scale *= IndexScale.getSExtValue();
Jakub Staszak07f383f2013-08-24 14:16:00 +0000396
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000397 // If we already had an occurrence of this index variable, merge this
Chris Lattner9f7500f2010-08-18 22:07:29 +0000398 // scale into it. For example, we want to handle:
399 // A[x][x] -> x*16 + x*4 -> x*20
400 // This also ensures that 'x' only appears in the index list once.
401 for (unsigned i = 0, e = VarIndices.size(); i != e; ++i) {
Chris Lattner1b9c3872010-08-18 22:47:56 +0000402 if (VarIndices[i].V == Index &&
403 VarIndices[i].Extension == Extension) {
404 Scale += VarIndices[i].Scale;
Chris Lattner9f7500f2010-08-18 22:07:29 +0000405 VarIndices.erase(VarIndices.begin()+i);
406 break;
407 }
408 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000409
Chris Lattner9f7500f2010-08-18 22:07:29 +0000410 // Make sure that we have a scale that makes sense for this target's
411 // pointer size.
Rafael Espindola5f57f462014-02-21 18:34:28 +0000412 if (unsigned ShiftBits = 64 - DL->getPointerSizeInBits(AS)) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000413 Scale <<= ShiftBits;
Eli Friedmanab3a1282010-09-15 20:08:03 +0000414 Scale = (int64_t)Scale >> ShiftBits;
Chris Lattner9f7500f2010-08-18 22:07:29 +0000415 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000416
Chris Lattner1b9c3872010-08-18 22:47:56 +0000417 if (Scale) {
Jeffrey Yasskin6381c012011-07-27 06:22:51 +0000418 VariableGEPIndex Entry = {Index, Extension,
419 static_cast<int64_t>(Scale)};
Chris Lattner1b9c3872010-08-18 22:47:56 +0000420 VarIndices.push_back(Entry);
421 }
Chris Lattner9f7500f2010-08-18 22:07:29 +0000422 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000423
Chris Lattner9f7500f2010-08-18 22:07:29 +0000424 // Analyze the base pointer next.
425 V = GEPOp->getOperand(0);
426 } while (--MaxLookup);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000427
Chris Lattner9f7500f2010-08-18 22:07:29 +0000428 // If the chain of expressions is too deep, just return early.
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000429 MaxLookupReached = true;
Chris Lattner9f7500f2010-08-18 22:07:29 +0000430 return V;
431}
432
Chris Lattner9f7500f2010-08-18 22:07:29 +0000433//===----------------------------------------------------------------------===//
Dan Gohman0824aff2010-06-29 00:50:39 +0000434// BasicAliasAnalysis Pass
Chris Lattner2d332972008-06-16 06:30:22 +0000435//===----------------------------------------------------------------------===//
436
Dan Gohman00ef9322010-07-07 14:27:09 +0000437#ifndef NDEBUG
Dan Gohman0824aff2010-06-29 00:50:39 +0000438static const Function *getParent(const Value *V) {
Dan Gohman1be9e7c2010-06-29 18:12:34 +0000439 if (const Instruction *inst = dyn_cast<Instruction>(V))
Dan Gohman0824aff2010-06-29 00:50:39 +0000440 return inst->getParent()->getParent();
441
Dan Gohman1be9e7c2010-06-29 18:12:34 +0000442 if (const Argument *arg = dyn_cast<Argument>(V))
Dan Gohman0824aff2010-06-29 00:50:39 +0000443 return arg->getParent();
444
Craig Topper9f008862014-04-15 04:59:12 +0000445 return nullptr;
Dan Gohman0824aff2010-06-29 00:50:39 +0000446}
447
Dan Gohman84f90a32010-07-01 20:08:40 +0000448static bool notDifferentParent(const Value *O1, const Value *O2) {
449
450 const Function *F1 = getParent(O1);
451 const Function *F2 = getParent(O2);
452
Dan Gohman0824aff2010-06-29 00:50:39 +0000453 return !F1 || !F2 || F1 == F2;
454}
Benjamin Kramer80b7bc02010-06-29 10:03:11 +0000455#endif
Dan Gohman0824aff2010-06-29 00:50:39 +0000456
Chris Lattner2d332972008-06-16 06:30:22 +0000457namespace {
Dan Gohmanda85ed82010-10-19 23:09:08 +0000458 /// BasicAliasAnalysis - This is the primary alias analysis implementation.
459 struct BasicAliasAnalysis : public ImmutablePass, public AliasAnalysis {
Chris Lattner2d332972008-06-16 06:30:22 +0000460 static char ID; // Class identification, replacement for typeinfo
Benjamin Kramer6c2649c2012-09-05 16:49:37 +0000461 BasicAliasAnalysis() : ImmutablePass(ID) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000462 initializeBasicAliasAnalysisPass(*PassRegistry::getPassRegistry());
463 }
Dan Gohman0824aff2010-06-29 00:50:39 +0000464
Craig Toppere9ba7592014-03-05 07:30:04 +0000465 void initializePass() override {
Dan Gohman02538ac2010-10-18 18:04:47 +0000466 InitializeAliasAnalysis(this);
467 }
468
Craig Toppere9ba7592014-03-05 07:30:04 +0000469 void getAnalysisUsage(AnalysisUsage &AU) const override {
Dan Gohman02538ac2010-10-18 18:04:47 +0000470 AU.addRequired<AliasAnalysis>();
Hal Finkel60db0582014-09-07 18:57:58 +0000471 AU.addRequired<AssumptionTracker>();
Owen Anderson653cb032011-09-06 23:33:25 +0000472 AU.addRequired<TargetLibraryInfo>();
Dan Gohman02538ac2010-10-18 18:04:47 +0000473 }
474
Craig Toppere9ba7592014-03-05 07:30:04 +0000475 AliasResult alias(const Location &LocA, const Location &LocB) override {
Dan Gohmanfb02cec2011-06-04 00:31:50 +0000476 assert(AliasCache.empty() && "AliasCache must be cleared after use!");
Dan Gohman41f14cf2010-09-14 21:25:10 +0000477 assert(notDifferentParent(LocA.Ptr, LocB.Ptr) &&
Dan Gohman00ef9322010-07-07 14:27:09 +0000478 "BasicAliasAnalysis doesn't support interprocedural queries.");
Hal Finkelcc39b672014-07-24 12:16:19 +0000479 AliasResult Alias = aliasCheck(LocA.Ptr, LocA.Size, LocA.AATags,
480 LocB.Ptr, LocB.Size, LocB.AATags);
Benjamin Kramer6c2649c2012-09-05 16:49:37 +0000481 // AliasCache rarely has more than 1 or 2 elements, always use
482 // shrink_and_clear so it quickly returns to the inline capacity of the
483 // SmallDenseMap if it ever grows larger.
484 // FIXME: This should really be shrink_to_inline_capacity_and_clear().
485 AliasCache.shrink_and_clear();
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +0000486 VisitedPhiBBs.clear();
Evan Chengb3ccb642009-10-14 06:46:26 +0000487 return Alias;
Evan Chengc10e88d2009-10-13 22:02:20 +0000488 }
Chris Lattner2d332972008-06-16 06:30:22 +0000489
Craig Toppere9ba7592014-03-05 07:30:04 +0000490 ModRefResult getModRefInfo(ImmutableCallSite CS,
491 const Location &Loc) override;
Dan Gohman5f1702e2010-08-06 01:25:49 +0000492
Craig Toppere9ba7592014-03-05 07:30:04 +0000493 ModRefResult getModRefInfo(ImmutableCallSite CS1,
Hal Finkel93046912014-07-25 21:13:35 +0000494 ImmutableCallSite CS2) override;
Owen Anderson98a36172009-02-05 23:36:27 +0000495
Chris Lattner2d332972008-06-16 06:30:22 +0000496 /// pointsToConstantMemory - Chase pointers until we find a (constant
497 /// global) or not.
Craig Toppere9ba7592014-03-05 07:30:04 +0000498 bool pointsToConstantMemory(const Location &Loc, bool OrLocal) override;
Dan Gohman5f1702e2010-08-06 01:25:49 +0000499
Hal Finkel354e23b2014-07-17 01:28:25 +0000500 /// Get the location associated with a pointer argument of a callsite.
501 Location getArgLocation(ImmutableCallSite CS, unsigned ArgIdx,
502 ModRefResult &Mask) override;
503
Dan Gohman5f1702e2010-08-06 01:25:49 +0000504 /// getModRefBehavior - Return the behavior when calling the given
505 /// call site.
Craig Toppere9ba7592014-03-05 07:30:04 +0000506 ModRefBehavior getModRefBehavior(ImmutableCallSite CS) override;
Dan Gohman5f1702e2010-08-06 01:25:49 +0000507
508 /// getModRefBehavior - Return the behavior when calling the given function.
509 /// For use when the call site is not known.
Craig Toppere9ba7592014-03-05 07:30:04 +0000510 ModRefBehavior getModRefBehavior(const Function *F) override;
Chris Lattner2d332972008-06-16 06:30:22 +0000511
Chris Lattneraf362f02010-01-20 19:26:14 +0000512 /// getAdjustedAnalysisPointer - This method is used when a pass implements
Dan Gohmane0d5c452010-08-05 23:48:14 +0000513 /// an analysis interface through multiple inheritance. If needed, it
514 /// should override this to adjust the this pointer as needed for the
515 /// specified pass info.
Craig Toppere9ba7592014-03-05 07:30:04 +0000516 void *getAdjustedAnalysisPointer(const void *ID) override {
Owen Andersona7aed182010-08-06 18:33:48 +0000517 if (ID == &AliasAnalysis::ID)
Chris Lattneraf362f02010-01-20 19:26:14 +0000518 return (AliasAnalysis*)this;
519 return this;
520 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000521
Chris Lattner2d332972008-06-16 06:30:22 +0000522 private:
Dan Gohmanfb02cec2011-06-04 00:31:50 +0000523 // AliasCache - Track alias queries to guard against recursion.
524 typedef std::pair<Location, Location> LocPair;
Benjamin Kramer6c2649c2012-09-05 16:49:37 +0000525 typedef SmallDenseMap<LocPair, AliasResult, 8> AliasCacheTy;
Dan Gohmanfb02cec2011-06-04 00:31:50 +0000526 AliasCacheTy AliasCache;
527
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +0000528 /// \brief Track phi nodes we have visited. When interpret "Value" pointer
529 /// equality as value equality we need to make sure that the "Value" is not
530 /// part of a cycle. Otherwise, two uses could come from different
531 /// "iterations" of a cycle and see different values for the same "Value"
532 /// pointer.
533 /// The following example shows the problem:
534 /// %p = phi(%alloca1, %addr2)
535 /// %l = load %ptr
536 /// %addr1 = gep, %alloca2, 0, %l
537 /// %addr2 = gep %alloca2, 0, (%l + 1)
538 /// alias(%p, %addr1) -> MayAlias !
539 /// store %l, ...
540 SmallPtrSet<const BasicBlock*, 8> VisitedPhiBBs;
541
Dan Gohmanfb02cec2011-06-04 00:31:50 +0000542 // Visited - Track instructions visited by pointsToConstantMemory.
Dan Gohman7c34ece2010-06-28 21:16:52 +0000543 SmallPtrSet<const Value*, 16> Visited;
Evan Cheng31565b32009-10-14 05:05:02 +0000544
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +0000545 /// \brief Check whether two Values can be considered equivalent.
546 ///
547 /// In addition to pointer equivalence of \p V1 and \p V2 this checks
548 /// whether they can not be part of a cycle in the value graph by looking at
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +0000549 /// all visited phi nodes an making sure that the phis cannot reach the
550 /// value. We have to do this because we are looking through phi nodes (That
551 /// is we say noalias(V, phi(VA, VB)) if noalias(V, VA) and noalias(V, VB).
552 bool isValueEqualInPotentialCycles(const Value *V1, const Value *V2);
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +0000553
554 /// \brief Dest and Src are the variable indices from two decomposed
555 /// GetElementPtr instructions GEP1 and GEP2 which have common base
556 /// pointers. Subtract the GEP2 indices from GEP1 to find the symbolic
557 /// difference between the two pointers.
558 void GetIndexDifference(SmallVectorImpl<VariableGEPIndex> &Dest,
559 const SmallVectorImpl<VariableGEPIndex> &Src);
560
Chris Lattner98e253262009-11-23 16:45:27 +0000561 // aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP
562 // instruction against another.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000563 AliasResult aliasGEP(const GEPOperator *V1, uint64_t V1Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000564 const AAMDNodes &V1AAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +0000565 const Value *V2, uint64_t V2Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000566 const AAMDNodes &V2AAInfo,
Chris Lattner5341c962009-11-26 02:14:59 +0000567 const Value *UnderlyingV1, const Value *UnderlyingV2);
Evan Chengc10e88d2009-10-13 22:02:20 +0000568
Chris Lattner98e253262009-11-23 16:45:27 +0000569 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI
570 // instruction against another.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000571 AliasResult aliasPHI(const PHINode *PN, uint64_t PNSize,
Hal Finkelcc39b672014-07-24 12:16:19 +0000572 const AAMDNodes &PNAAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +0000573 const Value *V2, uint64_t V2Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000574 const AAMDNodes &V2AAInfo);
Evan Chengc10e88d2009-10-13 22:02:20 +0000575
Dan Gohman3b7ba5f2009-10-26 21:55:43 +0000576 /// aliasSelect - Disambiguate a Select instruction against another value.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000577 AliasResult aliasSelect(const SelectInst *SI, uint64_t SISize,
Hal Finkelcc39b672014-07-24 12:16:19 +0000578 const AAMDNodes &SIAAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +0000579 const Value *V2, uint64_t V2Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000580 const AAMDNodes &V2AAInfo);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +0000581
Dan Gohmanf372cf82010-10-19 22:54:46 +0000582 AliasResult aliasCheck(const Value *V1, uint64_t V1Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000583 AAMDNodes V1AATag,
Dan Gohmanf372cf82010-10-19 22:54:46 +0000584 const Value *V2, uint64_t V2Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000585 AAMDNodes V2AATag);
Chris Lattner2d332972008-06-16 06:30:22 +0000586 };
587} // End of anonymous namespace
588
589// Register this pass...
590char BasicAliasAnalysis::ID = 0;
Owen Anderson653cb032011-09-06 23:33:25 +0000591INITIALIZE_AG_PASS_BEGIN(BasicAliasAnalysis, AliasAnalysis, "basicaa",
Dan Gohmanda85ed82010-10-19 23:09:08 +0000592 "Basic Alias Analysis (stateless AA impl)",
Dan Gohman02538ac2010-10-18 18:04:47 +0000593 false, true, false)
Hal Finkel60db0582014-09-07 18:57:58 +0000594INITIALIZE_PASS_DEPENDENCY(AssumptionTracker)
Owen Anderson653cb032011-09-06 23:33:25 +0000595INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
596INITIALIZE_AG_PASS_END(BasicAliasAnalysis, AliasAnalysis, "basicaa",
597 "Basic Alias Analysis (stateless AA impl)",
598 false, true, false)
599
Chris Lattner2d332972008-06-16 06:30:22 +0000600
601ImmutablePass *llvm::createBasicAliasAnalysisPass() {
602 return new BasicAliasAnalysis();
603}
604
Dan Gohman9130bad2010-11-08 16:45:26 +0000605/// pointsToConstantMemory - Returns whether the given pointer value
606/// points to memory that is local to the function, with global constants being
607/// considered local to all functions.
608bool
609BasicAliasAnalysis::pointsToConstantMemory(const Location &Loc, bool OrLocal) {
610 assert(Visited.empty() && "Visited must be cleared after use!");
Chris Lattner2d332972008-06-16 06:30:22 +0000611
Dan Gohman142ff822010-11-08 20:26:19 +0000612 unsigned MaxLookup = 8;
Dan Gohman9130bad2010-11-08 16:45:26 +0000613 SmallVector<const Value *, 16> Worklist;
614 Worklist.push_back(Loc.Ptr);
615 do {
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000616 const Value *V = GetUnderlyingObject(Worklist.pop_back_val(), DL);
Dan Gohman9130bad2010-11-08 16:45:26 +0000617 if (!Visited.insert(V)) {
618 Visited.clear();
619 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
620 }
Dan Gohman5f1702e2010-08-06 01:25:49 +0000621
Dan Gohman9130bad2010-11-08 16:45:26 +0000622 // An alloca instruction defines local memory.
623 if (OrLocal && isa<AllocaInst>(V))
624 continue;
625
626 // A global constant counts as local memory for our purposes.
627 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
628 // Note: this doesn't require GV to be "ODR" because it isn't legal for a
629 // global to be marked constant in some modules and non-constant in
630 // others. GV may even be a declaration, not a definition.
631 if (!GV->isConstant()) {
632 Visited.clear();
633 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
634 }
635 continue;
636 }
637
638 // If both select values point to local memory, then so does the select.
639 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
640 Worklist.push_back(SI->getTrueValue());
641 Worklist.push_back(SI->getFalseValue());
642 continue;
643 }
644
645 // If all values incoming to a phi node point to local memory, then so does
646 // the phi.
647 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
Dan Gohman142ff822010-11-08 20:26:19 +0000648 // Don't bother inspecting phi nodes with many operands.
649 if (PN->getNumIncomingValues() > MaxLookup) {
650 Visited.clear();
651 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
652 }
Dan Gohman9130bad2010-11-08 16:45:26 +0000653 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
654 Worklist.push_back(PN->getIncomingValue(i));
655 continue;
656 }
657
658 // Otherwise be conservative.
659 Visited.clear();
660 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
661
Dan Gohman142ff822010-11-08 20:26:19 +0000662 } while (!Worklist.empty() && --MaxLookup);
Dan Gohman9130bad2010-11-08 16:45:26 +0000663
664 Visited.clear();
Dan Gohman142ff822010-11-08 20:26:19 +0000665 return Worklist.empty();
Chris Lattner2d332972008-06-16 06:30:22 +0000666}
667
Hal Finkel354e23b2014-07-17 01:28:25 +0000668static bool isMemsetPattern16(const Function *MS,
669 const TargetLibraryInfo &TLI) {
670 if (TLI.has(LibFunc::memset_pattern16) &&
671 MS->getName() == "memset_pattern16") {
672 FunctionType *MemsetType = MS->getFunctionType();
673 if (!MemsetType->isVarArg() && MemsetType->getNumParams() == 3 &&
674 isa<PointerType>(MemsetType->getParamType(0)) &&
675 isa<PointerType>(MemsetType->getParamType(1)) &&
676 isa<IntegerType>(MemsetType->getParamType(2)))
677 return true;
678 }
679
680 return false;
681}
682
Dan Gohman5f1702e2010-08-06 01:25:49 +0000683/// getModRefBehavior - Return the behavior when calling the given call site.
684AliasAnalysis::ModRefBehavior
685BasicAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
686 if (CS.doesNotAccessMemory())
687 // Can't do better than this.
688 return DoesNotAccessMemory;
689
690 ModRefBehavior Min = UnknownModRefBehavior;
691
692 // If the callsite knows it only reads memory, don't return worse
693 // than that.
694 if (CS.onlyReadsMemory())
695 Min = OnlyReadsMemory;
696
697 // The AliasAnalysis base class has some smarts, lets use them.
Dan Gohman2694e142010-11-10 01:02:18 +0000698 return ModRefBehavior(AliasAnalysis::getModRefBehavior(CS) & Min);
Dan Gohman5f1702e2010-08-06 01:25:49 +0000699}
700
701/// getModRefBehavior - Return the behavior when calling the given function.
702/// For use when the call site is not known.
703AliasAnalysis::ModRefBehavior
704BasicAliasAnalysis::getModRefBehavior(const Function *F) {
Dan Gohmane461d7d2010-11-08 16:08:43 +0000705 // If the function declares it doesn't access memory, we can't do better.
Dan Gohman5f1702e2010-08-06 01:25:49 +0000706 if (F->doesNotAccessMemory())
Dan Gohman5f1702e2010-08-06 01:25:49 +0000707 return DoesNotAccessMemory;
Dan Gohmane461d7d2010-11-08 16:08:43 +0000708
709 // For intrinsics, we can check the table.
710 if (unsigned iid = F->getIntrinsicID()) {
711#define GET_INTRINSIC_MODREF_BEHAVIOR
Chandler Carruthdb25c6c2013-01-02 12:09:16 +0000712#include "llvm/IR/Intrinsics.gen"
Dan Gohmane461d7d2010-11-08 16:08:43 +0000713#undef GET_INTRINSIC_MODREF_BEHAVIOR
714 }
715
Dan Gohman2694e142010-11-10 01:02:18 +0000716 ModRefBehavior Min = UnknownModRefBehavior;
717
Dan Gohmane461d7d2010-11-08 16:08:43 +0000718 // If the function declares it only reads memory, go with that.
Dan Gohman5f1702e2010-08-06 01:25:49 +0000719 if (F->onlyReadsMemory())
Dan Gohman2694e142010-11-10 01:02:18 +0000720 Min = OnlyReadsMemory;
Dan Gohman5f1702e2010-08-06 01:25:49 +0000721
Hal Finkel354e23b2014-07-17 01:28:25 +0000722 const TargetLibraryInfo &TLI = getAnalysis<TargetLibraryInfo>();
723 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);
734 const TargetLibraryInfo &TLI = getAnalysis<TargetLibraryInfo>();
735 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
736 if (II != nullptr)
737 switch (II->getIntrinsicID()) {
738 default: break;
739 case Intrinsic::memset:
740 case Intrinsic::memcpy:
741 case Intrinsic::memmove: {
742 assert((ArgIdx == 0 || ArgIdx == 1) &&
743 "Invalid argument index for memory intrinsic");
744 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getArgOperand(2)))
745 Loc.Size = LenCI->getZExtValue();
746 assert(Loc.Ptr == II->getArgOperand(ArgIdx) &&
747 "Memory intrinsic location pointer not argument?");
748 Mask = ArgIdx ? Ref : Mod;
749 break;
750 }
751 case Intrinsic::lifetime_start:
752 case Intrinsic::lifetime_end:
753 case Intrinsic::invariant_start: {
754 assert(ArgIdx == 1 && "Invalid argument index");
755 assert(Loc.Ptr == II->getArgOperand(ArgIdx) &&
756 "Intrinsic location pointer not argument?");
757 Loc.Size = cast<ConstantInt>(II->getArgOperand(0))->getZExtValue();
758 break;
759 }
760 case Intrinsic::invariant_end: {
761 assert(ArgIdx == 2 && "Invalid argument index");
762 assert(Loc.Ptr == II->getArgOperand(ArgIdx) &&
763 "Intrinsic location pointer not argument?");
764 Loc.Size = cast<ConstantInt>(II->getArgOperand(1))->getZExtValue();
765 break;
766 }
767 case Intrinsic::arm_neon_vld1: {
768 assert(ArgIdx == 0 && "Invalid argument index");
769 assert(Loc.Ptr == II->getArgOperand(ArgIdx) &&
770 "Intrinsic location pointer not argument?");
771 // LLVM's vld1 and vst1 intrinsics currently only support a single
772 // vector register.
773 if (DL)
774 Loc.Size = DL->getTypeStoreSize(II->getType());
775 break;
776 }
777 case Intrinsic::arm_neon_vst1: {
778 assert(ArgIdx == 0 && "Invalid argument index");
779 assert(Loc.Ptr == II->getArgOperand(ArgIdx) &&
780 "Intrinsic location pointer not argument?");
781 if (DL)
782 Loc.Size = DL->getTypeStoreSize(II->getArgOperand(1)->getType());
783 break;
784 }
785 }
786
787 // We can bound the aliasing properties of memset_pattern16 just as we can
788 // for memcpy/memset. This is particularly important because the
789 // LoopIdiomRecognizer likes to turn loops into calls to memset_pattern16
790 // whenever possible.
791 else if (CS.getCalledFunction() &&
792 isMemsetPattern16(CS.getCalledFunction(), TLI)) {
793 assert((ArgIdx == 0 || ArgIdx == 1) &&
794 "Invalid argument index for memset_pattern16");
795 if (ArgIdx == 1)
796 Loc.Size = 16;
797 else if (const ConstantInt *LenCI =
798 dyn_cast<ConstantInt>(CS.getArgument(2)))
799 Loc.Size = LenCI->getZExtValue();
800 assert(Loc.Ptr == CS.getArgument(ArgIdx) &&
801 "memset_pattern16 location pointer not argument?");
802 Mask = ArgIdx ? Ref : Mod;
803 }
804 // FIXME: Handle memset_pattern4 and memset_pattern8 also.
805
806 return Loc;
807}
808
Hal Finkel93046912014-07-25 21:13:35 +0000809static bool isAssumeIntrinsic(ImmutableCallSite CS) {
810 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
811 if (II && II->getIntrinsicID() == Intrinsic::assume)
812 return true;
813
814 return false;
815}
816
Chris Lattner98e253262009-11-23 16:45:27 +0000817/// getModRefInfo - Check to see if the specified callsite can clobber the
818/// specified memory object. Since we only look at local properties of this
819/// function, we really can't say much about this query. We do, however, use
820/// simple "address taken" analysis on local objects.
Chris Lattner2d332972008-06-16 06:30:22 +0000821AliasAnalysis::ModRefResult
Dan Gohman5442c712010-08-03 21:48:53 +0000822BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS,
Dan Gohman41f14cf2010-09-14 21:25:10 +0000823 const Location &Loc) {
824 assert(notDifferentParent(CS.getInstruction(), Loc.Ptr) &&
Dan Gohman00ef9322010-07-07 14:27:09 +0000825 "AliasAnalysis query involving multiple functions!");
826
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000827 const Value *Object = GetUnderlyingObject(Loc.Ptr, DL);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000828
Dan Gohman41f14cf2010-09-14 21:25:10 +0000829 // If this is a tail call and Loc.Ptr points to a stack location, we know that
Chris Lattnerd6a49ad2009-11-22 16:05:05 +0000830 // the tail call cannot access or modify the local stack.
831 // We cannot exclude byval arguments here; these belong to the caller of
832 // the current function not to the current function, and a tail callee
833 // may reference them.
834 if (isa<AllocaInst>(Object))
Dan Gohman5442c712010-08-03 21:48:53 +0000835 if (const CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
Chris Lattnerd6a49ad2009-11-22 16:05:05 +0000836 if (CI->isTailCall())
837 return NoModRef;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000838
Chris Lattnerd6a49ad2009-11-22 16:05:05 +0000839 // If the pointer is to a locally allocated object that does not escape,
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000840 // then the call can not mod/ref the pointer unless the call takes the pointer
841 // as an argument, and itself doesn't capture it.
Chris Lattner1e7b37e2009-11-23 16:46:41 +0000842 if (!isa<Constant>(Object) && CS.getInstruction() != Object &&
Dan Gohman84f90a32010-07-01 20:08:40 +0000843 isNonEscapingLocalObject(Object)) {
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000844 bool PassedAsArg = false;
845 unsigned ArgNo = 0;
Dan Gohman5442c712010-08-03 21:48:53 +0000846 for (ImmutableCallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000847 CI != CE; ++CI, ++ArgNo) {
Chris Lattner026f5e62011-05-23 05:15:43 +0000848 // Only look at the no-capture or byval pointer arguments. If this
849 // pointer were passed to arguments that were neither of these, then it
850 // couldn't be no-capture.
Duncan Sands19d0b472010-02-16 11:11:14 +0000851 if (!(*CI)->getType()->isPointerTy() ||
Nick Lewycky612d70b2011-11-20 19:09:04 +0000852 (!CS.doesNotCapture(ArgNo) && !CS.isByValArgument(ArgNo)))
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000853 continue;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000854
Dan Gohman41f14cf2010-09-14 21:25:10 +0000855 // If this is a no-capture pointer argument, see if we can tell that it
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000856 // is impossible to alias the pointer we're checking. If not, we have to
857 // assume that the call could touch the pointer, even though it doesn't
858 // escape.
Eli Friedman5f476dc2011-09-28 00:34:27 +0000859 if (!isNoAlias(Location(*CI), Location(Object))) {
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000860 PassedAsArg = true;
861 break;
862 }
863 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000864
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000865 if (!PassedAsArg)
Chris Lattnerd6a49ad2009-11-22 16:05:05 +0000866 return NoModRef;
867 }
868
Hal Finkel93046912014-07-25 21:13:35 +0000869 // While the assume intrinsic is marked as arbitrarily writing so that
870 // proper control dependencies will be maintained, it never aliases any
871 // particular memory location.
872 if (isAssumeIntrinsic(CS))
873 return NoModRef;
874
Chris Lattner2d332972008-06-16 06:30:22 +0000875 // The AliasAnalysis base class has some smarts, lets use them.
Hal Finkel354e23b2014-07-17 01:28:25 +0000876 return AliasAnalysis::getModRefInfo(CS, Loc);
Dan Gohman64d842e2010-09-08 01:32:20 +0000877}
Chris Lattner2d332972008-06-16 06:30:22 +0000878
Hal Finkel93046912014-07-25 21:13:35 +0000879AliasAnalysis::ModRefResult
880BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
881 ImmutableCallSite CS2) {
882 // While the assume intrinsic is marked as arbitrarily writing so that
883 // proper control dependencies will be maintained, it never aliases any
884 // particular memory location.
885 if (isAssumeIntrinsic(CS1) || isAssumeIntrinsic(CS2))
886 return NoModRef;
887
888 // The AliasAnalysis base class has some smarts, lets use them.
889 return AliasAnalysis::getModRefInfo(CS1, CS2);
890}
891
Chris Lattnera99edbe2009-11-26 02:11:08 +0000892/// aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
893/// against another pointer. We know that V1 is a GEP, but we don't know
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000894/// anything about V2. UnderlyingV1 is GetUnderlyingObject(GEP1, DL),
Chris Lattner5341c962009-11-26 02:14:59 +0000895/// UnderlyingV2 is the same for V2.
Chris Lattnera99edbe2009-11-26 02:11:08 +0000896///
Chris Lattnerd6a2a992003-02-26 19:41:54 +0000897AliasAnalysis::AliasResult
Dan Gohmanf372cf82010-10-19 22:54:46 +0000898BasicAliasAnalysis::aliasGEP(const GEPOperator *GEP1, uint64_t V1Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000899 const AAMDNodes &V1AAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +0000900 const Value *V2, uint64_t V2Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000901 const AAMDNodes &V2AAInfo,
Chris Lattner5341c962009-11-26 02:14:59 +0000902 const Value *UnderlyingV1,
903 const Value *UnderlyingV2) {
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000904 int64_t GEP1BaseOffset;
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000905 bool GEP1MaxLookupReached;
Chris Lattner1b9c3872010-08-18 22:47:56 +0000906 SmallVector<VariableGEPIndex, 4> GEP1VariableIndices;
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000907
Hal Finkel60db0582014-09-07 18:57:58 +0000908 AssumptionTracker *AT = &getAnalysis<AssumptionTracker>();
909 DominatorTreeWrapperPass *DTWP =
910 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
911 DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
912
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000913 // If we have two gep instructions with must-alias or not-alias'ing base
914 // pointers, figure out if the indexes to the GEP tell us anything about the
915 // derived pointer.
Chris Lattnera99edbe2009-11-26 02:11:08 +0000916 if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
Arnold Schwaighoferaadf1042013-03-26 18:07:53 +0000917 // Do the base pointers alias?
Benjamin Kramer2e52f022014-10-04 22:44:29 +0000918 AliasResult BaseAlias = aliasCheck(UnderlyingV1, UnknownSize, AAMDNodes(),
919 UnderlyingV2, UnknownSize, AAMDNodes());
Arnold Schwaighoferaadf1042013-03-26 18:07:53 +0000920
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000921 // Check for geps of non-aliasing underlying pointers where the offsets are
922 // identical.
Arnold Schwaighoferaadf1042013-03-26 18:07:53 +0000923 if ((BaseAlias == MayAlias) && V1Size == V2Size) {
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000924 // Do the base pointers alias assuming type and size.
925 AliasResult PreciseBaseAlias = aliasCheck(UnderlyingV1, V1Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000926 V1AAInfo, UnderlyingV2,
927 V2Size, V2AAInfo);
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000928 if (PreciseBaseAlias == NoAlias) {
929 // See if the computed offset from the common pointer tells us about the
930 // relation of the resulting pointer.
931 int64_t GEP2BaseOffset;
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000932 bool GEP2MaxLookupReached;
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000933 SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
934 const Value *GEP2BasePtr =
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000935 DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices,
Hal Finkel60db0582014-09-07 18:57:58 +0000936 GEP2MaxLookupReached, DL, AT, DT);
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000937 const Value *GEP1BasePtr =
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000938 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
Hal Finkel60db0582014-09-07 18:57:58 +0000939 GEP1MaxLookupReached, DL, AT, DT);
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000940 // DecomposeGEPExpression and GetUnderlyingObject should return the
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000941 // same result except when DecomposeGEPExpression has no DataLayout.
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000942 if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
Craig Topper9f008862014-04-15 04:59:12 +0000943 assert(!DL &&
944 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000945 return MayAlias;
946 }
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000947 // If the max search depth is reached the result is undefined
948 if (GEP2MaxLookupReached || GEP1MaxLookupReached)
949 return MayAlias;
950
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000951 // Same offsets.
952 if (GEP1BaseOffset == GEP2BaseOffset &&
Benjamin Kramer147644d2014-04-18 19:48:03 +0000953 GEP1VariableIndices == GEP2VariableIndices)
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000954 return NoAlias;
955 GEP1VariableIndices.clear();
956 }
957 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000958
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000959 // If we get a No or May, then return it immediately, no amount of analysis
960 // will improve this situation.
961 if (BaseAlias != MustAlias) return BaseAlias;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000962
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000963 // Otherwise, we have a MustAlias. Since the base pointers alias each other
964 // exactly, see if the computed offset from the common pointer tells us
965 // about the relation of the resulting pointer.
966 const Value *GEP1BasePtr =
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000967 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
Hal Finkel60db0582014-09-07 18:57:58 +0000968 GEP1MaxLookupReached, DL, AT, DT);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000969
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000970 int64_t GEP2BaseOffset;
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000971 bool GEP2MaxLookupReached;
Chris Lattner1b9c3872010-08-18 22:47:56 +0000972 SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000973 const Value *GEP2BasePtr =
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000974 DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices,
Hal Finkel60db0582014-09-07 18:57:58 +0000975 GEP2MaxLookupReached, DL, AT, DT);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000976
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000977 // DecomposeGEPExpression and GetUnderlyingObject should return the
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000978 // same result except when DecomposeGEPExpression has no DataLayout.
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000979 if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
Craig Topper9f008862014-04-15 04:59:12 +0000980 assert(!DL &&
Dan Gohmana4fcd242010-12-15 20:02:24 +0000981 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000982 return MayAlias;
983 }
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000984 // If the max search depth is reached the result is undefined
985 if (GEP2MaxLookupReached || GEP1MaxLookupReached)
986 return MayAlias;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000987
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000988 // Subtract the GEP2 pointer from the GEP1 pointer to find out their
989 // symbolic difference.
990 GEP1BaseOffset -= GEP2BaseOffset;
Dan Gohmanad867b02010-08-03 20:23:52 +0000991 GetIndexDifference(GEP1VariableIndices, GEP2VariableIndices);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000992
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000993 } else {
994 // Check to see if these two pointers are related by the getelementptr
995 // instruction. If one pointer is a GEP with a non-zero index of the other
996 // pointer, we know they cannot alias.
Chris Lattner5c1cfc22009-11-26 16:52:32 +0000997
998 // If both accesses are unknown size, we can't do anything useful here.
Dan Gohman2a190082010-08-03 01:03:11 +0000999 if (V1Size == UnknownSize && V2Size == UnknownSize)
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001000 return MayAlias;
Chris Lattner6ea17f77f2003-12-11 22:44:13 +00001001
Benjamin Kramer2e52f022014-10-04 22:44:29 +00001002 AliasResult R = aliasCheck(UnderlyingV1, UnknownSize, AAMDNodes(),
Hal Finkelcc39b672014-07-24 12:16:19 +00001003 V2, V2Size, V2AAInfo);
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001004 if (R != MustAlias)
1005 // If V2 may alias GEP base pointer, conservatively returns MayAlias.
1006 // If V2 is known not to alias GEP base pointer, then the two values
1007 // cannot alias per GEP semantics: "A pointer value formed from a
1008 // getelementptr instruction is associated with the addresses associated
1009 // with the first operand of the getelementptr".
1010 return R;
Chris Lattner6ea17f77f2003-12-11 22:44:13 +00001011
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001012 const Value *GEP1BasePtr =
Arnold Schwaighofer1a444482014-03-26 21:30:19 +00001013 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
Hal Finkel60db0582014-09-07 18:57:58 +00001014 GEP1MaxLookupReached, DL, AT, DT);
Jakub Staszak07f383f2013-08-24 14:16:00 +00001015
Arnold Schwaighofer76dca582012-09-06 14:31:51 +00001016 // DecomposeGEPExpression and GetUnderlyingObject should return the
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001017 // same result except when DecomposeGEPExpression has no DataLayout.
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001018 if (GEP1BasePtr != UnderlyingV1) {
Craig Topper9f008862014-04-15 04:59:12 +00001019 assert(!DL &&
Dan Gohmana4fcd242010-12-15 20:02:24 +00001020 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001021 return MayAlias;
Chris Lattner6ea17f77f2003-12-11 22:44:13 +00001022 }
Arnold Schwaighofer1a444482014-03-26 21:30:19 +00001023 // If the max search depth is reached the result is undefined
1024 if (GEP1MaxLookupReached)
1025 return MayAlias;
Chris Lattner6ea17f77f2003-12-11 22:44:13 +00001026 }
Jakub Staszak07f383f2013-08-24 14:16:00 +00001027
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001028 // In the two GEP Case, if there is no difference in the offsets of the
1029 // computed pointers, the resultant pointers are a must alias. This
1030 // hapens when we have two lexically identical GEP's (for example).
Chris Lattnerd6a2a992003-02-26 19:41:54 +00001031 //
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001032 // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
1033 // must aliases the GEP, the end result is a must alias also.
1034 if (GEP1BaseOffset == 0 && GEP1VariableIndices.empty())
Evan Chengc1eed9d2009-10-14 06:41:49 +00001035 return MustAlias;
Evan Chengf1f3dd32009-10-13 18:42:04 +00001036
Eli Friedman3d1b3072011-09-08 02:23:31 +00001037 // If there is a constant difference between the pointers, but the difference
1038 // is less than the size of the associated memory object, then we know
1039 // that the objects are partially overlapping. If the difference is
1040 // greater, we know they do not overlap.
Dan Gohmanc4bf5ca2010-12-13 22:50:24 +00001041 if (GEP1BaseOffset != 0 && GEP1VariableIndices.empty()) {
Eli Friedman3d1b3072011-09-08 02:23:31 +00001042 if (GEP1BaseOffset >= 0) {
1043 if (V2Size != UnknownSize) {
1044 if ((uint64_t)GEP1BaseOffset < V2Size)
1045 return PartialAlias;
1046 return NoAlias;
1047 }
1048 } else {
Arnold Schwaighofere3ac0992014-01-16 04:53:18 +00001049 // We have the situation where:
1050 // + +
1051 // | BaseOffset |
1052 // ---------------->|
1053 // |-->V1Size |-------> V2Size
1054 // GEP1 V2
1055 // We need to know that V2Size is not unknown, otherwise we might have
1056 // stripped a gep with negative index ('gep <ptr>, -1, ...).
1057 if (V1Size != UnknownSize && V2Size != UnknownSize) {
Eli Friedman3d1b3072011-09-08 02:23:31 +00001058 if (-(uint64_t)GEP1BaseOffset < V1Size)
1059 return PartialAlias;
1060 return NoAlias;
1061 }
1062 }
Dan Gohmanc4bf5ca2010-12-13 22:50:24 +00001063 }
1064
Eli Friedmanb78ac542011-09-08 02:37:07 +00001065 if (!GEP1VariableIndices.empty()) {
1066 uint64_t Modulo = 0;
Hal Finkel45ba2c12014-11-13 09:16:54 +00001067 bool AllPositive = true;
1068 for (unsigned i = 0, e = GEP1VariableIndices.size(); i != e; ++i) {
1069
1070 // Try to distinguish something like &A[i][1] against &A[42][0].
1071 // Grab the least significant bit set in any of the scales. We
1072 // don't need std::abs here (even if the scale's negative) as we'll
1073 // be ^'ing Modulo with itself later.
1074 Modulo |= (uint64_t) GEP1VariableIndices[i].Scale;
1075
1076 if (AllPositive) {
1077 // If the Value could change between cycles, then any reasoning about
1078 // the Value this cycle may not hold in the next cycle. We'll just
1079 // give up if we can't determine conditions that hold for every cycle:
1080 const Value *V = GEP1VariableIndices[i].V;
1081
1082 bool SignKnownZero, SignKnownOne;
1083 ComputeSignBit(
1084 const_cast<Value *>(V),
1085 SignKnownZero, SignKnownOne,
1086 DL, 0, AT, nullptr, DT);
1087
1088 // Zero-extension widens the variable, and so forces the sign
1089 // bit to zero.
1090 bool IsZExt = GEP1VariableIndices[i].Extension == EK_ZeroExt;
1091 SignKnownZero |= IsZExt;
1092 SignKnownOne &= !IsZExt;
1093
1094 // If the variable begins with a zero then we know it's
1095 // positive, regardless of whether the value is signed or
1096 // unsigned.
1097 int64_t Scale = GEP1VariableIndices[i].Scale;
1098 AllPositive =
1099 (SignKnownZero && Scale >= 0) ||
1100 (SignKnownOne && Scale < 0);
1101 }
1102 }
1103
Eli Friedmanb78ac542011-09-08 02:37:07 +00001104 Modulo = Modulo ^ (Modulo & (Modulo - 1));
Eli Friedman3d1b3072011-09-08 02:23:31 +00001105
Eli Friedmanb78ac542011-09-08 02:37:07 +00001106 // We can compute the difference between the two addresses
1107 // mod Modulo. Check whether that difference guarantees that the
1108 // two locations do not alias.
1109 uint64_t ModOffset = (uint64_t)GEP1BaseOffset & (Modulo - 1);
1110 if (V1Size != UnknownSize && V2Size != UnknownSize &&
1111 ModOffset >= V2Size && V1Size <= Modulo - ModOffset)
1112 return NoAlias;
Hal Finkel45ba2c12014-11-13 09:16:54 +00001113
1114 // If we know all the variables are positive, then GEP1 >= GEP1BasePtr.
1115 // If GEP1BasePtr > V2 (GEP1BaseOffset > 0) then we know the pointers
1116 // don't alias if V2Size can fit in the gap between V2 and GEP1BasePtr.
1117 if (AllPositive && GEP1BaseOffset > 0 && V2Size <= (uint64_t) GEP1BaseOffset)
1118 return NoAlias;
Eli Friedmanb78ac542011-09-08 02:37:07 +00001119 }
Eli Friedman3d1b3072011-09-08 02:23:31 +00001120
Dan Gohmanadf80ae2011-06-04 06:50:18 +00001121 // Statically, we can see that the base objects are the same, but the
1122 // pointers have dynamic offsets which we can't resolve. And none of our
1123 // little tricks above worked.
1124 //
1125 // TODO: Returning PartialAlias instead of MayAlias is a mild hack; the
1126 // practical effect of this is protecting TBAA in the case of dynamic
Dan Gohman9017b842012-02-17 18:33:38 +00001127 // indices into arrays of unions or malloc'd memory.
Dan Gohmanadf80ae2011-06-04 06:50:18 +00001128 return PartialAlias;
Evan Chengf1f3dd32009-10-13 18:42:04 +00001129}
1130
Dan Gohman4e7e7952011-06-03 20:17:36 +00001131static AliasAnalysis::AliasResult
1132MergeAliasResults(AliasAnalysis::AliasResult A, AliasAnalysis::AliasResult B) {
1133 // If the results agree, take it.
1134 if (A == B)
1135 return A;
1136 // A mix of PartialAlias and MustAlias is PartialAlias.
1137 if ((A == AliasAnalysis::PartialAlias && B == AliasAnalysis::MustAlias) ||
1138 (B == AliasAnalysis::PartialAlias && A == AliasAnalysis::MustAlias))
1139 return AliasAnalysis::PartialAlias;
1140 // Otherwise, we don't know anything.
1141 return AliasAnalysis::MayAlias;
1142}
1143
Chris Lattner98e253262009-11-23 16:45:27 +00001144/// aliasSelect - Provide a bunch of ad-hoc rules to disambiguate a Select
1145/// instruction against another.
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001146AliasAnalysis::AliasResult
Dan Gohmanf372cf82010-10-19 22:54:46 +00001147BasicAliasAnalysis::aliasSelect(const SelectInst *SI, uint64_t SISize,
Hal Finkelcc39b672014-07-24 12:16:19 +00001148 const AAMDNodes &SIAAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +00001149 const Value *V2, uint64_t V2Size,
Hal Finkelcc39b672014-07-24 12:16:19 +00001150 const AAMDNodes &V2AAInfo) {
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001151 // If the values are Selects with the same condition, we can do a more precise
1152 // check: just check for aliases between the values on corresponding arms.
1153 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
1154 if (SI->getCondition() == SI2->getCondition()) {
1155 AliasResult Alias =
Hal Finkelcc39b672014-07-24 12:16:19 +00001156 aliasCheck(SI->getTrueValue(), SISize, SIAAInfo,
1157 SI2->getTrueValue(), V2Size, V2AAInfo);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001158 if (Alias == MayAlias)
1159 return MayAlias;
1160 AliasResult ThisAlias =
Hal Finkelcc39b672014-07-24 12:16:19 +00001161 aliasCheck(SI->getFalseValue(), SISize, SIAAInfo,
1162 SI2->getFalseValue(), V2Size, V2AAInfo);
Dan Gohman4e7e7952011-06-03 20:17:36 +00001163 return MergeAliasResults(ThisAlias, Alias);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001164 }
1165
1166 // If both arms of the Select node NoAlias or MustAlias V2, then returns
1167 // NoAlias / MustAlias. Otherwise, returns MayAlias.
1168 AliasResult Alias =
Hal Finkelcc39b672014-07-24 12:16:19 +00001169 aliasCheck(V2, V2Size, V2AAInfo, SI->getTrueValue(), SISize, SIAAInfo);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001170 if (Alias == MayAlias)
1171 return MayAlias;
Dan Gohman7c34ece2010-06-28 21:16:52 +00001172
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001173 AliasResult ThisAlias =
Hal Finkelcc39b672014-07-24 12:16:19 +00001174 aliasCheck(V2, V2Size, V2AAInfo, SI->getFalseValue(), SISize, SIAAInfo);
Dan Gohman4e7e7952011-06-03 20:17:36 +00001175 return MergeAliasResults(ThisAlias, Alias);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001176}
1177
Evan Chengf92f5552009-10-14 05:22:03 +00001178// aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
Evan Cheng31565b32009-10-14 05:05:02 +00001179// against another.
Evan Chengc10e88d2009-10-13 22:02:20 +00001180AliasAnalysis::AliasResult
Dan Gohmanf372cf82010-10-19 22:54:46 +00001181BasicAliasAnalysis::aliasPHI(const PHINode *PN, uint64_t PNSize,
Hal Finkelcc39b672014-07-24 12:16:19 +00001182 const AAMDNodes &PNAAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +00001183 const Value *V2, uint64_t V2Size,
Hal Finkelcc39b672014-07-24 12:16:19 +00001184 const AAMDNodes &V2AAInfo) {
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001185 // Track phi nodes we have visited. We use this information when we determine
1186 // value equivalence.
1187 VisitedPhiBBs.insert(PN->getParent());
1188
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001189 // If the values are PHIs in the same block, we can do a more precise
1190 // as well as efficient check: just check for aliases between the values
1191 // on corresponding edges.
1192 if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
1193 if (PN2->getParent() == PN->getParent()) {
Hal Finkelcc39b672014-07-24 12:16:19 +00001194 LocPair Locs(Location(PN, PNSize, PNAAInfo),
1195 Location(V2, V2Size, V2AAInfo));
Arnold Schwaighofer8dc34cf2012-09-06 14:41:53 +00001196 if (PN > V2)
1197 std::swap(Locs.first, Locs.second);
Arnold Schwaighoferedd62b12012-12-10 23:02:41 +00001198 // Analyse the PHIs' inputs under the assumption that the PHIs are
1199 // NoAlias.
1200 // If the PHIs are May/MustAlias there must be (recursively) an input
1201 // operand from outside the PHIs' cycle that is MayAlias/MustAlias or
1202 // there must be an operation on the PHIs within the PHIs' value cycle
1203 // that causes a MayAlias.
1204 // Pretend the phis do not alias.
1205 AliasResult Alias = NoAlias;
1206 assert(AliasCache.count(Locs) &&
1207 "There must exist an entry for the phi node");
1208 AliasResult OrigAliasResult = AliasCache[Locs];
1209 AliasCache[Locs] = NoAlias;
Arnold Schwaighofer8dc34cf2012-09-06 14:41:53 +00001210
Hal Finkela6f86fc2012-11-17 02:33:15 +00001211 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001212 AliasResult ThisAlias =
Hal Finkelcc39b672014-07-24 12:16:19 +00001213 aliasCheck(PN->getIncomingValue(i), PNSize, PNAAInfo,
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001214 PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
Hal Finkelcc39b672014-07-24 12:16:19 +00001215 V2Size, V2AAInfo);
Dan Gohman4e7e7952011-06-03 20:17:36 +00001216 Alias = MergeAliasResults(ThisAlias, Alias);
1217 if (Alias == MayAlias)
1218 break;
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001219 }
Arnold Schwaighofer8dc34cf2012-09-06 14:41:53 +00001220
1221 // Reset if speculation failed.
Arnold Schwaighoferedd62b12012-12-10 23:02:41 +00001222 if (Alias != NoAlias)
Arnold Schwaighofer8dc34cf2012-09-06 14:41:53 +00001223 AliasCache[Locs] = OrigAliasResult;
1224
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001225 return Alias;
1226 }
1227
Evan Cheng8ec25932009-10-16 00:33:09 +00001228 SmallPtrSet<Value*, 4> UniqueSrc;
Evan Chengc10e88d2009-10-13 22:02:20 +00001229 SmallVector<Value*, 4> V1Srcs;
Evan Chengc10e88d2009-10-13 22:02:20 +00001230 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1231 Value *PV1 = PN->getIncomingValue(i);
1232 if (isa<PHINode>(PV1))
1233 // If any of the source itself is a PHI, return MayAlias conservatively
Evan Chengc1eed9d2009-10-14 06:41:49 +00001234 // to avoid compile time explosion. The worst possible case is if both
1235 // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
1236 // and 'n' are the number of PHI sources.
Evan Chengc10e88d2009-10-13 22:02:20 +00001237 return MayAlias;
1238 if (UniqueSrc.insert(PV1))
1239 V1Srcs.push_back(PV1);
1240 }
1241
Hal Finkelcc39b672014-07-24 12:16:19 +00001242 AliasResult Alias = aliasCheck(V2, V2Size, V2AAInfo,
1243 V1Srcs[0], PNSize, PNAAInfo);
Evan Chengf92f5552009-10-14 05:22:03 +00001244 // Early exit if the check of the first PHI source against V2 is MayAlias.
1245 // Other results are not possible.
1246 if (Alias == MayAlias)
1247 return MayAlias;
1248
Evan Chengc10e88d2009-10-13 22:02:20 +00001249 // If all sources of the PHI node NoAlias or MustAlias V2, then returns
1250 // NoAlias / MustAlias. Otherwise, returns MayAlias.
Evan Chengc10e88d2009-10-13 22:02:20 +00001251 for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
1252 Value *V = V1Srcs[i];
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001253
Hal Finkelcc39b672014-07-24 12:16:19 +00001254 AliasResult ThisAlias = aliasCheck(V2, V2Size, V2AAInfo,
1255 V, PNSize, PNAAInfo);
Dan Gohman4e7e7952011-06-03 20:17:36 +00001256 Alias = MergeAliasResults(ThisAlias, Alias);
1257 if (Alias == MayAlias)
1258 break;
Evan Chengc10e88d2009-10-13 22:02:20 +00001259 }
1260
1261 return Alias;
1262}
1263
1264// aliasCheck - Provide a bunch of ad-hoc rules to disambiguate in common cases,
1265// such as array references.
Evan Chengf1f3dd32009-10-13 18:42:04 +00001266//
1267AliasAnalysis::AliasResult
Dan Gohmanf372cf82010-10-19 22:54:46 +00001268BasicAliasAnalysis::aliasCheck(const Value *V1, uint64_t V1Size,
Hal Finkelcc39b672014-07-24 12:16:19 +00001269 AAMDNodes V1AAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +00001270 const Value *V2, uint64_t V2Size,
Hal Finkelcc39b672014-07-24 12:16:19 +00001271 AAMDNodes V2AAInfo) {
Dan Gohmancb45bd92010-04-08 18:11:50 +00001272 // If either of the memory references is empty, it doesn't matter what the
1273 // pointer values are.
1274 if (V1Size == 0 || V2Size == 0)
1275 return NoAlias;
1276
Evan Chengf1f3dd32009-10-13 18:42:04 +00001277 // Strip off any casts if they exist.
1278 V1 = V1->stripPointerCasts();
1279 V2 = V2->stripPointerCasts();
1280
1281 // Are we checking for alias of the same value?
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001282 // Because we look 'through' phi nodes we could look at "Value" pointers from
1283 // different iterations. We must therefore make sure that this is not the
1284 // case. The function isValueEqualInPotentialCycles ensures that this cannot
1285 // happen by looking at the visited phi nodes and making sure they cannot
1286 // reach the value.
1287 if (isValueEqualInPotentialCycles(V1, V2))
1288 return MustAlias;
Evan Chengf1f3dd32009-10-13 18:42:04 +00001289
Duncan Sands19d0b472010-02-16 11:11:14 +00001290 if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
Evan Chengf1f3dd32009-10-13 18:42:04 +00001291 return NoAlias; // Scalars cannot alias each other
1292
1293 // Figure out what objects these things are pointing to if we can.
Arnold Schwaighofer1a444482014-03-26 21:30:19 +00001294 const Value *O1 = GetUnderlyingObject(V1, DL, MaxLookupSearchDepth);
1295 const Value *O2 = GetUnderlyingObject(V2, DL, MaxLookupSearchDepth);
Evan Chengf1f3dd32009-10-13 18:42:04 +00001296
Dan Gohmanccb45842009-11-09 19:29:11 +00001297 // Null values in the default address space don't point to any object, so they
1298 // don't alias any other pointer.
1299 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
1300 if (CPN->getType()->getAddressSpace() == 0)
1301 return NoAlias;
1302 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
1303 if (CPN->getType()->getAddressSpace() == 0)
1304 return NoAlias;
1305
Evan Chengf1f3dd32009-10-13 18:42:04 +00001306 if (O1 != O2) {
1307 // If V1/V2 point to two different objects we know that we have no alias.
Dan Gohman00ef9322010-07-07 14:27:09 +00001308 if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
Evan Chengf1f3dd32009-10-13 18:42:04 +00001309 return NoAlias;
Nick Lewyckyc53e2ec2009-11-14 06:15:14 +00001310
1311 // Constant pointers can't alias with non-const isIdentifiedObject objects.
Dan Gohman00ef9322010-07-07 14:27:09 +00001312 if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
1313 (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
Nick Lewyckyc53e2ec2009-11-14 06:15:14 +00001314 return NoAlias;
1315
Michael Kupersteinf3e663a2013-05-28 08:17:48 +00001316 // Function arguments can't alias with things that are known to be
1317 // unambigously identified at the function level.
1318 if ((isa<Argument>(O1) && isIdentifiedFunctionLocal(O2)) ||
1319 (isa<Argument>(O2) && isIdentifiedFunctionLocal(O1)))
Dan Gohman84f90a32010-07-01 20:08:40 +00001320 return NoAlias;
Evan Chengf1f3dd32009-10-13 18:42:04 +00001321
1322 // Most objects can't alias null.
Dan Gohman00ef9322010-07-07 14:27:09 +00001323 if ((isa<ConstantPointerNull>(O2) && isKnownNonNull(O1)) ||
1324 (isa<ConstantPointerNull>(O1) && isKnownNonNull(O2)))
Evan Chengf1f3dd32009-10-13 18:42:04 +00001325 return NoAlias;
Jakub Staszak07f383f2013-08-24 14:16:00 +00001326
Dan Gohman5b0a8a82010-07-07 14:30:04 +00001327 // If one pointer is the result of a call/invoke or load and the other is a
1328 // non-escaping local object within the same function, then we know the
1329 // object couldn't escape to a point where the call could return it.
1330 //
1331 // Note that if the pointers are in different functions, there are a
1332 // variety of complications. A call with a nocapture argument may still
1333 // temporary store the nocapture argument's value in a temporary memory
1334 // location if that memory location doesn't escape. Or it may pass a
1335 // nocapture value to other functions as long as they don't capture it.
1336 if (isEscapeSource(O1) && isNonEscapingLocalObject(O2))
1337 return NoAlias;
1338 if (isEscapeSource(O2) && isNonEscapingLocalObject(O1))
1339 return NoAlias;
1340 }
1341
Evan Chengf1f3dd32009-10-13 18:42:04 +00001342 // If the size of one access is larger than the entire object on the other
1343 // side, then we know such behavior is undefined and can assume no alias.
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001344 if (DL)
1345 if ((V1Size != UnknownSize && isObjectSmallerThan(O2, V1Size, *DL, *TLI)) ||
1346 (V2Size != UnknownSize && isObjectSmallerThan(O1, V2Size, *DL, *TLI)))
Evan Chengf1f3dd32009-10-13 18:42:04 +00001347 return NoAlias;
Jakub Staszak07f383f2013-08-24 14:16:00 +00001348
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001349 // Check the cache before climbing up use-def chains. This also terminates
1350 // otherwise infinitely recursive queries.
Hal Finkelcc39b672014-07-24 12:16:19 +00001351 LocPair Locs(Location(V1, V1Size, V1AAInfo),
1352 Location(V2, V2Size, V2AAInfo));
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001353 if (V1 > V2)
1354 std::swap(Locs.first, Locs.second);
1355 std::pair<AliasCacheTy::iterator, bool> Pair =
1356 AliasCache.insert(std::make_pair(Locs, MayAlias));
1357 if (!Pair.second)
1358 return Pair.first->second;
1359
Chris Lattner89288992009-11-26 02:13:03 +00001360 // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
1361 // GEP can't simplify, we don't even look at the PHI cases.
Chris Lattnerb2647b92009-10-17 23:48:54 +00001362 if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
Chris Lattnerd6a2a992003-02-26 19:41:54 +00001363 std::swap(V1, V2);
1364 std::swap(V1Size, V2Size);
Chris Lattner5341c962009-11-26 02:14:59 +00001365 std::swap(O1, O2);
Hal Finkelcc39b672014-07-24 12:16:19 +00001366 std::swap(V1AAInfo, V2AAInfo);
Chris Lattnerd6a2a992003-02-26 19:41:54 +00001367 }
Dan Gohman02538ac2010-10-18 18:04:47 +00001368 if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) {
Hal Finkelcc39b672014-07-24 12:16:19 +00001369 AliasResult Result = aliasGEP(GV1, V1Size, V1AAInfo, V2, V2Size, V2AAInfo, O1, O2);
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001370 if (Result != MayAlias) return AliasCache[Locs] = Result;
Dan Gohman02538ac2010-10-18 18:04:47 +00001371 }
Evan Chengc10e88d2009-10-13 22:02:20 +00001372
1373 if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
1374 std::swap(V1, V2);
1375 std::swap(V1Size, V2Size);
Hal Finkelcc39b672014-07-24 12:16:19 +00001376 std::swap(V1AAInfo, V2AAInfo);
Evan Chengc10e88d2009-10-13 22:02:20 +00001377 }
Dan Gohman02538ac2010-10-18 18:04:47 +00001378 if (const PHINode *PN = dyn_cast<PHINode>(V1)) {
Hal Finkelcc39b672014-07-24 12:16:19 +00001379 AliasResult Result = aliasPHI(PN, V1Size, V1AAInfo,
1380 V2, V2Size, V2AAInfo);
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001381 if (Result != MayAlias) return AliasCache[Locs] = Result;
Dan Gohman02538ac2010-10-18 18:04:47 +00001382 }
Misha Brukman01808ca2005-04-21 21:13:18 +00001383
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001384 if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
1385 std::swap(V1, V2);
1386 std::swap(V1Size, V2Size);
Hal Finkelcc39b672014-07-24 12:16:19 +00001387 std::swap(V1AAInfo, V2AAInfo);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001388 }
Dan Gohman02538ac2010-10-18 18:04:47 +00001389 if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) {
Hal Finkelcc39b672014-07-24 12:16:19 +00001390 AliasResult Result = aliasSelect(S1, V1Size, V1AAInfo,
1391 V2, V2Size, V2AAInfo);
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001392 if (Result != MayAlias) return AliasCache[Locs] = Result;
Dan Gohman02538ac2010-10-18 18:04:47 +00001393 }
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001394
Dan Gohman44da55b2011-01-18 21:16:06 +00001395 // If both pointers are pointing into the same object and one of them
1396 // accesses is accessing the entire object, then the accesses must
1397 // overlap in some way.
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001398 if (DL && O1 == O2)
1399 if ((V1Size != UnknownSize && isObjectSize(O1, V1Size, *DL, *TLI)) ||
1400 (V2Size != UnknownSize && isObjectSize(O2, V2Size, *DL, *TLI)))
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001401 return AliasCache[Locs] = PartialAlias;
Dan Gohman44da55b2011-01-18 21:16:06 +00001402
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001403 AliasResult Result =
Hal Finkelcc39b672014-07-24 12:16:19 +00001404 AliasAnalysis::alias(Location(V1, V1Size, V1AAInfo),
1405 Location(V2, V2Size, V2AAInfo));
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001406 return AliasCache[Locs] = Result;
Chris Lattnerd6a2a992003-02-26 19:41:54 +00001407}
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001408
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001409bool BasicAliasAnalysis::isValueEqualInPotentialCycles(const Value *V,
1410 const Value *V2) {
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001411 if (V != V2)
1412 return false;
1413
1414 const Instruction *Inst = dyn_cast<Instruction>(V);
1415 if (!Inst)
1416 return true;
1417
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001418 if (VisitedPhiBBs.size() > MaxNumPhiBBsValueReachabilityCheck)
1419 return false;
1420
1421 // Use dominance or loop info if available.
Chandler Carruth73523022014-01-13 13:07:17 +00001422 DominatorTreeWrapperPass *DTWP =
1423 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
Craig Topper9f008862014-04-15 04:59:12 +00001424 DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001425 LoopInfo *LI = getAnalysisIfAvailable<LoopInfo>();
1426
1427 // Make sure that the visited phis cannot reach the Value. This ensures that
1428 // the Values cannot come from different iterations of a potential cycle the
1429 // phi nodes could be involved in.
Craig Topper46276792014-08-24 23:23:06 +00001430 for (auto *P : VisitedPhiBBs)
1431 if (isPotentiallyReachable(P->begin(), Inst, DT, LI))
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001432 return false;
1433
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001434 return true;
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001435}
1436
1437/// GetIndexDifference - Dest and Src are the variable indices from two
1438/// decomposed GetElementPtr instructions GEP1 and GEP2 which have common base
1439/// pointers. Subtract the GEP2 indices from GEP1 to find the symbolic
1440/// difference between the two pointers.
1441void BasicAliasAnalysis::GetIndexDifference(
1442 SmallVectorImpl<VariableGEPIndex> &Dest,
1443 const SmallVectorImpl<VariableGEPIndex> &Src) {
1444 if (Src.empty())
1445 return;
1446
1447 for (unsigned i = 0, e = Src.size(); i != e; ++i) {
1448 const Value *V = Src[i].V;
1449 ExtensionKind Extension = Src[i].Extension;
1450 int64_t Scale = Src[i].Scale;
1451
1452 // Find V in Dest. This is N^2, but pointer indices almost never have more
1453 // than a few variable indexes.
1454 for (unsigned j = 0, e = Dest.size(); j != e; ++j) {
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001455 if (!isValueEqualInPotentialCycles(Dest[j].V, V) ||
1456 Dest[j].Extension != Extension)
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001457 continue;
1458
1459 // If we found it, subtract off Scale V's from the entry in Dest. If it
1460 // goes to zero, remove the entry.
1461 if (Dest[j].Scale != Scale)
1462 Dest[j].Scale -= Scale;
1463 else
1464 Dest.erase(Dest.begin() + j);
1465 Scale = 0;
1466 break;
1467 }
1468
1469 // If we didn't consume this entry, add it to the end of the Dest list.
1470 if (Scale) {
1471 VariableGEPIndex Entry = { V, Extension, -Scale };
1472 Dest.push_back(Entry);
1473 }
1474 }
1475}