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/LoopInfo.h"
16 #include "llvm/Analysis/ScalarEvolution.h"
17 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
18 #include "llvm/Analysis/ValueTracking.h"
19 #include "llvm/IR/DataLayout.h"
20 #include "llvm/IR/GlobalAlias.h"
21 #include "llvm/IR/GlobalVariable.h"
22 #include "llvm/IR/IntrinsicInst.h"
23 #include "llvm/IR/LLVMContext.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/IR/Operator.h"
26 #include "llvm/IR/Statepoint.h"
27 
28 using namespace llvm;
29 
30 static MaybeAlign getBaseAlign(const Value *Base, const DataLayout &DL) {
31   if (const MaybeAlign PA = Base->getPointerAlignment(DL))
32     return *PA;
33   Type *const Ty = Base->getType()->getPointerElementType();
34   if (!Ty->isSized())
35     return None;
36   return Align(DL.getABITypeAlignment(Ty));
37 }
38 
39 static bool isAligned(const Value *Base, const APInt &Offset, Align Alignment,
40                       const DataLayout &DL) {
41   if (MaybeAlign BA = getBaseAlign(Base, DL)) {
42     const APInt APBaseAlign(Offset.getBitWidth(), BA->value());
43     const APInt APAlign(Offset.getBitWidth(), Alignment.value());
44     assert(APAlign.isPowerOf2() && "must be a power of 2!");
45     return APBaseAlign.uge(APAlign) && !(Offset & (APAlign - 1));
46   }
47   return false;
48 }
49 
50 /// Test if V is always a pointer to allocated and suitably aligned memory for
51 /// a simple load or store.
52 static bool isDereferenceableAndAlignedPointer(
53     const Value *V, Align Alignment, const APInt &Size, const DataLayout &DL,
54     const Instruction *CtxI, const DominatorTree *DT,
55     SmallPtrSetImpl<const Value *> &Visited, unsigned MaxDepth) {
56 
57   // Recursion limit.
58   if (MaxDepth-- == 0)
59     return false;
60 
61   // Already visited?  Bail out, we've likely hit unreachable code.
62   if (!Visited.insert(V).second)
63     return false;
64 
65   // Note that it is not safe to speculate into a malloc'd region because
66   // malloc may return null.
67 
68   // bitcast instructions are no-ops as far as dereferenceability is concerned.
69   if (const BitCastOperator *BC = dyn_cast<BitCastOperator>(V))
70     return isDereferenceableAndAlignedPointer(BC->getOperand(0), Alignment,
71                                               Size, DL, CtxI, DT, Visited,
72                                               MaxDepth);
73 
74   bool CheckForNonNull = false;
75   APInt KnownDerefBytes(Size.getBitWidth(),
76                         V->getPointerDereferenceableBytes(DL, CheckForNonNull));
77   if (KnownDerefBytes.getBoolValue() && KnownDerefBytes.uge(Size))
78     if (!CheckForNonNull || isKnownNonZero(V, DL, 0, nullptr, CtxI, DT)) {
79       // As we recursed through GEPs to get here, we've incrementally checked
80       // that each step advanced by a multiple of the alignment. If our base is
81       // properly aligned, then the original offset accessed must also be.
82       Type *Ty = V->getType();
83       assert(Ty->isSized() && "must be sized");
84       APInt Offset(DL.getTypeStoreSizeInBits(Ty), 0);
85       return isAligned(V, Offset, Alignment, DL);
86     }
87 
88   // For GEPs, determine if the indexing lands within the allocated object.
89   if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
90     const Value *Base = GEP->getPointerOperand();
91 
92     APInt Offset(DL.getIndexTypeSizeInBits(GEP->getType()), 0);
93     if (!GEP->accumulateConstantOffset(DL, Offset) || Offset.isNegative() ||
94         !Offset.urem(APInt(Offset.getBitWidth(), Alignment.value()))
95              .isMinValue())
96       return false;
97 
98     // If the base pointer is dereferenceable for Offset+Size bytes, then the
99     // GEP (== Base + Offset) is dereferenceable for Size bytes.  If the base
100     // pointer is aligned to Align bytes, and the Offset is divisible by Align
101     // then the GEP (== Base + Offset == k_0 * Align + k_1 * Align) is also
102     // aligned to Align bytes.
103 
104     // Offset and Size may have different bit widths if we have visited an
105     // addrspacecast, so we can't do arithmetic directly on the APInt values.
106     return isDereferenceableAndAlignedPointer(
107         Base, Alignment, Offset + Size.sextOrTrunc(Offset.getBitWidth()), DL,
108         CtxI, DT, Visited, MaxDepth);
109   }
110 
111   // For gc.relocate, look through relocations
112   if (const GCRelocateInst *RelocateInst = dyn_cast<GCRelocateInst>(V))
113     return isDereferenceableAndAlignedPointer(
114       RelocateInst->getDerivedPtr(), Alignment, Size, DL, CtxI, DT, Visited, MaxDepth);
115 
116   if (const AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(V))
117     return isDereferenceableAndAlignedPointer(ASC->getOperand(0), Alignment,
118                                               Size, DL, CtxI, DT, Visited, MaxDepth);
119 
120   if (const auto *Call = dyn_cast<CallBase>(V))
121     if (auto *RP = getArgumentAliasingToReturnedPointer(Call, true))
122       return isDereferenceableAndAlignedPointer(RP, Alignment, Size, DL, CtxI,
123                                                 DT, Visited, MaxDepth);
124 
125   // If we don't know, assume the worst.
126   return false;
127 }
128 
129 bool llvm::isDereferenceableAndAlignedPointer(const Value *V, Align Alignment,
130                                               const APInt &Size,
131                                               const DataLayout &DL,
132                                               const Instruction *CtxI,
133                                               const DominatorTree *DT) {
134   // Note: At the moment, Size can be zero.  This ends up being interpreted as
135   // a query of whether [Base, V] is dereferenceable and V is aligned (since
136   // that's what the implementation happened to do).  It's unclear if this is
137   // the desired semantic, but at least SelectionDAG does exercise this case.
138 
139   SmallPtrSet<const Value *, 32> Visited;
140   return ::isDereferenceableAndAlignedPointer(V, Alignment, Size, DL, CtxI, DT,
141                                               Visited, 16);
142 }
143 
144 bool llvm::isDereferenceableAndAlignedPointer(const Value *V, Type *Ty,
145                                               MaybeAlign MA,
146                                               const DataLayout &DL,
147                                               const Instruction *CtxI,
148                                               const DominatorTree *DT) {
149   // For unsized types or scalable vectors we don't know exactly how many bytes
150   // are dereferenced, so bail out.
151   if (!Ty->isSized() || isa<ScalableVectorType>(Ty))
152     return false;
153 
154   // When dereferenceability information is provided by a dereferenceable
155   // attribute, we know exactly how many bytes are dereferenceable. If we can
156   // determine the exact offset to the attributed variable, we can use that
157   // information here.
158 
159   // Require ABI alignment for loads without alignment specification
160   const Align Alignment = DL.getValueOrABITypeAlignment(MA, Ty);
161   APInt AccessSize(DL.getPointerTypeSizeInBits(V->getType()),
162                    DL.getTypeStoreSize(Ty));
163   return isDereferenceableAndAlignedPointer(V, Alignment, AccessSize, DL, CtxI,
164                                             DT);
165 }
166 
167 bool llvm::isDereferenceablePointer(const Value *V, Type *Ty,
168                                     const DataLayout &DL,
169                                     const Instruction *CtxI,
170                                     const DominatorTree *DT) {
171   return isDereferenceableAndAlignedPointer(V, Ty, Align(1), DL, CtxI, DT);
172 }
173 
174 /// Test if A and B will obviously have the same value.
175 ///
176 /// This includes recognizing that %t0 and %t1 will have the same
177 /// value in code like this:
178 /// \code
179 ///   %t0 = getelementptr \@a, 0, 3
180 ///   store i32 0, i32* %t0
181 ///   %t1 = getelementptr \@a, 0, 3
182 ///   %t2 = load i32* %t1
183 /// \endcode
184 ///
185 static bool AreEquivalentAddressValues(const Value *A, const Value *B) {
186   // Test if the values are trivially equivalent.
187   if (A == B)
188     return true;
189 
190   // Test if the values come from identical arithmetic instructions.
191   // Use isIdenticalToWhenDefined instead of isIdenticalTo because
192   // this function is only used when one address use dominates the
193   // other, which means that they'll always either have the same
194   // value or one of them will have an undefined value.
195   if (isa<BinaryOperator>(A) || isa<CastInst>(A) || isa<PHINode>(A) ||
196       isa<GetElementPtrInst>(A))
197     if (const Instruction *BI = dyn_cast<Instruction>(B))
198       if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
199         return true;
200 
201   // Otherwise they may not be equivalent.
202   return false;
203 }
204 
205 bool llvm::isDereferenceableAndAlignedInLoop(LoadInst *LI, Loop *L,
206                                              ScalarEvolution &SE,
207                                              DominatorTree &DT) {
208   auto &DL = LI->getModule()->getDataLayout();
209   Value *Ptr = LI->getPointerOperand();
210 
211   APInt EltSize(DL.getIndexTypeSizeInBits(Ptr->getType()),
212                 DL.getTypeStoreSize(LI->getType()));
213   const Align Alignment = LI->getAlign();
214 
215   Instruction *HeaderFirstNonPHI = L->getHeader()->getFirstNonPHI();
216 
217   // If given a uniform (i.e. non-varying) address, see if we can prove the
218   // access is safe within the loop w/o needing predication.
219   if (L->isLoopInvariant(Ptr))
220     return isDereferenceableAndAlignedPointer(Ptr, Alignment, EltSize, DL,
221                                               HeaderFirstNonPHI, &DT);
222 
223   // Otherwise, check to see if we have a repeating access pattern where we can
224   // prove that all accesses are well aligned and dereferenceable.
225   auto *AddRec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Ptr));
226   if (!AddRec || AddRec->getLoop() != L || !AddRec->isAffine())
227     return false;
228   auto* Step = dyn_cast<SCEVConstant>(AddRec->getStepRecurrence(SE));
229   if (!Step)
230     return false;
231   // TODO: generalize to access patterns which have gaps
232   if (Step->getAPInt() != EltSize)
233     return false;
234 
235   // TODO: If the symbolic trip count has a small bound (max count), we might
236   // be able to prove safety.
237   auto TC = SE.getSmallConstantTripCount(L);
238   if (!TC)
239     return false;
240 
241   const APInt AccessSize = TC * EltSize;
242 
243   auto *StartS = dyn_cast<SCEVUnknown>(AddRec->getStart());
244   if (!StartS)
245     return false;
246   assert(SE.isLoopInvariant(StartS, L) && "implied by addrec definition");
247   Value *Base = StartS->getValue();
248 
249   // For the moment, restrict ourselves to the case where the access size is a
250   // multiple of the requested alignment and the base is aligned.
251   // TODO: generalize if a case found which warrants
252   if (EltSize.urem(Alignment.value()) != 0)
253     return false;
254   return isDereferenceableAndAlignedPointer(Base, Alignment, AccessSize, DL,
255                                             HeaderFirstNonPHI, &DT);
256 }
257 
258 /// Check if executing a load of this pointer value cannot trap.
259 ///
260 /// If DT and ScanFrom are specified this method performs context-sensitive
261 /// analysis and returns true if it is safe to load immediately before ScanFrom.
262 ///
263 /// If it is not obviously safe to load from the specified pointer, we do
264 /// a quick local scan of the basic block containing \c ScanFrom, to determine
265 /// if the address is already accessed.
266 ///
267 /// This uses the pointee type to determine how many bytes need to be safe to
268 /// load from the pointer.
269 bool llvm::isSafeToLoadUnconditionally(Value *V, Align Alignment, APInt &Size,
270                                        const DataLayout &DL,
271                                        Instruction *ScanFrom,
272                                        const DominatorTree *DT) {
273   // If DT is not specified we can't make context-sensitive query
274   const Instruction* CtxI = DT ? ScanFrom : nullptr;
275   if (isDereferenceableAndAlignedPointer(V, Alignment, Size, DL, CtxI, DT))
276     return true;
277 
278   if (!ScanFrom)
279     return false;
280 
281   if (Size.getBitWidth() > 64)
282     return false;
283   const uint64_t LoadSize = Size.getZExtValue();
284 
285   // Otherwise, be a little bit aggressive by scanning the local block where we
286   // want to check to see if the pointer is already being loaded or stored
287   // from/to.  If so, the previous load or store would have already trapped,
288   // so there is no harm doing an extra load (also, CSE will later eliminate
289   // the load entirely).
290   BasicBlock::iterator BBI = ScanFrom->getIterator(),
291                        E = ScanFrom->getParent()->begin();
292 
293   // We can at least always strip pointer casts even though we can't use the
294   // base here.
295   V = V->stripPointerCasts();
296 
297   while (BBI != E) {
298     --BBI;
299 
300     // If we see a free or a call which may write to memory (i.e. which might do
301     // a free) the pointer could be marked invalid.
302     if (isa<CallInst>(BBI) && BBI->mayWriteToMemory() &&
303         !isa<DbgInfoIntrinsic>(BBI))
304       return false;
305 
306     Value *AccessedPtr;
307     Type *AccessedTy;
308     Align AccessedAlign;
309     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
310       // Ignore volatile loads. The execution of a volatile load cannot
311       // be used to prove an address is backed by regular memory; it can,
312       // for example, point to an MMIO register.
313       if (LI->isVolatile())
314         continue;
315       AccessedPtr = LI->getPointerOperand();
316       AccessedTy = LI->getType();
317       AccessedAlign = LI->getAlign();
318     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
319       // Ignore volatile stores (see comment for loads).
320       if (SI->isVolatile())
321         continue;
322       AccessedPtr = SI->getPointerOperand();
323       AccessedTy = SI->getValueOperand()->getType();
324       AccessedAlign = SI->getAlign();
325     } else
326       continue;
327 
328     if (AccessedAlign < Alignment)
329       continue;
330 
331     // Handle trivial cases.
332     if (AccessedPtr == V &&
333         LoadSize <= DL.getTypeStoreSize(AccessedTy))
334       return true;
335 
336     if (AreEquivalentAddressValues(AccessedPtr->stripPointerCasts(), V) &&
337         LoadSize <= DL.getTypeStoreSize(AccessedTy))
338       return true;
339   }
340   return false;
341 }
342 
343 bool llvm::isSafeToLoadUnconditionally(Value *V, Type *Ty, Align Alignment,
344                                        const DataLayout &DL,
345                                        Instruction *ScanFrom,
346                                        const DominatorTree *DT) {
347   APInt Size(DL.getIndexTypeSizeInBits(V->getType()), DL.getTypeStoreSize(Ty));
348   return isSafeToLoadUnconditionally(V, Alignment, Size, DL, ScanFrom, DT);
349 }
350 
351   /// DefMaxInstsToScan - the default number of maximum instructions
352 /// to scan in the block, used by FindAvailableLoadedValue().
353 /// FindAvailableLoadedValue() was introduced in r60148, to improve jump
354 /// threading in part by eliminating partially redundant loads.
355 /// At that point, the value of MaxInstsToScan was already set to '6'
356 /// without documented explanation.
357 cl::opt<unsigned>
358 llvm::DefMaxInstsToScan("available-load-scan-limit", cl::init(6), cl::Hidden,
359   cl::desc("Use this to specify the default maximum number of instructions "
360            "to scan backward from a given instruction, when searching for "
361            "available loaded value"));
362 
363 Value *llvm::FindAvailableLoadedValue(LoadInst *Load,
364                                       BasicBlock *ScanBB,
365                                       BasicBlock::iterator &ScanFrom,
366                                       unsigned MaxInstsToScan,
367                                       AliasAnalysis *AA, bool *IsLoad,
368                                       unsigned *NumScanedInst) {
369   // Don't CSE load that is volatile or anything stronger than unordered.
370   if (!Load->isUnordered())
371     return nullptr;
372 
373   return FindAvailablePtrLoadStore(
374       Load->getPointerOperand(), Load->getType(), Load->isAtomic(), ScanBB,
375       ScanFrom, MaxInstsToScan, AA, IsLoad, NumScanedInst);
376 }
377 
378 // Check if the load and the store have the same base, constant offsets and
379 // non-overlapping access ranges.
380 static bool AreNonOverlapSameBaseLoadAndStore(
381     Value *LoadPtr, Type *LoadTy, Value *StorePtr, Type *StoreTy,
382     const DataLayout &DL) {
383   APInt LoadOffset(DL.getTypeSizeInBits(LoadPtr->getType()), 0);
384   APInt StoreOffset(DL.getTypeSizeInBits(StorePtr->getType()), 0);
385   Value *LoadBase = LoadPtr->stripAndAccumulateConstantOffsets(
386       DL, LoadOffset, /* AllowNonInbounds */ false);
387   Value *StoreBase = StorePtr->stripAndAccumulateConstantOffsets(
388       DL, StoreOffset, /* AllowNonInbounds */ false);
389   if (LoadBase != StoreBase)
390     return false;
391   auto LoadAccessSize = LocationSize::precise(DL.getTypeStoreSize(LoadTy));
392   auto StoreAccessSize = LocationSize::precise(DL.getTypeStoreSize(StoreTy));
393   ConstantRange LoadRange(LoadOffset,
394                           LoadOffset + LoadAccessSize.toRaw());
395   ConstantRange StoreRange(StoreOffset,
396                            StoreOffset + StoreAccessSize.toRaw());
397   return LoadRange.intersectWith(StoreRange).isEmptySet();
398 }
399 
400 Value *llvm::FindAvailablePtrLoadStore(Value *Ptr, Type *AccessTy,
401                                        bool AtLeastAtomic, BasicBlock *ScanBB,
402                                        BasicBlock::iterator &ScanFrom,
403                                        unsigned MaxInstsToScan,
404                                        AliasAnalysis *AA, bool *IsLoadCSE,
405                                        unsigned *NumScanedInst) {
406   if (MaxInstsToScan == 0)
407     MaxInstsToScan = ~0U;
408 
409   const DataLayout &DL = ScanBB->getModule()->getDataLayout();
410   Value *StrippedPtr = Ptr->stripPointerCasts();
411 
412   while (ScanFrom != ScanBB->begin()) {
413     // We must ignore debug info directives when counting (otherwise they
414     // would affect codegen).
415     Instruction *Inst = &*--ScanFrom;
416     if (isa<DbgInfoIntrinsic>(Inst))
417       continue;
418 
419     // Restore ScanFrom to expected value in case next test succeeds
420     ScanFrom++;
421 
422     if (NumScanedInst)
423       ++(*NumScanedInst);
424 
425     // Don't scan huge blocks.
426     if (MaxInstsToScan-- == 0)
427       return nullptr;
428 
429     --ScanFrom;
430     // If this is a load of Ptr, the loaded value is available.
431     // (This is true even if the load is volatile or atomic, although
432     // those cases are unlikely.)
433     if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
434       if (AreEquivalentAddressValues(
435               LI->getPointerOperand()->stripPointerCasts(), StrippedPtr) &&
436           CastInst::isBitOrNoopPointerCastable(LI->getType(), AccessTy, DL)) {
437 
438         // We can value forward from an atomic to a non-atomic, but not the
439         // other way around.
440         if (LI->isAtomic() < AtLeastAtomic)
441           return nullptr;
442 
443         if (IsLoadCSE)
444             *IsLoadCSE = true;
445         return LI;
446       }
447 
448     // Try to get the store size for the type.
449     auto AccessSize = LocationSize::precise(DL.getTypeStoreSize(AccessTy));
450 
451     if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
452       Value *StorePtr = SI->getPointerOperand()->stripPointerCasts();
453       // If this is a store through Ptr, the value is available!
454       // (This is true even if the store is volatile or atomic, although
455       // those cases are unlikely.)
456       if (AreEquivalentAddressValues(StorePtr, StrippedPtr) &&
457           CastInst::isBitOrNoopPointerCastable(SI->getValueOperand()->getType(),
458                                                AccessTy, DL)) {
459 
460         // We can value forward from an atomic to a non-atomic, but not the
461         // other way around.
462         if (SI->isAtomic() < AtLeastAtomic)
463           return nullptr;
464 
465         if (IsLoadCSE)
466           *IsLoadCSE = false;
467         return SI->getOperand(0);
468       }
469 
470       // If both StrippedPtr and StorePtr reach all the way to an alloca or
471       // global and they are different, ignore the store. This is a trivial form
472       // of alias analysis that is important for reg2mem'd code.
473       if ((isa<AllocaInst>(StrippedPtr) || isa<GlobalVariable>(StrippedPtr)) &&
474           (isa<AllocaInst>(StorePtr) || isa<GlobalVariable>(StorePtr)) &&
475           StrippedPtr != StorePtr)
476         continue;
477 
478       if (!AA) {
479         // When AA isn't available, but if the load and the store have the same
480         // base, constant offsets and non-overlapping access ranges, ignore the
481         // store. This is a simple form of alias analysis that is used by the
482         // inliner. FIXME: use BasicAA if possible.
483         if (AreNonOverlapSameBaseLoadAndStore(
484                 Ptr, AccessTy, SI->getPointerOperand(),
485                 SI->getValueOperand()->getType(), DL))
486           continue;
487       } else {
488         // If we have alias analysis and it says the store won't modify the
489         // loaded value, ignore the store.
490         if (!isModSet(AA->getModRefInfo(SI, StrippedPtr, AccessSize)))
491           continue;
492       }
493 
494       // Otherwise the store that may or may not alias the pointer, bail out.
495       ++ScanFrom;
496       return nullptr;
497     }
498 
499     // If this is some other instruction that may clobber Ptr, bail out.
500     if (Inst->mayWriteToMemory()) {
501       // If alias analysis claims that it really won't modify the load,
502       // ignore it.
503       if (AA && !isModSet(AA->getModRefInfo(Inst, StrippedPtr, AccessSize)))
504         continue;
505 
506       // May modify the pointer, bail out.
507       ++ScanFrom;
508       return nullptr;
509     }
510   }
511 
512   // Got to the start of the block, we didn't find it, but are done for this
513   // block.
514   return nullptr;
515 }
516