OSDN Git Service

intel/fs: Support min_lod parameters on texture instructions
[android-x86/external-mesa.git] / src / intel / compiler / brw_fs_nir.cpp
1 /*
2  * Copyright © 2010 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 "compiler/glsl/ir.h"
25 #include "brw_fs.h"
26 #include "brw_fs_surface_builder.h"
27 #include "brw_nir.h"
28 #include "util/u_math.h"
29 #include "util/bitscan.h"
30
31 using namespace brw;
32 using namespace brw::surface_access;
33
34 void
35 fs_visitor::emit_nir_code()
36 {
37    /* emit the arrays used for inputs and outputs - load/store intrinsics will
38     * be converted to reads/writes of these arrays
39     */
40    nir_setup_outputs();
41    nir_setup_uniforms();
42    nir_emit_system_values();
43
44    nir_emit_impl(nir_shader_get_entrypoint((nir_shader *)nir));
45 }
46
47 void
48 fs_visitor::nir_setup_outputs()
49 {
50    if (stage == MESA_SHADER_TESS_CTRL || stage == MESA_SHADER_FRAGMENT)
51       return;
52
53    unsigned vec4s[VARYING_SLOT_TESS_MAX] = { 0, };
54
55    /* Calculate the size of output registers in a separate pass, before
56     * allocating them.  With ARB_enhanced_layouts, multiple output variables
57     * may occupy the same slot, but have different type sizes.
58     */
59    nir_foreach_variable(var, &nir->outputs) {
60       const int loc = var->data.driver_location;
61       const unsigned var_vec4s =
62          var->data.compact ? DIV_ROUND_UP(glsl_get_length(var->type), 4)
63                            : type_size_vec4(var->type);
64       vec4s[loc] = MAX2(vec4s[loc], var_vec4s);
65    }
66
67    for (unsigned loc = 0; loc < ARRAY_SIZE(vec4s);) {
68       if (vec4s[loc] == 0) {
69          loc++;
70          continue;
71       }
72
73       unsigned reg_size = vec4s[loc];
74
75       /* Check if there are any ranges that start within this range and extend
76        * past it. If so, include them in this allocation.
77        */
78       for (unsigned i = 1; i < reg_size; i++)
79          reg_size = MAX2(vec4s[i + loc] + i, reg_size);
80
81       fs_reg reg = bld.vgrf(BRW_REGISTER_TYPE_F, 4 * reg_size);
82       for (unsigned i = 0; i < reg_size; i++)
83          outputs[loc + i] = offset(reg, bld, 4 * i);
84
85       loc += reg_size;
86    }
87 }
88
89 void
90 fs_visitor::nir_setup_uniforms()
91 {
92    /* Only the first compile gets to set up uniforms. */
93    if (push_constant_loc) {
94       assert(pull_constant_loc);
95       return;
96    }
97
98    uniforms = nir->num_uniforms / 4;
99
100    if (stage == MESA_SHADER_COMPUTE) {
101       /* Add a uniform for the thread local id.  It must be the last uniform
102        * on the list.
103        */
104       assert(uniforms == prog_data->nr_params);
105       uint32_t *param = brw_stage_prog_data_add_params(prog_data, 1);
106       *param = BRW_PARAM_BUILTIN_SUBGROUP_ID;
107       subgroup_id = fs_reg(UNIFORM, uniforms++, BRW_REGISTER_TYPE_UD);
108    }
109 }
110
111 static bool
112 emit_system_values_block(nir_block *block, fs_visitor *v)
113 {
114    fs_reg *reg;
115
116    nir_foreach_instr(instr, block) {
117       if (instr->type != nir_instr_type_intrinsic)
118          continue;
119
120       nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
121       switch (intrin->intrinsic) {
122       case nir_intrinsic_load_vertex_id:
123       case nir_intrinsic_load_base_vertex:
124          unreachable("should be lowered by nir_lower_system_values().");
125
126       case nir_intrinsic_load_vertex_id_zero_base:
127       case nir_intrinsic_load_is_indexed_draw:
128       case nir_intrinsic_load_first_vertex:
129       case nir_intrinsic_load_instance_id:
130       case nir_intrinsic_load_base_instance:
131       case nir_intrinsic_load_draw_id:
132          unreachable("should be lowered by brw_nir_lower_vs_inputs().");
133
134       case nir_intrinsic_load_invocation_id:
135          if (v->stage == MESA_SHADER_TESS_CTRL)
136             break;
137          assert(v->stage == MESA_SHADER_GEOMETRY);
138          reg = &v->nir_system_values[SYSTEM_VALUE_INVOCATION_ID];
139          if (reg->file == BAD_FILE) {
140             const fs_builder abld = v->bld.annotate("gl_InvocationID", NULL);
141             fs_reg g1(retype(brw_vec8_grf(1, 0), BRW_REGISTER_TYPE_UD));
142             fs_reg iid = abld.vgrf(BRW_REGISTER_TYPE_UD, 1);
143             abld.SHR(iid, g1, brw_imm_ud(27u));
144             *reg = iid;
145          }
146          break;
147
148       case nir_intrinsic_load_sample_pos:
149          assert(v->stage == MESA_SHADER_FRAGMENT);
150          reg = &v->nir_system_values[SYSTEM_VALUE_SAMPLE_POS];
151          if (reg->file == BAD_FILE)
152             *reg = *v->emit_samplepos_setup();
153          break;
154
155       case nir_intrinsic_load_sample_id:
156          assert(v->stage == MESA_SHADER_FRAGMENT);
157          reg = &v->nir_system_values[SYSTEM_VALUE_SAMPLE_ID];
158          if (reg->file == BAD_FILE)
159             *reg = *v->emit_sampleid_setup();
160          break;
161
162       case nir_intrinsic_load_sample_mask_in:
163          assert(v->stage == MESA_SHADER_FRAGMENT);
164          assert(v->devinfo->gen >= 7);
165          reg = &v->nir_system_values[SYSTEM_VALUE_SAMPLE_MASK_IN];
166          if (reg->file == BAD_FILE)
167             *reg = *v->emit_samplemaskin_setup();
168          break;
169
170       case nir_intrinsic_load_work_group_id:
171          assert(v->stage == MESA_SHADER_COMPUTE);
172          reg = &v->nir_system_values[SYSTEM_VALUE_WORK_GROUP_ID];
173          if (reg->file == BAD_FILE)
174             *reg = *v->emit_cs_work_group_id_setup();
175          break;
176
177       case nir_intrinsic_load_helper_invocation:
178          assert(v->stage == MESA_SHADER_FRAGMENT);
179          reg = &v->nir_system_values[SYSTEM_VALUE_HELPER_INVOCATION];
180          if (reg->file == BAD_FILE) {
181             const fs_builder abld =
182                v->bld.annotate("gl_HelperInvocation", NULL);
183
184             /* On Gen6+ (gl_HelperInvocation is only exposed on Gen7+) the
185              * pixel mask is in g1.7 of the thread payload.
186              *
187              * We move the per-channel pixel enable bit to the low bit of each
188              * channel by shifting the byte containing the pixel mask by the
189              * vector immediate 0x76543210UV.
190              *
191              * The region of <1,8,0> reads only 1 byte (the pixel masks for
192              * subspans 0 and 1) in SIMD8 and an additional byte (the pixel
193              * masks for 2 and 3) in SIMD16.
194              */
195             fs_reg shifted = abld.vgrf(BRW_REGISTER_TYPE_UW, 1);
196
197             for (unsigned i = 0; i < DIV_ROUND_UP(v->dispatch_width, 16); i++) {
198                const fs_builder hbld = abld.group(MIN2(16, v->dispatch_width), i);
199                hbld.SHR(offset(shifted, hbld, i),
200                         stride(retype(brw_vec1_grf(1 + i, 7),
201                                       BRW_REGISTER_TYPE_UB),
202                                1, 8, 0),
203                         brw_imm_v(0x76543210));
204             }
205
206             /* A set bit in the pixel mask means the channel is enabled, but
207              * that is the opposite of gl_HelperInvocation so we need to invert
208              * the mask.
209              *
210              * The negate source-modifier bit of logical instructions on Gen8+
211              * performs 1's complement negation, so we can use that instead of
212              * a NOT instruction.
213              */
214             fs_reg inverted = negate(shifted);
215             if (v->devinfo->gen < 8) {
216                inverted = abld.vgrf(BRW_REGISTER_TYPE_UW);
217                abld.NOT(inverted, shifted);
218             }
219
220             /* We then resolve the 0/1 result to 0/~0 boolean values by ANDing
221              * with 1 and negating.
222              */
223             fs_reg anded = abld.vgrf(BRW_REGISTER_TYPE_UD, 1);
224             abld.AND(anded, inverted, brw_imm_uw(1));
225
226             fs_reg dst = abld.vgrf(BRW_REGISTER_TYPE_D, 1);
227             abld.MOV(dst, negate(retype(anded, BRW_REGISTER_TYPE_D)));
228             *reg = dst;
229          }
230          break;
231
232       default:
233          break;
234       }
235    }
236
237    return true;
238 }
239
240 void
241 fs_visitor::nir_emit_system_values()
242 {
243    nir_system_values = ralloc_array(mem_ctx, fs_reg, SYSTEM_VALUE_MAX);
244    for (unsigned i = 0; i < SYSTEM_VALUE_MAX; i++) {
245       nir_system_values[i] = fs_reg();
246    }
247
248    /* Always emit SUBGROUP_INVOCATION.  Dead code will clean it up if we
249     * never end up using it.
250     */
251    {
252       const fs_builder abld = bld.annotate("gl_SubgroupInvocation", NULL);
253       fs_reg &reg = nir_system_values[SYSTEM_VALUE_SUBGROUP_INVOCATION];
254       reg = abld.vgrf(BRW_REGISTER_TYPE_UW);
255
256       const fs_builder allbld8 = abld.group(8, 0).exec_all();
257       allbld8.MOV(reg, brw_imm_v(0x76543210));
258       if (dispatch_width > 8)
259          allbld8.ADD(byte_offset(reg, 16), reg, brw_imm_uw(8u));
260       if (dispatch_width > 16) {
261          const fs_builder allbld16 = abld.group(16, 0).exec_all();
262          allbld16.ADD(byte_offset(reg, 32), reg, brw_imm_uw(16u));
263       }
264    }
265
266    nir_function_impl *impl = nir_shader_get_entrypoint((nir_shader *)nir);
267    nir_foreach_block(block, impl)
268       emit_system_values_block(block, this);
269 }
270
271 /*
272  * Returns a type based on a reference_type (word, float, half-float) and a
273  * given bit_size.
274  *
275  * Reference BRW_REGISTER_TYPE are HF,F,DF,W,D,UW,UD.
276  *
277  * @FIXME: 64-bit return types are always DF on integer types to maintain
278  * compability with uses of DF previously to the introduction of int64
279  * support.
280  */
281 static brw_reg_type
282 brw_reg_type_from_bit_size(const unsigned bit_size,
283                            const brw_reg_type reference_type)
284 {
285    switch(reference_type) {
286    case BRW_REGISTER_TYPE_HF:
287    case BRW_REGISTER_TYPE_F:
288    case BRW_REGISTER_TYPE_DF:
289       switch(bit_size) {
290       case 16:
291          return BRW_REGISTER_TYPE_HF;
292       case 32:
293          return BRW_REGISTER_TYPE_F;
294       case 64:
295          return BRW_REGISTER_TYPE_DF;
296       default:
297          unreachable("Invalid bit size");
298       }
299    case BRW_REGISTER_TYPE_B:
300    case BRW_REGISTER_TYPE_W:
301    case BRW_REGISTER_TYPE_D:
302    case BRW_REGISTER_TYPE_Q:
303       switch(bit_size) {
304       case 8:
305          return BRW_REGISTER_TYPE_B;
306       case 16:
307          return BRW_REGISTER_TYPE_W;
308       case 32:
309          return BRW_REGISTER_TYPE_D;
310       case 64:
311          return BRW_REGISTER_TYPE_Q;
312       default:
313          unreachable("Invalid bit size");
314       }
315    case BRW_REGISTER_TYPE_UB:
316    case BRW_REGISTER_TYPE_UW:
317    case BRW_REGISTER_TYPE_UD:
318    case BRW_REGISTER_TYPE_UQ:
319       switch(bit_size) {
320       case 8:
321          return BRW_REGISTER_TYPE_UB;
322       case 16:
323          return BRW_REGISTER_TYPE_UW;
324       case 32:
325          return BRW_REGISTER_TYPE_UD;
326       case 64:
327          return BRW_REGISTER_TYPE_UQ;
328       default:
329          unreachable("Invalid bit size");
330       }
331    default:
332       unreachable("Unknown type");
333    }
334 }
335
336 void
337 fs_visitor::nir_emit_impl(nir_function_impl *impl)
338 {
339    nir_locals = ralloc_array(mem_ctx, fs_reg, impl->reg_alloc);
340    for (unsigned i = 0; i < impl->reg_alloc; i++) {
341       nir_locals[i] = fs_reg();
342    }
343
344    foreach_list_typed(nir_register, reg, node, &impl->registers) {
345       unsigned array_elems =
346          reg->num_array_elems == 0 ? 1 : reg->num_array_elems;
347       unsigned size = array_elems * reg->num_components;
348       const brw_reg_type reg_type =
349          brw_reg_type_from_bit_size(reg->bit_size, BRW_REGISTER_TYPE_F);
350       nir_locals[reg->index] = bld.vgrf(reg_type, size);
351    }
352
353    nir_ssa_values = reralloc(mem_ctx, nir_ssa_values, fs_reg,
354                              impl->ssa_alloc);
355
356    nir_emit_cf_list(&impl->body);
357 }
358
359 void
360 fs_visitor::nir_emit_cf_list(exec_list *list)
361 {
362    exec_list_validate(list);
363    foreach_list_typed(nir_cf_node, node, node, list) {
364       switch (node->type) {
365       case nir_cf_node_if:
366          nir_emit_if(nir_cf_node_as_if(node));
367          break;
368
369       case nir_cf_node_loop:
370          nir_emit_loop(nir_cf_node_as_loop(node));
371          break;
372
373       case nir_cf_node_block:
374          nir_emit_block(nir_cf_node_as_block(node));
375          break;
376
377       default:
378          unreachable("Invalid CFG node block");
379       }
380    }
381 }
382
383 void
384 fs_visitor::nir_emit_if(nir_if *if_stmt)
385 {
386    /* first, put the condition into f0 */
387    fs_inst *inst = bld.MOV(bld.null_reg_d(),
388                             retype(get_nir_src(if_stmt->condition),
389                                    BRW_REGISTER_TYPE_D));
390    inst->conditional_mod = BRW_CONDITIONAL_NZ;
391
392    bld.IF(BRW_PREDICATE_NORMAL);
393
394    nir_emit_cf_list(&if_stmt->then_list);
395
396    /* note: if the else is empty, dead CF elimination will remove it */
397    bld.emit(BRW_OPCODE_ELSE);
398
399    nir_emit_cf_list(&if_stmt->else_list);
400
401    bld.emit(BRW_OPCODE_ENDIF);
402
403    if (devinfo->gen < 7)
404       limit_dispatch_width(16, "Non-uniform control flow unsupported "
405                            "in SIMD32 mode.");
406 }
407
408 void
409 fs_visitor::nir_emit_loop(nir_loop *loop)
410 {
411    bld.emit(BRW_OPCODE_DO);
412
413    nir_emit_cf_list(&loop->body);
414
415    bld.emit(BRW_OPCODE_WHILE);
416
417    if (devinfo->gen < 7)
418       limit_dispatch_width(16, "Non-uniform control flow unsupported "
419                            "in SIMD32 mode.");
420 }
421
422 void
423 fs_visitor::nir_emit_block(nir_block *block)
424 {
425    nir_foreach_instr(instr, block) {
426       nir_emit_instr(instr);
427    }
428 }
429
430 void
431 fs_visitor::nir_emit_instr(nir_instr *instr)
432 {
433    const fs_builder abld = bld.annotate(NULL, instr);
434
435    switch (instr->type) {
436    case nir_instr_type_alu:
437       nir_emit_alu(abld, nir_instr_as_alu(instr));
438       break;
439
440    case nir_instr_type_deref:
441       /* Derefs can exist for images but they do nothing */
442       break;
443
444    case nir_instr_type_intrinsic:
445       switch (stage) {
446       case MESA_SHADER_VERTEX:
447          nir_emit_vs_intrinsic(abld, nir_instr_as_intrinsic(instr));
448          break;
449       case MESA_SHADER_TESS_CTRL:
450          nir_emit_tcs_intrinsic(abld, nir_instr_as_intrinsic(instr));
451          break;
452       case MESA_SHADER_TESS_EVAL:
453          nir_emit_tes_intrinsic(abld, nir_instr_as_intrinsic(instr));
454          break;
455       case MESA_SHADER_GEOMETRY:
456          nir_emit_gs_intrinsic(abld, nir_instr_as_intrinsic(instr));
457          break;
458       case MESA_SHADER_FRAGMENT:
459          nir_emit_fs_intrinsic(abld, nir_instr_as_intrinsic(instr));
460          break;
461       case MESA_SHADER_COMPUTE:
462          nir_emit_cs_intrinsic(abld, nir_instr_as_intrinsic(instr));
463          break;
464       default:
465          unreachable("unsupported shader stage");
466       }
467       break;
468
469    case nir_instr_type_tex:
470       nir_emit_texture(abld, nir_instr_as_tex(instr));
471       break;
472
473    case nir_instr_type_load_const:
474       nir_emit_load_const(abld, nir_instr_as_load_const(instr));
475       break;
476
477    case nir_instr_type_ssa_undef:
478       /* We create a new VGRF for undefs on every use (by handling
479        * them in get_nir_src()), rather than for each definition.
480        * This helps register coalescing eliminate MOVs from undef.
481        */
482       break;
483
484    case nir_instr_type_jump:
485       nir_emit_jump(abld, nir_instr_as_jump(instr));
486       break;
487
488    default:
489       unreachable("unknown instruction type");
490    }
491 }
492
493 /**
494  * Recognizes a parent instruction of nir_op_extract_* and changes the type to
495  * match instr.
496  */
497 bool
498 fs_visitor::optimize_extract_to_float(nir_alu_instr *instr,
499                                       const fs_reg &result)
500 {
501    if (!instr->src[0].src.is_ssa ||
502        !instr->src[0].src.ssa->parent_instr)
503       return false;
504
505    if (instr->src[0].src.ssa->parent_instr->type != nir_instr_type_alu)
506       return false;
507
508    nir_alu_instr *src0 =
509       nir_instr_as_alu(instr->src[0].src.ssa->parent_instr);
510
511    if (src0->op != nir_op_extract_u8 && src0->op != nir_op_extract_u16 &&
512        src0->op != nir_op_extract_i8 && src0->op != nir_op_extract_i16)
513       return false;
514
515    unsigned element = nir_src_as_uint(src0->src[1].src);
516
517    /* Element type to extract.*/
518    const brw_reg_type type = brw_int_type(
519       src0->op == nir_op_extract_u16 || src0->op == nir_op_extract_i16 ? 2 : 1,
520       src0->op == nir_op_extract_i16 || src0->op == nir_op_extract_i8);
521
522    fs_reg op0 = get_nir_src(src0->src[0].src);
523    op0.type = brw_type_for_nir_type(devinfo,
524       (nir_alu_type)(nir_op_infos[src0->op].input_types[0] |
525                      nir_src_bit_size(src0->src[0].src)));
526    op0 = offset(op0, bld, src0->src[0].swizzle[0]);
527
528    set_saturate(instr->dest.saturate,
529                 bld.MOV(result, subscript(op0, type, element)));
530    return true;
531 }
532
533 bool
534 fs_visitor::optimize_frontfacing_ternary(nir_alu_instr *instr,
535                                          const fs_reg &result)
536 {
537    if (!instr->src[0].src.is_ssa ||
538        instr->src[0].src.ssa->parent_instr->type != nir_instr_type_intrinsic)
539       return false;
540
541    nir_intrinsic_instr *src0 =
542       nir_instr_as_intrinsic(instr->src[0].src.ssa->parent_instr);
543
544    if (src0->intrinsic != nir_intrinsic_load_front_face)
545       return false;
546
547    if (!nir_src_is_const(instr->src[1].src) ||
548        !nir_src_is_const(instr->src[2].src))
549       return false;
550
551    const float value1 = nir_src_as_float(instr->src[1].src);
552    const float value2 = nir_src_as_float(instr->src[2].src);
553    if (fabsf(value1) != 1.0f || fabsf(value2) != 1.0f)
554       return false;
555
556    /* nir_opt_algebraic should have gotten rid of bcsel(b, a, a) */
557    assert(value1 == -value2);
558
559    fs_reg tmp = vgrf(glsl_type::int_type);
560
561    if (devinfo->gen >= 6) {
562       /* Bit 15 of g0.0 is 0 if the polygon is front facing. */
563       fs_reg g0 = fs_reg(retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_W));
564
565       /* For (gl_FrontFacing ? 1.0 : -1.0), emit:
566        *
567        *    or(8)  tmp.1<2>W  g0.0<0,1,0>W  0x00003f80W
568        *    and(8) dst<1>D    tmp<8,8,1>D   0xbf800000D
569        *
570        * and negate g0.0<0,1,0>W for (gl_FrontFacing ? -1.0 : 1.0).
571        *
572        * This negation looks like it's safe in practice, because bits 0:4 will
573        * surely be TRIANGLES
574        */
575
576       if (value1 == -1.0f) {
577          g0.negate = true;
578       }
579
580       bld.OR(subscript(tmp, BRW_REGISTER_TYPE_W, 1),
581              g0, brw_imm_uw(0x3f80));
582    } else {
583       /* Bit 31 of g1.6 is 0 if the polygon is front facing. */
584       fs_reg g1_6 = fs_reg(retype(brw_vec1_grf(1, 6), BRW_REGISTER_TYPE_D));
585
586       /* For (gl_FrontFacing ? 1.0 : -1.0), emit:
587        *
588        *    or(8)  tmp<1>D  g1.6<0,1,0>D  0x3f800000D
589        *    and(8) dst<1>D  tmp<8,8,1>D   0xbf800000D
590        *
591        * and negate g1.6<0,1,0>D for (gl_FrontFacing ? -1.0 : 1.0).
592        *
593        * This negation looks like it's safe in practice, because bits 0:4 will
594        * surely be TRIANGLES
595        */
596
597       if (value1 == -1.0f) {
598          g1_6.negate = true;
599       }
600
601       bld.OR(tmp, g1_6, brw_imm_d(0x3f800000));
602    }
603    bld.AND(retype(result, BRW_REGISTER_TYPE_D), tmp, brw_imm_d(0xbf800000));
604
605    return true;
606 }
607
608 static void
609 emit_find_msb_using_lzd(const fs_builder &bld,
610                         const fs_reg &result,
611                         const fs_reg &src,
612                         bool is_signed)
613 {
614    fs_inst *inst;
615    fs_reg temp = src;
616
617    if (is_signed) {
618       /* LZD of an absolute value source almost always does the right
619        * thing.  There are two problem values:
620        *
621        * * 0x80000000.  Since abs(0x80000000) == 0x80000000, LZD returns
622        *   0.  However, findMSB(int(0x80000000)) == 30.
623        *
624        * * 0xffffffff.  Since abs(0xffffffff) == 1, LZD returns
625        *   31.  Section 8.8 (Integer Functions) of the GLSL 4.50 spec says:
626        *
627        *    For a value of zero or negative one, -1 will be returned.
628        *
629        * * Negative powers of two.  LZD(abs(-(1<<x))) returns x, but
630        *   findMSB(-(1<<x)) should return x-1.
631        *
632        * For all negative number cases, including 0x80000000 and
633        * 0xffffffff, the correct value is obtained from LZD if instead of
634        * negating the (already negative) value the logical-not is used.  A
635        * conditonal logical-not can be achieved in two instructions.
636        */
637       temp = bld.vgrf(BRW_REGISTER_TYPE_D);
638
639       bld.ASR(temp, src, brw_imm_d(31));
640       bld.XOR(temp, temp, src);
641    }
642
643    bld.LZD(retype(result, BRW_REGISTER_TYPE_UD),
644            retype(temp, BRW_REGISTER_TYPE_UD));
645
646    /* LZD counts from the MSB side, while GLSL's findMSB() wants the count
647     * from the LSB side. Subtract the result from 31 to convert the MSB
648     * count into an LSB count.  If no bits are set, LZD will return 32.
649     * 31-32 = -1, which is exactly what findMSB() is supposed to return.
650     */
651    inst = bld.ADD(result, retype(result, BRW_REGISTER_TYPE_D), brw_imm_d(31));
652    inst->src[0].negate = true;
653 }
654
655 static brw_rnd_mode
656 brw_rnd_mode_from_nir_op (const nir_op op) {
657    switch (op) {
658    case nir_op_f2f16_rtz:
659       return BRW_RND_MODE_RTZ;
660    case nir_op_f2f16_rtne:
661       return BRW_RND_MODE_RTNE;
662    default:
663       unreachable("Operation doesn't support rounding mode");
664    }
665 }
666
667 void
668 fs_visitor::nir_emit_alu(const fs_builder &bld, nir_alu_instr *instr)
669 {
670    struct brw_wm_prog_key *fs_key = (struct brw_wm_prog_key *) this->key;
671    fs_inst *inst;
672
673    fs_reg result = get_nir_dest(instr->dest.dest);
674    result.type = brw_type_for_nir_type(devinfo,
675       (nir_alu_type)(nir_op_infos[instr->op].output_type |
676                      nir_dest_bit_size(instr->dest.dest)));
677
678    fs_reg op[4];
679    for (unsigned i = 0; i < nir_op_infos[instr->op].num_inputs; i++) {
680       op[i] = get_nir_src(instr->src[i].src);
681       op[i].type = brw_type_for_nir_type(devinfo,
682          (nir_alu_type)(nir_op_infos[instr->op].input_types[i] |
683                         nir_src_bit_size(instr->src[i].src)));
684       op[i].abs = instr->src[i].abs;
685       op[i].negate = instr->src[i].negate;
686    }
687
688    /* We get a bunch of mov's out of the from_ssa pass and they may still
689     * be vectorized.  We'll handle them as a special-case.  We'll also
690     * handle vecN here because it's basically the same thing.
691     */
692    switch (instr->op) {
693    case nir_op_imov:
694    case nir_op_fmov:
695    case nir_op_vec2:
696    case nir_op_vec3:
697    case nir_op_vec4: {
698       fs_reg temp = result;
699       bool need_extra_copy = false;
700       for (unsigned i = 0; i < nir_op_infos[instr->op].num_inputs; i++) {
701          if (!instr->src[i].src.is_ssa &&
702              instr->dest.dest.reg.reg == instr->src[i].src.reg.reg) {
703             need_extra_copy = true;
704             temp = bld.vgrf(result.type, 4);
705             break;
706          }
707       }
708
709       for (unsigned i = 0; i < 4; i++) {
710          if (!(instr->dest.write_mask & (1 << i)))
711             continue;
712
713          if (instr->op == nir_op_imov || instr->op == nir_op_fmov) {
714             inst = bld.MOV(offset(temp, bld, i),
715                            offset(op[0], bld, instr->src[0].swizzle[i]));
716          } else {
717             inst = bld.MOV(offset(temp, bld, i),
718                            offset(op[i], bld, instr->src[i].swizzle[0]));
719          }
720          inst->saturate = instr->dest.saturate;
721       }
722
723       /* In this case the source and destination registers were the same,
724        * so we need to insert an extra set of moves in order to deal with
725        * any swizzling.
726        */
727       if (need_extra_copy) {
728          for (unsigned i = 0; i < 4; i++) {
729             if (!(instr->dest.write_mask & (1 << i)))
730                continue;
731
732             bld.MOV(offset(result, bld, i), offset(temp, bld, i));
733          }
734       }
735       return;
736    }
737    default:
738       break;
739    }
740
741    /* At this point, we have dealt with any instruction that operates on
742     * more than a single channel.  Therefore, we can just adjust the source
743     * and destination registers for that channel and emit the instruction.
744     */
745    unsigned channel = 0;
746    if (nir_op_infos[instr->op].output_size == 0) {
747       /* Since NIR is doing the scalarizing for us, we should only ever see
748        * vectorized operations with a single channel.
749        */
750       assert(util_bitcount(instr->dest.write_mask) == 1);
751       channel = ffs(instr->dest.write_mask) - 1;
752
753       result = offset(result, bld, channel);
754    }
755
756    for (unsigned i = 0; i < nir_op_infos[instr->op].num_inputs; i++) {
757       assert(nir_op_infos[instr->op].input_sizes[i] < 2);
758       op[i] = offset(op[i], bld, instr->src[i].swizzle[channel]);
759    }
760
761    switch (instr->op) {
762    case nir_op_i2f32:
763    case nir_op_u2f32:
764       if (optimize_extract_to_float(instr, result))
765          return;
766       inst = bld.MOV(result, op[0]);
767       inst->saturate = instr->dest.saturate;
768       break;
769
770    case nir_op_f2f16_rtne:
771    case nir_op_f2f16_rtz:
772       bld.emit(SHADER_OPCODE_RND_MODE, bld.null_reg_ud(),
773                brw_imm_d(brw_rnd_mode_from_nir_op(instr->op)));
774       /* fallthrough */
775
776       /* In theory, it would be better to use BRW_OPCODE_F32TO16. Depending
777        * on the HW gen, it is a special hw opcode or just a MOV, and
778        * brw_F32TO16 (at brw_eu_emit) would do the work to chose.
779        *
780        * But if we want to use that opcode, we need to provide support on
781        * different optimizations and lowerings. As right now HF support is
782        * only for gen8+, it will be better to use directly the MOV, and use
783        * BRW_OPCODE_F32TO16 when/if we work for HF support on gen7.
784        */
785
786    case nir_op_f2f16:
787       inst = bld.MOV(result, op[0]);
788       inst->saturate = instr->dest.saturate;
789       break;
790
791    case nir_op_b2i8:
792    case nir_op_b2i16:
793    case nir_op_b2i32:
794    case nir_op_b2i64:
795    case nir_op_b2f16:
796    case nir_op_b2f32:
797    case nir_op_b2f64:
798       op[0].type = BRW_REGISTER_TYPE_D;
799       op[0].negate = !op[0].negate;
800       /* fallthrough */
801    case nir_op_f2f64:
802    case nir_op_f2i64:
803    case nir_op_f2u64:
804    case nir_op_i2f64:
805    case nir_op_i2i64:
806    case nir_op_u2f64:
807    case nir_op_u2u64:
808       /* CHV PRM, vol07, 3D Media GPGPU Engine, Register Region Restrictions:
809        *
810        *    "When source or destination is 64b (...), regioning in Align1
811        *     must follow these rules:
812        *
813        *     1. Source and destination horizontal stride must be aligned to
814        *        the same qword.
815        *     (...)"
816        *
817        * This means that conversions from bit-sizes smaller than 64-bit to
818        * 64-bit need to have the source data elements aligned to 64-bit.
819        * This restriction does not apply to BDW and later.
820        */
821       if (nir_dest_bit_size(instr->dest.dest) == 64 &&
822           nir_src_bit_size(instr->src[0].src) < 64 &&
823           (devinfo->is_cherryview || gen_device_info_is_9lp(devinfo))) {
824          fs_reg tmp = bld.vgrf(result.type, 1);
825          tmp = subscript(tmp, op[0].type, 0);
826          inst = bld.MOV(tmp, op[0]);
827          inst = bld.MOV(result, tmp);
828          inst->saturate = instr->dest.saturate;
829          break;
830       }
831       /* fallthrough */
832    case nir_op_f2f32:
833    case nir_op_f2i32:
834    case nir_op_f2u32:
835    case nir_op_f2i16:
836    case nir_op_f2u16:
837    case nir_op_i2i32:
838    case nir_op_u2u32:
839    case nir_op_i2i16:
840    case nir_op_u2u16:
841    case nir_op_i2f16:
842    case nir_op_u2f16:
843    case nir_op_i2i8:
844    case nir_op_u2u8:
845       inst = bld.MOV(result, op[0]);
846       inst->saturate = instr->dest.saturate;
847       break;
848
849    case nir_op_fsign: {
850       assert(!instr->dest.saturate);
851       if (op[0].abs) {
852          /* Straightforward since the source can be assumed to be either
853           * strictly >= 0 or strictly <= 0 depending on the setting of the
854           * negate flag.
855           */
856          set_condmod(BRW_CONDITIONAL_NZ, bld.MOV(result, op[0]));
857
858          inst = (op[0].negate)
859             ? bld.MOV(result, brw_imm_f(-1.0f))
860             : bld.MOV(result, brw_imm_f(1.0f));
861
862          set_predicate(BRW_PREDICATE_NORMAL, inst);
863       } else if (type_sz(op[0].type) < 8) {
864          /* AND(val, 0x80000000) gives the sign bit.
865           *
866           * Predicated OR ORs 1.0 (0x3f800000) with the sign bit if val is not
867           * zero.
868           */
869          bld.CMP(bld.null_reg_f(), op[0], brw_imm_f(0.0f), BRW_CONDITIONAL_NZ);
870
871          fs_reg result_int = retype(result, BRW_REGISTER_TYPE_UD);
872          op[0].type = BRW_REGISTER_TYPE_UD;
873          result.type = BRW_REGISTER_TYPE_UD;
874          bld.AND(result_int, op[0], brw_imm_ud(0x80000000u));
875
876          inst = bld.OR(result_int, result_int, brw_imm_ud(0x3f800000u));
877          inst->predicate = BRW_PREDICATE_NORMAL;
878       } else {
879          /* For doubles we do the same but we need to consider:
880           *
881           * - 2-src instructions can't operate with 64-bit immediates
882           * - The sign is encoded in the high 32-bit of each DF
883           * - We need to produce a DF result.
884           */
885
886          fs_reg zero = vgrf(glsl_type::double_type);
887          bld.MOV(zero, setup_imm_df(bld, 0.0));
888          bld.CMP(bld.null_reg_df(), op[0], zero, BRW_CONDITIONAL_NZ);
889
890          bld.MOV(result, zero);
891
892          fs_reg r = subscript(result, BRW_REGISTER_TYPE_UD, 1);
893          bld.AND(r, subscript(op[0], BRW_REGISTER_TYPE_UD, 1),
894                  brw_imm_ud(0x80000000u));
895
896          set_predicate(BRW_PREDICATE_NORMAL,
897                        bld.OR(r, r, brw_imm_ud(0x3ff00000u)));
898       }
899       break;
900    }
901
902    case nir_op_isign: {
903       /*  ASR(val, 31) -> negative val generates 0xffffffff (signed -1).
904        *               -> non-negative val generates 0x00000000.
905        *  Predicated OR sets 1 if val is positive.
906        */
907       uint32_t bit_size = nir_dest_bit_size(instr->dest.dest);
908       assert(bit_size == 32 || bit_size == 16);
909
910       fs_reg zero = bit_size == 32 ? brw_imm_d(0) : brw_imm_w(0);
911       fs_reg one = bit_size == 32 ? brw_imm_d(1) : brw_imm_w(1);
912       fs_reg shift = bit_size == 32 ? brw_imm_d(31) : brw_imm_w(15);
913
914       bld.CMP(bld.null_reg_d(), op[0], zero, BRW_CONDITIONAL_G);
915       bld.ASR(result, op[0], shift);
916       inst = bld.OR(result, result, one);
917       inst->predicate = BRW_PREDICATE_NORMAL;
918       break;
919    }
920
921    case nir_op_frcp:
922       inst = bld.emit(SHADER_OPCODE_RCP, result, op[0]);
923       inst->saturate = instr->dest.saturate;
924       break;
925
926    case nir_op_fexp2:
927       inst = bld.emit(SHADER_OPCODE_EXP2, result, op[0]);
928       inst->saturate = instr->dest.saturate;
929       break;
930
931    case nir_op_flog2:
932       inst = bld.emit(SHADER_OPCODE_LOG2, result, op[0]);
933       inst->saturate = instr->dest.saturate;
934       break;
935
936    case nir_op_fsin:
937       inst = bld.emit(SHADER_OPCODE_SIN, result, op[0]);
938       inst->saturate = instr->dest.saturate;
939       break;
940
941    case nir_op_fcos:
942       inst = bld.emit(SHADER_OPCODE_COS, result, op[0]);
943       inst->saturate = instr->dest.saturate;
944       break;
945
946    case nir_op_fddx:
947       if (fs_key->high_quality_derivatives) {
948          inst = bld.emit(FS_OPCODE_DDX_FINE, result, op[0]);
949       } else {
950          inst = bld.emit(FS_OPCODE_DDX_COARSE, result, op[0]);
951       }
952       inst->saturate = instr->dest.saturate;
953       break;
954    case nir_op_fddx_fine:
955       inst = bld.emit(FS_OPCODE_DDX_FINE, result, op[0]);
956       inst->saturate = instr->dest.saturate;
957       break;
958    case nir_op_fddx_coarse:
959       inst = bld.emit(FS_OPCODE_DDX_COARSE, result, op[0]);
960       inst->saturate = instr->dest.saturate;
961       break;
962    case nir_op_fddy:
963       if (fs_key->high_quality_derivatives) {
964          inst = bld.emit(FS_OPCODE_DDY_FINE, result, op[0]);
965       } else {
966          inst = bld.emit(FS_OPCODE_DDY_COARSE, result, op[0]);
967       }
968       inst->saturate = instr->dest.saturate;
969       break;
970    case nir_op_fddy_fine:
971       inst = bld.emit(FS_OPCODE_DDY_FINE, result, op[0]);
972       inst->saturate = instr->dest.saturate;
973       break;
974    case nir_op_fddy_coarse:
975       inst = bld.emit(FS_OPCODE_DDY_COARSE, result, op[0]);
976       inst->saturate = instr->dest.saturate;
977       break;
978
979    case nir_op_iadd:
980    case nir_op_fadd:
981       inst = bld.ADD(result, op[0], op[1]);
982       inst->saturate = instr->dest.saturate;
983       break;
984
985    case nir_op_fmul:
986       inst = bld.MUL(result, op[0], op[1]);
987       inst->saturate = instr->dest.saturate;
988       break;
989
990    case nir_op_imul:
991       assert(nir_dest_bit_size(instr->dest.dest) < 64);
992       bld.MUL(result, op[0], op[1]);
993       break;
994
995    case nir_op_imul_high:
996    case nir_op_umul_high:
997       assert(nir_dest_bit_size(instr->dest.dest) < 64);
998       bld.emit(SHADER_OPCODE_MULH, result, op[0], op[1]);
999       break;
1000
1001    case nir_op_idiv:
1002    case nir_op_udiv:
1003       assert(nir_dest_bit_size(instr->dest.dest) < 64);
1004       bld.emit(SHADER_OPCODE_INT_QUOTIENT, result, op[0], op[1]);
1005       break;
1006
1007    case nir_op_uadd_carry:
1008       unreachable("Should have been lowered by carry_to_arith().");
1009
1010    case nir_op_usub_borrow:
1011       unreachable("Should have been lowered by borrow_to_arith().");
1012
1013    case nir_op_umod:
1014    case nir_op_irem:
1015       /* According to the sign table for INT DIV in the Ivy Bridge PRM, it
1016        * appears that our hardware just does the right thing for signed
1017        * remainder.
1018        */
1019       assert(nir_dest_bit_size(instr->dest.dest) < 64);
1020       bld.emit(SHADER_OPCODE_INT_REMAINDER, result, op[0], op[1]);
1021       break;
1022
1023    case nir_op_imod: {
1024       /* Get a regular C-style remainder.  If a % b == 0, set the predicate. */
1025       bld.emit(SHADER_OPCODE_INT_REMAINDER, result, op[0], op[1]);
1026
1027       /* Math instructions don't support conditional mod */
1028       inst = bld.MOV(bld.null_reg_d(), result);
1029       inst->conditional_mod = BRW_CONDITIONAL_NZ;
1030
1031       /* Now, we need to determine if signs of the sources are different.
1032        * When we XOR the sources, the top bit is 0 if they are the same and 1
1033        * if they are different.  We can then use a conditional modifier to
1034        * turn that into a predicate.  This leads us to an XOR.l instruction.
1035        *
1036        * Technically, according to the PRM, you're not allowed to use .l on a
1037        * XOR instruction.  However, emperical experiments and Curro's reading
1038        * of the simulator source both indicate that it's safe.
1039        */
1040       fs_reg tmp = bld.vgrf(BRW_REGISTER_TYPE_D);
1041       inst = bld.XOR(tmp, op[0], op[1]);
1042       inst->predicate = BRW_PREDICATE_NORMAL;
1043       inst->conditional_mod = BRW_CONDITIONAL_L;
1044
1045       /* If the result of the initial remainder operation is non-zero and the
1046        * two sources have different signs, add in a copy of op[1] to get the
1047        * final integer modulus value.
1048        */
1049       inst = bld.ADD(result, result, op[1]);
1050       inst->predicate = BRW_PREDICATE_NORMAL;
1051       break;
1052    }
1053
1054    case nir_op_flt:
1055    case nir_op_fge:
1056    case nir_op_feq:
1057    case nir_op_fne: {
1058       fs_reg dest = result;
1059
1060       const uint32_t bit_size =  nir_src_bit_size(instr->src[0].src);
1061       if (bit_size != 32)
1062          dest = bld.vgrf(op[0].type, 1);
1063
1064       brw_conditional_mod cond;
1065       switch (instr->op) {
1066       case nir_op_flt:
1067          cond = BRW_CONDITIONAL_L;
1068          break;
1069       case nir_op_fge:
1070          cond = BRW_CONDITIONAL_GE;
1071          break;
1072       case nir_op_feq:
1073          cond = BRW_CONDITIONAL_Z;
1074          break;
1075       case nir_op_fne:
1076          cond = BRW_CONDITIONAL_NZ;
1077          break;
1078       default:
1079          unreachable("bad opcode");
1080       }
1081
1082       bld.CMP(dest, op[0], op[1], cond);
1083
1084       if (bit_size > 32) {
1085          bld.MOV(result, subscript(dest, BRW_REGISTER_TYPE_UD, 0));
1086       } else if(bit_size < 32) {
1087          /* When we convert the result to 32-bit we need to be careful and do
1088           * it as a signed conversion to get sign extension (for 32-bit true)
1089           */
1090          const brw_reg_type src_type =
1091             brw_reg_type_from_bit_size(bit_size, BRW_REGISTER_TYPE_D);
1092
1093          bld.MOV(retype(result, BRW_REGISTER_TYPE_D), retype(dest, src_type));
1094       }
1095       break;
1096    }
1097
1098    case nir_op_ilt:
1099    case nir_op_ult:
1100    case nir_op_ige:
1101    case nir_op_uge:
1102    case nir_op_ieq:
1103    case nir_op_ine: {
1104       fs_reg dest = result;
1105
1106       const uint32_t bit_size = nir_src_bit_size(instr->src[0].src);
1107       if (bit_size != 32)
1108          dest = bld.vgrf(op[0].type, 1);
1109
1110       brw_conditional_mod cond;
1111       switch (instr->op) {
1112       case nir_op_ilt:
1113       case nir_op_ult:
1114          cond = BRW_CONDITIONAL_L;
1115          break;
1116       case nir_op_ige:
1117       case nir_op_uge:
1118          cond = BRW_CONDITIONAL_GE;
1119          break;
1120       case nir_op_ieq:
1121          cond = BRW_CONDITIONAL_Z;
1122          break;
1123       case nir_op_ine:
1124          cond = BRW_CONDITIONAL_NZ;
1125          break;
1126       default:
1127          unreachable("bad opcode");
1128       }
1129       bld.CMP(dest, op[0], op[1], cond);
1130
1131       if (bit_size > 32) {
1132          bld.MOV(result, subscript(dest, BRW_REGISTER_TYPE_UD, 0));
1133       } else if (bit_size < 32) {
1134          /* When we convert the result to 32-bit we need to be careful and do
1135           * it as a signed conversion to get sign extension (for 32-bit true)
1136           */
1137          const brw_reg_type src_type =
1138             brw_reg_type_from_bit_size(bit_size, BRW_REGISTER_TYPE_D);
1139
1140          bld.MOV(retype(result, BRW_REGISTER_TYPE_D), retype(dest, src_type));
1141       }
1142       break;
1143    }
1144
1145    case nir_op_inot:
1146       if (devinfo->gen >= 8) {
1147          op[0] = resolve_source_modifiers(op[0]);
1148       }
1149       bld.NOT(result, op[0]);
1150       break;
1151    case nir_op_ixor:
1152       if (devinfo->gen >= 8) {
1153          op[0] = resolve_source_modifiers(op[0]);
1154          op[1] = resolve_source_modifiers(op[1]);
1155       }
1156       bld.XOR(result, op[0], op[1]);
1157       break;
1158    case nir_op_ior:
1159       if (devinfo->gen >= 8) {
1160          op[0] = resolve_source_modifiers(op[0]);
1161          op[1] = resolve_source_modifiers(op[1]);
1162       }
1163       bld.OR(result, op[0], op[1]);
1164       break;
1165    case nir_op_iand:
1166       if (devinfo->gen >= 8) {
1167          op[0] = resolve_source_modifiers(op[0]);
1168          op[1] = resolve_source_modifiers(op[1]);
1169       }
1170       bld.AND(result, op[0], op[1]);
1171       break;
1172
1173    case nir_op_fdot2:
1174    case nir_op_fdot3:
1175    case nir_op_fdot4:
1176    case nir_op_ball_fequal2:
1177    case nir_op_ball_iequal2:
1178    case nir_op_ball_fequal3:
1179    case nir_op_ball_iequal3:
1180    case nir_op_ball_fequal4:
1181    case nir_op_ball_iequal4:
1182    case nir_op_bany_fnequal2:
1183    case nir_op_bany_inequal2:
1184    case nir_op_bany_fnequal3:
1185    case nir_op_bany_inequal3:
1186    case nir_op_bany_fnequal4:
1187    case nir_op_bany_inequal4:
1188       unreachable("Lowered by nir_lower_alu_reductions");
1189
1190    case nir_op_fnoise1_1:
1191    case nir_op_fnoise1_2:
1192    case nir_op_fnoise1_3:
1193    case nir_op_fnoise1_4:
1194    case nir_op_fnoise2_1:
1195    case nir_op_fnoise2_2:
1196    case nir_op_fnoise2_3:
1197    case nir_op_fnoise2_4:
1198    case nir_op_fnoise3_1:
1199    case nir_op_fnoise3_2:
1200    case nir_op_fnoise3_3:
1201    case nir_op_fnoise3_4:
1202    case nir_op_fnoise4_1:
1203    case nir_op_fnoise4_2:
1204    case nir_op_fnoise4_3:
1205    case nir_op_fnoise4_4:
1206       unreachable("not reached: should be handled by lower_noise");
1207
1208    case nir_op_ldexp:
1209       unreachable("not reached: should be handled by ldexp_to_arith()");
1210
1211    case nir_op_fsqrt:
1212       inst = bld.emit(SHADER_OPCODE_SQRT, result, op[0]);
1213       inst->saturate = instr->dest.saturate;
1214       break;
1215
1216    case nir_op_frsq:
1217       inst = bld.emit(SHADER_OPCODE_RSQ, result, op[0]);
1218       inst->saturate = instr->dest.saturate;
1219       break;
1220
1221    case nir_op_i2b32:
1222    case nir_op_f2b32: {
1223       uint32_t bit_size = nir_src_bit_size(instr->src[0].src);
1224       if (bit_size == 64) {
1225          /* two-argument instructions can't take 64-bit immediates */
1226          fs_reg zero;
1227          fs_reg tmp;
1228
1229          if (instr->op == nir_op_f2b32) {
1230             zero = vgrf(glsl_type::double_type);
1231             tmp = vgrf(glsl_type::double_type);
1232             bld.MOV(zero, setup_imm_df(bld, 0.0));
1233          } else {
1234             zero = vgrf(glsl_type::int64_t_type);
1235             tmp = vgrf(glsl_type::int64_t_type);
1236             bld.MOV(zero, brw_imm_q(0));
1237          }
1238
1239          /* A SIMD16 execution needs to be split in two instructions, so use
1240           * a vgrf instead of the flag register as dst so instruction splitting
1241           * works
1242           */
1243          bld.CMP(tmp, op[0], zero, BRW_CONDITIONAL_NZ);
1244          bld.MOV(result, subscript(tmp, BRW_REGISTER_TYPE_UD, 0));
1245       } else {
1246          fs_reg zero;
1247          if (bit_size == 32) {
1248             zero = instr->op == nir_op_f2b32 ? brw_imm_f(0.0f) : brw_imm_d(0);
1249          } else {
1250             assert(bit_size == 16);
1251             zero = instr->op == nir_op_f2b32 ?
1252                retype(brw_imm_w(0), BRW_REGISTER_TYPE_HF) : brw_imm_w(0);
1253          }
1254          bld.CMP(result, op[0], zero, BRW_CONDITIONAL_NZ);
1255       }
1256       break;
1257    }
1258
1259    case nir_op_ftrunc:
1260       inst = bld.RNDZ(result, op[0]);
1261       inst->saturate = instr->dest.saturate;
1262       break;
1263
1264    case nir_op_fceil: {
1265       op[0].negate = !op[0].negate;
1266       fs_reg temp = vgrf(glsl_type::float_type);
1267       bld.RNDD(temp, op[0]);
1268       temp.negate = true;
1269       inst = bld.MOV(result, temp);
1270       inst->saturate = instr->dest.saturate;
1271       break;
1272    }
1273    case nir_op_ffloor:
1274       inst = bld.RNDD(result, op[0]);
1275       inst->saturate = instr->dest.saturate;
1276       break;
1277    case nir_op_ffract:
1278       inst = bld.FRC(result, op[0]);
1279       inst->saturate = instr->dest.saturate;
1280       break;
1281    case nir_op_fround_even:
1282       inst = bld.RNDE(result, op[0]);
1283       inst->saturate = instr->dest.saturate;
1284       break;
1285
1286    case nir_op_fquantize2f16: {
1287       fs_reg tmp16 = bld.vgrf(BRW_REGISTER_TYPE_D);
1288       fs_reg tmp32 = bld.vgrf(BRW_REGISTER_TYPE_F);
1289       fs_reg zero = bld.vgrf(BRW_REGISTER_TYPE_F);
1290
1291       /* The destination stride must be at least as big as the source stride. */
1292       tmp16.type = BRW_REGISTER_TYPE_W;
1293       tmp16.stride = 2;
1294
1295       /* Check for denormal */
1296       fs_reg abs_src0 = op[0];
1297       abs_src0.abs = true;
1298       bld.CMP(bld.null_reg_f(), abs_src0, brw_imm_f(ldexpf(1.0, -14)),
1299               BRW_CONDITIONAL_L);
1300       /* Get the appropriately signed zero */
1301       bld.AND(retype(zero, BRW_REGISTER_TYPE_UD),
1302               retype(op[0], BRW_REGISTER_TYPE_UD),
1303               brw_imm_ud(0x80000000));
1304       /* Do the actual F32 -> F16 -> F32 conversion */
1305       bld.emit(BRW_OPCODE_F32TO16, tmp16, op[0]);
1306       bld.emit(BRW_OPCODE_F16TO32, tmp32, tmp16);
1307       /* Select that or zero based on normal status */
1308       inst = bld.SEL(result, zero, tmp32);
1309       inst->predicate = BRW_PREDICATE_NORMAL;
1310       inst->saturate = instr->dest.saturate;
1311       break;
1312    }
1313
1314    case nir_op_imin:
1315    case nir_op_umin:
1316    case nir_op_fmin:
1317       inst = bld.emit_minmax(result, op[0], op[1], BRW_CONDITIONAL_L);
1318       inst->saturate = instr->dest.saturate;
1319       break;
1320
1321    case nir_op_imax:
1322    case nir_op_umax:
1323    case nir_op_fmax:
1324       inst = bld.emit_minmax(result, op[0], op[1], BRW_CONDITIONAL_GE);
1325       inst->saturate = instr->dest.saturate;
1326       break;
1327
1328    case nir_op_pack_snorm_2x16:
1329    case nir_op_pack_snorm_4x8:
1330    case nir_op_pack_unorm_2x16:
1331    case nir_op_pack_unorm_4x8:
1332    case nir_op_unpack_snorm_2x16:
1333    case nir_op_unpack_snorm_4x8:
1334    case nir_op_unpack_unorm_2x16:
1335    case nir_op_unpack_unorm_4x8:
1336    case nir_op_unpack_half_2x16:
1337    case nir_op_pack_half_2x16:
1338       unreachable("not reached: should be handled by lower_packing_builtins");
1339
1340    case nir_op_unpack_half_2x16_split_x:
1341       inst = bld.emit(FS_OPCODE_UNPACK_HALF_2x16_SPLIT_X, result, op[0]);
1342       inst->saturate = instr->dest.saturate;
1343       break;
1344    case nir_op_unpack_half_2x16_split_y:
1345       inst = bld.emit(FS_OPCODE_UNPACK_HALF_2x16_SPLIT_Y, result, op[0]);
1346       inst->saturate = instr->dest.saturate;
1347       break;
1348
1349    case nir_op_pack_64_2x32_split:
1350    case nir_op_pack_32_2x16_split:
1351       bld.emit(FS_OPCODE_PACK, result, op[0], op[1]);
1352       break;
1353
1354    case nir_op_unpack_64_2x32_split_x:
1355    case nir_op_unpack_64_2x32_split_y: {
1356       if (instr->op == nir_op_unpack_64_2x32_split_x)
1357          bld.MOV(result, subscript(op[0], BRW_REGISTER_TYPE_UD, 0));
1358       else
1359          bld.MOV(result, subscript(op[0], BRW_REGISTER_TYPE_UD, 1));
1360       break;
1361    }
1362
1363    case nir_op_unpack_32_2x16_split_x:
1364    case nir_op_unpack_32_2x16_split_y: {
1365       if (instr->op == nir_op_unpack_32_2x16_split_x)
1366          bld.MOV(result, subscript(op[0], BRW_REGISTER_TYPE_UW, 0));
1367       else
1368          bld.MOV(result, subscript(op[0], BRW_REGISTER_TYPE_UW, 1));
1369       break;
1370    }
1371
1372    case nir_op_fpow:
1373       inst = bld.emit(SHADER_OPCODE_POW, result, op[0], op[1]);
1374       inst->saturate = instr->dest.saturate;
1375       break;
1376
1377    case nir_op_bitfield_reverse:
1378       assert(nir_dest_bit_size(instr->dest.dest) < 64);
1379       bld.BFREV(result, op[0]);
1380       break;
1381
1382    case nir_op_bit_count:
1383       assert(nir_dest_bit_size(instr->dest.dest) < 64);
1384       bld.CBIT(result, op[0]);
1385       break;
1386
1387    case nir_op_ufind_msb: {
1388       assert(nir_dest_bit_size(instr->dest.dest) < 64);
1389       emit_find_msb_using_lzd(bld, result, op[0], false);
1390       break;
1391    }
1392
1393    case nir_op_ifind_msb: {
1394       assert(nir_dest_bit_size(instr->dest.dest) < 64);
1395
1396       if (devinfo->gen < 7) {
1397          emit_find_msb_using_lzd(bld, result, op[0], true);
1398       } else {
1399          bld.FBH(retype(result, BRW_REGISTER_TYPE_UD), op[0]);
1400
1401          /* FBH counts from the MSB side, while GLSL's findMSB() wants the
1402           * count from the LSB side. If FBH didn't return an error
1403           * (0xFFFFFFFF), then subtract the result from 31 to convert the MSB
1404           * count into an LSB count.
1405           */
1406          bld.CMP(bld.null_reg_d(), result, brw_imm_d(-1), BRW_CONDITIONAL_NZ);
1407
1408          inst = bld.ADD(result, result, brw_imm_d(31));
1409          inst->predicate = BRW_PREDICATE_NORMAL;
1410          inst->src[0].negate = true;
1411       }
1412       break;
1413    }
1414
1415    case nir_op_find_lsb:
1416       assert(nir_dest_bit_size(instr->dest.dest) < 64);
1417
1418       if (devinfo->gen < 7) {
1419          fs_reg temp = vgrf(glsl_type::int_type);
1420
1421          /* (x & -x) generates a value that consists of only the LSB of x.
1422           * For all powers of 2, findMSB(y) == findLSB(y).
1423           */
1424          fs_reg src = retype(op[0], BRW_REGISTER_TYPE_D);
1425          fs_reg negated_src = src;
1426
1427          /* One must be negated, and the other must be non-negated.  It
1428           * doesn't matter which is which.
1429           */
1430          negated_src.negate = true;
1431          src.negate = false;
1432
1433          bld.AND(temp, src, negated_src);
1434          emit_find_msb_using_lzd(bld, result, temp, false);
1435       } else {
1436          bld.FBL(result, op[0]);
1437       }
1438       break;
1439
1440    case nir_op_ubitfield_extract:
1441    case nir_op_ibitfield_extract:
1442       unreachable("should have been lowered");
1443    case nir_op_ubfe:
1444    case nir_op_ibfe:
1445       assert(nir_dest_bit_size(instr->dest.dest) < 64);
1446       bld.BFE(result, op[2], op[1], op[0]);
1447       break;
1448    case nir_op_bfm:
1449       assert(nir_dest_bit_size(instr->dest.dest) < 64);
1450       bld.BFI1(result, op[0], op[1]);
1451       break;
1452    case nir_op_bfi:
1453       assert(nir_dest_bit_size(instr->dest.dest) < 64);
1454       bld.BFI2(result, op[0], op[1], op[2]);
1455       break;
1456
1457    case nir_op_bitfield_insert:
1458       unreachable("not reached: should have been lowered");
1459
1460    case nir_op_ishl:
1461    case nir_op_ishr:
1462    case nir_op_ushr: {
1463       fs_reg shift_count = op[1];
1464
1465       if (devinfo->is_cherryview || gen_device_info_is_9lp(devinfo)) {
1466          if (op[1].file == VGRF &&
1467              (result.type == BRW_REGISTER_TYPE_Q ||
1468               result.type == BRW_REGISTER_TYPE_UQ)) {
1469             shift_count = fs_reg(VGRF, alloc.allocate(dispatch_width / 4),
1470                                  BRW_REGISTER_TYPE_UD);
1471             shift_count.stride = 2;
1472             bld.MOV(shift_count, op[1]);
1473          }
1474       }
1475
1476       switch (instr->op) {
1477       case nir_op_ishl:
1478          bld.SHL(result, op[0], shift_count);
1479          break;
1480       case nir_op_ishr:
1481          bld.ASR(result, op[0], shift_count);
1482          break;
1483       case nir_op_ushr:
1484          bld.SHR(result, op[0], shift_count);
1485          break;
1486       default:
1487          unreachable("not reached");
1488       }
1489       break;
1490    }
1491
1492    case nir_op_pack_half_2x16_split:
1493       bld.emit(FS_OPCODE_PACK_HALF_2x16_SPLIT, result, op[0], op[1]);
1494       break;
1495
1496    case nir_op_ffma:
1497       inst = bld.MAD(result, op[2], op[1], op[0]);
1498       inst->saturate = instr->dest.saturate;
1499       break;
1500
1501    case nir_op_flrp:
1502       inst = bld.LRP(result, op[0], op[1], op[2]);
1503       inst->saturate = instr->dest.saturate;
1504       break;
1505
1506    case nir_op_bcsel:
1507       if (optimize_frontfacing_ternary(instr, result))
1508          return;
1509
1510       bld.CMP(bld.null_reg_d(), op[0], brw_imm_d(0), BRW_CONDITIONAL_NZ);
1511       inst = bld.SEL(result, op[1], op[2]);
1512       inst->predicate = BRW_PREDICATE_NORMAL;
1513       break;
1514
1515    case nir_op_extract_u8:
1516    case nir_op_extract_i8: {
1517       unsigned byte = nir_src_as_uint(instr->src[1].src);
1518
1519       /* The PRMs say:
1520        *
1521        *    BDW+
1522        *    There is no direct conversion from B/UB to Q/UQ or Q/UQ to B/UB.
1523        *    Use two instructions and a word or DWord intermediate integer type.
1524        */
1525       if (nir_dest_bit_size(instr->dest.dest) == 64) {
1526          const brw_reg_type type = brw_int_type(2, instr->op == nir_op_extract_i8);
1527
1528          if (instr->op == nir_op_extract_i8) {
1529             /* If we need to sign extend, extract to a word first */
1530             fs_reg w_temp = bld.vgrf(BRW_REGISTER_TYPE_W);
1531             bld.MOV(w_temp, subscript(op[0], type, byte));
1532             bld.MOV(result, w_temp);
1533          } else {
1534             /* Otherwise use an AND with 0xff and a word type */
1535             bld.AND(result, subscript(op[0], type, byte / 2), brw_imm_uw(0xff));
1536          }
1537       } else {
1538          const brw_reg_type type = brw_int_type(1, instr->op == nir_op_extract_i8);
1539          bld.MOV(result, subscript(op[0], type, byte));
1540       }
1541       break;
1542    }
1543
1544    case nir_op_extract_u16:
1545    case nir_op_extract_i16: {
1546       const brw_reg_type type = brw_int_type(2, instr->op == nir_op_extract_i16);
1547       unsigned word = nir_src_as_uint(instr->src[1].src);
1548       bld.MOV(result, subscript(op[0], type, word));
1549       break;
1550    }
1551
1552    default:
1553       unreachable("unhandled instruction");
1554    }
1555
1556    /* If we need to do a boolean resolve, replace the result with -(x & 1)
1557     * to sign extend the low bit to 0/~0
1558     */
1559    if (devinfo->gen <= 5 &&
1560        (instr->instr.pass_flags & BRW_NIR_BOOLEAN_MASK) == BRW_NIR_BOOLEAN_NEEDS_RESOLVE) {
1561       fs_reg masked = vgrf(glsl_type::int_type);
1562       bld.AND(masked, result, brw_imm_d(1));
1563       masked.negate = true;
1564       bld.MOV(retype(result, BRW_REGISTER_TYPE_D), masked);
1565    }
1566 }
1567
1568 void
1569 fs_visitor::nir_emit_load_const(const fs_builder &bld,
1570                                 nir_load_const_instr *instr)
1571 {
1572    const brw_reg_type reg_type =
1573       brw_reg_type_from_bit_size(instr->def.bit_size, BRW_REGISTER_TYPE_D);
1574    fs_reg reg = bld.vgrf(reg_type, instr->def.num_components);
1575
1576    switch (instr->def.bit_size) {
1577    case 8:
1578       for (unsigned i = 0; i < instr->def.num_components; i++)
1579          bld.MOV(offset(reg, bld, i), setup_imm_b(bld, instr->value.i8[i]));
1580       break;
1581
1582    case 16:
1583       for (unsigned i = 0; i < instr->def.num_components; i++)
1584          bld.MOV(offset(reg, bld, i), brw_imm_w(instr->value.i16[i]));
1585       break;
1586
1587    case 32:
1588       for (unsigned i = 0; i < instr->def.num_components; i++)
1589          bld.MOV(offset(reg, bld, i), brw_imm_d(instr->value.i32[i]));
1590       break;
1591
1592    case 64:
1593       assert(devinfo->gen >= 7);
1594       if (devinfo->gen == 7) {
1595          /* We don't get 64-bit integer types until gen8 */
1596          for (unsigned i = 0; i < instr->def.num_components; i++) {
1597             bld.MOV(retype(offset(reg, bld, i), BRW_REGISTER_TYPE_DF),
1598                     setup_imm_df(bld, instr->value.f64[i]));
1599          }
1600       } else {
1601          for (unsigned i = 0; i < instr->def.num_components; i++)
1602             bld.MOV(offset(reg, bld, i), brw_imm_q(instr->value.i64[i]));
1603       }
1604       break;
1605
1606    default:
1607       unreachable("Invalid bit size");
1608    }
1609
1610    nir_ssa_values[instr->def.index] = reg;
1611 }
1612
1613 fs_reg
1614 fs_visitor::get_nir_src(const nir_src &src)
1615 {
1616    fs_reg reg;
1617    if (src.is_ssa) {
1618       if (src.ssa->parent_instr->type == nir_instr_type_ssa_undef) {
1619          const brw_reg_type reg_type =
1620             brw_reg_type_from_bit_size(src.ssa->bit_size, BRW_REGISTER_TYPE_D);
1621          reg = bld.vgrf(reg_type, src.ssa->num_components);
1622       } else {
1623          reg = nir_ssa_values[src.ssa->index];
1624       }
1625    } else {
1626       /* We don't handle indirects on locals */
1627       assert(src.reg.indirect == NULL);
1628       reg = offset(nir_locals[src.reg.reg->index], bld,
1629                    src.reg.base_offset * src.reg.reg->num_components);
1630    }
1631
1632    if (nir_src_bit_size(src) == 64 && devinfo->gen == 7) {
1633       /* The only 64-bit type available on gen7 is DF, so use that. */
1634       reg.type = BRW_REGISTER_TYPE_DF;
1635    } else {
1636       /* To avoid floating-point denorm flushing problems, set the type by
1637        * default to an integer type - instructions that need floating point
1638        * semantics will set this to F if they need to
1639        */
1640       reg.type = brw_reg_type_from_bit_size(nir_src_bit_size(src),
1641                                             BRW_REGISTER_TYPE_D);
1642    }
1643
1644    return reg;
1645 }
1646
1647 /**
1648  * Return an IMM for constants; otherwise call get_nir_src() as normal.
1649  *
1650  * This function should not be called on any value which may be 64 bits.
1651  * We could theoretically support 64-bit on gen8+ but we choose not to
1652  * because it wouldn't work in general (no gen7 support) and there are
1653  * enough restrictions in 64-bit immediates that you can't take the return
1654  * value and treat it the same as the result of get_nir_src().
1655  */
1656 fs_reg
1657 fs_visitor::get_nir_src_imm(const nir_src &src)
1658 {
1659    assert(nir_src_bit_size(src) == 32);
1660    return nir_src_is_const(src) ?
1661           fs_reg(brw_imm_d(nir_src_as_int(src))) : get_nir_src(src);
1662 }
1663
1664 fs_reg
1665 fs_visitor::get_nir_dest(const nir_dest &dest)
1666 {
1667    if (dest.is_ssa) {
1668       const brw_reg_type reg_type =
1669          brw_reg_type_from_bit_size(dest.ssa.bit_size,
1670                                     dest.ssa.bit_size == 8 ?
1671                                     BRW_REGISTER_TYPE_D :
1672                                     BRW_REGISTER_TYPE_F);
1673       nir_ssa_values[dest.ssa.index] =
1674          bld.vgrf(reg_type, dest.ssa.num_components);
1675       return nir_ssa_values[dest.ssa.index];
1676    } else {
1677       /* We don't handle indirects on locals */
1678       assert(dest.reg.indirect == NULL);
1679       return offset(nir_locals[dest.reg.reg->index], bld,
1680                     dest.reg.base_offset * dest.reg.reg->num_components);
1681    }
1682 }
1683
1684 void
1685 fs_visitor::emit_percomp(const fs_builder &bld, const fs_inst &inst,
1686                          unsigned wr_mask)
1687 {
1688    for (unsigned i = 0; i < 4; i++) {
1689       if (!((wr_mask >> i) & 1))
1690          continue;
1691
1692       fs_inst *new_inst = new(mem_ctx) fs_inst(inst);
1693       new_inst->dst = offset(new_inst->dst, bld, i);
1694       for (unsigned j = 0; j < new_inst->sources; j++)
1695          if (new_inst->src[j].file == VGRF)
1696             new_inst->src[j] = offset(new_inst->src[j], bld, i);
1697
1698       bld.emit(new_inst);
1699    }
1700 }
1701
1702 static fs_inst *
1703 emit_pixel_interpolater_send(const fs_builder &bld,
1704                              enum opcode opcode,
1705                              const fs_reg &dst,
1706                              const fs_reg &src,
1707                              const fs_reg &desc,
1708                              glsl_interp_mode interpolation)
1709 {
1710    struct brw_wm_prog_data *wm_prog_data =
1711       brw_wm_prog_data(bld.shader->stage_prog_data);
1712
1713    fs_inst *inst = bld.emit(opcode, dst, src, desc);
1714    /* 2 floats per slot returned */
1715    inst->size_written = 2 * dst.component_size(inst->exec_size);
1716    inst->pi_noperspective = interpolation == INTERP_MODE_NOPERSPECTIVE;
1717
1718    wm_prog_data->pulls_bary = true;
1719
1720    return inst;
1721 }
1722
1723 /**
1724  * Computes 1 << x, given a D/UD register containing some value x.
1725  */
1726 static fs_reg
1727 intexp2(const fs_builder &bld, const fs_reg &x)
1728 {
1729    assert(x.type == BRW_REGISTER_TYPE_UD || x.type == BRW_REGISTER_TYPE_D);
1730
1731    fs_reg result = bld.vgrf(x.type, 1);
1732    fs_reg one = bld.vgrf(x.type, 1);
1733
1734    bld.MOV(one, retype(brw_imm_d(1), one.type));
1735    bld.SHL(result, one, x);
1736    return result;
1737 }
1738
1739 void
1740 fs_visitor::emit_gs_end_primitive(const nir_src &vertex_count_nir_src)
1741 {
1742    assert(stage == MESA_SHADER_GEOMETRY);
1743
1744    struct brw_gs_prog_data *gs_prog_data = brw_gs_prog_data(prog_data);
1745
1746    if (gs_compile->control_data_header_size_bits == 0)
1747       return;
1748
1749    /* We can only do EndPrimitive() functionality when the control data
1750     * consists of cut bits.  Fortunately, the only time it isn't is when the
1751     * output type is points, in which case EndPrimitive() is a no-op.
1752     */
1753    if (gs_prog_data->control_data_format !=
1754        GEN7_GS_CONTROL_DATA_FORMAT_GSCTL_CUT) {
1755       return;
1756    }
1757
1758    /* Cut bits use one bit per vertex. */
1759    assert(gs_compile->control_data_bits_per_vertex == 1);
1760
1761    fs_reg vertex_count = get_nir_src(vertex_count_nir_src);
1762    vertex_count.type = BRW_REGISTER_TYPE_UD;
1763
1764    /* Cut bit n should be set to 1 if EndPrimitive() was called after emitting
1765     * vertex n, 0 otherwise.  So all we need to do here is mark bit
1766     * (vertex_count - 1) % 32 in the cut_bits register to indicate that
1767     * EndPrimitive() was called after emitting vertex (vertex_count - 1);
1768     * vec4_gs_visitor::emit_control_data_bits() will take care of the rest.
1769     *
1770     * Note that if EndPrimitive() is called before emitting any vertices, this
1771     * will cause us to set bit 31 of the control_data_bits register to 1.
1772     * That's fine because:
1773     *
1774     * - If max_vertices < 32, then vertex number 31 (zero-based) will never be
1775     *   output, so the hardware will ignore cut bit 31.
1776     *
1777     * - If max_vertices == 32, then vertex number 31 is guaranteed to be the
1778     *   last vertex, so setting cut bit 31 has no effect (since the primitive
1779     *   is automatically ended when the GS terminates).
1780     *
1781     * - If max_vertices > 32, then the ir_emit_vertex visitor will reset the
1782     *   control_data_bits register to 0 when the first vertex is emitted.
1783     */
1784
1785    const fs_builder abld = bld.annotate("end primitive");
1786
1787    /* control_data_bits |= 1 << ((vertex_count - 1) % 32) */
1788    fs_reg prev_count = bld.vgrf(BRW_REGISTER_TYPE_UD, 1);
1789    abld.ADD(prev_count, vertex_count, brw_imm_ud(0xffffffffu));
1790    fs_reg mask = intexp2(abld, prev_count);
1791    /* Note: we're relying on the fact that the GEN SHL instruction only pays
1792     * attention to the lower 5 bits of its second source argument, so on this
1793     * architecture, 1 << (vertex_count - 1) is equivalent to 1 <<
1794     * ((vertex_count - 1) % 32).
1795     */
1796    abld.OR(this->control_data_bits, this->control_data_bits, mask);
1797 }
1798
1799 void
1800 fs_visitor::emit_gs_control_data_bits(const fs_reg &vertex_count)
1801 {
1802    assert(stage == MESA_SHADER_GEOMETRY);
1803    assert(gs_compile->control_data_bits_per_vertex != 0);
1804
1805    struct brw_gs_prog_data *gs_prog_data = brw_gs_prog_data(prog_data);
1806
1807    const fs_builder abld = bld.annotate("emit control data bits");
1808    const fs_builder fwa_bld = bld.exec_all();
1809
1810    /* We use a single UD register to accumulate control data bits (32 bits
1811     * for each of the SIMD8 channels).  So we need to write a DWord (32 bits)
1812     * at a time.
1813     *
1814     * Unfortunately, the URB_WRITE_SIMD8 message uses 128-bit (OWord) offsets.
1815     * We have select a 128-bit group via the Global and Per-Slot Offsets, then
1816     * use the Channel Mask phase to enable/disable which DWord within that
1817     * group to write.  (Remember, different SIMD8 channels may have emitted
1818     * different numbers of vertices, so we may need per-slot offsets.)
1819     *
1820     * Channel masking presents an annoying problem: we may have to replicate
1821     * the data up to 4 times:
1822     *
1823     * Msg = Handles, Per-Slot Offsets, Channel Masks, Data, Data, Data, Data.
1824     *
1825     * To avoid penalizing shaders that emit a small number of vertices, we
1826     * can avoid these sometimes: if the size of the control data header is
1827     * <= 128 bits, then there is only 1 OWord.  All SIMD8 channels will land
1828     * land in the same 128-bit group, so we can skip per-slot offsets.
1829     *
1830     * Similarly, if the control data header is <= 32 bits, there is only one
1831     * DWord, so we can skip channel masks.
1832     */
1833    enum opcode opcode = SHADER_OPCODE_URB_WRITE_SIMD8;
1834
1835    fs_reg channel_mask, per_slot_offset;
1836
1837    if (gs_compile->control_data_header_size_bits > 32) {
1838       opcode = SHADER_OPCODE_URB_WRITE_SIMD8_MASKED;
1839       channel_mask = vgrf(glsl_type::uint_type);
1840    }
1841
1842    if (gs_compile->control_data_header_size_bits > 128) {
1843       opcode = SHADER_OPCODE_URB_WRITE_SIMD8_MASKED_PER_SLOT;
1844       per_slot_offset = vgrf(glsl_type::uint_type);
1845    }
1846
1847    /* Figure out which DWord we're trying to write to using the formula:
1848     *
1849     *    dword_index = (vertex_count - 1) * bits_per_vertex / 32
1850     *
1851     * Since bits_per_vertex is a power of two, and is known at compile
1852     * time, this can be optimized to:
1853     *
1854     *    dword_index = (vertex_count - 1) >> (6 - log2(bits_per_vertex))
1855     */
1856    if (opcode != SHADER_OPCODE_URB_WRITE_SIMD8) {
1857       fs_reg dword_index = bld.vgrf(BRW_REGISTER_TYPE_UD, 1);
1858       fs_reg prev_count = bld.vgrf(BRW_REGISTER_TYPE_UD, 1);
1859       abld.ADD(prev_count, vertex_count, brw_imm_ud(0xffffffffu));
1860       unsigned log2_bits_per_vertex =
1861          util_last_bit(gs_compile->control_data_bits_per_vertex);
1862       abld.SHR(dword_index, prev_count, brw_imm_ud(6u - log2_bits_per_vertex));
1863
1864       if (per_slot_offset.file != BAD_FILE) {
1865          /* Set the per-slot offset to dword_index / 4, so that we'll write to
1866           * the appropriate OWord within the control data header.
1867           */
1868          abld.SHR(per_slot_offset, dword_index, brw_imm_ud(2u));
1869       }
1870
1871       /* Set the channel masks to 1 << (dword_index % 4), so that we'll
1872        * write to the appropriate DWORD within the OWORD.
1873        */
1874       fs_reg channel = bld.vgrf(BRW_REGISTER_TYPE_UD, 1);
1875       fwa_bld.AND(channel, dword_index, brw_imm_ud(3u));
1876       channel_mask = intexp2(fwa_bld, channel);
1877       /* Then the channel masks need to be in bits 23:16. */
1878       fwa_bld.SHL(channel_mask, channel_mask, brw_imm_ud(16u));
1879    }
1880
1881    /* Store the control data bits in the message payload and send it. */
1882    int mlen = 2;
1883    if (channel_mask.file != BAD_FILE)
1884       mlen += 4; /* channel masks, plus 3 extra copies of the data */
1885    if (per_slot_offset.file != BAD_FILE)
1886       mlen++;
1887
1888    fs_reg payload = bld.vgrf(BRW_REGISTER_TYPE_UD, mlen);
1889    fs_reg *sources = ralloc_array(mem_ctx, fs_reg, mlen);
1890    int i = 0;
1891    sources[i++] = fs_reg(retype(brw_vec8_grf(1, 0), BRW_REGISTER_TYPE_UD));
1892    if (per_slot_offset.file != BAD_FILE)
1893       sources[i++] = per_slot_offset;
1894    if (channel_mask.file != BAD_FILE)
1895       sources[i++] = channel_mask;
1896    while (i < mlen) {
1897       sources[i++] = this->control_data_bits;
1898    }
1899
1900    abld.LOAD_PAYLOAD(payload, sources, mlen, mlen);
1901    fs_inst *inst = abld.emit(opcode, reg_undef, payload);
1902    inst->mlen = mlen;
1903    /* We need to increment Global Offset by 256-bits to make room for
1904     * Broadwell's extra "Vertex Count" payload at the beginning of the
1905     * URB entry.  Since this is an OWord message, Global Offset is counted
1906     * in 128-bit units, so we must set it to 2.
1907     */
1908    if (gs_prog_data->static_vertex_count == -1)
1909       inst->offset = 2;
1910 }
1911
1912 void
1913 fs_visitor::set_gs_stream_control_data_bits(const fs_reg &vertex_count,
1914                                             unsigned stream_id)
1915 {
1916    /* control_data_bits |= stream_id << ((2 * (vertex_count - 1)) % 32) */
1917
1918    /* Note: we are calling this *before* increasing vertex_count, so
1919     * this->vertex_count == vertex_count - 1 in the formula above.
1920     */
1921
1922    /* Stream mode uses 2 bits per vertex */
1923    assert(gs_compile->control_data_bits_per_vertex == 2);
1924
1925    /* Must be a valid stream */
1926    assert(stream_id < MAX_VERTEX_STREAMS);
1927
1928    /* Control data bits are initialized to 0 so we don't have to set any
1929     * bits when sending vertices to stream 0.
1930     */
1931    if (stream_id == 0)
1932       return;
1933
1934    const fs_builder abld = bld.annotate("set stream control data bits", NULL);
1935
1936    /* reg::sid = stream_id */
1937    fs_reg sid = bld.vgrf(BRW_REGISTER_TYPE_UD, 1);
1938    abld.MOV(sid, brw_imm_ud(stream_id));
1939
1940    /* reg:shift_count = 2 * (vertex_count - 1) */
1941    fs_reg shift_count = bld.vgrf(BRW_REGISTER_TYPE_UD, 1);
1942    abld.SHL(shift_count, vertex_count, brw_imm_ud(1u));
1943
1944    /* Note: we're relying on the fact that the GEN SHL instruction only pays
1945     * attention to the lower 5 bits of its second source argument, so on this
1946     * architecture, stream_id << 2 * (vertex_count - 1) is equivalent to
1947     * stream_id << ((2 * (vertex_count - 1)) % 32).
1948     */
1949    fs_reg mask = bld.vgrf(BRW_REGISTER_TYPE_UD, 1);
1950    abld.SHL(mask, sid, shift_count);
1951    abld.OR(this->control_data_bits, this->control_data_bits, mask);
1952 }
1953
1954 void
1955 fs_visitor::emit_gs_vertex(const nir_src &vertex_count_nir_src,
1956                            unsigned stream_id)
1957 {
1958    assert(stage == MESA_SHADER_GEOMETRY);
1959
1960    struct brw_gs_prog_data *gs_prog_data = brw_gs_prog_data(prog_data);
1961
1962    fs_reg vertex_count = get_nir_src(vertex_count_nir_src);
1963    vertex_count.type = BRW_REGISTER_TYPE_UD;
1964
1965    /* Haswell and later hardware ignores the "Render Stream Select" bits
1966     * from the 3DSTATE_STREAMOUT packet when the SOL stage is disabled,
1967     * and instead sends all primitives down the pipeline for rasterization.
1968     * If the SOL stage is enabled, "Render Stream Select" is honored and
1969     * primitives bound to non-zero streams are discarded after stream output.
1970     *
1971     * Since the only purpose of primives sent to non-zero streams is to
1972     * be recorded by transform feedback, we can simply discard all geometry
1973     * bound to these streams when transform feedback is disabled.
1974     */
1975    if (stream_id > 0 && !nir->info.has_transform_feedback_varyings)
1976       return;
1977
1978    /* If we're outputting 32 control data bits or less, then we can wait
1979     * until the shader is over to output them all.  Otherwise we need to
1980     * output them as we go.  Now is the time to do it, since we're about to
1981     * output the vertex_count'th vertex, so it's guaranteed that the
1982     * control data bits associated with the (vertex_count - 1)th vertex are
1983     * correct.
1984     */
1985    if (gs_compile->control_data_header_size_bits > 32) {
1986       const fs_builder abld =
1987          bld.annotate("emit vertex: emit control data bits");
1988
1989       /* Only emit control data bits if we've finished accumulating a batch
1990        * of 32 bits.  This is the case when:
1991        *
1992        *     (vertex_count * bits_per_vertex) % 32 == 0
1993        *
1994        * (in other words, when the last 5 bits of vertex_count *
1995        * bits_per_vertex are 0).  Assuming bits_per_vertex == 2^n for some
1996        * integer n (which is always the case, since bits_per_vertex is
1997        * always 1 or 2), this is equivalent to requiring that the last 5-n
1998        * bits of vertex_count are 0:
1999        *
2000        *     vertex_count & (2^(5-n) - 1) == 0
2001        *
2002        * 2^(5-n) == 2^5 / 2^n == 32 / bits_per_vertex, so this is
2003        * equivalent to:
2004        *
2005        *     vertex_count & (32 / bits_per_vertex - 1) == 0
2006        *
2007        * TODO: If vertex_count is an immediate, we could do some of this math
2008        *       at compile time...
2009        */
2010       fs_inst *inst =
2011          abld.AND(bld.null_reg_d(), vertex_count,
2012                   brw_imm_ud(32u / gs_compile->control_data_bits_per_vertex - 1u));
2013       inst->conditional_mod = BRW_CONDITIONAL_Z;
2014
2015       abld.IF(BRW_PREDICATE_NORMAL);
2016       /* If vertex_count is 0, then no control data bits have been
2017        * accumulated yet, so we can skip emitting them.
2018        */
2019       abld.CMP(bld.null_reg_d(), vertex_count, brw_imm_ud(0u),
2020                BRW_CONDITIONAL_NEQ);
2021       abld.IF(BRW_PREDICATE_NORMAL);
2022       emit_gs_control_data_bits(vertex_count);
2023       abld.emit(BRW_OPCODE_ENDIF);
2024
2025       /* Reset control_data_bits to 0 so we can start accumulating a new
2026        * batch.
2027        *
2028        * Note: in the case where vertex_count == 0, this neutralizes the
2029        * effect of any call to EndPrimitive() that the shader may have
2030        * made before outputting its first vertex.
2031        */
2032       inst = abld.MOV(this->control_data_bits, brw_imm_ud(0u));
2033       inst->force_writemask_all = true;
2034       abld.emit(BRW_OPCODE_ENDIF);
2035    }
2036
2037    emit_urb_writes(vertex_count);
2038
2039    /* In stream mode we have to set control data bits for all vertices
2040     * unless we have disabled control data bits completely (which we do
2041     * do for GL_POINTS outputs that don't use streams).
2042     */
2043    if (gs_compile->control_data_header_size_bits > 0 &&
2044        gs_prog_data->control_data_format ==
2045           GEN7_GS_CONTROL_DATA_FORMAT_GSCTL_SID) {
2046       set_gs_stream_control_data_bits(vertex_count, stream_id);
2047    }
2048 }
2049
2050 void
2051 fs_visitor::emit_gs_input_load(const fs_reg &dst,
2052                                const nir_src &vertex_src,
2053                                unsigned base_offset,
2054                                const nir_src &offset_src,
2055                                unsigned num_components,
2056                                unsigned first_component)
2057 {
2058    struct brw_gs_prog_data *gs_prog_data = brw_gs_prog_data(prog_data);
2059    const unsigned push_reg_count = gs_prog_data->base.urb_read_length * 8;
2060
2061    /* TODO: figure out push input layout for invocations == 1 */
2062    /* TODO: make this work with 64-bit inputs */
2063    if (gs_prog_data->invocations == 1 &&
2064        type_sz(dst.type) <= 4 &&
2065        nir_src_is_const(offset_src) && nir_src_is_const(vertex_src) &&
2066        4 * (base_offset + nir_src_as_uint(offset_src)) < push_reg_count) {
2067       int imm_offset = (base_offset + nir_src_as_uint(offset_src)) * 4 +
2068                        nir_src_as_uint(vertex_src) * push_reg_count;
2069       for (unsigned i = 0; i < num_components; i++) {
2070          bld.MOV(offset(dst, bld, i),
2071                  fs_reg(ATTR, imm_offset + i + first_component, dst.type));
2072       }
2073       return;
2074    }
2075
2076    /* Resort to the pull model.  Ensure the VUE handles are provided. */
2077    assert(gs_prog_data->base.include_vue_handles);
2078
2079    unsigned first_icp_handle = gs_prog_data->include_primitive_id ? 3 : 2;
2080    fs_reg icp_handle = bld.vgrf(BRW_REGISTER_TYPE_UD, 1);
2081
2082    if (gs_prog_data->invocations == 1) {
2083       if (nir_src_is_const(vertex_src)) {
2084          /* The vertex index is constant; just select the proper URB handle. */
2085          icp_handle =
2086             retype(brw_vec8_grf(first_icp_handle + nir_src_as_uint(vertex_src), 0),
2087                    BRW_REGISTER_TYPE_UD);
2088       } else {
2089          /* The vertex index is non-constant.  We need to use indirect
2090           * addressing to fetch the proper URB handle.
2091           *
2092           * First, we start with the sequence <7, 6, 5, 4, 3, 2, 1, 0>
2093           * indicating that channel <n> should read the handle from
2094           * DWord <n>.  We convert that to bytes by multiplying by 4.
2095           *
2096           * Next, we convert the vertex index to bytes by multiplying
2097           * by 32 (shifting by 5), and add the two together.  This is
2098           * the final indirect byte offset.
2099           */
2100          fs_reg sequence = bld.vgrf(BRW_REGISTER_TYPE_UW, 1);
2101          fs_reg channel_offsets = bld.vgrf(BRW_REGISTER_TYPE_UD, 1);
2102          fs_reg vertex_offset_bytes = bld.vgrf(BRW_REGISTER_TYPE_UD, 1);
2103          fs_reg icp_offset_bytes = bld.vgrf(BRW_REGISTER_TYPE_UD, 1);
2104
2105          /* sequence = <7, 6, 5, 4, 3, 2, 1, 0> */
2106          bld.MOV(sequence, fs_reg(brw_imm_v(0x76543210)));
2107          /* channel_offsets = 4 * sequence = <28, 24, 20, 16, 12, 8, 4, 0> */
2108          bld.SHL(channel_offsets, sequence, brw_imm_ud(2u));
2109          /* Convert vertex_index to bytes (multiply by 32) */
2110          bld.SHL(vertex_offset_bytes,
2111                  retype(get_nir_src(vertex_src), BRW_REGISTER_TYPE_UD),
2112                  brw_imm_ud(5u));
2113          bld.ADD(icp_offset_bytes, vertex_offset_bytes, channel_offsets);
2114
2115          /* Use first_icp_handle as the base offset.  There is one register
2116           * of URB handles per vertex, so inform the register allocator that
2117           * we might read up to nir->info.gs.vertices_in registers.
2118           */
2119          bld.emit(SHADER_OPCODE_MOV_INDIRECT, icp_handle,
2120                   retype(brw_vec8_grf(first_icp_handle, 0), icp_handle.type),
2121                   fs_reg(icp_offset_bytes),
2122                   brw_imm_ud(nir->info.gs.vertices_in * REG_SIZE));
2123       }
2124    } else {
2125       assert(gs_prog_data->invocations > 1);
2126
2127       if (nir_src_is_const(vertex_src)) {
2128          unsigned vertex = nir_src_as_uint(vertex_src);
2129          assert(devinfo->gen >= 9 || vertex <= 5);
2130          bld.MOV(icp_handle,
2131                  retype(brw_vec1_grf(first_icp_handle + vertex / 8, vertex % 8),
2132                         BRW_REGISTER_TYPE_UD));
2133       } else {
2134          /* The vertex index is non-constant.  We need to use indirect
2135           * addressing to fetch the proper URB handle.
2136           *
2137           */
2138          fs_reg icp_offset_bytes = bld.vgrf(BRW_REGISTER_TYPE_UD, 1);
2139
2140          /* Convert vertex_index to bytes (multiply by 4) */
2141          bld.SHL(icp_offset_bytes,
2142                  retype(get_nir_src(vertex_src), BRW_REGISTER_TYPE_UD),
2143                  brw_imm_ud(2u));
2144
2145          /* Use first_icp_handle as the base offset.  There is one DWord
2146           * of URB handles per vertex, so inform the register allocator that
2147           * we might read up to ceil(nir->info.gs.vertices_in / 8) registers.
2148           */
2149          bld.emit(SHADER_OPCODE_MOV_INDIRECT, icp_handle,
2150                   retype(brw_vec8_grf(first_icp_handle, 0), icp_handle.type),
2151                   fs_reg(icp_offset_bytes),
2152                   brw_imm_ud(DIV_ROUND_UP(nir->info.gs.vertices_in, 8) *
2153                              REG_SIZE));
2154       }
2155    }
2156
2157    fs_inst *inst;
2158
2159    fs_reg tmp_dst = dst;
2160    fs_reg indirect_offset = get_nir_src(offset_src);
2161    unsigned num_iterations = 1;
2162    unsigned orig_num_components = num_components;
2163
2164    if (type_sz(dst.type) == 8) {
2165       if (num_components > 2) {
2166          num_iterations = 2;
2167          num_components = 2;
2168       }
2169       fs_reg tmp = fs_reg(VGRF, alloc.allocate(4), dst.type);
2170       tmp_dst = tmp;
2171       first_component = first_component / 2;
2172    }
2173
2174    for (unsigned iter = 0; iter < num_iterations; iter++) {
2175       if (nir_src_is_const(offset_src)) {
2176          /* Constant indexing - use global offset. */
2177          if (first_component != 0) {
2178             unsigned read_components = num_components + first_component;
2179             fs_reg tmp = bld.vgrf(dst.type, read_components);
2180             inst = bld.emit(SHADER_OPCODE_URB_READ_SIMD8, tmp, icp_handle);
2181             inst->size_written = read_components *
2182                                  tmp.component_size(inst->exec_size);
2183             for (unsigned i = 0; i < num_components; i++) {
2184                bld.MOV(offset(tmp_dst, bld, i),
2185                        offset(tmp, bld, i + first_component));
2186             }
2187          } else {
2188             inst = bld.emit(SHADER_OPCODE_URB_READ_SIMD8, tmp_dst,
2189                             icp_handle);
2190             inst->size_written = num_components *
2191                                  tmp_dst.component_size(inst->exec_size);
2192          }
2193          inst->offset = base_offset + nir_src_as_uint(offset_src);
2194          inst->mlen = 1;
2195       } else {
2196          /* Indirect indexing - use per-slot offsets as well. */
2197          const fs_reg srcs[] = { icp_handle, indirect_offset };
2198          unsigned read_components = num_components + first_component;
2199          fs_reg tmp = bld.vgrf(dst.type, read_components);
2200          fs_reg payload = bld.vgrf(BRW_REGISTER_TYPE_UD, 2);
2201          bld.LOAD_PAYLOAD(payload, srcs, ARRAY_SIZE(srcs), 0);
2202          if (first_component != 0) {
2203             inst = bld.emit(SHADER_OPCODE_URB_READ_SIMD8_PER_SLOT, tmp,
2204                             payload);
2205             inst->size_written = read_components *
2206                                  tmp.component_size(inst->exec_size);
2207             for (unsigned i = 0; i < num_components; i++) {
2208                bld.MOV(offset(tmp_dst, bld, i),
2209                        offset(tmp, bld, i + first_component));
2210             }
2211          } else {
2212             inst = bld.emit(SHADER_OPCODE_URB_READ_SIMD8_PER_SLOT, tmp_dst,
2213                          payload);
2214             inst->size_written = num_components *
2215                                  tmp_dst.component_size(inst->exec_size);
2216          }
2217          inst->offset = base_offset;
2218          inst->mlen = 2;
2219       }
2220
2221       if (type_sz(dst.type) == 8) {
2222          shuffle_from_32bit_read(bld,
2223                                  offset(dst, bld, iter * 2),
2224                                  retype(tmp_dst, BRW_REGISTER_TYPE_D),
2225                                  0,
2226                                  num_components);
2227       }
2228
2229       if (num_iterations > 1) {
2230          num_components = orig_num_components - 2;
2231          if(nir_src_is_const(offset_src)) {
2232             base_offset++;
2233          } else {
2234             fs_reg new_indirect = bld.vgrf(BRW_REGISTER_TYPE_UD, 1);
2235             bld.ADD(new_indirect, indirect_offset, brw_imm_ud(1u));
2236             indirect_offset = new_indirect;
2237          }
2238       }
2239    }
2240 }
2241
2242 fs_reg
2243 fs_visitor::get_indirect_offset(nir_intrinsic_instr *instr)
2244 {
2245    nir_src *offset_src = nir_get_io_offset_src(instr);
2246
2247    if (nir_src_is_const(*offset_src)) {
2248       /* The only constant offset we should find is 0.  brw_nir.c's
2249        * add_const_offset_to_base() will fold other constant offsets
2250        * into instr->const_index[0].
2251        */
2252       assert(nir_src_as_uint(*offset_src) == 0);
2253       return fs_reg();
2254    }
2255
2256    return get_nir_src(*offset_src);
2257 }
2258
2259 void
2260 fs_visitor::nir_emit_vs_intrinsic(const fs_builder &bld,
2261                                   nir_intrinsic_instr *instr)
2262 {
2263    assert(stage == MESA_SHADER_VERTEX);
2264
2265    fs_reg dest;
2266    if (nir_intrinsic_infos[instr->intrinsic].has_dest)
2267       dest = get_nir_dest(instr->dest);
2268
2269    switch (instr->intrinsic) {
2270    case nir_intrinsic_load_vertex_id:
2271    case nir_intrinsic_load_base_vertex:
2272       unreachable("should be lowered by nir_lower_system_values()");
2273
2274    case nir_intrinsic_load_input: {
2275       fs_reg src = fs_reg(ATTR, nir_intrinsic_base(instr) * 4, dest.type);
2276       unsigned first_component = nir_intrinsic_component(instr);
2277       unsigned num_components = instr->num_components;
2278
2279       src = offset(src, bld, nir_src_as_uint(instr->src[0]));
2280
2281       if (type_sz(dest.type) == 8)
2282          first_component /= 2;
2283
2284       /* For 16-bit support maybe a temporary will be needed to copy from
2285        * the ATTR file.
2286        */
2287       shuffle_from_32bit_read(bld, dest, retype(src, BRW_REGISTER_TYPE_D),
2288                               first_component, num_components);
2289       break;
2290    }
2291
2292    case nir_intrinsic_load_vertex_id_zero_base:
2293    case nir_intrinsic_load_instance_id:
2294    case nir_intrinsic_load_base_instance:
2295    case nir_intrinsic_load_draw_id:
2296    case nir_intrinsic_load_first_vertex:
2297    case nir_intrinsic_load_is_indexed_draw:
2298       unreachable("lowered by brw_nir_lower_vs_inputs");
2299
2300    default:
2301       nir_emit_intrinsic(bld, instr);
2302       break;
2303    }
2304 }
2305
2306 void
2307 fs_visitor::nir_emit_tcs_intrinsic(const fs_builder &bld,
2308                                    nir_intrinsic_instr *instr)
2309 {
2310    assert(stage == MESA_SHADER_TESS_CTRL);
2311    struct brw_tcs_prog_key *tcs_key = (struct brw_tcs_prog_key *) key;
2312    struct brw_tcs_prog_data *tcs_prog_data = brw_tcs_prog_data(prog_data);
2313
2314    fs_reg dst;
2315    if (nir_intrinsic_infos[instr->intrinsic].has_dest)
2316       dst = get_nir_dest(instr->dest);
2317
2318    switch (instr->intrinsic) {
2319    case nir_intrinsic_load_primitive_id:
2320       bld.MOV(dst, fs_reg(brw_vec1_grf(0, 1)));
2321       break;
2322    case nir_intrinsic_load_invocation_id:
2323       bld.MOV(retype(dst, invocation_id.type), invocation_id);
2324       break;
2325    case nir_intrinsic_load_patch_vertices_in:
2326       bld.MOV(retype(dst, BRW_REGISTER_TYPE_D),
2327               brw_imm_d(tcs_key->input_vertices));
2328       break;
2329
2330    case nir_intrinsic_barrier: {
2331       if (tcs_prog_data->instances == 1)
2332          break;
2333
2334       fs_reg m0 = bld.vgrf(BRW_REGISTER_TYPE_UD, 1);
2335       fs_reg m0_2 = component(m0, 2);
2336
2337       const fs_builder chanbld = bld.exec_all().group(1, 0);
2338
2339       /* Zero the message header */
2340       bld.exec_all().MOV(m0, brw_imm_ud(0u));
2341
2342       /* Copy "Barrier ID" from r0.2, bits 16:13 */
2343       chanbld.AND(m0_2, retype(brw_vec1_grf(0, 2), BRW_REGISTER_TYPE_UD),
2344                   brw_imm_ud(INTEL_MASK(16, 13)));
2345
2346       /* Shift it up to bits 27:24. */
2347       chanbld.SHL(m0_2, m0_2, brw_imm_ud(11));
2348
2349       /* Set the Barrier Count and the enable bit */
2350       chanbld.OR(m0_2, m0_2,
2351                  brw_imm_ud(tcs_prog_data->instances << 9 | (1 << 15)));
2352
2353       bld.emit(SHADER_OPCODE_BARRIER, bld.null_reg_ud(), m0);
2354       break;
2355    }
2356
2357    case nir_intrinsic_load_input:
2358       unreachable("nir_lower_io should never give us these.");
2359       break;
2360
2361    case nir_intrinsic_load_per_vertex_input: {
2362       fs_reg indirect_offset = get_indirect_offset(instr);
2363       unsigned imm_offset = instr->const_index[0];
2364
2365       const nir_src &vertex_src = instr->src[0];
2366
2367       fs_inst *inst;
2368
2369       fs_reg icp_handle;
2370
2371       if (nir_src_is_const(vertex_src)) {
2372          /* Emit a MOV to resolve <0,1,0> regioning. */
2373          icp_handle = bld.vgrf(BRW_REGISTER_TYPE_UD, 1);
2374          unsigned vertex = nir_src_as_uint(vertex_src);
2375          bld.MOV(icp_handle,
2376                  retype(brw_vec1_grf(1 + (vertex >> 3), vertex & 7),
2377                         BRW_REGISTER_TYPE_UD));
2378       } else if (tcs_prog_data->instances == 1 &&
2379                  vertex_src.is_ssa &&
2380                  vertex_src.ssa->parent_instr->type == nir_instr_type_intrinsic &&
2381                  nir_instr_as_intrinsic(vertex_src.ssa->parent_instr)->intrinsic == nir_intrinsic_load_invocation_id) {
2382          /* For the common case of only 1 instance, an array index of
2383           * gl_InvocationID means reading g1.  Skip all the indirect work.
2384           */
2385          icp_handle = retype(brw_vec8_grf(1, 0), BRW_REGISTER_TYPE_UD);
2386       } else {
2387          /* The vertex index is non-constant.  We need to use indirect
2388           * addressing to fetch the proper URB handle.
2389           */
2390          icp_handle = bld.vgrf(BRW_REGISTER_TYPE_UD, 1);
2391
2392          /* Each ICP handle is a single DWord (4 bytes) */
2393          fs_reg vertex_offset_bytes = bld.vgrf(BRW_REGISTER_TYPE_UD, 1);
2394          bld.SHL(vertex_offset_bytes,
2395                  retype(get_nir_src(vertex_src), BRW_REGISTER_TYPE_UD),
2396                  brw_imm_ud(2u));
2397
2398          /* Start at g1.  We might read up to 4 registers. */
2399          bld.emit(SHADER_OPCODE_MOV_INDIRECT, icp_handle,
2400                   retype(brw_vec8_grf(1, 0), icp_handle.type), vertex_offset_bytes,
2401                   brw_imm_ud(4 * REG_SIZE));
2402       }
2403
2404       /* We can only read two double components with each URB read, so
2405        * we send two read messages in that case, each one loading up to
2406        * two double components.
2407        */
2408       unsigned num_iterations = 1;
2409       unsigned num_components = instr->num_components;
2410       unsigned first_component = nir_intrinsic_component(instr);
2411       fs_reg orig_dst = dst;
2412       if (type_sz(dst.type) == 8) {
2413          first_component = first_component / 2;
2414          if (instr->num_components > 2) {
2415             num_iterations = 2;
2416             num_components = 2;
2417          }
2418
2419          fs_reg tmp = fs_reg(VGRF, alloc.allocate(4), dst.type);
2420          dst = tmp;
2421       }
2422
2423       for (unsigned iter = 0; iter < num_iterations; iter++) {
2424          if (indirect_offset.file == BAD_FILE) {
2425             /* Constant indexing - use global offset. */
2426             if (first_component != 0) {
2427                unsigned read_components = num_components + first_component;
2428                fs_reg tmp = bld.vgrf(dst.type, read_components);
2429                inst = bld.emit(SHADER_OPCODE_URB_READ_SIMD8, tmp, icp_handle);
2430                for (unsigned i = 0; i < num_components; i++) {
2431                   bld.MOV(offset(dst, bld, i),
2432                           offset(tmp, bld, i + first_component));
2433                }
2434             } else {
2435                inst = bld.emit(SHADER_OPCODE_URB_READ_SIMD8, dst, icp_handle);
2436             }
2437             inst->offset = imm_offset;
2438             inst->mlen = 1;
2439          } else {
2440             /* Indirect indexing - use per-slot offsets as well. */
2441             const fs_reg srcs[] = { icp_handle, indirect_offset };
2442             fs_reg payload = bld.vgrf(BRW_REGISTER_TYPE_UD, 2);
2443             bld.LOAD_PAYLOAD(payload, srcs, ARRAY_SIZE(srcs), 0);
2444             if (first_component != 0) {
2445                unsigned read_components = num_components + first_component;
2446                fs_reg tmp = bld.vgrf(dst.type, read_components);
2447                inst = bld.emit(SHADER_OPCODE_URB_READ_SIMD8_PER_SLOT, tmp,
2448                                payload);
2449                for (unsigned i = 0; i < num_components; i++) {
2450                   bld.MOV(offset(dst, bld, i),
2451                           offset(tmp, bld, i + first_component));
2452                }
2453             } else {
2454                inst = bld.emit(SHADER_OPCODE_URB_READ_SIMD8_PER_SLOT, dst,
2455                                payload);
2456             }
2457             inst->offset = imm_offset;
2458             inst->mlen = 2;
2459          }
2460          inst->size_written = (num_components + first_component) *
2461                               inst->dst.component_size(inst->exec_size);
2462
2463          /* If we are reading 64-bit data using 32-bit read messages we need
2464           * build proper 64-bit data elements by shuffling the low and high
2465           * 32-bit components around like we do for other things like UBOs
2466           * or SSBOs.
2467           */
2468          if (type_sz(dst.type) == 8) {
2469             shuffle_from_32bit_read(bld,
2470                                     offset(orig_dst, bld, iter * 2),
2471                                     retype(dst, BRW_REGISTER_TYPE_D),
2472                                     0, num_components);
2473          }
2474
2475          /* Copy the temporary to the destination to deal with writemasking.
2476           *
2477           * Also attempt to deal with gl_PointSize being in the .w component.
2478           */
2479          if (inst->offset == 0 && indirect_offset.file == BAD_FILE) {
2480             assert(type_sz(dst.type) < 8);
2481             inst->dst = bld.vgrf(dst.type, 4);
2482             inst->size_written = 4 * REG_SIZE;
2483             bld.MOV(dst, offset(inst->dst, bld, 3));
2484          }
2485
2486          /* If we are loading double data and we need a second read message
2487           * adjust the write offset
2488           */
2489          if (num_iterations > 1) {
2490             num_components = instr->num_components - 2;
2491             imm_offset++;
2492          }
2493       }
2494       break;
2495    }
2496
2497    case nir_intrinsic_load_output:
2498    case nir_intrinsic_load_per_vertex_output: {
2499       fs_reg indirect_offset = get_indirect_offset(instr);
2500       unsigned imm_offset = instr->const_index[0];
2501       unsigned first_component = nir_intrinsic_component(instr);
2502
2503       fs_inst *inst;
2504       if (indirect_offset.file == BAD_FILE) {
2505          /* Replicate the patch handle to all enabled channels */
2506          fs_reg patch_handle = bld.vgrf(BRW_REGISTER_TYPE_UD, 1);
2507          bld.MOV(patch_handle,
2508                  retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_UD));
2509
2510          {
2511             if (first_component != 0) {
2512                unsigned read_components =
2513                   instr->num_components + first_component;
2514                fs_reg tmp = bld.vgrf(dst.type, read_components);
2515                inst = bld.emit(SHADER_OPCODE_URB_READ_SIMD8, tmp,
2516                                patch_handle);
2517                inst->size_written = read_components * REG_SIZE;
2518                for (unsigned i = 0; i < instr->num_components; i++) {
2519                   bld.MOV(offset(dst, bld, i),
2520                           offset(tmp, bld, i + first_component));
2521                }
2522             } else {
2523                inst = bld.emit(SHADER_OPCODE_URB_READ_SIMD8, dst,
2524                                patch_handle);
2525                inst->size_written = instr->num_components * REG_SIZE;
2526             }
2527             inst->offset = imm_offset;
2528             inst->mlen = 1;
2529          }
2530       } else {
2531          /* Indirect indexing - use per-slot offsets as well. */
2532          const fs_reg srcs[] = {
2533             retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_UD),
2534             indirect_offset
2535          };
2536          fs_reg payload = bld.vgrf(BRW_REGISTER_TYPE_UD, 2);
2537          bld.LOAD_PAYLOAD(payload, srcs, ARRAY_SIZE(srcs), 0);
2538          if (first_component != 0) {
2539             unsigned read_components =
2540                instr->num_components + first_component;
2541             fs_reg tmp = bld.vgrf(dst.type, read_components);
2542             inst = bld.emit(SHADER_OPCODE_URB_READ_SIMD8_PER_SLOT, tmp,
2543                             payload);
2544             inst->size_written = read_components * REG_SIZE;
2545             for (unsigned i = 0; i < instr->num_components; i++) {
2546                bld.MOV(offset(dst, bld, i),
2547                        offset(tmp, bld, i + first_component));
2548             }
2549          } else {
2550             inst = bld.emit(SHADER_OPCODE_URB_READ_SIMD8_PER_SLOT, dst,
2551                             payload);
2552             inst->size_written = instr->num_components * REG_SIZE;
2553          }
2554          inst->offset = imm_offset;
2555          inst->mlen = 2;
2556       }
2557       break;
2558    }
2559
2560    case nir_intrinsic_store_output:
2561    case nir_intrinsic_store_per_vertex_output: {
2562       fs_reg value = get_nir_src(instr->src[0]);
2563       bool is_64bit = (instr->src[0].is_ssa ?
2564          instr->src[0].ssa->bit_size : instr->src[0].reg.reg->bit_size) == 64;
2565       fs_reg indirect_offset = get_indirect_offset(instr);
2566       unsigned imm_offset = instr->const_index[0];
2567       unsigned mask = instr->const_index[1];
2568       unsigned header_regs = 0;
2569       fs_reg srcs[7];
2570       srcs[header_regs++] = retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_UD);
2571
2572       if (indirect_offset.file != BAD_FILE) {
2573          srcs[header_regs++] = indirect_offset;
2574       }
2575
2576       if (mask == 0)
2577          break;
2578
2579       unsigned num_components = util_last_bit(mask);
2580       enum opcode opcode;
2581
2582       /* We can only pack two 64-bit components in a single message, so send
2583        * 2 messages if we have more components
2584        */
2585       unsigned num_iterations = 1;
2586       unsigned iter_components = num_components;
2587       unsigned first_component = nir_intrinsic_component(instr);
2588       if (is_64bit) {
2589          first_component = first_component / 2;
2590          if (instr->num_components > 2) {
2591             num_iterations = 2;
2592             iter_components = 2;
2593          }
2594       }
2595
2596       mask = mask << first_component;
2597
2598       for (unsigned iter = 0; iter < num_iterations; iter++) {
2599          if (!is_64bit && mask != WRITEMASK_XYZW) {
2600             srcs[header_regs++] = brw_imm_ud(mask << 16);
2601             opcode = indirect_offset.file != BAD_FILE ?
2602                SHADER_OPCODE_URB_WRITE_SIMD8_MASKED_PER_SLOT :
2603                SHADER_OPCODE_URB_WRITE_SIMD8_MASKED;
2604          } else if (is_64bit && ((mask & WRITEMASK_XY) != WRITEMASK_XY)) {
2605             /* Expand the 64-bit mask to 32-bit channels. We only handle
2606              * two channels in each iteration, so we only care about X/Y.
2607              */
2608             unsigned mask32 = 0;
2609             if (mask & WRITEMASK_X)
2610                mask32 |= WRITEMASK_XY;
2611             if (mask & WRITEMASK_Y)
2612                mask32 |= WRITEMASK_ZW;
2613
2614             /* If the mask does not include any of the channels X or Y there
2615              * is nothing to do in this iteration. Move on to the next couple
2616              * of 64-bit channels.
2617              */
2618             if (!mask32) {
2619                mask >>= 2;
2620                imm_offset++;
2621                continue;
2622             }
2623
2624             srcs[header_regs++] = brw_imm_ud(mask32 << 16);
2625             opcode = indirect_offset.file != BAD_FILE ?
2626                SHADER_OPCODE_URB_WRITE_SIMD8_MASKED_PER_SLOT :
2627                SHADER_OPCODE_URB_WRITE_SIMD8_MASKED;
2628          } else {
2629             opcode = indirect_offset.file != BAD_FILE ?
2630                SHADER_OPCODE_URB_WRITE_SIMD8_PER_SLOT :
2631                SHADER_OPCODE_URB_WRITE_SIMD8;
2632          }
2633
2634          for (unsigned i = 0; i < iter_components; i++) {
2635             if (!(mask & (1 << (i + first_component))))
2636                continue;
2637
2638             if (!is_64bit) {
2639                srcs[header_regs + i + first_component] = offset(value, bld, i);
2640             } else {
2641                /* We need to shuffle the 64-bit data to match the layout
2642                 * expected by our 32-bit URB write messages. We use a temporary
2643                 * for that.
2644                 */
2645                unsigned channel = iter * 2 + i;
2646                fs_reg dest = shuffle_for_32bit_write(bld, value, channel, 1);
2647
2648                srcs[header_regs + (i + first_component) * 2] = dest;
2649                srcs[header_regs + (i + first_component) * 2 + 1] =
2650                   offset(dest, bld, 1);
2651             }
2652          }
2653
2654          unsigned mlen =
2655             header_regs + (is_64bit ? 2 * iter_components : iter_components) +
2656             (is_64bit ? 2 * first_component : first_component);
2657          fs_reg payload =
2658             bld.vgrf(BRW_REGISTER_TYPE_UD, mlen);
2659          bld.LOAD_PAYLOAD(payload, srcs, mlen, header_regs);
2660
2661          fs_inst *inst = bld.emit(opcode, bld.null_reg_ud(), payload);
2662          inst->offset = imm_offset;
2663          inst->mlen = mlen;
2664
2665          /* If this is a 64-bit attribute, select the next two 64-bit channels
2666           * to be handled in the next iteration.
2667           */
2668          if (is_64bit) {
2669             mask >>= 2;
2670             imm_offset++;
2671          }
2672       }
2673       break;
2674    }
2675
2676    default:
2677       nir_emit_intrinsic(bld, instr);
2678       break;
2679    }
2680 }
2681
2682 void
2683 fs_visitor::nir_emit_tes_intrinsic(const fs_builder &bld,
2684                                    nir_intrinsic_instr *instr)
2685 {
2686    assert(stage == MESA_SHADER_TESS_EVAL);
2687    struct brw_tes_prog_data *tes_prog_data = brw_tes_prog_data(prog_data);
2688
2689    fs_reg dest;
2690    if (nir_intrinsic_infos[instr->intrinsic].has_dest)
2691       dest = get_nir_dest(instr->dest);
2692
2693    switch (instr->intrinsic) {
2694    case nir_intrinsic_load_primitive_id:
2695       bld.MOV(dest, fs_reg(brw_vec1_grf(0, 1)));
2696       break;
2697    case nir_intrinsic_load_tess_coord:
2698       /* gl_TessCoord is part of the payload in g1-3 */
2699       for (unsigned i = 0; i < 3; i++) {
2700          bld.MOV(offset(dest, bld, i), fs_reg(brw_vec8_grf(1 + i, 0)));
2701       }
2702       break;
2703
2704    case nir_intrinsic_load_input:
2705    case nir_intrinsic_load_per_vertex_input: {
2706       fs_reg indirect_offset = get_indirect_offset(instr);
2707       unsigned imm_offset = instr->const_index[0];
2708       unsigned first_component = nir_intrinsic_component(instr);
2709
2710       if (type_sz(dest.type) == 8) {
2711          first_component = first_component / 2;
2712       }
2713
2714       fs_inst *inst;
2715       if (indirect_offset.file == BAD_FILE) {
2716          /* Arbitrarily only push up to 32 vec4 slots worth of data,
2717           * which is 16 registers (since each holds 2 vec4 slots).
2718           */
2719          unsigned slot_count = 1;
2720          if (type_sz(dest.type) == 8 && instr->num_components > 2)
2721             slot_count++;
2722
2723          const unsigned max_push_slots = 32;
2724          if (imm_offset + slot_count <= max_push_slots) {
2725             fs_reg src = fs_reg(ATTR, imm_offset / 2, dest.type);
2726             for (int i = 0; i < instr->num_components; i++) {
2727                unsigned comp = 16 / type_sz(dest.type) * (imm_offset % 2) +
2728                   i + first_component;
2729                bld.MOV(offset(dest, bld, i), component(src, comp));
2730             }
2731
2732             tes_prog_data->base.urb_read_length =
2733                MAX2(tes_prog_data->base.urb_read_length,
2734                     DIV_ROUND_UP(imm_offset + slot_count, 2));
2735          } else {
2736             /* Replicate the patch handle to all enabled channels */
2737             const fs_reg srcs[] = {
2738                retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_UD)
2739             };
2740             fs_reg patch_handle = bld.vgrf(BRW_REGISTER_TYPE_UD, 1);
2741             bld.LOAD_PAYLOAD(patch_handle, srcs, ARRAY_SIZE(srcs), 0);
2742
2743             if (first_component != 0) {
2744                unsigned read_components =
2745                   instr->num_components + first_component;
2746                fs_reg tmp = bld.vgrf(dest.type, read_components);
2747                inst = bld.emit(SHADER_OPCODE_URB_READ_SIMD8, tmp,
2748                                patch_handle);
2749                inst->size_written = read_components * REG_SIZE;
2750                for (unsigned i = 0; i < instr->num_components; i++) {
2751                   bld.MOV(offset(dest, bld, i),
2752                           offset(tmp, bld, i + first_component));
2753                }
2754             } else {
2755                inst = bld.emit(SHADER_OPCODE_URB_READ_SIMD8, dest,
2756                                patch_handle);
2757                inst->size_written = instr->num_components * REG_SIZE;
2758             }
2759             inst->mlen = 1;
2760             inst->offset = imm_offset;
2761          }
2762       } else {
2763          /* Indirect indexing - use per-slot offsets as well. */
2764
2765          /* We can only read two double components with each URB read, so
2766           * we send two read messages in that case, each one loading up to
2767           * two double components.
2768           */
2769          unsigned num_iterations = 1;
2770          unsigned num_components = instr->num_components;
2771          fs_reg orig_dest = dest;
2772          if (type_sz(dest.type) == 8) {
2773             if (instr->num_components > 2) {
2774                num_iterations = 2;
2775                num_components = 2;
2776             }
2777             fs_reg tmp = fs_reg(VGRF, alloc.allocate(4), dest.type);
2778             dest = tmp;
2779          }
2780
2781          for (unsigned iter = 0; iter < num_iterations; iter++) {
2782             const fs_reg srcs[] = {
2783                retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_UD),
2784                indirect_offset
2785             };
2786             fs_reg payload = bld.vgrf(BRW_REGISTER_TYPE_UD, 2);
2787             bld.LOAD_PAYLOAD(payload, srcs, ARRAY_SIZE(srcs), 0);
2788
2789             if (first_component != 0) {
2790                unsigned read_components =
2791                    num_components + first_component;
2792                fs_reg tmp = bld.vgrf(dest.type, read_components);
2793                inst = bld.emit(SHADER_OPCODE_URB_READ_SIMD8_PER_SLOT, tmp,
2794                                payload);
2795                for (unsigned i = 0; i < num_components; i++) {
2796                   bld.MOV(offset(dest, bld, i),
2797                           offset(tmp, bld, i + first_component));
2798                }
2799             } else {
2800                inst = bld.emit(SHADER_OPCODE_URB_READ_SIMD8_PER_SLOT, dest,
2801                                payload);
2802             }
2803             inst->mlen = 2;
2804             inst->offset = imm_offset;
2805             inst->size_written = (num_components + first_component) *
2806                                  inst->dst.component_size(inst->exec_size);
2807
2808             /* If we are reading 64-bit data using 32-bit read messages we need
2809              * build proper 64-bit data elements by shuffling the low and high
2810              * 32-bit components around like we do for other things like UBOs
2811              * or SSBOs.
2812              */
2813             if (type_sz(dest.type) == 8) {
2814                shuffle_from_32bit_read(bld,
2815                                        offset(orig_dest, bld, iter * 2),
2816                                        retype(dest, BRW_REGISTER_TYPE_D),
2817                                        0, num_components);
2818             }
2819
2820             /* If we are loading double data and we need a second read message
2821              * adjust the offset
2822              */
2823             if (num_iterations > 1) {
2824                num_components = instr->num_components - 2;
2825                imm_offset++;
2826             }
2827          }
2828       }
2829       break;
2830    }
2831    default:
2832       nir_emit_intrinsic(bld, instr);
2833       break;
2834    }
2835 }
2836
2837 void
2838 fs_visitor::nir_emit_gs_intrinsic(const fs_builder &bld,
2839                                   nir_intrinsic_instr *instr)
2840 {
2841    assert(stage == MESA_SHADER_GEOMETRY);
2842    fs_reg indirect_offset;
2843
2844    fs_reg dest;
2845    if (nir_intrinsic_infos[instr->intrinsic].has_dest)
2846       dest = get_nir_dest(instr->dest);
2847
2848    switch (instr->intrinsic) {
2849    case nir_intrinsic_load_primitive_id:
2850       assert(stage == MESA_SHADER_GEOMETRY);
2851       assert(brw_gs_prog_data(prog_data)->include_primitive_id);
2852       bld.MOV(retype(dest, BRW_REGISTER_TYPE_UD),
2853               retype(fs_reg(brw_vec8_grf(2, 0)), BRW_REGISTER_TYPE_UD));
2854       break;
2855
2856    case nir_intrinsic_load_input:
2857       unreachable("load_input intrinsics are invalid for the GS stage");
2858
2859    case nir_intrinsic_load_per_vertex_input:
2860       emit_gs_input_load(dest, instr->src[0], instr->const_index[0],
2861                          instr->src[1], instr->num_components,
2862                          nir_intrinsic_component(instr));
2863       break;
2864
2865    case nir_intrinsic_emit_vertex_with_counter:
2866       emit_gs_vertex(instr->src[0], instr->const_index[0]);
2867       break;
2868
2869    case nir_intrinsic_end_primitive_with_counter:
2870       emit_gs_end_primitive(instr->src[0]);
2871       break;
2872
2873    case nir_intrinsic_set_vertex_count:
2874       bld.MOV(this->final_gs_vertex_count, get_nir_src(instr->src[0]));
2875       break;
2876
2877    case nir_intrinsic_load_invocation_id: {
2878       fs_reg val = nir_system_values[SYSTEM_VALUE_INVOCATION_ID];
2879       assert(val.file != BAD_FILE);
2880       dest.type = val.type;
2881       bld.MOV(dest, val);
2882       break;
2883    }
2884
2885    default:
2886       nir_emit_intrinsic(bld, instr);
2887       break;
2888    }
2889 }
2890
2891 /**
2892  * Fetch the current render target layer index.
2893  */
2894 static fs_reg
2895 fetch_render_target_array_index(const fs_builder &bld)
2896 {
2897    if (bld.shader->devinfo->gen >= 6) {
2898       /* The render target array index is provided in the thread payload as
2899        * bits 26:16 of r0.0.
2900        */
2901       const fs_reg idx = bld.vgrf(BRW_REGISTER_TYPE_UD);
2902       bld.AND(idx, brw_uw1_reg(BRW_GENERAL_REGISTER_FILE, 0, 1),
2903               brw_imm_uw(0x7ff));
2904       return idx;
2905    } else {
2906       /* Pre-SNB we only ever render into the first layer of the framebuffer
2907        * since layered rendering is not implemented.
2908        */
2909       return brw_imm_ud(0);
2910    }
2911 }
2912
2913 /**
2914  * Fake non-coherent framebuffer read implemented using TXF to fetch from the
2915  * framebuffer at the current fragment coordinates and sample index.
2916  */
2917 fs_inst *
2918 fs_visitor::emit_non_coherent_fb_read(const fs_builder &bld, const fs_reg &dst,
2919                                       unsigned target)
2920 {
2921    const struct gen_device_info *devinfo = bld.shader->devinfo;
2922
2923    assert(bld.shader->stage == MESA_SHADER_FRAGMENT);
2924    const brw_wm_prog_key *wm_key =
2925       reinterpret_cast<const brw_wm_prog_key *>(key);
2926    assert(!wm_key->coherent_fb_fetch);
2927    const struct brw_wm_prog_data *wm_prog_data =
2928       brw_wm_prog_data(stage_prog_data);
2929
2930    /* Calculate the surface index relative to the start of the texture binding
2931     * table block, since that's what the texturing messages expect.
2932     */
2933    const unsigned surface = target +
2934       wm_prog_data->binding_table.render_target_read_start -
2935       wm_prog_data->base.binding_table.texture_start;
2936
2937    brw_mark_surface_used(
2938       bld.shader->stage_prog_data,
2939       wm_prog_data->binding_table.render_target_read_start + target);
2940
2941    /* Calculate the fragment coordinates. */
2942    const fs_reg coords = bld.vgrf(BRW_REGISTER_TYPE_UD, 3);
2943    bld.MOV(offset(coords, bld, 0), pixel_x);
2944    bld.MOV(offset(coords, bld, 1), pixel_y);
2945    bld.MOV(offset(coords, bld, 2), fetch_render_target_array_index(bld));
2946
2947    /* Calculate the sample index and MCS payload when multisampling.  Luckily
2948     * the MCS fetch message behaves deterministically for UMS surfaces, so it
2949     * shouldn't be necessary to recompile based on whether the framebuffer is
2950     * CMS or UMS.
2951     */
2952    if (wm_key->multisample_fbo &&
2953        nir_system_values[SYSTEM_VALUE_SAMPLE_ID].file == BAD_FILE)
2954       nir_system_values[SYSTEM_VALUE_SAMPLE_ID] = *emit_sampleid_setup();
2955
2956    const fs_reg sample = nir_system_values[SYSTEM_VALUE_SAMPLE_ID];
2957    const fs_reg mcs = wm_key->multisample_fbo ?
2958       emit_mcs_fetch(coords, 3, brw_imm_ud(surface)) : fs_reg();
2959
2960    /* Use either a normal or a CMS texel fetch message depending on whether
2961     * the framebuffer is single or multisample.  On SKL+ use the wide CMS
2962     * message just in case the framebuffer uses 16x multisampling, it should
2963     * be equivalent to the normal CMS fetch for lower multisampling modes.
2964     */
2965    const opcode op = !wm_key->multisample_fbo ? SHADER_OPCODE_TXF_LOGICAL :
2966                      devinfo->gen >= 9 ? SHADER_OPCODE_TXF_CMS_W_LOGICAL :
2967                      SHADER_OPCODE_TXF_CMS_LOGICAL;
2968
2969    /* Emit the instruction. */
2970    const fs_reg srcs[] = { coords, fs_reg(), brw_imm_ud(0), fs_reg(),
2971                            fs_reg(), sample, mcs,
2972                            brw_imm_ud(surface), brw_imm_ud(0),
2973                            fs_reg(), brw_imm_ud(3), brw_imm_ud(0) };
2974    STATIC_ASSERT(ARRAY_SIZE(srcs) == TEX_LOGICAL_NUM_SRCS);
2975
2976    fs_inst *inst = bld.emit(op, dst, srcs, ARRAY_SIZE(srcs));
2977    inst->size_written = 4 * inst->dst.component_size(inst->exec_size);
2978
2979    return inst;
2980 }
2981
2982 /**
2983  * Actual coherent framebuffer read implemented using the native render target
2984  * read message.  Requires SKL+.
2985  */
2986 static fs_inst *
2987 emit_coherent_fb_read(const fs_builder &bld, const fs_reg &dst, unsigned target)
2988 {
2989    assert(bld.shader->devinfo->gen >= 9);
2990    fs_inst *inst = bld.emit(FS_OPCODE_FB_READ_LOGICAL, dst);
2991    inst->target = target;
2992    inst->size_written = 4 * inst->dst.component_size(inst->exec_size);
2993
2994    return inst;
2995 }
2996
2997 static fs_reg
2998 alloc_temporary(const fs_builder &bld, unsigned size, fs_reg *regs, unsigned n)
2999 {
3000    if (n && regs[0].file != BAD_FILE) {
3001       return regs[0];
3002
3003    } else {
3004       const fs_reg tmp = bld.vgrf(BRW_REGISTER_TYPE_F, size);
3005
3006       for (unsigned i = 0; i < n; i++)
3007          regs[i] = tmp;
3008
3009       return tmp;
3010    }
3011 }
3012
3013 static fs_reg
3014 alloc_frag_output(fs_visitor *v, unsigned location)
3015 {
3016    assert(v->stage == MESA_SHADER_FRAGMENT);
3017    const brw_wm_prog_key *const key =
3018       reinterpret_cast<const brw_wm_prog_key *>(v->key);
3019    const unsigned l = GET_FIELD(location, BRW_NIR_FRAG_OUTPUT_LOCATION);
3020    const unsigned i = GET_FIELD(location, BRW_NIR_FRAG_OUTPUT_INDEX);
3021
3022    if (i > 0 || (key->force_dual_color_blend && l == FRAG_RESULT_DATA1))
3023       return alloc_temporary(v->bld, 4, &v->dual_src_output, 1);
3024
3025    else if (l == FRAG_RESULT_COLOR)
3026       return alloc_temporary(v->bld, 4, v->outputs,
3027                              MAX2(key->nr_color_regions, 1));
3028
3029    else if (l == FRAG_RESULT_DEPTH)
3030       return alloc_temporary(v->bld, 1, &v->frag_depth, 1);
3031
3032    else if (l == FRAG_RESULT_STENCIL)
3033       return alloc_temporary(v->bld, 1, &v->frag_stencil, 1);
3034
3035    else if (l == FRAG_RESULT_SAMPLE_MASK)
3036       return alloc_temporary(v->bld, 1, &v->sample_mask, 1);
3037
3038    else if (l >= FRAG_RESULT_DATA0 &&
3039             l < FRAG_RESULT_DATA0 + BRW_MAX_DRAW_BUFFERS)
3040       return alloc_temporary(v->bld, 4,
3041                              &v->outputs[l - FRAG_RESULT_DATA0], 1);
3042
3043    else
3044       unreachable("Invalid location");
3045 }
3046
3047 void
3048 fs_visitor::nir_emit_fs_intrinsic(const fs_builder &bld,
3049                                   nir_intrinsic_instr *instr)
3050 {
3051    assert(stage == MESA_SHADER_FRAGMENT);
3052
3053    fs_reg dest;
3054    if (nir_intrinsic_infos[instr->intrinsic].has_dest)
3055       dest = get_nir_dest(instr->dest);
3056
3057    switch (instr->intrinsic) {
3058    case nir_intrinsic_load_front_face:
3059       bld.MOV(retype(dest, BRW_REGISTER_TYPE_D),
3060               *emit_frontfacing_interpolation());
3061       break;
3062
3063    case nir_intrinsic_load_sample_pos: {
3064       fs_reg sample_pos = nir_system_values[SYSTEM_VALUE_SAMPLE_POS];
3065       assert(sample_pos.file != BAD_FILE);
3066       dest.type = sample_pos.type;
3067       bld.MOV(dest, sample_pos);
3068       bld.MOV(offset(dest, bld, 1), offset(sample_pos, bld, 1));
3069       break;
3070    }
3071
3072    case nir_intrinsic_load_layer_id:
3073       dest.type = BRW_REGISTER_TYPE_UD;
3074       bld.MOV(dest, fetch_render_target_array_index(bld));
3075       break;
3076
3077    case nir_intrinsic_load_helper_invocation:
3078    case nir_intrinsic_load_sample_mask_in:
3079    case nir_intrinsic_load_sample_id: {
3080       gl_system_value sv = nir_system_value_from_intrinsic(instr->intrinsic);
3081       fs_reg val = nir_system_values[sv];
3082       assert(val.file != BAD_FILE);
3083       dest.type = val.type;
3084       bld.MOV(dest, val);
3085       break;
3086    }
3087
3088    case nir_intrinsic_store_output: {
3089       const fs_reg src = get_nir_src(instr->src[0]);
3090       const unsigned store_offset = nir_src_as_uint(instr->src[1]);
3091       const unsigned location = nir_intrinsic_base(instr) +
3092          SET_FIELD(store_offset, BRW_NIR_FRAG_OUTPUT_LOCATION);
3093       const fs_reg new_dest = retype(alloc_frag_output(this, location),
3094                                      src.type);
3095
3096       for (unsigned j = 0; j < instr->num_components; j++)
3097          bld.MOV(offset(new_dest, bld, nir_intrinsic_component(instr) + j),
3098                  offset(src, bld, j));
3099
3100       break;
3101    }
3102
3103    case nir_intrinsic_load_output: {
3104       const unsigned l = GET_FIELD(nir_intrinsic_base(instr),
3105                                    BRW_NIR_FRAG_OUTPUT_LOCATION);
3106       assert(l >= FRAG_RESULT_DATA0);
3107       const unsigned load_offset = nir_src_as_uint(instr->src[0]);
3108       const unsigned target = l - FRAG_RESULT_DATA0 + load_offset;
3109       const fs_reg tmp = bld.vgrf(dest.type, 4);
3110
3111       if (reinterpret_cast<const brw_wm_prog_key *>(key)->coherent_fb_fetch)
3112          emit_coherent_fb_read(bld, tmp, target);
3113       else
3114          emit_non_coherent_fb_read(bld, tmp, target);
3115
3116       for (unsigned j = 0; j < instr->num_components; j++) {
3117          bld.MOV(offset(dest, bld, j),
3118                  offset(tmp, bld, nir_intrinsic_component(instr) + j));
3119       }
3120
3121       break;
3122    }
3123
3124    case nir_intrinsic_discard:
3125    case nir_intrinsic_discard_if: {
3126       /* We track our discarded pixels in f0.1.  By predicating on it, we can
3127        * update just the flag bits that aren't yet discarded.  If there's no
3128        * condition, we emit a CMP of g0 != g0, so all currently executing
3129        * channels will get turned off.
3130        */
3131       fs_inst *cmp;
3132       if (instr->intrinsic == nir_intrinsic_discard_if) {
3133          cmp = bld.CMP(bld.null_reg_f(), get_nir_src(instr->src[0]),
3134                        brw_imm_d(0), BRW_CONDITIONAL_Z);
3135       } else {
3136          fs_reg some_reg = fs_reg(retype(brw_vec8_grf(0, 0),
3137                                        BRW_REGISTER_TYPE_UW));
3138          cmp = bld.CMP(bld.null_reg_f(), some_reg, some_reg, BRW_CONDITIONAL_NZ);
3139       }
3140       cmp->predicate = BRW_PREDICATE_NORMAL;
3141       cmp->flag_subreg = 1;
3142
3143       if (devinfo->gen >= 6) {
3144          emit_discard_jump();
3145       }
3146
3147       limit_dispatch_width(16, "Fragment discard not implemented in SIMD32 mode.");
3148       break;
3149    }
3150
3151    case nir_intrinsic_load_input: {
3152       /* load_input is only used for flat inputs */
3153       unsigned base = nir_intrinsic_base(instr);
3154       unsigned comp = nir_intrinsic_component(instr);
3155       unsigned num_components = instr->num_components;
3156       fs_reg orig_dest = dest;
3157       enum brw_reg_type type = dest.type;
3158
3159       /* Special case fields in the VUE header */
3160       if (base == VARYING_SLOT_LAYER)
3161          comp = 1;
3162       else if (base == VARYING_SLOT_VIEWPORT)
3163          comp = 2;
3164
3165       if (nir_dest_bit_size(instr->dest) == 64) {
3166          /* const_index is in 32-bit type size units that could not be aligned
3167           * with DF. We need to read the double vector as if it was a float
3168           * vector of twice the number of components to fetch the right data.
3169           */
3170          type = BRW_REGISTER_TYPE_F;
3171          num_components *= 2;
3172          dest = bld.vgrf(type, num_components);
3173       }
3174
3175       for (unsigned int i = 0; i < num_components; i++) {
3176          bld.MOV(offset(retype(dest, type), bld, i),
3177                  retype(component(interp_reg(base, comp + i), 3), type));
3178       }
3179
3180       if (nir_dest_bit_size(instr->dest) == 64) {
3181          shuffle_from_32bit_read(bld, orig_dest, dest, 0,
3182                                  instr->num_components);
3183       }
3184       break;
3185    }
3186
3187    case nir_intrinsic_load_barycentric_pixel:
3188    case nir_intrinsic_load_barycentric_centroid:
3189    case nir_intrinsic_load_barycentric_sample:
3190       /* Do nothing - load_interpolated_input handling will handle it later. */
3191       break;
3192
3193    case nir_intrinsic_load_barycentric_at_sample: {
3194       const glsl_interp_mode interpolation =
3195          (enum glsl_interp_mode) nir_intrinsic_interp_mode(instr);
3196
3197       if (nir_src_is_const(instr->src[0])) {
3198          unsigned msg_data = nir_src_as_uint(instr->src[0]) << 4;
3199
3200          emit_pixel_interpolater_send(bld,
3201                                       FS_OPCODE_INTERPOLATE_AT_SAMPLE,
3202                                       dest,
3203                                       fs_reg(), /* src */
3204                                       brw_imm_ud(msg_data),
3205                                       interpolation);
3206       } else {
3207          const fs_reg sample_src = retype(get_nir_src(instr->src[0]),
3208                                           BRW_REGISTER_TYPE_UD);
3209
3210          if (nir_src_is_dynamically_uniform(instr->src[0])) {
3211             const fs_reg sample_id = bld.emit_uniformize(sample_src);
3212             const fs_reg msg_data = vgrf(glsl_type::uint_type);
3213             bld.exec_all().group(1, 0)
3214                .SHL(msg_data, sample_id, brw_imm_ud(4u));
3215             emit_pixel_interpolater_send(bld,
3216                                          FS_OPCODE_INTERPOLATE_AT_SAMPLE,
3217                                          dest,
3218                                          fs_reg(), /* src */
3219                                          msg_data,
3220                                          interpolation);
3221          } else {
3222             /* Make a loop that sends a message to the pixel interpolater
3223              * for the sample number in each live channel. If there are
3224              * multiple channels with the same sample number then these
3225              * will be handled simultaneously with a single interation of
3226              * the loop.
3227              */
3228             bld.emit(BRW_OPCODE_DO);
3229
3230             /* Get the next live sample number into sample_id_reg */
3231             const fs_reg sample_id = bld.emit_uniformize(sample_src);
3232
3233             /* Set the flag register so that we can perform the send
3234              * message on all channels that have the same sample number
3235              */
3236             bld.CMP(bld.null_reg_ud(),
3237                     sample_src, sample_id,
3238                     BRW_CONDITIONAL_EQ);
3239             const fs_reg msg_data = vgrf(glsl_type::uint_type);
3240             bld.exec_all().group(1, 0)
3241                .SHL(msg_data, sample_id, brw_imm_ud(4u));
3242             fs_inst *inst =
3243                emit_pixel_interpolater_send(bld,
3244                                             FS_OPCODE_INTERPOLATE_AT_SAMPLE,
3245                                             dest,
3246                                             fs_reg(), /* src */
3247                                             component(msg_data, 0),
3248                                             interpolation);
3249             set_predicate(BRW_PREDICATE_NORMAL, inst);
3250
3251             /* Continue the loop if there are any live channels left */
3252             set_predicate_inv(BRW_PREDICATE_NORMAL,
3253                               true, /* inverse */
3254                               bld.emit(BRW_OPCODE_WHILE));
3255          }
3256       }
3257       break;
3258    }
3259
3260    case nir_intrinsic_load_barycentric_at_offset: {
3261       const glsl_interp_mode interpolation =
3262          (enum glsl_interp_mode) nir_intrinsic_interp_mode(instr);
3263
3264       nir_const_value *const_offset = nir_src_as_const_value(instr->src[0]);
3265
3266       if (const_offset) {
3267          assert(nir_src_bit_size(instr->src[0]) == 32);
3268          unsigned off_x = MIN2((int)(const_offset->f32[0] * 16), 7) & 0xf;
3269          unsigned off_y = MIN2((int)(const_offset->f32[1] * 16), 7) & 0xf;
3270
3271          emit_pixel_interpolater_send(bld,
3272                                       FS_OPCODE_INTERPOLATE_AT_SHARED_OFFSET,
3273                                       dest,
3274                                       fs_reg(), /* src */
3275                                       brw_imm_ud(off_x | (off_y << 4)),
3276                                       interpolation);
3277       } else {
3278          fs_reg src = vgrf(glsl_type::ivec2_type);
3279          fs_reg offset_src = retype(get_nir_src(instr->src[0]),
3280                                     BRW_REGISTER_TYPE_F);
3281          for (int i = 0; i < 2; i++) {
3282             fs_reg temp = vgrf(glsl_type::float_type);
3283             bld.MUL(temp, offset(offset_src, bld, i), brw_imm_f(16.0f));
3284             fs_reg itemp = vgrf(glsl_type::int_type);
3285             /* float to int */
3286             bld.MOV(itemp, temp);
3287
3288             /* Clamp the upper end of the range to +7/16.
3289              * ARB_gpu_shader5 requires that we support a maximum offset
3290              * of +0.5, which isn't representable in a S0.4 value -- if
3291              * we didn't clamp it, we'd end up with -8/16, which is the
3292              * opposite of what the shader author wanted.
3293              *
3294              * This is legal due to ARB_gpu_shader5's quantization
3295              * rules:
3296              *
3297              * "Not all values of <offset> may be supported; x and y
3298              * offsets may be rounded to fixed-point values with the
3299              * number of fraction bits given by the
3300              * implementation-dependent constant
3301              * FRAGMENT_INTERPOLATION_OFFSET_BITS"
3302              */
3303             set_condmod(BRW_CONDITIONAL_L,
3304                         bld.SEL(offset(src, bld, i), itemp, brw_imm_d(7)));
3305          }
3306
3307          const enum opcode opcode = FS_OPCODE_INTERPOLATE_AT_PER_SLOT_OFFSET;
3308          emit_pixel_interpolater_send(bld,
3309                                       opcode,
3310                                       dest,
3311                                       src,
3312                                       brw_imm_ud(0u),
3313                                       interpolation);
3314       }
3315       break;
3316    }
3317
3318    case nir_intrinsic_load_interpolated_input: {
3319       if (nir_intrinsic_base(instr) == VARYING_SLOT_POS) {
3320          emit_fragcoord_interpolation(dest);
3321          break;
3322       }
3323
3324       assert(instr->src[0].ssa &&
3325              instr->src[0].ssa->parent_instr->type == nir_instr_type_intrinsic);
3326       nir_intrinsic_instr *bary_intrinsic =
3327          nir_instr_as_intrinsic(instr->src[0].ssa->parent_instr);
3328       nir_intrinsic_op bary_intrin = bary_intrinsic->intrinsic;
3329       enum glsl_interp_mode interp_mode =
3330          (enum glsl_interp_mode) nir_intrinsic_interp_mode(bary_intrinsic);
3331       fs_reg dst_xy;
3332
3333       if (bary_intrin == nir_intrinsic_load_barycentric_at_offset ||
3334           bary_intrin == nir_intrinsic_load_barycentric_at_sample) {
3335          /* Use the result of the PI message */
3336          dst_xy = retype(get_nir_src(instr->src[0]), BRW_REGISTER_TYPE_F);
3337       } else {
3338          /* Use the delta_xy values computed from the payload */
3339          enum brw_barycentric_mode bary =
3340             brw_barycentric_mode(interp_mode, bary_intrin);
3341
3342          dst_xy = this->delta_xy[bary];
3343       }
3344
3345       for (unsigned int i = 0; i < instr->num_components; i++) {
3346          fs_reg interp =
3347             component(interp_reg(nir_intrinsic_base(instr),
3348                                  nir_intrinsic_component(instr) + i), 0);
3349          interp.type = BRW_REGISTER_TYPE_F;
3350          dest.type = BRW_REGISTER_TYPE_F;
3351
3352          if (devinfo->gen < 6 && interp_mode == INTERP_MODE_SMOOTH) {
3353             fs_reg tmp = vgrf(glsl_type::float_type);
3354             bld.emit(FS_OPCODE_LINTERP, tmp, dst_xy, interp);
3355             bld.MUL(offset(dest, bld, i), tmp, this->pixel_w);
3356          } else {
3357             bld.emit(FS_OPCODE_LINTERP, offset(dest, bld, i), dst_xy, interp);
3358          }
3359       }
3360       break;
3361    }
3362
3363    default:
3364       nir_emit_intrinsic(bld, instr);
3365       break;
3366    }
3367 }
3368
3369 static int
3370 get_op_for_atomic_add(nir_intrinsic_instr *instr, unsigned src)
3371 {
3372    if (nir_src_is_const(instr->src[src])) {
3373       int64_t add_val = nir_src_as_int(instr->src[src]);
3374       if (add_val == 1)
3375          return BRW_AOP_INC;
3376       else if (add_val == -1)
3377          return BRW_AOP_DEC;
3378    }
3379
3380    return BRW_AOP_ADD;
3381 }
3382
3383 void
3384 fs_visitor::nir_emit_cs_intrinsic(const fs_builder &bld,
3385                                   nir_intrinsic_instr *instr)
3386 {
3387    assert(stage == MESA_SHADER_COMPUTE);
3388    struct brw_cs_prog_data *cs_prog_data = brw_cs_prog_data(prog_data);
3389
3390    fs_reg dest;
3391    if (nir_intrinsic_infos[instr->intrinsic].has_dest)
3392       dest = get_nir_dest(instr->dest);
3393
3394    switch (instr->intrinsic) {
3395    case nir_intrinsic_barrier:
3396       emit_barrier();
3397       cs_prog_data->uses_barrier = true;
3398       break;
3399
3400    case nir_intrinsic_load_subgroup_id:
3401       bld.MOV(retype(dest, BRW_REGISTER_TYPE_UD), subgroup_id);
3402       break;
3403
3404    case nir_intrinsic_load_local_invocation_id:
3405    case nir_intrinsic_load_work_group_id: {
3406       gl_system_value sv = nir_system_value_from_intrinsic(instr->intrinsic);
3407       fs_reg val = nir_system_values[sv];
3408       assert(val.file != BAD_FILE);
3409       dest.type = val.type;
3410       for (unsigned i = 0; i < 3; i++)
3411          bld.MOV(offset(dest, bld, i), offset(val, bld, i));
3412       break;
3413    }
3414
3415    case nir_intrinsic_load_num_work_groups: {
3416       const unsigned surface =
3417          cs_prog_data->binding_table.work_groups_start;
3418
3419       cs_prog_data->uses_num_work_groups = true;
3420
3421       fs_reg surf_index = brw_imm_ud(surface);
3422       brw_mark_surface_used(prog_data, surface);
3423
3424       /* Read the 3 GLuint components of gl_NumWorkGroups */
3425       for (unsigned i = 0; i < 3; i++) {
3426          fs_reg read_result =
3427             emit_untyped_read(bld, surf_index,
3428                               brw_imm_ud(i << 2),
3429                               1 /* dims */, 1 /* size */,
3430                               BRW_PREDICATE_NONE);
3431          read_result.type = dest.type;
3432          bld.MOV(dest, read_result);
3433          dest = offset(dest, bld, 1);
3434       }
3435       break;
3436    }
3437
3438    case nir_intrinsic_shared_atomic_add:
3439       nir_emit_shared_atomic(bld, get_op_for_atomic_add(instr, 1), instr);
3440       break;
3441    case nir_intrinsic_shared_atomic_imin:
3442       nir_emit_shared_atomic(bld, BRW_AOP_IMIN, instr);
3443       break;
3444    case nir_intrinsic_shared_atomic_umin:
3445       nir_emit_shared_atomic(bld, BRW_AOP_UMIN, instr);
3446       break;
3447    case nir_intrinsic_shared_atomic_imax:
3448       nir_emit_shared_atomic(bld, BRW_AOP_IMAX, instr);
3449       break;
3450    case nir_intrinsic_shared_atomic_umax:
3451       nir_emit_shared_atomic(bld, BRW_AOP_UMAX, instr);
3452       break;
3453    case nir_intrinsic_shared_atomic_and:
3454       nir_emit_shared_atomic(bld, BRW_AOP_AND, instr);
3455       break;
3456    case nir_intrinsic_shared_atomic_or:
3457       nir_emit_shared_atomic(bld, BRW_AOP_OR, instr);
3458       break;
3459    case nir_intrinsic_shared_atomic_xor:
3460       nir_emit_shared_atomic(bld, BRW_AOP_XOR, instr);
3461       break;
3462    case nir_intrinsic_shared_atomic_exchange:
3463       nir_emit_shared_atomic(bld, BRW_AOP_MOV, instr);
3464       break;
3465    case nir_intrinsic_shared_atomic_comp_swap:
3466       nir_emit_shared_atomic(bld, BRW_AOP_CMPWR, instr);
3467       break;
3468    case nir_intrinsic_shared_atomic_fmin:
3469       nir_emit_shared_atomic_float(bld, BRW_AOP_FMIN, instr);
3470       break;
3471    case nir_intrinsic_shared_atomic_fmax:
3472       nir_emit_shared_atomic_float(bld, BRW_AOP_FMAX, instr);
3473       break;
3474    case nir_intrinsic_shared_atomic_fcomp_swap:
3475       nir_emit_shared_atomic_float(bld, BRW_AOP_FCMPWR, instr);
3476       break;
3477
3478    case nir_intrinsic_load_shared: {
3479       assert(devinfo->gen >= 7);
3480       assert(stage == MESA_SHADER_COMPUTE);
3481
3482       const unsigned bit_size = nir_dest_bit_size(instr->dest);
3483       fs_reg offset_reg = retype(get_nir_src(instr->src[0]),
3484                                  BRW_REGISTER_TYPE_UD);
3485
3486       /* Make dest unsigned because that's what the temporary will be */
3487       dest.type = brw_reg_type_from_bit_size(bit_size, BRW_REGISTER_TYPE_UD);
3488
3489       /* Read the vector */
3490       if (nir_intrinsic_align(instr) >= 4) {
3491          assert(nir_dest_bit_size(instr->dest) == 32);
3492          fs_reg read_result = emit_untyped_read(bld, brw_imm_ud(GEN7_BTI_SLM),
3493                                                 offset_reg, 1 /* dims */,
3494                                                 instr->num_components,
3495                                                 BRW_PREDICATE_NONE);
3496          for (unsigned i = 0; i < instr->num_components; i++)
3497             bld.MOV(offset(dest, bld, i), offset(read_result, bld, i));
3498       } else {
3499          assert(nir_dest_bit_size(instr->dest) <= 32);
3500          assert(nir_dest_num_components(instr->dest) == 1);
3501          fs_reg read_result =
3502             emit_byte_scattered_read(bld, brw_imm_ud(GEN7_BTI_SLM), offset_reg,
3503                                      1 /* dims */, 1, bit_size,
3504                                      BRW_PREDICATE_NONE);
3505          bld.MOV(dest, read_result);
3506       }
3507       break;
3508    }
3509
3510    case nir_intrinsic_store_shared: {
3511       assert(devinfo->gen >= 7);
3512       assert(stage == MESA_SHADER_COMPUTE);
3513
3514       const unsigned bit_size = nir_src_bit_size(instr->src[0]);
3515       fs_reg val_reg = get_nir_src(instr->src[0]);
3516       fs_reg offset_reg = retype(get_nir_src(instr->src[1]),
3517                                  BRW_REGISTER_TYPE_UD);
3518
3519       val_reg.type = brw_reg_type_from_bit_size(bit_size, BRW_REGISTER_TYPE_UD);
3520
3521       assert(nir_intrinsic_write_mask(instr) ==
3522              (1u << instr->num_components) - 1);
3523       if (nir_intrinsic_align(instr) >= 4) {
3524          assert(nir_src_bit_size(instr->src[0]) == 32);
3525          assert(nir_src_num_components(instr->src[0]) <= 4);
3526          emit_untyped_write(bld, brw_imm_ud(GEN7_BTI_SLM), offset_reg, val_reg,
3527                             1 /* dims */, instr->num_components,
3528                             BRW_PREDICATE_NONE);
3529       } else {
3530          assert(nir_src_bit_size(instr->src[0]) <= 32);
3531          assert(nir_src_num_components(instr->src[0]) == 1);
3532          fs_reg write_src = bld.vgrf(BRW_REGISTER_TYPE_UD);
3533          bld.MOV(write_src, val_reg);
3534          emit_byte_scattered_write(bld, brw_imm_ud(GEN7_BTI_SLM), offset_reg,
3535                                    write_src, 1 /* dims */, bit_size,
3536                                    BRW_PREDICATE_NONE);
3537       }
3538       break;
3539    }
3540
3541    default:
3542       nir_emit_intrinsic(bld, instr);
3543       break;
3544    }
3545 }
3546
3547 static fs_reg
3548 brw_nir_reduction_op_identity(const fs_builder &bld,
3549                               nir_op op, brw_reg_type type)
3550 {
3551    nir_const_value value = nir_alu_binop_identity(op, type_sz(type) * 8);
3552    switch (type_sz(type)) {
3553    case 2:
3554       assert(type != BRW_REGISTER_TYPE_HF);
3555       return retype(brw_imm_uw(value.u16[0]), type);
3556    case 4:
3557       return retype(brw_imm_ud(value.u32[0]), type);
3558    case 8:
3559       if (type == BRW_REGISTER_TYPE_DF)
3560          return setup_imm_df(bld, value.f64[0]);
3561       else
3562          return retype(brw_imm_u64(value.u64[0]), type);
3563    default:
3564       unreachable("Invalid type size");
3565    }
3566 }
3567
3568 static opcode
3569 brw_op_for_nir_reduction_op(nir_op op)
3570 {
3571    switch (op) {
3572    case nir_op_iadd: return BRW_OPCODE_ADD;
3573    case nir_op_fadd: return BRW_OPCODE_ADD;
3574    case nir_op_imul: return BRW_OPCODE_MUL;
3575    case nir_op_fmul: return BRW_OPCODE_MUL;
3576    case nir_op_imin: return BRW_OPCODE_SEL;
3577    case nir_op_umin: return BRW_OPCODE_SEL;
3578    case nir_op_fmin: return BRW_OPCODE_SEL;
3579    case nir_op_imax: return BRW_OPCODE_SEL;
3580    case nir_op_umax: return BRW_OPCODE_SEL;
3581    case nir_op_fmax: return BRW_OPCODE_SEL;
3582    case nir_op_iand: return BRW_OPCODE_AND;
3583    case nir_op_ior:  return BRW_OPCODE_OR;
3584    case nir_op_ixor: return BRW_OPCODE_XOR;
3585    default:
3586       unreachable("Invalid reduction operation");
3587    }
3588 }
3589
3590 static brw_conditional_mod
3591 brw_cond_mod_for_nir_reduction_op(nir_op op)
3592 {
3593    switch (op) {
3594    case nir_op_iadd: return BRW_CONDITIONAL_NONE;
3595    case nir_op_fadd: return BRW_CONDITIONAL_NONE;
3596    case nir_op_imul: return BRW_CONDITIONAL_NONE;
3597    case nir_op_fmul: return BRW_CONDITIONAL_NONE;
3598    case nir_op_imin: return BRW_CONDITIONAL_L;
3599    case nir_op_umin: return BRW_CONDITIONAL_L;
3600    case nir_op_fmin: return BRW_CONDITIONAL_L;
3601    case nir_op_imax: return BRW_CONDITIONAL_GE;
3602    case nir_op_umax: return BRW_CONDITIONAL_GE;
3603    case nir_op_fmax: return BRW_CONDITIONAL_GE;
3604    case nir_op_iand: return BRW_CONDITIONAL_NONE;
3605    case nir_op_ior:  return BRW_CONDITIONAL_NONE;
3606    case nir_op_ixor: return BRW_CONDITIONAL_NONE;
3607    default:
3608       unreachable("Invalid reduction operation");
3609    }
3610 }
3611
3612 fs_reg
3613 fs_visitor::get_nir_image_intrinsic_image(const brw::fs_builder &bld,
3614                                           nir_intrinsic_instr *instr)
3615 {
3616    fs_reg image = retype(get_nir_src_imm(instr->src[0]), BRW_REGISTER_TYPE_UD);
3617
3618    if (stage_prog_data->binding_table.image_start > 0) {
3619       if (image.file == BRW_IMMEDIATE_VALUE) {
3620          image.d += stage_prog_data->binding_table.image_start;
3621       } else {
3622          bld.ADD(image, image,
3623                  brw_imm_d(stage_prog_data->binding_table.image_start));
3624       }
3625    }
3626
3627    return bld.emit_uniformize(image);
3628 }
3629
3630 fs_reg
3631 fs_visitor::get_nir_ssbo_intrinsic_index(const brw::fs_builder &bld,
3632                                          nir_intrinsic_instr *instr)
3633 {
3634    /* SSBO stores are weird in that their index is in src[1] */
3635    const unsigned src = instr->intrinsic == nir_intrinsic_store_ssbo ? 1 : 0;
3636
3637    fs_reg surf_index;
3638    if (nir_src_is_const(instr->src[src])) {
3639       unsigned index = stage_prog_data->binding_table.ssbo_start +
3640                        nir_src_as_uint(instr->src[src]);
3641       surf_index = brw_imm_ud(index);
3642       brw_mark_surface_used(prog_data, index);
3643    } else {
3644       surf_index = vgrf(glsl_type::uint_type);
3645       bld.ADD(surf_index, get_nir_src(instr->src[src]),
3646               brw_imm_ud(stage_prog_data->binding_table.ssbo_start));
3647
3648       /* Assume this may touch any UBO. It would be nice to provide
3649        * a tighter bound, but the array information is already lowered away.
3650        */
3651       brw_mark_surface_used(prog_data,
3652                             stage_prog_data->binding_table.ssbo_start +
3653                             nir->info.num_ssbos - 1);
3654    }
3655
3656    return surf_index;
3657 }
3658
3659 static unsigned
3660 image_intrinsic_coord_components(nir_intrinsic_instr *instr)
3661 {
3662    switch (nir_intrinsic_image_dim(instr)) {
3663    case GLSL_SAMPLER_DIM_1D:
3664       return 1 + nir_intrinsic_image_array(instr);
3665    case GLSL_SAMPLER_DIM_2D:
3666    case GLSL_SAMPLER_DIM_RECT:
3667       return 2 + nir_intrinsic_image_array(instr);
3668    case GLSL_SAMPLER_DIM_3D:
3669    case GLSL_SAMPLER_DIM_CUBE:
3670       return 3;
3671    case GLSL_SAMPLER_DIM_BUF:
3672       return 1;
3673    case GLSL_SAMPLER_DIM_MS:
3674       return 2 + nir_intrinsic_image_array(instr);
3675    default:
3676       unreachable("Invalid image dimension");
3677    }
3678 }
3679
3680 void
3681 fs_visitor::nir_emit_intrinsic(const fs_builder &bld, nir_intrinsic_instr *instr)
3682 {
3683    fs_reg dest;
3684    if (nir_intrinsic_infos[instr->intrinsic].has_dest)
3685       dest = get_nir_dest(instr->dest);
3686
3687    switch (instr->intrinsic) {
3688    case nir_intrinsic_image_load:
3689    case nir_intrinsic_image_store:
3690    case nir_intrinsic_image_atomic_add:
3691    case nir_intrinsic_image_atomic_min:
3692    case nir_intrinsic_image_atomic_max:
3693    case nir_intrinsic_image_atomic_and:
3694    case nir_intrinsic_image_atomic_or:
3695    case nir_intrinsic_image_atomic_xor:
3696    case nir_intrinsic_image_atomic_exchange:
3697    case nir_intrinsic_image_atomic_comp_swap: {
3698       if (stage == MESA_SHADER_FRAGMENT &&
3699           instr->intrinsic != nir_intrinsic_image_load)
3700          brw_wm_prog_data(prog_data)->has_side_effects = true;
3701
3702       /* Get some metadata from the image intrinsic. */
3703       const nir_intrinsic_info *info = &nir_intrinsic_infos[instr->intrinsic];
3704       const unsigned dims = image_intrinsic_coord_components(instr);
3705       const GLenum format = nir_intrinsic_format(instr);
3706       const unsigned dest_components = nir_intrinsic_dest_components(instr);
3707
3708       /* Get the arguments of the image intrinsic. */
3709       const fs_reg image = get_nir_image_intrinsic_image(bld, instr);
3710       const fs_reg coords = retype(get_nir_src(instr->src[1]),
3711                                    BRW_REGISTER_TYPE_UD);
3712       fs_reg tmp;
3713
3714       /* Emit an image load, store or atomic op. */
3715       if (instr->intrinsic == nir_intrinsic_image_load) {
3716          tmp = emit_typed_read(bld, image, coords, dims,
3717                                instr->num_components);
3718       } else if (instr->intrinsic == nir_intrinsic_image_store) {
3719          const fs_reg src0 = get_nir_src(instr->src[3]);
3720          emit_typed_write(bld, image, coords, src0, dims,
3721                           instr->num_components);
3722       } else {
3723          int op;
3724          unsigned num_srcs = info->num_srcs;
3725
3726          switch (instr->intrinsic) {
3727          case nir_intrinsic_image_atomic_add:
3728             assert(num_srcs == 4);
3729
3730             op = get_op_for_atomic_add(instr, 3);
3731
3732             if (op != BRW_AOP_ADD)
3733                num_srcs = 3;
3734             break;
3735          case nir_intrinsic_image_atomic_min:
3736             assert(format == GL_R32UI || format == GL_R32I);
3737             op = (format == GL_R32I) ? BRW_AOP_IMIN : BRW_AOP_UMIN;
3738             break;
3739          case nir_intrinsic_image_atomic_max:
3740             assert(format == GL_R32UI || format == GL_R32I);
3741             op = (format == GL_R32I) ? BRW_AOP_IMAX : BRW_AOP_UMAX;
3742             break;
3743          case nir_intrinsic_image_atomic_and:
3744             op = BRW_AOP_AND;
3745             break;
3746          case nir_intrinsic_image_atomic_or:
3747             op = BRW_AOP_OR;
3748             break;
3749          case nir_intrinsic_image_atomic_xor:
3750             op = BRW_AOP_XOR;
3751             break;
3752          case nir_intrinsic_image_atomic_exchange:
3753             op = BRW_AOP_MOV;
3754             break;
3755          case nir_intrinsic_image_atomic_comp_swap:
3756             op = BRW_AOP_CMPWR;
3757             break;
3758          default:
3759             unreachable("Not reachable.");
3760          }
3761
3762          const fs_reg src0 = (num_srcs >= 4 ?
3763                               get_nir_src(instr->src[3]) : fs_reg());
3764          const fs_reg src1 = (num_srcs >= 5 ?
3765                               get_nir_src(instr->src[4]) : fs_reg());
3766
3767          tmp = emit_typed_atomic(bld, image, coords, src0, src1, dims, 1, op);
3768       }
3769
3770       /* Assign the result. */
3771       for (unsigned c = 0; c < dest_components; ++c) {
3772          bld.MOV(offset(retype(dest, tmp.type), bld, c),
3773                  offset(tmp, bld, c));
3774       }
3775       break;
3776    }
3777
3778    case nir_intrinsic_image_size: {
3779       /* Unlike the [un]typed load and store opcodes, the TXS that this turns
3780        * into will handle the binding table index for us in the geneerator.
3781        */
3782       fs_reg image = retype(get_nir_src_imm(instr->src[0]),
3783                             BRW_REGISTER_TYPE_UD);
3784       image = bld.emit_uniformize(image);
3785
3786       /* Since the image size is always uniform, we can just emit a SIMD8
3787        * query instruction and splat the result out.
3788        */
3789       const fs_builder ubld = bld.exec_all().group(8, 0);
3790
3791       /* The LOD also serves as the message payload */
3792       fs_reg lod = ubld.vgrf(BRW_REGISTER_TYPE_UD);
3793       ubld.MOV(lod, brw_imm_ud(0));
3794
3795       fs_reg tmp = ubld.vgrf(BRW_REGISTER_TYPE_UD, 4);
3796       fs_inst *inst = ubld.emit(SHADER_OPCODE_IMAGE_SIZE, tmp, lod, image);
3797       inst->mlen = 1;
3798       inst->size_written = 4 * REG_SIZE;
3799
3800       for (unsigned c = 0; c < instr->dest.ssa.num_components; ++c) {
3801          if (c == 2 && nir_intrinsic_image_dim(instr) == GLSL_SAMPLER_DIM_CUBE) {
3802             bld.emit(SHADER_OPCODE_INT_QUOTIENT,
3803                      offset(retype(dest, tmp.type), bld, c),
3804                      component(offset(tmp, ubld, c), 0), brw_imm_ud(6));
3805          } else {
3806             bld.MOV(offset(retype(dest, tmp.type), bld, c),
3807                     component(offset(tmp, ubld, c), 0));
3808          }
3809       }
3810       break;
3811    }
3812
3813    case nir_intrinsic_image_load_raw_intel: {
3814       const fs_reg image = get_nir_image_intrinsic_image(bld, instr);
3815       const fs_reg addr = retype(get_nir_src(instr->src[1]),
3816                                  BRW_REGISTER_TYPE_UD);
3817
3818       fs_reg tmp = emit_untyped_read(bld, image, addr, 1,
3819                                      instr->num_components);
3820
3821       for (unsigned c = 0; c < instr->num_components; ++c) {
3822          bld.MOV(offset(retype(dest, tmp.type), bld, c),
3823                  offset(tmp, bld, c));
3824       }
3825       break;
3826    }
3827
3828    case nir_intrinsic_image_store_raw_intel: {
3829       const fs_reg image = get_nir_image_intrinsic_image(bld, instr);
3830       const fs_reg addr = retype(get_nir_src(instr->src[1]),
3831                                  BRW_REGISTER_TYPE_UD);
3832       const fs_reg data = retype(get_nir_src(instr->src[2]),
3833                                  BRW_REGISTER_TYPE_UD);
3834
3835       brw_wm_prog_data(prog_data)->has_side_effects = true;
3836
3837       emit_untyped_write(bld, image, addr, data, 1,
3838                          instr->num_components);
3839       break;
3840    }
3841
3842    case nir_intrinsic_group_memory_barrier:
3843    case nir_intrinsic_memory_barrier_shared:
3844    case nir_intrinsic_memory_barrier_atomic_counter:
3845    case nir_intrinsic_memory_barrier_buffer:
3846    case nir_intrinsic_memory_barrier_image:
3847    case nir_intrinsic_memory_barrier: {
3848       const fs_builder ubld = bld.group(8, 0);
3849       const fs_reg tmp = ubld.vgrf(BRW_REGISTER_TYPE_UD, 2);
3850       ubld.emit(SHADER_OPCODE_MEMORY_FENCE, tmp)
3851          ->size_written = 2 * REG_SIZE;
3852       break;
3853    }
3854
3855    case nir_intrinsic_shader_clock: {
3856       /* We cannot do anything if there is an event, so ignore it for now */
3857       const fs_reg shader_clock = get_timestamp(bld);
3858       const fs_reg srcs[] = { component(shader_clock, 0),
3859                               component(shader_clock, 1) };
3860       bld.LOAD_PAYLOAD(dest, srcs, ARRAY_SIZE(srcs), 0);
3861       break;
3862    }
3863
3864    case nir_intrinsic_image_samples:
3865       /* The driver does not support multi-sampled images. */
3866       bld.MOV(retype(dest, BRW_REGISTER_TYPE_D), brw_imm_d(1));
3867       break;
3868
3869    case nir_intrinsic_load_uniform: {
3870       /* Offsets are in bytes but they should always aligned to
3871        * the type size
3872        */
3873       assert(instr->const_index[0] % 4 == 0 ||
3874              instr->const_index[0] % type_sz(dest.type) == 0);
3875
3876       fs_reg src(UNIFORM, instr->const_index[0] / 4, dest.type);
3877
3878       if (nir_src_is_const(instr->src[0])) {
3879          unsigned load_offset = nir_src_as_uint(instr->src[0]);
3880          assert(load_offset % type_sz(dest.type) == 0);
3881          /* For 16-bit types we add the module of the const_index[0]
3882           * offset to access to not 32-bit aligned element
3883           */
3884          src.offset = load_offset + instr->const_index[0] % 4;
3885
3886          for (unsigned j = 0; j < instr->num_components; j++) {
3887             bld.MOV(offset(dest, bld, j), offset(src, bld, j));
3888          }
3889       } else {
3890          fs_reg indirect = retype(get_nir_src(instr->src[0]),
3891                                   BRW_REGISTER_TYPE_UD);
3892
3893          /* We need to pass a size to the MOV_INDIRECT but we don't want it to
3894           * go past the end of the uniform.  In order to keep the n'th
3895           * component from running past, we subtract off the size of all but
3896           * one component of the vector.
3897           */
3898          assert(instr->const_index[1] >=
3899                 instr->num_components * (int) type_sz(dest.type));
3900          unsigned read_size = instr->const_index[1] -
3901             (instr->num_components - 1) * type_sz(dest.type);
3902
3903          bool supports_64bit_indirects =
3904             !devinfo->is_cherryview && !gen_device_info_is_9lp(devinfo);
3905
3906          if (type_sz(dest.type) != 8 || supports_64bit_indirects) {
3907             for (unsigned j = 0; j < instr->num_components; j++) {
3908                bld.emit(SHADER_OPCODE_MOV_INDIRECT,
3909                         offset(dest, bld, j), offset(src, bld, j),
3910                         indirect, brw_imm_ud(read_size));
3911             }
3912          } else {
3913             const unsigned num_mov_indirects =
3914                type_sz(dest.type) / type_sz(BRW_REGISTER_TYPE_UD);
3915             /* We read a little bit less per MOV INDIRECT, as they are now
3916              * 32-bits ones instead of 64-bit. Fix read_size then.
3917              */
3918             const unsigned read_size_32bit = read_size -
3919                 (num_mov_indirects - 1) * type_sz(BRW_REGISTER_TYPE_UD);
3920             for (unsigned j = 0; j < instr->num_components; j++) {
3921                for (unsigned i = 0; i < num_mov_indirects; i++) {
3922                   bld.emit(SHADER_OPCODE_MOV_INDIRECT,
3923                            subscript(offset(dest, bld, j), BRW_REGISTER_TYPE_UD, i),
3924                            subscript(offset(src, bld, j), BRW_REGISTER_TYPE_UD, i),
3925                            indirect, brw_imm_ud(read_size_32bit));
3926                }
3927             }
3928          }
3929       }
3930       break;
3931    }
3932
3933    case nir_intrinsic_load_ubo: {
3934       fs_reg surf_index;
3935       if (nir_src_is_const(instr->src[0])) {
3936          const unsigned index = stage_prog_data->binding_table.ubo_start +
3937                                 nir_src_as_uint(instr->src[0]);
3938          surf_index = brw_imm_ud(index);
3939          brw_mark_surface_used(prog_data, index);
3940       } else {
3941          /* The block index is not a constant. Evaluate the index expression
3942           * per-channel and add the base UBO index; we have to select a value
3943           * from any live channel.
3944           */
3945          surf_index = vgrf(glsl_type::uint_type);
3946          bld.ADD(surf_index, get_nir_src(instr->src[0]),
3947                  brw_imm_ud(stage_prog_data->binding_table.ubo_start));
3948          surf_index = bld.emit_uniformize(surf_index);
3949
3950          /* Assume this may touch any UBO. It would be nice to provide
3951           * a tighter bound, but the array information is already lowered away.
3952           */
3953          brw_mark_surface_used(prog_data,
3954                                stage_prog_data->binding_table.ubo_start +
3955                                nir->info.num_ubos - 1);
3956       }
3957
3958       if (!nir_src_is_const(instr->src[1])) {
3959          fs_reg base_offset = retype(get_nir_src(instr->src[1]),
3960                                      BRW_REGISTER_TYPE_UD);
3961
3962          for (int i = 0; i < instr->num_components; i++)
3963             VARYING_PULL_CONSTANT_LOAD(bld, offset(dest, bld, i), surf_index,
3964                                        base_offset, i * type_sz(dest.type));
3965       } else {
3966          /* Even if we are loading doubles, a pull constant load will load
3967           * a 32-bit vec4, so should only reserve vgrf space for that. If we
3968           * need to load a full dvec4 we will have to emit 2 loads. This is
3969           * similar to demote_pull_constants(), except that in that case we
3970           * see individual accesses to each component of the vector and then
3971           * we let CSE deal with duplicate loads. Here we see a vector access
3972           * and we have to split it if necessary.
3973           */
3974          const unsigned type_size = type_sz(dest.type);
3975          const unsigned load_offset = nir_src_as_uint(instr->src[1]);
3976
3977          /* See if we've selected this as a push constant candidate */
3978          if (nir_src_is_const(instr->src[0])) {
3979             const unsigned ubo_block = nir_src_as_uint(instr->src[0]);
3980             const unsigned offset_256b = load_offset / 32;
3981
3982             fs_reg push_reg;
3983             for (int i = 0; i < 4; i++) {
3984                const struct brw_ubo_range *range = &prog_data->ubo_ranges[i];
3985                if (range->block == ubo_block &&
3986                    offset_256b >= range->start &&
3987                    offset_256b < range->start + range->length) {
3988
3989                   push_reg = fs_reg(UNIFORM, UBO_START + i, dest.type);
3990                   push_reg.offset = load_offset - 32 * range->start;
3991                   break;
3992                }
3993             }
3994
3995             if (push_reg.file != BAD_FILE) {
3996                for (unsigned i = 0; i < instr->num_components; i++) {
3997                   bld.MOV(offset(dest, bld, i),
3998                           byte_offset(push_reg, i * type_size));
3999                }
4000                break;
4001             }
4002          }
4003
4004          const unsigned block_sz = 64; /* Fetch one cacheline at a time. */
4005          const fs_builder ubld = bld.exec_all().group(block_sz / 4, 0);
4006          const fs_reg packed_consts = ubld.vgrf(BRW_REGISTER_TYPE_UD);
4007
4008          for (unsigned c = 0; c < instr->num_components;) {
4009             const unsigned base = load_offset + c * type_size;
4010             /* Number of usable components in the next block-aligned load. */
4011             const unsigned count = MIN2(instr->num_components - c,
4012                                         (block_sz - base % block_sz) / type_size);
4013
4014             ubld.emit(FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD,
4015                       packed_consts, surf_index,
4016                       brw_imm_ud(base & ~(block_sz - 1)));
4017
4018             const fs_reg consts =
4019                retype(byte_offset(packed_consts, base & (block_sz - 1)),
4020                       dest.type);
4021
4022             for (unsigned d = 0; d < count; d++)
4023                bld.MOV(offset(dest, bld, c + d), component(consts, d));
4024
4025             c += count;
4026          }
4027       }
4028       break;
4029    }
4030
4031    case nir_intrinsic_load_ssbo: {
4032       assert(devinfo->gen >= 7);
4033
4034       const unsigned bit_size = nir_dest_bit_size(instr->dest);
4035       fs_reg surf_index = get_nir_ssbo_intrinsic_index(bld, instr);
4036       fs_reg offset_reg = retype(get_nir_src(instr->src[1]),
4037                                  BRW_REGISTER_TYPE_UD);
4038
4039       /* Make dest unsigned because that's what the temporary will be */
4040       dest.type = brw_reg_type_from_bit_size(bit_size, BRW_REGISTER_TYPE_UD);
4041
4042       /* Read the vector */
4043       if (nir_intrinsic_align(instr) >= 4) {
4044          assert(nir_dest_bit_size(instr->dest) == 32);
4045          fs_reg read_result = emit_untyped_read(bld, surf_index, offset_reg,
4046                                                 1 /* dims */,
4047                                                 instr->num_components,
4048                                                 BRW_PREDICATE_NONE);
4049          for (unsigned i = 0; i < instr->num_components; i++)
4050             bld.MOV(offset(dest, bld, i), offset(read_result, bld, i));
4051       } else {
4052          assert(nir_dest_bit_size(instr->dest) <= 32);
4053          assert(nir_dest_num_components(instr->dest) == 1);
4054          fs_reg read_result =
4055             emit_byte_scattered_read(bld, surf_index, offset_reg,
4056                                      1 /* dims */, 1, bit_size,
4057                                      BRW_PREDICATE_NONE);
4058          bld.MOV(dest, read_result);
4059       }
4060       break;
4061    }
4062
4063    case nir_intrinsic_store_ssbo: {
4064       assert(devinfo->gen >= 7);
4065
4066       if (stage == MESA_SHADER_FRAGMENT)
4067          brw_wm_prog_data(prog_data)->has_side_effects = true;
4068
4069       const unsigned bit_size = nir_src_bit_size(instr->src[0]);
4070       fs_reg val_reg = get_nir_src(instr->src[0]);
4071       fs_reg surf_index = get_nir_ssbo_intrinsic_index(bld, instr);
4072       fs_reg offset_reg = retype(get_nir_src(instr->src[2]),
4073                                  BRW_REGISTER_TYPE_UD);
4074
4075       val_reg.type = brw_reg_type_from_bit_size(bit_size, BRW_REGISTER_TYPE_UD);
4076
4077       assert(nir_intrinsic_write_mask(instr) ==
4078              (1u << instr->num_components) - 1);
4079       if (nir_intrinsic_align(instr) >= 4) {
4080          assert(nir_src_bit_size(instr->src[0]) == 32);
4081          assert(nir_src_num_components(instr->src[0]) <= 4);
4082          emit_untyped_write(bld, surf_index, offset_reg, val_reg,
4083                             1 /* dims */, instr->num_components,
4084                             BRW_PREDICATE_NONE);
4085       } else {
4086          assert(nir_src_bit_size(instr->src[0]) <= 32);
4087          assert(nir_src_num_components(instr->src[0]) == 1);
4088          fs_reg write_src = bld.vgrf(BRW_REGISTER_TYPE_UD);
4089          bld.MOV(write_src, val_reg);
4090          emit_byte_scattered_write(bld, surf_index, offset_reg,
4091                                    write_src, 1 /* dims */, bit_size,
4092                                    BRW_PREDICATE_NONE);
4093       }
4094       break;
4095    }
4096
4097    case nir_intrinsic_store_output: {
4098       fs_reg src = get_nir_src(instr->src[0]);
4099
4100       unsigned store_offset = nir_src_as_uint(instr->src[1]);
4101       unsigned num_components = instr->num_components;
4102       unsigned first_component = nir_intrinsic_component(instr);
4103       if (nir_src_bit_size(instr->src[0]) == 64) {
4104          src = shuffle_for_32bit_write(bld, src, 0, num_components);
4105          num_components *= 2;
4106       }
4107
4108       fs_reg new_dest = retype(offset(outputs[instr->const_index[0]], bld,
4109                                       4 * store_offset), src.type);
4110       for (unsigned j = 0; j < num_components; j++) {
4111          bld.MOV(offset(new_dest, bld, j + first_component),
4112                  offset(src, bld, j));
4113       }
4114       break;
4115    }
4116
4117    case nir_intrinsic_ssbo_atomic_add:
4118       nir_emit_ssbo_atomic(bld, get_op_for_atomic_add(instr, 2), instr);
4119       break;
4120    case nir_intrinsic_ssbo_atomic_imin:
4121       nir_emit_ssbo_atomic(bld, BRW_AOP_IMIN, instr);
4122       break;
4123    case nir_intrinsic_ssbo_atomic_umin:
4124       nir_emit_ssbo_atomic(bld, BRW_AOP_UMIN, instr);
4125       break;
4126    case nir_intrinsic_ssbo_atomic_imax:
4127       nir_emit_ssbo_atomic(bld, BRW_AOP_IMAX, instr);
4128       break;
4129    case nir_intrinsic_ssbo_atomic_umax:
4130       nir_emit_ssbo_atomic(bld, BRW_AOP_UMAX, instr);
4131       break;
4132    case nir_intrinsic_ssbo_atomic_and:
4133       nir_emit_ssbo_atomic(bld, BRW_AOP_AND, instr);
4134       break;
4135    case nir_intrinsic_ssbo_atomic_or:
4136       nir_emit_ssbo_atomic(bld, BRW_AOP_OR, instr);
4137       break;
4138    case nir_intrinsic_ssbo_atomic_xor:
4139       nir_emit_ssbo_atomic(bld, BRW_AOP_XOR, instr);
4140       break;
4141    case nir_intrinsic_ssbo_atomic_exchange:
4142       nir_emit_ssbo_atomic(bld, BRW_AOP_MOV, instr);
4143       break;
4144    case nir_intrinsic_ssbo_atomic_comp_swap:
4145       nir_emit_ssbo_atomic(bld, BRW_AOP_CMPWR, instr);
4146       break;
4147    case nir_intrinsic_ssbo_atomic_fmin:
4148       nir_emit_ssbo_atomic_float(bld, BRW_AOP_FMIN, instr);
4149       break;
4150    case nir_intrinsic_ssbo_atomic_fmax:
4151       nir_emit_ssbo_atomic_float(bld, BRW_AOP_FMAX, instr);
4152       break;
4153    case nir_intrinsic_ssbo_atomic_fcomp_swap:
4154       nir_emit_ssbo_atomic_float(bld, BRW_AOP_FCMPWR, instr);
4155       break;
4156
4157    case nir_intrinsic_get_buffer_size: {
4158       unsigned ssbo_index = nir_src_is_const(instr->src[0]) ?
4159                             nir_src_as_uint(instr->src[0]) : 0;
4160
4161       /* A resinfo's sampler message is used to get the buffer size.  The
4162        * SIMD8's writeback message consists of four registers and SIMD16's
4163        * writeback message consists of 8 destination registers (two per each
4164        * component).  Because we are only interested on the first channel of
4165        * the first returned component, where resinfo returns the buffer size
4166        * for SURFTYPE_BUFFER, we can just use the SIMD8 variant regardless of
4167        * the dispatch width.
4168        */
4169       const fs_builder ubld = bld.exec_all().group(8, 0);
4170       fs_reg src_payload = ubld.vgrf(BRW_REGISTER_TYPE_UD);
4171       fs_reg ret_payload = ubld.vgrf(BRW_REGISTER_TYPE_UD, 4);
4172
4173       /* Set LOD = 0 */
4174       ubld.MOV(src_payload, brw_imm_d(0));
4175
4176       const unsigned index = prog_data->binding_table.ssbo_start + ssbo_index;
4177       fs_inst *inst = ubld.emit(SHADER_OPCODE_GET_BUFFER_SIZE, ret_payload,
4178                                 src_payload, brw_imm_ud(index));
4179       inst->header_size = 0;
4180       inst->mlen = 1;
4181       inst->size_written = 4 * REG_SIZE;
4182
4183       /* SKL PRM, vol07, 3D Media GPGPU Engine, Bounds Checking and Faulting:
4184        *
4185        * "Out-of-bounds checking is always performed at a DWord granularity. If
4186        * any part of the DWord is out-of-bounds then the whole DWord is
4187        * considered out-of-bounds."
4188        *
4189        * This implies that types with size smaller than 4-bytes need to be
4190        * padded if they don't complete the last dword of the buffer. But as we
4191        * need to maintain the original size we need to reverse the padding
4192        * calculation to return the correct size to know the number of elements
4193        * of an unsized array. As we stored in the last two bits of the surface
4194        * size the needed padding for the buffer, we calculate here the
4195        * original buffer_size reversing the surface_size calculation:
4196        *
4197        * surface_size = isl_align(buffer_size, 4) +
4198        *                (isl_align(buffer_size) - buffer_size)
4199        *
4200        * buffer_size = surface_size & ~3 - surface_size & 3
4201        */
4202
4203       fs_reg size_aligned4 = ubld.vgrf(BRW_REGISTER_TYPE_UD);
4204       fs_reg size_padding = ubld.vgrf(BRW_REGISTER_TYPE_UD);
4205       fs_reg buffer_size = ubld.vgrf(BRW_REGISTER_TYPE_UD);
4206
4207       ubld.AND(size_padding, ret_payload, brw_imm_ud(3));
4208       ubld.AND(size_aligned4, ret_payload, brw_imm_ud(~3));
4209       ubld.ADD(buffer_size, size_aligned4, negate(size_padding));
4210
4211       bld.MOV(retype(dest, ret_payload.type), component(buffer_size, 0));
4212
4213       brw_mark_surface_used(prog_data, index);
4214       break;
4215    }
4216
4217    case nir_intrinsic_load_subgroup_invocation:
4218       bld.MOV(retype(dest, BRW_REGISTER_TYPE_D),
4219               nir_system_values[SYSTEM_VALUE_SUBGROUP_INVOCATION]);
4220       break;
4221
4222    case nir_intrinsic_load_subgroup_eq_mask:
4223    case nir_intrinsic_load_subgroup_ge_mask:
4224    case nir_intrinsic_load_subgroup_gt_mask:
4225    case nir_intrinsic_load_subgroup_le_mask:
4226    case nir_intrinsic_load_subgroup_lt_mask:
4227       unreachable("not reached");
4228
4229    case nir_intrinsic_vote_any: {
4230       const fs_builder ubld = bld.exec_all().group(1, 0);
4231
4232       /* The any/all predicates do not consider channel enables. To prevent
4233        * dead channels from affecting the result, we initialize the flag with
4234        * with the identity value for the logical operation.
4235        */
4236       if (dispatch_width == 32) {
4237          /* For SIMD32, we use a UD type so we fill both f0.0 and f0.1. */
4238          ubld.MOV(retype(brw_flag_reg(0, 0), BRW_REGISTER_TYPE_UD),
4239                          brw_imm_ud(0));
4240       } else {
4241          ubld.MOV(brw_flag_reg(0, 0), brw_imm_uw(0));
4242       }
4243       bld.CMP(bld.null_reg_d(), get_nir_src(instr->src[0]), brw_imm_d(0), BRW_CONDITIONAL_NZ);
4244
4245       /* For some reason, the any/all predicates don't work properly with
4246        * SIMD32.  In particular, it appears that a SEL with a QtrCtrl of 2H
4247        * doesn't read the correct subset of the flag register and you end up
4248        * getting garbage in the second half.  Work around this by using a pair
4249        * of 1-wide MOVs and scattering the result.
4250        */
4251       fs_reg res1 = ubld.vgrf(BRW_REGISTER_TYPE_D);
4252       ubld.MOV(res1, brw_imm_d(0));
4253       set_predicate(dispatch_width == 8  ? BRW_PREDICATE_ALIGN1_ANY8H :
4254                     dispatch_width == 16 ? BRW_PREDICATE_ALIGN1_ANY16H :
4255                                            BRW_PREDICATE_ALIGN1_ANY32H,
4256                     ubld.MOV(res1, brw_imm_d(-1)));
4257
4258       bld.MOV(retype(dest, BRW_REGISTER_TYPE_D), component(res1, 0));
4259       break;
4260    }
4261    case nir_intrinsic_vote_all: {
4262       const fs_builder ubld = bld.exec_all().group(1, 0);
4263
4264       /* The any/all predicates do not consider channel enables. To prevent
4265        * dead channels from affecting the result, we initialize the flag with
4266        * with the identity value for the logical operation.
4267        */
4268       if (dispatch_width == 32) {
4269          /* For SIMD32, we use a UD type so we fill both f0.0 and f0.1. */
4270          ubld.MOV(retype(brw_flag_reg(0, 0), BRW_REGISTER_TYPE_UD),
4271                          brw_imm_ud(0xffffffff));
4272       } else {
4273          ubld.MOV(brw_flag_reg(0, 0), brw_imm_uw(0xffff));
4274       }
4275       bld.CMP(bld.null_reg_d(), get_nir_src(instr->src[0]), brw_imm_d(0), BRW_CONDITIONAL_NZ);
4276
4277       /* For some reason, the any/all predicates don't work properly with
4278        * SIMD32.  In particular, it appears that a SEL with a QtrCtrl of 2H
4279        * doesn't read the correct subset of the flag register and you end up
4280        * getting garbage in the second half.  Work around this by using a pair
4281        * of 1-wide MOVs and scattering the result.
4282        */
4283       fs_reg res1 = ubld.vgrf(BRW_REGISTER_TYPE_D);
4284       ubld.MOV(res1, brw_imm_d(0));
4285       set_predicate(dispatch_width == 8  ? BRW_PREDICATE_ALIGN1_ALL8H :
4286                     dispatch_width == 16 ? BRW_PREDICATE_ALIGN1_ALL16H :
4287                                            BRW_PREDICATE_ALIGN1_ALL32H,
4288                     ubld.MOV(res1, brw_imm_d(-1)));
4289
4290       bld.MOV(retype(dest, BRW_REGISTER_TYPE_D), component(res1, 0));
4291       break;
4292    }
4293    case nir_intrinsic_vote_feq:
4294    case nir_intrinsic_vote_ieq: {
4295       fs_reg value = get_nir_src(instr->src[0]);
4296       if (instr->intrinsic == nir_intrinsic_vote_feq) {
4297          const unsigned bit_size = nir_src_bit_size(instr->src[0]);
4298          value.type = brw_reg_type_from_bit_size(bit_size, BRW_REGISTER_TYPE_F);
4299       }
4300
4301       fs_reg uniformized = bld.emit_uniformize(value);
4302       const fs_builder ubld = bld.exec_all().group(1, 0);
4303
4304       /* The any/all predicates do not consider channel enables. To prevent
4305        * dead channels from affecting the result, we initialize the flag with
4306        * with the identity value for the logical operation.
4307        */
4308       if (dispatch_width == 32) {
4309          /* For SIMD32, we use a UD type so we fill both f0.0 and f0.1. */
4310          ubld.MOV(retype(brw_flag_reg(0, 0), BRW_REGISTER_TYPE_UD),
4311                          brw_imm_ud(0xffffffff));
4312       } else {
4313          ubld.MOV(brw_flag_reg(0, 0), brw_imm_uw(0xffff));
4314       }
4315       bld.CMP(bld.null_reg_d(), value, uniformized, BRW_CONDITIONAL_Z);
4316
4317       /* For some reason, the any/all predicates don't work properly with
4318        * SIMD32.  In particular, it appears that a SEL with a QtrCtrl of 2H
4319        * doesn't read the correct subset of the flag register and you end up
4320        * getting garbage in the second half.  Work around this by using a pair
4321        * of 1-wide MOVs and scattering the result.
4322        */
4323       fs_reg res1 = ubld.vgrf(BRW_REGISTER_TYPE_D);
4324       ubld.MOV(res1, brw_imm_d(0));
4325       set_predicate(dispatch_width == 8  ? BRW_PREDICATE_ALIGN1_ALL8H :
4326                     dispatch_width == 16 ? BRW_PREDICATE_ALIGN1_ALL16H :
4327                                            BRW_PREDICATE_ALIGN1_ALL32H,
4328                     ubld.MOV(res1, brw_imm_d(-1)));
4329
4330       bld.MOV(retype(dest, BRW_REGISTER_TYPE_D), component(res1, 0));
4331       break;
4332    }
4333
4334    case nir_intrinsic_ballot: {
4335       const fs_reg value = retype(get_nir_src(instr->src[0]),
4336                                   BRW_REGISTER_TYPE_UD);
4337       struct brw_reg flag = brw_flag_reg(0, 0);
4338       /* FIXME: For SIMD32 programs, this causes us to stomp on f0.1 as well
4339        * as f0.0.  This is a problem for fragment programs as we currently use
4340        * f0.1 for discards.  Fortunately, we don't support SIMD32 fragment
4341        * programs yet so this isn't a problem.  When we do, something will
4342        * have to change.
4343        */
4344       if (dispatch_width == 32)
4345          flag.type = BRW_REGISTER_TYPE_UD;
4346
4347       bld.exec_all().group(1, 0).MOV(flag, brw_imm_ud(0u));
4348       bld.CMP(bld.null_reg_ud(), value, brw_imm_ud(0u), BRW_CONDITIONAL_NZ);
4349
4350       if (instr->dest.ssa.bit_size > 32) {
4351          dest.type = BRW_REGISTER_TYPE_UQ;
4352       } else {
4353          dest.type = BRW_REGISTER_TYPE_UD;
4354       }
4355       bld.MOV(dest, flag);
4356       break;
4357    }
4358
4359    case nir_intrinsic_read_invocation: {
4360       const fs_reg value = get_nir_src(instr->src[0]);
4361       const fs_reg invocation = get_nir_src(instr->src[1]);
4362       fs_reg tmp = bld.vgrf(value.type);
4363
4364       bld.exec_all().emit(SHADER_OPCODE_BROADCAST, tmp, value,
4365                           bld.emit_uniformize(invocation));
4366
4367       bld.MOV(retype(dest, value.type), fs_reg(component(tmp, 0)));
4368       break;
4369    }
4370
4371    case nir_intrinsic_read_first_invocation: {
4372       const fs_reg value = get_nir_src(instr->src[0]);
4373       bld.MOV(retype(dest, value.type), bld.emit_uniformize(value));
4374       break;
4375    }
4376
4377    case nir_intrinsic_shuffle: {
4378       const fs_reg value = get_nir_src(instr->src[0]);
4379       const fs_reg index = get_nir_src(instr->src[1]);
4380
4381       bld.emit(SHADER_OPCODE_SHUFFLE, retype(dest, value.type), value, index);
4382       break;
4383    }
4384
4385    case nir_intrinsic_first_invocation: {
4386       fs_reg tmp = bld.vgrf(BRW_REGISTER_TYPE_UD);
4387       bld.exec_all().emit(SHADER_OPCODE_FIND_LIVE_CHANNEL, tmp);
4388       bld.MOV(retype(dest, BRW_REGISTER_TYPE_UD),
4389               fs_reg(component(tmp, 0)));
4390       break;
4391    }
4392
4393    case nir_intrinsic_quad_broadcast: {
4394       const fs_reg value = get_nir_src(instr->src[0]);
4395       const unsigned index = nir_src_as_uint(instr->src[1]);
4396
4397       bld.emit(SHADER_OPCODE_CLUSTER_BROADCAST, retype(dest, value.type),
4398                value, brw_imm_ud(index), brw_imm_ud(4));
4399       break;
4400    }
4401
4402    case nir_intrinsic_quad_swap_horizontal: {
4403       const fs_reg value = get_nir_src(instr->src[0]);
4404       const fs_reg tmp = bld.vgrf(value.type);
4405       const fs_builder ubld = bld.exec_all().group(dispatch_width / 2, 0);
4406
4407       const fs_reg src_left = horiz_stride(value, 2);
4408       const fs_reg src_right = horiz_stride(horiz_offset(value, 1), 2);
4409       const fs_reg tmp_left = horiz_stride(tmp, 2);
4410       const fs_reg tmp_right = horiz_stride(horiz_offset(tmp, 1), 2);
4411
4412       /* From the Cherryview PRM Vol. 7, "Register Region Restrictiosn":
4413        *
4414        *    "When source or destination datatype is 64b or operation is
4415        *    integer DWord multiply, regioning in Align1 must follow
4416        *    these rules:
4417        *
4418        *    [...]
4419        *
4420        *    3. Source and Destination offset must be the same, except
4421        *       the case of scalar source."
4422        *
4423        * In order to work around this, we have to emit two 32-bit MOVs instead
4424        * of a single 64-bit MOV to do the shuffle.
4425        */
4426       if (type_sz(value.type) > 4 &&
4427           (devinfo->is_cherryview || gen_device_info_is_9lp(devinfo))) {
4428          ubld.MOV(subscript(tmp_left, BRW_REGISTER_TYPE_D, 0),
4429                   subscript(src_right, BRW_REGISTER_TYPE_D, 0));
4430          ubld.MOV(subscript(tmp_left, BRW_REGISTER_TYPE_D, 1),
4431                   subscript(src_right, BRW_REGISTER_TYPE_D, 1));
4432          ubld.MOV(subscript(tmp_right, BRW_REGISTER_TYPE_D, 0),
4433                   subscript(src_left, BRW_REGISTER_TYPE_D, 0));
4434          ubld.MOV(subscript(tmp_right, BRW_REGISTER_TYPE_D, 1),
4435                   subscript(src_left, BRW_REGISTER_TYPE_D, 1));
4436       } else {
4437          ubld.MOV(tmp_left, src_right);
4438          ubld.MOV(tmp_right, src_left);
4439       }
4440       bld.MOV(retype(dest, value.type), tmp);
4441       break;
4442    }
4443
4444    case nir_intrinsic_quad_swap_vertical: {
4445       const fs_reg value = get_nir_src(instr->src[0]);
4446       if (nir_src_bit_size(instr->src[0]) == 32) {
4447          /* For 32-bit, we can use a SIMD4x2 instruction to do this easily */
4448          const fs_reg tmp = bld.vgrf(value.type);
4449          const fs_builder ubld = bld.exec_all();
4450          ubld.emit(SHADER_OPCODE_QUAD_SWIZZLE, tmp, value,
4451                    brw_imm_ud(BRW_SWIZZLE4(2,3,0,1)));
4452          bld.MOV(retype(dest, value.type), tmp);
4453       } else {
4454          /* For larger data types, we have to either emit dispatch_width many
4455           * MOVs or else fall back to doing indirects.
4456           */
4457          fs_reg idx = bld.vgrf(BRW_REGISTER_TYPE_W);
4458          bld.XOR(idx, nir_system_values[SYSTEM_VALUE_SUBGROUP_INVOCATION],
4459                       brw_imm_w(0x2));
4460          bld.emit(SHADER_OPCODE_SHUFFLE, retype(dest, value.type), value, idx);
4461       }
4462       break;
4463    }
4464
4465    case nir_intrinsic_quad_swap_diagonal: {
4466       const fs_reg value = get_nir_src(instr->src[0]);
4467       if (nir_src_bit_size(instr->src[0]) == 32) {
4468          /* For 32-bit, we can use a SIMD4x2 instruction to do this easily */
4469          const fs_reg tmp = bld.vgrf(value.type);
4470          const fs_builder ubld = bld.exec_all();
4471          ubld.emit(SHADER_OPCODE_QUAD_SWIZZLE, tmp, value,
4472                    brw_imm_ud(BRW_SWIZZLE4(3,2,1,0)));
4473          bld.MOV(retype(dest, value.type), tmp);
4474       } else {
4475          /* For larger data types, we have to either emit dispatch_width many
4476           * MOVs or else fall back to doing indirects.
4477           */
4478          fs_reg idx = bld.vgrf(BRW_REGISTER_TYPE_W);
4479          bld.XOR(idx, nir_system_values[SYSTEM_VALUE_SUBGROUP_INVOCATION],
4480                       brw_imm_w(0x3));
4481          bld.emit(SHADER_OPCODE_SHUFFLE, retype(dest, value.type), value, idx);
4482       }
4483       break;
4484    }
4485
4486    case nir_intrinsic_reduce: {
4487       fs_reg src = get_nir_src(instr->src[0]);
4488       nir_op redop = (nir_op)nir_intrinsic_reduction_op(instr);
4489       unsigned cluster_size = nir_intrinsic_cluster_size(instr);
4490       if (cluster_size == 0 || cluster_size > dispatch_width)
4491          cluster_size = dispatch_width;
4492
4493       /* Figure out the source type */
4494       src.type = brw_type_for_nir_type(devinfo,
4495          (nir_alu_type)(nir_op_infos[redop].input_types[0] |
4496                         nir_src_bit_size(instr->src[0])));
4497
4498       fs_reg identity = brw_nir_reduction_op_identity(bld, redop, src.type);
4499       opcode brw_op = brw_op_for_nir_reduction_op(redop);
4500       brw_conditional_mod cond_mod = brw_cond_mod_for_nir_reduction_op(redop);
4501
4502       /* Set up a register for all of our scratching around and initialize it
4503        * to reduction operation's identity value.
4504        */
4505       fs_reg scan = bld.vgrf(src.type);
4506       bld.exec_all().emit(SHADER_OPCODE_SEL_EXEC, scan, src, identity);
4507
4508       bld.emit_scan(brw_op, scan, cluster_size, cond_mod);
4509
4510       dest.type = src.type;
4511       if (cluster_size * type_sz(src.type) >= REG_SIZE * 2) {
4512          /* In this case, CLUSTER_BROADCAST instruction isn't needed because
4513           * the distance between clusters is at least 2 GRFs.  In this case,
4514           * we don't need the weird striding of the CLUSTER_BROADCAST
4515           * instruction and can just do regular MOVs.
4516           */
4517          assert((cluster_size * type_sz(src.type)) % (REG_SIZE * 2) == 0);
4518          const unsigned groups =
4519             (dispatch_width * type_sz(src.type)) / (REG_SIZE * 2);
4520          const unsigned group_size = dispatch_width / groups;
4521          for (unsigned i = 0; i < groups; i++) {
4522             const unsigned cluster = (i * group_size) / cluster_size;
4523             const unsigned comp = cluster * cluster_size + (cluster_size - 1);
4524             bld.group(group_size, i).MOV(horiz_offset(dest, i * group_size),
4525                                          component(scan, comp));
4526          }
4527       } else {
4528          bld.emit(SHADER_OPCODE_CLUSTER_BROADCAST, dest, scan,
4529                   brw_imm_ud(cluster_size - 1), brw_imm_ud(cluster_size));
4530       }
4531       break;
4532    }
4533
4534    case nir_intrinsic_inclusive_scan:
4535    case nir_intrinsic_exclusive_scan: {
4536       fs_reg src = get_nir_src(instr->src[0]);
4537       nir_op redop = (nir_op)nir_intrinsic_reduction_op(instr);
4538
4539       /* Figure out the source type */
4540       src.type = brw_type_for_nir_type(devinfo,
4541          (nir_alu_type)(nir_op_infos[redop].input_types[0] |
4542                         nir_src_bit_size(instr->src[0])));
4543
4544       fs_reg identity = brw_nir_reduction_op_identity(bld, redop, src.type);
4545       opcode brw_op = brw_op_for_nir_reduction_op(redop);
4546       brw_conditional_mod cond_mod = brw_cond_mod_for_nir_reduction_op(redop);
4547
4548       /* Set up a register for all of our scratching around and initialize it
4549        * to reduction operation's identity value.
4550        */
4551       fs_reg scan = bld.vgrf(src.type);
4552       const fs_builder allbld = bld.exec_all();
4553       allbld.emit(SHADER_OPCODE_SEL_EXEC, scan, src, identity);
4554
4555       if (instr->intrinsic == nir_intrinsic_exclusive_scan) {
4556          /* Exclusive scan is a bit harder because we have to do an annoying
4557           * shift of the contents before we can begin.  To make things worse,
4558           * we can't do this with a normal stride; we have to use indirects.
4559           */
4560          fs_reg shifted = bld.vgrf(src.type);
4561          fs_reg idx = bld.vgrf(BRW_REGISTER_TYPE_W);
4562          allbld.ADD(idx, nir_system_values[SYSTEM_VALUE_SUBGROUP_INVOCATION],
4563                          brw_imm_w(-1));
4564          allbld.emit(SHADER_OPCODE_SHUFFLE, shifted, scan, idx);
4565          allbld.group(1, 0).MOV(component(shifted, 0), identity);
4566          scan = shifted;
4567       }
4568
4569       bld.emit_scan(brw_op, scan, dispatch_width, cond_mod);
4570
4571       bld.MOV(retype(dest, src.type), scan);
4572       break;
4573    }
4574
4575    case nir_intrinsic_begin_invocation_interlock: {
4576       const fs_builder ubld = bld.group(8, 0);
4577       const fs_reg tmp = ubld.vgrf(BRW_REGISTER_TYPE_UD, 2);
4578
4579       ubld.emit(SHADER_OPCODE_INTERLOCK, tmp)->size_written = 2 *
4580          REG_SIZE;
4581
4582       break;
4583    }
4584
4585    case nir_intrinsic_end_invocation_interlock: {
4586       /* We don't need to do anything here */
4587       break;
4588    }
4589
4590    default:
4591       unreachable("unknown intrinsic");
4592    }
4593 }
4594
4595 void
4596 fs_visitor::nir_emit_ssbo_atomic(const fs_builder &bld,
4597                                  int op, nir_intrinsic_instr *instr)
4598 {
4599    if (stage == MESA_SHADER_FRAGMENT)
4600       brw_wm_prog_data(prog_data)->has_side_effects = true;
4601
4602    fs_reg dest;
4603    if (nir_intrinsic_infos[instr->intrinsic].has_dest)
4604       dest = get_nir_dest(instr->dest);
4605
4606    fs_reg surface = get_nir_ssbo_intrinsic_index(bld, instr);
4607    fs_reg offset = get_nir_src(instr->src[1]);
4608    fs_reg data1;
4609    if (op != BRW_AOP_INC && op != BRW_AOP_DEC && op != BRW_AOP_PREDEC)
4610       data1 = get_nir_src(instr->src[2]);
4611    fs_reg data2;
4612    if (op == BRW_AOP_CMPWR)
4613       data2 = get_nir_src(instr->src[3]);
4614
4615    /* Emit the actual atomic operation */
4616
4617    fs_reg atomic_result = emit_untyped_atomic(bld, surface, offset,
4618                                               data1, data2,
4619                                               1 /* dims */, 1 /* rsize */,
4620                                               op,
4621                                               BRW_PREDICATE_NONE);
4622    dest.type = atomic_result.type;
4623    bld.MOV(dest, atomic_result);
4624 }
4625
4626 void
4627 fs_visitor::nir_emit_ssbo_atomic_float(const fs_builder &bld,
4628                                        int op, nir_intrinsic_instr *instr)
4629 {
4630    if (stage == MESA_SHADER_FRAGMENT)
4631       brw_wm_prog_data(prog_data)->has_side_effects = true;
4632
4633    fs_reg dest;
4634    if (nir_intrinsic_infos[instr->intrinsic].has_dest)
4635       dest = get_nir_dest(instr->dest);
4636
4637    fs_reg surface = get_nir_ssbo_intrinsic_index(bld, instr);
4638    fs_reg offset = get_nir_src(instr->src[1]);
4639    fs_reg data1 = get_nir_src(instr->src[2]);
4640    fs_reg data2;
4641    if (op == BRW_AOP_FCMPWR)
4642       data2 = get_nir_src(instr->src[3]);
4643
4644    /* Emit the actual atomic operation */
4645
4646    fs_reg atomic_result = emit_untyped_atomic_float(bld, surface, offset,
4647                                                     data1, data2,
4648                                                     1 /* dims */, 1 /* rsize */,
4649                                                     op,
4650                                                     BRW_PREDICATE_NONE);
4651    dest.type = atomic_result.type;
4652    bld.MOV(dest, atomic_result);
4653 }
4654
4655 void
4656 fs_visitor::nir_emit_shared_atomic(const fs_builder &bld,
4657                                    int op, nir_intrinsic_instr *instr)
4658 {
4659    fs_reg dest;
4660    if (nir_intrinsic_infos[instr->intrinsic].has_dest)
4661       dest = get_nir_dest(instr->dest);
4662
4663    fs_reg surface = brw_imm_ud(GEN7_BTI_SLM);
4664    fs_reg offset;
4665    fs_reg data1;
4666    if (op != BRW_AOP_INC && op != BRW_AOP_DEC && op != BRW_AOP_PREDEC)
4667       data1 = get_nir_src(instr->src[1]);
4668    fs_reg data2;
4669    if (op == BRW_AOP_CMPWR)
4670       data2 = get_nir_src(instr->src[2]);
4671
4672    /* Get the offset */
4673    if (nir_src_is_const(instr->src[0])) {
4674       offset = brw_imm_ud(instr->const_index[0] +
4675                           nir_src_as_uint(instr->src[0]));
4676    } else {
4677       offset = vgrf(glsl_type::uint_type);
4678       bld.ADD(offset,
4679               retype(get_nir_src(instr->src[0]), BRW_REGISTER_TYPE_UD),
4680               brw_imm_ud(instr->const_index[0]));
4681    }
4682
4683    /* Emit the actual atomic operation operation */
4684
4685    fs_reg atomic_result = emit_untyped_atomic(bld, surface, offset,
4686                                               data1, data2,
4687                                               1 /* dims */, 1 /* rsize */,
4688                                               op,
4689                                               BRW_PREDICATE_NONE);
4690    dest.type = atomic_result.type;
4691    bld.MOV(dest, atomic_result);
4692 }
4693
4694 void
4695 fs_visitor::nir_emit_shared_atomic_float(const fs_builder &bld,
4696                                          int op, nir_intrinsic_instr *instr)
4697 {
4698    fs_reg dest;
4699    if (nir_intrinsic_infos[instr->intrinsic].has_dest)
4700       dest = get_nir_dest(instr->dest);
4701
4702    fs_reg surface = brw_imm_ud(GEN7_BTI_SLM);
4703    fs_reg offset;
4704    fs_reg data1 = get_nir_src(instr->src[1]);
4705    fs_reg data2;
4706    if (op == BRW_AOP_FCMPWR)
4707       data2 = get_nir_src(instr->src[2]);
4708
4709    /* Get the offset */
4710    if (nir_src_is_const(instr->src[0])) {
4711       offset = brw_imm_ud(instr->const_index[0] +
4712                           nir_src_as_uint(instr->src[0]));
4713    } else {
4714       offset = vgrf(glsl_type::uint_type);
4715       bld.ADD(offset,
4716               retype(get_nir_src(instr->src[0]), BRW_REGISTER_TYPE_UD),
4717               brw_imm_ud(instr->const_index[0]));
4718    }
4719
4720    /* Emit the actual atomic operation operation */
4721
4722    fs_reg atomic_result = emit_untyped_atomic_float(bld, surface, offset,
4723                                                     data1, data2,
4724                                                     1 /* dims */, 1 /* rsize */,
4725                                                     op,
4726                                                     BRW_PREDICATE_NONE);
4727    dest.type = atomic_result.type;
4728    bld.MOV(dest, atomic_result);
4729 }
4730
4731 void
4732 fs_visitor::nir_emit_texture(const fs_builder &bld, nir_tex_instr *instr)
4733 {
4734    unsigned texture = instr->texture_index;
4735    unsigned sampler = instr->sampler_index;
4736
4737    fs_reg srcs[TEX_LOGICAL_NUM_SRCS];
4738
4739    srcs[TEX_LOGICAL_SRC_SURFACE] = brw_imm_ud(texture);
4740    srcs[TEX_LOGICAL_SRC_SAMPLER] = brw_imm_ud(sampler);
4741
4742    int lod_components = 0;
4743
4744    /* The hardware requires a LOD for buffer textures */
4745    if (instr->sampler_dim == GLSL_SAMPLER_DIM_BUF)
4746       srcs[TEX_LOGICAL_SRC_LOD] = brw_imm_d(0);
4747
4748    uint32_t header_bits = 0;
4749    for (unsigned i = 0; i < instr->num_srcs; i++) {
4750       fs_reg src = get_nir_src(instr->src[i].src);
4751       switch (instr->src[i].src_type) {
4752       case nir_tex_src_bias:
4753          srcs[TEX_LOGICAL_SRC_LOD] =
4754             retype(get_nir_src_imm(instr->src[i].src), BRW_REGISTER_TYPE_F);
4755          break;
4756       case nir_tex_src_comparator:
4757          srcs[TEX_LOGICAL_SRC_SHADOW_C] = retype(src, BRW_REGISTER_TYPE_F);
4758          break;
4759       case nir_tex_src_coord:
4760          switch (instr->op) {
4761          case nir_texop_txf:
4762          case nir_texop_txf_ms:
4763          case nir_texop_txf_ms_mcs:
4764          case nir_texop_samples_identical:
4765             srcs[TEX_LOGICAL_SRC_COORDINATE] = retype(src, BRW_REGISTER_TYPE_D);
4766             break;
4767          default:
4768             srcs[TEX_LOGICAL_SRC_COORDINATE] = retype(src, BRW_REGISTER_TYPE_F);
4769             break;
4770          }
4771          break;
4772       case nir_tex_src_ddx:
4773          srcs[TEX_LOGICAL_SRC_LOD] = retype(src, BRW_REGISTER_TYPE_F);
4774          lod_components = nir_tex_instr_src_size(instr, i);
4775          break;
4776       case nir_tex_src_ddy:
4777          srcs[TEX_LOGICAL_SRC_LOD2] = retype(src, BRW_REGISTER_TYPE_F);
4778          break;
4779       case nir_tex_src_lod:
4780          switch (instr->op) {
4781          case nir_texop_txs:
4782             srcs[TEX_LOGICAL_SRC_LOD] =
4783                retype(get_nir_src_imm(instr->src[i].src), BRW_REGISTER_TYPE_UD);
4784             break;
4785          case nir_texop_txf:
4786             srcs[TEX_LOGICAL_SRC_LOD] =
4787                retype(get_nir_src_imm(instr->src[i].src), BRW_REGISTER_TYPE_D);
4788             break;
4789          default:
4790             srcs[TEX_LOGICAL_SRC_LOD] =
4791                retype(get_nir_src_imm(instr->src[i].src), BRW_REGISTER_TYPE_F);
4792             break;
4793          }
4794          break;
4795       case nir_tex_src_min_lod:
4796          srcs[TEX_LOGICAL_SRC_MIN_LOD] =
4797             retype(get_nir_src_imm(instr->src[i].src), BRW_REGISTER_TYPE_F);
4798          break;
4799       case nir_tex_src_ms_index:
4800          srcs[TEX_LOGICAL_SRC_SAMPLE_INDEX] = retype(src, BRW_REGISTER_TYPE_UD);
4801          break;
4802
4803       case nir_tex_src_offset: {
4804          nir_const_value *const_offset =
4805             nir_src_as_const_value(instr->src[i].src);
4806          assert(nir_src_bit_size(instr->src[i].src) == 32);
4807          unsigned offset_bits = 0;
4808          if (const_offset &&
4809              brw_texture_offset(const_offset->i32,
4810                                 nir_tex_instr_src_size(instr, i),
4811                                 &offset_bits)) {
4812             header_bits |= offset_bits;
4813          } else {
4814             srcs[TEX_LOGICAL_SRC_TG4_OFFSET] =
4815                retype(src, BRW_REGISTER_TYPE_D);
4816          }
4817          break;
4818       }
4819
4820       case nir_tex_src_projector:
4821          unreachable("should be lowered");
4822
4823       case nir_tex_src_texture_offset: {
4824          /* Figure out the highest possible texture index and mark it as used */
4825          uint32_t max_used = texture + instr->texture_array_size - 1;
4826          if (instr->op == nir_texop_tg4 && devinfo->gen < 8) {
4827             max_used += stage_prog_data->binding_table.gather_texture_start;
4828          } else {
4829             max_used += stage_prog_data->binding_table.texture_start;
4830          }
4831          brw_mark_surface_used(prog_data, max_used);
4832
4833          /* Emit code to evaluate the actual indexing expression */
4834          fs_reg tmp = vgrf(glsl_type::uint_type);
4835          bld.ADD(tmp, src, brw_imm_ud(texture));
4836          srcs[TEX_LOGICAL_SRC_SURFACE] = bld.emit_uniformize(tmp);
4837          break;
4838       }
4839
4840       case nir_tex_src_sampler_offset: {
4841          /* Emit code to evaluate the actual indexing expression */
4842          fs_reg tmp = vgrf(glsl_type::uint_type);
4843          bld.ADD(tmp, src, brw_imm_ud(sampler));
4844          srcs[TEX_LOGICAL_SRC_SAMPLER] = bld.emit_uniformize(tmp);
4845          break;
4846       }
4847
4848       case nir_tex_src_ms_mcs:
4849          assert(instr->op == nir_texop_txf_ms);
4850          srcs[TEX_LOGICAL_SRC_MCS] = retype(src, BRW_REGISTER_TYPE_D);
4851          break;
4852
4853       case nir_tex_src_plane: {
4854          const uint32_t plane = nir_src_as_uint(instr->src[i].src);
4855          const uint32_t texture_index =
4856             instr->texture_index +
4857             stage_prog_data->binding_table.plane_start[plane] -
4858             stage_prog_data->binding_table.texture_start;
4859
4860          srcs[TEX_LOGICAL_SRC_SURFACE] = brw_imm_ud(texture_index);
4861          break;
4862       }
4863
4864       default:
4865          unreachable("unknown texture source");
4866       }
4867    }
4868
4869    if (srcs[TEX_LOGICAL_SRC_MCS].file == BAD_FILE &&
4870        (instr->op == nir_texop_txf_ms ||
4871         instr->op == nir_texop_samples_identical)) {
4872       if (devinfo->gen >= 7 &&
4873           key_tex->compressed_multisample_layout_mask & (1 << texture)) {
4874          srcs[TEX_LOGICAL_SRC_MCS] =
4875             emit_mcs_fetch(srcs[TEX_LOGICAL_SRC_COORDINATE],
4876                            instr->coord_components,
4877                            srcs[TEX_LOGICAL_SRC_SURFACE]);
4878       } else {
4879          srcs[TEX_LOGICAL_SRC_MCS] = brw_imm_ud(0u);
4880       }
4881    }
4882
4883    srcs[TEX_LOGICAL_SRC_COORD_COMPONENTS] = brw_imm_d(instr->coord_components);
4884    srcs[TEX_LOGICAL_SRC_GRAD_COMPONENTS] = brw_imm_d(lod_components);
4885
4886    enum opcode opcode;
4887    switch (instr->op) {
4888    case nir_texop_tex:
4889       opcode = (stage == MESA_SHADER_FRAGMENT ? SHADER_OPCODE_TEX_LOGICAL :
4890                 SHADER_OPCODE_TXL_LOGICAL);
4891       break;
4892    case nir_texop_txb:
4893       opcode = FS_OPCODE_TXB_LOGICAL;
4894       break;
4895    case nir_texop_txl:
4896       opcode = SHADER_OPCODE_TXL_LOGICAL;
4897       break;
4898    case nir_texop_txd:
4899       opcode = SHADER_OPCODE_TXD_LOGICAL;
4900       break;
4901    case nir_texop_txf:
4902       opcode = SHADER_OPCODE_TXF_LOGICAL;
4903       break;
4904    case nir_texop_txf_ms:
4905       if ((key_tex->msaa_16 & (1 << sampler)))
4906          opcode = SHADER_OPCODE_TXF_CMS_W_LOGICAL;
4907       else
4908          opcode = SHADER_OPCODE_TXF_CMS_LOGICAL;
4909       break;
4910    case nir_texop_txf_ms_mcs:
4911       opcode = SHADER_OPCODE_TXF_MCS_LOGICAL;
4912       break;
4913    case nir_texop_query_levels:
4914    case nir_texop_txs:
4915       opcode = SHADER_OPCODE_TXS_LOGICAL;
4916       break;
4917    case nir_texop_lod:
4918       opcode = SHADER_OPCODE_LOD_LOGICAL;
4919       break;
4920    case nir_texop_tg4:
4921       if (srcs[TEX_LOGICAL_SRC_TG4_OFFSET].file != BAD_FILE)
4922          opcode = SHADER_OPCODE_TG4_OFFSET_LOGICAL;
4923       else
4924          opcode = SHADER_OPCODE_TG4_LOGICAL;
4925       break;
4926    case nir_texop_texture_samples:
4927       opcode = SHADER_OPCODE_SAMPLEINFO_LOGICAL;
4928       break;
4929    case nir_texop_samples_identical: {
4930       fs_reg dst = retype(get_nir_dest(instr->dest), BRW_REGISTER_TYPE_D);
4931
4932       /* If mcs is an immediate value, it means there is no MCS.  In that case
4933        * just return false.
4934        */
4935       if (srcs[TEX_LOGICAL_SRC_MCS].file == BRW_IMMEDIATE_VALUE) {
4936          bld.MOV(dst, brw_imm_ud(0u));
4937       } else if ((key_tex->msaa_16 & (1 << sampler))) {
4938          fs_reg tmp = vgrf(glsl_type::uint_type);
4939          bld.OR(tmp, srcs[TEX_LOGICAL_SRC_MCS],
4940                 offset(srcs[TEX_LOGICAL_SRC_MCS], bld, 1));
4941          bld.CMP(dst, tmp, brw_imm_ud(0u), BRW_CONDITIONAL_EQ);
4942       } else {
4943          bld.CMP(dst, srcs[TEX_LOGICAL_SRC_MCS], brw_imm_ud(0u),
4944                  BRW_CONDITIONAL_EQ);
4945       }
4946       return;
4947    }
4948    default:
4949       unreachable("unknown texture opcode");
4950    }
4951
4952    if (instr->op == nir_texop_tg4) {
4953       if (instr->component == 1 &&
4954           key_tex->gather_channel_quirk_mask & (1 << texture)) {
4955          /* gather4 sampler is broken for green channel on RG32F --
4956           * we must ask for blue instead.
4957           */
4958          header_bits |= 2 << 16;
4959       } else {
4960          header_bits |= instr->component << 16;
4961       }
4962    }
4963
4964    fs_reg dst = bld.vgrf(brw_type_for_nir_type(devinfo, instr->dest_type), 4);
4965    fs_inst *inst = bld.emit(opcode, dst, srcs, ARRAY_SIZE(srcs));
4966    inst->offset = header_bits;
4967
4968    const unsigned dest_size = nir_tex_instr_dest_size(instr);
4969    if (devinfo->gen >= 9 &&
4970        instr->op != nir_texop_tg4 && instr->op != nir_texop_query_levels) {
4971       unsigned write_mask = instr->dest.is_ssa ?
4972                             nir_ssa_def_components_read(&instr->dest.ssa):
4973                             (1 << dest_size) - 1;
4974       assert(write_mask != 0); /* dead code should have been eliminated */
4975       inst->size_written = util_last_bit(write_mask) *
4976                            inst->dst.component_size(inst->exec_size);
4977    } else {
4978       inst->size_written = 4 * inst->dst.component_size(inst->exec_size);
4979    }
4980
4981    if (srcs[TEX_LOGICAL_SRC_SHADOW_C].file != BAD_FILE)
4982       inst->shadow_compare = true;
4983
4984    if (instr->op == nir_texop_tg4 && devinfo->gen == 6)
4985       emit_gen6_gather_wa(key_tex->gen6_gather_wa[texture], dst);
4986
4987    fs_reg nir_dest[4];
4988    for (unsigned i = 0; i < dest_size; i++)
4989       nir_dest[i] = offset(dst, bld, i);
4990
4991    if (instr->op == nir_texop_query_levels) {
4992       /* # levels is in .w */
4993       nir_dest[0] = offset(dst, bld, 3);
4994    } else if (instr->op == nir_texop_txs &&
4995               dest_size >= 3 && devinfo->gen < 7) {
4996       /* Gen4-6 return 0 instead of 1 for single layer surfaces. */
4997       fs_reg depth = offset(dst, bld, 2);
4998       nir_dest[2] = vgrf(glsl_type::int_type);
4999       bld.emit_minmax(nir_dest[2], depth, brw_imm_d(1), BRW_CONDITIONAL_GE);
5000    }
5001
5002    bld.LOAD_PAYLOAD(get_nir_dest(instr->dest), nir_dest, dest_size, 0);
5003 }
5004
5005 void
5006 fs_visitor::nir_emit_jump(const fs_builder &bld, nir_jump_instr *instr)
5007 {
5008    switch (instr->type) {
5009    case nir_jump_break:
5010       bld.emit(BRW_OPCODE_BREAK);
5011       break;
5012    case nir_jump_continue:
5013       bld.emit(BRW_OPCODE_CONTINUE);
5014       break;
5015    case nir_jump_return:
5016    default:
5017       unreachable("unknown jump");
5018    }
5019 }
5020
5021 /*
5022  * This helper takes a source register and un/shuffles it into the destination
5023  * register.
5024  *
5025  * If source type size is smaller than destination type size the operation
5026  * needed is a component shuffle. The opposite case would be an unshuffle. If
5027  * source/destination type size is equal a shuffle is done that would be
5028  * equivalent to a simple MOV.
5029  *
5030  * For example, if source is a 16-bit type and destination is 32-bit. A 3
5031  * components .xyz 16-bit vector on SIMD8 would be.
5032  *
5033  *    |x1|x2|x3|x4|x5|x6|x7|x8|y1|y2|y3|y4|y5|y6|y7|y8|
5034  *    |z1|z2|z3|z4|z5|z6|z7|z8|  |  |  |  |  |  |  |  |
5035  *
5036  * This helper will return the following 2 32-bit components with the 16-bit
5037  * values shuffled:
5038  *
5039  *    |x1 y1|x2 y2|x3 y3|x4 y4|x5 y5|x6 y6|x7 y7|x8 y8|
5040  *    |z1   |z2   |z3   |z4   |z5   |z6   |z7   |z8   |
5041  *
5042  * For unshuffle, the example would be the opposite, a 64-bit type source
5043  * and a 32-bit destination. A 2 component .xy 64-bit vector on SIMD8
5044  * would be:
5045  *
5046  *    | x1l   x1h | x2l   x2h | x3l   x3h | x4l   x4h |
5047  *    | x5l   x5h | x6l   x6h | x7l   x7h | x8l   x8h |
5048  *    | y1l   y1h | y2l   y2h | y3l   y3h | y4l   y4h |
5049  *    | y5l   y5h | y6l   y6h | y7l   y7h | y8l   y8h |
5050  *
5051  * The returned result would be the following 4 32-bit components unshuffled:
5052  *
5053  *    | x1l | x2l | x3l | x4l | x5l | x6l | x7l | x8l |
5054  *    | x1h | x2h | x3h | x4h | x5h | x6h | x7h | x8h |
5055  *    | y1l | y2l | y3l | y4l | y5l | y6l | y7l | y8l |
5056  *    | y1h | y2h | y3h | y4h | y5h | y6h | y7h | y8h |
5057  *
5058  * - Source and destination register must not be overlapped.
5059  * - components units are measured in terms of the smaller type between
5060  *   source and destination because we are un/shuffling the smaller
5061  *   components from/into the bigger ones.
5062  * - first_component parameter allows skipping source components.
5063  */
5064 void
5065 shuffle_src_to_dst(const fs_builder &bld,
5066                    const fs_reg &dst,
5067                    const fs_reg &src,
5068                    uint32_t first_component,
5069                    uint32_t components)
5070 {
5071    if (type_sz(src.type) == type_sz(dst.type)) {
5072       assert(!regions_overlap(dst,
5073          type_sz(dst.type) * bld.dispatch_width() * components,
5074          offset(src, bld, first_component),
5075          type_sz(src.type) * bld.dispatch_width() * components));
5076       for (unsigned i = 0; i < components; i++) {
5077          bld.MOV(retype(offset(dst, bld, i), src.type),
5078                  offset(src, bld, i + first_component));
5079       }
5080    } else if (type_sz(src.type) < type_sz(dst.type)) {
5081       /* Source is shuffled into destination */
5082       unsigned size_ratio = type_sz(dst.type) / type_sz(src.type);
5083       assert(!regions_overlap(dst,
5084          type_sz(dst.type) * bld.dispatch_width() *
5085          DIV_ROUND_UP(components, size_ratio),
5086          offset(src, bld, first_component),
5087          type_sz(src.type) * bld.dispatch_width() * components));
5088
5089       brw_reg_type shuffle_type =
5090          brw_reg_type_from_bit_size(8 * type_sz(src.type),
5091                                     BRW_REGISTER_TYPE_D);
5092       for (unsigned i = 0; i < components; i++) {
5093          fs_reg shuffle_component_i =
5094             subscript(offset(dst, bld, i / size_ratio),
5095                       shuffle_type, i % size_ratio);
5096          bld.MOV(shuffle_component_i,
5097                  retype(offset(src, bld, i + first_component), shuffle_type));
5098       }
5099    } else {
5100       /* Source is unshuffled into destination */
5101       unsigned size_ratio = type_sz(src.type) / type_sz(dst.type);
5102       assert(!regions_overlap(dst,
5103          type_sz(dst.type) * bld.dispatch_width() * components,
5104          offset(src, bld, first_component / size_ratio),
5105          type_sz(src.type) * bld.dispatch_width() *
5106          DIV_ROUND_UP(components + (first_component % size_ratio),
5107                       size_ratio)));
5108
5109       brw_reg_type shuffle_type =
5110          brw_reg_type_from_bit_size(8 * type_sz(dst.type),
5111                                     BRW_REGISTER_TYPE_D);
5112       for (unsigned i = 0; i < components; i++) {
5113          fs_reg shuffle_component_i =
5114             subscript(offset(src, bld, (first_component + i) / size_ratio),
5115                       shuffle_type, (first_component + i) % size_ratio);
5116          bld.MOV(retype(offset(dst, bld, i), shuffle_type),
5117                  shuffle_component_i);
5118       }
5119    }
5120 }
5121
5122 void
5123 shuffle_from_32bit_read(const fs_builder &bld,
5124                         const fs_reg &dst,
5125                         const fs_reg &src,
5126                         uint32_t first_component,
5127                         uint32_t components)
5128 {
5129    assert(type_sz(src.type) == 4);
5130
5131    /* This function takes components in units of the destination type while
5132     * shuffle_src_to_dst takes components in units of the smallest type
5133     */
5134    if (type_sz(dst.type) > 4) {
5135       assert(type_sz(dst.type) == 8);
5136       first_component *= 2;
5137       components *= 2;
5138    }
5139
5140    shuffle_src_to_dst(bld, dst, src, first_component, components);
5141 }
5142
5143 fs_reg
5144 shuffle_for_32bit_write(const fs_builder &bld,
5145                         const fs_reg &src,
5146                         uint32_t first_component,
5147                         uint32_t components)
5148 {
5149    fs_reg dst = bld.vgrf(BRW_REGISTER_TYPE_D,
5150                          DIV_ROUND_UP (components * type_sz(src.type), 4));
5151    /* This function takes components in units of the source type while
5152     * shuffle_src_to_dst takes components in units of the smallest type
5153     */
5154    if (type_sz(src.type) > 4) {
5155       assert(type_sz(src.type) == 8);
5156       first_component *= 2;
5157       components *= 2;
5158    }
5159
5160    shuffle_src_to_dst(bld, dst, src, first_component, components);
5161
5162    return dst;
5163 }
5164
5165 fs_reg
5166 setup_imm_df(const fs_builder &bld, double v)
5167 {
5168    const struct gen_device_info *devinfo = bld.shader->devinfo;
5169    assert(devinfo->gen >= 7);
5170
5171    if (devinfo->gen >= 8)
5172       return brw_imm_df(v);
5173
5174    /* gen7.5 does not support DF immediates straighforward but the DIM
5175     * instruction allows to set the 64-bit immediate value.
5176     */
5177    if (devinfo->is_haswell) {
5178       const fs_builder ubld = bld.exec_all().group(1, 0);
5179       fs_reg dst = ubld.vgrf(BRW_REGISTER_TYPE_DF, 1);
5180       ubld.DIM(dst, brw_imm_df(v));
5181       return component(dst, 0);
5182    }
5183
5184    /* gen7 does not support DF immediates, so we generate a 64-bit constant by
5185     * writing the low 32-bit of the constant to suboffset 0 of a VGRF and
5186     * the high 32-bit to suboffset 4 and then applying a stride of 0.
5187     *
5188     * Alternatively, we could also produce a normal VGRF (without stride 0)
5189     * by writing to all the channels in the VGRF, however, that would hit the
5190     * gen7 bug where we have to split writes that span more than 1 register
5191     * into instructions with a width of 4 (otherwise the write to the second
5192     * register written runs into an execmask hardware bug) which isn't very
5193     * nice.
5194     */
5195    union {
5196       double d;
5197       struct {
5198          uint32_t i1;
5199          uint32_t i2;
5200       };
5201    } di;
5202
5203    di.d = v;
5204
5205    const fs_builder ubld = bld.exec_all().group(1, 0);
5206    const fs_reg tmp = ubld.vgrf(BRW_REGISTER_TYPE_UD, 2);
5207    ubld.MOV(tmp, brw_imm_ud(di.i1));
5208    ubld.MOV(horiz_offset(tmp, 1), brw_imm_ud(di.i2));
5209
5210    return component(retype(tmp, BRW_REGISTER_TYPE_DF), 0);
5211 }
5212
5213 fs_reg
5214 setup_imm_b(const fs_builder &bld, int8_t v)
5215 {
5216    const fs_reg tmp = bld.vgrf(BRW_REGISTER_TYPE_B);
5217    bld.MOV(tmp, brw_imm_w(v));
5218    return tmp;
5219 }
5220
5221 fs_reg
5222 setup_imm_ub(const fs_builder &bld, uint8_t v)
5223 {
5224    const fs_reg tmp = bld.vgrf(BRW_REGISTER_TYPE_UB);
5225    bld.MOV(tmp, brw_imm_uw(v));
5226    return tmp;
5227 }