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