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