blob: 74572eb2d46b446c9c721ff9214e127eb8ddac9e [file] [log] [blame]
Daniel Berlin5ac91792017-03-10 04:54:10 +00001#include "llvm/Transforms/Utils/VNCoercion.h"
2#include "llvm/Analysis/AliasAnalysis.h"
3#include "llvm/Analysis/ConstantFolding.h"
4#include "llvm/Analysis/MemoryDependenceAnalysis.h"
5#include "llvm/Analysis/ValueTracking.h"
6#include "llvm/IR/IRBuilder.h"
7#include "llvm/IR/IntrinsicInst.h"
8#include "llvm/Support/Debug.h"
9
10#define DEBUG_TYPE "vncoerce"
11namespace llvm {
12namespace VNCoercion {
13
14/// Return true if coerceAvailableValueToLoadType will succeed.
15bool canCoerceMustAliasedValueToLoad(Value *StoredVal, Type *LoadTy,
16 const DataLayout &DL) {
17 // If the loaded or stored value is an first class array or struct, don't try
18 // to transform them. We need to be able to bitcast to integer.
19 if (LoadTy->isStructTy() || LoadTy->isArrayTy() ||
20 StoredVal->getType()->isStructTy() || StoredVal->getType()->isArrayTy())
21 return false;
22
Matthew Voss30648ab2018-06-21 21:43:20 +000023 uint64_t StoreSize = DL.getTypeSizeInBits(StoredVal->getType());
24
25 // The store size must be byte-aligned to support future type casts.
26 if (llvm::alignTo(StoreSize, 8) != StoreSize)
27 return false;
28
Daniel Berlin5ac91792017-03-10 04:54:10 +000029 // The store has to be at least as big as the load.
Matthew Voss30648ab2018-06-21 21:43:20 +000030 if (StoreSize < DL.getTypeSizeInBits(LoadTy))
Daniel Berlin5ac91792017-03-10 04:54:10 +000031 return false;
32
Sanjoy Das59454472017-04-19 18:21:09 +000033 // Don't coerce non-integral pointers to integers or vice versa.
34 if (DL.isNonIntegralPointerType(StoredVal->getType()) !=
Philip Reames92756a82019-02-19 23:07:15 +000035 DL.isNonIntegralPointerType(LoadTy)) {
36 // As a special case, allow coercion of memset used to initialize
37 // an array w/null. Despite non-integral pointers not generally having a
38 // specific bit pattern, we do assume null is zero.
39 if (auto *CI = dyn_cast<ConstantInt>(StoredVal))
40 return CI->isZero();
Sanjoy Das59454472017-04-19 18:21:09 +000041 return false;
Philip Reames92756a82019-02-19 23:07:15 +000042 }
43
Daniel Berlin5ac91792017-03-10 04:54:10 +000044 return true;
45}
46
Daniel Berlin12883b12017-03-20 16:08:29 +000047template <class T, class HelperClass>
48static T *coerceAvailableValueToLoadTypeHelper(T *StoredVal, Type *LoadedTy,
49 HelperClass &Helper,
50 const DataLayout &DL) {
Daniel Berlin5ac91792017-03-10 04:54:10 +000051 assert(canCoerceMustAliasedValueToLoad(StoredVal, LoadedTy, DL) &&
52 "precondition violation - materialization can't fail");
Daniel Berlin5ac91792017-03-10 04:54:10 +000053 if (auto *C = dyn_cast<Constant>(StoredVal))
54 if (auto *FoldedStoredVal = ConstantFoldConstant(C, DL))
55 StoredVal = FoldedStoredVal;
56
57 // If this is already the right type, just return it.
58 Type *StoredValTy = StoredVal->getType();
59
60 uint64_t StoredValSize = DL.getTypeSizeInBits(StoredValTy);
61 uint64_t LoadedValSize = DL.getTypeSizeInBits(LoadedTy);
62
63 // If the store and reload are the same size, we can always reuse it.
64 if (StoredValSize == LoadedValSize) {
65 // Pointer to Pointer -> use bitcast.
Craig Topper95d23472017-07-09 07:04:00 +000066 if (StoredValTy->isPtrOrPtrVectorTy() && LoadedTy->isPtrOrPtrVectorTy()) {
Daniel Berlin12883b12017-03-20 16:08:29 +000067 StoredVal = Helper.CreateBitCast(StoredVal, LoadedTy);
Daniel Berlin5ac91792017-03-10 04:54:10 +000068 } else {
69 // Convert source pointers to integers, which can be bitcast.
Craig Topper95d23472017-07-09 07:04:00 +000070 if (StoredValTy->isPtrOrPtrVectorTy()) {
Daniel Berlin5ac91792017-03-10 04:54:10 +000071 StoredValTy = DL.getIntPtrType(StoredValTy);
Daniel Berlin12883b12017-03-20 16:08:29 +000072 StoredVal = Helper.CreatePtrToInt(StoredVal, StoredValTy);
Daniel Berlin5ac91792017-03-10 04:54:10 +000073 }
74
75 Type *TypeToCastTo = LoadedTy;
Craig Topper95d23472017-07-09 07:04:00 +000076 if (TypeToCastTo->isPtrOrPtrVectorTy())
Daniel Berlin5ac91792017-03-10 04:54:10 +000077 TypeToCastTo = DL.getIntPtrType(TypeToCastTo);
78
79 if (StoredValTy != TypeToCastTo)
Daniel Berlin12883b12017-03-20 16:08:29 +000080 StoredVal = Helper.CreateBitCast(StoredVal, TypeToCastTo);
Daniel Berlin5ac91792017-03-10 04:54:10 +000081
82 // Cast to pointer if the load needs a pointer type.
Craig Topper95d23472017-07-09 07:04:00 +000083 if (LoadedTy->isPtrOrPtrVectorTy())
Daniel Berlin12883b12017-03-20 16:08:29 +000084 StoredVal = Helper.CreateIntToPtr(StoredVal, LoadedTy);
Daniel Berlin5ac91792017-03-10 04:54:10 +000085 }
86
87 if (auto *C = dyn_cast<ConstantExpr>(StoredVal))
88 if (auto *FoldedStoredVal = ConstantFoldConstant(C, DL))
89 StoredVal = FoldedStoredVal;
90
91 return StoredVal;
92 }
Daniel Berlin5ac91792017-03-10 04:54:10 +000093 // If the loaded value is smaller than the available value, then we can
94 // extract out a piece from it. If the available value is too small, then we
95 // can't do anything.
96 assert(StoredValSize >= LoadedValSize &&
97 "canCoerceMustAliasedValueToLoad fail");
98
99 // Convert source pointers to integers, which can be manipulated.
Craig Topper95d23472017-07-09 07:04:00 +0000100 if (StoredValTy->isPtrOrPtrVectorTy()) {
Daniel Berlin5ac91792017-03-10 04:54:10 +0000101 StoredValTy = DL.getIntPtrType(StoredValTy);
Daniel Berlin12883b12017-03-20 16:08:29 +0000102 StoredVal = Helper.CreatePtrToInt(StoredVal, StoredValTy);
Daniel Berlin5ac91792017-03-10 04:54:10 +0000103 }
104
105 // Convert vectors and fp to integer, which can be manipulated.
106 if (!StoredValTy->isIntegerTy()) {
107 StoredValTy = IntegerType::get(StoredValTy->getContext(), StoredValSize);
Daniel Berlin12883b12017-03-20 16:08:29 +0000108 StoredVal = Helper.CreateBitCast(StoredVal, StoredValTy);
Daniel Berlin5ac91792017-03-10 04:54:10 +0000109 }
110
111 // If this is a big-endian system, we need to shift the value down to the low
112 // bits so that a truncate will work.
113 if (DL.isBigEndian()) {
114 uint64_t ShiftAmt = DL.getTypeStoreSizeInBits(StoredValTy) -
115 DL.getTypeStoreSizeInBits(LoadedTy);
Daniel Berlin12883b12017-03-20 16:08:29 +0000116 StoredVal = Helper.CreateLShr(
117 StoredVal, ConstantInt::get(StoredVal->getType(), ShiftAmt));
Daniel Berlin5ac91792017-03-10 04:54:10 +0000118 }
119
120 // Truncate the integer to the right size now.
121 Type *NewIntTy = IntegerType::get(StoredValTy->getContext(), LoadedValSize);
Daniel Berlin12883b12017-03-20 16:08:29 +0000122 StoredVal = Helper.CreateTruncOrBitCast(StoredVal, NewIntTy);
Daniel Berlin5ac91792017-03-10 04:54:10 +0000123
124 if (LoadedTy != NewIntTy) {
125 // If the result is a pointer, inttoptr.
Craig Topper95d23472017-07-09 07:04:00 +0000126 if (LoadedTy->isPtrOrPtrVectorTy())
Daniel Berlin12883b12017-03-20 16:08:29 +0000127 StoredVal = Helper.CreateIntToPtr(StoredVal, LoadedTy);
Daniel Berlin5ac91792017-03-10 04:54:10 +0000128 else
129 // Otherwise, bitcast.
Daniel Berlin12883b12017-03-20 16:08:29 +0000130 StoredVal = Helper.CreateBitCast(StoredVal, LoadedTy);
Daniel Berlin5ac91792017-03-10 04:54:10 +0000131 }
132
133 if (auto *C = dyn_cast<Constant>(StoredVal))
134 if (auto *FoldedStoredVal = ConstantFoldConstant(C, DL))
135 StoredVal = FoldedStoredVal;
136
137 return StoredVal;
138}
139
Daniel Berlin12883b12017-03-20 16:08:29 +0000140/// 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.
146Value *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.
Daniel Berlin5ac91792017-03-10 04:54:10 +0000155///
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.
159static 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.
214int analyzeLoadFromClobberingStore(Type *LoadTy, Value *LoadPtr,
Daniel Berlincd07a0f2017-03-11 00:51:01 +0000215 StoreInst *DepSI, const DataLayout &DL) {
Daniel Berlin5ac91792017-03-10 04:54:10 +0000216 // Cannot handle reading from store of first-class aggregate yet.
217 if (DepSI->getValueOperand()->getType()->isStructTy() ||
218 DepSI->getValueOperand()->getType()->isArrayTy())
219 return -1;
220
Daniel Berlin5ac91792017-03-10 04:54:10 +0000221 Value *StorePtr = DepSI->getPointerOperand();
222 uint64_t StoreSize =
223 DL.getTypeSizeInBits(DepSI->getValueOperand()->getType());
224 return analyzeLoadFromClobberingWrite(LoadTy, LoadPtr, StorePtr, StoreSize,
225 DL);
226}
227
228/// This function is called when we have a
229/// memdep query of a load that ends up being clobbered by another load. See if
230/// the other load can feed into the second load.
231int analyzeLoadFromClobberingLoad(Type *LoadTy, Value *LoadPtr, LoadInst *DepLI,
232 const DataLayout &DL) {
233 // Cannot handle reading from store of first-class aggregate yet.
234 if (DepLI->getType()->isStructTy() || DepLI->getType()->isArrayTy())
235 return -1;
236
237 Value *DepPtr = DepLI->getPointerOperand();
238 uint64_t DepSize = DL.getTypeSizeInBits(DepLI->getType());
239 int R = analyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, DepSize, DL);
240 if (R != -1)
241 return R;
242
243 // If we have a load/load clobber an DepLI can be widened to cover this load,
244 // then we should widen it!
245 int64_t LoadOffs = 0;
246 const Value *LoadBase =
247 GetPointerBaseWithConstantOffset(LoadPtr, LoadOffs, DL);
248 unsigned LoadSize = DL.getTypeStoreSize(LoadTy);
249
250 unsigned Size = MemoryDependenceResults::getLoadLoadClobberFullWidthSize(
251 LoadBase, LoadOffs, LoadSize, DepLI);
252 if (Size == 0)
253 return -1;
254
255 // Check non-obvious conditions enforced by MDA which we rely on for being
256 // able to materialize this potentially available value
257 assert(DepLI->isSimple() && "Cannot widen volatile/atomic load!");
258 assert(DepLI->getType()->isIntegerTy() && "Can't widen non-integer load");
259
260 return analyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, Size * 8, DL);
261}
262
263int analyzeLoadFromClobberingMemInst(Type *LoadTy, Value *LoadPtr,
264 MemIntrinsic *MI, const DataLayout &DL) {
265 // If the mem operation is a non-constant size, we can't handle it.
266 ConstantInt *SizeCst = dyn_cast<ConstantInt>(MI->getLength());
267 if (!SizeCst)
268 return -1;
269 uint64_t MemSizeInBits = SizeCst->getZExtValue() * 8;
270
271 // If this is memset, we just need to see if the offset is valid in the size
272 // of the memset..
Philip Reames92756a82019-02-19 23:07:15 +0000273 if (MI->getIntrinsicID() == Intrinsic::memset) {
274 Value *StoredVal = cast<MemSetInst>(MI)->getValue();
275 if (DL.isNonIntegralPointerType(LoadTy->getScalarType())) {
276 auto *CI = dyn_cast<ConstantInt>(StoredVal);
277 if (!CI || !CI->isZero())
278 return -1;
279 }
Daniel Berlin5ac91792017-03-10 04:54:10 +0000280 return analyzeLoadFromClobberingWrite(LoadTy, LoadPtr, MI->getDest(),
281 MemSizeInBits, DL);
Philip Reames92756a82019-02-19 23:07:15 +0000282 }
Daniel Berlin5ac91792017-03-10 04:54:10 +0000283
284 // If we have a memcpy/memmove, the only case we can handle is if this is a
285 // copy from constant memory. In that case, we can read directly from the
286 // constant memory.
287 MemTransferInst *MTI = cast<MemTransferInst>(MI);
288
289 Constant *Src = dyn_cast<Constant>(MTI->getSource());
290 if (!Src)
291 return -1;
292
293 GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Src, DL));
294 if (!GV || !GV->isConstant())
295 return -1;
296
297 // See if the access is within the bounds of the transfer.
298 int Offset = analyzeLoadFromClobberingWrite(LoadTy, LoadPtr, MI->getDest(),
299 MemSizeInBits, DL);
300 if (Offset == -1)
301 return Offset;
302
303 unsigned AS = Src->getType()->getPointerAddressSpace();
304 // Otherwise, see if we can constant fold a load from the constant with the
305 // offset applied as appropriate.
306 Src =
307 ConstantExpr::getBitCast(Src, Type::getInt8PtrTy(Src->getContext(), AS));
308 Constant *OffsetCst =
309 ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
310 Src = ConstantExpr::getGetElementPtr(Type::getInt8Ty(Src->getContext()), Src,
311 OffsetCst);
312 Src = ConstantExpr::getBitCast(Src, PointerType::get(LoadTy, AS));
313 if (ConstantFoldLoadFromConstPtr(Src, LoadTy, DL))
314 return Offset;
315 return -1;
316}
317
Daniel Berlin12883b12017-03-20 16:08:29 +0000318template <class T, class HelperClass>
319static T *getStoreValueForLoadHelper(T *SrcVal, unsigned Offset, Type *LoadTy,
320 HelperClass &Helper,
321 const DataLayout &DL) {
Daniel Berlin5ac91792017-03-10 04:54:10 +0000322 LLVMContext &Ctx = SrcVal->getType()->getContext();
323
Keno Fischer06f962c2017-05-09 21:07:20 +0000324 // If two pointers are in the same address space, they have the same size,
325 // so we don't need to do any truncation, etc. This avoids introducing
326 // ptrtoint instructions for pointers that may be non-integral.
327 if (SrcVal->getType()->isPointerTy() && LoadTy->isPointerTy() &&
328 cast<PointerType>(SrcVal->getType())->getAddressSpace() ==
329 cast<PointerType>(LoadTy)->getAddressSpace()) {
330 return SrcVal;
331 }
332
Daniel Berlin5ac91792017-03-10 04:54:10 +0000333 uint64_t StoreSize = (DL.getTypeSizeInBits(SrcVal->getType()) + 7) / 8;
334 uint64_t LoadSize = (DL.getTypeSizeInBits(LoadTy) + 7) / 8;
Daniel Berlin5ac91792017-03-10 04:54:10 +0000335 // Compute which bits of the stored value are being used by the load. Convert
336 // to an integer type to start with.
Craig Topper95d23472017-07-09 07:04:00 +0000337 if (SrcVal->getType()->isPtrOrPtrVectorTy())
Daniel Berlin12883b12017-03-20 16:08:29 +0000338 SrcVal = Helper.CreatePtrToInt(SrcVal, DL.getIntPtrType(SrcVal->getType()));
Daniel Berlin5ac91792017-03-10 04:54:10 +0000339 if (!SrcVal->getType()->isIntegerTy())
Daniel Berlin12883b12017-03-20 16:08:29 +0000340 SrcVal = Helper.CreateBitCast(SrcVal, IntegerType::get(Ctx, StoreSize * 8));
Daniel Berlin5ac91792017-03-10 04:54:10 +0000341
342 // Shift the bits to the least significant depending on endianness.
343 unsigned ShiftAmt;
344 if (DL.isLittleEndian())
345 ShiftAmt = Offset * 8;
346 else
347 ShiftAmt = (StoreSize - LoadSize - Offset) * 8;
Daniel Berlin5ac91792017-03-10 04:54:10 +0000348 if (ShiftAmt)
Daniel Berlin12883b12017-03-20 16:08:29 +0000349 SrcVal = Helper.CreateLShr(SrcVal,
350 ConstantInt::get(SrcVal->getType(), ShiftAmt));
Daniel Berlin5ac91792017-03-10 04:54:10 +0000351
352 if (LoadSize != StoreSize)
Daniel Berlin12883b12017-03-20 16:08:29 +0000353 SrcVal = Helper.CreateTruncOrBitCast(SrcVal,
354 IntegerType::get(Ctx, LoadSize * 8));
355 return SrcVal;
Daniel Berlin5ac91792017-03-10 04:54:10 +0000356}
357
Daniel Berlin12883b12017-03-20 16:08:29 +0000358/// This function is called when we have a memdep query of a load that ends up
359/// being a clobbering store. This means that the store provides bits used by
360/// the load but the pointers don't must-alias. Check this case to see if
361/// there is anything more we can do before we give up.
362Value *getStoreValueForLoad(Value *SrcVal, unsigned Offset, Type *LoadTy,
363 Instruction *InsertPt, const DataLayout &DL) {
Daniel Berlin5ac91792017-03-10 04:54:10 +0000364
Daniel Berlin12883b12017-03-20 16:08:29 +0000365 IRBuilder<> Builder(InsertPt);
366 SrcVal = getStoreValueForLoadHelper(SrcVal, Offset, LoadTy, Builder, DL);
367 return coerceAvailableValueToLoadTypeHelper(SrcVal, LoadTy, Builder, DL);
368}
369
370Constant *getConstantStoreValueForLoad(Constant *SrcVal, unsigned Offset,
371 Type *LoadTy, const DataLayout &DL) {
372 ConstantFolder F;
373 SrcVal = getStoreValueForLoadHelper(SrcVal, Offset, LoadTy, F, DL);
374 return coerceAvailableValueToLoadTypeHelper(SrcVal, LoadTy, F, DL);
375}
376
377/// This function is called when we have a memdep query of a load that ends up
378/// being a clobbering load. This means that the load *may* provide bits used
379/// by the load but we can't be sure because the pointers don't must-alias.
380/// Check this case to see if there is anything more we can do before we give
381/// up.
382Value *getLoadValueForLoad(LoadInst *SrcVal, unsigned Offset, Type *LoadTy,
383 Instruction *InsertPt, const DataLayout &DL) {
Daniel Berlin5ac91792017-03-10 04:54:10 +0000384 // If Offset+LoadTy exceeds the size of SrcVal, then we must be wanting to
385 // widen SrcVal out to a larger load.
386 unsigned SrcValStoreSize = DL.getTypeStoreSize(SrcVal->getType());
387 unsigned LoadSize = DL.getTypeStoreSize(LoadTy);
388 if (Offset + LoadSize > SrcValStoreSize) {
389 assert(SrcVal->isSimple() && "Cannot widen volatile/atomic load!");
390 assert(SrcVal->getType()->isIntegerTy() && "Can't widen non-integer load");
391 // If we have a load/load clobber an DepLI can be widened to cover this
392 // load, then we should widen it to the next power of 2 size big enough!
393 unsigned NewLoadSize = Offset + LoadSize;
394 if (!isPowerOf2_32(NewLoadSize))
395 NewLoadSize = NextPowerOf2(NewLoadSize);
396
397 Value *PtrVal = SrcVal->getPointerOperand();
Daniel Berlin5ac91792017-03-10 04:54:10 +0000398 // Insert the new load after the old load. This ensures that subsequent
399 // memdep queries will find the new load. We can't easily remove the old
400 // load completely because it is already in the value numbering table.
401 IRBuilder<> Builder(SrcVal->getParent(), ++BasicBlock::iterator(SrcVal));
James Y Knight14359ef2019-02-01 20:44:24 +0000402 Type *DestTy = IntegerType::get(LoadTy->getContext(), NewLoadSize * 8);
403 Type *DestPTy =
404 PointerType::get(DestTy, PtrVal->getType()->getPointerAddressSpace());
Daniel Berlin5ac91792017-03-10 04:54:10 +0000405 Builder.SetCurrentDebugLocation(SrcVal->getDebugLoc());
406 PtrVal = Builder.CreateBitCast(PtrVal, DestPTy);
James Y Knight14359ef2019-02-01 20:44:24 +0000407 LoadInst *NewLoad = Builder.CreateLoad(DestTy, PtrVal);
Daniel Berlin5ac91792017-03-10 04:54:10 +0000408 NewLoad->takeName(SrcVal);
409 NewLoad->setAlignment(SrcVal->getAlignment());
410
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000411 LLVM_DEBUG(dbgs() << "GVN WIDENED LOAD: " << *SrcVal << "\n");
412 LLVM_DEBUG(dbgs() << "TO: " << *NewLoad << "\n");
Daniel Berlin5ac91792017-03-10 04:54:10 +0000413
414 // Replace uses of the original load with the wider load. On a big endian
415 // system, we need to shift down to get the relevant bits.
416 Value *RV = NewLoad;
417 if (DL.isBigEndian())
418 RV = Builder.CreateLShr(RV, (NewLoadSize - SrcValStoreSize) * 8);
419 RV = Builder.CreateTrunc(RV, SrcVal->getType());
420 SrcVal->replaceAllUsesWith(RV);
421
422 SrcVal = NewLoad;
423 }
424
425 return getStoreValueForLoad(SrcVal, Offset, LoadTy, InsertPt, DL);
426}
427
Daniel Berlin12883b12017-03-20 16:08:29 +0000428Constant *getConstantLoadValueForLoad(Constant *SrcVal, unsigned Offset,
429 Type *LoadTy, const DataLayout &DL) {
430 unsigned SrcValStoreSize = DL.getTypeStoreSize(SrcVal->getType());
431 unsigned LoadSize = DL.getTypeStoreSize(LoadTy);
432 if (Offset + LoadSize > SrcValStoreSize)
433 return nullptr;
434 return getConstantStoreValueForLoad(SrcVal, Offset, LoadTy, DL);
435}
436
437template <class T, class HelperClass>
438T *getMemInstValueForLoadHelper(MemIntrinsic *SrcInst, unsigned Offset,
439 Type *LoadTy, HelperClass &Helper,
440 const DataLayout &DL) {
Daniel Berlin5ac91792017-03-10 04:54:10 +0000441 LLVMContext &Ctx = LoadTy->getContext();
442 uint64_t LoadSize = DL.getTypeSizeInBits(LoadTy) / 8;
443
Daniel Berlin5ac91792017-03-10 04:54:10 +0000444 // We know that this method is only called when the mem transfer fully
445 // provides the bits for the load.
446 if (MemSetInst *MSI = dyn_cast<MemSetInst>(SrcInst)) {
447 // memset(P, 'x', 1234) -> splat('x'), even if x is a variable, and
448 // independently of what the offset is.
Daniel Berlin12883b12017-03-20 16:08:29 +0000449 T *Val = cast<T>(MSI->getValue());
Daniel Berlin5ac91792017-03-10 04:54:10 +0000450 if (LoadSize != 1)
Daniel Berlin12883b12017-03-20 16:08:29 +0000451 Val =
452 Helper.CreateZExtOrBitCast(Val, IntegerType::get(Ctx, LoadSize * 8));
453 T *OneElt = Val;
Daniel Berlin5ac91792017-03-10 04:54:10 +0000454
455 // Splat the value out to the right number of bits.
456 for (unsigned NumBytesSet = 1; NumBytesSet != LoadSize;) {
457 // If we can double the number of bytes set, do it.
458 if (NumBytesSet * 2 <= LoadSize) {
Daniel Berlin12883b12017-03-20 16:08:29 +0000459 T *ShVal = Helper.CreateShl(
460 Val, ConstantInt::get(Val->getType(), NumBytesSet * 8));
461 Val = Helper.CreateOr(Val, ShVal);
Daniel Berlin5ac91792017-03-10 04:54:10 +0000462 NumBytesSet <<= 1;
463 continue;
464 }
465
466 // Otherwise insert one byte at a time.
Daniel Berlin12883b12017-03-20 16:08:29 +0000467 T *ShVal = Helper.CreateShl(Val, ConstantInt::get(Val->getType(), 1 * 8));
468 Val = Helper.CreateOr(OneElt, ShVal);
Daniel Berlin5ac91792017-03-10 04:54:10 +0000469 ++NumBytesSet;
470 }
471
Daniel Berlin12883b12017-03-20 16:08:29 +0000472 return coerceAvailableValueToLoadTypeHelper(Val, LoadTy, Helper, DL);
Daniel Berlin5ac91792017-03-10 04:54:10 +0000473 }
474
475 // Otherwise, this is a memcpy/memmove from a constant global.
476 MemTransferInst *MTI = cast<MemTransferInst>(SrcInst);
477 Constant *Src = cast<Constant>(MTI->getSource());
478 unsigned AS = Src->getType()->getPointerAddressSpace();
479
480 // Otherwise, see if we can constant fold a load from the constant with the
481 // offset applied as appropriate.
482 Src =
483 ConstantExpr::getBitCast(Src, Type::getInt8PtrTy(Src->getContext(), AS));
484 Constant *OffsetCst =
485 ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
486 Src = ConstantExpr::getGetElementPtr(Type::getInt8Ty(Src->getContext()), Src,
487 OffsetCst);
488 Src = ConstantExpr::getBitCast(Src, PointerType::get(LoadTy, AS));
489 return ConstantFoldLoadFromConstPtr(Src, LoadTy, DL);
490}
Daniel Berlin12883b12017-03-20 16:08:29 +0000491
492/// This function is called when we have a
493/// memdep query of a load that ends up being a clobbering mem intrinsic.
494Value *getMemInstValueForLoad(MemIntrinsic *SrcInst, unsigned Offset,
495 Type *LoadTy, Instruction *InsertPt,
496 const DataLayout &DL) {
497 IRBuilder<> Builder(InsertPt);
498 return getMemInstValueForLoadHelper<Value, IRBuilder<>>(SrcInst, Offset,
499 LoadTy, Builder, DL);
500}
501
502Constant *getConstantMemInstValueForLoad(MemIntrinsic *SrcInst, unsigned Offset,
503 Type *LoadTy, const DataLayout &DL) {
504 // The only case analyzeLoadFromClobberingMemInst cannot be converted to a
505 // constant is when it's a memset of a non-constant.
506 if (auto *MSI = dyn_cast<MemSetInst>(SrcInst))
507 if (!isa<Constant>(MSI->getValue()))
508 return nullptr;
509 ConstantFolder F;
510 return getMemInstValueForLoadHelper<Constant, ConstantFolder>(SrcInst, Offset,
511 LoadTy, F, DL);
512}
Daniel Berlin5ac91792017-03-10 04:54:10 +0000513} // namespace VNCoercion
514} // namespace llvm