1 //===- Loads.cpp - Local load analysis ------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines simple local analyses for load instructions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/Analysis/Loads.h"
14 #include "llvm/Analysis/AliasAnalysis.h"
15 #include "llvm/Analysis/AssumeBundleQueries.h"
16 #include "llvm/Analysis/CaptureTracking.h"
17 #include "llvm/Analysis/LoopInfo.h"
18 #include "llvm/Analysis/MemoryBuiltins.h"
19 #include "llvm/Analysis/ScalarEvolution.h"
20 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
21 #include "llvm/Analysis/TargetLibraryInfo.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/GlobalAlias.h"
25 #include "llvm/IR/GlobalVariable.h"
26 #include "llvm/IR/IntrinsicInst.h"
27 #include "llvm/IR/LLVMContext.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/Operator.h"
30 #include "llvm/IR/Statepoint.h"
31 
32 using namespace llvm;
33 
34 static bool isAligned(const Value *Base, const APInt &Offset, Align Alignment,
35                       const DataLayout &DL) {
36   Align BA = Base->getPointerAlignment(DL);
37   const APInt APAlign(Offset.getBitWidth(), Alignment.value());
38   assert(APAlign.isPowerOf2() && "must be a power of 2!");
39   return BA >= Alignment && !(Offset & (APAlign - 1));
40 }
41 
42 /// Test if V is always a pointer to allocated and suitably aligned memory for
43 /// a simple load or store.
44 static bool isDereferenceableAndAlignedPointer(
45     const Value *V, Align Alignment, const APInt &Size, const DataLayout &DL,
46     const Instruction *CtxI, const DominatorTree *DT,
47     const TargetLibraryInfo *TLI, SmallPtrSetImpl<const Value *> &Visited,
48     unsigned MaxDepth) {
49   assert(V->getType()->isPointerTy() && "Base must be pointer");
50 
51   // Recursion limit.
52   if (MaxDepth-- == 0)
53     return false;
54 
55   // Already visited?  Bail out, we've likely hit unreachable code.
56   if (!Visited.insert(V).second)
57     return false;
58 
59   // Note that it is not safe to speculate into a malloc'd region because
60   // malloc may return null.
61 
62   // bitcast instructions are no-ops as far as dereferenceability is concerned.
63   if (const BitCastOperator *BC = dyn_cast<BitCastOperator>(V)) {
64     if (BC->getSrcTy()->isPointerTy())
65       return isDereferenceableAndAlignedPointer(
66           BC->getOperand(0), Alignment, Size, DL, CtxI, DT, TLI,
67           Visited, MaxDepth);
68   }
69 
70   bool CheckForNonNull = false;
71   APInt KnownDerefBytes(Size.getBitWidth(),
72                         V->getPointerDereferenceableBytes(DL, CheckForNonNull));
73   if (KnownDerefBytes.getBoolValue() && KnownDerefBytes.uge(Size))
74     if (!CheckForNonNull || isKnownNonZero(V, DL, 0, nullptr, CtxI, DT)) {
75       // As we recursed through GEPs to get here, we've incrementally checked
76       // that each step advanced by a multiple of the alignment. If our base is
77       // properly aligned, then the original offset accessed must also be.
78       Type *Ty = V->getType();
79       assert(Ty->isSized() && "must be sized");
80       APInt Offset(DL.getTypeStoreSizeInBits(Ty), 0);
81       return isAligned(V, Offset, Alignment, DL);
82     }
83 
84   if (CtxI) {
85     /// Look through assumes to see if both dereferencability and alignment can
86     /// be provent by an assume
87     RetainedKnowledge AlignRK;
88     RetainedKnowledge DerefRK;
89     if (getKnowledgeForValue(
90             V, {Attribute::Dereferenceable, Attribute::Alignment}, nullptr,
91             [&](RetainedKnowledge RK, Instruction *Assume, auto) {
92               if (!isValidAssumeForContext(Assume, CtxI))
93                 return false;
94               if (RK.AttrKind == Attribute::Alignment)
95                 AlignRK = std::max(AlignRK, RK);
96               if (RK.AttrKind == Attribute::Dereferenceable)
97                 DerefRK = std::max(DerefRK, RK);
98               if (AlignRK && DerefRK && AlignRK.ArgValue >= Alignment.value() &&
99                   DerefRK.ArgValue >= Size.getZExtValue())
100                 return true; // We have found what we needed so we stop looking
101               return false;  // Other assumes may have better information. so
102                              // keep looking
103             }))
104       return true;
105   }
106   /// TODO refactor this function to be able to search independently for
107   /// Dereferencability and Alignment requirements.
108 
109   // For GEPs, determine if the indexing lands within the allocated object.
110   if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
111     const Value *Base = GEP->getPointerOperand();
112 
113     APInt Offset(DL.getIndexTypeSizeInBits(GEP->getType()), 0);
114     if (!GEP->accumulateConstantOffset(DL, Offset) || Offset.isNegative() ||
115         !Offset.urem(APInt(Offset.getBitWidth(), Alignment.value()))
116              .isMinValue())
117       return false;
118 
119     // If the base pointer is dereferenceable for Offset+Size bytes, then the
120     // GEP (== Base + Offset) is dereferenceable for Size bytes.  If the base
121     // pointer is aligned to Align bytes, and the Offset is divisible by Align
122     // then the GEP (== Base + Offset == k_0 * Align + k_1 * Align) is also
123     // aligned to Align bytes.
124 
125     // Offset and Size may have different bit widths if we have visited an
126     // addrspacecast, so we can't do arithmetic directly on the APInt values.
127     return isDereferenceableAndAlignedPointer(
128         Base, Alignment, Offset + Size.sextOrTrunc(Offset.getBitWidth()), DL,
129         CtxI, DT, TLI, Visited, MaxDepth);
130   }
131 
132   // For gc.relocate, look through relocations
133   if (const GCRelocateInst *RelocateInst = dyn_cast<GCRelocateInst>(V))
134     return isDereferenceableAndAlignedPointer(RelocateInst->getDerivedPtr(),
135                                               Alignment, Size, DL, CtxI, DT,
136                                               TLI, Visited, MaxDepth);
137 
138   if (const AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(V))
139     return isDereferenceableAndAlignedPointer(ASC->getOperand(0), Alignment,
140                                               Size, DL, CtxI, DT, TLI,
141                                               Visited, MaxDepth);
142 
143   if (const auto *Call = dyn_cast<CallBase>(V)) {
144     if (auto *RP = getArgumentAliasingToReturnedPointer(Call, true))
145       return isDereferenceableAndAlignedPointer(RP, Alignment, Size, DL, CtxI,
146                                                 DT, TLI, Visited, MaxDepth);
147 
148     // If we have a call we can't recurse through, check to see if this is an
149     // allocation function for which we can establish an minimum object size.
150     // Such a minimum object size is analogous to a deref_or_null attribute in
151     // that we still need to prove the result non-null at point of use.
152     // NOTE: We can only use the object size as a base fact as we a) need to
153     // prove alignment too, and b) don't want the compile time impact of a
154     // separate recursive walk.
155     ObjectSizeOpts Opts;
156     // TODO: It may be okay to round to align, but that would imply that
157     // accessing slightly out of bounds was legal, and we're currently
158     // inconsistent about that.  For the moment, be conservative.
159     Opts.RoundToAlign = false;
160     Opts.NullIsUnknownSize = true;
161     uint64_t ObjSize;
162     // TODO: Plumb through TLI so that malloc routines and such working.
163     if (getObjectSize(V, ObjSize, DL, nullptr, Opts)) {
164       APInt KnownDerefBytes(Size.getBitWidth(), ObjSize);
165       if (KnownDerefBytes.getBoolValue() && KnownDerefBytes.uge(Size) &&
166           isKnownNonZero(V, DL, 0, nullptr, CtxI, DT) &&
167           // TODO: We're currently inconsistent about whether deref(N) is a
168           // global fact or a point in time fact.  Once D61652 eventually
169           // lands, this check will be restricted to the point in time
170           // variant. For that variant, we need to prove that object hasn't
171           // been conditionally freed before ontext instruction - if it has, we
172           // might be hoisting over the inverse conditional and creating a
173           // dynamic use after free.
174           !PointerMayBeCapturedBefore(V, true, true, CtxI, DT, true)) {
175         // As we recursed through GEPs to get here, we've incrementally
176         // checked that each step advanced by a multiple of the alignment. If
177         // our base is properly aligned, then the original offset accessed
178         // must also be.
179         Type *Ty = V->getType();
180         assert(Ty->isSized() && "must be sized");
181         APInt Offset(DL.getTypeStoreSizeInBits(Ty), 0);
182         return isAligned(V, Offset, Alignment, DL);
183       }
184     }
185   }
186 
187   // If we don't know, assume the worst.
188   return false;
189 }
190 
191 bool llvm::isDereferenceableAndAlignedPointer(const Value *V, Align Alignment,
192                                               const APInt &Size,
193                                               const DataLayout &DL,
194                                               const Instruction *CtxI,
195                                               const DominatorTree *DT,
196                                               const TargetLibraryInfo *TLI) {
197   // Note: At the moment, Size can be zero.  This ends up being interpreted as
198   // a query of whether [Base, V] is dereferenceable and V is aligned (since
199   // that's what the implementation happened to do).  It's unclear if this is
200   // the desired semantic, but at least SelectionDAG does exercise this case.
201 
202   SmallPtrSet<const Value *, 32> Visited;
203   return ::isDereferenceableAndAlignedPointer(V, Alignment, Size, DL, CtxI, DT,
204                                               TLI, Visited, 16);
205 }
206 
207 bool llvm::isDereferenceableAndAlignedPointer(const Value *V, Type *Ty,
208                                               MaybeAlign MA,
209                                               const DataLayout &DL,
210                                               const Instruction *CtxI,
211                                               const DominatorTree *DT,
212                                               const TargetLibraryInfo *TLI) {
213   // For unsized types or scalable vectors we don't know exactly how many bytes
214   // are dereferenced, so bail out.
215   if (!Ty->isSized() || isa<ScalableVectorType>(Ty))
216     return false;
217 
218   // When dereferenceability information is provided by a dereferenceable
219   // attribute, we know exactly how many bytes are dereferenceable. If we can
220   // determine the exact offset to the attributed variable, we can use that
221   // information here.
222 
223   // Require ABI alignment for loads without alignment specification
224   const Align Alignment = DL.getValueOrABITypeAlignment(MA, Ty);
225   APInt AccessSize(DL.getPointerTypeSizeInBits(V->getType()),
226                    DL.getTypeStoreSize(Ty));
227   return isDereferenceableAndAlignedPointer(V, Alignment, AccessSize, DL, CtxI,
228                                             DT, TLI);
229 }
230 
231 bool llvm::isDereferenceablePointer(const Value *V, Type *Ty,
232                                     const DataLayout &DL,
233                                     const Instruction *CtxI,
234                                     const DominatorTree *DT,
235                                     const TargetLibraryInfo *TLI) {
236   return isDereferenceableAndAlignedPointer(V, Ty, Align(1), DL, CtxI, DT, TLI);
237 }
238 
239 /// Test if A and B will obviously have the same value.
240 ///
241 /// This includes recognizing that %t0 and %t1 will have the same
242 /// value in code like this:
243 /// \code
244 ///   %t0 = getelementptr \@a, 0, 3
245 ///   store i32 0, i32* %t0
246 ///   %t1 = getelementptr \@a, 0, 3
247 ///   %t2 = load i32* %t1
248 /// \endcode
249 ///
250 static bool AreEquivalentAddressValues(const Value *A, const Value *B) {
251   // Test if the values are trivially equivalent.
252   if (A == B)
253     return true;
254 
255   // Test if the values come from identical arithmetic instructions.
256   // Use isIdenticalToWhenDefined instead of isIdenticalTo because
257   // this function is only used when one address use dominates the
258   // other, which means that they'll always either have the same
259   // value or one of them will have an undefined value.
260   if (isa<BinaryOperator>(A) || isa<CastInst>(A) || isa<PHINode>(A) ||
261       isa<GetElementPtrInst>(A))
262     if (const Instruction *BI = dyn_cast<Instruction>(B))
263       if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
264         return true;
265 
266   // Otherwise they may not be equivalent.
267   return false;
268 }
269 
270 bool llvm::isDereferenceableAndAlignedInLoop(LoadInst *LI, Loop *L,
271                                              ScalarEvolution &SE,
272                                              DominatorTree &DT) {
273   auto &DL = LI->getModule()->getDataLayout();
274   Value *Ptr = LI->getPointerOperand();
275 
276   APInt EltSize(DL.getIndexTypeSizeInBits(Ptr->getType()),
277                 DL.getTypeStoreSize(LI->getType()).getFixedSize());
278   const Align Alignment = LI->getAlign();
279 
280   Instruction *HeaderFirstNonPHI = L->getHeader()->getFirstNonPHI();
281 
282   // If given a uniform (i.e. non-varying) address, see if we can prove the
283   // access is safe within the loop w/o needing predication.
284   if (L->isLoopInvariant(Ptr))
285     return isDereferenceableAndAlignedPointer(Ptr, Alignment, EltSize, DL,
286                                               HeaderFirstNonPHI, &DT);
287 
288   // Otherwise, check to see if we have a repeating access pattern where we can
289   // prove that all accesses are well aligned and dereferenceable.
290   auto *AddRec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Ptr));
291   if (!AddRec || AddRec->getLoop() != L || !AddRec->isAffine())
292     return false;
293   auto* Step = dyn_cast<SCEVConstant>(AddRec->getStepRecurrence(SE));
294   if (!Step)
295     return false;
296   // TODO: generalize to access patterns which have gaps
297   if (Step->getAPInt() != EltSize)
298     return false;
299 
300   auto TC = SE.getSmallConstantMaxTripCount(L);
301   if (!TC)
302     return false;
303 
304   const APInt AccessSize = TC * EltSize;
305 
306   auto *StartS = dyn_cast<SCEVUnknown>(AddRec->getStart());
307   if (!StartS)
308     return false;
309   assert(SE.isLoopInvariant(StartS, L) && "implied by addrec definition");
310   Value *Base = StartS->getValue();
311 
312   // For the moment, restrict ourselves to the case where the access size is a
313   // multiple of the requested alignment and the base is aligned.
314   // TODO: generalize if a case found which warrants
315   if (EltSize.urem(Alignment.value()) != 0)
316     return false;
317   return isDereferenceableAndAlignedPointer(Base, Alignment, AccessSize, DL,
318                                             HeaderFirstNonPHI, &DT);
319 }
320 
321 /// Check if executing a load of this pointer value cannot trap.
322 ///
323 /// If DT and ScanFrom are specified this method performs context-sensitive
324 /// analysis and returns true if it is safe to load immediately before ScanFrom.
325 ///
326 /// If it is not obviously safe to load from the specified pointer, we do
327 /// a quick local scan of the basic block containing \c ScanFrom, to determine
328 /// if the address is already accessed.
329 ///
330 /// This uses the pointee type to determine how many bytes need to be safe to
331 /// load from the pointer.
332 bool llvm::isSafeToLoadUnconditionally(Value *V, Align Alignment, APInt &Size,
333                                        const DataLayout &DL,
334                                        Instruction *ScanFrom,
335                                        const DominatorTree *DT,
336                                        const TargetLibraryInfo *TLI) {
337   // If DT is not specified we can't make context-sensitive query
338   const Instruction* CtxI = DT ? ScanFrom : nullptr;
339   if (isDereferenceableAndAlignedPointer(V, Alignment, Size, DL, CtxI, DT, TLI))
340     return true;
341 
342   if (!ScanFrom)
343     return false;
344 
345   if (Size.getBitWidth() > 64)
346     return false;
347   const uint64_t LoadSize = Size.getZExtValue();
348 
349   // Otherwise, be a little bit aggressive by scanning the local block where we
350   // want to check to see if the pointer is already being loaded or stored
351   // from/to.  If so, the previous load or store would have already trapped,
352   // so there is no harm doing an extra load (also, CSE will later eliminate
353   // the load entirely).
354   BasicBlock::iterator BBI = ScanFrom->getIterator(),
355                        E = ScanFrom->getParent()->begin();
356 
357   // We can at least always strip pointer casts even though we can't use the
358   // base here.
359   V = V->stripPointerCasts();
360 
361   while (BBI != E) {
362     --BBI;
363 
364     // If we see a free or a call which may write to memory (i.e. which might do
365     // a free) the pointer could be marked invalid.
366     if (isa<CallInst>(BBI) && BBI->mayWriteToMemory() &&
367         !isa<DbgInfoIntrinsic>(BBI))
368       return false;
369 
370     Value *AccessedPtr;
371     Type *AccessedTy;
372     Align AccessedAlign;
373     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
374       // Ignore volatile loads. The execution of a volatile load cannot
375       // be used to prove an address is backed by regular memory; it can,
376       // for example, point to an MMIO register.
377       if (LI->isVolatile())
378         continue;
379       AccessedPtr = LI->getPointerOperand();
380       AccessedTy = LI->getType();
381       AccessedAlign = LI->getAlign();
382     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
383       // Ignore volatile stores (see comment for loads).
384       if (SI->isVolatile())
385         continue;
386       AccessedPtr = SI->getPointerOperand();
387       AccessedTy = SI->getValueOperand()->getType();
388       AccessedAlign = SI->getAlign();
389     } else
390       continue;
391 
392     if (AccessedAlign < Alignment)
393       continue;
394 
395     // Handle trivial cases.
396     if (AccessedPtr == V &&
397         LoadSize <= DL.getTypeStoreSize(AccessedTy))
398       return true;
399 
400     if (AreEquivalentAddressValues(AccessedPtr->stripPointerCasts(), V) &&
401         LoadSize <= DL.getTypeStoreSize(AccessedTy))
402       return true;
403   }
404   return false;
405 }
406 
407 bool llvm::isSafeToLoadUnconditionally(Value *V, Type *Ty, Align Alignment,
408                                        const DataLayout &DL,
409                                        Instruction *ScanFrom,
410                                        const DominatorTree *DT,
411                                        const TargetLibraryInfo *TLI) {
412   APInt Size(DL.getIndexTypeSizeInBits(V->getType()), DL.getTypeStoreSize(Ty));
413   return isSafeToLoadUnconditionally(V, Alignment, Size, DL, ScanFrom, DT, TLI);
414 }
415 
416   /// DefMaxInstsToScan - the default number of maximum instructions
417 /// to scan in the block, used by FindAvailableLoadedValue().
418 /// FindAvailableLoadedValue() was introduced in r60148, to improve jump
419 /// threading in part by eliminating partially redundant loads.
420 /// At that point, the value of MaxInstsToScan was already set to '6'
421 /// without documented explanation.
422 cl::opt<unsigned>
423 llvm::DefMaxInstsToScan("available-load-scan-limit", cl::init(6), cl::Hidden,
424   cl::desc("Use this to specify the default maximum number of instructions "
425            "to scan backward from a given instruction, when searching for "
426            "available loaded value"));
427 
428 Value *llvm::FindAvailableLoadedValue(LoadInst *Load,
429                                       BasicBlock *ScanBB,
430                                       BasicBlock::iterator &ScanFrom,
431                                       unsigned MaxInstsToScan,
432                                       AAResults *AA, bool *IsLoad,
433                                       unsigned *NumScanedInst) {
434   // Don't CSE load that is volatile or anything stronger than unordered.
435   if (!Load->isUnordered())
436     return nullptr;
437 
438   return FindAvailablePtrLoadStore(
439       Load->getPointerOperand(), Load->getType(), Load->isAtomic(), ScanBB,
440       ScanFrom, MaxInstsToScan, AA, IsLoad, NumScanedInst);
441 }
442 
443 // Check if the load and the store have the same base, constant offsets and
444 // non-overlapping access ranges.
445 static bool AreNonOverlapSameBaseLoadAndStore(
446     Value *LoadPtr, Type *LoadTy, Value *StorePtr, Type *StoreTy,
447     const DataLayout &DL) {
448   APInt LoadOffset(DL.getTypeSizeInBits(LoadPtr->getType()), 0);
449   APInt StoreOffset(DL.getTypeSizeInBits(StorePtr->getType()), 0);
450   Value *LoadBase = LoadPtr->stripAndAccumulateConstantOffsets(
451       DL, LoadOffset, /* AllowNonInbounds */ false);
452   Value *StoreBase = StorePtr->stripAndAccumulateConstantOffsets(
453       DL, StoreOffset, /* AllowNonInbounds */ false);
454   if (LoadBase != StoreBase)
455     return false;
456   auto LoadAccessSize = LocationSize::precise(DL.getTypeStoreSize(LoadTy));
457   auto StoreAccessSize = LocationSize::precise(DL.getTypeStoreSize(StoreTy));
458   ConstantRange LoadRange(LoadOffset,
459                           LoadOffset + LoadAccessSize.toRaw());
460   ConstantRange StoreRange(StoreOffset,
461                            StoreOffset + StoreAccessSize.toRaw());
462   return LoadRange.intersectWith(StoreRange).isEmptySet();
463 }
464 
465 static Value *getAvailableLoadStore(Instruction *Inst, Value *Ptr,
466                                     Type *AccessTy, bool AtLeastAtomic,
467                                     const DataLayout &DL, bool *IsLoadCSE) {
468   // If this is a load of Ptr, the loaded value is available.
469   // (This is true even if the load is volatile or atomic, although
470   // those cases are unlikely.)
471   if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
472     // We can value forward from an atomic to a non-atomic, but not the
473     // other way around.
474     if (LI->isAtomic() < AtLeastAtomic)
475       return nullptr;
476 
477     Value *LoadPtr = LI->getPointerOperand()->stripPointerCasts();
478     if (!AreEquivalentAddressValues(LoadPtr, Ptr))
479       return nullptr;
480 
481     if (CastInst::isBitOrNoopPointerCastable(LI->getType(), AccessTy, DL)) {
482       if (IsLoadCSE)
483         *IsLoadCSE = true;
484       return LI;
485     }
486   }
487 
488   // If this is a store through Ptr, the value is available!
489   // (This is true even if the store is volatile or atomic, although
490   // those cases are unlikely.)
491   if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
492     // We can value forward from an atomic to a non-atomic, but not the
493     // other way around.
494     if (SI->isAtomic() < AtLeastAtomic)
495       return nullptr;
496 
497     Value *StorePtr = SI->getPointerOperand()->stripPointerCasts();
498     if (!AreEquivalentAddressValues(StorePtr, Ptr))
499       return nullptr;
500 
501     Value *Val = SI->getValueOperand();
502     if (CastInst::isBitOrNoopPointerCastable(Val->getType(), AccessTy, DL)) {
503       if (IsLoadCSE)
504         *IsLoadCSE = false;
505       return Val;
506     }
507   }
508 
509   return nullptr;
510 }
511 
512 Value *llvm::FindAvailablePtrLoadStore(Value *Ptr, Type *AccessTy,
513                                        bool AtLeastAtomic, BasicBlock *ScanBB,
514                                        BasicBlock::iterator &ScanFrom,
515                                        unsigned MaxInstsToScan,
516                                        AAResults *AA, bool *IsLoadCSE,
517                                        unsigned *NumScanedInst) {
518   if (MaxInstsToScan == 0)
519     MaxInstsToScan = ~0U;
520 
521   const DataLayout &DL = ScanBB->getModule()->getDataLayout();
522   Value *StrippedPtr = Ptr->stripPointerCasts();
523 
524   while (ScanFrom != ScanBB->begin()) {
525     // We must ignore debug info directives when counting (otherwise they
526     // would affect codegen).
527     Instruction *Inst = &*--ScanFrom;
528     if (isa<DbgInfoIntrinsic>(Inst))
529       continue;
530 
531     // Restore ScanFrom to expected value in case next test succeeds
532     ScanFrom++;
533 
534     if (NumScanedInst)
535       ++(*NumScanedInst);
536 
537     // Don't scan huge blocks.
538     if (MaxInstsToScan-- == 0)
539       return nullptr;
540 
541     --ScanFrom;
542 
543     if (Value *Available = getAvailableLoadStore(Inst, StrippedPtr, AccessTy,
544                                                  AtLeastAtomic, DL, IsLoadCSE))
545       return Available;
546 
547     // Try to get the store size for the type.
548     auto AccessSize = LocationSize::precise(DL.getTypeStoreSize(AccessTy));
549 
550     if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
551       Value *StorePtr = SI->getPointerOperand()->stripPointerCasts();
552 
553       // If both StrippedPtr and StorePtr reach all the way to an alloca or
554       // global and they are different, ignore the store. This is a trivial form
555       // of alias analysis that is important for reg2mem'd code.
556       if ((isa<AllocaInst>(StrippedPtr) || isa<GlobalVariable>(StrippedPtr)) &&
557           (isa<AllocaInst>(StorePtr) || isa<GlobalVariable>(StorePtr)) &&
558           StrippedPtr != StorePtr)
559         continue;
560 
561       if (!AA) {
562         // When AA isn't available, but if the load and the store have the same
563         // base, constant offsets and non-overlapping access ranges, ignore the
564         // store. This is a simple form of alias analysis that is used by the
565         // inliner. FIXME: use BasicAA if possible.
566         if (AreNonOverlapSameBaseLoadAndStore(
567                 Ptr, AccessTy, SI->getPointerOperand(),
568                 SI->getValueOperand()->getType(), DL))
569           continue;
570       } else {
571         // If we have alias analysis and it says the store won't modify the
572         // loaded value, ignore the store.
573         if (!isModSet(AA->getModRefInfo(SI, StrippedPtr, AccessSize)))
574           continue;
575       }
576 
577       // Otherwise the store that may or may not alias the pointer, bail out.
578       ++ScanFrom;
579       return nullptr;
580     }
581 
582     // If this is some other instruction that may clobber Ptr, bail out.
583     if (Inst->mayWriteToMemory()) {
584       // If alias analysis claims that it really won't modify the load,
585       // ignore it.
586       if (AA && !isModSet(AA->getModRefInfo(Inst, StrippedPtr, AccessSize)))
587         continue;
588 
589       // May modify the pointer, bail out.
590       ++ScanFrom;
591       return nullptr;
592     }
593   }
594 
595   // Got to the start of the block, we didn't find it, but are done for this
596   // block.
597   return nullptr;
598 }
599 
600 Value *llvm::FindAvailableLoadedValue(LoadInst *Load, AAResults &AA,
601                                       bool *IsLoadCSE,
602                                       unsigned MaxInstsToScan) {
603   const DataLayout &DL = Load->getModule()->getDataLayout();
604   Value *StrippedPtr = Load->getPointerOperand()->stripPointerCasts();
605   BasicBlock *ScanBB = Load->getParent();
606   Type *AccessTy = Load->getType();
607   bool AtLeastAtomic = Load->isAtomic();
608 
609   if (!Load->isUnordered())
610     return nullptr;
611 
612   // Try to find an available value first, and delay expensive alias analysis
613   // queries until later.
614   Value *Available = nullptr;;
615   SmallVector<Instruction *> MustNotAliasInsts;
616   for (Instruction &Inst : make_range(++Load->getReverseIterator(),
617                                       ScanBB->rend())) {
618     if (isa<DbgInfoIntrinsic>(&Inst))
619       continue;
620 
621     if (MaxInstsToScan-- == 0)
622       return nullptr;
623 
624     Available = getAvailableLoadStore(&Inst, StrippedPtr, AccessTy,
625                                       AtLeastAtomic, DL, IsLoadCSE);
626     if (Available)
627       break;
628 
629     if (Inst.mayWriteToMemory())
630       MustNotAliasInsts.push_back(&Inst);
631   }
632 
633   // If we found an available value, ensure that the instructions in between
634   // did not modify the memory location.
635   if (Available) {
636     auto AccessSize = LocationSize::precise(DL.getTypeStoreSize(AccessTy));
637     for (Instruction *Inst : MustNotAliasInsts)
638       if (isModSet(AA.getModRefInfo(Inst, StrippedPtr, AccessSize)))
639         return nullptr;
640   }
641 
642   return Available;
643 }
644 
645 bool llvm::canReplacePointersIfEqual(Value *A, Value *B, const DataLayout &DL,
646                                      Instruction *CtxI) {
647   Type *Ty = A->getType();
648   assert(Ty == B->getType() && Ty->isPointerTy() &&
649          "values must have matching pointer types");
650 
651   // NOTE: The checks in the function are incomplete and currently miss illegal
652   // cases! The current implementation is a starting point and the
653   // implementation should be made stricter over time.
654   if (auto *C = dyn_cast<Constant>(B)) {
655     // Do not allow replacing a pointer with a constant pointer, unless it is
656     // either null or at least one byte is dereferenceable.
657     APInt OneByte(DL.getPointerTypeSizeInBits(Ty), 1);
658     return C->isNullValue() ||
659            isDereferenceableAndAlignedPointer(B, Align(1), OneByte, DL, CtxI);
660   }
661 
662   return true;
663 }
664