intel/fs: clamp per vertex input accesses to patchControlPoints
authorLionel Landwerlin <lionel.g.landwerlin@intel.com>
Thu, 25 Mar 2021 12:53:32 +0000 (14:53 +0200)
committerMarge Bot <emma+marge@anholt.net>
Wed, 7 Dec 2022 08:16:03 +0000 (08:16 +0000)
commite25e17dd0c39675acd48fd4a6982fcd77530ef2c
treed2e0ae08aa234a3c7181a9800003c956b73b549f
parent9d43aebcaddfc081158db8313209a9b12afb864d
intel/fs: clamp per vertex input accesses to patchControlPoints

In a tesselation control shader where an input array is accessed using
the index gl_InvocationID, we can end up accessing elements beyond the
number of input vertices specified in the shader key.

This happens because of the lowering in nir_lower_indirect_derefs().
This lowering will affect compact variables which happens in this
case :

  in gl_PerVertex {
      vec4  gl_Position;
      float gl_ClipDistance[1];
  } gl_in[gl_MaxPatchVertices];

The lowered code produced by NIR is somewhat ineffecient (implements a
binary seach) :

  if (gl_InvocationID < 16) {
     if (gl_InvocationID < 8) {
        if (gl_InvocationID < 4) {
          vec4 vals = load_at_offset(0);
          value = bcsel(vals, gl_InvocationID);
        } else {
          vec4 vals = load_at_offset(4);
          value = bcsel(vals, gl_InvocationID - 4);
        }
     } else {
        if (gl_InvocationID < 12) {
          vec4 vals = load_at_offset(8);
          value = bcsel(vals, gl_InvocationID - 8);
        } else {
          vec4 vals = load_at_offset(12);
          value = bcsel(vals, gl_InvocationID - 12);
        }
     }
  } else {
     if (gl_InvocationID < 24) {
        ...
     } else {
        ...
     }
  }

By default the gl_MaxPatchVertices must be set at 32 items and that's
what the lowering code will use to divide the access into chunks of 4.
But when running with 3 input vertices, this means we'll pull one more
item than what was delivered in the shader payload.

This triggers issues further down the register scheduling where the
g5UD (register for the 4th item) is overwritten by a previous SEND,
leading the URB read to use an invalid handle.

This pass clamps any access load_per_vertex_input intrinsic vertex
indice to (input_vertices - 1).

Fixes issues with tests like :
dEQP-VK.clipping.user_defined.clip_distance.vert_tess.*

Also fixes a hang with zink/anv on :
KHR-GL46.draw_elements_base_vertex_tests.AEP_shader_stages

v2: Don't replace source register

v3: Implement in NIR

v4: Clamp per vertex array sizes in NIR (Jason)

v5: Move the clamping on the intel compiler

Signed-off-by: Lionel Landwerlin <lionel.g.landwerlin@intel.com>
Reviewed-by: Tapani Pälli <tapani.palli@intel.com>
Part-of: <https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/9749>
src/intel/compiler/brw_nir.h
src/intel/compiler/brw_nir_clamp_per_vertex_loads.c [new file with mode: 0644]
src/intel/compiler/brw_vec4_tcs.cpp
src/intel/compiler/meson.build