• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright © 2015 Red Hat
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  *
23  * Authors:
24  *    Rob Clark <robclark@freedesktop.org>
25  */
26 
27 #include "nir.h"
28 #include "nir_builder.h"
29 
30 #define MAX_CLIP_PLANES 8
31 
32 /* Generates the lowering code for user-clip-planes, generating CLIPDIST
33  * from UCP[n] + CLIPVERTEX or POSITION.  Additionally, an optional pass
34  * for fragment shaders to insert conditional kills based on the inter-
35  * polated CLIPDIST
36  *
37  * NOTE: should be run after nir_lower_outputs_to_temporaries() (or at
38  * least in scenarios where you can count on each output written once
39  * and only once).
40  */
41 
42 
43 static nir_variable *
create_clipdist_var(nir_shader * shader,bool output,gl_varying_slot slot,unsigned array_size)44 create_clipdist_var(nir_shader *shader,
45                     bool output, gl_varying_slot slot, unsigned array_size)
46 {
47    nir_variable *var = rzalloc(shader, nir_variable);
48 
49    /* TODO use type_size() for num_inputs/outputs */
50    if (output) {
51       var->data.driver_location = shader->num_outputs++;
52       var->data.mode = nir_var_shader_out;
53    } else {
54       var->data.driver_location = shader->num_inputs++;
55       var->data.mode = nir_var_shader_in;
56    }
57    var->name = ralloc_asprintf(var, "clipdist_%d", var->data.driver_location);
58    var->data.index = 0;
59    var->data.location = slot;
60 
61    if (array_size > 0) {
62       var->type = glsl_array_type(glsl_float_type(), array_size,
63                                   sizeof(float));
64       var->data.compact = 1;
65    } else
66       var->type = glsl_vec4_type();
67 
68    nir_shader_add_variable(shader, var);
69    return var;
70 }
71 
72 static void
create_clipdist_vars(nir_shader * shader,nir_variable ** io_vars,unsigned ucp_enables,bool output,bool use_clipdist_array)73 create_clipdist_vars(nir_shader *shader, nir_variable **io_vars,
74                      unsigned ucp_enables, bool output,
75                      bool use_clipdist_array)
76 {
77    if (use_clipdist_array) {
78       io_vars[0] =
79          create_clipdist_var(shader, output,
80                              VARYING_SLOT_CLIP_DIST0,
81                              util_last_bit(ucp_enables));
82    } else {
83       if (ucp_enables & 0x0f)
84          io_vars[0] =
85             create_clipdist_var(shader, output,
86                                 VARYING_SLOT_CLIP_DIST0, 0);
87       if (ucp_enables & 0xf0)
88          io_vars[1] =
89             create_clipdist_var(shader, output,
90                                 VARYING_SLOT_CLIP_DIST1, 0);
91    }
92 }
93 
94 static void
store_clipdist_output(nir_builder * b,nir_variable * out,nir_ssa_def ** val)95 store_clipdist_output(nir_builder *b, nir_variable *out, nir_ssa_def **val)
96 {
97    nir_intrinsic_instr *store;
98 
99    store = nir_intrinsic_instr_create(b->shader, nir_intrinsic_store_output);
100    store->num_components = 4;
101    nir_intrinsic_set_base(store, out->data.driver_location);
102    nir_intrinsic_set_write_mask(store, 0xf);
103 
104    nir_io_semantics semantics = {
105       .location = out->data.location,
106       .num_slots = 1,
107    };
108    nir_intrinsic_set_io_semantics(store, semantics);
109 
110    store->src[0].ssa = nir_vec4(b, val[0], val[1], val[2], val[3]);
111    store->src[0].is_ssa = true;
112    store->src[1] = nir_src_for_ssa(nir_imm_int(b, 0));
113    nir_builder_instr_insert(b, &store->instr);
114 }
115 
116 static void
load_clipdist_input(nir_builder * b,nir_variable * in,int location_offset,nir_ssa_def ** val)117 load_clipdist_input(nir_builder *b, nir_variable *in, int location_offset,
118                     nir_ssa_def **val)
119 {
120    nir_intrinsic_instr *load;
121 
122    load = nir_intrinsic_instr_create(b->shader, nir_intrinsic_load_input);
123    load->num_components = 4;
124    nir_intrinsic_set_base(load, in->data.driver_location + location_offset);
125 
126    nir_io_semantics semantics = {
127       .location = in->data.location,
128       .num_slots = 1,
129    };
130    nir_intrinsic_set_io_semantics(load, semantics);
131 
132    load->src[0] = nir_src_for_ssa(nir_imm_int(b, 0));
133    nir_ssa_dest_init(&load->instr, &load->dest, 4, 32, NULL);
134    nir_builder_instr_insert(b, &load->instr);
135 
136    val[0] = nir_channel(b, &load->dest.ssa, 0);
137    val[1] = nir_channel(b, &load->dest.ssa, 1);
138    val[2] = nir_channel(b, &load->dest.ssa, 2);
139    val[3] = nir_channel(b, &load->dest.ssa, 3);
140 }
141 
142 static nir_ssa_def *
find_output_in_block(nir_block * block,unsigned drvloc)143 find_output_in_block(nir_block *block, unsigned drvloc)
144 {
145    nir_foreach_instr(instr, block) {
146 
147       if (instr->type == nir_instr_type_intrinsic) {
148          nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr);
149          if ((intr->intrinsic == nir_intrinsic_store_output) &&
150              nir_intrinsic_base(intr) == drvloc) {
151             assert(intr->src[0].is_ssa);
152             assert(nir_src_is_const(intr->src[1]));
153             return intr->src[0].ssa;
154          }
155       }
156    }
157 
158    return NULL;
159 }
160 
161 /* TODO: maybe this would be a useful helper?
162  * NOTE: assumes each output is written exactly once (and unconditionally)
163  * so if needed nir_lower_outputs_to_temporaries()
164  */
165 static nir_ssa_def *
find_output(nir_shader * shader,unsigned drvloc)166 find_output(nir_shader *shader, unsigned drvloc)
167 {
168    nir_ssa_def *def = NULL;
169    nir_foreach_function(function, shader) {
170       if (function->impl) {
171          nir_foreach_block_reverse(block, function->impl) {
172             nir_ssa_def *new_def = find_output_in_block(block, drvloc);
173             assert(!(new_def && def));
174             def = new_def;
175 #if !defined(DEBUG)
176             /* for debug builds, scan entire shader to assert
177              * if output is written multiple times.  For release
178              * builds just assume all is well and bail when we
179              * find first:
180              */
181             if (def)
182                break;
183 #endif
184          }
185       }
186    }
187 
188    return def;
189 }
190 
191 static bool
find_clipvertex_and_position_outputs(nir_shader * shader,nir_variable ** clipvertex,nir_variable ** position)192 find_clipvertex_and_position_outputs(nir_shader *shader,
193                                      nir_variable **clipvertex,
194                                      nir_variable **position)
195 {
196    nir_foreach_shader_out_variable(var, shader) {
197       switch (var->data.location) {
198       case VARYING_SLOT_POS:
199          *position = var;
200          break;
201       case VARYING_SLOT_CLIP_VERTEX:
202          *clipvertex = var;
203          break;
204       case VARYING_SLOT_CLIP_DIST0:
205       case VARYING_SLOT_CLIP_DIST1:
206          /* if shader is already writing CLIPDIST, then
207           * there should be no user-clip-planes to deal
208           * with.
209           *
210           * We assume nir_remove_dead_variables has removed the clipdist
211           * variables if they're not written.
212           */
213          return false;
214       }
215    }
216 
217    return *clipvertex || *position;
218 }
219 
220 static nir_ssa_def *
get_ucp(nir_builder * b,int plane,const gl_state_index16 clipplane_state_tokens[][STATE_LENGTH])221 get_ucp(nir_builder *b, int plane,
222         const gl_state_index16 clipplane_state_tokens[][STATE_LENGTH])
223 {
224    if (clipplane_state_tokens) {
225       char tmp[100];
226       snprintf(tmp, ARRAY_SIZE(tmp), "gl_ClipPlane%dMESA", plane);
227       nir_variable *var = nir_variable_create(b->shader,
228                                               nir_var_uniform,
229                                               glsl_vec4_type(),
230                                               tmp);
231 
232       var->num_state_slots = 1;
233       var->state_slots = ralloc_array(var, nir_state_slot, 1);
234       memcpy(var->state_slots[0].tokens,
235              clipplane_state_tokens[plane],
236              sizeof(var->state_slots[0].tokens));
237       return nir_load_var(b, var);
238    } else
239       return nir_load_user_clip_plane(b, plane);
240 }
241 
242 
243 static void
lower_clip_outputs(nir_builder * b,nir_variable * position,nir_variable * clipvertex,nir_variable ** out,unsigned ucp_enables,bool use_vars,bool use_clipdist_array,const gl_state_index16 clipplane_state_tokens[][STATE_LENGTH])244 lower_clip_outputs(nir_builder *b, nir_variable *position,
245                    nir_variable *clipvertex, nir_variable **out,
246                    unsigned ucp_enables, bool use_vars,
247                    bool use_clipdist_array,
248                    const gl_state_index16 clipplane_state_tokens[][STATE_LENGTH])
249 {
250    nir_ssa_def *clipdist[MAX_CLIP_PLANES];
251    nir_ssa_def *cv;
252 
253    if (use_vars) {
254       cv = nir_load_var(b, clipvertex ? clipvertex : position);
255 
256       if (clipvertex) {
257          clipvertex->data.mode = nir_var_shader_temp;
258          nir_fixup_deref_modes(b->shader);
259       }
260    } else {
261       if (clipvertex)
262          cv = find_output(b->shader, clipvertex->data.driver_location);
263       else {
264          assert(position);
265          cv = find_output(b->shader, position->data.driver_location);
266       }
267    }
268 
269    for (int plane = 0; plane < MAX_CLIP_PLANES; plane++) {
270       if (ucp_enables & (1 << plane)) {
271          nir_ssa_def *ucp = get_ucp(b, plane, clipplane_state_tokens);
272 
273          /* calculate clipdist[plane] - dot(ucp, cv): */
274          clipdist[plane] = nir_fdot4(b, ucp, cv);
275       } else {
276          /* 0.0 == don't-clip == disabled: */
277          clipdist[plane] = nir_imm_float(b, 0.0);
278       }
279       if (use_clipdist_array && plane < util_last_bit(ucp_enables)) {
280          assert(use_vars);
281          nir_deref_instr *deref;
282          deref = nir_build_deref_array_imm(b,
283                                            nir_build_deref_var(b, out[0]),
284                                            plane);
285          nir_store_deref(b, deref, clipdist[plane], 1);
286       }
287    }
288 
289    if (!use_clipdist_array) {
290       if (use_vars) {
291          if (ucp_enables & 0x0f)
292             nir_store_var(b, out[0], nir_vec(b, clipdist, 4), 0xf);
293          if (ucp_enables & 0xf0)
294             nir_store_var(b, out[1], nir_vec(b, &clipdist[4], 4), 0xf);
295       } else {
296          if (ucp_enables & 0x0f)
297             store_clipdist_output(b, out[0], &clipdist[0]);
298          if (ucp_enables & 0xf0)
299             store_clipdist_output(b, out[1], &clipdist[4]);
300       }
301    }
302 }
303 
304 /*
305  * VS lowering
306  */
307 
308 /* ucp_enables is bitmask of enabled ucps.  Actual ucp values are
309  * passed in to shader via user_clip_plane system-values
310  *
311  * If use_vars is true, the pass will use variable loads and stores instead
312  * of working with store_output intrinsics.
313  *
314  * If use_clipdist_array is true, the pass will use compact arrays for the
315  * clipdist output instead of two vec4s.
316  */
317 bool
nir_lower_clip_vs(nir_shader * shader,unsigned ucp_enables,bool use_vars,bool use_clipdist_array,const gl_state_index16 clipplane_state_tokens[][STATE_LENGTH])318 nir_lower_clip_vs(nir_shader *shader, unsigned ucp_enables, bool use_vars,
319                   bool use_clipdist_array,
320                   const gl_state_index16 clipplane_state_tokens[][STATE_LENGTH])
321 {
322    nir_function_impl *impl = nir_shader_get_entrypoint(shader);
323    nir_builder b;
324    nir_variable *position = NULL;
325    nir_variable *clipvertex = NULL;
326    nir_variable *out[2] = { NULL };
327 
328    if (!ucp_enables)
329       return false;
330 
331    nir_builder_init(&b, impl);
332 
333    /* NIR should ensure that, even in case of loops/if-else, there
334     * should be only a single predecessor block to end_block, which
335     * makes the perfect place to insert the clipdist calculations.
336     *
337     * NOTE: in case of early returns, these would have to be lowered
338     * to jumps to end_block predecessor in a previous pass.  Not sure
339     * if there is a good way to sanity check this, but for now the
340     * users of this pass don't support sub-routines.
341     */
342    assert(impl->end_block->predecessors->entries == 1);
343    b.cursor = nir_after_cf_list(&impl->body);
344 
345    /* find clipvertex/position outputs */
346    if (!find_clipvertex_and_position_outputs(shader, &clipvertex, &position))
347       return false;
348 
349    /* insert CLIPDIST outputs */
350    create_clipdist_vars(shader, out, ucp_enables, true,
351                         use_clipdist_array);
352 
353    lower_clip_outputs(&b, position, clipvertex, out, ucp_enables, use_vars,
354                       use_clipdist_array, clipplane_state_tokens);
355 
356    nir_metadata_preserve(impl, nir_metadata_dominance);
357 
358    return true;
359 }
360 
361 static void
lower_clip_in_gs_block(nir_builder * b,nir_block * block,nir_variable * position,nir_variable * clipvertex,nir_variable ** out,unsigned ucp_enables,bool use_clipdist_array,const gl_state_index16 clipplane_state_tokens[][STATE_LENGTH])362 lower_clip_in_gs_block(nir_builder *b, nir_block *block, nir_variable *position,
363                        nir_variable *clipvertex, nir_variable **out,
364                        unsigned ucp_enables, bool use_clipdist_array,
365                        const gl_state_index16 clipplane_state_tokens[][STATE_LENGTH])
366 {
367    nir_foreach_instr_safe(instr, block) {
368       if (instr->type != nir_instr_type_intrinsic)
369          continue;
370 
371       nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
372       switch (intrin->intrinsic) {
373       case nir_intrinsic_emit_vertex_with_counter:
374       case nir_intrinsic_emit_vertex:
375          b->cursor = nir_before_instr(instr);
376          lower_clip_outputs(b, position, clipvertex, out, ucp_enables, true,
377                             use_clipdist_array, clipplane_state_tokens);
378          break;
379       default:
380          /* not interesting; skip this */
381          break;
382       }
383    }
384 }
385 
386 /*
387  * GS lowering
388  */
389 
390 bool
nir_lower_clip_gs(nir_shader * shader,unsigned ucp_enables,bool use_clipdist_array,const gl_state_index16 clipplane_state_tokens[][STATE_LENGTH])391 nir_lower_clip_gs(nir_shader *shader, unsigned ucp_enables,
392                   bool use_clipdist_array,
393                   const gl_state_index16 clipplane_state_tokens[][STATE_LENGTH])
394 {
395    nir_function_impl *impl = nir_shader_get_entrypoint(shader);
396    nir_builder b;
397    nir_variable *position = NULL;
398    nir_variable *clipvertex = NULL;
399    nir_variable *out[2] = { NULL };
400 
401    if (!ucp_enables)
402       return false;
403 
404    /* find clipvertex/position outputs */
405    if (!find_clipvertex_and_position_outputs(shader, &clipvertex, &position))
406       return false;
407 
408    /* insert CLIPDIST outputs */
409    create_clipdist_vars(shader, out, ucp_enables, true,
410                         use_clipdist_array);
411 
412    nir_builder_init(&b, impl);
413 
414    nir_foreach_block(block, impl)
415       lower_clip_in_gs_block(&b, block, position, clipvertex, out,
416                              ucp_enables, use_clipdist_array,
417                              clipplane_state_tokens);
418 
419    nir_metadata_preserve(impl, nir_metadata_dominance);
420 
421    return true;
422 }
423 
424 /*
425  * FS lowering
426  */
427 
428 static void
lower_clip_fs(nir_function_impl * impl,unsigned ucp_enables,nir_variable ** in,bool use_clipdist_array)429 lower_clip_fs(nir_function_impl *impl, unsigned ucp_enables,
430               nir_variable **in, bool use_clipdist_array)
431 {
432    nir_ssa_def *clipdist[MAX_CLIP_PLANES];
433    nir_builder b;
434 
435    nir_builder_init(&b, impl);
436    b.cursor = nir_before_cf_list(&impl->body);
437 
438    if (!use_clipdist_array) {
439       if (ucp_enables & 0x0f)
440          load_clipdist_input(&b, in[0], 0, &clipdist[0]);
441       if (ucp_enables & 0xf0)
442          load_clipdist_input(&b, in[1], 0, &clipdist[4]);
443    } else {
444       if (ucp_enables & 0x0f)
445          load_clipdist_input(&b, in[0], 0, &clipdist[0]);
446       if (ucp_enables & 0xf0)
447          load_clipdist_input(&b, in[0], 1, &clipdist[4]);
448    }
449 
450    for (int plane = 0; plane < MAX_CLIP_PLANES; plane++) {
451       if (ucp_enables & (1 << plane)) {
452          nir_intrinsic_instr *discard;
453          nir_ssa_def *cond;
454 
455          cond = nir_flt(&b, clipdist[plane], nir_imm_float(&b, 0.0));
456 
457          discard = nir_intrinsic_instr_create(b.shader,
458                                               nir_intrinsic_discard_if);
459          discard->src[0] = nir_src_for_ssa(cond);
460          nir_builder_instr_insert(&b, &discard->instr);
461 
462          b.shader->info.fs.uses_discard = true;
463       }
464    }
465 
466    nir_metadata_preserve(impl, nir_metadata_dominance);
467 }
468 
469 static bool
fs_has_clip_dist_input_var(nir_shader * shader,nir_variable ** io_vars,unsigned * ucp_enables)470 fs_has_clip_dist_input_var(nir_shader *shader, nir_variable **io_vars,
471                             unsigned *ucp_enables)
472 {
473    assert(shader->info.stage == MESA_SHADER_FRAGMENT);
474    nir_foreach_shader_in_variable(var, shader) {
475       switch (var->data.location) {
476       case VARYING_SLOT_CLIP_DIST0:
477          assert(var->data.compact);
478          io_vars[0] = var;
479          *ucp_enables &= (1 << glsl_get_length(var->type)) - 1;
480          return true;
481       default:
482          break;
483       }
484    }
485    return false;
486 }
487 
488 /* insert conditional kill based on interpolated CLIPDIST
489  */
490 bool
nir_lower_clip_fs(nir_shader * shader,unsigned ucp_enables,bool use_clipdist_array)491 nir_lower_clip_fs(nir_shader *shader, unsigned ucp_enables,
492                   bool use_clipdist_array)
493 {
494    nir_variable *in[2] = {0};
495 
496    if (!ucp_enables)
497       return false;
498 
499    /* Fragment shaders can't read gl_ClipDistance[] in OpenGL so it will not
500     * have the variable defined, but Vulkan allows this, in which case the
501     * SPIR-V compiler would have already added it as a compact array.
502     */
503    if (!fs_has_clip_dist_input_var(shader, in, &ucp_enables))
504       create_clipdist_vars(shader, in, ucp_enables, false, use_clipdist_array);
505    else
506       assert(use_clipdist_array);
507 
508    nir_foreach_function(function, shader) {
509       if (!strcmp(function->name, "main"))
510          lower_clip_fs(function->impl, ucp_enables, in, use_clipdist_array);
511    }
512 
513    return true;
514 }
515