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