Issue 244021
Summary [mlir][OpenMP] mlir-translate crashes with OpenMP device code after CallConvLowering with some spirv* triples
Labels mlir
Assignees
Reporter Qi-Ye-079
    ## Summary

ClangIR's call-convention lowering for SPIR-V (`cir-opt -cir-call-conv-lowering=target=spirv`) gives OpenMP device code the same signatures classic clang does: structs are passed `byval` and returned through `sret` pointers. Translating the resulting module to LLVM IR then aborts in `llvm::CallInst::init`, on `spirv64-intel` and on `spirv32`:

```
Assertion `(i >= FTy->getNumParams() || FTy->getParamType(i) == Args[i]->getType()) && "Calling a function with a bad signature!"' failed.
```

Three problems in the MLIR OpenMP passes and translation combine to cause this:

- **A. `omp-stack-to-shared` moves `byval` temporaries and `sret` slots into shared memory.** It treats every local passed as a call argument as one that has to go into team-shared memory, and replaces the `llvm.alloca` with `omp.alloc_shared_mem`. Classic clang keeps those ABI temporaries on the stack. This affects both triples, and it's what brings the call-convention lowered code to the two translation bugs below.
- **B. `spirv64-intel`, whose program address space is 9: wrong address space, and no cast.** `omp.alloc_shared_mem` is translated to `__kmpc_alloc_shared`, which returns `ptr addrspace(9)` because the program address space is used as the default address space. The result is never cast back to the op's type, `!llvm.ptr`, so passing it to `@dev(ptr byval)` asserts.
- **C. `spirv32`, which has 32-bit pointers: wrong size type.** The allocation size is always built as `i64`, while `__kmpc_alloc_shared` takes a pointer-sized integer, `i32` here. `createOMPAllocShared` asserts.

AMDGPU and NVPTX64 don't crash: their program and default address spaces are both 0 and their pointers are 64-bit, so B and C don't happen, although A still moves the temporaries.

Without call-convention lowering, the struct is passed by value, no temporary escapes into a call, and translation succeeds on both triples. But B and C are not specific to call-convention lowering:
- **B** also gives wrong IR for any genuinely escaping local on `spirv64-intel`: it is allocated through `ptr addrspace(9)` and then cast to AS 4.
- **C** crashes plain `clang -fclangir -emit-llvm` on `spirv32` for any `declare target` function that passes a local's address to a call.

**Toolchain:** llvm/llvm-project `main` at `20b943451383` (2026-11-16), built with assertions. `cir-opt -cir-call-conv-lowering=target=spirv` is available since #241531. If a later commit makes `CallConvLowering` reject OpenMP device modules for SPIR-V, which is a planned temporary workaround, that check has to be reverted to reproduce this.

**Reproducer,** used in both parts below, `repro.c`:
```c
typedef struct { int a; float b; } S;
#pragma omp declare target
void dev(S s) {}
void caller(S *s) { dev(*s); }
#pragma omp end declare target
```
`dev` takes a struct by value, so after call-convention lowering `caller` copies `*s` into a `byval` temporary and passes its address. An `sret` return fails in the same way, for example with `S dev(void)` and `S r = dev();`.

---

## Part 1: `spirv64-intel`

### Reproducer and commands

```
clang -cc1 -fopenmp -fopenmp-is-target-device -triple spirv64-intel -fclangir -emit-cir repro.c -o repro.cir
cir-opt repro.cir -cir-call-conv-lowering=target=spirv -o repro.cc.cir
cir-translate repro.cc.cir -cir-to-llvmir -o repro.ll
```

The first two steps succeed. After `cir-opt`, the signatures match classic:
```
cir.func no_inline hidden dso_local @dev(%arg0: !cir.ptr<!rec_S> {llvm.align = 4 : i64, llvm.byval = !rec_S, llvm.noundef}) cc(spir_function)
cir.func no_inline hidden dso_local @caller(%arg0: !cir.ptr<!rec_S, target_address_space(4)> {llvm.noundef}) cc(spir_function)
  cir.call @dev(%3) cc(spir_function) : (!cir.ptr<!rec_S> {llvm.align = 4 : i64, llvm.byval = !rec_S, llvm.noundef}) -> ()
```

Running `cir-translate` on `repro.cir`, without the `cir-opt` step, succeeds.

### Current output

```
cir-translate: llvm/lib/IR/Instructions.cpp:804: void llvm::CallInst::init(llvm::FunctionType*, llvm::Value*, llvm::ArrayRef<llvm::Value*>, llvm::ArrayRef<llvm::OperandBundleDefT<llvm::Value*> >, const llvm::Twine&): Assertion `(i >= FTy->getNumParams() || FTy->getParamType(i) == Args[i]->getType()) && "Calling a function with a bad signature!"' failed.
```

### Expected output

Translation succeeds, and the `byval` temporary stays on the stack, as in classic clang. From `clang -cc1 -fopenmp -fopenmp-is-target-device -triple spirv64-intel -emit-llvm repro.c`:
```llvm
define hidden spir_func void @dev(ptr noundef byval(%struct.S) align 4 %s) addrspace(9)
define hidden spir_func void @caller(ptr addrspace(4) noundef %s) addrspace(9)
  %byval-temp = alloca %struct.S, align 4
  call spir_func addrspace(9) void @dev(ptr noundef byval(%struct.S) align 4 %byval-temp)
```

Where a local really does need shared memory, for a local whose address the source code passes to a call, classic allocates it through the default address space and casts the result:
```llvm
  %x = call spir_func align 8 addrspace(9) ptr addrspace(4) @__kmpc_alloc_shared(i64 4)
  %x_on_stack = addrspacecast ptr addrspace(4) %x to ptr
  ...
  call spir_func addrspace(9) void @__kmpc_free_shared(ptr addrspace(4) %x, i64 4)
declare spir_func noalias ptr addrspace(4) @__kmpc_alloc_shared(i64) addrspace(9)
```

### Root cause analysis (by Claude)

**A. `omp-stack-to-shared` moves ABI temporaries into shared memory.** `allocaUseRequiresSharedMem` treats any call-argument use of an alloca as requiring shared memory:
```cpp
// mlir/lib/Dialect/OpenMP/Utils/Utils.cpp:72, allocaUseRequiresSharedMem
} else if (auto callOp = dyn_cast<CallOpInterface>(owner)) {
  if (llvm::is_contained(callOp.getArgOperands(), use.get()))
    return true;
}
```
That includes operands with `llvm.byval` or `llvm.sret`. A `byval` temporary can't be seen by any other thread, because the callee gets its own copy. An `sret` slot is the caller's result temporary. Classic clang decides what to move from source-level escape analysis, and moves neither. Skipping these operands, or at least `byval` ones, would keep these temporaries on the stack, match classic, and avoid B in this reproducer.

**B. `omp.alloc_shared_mem` is translated with the wrong address space, and without a cast.**
1. The OpenMPIRBuilder's default target address space is set from the program address space:
   ```cpp
   // mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp:132
 config.setDefaultTargetAS(module.getDataLayout().getProgramAddressSpace());
 ```
   `OpenMPIRBuilder::initializeTypes` uses that value for every runtime pointer type, including the `VoidPtr` that `__kmpc_alloc_shared` returns and `__kmpc_free_shared` takes (`llvm/include/llvm/Frontend/OpenMP/OMPKinds.def:29`, `:510-511`). On `spirv64-intel` that's address space 9, which is for code. Clang sets it to the target address space of `LangAS::Default` instead, 4 (generic) on Intel SPIR-V:
   ```cpp
   // clang/lib/CodeGen/CGOpenMPRuntime.cpp:1059 (same in CGOpenMPRuntimeGPU.cpp)
   Config.setDefaultTargetAS(
 CGM.getContext().getTargetInfo().getTargetAddressSpace(LangAS::Default));
 ```
   The MLIR data layout has no entry for that language-level default, so the frontend would have to supply it, for example through a module attribute.
2. The result isn't cast back to the op's type:
   ```cpp
   // OpenMPToLLVMIRTranslation.cpp:10841, convertAllocSharedMemOp
 moduleTranslation.mapValue(allocMemOp.getResult(),
 ompBuilder->createOMPAllocShared(builder, size));
   ```
   The op's result type is `!llvm.ptr` (AS 0), but it's mapped to a `ptr addrspace(DefaultTargetAS)` value, so every typed user sees the wrong type.

Fixing only the cast stops the assertion, but still allocates through `ptr addrspace(9)`, which classic doesn't do. Fixing only the address space still mismatches, because the result (AS 4) feeds `ptr` (AS 0) users. Fixing A avoids the crash for `byval`/`sret` temporaries, but not for genuinely escaping locals.

---

## Part 2: `spirv32`

### Reproducer and commands

The same `repro.c`:
```
clang -cc1 -fopenmp -fopenmp-is-target-device -triple spirv32-unknown-unknown -fclangir -emit-cir repro.c -o repro.cir
cir-opt repro.cir -cir-call-conv-lowering=target=spirv -o repro.cc.cir
cir-translate repro.cc.cir -cir-to-llvmir -o repro.ll
```

After `cir-opt`:
```
cir.func no_inline hidden dso_local @dev(%arg0: !cir.ptr<!rec_S> {llvm.align = 4 : i64, llvm.byval = !rec_S, llvm.noundef}) cc(spir_function)
cir.func no_inline hidden dso_local @caller(%arg0: !cir.ptr<!rec_S> {llvm.noundef}) cc(spir_function)
  cir.call @dev(%2) cc(spir_function) : (!cir.ptr<!rec_S> {llvm.align = 4 : i64, llvm.byval = !rec_S, llvm.noundef}) -> ()
```

Running `cir-translate` on `repro.cir`, without the `cir-opt` step, succeeds for this source.

The size-type bug (problem C in the Summary) doesn't depend on call-convention lowering, though. A local whose address the source code passes to a call crashes even without `cir-opt`:
```c
#pragma omp declare target
void use(int *p);
void caller(void) { int x = 0; use(&x); }
#pragma omp end declare target
```
```
clang -cc1 -fopenmp -fopenmp-is-target-device -triple spirv32-unknown-unknown -fclangir -emit-llvm escape.c -o escape.ll # same assertion
```

### Current output

```
cir-translate: llvm/lib/IR/Instructions.cpp:804: void llvm::CallInst::init(llvm::FunctionType*, llvm::Value*, llvm::ArrayRef<llvm::Value*>, llvm::ArrayRef<llvm::OperandBundleDefT<llvm::Value*> >, const llvm::Twine&): Assertion `(i >= FTy->getNumParams() || FTy->getParamType(i) == Args[i]->getType()) && "Calling a function with a bad signature!"' failed.
```

### Expected output

Translation succeeds, and the `byval` temporary stays on the stack. Classic clang (`clang -cc1 -fopenmp -fopenmp-is-target-device -triple spirv32-unknown-unknown -emit-llvm repro.c`) passes `byval` without any shared allocation:
```llvm
define hidden spir_func void @dev(ptr noundef byval(%struct.S) align 4 %s)
define hidden spir_func void @caller(ptr noundef %s)
  call spir_func void @dev(ptr noundef byval(%struct.S) align 4 %0)
```

Classic doesn't use its GPU OpenMP runtime for `spirv32`, only for `spirv64` (`CodeGenModule::createOpenMPRuntime`), so it never calls `__kmpc_alloc_shared` on this triple. ClangIR sets `omp.is_gpu` from `Triple::isGPU()`, which includes `spirv32`. Whether ClangIR should match classic there is a separate question. Either way, when the translation does emit `__kmpc_alloc_shared` for a module with 32-bit pointers, the size should be `i32`:
```llvm
  %1 = call align 8 ptr @__kmpc_alloc_shared(i32 8)
 ...
  call void @__kmpc_free_shared(ptr %1, i32 8)
declare noalias ptr @__kmpc_alloc_shared(i32)
```

### Root cause analysis (by Claude)

**A**, as in Part 1, moves the `byval` temporary into shared memory.

**C. The size of `omp.alloc_shared_mem` is always `i64`.**
```cpp
// mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp:10787, getAllocationSize
llvm::Value *allocSize = builder.getInt64(typeSize.getFixedValue());
return builder.CreateMul(
 allocSize,
 builder.CreateIntCast(moduleTranslation.lookupValue(op.getMemArraySize()),
 builder.getInt64Ty(),
 /*isSigned=*/false));
```
But the runtime functions take `SizeTy`, which is pointer-sized:
```cpp
// llvm/include/llvm/Frontend/OpenMP/OMPKinds.def:43, 510-511
OMP_TYPE(SizeTy, M.getDataLayout().getIntPtrType(Ctx))
__OMP_RTL(__kmpc_alloc_shared, false, VoidPtr, SizeTy)
__OMP_RTL(__kmpc_free_shared, false, Void, VoidPtr, SizeTy)
```
With 32-bit pointers `SizeTy` is `i32`, so `createOMPAllocShared` calls `__kmpc_alloc_shared(i32)` with an `i64`. `createOMPFreeShared` would mismatch the same way. The `Type *VarType` overload of `createOMPAllocShared` also passes `Builder.getInt64(...)`.

Possible fixes: build the size in `SizeTy` in `getAllocationSize`, or cast it to the parameter type before the call, in `convertAllocSharedMemOp` / `convertFreeSharedMemOp` or in `createOMPAllocShared` / `createOMPFreeShared`.

_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to