iree icon indicating copy to clipboard operation
iree copied to clipboard

[Codegen] Shared-memory padding produces invalid IR for loop-carried memrefs

Open Cerulime opened this issue 1 month ago • 3 comments

What happened?

Summary

The checks in canReplaceMemrefUsesAndPropagateType do not filter out operations such as scf.for and scf.while that cannot directly accept changes to their operand types, causing compilation errors. These operations should be filtered out.

Steps to reproduce your issue

Reproducer

The following standalone pass reproducer uses a shared-memory allocation as a loop-carried scf.for operand. It requires no GPU execution, model input, or custom dialect operations.

repro.mlir:

module {
  func.func @loop_carried_memref(%lb: index, %ub: index, %step: index) {
    %alloc = memref.alloc() : memref<1x1x4xf32, #gpu.address_space<workgroup>>
    %result = scf.for %i = %lb to %ub step %step iter_args(%buffer = %alloc) -> (memref<1x1x4xf32, #gpu.address_space<workgroup>>) {
      scf.yield %buffer : memref<1x1x4xf32, #gpu.address_space<workgroup>>
    }
    return
  }
}

Commands:

iree-opt repro.mlir -o /dev/null

iree-opt repro.mlir \
  --pass-pipeline='builtin.module(func.func(iree-codegen-gpu-reduce-bank-conflicts{padding-bits=64}))'

Input verification succeeds with exit code 0. Running the bank-conflict pass on the same input fails with exit code 1, with the default pass verification enabled.

Only this pass is needed to reproduce the failure; no canonicalization or other optimization pass is included in the reproducer.

Actual behavior

The pass produces a loop whose initial operand has a padded layout, while the corresponding region argument and result retain the original layout. Verification fails with the following diagnostic, with the local filename normalized to repro.mlir:

repro.mlir:4:15: error: 'scf.for' op along control flow edge from parent to Region #0: successor operand type #0 'memref<1x1x4xf32, strided<[6, 6, 1]>, #gpu.address_space<workgroup>>' should match successor input type #0 'memref<1x1x4xf32, #gpu.address_space<workgroup>>'

The diagnostic prints the affected loop as:

%2 = "scf.for"(%arg0, %arg1, %arg2, %1) ({
^bb0(%arg3: index, %arg4: memref<1x1x4xf32, #gpu.address_space<workgroup>>):
  "scf.yield"(%arg4) : (memref<1x1x4xf32, #gpu.address_space<workgroup>>) -> ()
}) : (index, index, index, memref<1x1x4xf32, strided<[6, 6, 1]>, #gpu.address_space<workgroup>>) -> memref<1x1x4xf32, #gpu.address_space<workgroup>>

With 64 bits of padding and f32 elements, the allocation's innermost extent increases from four to six. A subview retains the logical shape 1x1x4, but its layout becomes strided<[6, 6, 1]>. The loop's initial operand is replaced with this subview without updating its region argument, yielded value, or result type.

Expected behavior

The pass should preserve valid IR. With the current type-propagation implementation, the precheck should reject this replacement, allowing the existing padAlloc failure path to leave the allocation and its users unchanged.

Allocations whose users support the layout change should remain eligible for padding. Supporting padding through loops would require coordinated propagation through their region signatures, terminators, and results.

What component(s) does this issue relate to?

Compiler

Version information

Environment

  • Tool: the existing local IREE iree-opt on Linux.
  • The standalone reproducer uses only Builtin, Func, MemRef, and SCF operations plus a standard GPU address-space attribute.
  • Input verification succeeds with exit code 0; applying the bank-conflict pass fails with exit code 1.
  • Validation used the existing compiler tools only. No compiler source modification, compiler rebuild, or GPU execution was performed for the standalone reproducer.

Additional context

Root cause

The relevant helpers are canReplaceMemrefUsesAndPropagateType and replaceMemrefUsesAndPropagateType in compiler/src/iree/compiler/Codegen/Utils/Utils.cpp.

After excluding ReturnLike users, the precheck assumes that users outside the recognized reshape operations can accept the new operand type directly:

// Non-reshape operations can accept the new operand type directly.
if (!isNonTrivialMemrefReshapeOp(user)) {
  continue;
}

For this input, the allocation is used as a scf.for initial operand. The loop is not classified as a nontrivial reshape operation, so the precheck succeeds without examining its tied region argument or result.

The replacement helper also has no loop-signature rewrite for this use and falls back to replacing the operand. This breaks the required type agreement between the initial operand, region argument, yielded value, and result.

padAlloc in GPUReduceBankConflicts.cpp relies on the precheck before creating the padded allocation and replacing the original allocation's uses. Thus an unsupported replacement is allowed to proceed.

The helper's documented reshape propagation does not describe region-signature rewrites. The concrete problem is the unchecked assumption about non-reshape users at this call site. scf.while also ties incoming operands to region arguments and should be considered when defining the supported-use boundary; only the scf.for reproducer above was executed locally.

Candidate fix

Extend the precheck's existing rejection of ReturnLike users to reject RegionBranchOpInterface users while region-signature type propagation is unsupported. Include mlir/Interfaces/ControlFlowInterfaces.h and update the rejection diagnostic and comment accordingly:

// These operations may tie operand types to region arguments or results,
// which this helper does not update.
if (user->hasTrait<OpTrait::ReturnLike>() ||
    isa<RegionBranchOpInterface>(user)) {
  LDBG() << "canReplaceMemrefUsesAndPropagateType: cannot propagate "
            "type through op: "
         << *user;
  return failure();
}

This lets padAlloc skip the affected allocation before modifying IR. Other allocations can still be padded. The interface check covers related control-flow operations without maintaining a separate list of loop operation names.

This is a conservative capability check: it can skip padding for some region operations that could be supported by a more complete type-propagation implementation. Full support would require handling the corresponding region arguments, control-flow edges, terminators, and results together.

Rejecting the replacement in the precheck is necessary. Merely leaving a loop use untouched in the replacement helper would be insufficient because padAlloc subsequently erases the original allocation.

Suggested regression coverage in reduce_bank_conflicts.mlir should check that a loop-carried allocation keeps its original layout, including when reached through a subview, while an unrelated ordinary allocation in the same function is still padded.

The candidate fix has not been applied or validated in a rebuilt compiler.

AI assistance disclosure

OpenAI Codex provided substantial assistance with translating the reporter-written summary, source analysis, reducing and validating the standalone reproducer, and drafting the technical sections of this report.

Cerulime avatar Oct 07 '26 11:10 Cerulime

Hello @Cerulime :wave:

Thank you for submitting an issue to IREE! It looks like it's your first one.

The volume of issues is huge, and triage times may vary. If you need quicker assistance on the issue, consider posting it on IREE Discord and providing short context there. Feel free to identify the most frequent contributors to the corresponding part of the codebase via Git history/CODEOWNERS and (gently!) tag them below.


Action required: acknowledge IREE project policies

IREE is a Linux Foundation project. All participants are expected to follow the LF Projects Code of Conduct.

Please note that all contributions to IREE, including GitHub issues, must follow our IREE AI Tool Use Policy. This means:

  • Issue reporters must fully understand the primary issue and the impact of the problem. For bug reports, specifics of the use-case, workflow and/or crash scenario usually suffice. For improvement suggestions, this usually implies deeper understanding of suboptimal code, IR design choices, assumed performance tradeoffs, etc.
  • Contributors must write the summary of the issue themselves, so that the exact impact and scenario is clear to other participants.
  • Issue authors are expected to review and understand all LLM/AI-assisted segments of the report, if any. E.g.: CLI commands and IR reproducers, model/framework details, lowering pipeline details, assumptions about problematic behaviors of IREE components.
  • Substantial use of LLM/generative AI tools must be disclaimed in the header or footer of the issue description.

Before the issue can be triaged, we kindly ask you to reply to this message and confirm that you understand and accept the proposed policy. As required, please adjust your initial issue description.


If you have any questions, feel free to leave a comment here, or ask away on IREE Discord.

Thank you, The IREE Community

github-actions[bot] avatar Oct 07 '26 11:10 github-actions[bot]

Hello @Cerulime 👋

Thank you for submitting an issue to IREE! It looks like it's your first one.

The volume of issues is huge, and triage times may vary. If you need quicker assistance on the issue, consider posting it on IREE Discord and providing short context there. Feel free to identify the most frequent contributors to the corresponding part of the codebase via Git history/CODEOWNERS and (gently!) tag them below.

Action required: acknowledge IREE project policies

IREE is a Linux Foundation project. All participants are expected to follow the LF Projects Code of Conduct.

Please note that all contributions to IREE, including GitHub issues, must follow our IREE AI Tool Use Policy. This means:

  • Issue reporters must fully understand the primary issue and the impact of the problem. For bug reports, specifics of the use-case, workflow and/or crash scenario usually suffice. For improvement suggestions, this usually implies deeper understanding of suboptimal code, IR design choices, assumed performance tradeoffs, etc.
  • Contributors must write the summary of the issue themselves, so that the exact impact and scenario is clear to other participants.
  • Issue authors are expected to review and understand all LLM/AI-assisted segments of the report, if any. E.g.: CLI commands and IR reproducers, model/framework details, lowering pipeline details, assumptions about problematic behaviors of IREE components.
  • Substantial use of LLM/generative AI tools must be disclaimed in the header or footer of the issue description.

Before the issue can be triaged, we kindly ask you to reply to this message and confirm that you understand and accept the proposed policy. As required, please adjust your initial issue description.

If you have any questions, feel free to leave a comment here, or ask away on IREE Discord.

Thank you, The IREE Community

I understand it.

Cerulime avatar Oct 07 '26 11:10 Cerulime

I found another affected caller: iree-codegen-pad-dynamic-alloc. It calls replaceMemrefUsesAndPropagateType without first calling canReplaceMemrefUsesAndPropagateType. With my local RegionBranchOpInterface precheck change, the original bank-conflict reproducer now succeeds, but the standalone reproducer below still fails. CRISP is explicitly disabled, and the input uses only standard dialects.

module {
  func.func @loop_carried_alloca(%size: index) {
    %c0 = arith.constant 0 : index
    %c1 = arith.constant 1 : index
    %c8 = arith.constant 8 : index
    %rem = arith.remui %size, %c8 : index
    %dim = arith.addi %rem, %c1 : index
    %buffer = memref.alloca(%dim) : memref<1x?xf32>
    %result = scf.for %i = %c0 to %c1 step %c1
        iter_args(%arg = %buffer) -> (memref<1x?xf32>) {
      scf.yield %arg : memref<1x?xf32>
    }
    return
  }
}
# Input verification: exit 0.
iree-opt repro.mlir --iree-llvmgpu-enable-crisp=false -o /dev/null

# Pass verification: exit 1.
iree-opt repro.mlir --iree-llvmgpu-enable-crisp=false \
  --pass-pipeline='builtin.module(func.func(iree-codegen-pad-dynamic-alloc))'

Padding changes the initial operand to memref<1x?xf32, strided<[8, 1]>>, while the region argument and result retain memref<1x?xf32>. I also reproduced this with memref.alloc, scf.while, and a subview between the allocation and the loop. The fix should therefore cover both the precheck and this unchecked caller. PadDynamicAlloc should infer the replacement subview type and check propagation before mutating IR. Skipping an unsupported replacement prevents malformed IR; successful GPU legalization may additionally require coordinated region-signature propagation.

Cerulime avatar Oct 09 '26 05:10 Cerulime