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