shader-slang / slang

Making it easier to work with shaders
MIT License
1.79k stars 160 forks source link

constexpr doesn't work as expected when used on a function #4236

Open jkwak-work opened 1 month ago

jkwak-work commented 1 month ago

Problem description When constexpr is used on a function, the return value is expected to be available at compile-time. But it doesn't seem to be working as expected.

Repro The following code shows a simple function, "LoopCount", that returns a given input. It has constexpr on the return type and the input type. But it leads to an error when used for [ForceUnroll].

//TEST(compute):COMPARE_COMPUTE_EX:-slang -compute -shaderobj -output-using-type
//TEST(compute, vulkan):COMPARE_COMPUTE_EX:-vk -compute -shaderobj -output-using-type

//TEST_INPUT: set g_texture = Texture2D(size=8, content = one)
//TEST_INPUT: set g_sampler = Sampler
//TEST_INPUT:ubuffer(data=[0], stride=4):out,name=outputBuffer

Texture2D g_texture;
SamplerState g_sampler;
RWStructuredBuffer<float> outputBuffer;

float4 sample(float2 uv, constexpr int2 ofs )
{
    return g_texture.SampleLevel(g_sampler, uv, 0.0, ofs);
}

[ForceInline]
constexpr int LoopCount(constexpr int v) // <===== constexpr on a function
{
    return v;
}

[numthreads(1, 1, 1)]
void computeMain(int3 dispatchThreadID: SV_DispatchThreadID)
{
    float4 result = 0;
    [ForceUnroll] // <================== Works fine without this line
    for (int i = 0; i < LoopCount(3); i++)
        result += sample(float2(1.0), int2(i, i));
    outputBuffer[dispatchThreadID.x] = result.x;
}

The error message is also a little unclear what the real problem is. It shows that the variable, "i", is not a compile-time constant, which is true but not a real reason for the error.

tests/language-feature/constants/constexpr-loop.slang(28): error 40006: expected a compile-time constant
    for (int i = 0; i < LoopCount(3); i++)
                                       ^~

Goal We should make constexpr working for functions. Or we should describe the limitation on our document.

bmillsNV commented 1 month ago

Should be documented as not working.

jkwak-work commented 1 month ago

I am leaving a note from our discussion.

The implementation of constexpr hasn't been never been completed. We will make a document to keep track of features like this and follow up.

This task is WNF for now and revisit later when the priority arise.

bmillsNV commented 1 month ago

Assigning to @swoods-nv to get a doc tracking of unfinished features.