blob: 241355e9c3c3af56f69e5be6d5752f742e66419a [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"
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +000020#include "llvm/Analysis/CFG.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000021#include "llvm/Analysis/CaptureTracking.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/Analysis/InstructionSimplify.h"
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +000023#include "llvm/Analysis/LoopInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/Analysis/MemoryBuiltins.h"
25#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Constants.h"
27#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000029#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000031#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/GlobalAlias.h"
33#include "llvm/IR/GlobalVariable.h"
34#include "llvm/IR/Instructions.h"
35#include "llvm/IR/IntrinsicInst.h"
36#include "llvm/IR/LLVMContext.h"
37#include "llvm/IR/Operator.h"
Chris Lattnerd82256a2004-03-15 03:36:49 +000038#include "llvm/Pass.h"
Torok Edwin56d06592009-07-11 20:10:48 +000039#include "llvm/Support/ErrorHandling.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000040#include "llvm/Target/TargetLibraryInfo.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000041#include <algorithm>
Chris Lattner35997482003-11-25 18:33:40 +000042using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000043
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +000044/// Cutoff after which to stop analysing a set of phi nodes potentially involved
45/// in a cycle. Because we are analysing 'through' phi nodes we need to be
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +000046/// careful with value equivalence. We use reachability to make sure a value
47/// cannot be involved in a cycle.
48const unsigned MaxNumPhiBBsValueReachabilityCheck = 20;
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +000049
Arnold Schwaighofer1a444482014-03-26 21:30:19 +000050// The max limit of the search depth in DecomposeGEPExpression() and
51// GetUnderlyingObject(), both functions need to use the same search
52// depth otherwise the algorithm in aliasGEP will assert.
53static const unsigned MaxLookupSearchDepth = 6;
54
Chris Lattner2d332972008-06-16 06:30:22 +000055//===----------------------------------------------------------------------===//
56// Useful predicates
57//===----------------------------------------------------------------------===//
Devang Patel09f162c2007-05-01 21:15:47 +000058
Chris Lattnerb35d9b52008-06-16 06:19:11 +000059/// isNonEscapingLocalObject - Return true if the pointer is to a function-local
60/// object that never escapes from the function.
Dan Gohman84f90a32010-07-01 20:08:40 +000061static bool isNonEscapingLocalObject(const Value *V) {
Chris Lattnerfa482582008-06-16 06:28:01 +000062 // If this is a local allocation, check to see if it escapes.
Dan Gohman84f90a32010-07-01 20:08:40 +000063 if (isa<AllocaInst>(V) || isNoAliasCall(V))
Dan Gohman94e61762009-11-19 21:57:48 +000064 // Set StoreCaptures to True so that we can assume in our callers that the
65 // pointer is not the result of a load instruction. Currently
66 // PointerMayBeCaptured doesn't have any special analysis for the
67 // StoreCaptures=false case; if it did, our callers could be refined to be
68 // more precise.
69 return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
Duncan Sands8d65f362009-01-05 21:19:53 +000070
Chris Lattnerfa482582008-06-16 06:28:01 +000071 // If this is an argument that corresponds to a byval or noalias argument,
Duncan Sands8d65f362009-01-05 21:19:53 +000072 // then it has not escaped before entering the function. Check if it escapes
73 // inside the function.
Dan Gohman84f90a32010-07-01 20:08:40 +000074 if (const Argument *A = dyn_cast<Argument>(V))
Richard Osbornea1fffcf2012-11-05 10:48:24 +000075 if (A->hasByValAttr() || A->hasNoAliasAttr())
76 // Note even if the argument is marked nocapture we still need to check
77 // for copies made inside the function. The nocapture attribute only
78 // specifies that there are no copies made that outlive the function.
Dan Gohman84f90a32010-07-01 20:08:40 +000079 return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
Richard Osbornea1fffcf2012-11-05 10:48:24 +000080
Chris Lattnerb35d9b52008-06-16 06:19:11 +000081 return false;
82}
83
Dan Gohman0824aff2010-06-29 00:50:39 +000084/// isEscapeSource - Return true if the pointer is one which would have
85/// been considered an escape by isNonEscapingLocalObject.
Dan Gohman84f90a32010-07-01 20:08:40 +000086static bool isEscapeSource(const Value *V) {
87 if (isa<CallInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V))
88 return true;
Dan Gohman0824aff2010-06-29 00:50:39 +000089
90 // The load case works because isNonEscapingLocalObject considers all
91 // stores to be escapes (it passes true for the StoreCaptures argument
92 // to PointerMayBeCaptured).
93 if (isa<LoadInst>(V))
94 return true;
95
96 return false;
97}
Chris Lattnerb35d9b52008-06-16 06:19:11 +000098
Dan Gohman44da55b2011-01-18 21:16:06 +000099/// getObjectSize - Return the size of the object specified by V, or
100/// UnknownSize if unknown.
Rafael Espindola5f57f462014-02-21 18:34:28 +0000101static uint64_t getObjectSize(const Value *V, const DataLayout &DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000102 const TargetLibraryInfo &TLI,
Eli Friedman8bc169c2012-02-27 20:46:07 +0000103 bool RoundToAlign = false) {
Nuno Lopes55fff832012-06-21 15:45:28 +0000104 uint64_t Size;
Rafael Espindola5f57f462014-02-21 18:34:28 +0000105 if (getObjectSize(V, Size, &DL, &TLI, RoundToAlign))
Nuno Lopes55fff832012-06-21 15:45:28 +0000106 return Size;
107 return AliasAnalysis::UnknownSize;
Dan Gohman44da55b2011-01-18 21:16:06 +0000108}
109
110/// isObjectSmallerThan - Return true if we can prove that the object specified
111/// by V is smaller than Size.
112static bool isObjectSmallerThan(const Value *V, uint64_t Size,
Rafael Espindola5f57f462014-02-21 18:34:28 +0000113 const DataLayout &DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000114 const TargetLibraryInfo &TLI) {
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000115 // Note that the meanings of the "object" are slightly different in the
116 // following contexts:
117 // c1: llvm::getObjectSize()
118 // c2: llvm.objectsize() intrinsic
119 // c3: isObjectSmallerThan()
120 // c1 and c2 share the same meaning; however, the meaning of "object" in c3
121 // refers to the "entire object".
122 //
123 // Consider this example:
124 // char *p = (char*)malloc(100)
125 // char *q = p+80;
126 //
127 // In the context of c1 and c2, the "object" pointed by q refers to the
128 // stretch of memory of q[0:19]. So, getObjectSize(q) should return 20.
129 //
130 // However, in the context of c3, the "object" refers to the chunk of memory
131 // being allocated. So, the "object" has 100 bytes, and q points to the middle
132 // the "object". In case q is passed to isObjectSmallerThan() as the 1st
133 // parameter, before the llvm::getObjectSize() is called to get the size of
134 // entire object, we should:
135 // - either rewind the pointer q to the base-address of the object in
136 // question (in this case rewind to p), or
137 // - just give up. It is up to caller to make sure the pointer is pointing
138 // to the base address the object.
Jakub Staszak07f383f2013-08-24 14:16:00 +0000139 //
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000140 // We go for 2nd option for simplicity.
141 if (!isIdentifiedObject(V))
142 return false;
143
Eli Friedman8bc169c2012-02-27 20:46:07 +0000144 // This function needs to use the aligned object size because we allow
145 // reads a bit past the end given sufficient alignment.
Rafael Espindola5f57f462014-02-21 18:34:28 +0000146 uint64_t ObjectSize = getObjectSize(V, DL, TLI, /*RoundToAlign*/true);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000147
Dan Gohman44da55b2011-01-18 21:16:06 +0000148 return ObjectSize != AliasAnalysis::UnknownSize && ObjectSize < Size;
149}
150
151/// isObjectSize - Return true if we can prove that the object specified
152/// by V has size Size.
153static bool isObjectSize(const Value *V, uint64_t Size,
Rafael Espindola5f57f462014-02-21 18:34:28 +0000154 const DataLayout &DL, const TargetLibraryInfo &TLI) {
155 uint64_t ObjectSize = getObjectSize(V, DL, TLI);
Dan Gohman44da55b2011-01-18 21:16:06 +0000156 return ObjectSize != AliasAnalysis::UnknownSize && ObjectSize == Size;
Chris Lattner98ad8162008-06-16 06:10:11 +0000157}
158
Michael Kupersteinf3e663a2013-05-28 08:17:48 +0000159/// isIdentifiedFunctionLocal - Return true if V is umabigously identified
160/// at the function-level. Different IdentifiedFunctionLocals can't alias.
161/// Further, an IdentifiedFunctionLocal can not alias with any function
Alp Tokercb402912014-01-24 17:20:08 +0000162/// arguments other than itself, which is not necessarily true for
Michael Kupersteinf3e663a2013-05-28 08:17:48 +0000163/// IdentifiedObjects.
164static bool isIdentifiedFunctionLocal(const Value *V)
165{
166 return isa<AllocaInst>(V) || isNoAliasCall(V) || isNoAliasArgument(V);
167}
168
169
Chris Lattner2d332972008-06-16 06:30:22 +0000170//===----------------------------------------------------------------------===//
Chris Lattner9f7500f2010-08-18 22:07:29 +0000171// GetElementPtr Instruction Decomposition and Analysis
172//===----------------------------------------------------------------------===//
173
Chris Lattner1b9c3872010-08-18 22:47:56 +0000174namespace {
175 enum ExtensionKind {
176 EK_NotExtended,
177 EK_SignExt,
178 EK_ZeroExt
179 };
Jakub Staszak07f383f2013-08-24 14:16:00 +0000180
Chris Lattner1b9c3872010-08-18 22:47:56 +0000181 struct VariableGEPIndex {
182 const Value *V;
183 ExtensionKind Extension;
184 int64_t Scale;
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000185
186 bool operator==(const VariableGEPIndex &Other) const {
187 return V == Other.V && Extension == Other.Extension &&
188 Scale == Other.Scale;
189 }
190
191 bool operator!=(const VariableGEPIndex &Other) const {
192 return !operator==(Other);
193 }
Chris Lattner1b9c3872010-08-18 22:47:56 +0000194 };
195}
196
Chris Lattner9f7500f2010-08-18 22:07:29 +0000197
198/// GetLinearExpression - Analyze the specified value as a linear expression:
199/// "A*V + B", where A and B are constant integers. Return the scale and offset
Chris Lattner3decde92010-08-18 23:09:49 +0000200/// values as APInts and return V as a Value*, and return whether we looked
201/// through any sign or zero extends. The incoming Value is known to have
202/// IntegerType and it may already be sign or zero extended.
203///
204/// Note that this looks through extends, so the high bits may not be
205/// represented in the result.
Chris Lattner9f7500f2010-08-18 22:07:29 +0000206static Value *GetLinearExpression(Value *V, APInt &Scale, APInt &Offset,
Chris Lattner3decde92010-08-18 23:09:49 +0000207 ExtensionKind &Extension,
Rafael Espindola5f57f462014-02-21 18:34:28 +0000208 const DataLayout &DL, unsigned Depth) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000209 assert(V->getType()->isIntegerTy() && "Not an integer value");
210
211 // Limit our recursion depth.
212 if (Depth == 6) {
213 Scale = 1;
214 Offset = 0;
215 return V;
216 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000217
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.
Rafael Espindola5f57f462014-02-21 18:34:28 +0000225 if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), &DL))
Chris Lattner9f7500f2010-08-18 22:07:29 +0000226 break;
227 // FALL THROUGH.
228 case Instruction::Add:
Chris Lattner3decde92010-08-18 23:09:49 +0000229 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
Rafael Espindola5f57f462014-02-21 18:34:28 +0000230 DL, Depth+1);
Chris Lattner9f7500f2010-08-18 22:07:29 +0000231 Offset += RHSC->getValue();
232 return V;
233 case Instruction::Mul:
Chris Lattner3decde92010-08-18 23:09:49 +0000234 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
Rafael Espindola5f57f462014-02-21 18:34:28 +0000235 DL, Depth+1);
Chris Lattner9f7500f2010-08-18 22:07:29 +0000236 Offset *= RHSC->getValue();
237 Scale *= RHSC->getValue();
238 return V;
239 case Instruction::Shl:
Chris Lattner3decde92010-08-18 23:09:49 +0000240 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
Rafael Espindola5f57f462014-02-21 18:34:28 +0000241 DL, Depth+1);
Chris Lattner9f7500f2010-08-18 22:07:29 +0000242 Offset <<= RHSC->getValue().getLimitedValue();
243 Scale <<= RHSC->getValue().getLimitedValue();
244 return V;
245 }
246 }
247 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000248
Chris Lattner9f7500f2010-08-18 22:07:29 +0000249 // Since GEP indices are sign extended anyway, we don't care about the high
Chris Lattner3decde92010-08-18 23:09:49 +0000250 // bits of a sign or zero extended value - just scales and offsets. The
251 // extensions have to be consistent though.
252 if ((isa<SExtInst>(V) && Extension != EK_ZeroExt) ||
253 (isa<ZExtInst>(V) && Extension != EK_SignExt)) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000254 Value *CastOp = cast<CastInst>(V)->getOperand(0);
255 unsigned OldWidth = Scale.getBitWidth();
256 unsigned SmallWidth = CastOp->getType()->getPrimitiveSizeInBits();
Jay Foad583abbc2010-12-07 08:25:19 +0000257 Scale = Scale.trunc(SmallWidth);
258 Offset = Offset.trunc(SmallWidth);
Chris Lattner3decde92010-08-18 23:09:49 +0000259 Extension = isa<SExtInst>(V) ? EK_SignExt : EK_ZeroExt;
260
261 Value *Result = GetLinearExpression(CastOp, Scale, Offset, Extension,
Rafael Espindola5f57f462014-02-21 18:34:28 +0000262 DL, Depth+1);
Jay Foad583abbc2010-12-07 08:25:19 +0000263 Scale = Scale.zext(OldWidth);
264 Offset = Offset.zext(OldWidth);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000265
Chris Lattner9f7500f2010-08-18 22:07:29 +0000266 return Result;
267 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000268
Chris Lattner9f7500f2010-08-18 22:07:29 +0000269 Scale = 1;
270 Offset = 0;
271 return V;
272}
273
274/// DecomposeGEPExpression - If V is a symbolic pointer expression, decompose it
275/// into a base pointer with a constant offset and a number of scaled symbolic
276/// offsets.
277///
278/// The scaled symbolic offsets (represented by pairs of a Value* and a scale in
279/// the VarIndices vector) are Value*'s that are known to be scaled by the
280/// specified amount, but which may have other unrepresented high bits. As such,
281/// the gep cannot necessarily be reconstructed from its decomposed form.
282///
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000283/// When DataLayout is around, this function is capable of analyzing everything
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000284/// that GetUnderlyingObject can look through. To be able to do that
285/// GetUnderlyingObject and DecomposeGEPExpression must use the same search
286/// depth (MaxLookupSearchDepth).
287/// When DataLayout not is around, it just looks through pointer casts.
Chris Lattner9f7500f2010-08-18 22:07:29 +0000288///
289static const Value *
290DecomposeGEPExpression(const Value *V, int64_t &BaseOffs,
Chris Lattner1b9c3872010-08-18 22:47:56 +0000291 SmallVectorImpl<VariableGEPIndex> &VarIndices,
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000292 bool &MaxLookupReached, const DataLayout *DL) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000293 // Limit recursion depth to limit compile time in crazy cases.
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000294 unsigned MaxLookup = MaxLookupSearchDepth;
295 MaxLookupReached = false;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000296
Chris Lattner9f7500f2010-08-18 22:07:29 +0000297 BaseOffs = 0;
298 do {
299 // See if this is a bitcast or GEP.
300 const Operator *Op = dyn_cast<Operator>(V);
Craig Topper9f008862014-04-15 04:59:12 +0000301 if (!Op) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000302 // The only non-operator case we can handle are GlobalAliases.
303 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
304 if (!GA->mayBeOverridden()) {
305 V = GA->getAliasee();
306 continue;
307 }
308 }
309 return V;
310 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000311
Matt Arsenault70f4db882014-07-15 00:56:40 +0000312 if (Op->getOpcode() == Instruction::BitCast ||
313 Op->getOpcode() == Instruction::AddrSpaceCast) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000314 V = Op->getOperand(0);
315 continue;
316 }
Dan Gohman05b18f12010-12-15 20:49:55 +0000317
Chris Lattner9f7500f2010-08-18 22:07:29 +0000318 const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
Craig Topper9f008862014-04-15 04:59:12 +0000319 if (!GEPOp) {
Dan Gohman0573b552011-05-24 18:24:08 +0000320 // If it's not a GEP, hand it off to SimplifyInstruction to see if it
321 // can come up with something. This matches what GetUnderlyingObject does.
322 if (const Instruction *I = dyn_cast<Instruction>(V))
323 // TODO: Get a DominatorTree and use it here.
324 if (const Value *Simplified =
Rafael Espindola5f57f462014-02-21 18:34:28 +0000325 SimplifyInstruction(const_cast<Instruction *>(I), DL)) {
Dan Gohman0573b552011-05-24 18:24:08 +0000326 V = Simplified;
327 continue;
328 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000329
Chris Lattner9f7500f2010-08-18 22:07:29 +0000330 return V;
Dan Gohman0573b552011-05-24 18:24:08 +0000331 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000332
Chris Lattner9f7500f2010-08-18 22:07:29 +0000333 // Don't attempt to analyze GEPs over unsized objects.
Matt Arsenaultfa252722013-09-27 22:18:51 +0000334 if (!GEPOp->getOperand(0)->getType()->getPointerElementType()->isSized())
Chris Lattner9f7500f2010-08-18 22:07:29 +0000335 return V;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000336
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000337 // If we are lacking DataLayout information, we can't compute the offets of
Chris Lattner9f7500f2010-08-18 22:07:29 +0000338 // elements computed by GEPs. However, we can handle bitcast equivalent
339 // GEPs.
Craig Topper9f008862014-04-15 04:59:12 +0000340 if (!DL) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000341 if (!GEPOp->hasAllZeroIndices())
342 return V;
343 V = GEPOp->getOperand(0);
344 continue;
345 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000346
Matt Arsenaulta8fe22b2013-11-16 00:36:43 +0000347 unsigned AS = GEPOp->getPointerAddressSpace();
Chris Lattner9f7500f2010-08-18 22:07:29 +0000348 // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
349 gep_type_iterator GTI = gep_type_begin(GEPOp);
350 for (User::const_op_iterator I = GEPOp->op_begin()+1,
351 E = GEPOp->op_end(); I != E; ++I) {
352 Value *Index = *I;
353 // Compute the (potentially symbolic) offset in bytes for this index.
Chris Lattner229907c2011-07-18 04:54:35 +0000354 if (StructType *STy = dyn_cast<StructType>(*GTI++)) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000355 // For a struct, add the member offset.
356 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
357 if (FieldNo == 0) continue;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000358
Rafael Espindola5f57f462014-02-21 18:34:28 +0000359 BaseOffs += DL->getStructLayout(STy)->getElementOffset(FieldNo);
Chris Lattner9f7500f2010-08-18 22:07:29 +0000360 continue;
361 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000362
Chris Lattner9f7500f2010-08-18 22:07:29 +0000363 // For an array/pointer, add the element offset, explicitly scaled.
364 if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
365 if (CIdx->isZero()) continue;
Rafael Espindola5f57f462014-02-21 18:34:28 +0000366 BaseOffs += DL->getTypeAllocSize(*GTI)*CIdx->getSExtValue();
Chris Lattner9f7500f2010-08-18 22:07:29 +0000367 continue;
368 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000369
Rafael Espindola5f57f462014-02-21 18:34:28 +0000370 uint64_t Scale = DL->getTypeAllocSize(*GTI);
Chris Lattner1b9c3872010-08-18 22:47:56 +0000371 ExtensionKind Extension = EK_NotExtended;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000372
Chris Lattner3decde92010-08-18 23:09:49 +0000373 // If the integer type is smaller than the pointer size, it is implicitly
374 // sign extended to pointer size.
Matt Arsenaultfa252722013-09-27 22:18:51 +0000375 unsigned Width = Index->getType()->getIntegerBitWidth();
Rafael Espindola5f57f462014-02-21 18:34:28 +0000376 if (DL->getPointerSizeInBits(AS) > Width)
Chris Lattner3decde92010-08-18 23:09:49 +0000377 Extension = EK_SignExt;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000378
Chris Lattner3decde92010-08-18 23:09:49 +0000379 // Use GetLinearExpression to decompose the index into a C1*V+C2 form.
Chris Lattner9f7500f2010-08-18 22:07:29 +0000380 APInt IndexScale(Width, 0), IndexOffset(Width, 0);
Chris Lattner3decde92010-08-18 23:09:49 +0000381 Index = GetLinearExpression(Index, IndexScale, IndexOffset, Extension,
Rafael Espindola5f57f462014-02-21 18:34:28 +0000382 *DL, 0);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000383
Chris Lattner9f7500f2010-08-18 22:07:29 +0000384 // The GEP index scale ("Scale") scales C1*V+C2, yielding (C1*V+C2)*Scale.
385 // This gives us an aggregate computation of (C1*Scale)*V + C2*Scale.
Eli Friedmanab3a1282010-09-15 20:08:03 +0000386 BaseOffs += IndexOffset.getSExtValue()*Scale;
387 Scale *= IndexScale.getSExtValue();
Jakub Staszak07f383f2013-08-24 14:16:00 +0000388
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000389 // If we already had an occurrence of this index variable, merge this
Chris Lattner9f7500f2010-08-18 22:07:29 +0000390 // scale into it. For example, we want to handle:
391 // A[x][x] -> x*16 + x*4 -> x*20
392 // This also ensures that 'x' only appears in the index list once.
393 for (unsigned i = 0, e = VarIndices.size(); i != e; ++i) {
Chris Lattner1b9c3872010-08-18 22:47:56 +0000394 if (VarIndices[i].V == Index &&
395 VarIndices[i].Extension == Extension) {
396 Scale += VarIndices[i].Scale;
Chris Lattner9f7500f2010-08-18 22:07:29 +0000397 VarIndices.erase(VarIndices.begin()+i);
398 break;
399 }
400 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000401
Chris Lattner9f7500f2010-08-18 22:07:29 +0000402 // Make sure that we have a scale that makes sense for this target's
403 // pointer size.
Rafael Espindola5f57f462014-02-21 18:34:28 +0000404 if (unsigned ShiftBits = 64 - DL->getPointerSizeInBits(AS)) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000405 Scale <<= ShiftBits;
Eli Friedmanab3a1282010-09-15 20:08:03 +0000406 Scale = (int64_t)Scale >> ShiftBits;
Chris Lattner9f7500f2010-08-18 22:07:29 +0000407 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000408
Chris Lattner1b9c3872010-08-18 22:47:56 +0000409 if (Scale) {
Jeffrey Yasskin6381c012011-07-27 06:22:51 +0000410 VariableGEPIndex Entry = {Index, Extension,
411 static_cast<int64_t>(Scale)};
Chris Lattner1b9c3872010-08-18 22:47:56 +0000412 VarIndices.push_back(Entry);
413 }
Chris Lattner9f7500f2010-08-18 22:07:29 +0000414 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000415
Chris Lattner9f7500f2010-08-18 22:07:29 +0000416 // Analyze the base pointer next.
417 V = GEPOp->getOperand(0);
418 } while (--MaxLookup);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000419
Chris Lattner9f7500f2010-08-18 22:07:29 +0000420 // If the chain of expressions is too deep, just return early.
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000421 MaxLookupReached = true;
Chris Lattner9f7500f2010-08-18 22:07:29 +0000422 return V;
423}
424
Chris Lattner9f7500f2010-08-18 22:07:29 +0000425//===----------------------------------------------------------------------===//
Dan Gohman0824aff2010-06-29 00:50:39 +0000426// BasicAliasAnalysis Pass
Chris Lattner2d332972008-06-16 06:30:22 +0000427//===----------------------------------------------------------------------===//
428
Dan Gohman00ef9322010-07-07 14:27:09 +0000429#ifndef NDEBUG
Dan Gohman0824aff2010-06-29 00:50:39 +0000430static const Function *getParent(const Value *V) {
Dan Gohman1be9e7c2010-06-29 18:12:34 +0000431 if (const Instruction *inst = dyn_cast<Instruction>(V))
Dan Gohman0824aff2010-06-29 00:50:39 +0000432 return inst->getParent()->getParent();
433
Dan Gohman1be9e7c2010-06-29 18:12:34 +0000434 if (const Argument *arg = dyn_cast<Argument>(V))
Dan Gohman0824aff2010-06-29 00:50:39 +0000435 return arg->getParent();
436
Craig Topper9f008862014-04-15 04:59:12 +0000437 return nullptr;
Dan Gohman0824aff2010-06-29 00:50:39 +0000438}
439
Dan Gohman84f90a32010-07-01 20:08:40 +0000440static bool notDifferentParent(const Value *O1, const Value *O2) {
441
442 const Function *F1 = getParent(O1);
443 const Function *F2 = getParent(O2);
444
Dan Gohman0824aff2010-06-29 00:50:39 +0000445 return !F1 || !F2 || F1 == F2;
446}
Benjamin Kramer80b7bc02010-06-29 10:03:11 +0000447#endif
Dan Gohman0824aff2010-06-29 00:50:39 +0000448
Chris Lattner2d332972008-06-16 06:30:22 +0000449namespace {
Dan Gohmanda85ed82010-10-19 23:09:08 +0000450 /// BasicAliasAnalysis - This is the primary alias analysis implementation.
451 struct BasicAliasAnalysis : public ImmutablePass, public AliasAnalysis {
Chris Lattner2d332972008-06-16 06:30:22 +0000452 static char ID; // Class identification, replacement for typeinfo
Benjamin Kramer6c2649c2012-09-05 16:49:37 +0000453 BasicAliasAnalysis() : ImmutablePass(ID) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000454 initializeBasicAliasAnalysisPass(*PassRegistry::getPassRegistry());
455 }
Dan Gohman0824aff2010-06-29 00:50:39 +0000456
Craig Toppere9ba7592014-03-05 07:30:04 +0000457 void initializePass() override {
Dan Gohman02538ac2010-10-18 18:04:47 +0000458 InitializeAliasAnalysis(this);
459 }
460
Craig Toppere9ba7592014-03-05 07:30:04 +0000461 void getAnalysisUsage(AnalysisUsage &AU) const override {
Dan Gohman02538ac2010-10-18 18:04:47 +0000462 AU.addRequired<AliasAnalysis>();
Owen Anderson653cb032011-09-06 23:33:25 +0000463 AU.addRequired<TargetLibraryInfo>();
Dan Gohman02538ac2010-10-18 18:04:47 +0000464 }
465
Craig Toppere9ba7592014-03-05 07:30:04 +0000466 AliasResult alias(const Location &LocA, const Location &LocB) override {
Dan Gohmanfb02cec2011-06-04 00:31:50 +0000467 assert(AliasCache.empty() && "AliasCache must be cleared after use!");
Dan Gohman41f14cf2010-09-14 21:25:10 +0000468 assert(notDifferentParent(LocA.Ptr, LocB.Ptr) &&
Dan Gohman00ef9322010-07-07 14:27:09 +0000469 "BasicAliasAnalysis doesn't support interprocedural queries.");
Dan Gohmanf3702452010-10-18 18:45:11 +0000470 AliasResult Alias = aliasCheck(LocA.Ptr, LocA.Size, LocA.TBAATag,
471 LocB.Ptr, LocB.Size, LocB.TBAATag);
Benjamin Kramer6c2649c2012-09-05 16:49:37 +0000472 // AliasCache rarely has more than 1 or 2 elements, always use
473 // shrink_and_clear so it quickly returns to the inline capacity of the
474 // SmallDenseMap if it ever grows larger.
475 // FIXME: This should really be shrink_to_inline_capacity_and_clear().
476 AliasCache.shrink_and_clear();
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +0000477 VisitedPhiBBs.clear();
Evan Chengb3ccb642009-10-14 06:46:26 +0000478 return Alias;
Evan Chengc10e88d2009-10-13 22:02:20 +0000479 }
Chris Lattner2d332972008-06-16 06:30:22 +0000480
Craig Toppere9ba7592014-03-05 07:30:04 +0000481 ModRefResult getModRefInfo(ImmutableCallSite CS,
482 const Location &Loc) override;
Dan Gohman5f1702e2010-08-06 01:25:49 +0000483
Craig Toppere9ba7592014-03-05 07:30:04 +0000484 ModRefResult getModRefInfo(ImmutableCallSite CS1,
485 ImmutableCallSite CS2) override {
Dan Gohman5f1702e2010-08-06 01:25:49 +0000486 // The AliasAnalysis base class has some smarts, lets use them.
487 return AliasAnalysis::getModRefInfo(CS1, CS2);
488 }
Owen Anderson98a36172009-02-05 23:36:27 +0000489
Chris Lattner2d332972008-06-16 06:30:22 +0000490 /// pointsToConstantMemory - Chase pointers until we find a (constant
491 /// global) or not.
Craig Toppere9ba7592014-03-05 07:30:04 +0000492 bool pointsToConstantMemory(const Location &Loc, bool OrLocal) override;
Dan Gohman5f1702e2010-08-06 01:25:49 +0000493
494 /// getModRefBehavior - Return the behavior when calling the given
495 /// call site.
Craig Toppere9ba7592014-03-05 07:30:04 +0000496 ModRefBehavior getModRefBehavior(ImmutableCallSite CS) override;
Dan Gohman5f1702e2010-08-06 01:25:49 +0000497
498 /// getModRefBehavior - Return the behavior when calling the given function.
499 /// For use when the call site is not known.
Craig Toppere9ba7592014-03-05 07:30:04 +0000500 ModRefBehavior getModRefBehavior(const Function *F) override;
Chris Lattner2d332972008-06-16 06:30:22 +0000501
Chris Lattneraf362f02010-01-20 19:26:14 +0000502 /// getAdjustedAnalysisPointer - This method is used when a pass implements
Dan Gohmane0d5c452010-08-05 23:48:14 +0000503 /// an analysis interface through multiple inheritance. If needed, it
504 /// should override this to adjust the this pointer as needed for the
505 /// specified pass info.
Craig Toppere9ba7592014-03-05 07:30:04 +0000506 void *getAdjustedAnalysisPointer(const void *ID) override {
Owen Andersona7aed182010-08-06 18:33:48 +0000507 if (ID == &AliasAnalysis::ID)
Chris Lattneraf362f02010-01-20 19:26:14 +0000508 return (AliasAnalysis*)this;
509 return this;
510 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000511
Chris Lattner2d332972008-06-16 06:30:22 +0000512 private:
Dan Gohmanfb02cec2011-06-04 00:31:50 +0000513 // AliasCache - Track alias queries to guard against recursion.
514 typedef std::pair<Location, Location> LocPair;
Benjamin Kramer6c2649c2012-09-05 16:49:37 +0000515 typedef SmallDenseMap<LocPair, AliasResult, 8> AliasCacheTy;
Dan Gohmanfb02cec2011-06-04 00:31:50 +0000516 AliasCacheTy AliasCache;
517
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +0000518 /// \brief Track phi nodes we have visited. When interpret "Value" pointer
519 /// equality as value equality we need to make sure that the "Value" is not
520 /// part of a cycle. Otherwise, two uses could come from different
521 /// "iterations" of a cycle and see different values for the same "Value"
522 /// pointer.
523 /// The following example shows the problem:
524 /// %p = phi(%alloca1, %addr2)
525 /// %l = load %ptr
526 /// %addr1 = gep, %alloca2, 0, %l
527 /// %addr2 = gep %alloca2, 0, (%l + 1)
528 /// alias(%p, %addr1) -> MayAlias !
529 /// store %l, ...
530 SmallPtrSet<const BasicBlock*, 8> VisitedPhiBBs;
531
Dan Gohmanfb02cec2011-06-04 00:31:50 +0000532 // Visited - Track instructions visited by pointsToConstantMemory.
Dan Gohman7c34ece2010-06-28 21:16:52 +0000533 SmallPtrSet<const Value*, 16> Visited;
Evan Cheng31565b32009-10-14 05:05:02 +0000534
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +0000535 /// \brief Check whether two Values can be considered equivalent.
536 ///
537 /// In addition to pointer equivalence of \p V1 and \p V2 this checks
538 /// whether they can not be part of a cycle in the value graph by looking at
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +0000539 /// all visited phi nodes an making sure that the phis cannot reach the
540 /// value. We have to do this because we are looking through phi nodes (That
541 /// is we say noalias(V, phi(VA, VB)) if noalias(V, VA) and noalias(V, VB).
542 bool isValueEqualInPotentialCycles(const Value *V1, const Value *V2);
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +0000543
544 /// \brief Dest and Src are the variable indices from two decomposed
545 /// GetElementPtr instructions GEP1 and GEP2 which have common base
546 /// pointers. Subtract the GEP2 indices from GEP1 to find the symbolic
547 /// difference between the two pointers.
548 void GetIndexDifference(SmallVectorImpl<VariableGEPIndex> &Dest,
549 const SmallVectorImpl<VariableGEPIndex> &Src);
550
Chris Lattner98e253262009-11-23 16:45:27 +0000551 // aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP
552 // instruction against another.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000553 AliasResult aliasGEP(const GEPOperator *V1, uint64_t V1Size,
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000554 const MDNode *V1TBAAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +0000555 const Value *V2, uint64_t V2Size,
Dan Gohmanf3702452010-10-18 18:45:11 +0000556 const MDNode *V2TBAAInfo,
Chris Lattner5341c962009-11-26 02:14:59 +0000557 const Value *UnderlyingV1, const Value *UnderlyingV2);
Evan Chengc10e88d2009-10-13 22:02:20 +0000558
Chris Lattner98e253262009-11-23 16:45:27 +0000559 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI
560 // instruction against another.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000561 AliasResult aliasPHI(const PHINode *PN, uint64_t PNSize,
Dan Gohmanf3702452010-10-18 18:45:11 +0000562 const MDNode *PNTBAAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +0000563 const Value *V2, uint64_t V2Size,
Dan Gohmanf3702452010-10-18 18:45:11 +0000564 const MDNode *V2TBAAInfo);
Evan Chengc10e88d2009-10-13 22:02:20 +0000565
Dan Gohman3b7ba5f2009-10-26 21:55:43 +0000566 /// aliasSelect - Disambiguate a Select instruction against another value.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000567 AliasResult aliasSelect(const SelectInst *SI, uint64_t SISize,
Dan Gohmanf3702452010-10-18 18:45:11 +0000568 const MDNode *SITBAAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +0000569 const Value *V2, uint64_t V2Size,
Dan Gohmanf3702452010-10-18 18:45:11 +0000570 const MDNode *V2TBAAInfo);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +0000571
Dan Gohmanf372cf82010-10-19 22:54:46 +0000572 AliasResult aliasCheck(const Value *V1, uint64_t V1Size,
Dan Gohmanf3702452010-10-18 18:45:11 +0000573 const MDNode *V1TBAATag,
Dan Gohmanf372cf82010-10-19 22:54:46 +0000574 const Value *V2, uint64_t V2Size,
Dan Gohmanf3702452010-10-18 18:45:11 +0000575 const MDNode *V2TBAATag);
Chris Lattner2d332972008-06-16 06:30:22 +0000576 };
577} // End of anonymous namespace
578
579// Register this pass...
580char BasicAliasAnalysis::ID = 0;
Owen Anderson653cb032011-09-06 23:33:25 +0000581INITIALIZE_AG_PASS_BEGIN(BasicAliasAnalysis, AliasAnalysis, "basicaa",
Dan Gohmanda85ed82010-10-19 23:09:08 +0000582 "Basic Alias Analysis (stateless AA impl)",
Dan Gohman02538ac2010-10-18 18:04:47 +0000583 false, true, false)
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
Dan Gohman5f1702e2010-08-06 01:25:49 +0000657/// getModRefBehavior - Return the behavior when calling the given call site.
658AliasAnalysis::ModRefBehavior
659BasicAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
660 if (CS.doesNotAccessMemory())
661 // Can't do better than this.
662 return DoesNotAccessMemory;
663
664 ModRefBehavior Min = UnknownModRefBehavior;
665
666 // If the callsite knows it only reads memory, don't return worse
667 // than that.
668 if (CS.onlyReadsMemory())
669 Min = OnlyReadsMemory;
670
671 // The AliasAnalysis base class has some smarts, lets use them.
Dan Gohman2694e142010-11-10 01:02:18 +0000672 return ModRefBehavior(AliasAnalysis::getModRefBehavior(CS) & Min);
Dan Gohman5f1702e2010-08-06 01:25:49 +0000673}
674
675/// getModRefBehavior - Return the behavior when calling the given function.
676/// For use when the call site is not known.
677AliasAnalysis::ModRefBehavior
678BasicAliasAnalysis::getModRefBehavior(const Function *F) {
Dan Gohmane461d7d2010-11-08 16:08:43 +0000679 // If the function declares it doesn't access memory, we can't do better.
Dan Gohman5f1702e2010-08-06 01:25:49 +0000680 if (F->doesNotAccessMemory())
Dan Gohman5f1702e2010-08-06 01:25:49 +0000681 return DoesNotAccessMemory;
Dan Gohmane461d7d2010-11-08 16:08:43 +0000682
683 // For intrinsics, we can check the table.
684 if (unsigned iid = F->getIntrinsicID()) {
685#define GET_INTRINSIC_MODREF_BEHAVIOR
Chandler Carruthdb25c6c2013-01-02 12:09:16 +0000686#include "llvm/IR/Intrinsics.gen"
Dan Gohmane461d7d2010-11-08 16:08:43 +0000687#undef GET_INTRINSIC_MODREF_BEHAVIOR
688 }
689
Dan Gohman2694e142010-11-10 01:02:18 +0000690 ModRefBehavior Min = UnknownModRefBehavior;
691
Dan Gohmane461d7d2010-11-08 16:08:43 +0000692 // If the function declares it only reads memory, go with that.
Dan Gohman5f1702e2010-08-06 01:25:49 +0000693 if (F->onlyReadsMemory())
Dan Gohman2694e142010-11-10 01:02:18 +0000694 Min = OnlyReadsMemory;
Dan Gohman5f1702e2010-08-06 01:25:49 +0000695
Dan Gohmane461d7d2010-11-08 16:08:43 +0000696 // Otherwise be conservative.
Dan Gohman2694e142010-11-10 01:02:18 +0000697 return ModRefBehavior(AliasAnalysis::getModRefBehavior(F) & Min);
Dan Gohman5f1702e2010-08-06 01:25:49 +0000698}
Owen Anderson98a36172009-02-05 23:36:27 +0000699
Chris Lattner98e253262009-11-23 16:45:27 +0000700/// getModRefInfo - Check to see if the specified callsite can clobber the
701/// specified memory object. Since we only look at local properties of this
702/// function, we really can't say much about this query. We do, however, use
703/// simple "address taken" analysis on local objects.
Chris Lattner2d332972008-06-16 06:30:22 +0000704AliasAnalysis::ModRefResult
Dan Gohman5442c712010-08-03 21:48:53 +0000705BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS,
Dan Gohman41f14cf2010-09-14 21:25:10 +0000706 const Location &Loc) {
707 assert(notDifferentParent(CS.getInstruction(), Loc.Ptr) &&
Dan Gohman00ef9322010-07-07 14:27:09 +0000708 "AliasAnalysis query involving multiple functions!");
709
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000710 const Value *Object = GetUnderlyingObject(Loc.Ptr, DL);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000711
Dan Gohman41f14cf2010-09-14 21:25:10 +0000712 // If this is a tail call and Loc.Ptr points to a stack location, we know that
Chris Lattnerd6a49ad2009-11-22 16:05:05 +0000713 // the tail call cannot access or modify the local stack.
714 // We cannot exclude byval arguments here; these belong to the caller of
715 // the current function not to the current function, and a tail callee
716 // may reference them.
717 if (isa<AllocaInst>(Object))
Dan Gohman5442c712010-08-03 21:48:53 +0000718 if (const CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
Chris Lattnerd6a49ad2009-11-22 16:05:05 +0000719 if (CI->isTailCall())
720 return NoModRef;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000721
Chris Lattnerd6a49ad2009-11-22 16:05:05 +0000722 // If the pointer is to a locally allocated object that does not escape,
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000723 // then the call can not mod/ref the pointer unless the call takes the pointer
724 // as an argument, and itself doesn't capture it.
Chris Lattner1e7b37e2009-11-23 16:46:41 +0000725 if (!isa<Constant>(Object) && CS.getInstruction() != Object &&
Dan Gohman84f90a32010-07-01 20:08:40 +0000726 isNonEscapingLocalObject(Object)) {
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000727 bool PassedAsArg = false;
728 unsigned ArgNo = 0;
Dan Gohman5442c712010-08-03 21:48:53 +0000729 for (ImmutableCallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000730 CI != CE; ++CI, ++ArgNo) {
Chris Lattner026f5e62011-05-23 05:15:43 +0000731 // Only look at the no-capture or byval pointer arguments. If this
732 // pointer were passed to arguments that were neither of these, then it
733 // couldn't be no-capture.
Duncan Sands19d0b472010-02-16 11:11:14 +0000734 if (!(*CI)->getType()->isPointerTy() ||
Nick Lewycky612d70b2011-11-20 19:09:04 +0000735 (!CS.doesNotCapture(ArgNo) && !CS.isByValArgument(ArgNo)))
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000736 continue;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000737
Dan Gohman41f14cf2010-09-14 21:25:10 +0000738 // If this is a no-capture pointer argument, see if we can tell that it
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000739 // is impossible to alias the pointer we're checking. If not, we have to
740 // assume that the call could touch the pointer, even though it doesn't
741 // escape.
Eli Friedman5f476dc2011-09-28 00:34:27 +0000742 if (!isNoAlias(Location(*CI), Location(Object))) {
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000743 PassedAsArg = true;
744 break;
745 }
746 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000747
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000748 if (!PassedAsArg)
Chris Lattnerd6a49ad2009-11-22 16:05:05 +0000749 return NoModRef;
750 }
751
Nick Lewycky7a63c3b2014-07-15 00:53:38 +0000752 const TargetLibraryInfo &TLI = getAnalysis<TargetLibraryInfo>();
753 ModRefResult Min = ModRef;
754
755 // Finally, handle specific knowledge of intrinsics.
756 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
757 if (II != nullptr)
758 switch (II->getIntrinsicID()) {
759 default: break;
760 case Intrinsic::memcpy:
761 case Intrinsic::memmove: {
762 uint64_t Len = UnknownSize;
763 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getArgOperand(2)))
764 Len = LenCI->getZExtValue();
765 Value *Dest = II->getArgOperand(0);
766 Value *Src = II->getArgOperand(1);
767 // If it can't overlap the source dest, then it doesn't modref the loc.
768 if (isNoAlias(Location(Dest, Len), Loc)) {
769 if (isNoAlias(Location(Src, Len), Loc))
770 return NoModRef;
771 // If it can't overlap the dest, then worst case it reads the loc.
772 Min = Ref;
773 } else if (isNoAlias(Location(Src, Len), Loc)) {
774 // If it can't overlap the source, then worst case it mutates the loc.
775 Min = Mod;
776 }
777 break;
778 }
779 case Intrinsic::memset:
780 // Since memset is 'accesses arguments' only, the AliasAnalysis base class
781 // will handle it for the variable length case.
782 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
783 uint64_t Len = LenCI->getZExtValue();
784 Value *Dest = II->getArgOperand(0);
785 if (isNoAlias(Location(Dest, Len), Loc))
786 return NoModRef;
787 }
788 // We know that memset doesn't load anything.
789 Min = Mod;
790 break;
791 case Intrinsic::lifetime_start:
792 case Intrinsic::lifetime_end:
793 case Intrinsic::invariant_start: {
794 uint64_t PtrSize =
795 cast<ConstantInt>(II->getArgOperand(0))->getZExtValue();
796 if (isNoAlias(Location(II->getArgOperand(1),
797 PtrSize,
798 II->getMetadata(LLVMContext::MD_tbaa)),
799 Loc))
800 return NoModRef;
801 break;
802 }
803 case Intrinsic::invariant_end: {
804 uint64_t PtrSize =
805 cast<ConstantInt>(II->getArgOperand(1))->getZExtValue();
806 if (isNoAlias(Location(II->getArgOperand(2),
807 PtrSize,
808 II->getMetadata(LLVMContext::MD_tbaa)),
809 Loc))
810 return NoModRef;
811 break;
812 }
813 case Intrinsic::arm_neon_vld1: {
814 // LLVM's vld1 and vst1 intrinsics currently only support a single
815 // vector register.
816 uint64_t Size =
817 DL ? DL->getTypeStoreSize(II->getType()) : UnknownSize;
818 if (isNoAlias(Location(II->getArgOperand(0), Size,
819 II->getMetadata(LLVMContext::MD_tbaa)),
820 Loc))
821 return NoModRef;
822 break;
823 }
824 case Intrinsic::arm_neon_vst1: {
825 uint64_t Size =
826 DL ? DL->getTypeStoreSize(II->getArgOperand(1)->getType()) : UnknownSize;
827 if (isNoAlias(Location(II->getArgOperand(0), Size,
828 II->getMetadata(LLVMContext::MD_tbaa)),
829 Loc))
830 return NoModRef;
831 break;
832 }
833 }
834
835 // We can bound the aliasing properties of memset_pattern16 just as we can
836 // for memcpy/memset. This is particularly important because the
837 // LoopIdiomRecognizer likes to turn loops into calls to memset_pattern16
838 // whenever possible.
839 else if (TLI.has(LibFunc::memset_pattern16) &&
840 CS.getCalledFunction() &&
841 CS.getCalledFunction()->getName() == "memset_pattern16") {
842 const Function *MS = CS.getCalledFunction();
843 FunctionType *MemsetType = MS->getFunctionType();
844 if (!MemsetType->isVarArg() && MemsetType->getNumParams() == 3 &&
845 isa<PointerType>(MemsetType->getParamType(0)) &&
846 isa<PointerType>(MemsetType->getParamType(1)) &&
847 isa<IntegerType>(MemsetType->getParamType(2))) {
848 uint64_t Len = UnknownSize;
849 if (const ConstantInt *LenCI = dyn_cast<ConstantInt>(CS.getArgument(2)))
850 Len = LenCI->getZExtValue();
851 const Value *Dest = CS.getArgument(0);
852 const Value *Src = CS.getArgument(1);
853 // If it can't overlap the source dest, then it doesn't modref the loc.
854 if (isNoAlias(Location(Dest, Len), Loc)) {
855 // Always reads 16 bytes of the source.
856 if (isNoAlias(Location(Src, 16), Loc))
857 return NoModRef;
858 // If it can't overlap the dest, then worst case it reads the loc.
859 Min = Ref;
860 // Always reads 16 bytes of the source.
861 } else if (isNoAlias(Location(Src, 16), Loc)) {
862 // If it can't overlap the source, then worst case it mutates the loc.
863 Min = Mod;
864 }
865 }
866 }
867
Chris Lattner2d332972008-06-16 06:30:22 +0000868 // The AliasAnalysis base class has some smarts, lets use them.
Nick Lewycky7a63c3b2014-07-15 00:53:38 +0000869 return ModRefResult(AliasAnalysis::getModRefInfo(CS, Loc) & Min);
Dan Gohman64d842e2010-09-08 01:32:20 +0000870}
Chris Lattner2d332972008-06-16 06:30:22 +0000871
Chris Lattnera99edbe2009-11-26 02:11:08 +0000872/// aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
873/// against another pointer. We know that V1 is a GEP, but we don't know
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000874/// anything about V2. UnderlyingV1 is GetUnderlyingObject(GEP1, DL),
Chris Lattner5341c962009-11-26 02:14:59 +0000875/// UnderlyingV2 is the same for V2.
Chris Lattnera99edbe2009-11-26 02:11:08 +0000876///
Chris Lattnerd6a2a992003-02-26 19:41:54 +0000877AliasAnalysis::AliasResult
Dan Gohmanf372cf82010-10-19 22:54:46 +0000878BasicAliasAnalysis::aliasGEP(const GEPOperator *GEP1, uint64_t V1Size,
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000879 const MDNode *V1TBAAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +0000880 const Value *V2, uint64_t V2Size,
Dan Gohmanf3702452010-10-18 18:45:11 +0000881 const MDNode *V2TBAAInfo,
Chris Lattner5341c962009-11-26 02:14:59 +0000882 const Value *UnderlyingV1,
883 const Value *UnderlyingV2) {
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000884 int64_t GEP1BaseOffset;
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000885 bool GEP1MaxLookupReached;
Chris Lattner1b9c3872010-08-18 22:47:56 +0000886 SmallVector<VariableGEPIndex, 4> GEP1VariableIndices;
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000887
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000888 // If we have two gep instructions with must-alias or not-alias'ing base
889 // pointers, figure out if the indexes to the GEP tell us anything about the
890 // derived pointer.
Chris Lattnera99edbe2009-11-26 02:11:08 +0000891 if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
Arnold Schwaighoferaadf1042013-03-26 18:07:53 +0000892 // Do the base pointers alias?
Craig Topper9f008862014-04-15 04:59:12 +0000893 AliasResult BaseAlias = aliasCheck(UnderlyingV1, UnknownSize, nullptr,
894 UnderlyingV2, UnknownSize, nullptr);
Arnold Schwaighoferaadf1042013-03-26 18:07:53 +0000895
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000896 // Check for geps of non-aliasing underlying pointers where the offsets are
897 // identical.
Arnold Schwaighoferaadf1042013-03-26 18:07:53 +0000898 if ((BaseAlias == MayAlias) && V1Size == V2Size) {
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000899 // Do the base pointers alias assuming type and size.
900 AliasResult PreciseBaseAlias = aliasCheck(UnderlyingV1, V1Size,
901 V1TBAAInfo, UnderlyingV2,
902 V2Size, V2TBAAInfo);
903 if (PreciseBaseAlias == NoAlias) {
904 // See if the computed offset from the common pointer tells us about the
905 // relation of the resulting pointer.
906 int64_t GEP2BaseOffset;
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000907 bool GEP2MaxLookupReached;
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000908 SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
909 const Value *GEP2BasePtr =
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000910 DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices,
911 GEP2MaxLookupReached, DL);
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000912 const Value *GEP1BasePtr =
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000913 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
914 GEP1MaxLookupReached, DL);
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000915 // DecomposeGEPExpression and GetUnderlyingObject should return the
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000916 // same result except when DecomposeGEPExpression has no DataLayout.
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000917 if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
Craig Topper9f008862014-04-15 04:59:12 +0000918 assert(!DL &&
919 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000920 return MayAlias;
921 }
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000922 // If the max search depth is reached the result is undefined
923 if (GEP2MaxLookupReached || GEP1MaxLookupReached)
924 return MayAlias;
925
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000926 // Same offsets.
927 if (GEP1BaseOffset == GEP2BaseOffset &&
Benjamin Kramer147644d2014-04-18 19:48:03 +0000928 GEP1VariableIndices == GEP2VariableIndices)
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000929 return NoAlias;
930 GEP1VariableIndices.clear();
931 }
932 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000933
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000934 // If we get a No or May, then return it immediately, no amount of analysis
935 // will improve this situation.
936 if (BaseAlias != MustAlias) return BaseAlias;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000937
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000938 // Otherwise, we have a MustAlias. Since the base pointers alias each other
939 // exactly, see if the computed offset from the common pointer tells us
940 // about the relation of the resulting pointer.
941 const Value *GEP1BasePtr =
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000942 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
943 GEP1MaxLookupReached, DL);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000944
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000945 int64_t GEP2BaseOffset;
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000946 bool GEP2MaxLookupReached;
Chris Lattner1b9c3872010-08-18 22:47:56 +0000947 SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000948 const Value *GEP2BasePtr =
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000949 DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices,
950 GEP2MaxLookupReached, DL);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000951
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000952 // DecomposeGEPExpression and GetUnderlyingObject should return the
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000953 // same result except when DecomposeGEPExpression has no DataLayout.
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000954 if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
Craig Topper9f008862014-04-15 04:59:12 +0000955 assert(!DL &&
Dan Gohmana4fcd242010-12-15 20:02:24 +0000956 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000957 return MayAlias;
958 }
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000959 // If the max search depth is reached the result is undefined
960 if (GEP2MaxLookupReached || GEP1MaxLookupReached)
961 return MayAlias;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000962
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000963 // Subtract the GEP2 pointer from the GEP1 pointer to find out their
964 // symbolic difference.
965 GEP1BaseOffset -= GEP2BaseOffset;
Dan Gohmanad867b02010-08-03 20:23:52 +0000966 GetIndexDifference(GEP1VariableIndices, GEP2VariableIndices);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000967
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000968 } else {
969 // Check to see if these two pointers are related by the getelementptr
970 // instruction. If one pointer is a GEP with a non-zero index of the other
971 // pointer, we know they cannot alias.
Chris Lattner5c1cfc22009-11-26 16:52:32 +0000972
973 // If both accesses are unknown size, we can't do anything useful here.
Dan Gohman2a190082010-08-03 01:03:11 +0000974 if (V1Size == UnknownSize && V2Size == UnknownSize)
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000975 return MayAlias;
Chris Lattner6ea17f77f2003-12-11 22:44:13 +0000976
Craig Topper9f008862014-04-15 04:59:12 +0000977 AliasResult R = aliasCheck(UnderlyingV1, UnknownSize, nullptr,
Dan Gohmanf3702452010-10-18 18:45:11 +0000978 V2, V2Size, V2TBAAInfo);
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000979 if (R != MustAlias)
980 // If V2 may alias GEP base pointer, conservatively returns MayAlias.
981 // If V2 is known not to alias GEP base pointer, then the two values
982 // cannot alias per GEP semantics: "A pointer value formed from a
983 // getelementptr instruction is associated with the addresses associated
984 // with the first operand of the getelementptr".
985 return R;
Chris Lattner6ea17f77f2003-12-11 22:44:13 +0000986
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000987 const Value *GEP1BasePtr =
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000988 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
989 GEP1MaxLookupReached, DL);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000990
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000991 // DecomposeGEPExpression and GetUnderlyingObject should return the
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000992 // same result except when DecomposeGEPExpression has no DataLayout.
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000993 if (GEP1BasePtr != UnderlyingV1) {
Craig Topper9f008862014-04-15 04:59:12 +0000994 assert(!DL &&
Dan Gohmana4fcd242010-12-15 20:02:24 +0000995 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000996 return MayAlias;
Chris Lattner6ea17f77f2003-12-11 22:44:13 +0000997 }
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000998 // If the max search depth is reached the result is undefined
999 if (GEP1MaxLookupReached)
1000 return MayAlias;
Chris Lattner6ea17f77f2003-12-11 22:44:13 +00001001 }
Jakub Staszak07f383f2013-08-24 14:16:00 +00001002
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001003 // In the two GEP Case, if there is no difference in the offsets of the
1004 // computed pointers, the resultant pointers are a must alias. This
1005 // hapens when we have two lexically identical GEP's (for example).
Chris Lattnerd6a2a992003-02-26 19:41:54 +00001006 //
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001007 // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
1008 // must aliases the GEP, the end result is a must alias also.
1009 if (GEP1BaseOffset == 0 && GEP1VariableIndices.empty())
Evan Chengc1eed9d2009-10-14 06:41:49 +00001010 return MustAlias;
Evan Chengf1f3dd32009-10-13 18:42:04 +00001011
Eli Friedman3d1b3072011-09-08 02:23:31 +00001012 // If there is a constant difference between the pointers, but the difference
1013 // is less than the size of the associated memory object, then we know
1014 // that the objects are partially overlapping. If the difference is
1015 // greater, we know they do not overlap.
Dan Gohmanc4bf5ca2010-12-13 22:50:24 +00001016 if (GEP1BaseOffset != 0 && GEP1VariableIndices.empty()) {
Eli Friedman3d1b3072011-09-08 02:23:31 +00001017 if (GEP1BaseOffset >= 0) {
1018 if (V2Size != UnknownSize) {
1019 if ((uint64_t)GEP1BaseOffset < V2Size)
1020 return PartialAlias;
1021 return NoAlias;
1022 }
1023 } else {
Arnold Schwaighofere3ac0992014-01-16 04:53:18 +00001024 // We have the situation where:
1025 // + +
1026 // | BaseOffset |
1027 // ---------------->|
1028 // |-->V1Size |-------> V2Size
1029 // GEP1 V2
1030 // We need to know that V2Size is not unknown, otherwise we might have
1031 // stripped a gep with negative index ('gep <ptr>, -1, ...).
1032 if (V1Size != UnknownSize && V2Size != UnknownSize) {
Eli Friedman3d1b3072011-09-08 02:23:31 +00001033 if (-(uint64_t)GEP1BaseOffset < V1Size)
1034 return PartialAlias;
1035 return NoAlias;
1036 }
1037 }
Dan Gohmanc4bf5ca2010-12-13 22:50:24 +00001038 }
1039
Eli Friedman3d1b3072011-09-08 02:23:31 +00001040 // Try to distinguish something like &A[i][1] against &A[42][0].
1041 // Grab the least significant bit set in any of the scales.
Eli Friedmanb78ac542011-09-08 02:37:07 +00001042 if (!GEP1VariableIndices.empty()) {
1043 uint64_t Modulo = 0;
1044 for (unsigned i = 0, e = GEP1VariableIndices.size(); i != e; ++i)
1045 Modulo |= (uint64_t)GEP1VariableIndices[i].Scale;
1046 Modulo = Modulo ^ (Modulo & (Modulo - 1));
Eli Friedman3d1b3072011-09-08 02:23:31 +00001047
Eli Friedmanb78ac542011-09-08 02:37:07 +00001048 // We can compute the difference between the two addresses
1049 // mod Modulo. Check whether that difference guarantees that the
1050 // two locations do not alias.
1051 uint64_t ModOffset = (uint64_t)GEP1BaseOffset & (Modulo - 1);
1052 if (V1Size != UnknownSize && V2Size != UnknownSize &&
1053 ModOffset >= V2Size && V1Size <= Modulo - ModOffset)
1054 return NoAlias;
1055 }
Eli Friedman3d1b3072011-09-08 02:23:31 +00001056
Dan Gohmanadf80ae2011-06-04 06:50:18 +00001057 // Statically, we can see that the base objects are the same, but the
1058 // pointers have dynamic offsets which we can't resolve. And none of our
1059 // little tricks above worked.
1060 //
1061 // TODO: Returning PartialAlias instead of MayAlias is a mild hack; the
1062 // practical effect of this is protecting TBAA in the case of dynamic
Dan Gohman9017b842012-02-17 18:33:38 +00001063 // indices into arrays of unions or malloc'd memory.
Dan Gohmanadf80ae2011-06-04 06:50:18 +00001064 return PartialAlias;
Evan Chengf1f3dd32009-10-13 18:42:04 +00001065}
1066
Dan Gohman4e7e7952011-06-03 20:17:36 +00001067static AliasAnalysis::AliasResult
1068MergeAliasResults(AliasAnalysis::AliasResult A, AliasAnalysis::AliasResult B) {
1069 // If the results agree, take it.
1070 if (A == B)
1071 return A;
1072 // A mix of PartialAlias and MustAlias is PartialAlias.
1073 if ((A == AliasAnalysis::PartialAlias && B == AliasAnalysis::MustAlias) ||
1074 (B == AliasAnalysis::PartialAlias && A == AliasAnalysis::MustAlias))
1075 return AliasAnalysis::PartialAlias;
1076 // Otherwise, we don't know anything.
1077 return AliasAnalysis::MayAlias;
1078}
1079
Chris Lattner98e253262009-11-23 16:45:27 +00001080/// aliasSelect - Provide a bunch of ad-hoc rules to disambiguate a Select
1081/// instruction against another.
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001082AliasAnalysis::AliasResult
Dan Gohmanf372cf82010-10-19 22:54:46 +00001083BasicAliasAnalysis::aliasSelect(const SelectInst *SI, uint64_t SISize,
Dan Gohmanf3702452010-10-18 18:45:11 +00001084 const MDNode *SITBAAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +00001085 const Value *V2, uint64_t V2Size,
Dan Gohmanf3702452010-10-18 18:45:11 +00001086 const MDNode *V2TBAAInfo) {
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001087 // If the values are Selects with the same condition, we can do a more precise
1088 // check: just check for aliases between the values on corresponding arms.
1089 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
1090 if (SI->getCondition() == SI2->getCondition()) {
1091 AliasResult Alias =
Dan Gohmanf3702452010-10-18 18:45:11 +00001092 aliasCheck(SI->getTrueValue(), SISize, SITBAAInfo,
1093 SI2->getTrueValue(), V2Size, V2TBAAInfo);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001094 if (Alias == MayAlias)
1095 return MayAlias;
1096 AliasResult ThisAlias =
Dan Gohmanf3702452010-10-18 18:45:11 +00001097 aliasCheck(SI->getFalseValue(), SISize, SITBAAInfo,
1098 SI2->getFalseValue(), V2Size, V2TBAAInfo);
Dan Gohman4e7e7952011-06-03 20:17:36 +00001099 return MergeAliasResults(ThisAlias, Alias);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001100 }
1101
1102 // If both arms of the Select node NoAlias or MustAlias V2, then returns
1103 // NoAlias / MustAlias. Otherwise, returns MayAlias.
1104 AliasResult Alias =
Dan Gohmanf3702452010-10-18 18:45:11 +00001105 aliasCheck(V2, V2Size, V2TBAAInfo, SI->getTrueValue(), SISize, SITBAAInfo);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001106 if (Alias == MayAlias)
1107 return MayAlias;
Dan Gohman7c34ece2010-06-28 21:16:52 +00001108
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001109 AliasResult ThisAlias =
Dan Gohmanf3702452010-10-18 18:45:11 +00001110 aliasCheck(V2, V2Size, V2TBAAInfo, SI->getFalseValue(), SISize, SITBAAInfo);
Dan Gohman4e7e7952011-06-03 20:17:36 +00001111 return MergeAliasResults(ThisAlias, Alias);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001112}
1113
Evan Chengf92f5552009-10-14 05:22:03 +00001114// aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
Evan Cheng31565b32009-10-14 05:05:02 +00001115// against another.
Evan Chengc10e88d2009-10-13 22:02:20 +00001116AliasAnalysis::AliasResult
Dan Gohmanf372cf82010-10-19 22:54:46 +00001117BasicAliasAnalysis::aliasPHI(const PHINode *PN, uint64_t PNSize,
Dan Gohmanf3702452010-10-18 18:45:11 +00001118 const MDNode *PNTBAAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +00001119 const Value *V2, uint64_t V2Size,
Dan Gohmanf3702452010-10-18 18:45:11 +00001120 const MDNode *V2TBAAInfo) {
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001121 // Track phi nodes we have visited. We use this information when we determine
1122 // value equivalence.
1123 VisitedPhiBBs.insert(PN->getParent());
1124
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001125 // If the values are PHIs in the same block, we can do a more precise
1126 // as well as efficient check: just check for aliases between the values
1127 // on corresponding edges.
1128 if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
1129 if (PN2->getParent() == PN->getParent()) {
Arnold Schwaighofer8dc34cf2012-09-06 14:41:53 +00001130 LocPair Locs(Location(PN, PNSize, PNTBAAInfo),
1131 Location(V2, V2Size, V2TBAAInfo));
1132 if (PN > V2)
1133 std::swap(Locs.first, Locs.second);
Arnold Schwaighoferedd62b12012-12-10 23:02:41 +00001134 // Analyse the PHIs' inputs under the assumption that the PHIs are
1135 // NoAlias.
1136 // If the PHIs are May/MustAlias there must be (recursively) an input
1137 // operand from outside the PHIs' cycle that is MayAlias/MustAlias or
1138 // there must be an operation on the PHIs within the PHIs' value cycle
1139 // that causes a MayAlias.
1140 // Pretend the phis do not alias.
1141 AliasResult Alias = NoAlias;
1142 assert(AliasCache.count(Locs) &&
1143 "There must exist an entry for the phi node");
1144 AliasResult OrigAliasResult = AliasCache[Locs];
1145 AliasCache[Locs] = NoAlias;
Arnold Schwaighofer8dc34cf2012-09-06 14:41:53 +00001146
Hal Finkela6f86fc2012-11-17 02:33:15 +00001147 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001148 AliasResult ThisAlias =
Dan Gohmanf3702452010-10-18 18:45:11 +00001149 aliasCheck(PN->getIncomingValue(i), PNSize, PNTBAAInfo,
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001150 PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
Dan Gohmanf3702452010-10-18 18:45:11 +00001151 V2Size, V2TBAAInfo);
Dan Gohman4e7e7952011-06-03 20:17:36 +00001152 Alias = MergeAliasResults(ThisAlias, Alias);
1153 if (Alias == MayAlias)
1154 break;
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001155 }
Arnold Schwaighofer8dc34cf2012-09-06 14:41:53 +00001156
1157 // Reset if speculation failed.
Arnold Schwaighoferedd62b12012-12-10 23:02:41 +00001158 if (Alias != NoAlias)
Arnold Schwaighofer8dc34cf2012-09-06 14:41:53 +00001159 AliasCache[Locs] = OrigAliasResult;
1160
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001161 return Alias;
1162 }
1163
Evan Cheng8ec25932009-10-16 00:33:09 +00001164 SmallPtrSet<Value*, 4> UniqueSrc;
Evan Chengc10e88d2009-10-13 22:02:20 +00001165 SmallVector<Value*, 4> V1Srcs;
Evan Chengc10e88d2009-10-13 22:02:20 +00001166 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1167 Value *PV1 = PN->getIncomingValue(i);
1168 if (isa<PHINode>(PV1))
1169 // If any of the source itself is a PHI, return MayAlias conservatively
Evan Chengc1eed9d2009-10-14 06:41:49 +00001170 // to avoid compile time explosion. The worst possible case is if both
1171 // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
1172 // and 'n' are the number of PHI sources.
Evan Chengc10e88d2009-10-13 22:02:20 +00001173 return MayAlias;
1174 if (UniqueSrc.insert(PV1))
1175 V1Srcs.push_back(PV1);
1176 }
1177
Dan Gohmanf3702452010-10-18 18:45:11 +00001178 AliasResult Alias = aliasCheck(V2, V2Size, V2TBAAInfo,
1179 V1Srcs[0], PNSize, PNTBAAInfo);
Evan Chengf92f5552009-10-14 05:22:03 +00001180 // Early exit if the check of the first PHI source against V2 is MayAlias.
1181 // Other results are not possible.
1182 if (Alias == MayAlias)
1183 return MayAlias;
1184
Evan Chengc10e88d2009-10-13 22:02:20 +00001185 // If all sources of the PHI node NoAlias or MustAlias V2, then returns
1186 // NoAlias / MustAlias. Otherwise, returns MayAlias.
Evan Chengc10e88d2009-10-13 22:02:20 +00001187 for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
1188 Value *V = V1Srcs[i];
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001189
Dan Gohmanf3702452010-10-18 18:45:11 +00001190 AliasResult ThisAlias = aliasCheck(V2, V2Size, V2TBAAInfo,
1191 V, PNSize, PNTBAAInfo);
Dan Gohman4e7e7952011-06-03 20:17:36 +00001192 Alias = MergeAliasResults(ThisAlias, Alias);
1193 if (Alias == MayAlias)
1194 break;
Evan Chengc10e88d2009-10-13 22:02:20 +00001195 }
1196
1197 return Alias;
1198}
1199
1200// aliasCheck - Provide a bunch of ad-hoc rules to disambiguate in common cases,
1201// such as array references.
Evan Chengf1f3dd32009-10-13 18:42:04 +00001202//
1203AliasAnalysis::AliasResult
Dan Gohmanf372cf82010-10-19 22:54:46 +00001204BasicAliasAnalysis::aliasCheck(const Value *V1, uint64_t V1Size,
Dan Gohmanf3702452010-10-18 18:45:11 +00001205 const MDNode *V1TBAAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +00001206 const Value *V2, uint64_t V2Size,
Dan Gohmanf3702452010-10-18 18:45:11 +00001207 const MDNode *V2TBAAInfo) {
Dan Gohmancb45bd92010-04-08 18:11:50 +00001208 // If either of the memory references is empty, it doesn't matter what the
1209 // pointer values are.
1210 if (V1Size == 0 || V2Size == 0)
1211 return NoAlias;
1212
Evan Chengf1f3dd32009-10-13 18:42:04 +00001213 // Strip off any casts if they exist.
1214 V1 = V1->stripPointerCasts();
1215 V2 = V2->stripPointerCasts();
1216
1217 // Are we checking for alias of the same value?
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001218 // Because we look 'through' phi nodes we could look at "Value" pointers from
1219 // different iterations. We must therefore make sure that this is not the
1220 // case. The function isValueEqualInPotentialCycles ensures that this cannot
1221 // happen by looking at the visited phi nodes and making sure they cannot
1222 // reach the value.
1223 if (isValueEqualInPotentialCycles(V1, V2))
1224 return MustAlias;
Evan Chengf1f3dd32009-10-13 18:42:04 +00001225
Duncan Sands19d0b472010-02-16 11:11:14 +00001226 if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
Evan Chengf1f3dd32009-10-13 18:42:04 +00001227 return NoAlias; // Scalars cannot alias each other
1228
1229 // Figure out what objects these things are pointing to if we can.
Arnold Schwaighofer1a444482014-03-26 21:30:19 +00001230 const Value *O1 = GetUnderlyingObject(V1, DL, MaxLookupSearchDepth);
1231 const Value *O2 = GetUnderlyingObject(V2, DL, MaxLookupSearchDepth);
Evan Chengf1f3dd32009-10-13 18:42:04 +00001232
Dan Gohmanccb45842009-11-09 19:29:11 +00001233 // Null values in the default address space don't point to any object, so they
1234 // don't alias any other pointer.
1235 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
1236 if (CPN->getType()->getAddressSpace() == 0)
1237 return NoAlias;
1238 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
1239 if (CPN->getType()->getAddressSpace() == 0)
1240 return NoAlias;
1241
Evan Chengf1f3dd32009-10-13 18:42:04 +00001242 if (O1 != O2) {
1243 // If V1/V2 point to two different objects we know that we have no alias.
Dan Gohman00ef9322010-07-07 14:27:09 +00001244 if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
Evan Chengf1f3dd32009-10-13 18:42:04 +00001245 return NoAlias;
Nick Lewyckyc53e2ec2009-11-14 06:15:14 +00001246
1247 // Constant pointers can't alias with non-const isIdentifiedObject objects.
Dan Gohman00ef9322010-07-07 14:27:09 +00001248 if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
1249 (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
Nick Lewyckyc53e2ec2009-11-14 06:15:14 +00001250 return NoAlias;
1251
Michael Kupersteinf3e663a2013-05-28 08:17:48 +00001252 // Function arguments can't alias with things that are known to be
1253 // unambigously identified at the function level.
1254 if ((isa<Argument>(O1) && isIdentifiedFunctionLocal(O2)) ||
1255 (isa<Argument>(O2) && isIdentifiedFunctionLocal(O1)))
Dan Gohman84f90a32010-07-01 20:08:40 +00001256 return NoAlias;
Evan Chengf1f3dd32009-10-13 18:42:04 +00001257
1258 // Most objects can't alias null.
Dan Gohman00ef9322010-07-07 14:27:09 +00001259 if ((isa<ConstantPointerNull>(O2) && isKnownNonNull(O1)) ||
1260 (isa<ConstantPointerNull>(O1) && isKnownNonNull(O2)))
Evan Chengf1f3dd32009-10-13 18:42:04 +00001261 return NoAlias;
Jakub Staszak07f383f2013-08-24 14:16:00 +00001262
Dan Gohman5b0a8a82010-07-07 14:30:04 +00001263 // If one pointer is the result of a call/invoke or load and the other is a
1264 // non-escaping local object within the same function, then we know the
1265 // object couldn't escape to a point where the call could return it.
1266 //
1267 // Note that if the pointers are in different functions, there are a
1268 // variety of complications. A call with a nocapture argument may still
1269 // temporary store the nocapture argument's value in a temporary memory
1270 // location if that memory location doesn't escape. Or it may pass a
1271 // nocapture value to other functions as long as they don't capture it.
1272 if (isEscapeSource(O1) && isNonEscapingLocalObject(O2))
1273 return NoAlias;
1274 if (isEscapeSource(O2) && isNonEscapingLocalObject(O1))
1275 return NoAlias;
1276 }
1277
Evan Chengf1f3dd32009-10-13 18:42:04 +00001278 // If the size of one access is larger than the entire object on the other
1279 // side, then we know such behavior is undefined and can assume no alias.
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001280 if (DL)
1281 if ((V1Size != UnknownSize && isObjectSmallerThan(O2, V1Size, *DL, *TLI)) ||
1282 (V2Size != UnknownSize && isObjectSmallerThan(O1, V2Size, *DL, *TLI)))
Evan Chengf1f3dd32009-10-13 18:42:04 +00001283 return NoAlias;
Jakub Staszak07f383f2013-08-24 14:16:00 +00001284
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001285 // Check the cache before climbing up use-def chains. This also terminates
1286 // otherwise infinitely recursive queries.
1287 LocPair Locs(Location(V1, V1Size, V1TBAAInfo),
1288 Location(V2, V2Size, V2TBAAInfo));
1289 if (V1 > V2)
1290 std::swap(Locs.first, Locs.second);
1291 std::pair<AliasCacheTy::iterator, bool> Pair =
1292 AliasCache.insert(std::make_pair(Locs, MayAlias));
1293 if (!Pair.second)
1294 return Pair.first->second;
1295
Chris Lattner89288992009-11-26 02:13:03 +00001296 // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
1297 // GEP can't simplify, we don't even look at the PHI cases.
Chris Lattnerb2647b92009-10-17 23:48:54 +00001298 if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
Chris Lattnerd6a2a992003-02-26 19:41:54 +00001299 std::swap(V1, V2);
1300 std::swap(V1Size, V2Size);
Chris Lattner5341c962009-11-26 02:14:59 +00001301 std::swap(O1, O2);
Duncan Sands71c20702012-11-04 09:02:45 +00001302 std::swap(V1TBAAInfo, V2TBAAInfo);
Chris Lattnerd6a2a992003-02-26 19:41:54 +00001303 }
Dan Gohman02538ac2010-10-18 18:04:47 +00001304 if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) {
Arnold Schwaighofer76dca582012-09-06 14:31:51 +00001305 AliasResult Result = aliasGEP(GV1, V1Size, V1TBAAInfo, V2, V2Size, V2TBAAInfo, O1, O2);
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001306 if (Result != MayAlias) return AliasCache[Locs] = Result;
Dan Gohman02538ac2010-10-18 18:04:47 +00001307 }
Evan Chengc10e88d2009-10-13 22:02:20 +00001308
1309 if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
1310 std::swap(V1, V2);
1311 std::swap(V1Size, V2Size);
Duncan Sands71c20702012-11-04 09:02:45 +00001312 std::swap(V1TBAAInfo, V2TBAAInfo);
Evan Chengc10e88d2009-10-13 22:02:20 +00001313 }
Dan Gohman02538ac2010-10-18 18:04:47 +00001314 if (const PHINode *PN = dyn_cast<PHINode>(V1)) {
Dan Gohmanf3702452010-10-18 18:45:11 +00001315 AliasResult Result = aliasPHI(PN, V1Size, V1TBAAInfo,
1316 V2, V2Size, V2TBAAInfo);
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001317 if (Result != MayAlias) return AliasCache[Locs] = Result;
Dan Gohman02538ac2010-10-18 18:04:47 +00001318 }
Misha Brukman01808ca2005-04-21 21:13:18 +00001319
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001320 if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
1321 std::swap(V1, V2);
1322 std::swap(V1Size, V2Size);
Duncan Sands71c20702012-11-04 09:02:45 +00001323 std::swap(V1TBAAInfo, V2TBAAInfo);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001324 }
Dan Gohman02538ac2010-10-18 18:04:47 +00001325 if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) {
Dan Gohmanf3702452010-10-18 18:45:11 +00001326 AliasResult Result = aliasSelect(S1, V1Size, V1TBAAInfo,
1327 V2, V2Size, V2TBAAInfo);
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001328 if (Result != MayAlias) return AliasCache[Locs] = Result;
Dan Gohman02538ac2010-10-18 18:04:47 +00001329 }
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001330
Dan Gohman44da55b2011-01-18 21:16:06 +00001331 // If both pointers are pointing into the same object and one of them
1332 // accesses is accessing the entire object, then the accesses must
1333 // overlap in some way.
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001334 if (DL && O1 == O2)
1335 if ((V1Size != UnknownSize && isObjectSize(O1, V1Size, *DL, *TLI)) ||
1336 (V2Size != UnknownSize && isObjectSize(O2, V2Size, *DL, *TLI)))
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001337 return AliasCache[Locs] = PartialAlias;
Dan Gohman44da55b2011-01-18 21:16:06 +00001338
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001339 AliasResult Result =
1340 AliasAnalysis::alias(Location(V1, V1Size, V1TBAAInfo),
1341 Location(V2, V2Size, V2TBAAInfo));
1342 return AliasCache[Locs] = Result;
Chris Lattnerd6a2a992003-02-26 19:41:54 +00001343}
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001344
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001345bool BasicAliasAnalysis::isValueEqualInPotentialCycles(const Value *V,
1346 const Value *V2) {
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001347 if (V != V2)
1348 return false;
1349
1350 const Instruction *Inst = dyn_cast<Instruction>(V);
1351 if (!Inst)
1352 return true;
1353
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001354 if (VisitedPhiBBs.size() > MaxNumPhiBBsValueReachabilityCheck)
1355 return false;
1356
1357 // Use dominance or loop info if available.
Chandler Carruth73523022014-01-13 13:07:17 +00001358 DominatorTreeWrapperPass *DTWP =
1359 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
Craig Topper9f008862014-04-15 04:59:12 +00001360 DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001361 LoopInfo *LI = getAnalysisIfAvailable<LoopInfo>();
1362
1363 // Make sure that the visited phis cannot reach the Value. This ensures that
1364 // the Values cannot come from different iterations of a potential cycle the
1365 // phi nodes could be involved in.
1366 for (SmallPtrSet<const BasicBlock *, 8>::iterator PI = VisitedPhiBBs.begin(),
1367 PE = VisitedPhiBBs.end();
1368 PI != PE; ++PI)
1369 if (isPotentiallyReachable((*PI)->begin(), Inst, DT, LI))
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001370 return false;
1371
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001372 return true;
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001373}
1374
1375/// GetIndexDifference - Dest and Src are the variable indices from two
1376/// decomposed GetElementPtr instructions GEP1 and GEP2 which have common base
1377/// pointers. Subtract the GEP2 indices from GEP1 to find the symbolic
1378/// difference between the two pointers.
1379void BasicAliasAnalysis::GetIndexDifference(
1380 SmallVectorImpl<VariableGEPIndex> &Dest,
1381 const SmallVectorImpl<VariableGEPIndex> &Src) {
1382 if (Src.empty())
1383 return;
1384
1385 for (unsigned i = 0, e = Src.size(); i != e; ++i) {
1386 const Value *V = Src[i].V;
1387 ExtensionKind Extension = Src[i].Extension;
1388 int64_t Scale = Src[i].Scale;
1389
1390 // Find V in Dest. This is N^2, but pointer indices almost never have more
1391 // than a few variable indexes.
1392 for (unsigned j = 0, e = Dest.size(); j != e; ++j) {
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001393 if (!isValueEqualInPotentialCycles(Dest[j].V, V) ||
1394 Dest[j].Extension != Extension)
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001395 continue;
1396
1397 // If we found it, subtract off Scale V's from the entry in Dest. If it
1398 // goes to zero, remove the entry.
1399 if (Dest[j].Scale != Scale)
1400 Dest[j].Scale -= Scale;
1401 else
1402 Dest.erase(Dest.begin() + j);
1403 Scale = 0;
1404 break;
1405 }
1406
1407 // If we didn't consume this entry, add it to the end of the Dest list.
1408 if (Scale) {
1409 VariableGEPIndex Entry = { V, Extension, -Scale };
1410 Dest.push_back(Entry);
1411 }
1412 }
1413}