[llvm] [VectorCombine] Fold contiguous loads into a single vector load (PR #185736)

Simon Pilgrim via llvm-commits llvm-commits at lists.llvm.org
Mon Jun 1 05:53:58 PDT 2026


================
@@ -6053,6 +6054,116 @@ bool VectorCombine::shrinkPhiOfShuffles(Instruction &I) {
   return true;
 }
 
+/// Check if a vector instruction's lanes originate from contiguous memory
+/// accesses. Fold the original loads and shuffles into a single vector load
+/// if it is profitable. For example:
+///     shufflevector(load <4 x float> ptr), poison, <2, 3>
+///       -> load <2 x float> (ptradd ptr, 8)
+/// Cost model calculations take into account the cost of the original
+/// unique load(s) and the target instruction versus the cost of the new
+/// aligned vector load.
+bool VectorCombine::foldContiguousLoads(Instruction &I) {
+  auto *VT = dyn_cast<FixedVectorType>(I.getType());
+  if (!VT || I.use_empty())
+    return false;
+
+  Type *EltTy = VT->getElementType();
+  if (!DL->typeSizeEqualsStoreSize(EltTy))
+    return false;
+
+  auto MaxInt64 = static_cast<uint64_t>(std::numeric_limits<int64_t>::max());
+  uint64_t ElementSizeBits = DL->getTypeStoreSizeInBits(EltTy);
+  assert((ElementSizeBits <= MaxInt64) && "element size far too large?");
+  int64_t ElementSize = static_cast<int64_t>(ElementSizeBits);
+  unsigned NumElts = VT->getNumElements();
+  Value *CommonBase = nullptr;
+  int64_t ExpectedBaseBitOffset = 0, FirstLoadOffset = 0;
+  LoadInst *FirstLI = nullptr;
+  SmallPtrSet<LoadInst *, 4> Loads;
+  for (unsigned Lane = 0; Lane < NumElts; ++Lane) {
+    InstLane IL = lookThroughShuffles(&I, Lane);
+    if (!IL.first)
+      return false;
+
+    auto *LI = dyn_cast<LoadInst>(IL.first);
+    if (!LI)
+      return false;
+
+    if (!LI->isSimple() || !LI->hasOneUse())
+      return false;
+
+    auto *LIVTy = dyn_cast<FixedVectorType>(LI->getType());
+    if (!LIVTy || LIVTy->getElementType() != EltTy)
+      return false;
+
+    if (LI->getParent() != I.getParent())
+      return false;
+
+    if (isMemModifiedBetween(std::next(LI->getIterator()), I.getIterator(),
+                             MemoryLocation::get(LI), AA))
+      return false;
+
+    int64_t ConstantOffset = 0;
+    Value *Base = GetPointerBaseWithConstantOffset(LI->getPointerOperand(),
+                                                   ConstantOffset, *DL);
+    int64_t AbsoluteBitOffset =
----------------
RKSimon wrote:

ensure you briefly comment key stages

https://github.com/llvm/llvm-project/pull/185736


More information about the llvm-commits mailing list