blob: 170782d84bb73fe94420b6d5ba75246396993021 [file] [log] [blame]
Dan Gohman826bdf82010-05-28 16:19:17 +00001//===- Loads.cpp - Local load analysis ------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines simple local analyses for load instructions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Analysis/Loads.h"
15#include "llvm/Analysis/AliasAnalysis.h"
Nuno Lopes69dcc7d2012-12-31 17:42:11 +000016#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/DataLayout.h"
18#include "llvm/IR/GlobalAlias.h"
19#include "llvm/IR/GlobalVariable.h"
20#include "llvm/IR/IntrinsicInst.h"
21#include "llvm/IR/LLVMContext.h"
Mehdi Amini9a9738f2015-03-03 22:01:13 +000022#include "llvm/IR/Module.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/Operator.h"
Artur Pilipenko31bcca42016-02-24 12:49:04 +000024#include "llvm/IR/Statepoint.h"
25
Dan Gohman826bdf82010-05-28 16:19:17 +000026using namespace llvm;
27
Sanjoy Das10df4972016-06-01 16:47:45 +000028static bool isDereferenceableFromAttribute(const Value *BV, APInt Size,
29 const DataLayout &DL,
Artur Pilipenko31bcca42016-02-24 12:49:04 +000030 const Instruction *CtxI,
31 const DominatorTree *DT,
32 const TargetLibraryInfo *TLI) {
Artur Pilipenko31bcca42016-02-24 12:49:04 +000033 bool CheckForNonNull = false;
Sanjoy Das10df4972016-06-01 16:47:45 +000034 APInt DerefBytes(Size.getBitWidth(),
Artur Pilipenko345f0142016-04-27 12:51:01 +000035 BV->getPointerDereferenceableBytes(CheckForNonNull));
Artur Pilipenko31bcca42016-02-24 12:49:04 +000036
37 if (DerefBytes.getBoolValue())
Sanjoy Das10df4972016-06-01 16:47:45 +000038 if (DerefBytes.uge(Size))
Artur Pilipenko31bcca42016-02-24 12:49:04 +000039 if (!CheckForNonNull || isKnownNonNullAt(BV, CtxI, DT, TLI))
40 return true;
41
42 return false;
43}
44
Artur Pilipenko31bcca42016-02-24 12:49:04 +000045static bool isAligned(const Value *Base, APInt Offset, unsigned Align,
46 const DataLayout &DL) {
47 APInt BaseAlign(Offset.getBitWidth(), Base->getPointerAlignment(DL));
48
49 if (!BaseAlign) {
50 Type *Ty = Base->getType()->getPointerElementType();
51 if (!Ty->isSized())
52 return false;
53 BaseAlign = DL.getABITypeAlignment(Ty);
54 }
55
56 APInt Alignment(Offset.getBitWidth(), Align);
57
58 assert(Alignment.isPowerOf2() && "must be a power of 2!");
59 return BaseAlign.uge(Alignment) && !(Offset & (Alignment-1));
60}
61
62static bool isAligned(const Value *Base, unsigned Align, const DataLayout &DL) {
63 Type *Ty = Base->getType();
64 assert(Ty->isSized() && "must be sized");
65 APInt Offset(DL.getTypeStoreSizeInBits(Ty), 0);
66 return isAligned(Base, Offset, Align, DL);
67}
68
69/// Test if V is always a pointer to allocated and suitably aligned memory for
70/// a simple load or store.
71static bool isDereferenceableAndAlignedPointer(
Sanjoy Das10df4972016-06-01 16:47:45 +000072 const Value *V, unsigned Align, APInt Size, const DataLayout &DL,
Artur Pilipenko31bcca42016-02-24 12:49:04 +000073 const Instruction *CtxI, const DominatorTree *DT,
74 const TargetLibraryInfo *TLI, SmallPtrSetImpl<const Value *> &Visited) {
75 // Note that it is not safe to speculate into a malloc'd region because
76 // malloc may return null.
77
Artur Pilipenko7a2632642016-05-11 14:43:28 +000078 bool CheckForNonNull;
79 if (V->isPointerDereferenceable(CheckForNonNull)) {
Sanjoy Das10df4972016-06-01 16:47:45 +000080 Type *ETy = V->getType()->getPointerElementType();
81 if (ETy->isSized() && Size.ule(DL.getTypeStoreSize(ETy))) {
82 if (CheckForNonNull && !isKnownNonNullAt(V, CtxI, DT, TLI))
83 return false;
84 return isAligned(V, Align, DL);
85 }
Artur Pilipenko7a2632642016-05-11 14:43:28 +000086 }
Artur Pilipenko31bcca42016-02-24 12:49:04 +000087
Sanjoy Das10df4972016-06-01 16:47:45 +000088 // bitcast instructions are no-ops as far as dereferenceability is concerned.
89 if (const BitCastOperator *BC = dyn_cast<BitCastOperator>(V))
90 return isDereferenceableAndAlignedPointer(BC->getOperand(0), Align, Size,
91 DL, CtxI, DT, TLI, Visited);
Artur Pilipenko31bcca42016-02-24 12:49:04 +000092
Sanjoy Das10df4972016-06-01 16:47:45 +000093 if (isDereferenceableFromAttribute(V, Size, DL, CtxI, DT, TLI))
Artur Pilipenko31bcca42016-02-24 12:49:04 +000094 return isAligned(V, Align, DL);
95
96 // For GEPs, determine if the indexing lands within the allocated object.
97 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Artur Pilipenko31bcca42016-02-24 12:49:04 +000098 const Value *Base = GEP->getPointerOperand();
99
Artur Pilipenko31bcca42016-02-24 12:49:04 +0000100 APInt Offset(DL.getPointerTypeSizeInBits(GEP->getType()), 0);
Sanjoy Das10df4972016-06-01 16:47:45 +0000101 if (!GEP->accumulateConstantOffset(DL, Offset) || Offset.isNegative() ||
102 !Offset.urem(APInt(Offset.getBitWidth(), Align)).isMinValue())
Artur Pilipenko31bcca42016-02-24 12:49:04 +0000103 return false;
104
Sanjoy Das10df4972016-06-01 16:47:45 +0000105 // If the base pointer is dereferenceable for Offset+Size bytes, then the
106 // GEP (== Base + Offset) is dereferenceable for Size bytes. If the base
107 // pointer is aligned to Align bytes, and the Offset is divisible by Align
108 // then the GEP (== Base + Offset == k_0 * Align + k_1 * Align) is also
109 // aligned to Align bytes.
110
111 return Visited.insert(Base).second &&
112 isDereferenceableAndAlignedPointer(Base, Align, Offset + Size, DL,
113 CtxI, DT, TLI, Visited);
Artur Pilipenko31bcca42016-02-24 12:49:04 +0000114 }
115
116 // For gc.relocate, look through relocations
117 if (const GCRelocateInst *RelocateInst = dyn_cast<GCRelocateInst>(V))
118 return isDereferenceableAndAlignedPointer(
Sanjoy Das10df4972016-06-01 16:47:45 +0000119 RelocateInst->getDerivedPtr(), Align, Size, DL, CtxI, DT, TLI, Visited);
Artur Pilipenko31bcca42016-02-24 12:49:04 +0000120
121 if (const AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(V))
Sanjoy Das10df4972016-06-01 16:47:45 +0000122 return isDereferenceableAndAlignedPointer(ASC->getOperand(0), Align, Size,
123 DL, CtxI, DT, TLI, Visited);
Artur Pilipenko31bcca42016-02-24 12:49:04 +0000124
125 // If we don't know, assume the worst.
126 return false;
127}
128
129bool llvm::isDereferenceableAndAlignedPointer(const Value *V, unsigned Align,
130 const DataLayout &DL,
131 const Instruction *CtxI,
132 const DominatorTree *DT,
133 const TargetLibraryInfo *TLI) {
134 // When dereferenceability information is provided by a dereferenceable
135 // attribute, we know exactly how many bytes are dereferenceable. If we can
136 // determine the exact offset to the attributed variable, we can use that
137 // information here.
138 Type *VTy = V->getType();
139 Type *Ty = VTy->getPointerElementType();
140
141 // Require ABI alignment for loads without alignment specification
142 if (Align == 0)
143 Align = DL.getABITypeAlignment(Ty);
144
Sanjoy Das10df4972016-06-01 16:47:45 +0000145 if (!Ty->isSized())
146 return false;
Artur Pilipenko31bcca42016-02-24 12:49:04 +0000147
148 SmallPtrSet<const Value *, 32> Visited;
Sanjoy Das10df4972016-06-01 16:47:45 +0000149 return ::isDereferenceableAndAlignedPointer(
150 V, Align, APInt(DL.getTypeSizeInBits(VTy), DL.getTypeStoreSize(Ty)), DL,
151 CtxI, DT, TLI, Visited);
Artur Pilipenko31bcca42016-02-24 12:49:04 +0000152}
153
154bool llvm::isDereferenceablePointer(const Value *V, const DataLayout &DL,
155 const Instruction *CtxI,
156 const DominatorTree *DT,
157 const TargetLibraryInfo *TLI) {
158 return isDereferenceableAndAlignedPointer(V, 1, DL, CtxI, DT, TLI);
159}
160
Chandler Carruthb56052f2014-10-18 23:31:55 +0000161/// \brief Test if A and B will obviously have the same value.
162///
163/// This includes recognizing that %t0 and %t1 will have the same
Dan Gohman826bdf82010-05-28 16:19:17 +0000164/// value in code like this:
Chandler Carruthb56052f2014-10-18 23:31:55 +0000165/// \code
Dan Gohman826bdf82010-05-28 16:19:17 +0000166/// %t0 = getelementptr \@a, 0, 3
167/// store i32 0, i32* %t0
168/// %t1 = getelementptr \@a, 0, 3
169/// %t2 = load i32* %t1
Chandler Carruthb56052f2014-10-18 23:31:55 +0000170/// \endcode
Dan Gohman826bdf82010-05-28 16:19:17 +0000171///
172static bool AreEquivalentAddressValues(const Value *A, const Value *B) {
173 // Test if the values are trivially equivalent.
Chandler Carruthbe49df32014-10-18 23:41:25 +0000174 if (A == B)
175 return true;
Hans Wennborg060b9942011-06-03 17:15:37 +0000176
Dan Gohman826bdf82010-05-28 16:19:17 +0000177 // Test if the values come from identical arithmetic instructions.
178 // Use isIdenticalToWhenDefined instead of isIdenticalTo because
179 // this function is only used when one address use dominates the
180 // other, which means that they'll always either have the same
181 // value or one of them will have an undefined value.
Chandler Carruthbe49df32014-10-18 23:41:25 +0000182 if (isa<BinaryOperator>(A) || isa<CastInst>(A) || isa<PHINode>(A) ||
183 isa<GetElementPtrInst>(A))
Dan Gohman826bdf82010-05-28 16:19:17 +0000184 if (const Instruction *BI = dyn_cast<Instruction>(B))
185 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
186 return true;
Hans Wennborg060b9942011-06-03 17:15:37 +0000187
Dan Gohman826bdf82010-05-28 16:19:17 +0000188 // Otherwise they may not be equivalent.
189 return false;
190}
191
Chandler Carruth1f27f032014-10-18 23:46:17 +0000192/// \brief Check if executing a load of this pointer value cannot trap.
193///
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +0000194/// If DT and ScanFrom are specified this method performs context-sensitive
195/// analysis and returns true if it is safe to load immediately before ScanFrom.
Artur Pilipenko66d6d3e2016-02-11 13:42:59 +0000196///
Chandler Carruth1f27f032014-10-18 23:46:17 +0000197/// If it is not obviously safe to load from the specified pointer, we do
198/// a quick local scan of the basic block containing \c ScanFrom, to determine
199/// if the address is already accessed.
200///
201/// This uses the pointee type to determine how many bytes need to be safe to
202/// load from the pointer.
Artur Pilipenko6dd69692016-01-15 15:27:46 +0000203bool llvm::isSafeToLoadUnconditionally(Value *V, unsigned Align,
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +0000204 const DataLayout &DL,
Artur Pilipenko66d6d3e2016-02-11 13:42:59 +0000205 Instruction *ScanFrom,
206 const DominatorTree *DT,
207 const TargetLibraryInfo *TLI) {
Artur Pilipenko0e21d542015-06-25 12:18:43 +0000208 // Zero alignment means that the load has the ABI alignment for the target
209 if (Align == 0)
210 Align = DL.getABITypeAlignment(V->getType()->getPointerElementType());
211 assert(isPowerOf2_32(Align));
212
Artur Pilipenko66d6d3e2016-02-11 13:42:59 +0000213 // If DT is not specified we can't make context-sensitive query
214 const Instruction* CtxI = DT ? ScanFrom : nullptr;
215 if (isDereferenceableAndAlignedPointer(V, Align, DL, CtxI, DT, TLI))
Artur Pilipenkof84dc062016-01-17 12:35:29 +0000216 return true;
217
Nuno Lopes69dcc7d2012-12-31 17:42:11 +0000218 int64_t ByteOffset = 0;
Dan Gohman826bdf82010-05-28 16:19:17 +0000219 Value *Base = V;
Chandler Carruth38e98d52014-10-18 23:47:22 +0000220 Base = GetPointerBaseWithConstantOffset(V, ByteOffset, DL);
Nuno Lopes69dcc7d2012-12-31 17:42:11 +0000221
222 if (ByteOffset < 0) // out of bounds
223 return false;
Dan Gohman826bdf82010-05-28 16:19:17 +0000224
Craig Topper9f008862014-04-15 04:59:12 +0000225 Type *BaseType = nullptr;
Dan Gohman826bdf82010-05-28 16:19:17 +0000226 unsigned BaseAlign = 0;
227 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Base)) {
228 // An alloca is safe to load from as load as it is suitably aligned.
229 BaseType = AI->getAllocatedType();
230 BaseAlign = AI->getAlignment();
Nuno Lopes69dcc7d2012-12-31 17:42:11 +0000231 } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Base)) {
Chandler Carruth8a993732014-10-19 00:42:16 +0000232 // Global variables are not necessarily safe to load from if they are
Sanjoy Das5ce32722016-04-08 00:48:30 +0000233 // interposed arbitrarily. Their size may change or they may be weak and
234 // require a test to determine if they were in fact provided.
235 if (!GV->isInterposable()) {
Dan Gohman826bdf82010-05-28 16:19:17 +0000236 BaseType = GV->getType()->getElementType();
237 BaseAlign = GV->getAlignment();
238 }
239 }
240
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000241 PointerType *AddrTy = cast<PointerType>(V->getType());
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000242 uint64_t LoadSize = DL.getTypeStoreSize(AddrTy->getElementType());
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000243
Chandler Carruth8a993732014-10-19 00:42:16 +0000244 // If we found a base allocated type from either an alloca or global variable,
245 // try to see if we are definitively within the allocated region. We need to
246 // know the size of the base type and the loaded type to do anything in this
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000247 // case.
248 if (BaseType && BaseType->isSized()) {
Chandler Carruth8a993732014-10-19 00:42:16 +0000249 if (BaseAlign == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000250 BaseAlign = DL.getPrefTypeAlignment(BaseType);
Dan Gohman826bdf82010-05-28 16:19:17 +0000251
252 if (Align <= BaseAlign) {
Dan Gohman826bdf82010-05-28 16:19:17 +0000253 // Check if the load is within the bounds of the underlying object.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000254 if (ByteOffset + LoadSize <= DL.getTypeAllocSize(BaseType) &&
Artur Pilipenko0e21d542015-06-25 12:18:43 +0000255 ((ByteOffset % Align) == 0))
Dan Gohman826bdf82010-05-28 16:19:17 +0000256 return true;
257 }
258 }
259
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +0000260 if (!ScanFrom)
261 return false;
262
Dan Gohman826bdf82010-05-28 16:19:17 +0000263 // Otherwise, be a little bit aggressive by scanning the local block where we
264 // want to check to see if the pointer is already being loaded or stored
265 // from/to. If so, the previous load or store would have already trapped,
266 // so there is no harm doing an extra load (also, CSE will later eliminate
267 // the load entirely).
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000268 BasicBlock::iterator BBI = ScanFrom->getIterator(),
269 E = ScanFrom->getParent()->begin();
Dan Gohman826bdf82010-05-28 16:19:17 +0000270
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000271 // We can at least always strip pointer casts even though we can't use the
272 // base here.
273 V = V->stripPointerCasts();
274
Dan Gohman826bdf82010-05-28 16:19:17 +0000275 while (BBI != E) {
276 --BBI;
277
278 // If we see a free or a call which may write to memory (i.e. which might do
279 // a free) the pointer could be marked invalid.
280 if (isa<CallInst>(BBI) && BBI->mayWriteToMemory() &&
281 !isa<DbgInfoIntrinsic>(BBI))
282 return false;
283
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000284 Value *AccessedPtr;
Artur Pilipenko0e21d542015-06-25 12:18:43 +0000285 unsigned AccessedAlign;
286 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000287 AccessedPtr = LI->getPointerOperand();
Artur Pilipenko0e21d542015-06-25 12:18:43 +0000288 AccessedAlign = LI->getAlignment();
289 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000290 AccessedPtr = SI->getPointerOperand();
Artur Pilipenko0e21d542015-06-25 12:18:43 +0000291 AccessedAlign = SI->getAlignment();
292 } else
293 continue;
294
295 Type *AccessedTy = AccessedPtr->getType()->getPointerElementType();
296 if (AccessedAlign == 0)
297 AccessedAlign = DL.getABITypeAlignment(AccessedTy);
298 if (AccessedAlign < Align)
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000299 continue;
300
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000301 // Handle trivial cases.
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000302 if (AccessedPtr == V)
303 return true;
304
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000305 if (AreEquivalentAddressValues(AccessedPtr->stripPointerCasts(), V) &&
Artur Pilipenko0e21d542015-06-25 12:18:43 +0000306 LoadSize <= DL.getTypeStoreSize(AccessedTy))
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000307 return true;
Dan Gohman826bdf82010-05-28 16:19:17 +0000308 }
309 return false;
310}
311
Larisse Voufo532bf712015-09-18 19:14:35 +0000312/// DefMaxInstsToScan - the default number of maximum instructions
313/// to scan in the block, used by FindAvailableLoadedValue().
314/// FindAvailableLoadedValue() was introduced in r60148, to improve jump
315/// threading in part by eliminating partially redundant loads.
316/// At that point, the value of MaxInstsToScan was already set to '6'
317/// without documented explanation.
318cl::opt<unsigned>
319llvm::DefMaxInstsToScan("available-load-scan-limit", cl::init(6), cl::Hidden,
320 cl::desc("Use this to specify the default maximum number of instructions "
321 "to scan backward from a given instruction, when searching for "
322 "available loaded value"));
323
Chandler Carruthb56052f2014-10-18 23:31:55 +0000324/// \brief Scan the ScanBB block backwards to see if we have the value at the
Dan Gohman826bdf82010-05-28 16:19:17 +0000325/// memory address *Ptr locally available within a small number of instructions.
Dan Gohman826bdf82010-05-28 16:19:17 +0000326///
Chandler Carruthb56052f2014-10-18 23:31:55 +0000327/// The scan starts from \c ScanFrom. \c MaxInstsToScan specifies the maximum
328/// instructions to scan in the block. If it is set to \c 0, it will scan the whole
329/// block.
Dan Gohman826bdf82010-05-28 16:19:17 +0000330///
Chandler Carruthb56052f2014-10-18 23:31:55 +0000331/// If the value is available, this function returns it. If not, it returns the
332/// iterator for the last validated instruction that the value would be live
333/// through. If we scanned the entire block and didn't find something that
334/// invalidates \c *Ptr or provides it, \c ScanFrom is left at the last
335/// instruction processed and this returns null.
Chris Lattner87fa77b2012-03-13 18:07:41 +0000336///
Chandler Carruthb56052f2014-10-18 23:31:55 +0000337/// You can also optionally specify an alias analysis implementation, which
338/// makes this more precise.
339///
340/// If \c AATags is non-null and a load or store is found, the AA tags from the
341/// load or store are recorded there. If there are no AA tags or if no access is
342/// found, it is left unmodified.
Eduard Burtescue2a69172016-01-22 01:51:51 +0000343Value *llvm::FindAvailableLoadedValue(LoadInst *Load, BasicBlock *ScanBB,
Dan Gohman826bdf82010-05-28 16:19:17 +0000344 BasicBlock::iterator &ScanFrom,
345 unsigned MaxInstsToScan,
Chandler Carruthd67244d2014-10-18 23:19:03 +0000346 AliasAnalysis *AA, AAMDNodes *AATags) {
347 if (MaxInstsToScan == 0)
348 MaxInstsToScan = ~0U;
Dan Gohman826bdf82010-05-28 16:19:17 +0000349
Eduard Burtescue2a69172016-01-22 01:51:51 +0000350 Value *Ptr = Load->getPointerOperand();
351 Type *AccessTy = Load->getType();
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000352
Philip Reames92c43692016-04-21 16:51:08 +0000353 // We can never remove a volatile load
354 if (Load->isVolatile())
355 return nullptr;
356
357 // Anything stronger than unordered is currently unimplemented.
358 if (!Load->isUnordered())
359 return nullptr;
360
Mehdi Amini46a43552015-03-04 18:43:29 +0000361 const DataLayout &DL = ScanBB->getModule()->getDataLayout();
Chandler Carruth1a3c2c42014-11-25 08:20:27 +0000362
363 // Try to get the store size for the type.
Mehdi Amini46a43552015-03-04 18:43:29 +0000364 uint64_t AccessSize = DL.getTypeStoreSize(AccessTy);
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000365
366 Value *StrippedPtr = Ptr->stripPointerCasts();
Chandler Carruthd67244d2014-10-18 23:19:03 +0000367
Dan Gohman826bdf82010-05-28 16:19:17 +0000368 while (ScanFrom != ScanBB->begin()) {
369 // We must ignore debug info directives when counting (otherwise they
370 // would affect codegen).
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000371 Instruction *Inst = &*--ScanFrom;
Dan Gohman826bdf82010-05-28 16:19:17 +0000372 if (isa<DbgInfoIntrinsic>(Inst))
373 continue;
374
375 // Restore ScanFrom to expected value in case next test succeeds
376 ScanFrom++;
Chandler Carruthd67244d2014-10-18 23:19:03 +0000377
Dan Gohman826bdf82010-05-28 16:19:17 +0000378 // Don't scan huge blocks.
Chandler Carruthd67244d2014-10-18 23:19:03 +0000379 if (MaxInstsToScan-- == 0)
380 return nullptr;
381
Dan Gohman826bdf82010-05-28 16:19:17 +0000382 --ScanFrom;
383 // If this is a load of Ptr, the loaded value is available.
Eli Friedman4419cd22011-08-15 21:56:39 +0000384 // (This is true even if the load is volatile or atomic, although
385 // those cases are unlikely.)
Dan Gohman826bdf82010-05-28 16:19:17 +0000386 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000387 if (AreEquivalentAddressValues(
388 LI->getPointerOperand()->stripPointerCasts(), StrippedPtr) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000389 CastInst::isBitOrNoopPointerCastable(LI->getType(), AccessTy, DL)) {
Philip Reames92c43692016-04-21 16:51:08 +0000390
391 // We can value forward from an atomic to a non-atomic, but not the
392 // other way around.
393 if (LI->isAtomic() < Load->isAtomic())
394 return nullptr;
395
Chandler Carruthd67244d2014-10-18 23:19:03 +0000396 if (AATags)
397 LI->getAAMetadata(*AATags);
Dan Gohman826bdf82010-05-28 16:19:17 +0000398 return LI;
Chris Lattner87fa77b2012-03-13 18:07:41 +0000399 }
Chandler Carruthd67244d2014-10-18 23:19:03 +0000400
Dan Gohman826bdf82010-05-28 16:19:17 +0000401 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000402 Value *StorePtr = SI->getPointerOperand()->stripPointerCasts();
Dan Gohman826bdf82010-05-28 16:19:17 +0000403 // If this is a store through Ptr, the value is available!
Eli Friedman4419cd22011-08-15 21:56:39 +0000404 // (This is true even if the store is volatile or atomic, although
405 // those cases are unlikely.)
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000406 if (AreEquivalentAddressValues(StorePtr, StrippedPtr) &&
Chandler Carruth1a3c2c42014-11-25 08:20:27 +0000407 CastInst::isBitOrNoopPointerCastable(SI->getValueOperand()->getType(),
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000408 AccessTy, DL)) {
Philip Reames92c43692016-04-21 16:51:08 +0000409
410 // We can value forward from an atomic to a non-atomic, but not the
411 // other way around.
412 if (SI->isAtomic() < Load->isAtomic())
413 return nullptr;
414
Chandler Carruthd67244d2014-10-18 23:19:03 +0000415 if (AATags)
416 SI->getAAMetadata(*AATags);
Dan Gohman826bdf82010-05-28 16:19:17 +0000417 return SI->getOperand(0);
Chris Lattner87fa77b2012-03-13 18:07:41 +0000418 }
Chandler Carruthd67244d2014-10-18 23:19:03 +0000419
Chandler Carrutha32038b2014-10-20 10:03:01 +0000420 // If both StrippedPtr and StorePtr reach all the way to an alloca or
421 // global and they are different, ignore the store. This is a trivial form
422 // of alias analysis that is important for reg2mem'd code.
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000423 if ((isa<AllocaInst>(StrippedPtr) || isa<GlobalVariable>(StrippedPtr)) &&
Chandler Carrutha32038b2014-10-20 10:03:01 +0000424 (isa<AllocaInst>(StorePtr) || isa<GlobalVariable>(StorePtr)) &&
425 StrippedPtr != StorePtr)
Dan Gohman826bdf82010-05-28 16:19:17 +0000426 continue;
Chandler Carruthd67244d2014-10-18 23:19:03 +0000427
Dan Gohman826bdf82010-05-28 16:19:17 +0000428 // If we have alias analysis and it says the store won't modify the loaded
429 // value, ignore the store.
Chandler Carruth194f59c2015-07-22 23:15:57 +0000430 if (AA && (AA->getModRefInfo(SI, StrippedPtr, AccessSize) & MRI_Mod) == 0)
Dan Gohman826bdf82010-05-28 16:19:17 +0000431 continue;
Chandler Carruthd67244d2014-10-18 23:19:03 +0000432
Dan Gohman826bdf82010-05-28 16:19:17 +0000433 // Otherwise the store that may or may not alias the pointer, bail out.
434 ++ScanFrom;
Craig Topper9f008862014-04-15 04:59:12 +0000435 return nullptr;
Dan Gohman826bdf82010-05-28 16:19:17 +0000436 }
Chandler Carruthd67244d2014-10-18 23:19:03 +0000437
Dan Gohman826bdf82010-05-28 16:19:17 +0000438 // If this is some other instruction that may clobber Ptr, bail out.
439 if (Inst->mayWriteToMemory()) {
440 // If alias analysis claims that it really won't modify the load,
441 // ignore it.
442 if (AA &&
Chandler Carruth194f59c2015-07-22 23:15:57 +0000443 (AA->getModRefInfo(Inst, StrippedPtr, AccessSize) & MRI_Mod) == 0)
Dan Gohman826bdf82010-05-28 16:19:17 +0000444 continue;
Chandler Carruthd67244d2014-10-18 23:19:03 +0000445
Dan Gohman826bdf82010-05-28 16:19:17 +0000446 // May modify the pointer, bail out.
447 ++ScanFrom;
Craig Topper9f008862014-04-15 04:59:12 +0000448 return nullptr;
Dan Gohman826bdf82010-05-28 16:19:17 +0000449 }
450 }
Chandler Carruthd67244d2014-10-18 23:19:03 +0000451
Dan Gohman826bdf82010-05-28 16:19:17 +0000452 // Got to the start of the block, we didn't find it, but are done for this
453 // block.
Craig Topper9f008862014-04-15 04:59:12 +0000454 return nullptr;
Dan Gohman826bdf82010-05-28 16:19:17 +0000455}