Skip to content

hoistOneStaticallyBoundAllocation produces bogus 2^52-element static allocas when dynamic dim bounds default to the index umax #24483

Open

Description

@bjacob

(Note: all of this is generated by AI).

Summary

hoistStaticallyBoundAllocations (compiler/src/iree/compiler/Codegen/Common/HoistStaticallyBoundAllocations.cpp) accepts any result of ValueBoundsConstraintSet::computeConstantBound — including the trivial upper bound 2^53 - 1 that any index value carries when it has no other constraint — as the static dim of a hoisted memref.alloca. With one affine.apply of ceildiv 2 between the unconstrained value and the alloca, that produces a memref.alloca() : memref<4503599627370496xi32> (a 2^52-element static-shape stack allocation ≈ 16 PiB), silently, with no diagnostic. Downstream codegen then computes strides as products of these dims (overflowing i64 to poison) and the LLVM lowering ends up with llvm.alloca poison.

This isn't theoretical — it's hit by the CPU pack pipeline whenever the encoder swizzle materializes a rank-N inner tile under a dynamic-shape dispatch, see "How this blocks us" below.

Minimal reproducer

repro.mlir:

// Reproduces hoistStaticallyBoundAllocations producing a bogus
// 2^52-element static alloca when the dynamic dim's upper bound
// is the default `index` umax (2^53 - 1).

func.func @hoist_with_umax_bounded_dim(%arg0: index) {
  %c0 = arith.constant 0 : index
  %c1 = arith.constant 1 : index
  %c42 = arith.constant 42 : i32
  // What iree-stream-annotate-dispatch-assumptions emits for an
  // unconstrained dispatch workload operand:
  %assumed = util.assume.int %arg0<umin = 0, umax = 9007199254740991> : index
  // What data tiling emits when sizing a packed-outer dim:
  %dim = affine.apply affine_map<()[s0] -> (s0 ceildiv 2)>()[%assumed]
  // Force the alloca outside the entry block so the hoist pass picks it up.
  scf.for %iv = %c0 to %c1 step %c1 {
    %a = memref.alloca(%dim) : memref<?xi32>
    memref.store %c42, %a[%iv] : memref<?xi32>
    scf.yield
  }
  return
}

Run:

iree-opt \
  --pass-pipeline="builtin.module(func.func(iree-codegen-hoist-statically-bound-allocations))" \
  repro.mlir

Output (pass succeeds, no diagnostic):

func.func @hoist_with_umax_bounded_dim(%arg0: index) {
  %alloca = memref.alloca() : memref<4503599627370496xi32>      // 2^52 i32 ≈ 16 PiB
  %c0 = arith.constant 0 : index
  %c1 = arith.constant 1 : index
  %c42_i32 = arith.constant 42 : i32
  %0 = util.assume.int %arg0<umin = 0, umax = 9007199254740991> : index
  %1 = affine.apply affine_map<()[s0] -> (s0 ceildiv 2)>()[%0]
  scf.for %arg1 = %c0 to %c1 step %c1 {
    %subview = memref.subview %alloca[0] [%1] [1] :
               memref<4503599627370496xi32> to memref<?xi32, strided<[1]>>
    %cast = memref.cast %subview : memref<?xi32, strided<[1]>> to memref<?xi32>
    memref.store %c42_i32, %cast[%arg1] : memref<?xi32>
  }
  return
}

4503599627370496 = 2^52 = ceildiv(2^53 - 1, 2) — exactly the closedUB of %dim if you take %arg0's umax as the bound for %assumed.

Root cause

hoistOneStaticallyBoundAllocation (in compiler/src/iree/compiler/Codegen/Transforms/Transforms.cpp, around lines 127–252) computes a constant upper bound for each dynamic alloca operand:

auto ub = ValueBoundsConstraintSet::computeConstantBound(
    presburger::BoundType::UB, {value, std::nullopt},
    /*stopCondition=*/nullptr, ValueBoundsOptions{/*closedUB=*/true});
if (failed(ub)) {
  return std::nullopt;
}
return OpFoldResult(builder.getIndexAttr(*ub));

and uses it directly as the static dim of a hoisted alloca, with no cap. There is no check against:

  • the size of the resulting allocation in bytes,
  • the target's max_stack_allocation_size,
  • any sanity threshold beyond which the bound is clearly not a meaningful problem-size bound.

So when value is a util.assume.int %x<umin=0, umax=9007199254740991> (or anything derived from one), the hoist happily produces a 2^52-static-dim alloca. The bogus dim then propagates through stride computation (strides being products of inner dims, overflowing i64 to negative or wrap values) and through the LLVM lowering, where the size of the equivalent llvm.alloca <size> is whichever poison value the upstream multiplications collapsed to. The dispatch loads and stores then read/write whichever virtual memory the resulting pointer happens to land in — there is no SIGSEGV, no diagnostic, just silently undefined memory traffic that doesn't preserve the values stored in it.

LLVMCPUCheckIRBeforeLLVMConversionPass is meant to catch oversize stack allocations against max_stack_allocation_size, but by the time it runs the alloca is statically shaped (with the bogus dim) — checkStackAllocationSize multiplies the static dims, overflows i64 itself, and depending on which wrap value it lands on may or may not exceed the configured limit. In practice, with cumSize running through int and various multiplications, the check often does not trip on these allocations.

How CPU differs from GPU

GPU does not go through hoistOneStaticallyBoundAllocation at all.

gpuAllocationFn (compiler/src/iree/compiler/Codegen/LLVMGPU/Passes.cpp, lines ~152–179):

static FailureOr<Value> gpuAllocationFn(OpBuilder &builder, Location loc,
                                        MemRefType memRefType,
                                        ValueRange dynamicSizes,
                                        unsigned alignment) {
  ...
  if (enclosingForall && hasThreadMapping(enclosingForall)) {
    // Thread-private: emit memref.alloca with dynamicSizes passed
    // through as runtime operands.
    return memref::AllocaOp::create(builder, loc, allocType, dynamicSizes)...;
  }
  // Workgroup-shared: emit memref.alloc in workgroup address space.
  return memref::AllocOp::create(builder, loc, allocType, dynamicSizes)...;
}

Neither branch touches computeConstantBound. dynamicSizes flows through to the alloc/alloca op verbatim; the resulting memref keeps its ? dims with real SSA size operands. The GPU runtime can dynamically size workgroup memory and thread-private memory, so dynamic-sized allocations within a dispatch are unproblematic.

cpuAllocationFn (compiler/src/iree/compiler/Codegen/Common/CPU/Passes.cpp, lines ~21–38) instead:

static FailureOr<Value> cpuAllocationFn(OpBuilder &builder, Location loc,
                                        MemRefType memRefType,
                                        ValueRange dynamicSizes,
                                        unsigned alignment) {
  auto funcOp = ...;
  if (funcOp) {
    std::optional<Value> hoistedAllocation =
        hoistOneStaticallyBoundAllocation<memref::AllocaOp>(
            funcOp, builder, loc, memRefType, dynamicSizes, alignment);
    if (hoistedAllocation) {
      return hoistedAllocation.value();
    }
  }
  return memref::AllocaOp::create(...);
}

hoistOneStaticallyBoundAllocation is tried first. The trick — compute an upper bound on each dynamic size, materialize a statically-shaped alloca with those bounds, expose the actual size via a subview — exists because CPU dispatches don't have an in-dispatch malloc available, so anything dynamic-sized has to be promoted to a compile-time-known size to land on the stack.

That trick was implicitly designed for tight bounds (e.g. an affine.min-clamped tile size). It silently fails when the upper bound is the type-level umax. The asymmetry is intentional, the failure mode wasn't anticipated.

How this blocks us

We're working on a CPU inner_tiled lowering stack (see #24323 — the broader CPU data-tiled MMA effort). One of its prerequisite PRs (#24455, merged) attaches the per-operand TileSwizzle to the encoder's MaterializeEncodingInfo, so the pack pipeline produces the rank-N permuted inner-tile layout that DataTiledMMAAttr::getUndistributedTileTypes returns. For an ACC swizzle with a non-identity permutation (e.g. the generic-scalar fallback with intrinsics_m = 2, intrinsics_n = 4), the pack pipeline ends up emitting:

linalg.pack  →  tensor.expand_shape  →  linalg.transpose (with the swizzle's permutation)

The linalg.pack writes to an intermediate tensor<?x?x2x4xf32> whose outer dims are ceildiv(M_user, 2) and ceildiv(N_user, 4). Under a dynamic-shape dispatch, M_user and N_user are workload operands carrying only the default util.assume.int %x<umin=0, umax=2^53-1> annotation. Bufferization → cpuAllocationFn → hoistOneStaticallyBoundAllocation then materializes the intermediate buffer as memref.alloca() : memref<2^52 x 2^51 x 2 x 4 x f32> — exactly the failure mode above.

The visible symptom is that all 15 e2e_matmul_cpu_dt_inner_tiled_* variants that fall back to the generic-scalar MMA (everything except those with hardware MMA support — f32_f32 avx2/avx512, i8_i32 avx512vnni, f16_f32 avx512, bf16_f32 avx512bf16) compile cleanly and silently return LHS * RHS instead of LHS * RHS + ACC — the user's accumulator initial values get written to the bogus alloca's undefined memory and are never read back. The matmul math itself is correct; the ACC operand silently doesn't make it.

The legacy data-tiling path (linalg.mmt4d via --iree-opt-data-tiling without --iree-llvmcpu-enable-inner-tiled) is unaffected — its packed inner tile is rank-2 row-major, no tensor.expand_shape + linalg.transpose pattern, no intermediate alloca. Hardware-MMA inner_tiled cases are also unaffected, because their tile shapes are statically known at the encoder level. It is specifically the inner_tiled + dynamic-shape + generic-scalar-fallback combination that lands on this bug.

Possible fixes

In rough order of blast radius:

  1. Cap the bound in hoistOneStaticallyBoundAllocation. Refuse to hoist when the resulting static allocation exceeds the target's max_stack_allocation_size (or some sensible default), and fall back to leaving the alloca dynamic. This is a one-place fix in Transforms.cpp but reveals a second issue: LLVMCPUCheckIRBeforeLLVMConversionPass then rejects the dynamic alloca with expected no unbounded stack allocations, because computeScalableBound on the same operand returns failure (closed under the same umax) or a too-large bound. So a full fix here likely also needs the check pass to either widen its acceptance criterion or run heap-allocation for unbounded cases — which CPU dispatches don't currently support.

  2. Tighten util.assume.int bounds on workload ordinals at the front end. If iree-stream-annotate-dispatch-assumptions produced something narrower than the type-level umax for dimensions where the front end actually has a bound (e.g. from program-wide range analysis or user-supplied annotations), the hoist would size the alloca correctly. Doesn't help fully-dynamic dispatches but is the cleanest fix for the cases where bounds exist.

  3. Skip the swizzle transpose when its permutation is a no-op modulo unit dims. Targeted fix specifically for MaterializeEncoding's swizzle lowering. For e.g. the generic-scalar 1×1×1 case, the swizzle's permutation only shuffles Internal(1) placeholder dims among the CrossIntrinsic non-unit dims — the linearized memory layout is identical before and after. Detecting that pattern and replacing linalg.transpose with a shape-only tensor.collapse_shape/expand_shape round-trip eliminates the intermediate buffer entirely for the cases that currently trigger the bug. Doesn't fix the underlying hoist issue, but unblocks the inner_tiled stack.

We'd take (3) for the immediate unblock and would prefer (1) or (2) as the eventual real fix — the hoist's silent acceptance of the umax-derived bound is a footgun for anything that lands in this code path in the future.

Versions

Repro verified on origin/main at commit 2418e613e1 (the merge of #24455, which is what surfaced this for us in production). The two files that contain the bug (HoistStaticallyBoundAllocations.cpp, Transforms.cpp) are unchanged across the recent history, so the bug has been latent for as long as that hoist has existed — anything reaching it with index-umax bounds would have hit it.

Activity

  1. added
    bug 🐞
    codegen/llvm
    on May 13, 2026
  2. self-assigned this
    on May 13, 2026
  3. added a commit that references this issue on Nov 16, 2026
    bb85bb4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bug 🐞codegen/llvm

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions