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() || 152 (Ty->isVectorTy() && cast<VectorType>(Ty)->isScalable())) 153 return false; 154 155 // When dereferenceability information is provided by a dereferenceable 156 // attribute, we know exactly how many bytes are dereferenceable. If we can 157 // determine the exact offset to the attributed variable, we can use that 158 // information here. 159 160 // Require ABI alignment for loads without alignment specification 161 const Align Alignment = DL.getValueOrABITypeAlignment(MA, Ty); 162 APInt AccessSize(DL.getPointerTypeSizeInBits(V->getType()), 163 DL.getTypeStoreSize(Ty)); 164 return isDereferenceableAndAlignedPointer(V, Alignment, AccessSize, DL, CtxI, 165 DT); 166 } 167 168 bool llvm::isDereferenceablePointer(const Value *V, Type *Ty, 169 const DataLayout &DL, 170 const Instruction *CtxI, 171 const DominatorTree *DT) { 172 return isDereferenceableAndAlignedPointer(V, Ty, Align(1), DL, CtxI, DT); 173 } 174 175 /// Test if A and B will obviously have the same value. 176 /// 177 /// This includes recognizing that %t0 and %t1 will have the same 178 /// value in code like this: 179 /// \code 180 /// %t0 = getelementptr \@a, 0, 3 181 /// store i32 0, i32* %t0 182 /// %t1 = getelementptr \@a, 0, 3 183 /// %t2 = load i32* %t1 184 /// \endcode 185 /// 186 static bool AreEquivalentAddressValues(const Value *A, const Value *B) { 187 // Test if the values are trivially equivalent. 188 if (A == B) 189 return true; 190 191 // Test if the values come from identical arithmetic instructions. 192 // Use isIdenticalToWhenDefined instead of isIdenticalTo because 193 // this function is only used when one address use dominates the 194 // other, which means that they'll always either have the same 195 // value or one of them will have an undefined value. 196 if (isa<BinaryOperator>(A) || isa<CastInst>(A) || isa<PHINode>(A) || 197 isa<GetElementPtrInst>(A)) 198 if (const Instruction *BI = dyn_cast<Instruction>(B)) 199 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI)) 200 return true; 201 202 // Otherwise they may not be equivalent. 203 return false; 204 } 205 206 bool llvm::isDereferenceableAndAlignedInLoop(LoadInst *LI, Loop *L, 207 ScalarEvolution &SE, 208 DominatorTree &DT) { 209 auto &DL = LI->getModule()->getDataLayout(); 210 Value *Ptr = LI->getPointerOperand(); 211 212 APInt EltSize(DL.getIndexTypeSizeInBits(Ptr->getType()), 213 DL.getTypeStoreSize(LI->getType())); 214 const Align Alignment = DL.getValueOrABITypeAlignment( 215 MaybeAlign(LI->getAlignment()), LI->getType()); 216 217 Instruction *HeaderFirstNonPHI = L->getHeader()->getFirstNonPHI(); 218 219 // If given a uniform (i.e. non-varying) address, see if we can prove the 220 // access is safe within the loop w/o needing predication. 221 if (L->isLoopInvariant(Ptr)) 222 return isDereferenceableAndAlignedPointer(Ptr, Alignment, EltSize, DL, 223 HeaderFirstNonPHI, &DT); 224 225 // Otherwise, check to see if we have a repeating access pattern where we can 226 // prove that all accesses are well aligned and dereferenceable. 227 auto *AddRec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Ptr)); 228 if (!AddRec || AddRec->getLoop() != L || !AddRec->isAffine()) 229 return false; 230 auto* Step = dyn_cast<SCEVConstant>(AddRec->getStepRecurrence(SE)); 231 if (!Step) 232 return false; 233 // TODO: generalize to access patterns which have gaps 234 if (Step->getAPInt() != EltSize) 235 return false; 236 237 // TODO: If the symbolic trip count has a small bound (max count), we might 238 // be able to prove safety. 239 auto TC = SE.getSmallConstantTripCount(L); 240 if (!TC) 241 return false; 242 243 const APInt AccessSize = TC * EltSize; 244 245 auto *StartS = dyn_cast<SCEVUnknown>(AddRec->getStart()); 246 if (!StartS) 247 return false; 248 assert(SE.isLoopInvariant(StartS, L) && "implied by addrec definition"); 249 Value *Base = StartS->getValue(); 250 251 // For the moment, restrict ourselves to the case where the access size is a 252 // multiple of the requested alignment and the base is aligned. 253 // TODO: generalize if a case found which warrants 254 if (EltSize.urem(Alignment.value()) != 0) 255 return false; 256 return isDereferenceableAndAlignedPointer(Base, Alignment, AccessSize, DL, 257 HeaderFirstNonPHI, &DT); 258 } 259 260 /// Check if executing a load of this pointer value cannot trap. 261 /// 262 /// If DT and ScanFrom are specified this method performs context-sensitive 263 /// analysis and returns true if it is safe to load immediately before ScanFrom. 264 /// 265 /// If it is not obviously safe to load from the specified pointer, we do 266 /// a quick local scan of the basic block containing \c ScanFrom, to determine 267 /// if the address is already accessed. 268 /// 269 /// This uses the pointee type to determine how many bytes need to be safe to 270 /// load from the pointer. 271 bool llvm::isSafeToLoadUnconditionally(Value *V, MaybeAlign MA, APInt &Size, 272 const DataLayout &DL, 273 Instruction *ScanFrom, 274 const DominatorTree *DT) { 275 // Zero alignment means that the load has the ABI alignment for the target 276 const Align Alignment = 277 DL.getValueOrABITypeAlignment(MA, V->getType()->getPointerElementType()); 278 279 // If DT is not specified we can't make context-sensitive query 280 const Instruction* CtxI = DT ? ScanFrom : nullptr; 281 if (isDereferenceableAndAlignedPointer(V, Alignment, Size, DL, CtxI, DT)) 282 return true; 283 284 if (!ScanFrom) 285 return false; 286 287 if (Size.getBitWidth() > 64) 288 return false; 289 const uint64_t LoadSize = Size.getZExtValue(); 290 291 // Otherwise, be a little bit aggressive by scanning the local block where we 292 // want to check to see if the pointer is already being loaded or stored 293 // from/to. If so, the previous load or store would have already trapped, 294 // so there is no harm doing an extra load (also, CSE will later eliminate 295 // the load entirely). 296 BasicBlock::iterator BBI = ScanFrom->getIterator(), 297 E = ScanFrom->getParent()->begin(); 298 299 // We can at least always strip pointer casts even though we can't use the 300 // base here. 301 V = V->stripPointerCasts(); 302 303 while (BBI != E) { 304 --BBI; 305 306 // If we see a free or a call which may write to memory (i.e. which might do 307 // a free) the pointer could be marked invalid. 308 if (isa<CallInst>(BBI) && BBI->mayWriteToMemory() && 309 !isa<DbgInfoIntrinsic>(BBI)) 310 return false; 311 312 Value *AccessedPtr; 313 MaybeAlign MaybeAccessedAlign; 314 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) { 315 // Ignore volatile loads. The execution of a volatile load cannot 316 // be used to prove an address is backed by regular memory; it can, 317 // for example, point to an MMIO register. 318 if (LI->isVolatile()) 319 continue; 320 AccessedPtr = LI->getPointerOperand(); 321 MaybeAccessedAlign = MaybeAlign(LI->getAlignment()); 322 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) { 323 // Ignore volatile stores (see comment for loads). 324 if (SI->isVolatile()) 325 continue; 326 AccessedPtr = SI->getPointerOperand(); 327 MaybeAccessedAlign = MaybeAlign(SI->getAlignment()); 328 } else 329 continue; 330 331 Type *AccessedTy = AccessedPtr->getType()->getPointerElementType(); 332 333 const Align AccessedAlign = 334 DL.getValueOrABITypeAlignment(MaybeAccessedAlign, AccessedTy); 335 if (AccessedAlign < Alignment) 336 continue; 337 338 // Handle trivial cases. 339 if (AccessedPtr == V && 340 LoadSize <= DL.getTypeStoreSize(AccessedTy)) 341 return true; 342 343 if (AreEquivalentAddressValues(AccessedPtr->stripPointerCasts(), V) && 344 LoadSize <= DL.getTypeStoreSize(AccessedTy)) 345 return true; 346 } 347 return false; 348 } 349 350 bool llvm::isSafeToLoadUnconditionally(Value *V, Type *Ty, MaybeAlign Alignment, 351 const DataLayout &DL, 352 Instruction *ScanFrom, 353 const DominatorTree *DT) { 354 APInt Size(DL.getIndexTypeSizeInBits(V->getType()), DL.getTypeStoreSize(Ty)); 355 return isSafeToLoadUnconditionally(V, Alignment, Size, DL, ScanFrom, DT); 356 } 357 358 /// DefMaxInstsToScan - the default number of maximum instructions 359 /// to scan in the block, used by FindAvailableLoadedValue(). 360 /// FindAvailableLoadedValue() was introduced in r60148, to improve jump 361 /// threading in part by eliminating partially redundant loads. 362 /// At that point, the value of MaxInstsToScan was already set to '6' 363 /// without documented explanation. 364 cl::opt<unsigned> 365 llvm::DefMaxInstsToScan("available-load-scan-limit", cl::init(6), cl::Hidden, 366 cl::desc("Use this to specify the default maximum number of instructions " 367 "to scan backward from a given instruction, when searching for " 368 "available loaded value")); 369 370 Value *llvm::FindAvailableLoadedValue(LoadInst *Load, 371 BasicBlock *ScanBB, 372 BasicBlock::iterator &ScanFrom, 373 unsigned MaxInstsToScan, 374 AliasAnalysis *AA, bool *IsLoad, 375 unsigned *NumScanedInst) { 376 // Don't CSE load that is volatile or anything stronger than unordered. 377 if (!Load->isUnordered()) 378 return nullptr; 379 380 return FindAvailablePtrLoadStore( 381 Load->getPointerOperand(), Load->getType(), Load->isAtomic(), ScanBB, 382 ScanFrom, MaxInstsToScan, AA, IsLoad, NumScanedInst); 383 } 384 385 // Check if the load and the store have the same base, constant offsets and 386 // non-overlapping access ranges. 387 static bool AreNonOverlapSameBaseLoadAndStore( 388 Value *LoadPtr, Type *LoadTy, Value *StorePtr, Type *StoreTy, 389 const DataLayout &DL) { 390 APInt LoadOffset(DL.getTypeSizeInBits(LoadPtr->getType()), 0); 391 APInt StoreOffset(DL.getTypeSizeInBits(StorePtr->getType()), 0); 392 Value *LoadBase = LoadPtr->stripAndAccumulateConstantOffsets( 393 DL, LoadOffset, /* AllowNonInbounds */ false); 394 Value *StoreBase = StorePtr->stripAndAccumulateConstantOffsets( 395 DL, StoreOffset, /* AllowNonInbounds */ false); 396 if (LoadBase != StoreBase) 397 return false; 398 auto LoadAccessSize = LocationSize::precise(DL.getTypeStoreSize(LoadTy)); 399 auto StoreAccessSize = LocationSize::precise(DL.getTypeStoreSize(StoreTy)); 400 ConstantRange LoadRange(LoadOffset, 401 LoadOffset + LoadAccessSize.toRaw()); 402 ConstantRange StoreRange(StoreOffset, 403 StoreOffset + StoreAccessSize.toRaw()); 404 return LoadRange.intersectWith(StoreRange).isEmptySet(); 405 } 406 407 Value *llvm::FindAvailablePtrLoadStore(Value *Ptr, Type *AccessTy, 408 bool AtLeastAtomic, BasicBlock *ScanBB, 409 BasicBlock::iterator &ScanFrom, 410 unsigned MaxInstsToScan, 411 AliasAnalysis *AA, bool *IsLoadCSE, 412 unsigned *NumScanedInst) { 413 if (MaxInstsToScan == 0) 414 MaxInstsToScan = ~0U; 415 416 const DataLayout &DL = ScanBB->getModule()->getDataLayout(); 417 Value *StrippedPtr = Ptr->stripPointerCasts(); 418 419 while (ScanFrom != ScanBB->begin()) { 420 // We must ignore debug info directives when counting (otherwise they 421 // would affect codegen). 422 Instruction *Inst = &*--ScanFrom; 423 if (isa<DbgInfoIntrinsic>(Inst)) 424 continue; 425 426 // Restore ScanFrom to expected value in case next test succeeds 427 ScanFrom++; 428 429 if (NumScanedInst) 430 ++(*NumScanedInst); 431 432 // Don't scan huge blocks. 433 if (MaxInstsToScan-- == 0) 434 return nullptr; 435 436 --ScanFrom; 437 // If this is a load of Ptr, the loaded value is available. 438 // (This is true even if the load is volatile or atomic, although 439 // those cases are unlikely.) 440 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) 441 if (AreEquivalentAddressValues( 442 LI->getPointerOperand()->stripPointerCasts(), StrippedPtr) && 443 CastInst::isBitOrNoopPointerCastable(LI->getType(), AccessTy, DL)) { 444 445 // We can value forward from an atomic to a non-atomic, but not the 446 // other way around. 447 if (LI->isAtomic() < AtLeastAtomic) 448 return nullptr; 449 450 if (IsLoadCSE) 451 *IsLoadCSE = true; 452 return LI; 453 } 454 455 // Try to get the store size for the type. 456 auto AccessSize = LocationSize::precise(DL.getTypeStoreSize(AccessTy)); 457 458 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 459 Value *StorePtr = SI->getPointerOperand()->stripPointerCasts(); 460 // If this is a store through Ptr, the value is available! 461 // (This is true even if the store is volatile or atomic, although 462 // those cases are unlikely.) 463 if (AreEquivalentAddressValues(StorePtr, StrippedPtr) && 464 CastInst::isBitOrNoopPointerCastable(SI->getValueOperand()->getType(), 465 AccessTy, DL)) { 466 467 // We can value forward from an atomic to a non-atomic, but not the 468 // other way around. 469 if (SI->isAtomic() < AtLeastAtomic) 470 return nullptr; 471 472 if (IsLoadCSE) 473 *IsLoadCSE = false; 474 return SI->getOperand(0); 475 } 476 477 // If both StrippedPtr and StorePtr reach all the way to an alloca or 478 // global and they are different, ignore the store. This is a trivial form 479 // of alias analysis that is important for reg2mem'd code. 480 if ((isa<AllocaInst>(StrippedPtr) || isa<GlobalVariable>(StrippedPtr)) && 481 (isa<AllocaInst>(StorePtr) || isa<GlobalVariable>(StorePtr)) && 482 StrippedPtr != StorePtr) 483 continue; 484 485 if (!AA) { 486 // When AA isn't available, but if the load and the store have the same 487 // base, constant offsets and non-overlapping access ranges, ignore the 488 // store. This is a simple form of alias analysis that is used by the 489 // inliner. FIXME: use BasicAA if possible. 490 if (AreNonOverlapSameBaseLoadAndStore( 491 Ptr, AccessTy, SI->getPointerOperand(), 492 SI->getValueOperand()->getType(), DL)) 493 continue; 494 } else { 495 // If we have alias analysis and it says the store won't modify the 496 // loaded value, ignore the store. 497 if (!isModSet(AA->getModRefInfo(SI, StrippedPtr, AccessSize))) 498 continue; 499 } 500 501 // Otherwise the store that may or may not alias the pointer, bail out. 502 ++ScanFrom; 503 return nullptr; 504 } 505 506 // If this is some other instruction that may clobber Ptr, bail out. 507 if (Inst->mayWriteToMemory()) { 508 // If alias analysis claims that it really won't modify the load, 509 // ignore it. 510 if (AA && !isModSet(AA->getModRefInfo(Inst, StrippedPtr, AccessSize))) 511 continue; 512 513 // May modify the pointer, bail out. 514 ++ScanFrom; 515 return nullptr; 516 } 517 } 518 519 // Got to the start of the block, we didn't find it, but are done for this 520 // block. 521 return nullptr; 522 } 523