1 //===- Loads.cpp - Local load analysis ------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines simple local analyses for load instructions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Analysis/Loads.h"
15 #include "llvm/Analysis/AliasAnalysis.h"
16 #include "llvm/Analysis/ValueTracking.h"
17 #include "llvm/IR/DataLayout.h"
18 #include "llvm/IR/GlobalAlias.h"
19 #include "llvm/IR/GlobalVariable.h"
20 #include "llvm/IR/IntrinsicInst.h"
21 #include "llvm/IR/LLVMContext.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/IR/Operator.h"
24 #include "llvm/IR/Statepoint.h"
25 
26 using namespace llvm;
27 
28 static bool isAligned(const Value *Base, const APInt &Offset, unsigned Align,
29                       const DataLayout &DL) {
30   APInt BaseAlign(Offset.getBitWidth(), Base->getPointerAlignment(DL));
31 
32   if (!BaseAlign) {
33     Type *Ty = Base->getType()->getPointerElementType();
34     if (!Ty->isSized())
35       return false;
36     BaseAlign = DL.getABITypeAlignment(Ty);
37   }
38 
39   APInt Alignment(Offset.getBitWidth(), Align);
40 
41   assert(Alignment.isPowerOf2() && "must be a power of 2!");
42   return BaseAlign.uge(Alignment) && !(Offset & (Alignment-1));
43 }
44 
45 static bool isAligned(const Value *Base, unsigned Align, const DataLayout &DL) {
46   Type *Ty = Base->getType();
47   assert(Ty->isSized() && "must be sized");
48   APInt Offset(DL.getTypeStoreSizeInBits(Ty), 0);
49   return isAligned(Base, Offset, Align, DL);
50 }
51 
52 /// Test if V is always a pointer to allocated and suitably aligned memory for
53 /// a simple load or store.
54 static bool isDereferenceableAndAlignedPointer(
55     const Value *V, unsigned Align, const APInt &Size, const DataLayout &DL,
56     const Instruction *CtxI, const DominatorTree *DT,
57     SmallPtrSetImpl<const Value *> &Visited) {
58   // Already visited?  Bail out, we've likely hit unreachable code.
59   if (!Visited.insert(V).second)
60     return false;
61 
62   // Note that it is not safe to speculate into a malloc'd region because
63   // malloc may return null.
64 
65   // bitcast instructions are no-ops as far as dereferenceability is concerned.
66   if (const BitCastOperator *BC = dyn_cast<BitCastOperator>(V))
67     return isDereferenceableAndAlignedPointer(BC->getOperand(0), Align, Size,
68                                               DL, CtxI, DT, Visited);
69 
70   bool CheckForNonNull = false;
71   APInt KnownDerefBytes(Size.getBitWidth(),
72                         V->getPointerDereferenceableBytes(DL, CheckForNonNull));
73   if (KnownDerefBytes.getBoolValue()) {
74     if (KnownDerefBytes.uge(Size))
75       if (!CheckForNonNull || isKnownNonNullAt(V, CtxI, DT))
76         return isAligned(V, Align, DL);
77   }
78 
79   // For GEPs, determine if the indexing lands within the allocated object.
80   if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
81     const Value *Base = GEP->getPointerOperand();
82 
83     APInt Offset(DL.getPointerTypeSizeInBits(GEP->getType()), 0);
84     if (!GEP->accumulateConstantOffset(DL, Offset) || Offset.isNegative() ||
85         !Offset.urem(APInt(Offset.getBitWidth(), Align)).isMinValue())
86       return false;
87 
88     // If the base pointer is dereferenceable for Offset+Size bytes, then the
89     // GEP (== Base + Offset) is dereferenceable for Size bytes.  If the base
90     // pointer is aligned to Align bytes, and the Offset is divisible by Align
91     // then the GEP (== Base + Offset == k_0 * Align + k_1 * Align) is also
92     // aligned to Align bytes.
93 
94     return isDereferenceableAndAlignedPointer(Base, Align, Offset + Size, DL,
95                                               CtxI, DT, Visited);
96   }
97 
98   // For gc.relocate, look through relocations
99   if (const GCRelocateInst *RelocateInst = dyn_cast<GCRelocateInst>(V))
100     return isDereferenceableAndAlignedPointer(
101         RelocateInst->getDerivedPtr(), Align, Size, DL, CtxI, DT, Visited);
102 
103   if (const AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(V))
104     return isDereferenceableAndAlignedPointer(ASC->getOperand(0), Align, Size,
105                                               DL, CtxI, DT, Visited);
106 
107   if (auto CS = ImmutableCallSite(V))
108     if (const Value *RV = CS.getReturnedArgOperand())
109       return isDereferenceableAndAlignedPointer(RV, Align, Size, DL, CtxI, DT,
110                                                 Visited);
111 
112   // If we don't know, assume the worst.
113   return false;
114 }
115 
116 bool llvm::isDereferenceableAndAlignedPointer(const Value *V, unsigned Align,
117                                               const DataLayout &DL,
118                                               const Instruction *CtxI,
119                                               const DominatorTree *DT) {
120   // When dereferenceability information is provided by a dereferenceable
121   // attribute, we know exactly how many bytes are dereferenceable. If we can
122   // determine the exact offset to the attributed variable, we can use that
123   // information here.
124   Type *VTy = V->getType();
125   Type *Ty = VTy->getPointerElementType();
126 
127   // Require ABI alignment for loads without alignment specification
128   if (Align == 0)
129     Align = DL.getABITypeAlignment(Ty);
130 
131   if (!Ty->isSized())
132     return false;
133 
134   SmallPtrSet<const Value *, 32> Visited;
135   return ::isDereferenceableAndAlignedPointer(
136       V, Align, APInt(DL.getTypeSizeInBits(VTy), DL.getTypeStoreSize(Ty)), DL,
137       CtxI, DT, Visited);
138 }
139 
140 bool llvm::isDereferenceablePointer(const Value *V, const DataLayout &DL,
141                                     const Instruction *CtxI,
142                                     const DominatorTree *DT) {
143   return isDereferenceableAndAlignedPointer(V, 1, DL, CtxI, DT);
144 }
145 
146 /// \brief Test if A and B will obviously have the same value.
147 ///
148 /// This includes recognizing that %t0 and %t1 will have the same
149 /// value in code like this:
150 /// \code
151 ///   %t0 = getelementptr \@a, 0, 3
152 ///   store i32 0, i32* %t0
153 ///   %t1 = getelementptr \@a, 0, 3
154 ///   %t2 = load i32* %t1
155 /// \endcode
156 ///
157 static bool AreEquivalentAddressValues(const Value *A, const Value *B) {
158   // Test if the values are trivially equivalent.
159   if (A == B)
160     return true;
161 
162   // Test if the values come from identical arithmetic instructions.
163   // Use isIdenticalToWhenDefined instead of isIdenticalTo because
164   // this function is only used when one address use dominates the
165   // other, which means that they'll always either have the same
166   // value or one of them will have an undefined value.
167   if (isa<BinaryOperator>(A) || isa<CastInst>(A) || isa<PHINode>(A) ||
168       isa<GetElementPtrInst>(A))
169     if (const Instruction *BI = dyn_cast<Instruction>(B))
170       if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
171         return true;
172 
173   // Otherwise they may not be equivalent.
174   return false;
175 }
176 
177 /// \brief Check if executing a load of this pointer value cannot trap.
178 ///
179 /// If DT and ScanFrom are specified this method performs context-sensitive
180 /// analysis and returns true if it is safe to load immediately before ScanFrom.
181 ///
182 /// If it is not obviously safe to load from the specified pointer, we do
183 /// a quick local scan of the basic block containing \c ScanFrom, to determine
184 /// if the address is already accessed.
185 ///
186 /// This uses the pointee type to determine how many bytes need to be safe to
187 /// load from the pointer.
188 bool llvm::isSafeToLoadUnconditionally(Value *V, unsigned Align,
189                                        const DataLayout &DL,
190                                        Instruction *ScanFrom,
191                                        const DominatorTree *DT) {
192   // Zero alignment means that the load has the ABI alignment for the target
193   if (Align == 0)
194     Align = DL.getABITypeAlignment(V->getType()->getPointerElementType());
195   assert(isPowerOf2_32(Align));
196 
197   // If DT is not specified we can't make context-sensitive query
198   const Instruction* CtxI = DT ? ScanFrom : nullptr;
199   if (isDereferenceableAndAlignedPointer(V, Align, DL, CtxI, DT))
200     return true;
201 
202   int64_t ByteOffset = 0;
203   Value *Base = V;
204   Base = GetPointerBaseWithConstantOffset(V, ByteOffset, DL);
205 
206   if (ByteOffset < 0) // out of bounds
207     return false;
208 
209   Type *BaseType = nullptr;
210   unsigned BaseAlign = 0;
211   if (const AllocaInst *AI = dyn_cast<AllocaInst>(Base)) {
212     // An alloca is safe to load from as load as it is suitably aligned.
213     BaseType = AI->getAllocatedType();
214     BaseAlign = AI->getAlignment();
215   } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Base)) {
216     // Global variables are not necessarily safe to load from if they are
217     // interposed arbitrarily. Their size may change or they may be weak and
218     // require a test to determine if they were in fact provided.
219     if (!GV->isInterposable()) {
220       BaseType = GV->getType()->getElementType();
221       BaseAlign = GV->getAlignment();
222     }
223   }
224 
225   PointerType *AddrTy = cast<PointerType>(V->getType());
226   uint64_t LoadSize = DL.getTypeStoreSize(AddrTy->getElementType());
227 
228   // If we found a base allocated type from either an alloca or global variable,
229   // try to see if we are definitively within the allocated region. We need to
230   // know the size of the base type and the loaded type to do anything in this
231   // case.
232   if (BaseType && BaseType->isSized()) {
233     if (BaseAlign == 0)
234       BaseAlign = DL.getPrefTypeAlignment(BaseType);
235 
236     if (Align <= BaseAlign) {
237       // Check if the load is within the bounds of the underlying object.
238       if (ByteOffset + LoadSize <= DL.getTypeAllocSize(BaseType) &&
239           ((ByteOffset % Align) == 0))
240         return true;
241     }
242   }
243 
244   if (!ScanFrom)
245     return false;
246 
247   // Otherwise, be a little bit aggressive by scanning the local block where we
248   // want to check to see if the pointer is already being loaded or stored
249   // from/to.  If so, the previous load or store would have already trapped,
250   // so there is no harm doing an extra load (also, CSE will later eliminate
251   // the load entirely).
252   BasicBlock::iterator BBI = ScanFrom->getIterator(),
253                        E = ScanFrom->getParent()->begin();
254 
255   // We can at least always strip pointer casts even though we can't use the
256   // base here.
257   V = V->stripPointerCasts();
258 
259   while (BBI != E) {
260     --BBI;
261 
262     // If we see a free or a call which may write to memory (i.e. which might do
263     // a free) the pointer could be marked invalid.
264     if (isa<CallInst>(BBI) && BBI->mayWriteToMemory() &&
265         !isa<DbgInfoIntrinsic>(BBI))
266       return false;
267 
268     Value *AccessedPtr;
269     unsigned AccessedAlign;
270     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
271       AccessedPtr = LI->getPointerOperand();
272       AccessedAlign = LI->getAlignment();
273     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
274       AccessedPtr = SI->getPointerOperand();
275       AccessedAlign = SI->getAlignment();
276     } else
277       continue;
278 
279     Type *AccessedTy = AccessedPtr->getType()->getPointerElementType();
280     if (AccessedAlign == 0)
281       AccessedAlign = DL.getABITypeAlignment(AccessedTy);
282     if (AccessedAlign < Align)
283       continue;
284 
285     // Handle trivial cases.
286     if (AccessedPtr == V)
287       return true;
288 
289     if (AreEquivalentAddressValues(AccessedPtr->stripPointerCasts(), V) &&
290         LoadSize <= DL.getTypeStoreSize(AccessedTy))
291       return true;
292   }
293   return false;
294 }
295 
296 /// DefMaxInstsToScan - the default number of maximum instructions
297 /// to scan in the block, used by FindAvailableLoadedValue().
298 /// FindAvailableLoadedValue() was introduced in r60148, to improve jump
299 /// threading in part by eliminating partially redundant loads.
300 /// At that point, the value of MaxInstsToScan was already set to '6'
301 /// without documented explanation.
302 cl::opt<unsigned>
303 llvm::DefMaxInstsToScan("available-load-scan-limit", cl::init(6), cl::Hidden,
304   cl::desc("Use this to specify the default maximum number of instructions "
305            "to scan backward from a given instruction, when searching for "
306            "available loaded value"));
307 
308 Value *llvm::FindAvailableLoadedValue(LoadInst *Load,
309                                       BasicBlock *ScanBB,
310                                       BasicBlock::iterator &ScanFrom,
311                                       unsigned MaxInstsToScan,
312                                       AliasAnalysis *AA, bool *IsLoadCSE) {
313   if (MaxInstsToScan == 0)
314     MaxInstsToScan = ~0U;
315 
316   Value *Ptr = Load->getPointerOperand();
317   Type *AccessTy = Load->getType();
318 
319   // We can never remove a volatile load
320   if (Load->isVolatile())
321     return nullptr;
322 
323   // Anything stronger than unordered is currently unimplemented.
324   if (!Load->isUnordered())
325     return nullptr;
326 
327   const DataLayout &DL = ScanBB->getModule()->getDataLayout();
328 
329   // Try to get the store size for the type.
330   uint64_t AccessSize = DL.getTypeStoreSize(AccessTy);
331 
332   Value *StrippedPtr = Ptr->stripPointerCasts();
333 
334   while (ScanFrom != ScanBB->begin()) {
335     // We must ignore debug info directives when counting (otherwise they
336     // would affect codegen).
337     Instruction *Inst = &*--ScanFrom;
338     if (isa<DbgInfoIntrinsic>(Inst))
339       continue;
340 
341     // Restore ScanFrom to expected value in case next test succeeds
342     ScanFrom++;
343 
344     // Don't scan huge blocks.
345     if (MaxInstsToScan-- == 0)
346       return nullptr;
347 
348     --ScanFrom;
349     // If this is a load of Ptr, the loaded value is available.
350     // (This is true even if the load is volatile or atomic, although
351     // those cases are unlikely.)
352     if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
353       if (AreEquivalentAddressValues(
354               LI->getPointerOperand()->stripPointerCasts(), StrippedPtr) &&
355           CastInst::isBitOrNoopPointerCastable(LI->getType(), AccessTy, DL)) {
356 
357         // We can value forward from an atomic to a non-atomic, but not the
358         // other way around.
359         if (LI->isAtomic() < Load->isAtomic())
360           return nullptr;
361 
362         if (IsLoadCSE)
363             *IsLoadCSE = true;
364         return LI;
365       }
366 
367     if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
368       Value *StorePtr = SI->getPointerOperand()->stripPointerCasts();
369       // If this is a store through Ptr, the value is available!
370       // (This is true even if the store is volatile or atomic, although
371       // those cases are unlikely.)
372       if (AreEquivalentAddressValues(StorePtr, StrippedPtr) &&
373           CastInst::isBitOrNoopPointerCastable(SI->getValueOperand()->getType(),
374                                                AccessTy, DL)) {
375 
376         // We can value forward from an atomic to a non-atomic, but not the
377         // other way around.
378         if (SI->isAtomic() < Load->isAtomic())
379           return nullptr;
380 
381         if (IsLoadCSE)
382           *IsLoadCSE = false;
383         return SI->getOperand(0);
384       }
385 
386       // If both StrippedPtr and StorePtr reach all the way to an alloca or
387       // global and they are different, ignore the store. This is a trivial form
388       // of alias analysis that is important for reg2mem'd code.
389       if ((isa<AllocaInst>(StrippedPtr) || isa<GlobalVariable>(StrippedPtr)) &&
390           (isa<AllocaInst>(StorePtr) || isa<GlobalVariable>(StorePtr)) &&
391           StrippedPtr != StorePtr)
392         continue;
393 
394       // If we have alias analysis and it says the store won't modify the loaded
395       // value, ignore the store.
396       if (AA && (AA->getModRefInfo(SI, StrippedPtr, AccessSize) & MRI_Mod) == 0)
397         continue;
398 
399       // Otherwise the store that may or may not alias the pointer, bail out.
400       ++ScanFrom;
401       return nullptr;
402     }
403 
404     // If this is some other instruction that may clobber Ptr, bail out.
405     if (Inst->mayWriteToMemory()) {
406       // If alias analysis claims that it really won't modify the load,
407       // ignore it.
408       if (AA &&
409           (AA->getModRefInfo(Inst, StrippedPtr, AccessSize) & MRI_Mod) == 0)
410         continue;
411 
412       // May modify the pointer, bail out.
413       ++ScanFrom;
414       return nullptr;
415     }
416   }
417 
418   // Got to the start of the block, we didn't find it, but are done for this
419   // block.
420   return nullptr;
421 }
422