c9a2767b39331e6e7ee35c05d88f6e93bd7ca11a
[mesa.git] / src / mesa / drivers / dri / i965 / brw_nir.c
1 /*
2 * Copyright © 2014 Intel Corporation
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
24 #include "brw_nir.h"
25 #include "brw_shader.h"
26 #include "glsl/nir/glsl_to_nir.h"
27 #include "glsl/nir/nir_builder.h"
28 #include "program/prog_to_nir.h"
29
30 static bool
31 is_input(nir_intrinsic_instr *intrin)
32 {
33 return intrin->intrinsic == nir_intrinsic_load_input ||
34 intrin->intrinsic == nir_intrinsic_load_per_vertex_input;
35 }
36
37 static bool
38 is_output(nir_intrinsic_instr *intrin)
39 {
40 return intrin->intrinsic == nir_intrinsic_load_output ||
41 intrin->intrinsic == nir_intrinsic_load_per_vertex_output ||
42 intrin->intrinsic == nir_intrinsic_store_output ||
43 intrin->intrinsic == nir_intrinsic_store_per_vertex_output;
44 }
45
46 /**
47 * In many cases, we just add the base and offset together, so there's no
48 * reason to keep them separate. Sometimes, combining them is essential:
49 * if a shader only accesses part of a compound variable (such as a matrix
50 * or array), the variable's base may not actually exist in the VUE map.
51 *
52 * This pass adds constant offsets to instr->const_index[0], and resets
53 * the offset source to 0. Non-constant offsets remain unchanged - since
54 * we don't know what part of a compound variable is accessed, we allocate
55 * storage for the entire thing.
56 */
57 struct add_const_offset_to_base_params {
58 nir_builder b;
59 nir_variable_mode mode;
60 };
61
62 static bool
63 add_const_offset_to_base(nir_block *block, void *closure)
64 {
65 struct add_const_offset_to_base_params *params = closure;
66 nir_builder *b = &params->b;
67
68 nir_foreach_instr_safe(block, instr) {
69 if (instr->type != nir_instr_type_intrinsic)
70 continue;
71
72 nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
73
74 if ((params->mode == nir_var_shader_in && is_input(intrin)) ||
75 (params->mode == nir_var_shader_out && is_output(intrin))) {
76 nir_src *offset = nir_get_io_offset_src(intrin);
77 nir_const_value *const_offset = nir_src_as_const_value(*offset);
78
79 if (const_offset) {
80 intrin->const_index[0] += const_offset->u[0];
81 b->cursor = nir_before_instr(&intrin->instr);
82 nir_instr_rewrite_src(&intrin->instr, offset,
83 nir_src_for_ssa(nir_imm_int(b, 0)));
84 }
85 }
86 }
87 return true;
88
89 }
90
91 static bool
92 remap_vs_attrs(nir_block *block, void *closure)
93 {
94 GLbitfield64 inputs_read = *((GLbitfield64 *) closure);
95
96 nir_foreach_instr(block, instr) {
97 if (instr->type != nir_instr_type_intrinsic)
98 continue;
99
100 nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
101
102 if (intrin->intrinsic == nir_intrinsic_load_input) {
103 /* Attributes come in a contiguous block, ordered by their
104 * gl_vert_attrib value. That means we can compute the slot
105 * number for an attribute by masking out the enabled attributes
106 * before it and counting the bits.
107 */
108 int attr = intrin->const_index[0];
109 int slot = _mesa_bitcount_64(inputs_read & BITFIELD64_MASK(attr));
110
111 intrin->const_index[0] = 4 * slot;
112 }
113 }
114 return true;
115 }
116
117 static void
118 brw_nir_lower_inputs(nir_shader *nir,
119 const struct brw_device_info *devinfo,
120 bool is_scalar)
121 {
122 struct add_const_offset_to_base_params params = {
123 .mode = nir_var_shader_in
124 };
125
126 switch (nir->stage) {
127 case MESA_SHADER_VERTEX:
128 /* Start with the location of the variable's base. */
129 foreach_list_typed(nir_variable, var, node, &nir->inputs) {
130 var->data.driver_location = var->data.location;
131 }
132
133 /* Now use nir_lower_io to walk dereference chains. Attribute arrays
134 * are loaded as one vec4 per element (or matrix column), so we use
135 * type_size_vec4 here.
136 */
137 nir_lower_io(nir, nir_var_shader_in, type_size_vec4);
138
139 if (is_scalar) {
140 /* Finally, translate VERT_ATTRIB_* values into the actual registers.
141 *
142 * Note that we can use nir->info.inputs_read instead of
143 * key->inputs_read since the two are identical aside from Gen4-5
144 * edge flag differences.
145 */
146 GLbitfield64 inputs_read = nir->info.inputs_read;
147
148 /* This pass needs actual constants */
149 nir_opt_constant_folding(nir);
150
151 nir_foreach_overload(nir, overload) {
152 if (overload->impl) {
153 nir_builder_init(&params.b, overload->impl);
154 nir_foreach_block(overload->impl, add_const_offset_to_base, &params);
155 nir_foreach_block(overload->impl, remap_vs_attrs, &inputs_read);
156 }
157 }
158 }
159 break;
160 case MESA_SHADER_GEOMETRY: {
161 if (!is_scalar) {
162 foreach_list_typed(nir_variable, var, node, &nir->inputs) {
163 var->data.driver_location = var->data.location;
164 }
165 } else {
166 /* The GLSL linker will have already matched up GS inputs and
167 * the outputs of prior stages. The driver does extend VS outputs
168 * in some cases, but only for legacy OpenGL or Gen4-5 hardware,
169 * neither of which offer geometry shader support. So we can
170 * safely ignore that.
171 *
172 * For SSO pipelines, we use a fixed VUE map layout based on variable
173 * locations, so we can rely on rendezvous-by-location to make this
174 * work.
175 *
176 * However, we need to ignore VARYING_SLOT_PRIMITIVE_ID, as it's not
177 * written by previous stages and shows up via payload magic.
178 */
179 struct brw_vue_map input_vue_map;
180 GLbitfield64 inputs_read =
181 nir->info.inputs_read & ~VARYING_BIT_PRIMITIVE_ID;
182 brw_compute_vue_map(devinfo, &input_vue_map, inputs_read,
183 nir->info.separate_shader);
184
185 /* Start with the slot for the variable's base. */
186 foreach_list_typed(nir_variable, var, node, &nir->inputs) {
187 assert(input_vue_map.varying_to_slot[var->data.location] != -1);
188 var->data.driver_location =
189 input_vue_map.varying_to_slot[var->data.location];
190 }
191
192 /* Inputs are stored in vec4 slots, so use type_size_vec4(). */
193 nir_lower_io(nir, nir_var_shader_in, type_size_vec4);
194 }
195 break;
196 }
197 case MESA_SHADER_FRAGMENT:
198 assert(is_scalar);
199 nir_assign_var_locations(&nir->inputs, &nir->num_inputs,
200 type_size_scalar);
201 break;
202 case MESA_SHADER_COMPUTE:
203 /* Compute shaders have no inputs. */
204 assert(exec_list_is_empty(&nir->inputs));
205 break;
206 default:
207 unreachable("unsupported shader stage");
208 }
209 }
210
211 static void
212 brw_nir_lower_outputs(nir_shader *nir, bool is_scalar)
213 {
214 switch (nir->stage) {
215 case MESA_SHADER_VERTEX:
216 case MESA_SHADER_GEOMETRY:
217 if (is_scalar) {
218 nir_assign_var_locations(&nir->outputs, &nir->num_outputs,
219 type_size_vec4_times_4);
220 nir_lower_io(nir, nir_var_shader_out, type_size_vec4_times_4);
221 } else {
222 nir_foreach_variable(var, &nir->outputs)
223 var->data.driver_location = var->data.location;
224 }
225 break;
226 case MESA_SHADER_FRAGMENT:
227 nir_assign_var_locations(&nir->outputs, &nir->num_outputs,
228 type_size_scalar);
229 break;
230 case MESA_SHADER_COMPUTE:
231 /* Compute shaders have no outputs. */
232 assert(exec_list_is_empty(&nir->outputs));
233 break;
234 default:
235 unreachable("unsupported shader stage");
236 }
237 }
238
239 static int
240 type_size_scalar_bytes(const struct glsl_type *type)
241 {
242 return type_size_scalar(type) * 4;
243 }
244
245 static int
246 type_size_vec4_bytes(const struct glsl_type *type)
247 {
248 return type_size_vec4(type) * 16;
249 }
250
251 static void
252 brw_nir_lower_uniforms(nir_shader *nir, bool is_scalar)
253 {
254 if (is_scalar) {
255 nir_assign_var_locations(&nir->uniforms, &nir->num_uniforms,
256 type_size_scalar_bytes);
257 nir_lower_io(nir, nir_var_uniform, type_size_scalar_bytes);
258 } else {
259 nir_assign_var_locations(&nir->uniforms, &nir->num_uniforms,
260 type_size_vec4_bytes);
261 nir_lower_io(nir, nir_var_uniform, type_size_vec4_bytes);
262 }
263 }
264
265 #include "util/debug.h"
266
267 static bool
268 should_clone_nir()
269 {
270 static int should_clone = -1;
271 if (should_clone < 1)
272 should_clone = env_var_as_boolean("NIR_TEST_CLONE", false);
273
274 return should_clone;
275 }
276
277 #define _OPT(do_pass) (({ \
278 bool this_progress = true; \
279 do_pass \
280 nir_validate_shader(nir); \
281 if (should_clone_nir()) { \
282 nir_shader *clone = nir_shader_clone(ralloc_parent(nir), nir); \
283 ralloc_free(nir); \
284 nir = clone; \
285 } \
286 this_progress; \
287 }))
288
289 #define OPT(pass, ...) _OPT( \
290 nir_metadata_set_validation_flag(nir); \
291 this_progress = pass(nir ,##__VA_ARGS__); \
292 if (this_progress) { \
293 progress = true; \
294 nir_metadata_check_validation_flag(nir); \
295 } \
296 )
297
298 #define OPT_V(pass, ...) _OPT( \
299 pass(nir, ##__VA_ARGS__); \
300 )
301
302 static nir_shader *
303 nir_optimize(nir_shader *nir, bool is_scalar)
304 {
305 bool progress;
306 do {
307 progress = false;
308 OPT_V(nir_lower_vars_to_ssa);
309
310 if (is_scalar) {
311 OPT_V(nir_lower_alu_to_scalar);
312 }
313
314 OPT(nir_copy_prop);
315
316 if (is_scalar) {
317 OPT_V(nir_lower_phis_to_scalar);
318 }
319
320 OPT(nir_copy_prop);
321 OPT(nir_opt_dce);
322 OPT(nir_opt_cse);
323 OPT(nir_opt_peephole_select);
324 OPT(nir_opt_algebraic);
325 OPT(nir_opt_constant_folding);
326 OPT(nir_opt_dead_cf);
327 OPT(nir_opt_remove_phis);
328 OPT(nir_opt_undef);
329 } while (progress);
330
331 return nir;
332 }
333
334 /* Does some simple lowering and runs the standard suite of optimizations
335 *
336 * This is intended to be called more-or-less directly after you get the
337 * shader out of GLSL or some other source. While it is geared towards i965,
338 * it is not at all generator-specific except for the is_scalar flag. Even
339 * there, it is safe to call with is_scalar = false for a shader that is
340 * intended for the FS backend as long as nir_optimize is called again with
341 * is_scalar = true to scalarize everything prior to code gen.
342 */
343 nir_shader *
344 brw_preprocess_nir(nir_shader *nir, bool is_scalar)
345 {
346 bool progress; /* Written by OPT and OPT_V */
347 (void)progress;
348
349 if (nir->stage == MESA_SHADER_GEOMETRY)
350 OPT(nir_lower_gs_intrinsics);
351
352 static const nir_lower_tex_options tex_options = {
353 .lower_txp = ~0,
354 };
355
356 OPT(nir_lower_tex, &tex_options);
357 OPT(nir_normalize_cubemap_coords);
358
359 OPT(nir_lower_global_vars_to_local);
360
361 OPT(nir_split_var_copies);
362
363 nir = nir_optimize(nir, is_scalar);
364
365 /* Lower a bunch of stuff */
366 OPT_V(nir_lower_var_copies);
367
368 /* Get rid of split copies */
369 nir = nir_optimize(nir, is_scalar);
370
371 OPT(nir_remove_dead_variables);
372
373 return nir;
374 }
375
376 /* Lowers inputs, outputs, uniforms, and samplers for i965
377 *
378 * This function does all of the standard lowering prior to post-processing.
379 * The lowering done is highly gen, stage, and backend-specific. The
380 * shader_prog parameter is optional and is used only for lowering sampler
381 * derefs and atomics for GLSL shaders.
382 */
383 nir_shader *
384 brw_lower_nir(nir_shader *nir,
385 const struct brw_device_info *devinfo,
386 const struct gl_shader_program *shader_prog,
387 bool is_scalar)
388 {
389 bool progress; /* Written by OPT and OPT_V */
390 (void)progress;
391
392 OPT_V(brw_nir_lower_inputs, devinfo, is_scalar);
393 OPT_V(brw_nir_lower_outputs, is_scalar);
394 OPT_V(brw_nir_lower_uniforms, is_scalar);
395 OPT_V(nir_lower_io, nir_var_all, is_scalar ? type_size_scalar : type_size_vec4);
396
397 if (shader_prog) {
398 OPT_V(nir_lower_samplers, shader_prog);
399 }
400
401 OPT(nir_lower_system_values);
402
403 if (shader_prog) {
404 OPT_V(nir_lower_atomics, shader_prog);
405 }
406
407 return nir_optimize(nir, is_scalar);
408 }
409
410 /* Prepare the given shader for codegen
411 *
412 * This function is intended to be called right before going into the actual
413 * backend and is highly backend-specific. Also, once this function has been
414 * called on a shader, it will no longer be in SSA form so most optimizations
415 * will not work.
416 */
417 nir_shader *
418 brw_postprocess_nir(nir_shader *nir,
419 const struct brw_device_info *devinfo,
420 bool is_scalar)
421 {
422 bool debug_enabled =
423 (INTEL_DEBUG & intel_debug_flag_for_shader_stage(nir->stage));
424
425 bool progress; /* Written by OPT and OPT_V */
426 (void)progress;
427
428 if (devinfo->gen >= 6) {
429 /* Try and fuse multiply-adds */
430 OPT(brw_nir_opt_peephole_ffma);
431 }
432
433 OPT(nir_opt_algebraic_late);
434
435 OPT(nir_lower_locals_to_regs);
436
437 OPT_V(nir_lower_to_source_mods);
438 OPT(nir_copy_prop);
439 OPT(nir_opt_dce);
440
441 if (unlikely(debug_enabled)) {
442 /* Re-index SSA defs so we print more sensible numbers. */
443 nir_foreach_overload(nir, overload) {
444 if (overload->impl)
445 nir_index_ssa_defs(overload->impl);
446 }
447
448 fprintf(stderr, "NIR (SSA form) for %s shader:\n",
449 _mesa_shader_stage_to_string(nir->stage));
450 nir_print_shader(nir, stderr);
451 }
452
453 OPT_V(nir_convert_from_ssa, true);
454
455 if (!is_scalar) {
456 OPT_V(nir_move_vec_src_uses_to_dest);
457 OPT(nir_lower_vec_to_movs);
458 }
459
460 /* This is the last pass we run before we start emitting stuff. It
461 * determines when we need to insert boolean resolves on Gen <= 5. We
462 * run it last because it stashes data in instr->pass_flags and we don't
463 * want that to be squashed by other NIR passes.
464 */
465 if (devinfo->gen <= 5)
466 brw_nir_analyze_boolean_resolves(nir);
467
468 nir_sweep(nir);
469
470 if (unlikely(debug_enabled)) {
471 fprintf(stderr, "NIR (final form) for %s shader:\n",
472 _mesa_shader_stage_to_string(nir->stage));
473 nir_print_shader(nir, stderr);
474 }
475
476 return nir;
477 }
478
479 nir_shader *
480 brw_create_nir(struct brw_context *brw,
481 const struct gl_shader_program *shader_prog,
482 const struct gl_program *prog,
483 gl_shader_stage stage,
484 bool is_scalar)
485 {
486 struct gl_context *ctx = &brw->ctx;
487 const struct brw_device_info *devinfo = brw->intelScreen->devinfo;
488 const nir_shader_compiler_options *options =
489 ctx->Const.ShaderCompilerOptions[stage].NirOptions;
490 bool progress;
491 nir_shader *nir;
492
493 /* First, lower the GLSL IR or Mesa IR to NIR */
494 if (shader_prog) {
495 nir = glsl_to_nir(shader_prog, stage, options);
496 } else {
497 nir = prog_to_nir(prog, options);
498 OPT_V(nir_convert_to_ssa); /* turn registers into SSA */
499 }
500 nir_validate_shader(nir);
501
502 (void)progress;
503
504 nir = brw_preprocess_nir(nir, is_scalar);
505 nir = brw_lower_nir(nir, devinfo, shader_prog, is_scalar);
506
507 return nir;
508 }
509
510 nir_shader *
511 brw_nir_apply_sampler_key(nir_shader *nir,
512 const struct brw_device_info *devinfo,
513 const struct brw_sampler_prog_key_data *key_tex,
514 bool is_scalar)
515 {
516 nir_lower_tex_options tex_options = { 0 };
517
518 /* Iron Lake and prior require lowering of all rectangle textures */
519 if (devinfo->gen < 6)
520 tex_options.lower_rect = true;
521
522 /* Prior to Broadwell, our hardware can't actually do GL_CLAMP */
523 if (devinfo->gen < 8) {
524 tex_options.saturate_s = key_tex->gl_clamp_mask[0];
525 tex_options.saturate_t = key_tex->gl_clamp_mask[1];
526 tex_options.saturate_r = key_tex->gl_clamp_mask[2];
527 }
528
529 /* Prior to Haswell, we have to fake texture swizzle */
530 for (unsigned s = 0; s < MAX_SAMPLERS; s++) {
531 if (key_tex->swizzles[s] == SWIZZLE_NOOP)
532 continue;
533
534 tex_options.swizzle_result |= (1 << s);
535 for (unsigned c = 0; c < 4; c++)
536 tex_options.swizzles[s][c] = GET_SWZ(key_tex->swizzles[s], c);
537 }
538
539 if (nir_lower_tex(nir, &tex_options)) {
540 nir_validate_shader(nir);
541 nir = nir_optimize(nir, is_scalar);
542 }
543
544 return nir;
545 }
546
547 enum brw_reg_type
548 brw_type_for_nir_type(nir_alu_type type)
549 {
550 switch (type) {
551 case nir_type_uint:
552 return BRW_REGISTER_TYPE_UD;
553 case nir_type_bool:
554 case nir_type_int:
555 return BRW_REGISTER_TYPE_D;
556 case nir_type_float:
557 return BRW_REGISTER_TYPE_F;
558 default:
559 unreachable("unknown type");
560 }
561
562 return BRW_REGISTER_TYPE_F;
563 }
564
565 /* Returns the glsl_base_type corresponding to a nir_alu_type.
566 * This is used by both brw_vec4_nir and brw_fs_nir.
567 */
568 enum glsl_base_type
569 brw_glsl_base_type_for_nir_type(nir_alu_type type)
570 {
571 switch (type) {
572 case nir_type_float:
573 return GLSL_TYPE_FLOAT;
574
575 case nir_type_int:
576 return GLSL_TYPE_INT;
577
578 case nir_type_uint:
579 return GLSL_TYPE_UINT;
580
581 default:
582 unreachable("bad type");
583 }
584 }