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