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) {
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     return isDereferenceableAndAlignedPointer(BC->getOperand(0), Alignment,
66                                               Size, DL, CtxI, DT, Visited);
67 
68   bool CheckForNonNull = false;
69   APInt KnownDerefBytes(Size.getBitWidth(),
70                         V->getPointerDereferenceableBytes(DL, CheckForNonNull));
71   if (KnownDerefBytes.getBoolValue() && KnownDerefBytes.uge(Size))
72     if (!CheckForNonNull || isKnownNonZero(V, DL, 0, nullptr, CtxI, DT)) {
73       // As we recursed through GEPs to get here, we've incrementally checked
74       // that each step advanced by a multiple of the alignment. If our base is
75       // properly aligned, then the original offset accessed must also be.
76       Type *Ty = V->getType();
77       assert(Ty->isSized() && "must be sized");
78       APInt Offset(DL.getTypeStoreSizeInBits(Ty), 0);
79       return isAligned(V, Offset, Alignment, DL);
80     }
81 
82   // For GEPs, determine if the indexing lands within the allocated object.
83   if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
84     const Value *Base = GEP->getPointerOperand();
85 
86     APInt Offset(DL.getIndexTypeSizeInBits(GEP->getType()), 0);
87     if (!GEP->accumulateConstantOffset(DL, Offset) || Offset.isNegative() ||
88         !Offset.urem(APInt(Offset.getBitWidth(), Alignment.value()))
89              .isMinValue())
90       return false;
91 
92     // If the base pointer is dereferenceable for Offset+Size bytes, then the
93     // GEP (== Base + Offset) is dereferenceable for Size bytes.  If the base
94     // pointer is aligned to Align bytes, and the Offset is divisible by Align
95     // then the GEP (== Base + Offset == k_0 * Align + k_1 * Align) is also
96     // aligned to Align bytes.
97 
98     // Offset and Size may have different bit widths if we have visited an
99     // addrspacecast, so we can't do arithmetic directly on the APInt values.
100     return isDereferenceableAndAlignedPointer(
101         Base, Alignment, Offset + Size.sextOrTrunc(Offset.getBitWidth()), DL,
102         CtxI, DT, Visited);
103   }
104 
105   // For gc.relocate, look through relocations
106   if (const GCRelocateInst *RelocateInst = dyn_cast<GCRelocateInst>(V))
107     return isDereferenceableAndAlignedPointer(
108         RelocateInst->getDerivedPtr(), Alignment, Size, DL, CtxI, DT, Visited);
109 
110   if (const AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(V))
111     return isDereferenceableAndAlignedPointer(ASC->getOperand(0), Alignment,
112                                               Size, DL, CtxI, DT, Visited);
113 
114   if (const auto *Call = dyn_cast<CallBase>(V))
115     if (auto *RP = getArgumentAliasingToReturnedPointer(Call, true))
116       return isDereferenceableAndAlignedPointer(RP, Alignment, Size, DL, CtxI,
117                                                 DT, Visited);
118 
119   // If we don't know, assume the worst.
120   return false;
121 }
122 
123 bool llvm::isDereferenceableAndAlignedPointer(const Value *V, Align Alignment,
124                                               const APInt &Size,
125                                               const DataLayout &DL,
126                                               const Instruction *CtxI,
127                                               const DominatorTree *DT) {
128   // Note: At the moment, Size can be zero.  This ends up being interpreted as
129   // a query of whether [Base, V] is dereferenceable and V is aligned (since
130   // that's what the implementation happened to do).  It's unclear if this is
131   // the desired semantic, but at least SelectionDAG does exercise this case.
132 
133   SmallPtrSet<const Value *, 32> Visited;
134   return ::isDereferenceableAndAlignedPointer(V, Alignment, Size, DL, CtxI, DT,
135                                               Visited);
136 }
137 
138 bool llvm::isDereferenceableAndAlignedPointer(const Value *V, Type *Ty,
139                                               MaybeAlign MA,
140                                               const DataLayout &DL,
141                                               const Instruction *CtxI,
142                                               const DominatorTree *DT) {
143   // For unsized types or scalable vectors we don't know exactly how many bytes
144   // are dereferenced, so bail out.
145   if (!Ty->isSized() || (Ty->isVectorTy() && Ty->getVectorIsScalable()))
146     return false;
147 
148   // When dereferenceability information is provided by a dereferenceable
149   // attribute, we know exactly how many bytes are dereferenceable. If we can
150   // determine the exact offset to the attributed variable, we can use that
151   // information here.
152 
153   // Require ABI alignment for loads without alignment specification
154   const Align Alignment = DL.getValueOrABITypeAlignment(MA, Ty);
155   APInt AccessSize(DL.getPointerTypeSizeInBits(V->getType()),
156                    DL.getTypeStoreSize(Ty));
157   return isDereferenceableAndAlignedPointer(V, Alignment, AccessSize, DL, CtxI,
158                                             DT);
159 }
160 
161 bool llvm::isDereferenceablePointer(const Value *V, Type *Ty,
162                                     const DataLayout &DL,
163                                     const Instruction *CtxI,
164                                     const DominatorTree *DT) {
165   return isDereferenceableAndAlignedPointer(V, Ty, Align(1), DL, CtxI, DT);
166 }
167 
168 /// Test if A and B will obviously have the same value.
169 ///
170 /// This includes recognizing that %t0 and %t1 will have the same
171 /// value in code like this:
172 /// \code
173 ///   %t0 = getelementptr \@a, 0, 3
174 ///   store i32 0, i32* %t0
175 ///   %t1 = getelementptr \@a, 0, 3
176 ///   %t2 = load i32* %t1
177 /// \endcode
178 ///
179 static bool AreEquivalentAddressValues(const Value *A, const Value *B) {
180   // Test if the values are trivially equivalent.
181   if (A == B)
182     return true;
183 
184   // Test if the values come from identical arithmetic instructions.
185   // Use isIdenticalToWhenDefined instead of isIdenticalTo because
186   // this function is only used when one address use dominates the
187   // other, which means that they'll always either have the same
188   // value or one of them will have an undefined value.
189   if (isa<BinaryOperator>(A) || isa<CastInst>(A) || isa<PHINode>(A) ||
190       isa<GetElementPtrInst>(A))
191     if (const Instruction *BI = dyn_cast<Instruction>(B))
192       if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
193         return true;
194 
195   // Otherwise they may not be equivalent.
196   return false;
197 }
198 
199 bool llvm::isDereferenceableAndAlignedInLoop(LoadInst *LI, Loop *L,
200                                              ScalarEvolution &SE,
201                                              DominatorTree &DT) {
202   auto &DL = LI->getModule()->getDataLayout();
203   Value *Ptr = LI->getPointerOperand();
204 
205   APInt EltSize(DL.getIndexTypeSizeInBits(Ptr->getType()),
206                 DL.getTypeStoreSize(LI->getType()));
207   const Align Alignment = DL.getValueOrABITypeAlignment(
208       MaybeAlign(LI->getAlignment()), LI->getType());
209 
210   Instruction *HeaderFirstNonPHI = L->getHeader()->getFirstNonPHI();
211 
212   // If given a uniform (i.e. non-varying) address, see if we can prove the
213   // access is safe within the loop w/o needing predication.
214   if (L->isLoopInvariant(Ptr))
215     return isDereferenceableAndAlignedPointer(Ptr, Alignment, EltSize, DL,
216                                               HeaderFirstNonPHI, &DT);
217 
218   // Otherwise, check to see if we have a repeating access pattern where we can
219   // prove that all accesses are well aligned and dereferenceable.
220   auto *AddRec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Ptr));
221   if (!AddRec || AddRec->getLoop() != L || !AddRec->isAffine())
222     return false;
223   auto* Step = dyn_cast<SCEVConstant>(AddRec->getStepRecurrence(SE));
224   if (!Step)
225     return false;
226   // TODO: generalize to access patterns which have gaps
227   if (Step->getAPInt() != EltSize)
228     return false;
229 
230   // TODO: If the symbolic trip count has a small bound (max count), we might
231   // be able to prove safety.
232   auto TC = SE.getSmallConstantTripCount(L);
233   if (!TC)
234     return false;
235 
236   const APInt AccessSize = TC * EltSize;
237 
238   auto *StartS = dyn_cast<SCEVUnknown>(AddRec->getStart());
239   if (!StartS)
240     return false;
241   assert(SE.isLoopInvariant(StartS, L) && "implied by addrec definition");
242   Value *Base = StartS->getValue();
243 
244   // For the moment, restrict ourselves to the case where the access size is a
245   // multiple of the requested alignment and the base is aligned.
246   // TODO: generalize if a case found which warrants
247   if (EltSize.urem(Alignment.value()) != 0)
248     return false;
249   return isDereferenceableAndAlignedPointer(Base, Alignment, AccessSize, DL,
250                                             HeaderFirstNonPHI, &DT);
251 }
252 
253 /// Check if executing a load of this pointer value cannot trap.
254 ///
255 /// If DT and ScanFrom are specified this method performs context-sensitive
256 /// analysis and returns true if it is safe to load immediately before ScanFrom.
257 ///
258 /// If it is not obviously safe to load from the specified pointer, we do
259 /// a quick local scan of the basic block containing \c ScanFrom, to determine
260 /// if the address is already accessed.
261 ///
262 /// This uses the pointee type to determine how many bytes need to be safe to
263 /// load from the pointer.
264 bool llvm::isSafeToLoadUnconditionally(Value *V, MaybeAlign MA, APInt &Size,
265                                        const DataLayout &DL,
266                                        Instruction *ScanFrom,
267                                        const DominatorTree *DT) {
268   // Zero alignment means that the load has the ABI alignment for the target
269   const Align Alignment =
270       DL.getValueOrABITypeAlignment(MA, V->getType()->getPointerElementType());
271 
272   // If DT is not specified we can't make context-sensitive query
273   const Instruction* CtxI = DT ? ScanFrom : nullptr;
274   if (isDereferenceableAndAlignedPointer(V, Alignment, Size, DL, CtxI, DT))
275     return true;
276 
277   if (!ScanFrom)
278     return false;
279 
280   if (Size.getBitWidth() > 64)
281     return false;
282   const uint64_t LoadSize = Size.getZExtValue();
283 
284   // Otherwise, be a little bit aggressive by scanning the local block where we
285   // want to check to see if the pointer is already being loaded or stored
286   // from/to.  If so, the previous load or store would have already trapped,
287   // so there is no harm doing an extra load (also, CSE will later eliminate
288   // the load entirely).
289   BasicBlock::iterator BBI = ScanFrom->getIterator(),
290                        E = ScanFrom->getParent()->begin();
291 
292   // We can at least always strip pointer casts even though we can't use the
293   // base here.
294   V = V->stripPointerCasts();
295 
296   while (BBI != E) {
297     --BBI;
298 
299     // If we see a free or a call which may write to memory (i.e. which might do
300     // a free) the pointer could be marked invalid.
301     if (isa<CallInst>(BBI) && BBI->mayWriteToMemory() &&
302         !isa<DbgInfoIntrinsic>(BBI))
303       return false;
304 
305     Value *AccessedPtr;
306     MaybeAlign MaybeAccessedAlign;
307     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
308       // Ignore volatile loads. The execution of a volatile load cannot
309       // be used to prove an address is backed by regular memory; it can,
310       // for example, point to an MMIO register.
311       if (LI->isVolatile())
312         continue;
313       AccessedPtr = LI->getPointerOperand();
314       MaybeAccessedAlign = MaybeAlign(LI->getAlignment());
315     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
316       // Ignore volatile stores (see comment for loads).
317       if (SI->isVolatile())
318         continue;
319       AccessedPtr = SI->getPointerOperand();
320       MaybeAccessedAlign = MaybeAlign(SI->getAlignment());
321     } else
322       continue;
323 
324     Type *AccessedTy = AccessedPtr->getType()->getPointerElementType();
325 
326     const Align AccessedAlign =
327         DL.getValueOrABITypeAlignment(MaybeAccessedAlign, AccessedTy);
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, MaybeAlign 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 Value *llvm::FindAvailablePtrLoadStore(Value *Ptr, Type *AccessTy,
379                                        bool AtLeastAtomic, BasicBlock *ScanBB,
380                                        BasicBlock::iterator &ScanFrom,
381                                        unsigned MaxInstsToScan,
382                                        AliasAnalysis *AA, bool *IsLoadCSE,
383                                        unsigned *NumScanedInst) {
384   if (MaxInstsToScan == 0)
385     MaxInstsToScan = ~0U;
386 
387   const DataLayout &DL = ScanBB->getModule()->getDataLayout();
388   Value *StrippedPtr = Ptr->stripPointerCasts();
389 
390   while (ScanFrom != ScanBB->begin()) {
391     // We must ignore debug info directives when counting (otherwise they
392     // would affect codegen).
393     Instruction *Inst = &*--ScanFrom;
394     if (isa<DbgInfoIntrinsic>(Inst))
395       continue;
396 
397     // Restore ScanFrom to expected value in case next test succeeds
398     ScanFrom++;
399 
400     if (NumScanedInst)
401       ++(*NumScanedInst);
402 
403     // Don't scan huge blocks.
404     if (MaxInstsToScan-- == 0)
405       return nullptr;
406 
407     --ScanFrom;
408     // If this is a load of Ptr, the loaded value is available.
409     // (This is true even if the load is volatile or atomic, although
410     // those cases are unlikely.)
411     if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
412       if (AreEquivalentAddressValues(
413               LI->getPointerOperand()->stripPointerCasts(), StrippedPtr) &&
414           CastInst::isBitOrNoopPointerCastable(LI->getType(), AccessTy, DL)) {
415 
416         // We can value forward from an atomic to a non-atomic, but not the
417         // other way around.
418         if (LI->isAtomic() < AtLeastAtomic)
419           return nullptr;
420 
421         if (IsLoadCSE)
422             *IsLoadCSE = true;
423         return LI;
424       }
425 
426     // Try to get the store size for the type.
427     auto AccessSize = LocationSize::precise(DL.getTypeStoreSize(AccessTy));
428 
429     if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
430       Value *StorePtr = SI->getPointerOperand()->stripPointerCasts();
431       // If this is a store through Ptr, the value is available!
432       // (This is true even if the store is volatile or atomic, although
433       // those cases are unlikely.)
434       if (AreEquivalentAddressValues(StorePtr, StrippedPtr) &&
435           CastInst::isBitOrNoopPointerCastable(SI->getValueOperand()->getType(),
436                                                AccessTy, DL)) {
437 
438         // We can value forward from an atomic to a non-atomic, but not the
439         // other way around.
440         if (SI->isAtomic() < AtLeastAtomic)
441           return nullptr;
442 
443         if (IsLoadCSE)
444           *IsLoadCSE = false;
445         return SI->getOperand(0);
446       }
447 
448       // If both StrippedPtr and StorePtr reach all the way to an alloca or
449       // global and they are different, ignore the store. This is a trivial form
450       // of alias analysis that is important for reg2mem'd code.
451       if ((isa<AllocaInst>(StrippedPtr) || isa<GlobalVariable>(StrippedPtr)) &&
452           (isa<AllocaInst>(StorePtr) || isa<GlobalVariable>(StorePtr)) &&
453           StrippedPtr != StorePtr)
454         continue;
455 
456       // If we have alias analysis and it says the store won't modify the loaded
457       // value, ignore the store.
458       if (AA && !isModSet(AA->getModRefInfo(SI, StrippedPtr, AccessSize)))
459         continue;
460 
461       // Otherwise the store that may or may not alias the pointer, bail out.
462       ++ScanFrom;
463       return nullptr;
464     }
465 
466     // If this is some other instruction that may clobber Ptr, bail out.
467     if (Inst->mayWriteToMemory()) {
468       // If alias analysis claims that it really won't modify the load,
469       // ignore it.
470       if (AA && !isModSet(AA->getModRefInfo(Inst, StrippedPtr, AccessSize)))
471         continue;
472 
473       // May modify the pointer, bail out.
474       ++ScanFrom;
475       return nullptr;
476     }
477   }
478 
479   // Got to the start of the block, we didn't find it, but are done for this
480   // block.
481   return nullptr;
482 }
483