VNCoercion.cpp 24 KB

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