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