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