1 #include "llvm/Transforms/Utils/VNCoercion.h" 2 #include "llvm/Analysis/ConstantFolding.h" 3 #include "llvm/Analysis/ValueTracking.h" 4 #include "llvm/IR/IRBuilder.h" 5 #include "llvm/Support/Debug.h" 6 7 #define DEBUG_TYPE "vncoerce" 8 9 namespace llvm { 10 namespace VNCoercion { 11 12 static bool isFirstClassAggregateOrScalableType(Type *Ty) { 13 return Ty->isStructTy() || Ty->isArrayTy() || isa<ScalableVectorType>(Ty); 14 } 15 16 /// Return true if coerceAvailableValueToLoadType will succeed. 17 bool canCoerceMustAliasedValueToLoad(Value *StoredVal, Type *LoadTy, 18 const DataLayout &DL) { 19 Type *StoredTy = StoredVal->getType(); 20 21 if (StoredTy == LoadTy) 22 return true; 23 24 // If the loaded/stored value is a first class array/struct, or scalable type, 25 // don't try to transform them. We need to be able to bitcast to integer. 26 if (isFirstClassAggregateOrScalableType(LoadTy) || 27 isFirstClassAggregateOrScalableType(StoredTy)) 28 return false; 29 30 uint64_t StoreSize = DL.getTypeSizeInBits(StoredTy).getFixedSize(); 31 32 // The store size must be byte-aligned to support future type casts. 33 if (llvm::alignTo(StoreSize, 8) != StoreSize) 34 return false; 35 36 // The store has to be at least as big as the load. 37 if (StoreSize < DL.getTypeSizeInBits(LoadTy).getFixedSize()) 38 return false; 39 40 bool StoredNI = DL.isNonIntegralPointerType(StoredTy->getScalarType()); 41 bool LoadNI = DL.isNonIntegralPointerType(LoadTy->getScalarType()); 42 // Don't coerce non-integral pointers to integers or vice versa. 43 if (StoredNI != LoadNI) { 44 // As a special case, allow coercion of memset used to initialize 45 // an array w/null. Despite non-integral pointers not generally having a 46 // specific bit pattern, we do assume null is zero. 47 if (auto *CI = dyn_cast<Constant>(StoredVal)) 48 return CI->isNullValue(); 49 return false; 50 } else if (StoredNI && LoadNI && 51 StoredTy->getPointerAddressSpace() != 52 LoadTy->getPointerAddressSpace()) { 53 return false; 54 } 55 56 57 // The implementation below uses inttoptr for vectors of unequal size; we 58 // can't allow this for non integral pointers. We could teach it to extract 59 // exact subvectors if desired. 60 if (StoredNI && StoreSize != DL.getTypeSizeInBits(LoadTy).getFixedSize()) 61 return false; 62 63 return true; 64 } 65 66 template <class T, class HelperClass> 67 static T *coerceAvailableValueToLoadTypeHelper(T *StoredVal, Type *LoadedTy, 68 HelperClass &Helper, 69 const DataLayout &DL) { 70 assert(canCoerceMustAliasedValueToLoad(StoredVal, LoadedTy, DL) && 71 "precondition violation - materialization can't fail"); 72 if (auto *C = dyn_cast<Constant>(StoredVal)) 73 StoredVal = ConstantFoldConstant(C, DL); 74 75 // If this is already the right type, just return it. 76 Type *StoredValTy = StoredVal->getType(); 77 78 uint64_t StoredValSize = DL.getTypeSizeInBits(StoredValTy).getFixedSize(); 79 uint64_t LoadedValSize = DL.getTypeSizeInBits(LoadedTy).getFixedSize(); 80 81 // If the store and reload are the same size, we can always reuse it. 82 if (StoredValSize == LoadedValSize) { 83 // Pointer to Pointer -> use bitcast. 84 if (StoredValTy->isPtrOrPtrVectorTy() && LoadedTy->isPtrOrPtrVectorTy()) { 85 StoredVal = Helper.CreateBitCast(StoredVal, LoadedTy); 86 } else { 87 // Convert source pointers to integers, which can be bitcast. 88 if (StoredValTy->isPtrOrPtrVectorTy()) { 89 StoredValTy = DL.getIntPtrType(StoredValTy); 90 StoredVal = Helper.CreatePtrToInt(StoredVal, StoredValTy); 91 } 92 93 Type *TypeToCastTo = LoadedTy; 94 if (TypeToCastTo->isPtrOrPtrVectorTy()) 95 TypeToCastTo = DL.getIntPtrType(TypeToCastTo); 96 97 if (StoredValTy != TypeToCastTo) 98 StoredVal = Helper.CreateBitCast(StoredVal, TypeToCastTo); 99 100 // Cast to pointer if the load needs a pointer type. 101 if (LoadedTy->isPtrOrPtrVectorTy()) 102 StoredVal = Helper.CreateIntToPtr(StoredVal, LoadedTy); 103 } 104 105 if (auto *C = dyn_cast<ConstantExpr>(StoredVal)) 106 StoredVal = ConstantFoldConstant(C, DL); 107 108 return StoredVal; 109 } 110 // If the loaded value is smaller than the available value, then we can 111 // extract out a piece from it. If the available value is too small, then we 112 // can't do anything. 113 assert(StoredValSize >= LoadedValSize && 114 "canCoerceMustAliasedValueToLoad fail"); 115 116 // Convert source pointers to integers, which can be manipulated. 117 if (StoredValTy->isPtrOrPtrVectorTy()) { 118 StoredValTy = DL.getIntPtrType(StoredValTy); 119 StoredVal = Helper.CreatePtrToInt(StoredVal, StoredValTy); 120 } 121 122 // Convert vectors and fp to integer, which can be manipulated. 123 if (!StoredValTy->isIntegerTy()) { 124 StoredValTy = IntegerType::get(StoredValTy->getContext(), StoredValSize); 125 StoredVal = Helper.CreateBitCast(StoredVal, StoredValTy); 126 } 127 128 // If this is a big-endian system, we need to shift the value down to the low 129 // bits so that a truncate will work. 130 if (DL.isBigEndian()) { 131 uint64_t ShiftAmt = DL.getTypeStoreSizeInBits(StoredValTy).getFixedSize() - 132 DL.getTypeStoreSizeInBits(LoadedTy).getFixedSize(); 133 StoredVal = Helper.CreateLShr( 134 StoredVal, ConstantInt::get(StoredVal->getType(), ShiftAmt)); 135 } 136 137 // Truncate the integer to the right size now. 138 Type *NewIntTy = IntegerType::get(StoredValTy->getContext(), LoadedValSize); 139 StoredVal = Helper.CreateTruncOrBitCast(StoredVal, NewIntTy); 140 141 if (LoadedTy != NewIntTy) { 142 // If the result is a pointer, inttoptr. 143 if (LoadedTy->isPtrOrPtrVectorTy()) 144 StoredVal = Helper.CreateIntToPtr(StoredVal, LoadedTy); 145 else 146 // Otherwise, bitcast. 147 StoredVal = Helper.CreateBitCast(StoredVal, LoadedTy); 148 } 149 150 if (auto *C = dyn_cast<Constant>(StoredVal)) 151 StoredVal = ConstantFoldConstant(C, DL); 152 153 return StoredVal; 154 } 155 156 /// If we saw a store of a value to memory, and 157 /// then a load from a must-aliased pointer of a different type, try to coerce 158 /// the stored value. LoadedTy is the type of the load we want to replace. 159 /// IRB is IRBuilder used to insert new instructions. 160 /// 161 /// If we can't do it, return null. 162 Value *coerceAvailableValueToLoadType(Value *StoredVal, Type *LoadedTy, 163 IRBuilderBase &IRB, 164 const DataLayout &DL) { 165 return coerceAvailableValueToLoadTypeHelper(StoredVal, LoadedTy, IRB, DL); 166 } 167 168 /// This function is called when we have a memdep query of a load that ends up 169 /// being a clobbering memory write (store, memset, memcpy, memmove). This 170 /// means that the write *may* provide bits used by the load but we can't be 171 /// sure because the pointers don't must-alias. 172 /// 173 /// Check this case to see if there is anything more we can do before we give 174 /// up. This returns -1 if we have to give up, or a byte number in the stored 175 /// value of the piece that feeds the load. 176 static int analyzeLoadFromClobberingWrite(Type *LoadTy, Value *LoadPtr, 177 Value *WritePtr, 178 uint64_t WriteSizeInBits, 179 const DataLayout &DL) { 180 // If the loaded/stored value is a first class array/struct, or scalable type, 181 // don't try to transform them. We need to be able to bitcast to integer. 182 if (isFirstClassAggregateOrScalableType(LoadTy)) 183 return -1; 184 185 int64_t StoreOffset = 0, LoadOffset = 0; 186 Value *StoreBase = 187 GetPointerBaseWithConstantOffset(WritePtr, StoreOffset, DL); 188 Value *LoadBase = GetPointerBaseWithConstantOffset(LoadPtr, LoadOffset, DL); 189 if (StoreBase != LoadBase) 190 return -1; 191 192 uint64_t LoadSize = DL.getTypeSizeInBits(LoadTy).getFixedSize(); 193 194 if ((WriteSizeInBits & 7) | (LoadSize & 7)) 195 return -1; 196 uint64_t StoreSize = WriteSizeInBits / 8; // Convert to bytes. 197 LoadSize /= 8; 198 199 // If the Load isn't completely contained within the stored bits, we don't 200 // have all the bits to feed it. We could do something crazy in the future 201 // (issue a smaller load then merge the bits in) but this seems unlikely to be 202 // valuable. 203 if (StoreOffset > LoadOffset || 204 StoreOffset + int64_t(StoreSize) < LoadOffset + int64_t(LoadSize)) 205 return -1; 206 207 // Okay, we can do this transformation. Return the number of bytes into the 208 // store that the load is. 209 return LoadOffset - StoreOffset; 210 } 211 212 /// This function is called when we have a 213 /// memdep query of a load that ends up being a clobbering store. 214 int analyzeLoadFromClobberingStore(Type *LoadTy, Value *LoadPtr, 215 StoreInst *DepSI, const DataLayout &DL) { 216 auto *StoredVal = DepSI->getValueOperand(); 217 218 // Cannot handle reading from store of first-class aggregate or scalable type. 219 if (isFirstClassAggregateOrScalableType(StoredVal->getType())) 220 return -1; 221 222 if (!canCoerceMustAliasedValueToLoad(StoredVal, LoadTy, DL)) 223 return -1; 224 225 Value *StorePtr = DepSI->getPointerOperand(); 226 uint64_t StoreSize = 227 DL.getTypeSizeInBits(DepSI->getValueOperand()->getType()).getFixedSize(); 228 return analyzeLoadFromClobberingWrite(LoadTy, LoadPtr, StorePtr, StoreSize, 229 DL); 230 } 231 232 /// Looks at a memory location for a load (specified by MemLocBase, Offs, and 233 /// Size) and compares it against a load. 234 /// 235 /// If the specified load could be safely widened to a larger integer load 236 /// that is 1) still efficient, 2) safe for the target, and 3) would provide 237 /// the specified memory location value, then this function returns the size 238 /// in bytes of the load width to use. If not, this returns zero. 239 static unsigned getLoadLoadClobberFullWidthSize(const Value *MemLocBase, 240 int64_t MemLocOffs, 241 unsigned MemLocSize, 242 const LoadInst *LI) { 243 // We can only extend simple integer loads. 244 if (!isa<IntegerType>(LI->getType()) || !LI->isSimple()) 245 return 0; 246 247 // Load widening is hostile to ThreadSanitizer: it may cause false positives 248 // or make the reports more cryptic (access sizes are wrong). 249 if (LI->getParent()->getParent()->hasFnAttribute(Attribute::SanitizeThread)) 250 return 0; 251 252 const DataLayout &DL = LI->getModule()->getDataLayout(); 253 254 // Get the base of this load. 255 int64_t LIOffs = 0; 256 const Value *LIBase = 257 GetPointerBaseWithConstantOffset(LI->getPointerOperand(), LIOffs, DL); 258 259 // If the two pointers are not based on the same pointer, we can't tell that 260 // they are related. 261 if (LIBase != MemLocBase) 262 return 0; 263 264 // Okay, the two values are based on the same pointer, but returned as 265 // no-alias. This happens when we have things like two byte loads at "P+1" 266 // and "P+3". Check to see if increasing the size of the "LI" load up to its 267 // alignment (or the largest native integer type) will allow us to load all 268 // the bits required by MemLoc. 269 270 // If MemLoc is before LI, then no widening of LI will help us out. 271 if (MemLocOffs < LIOffs) 272 return 0; 273 274 // Get the alignment of the load in bytes. We assume that it is safe to load 275 // any legal integer up to this size without a problem. For example, if we're 276 // looking at an i8 load on x86-32 that is known 1024 byte aligned, we can 277 // widen it up to an i32 load. If it is known 2-byte aligned, we can widen it 278 // to i16. 279 unsigned LoadAlign = LI->getAlignment(); 280 281 int64_t MemLocEnd = MemLocOffs + MemLocSize; 282 283 // If no amount of rounding up will let MemLoc fit into LI, then bail out. 284 if (LIOffs + LoadAlign < MemLocEnd) 285 return 0; 286 287 // This is the size of the load to try. Start with the next larger power of 288 // two. 289 unsigned NewLoadByteSize = LI->getType()->getPrimitiveSizeInBits() / 8U; 290 NewLoadByteSize = NextPowerOf2(NewLoadByteSize); 291 292 while (true) { 293 // If this load size is bigger than our known alignment or would not fit 294 // into a native integer register, then we fail. 295 if (NewLoadByteSize > LoadAlign || 296 !DL.fitsInLegalInteger(NewLoadByteSize * 8)) 297 return 0; 298 299 if (LIOffs + NewLoadByteSize > MemLocEnd && 300 (LI->getParent()->getParent()->hasFnAttribute( 301 Attribute::SanitizeAddress) || 302 LI->getParent()->getParent()->hasFnAttribute( 303 Attribute::SanitizeHWAddress))) 304 // We will be reading past the location accessed by the original program. 305 // While this is safe in a regular build, Address Safety analysis tools 306 // may start reporting false warnings. So, don't do widening. 307 return 0; 308 309 // If a load of this width would include all of MemLoc, then we succeed. 310 if (LIOffs + NewLoadByteSize >= MemLocEnd) 311 return NewLoadByteSize; 312 313 NewLoadByteSize <<= 1; 314 } 315 } 316 317 /// This function is called when we have a 318 /// memdep query of a load that ends up being clobbered by another load. See if 319 /// the other load can feed into the second load. 320 int analyzeLoadFromClobberingLoad(Type *LoadTy, Value *LoadPtr, LoadInst *DepLI, 321 const DataLayout &DL) { 322 // Cannot handle reading from store of first-class aggregate yet. 323 if (DepLI->getType()->isStructTy() || DepLI->getType()->isArrayTy()) 324 return -1; 325 326 if (!canCoerceMustAliasedValueToLoad(DepLI, LoadTy, DL)) 327 return -1; 328 329 Value *DepPtr = DepLI->getPointerOperand(); 330 uint64_t DepSize = DL.getTypeSizeInBits(DepLI->getType()).getFixedSize(); 331 int R = analyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, DepSize, DL); 332 if (R != -1) 333 return R; 334 335 // If we have a load/load clobber an DepLI can be widened to cover this load, 336 // then we should widen it! 337 int64_t LoadOffs = 0; 338 const Value *LoadBase = 339 GetPointerBaseWithConstantOffset(LoadPtr, LoadOffs, DL); 340 unsigned LoadSize = DL.getTypeStoreSize(LoadTy).getFixedSize(); 341 342 unsigned Size = 343 getLoadLoadClobberFullWidthSize(LoadBase, LoadOffs, LoadSize, DepLI); 344 if (Size == 0) 345 return -1; 346 347 // Check non-obvious conditions enforced by MDA which we rely on for being 348 // able to materialize this potentially available value 349 assert(DepLI->isSimple() && "Cannot widen volatile/atomic load!"); 350 assert(DepLI->getType()->isIntegerTy() && "Can't widen non-integer load"); 351 352 return analyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, Size * 8, DL); 353 } 354 355 int analyzeLoadFromClobberingMemInst(Type *LoadTy, Value *LoadPtr, 356 MemIntrinsic *MI, const DataLayout &DL) { 357 // If the mem operation is a non-constant size, we can't handle it. 358 ConstantInt *SizeCst = dyn_cast<ConstantInt>(MI->getLength()); 359 if (!SizeCst) 360 return -1; 361 uint64_t MemSizeInBits = SizeCst->getZExtValue() * 8; 362 363 // If this is memset, we just need to see if the offset is valid in the size 364 // of the memset.. 365 if (MI->getIntrinsicID() == Intrinsic::memset) { 366 if (DL.isNonIntegralPointerType(LoadTy->getScalarType())) { 367 auto *CI = dyn_cast<ConstantInt>(cast<MemSetInst>(MI)->getValue()); 368 if (!CI || !CI->isZero()) 369 return -1; 370 } 371 return analyzeLoadFromClobberingWrite(LoadTy, LoadPtr, MI->getDest(), 372 MemSizeInBits, DL); 373 } 374 375 // If we have a memcpy/memmove, the only case we can handle is if this is a 376 // copy from constant memory. In that case, we can read directly from the 377 // constant memory. 378 MemTransferInst *MTI = cast<MemTransferInst>(MI); 379 380 Constant *Src = dyn_cast<Constant>(MTI->getSource()); 381 if (!Src) 382 return -1; 383 384 GlobalVariable *GV = dyn_cast<GlobalVariable>(getUnderlyingObject(Src)); 385 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer()) 386 return -1; 387 388 // See if the access is within the bounds of the transfer. 389 int Offset = analyzeLoadFromClobberingWrite(LoadTy, LoadPtr, MI->getDest(), 390 MemSizeInBits, DL); 391 if (Offset == -1) 392 return Offset; 393 394 // Otherwise, see if we can constant fold a load from the constant with the 395 // offset applied as appropriate. 396 unsigned IndexSize = DL.getIndexTypeSizeInBits(Src->getType()); 397 if (ConstantFoldLoadFromConstPtr(Src, LoadTy, APInt(IndexSize, Offset), DL)) 398 return Offset; 399 return -1; 400 } 401 402 template <class T, class HelperClass> 403 static T *getStoreValueForLoadHelper(T *SrcVal, unsigned Offset, Type *LoadTy, 404 HelperClass &Helper, 405 const DataLayout &DL) { 406 LLVMContext &Ctx = SrcVal->getType()->getContext(); 407 408 // If two pointers are in the same address space, they have the same size, 409 // so we don't need to do any truncation, etc. This avoids introducing 410 // ptrtoint instructions for pointers that may be non-integral. 411 if (SrcVal->getType()->isPointerTy() && LoadTy->isPointerTy() && 412 cast<PointerType>(SrcVal->getType())->getAddressSpace() == 413 cast<PointerType>(LoadTy)->getAddressSpace()) { 414 return SrcVal; 415 } 416 417 uint64_t StoreSize = 418 (DL.getTypeSizeInBits(SrcVal->getType()).getFixedSize() + 7) / 8; 419 uint64_t LoadSize = (DL.getTypeSizeInBits(LoadTy).getFixedSize() + 7) / 8; 420 // Compute which bits of the stored value are being used by the load. Convert 421 // to an integer type to start with. 422 if (SrcVal->getType()->isPtrOrPtrVectorTy()) 423 SrcVal = Helper.CreatePtrToInt(SrcVal, DL.getIntPtrType(SrcVal->getType())); 424 if (!SrcVal->getType()->isIntegerTy()) 425 SrcVal = Helper.CreateBitCast(SrcVal, IntegerType::get(Ctx, StoreSize * 8)); 426 427 // Shift the bits to the least significant depending on endianness. 428 unsigned ShiftAmt; 429 if (DL.isLittleEndian()) 430 ShiftAmt = Offset * 8; 431 else 432 ShiftAmt = (StoreSize - LoadSize - Offset) * 8; 433 if (ShiftAmt) 434 SrcVal = Helper.CreateLShr(SrcVal, 435 ConstantInt::get(SrcVal->getType(), ShiftAmt)); 436 437 if (LoadSize != StoreSize) 438 SrcVal = Helper.CreateTruncOrBitCast(SrcVal, 439 IntegerType::get(Ctx, LoadSize * 8)); 440 return SrcVal; 441 } 442 443 /// This function is called when we have a memdep query of a load that ends up 444 /// being a clobbering store. This means that the store provides bits used by 445 /// the load but the pointers don't must-alias. Check this case to see if 446 /// there is anything more we can do before we give up. 447 Value *getStoreValueForLoad(Value *SrcVal, unsigned Offset, Type *LoadTy, 448 Instruction *InsertPt, const DataLayout &DL) { 449 450 IRBuilder<> Builder(InsertPt); 451 SrcVal = getStoreValueForLoadHelper(SrcVal, Offset, LoadTy, Builder, DL); 452 return coerceAvailableValueToLoadTypeHelper(SrcVal, LoadTy, Builder, DL); 453 } 454 455 Constant *getConstantStoreValueForLoad(Constant *SrcVal, unsigned Offset, 456 Type *LoadTy, const DataLayout &DL) { 457 ConstantFolder F; 458 SrcVal = getStoreValueForLoadHelper(SrcVal, Offset, LoadTy, F, DL); 459 return coerceAvailableValueToLoadTypeHelper(SrcVal, LoadTy, F, DL); 460 } 461 462 /// This function is called when we have a memdep query of a load that ends up 463 /// being a clobbering load. This means that the load *may* provide bits used 464 /// by the load but we can't be sure because the pointers don't must-alias. 465 /// Check this case to see if there is anything more we can do before we give 466 /// up. 467 Value *getLoadValueForLoad(LoadInst *SrcVal, unsigned Offset, Type *LoadTy, 468 Instruction *InsertPt, const DataLayout &DL) { 469 // If Offset+LoadTy exceeds the size of SrcVal, then we must be wanting to 470 // widen SrcVal out to a larger load. 471 unsigned SrcValStoreSize = 472 DL.getTypeStoreSize(SrcVal->getType()).getFixedSize(); 473 unsigned LoadSize = DL.getTypeStoreSize(LoadTy).getFixedSize(); 474 if (Offset + LoadSize > SrcValStoreSize) { 475 assert(SrcVal->isSimple() && "Cannot widen volatile/atomic load!"); 476 assert(SrcVal->getType()->isIntegerTy() && "Can't widen non-integer load"); 477 // If we have a load/load clobber an DepLI can be widened to cover this 478 // load, then we should widen it to the next power of 2 size big enough! 479 unsigned NewLoadSize = Offset + LoadSize; 480 if (!isPowerOf2_32(NewLoadSize)) 481 NewLoadSize = NextPowerOf2(NewLoadSize); 482 483 Value *PtrVal = SrcVal->getPointerOperand(); 484 // Insert the new load after the old load. This ensures that subsequent 485 // memdep queries will find the new load. We can't easily remove the old 486 // load completely because it is already in the value numbering table. 487 IRBuilder<> Builder(SrcVal->getParent(), ++BasicBlock::iterator(SrcVal)); 488 Type *DestTy = IntegerType::get(LoadTy->getContext(), NewLoadSize * 8); 489 Type *DestPTy = 490 PointerType::get(DestTy, PtrVal->getType()->getPointerAddressSpace()); 491 Builder.SetCurrentDebugLocation(SrcVal->getDebugLoc()); 492 PtrVal = Builder.CreateBitCast(PtrVal, DestPTy); 493 LoadInst *NewLoad = Builder.CreateLoad(DestTy, PtrVal); 494 NewLoad->takeName(SrcVal); 495 NewLoad->setAlignment(SrcVal->getAlign()); 496 497 LLVM_DEBUG(dbgs() << "GVN WIDENED LOAD: " << *SrcVal << "\n"); 498 LLVM_DEBUG(dbgs() << "TO: " << *NewLoad << "\n"); 499 500 // Replace uses of the original load with the wider load. On a big endian 501 // system, we need to shift down to get the relevant bits. 502 Value *RV = NewLoad; 503 if (DL.isBigEndian()) 504 RV = Builder.CreateLShr(RV, (NewLoadSize - SrcValStoreSize) * 8); 505 RV = Builder.CreateTrunc(RV, SrcVal->getType()); 506 SrcVal->replaceAllUsesWith(RV); 507 508 SrcVal = NewLoad; 509 } 510 511 return getStoreValueForLoad(SrcVal, Offset, LoadTy, InsertPt, DL); 512 } 513 514 Constant *getConstantLoadValueForLoad(Constant *SrcVal, unsigned Offset, 515 Type *LoadTy, const DataLayout &DL) { 516 unsigned SrcValStoreSize = 517 DL.getTypeStoreSize(SrcVal->getType()).getFixedSize(); 518 unsigned LoadSize = DL.getTypeStoreSize(LoadTy).getFixedSize(); 519 if (Offset + LoadSize > SrcValStoreSize) 520 return nullptr; 521 return getConstantStoreValueForLoad(SrcVal, Offset, LoadTy, DL); 522 } 523 524 template <class T, class HelperClass> 525 T *getMemInstValueForLoadHelper(MemIntrinsic *SrcInst, unsigned Offset, 526 Type *LoadTy, HelperClass &Helper, 527 const DataLayout &DL) { 528 LLVMContext &Ctx = LoadTy->getContext(); 529 uint64_t LoadSize = DL.getTypeSizeInBits(LoadTy).getFixedSize() / 8; 530 531 // We know that this method is only called when the mem transfer fully 532 // provides the bits for the load. 533 if (MemSetInst *MSI = dyn_cast<MemSetInst>(SrcInst)) { 534 // memset(P, 'x', 1234) -> splat('x'), even if x is a variable, and 535 // independently of what the offset is. 536 T *Val = cast<T>(MSI->getValue()); 537 if (LoadSize != 1) 538 Val = 539 Helper.CreateZExtOrBitCast(Val, IntegerType::get(Ctx, LoadSize * 8)); 540 T *OneElt = Val; 541 542 // Splat the value out to the right number of bits. 543 for (unsigned NumBytesSet = 1; NumBytesSet != LoadSize;) { 544 // If we can double the number of bytes set, do it. 545 if (NumBytesSet * 2 <= LoadSize) { 546 T *ShVal = Helper.CreateShl( 547 Val, ConstantInt::get(Val->getType(), NumBytesSet * 8)); 548 Val = Helper.CreateOr(Val, ShVal); 549 NumBytesSet <<= 1; 550 continue; 551 } 552 553 // Otherwise insert one byte at a time. 554 T *ShVal = Helper.CreateShl(Val, ConstantInt::get(Val->getType(), 1 * 8)); 555 Val = Helper.CreateOr(OneElt, ShVal); 556 ++NumBytesSet; 557 } 558 559 return coerceAvailableValueToLoadTypeHelper(Val, LoadTy, Helper, DL); 560 } 561 562 // Otherwise, this is a memcpy/memmove from a constant global. 563 MemTransferInst *MTI = cast<MemTransferInst>(SrcInst); 564 Constant *Src = cast<Constant>(MTI->getSource()); 565 566 // Otherwise, see if we can constant fold a load from the constant with the 567 // offset applied as appropriate. 568 unsigned IndexSize = DL.getIndexTypeSizeInBits(Src->getType()); 569 return ConstantFoldLoadFromConstPtr( 570 Src, LoadTy, APInt(IndexSize, Offset), DL); 571 } 572 573 /// This function is called when we have a 574 /// memdep query of a load that ends up being a clobbering mem intrinsic. 575 Value *getMemInstValueForLoad(MemIntrinsic *SrcInst, unsigned Offset, 576 Type *LoadTy, Instruction *InsertPt, 577 const DataLayout &DL) { 578 IRBuilder<> Builder(InsertPt); 579 return getMemInstValueForLoadHelper<Value, IRBuilder<>>(SrcInst, Offset, 580 LoadTy, Builder, DL); 581 } 582 583 Constant *getConstantMemInstValueForLoad(MemIntrinsic *SrcInst, unsigned Offset, 584 Type *LoadTy, const DataLayout &DL) { 585 // The only case analyzeLoadFromClobberingMemInst cannot be converted to a 586 // constant is when it's a memset of a non-constant. 587 if (auto *MSI = dyn_cast<MemSetInst>(SrcInst)) 588 if (!isa<Constant>(MSI->getValue())) 589 return nullptr; 590 ConstantFolder F; 591 return getMemInstValueForLoadHelper<Constant, ConstantFolder>(SrcInst, Offset, 592 LoadTy, F, DL); 593 } 594 } // namespace VNCoercion 595 } // namespace llvm 596