shader-slang / slang

Making it easier to work with shaders
MIT License
1.78k stars 159 forks source link

Failed to compile a shader with an array of the structure with RWBuffer resource #3328

Open SuikaSibyl opened 7 months ago

SuikaSibyl commented 7 months ago

When compiling a Slang shader with an array of the structure (e.g. TensorView below), where the structure contains a buffer resource type (e.g. RWByteAddressBuffer), into the GLSL target, the compiler will crash without any diagnosis information.

A simpler one might be successfully compiled, as everything is somehow inlined.

An example minimum code snippet: (Target: GLSL, slang version: newest Release now)

RWByteAddressBuffer g_gradient_buffer;

struct TensorView {
    RWByteAddressBuffer gradient_buffer;
    uint offset_grad;
    void interlocked_add_grad(int x, float val) {
        gradient_buffer.InterlockedAddF32((offset_grad + x) * sizeof(float), val); 
    }
};

struct Foo {
    TensorView view;
    __init(TensorView view) {
        this.view = view;
    }
    void bar() {
        view.interlocked_add_grad(0, 1.f);
    }
};

[shader("compute")]
[numthreads(32, 4, 1)]
void ComputeMain(int3 gtid: SV_GroupThreadID) {    
    TensorView views[3] = {
        {g_gradient_buffer, 0},
        {g_gradient_buffer, 4},
        {g_gradient_buffer, 8},
    };

    Foo foos[3] = {
        Foo(views[0]),
        Foo(views[1]),
        Foo(views[2]),
    };

    for (int i = 0; i < 3; ++i) {
        foos[i].bar();
    }
}
csyonghe commented 7 months ago

Resources types in a shader target (hlsl/glsl) has a lot of restrictions in that they are not true data types and cannot used without restrictions when placed in arrays or structs. If the compiler can't legalize them out of existence from those array/struct types, it can't generate valid hlsl/glsl code.

A way around this is to define a global array of buffers and store indices in the user defined struct/array types.

However if the compiler crashes without diagnostics, it is something we should fix.

natduca commented 7 months ago

Thanks for the bug report! Putting some labels on this so we can figure out when to get to it :)