optimizationcompilationhlsl

HLSL compiler optimizes strange?


I am not an expert in HLSL compilers and how they work with branches but I have read different opinions about this issue. So to be concrete: In C/C++ it would make perfect sense to implement something like:

if (factor == 0)
{
// Simple calculation in special case of factor=0
}
else if (factor == 1)
{
// Simple calculation in special case of factor=1
}
else
{
// Much more complex calculation in general case of arbitrary factor
}

in situations where most of the time factor is 0 or 1. Is the same true for HLSL? I have read multiple times that HLSL compilers work differently and e.g. in the resulting machine code all branches are computed anyway. In this case the above construction would not make sense and could be replaced by only the else case.


Solution

  • As stated in the documentation you can tell the compiler, whether both cases should be executed (tag [flatten]) or only one side (tag [branch]). If you're using gradient functions like tex2D you can't use branch, except you replace them with something like tex2Dlod.