[llvm-branch-commits] [llvm] [InstCombine][JumpTableToSwitch] Make a helper for iterating global elements (PR #242822)

Ömer Sinan Ağacan via llvm-branch-commits llvm-branch-commits at lists.llvm.org
Sun Nov 15 06:36:41 PST 2026


================
@@ -1068,3 +1069,80 @@ LinearExpression llvm::decomposeLinearExpression(const DataLayout &DL,
 
   return Expr;
 }
+
+std::optional<ConstGlobalIterator>
+ConstGlobalIterator::fromLoadInst(LoadInst *LI) {
+  const DataLayout &DL = LI->getDataLayout();
+  Value *Ptr = LI->getPointerOperand();
+  auto *GV = dyn_cast<GlobalVariable>(getUnderlyingObject(Ptr));
+  if (LI->isVolatile() || !GV || !GV->isConstant() ||
+      !GV->hasDefinitiveInitializer())
+    return std::nullopt;
+
+  Type *EltTy = LI->getType();
+  TypeSize EltSize = DL.getTypeStoreSize(EltTy);
+  if (EltSize.isScalable())
+    return std::nullopt;
+
+  LinearExpression Expr = decomposeLinearExpression(DL, Ptr);
+  if (!Expr.Index || Expr.BasePtr != GV || Expr.Offset.getBitWidth() > 64)
+    return std::nullopt;
+
+  Constant *Init = GV->getInitializer();
+  TypeSize GlobalSize = DL.getTypeAllocSize(Init->getType());
+
+  const APInt &Stride = Expr.Scale;
+  const APInt &ConstOffset = Expr.Offset;
+
+  // Allow an additional context offset, but only within the stride.
+  if (!ConstOffset.ult(Stride))
+    return std::nullopt;
+
+  // Don't handle overlapping loads for now.
+  if (!Stride.uge(EltSize.getFixedValue()))
+    return std::nullopt;
+
+  // - With nuw: `Idx * Stride` does not wrap and all strides are valid.
+  // - With nusw: `Idx * Stride` does not wrap as signed, and the following
+  //   enumeration over ArrayElementCount is valid so long as the stride is
+  //   positive.
+  // - Without nusw or nuw: `Idx * Stride` is computed modulo 2^N (see
+  //   getIndex), and the masking in getIndex is only exact when the stride is
+  //   a power of two.
+  bool StrideIsValid =
+      Expr.Flags.hasNoUnsignedWrap() ||
+      (Expr.Flags.hasNoUnsignedSignedWrap() ? !Stride.isNegative()
+                                            : Stride.isPowerOf2());
+  if (!StrideIsValid)
+    return std::nullopt;
+
+  uint64_t ArrayElementCount =
+      divideCeil((GlobalSize.getFixedValue() - ConstOffset.getZExtValue()),
+                 Stride.getZExtValue());
----------------
osa1 wrote:

This can wrap around and generate a large number. I think this is only working as expected today because all the call sites check the global size against a limit.

I also don't quite understand why the zext here is correct, given that the stride can be negative. We should document it.

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


More information about the llvm-branch-commits mailing list