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/AssumeBundleQueries.h" 16 #include "llvm/Analysis/CaptureTracking.h" 17 #include "llvm/Analysis/LoopInfo.h" 18 #include "llvm/Analysis/MemoryBuiltins.h" 19 #include "llvm/Analysis/ScalarEvolution.h" 20 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 21 #include "llvm/Analysis/TargetLibraryInfo.h" 22 #include "llvm/Analysis/ValueTracking.h" 23 #include "llvm/IR/DataLayout.h" 24 #include "llvm/IR/GlobalAlias.h" 25 #include "llvm/IR/GlobalVariable.h" 26 #include "llvm/IR/IntrinsicInst.h" 27 #include "llvm/IR/LLVMContext.h" 28 #include "llvm/IR/Module.h" 29 #include "llvm/IR/Operator.h" 30 #include "llvm/IR/Statepoint.h" 31 32 using namespace llvm; 33 34 static bool isAligned(const Value *Base, const APInt &Offset, Align Alignment, 35 const DataLayout &DL) { 36 Align BA = Base->getPointerAlignment(DL); 37 const APInt APAlign(Offset.getBitWidth(), Alignment.value()); 38 assert(APAlign.isPowerOf2() && "must be a power of 2!"); 39 return BA >= Alignment && !(Offset & (APAlign - 1)); 40 } 41 42 /// Test if V is always a pointer to allocated and suitably aligned memory for 43 /// a simple load or store. 44 static bool isDereferenceableAndAlignedPointer( 45 const Value *V, Align Alignment, const APInt &Size, const DataLayout &DL, 46 const Instruction *CtxI, const DominatorTree *DT, 47 const TargetLibraryInfo *TLI, SmallPtrSetImpl<const Value *> &Visited, 48 unsigned MaxDepth) { 49 assert(V->getType()->isPointerTy() && "Base must be pointer"); 50 51 // Recursion limit. 52 if (MaxDepth-- == 0) 53 return false; 54 55 // Already visited? Bail out, we've likely hit unreachable code. 56 if (!Visited.insert(V).second) 57 return false; 58 59 // Note that it is not safe to speculate into a malloc'd region because 60 // malloc may return null. 61 62 // bitcast instructions are no-ops as far as dereferenceability is concerned. 63 if (const BitCastOperator *BC = dyn_cast<BitCastOperator>(V)) { 64 if (BC->getSrcTy()->isPointerTy()) 65 return isDereferenceableAndAlignedPointer( 66 BC->getOperand(0), Alignment, Size, DL, CtxI, DT, TLI, 67 Visited, MaxDepth); 68 } 69 70 bool CheckForNonNull, CheckForFreed; 71 APInt KnownDerefBytes(Size.getBitWidth(), 72 V->getPointerDereferenceableBytes(DL, CheckForNonNull, 73 CheckForFreed)); 74 if (KnownDerefBytes.getBoolValue() && KnownDerefBytes.uge(Size) && 75 !CheckForFreed) 76 if (!CheckForNonNull || isKnownNonZero(V, DL, 0, nullptr, CtxI, DT)) { 77 // As we recursed through GEPs to get here, we've incrementally checked 78 // that each step advanced by a multiple of the alignment. If our base is 79 // properly aligned, then the original offset accessed must also be. 80 Type *Ty = V->getType(); 81 assert(Ty->isSized() && "must be sized"); 82 APInt Offset(DL.getTypeStoreSizeInBits(Ty), 0); 83 return isAligned(V, Offset, Alignment, DL); 84 } 85 86 if (CtxI) { 87 /// Look through assumes to see if both dereferencability and alignment can 88 /// be provent by an assume 89 RetainedKnowledge AlignRK; 90 RetainedKnowledge DerefRK; 91 if (getKnowledgeForValue( 92 V, {Attribute::Dereferenceable, Attribute::Alignment}, nullptr, 93 [&](RetainedKnowledge RK, Instruction *Assume, auto) { 94 if (!isValidAssumeForContext(Assume, CtxI)) 95 return false; 96 if (RK.AttrKind == Attribute::Alignment) 97 AlignRK = std::max(AlignRK, RK); 98 if (RK.AttrKind == Attribute::Dereferenceable) 99 DerefRK = std::max(DerefRK, RK); 100 if (AlignRK && DerefRK && AlignRK.ArgValue >= Alignment.value() && 101 DerefRK.ArgValue >= Size.getZExtValue()) 102 return true; // We have found what we needed so we stop looking 103 return false; // Other assumes may have better information. so 104 // keep looking 105 })) 106 return true; 107 } 108 /// TODO refactor this function to be able to search independently for 109 /// Dereferencability and Alignment requirements. 110 111 // For GEPs, determine if the indexing lands within the allocated object. 112 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) { 113 const Value *Base = GEP->getPointerOperand(); 114 115 APInt Offset(DL.getIndexTypeSizeInBits(GEP->getType()), 0); 116 if (!GEP->accumulateConstantOffset(DL, Offset) || Offset.isNegative() || 117 !Offset.urem(APInt(Offset.getBitWidth(), Alignment.value())) 118 .isMinValue()) 119 return false; 120 121 // If the base pointer is dereferenceable for Offset+Size bytes, then the 122 // GEP (== Base + Offset) is dereferenceable for Size bytes. If the base 123 // pointer is aligned to Align bytes, and the Offset is divisible by Align 124 // then the GEP (== Base + Offset == k_0 * Align + k_1 * Align) is also 125 // aligned to Align bytes. 126 127 // Offset and Size may have different bit widths if we have visited an 128 // addrspacecast, so we can't do arithmetic directly on the APInt values. 129 return isDereferenceableAndAlignedPointer( 130 Base, Alignment, Offset + Size.sextOrTrunc(Offset.getBitWidth()), DL, 131 CtxI, DT, TLI, Visited, MaxDepth); 132 } 133 134 // For gc.relocate, look through relocations 135 if (const GCRelocateInst *RelocateInst = dyn_cast<GCRelocateInst>(V)) 136 return isDereferenceableAndAlignedPointer(RelocateInst->getDerivedPtr(), 137 Alignment, Size, DL, CtxI, DT, 138 TLI, Visited, MaxDepth); 139 140 if (const AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(V)) 141 return isDereferenceableAndAlignedPointer(ASC->getOperand(0), Alignment, 142 Size, DL, CtxI, DT, TLI, 143 Visited, MaxDepth); 144 145 if (const auto *Call = dyn_cast<CallBase>(V)) { 146 if (auto *RP = getArgumentAliasingToReturnedPointer(Call, true)) 147 return isDereferenceableAndAlignedPointer(RP, Alignment, Size, DL, CtxI, 148 DT, TLI, Visited, MaxDepth); 149 150 // If we have a call we can't recurse through, check to see if this is an 151 // allocation function for which we can establish an minimum object size. 152 // Such a minimum object size is analogous to a deref_or_null attribute in 153 // that we still need to prove the result non-null at point of use. 154 // NOTE: We can only use the object size as a base fact as we a) need to 155 // prove alignment too, and b) don't want the compile time impact of a 156 // separate recursive walk. 157 ObjectSizeOpts Opts; 158 // TODO: It may be okay to round to align, but that would imply that 159 // accessing slightly out of bounds was legal, and we're currently 160 // inconsistent about that. For the moment, be conservative. 161 Opts.RoundToAlign = false; 162 Opts.NullIsUnknownSize = true; 163 uint64_t ObjSize; 164 // TODO: Plumb through TLI so that malloc routines and such working. 165 if (getObjectSize(V, ObjSize, DL, nullptr, Opts)) { 166 APInt KnownDerefBytes(Size.getBitWidth(), ObjSize); 167 if (KnownDerefBytes.getBoolValue() && KnownDerefBytes.uge(Size) && 168 isKnownNonZero(V, DL, 0, nullptr, CtxI, DT) && 169 // TODO: We're currently inconsistent about whether deref(N) is a 170 // global fact or a point in time fact. Once D61652 eventually 171 // lands, this check will be restricted to the point in time 172 // variant. For that variant, we need to prove that object hasn't 173 // been conditionally freed before ontext instruction - if it has, we 174 // might be hoisting over the inverse conditional and creating a 175 // dynamic use after free. 176 !PointerMayBeCapturedBefore(V, true, true, CtxI, DT, true)) { 177 // As we recursed through GEPs to get here, we've incrementally 178 // checked that each step advanced by a multiple of the alignment. If 179 // our base is properly aligned, then the original offset accessed 180 // must also be. 181 Type *Ty = V->getType(); 182 assert(Ty->isSized() && "must be sized"); 183 APInt Offset(DL.getTypeStoreSizeInBits(Ty), 0); 184 return isAligned(V, Offset, Alignment, DL); 185 } 186 } 187 } 188 189 // If we don't know, assume the worst. 190 return false; 191 } 192 193 bool llvm::isDereferenceableAndAlignedPointer(const Value *V, Align Alignment, 194 const APInt &Size, 195 const DataLayout &DL, 196 const Instruction *CtxI, 197 const DominatorTree *DT, 198 const TargetLibraryInfo *TLI) { 199 // Note: At the moment, Size can be zero. This ends up being interpreted as 200 // a query of whether [Base, V] is dereferenceable and V is aligned (since 201 // that's what the implementation happened to do). It's unclear if this is 202 // the desired semantic, but at least SelectionDAG does exercise this case. 203 204 SmallPtrSet<const Value *, 32> Visited; 205 return ::isDereferenceableAndAlignedPointer(V, Alignment, Size, DL, CtxI, DT, 206 TLI, Visited, 16); 207 } 208 209 bool llvm::isDereferenceableAndAlignedPointer(const Value *V, Type *Ty, 210 MaybeAlign MA, 211 const DataLayout &DL, 212 const Instruction *CtxI, 213 const DominatorTree *DT, 214 const TargetLibraryInfo *TLI) { 215 // For unsized types or scalable vectors we don't know exactly how many bytes 216 // are dereferenced, so bail out. 217 if (!Ty->isSized() || isa<ScalableVectorType>(Ty)) 218 return false; 219 220 // When dereferenceability information is provided by a dereferenceable 221 // attribute, we know exactly how many bytes are dereferenceable. If we can 222 // determine the exact offset to the attributed variable, we can use that 223 // information here. 224 225 // Require ABI alignment for loads without alignment specification 226 const Align Alignment = DL.getValueOrABITypeAlignment(MA, Ty); 227 APInt AccessSize(DL.getPointerTypeSizeInBits(V->getType()), 228 DL.getTypeStoreSize(Ty)); 229 return isDereferenceableAndAlignedPointer(V, Alignment, AccessSize, DL, CtxI, 230 DT, TLI); 231 } 232 233 bool llvm::isDereferenceablePointer(const Value *V, Type *Ty, 234 const DataLayout &DL, 235 const Instruction *CtxI, 236 const DominatorTree *DT, 237 const TargetLibraryInfo *TLI) { 238 return isDereferenceableAndAlignedPointer(V, Ty, Align(1), DL, CtxI, DT, TLI); 239 } 240 241 /// Test if A and B will obviously have the same value. 242 /// 243 /// This includes recognizing that %t0 and %t1 will have the same 244 /// value in code like this: 245 /// \code 246 /// %t0 = getelementptr \@a, 0, 3 247 /// store i32 0, i32* %t0 248 /// %t1 = getelementptr \@a, 0, 3 249 /// %t2 = load i32* %t1 250 /// \endcode 251 /// 252 static bool AreEquivalentAddressValues(const Value *A, const Value *B) { 253 // Test if the values are trivially equivalent. 254 if (A == B) 255 return true; 256 257 // Test if the values come from identical arithmetic instructions. 258 // Use isIdenticalToWhenDefined instead of isIdenticalTo because 259 // this function is only used when one address use dominates the 260 // other, which means that they'll always either have the same 261 // value or one of them will have an undefined value. 262 if (isa<BinaryOperator>(A) || isa<CastInst>(A) || isa<PHINode>(A) || 263 isa<GetElementPtrInst>(A)) 264 if (const Instruction *BI = dyn_cast<Instruction>(B)) 265 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI)) 266 return true; 267 268 // Otherwise they may not be equivalent. 269 return false; 270 } 271 272 bool llvm::isDereferenceableAndAlignedInLoop(LoadInst *LI, Loop *L, 273 ScalarEvolution &SE, 274 DominatorTree &DT) { 275 auto &DL = LI->getModule()->getDataLayout(); 276 Value *Ptr = LI->getPointerOperand(); 277 278 APInt EltSize(DL.getIndexTypeSizeInBits(Ptr->getType()), 279 DL.getTypeStoreSize(LI->getType()).getFixedSize()); 280 const Align Alignment = LI->getAlign(); 281 282 Instruction *HeaderFirstNonPHI = L->getHeader()->getFirstNonPHI(); 283 284 // If given a uniform (i.e. non-varying) address, see if we can prove the 285 // access is safe within the loop w/o needing predication. 286 if (L->isLoopInvariant(Ptr)) 287 return isDereferenceableAndAlignedPointer(Ptr, Alignment, EltSize, DL, 288 HeaderFirstNonPHI, &DT); 289 290 // Otherwise, check to see if we have a repeating access pattern where we can 291 // prove that all accesses are well aligned and dereferenceable. 292 auto *AddRec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Ptr)); 293 if (!AddRec || AddRec->getLoop() != L || !AddRec->isAffine()) 294 return false; 295 auto* Step = dyn_cast<SCEVConstant>(AddRec->getStepRecurrence(SE)); 296 if (!Step) 297 return false; 298 // TODO: generalize to access patterns which have gaps 299 if (Step->getAPInt() != EltSize) 300 return false; 301 302 auto TC = SE.getSmallConstantMaxTripCount(L); 303 if (!TC) 304 return false; 305 306 const APInt AccessSize = TC * EltSize; 307 308 auto *StartS = dyn_cast<SCEVUnknown>(AddRec->getStart()); 309 if (!StartS) 310 return false; 311 assert(SE.isLoopInvariant(StartS, L) && "implied by addrec definition"); 312 Value *Base = StartS->getValue(); 313 314 // For the moment, restrict ourselves to the case where the access size is a 315 // multiple of the requested alignment and the base is aligned. 316 // TODO: generalize if a case found which warrants 317 if (EltSize.urem(Alignment.value()) != 0) 318 return false; 319 return isDereferenceableAndAlignedPointer(Base, Alignment, AccessSize, DL, 320 HeaderFirstNonPHI, &DT); 321 } 322 323 /// Check if executing a load of this pointer value cannot trap. 324 /// 325 /// If DT and ScanFrom are specified this method performs context-sensitive 326 /// analysis and returns true if it is safe to load immediately before ScanFrom. 327 /// 328 /// If it is not obviously safe to load from the specified pointer, we do 329 /// a quick local scan of the basic block containing \c ScanFrom, to determine 330 /// if the address is already accessed. 331 /// 332 /// This uses the pointee type to determine how many bytes need to be safe to 333 /// load from the pointer. 334 bool llvm::isSafeToLoadUnconditionally(Value *V, Align Alignment, APInt &Size, 335 const DataLayout &DL, 336 Instruction *ScanFrom, 337 const DominatorTree *DT, 338 const TargetLibraryInfo *TLI) { 339 // If DT is not specified we can't make context-sensitive query 340 const Instruction* CtxI = DT ? ScanFrom : nullptr; 341 if (isDereferenceableAndAlignedPointer(V, Alignment, Size, DL, CtxI, DT, TLI)) 342 return true; 343 344 if (!ScanFrom) 345 return false; 346 347 if (Size.getBitWidth() > 64) 348 return false; 349 const uint64_t LoadSize = Size.getZExtValue(); 350 351 // Otherwise, be a little bit aggressive by scanning the local block where we 352 // want to check to see if the pointer is already being loaded or stored 353 // from/to. If so, the previous load or store would have already trapped, 354 // so there is no harm doing an extra load (also, CSE will later eliminate 355 // the load entirely). 356 BasicBlock::iterator BBI = ScanFrom->getIterator(), 357 E = ScanFrom->getParent()->begin(); 358 359 // We can at least always strip pointer casts even though we can't use the 360 // base here. 361 V = V->stripPointerCasts(); 362 363 while (BBI != E) { 364 --BBI; 365 366 // If we see a free or a call which may write to memory (i.e. which might do 367 // a free) the pointer could be marked invalid. 368 if (isa<CallInst>(BBI) && BBI->mayWriteToMemory() && 369 !isa<DbgInfoIntrinsic>(BBI)) 370 return false; 371 372 Value *AccessedPtr; 373 Type *AccessedTy; 374 Align AccessedAlign; 375 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) { 376 // Ignore volatile loads. The execution of a volatile load cannot 377 // be used to prove an address is backed by regular memory; it can, 378 // for example, point to an MMIO register. 379 if (LI->isVolatile()) 380 continue; 381 AccessedPtr = LI->getPointerOperand(); 382 AccessedTy = LI->getType(); 383 AccessedAlign = LI->getAlign(); 384 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) { 385 // Ignore volatile stores (see comment for loads). 386 if (SI->isVolatile()) 387 continue; 388 AccessedPtr = SI->getPointerOperand(); 389 AccessedTy = SI->getValueOperand()->getType(); 390 AccessedAlign = SI->getAlign(); 391 } else 392 continue; 393 394 if (AccessedAlign < Alignment) 395 continue; 396 397 // Handle trivial cases. 398 if (AccessedPtr == V && 399 LoadSize <= DL.getTypeStoreSize(AccessedTy)) 400 return true; 401 402 if (AreEquivalentAddressValues(AccessedPtr->stripPointerCasts(), V) && 403 LoadSize <= DL.getTypeStoreSize(AccessedTy)) 404 return true; 405 } 406 return false; 407 } 408 409 bool llvm::isSafeToLoadUnconditionally(Value *V, Type *Ty, Align Alignment, 410 const DataLayout &DL, 411 Instruction *ScanFrom, 412 const DominatorTree *DT, 413 const TargetLibraryInfo *TLI) { 414 APInt Size(DL.getIndexTypeSizeInBits(V->getType()), DL.getTypeStoreSize(Ty)); 415 return isSafeToLoadUnconditionally(V, Alignment, Size, DL, ScanFrom, DT, TLI); 416 } 417 418 /// DefMaxInstsToScan - the default number of maximum instructions 419 /// to scan in the block, used by FindAvailableLoadedValue(). 420 /// FindAvailableLoadedValue() was introduced in r60148, to improve jump 421 /// threading in part by eliminating partially redundant loads. 422 /// At that point, the value of MaxInstsToScan was already set to '6' 423 /// without documented explanation. 424 cl::opt<unsigned> 425 llvm::DefMaxInstsToScan("available-load-scan-limit", cl::init(6), cl::Hidden, 426 cl::desc("Use this to specify the default maximum number of instructions " 427 "to scan backward from a given instruction, when searching for " 428 "available loaded value")); 429 430 Value *llvm::FindAvailableLoadedValue(LoadInst *Load, 431 BasicBlock *ScanBB, 432 BasicBlock::iterator &ScanFrom, 433 unsigned MaxInstsToScan, 434 AAResults *AA, bool *IsLoad, 435 unsigned *NumScanedInst) { 436 // Don't CSE load that is volatile or anything stronger than unordered. 437 if (!Load->isUnordered()) 438 return nullptr; 439 440 return FindAvailablePtrLoadStore( 441 Load->getPointerOperand(), Load->getType(), Load->isAtomic(), ScanBB, 442 ScanFrom, MaxInstsToScan, AA, IsLoad, NumScanedInst); 443 } 444 445 // Check if the load and the store have the same base, constant offsets and 446 // non-overlapping access ranges. 447 static bool AreNonOverlapSameBaseLoadAndStore( 448 Value *LoadPtr, Type *LoadTy, Value *StorePtr, Type *StoreTy, 449 const DataLayout &DL) { 450 APInt LoadOffset(DL.getTypeSizeInBits(LoadPtr->getType()), 0); 451 APInt StoreOffset(DL.getTypeSizeInBits(StorePtr->getType()), 0); 452 Value *LoadBase = LoadPtr->stripAndAccumulateConstantOffsets( 453 DL, LoadOffset, /* AllowNonInbounds */ false); 454 Value *StoreBase = StorePtr->stripAndAccumulateConstantOffsets( 455 DL, StoreOffset, /* AllowNonInbounds */ false); 456 if (LoadBase != StoreBase) 457 return false; 458 auto LoadAccessSize = LocationSize::precise(DL.getTypeStoreSize(LoadTy)); 459 auto StoreAccessSize = LocationSize::precise(DL.getTypeStoreSize(StoreTy)); 460 ConstantRange LoadRange(LoadOffset, 461 LoadOffset + LoadAccessSize.toRaw()); 462 ConstantRange StoreRange(StoreOffset, 463 StoreOffset + StoreAccessSize.toRaw()); 464 return LoadRange.intersectWith(StoreRange).isEmptySet(); 465 } 466 467 static Value *getAvailableLoadStore(Instruction *Inst, Value *Ptr, 468 Type *AccessTy, bool AtLeastAtomic, 469 const DataLayout &DL, bool *IsLoadCSE) { 470 // If this is a load of Ptr, the loaded value is available. 471 // (This is true even if the load is volatile or atomic, although 472 // those cases are unlikely.) 473 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) { 474 // We can value forward from an atomic to a non-atomic, but not the 475 // other way around. 476 if (LI->isAtomic() < AtLeastAtomic) 477 return nullptr; 478 479 Value *LoadPtr = LI->getPointerOperand()->stripPointerCasts(); 480 if (!AreEquivalentAddressValues(LoadPtr, Ptr)) 481 return nullptr; 482 483 if (CastInst::isBitOrNoopPointerCastable(LI->getType(), AccessTy, DL)) { 484 if (IsLoadCSE) 485 *IsLoadCSE = true; 486 return LI; 487 } 488 } 489 490 // If this is a store through Ptr, the value is available! 491 // (This is true even if the store is volatile or atomic, although 492 // those cases are unlikely.) 493 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 494 // We can value forward from an atomic to a non-atomic, but not the 495 // other way around. 496 if (SI->isAtomic() < AtLeastAtomic) 497 return nullptr; 498 499 Value *StorePtr = SI->getPointerOperand()->stripPointerCasts(); 500 if (!AreEquivalentAddressValues(StorePtr, Ptr)) 501 return nullptr; 502 503 Value *Val = SI->getValueOperand(); 504 if (CastInst::isBitOrNoopPointerCastable(Val->getType(), AccessTy, DL)) { 505 if (IsLoadCSE) 506 *IsLoadCSE = false; 507 return Val; 508 } 509 } 510 511 return nullptr; 512 } 513 514 Value *llvm::FindAvailablePtrLoadStore(Value *Ptr, Type *AccessTy, 515 bool AtLeastAtomic, BasicBlock *ScanBB, 516 BasicBlock::iterator &ScanFrom, 517 unsigned MaxInstsToScan, 518 AAResults *AA, bool *IsLoadCSE, 519 unsigned *NumScanedInst) { 520 if (MaxInstsToScan == 0) 521 MaxInstsToScan = ~0U; 522 523 const DataLayout &DL = ScanBB->getModule()->getDataLayout(); 524 Value *StrippedPtr = Ptr->stripPointerCasts(); 525 526 while (ScanFrom != ScanBB->begin()) { 527 // We must ignore debug info directives when counting (otherwise they 528 // would affect codegen). 529 Instruction *Inst = &*--ScanFrom; 530 if (isa<DbgInfoIntrinsic>(Inst)) 531 continue; 532 533 // Restore ScanFrom to expected value in case next test succeeds 534 ScanFrom++; 535 536 if (NumScanedInst) 537 ++(*NumScanedInst); 538 539 // Don't scan huge blocks. 540 if (MaxInstsToScan-- == 0) 541 return nullptr; 542 543 --ScanFrom; 544 545 if (Value *Available = getAvailableLoadStore(Inst, StrippedPtr, AccessTy, 546 AtLeastAtomic, DL, IsLoadCSE)) 547 return Available; 548 549 // Try to get the store size for the type. 550 auto AccessSize = LocationSize::precise(DL.getTypeStoreSize(AccessTy)); 551 552 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 553 Value *StorePtr = SI->getPointerOperand()->stripPointerCasts(); 554 555 // If both StrippedPtr and StorePtr reach all the way to an alloca or 556 // global and they are different, ignore the store. This is a trivial form 557 // of alias analysis that is important for reg2mem'd code. 558 if ((isa<AllocaInst>(StrippedPtr) || isa<GlobalVariable>(StrippedPtr)) && 559 (isa<AllocaInst>(StorePtr) || isa<GlobalVariable>(StorePtr)) && 560 StrippedPtr != StorePtr) 561 continue; 562 563 if (!AA) { 564 // When AA isn't available, but if the load and the store have the same 565 // base, constant offsets and non-overlapping access ranges, ignore the 566 // store. This is a simple form of alias analysis that is used by the 567 // inliner. FIXME: use BasicAA if possible. 568 if (AreNonOverlapSameBaseLoadAndStore( 569 Ptr, AccessTy, SI->getPointerOperand(), 570 SI->getValueOperand()->getType(), DL)) 571 continue; 572 } else { 573 // If we have alias analysis and it says the store won't modify the 574 // loaded value, ignore the store. 575 if (!isModSet(AA->getModRefInfo(SI, StrippedPtr, AccessSize))) 576 continue; 577 } 578 579 // Otherwise the store that may or may not alias the pointer, bail out. 580 ++ScanFrom; 581 return nullptr; 582 } 583 584 // If this is some other instruction that may clobber Ptr, bail out. 585 if (Inst->mayWriteToMemory()) { 586 // If alias analysis claims that it really won't modify the load, 587 // ignore it. 588 if (AA && !isModSet(AA->getModRefInfo(Inst, StrippedPtr, AccessSize))) 589 continue; 590 591 // May modify the pointer, bail out. 592 ++ScanFrom; 593 return nullptr; 594 } 595 } 596 597 // Got to the start of the block, we didn't find it, but are done for this 598 // block. 599 return nullptr; 600 } 601 602 Value *llvm::FindAvailableLoadedValue(LoadInst *Load, AAResults &AA, 603 bool *IsLoadCSE, 604 unsigned MaxInstsToScan) { 605 const DataLayout &DL = Load->getModule()->getDataLayout(); 606 Value *StrippedPtr = Load->getPointerOperand()->stripPointerCasts(); 607 BasicBlock *ScanBB = Load->getParent(); 608 Type *AccessTy = Load->getType(); 609 bool AtLeastAtomic = Load->isAtomic(); 610 611 if (!Load->isUnordered()) 612 return nullptr; 613 614 // Try to find an available value first, and delay expensive alias analysis 615 // queries until later. 616 Value *Available = nullptr;; 617 SmallVector<Instruction *> MustNotAliasInsts; 618 for (Instruction &Inst : make_range(++Load->getReverseIterator(), 619 ScanBB->rend())) { 620 if (isa<DbgInfoIntrinsic>(&Inst)) 621 continue; 622 623 if (MaxInstsToScan-- == 0) 624 return nullptr; 625 626 Available = getAvailableLoadStore(&Inst, StrippedPtr, AccessTy, 627 AtLeastAtomic, DL, IsLoadCSE); 628 if (Available) 629 break; 630 631 if (Inst.mayWriteToMemory()) 632 MustNotAliasInsts.push_back(&Inst); 633 } 634 635 // If we found an available value, ensure that the instructions in between 636 // did not modify the memory location. 637 if (Available) { 638 auto AccessSize = LocationSize::precise(DL.getTypeStoreSize(AccessTy)); 639 for (Instruction *Inst : MustNotAliasInsts) 640 if (isModSet(AA.getModRefInfo(Inst, StrippedPtr, AccessSize))) 641 return nullptr; 642 } 643 644 return Available; 645 } 646 647 bool llvm::canReplacePointersIfEqual(Value *A, Value *B, const DataLayout &DL, 648 Instruction *CtxI) { 649 Type *Ty = A->getType(); 650 assert(Ty == B->getType() && Ty->isPointerTy() && 651 "values must have matching pointer types"); 652 653 // NOTE: The checks in the function are incomplete and currently miss illegal 654 // cases! The current implementation is a starting point and the 655 // implementation should be made stricter over time. 656 if (auto *C = dyn_cast<Constant>(B)) { 657 // Do not allow replacing a pointer with a constant pointer, unless it is 658 // either null or at least one byte is dereferenceable. 659 APInt OneByte(DL.getPointerTypeSizeInBits(Ty), 1); 660 return C->isNullValue() || 661 isDereferenceableAndAlignedPointer(B, Align(1), OneByte, DL, CtxI); 662 } 663 664 return true; 665 } 666