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