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