• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 /** @file brw_fs.cpp
25  *
26  * This file drives the GLSL IR -> LIR translation, contains the
27  * optimizations on the LIR, and drives the generation of native code
28  * from the LIR.
29  */
30 
31 #include "main/macros.h"
32 #include "brw_eu.h"
33 #include "brw_fs.h"
34 #include "brw_fs_live_variables.h"
35 #include "brw_nir.h"
36 #include "brw_vec4_gs_visitor.h"
37 #include "brw_cfg.h"
38 #include "brw_dead_control_flow.h"
39 #include "brw_private.h"
40 #include "dev/intel_debug.h"
41 #include "compiler/glsl_types.h"
42 #include "compiler/nir/nir_builder.h"
43 #include "program/prog_parameter.h"
44 #include "util/u_math.h"
45 
46 using namespace brw;
47 
48 static unsigned get_lowered_simd_width(const struct brw_compiler *compiler,
49                                        const fs_inst *inst);
50 
51 void
init(enum opcode opcode,uint8_t exec_size,const fs_reg & dst,const fs_reg * src,unsigned sources)52 fs_inst::init(enum opcode opcode, uint8_t exec_size, const fs_reg &dst,
53               const fs_reg *src, unsigned sources)
54 {
55    memset((void*)this, 0, sizeof(*this));
56 
57    this->src = new fs_reg[MAX2(sources, 3)];
58    for (unsigned i = 0; i < sources; i++)
59       this->src[i] = src[i];
60 
61    this->opcode = opcode;
62    this->dst = dst;
63    this->sources = sources;
64    this->exec_size = exec_size;
65    this->base_mrf = -1;
66 
67    assert(dst.file != IMM && dst.file != UNIFORM);
68 
69    assert(this->exec_size != 0);
70 
71    this->conditional_mod = BRW_CONDITIONAL_NONE;
72 
73    /* This will be the case for almost all instructions. */
74    switch (dst.file) {
75    case VGRF:
76    case ARF:
77    case FIXED_GRF:
78    case MRF:
79    case ATTR:
80       this->size_written = dst.component_size(exec_size);
81       break;
82    case BAD_FILE:
83       this->size_written = 0;
84       break;
85    case IMM:
86    case UNIFORM:
87       unreachable("Invalid destination register file");
88    }
89 
90    this->writes_accumulator = false;
91 }
92 
fs_inst()93 fs_inst::fs_inst()
94 {
95    init(BRW_OPCODE_NOP, 8, dst, NULL, 0);
96 }
97 
fs_inst(enum opcode opcode,uint8_t exec_size)98 fs_inst::fs_inst(enum opcode opcode, uint8_t exec_size)
99 {
100    init(opcode, exec_size, reg_undef, NULL, 0);
101 }
102 
fs_inst(enum opcode opcode,uint8_t exec_size,const fs_reg & dst)103 fs_inst::fs_inst(enum opcode opcode, uint8_t exec_size, const fs_reg &dst)
104 {
105    init(opcode, exec_size, dst, NULL, 0);
106 }
107 
fs_inst(enum opcode opcode,uint8_t exec_size,const fs_reg & dst,const fs_reg & src0)108 fs_inst::fs_inst(enum opcode opcode, uint8_t exec_size, const fs_reg &dst,
109                  const fs_reg &src0)
110 {
111    const fs_reg src[1] = { src0 };
112    init(opcode, exec_size, dst, src, 1);
113 }
114 
fs_inst(enum opcode opcode,uint8_t exec_size,const fs_reg & dst,const fs_reg & src0,const fs_reg & src1)115 fs_inst::fs_inst(enum opcode opcode, uint8_t exec_size, const fs_reg &dst,
116                  const fs_reg &src0, const fs_reg &src1)
117 {
118    const fs_reg src[2] = { src0, src1 };
119    init(opcode, exec_size, dst, src, 2);
120 }
121 
fs_inst(enum opcode opcode,uint8_t exec_size,const fs_reg & dst,const fs_reg & src0,const fs_reg & src1,const fs_reg & src2)122 fs_inst::fs_inst(enum opcode opcode, uint8_t exec_size, const fs_reg &dst,
123                  const fs_reg &src0, const fs_reg &src1, const fs_reg &src2)
124 {
125    const fs_reg src[3] = { src0, src1, src2 };
126    init(opcode, exec_size, dst, src, 3);
127 }
128 
fs_inst(enum opcode opcode,uint8_t exec_width,const fs_reg & dst,const fs_reg src[],unsigned sources)129 fs_inst::fs_inst(enum opcode opcode, uint8_t exec_width, const fs_reg &dst,
130                  const fs_reg src[], unsigned sources)
131 {
132    init(opcode, exec_width, dst, src, sources);
133 }
134 
fs_inst(const fs_inst & that)135 fs_inst::fs_inst(const fs_inst &that)
136 {
137    memcpy((void*)this, &that, sizeof(that));
138 
139    this->src = new fs_reg[MAX2(that.sources, 3)];
140 
141    for (unsigned i = 0; i < that.sources; i++)
142       this->src[i] = that.src[i];
143 }
144 
~fs_inst()145 fs_inst::~fs_inst()
146 {
147    delete[] this->src;
148 }
149 
150 void
resize_sources(uint8_t num_sources)151 fs_inst::resize_sources(uint8_t num_sources)
152 {
153    if (this->sources != num_sources) {
154       fs_reg *src = new fs_reg[MAX2(num_sources, 3)];
155 
156       for (unsigned i = 0; i < MIN2(this->sources, num_sources); ++i)
157          src[i] = this->src[i];
158 
159       delete[] this->src;
160       this->src = src;
161       this->sources = num_sources;
162    }
163 }
164 
165 void
VARYING_PULL_CONSTANT_LOAD(const fs_builder & bld,const fs_reg & dst,const fs_reg & surf_index,const fs_reg & varying_offset,uint32_t const_offset,uint8_t alignment)166 fs_visitor::VARYING_PULL_CONSTANT_LOAD(const fs_builder &bld,
167                                        const fs_reg &dst,
168                                        const fs_reg &surf_index,
169                                        const fs_reg &varying_offset,
170                                        uint32_t const_offset,
171                                        uint8_t alignment)
172 {
173    /* We have our constant surface use a pitch of 4 bytes, so our index can
174     * be any component of a vector, and then we load 4 contiguous
175     * components starting from that.
176     *
177     * We break down the const_offset to a portion added to the variable offset
178     * and a portion done using fs_reg::offset, which means that if you have
179     * GLSL using something like "uniform vec4 a[20]; gl_FragColor = a[i]",
180     * we'll temporarily generate 4 vec4 loads from offset i * 4, and CSE can
181     * later notice that those loads are all the same and eliminate the
182     * redundant ones.
183     */
184    fs_reg vec4_offset = vgrf(glsl_type::uint_type);
185    bld.ADD(vec4_offset, varying_offset, brw_imm_ud(const_offset & ~0xf));
186 
187    /* The pull load message will load a vec4 (16 bytes). If we are loading
188     * a double this means we are only loading 2 elements worth of data.
189     * We also want to use a 32-bit data type for the dst of the load operation
190     * so other parts of the driver don't get confused about the size of the
191     * result.
192     */
193    fs_reg vec4_result = bld.vgrf(BRW_REGISTER_TYPE_F, 4);
194    fs_inst *inst = bld.emit(FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_LOGICAL,
195                             vec4_result, surf_index, vec4_offset,
196                             brw_imm_ud(alignment));
197    inst->size_written = 4 * vec4_result.component_size(inst->exec_size);
198 
199    shuffle_from_32bit_read(bld, dst, vec4_result,
200                            (const_offset & 0xf) / type_sz(dst.type), 1);
201 }
202 
203 /**
204  * A helper for MOV generation for fixing up broken hardware SEND dependency
205  * handling.
206  */
207 void
DEP_RESOLVE_MOV(const fs_builder & bld,int grf)208 fs_visitor::DEP_RESOLVE_MOV(const fs_builder &bld, int grf)
209 {
210    /* The caller always wants uncompressed to emit the minimal extra
211     * dependencies, and to avoid having to deal with aligning its regs to 2.
212     */
213    const fs_builder ubld = bld.annotate("send dependency resolve")
214                               .quarter(0);
215 
216    ubld.MOV(ubld.null_reg_f(), fs_reg(VGRF, grf, BRW_REGISTER_TYPE_F));
217 }
218 
219 bool
is_send_from_grf() const220 fs_inst::is_send_from_grf() const
221 {
222    switch (opcode) {
223    case SHADER_OPCODE_SEND:
224    case FS_OPCODE_INTERPOLATE_AT_SAMPLE:
225    case FS_OPCODE_INTERPOLATE_AT_SHARED_OFFSET:
226    case FS_OPCODE_INTERPOLATE_AT_PER_SLOT_OFFSET:
227    case SHADER_OPCODE_INTERLOCK:
228    case SHADER_OPCODE_MEMORY_FENCE:
229    case SHADER_OPCODE_BARRIER:
230       return true;
231    case FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD:
232       return src[1].file == VGRF;
233    case FS_OPCODE_FB_WRITE:
234    case FS_OPCODE_FB_READ:
235       return src[0].file == VGRF;
236    default:
237       if (is_tex())
238          return src[0].file == VGRF;
239 
240       return false;
241    }
242 }
243 
244 bool
is_control_source(unsigned arg) const245 fs_inst::is_control_source(unsigned arg) const
246 {
247    switch (opcode) {
248    case FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD:
249    case FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD_GFX7:
250    case FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_GFX4:
251       return arg == 0;
252 
253    case SHADER_OPCODE_BROADCAST:
254    case SHADER_OPCODE_SHUFFLE:
255    case SHADER_OPCODE_QUAD_SWIZZLE:
256    case FS_OPCODE_INTERPOLATE_AT_SAMPLE:
257    case FS_OPCODE_INTERPOLATE_AT_SHARED_OFFSET:
258    case FS_OPCODE_INTERPOLATE_AT_PER_SLOT_OFFSET:
259    case SHADER_OPCODE_GET_BUFFER_SIZE:
260       return arg == 1;
261 
262    case SHADER_OPCODE_MOV_INDIRECT:
263    case SHADER_OPCODE_CLUSTER_BROADCAST:
264    case SHADER_OPCODE_TEX:
265    case FS_OPCODE_TXB:
266    case SHADER_OPCODE_TXD:
267    case SHADER_OPCODE_TXF:
268    case SHADER_OPCODE_TXF_LZ:
269    case SHADER_OPCODE_TXF_CMS:
270    case SHADER_OPCODE_TXF_CMS_W:
271    case SHADER_OPCODE_TXF_UMS:
272    case SHADER_OPCODE_TXF_MCS:
273    case SHADER_OPCODE_TXL:
274    case SHADER_OPCODE_TXL_LZ:
275    case SHADER_OPCODE_TXS:
276    case SHADER_OPCODE_LOD:
277    case SHADER_OPCODE_TG4:
278    case SHADER_OPCODE_TG4_OFFSET:
279    case SHADER_OPCODE_SAMPLEINFO:
280       return arg == 1 || arg == 2;
281 
282    case SHADER_OPCODE_SEND:
283       return arg == 0 || arg == 1;
284 
285    default:
286       return false;
287    }
288 }
289 
290 bool
is_payload(unsigned arg) const291 fs_inst::is_payload(unsigned arg) const
292 {
293    switch (opcode) {
294    case FS_OPCODE_FB_WRITE:
295    case FS_OPCODE_FB_READ:
296    case VEC4_OPCODE_UNTYPED_ATOMIC:
297    case VEC4_OPCODE_UNTYPED_SURFACE_READ:
298    case VEC4_OPCODE_UNTYPED_SURFACE_WRITE:
299    case FS_OPCODE_INTERPOLATE_AT_PER_SLOT_OFFSET:
300    case FS_OPCODE_INTERPOLATE_AT_SAMPLE:
301    case FS_OPCODE_INTERPOLATE_AT_SHARED_OFFSET:
302    case SHADER_OPCODE_INTERLOCK:
303    case SHADER_OPCODE_MEMORY_FENCE:
304    case SHADER_OPCODE_BARRIER:
305       return arg == 0;
306 
307    case FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD_GFX7:
308       return arg == 1;
309 
310    case SHADER_OPCODE_SEND:
311       return arg == 2 || arg == 3;
312 
313    default:
314       if (is_tex())
315          return arg == 0;
316       else
317          return false;
318    }
319 }
320 
321 /**
322  * Returns true if this instruction's sources and destinations cannot
323  * safely be the same register.
324  *
325  * In most cases, a register can be written over safely by the same
326  * instruction that is its last use.  For a single instruction, the
327  * sources are dereferenced before writing of the destination starts
328  * (naturally).
329  *
330  * However, there are a few cases where this can be problematic:
331  *
332  * - Virtual opcodes that translate to multiple instructions in the
333  *   code generator: if src == dst and one instruction writes the
334  *   destination before a later instruction reads the source, then
335  *   src will have been clobbered.
336  *
337  * - SIMD16 compressed instructions with certain regioning (see below).
338  *
339  * The register allocator uses this information to set up conflicts between
340  * GRF sources and the destination.
341  */
342 bool
has_source_and_destination_hazard() const343 fs_inst::has_source_and_destination_hazard() const
344 {
345    switch (opcode) {
346    case FS_OPCODE_PACK_HALF_2x16_SPLIT:
347       /* Multiple partial writes to the destination */
348       return true;
349    case SHADER_OPCODE_SHUFFLE:
350       /* This instruction returns an arbitrary channel from the source and
351        * gets split into smaller instructions in the generator.  It's possible
352        * that one of the instructions will read from a channel corresponding
353        * to an earlier instruction.
354        */
355    case SHADER_OPCODE_SEL_EXEC:
356       /* This is implemented as
357        *
358        * mov(16)      g4<1>D      0D            { align1 WE_all 1H };
359        * mov(16)      g4<1>D      g5<8,8,1>D    { align1 1H }
360        *
361        * Because the source is only read in the second instruction, the first
362        * may stomp all over it.
363        */
364       return true;
365    case SHADER_OPCODE_QUAD_SWIZZLE:
366       switch (src[1].ud) {
367       case BRW_SWIZZLE_XXXX:
368       case BRW_SWIZZLE_YYYY:
369       case BRW_SWIZZLE_ZZZZ:
370       case BRW_SWIZZLE_WWWW:
371       case BRW_SWIZZLE_XXZZ:
372       case BRW_SWIZZLE_YYWW:
373       case BRW_SWIZZLE_XYXY:
374       case BRW_SWIZZLE_ZWZW:
375          /* These can be implemented as a single Align1 region on all
376           * platforms, so there's never a hazard between source and
377           * destination.  C.f. fs_generator::generate_quad_swizzle().
378           */
379          return false;
380       default:
381          return !is_uniform(src[0]);
382       }
383    default:
384       /* The SIMD16 compressed instruction
385        *
386        * add(16)      g4<1>F      g4<8,8,1>F   g6<8,8,1>F
387        *
388        * is actually decoded in hardware as:
389        *
390        * add(8)       g4<1>F      g4<8,8,1>F   g6<8,8,1>F
391        * add(8)       g5<1>F      g5<8,8,1>F   g7<8,8,1>F
392        *
393        * Which is safe.  However, if we have uniform accesses
394        * happening, we get into trouble:
395        *
396        * add(8)       g4<1>F      g4<0,1,0>F   g6<8,8,1>F
397        * add(8)       g5<1>F      g4<0,1,0>F   g7<8,8,1>F
398        *
399        * Now our destination for the first instruction overwrote the
400        * second instruction's src0, and we get garbage for those 8
401        * pixels.  There's a similar issue for the pre-gfx6
402        * pixel_x/pixel_y, which are registers of 16-bit values and thus
403        * would get stomped by the first decode as well.
404        */
405       if (exec_size == 16) {
406          for (int i = 0; i < sources; i++) {
407             if (src[i].file == VGRF && (src[i].stride == 0 ||
408                                         src[i].type == BRW_REGISTER_TYPE_UW ||
409                                         src[i].type == BRW_REGISTER_TYPE_W ||
410                                         src[i].type == BRW_REGISTER_TYPE_UB ||
411                                         src[i].type == BRW_REGISTER_TYPE_B)) {
412                return true;
413             }
414          }
415       }
416       return false;
417    }
418 }
419 
420 bool
can_do_source_mods(const struct intel_device_info * devinfo) const421 fs_inst::can_do_source_mods(const struct intel_device_info *devinfo) const
422 {
423    if (devinfo->ver == 6 && is_math())
424       return false;
425 
426    if (is_send_from_grf())
427       return false;
428 
429    /* From Wa_1604601757:
430     *
431     * "When multiplying a DW and any lower precision integer, source modifier
432     *  is not supported."
433     */
434    if (devinfo->ver >= 12 && (opcode == BRW_OPCODE_MUL ||
435                               opcode == BRW_OPCODE_MAD)) {
436       const brw_reg_type exec_type = get_exec_type(this);
437       const unsigned min_type_sz = opcode == BRW_OPCODE_MAD ?
438          MIN2(type_sz(src[1].type), type_sz(src[2].type)) :
439          MIN2(type_sz(src[0].type), type_sz(src[1].type));
440 
441       if (brw_reg_type_is_integer(exec_type) &&
442           type_sz(exec_type) >= 4 &&
443           type_sz(exec_type) != min_type_sz)
444          return false;
445    }
446 
447    if (!backend_instruction::can_do_source_mods())
448       return false;
449 
450    return true;
451 }
452 
453 bool
can_do_cmod()454 fs_inst::can_do_cmod()
455 {
456    if (!backend_instruction::can_do_cmod())
457       return false;
458 
459    /* The accumulator result appears to get used for the conditional modifier
460     * generation.  When negating a UD value, there is a 33rd bit generated for
461     * the sign in the accumulator value, so now you can't check, for example,
462     * equality with a 32-bit value.  See piglit fs-op-neg-uvec4.
463     */
464    for (unsigned i = 0; i < sources; i++) {
465       if (brw_reg_type_is_unsigned_integer(src[i].type) && src[i].negate)
466          return false;
467    }
468 
469    return true;
470 }
471 
472 bool
can_change_types() const473 fs_inst::can_change_types() const
474 {
475    return dst.type == src[0].type &&
476           !src[0].abs && !src[0].negate && !saturate &&
477           (opcode == BRW_OPCODE_MOV ||
478            (opcode == BRW_OPCODE_SEL &&
479             dst.type == src[1].type &&
480             predicate != BRW_PREDICATE_NONE &&
481             !src[1].abs && !src[1].negate));
482 }
483 
484 void
init()485 fs_reg::init()
486 {
487    memset((void*)this, 0, sizeof(*this));
488    type = BRW_REGISTER_TYPE_UD;
489    stride = 1;
490 }
491 
492 /** Generic unset register constructor. */
fs_reg()493 fs_reg::fs_reg()
494 {
495    init();
496    this->file = BAD_FILE;
497 }
498 
fs_reg(struct::brw_reg reg)499 fs_reg::fs_reg(struct ::brw_reg reg) :
500    backend_reg(reg)
501 {
502    this->offset = 0;
503    this->stride = 1;
504    if (this->file == IMM &&
505        (this->type != BRW_REGISTER_TYPE_V &&
506         this->type != BRW_REGISTER_TYPE_UV &&
507         this->type != BRW_REGISTER_TYPE_VF)) {
508       this->stride = 0;
509    }
510 }
511 
512 bool
equals(const fs_reg & r) const513 fs_reg::equals(const fs_reg &r) const
514 {
515    return (this->backend_reg::equals(r) &&
516            stride == r.stride);
517 }
518 
519 bool
negative_equals(const fs_reg & r) const520 fs_reg::negative_equals(const fs_reg &r) const
521 {
522    return (this->backend_reg::negative_equals(r) &&
523            stride == r.stride);
524 }
525 
526 bool
is_contiguous() const527 fs_reg::is_contiguous() const
528 {
529    switch (file) {
530    case ARF:
531    case FIXED_GRF:
532       return hstride == BRW_HORIZONTAL_STRIDE_1 &&
533              vstride == width + hstride;
534    case MRF:
535    case VGRF:
536    case ATTR:
537       return stride == 1;
538    case UNIFORM:
539    case IMM:
540    case BAD_FILE:
541       return true;
542    }
543 
544    unreachable("Invalid register file");
545 }
546 
547 unsigned
component_size(unsigned width) const548 fs_reg::component_size(unsigned width) const
549 {
550    const unsigned stride = ((file != ARF && file != FIXED_GRF) ? this->stride :
551                             hstride == 0 ? 0 :
552                             1 << (hstride - 1));
553    return MAX2(width * stride, 1) * type_sz(type);
554 }
555 
556 /**
557  * Create a MOV to read the timestamp register.
558  */
559 fs_reg
get_timestamp(const fs_builder & bld)560 fs_visitor::get_timestamp(const fs_builder &bld)
561 {
562    assert(devinfo->ver >= 7);
563 
564    fs_reg ts = fs_reg(retype(brw_vec4_reg(BRW_ARCHITECTURE_REGISTER_FILE,
565                                           BRW_ARF_TIMESTAMP,
566                                           0),
567                              BRW_REGISTER_TYPE_UD));
568 
569    fs_reg dst = fs_reg(VGRF, alloc.allocate(1), BRW_REGISTER_TYPE_UD);
570 
571    /* We want to read the 3 fields we care about even if it's not enabled in
572     * the dispatch.
573     */
574    bld.group(4, 0).exec_all().MOV(dst, ts);
575 
576    return dst;
577 }
578 
579 void
vfail(const char * format,va_list va)580 fs_visitor::vfail(const char *format, va_list va)
581 {
582    char *msg;
583 
584    if (failed)
585       return;
586 
587    failed = true;
588 
589    msg = ralloc_vasprintf(mem_ctx, format, va);
590    msg = ralloc_asprintf(mem_ctx, "SIMD%d %s compile failed: %s\n",
591          dispatch_width, stage_abbrev, msg);
592 
593    this->fail_msg = msg;
594 
595    if (unlikely(debug_enabled)) {
596       fprintf(stderr, "%s",  msg);
597    }
598 }
599 
600 void
fail(const char * format,...)601 fs_visitor::fail(const char *format, ...)
602 {
603    va_list va;
604 
605    va_start(va, format);
606    vfail(format, va);
607    va_end(va);
608 }
609 
610 /**
611  * Mark this program as impossible to compile with dispatch width greater
612  * than n.
613  *
614  * During the SIMD8 compile (which happens first), we can detect and flag
615  * things that are unsupported in SIMD16+ mode, so the compiler can skip the
616  * SIMD16+ compile altogether.
617  *
618  * During a compile of dispatch width greater than n (if one happens anyway),
619  * this just calls fail().
620  */
621 void
limit_dispatch_width(unsigned n,const char * msg)622 fs_visitor::limit_dispatch_width(unsigned n, const char *msg)
623 {
624    if (dispatch_width > n) {
625       fail("%s", msg);
626    } else {
627       max_dispatch_width = MIN2(max_dispatch_width, n);
628       brw_shader_perf_log(compiler, log_data,
629                           "Shader dispatch width limited to SIMD%d: %s\n",
630                           n, msg);
631    }
632 }
633 
634 /**
635  * Returns true if the instruction has a flag that means it won't
636  * update an entire destination register.
637  *
638  * For example, dead code elimination and live variable analysis want to know
639  * when a write to a variable screens off any preceding values that were in
640  * it.
641  */
642 bool
is_partial_write() const643 fs_inst::is_partial_write() const
644 {
645    return ((this->predicate && this->opcode != BRW_OPCODE_SEL) ||
646            (this->exec_size * type_sz(this->dst.type)) < 32 ||
647            !this->dst.is_contiguous() ||
648            this->dst.offset % REG_SIZE != 0);
649 }
650 
651 unsigned
components_read(unsigned i) const652 fs_inst::components_read(unsigned i) const
653 {
654    /* Return zero if the source is not present. */
655    if (src[i].file == BAD_FILE)
656       return 0;
657 
658    switch (opcode) {
659    case FS_OPCODE_LINTERP:
660       if (i == 0)
661          return 2;
662       else
663          return 1;
664 
665    case FS_OPCODE_PIXEL_X:
666    case FS_OPCODE_PIXEL_Y:
667       assert(i < 2);
668       if (i == 0)
669          return 2;
670       else
671          return 1;
672 
673    case FS_OPCODE_FB_WRITE_LOGICAL:
674       assert(src[FB_WRITE_LOGICAL_SRC_COMPONENTS].file == IMM);
675       /* First/second FB write color. */
676       if (i < 2)
677          return src[FB_WRITE_LOGICAL_SRC_COMPONENTS].ud;
678       else
679          return 1;
680 
681    case SHADER_OPCODE_TEX_LOGICAL:
682    case SHADER_OPCODE_TXD_LOGICAL:
683    case SHADER_OPCODE_TXF_LOGICAL:
684    case SHADER_OPCODE_TXL_LOGICAL:
685    case SHADER_OPCODE_TXS_LOGICAL:
686    case SHADER_OPCODE_IMAGE_SIZE_LOGICAL:
687    case FS_OPCODE_TXB_LOGICAL:
688    case SHADER_OPCODE_TXF_CMS_LOGICAL:
689    case SHADER_OPCODE_TXF_CMS_W_LOGICAL:
690    case SHADER_OPCODE_TXF_CMS_W_GFX12_LOGICAL:
691    case SHADER_OPCODE_TXF_UMS_LOGICAL:
692    case SHADER_OPCODE_TXF_MCS_LOGICAL:
693    case SHADER_OPCODE_LOD_LOGICAL:
694    case SHADER_OPCODE_TG4_LOGICAL:
695    case SHADER_OPCODE_TG4_OFFSET_LOGICAL:
696    case SHADER_OPCODE_SAMPLEINFO_LOGICAL:
697       assert(src[TEX_LOGICAL_SRC_COORD_COMPONENTS].file == IMM &&
698              src[TEX_LOGICAL_SRC_GRAD_COMPONENTS].file == IMM);
699       /* Texture coordinates. */
700       if (i == TEX_LOGICAL_SRC_COORDINATE)
701          return src[TEX_LOGICAL_SRC_COORD_COMPONENTS].ud;
702       /* Texture derivatives. */
703       else if ((i == TEX_LOGICAL_SRC_LOD || i == TEX_LOGICAL_SRC_LOD2) &&
704                opcode == SHADER_OPCODE_TXD_LOGICAL)
705          return src[TEX_LOGICAL_SRC_GRAD_COMPONENTS].ud;
706       /* Texture offset. */
707       else if (i == TEX_LOGICAL_SRC_TG4_OFFSET)
708          return 2;
709       /* MCS */
710       else if (i == TEX_LOGICAL_SRC_MCS) {
711          if (opcode == SHADER_OPCODE_TXF_CMS_W_LOGICAL)
712             return 2;
713          else if (opcode == SHADER_OPCODE_TXF_CMS_W_GFX12_LOGICAL)
714             return 4;
715          else
716             return 1;
717       } else
718          return 1;
719 
720    case SHADER_OPCODE_UNTYPED_SURFACE_READ_LOGICAL:
721    case SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL:
722       assert(src[SURFACE_LOGICAL_SRC_IMM_DIMS].file == IMM);
723       /* Surface coordinates. */
724       if (i == SURFACE_LOGICAL_SRC_ADDRESS)
725          return src[SURFACE_LOGICAL_SRC_IMM_DIMS].ud;
726       /* Surface operation source (ignored for reads). */
727       else if (i == SURFACE_LOGICAL_SRC_DATA)
728          return 0;
729       else
730          return 1;
731 
732    case SHADER_OPCODE_UNTYPED_SURFACE_WRITE_LOGICAL:
733    case SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL:
734       assert(src[SURFACE_LOGICAL_SRC_IMM_DIMS].file == IMM &&
735              src[SURFACE_LOGICAL_SRC_IMM_ARG].file == IMM);
736       /* Surface coordinates. */
737       if (i == SURFACE_LOGICAL_SRC_ADDRESS)
738          return src[SURFACE_LOGICAL_SRC_IMM_DIMS].ud;
739       /* Surface operation source. */
740       else if (i == SURFACE_LOGICAL_SRC_DATA)
741          return src[SURFACE_LOGICAL_SRC_IMM_ARG].ud;
742       else
743          return 1;
744 
745    case SHADER_OPCODE_A64_UNTYPED_READ_LOGICAL:
746    case SHADER_OPCODE_A64_OWORD_BLOCK_READ_LOGICAL:
747    case SHADER_OPCODE_A64_UNALIGNED_OWORD_BLOCK_READ_LOGICAL:
748       assert(src[2].file == IMM);
749       return 1;
750 
751    case SHADER_OPCODE_A64_OWORD_BLOCK_WRITE_LOGICAL:
752       assert(src[2].file == IMM);
753       if (i == 1) { /* data to write */
754          const unsigned comps = src[2].ud / exec_size;
755          assert(comps > 0);
756          return comps;
757       } else {
758          return 1;
759       }
760 
761    case SHADER_OPCODE_OWORD_BLOCK_READ_LOGICAL:
762    case SHADER_OPCODE_UNALIGNED_OWORD_BLOCK_READ_LOGICAL:
763       assert(src[SURFACE_LOGICAL_SRC_IMM_ARG].file == IMM);
764       return 1;
765 
766    case SHADER_OPCODE_OWORD_BLOCK_WRITE_LOGICAL:
767       assert(src[SURFACE_LOGICAL_SRC_IMM_ARG].file == IMM);
768       if (i == SURFACE_LOGICAL_SRC_DATA) {
769          const unsigned comps = src[SURFACE_LOGICAL_SRC_IMM_ARG].ud / exec_size;
770          assert(comps > 0);
771          return comps;
772       } else {
773          return 1;
774       }
775 
776    case SHADER_OPCODE_A64_UNTYPED_WRITE_LOGICAL:
777       assert(src[2].file == IMM);
778       return i == 1 ? src[2].ud : 1;
779 
780    case SHADER_OPCODE_A64_UNTYPED_ATOMIC_LOGICAL:
781    case SHADER_OPCODE_A64_UNTYPED_ATOMIC_INT16_LOGICAL:
782    case SHADER_OPCODE_A64_UNTYPED_ATOMIC_INT64_LOGICAL:
783       assert(src[2].file == IMM);
784       if (i == 1) {
785          /* Data source */
786          const unsigned op = src[2].ud;
787          switch (op) {
788          case BRW_AOP_INC:
789          case BRW_AOP_DEC:
790          case BRW_AOP_PREDEC:
791             return 0;
792          case BRW_AOP_CMPWR:
793             return 2;
794          default:
795             return 1;
796          }
797       } else {
798          return 1;
799       }
800 
801    case SHADER_OPCODE_A64_UNTYPED_ATOMIC_FLOAT16_LOGICAL:
802    case SHADER_OPCODE_A64_UNTYPED_ATOMIC_FLOAT32_LOGICAL:
803    case SHADER_OPCODE_A64_UNTYPED_ATOMIC_FLOAT64_LOGICAL:
804       assert(src[2].file == IMM);
805       if (i == 1) {
806          /* Data source */
807          const unsigned op = src[2].ud;
808          return op == BRW_AOP_FCMPWR ? 2 : 1;
809       } else {
810          return 1;
811       }
812 
813    case SHADER_OPCODE_BYTE_SCATTERED_READ_LOGICAL:
814    case SHADER_OPCODE_DWORD_SCATTERED_READ_LOGICAL:
815       /* Scattered logical opcodes use the following params:
816        * src[0] Surface coordinates
817        * src[1] Surface operation source (ignored for reads)
818        * src[2] Surface
819        * src[3] IMM with always 1 dimension.
820        * src[4] IMM with arg bitsize for scattered read/write 8, 16, 32
821        */
822       assert(src[SURFACE_LOGICAL_SRC_IMM_DIMS].file == IMM &&
823              src[SURFACE_LOGICAL_SRC_IMM_ARG].file == IMM);
824       return i == SURFACE_LOGICAL_SRC_DATA ? 0 : 1;
825 
826    case SHADER_OPCODE_BYTE_SCATTERED_WRITE_LOGICAL:
827    case SHADER_OPCODE_DWORD_SCATTERED_WRITE_LOGICAL:
828       assert(src[SURFACE_LOGICAL_SRC_IMM_DIMS].file == IMM &&
829              src[SURFACE_LOGICAL_SRC_IMM_ARG].file == IMM);
830       return 1;
831 
832    case SHADER_OPCODE_UNTYPED_ATOMIC_LOGICAL:
833    case SHADER_OPCODE_TYPED_ATOMIC_LOGICAL: {
834       assert(src[SURFACE_LOGICAL_SRC_IMM_DIMS].file == IMM &&
835              src[SURFACE_LOGICAL_SRC_IMM_ARG].file == IMM);
836       const unsigned op = src[SURFACE_LOGICAL_SRC_IMM_ARG].ud;
837       /* Surface coordinates. */
838       if (i == SURFACE_LOGICAL_SRC_ADDRESS)
839          return src[SURFACE_LOGICAL_SRC_IMM_DIMS].ud;
840       /* Surface operation source. */
841       else if (i == SURFACE_LOGICAL_SRC_DATA && op == BRW_AOP_CMPWR)
842          return 2;
843       else if (i == SURFACE_LOGICAL_SRC_DATA &&
844                (op == BRW_AOP_INC || op == BRW_AOP_DEC || op == BRW_AOP_PREDEC))
845          return 0;
846       else
847          return 1;
848    }
849    case FS_OPCODE_INTERPOLATE_AT_PER_SLOT_OFFSET:
850       return (i == 0 ? 2 : 1);
851 
852    case SHADER_OPCODE_UNTYPED_ATOMIC_FLOAT_LOGICAL: {
853       assert(src[SURFACE_LOGICAL_SRC_IMM_DIMS].file == IMM &&
854              src[SURFACE_LOGICAL_SRC_IMM_ARG].file == IMM);
855       const unsigned op = src[SURFACE_LOGICAL_SRC_IMM_ARG].ud;
856       /* Surface coordinates. */
857       if (i == SURFACE_LOGICAL_SRC_ADDRESS)
858          return src[SURFACE_LOGICAL_SRC_IMM_DIMS].ud;
859       /* Surface operation source. */
860       else if (i == SURFACE_LOGICAL_SRC_DATA && op == BRW_AOP_FCMPWR)
861          return 2;
862       else
863          return 1;
864    }
865 
866    case SHADER_OPCODE_URB_WRITE_LOGICAL:
867       if (i == URB_LOGICAL_SRC_DATA)
868          return mlen - 1 -
869             unsigned(src[URB_LOGICAL_SRC_PER_SLOT_OFFSETS].file != BAD_FILE) -
870             unsigned(src[URB_LOGICAL_SRC_CHANNEL_MASK].file != BAD_FILE);
871       else
872          return 1;
873 
874    default:
875       return 1;
876    }
877 }
878 
879 unsigned
size_read(int arg) const880 fs_inst::size_read(int arg) const
881 {
882    switch (opcode) {
883    case SHADER_OPCODE_SEND:
884       if (arg == 2) {
885          return mlen * REG_SIZE;
886       } else if (arg == 3) {
887          return ex_mlen * REG_SIZE;
888       }
889       break;
890 
891    case FS_OPCODE_FB_WRITE:
892    case FS_OPCODE_REP_FB_WRITE:
893       if (arg == 0) {
894          if (base_mrf >= 0)
895             return src[0].file == BAD_FILE ? 0 : 2 * REG_SIZE;
896          else
897             return mlen * REG_SIZE;
898       }
899       break;
900 
901    case FS_OPCODE_FB_READ:
902    case FS_OPCODE_INTERPOLATE_AT_SAMPLE:
903    case FS_OPCODE_INTERPOLATE_AT_SHARED_OFFSET:
904       if (arg == 0)
905          return mlen * REG_SIZE;
906       break;
907 
908    case FS_OPCODE_SET_SAMPLE_ID:
909       if (arg == 1)
910          return 1;
911       break;
912 
913    case FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD_GFX7:
914       /* The payload is actually stored in src1 */
915       if (arg == 1)
916          return mlen * REG_SIZE;
917       break;
918 
919    case FS_OPCODE_LINTERP:
920       if (arg == 1)
921          return 16;
922       break;
923 
924    case SHADER_OPCODE_LOAD_PAYLOAD:
925       if (arg < this->header_size)
926          return REG_SIZE;
927       break;
928 
929    case CS_OPCODE_CS_TERMINATE:
930    case SHADER_OPCODE_BARRIER:
931       return REG_SIZE;
932 
933    case SHADER_OPCODE_MOV_INDIRECT:
934       if (arg == 0) {
935          assert(src[2].file == IMM);
936          return src[2].ud;
937       }
938       break;
939 
940    default:
941       if (is_tex() && arg == 0 && src[0].file == VGRF)
942          return mlen * REG_SIZE;
943       break;
944    }
945 
946    switch (src[arg].file) {
947    case UNIFORM:
948    case IMM:
949       return components_read(arg) * type_sz(src[arg].type);
950    case BAD_FILE:
951    case ARF:
952    case FIXED_GRF:
953    case VGRF:
954    case ATTR:
955       return components_read(arg) * src[arg].component_size(exec_size);
956    case MRF:
957       unreachable("MRF registers are not allowed as sources");
958    }
959    return 0;
960 }
961 
962 namespace {
963    unsigned
predicate_width(brw_predicate predicate)964    predicate_width(brw_predicate predicate)
965    {
966       switch (predicate) {
967       case BRW_PREDICATE_NONE:            return 1;
968       case BRW_PREDICATE_NORMAL:          return 1;
969       case BRW_PREDICATE_ALIGN1_ANY2H:    return 2;
970       case BRW_PREDICATE_ALIGN1_ALL2H:    return 2;
971       case BRW_PREDICATE_ALIGN1_ANY4H:    return 4;
972       case BRW_PREDICATE_ALIGN1_ALL4H:    return 4;
973       case BRW_PREDICATE_ALIGN1_ANY8H:    return 8;
974       case BRW_PREDICATE_ALIGN1_ALL8H:    return 8;
975       case BRW_PREDICATE_ALIGN1_ANY16H:   return 16;
976       case BRW_PREDICATE_ALIGN1_ALL16H:   return 16;
977       case BRW_PREDICATE_ALIGN1_ANY32H:   return 32;
978       case BRW_PREDICATE_ALIGN1_ALL32H:   return 32;
979       default: unreachable("Unsupported predicate");
980       }
981    }
982 
983    /* Return the subset of flag registers that an instruction could
984     * potentially read or write based on the execution controls and flag
985     * subregister number of the instruction.
986     */
987    unsigned
flag_mask(const fs_inst * inst,unsigned width)988    flag_mask(const fs_inst *inst, unsigned width)
989    {
990       assert(util_is_power_of_two_nonzero(width));
991       const unsigned start = (inst->flag_subreg * 16 + inst->group) &
992                              ~(width - 1);
993       const unsigned end = start + ALIGN(inst->exec_size, width);
994       return ((1 << DIV_ROUND_UP(end, 8)) - 1) & ~((1 << (start / 8)) - 1);
995    }
996 
997    unsigned
bit_mask(unsigned n)998    bit_mask(unsigned n)
999    {
1000       return (n >= CHAR_BIT * sizeof(bit_mask(n)) ? ~0u : (1u << n) - 1);
1001    }
1002 
1003    unsigned
flag_mask(const fs_reg & r,unsigned sz)1004    flag_mask(const fs_reg &r, unsigned sz)
1005    {
1006       if (r.file == ARF) {
1007          const unsigned start = (r.nr - BRW_ARF_FLAG) * 4 + r.subnr;
1008          const unsigned end = start + sz;
1009          return bit_mask(end) & ~bit_mask(start);
1010       } else {
1011          return 0;
1012       }
1013    }
1014 }
1015 
1016 unsigned
flags_read(const intel_device_info * devinfo) const1017 fs_inst::flags_read(const intel_device_info *devinfo) const
1018 {
1019    if (predicate == BRW_PREDICATE_ALIGN1_ANYV ||
1020        predicate == BRW_PREDICATE_ALIGN1_ALLV) {
1021       /* The vertical predication modes combine corresponding bits from
1022        * f0.0 and f1.0 on Gfx7+, and f0.0 and f0.1 on older hardware.
1023        */
1024       const unsigned shift = devinfo->ver >= 7 ? 4 : 2;
1025       return flag_mask(this, 1) << shift | flag_mask(this, 1);
1026    } else if (predicate) {
1027       return flag_mask(this, predicate_width(predicate));
1028    } else {
1029       unsigned mask = 0;
1030       for (int i = 0; i < sources; i++) {
1031          mask |= flag_mask(src[i], size_read(i));
1032       }
1033       return mask;
1034    }
1035 }
1036 
1037 unsigned
flags_written(const intel_device_info * devinfo) const1038 fs_inst::flags_written(const intel_device_info *devinfo) const
1039 {
1040    /* On Gfx4 and Gfx5, sel.l (for min) and sel.ge (for max) are implemented
1041     * using a separate cmpn and sel instruction.  This lowering occurs in
1042     * fs_vistor::lower_minmax which is called very, very late.
1043     */
1044    if ((conditional_mod && ((opcode != BRW_OPCODE_SEL || devinfo->ver <= 5) &&
1045                             opcode != BRW_OPCODE_CSEL &&
1046                             opcode != BRW_OPCODE_IF &&
1047                             opcode != BRW_OPCODE_WHILE)) ||
1048        opcode == FS_OPCODE_FB_WRITE) {
1049       return flag_mask(this, 1);
1050    } else if (opcode == SHADER_OPCODE_FIND_LIVE_CHANNEL ||
1051               opcode == SHADER_OPCODE_FIND_LAST_LIVE_CHANNEL ||
1052               opcode == FS_OPCODE_LOAD_LIVE_CHANNELS) {
1053       return flag_mask(this, 32);
1054    } else {
1055       return flag_mask(dst, size_written);
1056    }
1057 }
1058 
1059 /**
1060  * Returns how many MRFs an FS opcode will write over.
1061  *
1062  * Note that this is not the 0 or 1 implied writes in an actual gen
1063  * instruction -- the FS opcodes often generate MOVs in addition.
1064  */
1065 unsigned
implied_mrf_writes() const1066 fs_inst::implied_mrf_writes() const
1067 {
1068    if (mlen == 0)
1069       return 0;
1070 
1071    if (base_mrf == -1)
1072       return 0;
1073 
1074    switch (opcode) {
1075    case SHADER_OPCODE_RCP:
1076    case SHADER_OPCODE_RSQ:
1077    case SHADER_OPCODE_SQRT:
1078    case SHADER_OPCODE_EXP2:
1079    case SHADER_OPCODE_LOG2:
1080    case SHADER_OPCODE_SIN:
1081    case SHADER_OPCODE_COS:
1082       return 1 * exec_size / 8;
1083    case SHADER_OPCODE_POW:
1084    case SHADER_OPCODE_INT_QUOTIENT:
1085    case SHADER_OPCODE_INT_REMAINDER:
1086       return 2 * exec_size / 8;
1087    case SHADER_OPCODE_TEX:
1088    case FS_OPCODE_TXB:
1089    case SHADER_OPCODE_TXD:
1090    case SHADER_OPCODE_TXF:
1091    case SHADER_OPCODE_TXF_CMS:
1092    case SHADER_OPCODE_TXF_MCS:
1093    case SHADER_OPCODE_TG4:
1094    case SHADER_OPCODE_TG4_OFFSET:
1095    case SHADER_OPCODE_TXL:
1096    case SHADER_OPCODE_TXS:
1097    case SHADER_OPCODE_LOD:
1098    case SHADER_OPCODE_SAMPLEINFO:
1099       return 1;
1100    case FS_OPCODE_FB_WRITE:
1101    case FS_OPCODE_REP_FB_WRITE:
1102       return src[0].file == BAD_FILE ? 0 : 2;
1103    case FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD:
1104    case SHADER_OPCODE_GFX4_SCRATCH_READ:
1105       return 1;
1106    case FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_GFX4:
1107       return mlen;
1108    case SHADER_OPCODE_GFX4_SCRATCH_WRITE:
1109       return mlen;
1110    default:
1111       unreachable("not reached");
1112    }
1113 }
1114 
1115 fs_reg
vgrf(const glsl_type * const type)1116 fs_visitor::vgrf(const glsl_type *const type)
1117 {
1118    int reg_width = dispatch_width / 8;
1119    return fs_reg(VGRF,
1120                  alloc.allocate(glsl_count_dword_slots(type, false) * reg_width),
1121                  brw_type_for_base_type(type));
1122 }
1123 
fs_reg(enum brw_reg_file file,int nr)1124 fs_reg::fs_reg(enum brw_reg_file file, int nr)
1125 {
1126    init();
1127    this->file = file;
1128    this->nr = nr;
1129    this->type = BRW_REGISTER_TYPE_F;
1130    this->stride = (file == UNIFORM ? 0 : 1);
1131 }
1132 
fs_reg(enum brw_reg_file file,int nr,enum brw_reg_type type)1133 fs_reg::fs_reg(enum brw_reg_file file, int nr, enum brw_reg_type type)
1134 {
1135    init();
1136    this->file = file;
1137    this->nr = nr;
1138    this->type = type;
1139    this->stride = (file == UNIFORM ? 0 : 1);
1140 }
1141 
1142 /* For SIMD16, we need to follow from the uniform setup of SIMD8 dispatch.
1143  * This brings in those uniform definitions
1144  */
1145 void
import_uniforms(fs_visitor * v)1146 fs_visitor::import_uniforms(fs_visitor *v)
1147 {
1148    this->push_constant_loc = v->push_constant_loc;
1149    this->uniforms = v->uniforms;
1150    this->subgroup_id = v->subgroup_id;
1151    for (unsigned i = 0; i < ARRAY_SIZE(this->group_size); i++)
1152       this->group_size[i] = v->group_size[i];
1153 }
1154 
1155 void
emit_fragcoord_interpolation(fs_reg wpos)1156 fs_visitor::emit_fragcoord_interpolation(fs_reg wpos)
1157 {
1158    assert(stage == MESA_SHADER_FRAGMENT);
1159 
1160    /* gl_FragCoord.x */
1161    bld.MOV(wpos, this->pixel_x);
1162    wpos = offset(wpos, bld, 1);
1163 
1164    /* gl_FragCoord.y */
1165    bld.MOV(wpos, this->pixel_y);
1166    wpos = offset(wpos, bld, 1);
1167 
1168    /* gl_FragCoord.z */
1169    if (devinfo->ver >= 6) {
1170       bld.MOV(wpos, this->pixel_z);
1171    } else {
1172       bld.emit(FS_OPCODE_LINTERP, wpos,
1173                this->delta_xy[BRW_BARYCENTRIC_PERSPECTIVE_PIXEL],
1174                component(interp_reg(VARYING_SLOT_POS, 2), 0));
1175    }
1176    wpos = offset(wpos, bld, 1);
1177 
1178    /* gl_FragCoord.w: Already set up in emit_interpolation */
1179    bld.MOV(wpos, this->wpos_w);
1180 }
1181 
1182 enum brw_barycentric_mode
brw_barycentric_mode(nir_intrinsic_instr * intr)1183 brw_barycentric_mode(nir_intrinsic_instr *intr)
1184 {
1185    const glsl_interp_mode mode =
1186       (enum glsl_interp_mode) nir_intrinsic_interp_mode(intr);
1187 
1188    /* Barycentric modes don't make sense for flat inputs. */
1189    assert(mode != INTERP_MODE_FLAT);
1190 
1191    unsigned bary;
1192    switch (intr->intrinsic) {
1193    case nir_intrinsic_load_barycentric_pixel:
1194    case nir_intrinsic_load_barycentric_at_offset:
1195       bary = BRW_BARYCENTRIC_PERSPECTIVE_PIXEL;
1196       break;
1197    case nir_intrinsic_load_barycentric_centroid:
1198       bary = BRW_BARYCENTRIC_PERSPECTIVE_CENTROID;
1199       break;
1200    case nir_intrinsic_load_barycentric_sample:
1201    case nir_intrinsic_load_barycentric_at_sample:
1202       bary = BRW_BARYCENTRIC_PERSPECTIVE_SAMPLE;
1203       break;
1204    default:
1205       unreachable("invalid intrinsic");
1206    }
1207 
1208    if (mode == INTERP_MODE_NOPERSPECTIVE)
1209       bary += 3;
1210 
1211    return (enum brw_barycentric_mode) bary;
1212 }
1213 
1214 /**
1215  * Turn one of the two CENTROID barycentric modes into PIXEL mode.
1216  */
1217 static enum brw_barycentric_mode
centroid_to_pixel(enum brw_barycentric_mode bary)1218 centroid_to_pixel(enum brw_barycentric_mode bary)
1219 {
1220    assert(bary == BRW_BARYCENTRIC_PERSPECTIVE_CENTROID ||
1221           bary == BRW_BARYCENTRIC_NONPERSPECTIVE_CENTROID);
1222    return (enum brw_barycentric_mode) ((unsigned) bary - 1);
1223 }
1224 
1225 fs_reg
emit_frontfacing_interpolation()1226 fs_visitor::emit_frontfacing_interpolation()
1227 {
1228    fs_reg ff = bld.vgrf(BRW_REGISTER_TYPE_D);
1229 
1230    if (devinfo->ver >= 12) {
1231       fs_reg g1 = fs_reg(retype(brw_vec1_grf(1, 1), BRW_REGISTER_TYPE_W));
1232 
1233       fs_reg tmp = bld.vgrf(BRW_REGISTER_TYPE_W);
1234       bld.ASR(tmp, g1, brw_imm_d(15));
1235       bld.NOT(ff, tmp);
1236    } else if (devinfo->ver >= 6) {
1237       /* Bit 15 of g0.0 is 0 if the polygon is front facing. We want to create
1238        * a boolean result from this (~0/true or 0/false).
1239        *
1240        * We can use the fact that bit 15 is the MSB of g0.0:W to accomplish
1241        * this task in only one instruction:
1242        *    - a negation source modifier will flip the bit; and
1243        *    - a W -> D type conversion will sign extend the bit into the high
1244        *      word of the destination.
1245        *
1246        * An ASR 15 fills the low word of the destination.
1247        */
1248       fs_reg g0 = fs_reg(retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_W));
1249       g0.negate = true;
1250 
1251       bld.ASR(ff, g0, brw_imm_d(15));
1252    } else {
1253       /* Bit 31 of g1.6 is 0 if the polygon is front facing. We want to create
1254        * a boolean result from this (1/true or 0/false).
1255        *
1256        * Like in the above case, since the bit is the MSB of g1.6:UD we can use
1257        * the negation source modifier to flip it. Unfortunately the SHR
1258        * instruction only operates on UD (or D with an abs source modifier)
1259        * sources without negation.
1260        *
1261        * Instead, use ASR (which will give ~0/true or 0/false).
1262        */
1263       fs_reg g1_6 = fs_reg(retype(brw_vec1_grf(1, 6), BRW_REGISTER_TYPE_D));
1264       g1_6.negate = true;
1265 
1266       bld.ASR(ff, g1_6, brw_imm_d(31));
1267    }
1268 
1269    return ff;
1270 }
1271 
1272 fs_reg
emit_samplepos_setup()1273 fs_visitor::emit_samplepos_setup()
1274 {
1275    assert(stage == MESA_SHADER_FRAGMENT);
1276    struct brw_wm_prog_data *wm_prog_data = brw_wm_prog_data(this->prog_data);
1277    assert(devinfo->ver >= 6);
1278 
1279    const fs_builder abld = bld.annotate("compute sample position");
1280    fs_reg pos = abld.vgrf(BRW_REGISTER_TYPE_F, 2);
1281 
1282    if (!wm_prog_data->persample_dispatch) {
1283       /* From ARB_sample_shading specification:
1284        * "When rendering to a non-multisample buffer, or if multisample
1285        *  rasterization is disabled, gl_SamplePosition will always be
1286        *  (0.5, 0.5).
1287        */
1288       bld.MOV(offset(pos, bld, 0), brw_imm_f(0.5f));
1289       bld.MOV(offset(pos, bld, 1), brw_imm_f(0.5f));
1290       return pos;
1291    }
1292 
1293    /* WM will be run in MSDISPMODE_PERSAMPLE. So, only one of SIMD8 or SIMD16
1294     * mode will be enabled.
1295     *
1296     * From the Ivy Bridge PRM, volume 2 part 1, page 344:
1297     * R31.1:0         Position Offset X/Y for Slot[3:0]
1298     * R31.3:2         Position Offset X/Y for Slot[7:4]
1299     * .....
1300     *
1301     * The X, Y sample positions come in as bytes in  thread payload. So, read
1302     * the positions using vstride=16, width=8, hstride=2.
1303     */
1304    const fs_reg sample_pos_reg =
1305       fetch_payload_reg(abld, payload.sample_pos_reg, BRW_REGISTER_TYPE_W);
1306 
1307    for (unsigned i = 0; i < 2; i++) {
1308       fs_reg tmp_d = bld.vgrf(BRW_REGISTER_TYPE_D);
1309       abld.MOV(tmp_d, subscript(sample_pos_reg, BRW_REGISTER_TYPE_B, i));
1310       /* Convert int_sample_pos to floating point */
1311       fs_reg tmp_f = bld.vgrf(BRW_REGISTER_TYPE_F);
1312       abld.MOV(tmp_f, tmp_d);
1313       /* Scale to the range [0, 1] */
1314       abld.MUL(offset(pos, abld, i), tmp_f, brw_imm_f(1 / 16.0f));
1315    }
1316 
1317    return pos;
1318 }
1319 
1320 fs_reg
emit_sampleid_setup()1321 fs_visitor::emit_sampleid_setup()
1322 {
1323    assert(stage == MESA_SHADER_FRAGMENT);
1324    brw_wm_prog_key *key = (brw_wm_prog_key*) this->key;
1325    assert(devinfo->ver >= 6);
1326 
1327    const fs_builder abld = bld.annotate("compute sample id");
1328    fs_reg sample_id = abld.vgrf(BRW_REGISTER_TYPE_UD);
1329 
1330    assert(key->multisample_fbo);
1331 
1332    if (devinfo->ver >= 8) {
1333       /* Sample ID comes in as 4-bit numbers in g1.0:
1334        *
1335        *    15:12 Slot 3 SampleID (only used in SIMD16)
1336        *     11:8 Slot 2 SampleID (only used in SIMD16)
1337        *      7:4 Slot 1 SampleID
1338        *      3:0 Slot 0 SampleID
1339        *
1340        * Each slot corresponds to four channels, so we want to replicate each
1341        * half-byte value to 4 channels in a row:
1342        *
1343        *    dst+0:    .7    .6    .5    .4    .3    .2    .1    .0
1344        *             7:4   7:4   7:4   7:4   3:0   3:0   3:0   3:0
1345        *
1346        *    dst+1:    .7    .6    .5    .4    .3    .2    .1    .0  (if SIMD16)
1347        *           15:12 15:12 15:12 15:12  11:8  11:8  11:8  11:8
1348        *
1349        * First, we read g1.0 with a <1,8,0>UB region, causing the first 8
1350        * channels to read the first byte (7:0), and the second group of 8
1351        * channels to read the second byte (15:8).  Then, we shift right by
1352        * a vector immediate of <4, 4, 4, 4, 0, 0, 0, 0>, moving the slot 1 / 3
1353        * values into place.  Finally, we AND with 0xf to keep the low nibble.
1354        *
1355        *    shr(16) tmp<1>W g1.0<1,8,0>B 0x44440000:V
1356        *    and(16) dst<1>D tmp<8,8,1>W  0xf:W
1357        *
1358        * TODO: These payload bits exist on Gfx7 too, but they appear to always
1359        *       be zero, so this code fails to work.  We should find out why.
1360        */
1361       const fs_reg tmp = abld.vgrf(BRW_REGISTER_TYPE_UW);
1362 
1363       for (unsigned i = 0; i < DIV_ROUND_UP(dispatch_width, 16); i++) {
1364          const fs_builder hbld = abld.group(MIN2(16, dispatch_width), i);
1365          hbld.SHR(offset(tmp, hbld, i),
1366                   stride(retype(brw_vec1_grf(1 + i, 0), BRW_REGISTER_TYPE_UB),
1367                          1, 8, 0),
1368                   brw_imm_v(0x44440000));
1369       }
1370 
1371       abld.AND(sample_id, tmp, brw_imm_w(0xf));
1372    } else {
1373       const fs_reg t1 = component(abld.vgrf(BRW_REGISTER_TYPE_UD), 0);
1374       const fs_reg t2 = abld.vgrf(BRW_REGISTER_TYPE_UW);
1375 
1376       /* The PS will be run in MSDISPMODE_PERSAMPLE. For example with
1377        * 8x multisampling, subspan 0 will represent sample N (where N
1378        * is 0, 2, 4 or 6), subspan 1 will represent sample 1, 3, 5 or
1379        * 7. We can find the value of N by looking at R0.0 bits 7:6
1380        * ("Starting Sample Pair Index (SSPI)") and multiplying by two
1381        * (since samples are always delivered in pairs). That is, we
1382        * compute 2*((R0.0 & 0xc0) >> 6) == (R0.0 & 0xc0) >> 5. Then
1383        * we need to add N to the sequence (0, 0, 0, 0, 1, 1, 1, 1) in
1384        * case of SIMD8 and sequence (0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2,
1385        * 2, 3, 3, 3, 3) in case of SIMD16. We compute this sequence by
1386        * populating a temporary variable with the sequence (0, 1, 2, 3),
1387        * and then reading from it using vstride=1, width=4, hstride=0.
1388        * These computations hold good for 4x multisampling as well.
1389        *
1390        * For 2x MSAA and SIMD16, we want to use the sequence (0, 1, 0, 1):
1391        * the first four slots are sample 0 of subspan 0; the next four
1392        * are sample 1 of subspan 0; the third group is sample 0 of
1393        * subspan 1, and finally sample 1 of subspan 1.
1394        */
1395 
1396       /* SKL+ has an extra bit for the Starting Sample Pair Index to
1397        * accommodate 16x MSAA.
1398        */
1399       abld.exec_all().group(1, 0)
1400           .AND(t1, fs_reg(retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_UD)),
1401                brw_imm_ud(0xc0));
1402       abld.exec_all().group(1, 0).SHR(t1, t1, brw_imm_d(5));
1403 
1404       /* This works for SIMD8-SIMD16.  It also works for SIMD32 but only if we
1405        * can assume 4x MSAA.  Disallow it on IVB+
1406        *
1407        * FINISHME: One day, we could come up with a way to do this that
1408        * actually works on gfx7.
1409        */
1410       if (devinfo->ver >= 7)
1411          limit_dispatch_width(16, "gl_SampleId is unsupported in SIMD32 on gfx7");
1412       abld.exec_all().group(8, 0).MOV(t2, brw_imm_v(0x32103210));
1413 
1414       /* This special instruction takes care of setting vstride=1,
1415        * width=4, hstride=0 of t2 during an ADD instruction.
1416        */
1417       abld.emit(FS_OPCODE_SET_SAMPLE_ID, sample_id, t1, t2);
1418    }
1419 
1420    return sample_id;
1421 }
1422 
1423 fs_reg
emit_samplemaskin_setup()1424 fs_visitor::emit_samplemaskin_setup()
1425 {
1426    assert(stage == MESA_SHADER_FRAGMENT);
1427    struct brw_wm_prog_data *wm_prog_data = brw_wm_prog_data(this->prog_data);
1428    assert(devinfo->ver >= 6);
1429 
1430    fs_reg mask = bld.vgrf(BRW_REGISTER_TYPE_D);
1431 
1432    /* The HW doesn't provide us with expected values. */
1433    assert(!wm_prog_data->per_coarse_pixel_dispatch);
1434 
1435    fs_reg coverage_mask =
1436       fetch_payload_reg(bld, payload.sample_mask_in_reg, BRW_REGISTER_TYPE_D);
1437 
1438    if (wm_prog_data->persample_dispatch) {
1439       /* gl_SampleMaskIn[] comes from two sources: the input coverage mask,
1440        * and a mask representing which sample is being processed by the
1441        * current shader invocation.
1442        *
1443        * From the OES_sample_variables specification:
1444        * "When per-sample shading is active due to the use of a fragment input
1445        *  qualified by "sample" or due to the use of the gl_SampleID or
1446        *  gl_SamplePosition variables, only the bit for the current sample is
1447        *  set in gl_SampleMaskIn."
1448        */
1449       const fs_builder abld = bld.annotate("compute gl_SampleMaskIn");
1450 
1451       if (nir_system_values[SYSTEM_VALUE_SAMPLE_ID].file == BAD_FILE)
1452          nir_system_values[SYSTEM_VALUE_SAMPLE_ID] = emit_sampleid_setup();
1453 
1454       fs_reg one = vgrf(glsl_type::int_type);
1455       fs_reg enabled_mask = vgrf(glsl_type::int_type);
1456       abld.MOV(one, brw_imm_d(1));
1457       abld.SHL(enabled_mask, one, nir_system_values[SYSTEM_VALUE_SAMPLE_ID]);
1458       abld.AND(mask, enabled_mask, coverage_mask);
1459    } else {
1460       /* In per-pixel mode, the coverage mask is sufficient. */
1461       mask = coverage_mask;
1462    }
1463    return mask;
1464 }
1465 
1466 fs_reg
emit_shading_rate_setup()1467 fs_visitor::emit_shading_rate_setup()
1468 {
1469    assert(devinfo->ver >= 11);
1470 
1471    const fs_builder abld = bld.annotate("compute fragment shading rate");
1472    fs_reg rate = abld.vgrf(BRW_REGISTER_TYPE_UD);
1473 
1474    struct brw_wm_prog_data *wm_prog_data =
1475       brw_wm_prog_data(bld.shader->stage_prog_data);
1476 
1477    /* Coarse pixel shading size fields overlap with other fields of not in
1478     * coarse pixel dispatch mode, so report 0 when that's not the case.
1479     */
1480    if (wm_prog_data->per_coarse_pixel_dispatch) {
1481       /* The shading rates provided in the shader are the actual 2D shading
1482        * rate while the SPIR-V built-in is the enum value that has the shading
1483        * rate encoded as a bitfield.  Fortunately, the bitfield value is just
1484        * the shading rate divided by two and shifted.
1485        */
1486 
1487       /* r1.0 - 0:7 ActualCoarsePixelShadingSize.X */
1488       fs_reg actual_x = fs_reg(retype(brw_vec1_grf(1, 0), BRW_REGISTER_TYPE_UB));
1489       /* r1.0 - 15:8 ActualCoarsePixelShadingSize.Y */
1490       fs_reg actual_y = byte_offset(actual_x, 1);
1491 
1492       fs_reg int_rate_x = bld.vgrf(BRW_REGISTER_TYPE_UD);
1493       fs_reg int_rate_y = bld.vgrf(BRW_REGISTER_TYPE_UD);
1494 
1495       abld.SHR(int_rate_y, actual_y, brw_imm_ud(1));
1496       abld.SHR(int_rate_x, actual_x, brw_imm_ud(1));
1497       abld.SHL(int_rate_x, int_rate_x, brw_imm_ud(2));
1498       abld.OR(rate, int_rate_x, int_rate_y);
1499    } else {
1500       abld.MOV(rate, brw_imm_ud(0));
1501    }
1502 
1503    return rate;
1504 }
1505 
1506 fs_reg
resolve_source_modifiers(const fs_reg & src)1507 fs_visitor::resolve_source_modifiers(const fs_reg &src)
1508 {
1509    if (!src.abs && !src.negate)
1510       return src;
1511 
1512    fs_reg temp = bld.vgrf(src.type);
1513    bld.MOV(temp, src);
1514 
1515    return temp;
1516 }
1517 
1518 void
emit_gs_thread_end()1519 fs_visitor::emit_gs_thread_end()
1520 {
1521    assert(stage == MESA_SHADER_GEOMETRY);
1522 
1523    struct brw_gs_prog_data *gs_prog_data = brw_gs_prog_data(prog_data);
1524 
1525    if (gs_compile->control_data_header_size_bits > 0) {
1526       emit_gs_control_data_bits(this->final_gs_vertex_count);
1527    }
1528 
1529    const fs_builder abld = bld.annotate("thread end");
1530    fs_inst *inst;
1531 
1532    if (gs_prog_data->static_vertex_count != -1) {
1533       foreach_in_list_reverse(fs_inst, prev, &this->instructions) {
1534          if (prev->opcode == SHADER_OPCODE_URB_WRITE_LOGICAL) {
1535             prev->eot = true;
1536 
1537             /* Delete now dead instructions. */
1538             foreach_in_list_reverse_safe(exec_node, dead, &this->instructions) {
1539                if (dead == prev)
1540                   break;
1541                dead->remove();
1542             }
1543             return;
1544          } else if (prev->is_control_flow() || prev->has_side_effects()) {
1545             break;
1546          }
1547       }
1548       fs_reg srcs[URB_LOGICAL_NUM_SRCS];
1549       srcs[URB_LOGICAL_SRC_HANDLE] = fs_reg(retype(brw_vec8_grf(1, 0), BRW_REGISTER_TYPE_UD));
1550       inst = abld.emit(SHADER_OPCODE_URB_WRITE_LOGICAL, reg_undef,
1551                        srcs, ARRAY_SIZE(srcs));
1552       inst->mlen = 1;
1553    } else {
1554       fs_reg srcs[URB_LOGICAL_NUM_SRCS];
1555       srcs[URB_LOGICAL_SRC_HANDLE] = fs_reg(retype(brw_vec8_grf(1, 0), BRW_REGISTER_TYPE_UD));
1556       srcs[URB_LOGICAL_SRC_DATA] = this->final_gs_vertex_count;
1557       inst = abld.emit(SHADER_OPCODE_URB_WRITE_LOGICAL, reg_undef,
1558                        srcs, ARRAY_SIZE(srcs));
1559       inst->mlen = 2;
1560    }
1561    inst->eot = true;
1562    inst->offset = 0;
1563 }
1564 
1565 void
assign_curb_setup()1566 fs_visitor::assign_curb_setup()
1567 {
1568    unsigned uniform_push_length = DIV_ROUND_UP(stage_prog_data->nr_params, 8);
1569 
1570    unsigned ubo_push_length = 0;
1571    unsigned ubo_push_start[4];
1572    for (int i = 0; i < 4; i++) {
1573       ubo_push_start[i] = 8 * (ubo_push_length + uniform_push_length);
1574       ubo_push_length += stage_prog_data->ubo_ranges[i].length;
1575    }
1576 
1577    prog_data->curb_read_length = uniform_push_length + ubo_push_length;
1578 
1579    uint64_t used = 0;
1580    bool is_compute = gl_shader_stage_is_compute(stage);
1581 
1582    if (is_compute && brw_cs_prog_data(prog_data)->uses_inline_data) {
1583       /* With COMPUTE_WALKER, we can push up to one register worth of data via
1584        * the inline data parameter in the COMPUTE_WALKER command itself.
1585        *
1586        * TODO: Support inline data and push at the same time.
1587        */
1588       assert(devinfo->verx10 >= 125);
1589       assert(uniform_push_length <= 1);
1590    } else if (is_compute && devinfo->verx10 >= 125) {
1591       fs_builder ubld = bld.exec_all().group(8, 0).at(
1592          cfg->first_block(), cfg->first_block()->start());
1593 
1594       /* The base address for our push data is passed in as R0.0[31:6].  We
1595        * have to mask off the bottom 6 bits.
1596        */
1597       fs_reg base_addr = ubld.vgrf(BRW_REGISTER_TYPE_UD);
1598       ubld.group(1, 0).AND(base_addr,
1599                            retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_UD),
1600                            brw_imm_ud(INTEL_MASK(31, 6)));
1601 
1602       fs_reg header0 = ubld.vgrf(BRW_REGISTER_TYPE_UD);
1603       ubld.MOV(header0, brw_imm_ud(0));
1604       ubld.group(1, 0).SHR(component(header0, 2), base_addr, brw_imm_ud(4));
1605 
1606       /* On Gfx12-HP we load constants at the start of the program using A32
1607        * stateless messages.
1608        */
1609       for (unsigned i = 0; i < uniform_push_length;) {
1610          /* Limit ourselves to HW limit of 8 Owords (8 * 16bytes = 128 bytes
1611           * or 4 registers).
1612           */
1613          unsigned num_regs = MIN2(uniform_push_length - i, 4);
1614          assert(num_regs > 0);
1615          num_regs = 1 << util_logbase2(num_regs);
1616 
1617          fs_reg header;
1618          if (i == 0) {
1619             header = header0;
1620          } else {
1621             header = ubld.vgrf(BRW_REGISTER_TYPE_UD);
1622             ubld.MOV(header, brw_imm_ud(0));
1623             ubld.group(1, 0).ADD(component(header, 2),
1624                                  component(header0, 2),
1625                                  brw_imm_ud(i * 2));
1626          }
1627 
1628          fs_reg srcs[4] = {
1629             brw_imm_ud(0), /* desc */
1630             brw_imm_ud(0), /* ex_desc */
1631             header, /* payload */
1632             fs_reg(), /* payload2 */
1633          };
1634 
1635          fs_reg dest = retype(brw_vec8_grf(payload.num_regs + i, 0),
1636                               BRW_REGISTER_TYPE_UD);
1637 
1638          /* This instruction has to be run SIMD16 if we're filling more than a
1639           * single register.
1640           */
1641          unsigned send_width = MIN2(16, num_regs * 8);
1642 
1643          fs_inst *send = ubld.group(send_width, 0).emit(SHADER_OPCODE_SEND,
1644                                                         dest, srcs, 4);
1645          send->sfid = GFX7_SFID_DATAPORT_DATA_CACHE;
1646          send->desc = brw_dp_desc(devinfo, GFX8_BTI_STATELESS_NON_COHERENT,
1647                                   GFX7_DATAPORT_DC_OWORD_BLOCK_READ,
1648                                   BRW_DATAPORT_OWORD_BLOCK_OWORDS(num_regs * 2));
1649          send->header_size = 1;
1650          send->mlen = 1;
1651          send->size_written = num_regs * REG_SIZE;
1652          send->send_is_volatile = true;
1653 
1654          i += num_regs;
1655       }
1656 
1657       invalidate_analysis(DEPENDENCY_INSTRUCTIONS);
1658    }
1659 
1660    /* Map the offsets in the UNIFORM file to fixed HW regs. */
1661    foreach_block_and_inst(block, fs_inst, inst, cfg) {
1662       for (unsigned int i = 0; i < inst->sources; i++) {
1663 	 if (inst->src[i].file == UNIFORM) {
1664             int uniform_nr = inst->src[i].nr + inst->src[i].offset / 4;
1665             int constant_nr;
1666             if (inst->src[i].nr >= UBO_START) {
1667                /* constant_nr is in 32-bit units, the rest are in bytes */
1668                constant_nr = ubo_push_start[inst->src[i].nr - UBO_START] +
1669                              inst->src[i].offset / 4;
1670             } else if (uniform_nr >= 0 && uniform_nr < (int) uniforms) {
1671                constant_nr = push_constant_loc[uniform_nr];
1672             } else {
1673                /* Section 5.11 of the OpenGL 4.1 spec says:
1674                 * "Out-of-bounds reads return undefined values, which include
1675                 *  values from other variables of the active program or zero."
1676                 * Just return the first push constant.
1677                 */
1678                constant_nr = 0;
1679             }
1680 
1681             assert(constant_nr / 8 < 64);
1682             used |= BITFIELD64_BIT(constant_nr / 8);
1683 
1684 	    struct brw_reg brw_reg = brw_vec1_grf(payload.num_regs +
1685 						  constant_nr / 8,
1686 						  constant_nr % 8);
1687             brw_reg.abs = inst->src[i].abs;
1688             brw_reg.negate = inst->src[i].negate;
1689 
1690             assert(inst->src[i].stride == 0);
1691             inst->src[i] = byte_offset(
1692                retype(brw_reg, inst->src[i].type),
1693                inst->src[i].offset % 4);
1694 	 }
1695       }
1696    }
1697 
1698    uint64_t want_zero = used & stage_prog_data->zero_push_reg;
1699    if (want_zero) {
1700       fs_builder ubld = bld.exec_all().group(8, 0).at(
1701          cfg->first_block(), cfg->first_block()->start());
1702 
1703       /* push_reg_mask_param is in 32-bit units */
1704       unsigned mask_param = stage_prog_data->push_reg_mask_param;
1705       struct brw_reg mask = brw_vec1_grf(payload.num_regs + mask_param / 8,
1706                                                             mask_param % 8);
1707 
1708       fs_reg b32;
1709       for (unsigned i = 0; i < 64; i++) {
1710          if (i % 16 == 0 && (want_zero & BITFIELD64_RANGE(i, 16))) {
1711             fs_reg shifted = ubld.vgrf(BRW_REGISTER_TYPE_W, 2);
1712             ubld.SHL(horiz_offset(shifted, 8),
1713                      byte_offset(retype(mask, BRW_REGISTER_TYPE_W), i / 8),
1714                      brw_imm_v(0x01234567));
1715             ubld.SHL(shifted, horiz_offset(shifted, 8), brw_imm_w(8));
1716 
1717             fs_builder ubld16 = ubld.group(16, 0);
1718             b32 = ubld16.vgrf(BRW_REGISTER_TYPE_D);
1719             ubld16.group(16, 0).ASR(b32, shifted, brw_imm_w(15));
1720          }
1721 
1722          if (want_zero & BITFIELD64_BIT(i)) {
1723             assert(i < prog_data->curb_read_length);
1724             struct brw_reg push_reg =
1725                retype(brw_vec8_grf(payload.num_regs + i, 0),
1726                       BRW_REGISTER_TYPE_D);
1727 
1728             ubld.AND(push_reg, push_reg, component(b32, i % 16));
1729          }
1730       }
1731 
1732       invalidate_analysis(DEPENDENCY_INSTRUCTIONS);
1733    }
1734 
1735    /* This may be updated in assign_urb_setup or assign_vs_urb_setup. */
1736    this->first_non_payload_grf = payload.num_regs + prog_data->curb_read_length;
1737 }
1738 
1739 /*
1740  * Build up an array of indices into the urb_setup array that
1741  * references the active entries of the urb_setup array.
1742  * Used to accelerate walking the active entries of the urb_setup array
1743  * on each upload.
1744  */
1745 void
brw_compute_urb_setup_index(struct brw_wm_prog_data * wm_prog_data)1746 brw_compute_urb_setup_index(struct brw_wm_prog_data *wm_prog_data)
1747 {
1748    /* TODO(mesh): Review usage of this in the context of Mesh, we may want to
1749     * skip per-primitive attributes here.
1750     */
1751 
1752    /* Make sure uint8_t is sufficient */
1753    STATIC_ASSERT(VARYING_SLOT_MAX <= 0xff);
1754    uint8_t index = 0;
1755    for (uint8_t attr = 0; attr < VARYING_SLOT_MAX; attr++) {
1756       if (wm_prog_data->urb_setup[attr] >= 0) {
1757          wm_prog_data->urb_setup_attribs[index++] = attr;
1758       }
1759    }
1760    wm_prog_data->urb_setup_attribs_count = index;
1761 }
1762 
1763 static void
calculate_urb_setup(const struct intel_device_info * devinfo,const struct brw_wm_prog_key * key,struct brw_wm_prog_data * prog_data,const nir_shader * nir,const struct brw_mue_map * mue_map)1764 calculate_urb_setup(const struct intel_device_info *devinfo,
1765                     const struct brw_wm_prog_key *key,
1766                     struct brw_wm_prog_data *prog_data,
1767                     const nir_shader *nir,
1768                     const struct brw_mue_map *mue_map)
1769 {
1770    memset(prog_data->urb_setup, -1,
1771           sizeof(prog_data->urb_setup[0]) * VARYING_SLOT_MAX);
1772 
1773    int urb_next = 0;
1774 
1775    const uint64_t inputs_read =
1776       nir->info.inputs_read & ~nir->info.per_primitive_inputs;
1777 
1778    /* Figure out where each of the incoming setup attributes lands. */
1779    if (mue_map) {
1780       /* Per-Primitive Attributes are laid out by Hardware before the regular
1781        * attributes, so order them like this to make easy later to map setup
1782        * into real HW registers.
1783        */
1784       if (nir->info.per_primitive_inputs) {
1785          uint64_t per_prim_inputs_read =
1786                nir->info.inputs_read & nir->info.per_primitive_inputs;
1787 
1788          /* In Mesh, PRIMITIVE_SHADING_RATE, VIEWPORT and LAYER slots
1789           * are always at the beginning, because they come from MUE
1790           * Primitive Header, not Per-Primitive Attributes.
1791           */
1792          const uint64_t primitive_header_bits = VARYING_BIT_VIEWPORT |
1793                                                 VARYING_BIT_LAYER |
1794                                                 VARYING_BIT_PRIMITIVE_SHADING_RATE;
1795 
1796          if (per_prim_inputs_read & primitive_header_bits) {
1797             /* Primitive Shading Rate, Layer and Viewport live in the same
1798              * 4-dwords slot (psr is dword 0, layer is dword 1, and viewport
1799              * is dword 2).
1800              */
1801             if (per_prim_inputs_read & VARYING_BIT_PRIMITIVE_SHADING_RATE)
1802                prog_data->urb_setup[VARYING_SLOT_PRIMITIVE_SHADING_RATE] = 0;
1803 
1804             if (per_prim_inputs_read & VARYING_BIT_LAYER)
1805                prog_data->urb_setup[VARYING_SLOT_LAYER] = 0;
1806 
1807             if (per_prim_inputs_read & VARYING_BIT_VIEWPORT)
1808                prog_data->urb_setup[VARYING_SLOT_VIEWPORT] = 0;
1809 
1810             /* 3DSTATE_SBE_MESH.Per[Primitive|Vertex]URBEntryOutputRead[Offset|Length]
1811              * are in full GRFs (8 dwords) and MUE Primitive Header is 8 dwords,
1812              * so next per-primitive attribute must be placed in slot 2 (each slot
1813              * is 4 dwords long).
1814              */
1815             urb_next = 2;
1816             per_prim_inputs_read &= ~primitive_header_bits;
1817          }
1818 
1819          for (unsigned i = 0; i < VARYING_SLOT_MAX; i++) {
1820             if (per_prim_inputs_read & BITFIELD64_BIT(i)) {
1821                prog_data->urb_setup[i] = urb_next++;
1822             }
1823          }
1824 
1825          /* The actual setup attributes later must be aligned to a full GRF. */
1826          urb_next = ALIGN(urb_next, 2);
1827 
1828          prog_data->num_per_primitive_inputs = urb_next;
1829       }
1830 
1831       const uint64_t clip_dist_bits = VARYING_BIT_CLIP_DIST0 |
1832                                       VARYING_BIT_CLIP_DIST1;
1833 
1834       uint64_t unique_fs_attrs = inputs_read & BRW_FS_VARYING_INPUT_MASK;
1835 
1836       if (inputs_read & clip_dist_bits) {
1837          assert(mue_map->per_vertex_header_size_dw > 8);
1838          unique_fs_attrs &= ~clip_dist_bits;
1839       }
1840 
1841       /* In Mesh, CLIP_DIST slots are always at the beginning, because
1842        * they come from MUE Vertex Header, not Per-Vertex Attributes.
1843        */
1844       if (inputs_read & clip_dist_bits) {
1845          prog_data->urb_setup[VARYING_SLOT_CLIP_DIST0] = urb_next++;
1846          prog_data->urb_setup[VARYING_SLOT_CLIP_DIST1] = urb_next++;
1847       }
1848 
1849       /* Per-Vertex attributes are laid out ordered.  Because we always link
1850        * Mesh and Fragment shaders, the which slots are written and read by
1851        * each of them will match. */
1852       for (unsigned int i = 0; i < VARYING_SLOT_MAX; i++) {
1853          if (unique_fs_attrs & BITFIELD64_BIT(i))
1854             prog_data->urb_setup[i] = urb_next++;
1855       }
1856    } else if (devinfo->ver >= 6) {
1857       uint64_t vue_header_bits =
1858          VARYING_BIT_PSIZ | VARYING_BIT_LAYER | VARYING_BIT_VIEWPORT;
1859 
1860       uint64_t unique_fs_attrs = inputs_read & BRW_FS_VARYING_INPUT_MASK;
1861 
1862       /* VUE header fields all live in the same URB slot, so we pass them
1863        * as a single FS input attribute.  We want to only count them once.
1864        */
1865       if (inputs_read & vue_header_bits) {
1866          unique_fs_attrs &= ~vue_header_bits;
1867          unique_fs_attrs |= VARYING_BIT_PSIZ;
1868       }
1869 
1870       if (util_bitcount64(unique_fs_attrs) <= 16) {
1871          /* The SF/SBE pipeline stage can do arbitrary rearrangement of the
1872           * first 16 varying inputs, so we can put them wherever we want.
1873           * Just put them in order.
1874           *
1875           * This is useful because it means that (a) inputs not used by the
1876           * fragment shader won't take up valuable register space, and (b) we
1877           * won't have to recompile the fragment shader if it gets paired with
1878           * a different vertex (or geometry) shader.
1879           *
1880           * VUE header fields share the same FS input attribute.
1881           */
1882          if (inputs_read & vue_header_bits) {
1883             if (inputs_read & VARYING_BIT_PSIZ)
1884                prog_data->urb_setup[VARYING_SLOT_PSIZ] = urb_next;
1885             if (inputs_read & VARYING_BIT_LAYER)
1886                prog_data->urb_setup[VARYING_SLOT_LAYER] = urb_next;
1887             if (inputs_read & VARYING_BIT_VIEWPORT)
1888                prog_data->urb_setup[VARYING_SLOT_VIEWPORT] = urb_next;
1889 
1890             urb_next++;
1891          }
1892 
1893          for (unsigned int i = 0; i < VARYING_SLOT_MAX; i++) {
1894             if (inputs_read & BRW_FS_VARYING_INPUT_MASK & ~vue_header_bits &
1895                 BITFIELD64_BIT(i)) {
1896                prog_data->urb_setup[i] = urb_next++;
1897             }
1898          }
1899       } else {
1900          /* We have enough input varyings that the SF/SBE pipeline stage can't
1901           * arbitrarily rearrange them to suit our whim; we have to put them
1902           * in an order that matches the output of the previous pipeline stage
1903           * (geometry or vertex shader).
1904           */
1905 
1906          /* Re-compute the VUE map here in the case that the one coming from
1907           * geometry has more than one position slot (used for Primitive
1908           * Replication).
1909           */
1910          struct brw_vue_map prev_stage_vue_map;
1911          brw_compute_vue_map(devinfo, &prev_stage_vue_map,
1912                              key->input_slots_valid,
1913                              nir->info.separate_shader, 1);
1914 
1915          int first_slot =
1916             brw_compute_first_urb_slot_required(inputs_read,
1917                                                 &prev_stage_vue_map);
1918 
1919          assert(prev_stage_vue_map.num_slots <= first_slot + 32);
1920          for (int slot = first_slot; slot < prev_stage_vue_map.num_slots;
1921               slot++) {
1922             int varying = prev_stage_vue_map.slot_to_varying[slot];
1923             if (varying != BRW_VARYING_SLOT_PAD &&
1924                 (inputs_read & BRW_FS_VARYING_INPUT_MASK &
1925                  BITFIELD64_BIT(varying))) {
1926                prog_data->urb_setup[varying] = slot - first_slot;
1927             }
1928          }
1929          urb_next = prev_stage_vue_map.num_slots - first_slot;
1930       }
1931    } else {
1932       /* FINISHME: The sf doesn't map VS->FS inputs for us very well. */
1933       for (unsigned int i = 0; i < VARYING_SLOT_MAX; i++) {
1934          /* Point size is packed into the header, not as a general attribute */
1935          if (i == VARYING_SLOT_PSIZ)
1936             continue;
1937 
1938 	 if (key->input_slots_valid & BITFIELD64_BIT(i)) {
1939 	    /* The back color slot is skipped when the front color is
1940 	     * also written to.  In addition, some slots can be
1941 	     * written in the vertex shader and not read in the
1942 	     * fragment shader.  So the register number must always be
1943 	     * incremented, mapped or not.
1944 	     */
1945 	    if (_mesa_varying_slot_in_fs((gl_varying_slot) i))
1946 	       prog_data->urb_setup[i] = urb_next;
1947             urb_next++;
1948 	 }
1949       }
1950 
1951       /*
1952        * It's a FS only attribute, and we did interpolation for this attribute
1953        * in SF thread. So, count it here, too.
1954        *
1955        * See compile_sf_prog() for more info.
1956        */
1957       if (inputs_read & BITFIELD64_BIT(VARYING_SLOT_PNTC))
1958          prog_data->urb_setup[VARYING_SLOT_PNTC] = urb_next++;
1959    }
1960 
1961    prog_data->num_varying_inputs = urb_next - prog_data->num_per_primitive_inputs;
1962    prog_data->inputs = inputs_read;
1963 
1964    brw_compute_urb_setup_index(prog_data);
1965 }
1966 
1967 void
assign_urb_setup()1968 fs_visitor::assign_urb_setup()
1969 {
1970    assert(stage == MESA_SHADER_FRAGMENT);
1971    struct brw_wm_prog_data *prog_data = brw_wm_prog_data(this->prog_data);
1972 
1973    int urb_start = payload.num_regs + prog_data->base.curb_read_length;
1974 
1975    /* Offset all the urb_setup[] index by the actual position of the
1976     * setup regs, now that the location of the constants has been chosen.
1977     */
1978    foreach_block_and_inst(block, fs_inst, inst, cfg) {
1979       for (int i = 0; i < inst->sources; i++) {
1980          if (inst->src[i].file == ATTR) {
1981             /* ATTR regs in the FS are in units of logical scalar inputs each
1982              * of which consumes half of a GRF register.
1983              */
1984             assert(inst->src[i].offset < REG_SIZE / 2);
1985             const unsigned grf = urb_start + inst->src[i].nr / 2;
1986             const unsigned offset = (inst->src[i].nr % 2) * (REG_SIZE / 2) +
1987                                     inst->src[i].offset;
1988             const unsigned width = inst->src[i].stride == 0 ?
1989                                    1 : MIN2(inst->exec_size, 8);
1990             struct brw_reg reg = stride(
1991                byte_offset(retype(brw_vec8_grf(grf, 0), inst->src[i].type),
1992                            offset),
1993                width * inst->src[i].stride,
1994                width, inst->src[i].stride);
1995             reg.abs = inst->src[i].abs;
1996             reg.negate = inst->src[i].negate;
1997             inst->src[i] = reg;
1998          }
1999       }
2000    }
2001 
2002    /* Each attribute is 4 setup channels, each of which is half a reg. */
2003    this->first_non_payload_grf += prog_data->num_varying_inputs * 2;
2004 
2005    /* Unlike regular attributes, per-primitive attributes have all 4 channels
2006     * in the same slot, so each GRF can store two slots.
2007     */
2008    assert(prog_data->num_per_primitive_inputs % 2 == 0);
2009    this->first_non_payload_grf += prog_data->num_per_primitive_inputs / 2;
2010 }
2011 
2012 void
convert_attr_sources_to_hw_regs(fs_inst * inst)2013 fs_visitor::convert_attr_sources_to_hw_regs(fs_inst *inst)
2014 {
2015    for (int i = 0; i < inst->sources; i++) {
2016       if (inst->src[i].file == ATTR) {
2017          int grf = payload.num_regs +
2018                    prog_data->curb_read_length +
2019                    inst->src[i].nr +
2020                    inst->src[i].offset / REG_SIZE;
2021 
2022          /* As explained at brw_reg_from_fs_reg, From the Haswell PRM:
2023           *
2024           * VertStride must be used to cross GRF register boundaries. This
2025           * rule implies that elements within a 'Width' cannot cross GRF
2026           * boundaries.
2027           *
2028           * So, for registers that are large enough, we have to split the exec
2029           * size in two and trust the compression state to sort it out.
2030           */
2031          unsigned total_size = inst->exec_size *
2032                                inst->src[i].stride *
2033                                type_sz(inst->src[i].type);
2034 
2035          assert(total_size <= 2 * REG_SIZE);
2036          const unsigned exec_size =
2037             (total_size <= REG_SIZE) ? inst->exec_size : inst->exec_size / 2;
2038 
2039          unsigned width = inst->src[i].stride == 0 ? 1 : exec_size;
2040          struct brw_reg reg =
2041             stride(byte_offset(retype(brw_vec8_grf(grf, 0), inst->src[i].type),
2042                                inst->src[i].offset % REG_SIZE),
2043                    exec_size * inst->src[i].stride,
2044                    width, inst->src[i].stride);
2045          reg.abs = inst->src[i].abs;
2046          reg.negate = inst->src[i].negate;
2047 
2048          inst->src[i] = reg;
2049       }
2050    }
2051 }
2052 
2053 void
assign_vs_urb_setup()2054 fs_visitor::assign_vs_urb_setup()
2055 {
2056    struct brw_vs_prog_data *vs_prog_data = brw_vs_prog_data(prog_data);
2057 
2058    assert(stage == MESA_SHADER_VERTEX);
2059 
2060    /* Each attribute is 4 regs. */
2061    this->first_non_payload_grf += 4 * vs_prog_data->nr_attribute_slots;
2062 
2063    assert(vs_prog_data->base.urb_read_length <= 15);
2064 
2065    /* Rewrite all ATTR file references to the hw grf that they land in. */
2066    foreach_block_and_inst(block, fs_inst, inst, cfg) {
2067       convert_attr_sources_to_hw_regs(inst);
2068    }
2069 }
2070 
2071 void
assign_tcs_urb_setup()2072 fs_visitor::assign_tcs_urb_setup()
2073 {
2074    assert(stage == MESA_SHADER_TESS_CTRL);
2075 
2076    /* Rewrite all ATTR file references to HW_REGs. */
2077    foreach_block_and_inst(block, fs_inst, inst, cfg) {
2078       convert_attr_sources_to_hw_regs(inst);
2079    }
2080 }
2081 
2082 void
assign_tes_urb_setup()2083 fs_visitor::assign_tes_urb_setup()
2084 {
2085    assert(stage == MESA_SHADER_TESS_EVAL);
2086 
2087    struct brw_vue_prog_data *vue_prog_data = brw_vue_prog_data(prog_data);
2088 
2089    first_non_payload_grf += 8 * vue_prog_data->urb_read_length;
2090 
2091    /* Rewrite all ATTR file references to HW_REGs. */
2092    foreach_block_and_inst(block, fs_inst, inst, cfg) {
2093       convert_attr_sources_to_hw_regs(inst);
2094    }
2095 }
2096 
2097 void
assign_gs_urb_setup()2098 fs_visitor::assign_gs_urb_setup()
2099 {
2100    assert(stage == MESA_SHADER_GEOMETRY);
2101 
2102    struct brw_vue_prog_data *vue_prog_data = brw_vue_prog_data(prog_data);
2103 
2104    first_non_payload_grf +=
2105       8 * vue_prog_data->urb_read_length * nir->info.gs.vertices_in;
2106 
2107    foreach_block_and_inst(block, fs_inst, inst, cfg) {
2108       /* Rewrite all ATTR file references to GRFs. */
2109       convert_attr_sources_to_hw_regs(inst);
2110    }
2111 }
2112 
2113 
2114 /**
2115  * Split large virtual GRFs into separate components if we can.
2116  *
2117  * This pass aggressively splits VGRFs into as small a chunks as possible,
2118  * down to single registers if it can.  If no VGRFs can be split, we return
2119  * false so this pass can safely be used inside an optimization loop.  We
2120  * want to split, because virtual GRFs are what we register allocate and
2121  * spill (due to contiguousness requirements for some instructions), and
2122  * they're what we naturally generate in the codegen process, but most
2123  * virtual GRFs don't actually need to be contiguous sets of GRFs.  If we
2124  * split, we'll end up with reduced live intervals and better dead code
2125  * elimination and coalescing.
2126  */
2127 bool
split_virtual_grfs()2128 fs_visitor::split_virtual_grfs()
2129 {
2130    /* Compact the register file so we eliminate dead vgrfs.  This
2131     * only defines split points for live registers, so if we have
2132     * too large dead registers they will hit assertions later.
2133     */
2134    compact_virtual_grfs();
2135 
2136    int num_vars = this->alloc.count;
2137 
2138    /* Count the total number of registers */
2139    int reg_count = 0;
2140    int vgrf_to_reg[num_vars];
2141    for (int i = 0; i < num_vars; i++) {
2142       vgrf_to_reg[i] = reg_count;
2143       reg_count += alloc.sizes[i];
2144    }
2145 
2146    /* An array of "split points".  For each register slot, this indicates
2147     * if this slot can be separated from the previous slot.  Every time an
2148     * instruction uses multiple elements of a register (as a source or
2149     * destination), we mark the used slots as inseparable.  Then we go
2150     * through and split the registers into the smallest pieces we can.
2151     */
2152    bool *split_points = new bool[reg_count];
2153    memset(split_points, 0, reg_count * sizeof(*split_points));
2154 
2155    /* Mark all used registers as fully splittable */
2156    foreach_block_and_inst(block, fs_inst, inst, cfg) {
2157       if (inst->dst.file == VGRF) {
2158          int reg = vgrf_to_reg[inst->dst.nr];
2159          for (unsigned j = 1; j < this->alloc.sizes[inst->dst.nr]; j++)
2160             split_points[reg + j] = true;
2161       }
2162 
2163       for (int i = 0; i < inst->sources; i++) {
2164          if (inst->src[i].file == VGRF) {
2165             int reg = vgrf_to_reg[inst->src[i].nr];
2166             for (unsigned j = 1; j < this->alloc.sizes[inst->src[i].nr]; j++)
2167                split_points[reg + j] = true;
2168          }
2169       }
2170    }
2171 
2172    foreach_block_and_inst(block, fs_inst, inst, cfg) {
2173       /* We fix up undef instructions later */
2174       if (inst->opcode == SHADER_OPCODE_UNDEF) {
2175          /* UNDEF instructions are currently only used to undef entire
2176           * registers.  We need this invariant later when we split them.
2177           */
2178          assert(inst->dst.file == VGRF);
2179          assert(inst->dst.offset == 0);
2180          assert(inst->size_written == alloc.sizes[inst->dst.nr] * REG_SIZE);
2181          continue;
2182       }
2183 
2184       if (inst->dst.file == VGRF) {
2185          int reg = vgrf_to_reg[inst->dst.nr] + inst->dst.offset / REG_SIZE;
2186          for (unsigned j = 1; j < regs_written(inst); j++)
2187             split_points[reg + j] = false;
2188       }
2189       for (int i = 0; i < inst->sources; i++) {
2190          if (inst->src[i].file == VGRF) {
2191             int reg = vgrf_to_reg[inst->src[i].nr] + inst->src[i].offset / REG_SIZE;
2192             for (unsigned j = 1; j < regs_read(inst, i); j++)
2193                split_points[reg + j] = false;
2194          }
2195       }
2196    }
2197 
2198    /* Bitset of which registers have been split */
2199    bool *vgrf_has_split = new bool[num_vars];
2200    memset(vgrf_has_split, 0, num_vars * sizeof(*vgrf_has_split));
2201 
2202    int *new_virtual_grf = new int[reg_count];
2203    int *new_reg_offset = new int[reg_count];
2204 
2205    int reg = 0;
2206    bool has_splits = false;
2207    for (int i = 0; i < num_vars; i++) {
2208       /* The first one should always be 0 as a quick sanity check. */
2209       assert(split_points[reg] == false);
2210 
2211       /* j = 0 case */
2212       new_reg_offset[reg] = 0;
2213       reg++;
2214       int offset = 1;
2215 
2216       /* j > 0 case */
2217       for (unsigned j = 1; j < alloc.sizes[i]; j++) {
2218          /* If this is a split point, reset the offset to 0 and allocate a
2219           * new virtual GRF for the previous offset many registers
2220           */
2221          if (split_points[reg]) {
2222             has_splits = true;
2223             vgrf_has_split[i] = true;
2224             assert(offset <= MAX_VGRF_SIZE);
2225             int grf = alloc.allocate(offset);
2226             for (int k = reg - offset; k < reg; k++)
2227                new_virtual_grf[k] = grf;
2228             offset = 0;
2229          }
2230          new_reg_offset[reg] = offset;
2231          offset++;
2232          reg++;
2233       }
2234 
2235       /* The last one gets the original register number */
2236       assert(offset <= MAX_VGRF_SIZE);
2237       alloc.sizes[i] = offset;
2238       for (int k = reg - offset; k < reg; k++)
2239          new_virtual_grf[k] = i;
2240    }
2241    assert(reg == reg_count);
2242 
2243    bool progress;
2244    if (!has_splits) {
2245       progress = false;
2246       goto cleanup;
2247    }
2248 
2249    foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
2250       if (inst->opcode == SHADER_OPCODE_UNDEF) {
2251          assert(inst->dst.file == VGRF);
2252          if (vgrf_has_split[inst->dst.nr]) {
2253             const fs_builder ibld(this, block, inst);
2254             assert(inst->size_written % REG_SIZE == 0);
2255             unsigned reg_offset = 0;
2256             while (reg_offset < inst->size_written / REG_SIZE) {
2257                reg = vgrf_to_reg[inst->dst.nr] + reg_offset;
2258                ibld.UNDEF(fs_reg(VGRF, new_virtual_grf[reg], inst->dst.type));
2259                reg_offset += alloc.sizes[new_virtual_grf[reg]];
2260             }
2261             inst->remove(block);
2262          } else {
2263             reg = vgrf_to_reg[inst->dst.nr];
2264             assert(new_reg_offset[reg] == 0);
2265             assert(new_virtual_grf[reg] == (int)inst->dst.nr);
2266          }
2267          continue;
2268       }
2269 
2270       if (inst->dst.file == VGRF) {
2271          reg = vgrf_to_reg[inst->dst.nr] + inst->dst.offset / REG_SIZE;
2272          if (vgrf_has_split[inst->dst.nr]) {
2273             inst->dst.nr = new_virtual_grf[reg];
2274             inst->dst.offset = new_reg_offset[reg] * REG_SIZE +
2275                                inst->dst.offset % REG_SIZE;
2276             assert((unsigned)new_reg_offset[reg] <
2277                    alloc.sizes[new_virtual_grf[reg]]);
2278          } else {
2279             assert(new_reg_offset[reg] == inst->dst.offset / REG_SIZE);
2280             assert(new_virtual_grf[reg] == (int)inst->dst.nr);
2281          }
2282       }
2283       for (int i = 0; i < inst->sources; i++) {
2284 	 if (inst->src[i].file != VGRF)
2285             continue;
2286 
2287          reg = vgrf_to_reg[inst->src[i].nr] + inst->src[i].offset / REG_SIZE;
2288          if (vgrf_has_split[inst->src[i].nr]) {
2289             inst->src[i].nr = new_virtual_grf[reg];
2290             inst->src[i].offset = new_reg_offset[reg] * REG_SIZE +
2291                                   inst->src[i].offset % REG_SIZE;
2292             assert((unsigned)new_reg_offset[reg] <
2293                    alloc.sizes[new_virtual_grf[reg]]);
2294          } else {
2295             assert(new_reg_offset[reg] == inst->src[i].offset / REG_SIZE);
2296             assert(new_virtual_grf[reg] == (int)inst->src[i].nr);
2297          }
2298       }
2299    }
2300    invalidate_analysis(DEPENDENCY_INSTRUCTION_DETAIL | DEPENDENCY_VARIABLES);
2301 
2302    progress = true;
2303 
2304 cleanup:
2305    delete[] split_points;
2306    delete[] vgrf_has_split;
2307    delete[] new_virtual_grf;
2308    delete[] new_reg_offset;
2309 
2310    return progress;
2311 }
2312 
2313 /**
2314  * Remove unused virtual GRFs and compact the vgrf_* arrays.
2315  *
2316  * During code generation, we create tons of temporary variables, many of
2317  * which get immediately killed and are never used again.  Yet, in later
2318  * optimization and analysis passes, such as compute_live_intervals, we need
2319  * to loop over all the virtual GRFs.  Compacting them can save a lot of
2320  * overhead.
2321  */
2322 bool
compact_virtual_grfs()2323 fs_visitor::compact_virtual_grfs()
2324 {
2325    bool progress = false;
2326    int *remap_table = new int[this->alloc.count];
2327    memset(remap_table, -1, this->alloc.count * sizeof(int));
2328 
2329    /* Mark which virtual GRFs are used. */
2330    foreach_block_and_inst(block, const fs_inst, inst, cfg) {
2331       if (inst->dst.file == VGRF)
2332          remap_table[inst->dst.nr] = 0;
2333 
2334       for (int i = 0; i < inst->sources; i++) {
2335          if (inst->src[i].file == VGRF)
2336             remap_table[inst->src[i].nr] = 0;
2337       }
2338    }
2339 
2340    /* Compact the GRF arrays. */
2341    int new_index = 0;
2342    for (unsigned i = 0; i < this->alloc.count; i++) {
2343       if (remap_table[i] == -1) {
2344          /* We just found an unused register.  This means that we are
2345           * actually going to compact something.
2346           */
2347          progress = true;
2348       } else {
2349          remap_table[i] = new_index;
2350          alloc.sizes[new_index] = alloc.sizes[i];
2351          invalidate_analysis(DEPENDENCY_INSTRUCTION_DETAIL | DEPENDENCY_VARIABLES);
2352          ++new_index;
2353       }
2354    }
2355 
2356    this->alloc.count = new_index;
2357 
2358    /* Patch all the instructions to use the newly renumbered registers */
2359    foreach_block_and_inst(block, fs_inst, inst, cfg) {
2360       if (inst->dst.file == VGRF)
2361          inst->dst.nr = remap_table[inst->dst.nr];
2362 
2363       for (int i = 0; i < inst->sources; i++) {
2364          if (inst->src[i].file == VGRF)
2365             inst->src[i].nr = remap_table[inst->src[i].nr];
2366       }
2367    }
2368 
2369    /* Patch all the references to delta_xy, since they're used in register
2370     * allocation.  If they're unused, switch them to BAD_FILE so we don't
2371     * think some random VGRF is delta_xy.
2372     */
2373    for (unsigned i = 0; i < ARRAY_SIZE(delta_xy); i++) {
2374       if (delta_xy[i].file == VGRF) {
2375          if (remap_table[delta_xy[i].nr] != -1) {
2376             delta_xy[i].nr = remap_table[delta_xy[i].nr];
2377          } else {
2378             delta_xy[i].file = BAD_FILE;
2379          }
2380       }
2381    }
2382 
2383    delete[] remap_table;
2384 
2385    return progress;
2386 }
2387 
2388 static int
get_subgroup_id_param_index(const intel_device_info * devinfo,const brw_stage_prog_data * prog_data)2389 get_subgroup_id_param_index(const intel_device_info *devinfo,
2390                             const brw_stage_prog_data *prog_data)
2391 {
2392    if (prog_data->nr_params == 0)
2393       return -1;
2394 
2395    if (devinfo->verx10 >= 125)
2396       return -1;
2397 
2398    /* The local thread id is always the last parameter in the list */
2399    uint32_t last_param = prog_data->param[prog_data->nr_params - 1];
2400    if (last_param == BRW_PARAM_BUILTIN_SUBGROUP_ID)
2401       return prog_data->nr_params - 1;
2402 
2403    return -1;
2404 }
2405 
2406 /**
2407  * Assign UNIFORM file registers to either push constants or pull constants.
2408  *
2409  * We allow a fragment shader to have more than the specified minimum
2410  * maximum number of fragment shader uniform components (64).  If
2411  * there are too many of these, they'd fill up all of register space.
2412  * So, this will push some of them out to the pull constant buffer and
2413  * update the program to load them.
2414  */
2415 void
assign_constant_locations()2416 fs_visitor::assign_constant_locations()
2417 {
2418    /* Only the first compile gets to decide on locations. */
2419    if (push_constant_loc)
2420       return;
2421 
2422    push_constant_loc = ralloc_array(mem_ctx, int, uniforms);
2423    for (unsigned u = 0; u < uniforms; u++)
2424       push_constant_loc[u] = u;
2425 
2426    /* Now that we know how many regular uniforms we'll push, reduce the
2427     * UBO push ranges so we don't exceed the 3DSTATE_CONSTANT limits.
2428     */
2429    /* For gen4/5:
2430     * Only allow 16 registers (128 uniform components) as push constants.
2431     *
2432     * If changing this value, note the limitation about total_regs in
2433     * brw_curbe.c/crocus_state.c
2434     */
2435    const unsigned max_push_length = compiler->devinfo->ver < 6 ? 16 : 64;
2436    unsigned push_length = DIV_ROUND_UP(stage_prog_data->nr_params, 8);
2437    for (int i = 0; i < 4; i++) {
2438       struct brw_ubo_range *range = &prog_data->ubo_ranges[i];
2439 
2440       if (push_length + range->length > max_push_length)
2441          range->length = max_push_length - push_length;
2442 
2443       push_length += range->length;
2444    }
2445    assert(push_length <= max_push_length);
2446 }
2447 
2448 bool
get_pull_locs(const fs_reg & src,unsigned * out_surf_index,unsigned * out_pull_index)2449 fs_visitor::get_pull_locs(const fs_reg &src,
2450                           unsigned *out_surf_index,
2451                           unsigned *out_pull_index)
2452 {
2453    assert(src.file == UNIFORM);
2454 
2455    if (src.nr < UBO_START)
2456       return false;
2457 
2458    const struct brw_ubo_range *range =
2459       &prog_data->ubo_ranges[src.nr - UBO_START];
2460 
2461    /* If this access is in our (reduced) range, use the push data. */
2462    if (src.offset / 32 < range->length)
2463       return false;
2464 
2465    *out_surf_index = range->block;
2466    *out_pull_index = (32 * range->start + src.offset) / 4;
2467 
2468    prog_data->has_ubo_pull = true;
2469 
2470    return true;
2471 }
2472 
2473 /**
2474  * Replace UNIFORM register file access with either UNIFORM_PULL_CONSTANT_LOAD
2475  * or VARYING_PULL_CONSTANT_LOAD instructions which load values into VGRFs.
2476  */
2477 void
lower_constant_loads()2478 fs_visitor::lower_constant_loads()
2479 {
2480    unsigned index, pull_index;
2481 
2482    foreach_block_and_inst_safe (block, fs_inst, inst, cfg) {
2483       /* Set up the annotation tracking for new generated instructions. */
2484       const fs_builder ibld(this, block, inst);
2485 
2486       for (int i = 0; i < inst->sources; i++) {
2487 	 if (inst->src[i].file != UNIFORM)
2488 	    continue;
2489 
2490          /* We'll handle this case later */
2491          if (inst->opcode == SHADER_OPCODE_MOV_INDIRECT && i == 0)
2492             continue;
2493 
2494          if (!get_pull_locs(inst->src[i], &index, &pull_index))
2495 	    continue;
2496 
2497          assert(inst->src[i].stride == 0);
2498 
2499          const unsigned block_sz = 64; /* Fetch one cacheline at a time. */
2500          const fs_builder ubld = ibld.exec_all().group(block_sz / 4, 0);
2501          const fs_reg dst = ubld.vgrf(BRW_REGISTER_TYPE_UD);
2502          const unsigned base = pull_index * 4;
2503 
2504          ubld.emit(FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD,
2505                    dst, brw_imm_ud(index), brw_imm_ud(base & ~(block_sz - 1)));
2506 
2507          /* Rewrite the instruction to use the temporary VGRF. */
2508          inst->src[i].file = VGRF;
2509          inst->src[i].nr = dst.nr;
2510          inst->src[i].offset = (base & (block_sz - 1)) +
2511                                inst->src[i].offset % 4;
2512       }
2513 
2514       if (inst->opcode == SHADER_OPCODE_MOV_INDIRECT &&
2515           inst->src[0].file == UNIFORM) {
2516 
2517          if (!get_pull_locs(inst->src[0], &index, &pull_index))
2518             continue;
2519 
2520          VARYING_PULL_CONSTANT_LOAD(ibld, inst->dst,
2521                                     brw_imm_ud(index),
2522                                     inst->src[1],
2523                                     pull_index * 4, 4);
2524          inst->remove(block);
2525       }
2526    }
2527    invalidate_analysis(DEPENDENCY_INSTRUCTIONS);
2528 }
2529 
2530 bool
opt_algebraic()2531 fs_visitor::opt_algebraic()
2532 {
2533    bool progress = false;
2534 
2535    foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
2536       switch (inst->opcode) {
2537       case BRW_OPCODE_MOV:
2538          if (!devinfo->has_64bit_float &&
2539              inst->dst.type == BRW_REGISTER_TYPE_DF) {
2540             assert(inst->dst.type == inst->src[0].type);
2541             assert(!inst->saturate);
2542             assert(!inst->src[0].abs);
2543             assert(!inst->src[0].negate);
2544             const brw::fs_builder ibld(this, block, inst);
2545 
2546             ibld.MOV(subscript(inst->dst, BRW_REGISTER_TYPE_F, 1),
2547                      subscript(inst->src[0], BRW_REGISTER_TYPE_F, 1));
2548             ibld.MOV(subscript(inst->dst, BRW_REGISTER_TYPE_F, 0),
2549                      subscript(inst->src[0], BRW_REGISTER_TYPE_F, 0));
2550 
2551             inst->remove(block);
2552             progress = true;
2553          }
2554 
2555          if (!devinfo->has_64bit_int &&
2556              (inst->dst.type == BRW_REGISTER_TYPE_UQ ||
2557               inst->dst.type == BRW_REGISTER_TYPE_Q)) {
2558             assert(inst->dst.type == inst->src[0].type);
2559             assert(!inst->saturate);
2560             assert(!inst->src[0].abs);
2561             assert(!inst->src[0].negate);
2562             const brw::fs_builder ibld(this, block, inst);
2563 
2564             ibld.MOV(subscript(inst->dst, BRW_REGISTER_TYPE_UD, 1),
2565                      subscript(inst->src[0], BRW_REGISTER_TYPE_UD, 1));
2566             ibld.MOV(subscript(inst->dst, BRW_REGISTER_TYPE_UD, 0),
2567                      subscript(inst->src[0], BRW_REGISTER_TYPE_UD, 0));
2568 
2569             inst->remove(block);
2570             progress = true;
2571          }
2572 
2573          if ((inst->conditional_mod == BRW_CONDITIONAL_Z ||
2574               inst->conditional_mod == BRW_CONDITIONAL_NZ) &&
2575              inst->dst.is_null() &&
2576              (inst->src[0].abs || inst->src[0].negate)) {
2577             inst->src[0].abs = false;
2578             inst->src[0].negate = false;
2579             progress = true;
2580             break;
2581          }
2582 
2583          if (inst->src[0].file != IMM)
2584             break;
2585 
2586          if (inst->saturate) {
2587             /* Full mixed-type saturates don't happen.  However, we can end up
2588              * with things like:
2589              *
2590              *    mov.sat(8) g21<1>DF       -1F
2591              *
2592              * Other mixed-size-but-same-base-type cases may also be possible.
2593              */
2594             if (inst->dst.type != inst->src[0].type &&
2595                 inst->dst.type != BRW_REGISTER_TYPE_DF &&
2596                 inst->src[0].type != BRW_REGISTER_TYPE_F)
2597                assert(!"unimplemented: saturate mixed types");
2598 
2599             if (brw_saturate_immediate(inst->src[0].type,
2600                                        &inst->src[0].as_brw_reg())) {
2601                inst->saturate = false;
2602                progress = true;
2603             }
2604          }
2605          break;
2606 
2607       case BRW_OPCODE_MUL:
2608          if (inst->src[1].file != IMM)
2609             continue;
2610 
2611          if (brw_reg_type_is_floating_point(inst->src[1].type))
2612             break;
2613 
2614          /* a * 1.0 = a */
2615          if (inst->src[1].is_one()) {
2616             inst->opcode = BRW_OPCODE_MOV;
2617             inst->src[1] = reg_undef;
2618             progress = true;
2619             break;
2620          }
2621 
2622          /* a * -1.0 = -a */
2623          if (inst->src[1].is_negative_one()) {
2624             inst->opcode = BRW_OPCODE_MOV;
2625             inst->src[0].negate = !inst->src[0].negate;
2626             inst->src[1] = reg_undef;
2627             progress = true;
2628             break;
2629          }
2630 
2631          break;
2632       case BRW_OPCODE_ADD:
2633          if (inst->src[1].file != IMM)
2634             continue;
2635 
2636          if (brw_reg_type_is_integer(inst->src[1].type) &&
2637              inst->src[1].is_zero()) {
2638             inst->opcode = BRW_OPCODE_MOV;
2639             inst->src[1] = reg_undef;
2640             progress = true;
2641             break;
2642          }
2643 
2644          if (inst->src[0].file == IMM) {
2645             assert(inst->src[0].type == BRW_REGISTER_TYPE_F);
2646             inst->opcode = BRW_OPCODE_MOV;
2647             inst->src[0].f += inst->src[1].f;
2648             inst->src[1] = reg_undef;
2649             progress = true;
2650             break;
2651          }
2652          break;
2653       case BRW_OPCODE_OR:
2654          if (inst->src[0].equals(inst->src[1]) ||
2655              inst->src[1].is_zero()) {
2656             /* On Gfx8+, the OR instruction can have a source modifier that
2657              * performs logical not on the operand.  Cases of 'OR r0, ~r1, 0'
2658              * or 'OR r0, ~r1, ~r1' should become a NOT instead of a MOV.
2659              */
2660             if (inst->src[0].negate) {
2661                inst->opcode = BRW_OPCODE_NOT;
2662                inst->src[0].negate = false;
2663             } else {
2664                inst->opcode = BRW_OPCODE_MOV;
2665             }
2666             inst->src[1] = reg_undef;
2667             progress = true;
2668             break;
2669          }
2670          break;
2671       case BRW_OPCODE_CMP:
2672          if ((inst->conditional_mod == BRW_CONDITIONAL_Z ||
2673               inst->conditional_mod == BRW_CONDITIONAL_NZ) &&
2674              inst->src[1].is_zero() &&
2675              (inst->src[0].abs || inst->src[0].negate)) {
2676             inst->src[0].abs = false;
2677             inst->src[0].negate = false;
2678             progress = true;
2679             break;
2680          }
2681          break;
2682       case BRW_OPCODE_SEL:
2683          if (!devinfo->has_64bit_float &&
2684              !devinfo->has_64bit_int &&
2685              (inst->dst.type == BRW_REGISTER_TYPE_DF ||
2686               inst->dst.type == BRW_REGISTER_TYPE_UQ ||
2687               inst->dst.type == BRW_REGISTER_TYPE_Q)) {
2688             assert(inst->dst.type == inst->src[0].type);
2689             assert(!inst->saturate);
2690             assert(!inst->src[0].abs && !inst->src[0].negate);
2691             assert(!inst->src[1].abs && !inst->src[1].negate);
2692             const brw::fs_builder ibld(this, block, inst);
2693 
2694             set_predicate(inst->predicate,
2695                           ibld.SEL(subscript(inst->dst, BRW_REGISTER_TYPE_UD, 0),
2696                                    subscript(inst->src[0], BRW_REGISTER_TYPE_UD, 0),
2697                                    subscript(inst->src[1], BRW_REGISTER_TYPE_UD, 0)));
2698             set_predicate(inst->predicate,
2699                           ibld.SEL(subscript(inst->dst, BRW_REGISTER_TYPE_UD, 1),
2700                                    subscript(inst->src[0], BRW_REGISTER_TYPE_UD, 1),
2701                                    subscript(inst->src[1], BRW_REGISTER_TYPE_UD, 1)));
2702 
2703             inst->remove(block);
2704             progress = true;
2705          }
2706          if (inst->src[0].equals(inst->src[1])) {
2707             inst->opcode = BRW_OPCODE_MOV;
2708             inst->src[1] = reg_undef;
2709             inst->predicate = BRW_PREDICATE_NONE;
2710             inst->predicate_inverse = false;
2711             progress = true;
2712          } else if (inst->saturate && inst->src[1].file == IMM) {
2713             switch (inst->conditional_mod) {
2714             case BRW_CONDITIONAL_LE:
2715             case BRW_CONDITIONAL_L:
2716                switch (inst->src[1].type) {
2717                case BRW_REGISTER_TYPE_F:
2718                   if (inst->src[1].f >= 1.0f) {
2719                      inst->opcode = BRW_OPCODE_MOV;
2720                      inst->src[1] = reg_undef;
2721                      inst->conditional_mod = BRW_CONDITIONAL_NONE;
2722                      progress = true;
2723                   }
2724                   break;
2725                default:
2726                   break;
2727                }
2728                break;
2729             case BRW_CONDITIONAL_GE:
2730             case BRW_CONDITIONAL_G:
2731                switch (inst->src[1].type) {
2732                case BRW_REGISTER_TYPE_F:
2733                   if (inst->src[1].f <= 0.0f) {
2734                      inst->opcode = BRW_OPCODE_MOV;
2735                      inst->src[1] = reg_undef;
2736                      inst->conditional_mod = BRW_CONDITIONAL_NONE;
2737                      progress = true;
2738                   }
2739                   break;
2740                default:
2741                   break;
2742                }
2743             default:
2744                break;
2745             }
2746          }
2747          break;
2748       case BRW_OPCODE_MAD:
2749          if (inst->src[0].type != BRW_REGISTER_TYPE_F ||
2750              inst->src[1].type != BRW_REGISTER_TYPE_F ||
2751              inst->src[2].type != BRW_REGISTER_TYPE_F)
2752             break;
2753          if (inst->src[1].is_one()) {
2754             inst->opcode = BRW_OPCODE_ADD;
2755             inst->src[1] = inst->src[2];
2756             inst->src[2] = reg_undef;
2757             progress = true;
2758          } else if (inst->src[2].is_one()) {
2759             inst->opcode = BRW_OPCODE_ADD;
2760             inst->src[2] = reg_undef;
2761             progress = true;
2762          }
2763          break;
2764       case SHADER_OPCODE_BROADCAST:
2765          if (is_uniform(inst->src[0])) {
2766             inst->opcode = BRW_OPCODE_MOV;
2767             inst->sources = 1;
2768             inst->force_writemask_all = true;
2769             progress = true;
2770          } else if (inst->src[1].file == IMM) {
2771             inst->opcode = BRW_OPCODE_MOV;
2772             /* It's possible that the selected component will be too large and
2773              * overflow the register.  This can happen if someone does a
2774              * readInvocation() from GLSL or SPIR-V and provides an OOB
2775              * invocationIndex.  If this happens and we some how manage
2776              * to constant fold it in and get here, then component() may cause
2777              * us to start reading outside of the VGRF which will lead to an
2778              * assert later.  Instead, just let it wrap around if it goes over
2779              * exec_size.
2780              */
2781             const unsigned comp = inst->src[1].ud & (inst->exec_size - 1);
2782             inst->src[0] = component(inst->src[0], comp);
2783             inst->sources = 1;
2784             inst->force_writemask_all = true;
2785             progress = true;
2786          }
2787          break;
2788 
2789       case SHADER_OPCODE_SHUFFLE:
2790          if (is_uniform(inst->src[0])) {
2791             inst->opcode = BRW_OPCODE_MOV;
2792             inst->sources = 1;
2793             progress = true;
2794          } else if (inst->src[1].file == IMM) {
2795             inst->opcode = BRW_OPCODE_MOV;
2796             inst->src[0] = component(inst->src[0],
2797                                      inst->src[1].ud);
2798             inst->sources = 1;
2799             progress = true;
2800          }
2801          break;
2802 
2803       default:
2804 	 break;
2805       }
2806 
2807       /* Swap if src[0] is immediate. */
2808       if (progress && inst->is_commutative()) {
2809          if (inst->src[0].file == IMM) {
2810             fs_reg tmp = inst->src[1];
2811             inst->src[1] = inst->src[0];
2812             inst->src[0] = tmp;
2813          }
2814       }
2815    }
2816 
2817    if (progress)
2818       invalidate_analysis(DEPENDENCY_INSTRUCTION_DATA_FLOW |
2819                           DEPENDENCY_INSTRUCTION_DETAIL);
2820 
2821    return progress;
2822 }
2823 
2824 /**
2825  * Optimize sample messages that have constant zero values for the trailing
2826  * texture coordinates. We can just reduce the message length for these
2827  * instructions instead of reserving a register for it. Trailing parameters
2828  * that aren't sent default to zero anyway. This will cause the dead code
2829  * eliminator to remove the MOV instruction that would otherwise be emitted to
2830  * set up the zero value.
2831  */
2832 bool
opt_zero_samples()2833 fs_visitor::opt_zero_samples()
2834 {
2835    /* Gfx4 infers the texturing opcode based on the message length so we can't
2836     * change it.  Gfx12.5 has restrictions on the number of coordinate
2837     * parameters that have to be provided for some texture types
2838     * (Wa_14013363432).
2839     */
2840    if (devinfo->ver < 5 || devinfo->verx10 == 125)
2841       return false;
2842 
2843    bool progress = false;
2844 
2845    foreach_block_and_inst(block, fs_inst, inst, cfg) {
2846       if (!inst->is_tex())
2847          continue;
2848 
2849       fs_inst *load_payload = (fs_inst *) inst->prev;
2850 
2851       if (load_payload->is_head_sentinel() ||
2852           load_payload->opcode != SHADER_OPCODE_LOAD_PAYLOAD)
2853          continue;
2854 
2855       /* We don't want to remove the message header or the first parameter.
2856        * Removing the first parameter is not allowed, see the Haswell PRM
2857        * volume 7, page 149:
2858        *
2859        *     "Parameter 0 is required except for the sampleinfo message, which
2860        *      has no parameter 0"
2861        */
2862       while (inst->mlen > inst->header_size + inst->exec_size / 8 &&
2863              load_payload->src[(inst->mlen - inst->header_size) /
2864                                (inst->exec_size / 8) +
2865                                inst->header_size - 1].is_zero()) {
2866          inst->mlen -= inst->exec_size / 8;
2867          progress = true;
2868       }
2869    }
2870 
2871    if (progress)
2872       invalidate_analysis(DEPENDENCY_INSTRUCTION_DETAIL);
2873 
2874    return progress;
2875 }
2876 
2877 /**
2878  * Opportunistically split SEND message payloads.
2879  *
2880  * Gfx9+ supports "split" SEND messages, which take two payloads that are
2881  * implicitly concatenated.  If we find a SEND message with a single payload,
2882  * we can split that payload in two.  This results in smaller contiguous
2883  * register blocks for us to allocate.  But it can help beyond that, too.
2884  *
2885  * We try and split a LOAD_PAYLOAD between sources which change registers.
2886  * For example, a sampler message often contains a x/y/z coordinate that may
2887  * already be in a contiguous VGRF, combined with an LOD, shadow comparitor,
2888  * or array index, which comes from elsewhere.  In this case, the first few
2889  * sources will be different offsets of the same VGRF, then a later source
2890  * will be a different VGRF.  So we split there, possibly eliminating the
2891  * payload concatenation altogether.
2892  */
2893 bool
opt_split_sends()2894 fs_visitor::opt_split_sends()
2895 {
2896    if (devinfo->ver < 9)
2897       return false;
2898 
2899    bool progress = false;
2900 
2901    const fs_live_variables &live = live_analysis.require();
2902 
2903    int next_ip = 0;
2904 
2905    foreach_block_and_inst_safe(block, fs_inst, send, cfg) {
2906       int ip = next_ip;
2907       next_ip++;
2908 
2909       if (send->opcode != SHADER_OPCODE_SEND ||
2910           send->mlen == 1 || send->ex_mlen > 0)
2911          continue;
2912 
2913       /* Don't split payloads which are also read later. */
2914       assert(send->src[2].file == VGRF);
2915       if (live.vgrf_end[send->src[2].nr] > ip)
2916          continue;
2917 
2918       fs_inst *lp = (fs_inst *) send->prev;
2919 
2920       if (lp->is_head_sentinel() || lp->opcode != SHADER_OPCODE_LOAD_PAYLOAD)
2921          continue;
2922 
2923       if (lp->dst.file != send->src[2].file || lp->dst.nr != send->src[2].nr)
2924          continue;
2925 
2926       /* Split either after the header (if present), or when consecutive
2927        * sources switch from one VGRF to a different one.
2928        */
2929       unsigned i = lp->header_size;
2930       if (lp->header_size == 0) {
2931          for (i = 1; i < lp->sources; i++) {
2932             if (lp->src[i].file == BAD_FILE)
2933                continue;
2934 
2935             if (lp->src[0].file != lp->src[i].file ||
2936                 lp->src[0].nr != lp->src[i].nr)
2937                break;
2938          }
2939       }
2940 
2941       if (i != lp->sources) {
2942          const fs_builder ibld(this, block, lp);
2943          fs_inst *lp2 =
2944             ibld.LOAD_PAYLOAD(lp->dst, &lp->src[i], lp->sources - i, 0);
2945 
2946          lp->resize_sources(i);
2947          lp->size_written -= lp2->size_written;
2948 
2949          lp->dst = fs_reg(VGRF, alloc.allocate(lp->size_written / REG_SIZE), lp->dst.type);
2950          lp2->dst = fs_reg(VGRF, alloc.allocate(lp2->size_written / REG_SIZE), lp2->dst.type);
2951 
2952          send->resize_sources(4);
2953          send->src[2] = lp->dst;
2954          send->src[3] = lp2->dst;
2955          send->ex_mlen = lp2->size_written / REG_SIZE;
2956          send->mlen -= send->ex_mlen;
2957 
2958          progress = true;
2959       }
2960    }
2961 
2962    if (progress)
2963       invalidate_analysis(DEPENDENCY_INSTRUCTIONS | DEPENDENCY_VARIABLES);
2964 
2965    return progress;
2966 }
2967 
2968 
2969 bool
opt_register_renaming()2970 fs_visitor::opt_register_renaming()
2971 {
2972    bool progress = false;
2973    int depth = 0;
2974 
2975    unsigned remap[alloc.count];
2976    memset(remap, ~0u, sizeof(unsigned) * alloc.count);
2977 
2978    foreach_block_and_inst(block, fs_inst, inst, cfg) {
2979       if (inst->opcode == BRW_OPCODE_IF || inst->opcode == BRW_OPCODE_DO) {
2980          depth++;
2981       } else if (inst->opcode == BRW_OPCODE_ENDIF ||
2982                  inst->opcode == BRW_OPCODE_WHILE) {
2983          depth--;
2984       }
2985 
2986       /* Rewrite instruction sources. */
2987       for (int i = 0; i < inst->sources; i++) {
2988          if (inst->src[i].file == VGRF &&
2989              remap[inst->src[i].nr] != ~0u &&
2990              remap[inst->src[i].nr] != inst->src[i].nr) {
2991             inst->src[i].nr = remap[inst->src[i].nr];
2992             progress = true;
2993          }
2994       }
2995 
2996       const unsigned dst = inst->dst.nr;
2997 
2998       if (depth == 0 &&
2999           inst->dst.file == VGRF &&
3000           alloc.sizes[inst->dst.nr] * REG_SIZE == inst->size_written &&
3001           !inst->is_partial_write()) {
3002          if (remap[dst] == ~0u) {
3003             remap[dst] = dst;
3004          } else {
3005             remap[dst] = alloc.allocate(regs_written(inst));
3006             inst->dst.nr = remap[dst];
3007             progress = true;
3008          }
3009       } else if (inst->dst.file == VGRF &&
3010                  remap[dst] != ~0u &&
3011                  remap[dst] != dst) {
3012          inst->dst.nr = remap[dst];
3013          progress = true;
3014       }
3015    }
3016 
3017    if (progress) {
3018       invalidate_analysis(DEPENDENCY_INSTRUCTION_DETAIL |
3019                           DEPENDENCY_VARIABLES);
3020 
3021       for (unsigned i = 0; i < ARRAY_SIZE(delta_xy); i++) {
3022          if (delta_xy[i].file == VGRF && remap[delta_xy[i].nr] != ~0u) {
3023             delta_xy[i].nr = remap[delta_xy[i].nr];
3024          }
3025       }
3026    }
3027 
3028    return progress;
3029 }
3030 
3031 /**
3032  * Remove redundant or useless halts.
3033  *
3034  * For example, we can eliminate halts in the following sequence:
3035  *
3036  * halt        (redundant with the next halt)
3037  * halt        (useless; jumps to the next instruction)
3038  * halt-target
3039  */
3040 bool
opt_redundant_halt()3041 fs_visitor::opt_redundant_halt()
3042 {
3043    bool progress = false;
3044 
3045    unsigned halt_count = 0;
3046    fs_inst *halt_target = NULL;
3047    bblock_t *halt_target_block = NULL;
3048    foreach_block_and_inst(block, fs_inst, inst, cfg) {
3049       if (inst->opcode == BRW_OPCODE_HALT)
3050          halt_count++;
3051 
3052       if (inst->opcode == SHADER_OPCODE_HALT_TARGET) {
3053          halt_target = inst;
3054          halt_target_block = block;
3055          break;
3056       }
3057    }
3058 
3059    if (!halt_target) {
3060       assert(halt_count == 0);
3061       return false;
3062    }
3063 
3064    /* Delete any HALTs immediately before the halt target. */
3065    for (fs_inst *prev = (fs_inst *) halt_target->prev;
3066         !prev->is_head_sentinel() && prev->opcode == BRW_OPCODE_HALT;
3067         prev = (fs_inst *) halt_target->prev) {
3068       prev->remove(halt_target_block);
3069       halt_count--;
3070       progress = true;
3071    }
3072 
3073    if (halt_count == 0) {
3074       halt_target->remove(halt_target_block);
3075       progress = true;
3076    }
3077 
3078    if (progress)
3079       invalidate_analysis(DEPENDENCY_INSTRUCTIONS);
3080 
3081    return progress;
3082 }
3083 
3084 /**
3085  * Compute a bitmask with GRF granularity with a bit set for each GRF starting
3086  * from \p r.offset which overlaps the region starting at \p s.offset and
3087  * spanning \p ds bytes.
3088  */
3089 static inline unsigned
mask_relative_to(const fs_reg & r,const fs_reg & s,unsigned ds)3090 mask_relative_to(const fs_reg &r, const fs_reg &s, unsigned ds)
3091 {
3092    const int rel_offset = reg_offset(s) - reg_offset(r);
3093    const int shift = rel_offset / REG_SIZE;
3094    const unsigned n = DIV_ROUND_UP(rel_offset % REG_SIZE + ds, REG_SIZE);
3095    assert(reg_space(r) == reg_space(s) &&
3096           shift >= 0 && shift < int(8 * sizeof(unsigned)));
3097    return ((1 << n) - 1) << shift;
3098 }
3099 
3100 bool
compute_to_mrf()3101 fs_visitor::compute_to_mrf()
3102 {
3103    bool progress = false;
3104    int next_ip = 0;
3105 
3106    /* No MRFs on Gen >= 7. */
3107    if (devinfo->ver >= 7)
3108       return false;
3109 
3110    const fs_live_variables &live = live_analysis.require();
3111 
3112    foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
3113       int ip = next_ip;
3114       next_ip++;
3115 
3116       if (inst->opcode != BRW_OPCODE_MOV ||
3117 	  inst->is_partial_write() ||
3118 	  inst->dst.file != MRF || inst->src[0].file != VGRF ||
3119 	  inst->dst.type != inst->src[0].type ||
3120 	  inst->src[0].abs || inst->src[0].negate ||
3121           !inst->src[0].is_contiguous() ||
3122           inst->src[0].offset % REG_SIZE != 0)
3123 	 continue;
3124 
3125       /* Can't compute-to-MRF this GRF if someone else was going to
3126        * read it later.
3127        */
3128       if (live.vgrf_end[inst->src[0].nr] > ip)
3129 	 continue;
3130 
3131       /* Found a move of a GRF to a MRF.  Let's see if we can go rewrite the
3132        * things that computed the value of all GRFs of the source region.  The
3133        * regs_left bitset keeps track of the registers we haven't yet found a
3134        * generating instruction for.
3135        */
3136       unsigned regs_left = (1 << regs_read(inst, 0)) - 1;
3137 
3138       foreach_inst_in_block_reverse_starting_from(fs_inst, scan_inst, inst) {
3139          if (regions_overlap(scan_inst->dst, scan_inst->size_written,
3140                              inst->src[0], inst->size_read(0))) {
3141 	    /* Found the last thing to write our reg we want to turn
3142 	     * into a compute-to-MRF.
3143 	     */
3144 
3145 	    /* If this one instruction didn't populate all the
3146 	     * channels, bail.  We might be able to rewrite everything
3147 	     * that writes that reg, but it would require smarter
3148 	     * tracking.
3149 	     */
3150 	    if (scan_inst->is_partial_write())
3151 	       break;
3152 
3153             /* Handling things not fully contained in the source of the copy
3154              * would need us to understand coalescing out more than one MOV at
3155              * a time.
3156              */
3157             if (!region_contained_in(scan_inst->dst, scan_inst->size_written,
3158                                      inst->src[0], inst->size_read(0)))
3159                break;
3160 
3161 	    /* SEND instructions can't have MRF as a destination. */
3162 	    if (scan_inst->mlen)
3163 	       break;
3164 
3165 	    if (devinfo->ver == 6) {
3166 	       /* gfx6 math instructions must have the destination be
3167 		* GRF, so no compute-to-MRF for them.
3168 		*/
3169 	       if (scan_inst->is_math()) {
3170 		  break;
3171 	       }
3172 	    }
3173 
3174             /* Clear the bits for any registers this instruction overwrites. */
3175             regs_left &= ~mask_relative_to(
3176                inst->src[0], scan_inst->dst, scan_inst->size_written);
3177             if (!regs_left)
3178                break;
3179 	 }
3180 
3181 	 /* We don't handle control flow here.  Most computation of
3182 	  * values that end up in MRFs are shortly before the MRF
3183 	  * write anyway.
3184 	  */
3185 	 if (block->start() == scan_inst)
3186 	    break;
3187 
3188 	 /* You can't read from an MRF, so if someone else reads our
3189 	  * MRF's source GRF that we wanted to rewrite, that stops us.
3190 	  */
3191 	 bool interfered = false;
3192 	 for (int i = 0; i < scan_inst->sources; i++) {
3193             if (regions_overlap(scan_inst->src[i], scan_inst->size_read(i),
3194                                 inst->src[0], inst->size_read(0))) {
3195 	       interfered = true;
3196 	    }
3197 	 }
3198 	 if (interfered)
3199 	    break;
3200 
3201          if (regions_overlap(scan_inst->dst, scan_inst->size_written,
3202                              inst->dst, inst->size_written)) {
3203 	    /* If somebody else writes our MRF here, we can't
3204 	     * compute-to-MRF before that.
3205 	     */
3206             break;
3207          }
3208 
3209          if (scan_inst->mlen > 0 && scan_inst->base_mrf != -1 &&
3210              regions_overlap(fs_reg(MRF, scan_inst->base_mrf), scan_inst->mlen * REG_SIZE,
3211                              inst->dst, inst->size_written)) {
3212 	    /* Found a SEND instruction, which means that there are
3213 	     * live values in MRFs from base_mrf to base_mrf +
3214 	     * scan_inst->mlen - 1.  Don't go pushing our MRF write up
3215 	     * above it.
3216 	     */
3217             break;
3218          }
3219       }
3220 
3221       if (regs_left)
3222          continue;
3223 
3224       /* Found all generating instructions of our MRF's source value, so it
3225        * should be safe to rewrite them to point to the MRF directly.
3226        */
3227       regs_left = (1 << regs_read(inst, 0)) - 1;
3228 
3229       foreach_inst_in_block_reverse_starting_from(fs_inst, scan_inst, inst) {
3230          if (regions_overlap(scan_inst->dst, scan_inst->size_written,
3231                              inst->src[0], inst->size_read(0))) {
3232             /* Clear the bits for any registers this instruction overwrites. */
3233             regs_left &= ~mask_relative_to(
3234                inst->src[0], scan_inst->dst, scan_inst->size_written);
3235 
3236             const unsigned rel_offset = reg_offset(scan_inst->dst) -
3237                                         reg_offset(inst->src[0]);
3238 
3239             if (inst->dst.nr & BRW_MRF_COMPR4) {
3240                /* Apply the same address transformation done by the hardware
3241                 * for COMPR4 MRF writes.
3242                 */
3243                assert(rel_offset < 2 * REG_SIZE);
3244                scan_inst->dst.nr = inst->dst.nr + rel_offset / REG_SIZE * 4;
3245 
3246                /* Clear the COMPR4 bit if the generating instruction is not
3247                 * compressed.
3248                 */
3249                if (scan_inst->size_written < 2 * REG_SIZE)
3250                   scan_inst->dst.nr &= ~BRW_MRF_COMPR4;
3251 
3252             } else {
3253                /* Calculate the MRF number the result of this instruction is
3254                 * ultimately written to.
3255                 */
3256                scan_inst->dst.nr = inst->dst.nr + rel_offset / REG_SIZE;
3257             }
3258 
3259             scan_inst->dst.file = MRF;
3260             scan_inst->dst.offset = inst->dst.offset + rel_offset % REG_SIZE;
3261             scan_inst->saturate |= inst->saturate;
3262             if (!regs_left)
3263                break;
3264          }
3265       }
3266 
3267       assert(!regs_left);
3268       inst->remove(block);
3269       progress = true;
3270    }
3271 
3272    if (progress)
3273       invalidate_analysis(DEPENDENCY_INSTRUCTIONS);
3274 
3275    return progress;
3276 }
3277 
3278 /**
3279  * Eliminate FIND_LIVE_CHANNEL instructions occurring outside any control
3280  * flow.  We could probably do better here with some form of divergence
3281  * analysis.
3282  */
3283 bool
eliminate_find_live_channel()3284 fs_visitor::eliminate_find_live_channel()
3285 {
3286    bool progress = false;
3287    unsigned depth = 0;
3288 
3289    if (!brw_stage_has_packed_dispatch(devinfo, stage, stage_prog_data)) {
3290       /* The optimization below assumes that channel zero is live on thread
3291        * dispatch, which may not be the case if the fixed function dispatches
3292        * threads sparsely.
3293        */
3294       return false;
3295    }
3296 
3297    foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
3298       switch (inst->opcode) {
3299       case BRW_OPCODE_IF:
3300       case BRW_OPCODE_DO:
3301          depth++;
3302          break;
3303 
3304       case BRW_OPCODE_ENDIF:
3305       case BRW_OPCODE_WHILE:
3306          depth--;
3307          break;
3308 
3309       case BRW_OPCODE_HALT:
3310          /* This can potentially make control flow non-uniform until the end
3311           * of the program.
3312           */
3313          goto out;
3314 
3315       case SHADER_OPCODE_FIND_LIVE_CHANNEL:
3316          if (depth == 0) {
3317             inst->opcode = BRW_OPCODE_MOV;
3318             inst->src[0] = brw_imm_ud(0u);
3319             inst->sources = 1;
3320             inst->force_writemask_all = true;
3321             progress = true;
3322          }
3323          break;
3324 
3325       default:
3326          break;
3327       }
3328    }
3329 
3330 out:
3331    if (progress)
3332       invalidate_analysis(DEPENDENCY_INSTRUCTION_DETAIL);
3333 
3334    return progress;
3335 }
3336 
3337 /**
3338  * Once we've generated code, try to convert normal FS_OPCODE_FB_WRITE
3339  * instructions to FS_OPCODE_REP_FB_WRITE.
3340  */
3341 void
emit_repclear_shader()3342 fs_visitor::emit_repclear_shader()
3343 {
3344    brw_wm_prog_key *key = (brw_wm_prog_key*) this->key;
3345    int base_mrf = 0;
3346    int color_mrf = base_mrf + 2;
3347    fs_inst *mov;
3348 
3349    if (uniforms > 0) {
3350       mov = bld.exec_all().group(4, 0)
3351                .MOV(brw_message_reg(color_mrf),
3352                     fs_reg(UNIFORM, 0, BRW_REGISTER_TYPE_F));
3353    } else {
3354       struct brw_reg reg =
3355          brw_reg(BRW_GENERAL_REGISTER_FILE, 2, 3, 0, 0, BRW_REGISTER_TYPE_UD,
3356                  BRW_VERTICAL_STRIDE_8, BRW_WIDTH_2, BRW_HORIZONTAL_STRIDE_4,
3357                  BRW_SWIZZLE_XYZW, WRITEMASK_XYZW);
3358 
3359       mov = bld.exec_all().group(4, 0)
3360                .MOV(brw_uvec_mrf(4, color_mrf, 0), fs_reg(reg));
3361    }
3362 
3363    fs_inst *write = NULL;
3364    if (key->nr_color_regions == 1) {
3365       write = bld.emit(FS_OPCODE_REP_FB_WRITE);
3366       write->saturate = key->clamp_fragment_color;
3367       write->base_mrf = color_mrf;
3368       write->target = 0;
3369       write->header_size = 0;
3370       write->mlen = 1;
3371    } else {
3372       assume(key->nr_color_regions > 0);
3373 
3374       struct brw_reg header =
3375          retype(brw_message_reg(base_mrf), BRW_REGISTER_TYPE_UD);
3376       bld.exec_all().group(16, 0)
3377          .MOV(header, retype(brw_vec8_grf(0, 0), BRW_REGISTER_TYPE_UD));
3378 
3379       for (int i = 0; i < key->nr_color_regions; ++i) {
3380          if (i > 0) {
3381             bld.exec_all().group(1, 0)
3382                .MOV(component(header, 2), brw_imm_ud(i));
3383          }
3384 
3385          write = bld.emit(FS_OPCODE_REP_FB_WRITE);
3386          write->saturate = key->clamp_fragment_color;
3387          write->base_mrf = base_mrf;
3388          write->target = i;
3389          write->header_size = 2;
3390          write->mlen = 3;
3391       }
3392    }
3393    write->eot = true;
3394    write->last_rt = true;
3395 
3396    calculate_cfg();
3397 
3398    assign_constant_locations();
3399    assign_curb_setup();
3400 
3401    /* Now that we have the uniform assigned, go ahead and force it to a vec4. */
3402    if (uniforms > 0) {
3403       assert(mov->src[0].file == FIXED_GRF);
3404       mov->src[0] = brw_vec4_grf(mov->src[0].nr, 0);
3405    }
3406 
3407    lower_scoreboard();
3408 }
3409 
3410 /**
3411  * Walks through basic blocks, looking for repeated MRF writes and
3412  * removing the later ones.
3413  */
3414 bool
remove_duplicate_mrf_writes()3415 fs_visitor::remove_duplicate_mrf_writes()
3416 {
3417    fs_inst *last_mrf_move[BRW_MAX_MRF(devinfo->ver)];
3418    bool progress = false;
3419 
3420    /* Need to update the MRF tracking for compressed instructions. */
3421    if (dispatch_width >= 16)
3422       return false;
3423 
3424    memset(last_mrf_move, 0, sizeof(last_mrf_move));
3425 
3426    foreach_block_and_inst_safe (block, fs_inst, inst, cfg) {
3427       if (inst->is_control_flow()) {
3428 	 memset(last_mrf_move, 0, sizeof(last_mrf_move));
3429       }
3430 
3431       if (inst->opcode == BRW_OPCODE_MOV &&
3432 	  inst->dst.file == MRF) {
3433          fs_inst *prev_inst = last_mrf_move[inst->dst.nr];
3434 	 if (prev_inst && prev_inst->opcode == BRW_OPCODE_MOV &&
3435              inst->dst.equals(prev_inst->dst) &&
3436              inst->src[0].equals(prev_inst->src[0]) &&
3437              inst->saturate == prev_inst->saturate &&
3438              inst->predicate == prev_inst->predicate &&
3439              inst->conditional_mod == prev_inst->conditional_mod &&
3440              inst->exec_size == prev_inst->exec_size) {
3441 	    inst->remove(block);
3442 	    progress = true;
3443 	    continue;
3444 	 }
3445       }
3446 
3447       /* Clear out the last-write records for MRFs that were overwritten. */
3448       if (inst->dst.file == MRF) {
3449          last_mrf_move[inst->dst.nr] = NULL;
3450       }
3451 
3452       if (inst->mlen > 0 && inst->base_mrf != -1) {
3453 	 /* Found a SEND instruction, which will include two or fewer
3454 	  * implied MRF writes.  We could do better here.
3455 	  */
3456 	 for (unsigned i = 0; i < inst->implied_mrf_writes(); i++) {
3457 	    last_mrf_move[inst->base_mrf + i] = NULL;
3458 	 }
3459       }
3460 
3461       /* Clear out any MRF move records whose sources got overwritten. */
3462       for (unsigned i = 0; i < ARRAY_SIZE(last_mrf_move); i++) {
3463          if (last_mrf_move[i] &&
3464              regions_overlap(inst->dst, inst->size_written,
3465                              last_mrf_move[i]->src[0],
3466                              last_mrf_move[i]->size_read(0))) {
3467             last_mrf_move[i] = NULL;
3468          }
3469       }
3470 
3471       if (inst->opcode == BRW_OPCODE_MOV &&
3472 	  inst->dst.file == MRF &&
3473 	  inst->src[0].file != ARF &&
3474 	  !inst->is_partial_write()) {
3475          last_mrf_move[inst->dst.nr] = inst;
3476       }
3477    }
3478 
3479    if (progress)
3480       invalidate_analysis(DEPENDENCY_INSTRUCTIONS);
3481 
3482    return progress;
3483 }
3484 
3485 /**
3486  * Rounding modes for conversion instructions are included for each
3487  * conversion, but right now it is a state. So once it is set,
3488  * we don't need to call it again for subsequent calls.
3489  *
3490  * This is useful for vector/matrices conversions, as setting the
3491  * mode once is enough for the full vector/matrix
3492  */
3493 bool
remove_extra_rounding_modes()3494 fs_visitor::remove_extra_rounding_modes()
3495 {
3496    bool progress = false;
3497    unsigned execution_mode = this->nir->info.float_controls_execution_mode;
3498 
3499    brw_rnd_mode base_mode = BRW_RND_MODE_UNSPECIFIED;
3500    if ((FLOAT_CONTROLS_ROUNDING_MODE_RTE_FP16 |
3501         FLOAT_CONTROLS_ROUNDING_MODE_RTE_FP32 |
3502         FLOAT_CONTROLS_ROUNDING_MODE_RTE_FP64) &
3503        execution_mode)
3504       base_mode = BRW_RND_MODE_RTNE;
3505    if ((FLOAT_CONTROLS_ROUNDING_MODE_RTZ_FP16 |
3506         FLOAT_CONTROLS_ROUNDING_MODE_RTZ_FP32 |
3507         FLOAT_CONTROLS_ROUNDING_MODE_RTZ_FP64) &
3508        execution_mode)
3509       base_mode = BRW_RND_MODE_RTZ;
3510 
3511    foreach_block (block, cfg) {
3512       brw_rnd_mode prev_mode = base_mode;
3513 
3514       foreach_inst_in_block_safe (fs_inst, inst, block) {
3515          if (inst->opcode == SHADER_OPCODE_RND_MODE) {
3516             assert(inst->src[0].file == BRW_IMMEDIATE_VALUE);
3517             const brw_rnd_mode mode = (brw_rnd_mode) inst->src[0].d;
3518             if (mode == prev_mode) {
3519                inst->remove(block);
3520                progress = true;
3521             } else {
3522                prev_mode = mode;
3523             }
3524          }
3525       }
3526    }
3527 
3528    if (progress)
3529       invalidate_analysis(DEPENDENCY_INSTRUCTIONS);
3530 
3531    return progress;
3532 }
3533 
3534 static void
clear_deps_for_inst_src(fs_inst * inst,bool * deps,int first_grf,int grf_len)3535 clear_deps_for_inst_src(fs_inst *inst, bool *deps, int first_grf, int grf_len)
3536 {
3537    /* Clear the flag for registers that actually got read (as expected). */
3538    for (int i = 0; i < inst->sources; i++) {
3539       int grf;
3540       if (inst->src[i].file == VGRF || inst->src[i].file == FIXED_GRF) {
3541          grf = inst->src[i].nr;
3542       } else {
3543          continue;
3544       }
3545 
3546       if (grf >= first_grf &&
3547           grf < first_grf + grf_len) {
3548          deps[grf - first_grf] = false;
3549          if (inst->exec_size == 16)
3550             deps[grf - first_grf + 1] = false;
3551       }
3552    }
3553 }
3554 
3555 /**
3556  * Implements this workaround for the original 965:
3557  *
3558  *     "[DevBW, DevCL] Implementation Restrictions: As the hardware does not
3559  *      check for post destination dependencies on this instruction, software
3560  *      must ensure that there is no destination hazard for the case of ‘write
3561  *      followed by a posted write’ shown in the following example.
3562  *
3563  *      1. mov r3 0
3564  *      2. send r3.xy <rest of send instruction>
3565  *      3. mov r2 r3
3566  *
3567  *      Due to no post-destination dependency check on the ‘send’, the above
3568  *      code sequence could have two instructions (1 and 2) in flight at the
3569  *      same time that both consider ‘r3’ as the target of their final writes.
3570  */
3571 void
insert_gfx4_pre_send_dependency_workarounds(bblock_t * block,fs_inst * inst)3572 fs_visitor::insert_gfx4_pre_send_dependency_workarounds(bblock_t *block,
3573                                                         fs_inst *inst)
3574 {
3575    int write_len = regs_written(inst);
3576    int first_write_grf = inst->dst.nr;
3577    bool needs_dep[BRW_MAX_MRF(devinfo->ver)];
3578    assert(write_len < (int)sizeof(needs_dep) - 1);
3579 
3580    memset(needs_dep, false, sizeof(needs_dep));
3581    memset(needs_dep, true, write_len);
3582 
3583    clear_deps_for_inst_src(inst, needs_dep, first_write_grf, write_len);
3584 
3585    /* Walk backwards looking for writes to registers we're writing which
3586     * aren't read since being written.  If we hit the start of the program,
3587     * we assume that there are no outstanding dependencies on entry to the
3588     * program.
3589     */
3590    foreach_inst_in_block_reverse_starting_from(fs_inst, scan_inst, inst) {
3591       /* If we hit control flow, assume that there *are* outstanding
3592        * dependencies, and force their cleanup before our instruction.
3593        */
3594       if (block->start() == scan_inst && block->num != 0) {
3595          for (int i = 0; i < write_len; i++) {
3596             if (needs_dep[i])
3597                DEP_RESOLVE_MOV(fs_builder(this, block, inst),
3598                                first_write_grf + i);
3599          }
3600          return;
3601       }
3602 
3603       /* We insert our reads as late as possible on the assumption that any
3604        * instruction but a MOV that might have left us an outstanding
3605        * dependency has more latency than a MOV.
3606        */
3607       if (scan_inst->dst.file == VGRF) {
3608          for (unsigned i = 0; i < regs_written(scan_inst); i++) {
3609             int reg = scan_inst->dst.nr + i;
3610 
3611             if (reg >= first_write_grf &&
3612                 reg < first_write_grf + write_len &&
3613                 needs_dep[reg - first_write_grf]) {
3614                DEP_RESOLVE_MOV(fs_builder(this, block, inst), reg);
3615                needs_dep[reg - first_write_grf] = false;
3616                if (scan_inst->exec_size == 16)
3617                   needs_dep[reg - first_write_grf + 1] = false;
3618             }
3619          }
3620       }
3621 
3622       /* Clear the flag for registers that actually got read (as expected). */
3623       clear_deps_for_inst_src(scan_inst, needs_dep, first_write_grf, write_len);
3624 
3625       /* Continue the loop only if we haven't resolved all the dependencies */
3626       int i;
3627       for (i = 0; i < write_len; i++) {
3628          if (needs_dep[i])
3629             break;
3630       }
3631       if (i == write_len)
3632          return;
3633    }
3634 }
3635 
3636 /**
3637  * Implements this workaround for the original 965:
3638  *
3639  *     "[DevBW, DevCL] Errata: A destination register from a send can not be
3640  *      used as a destination register until after it has been sourced by an
3641  *      instruction with a different destination register.
3642  */
3643 void
insert_gfx4_post_send_dependency_workarounds(bblock_t * block,fs_inst * inst)3644 fs_visitor::insert_gfx4_post_send_dependency_workarounds(bblock_t *block, fs_inst *inst)
3645 {
3646    int write_len = regs_written(inst);
3647    unsigned first_write_grf = inst->dst.nr;
3648    bool needs_dep[BRW_MAX_MRF(devinfo->ver)];
3649    assert(write_len < (int)sizeof(needs_dep) - 1);
3650 
3651    memset(needs_dep, false, sizeof(needs_dep));
3652    memset(needs_dep, true, write_len);
3653    /* Walk forwards looking for writes to registers we're writing which aren't
3654     * read before being written.
3655     */
3656    foreach_inst_in_block_starting_from(fs_inst, scan_inst, inst) {
3657       /* If we hit control flow, force resolve all remaining dependencies. */
3658       if (block->end() == scan_inst && block->num != cfg->num_blocks - 1) {
3659          for (int i = 0; i < write_len; i++) {
3660             if (needs_dep[i])
3661                DEP_RESOLVE_MOV(fs_builder(this, block, scan_inst),
3662                                first_write_grf + i);
3663          }
3664          return;
3665       }
3666 
3667       /* Clear the flag for registers that actually got read (as expected). */
3668       clear_deps_for_inst_src(scan_inst, needs_dep, first_write_grf, write_len);
3669 
3670       /* We insert our reads as late as possible since they're reading the
3671        * result of a SEND, which has massive latency.
3672        */
3673       if (scan_inst->dst.file == VGRF &&
3674           scan_inst->dst.nr >= first_write_grf &&
3675           scan_inst->dst.nr < first_write_grf + write_len &&
3676           needs_dep[scan_inst->dst.nr - first_write_grf]) {
3677          DEP_RESOLVE_MOV(fs_builder(this, block, scan_inst),
3678                          scan_inst->dst.nr);
3679          needs_dep[scan_inst->dst.nr - first_write_grf] = false;
3680       }
3681 
3682       /* Continue the loop only if we haven't resolved all the dependencies */
3683       int i;
3684       for (i = 0; i < write_len; i++) {
3685          if (needs_dep[i])
3686             break;
3687       }
3688       if (i == write_len)
3689          return;
3690    }
3691 }
3692 
3693 void
insert_gfx4_send_dependency_workarounds()3694 fs_visitor::insert_gfx4_send_dependency_workarounds()
3695 {
3696    if (devinfo->ver != 4 || devinfo->platform == INTEL_PLATFORM_G4X)
3697       return;
3698 
3699    bool progress = false;
3700 
3701    foreach_block_and_inst(block, fs_inst, inst, cfg) {
3702       if (inst->mlen != 0 && inst->dst.file == VGRF) {
3703          insert_gfx4_pre_send_dependency_workarounds(block, inst);
3704          insert_gfx4_post_send_dependency_workarounds(block, inst);
3705          progress = true;
3706       }
3707    }
3708 
3709    if (progress)
3710       invalidate_analysis(DEPENDENCY_INSTRUCTIONS);
3711 }
3712 
3713 /**
3714  * Turns the generic expression-style uniform pull constant load instruction
3715  * into a hardware-specific series of instructions for loading a pull
3716  * constant.
3717  *
3718  * The expression style allows the CSE pass before this to optimize out
3719  * repeated loads from the same offset, and gives the pre-register-allocation
3720  * scheduling full flexibility, while the conversion to native instructions
3721  * allows the post-register-allocation scheduler the best information
3722  * possible.
3723  *
3724  * Note that execution masking for setting up pull constant loads is special:
3725  * the channels that need to be written are unrelated to the current execution
3726  * mask, since a later instruction will use one of the result channels as a
3727  * source operand for all 8 or 16 of its channels.
3728  */
3729 void
lower_uniform_pull_constant_loads()3730 fs_visitor::lower_uniform_pull_constant_loads()
3731 {
3732    foreach_block_and_inst (block, fs_inst, inst, cfg) {
3733       if (inst->opcode != FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD)
3734          continue;
3735 
3736       const fs_reg& surface = inst->src[0];
3737       const fs_reg& offset_B = inst->src[1];
3738       assert(offset_B.file == IMM);
3739 
3740       if (devinfo->has_lsc) {
3741          const fs_builder ubld =
3742             fs_builder(this, block, inst).group(8, 0).exec_all();
3743 
3744          const fs_reg payload = ubld.vgrf(BRW_REGISTER_TYPE_UD);
3745          ubld.MOV(payload, offset_B);
3746 
3747          inst->sfid = GFX12_SFID_UGM;
3748          inst->desc = lsc_msg_desc(devinfo, LSC_OP_LOAD,
3749                                    1 /* simd_size */,
3750                                    LSC_ADDR_SURFTYPE_BTI,
3751                                    LSC_ADDR_SIZE_A32,
3752                                    1 /* num_coordinates */,
3753                                    LSC_DATA_SIZE_D32,
3754                                    inst->size_written / 4,
3755                                    true /* transpose */,
3756                                    LSC_CACHE_LOAD_L1STATE_L3MOCS,
3757                                    true /* has_dest */);
3758 
3759          fs_reg ex_desc;
3760          if (surface.file == IMM) {
3761             ex_desc = brw_imm_ud(lsc_bti_ex_desc(devinfo, surface.ud));
3762          } else {
3763             /* We only need the first component for the payload so we can use
3764              * one of the other components for the extended descriptor
3765              */
3766             ex_desc = component(payload, 1);
3767             ubld.group(1, 0).SHL(ex_desc, surface, brw_imm_ud(24));
3768          }
3769 
3770          /* Update the original instruction. */
3771          inst->opcode = SHADER_OPCODE_SEND;
3772          inst->mlen = lsc_msg_desc_src0_len(devinfo, inst->desc);
3773          inst->ex_mlen = 0;
3774          inst->header_size = 0;
3775          inst->send_has_side_effects = false;
3776          inst->send_is_volatile = true;
3777          inst->exec_size = 1;
3778 
3779          /* Finally, the payload */
3780          inst->resize_sources(3);
3781          inst->src[0] = brw_imm_ud(0); /* desc */
3782          inst->src[1] = ex_desc;
3783          inst->src[2] = payload;
3784 
3785          invalidate_analysis(DEPENDENCY_INSTRUCTIONS | DEPENDENCY_VARIABLES);
3786       } else if (devinfo->ver >= 7) {
3787          const fs_builder ubld = fs_builder(this, block, inst).exec_all();
3788          const fs_reg payload = ubld.group(8, 0).vgrf(BRW_REGISTER_TYPE_UD);
3789 
3790          ubld.group(8, 0).MOV(payload,
3791                               retype(brw_vec8_grf(0, 0), BRW_REGISTER_TYPE_UD));
3792          ubld.group(1, 0).MOV(component(payload, 2),
3793                               brw_imm_ud(offset_B.ud / 16));
3794 
3795          inst->opcode = FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD_GFX7;
3796          inst->src[1] = payload;
3797          inst->header_size = 1;
3798          inst->mlen = 1;
3799 
3800          invalidate_analysis(DEPENDENCY_INSTRUCTIONS | DEPENDENCY_VARIABLES);
3801       } else {
3802          /* Before register allocation, we didn't tell the scheduler about the
3803           * MRF we use.  We know it's safe to use this MRF because nothing
3804           * else does except for register spill/unspill, which generates and
3805           * uses its MRF within a single IR instruction.
3806           */
3807          inst->base_mrf = FIRST_PULL_LOAD_MRF(devinfo->ver) + 1;
3808          inst->mlen = 1;
3809       }
3810    }
3811 }
3812 
3813 bool
lower_load_payload()3814 fs_visitor::lower_load_payload()
3815 {
3816    bool progress = false;
3817 
3818    foreach_block_and_inst_safe (block, fs_inst, inst, cfg) {
3819       if (inst->opcode != SHADER_OPCODE_LOAD_PAYLOAD)
3820          continue;
3821 
3822       assert(inst->dst.file == MRF || inst->dst.file == VGRF);
3823       assert(inst->saturate == false);
3824       fs_reg dst = inst->dst;
3825 
3826       /* Get rid of COMPR4.  We'll add it back in if we need it */
3827       if (dst.file == MRF)
3828          dst.nr = dst.nr & ~BRW_MRF_COMPR4;
3829 
3830       const fs_builder ibld(this, block, inst);
3831       const fs_builder ubld = ibld.exec_all();
3832 
3833       for (uint8_t i = 0; i < inst->header_size;) {
3834          /* Number of header GRFs to initialize at once with a single MOV
3835           * instruction.
3836           */
3837          const unsigned n =
3838             (i + 1 < inst->header_size && inst->src[i].stride == 1 &&
3839              inst->src[i + 1].equals(byte_offset(inst->src[i], REG_SIZE))) ?
3840             2 : 1;
3841 
3842          if (inst->src[i].file != BAD_FILE)
3843             ubld.group(8 * n, 0).MOV(retype(dst, BRW_REGISTER_TYPE_UD),
3844                                      retype(inst->src[i], BRW_REGISTER_TYPE_UD));
3845 
3846          dst = byte_offset(dst, n * REG_SIZE);
3847          i += n;
3848       }
3849 
3850       if (inst->dst.file == MRF && (inst->dst.nr & BRW_MRF_COMPR4) &&
3851           inst->exec_size > 8) {
3852          /* In this case, the payload portion of the LOAD_PAYLOAD isn't
3853           * a straightforward copy.  Instead, the result of the
3854           * LOAD_PAYLOAD is treated as interleaved and the first four
3855           * non-header sources are unpacked as:
3856           *
3857           * m + 0: r0
3858           * m + 1: g0
3859           * m + 2: b0
3860           * m + 3: a0
3861           * m + 4: r1
3862           * m + 5: g1
3863           * m + 6: b1
3864           * m + 7: a1
3865           *
3866           * This is used for gen <= 5 fb writes.
3867           */
3868          assert(inst->exec_size == 16);
3869          assert(inst->header_size + 4 <= inst->sources);
3870          for (uint8_t i = inst->header_size; i < inst->header_size + 4; i++) {
3871             if (inst->src[i].file != BAD_FILE) {
3872                if (devinfo->has_compr4) {
3873                   fs_reg compr4_dst = retype(dst, inst->src[i].type);
3874                   compr4_dst.nr |= BRW_MRF_COMPR4;
3875                   ibld.MOV(compr4_dst, inst->src[i]);
3876                } else {
3877                   /* Platform doesn't have COMPR4.  We have to fake it */
3878                   fs_reg mov_dst = retype(dst, inst->src[i].type);
3879                   ibld.quarter(0).MOV(mov_dst, quarter(inst->src[i], 0));
3880                   mov_dst.nr += 4;
3881                   ibld.quarter(1).MOV(mov_dst, quarter(inst->src[i], 1));
3882                }
3883             }
3884 
3885             dst.nr++;
3886          }
3887 
3888          /* The loop above only ever incremented us through the first set
3889           * of 4 registers.  However, thanks to the magic of COMPR4, we
3890           * actually wrote to the first 8 registers, so we need to take
3891           * that into account now.
3892           */
3893          dst.nr += 4;
3894 
3895          /* The COMPR4 code took care of the first 4 sources.  We'll let
3896           * the regular path handle any remaining sources.  Yes, we are
3897           * modifying the instruction but we're about to delete it so
3898           * this really doesn't hurt anything.
3899           */
3900          inst->header_size += 4;
3901       }
3902 
3903       for (uint8_t i = inst->header_size; i < inst->sources; i++) {
3904          dst.type = inst->src[i].type;
3905          if (inst->src[i].file != BAD_FILE) {
3906             ibld.MOV(dst, inst->src[i]);
3907          }
3908          dst = offset(dst, ibld, 1);
3909       }
3910 
3911       inst->remove(block);
3912       progress = true;
3913    }
3914 
3915    if (progress)
3916       invalidate_analysis(DEPENDENCY_INSTRUCTIONS);
3917 
3918    return progress;
3919 }
3920 
3921 void
lower_mul_dword_inst(fs_inst * inst,bblock_t * block)3922 fs_visitor::lower_mul_dword_inst(fs_inst *inst, bblock_t *block)
3923 {
3924    const fs_builder ibld(this, block, inst);
3925 
3926    const bool ud = (inst->src[1].type == BRW_REGISTER_TYPE_UD);
3927    if (inst->src[1].file == IMM &&
3928        (( ud && inst->src[1].ud <= UINT16_MAX) ||
3929         (!ud && inst->src[1].d <= INT16_MAX && inst->src[1].d >= INT16_MIN))) {
3930       /* The MUL instruction isn't commutative. On Gen <= 6, only the low
3931        * 16-bits of src0 are read, and on Gen >= 7 only the low 16-bits of
3932        * src1 are used.
3933        *
3934        * If multiplying by an immediate value that fits in 16-bits, do a
3935        * single MUL instruction with that value in the proper location.
3936        */
3937       if (devinfo->ver < 7) {
3938          fs_reg imm(VGRF, alloc.allocate(dispatch_width / 8), inst->dst.type);
3939          ibld.MOV(imm, inst->src[1]);
3940          ibld.MUL(inst->dst, imm, inst->src[0]);
3941       } else {
3942          ibld.MUL(inst->dst, inst->src[0],
3943                   ud ? brw_imm_uw(inst->src[1].ud)
3944                      : brw_imm_w(inst->src[1].d));
3945       }
3946    } else {
3947       /* Gen < 8 (and some Gfx8+ low-power parts like Cherryview) cannot
3948        * do 32-bit integer multiplication in one instruction, but instead
3949        * must do a sequence (which actually calculates a 64-bit result):
3950        *
3951        *    mul(8)  acc0<1>D   g3<8,8,1>D      g4<8,8,1>D
3952        *    mach(8) null       g3<8,8,1>D      g4<8,8,1>D
3953        *    mov(8)  g2<1>D     acc0<8,8,1>D
3954        *
3955        * But on Gen > 6, the ability to use second accumulator register
3956        * (acc1) for non-float data types was removed, preventing a simple
3957        * implementation in SIMD16. A 16-channel result can be calculated by
3958        * executing the three instructions twice in SIMD8, once with quarter
3959        * control of 1Q for the first eight channels and again with 2Q for
3960        * the second eight channels.
3961        *
3962        * Which accumulator register is implicitly accessed (by AccWrEnable
3963        * for instance) is determined by the quarter control. Unfortunately
3964        * Ivybridge (and presumably Baytrail) has a hardware bug in which an
3965        * implicit accumulator access by an instruction with 2Q will access
3966        * acc1 regardless of whether the data type is usable in acc1.
3967        *
3968        * Specifically, the 2Q mach(8) writes acc1 which does not exist for
3969        * integer data types.
3970        *
3971        * Since we only want the low 32-bits of the result, we can do two
3972        * 32-bit x 16-bit multiplies (like the mul and mach are doing), and
3973        * adjust the high result and add them (like the mach is doing):
3974        *
3975        *    mul(8)  g7<1>D     g3<8,8,1>D      g4.0<8,8,1>UW
3976        *    mul(8)  g8<1>D     g3<8,8,1>D      g4.1<8,8,1>UW
3977        *    shl(8)  g9<1>D     g8<8,8,1>D      16D
3978        *    add(8)  g2<1>D     g7<8,8,1>D      g8<8,8,1>D
3979        *
3980        * We avoid the shl instruction by realizing that we only want to add
3981        * the low 16-bits of the "high" result to the high 16-bits of the
3982        * "low" result and using proper regioning on the add:
3983        *
3984        *    mul(8)  g7<1>D     g3<8,8,1>D      g4.0<16,8,2>UW
3985        *    mul(8)  g8<1>D     g3<8,8,1>D      g4.1<16,8,2>UW
3986        *    add(8)  g7.1<2>UW  g7.1<16,8,2>UW  g8<16,8,2>UW
3987        *
3988        * Since it does not use the (single) accumulator register, we can
3989        * schedule multi-component multiplications much better.
3990        */
3991 
3992       bool needs_mov = false;
3993       fs_reg orig_dst = inst->dst;
3994 
3995       /* Get a new VGRF for the "low" 32x16-bit multiplication result if
3996        * reusing the original destination is impossible due to hardware
3997        * restrictions, source/destination overlap, or it being the null
3998        * register.
3999        */
4000       fs_reg low = inst->dst;
4001       if (orig_dst.is_null() || orig_dst.file == MRF ||
4002           regions_overlap(inst->dst, inst->size_written,
4003                           inst->src[0], inst->size_read(0)) ||
4004           regions_overlap(inst->dst, inst->size_written,
4005                           inst->src[1], inst->size_read(1)) ||
4006           inst->dst.stride >= 4) {
4007          needs_mov = true;
4008          low = fs_reg(VGRF, alloc.allocate(regs_written(inst)),
4009                       inst->dst.type);
4010       }
4011 
4012       /* Get a new VGRF but keep the same stride as inst->dst */
4013       fs_reg high(VGRF, alloc.allocate(regs_written(inst)), inst->dst.type);
4014       high.stride = inst->dst.stride;
4015       high.offset = inst->dst.offset % REG_SIZE;
4016 
4017       if (devinfo->ver >= 7) {
4018          /* From Wa_1604601757:
4019           *
4020           * "When multiplying a DW and any lower precision integer, source modifier
4021           *  is not supported."
4022           *
4023           * An unsupported negate modifier on src[1] would ordinarily be
4024           * lowered by the subsequent lower_regioning pass.  In this case that
4025           * pass would spawn another dword multiply.  Instead, lower the
4026           * modifier first.
4027           */
4028          const bool source_mods_unsupported = (devinfo->ver >= 12);
4029 
4030          if (inst->src[1].abs || (inst->src[1].negate &&
4031                                   source_mods_unsupported))
4032             lower_src_modifiers(this, block, inst, 1);
4033 
4034          if (inst->src[1].file == IMM) {
4035             ibld.MUL(low, inst->src[0],
4036                      brw_imm_uw(inst->src[1].ud & 0xffff));
4037             ibld.MUL(high, inst->src[0],
4038                      brw_imm_uw(inst->src[1].ud >> 16));
4039          } else {
4040             ibld.MUL(low, inst->src[0],
4041                      subscript(inst->src[1], BRW_REGISTER_TYPE_UW, 0));
4042             ibld.MUL(high, inst->src[0],
4043                      subscript(inst->src[1], BRW_REGISTER_TYPE_UW, 1));
4044          }
4045       } else {
4046          if (inst->src[0].abs)
4047             lower_src_modifiers(this, block, inst, 0);
4048 
4049          ibld.MUL(low, subscript(inst->src[0], BRW_REGISTER_TYPE_UW, 0),
4050                   inst->src[1]);
4051          ibld.MUL(high, subscript(inst->src[0], BRW_REGISTER_TYPE_UW, 1),
4052                   inst->src[1]);
4053       }
4054 
4055       ibld.ADD(subscript(low, BRW_REGISTER_TYPE_UW, 1),
4056                subscript(low, BRW_REGISTER_TYPE_UW, 1),
4057                subscript(high, BRW_REGISTER_TYPE_UW, 0));
4058 
4059       if (needs_mov || inst->conditional_mod)
4060          set_condmod(inst->conditional_mod, ibld.MOV(orig_dst, low));
4061    }
4062 }
4063 
4064 void
lower_mul_qword_inst(fs_inst * inst,bblock_t * block)4065 fs_visitor::lower_mul_qword_inst(fs_inst *inst, bblock_t *block)
4066 {
4067    const fs_builder ibld(this, block, inst);
4068 
4069    /* Considering two 64-bit integers ab and cd where each letter        ab
4070     * corresponds to 32 bits, we get a 128-bit result WXYZ. We         * cd
4071     * only need to provide the YZ part of the result.               -------
4072     *                                                                    BD
4073     *  Only BD needs to be 64 bits. For AD and BC we only care       +  AD
4074     *  about the lower 32 bits (since they are part of the upper     +  BC
4075     *  32 bits of our result). AC is not needed since it starts      + AC
4076     *  on the 65th bit of the result.                               -------
4077     *                                                                  WXYZ
4078     */
4079    unsigned int q_regs = regs_written(inst);
4080    unsigned int d_regs = (q_regs + 1) / 2;
4081 
4082    fs_reg bd(VGRF, alloc.allocate(q_regs), BRW_REGISTER_TYPE_UQ);
4083    fs_reg ad(VGRF, alloc.allocate(d_regs), BRW_REGISTER_TYPE_UD);
4084    fs_reg bc(VGRF, alloc.allocate(d_regs), BRW_REGISTER_TYPE_UD);
4085 
4086    /* Here we need the full 64 bit result for 32b * 32b. */
4087    if (devinfo->has_integer_dword_mul) {
4088       ibld.MUL(bd, subscript(inst->src[0], BRW_REGISTER_TYPE_UD, 0),
4089                subscript(inst->src[1], BRW_REGISTER_TYPE_UD, 0));
4090    } else {
4091       fs_reg bd_high(VGRF, alloc.allocate(d_regs), BRW_REGISTER_TYPE_UD);
4092       fs_reg bd_low(VGRF, alloc.allocate(d_regs), BRW_REGISTER_TYPE_UD);
4093       fs_reg acc = retype(brw_acc_reg(inst->exec_size), BRW_REGISTER_TYPE_UD);
4094 
4095       fs_inst *mul = ibld.MUL(acc,
4096                             subscript(inst->src[0], BRW_REGISTER_TYPE_UD, 0),
4097                             subscript(inst->src[1], BRW_REGISTER_TYPE_UW, 0));
4098       mul->writes_accumulator = true;
4099 
4100       ibld.MACH(bd_high, subscript(inst->src[0], BRW_REGISTER_TYPE_UD, 0),
4101                 subscript(inst->src[1], BRW_REGISTER_TYPE_UD, 0));
4102       ibld.MOV(bd_low, acc);
4103 
4104       ibld.MOV(subscript(bd, BRW_REGISTER_TYPE_UD, 0), bd_low);
4105       ibld.MOV(subscript(bd, BRW_REGISTER_TYPE_UD, 1), bd_high);
4106    }
4107 
4108    ibld.MUL(ad, subscript(inst->src[0], BRW_REGISTER_TYPE_UD, 1),
4109             subscript(inst->src[1], BRW_REGISTER_TYPE_UD, 0));
4110    ibld.MUL(bc, subscript(inst->src[0], BRW_REGISTER_TYPE_UD, 0),
4111             subscript(inst->src[1], BRW_REGISTER_TYPE_UD, 1));
4112 
4113    ibld.ADD(ad, ad, bc);
4114    ibld.ADD(subscript(bd, BRW_REGISTER_TYPE_UD, 1),
4115             subscript(bd, BRW_REGISTER_TYPE_UD, 1), ad);
4116 
4117    if (devinfo->has_64bit_int) {
4118       ibld.MOV(inst->dst, bd);
4119    } else {
4120       ibld.MOV(subscript(inst->dst, BRW_REGISTER_TYPE_UD, 0),
4121                subscript(bd, BRW_REGISTER_TYPE_UD, 0));
4122       ibld.MOV(subscript(inst->dst, BRW_REGISTER_TYPE_UD, 1),
4123                subscript(bd, BRW_REGISTER_TYPE_UD, 1));
4124    }
4125 }
4126 
4127 void
lower_mulh_inst(fs_inst * inst,bblock_t * block)4128 fs_visitor::lower_mulh_inst(fs_inst *inst, bblock_t *block)
4129 {
4130    const fs_builder ibld(this, block, inst);
4131 
4132    /* According to the BDW+ BSpec page for the "Multiply Accumulate
4133     * High" instruction:
4134     *
4135     *  "An added preliminary mov is required for source modification on
4136     *   src1:
4137     *      mov (8) r3.0<1>:d -r3<8;8,1>:d
4138     *      mul (8) acc0:d r2.0<8;8,1>:d r3.0<16;8,2>:uw
4139     *      mach (8) r5.0<1>:d r2.0<8;8,1>:d r3.0<8;8,1>:d"
4140     */
4141    if (devinfo->ver >= 8 && (inst->src[1].negate || inst->src[1].abs))
4142       lower_src_modifiers(this, block, inst, 1);
4143 
4144    /* Should have been lowered to 8-wide. */
4145    assert(inst->exec_size <= get_lowered_simd_width(compiler, inst));
4146    const fs_reg acc = retype(brw_acc_reg(inst->exec_size), inst->dst.type);
4147    fs_inst *mul = ibld.MUL(acc, inst->src[0], inst->src[1]);
4148    fs_inst *mach = ibld.MACH(inst->dst, inst->src[0], inst->src[1]);
4149 
4150    if (devinfo->ver >= 8) {
4151       /* Until Gfx8, integer multiplies read 32-bits from one source,
4152        * and 16-bits from the other, and relying on the MACH instruction
4153        * to generate the high bits of the result.
4154        *
4155        * On Gfx8, the multiply instruction does a full 32x32-bit
4156        * multiply, but in order to do a 64-bit multiply we can simulate
4157        * the previous behavior and then use a MACH instruction.
4158        */
4159       assert(mul->src[1].type == BRW_REGISTER_TYPE_D ||
4160              mul->src[1].type == BRW_REGISTER_TYPE_UD);
4161       mul->src[1].type = BRW_REGISTER_TYPE_UW;
4162       mul->src[1].stride *= 2;
4163 
4164       if (mul->src[1].file == IMM) {
4165          mul->src[1] = brw_imm_uw(mul->src[1].ud);
4166       }
4167    } else if (devinfo->verx10 == 70 &&
4168               inst->group > 0) {
4169       /* Among other things the quarter control bits influence which
4170        * accumulator register is used by the hardware for instructions
4171        * that access the accumulator implicitly (e.g. MACH).  A
4172        * second-half instruction would normally map to acc1, which
4173        * doesn't exist on Gfx7 and up (the hardware does emulate it for
4174        * floating-point instructions *only* by taking advantage of the
4175        * extra precision of acc0 not normally used for floating point
4176        * arithmetic).
4177        *
4178        * HSW and up are careful enough not to try to access an
4179        * accumulator register that doesn't exist, but on earlier Gfx7
4180        * hardware we need to make sure that the quarter control bits are
4181        * zero to avoid non-deterministic behaviour and emit an extra MOV
4182        * to get the result masked correctly according to the current
4183        * channel enables.
4184        */
4185       mach->group = 0;
4186       mach->force_writemask_all = true;
4187       mach->dst = ibld.vgrf(inst->dst.type);
4188       ibld.MOV(inst->dst, mach->dst);
4189    }
4190 }
4191 
4192 bool
lower_integer_multiplication()4193 fs_visitor::lower_integer_multiplication()
4194 {
4195    bool progress = false;
4196 
4197    foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
4198       if (inst->opcode == BRW_OPCODE_MUL) {
4199          /* If the instruction is already in a form that does not need lowering,
4200           * return early.
4201           */
4202          if (devinfo->ver >= 7) {
4203             if (type_sz(inst->src[1].type) < 4 && type_sz(inst->src[0].type) <= 4)
4204                continue;
4205          } else {
4206             if (type_sz(inst->src[0].type) < 4 && type_sz(inst->src[1].type) <= 4)
4207                continue;
4208          }
4209 
4210          if ((inst->dst.type == BRW_REGISTER_TYPE_Q ||
4211               inst->dst.type == BRW_REGISTER_TYPE_UQ) &&
4212              (inst->src[0].type == BRW_REGISTER_TYPE_Q ||
4213               inst->src[0].type == BRW_REGISTER_TYPE_UQ) &&
4214              (inst->src[1].type == BRW_REGISTER_TYPE_Q ||
4215               inst->src[1].type == BRW_REGISTER_TYPE_UQ)) {
4216             lower_mul_qword_inst(inst, block);
4217             inst->remove(block);
4218             progress = true;
4219          } else if (!inst->dst.is_accumulator() &&
4220                     (inst->dst.type == BRW_REGISTER_TYPE_D ||
4221                      inst->dst.type == BRW_REGISTER_TYPE_UD) &&
4222                     (!devinfo->has_integer_dword_mul ||
4223                      devinfo->verx10 >= 125)) {
4224             lower_mul_dword_inst(inst, block);
4225             inst->remove(block);
4226             progress = true;
4227          }
4228       } else if (inst->opcode == SHADER_OPCODE_MULH) {
4229          lower_mulh_inst(inst, block);
4230          inst->remove(block);
4231          progress = true;
4232       }
4233 
4234    }
4235 
4236    if (progress)
4237       invalidate_analysis(DEPENDENCY_INSTRUCTIONS | DEPENDENCY_VARIABLES);
4238 
4239    return progress;
4240 }
4241 
4242 bool
lower_minmax()4243 fs_visitor::lower_minmax()
4244 {
4245    assert(devinfo->ver < 6);
4246 
4247    bool progress = false;
4248 
4249    foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
4250       const fs_builder ibld(this, block, inst);
4251 
4252       if (inst->opcode == BRW_OPCODE_SEL &&
4253           inst->predicate == BRW_PREDICATE_NONE) {
4254          /* If src1 is an immediate value that is not NaN, then it can't be
4255           * NaN.  In that case, emit CMP because it is much better for cmod
4256           * propagation.  Likewise if src1 is not float.  Gfx4 and Gfx5 don't
4257           * support HF or DF, so it is not necessary to check for those.
4258           */
4259          if (inst->src[1].type != BRW_REGISTER_TYPE_F ||
4260              (inst->src[1].file == IMM && !isnan(inst->src[1].f))) {
4261             ibld.CMP(ibld.null_reg_d(), inst->src[0], inst->src[1],
4262                      inst->conditional_mod);
4263          } else {
4264             ibld.CMPN(ibld.null_reg_d(), inst->src[0], inst->src[1],
4265                       inst->conditional_mod);
4266          }
4267          inst->predicate = BRW_PREDICATE_NORMAL;
4268          inst->conditional_mod = BRW_CONDITIONAL_NONE;
4269 
4270          progress = true;
4271       }
4272    }
4273 
4274    if (progress)
4275       invalidate_analysis(DEPENDENCY_INSTRUCTIONS);
4276 
4277    return progress;
4278 }
4279 
4280 bool
lower_sub_sat()4281 fs_visitor::lower_sub_sat()
4282 {
4283    bool progress = false;
4284 
4285    foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
4286       const fs_builder ibld(this, block, inst);
4287 
4288       if (inst->opcode == SHADER_OPCODE_USUB_SAT ||
4289           inst->opcode == SHADER_OPCODE_ISUB_SAT) {
4290          /* The fundamental problem is the hardware performs source negation
4291           * at the bit width of the source.  If the source is 0x80000000D, the
4292           * negation is 0x80000000D.  As a result, subtractSaturate(0,
4293           * 0x80000000) will produce 0x80000000 instead of 0x7fffffff.  There
4294           * are at least three ways to resolve this:
4295           *
4296           * 1. Use the accumulator for the negated source.  The accumulator is
4297           *    33 bits, so our source 0x80000000 is sign-extended to
4298           *    0x1800000000.  The negation of which is 0x080000000.  This
4299           *    doesn't help for 64-bit integers (which are already bigger than
4300           *    33 bits).  There are also only 8 accumulators, so SIMD16 or
4301           *    SIMD32 instructions would have to be split into multiple SIMD8
4302           *    instructions.
4303           *
4304           * 2. Use slightly different math.  For any n-bit value x, we know (x
4305           *    >> 1) != -(x >> 1).  We can use this fact to only do
4306           *    subtractions involving (x >> 1).  subtractSaturate(a, b) ==
4307           *    subtractSaturate(subtractSaturate(a, (b >> 1)), b - (b >> 1)).
4308           *
4309           * 3. For unsigned sources, it is sufficient to replace the
4310           *    subtractSaturate with (a > b) ? a - b : 0.
4311           *
4312           * It may also be possible to use the SUBB instruction.  This
4313           * implicitly writes the accumulator, so it could only be used in the
4314           * same situations as #1 above.  It is further limited by only
4315           * allowing UD sources.
4316           */
4317          if (inst->exec_size == 8 && inst->src[0].type != BRW_REGISTER_TYPE_Q &&
4318              inst->src[0].type != BRW_REGISTER_TYPE_UQ) {
4319             fs_reg acc(ARF, BRW_ARF_ACCUMULATOR, inst->src[1].type);
4320 
4321             ibld.MOV(acc, inst->src[1]);
4322             fs_inst *add = ibld.ADD(inst->dst, acc, inst->src[0]);
4323             add->saturate = true;
4324             add->src[0].negate = true;
4325          } else if (inst->opcode == SHADER_OPCODE_ISUB_SAT) {
4326             /* tmp = src1 >> 1;
4327              * dst = add.sat(add.sat(src0, -tmp), -(src1 - tmp));
4328              */
4329             fs_reg tmp1 = ibld.vgrf(inst->src[0].type);
4330             fs_reg tmp2 = ibld.vgrf(inst->src[0].type);
4331             fs_reg tmp3 = ibld.vgrf(inst->src[0].type);
4332             fs_inst *add;
4333 
4334             ibld.SHR(tmp1, inst->src[1], brw_imm_d(1));
4335 
4336             add = ibld.ADD(tmp2, inst->src[1], tmp1);
4337             add->src[1].negate = true;
4338 
4339             add = ibld.ADD(tmp3, inst->src[0], tmp1);
4340             add->src[1].negate = true;
4341             add->saturate = true;
4342 
4343             add = ibld.ADD(inst->dst, tmp3, tmp2);
4344             add->src[1].negate = true;
4345             add->saturate = true;
4346          } else {
4347             /* a > b ? a - b : 0 */
4348             ibld.CMP(ibld.null_reg_d(), inst->src[0], inst->src[1],
4349                      BRW_CONDITIONAL_G);
4350 
4351             fs_inst *add = ibld.ADD(inst->dst, inst->src[0], inst->src[1]);
4352             add->src[1].negate = !add->src[1].negate;
4353 
4354             ibld.SEL(inst->dst, inst->dst, brw_imm_ud(0))
4355                ->predicate = BRW_PREDICATE_NORMAL;
4356          }
4357 
4358          inst->remove(block);
4359          progress = true;
4360       }
4361    }
4362 
4363    if (progress)
4364       invalidate_analysis(DEPENDENCY_INSTRUCTIONS | DEPENDENCY_VARIABLES);
4365 
4366    return progress;
4367 }
4368 
4369 /**
4370  * Get the mask of SIMD channels enabled during dispatch and not yet disabled
4371  * by discard.  Due to the layout of the sample mask in the fragment shader
4372  * thread payload, \p bld is required to have a dispatch_width() not greater
4373  * than 16 for fragment shaders.
4374  */
4375 fs_reg
brw_sample_mask_reg(const fs_builder & bld)4376 brw_sample_mask_reg(const fs_builder &bld)
4377 {
4378    const fs_visitor *v = static_cast<const fs_visitor *>(bld.shader);
4379 
4380    if (v->stage != MESA_SHADER_FRAGMENT) {
4381       return brw_imm_ud(0xffffffff);
4382    } else if (brw_wm_prog_data(v->stage_prog_data)->uses_kill) {
4383       assert(bld.dispatch_width() <= 16);
4384       return brw_flag_subreg(sample_mask_flag_subreg(v) + bld.group() / 16);
4385    } else {
4386       assert(v->devinfo->ver >= 6 && bld.dispatch_width() <= 16);
4387       return retype(brw_vec1_grf((bld.group() >= 16 ? 2 : 1), 7),
4388                     BRW_REGISTER_TYPE_UW);
4389    }
4390 }
4391 
4392 uint32_t
brw_fb_write_msg_control(const fs_inst * inst,const struct brw_wm_prog_data * prog_data)4393 brw_fb_write_msg_control(const fs_inst *inst,
4394                          const struct brw_wm_prog_data *prog_data)
4395 {
4396    uint32_t mctl;
4397 
4398    if (inst->opcode == FS_OPCODE_REP_FB_WRITE) {
4399       assert(inst->group == 0 && inst->exec_size == 16);
4400       mctl = BRW_DATAPORT_RENDER_TARGET_WRITE_SIMD16_SINGLE_SOURCE_REPLICATED;
4401    } else if (prog_data->dual_src_blend) {
4402       assert(inst->exec_size == 8);
4403 
4404       if (inst->group % 16 == 0)
4405          mctl = BRW_DATAPORT_RENDER_TARGET_WRITE_SIMD8_DUAL_SOURCE_SUBSPAN01;
4406       else if (inst->group % 16 == 8)
4407          mctl = BRW_DATAPORT_RENDER_TARGET_WRITE_SIMD8_DUAL_SOURCE_SUBSPAN23;
4408       else
4409          unreachable("Invalid dual-source FB write instruction group");
4410    } else {
4411       assert(inst->group == 0 || (inst->group == 16 && inst->exec_size == 16));
4412 
4413       if (inst->exec_size == 16)
4414          mctl = BRW_DATAPORT_RENDER_TARGET_WRITE_SIMD16_SINGLE_SOURCE;
4415       else if (inst->exec_size == 8)
4416          mctl = BRW_DATAPORT_RENDER_TARGET_WRITE_SIMD8_SINGLE_SOURCE_SUBSPAN01;
4417       else
4418          unreachable("Invalid FB write execution size");
4419    }
4420 
4421    return mctl;
4422 }
4423 
4424  /**
4425  * Predicate the specified instruction on the sample mask.
4426  */
4427 void
brw_emit_predicate_on_sample_mask(const fs_builder & bld,fs_inst * inst)4428 brw_emit_predicate_on_sample_mask(const fs_builder &bld, fs_inst *inst)
4429 {
4430    assert(bld.shader->stage == MESA_SHADER_FRAGMENT &&
4431           bld.group() == inst->group &&
4432           bld.dispatch_width() == inst->exec_size);
4433 
4434    const fs_visitor *v = static_cast<const fs_visitor *>(bld.shader);
4435    const fs_reg sample_mask = brw_sample_mask_reg(bld);
4436    const unsigned subreg = sample_mask_flag_subreg(v);
4437 
4438    if (brw_wm_prog_data(v->stage_prog_data)->uses_kill) {
4439       assert(sample_mask.file == ARF &&
4440              sample_mask.nr == brw_flag_subreg(subreg).nr &&
4441              sample_mask.subnr == brw_flag_subreg(
4442                 subreg + inst->group / 16).subnr);
4443    } else {
4444       bld.group(1, 0).exec_all()
4445          .MOV(brw_flag_subreg(subreg + inst->group / 16), sample_mask);
4446    }
4447 
4448    if (inst->predicate) {
4449       assert(inst->predicate == BRW_PREDICATE_NORMAL);
4450       assert(!inst->predicate_inverse);
4451       assert(inst->flag_subreg == 0);
4452       /* Combine the sample mask with the existing predicate by using a
4453        * vertical predication mode.
4454        */
4455       inst->predicate = BRW_PREDICATE_ALIGN1_ALLV;
4456    } else {
4457       inst->flag_subreg = subreg;
4458       inst->predicate = BRW_PREDICATE_NORMAL;
4459       inst->predicate_inverse = false;
4460    }
4461 }
4462 
4463 void
emit_is_helper_invocation(fs_reg result)4464 fs_visitor::emit_is_helper_invocation(fs_reg result)
4465 {
4466    /* Unlike the regular gl_HelperInvocation, that is defined at dispatch,
4467     * the helperInvocationEXT() (aka SpvOpIsHelperInvocationEXT) takes into
4468     * consideration demoted invocations.
4469     */
4470    result.type = BRW_REGISTER_TYPE_UD;
4471 
4472    bld.MOV(result, brw_imm_ud(0));
4473 
4474    /* See brw_sample_mask_reg() for why we split SIMD32 into SIMD16 here. */
4475    unsigned width = bld.dispatch_width();
4476    for (unsigned i = 0; i < DIV_ROUND_UP(width, 16); i++) {
4477       const fs_builder b = bld.group(MIN2(width, 16), i);
4478 
4479       fs_inst *mov = b.MOV(offset(result, b, i), brw_imm_ud(~0));
4480 
4481       /* The at() ensures that any code emitted to get the predicate happens
4482        * before the mov right above.  This is not an issue elsewhere because
4483        * lowering code already set up the builder this way.
4484        */
4485       brw_emit_predicate_on_sample_mask(b.at(NULL, mov), mov);
4486       mov->predicate_inverse = true;
4487    }
4488 }
4489 
4490 static bool
is_mixed_float_with_fp32_dst(const fs_inst * inst)4491 is_mixed_float_with_fp32_dst(const fs_inst *inst)
4492 {
4493    /* This opcode sometimes uses :W type on the source even if the operand is
4494     * a :HF, because in gfx7 there is no support for :HF, and thus it uses :W.
4495     */
4496    if (inst->opcode == BRW_OPCODE_F16TO32)
4497       return true;
4498 
4499    if (inst->dst.type != BRW_REGISTER_TYPE_F)
4500       return false;
4501 
4502    for (int i = 0; i < inst->sources; i++) {
4503       if (inst->src[i].type == BRW_REGISTER_TYPE_HF)
4504          return true;
4505    }
4506 
4507    return false;
4508 }
4509 
4510 static bool
is_mixed_float_with_packed_fp16_dst(const fs_inst * inst)4511 is_mixed_float_with_packed_fp16_dst(const fs_inst *inst)
4512 {
4513    /* This opcode sometimes uses :W type on the destination even if the
4514     * destination is a :HF, because in gfx7 there is no support for :HF, and
4515     * thus it uses :W.
4516     */
4517    if (inst->opcode == BRW_OPCODE_F32TO16 &&
4518        inst->dst.stride == 1)
4519       return true;
4520 
4521    if (inst->dst.type != BRW_REGISTER_TYPE_HF ||
4522        inst->dst.stride != 1)
4523       return false;
4524 
4525    for (int i = 0; i < inst->sources; i++) {
4526       if (inst->src[i].type == BRW_REGISTER_TYPE_F)
4527          return true;
4528    }
4529 
4530    return false;
4531 }
4532 
4533 /**
4534  * Get the closest allowed SIMD width for instruction \p inst accounting for
4535  * some common regioning and execution control restrictions that apply to FPU
4536  * instructions.  These restrictions don't necessarily have any relevance to
4537  * instructions not executed by the FPU pipeline like extended math, control
4538  * flow or send message instructions.
4539  *
4540  * For virtual opcodes it's really up to the instruction -- In some cases
4541  * (e.g. where a virtual instruction unrolls into a simple sequence of FPU
4542  * instructions) it may simplify virtual instruction lowering if we can
4543  * enforce FPU-like regioning restrictions already on the virtual instruction,
4544  * in other cases (e.g. virtual send-like instructions) this may be
4545  * excessively restrictive.
4546  */
4547 static unsigned
get_fpu_lowered_simd_width(const struct brw_compiler * compiler,const fs_inst * inst)4548 get_fpu_lowered_simd_width(const struct brw_compiler *compiler,
4549                            const fs_inst *inst)
4550 {
4551    const struct intel_device_info *devinfo = compiler->devinfo;
4552 
4553    /* Maximum execution size representable in the instruction controls. */
4554    unsigned max_width = MIN2(32, inst->exec_size);
4555 
4556    /* According to the PRMs:
4557     *  "A. In Direct Addressing mode, a source cannot span more than 2
4558     *      adjacent GRF registers.
4559     *   B. A destination cannot span more than 2 adjacent GRF registers."
4560     *
4561     * Look for the source or destination with the largest register region
4562     * which is the one that is going to limit the overall execution size of
4563     * the instruction due to this rule.
4564     */
4565    unsigned reg_count = DIV_ROUND_UP(inst->size_written, REG_SIZE);
4566 
4567    for (unsigned i = 0; i < inst->sources; i++)
4568       reg_count = MAX2(reg_count, DIV_ROUND_UP(inst->size_read(i), REG_SIZE));
4569 
4570    /* Calculate the maximum execution size of the instruction based on the
4571     * factor by which it goes over the hardware limit of 2 GRFs.
4572     */
4573    if (reg_count > 2)
4574       max_width = MIN2(max_width, inst->exec_size / DIV_ROUND_UP(reg_count, 2));
4575 
4576    /* According to the IVB PRMs:
4577     *  "When destination spans two registers, the source MUST span two
4578     *   registers. The exception to the above rule:
4579     *
4580     *    - When source is scalar, the source registers are not incremented.
4581     *    - When source is packed integer Word and destination is packed
4582     *      integer DWord, the source register is not incremented but the
4583     *      source sub register is incremented."
4584     *
4585     * The hardware specs from Gfx4 to Gfx7.5 mention similar regioning
4586     * restrictions.  The code below intentionally doesn't check whether the
4587     * destination type is integer because empirically the hardware doesn't
4588     * seem to care what the actual type is as long as it's dword-aligned.
4589     */
4590    if (devinfo->ver < 8) {
4591       for (unsigned i = 0; i < inst->sources; i++) {
4592          /* IVB implements DF scalars as <0;2,1> regions. */
4593          const bool is_scalar_exception = is_uniform(inst->src[i]) &&
4594             (devinfo->platform == INTEL_PLATFORM_HSW || type_sz(inst->src[i].type) != 8);
4595          const bool is_packed_word_exception =
4596             type_sz(inst->dst.type) == 4 && inst->dst.stride == 1 &&
4597             type_sz(inst->src[i].type) == 2 && inst->src[i].stride == 1;
4598 
4599          /* We check size_read(i) against size_written instead of REG_SIZE
4600           * because we want to properly handle SIMD32.  In SIMD32, you can end
4601           * up with writes to 4 registers and a source that reads 2 registers
4602           * and we may still need to lower all the way to SIMD8 in that case.
4603           */
4604          if (inst->size_written > REG_SIZE &&
4605              inst->size_read(i) != 0 &&
4606              inst->size_read(i) < inst->size_written &&
4607              !is_scalar_exception && !is_packed_word_exception) {
4608             const unsigned reg_count = DIV_ROUND_UP(inst->size_written, REG_SIZE);
4609             max_width = MIN2(max_width, inst->exec_size / reg_count);
4610          }
4611       }
4612    }
4613 
4614    if (devinfo->ver < 6) {
4615       /* From the G45 PRM, Volume 4 Page 361:
4616        *
4617        *    "Operand Alignment Rule: With the exceptions listed below, a
4618        *     source/destination operand in general should be aligned to even
4619        *     256-bit physical register with a region size equal to two 256-bit
4620        *     physical registers."
4621        *
4622        * Normally we enforce this by allocating virtual registers to the
4623        * even-aligned class.  But we need to handle payload registers.
4624        */
4625       for (unsigned i = 0; i < inst->sources; i++) {
4626          if (inst->src[i].file == FIXED_GRF && (inst->src[i].nr & 1) &&
4627              inst->size_read(i) > REG_SIZE) {
4628             max_width = MIN2(max_width, 8);
4629          }
4630       }
4631    }
4632 
4633    /* From the IVB PRMs:
4634     *  "When an instruction is SIMD32, the low 16 bits of the execution mask
4635     *   are applied for both halves of the SIMD32 instruction. If different
4636     *   execution mask channels are required, split the instruction into two
4637     *   SIMD16 instructions."
4638     *
4639     * There is similar text in the HSW PRMs.  Gfx4-6 don't even implement
4640     * 32-wide control flow support in hardware and will behave similarly.
4641     */
4642    if (devinfo->ver < 8 && !inst->force_writemask_all)
4643       max_width = MIN2(max_width, 16);
4644 
4645    /* From the IVB PRMs (applies to HSW too):
4646     *  "Instructions with condition modifiers must not use SIMD32."
4647     *
4648     * From the BDW PRMs (applies to later hardware too):
4649     *  "Ternary instruction with condition modifiers must not use SIMD32."
4650     */
4651    if (inst->conditional_mod && (devinfo->ver < 8 || inst->is_3src(compiler)))
4652       max_width = MIN2(max_width, 16);
4653 
4654    /* From the IVB PRMs (applies to other devices that don't have the
4655     * intel_device_info::supports_simd16_3src flag set):
4656     *  "In Align16 access mode, SIMD16 is not allowed for DW operations and
4657     *   SIMD8 is not allowed for DF operations."
4658     */
4659    if (inst->is_3src(compiler) && !devinfo->supports_simd16_3src)
4660       max_width = MIN2(max_width, inst->exec_size / reg_count);
4661 
4662    /* Pre-Gfx8 EUs are hardwired to use the QtrCtrl+1 (where QtrCtrl is
4663     * the 8-bit quarter of the execution mask signals specified in the
4664     * instruction control fields) for the second compressed half of any
4665     * single-precision instruction (for double-precision instructions
4666     * it's hardwired to use NibCtrl+1, at least on HSW), which means that
4667     * the EU will apply the wrong execution controls for the second
4668     * sequential GRF write if the number of channels per GRF is not exactly
4669     * eight in single-precision mode (or four in double-float mode).
4670     *
4671     * In this situation we calculate the maximum size of the split
4672     * instructions so they only ever write to a single register.
4673     */
4674    if (devinfo->ver < 8 && inst->size_written > REG_SIZE &&
4675        !inst->force_writemask_all) {
4676       const unsigned channels_per_grf = inst->exec_size /
4677          DIV_ROUND_UP(inst->size_written, REG_SIZE);
4678       const unsigned exec_type_size = get_exec_type_size(inst);
4679       assert(exec_type_size);
4680 
4681       /* The hardware shifts exactly 8 channels per compressed half of the
4682        * instruction in single-precision mode and exactly 4 in double-precision.
4683        */
4684       if (channels_per_grf != (exec_type_size == 8 ? 4 : 8))
4685          max_width = MIN2(max_width, channels_per_grf);
4686 
4687       /* Lower all non-force_writemask_all DF instructions to SIMD4 on IVB/BYT
4688        * because HW applies the same channel enable signals to both halves of
4689        * the compressed instruction which will be just wrong under
4690        * non-uniform control flow.
4691        */
4692       if (devinfo->verx10 == 70 &&
4693           (exec_type_size == 8 || type_sz(inst->dst.type) == 8))
4694          max_width = MIN2(max_width, 4);
4695    }
4696 
4697    /* From the SKL PRM, Special Restrictions for Handling Mixed Mode
4698     * Float Operations:
4699     *
4700     *    "No SIMD16 in mixed mode when destination is f32. Instruction
4701     *     execution size must be no more than 8."
4702     *
4703     * FIXME: the simulator doesn't seem to complain if we don't do this and
4704     * empirical testing with existing CTS tests show that they pass just fine
4705     * without implementing this, however, since our interpretation of the PRM
4706     * is that conversion MOVs between HF and F are still mixed-float
4707     * instructions (and therefore subject to this restriction) we decided to
4708     * split them to be safe. Might be useful to do additional investigation to
4709     * lift the restriction if we can ensure that it is safe though, since these
4710     * conversions are common when half-float types are involved since many
4711     * instructions do not support HF types and conversions from/to F are
4712     * required.
4713     */
4714    if (is_mixed_float_with_fp32_dst(inst))
4715       max_width = MIN2(max_width, 8);
4716 
4717    /* From the SKL PRM, Special Restrictions for Handling Mixed Mode
4718     * Float Operations:
4719     *
4720     *    "No SIMD16 in mixed mode when destination is packed f16 for both
4721     *     Align1 and Align16."
4722     */
4723    if (is_mixed_float_with_packed_fp16_dst(inst))
4724       max_width = MIN2(max_width, 8);
4725 
4726    /* Only power-of-two execution sizes are representable in the instruction
4727     * control fields.
4728     */
4729    return 1 << util_logbase2(max_width);
4730 }
4731 
4732 /**
4733  * Get the maximum allowed SIMD width for instruction \p inst accounting for
4734  * various payload size restrictions that apply to sampler message
4735  * instructions.
4736  *
4737  * This is only intended to provide a maximum theoretical bound for the
4738  * execution size of the message based on the number of argument components
4739  * alone, which in most cases will determine whether the SIMD8 or SIMD16
4740  * variant of the message can be used, though some messages may have
4741  * additional restrictions not accounted for here (e.g. pre-ILK hardware uses
4742  * the message length to determine the exact SIMD width and argument count,
4743  * which makes a number of sampler message combinations impossible to
4744  * represent).
4745  */
4746 static unsigned
get_sampler_lowered_simd_width(const struct intel_device_info * devinfo,const fs_inst * inst)4747 get_sampler_lowered_simd_width(const struct intel_device_info *devinfo,
4748                                const fs_inst *inst)
4749 {
4750    /* If we have a min_lod parameter on anything other than a simple sample
4751     * message, it will push it over 5 arguments and we have to fall back to
4752     * SIMD8.
4753     */
4754    if (inst->opcode != SHADER_OPCODE_TEX &&
4755        inst->components_read(TEX_LOGICAL_SRC_MIN_LOD))
4756       return 8;
4757 
4758    /* Calculate the number of coordinate components that have to be present
4759     * assuming that additional arguments follow the texel coordinates in the
4760     * message payload.  On IVB+ there is no need for padding, on ILK-SNB we
4761     * need to pad to four or three components depending on the message,
4762     * pre-ILK we need to pad to at most three components.
4763     */
4764    const unsigned req_coord_components =
4765       (devinfo->ver >= 7 ||
4766        !inst->components_read(TEX_LOGICAL_SRC_COORDINATE)) ? 0 :
4767       (devinfo->ver >= 5 && inst->opcode != SHADER_OPCODE_TXF_LOGICAL &&
4768                             inst->opcode != SHADER_OPCODE_TXF_CMS_LOGICAL) ? 4 :
4769       3;
4770 
4771    /* On Gfx9+ the LOD argument is for free if we're able to use the LZ
4772     * variant of the TXL or TXF message.
4773     */
4774    const bool implicit_lod = devinfo->ver >= 9 &&
4775                              (inst->opcode == SHADER_OPCODE_TXL ||
4776                               inst->opcode == SHADER_OPCODE_TXF) &&
4777                              inst->src[TEX_LOGICAL_SRC_LOD].is_zero();
4778 
4779    /* Calculate the total number of argument components that need to be passed
4780     * to the sampler unit.
4781     */
4782    const unsigned num_payload_components =
4783       MAX2(inst->components_read(TEX_LOGICAL_SRC_COORDINATE),
4784            req_coord_components) +
4785       inst->components_read(TEX_LOGICAL_SRC_SHADOW_C) +
4786       (implicit_lod ? 0 : inst->components_read(TEX_LOGICAL_SRC_LOD)) +
4787       inst->components_read(TEX_LOGICAL_SRC_LOD2) +
4788       inst->components_read(TEX_LOGICAL_SRC_SAMPLE_INDEX) +
4789       (inst->opcode == SHADER_OPCODE_TG4_OFFSET_LOGICAL ?
4790        inst->components_read(TEX_LOGICAL_SRC_TG4_OFFSET) : 0) +
4791       inst->components_read(TEX_LOGICAL_SRC_MCS);
4792 
4793    /* SIMD16 messages with more than five arguments exceed the maximum message
4794     * size supported by the sampler, regardless of whether a header is
4795     * provided or not.
4796     */
4797    return MIN2(inst->exec_size,
4798                num_payload_components > MAX_SAMPLER_MESSAGE_SIZE / 2 ? 8 : 16);
4799 }
4800 
4801 /**
4802  * Get the closest native SIMD width supported by the hardware for instruction
4803  * \p inst.  The instruction will be left untouched by
4804  * fs_visitor::lower_simd_width() if the returned value is equal to the
4805  * original execution size.
4806  */
4807 static unsigned
get_lowered_simd_width(const struct brw_compiler * compiler,const fs_inst * inst)4808 get_lowered_simd_width(const struct brw_compiler *compiler,
4809                        const fs_inst *inst)
4810 {
4811    const struct intel_device_info *devinfo = compiler->devinfo;
4812 
4813    switch (inst->opcode) {
4814    case BRW_OPCODE_MOV:
4815    case BRW_OPCODE_SEL:
4816    case BRW_OPCODE_NOT:
4817    case BRW_OPCODE_AND:
4818    case BRW_OPCODE_OR:
4819    case BRW_OPCODE_XOR:
4820    case BRW_OPCODE_SHR:
4821    case BRW_OPCODE_SHL:
4822    case BRW_OPCODE_ASR:
4823    case BRW_OPCODE_ROR:
4824    case BRW_OPCODE_ROL:
4825    case BRW_OPCODE_CMPN:
4826    case BRW_OPCODE_CSEL:
4827    case BRW_OPCODE_F32TO16:
4828    case BRW_OPCODE_F16TO32:
4829    case BRW_OPCODE_BFREV:
4830    case BRW_OPCODE_BFE:
4831    case BRW_OPCODE_ADD:
4832    case BRW_OPCODE_MUL:
4833    case BRW_OPCODE_AVG:
4834    case BRW_OPCODE_FRC:
4835    case BRW_OPCODE_RNDU:
4836    case BRW_OPCODE_RNDD:
4837    case BRW_OPCODE_RNDE:
4838    case BRW_OPCODE_RNDZ:
4839    case BRW_OPCODE_LZD:
4840    case BRW_OPCODE_FBH:
4841    case BRW_OPCODE_FBL:
4842    case BRW_OPCODE_CBIT:
4843    case BRW_OPCODE_SAD2:
4844    case BRW_OPCODE_MAD:
4845    case BRW_OPCODE_LRP:
4846    case BRW_OPCODE_ADD3:
4847    case FS_OPCODE_PACK:
4848    case SHADER_OPCODE_SEL_EXEC:
4849    case SHADER_OPCODE_CLUSTER_BROADCAST:
4850    case SHADER_OPCODE_MOV_RELOC_IMM:
4851       return get_fpu_lowered_simd_width(compiler, inst);
4852 
4853    case BRW_OPCODE_CMP: {
4854       /* The Ivybridge/BayTrail WaCMPInstFlagDepClearedEarly workaround says that
4855        * when the destination is a GRF the dependency-clear bit on the flag
4856        * register is cleared early.
4857        *
4858        * Suggested workarounds are to disable coissuing CMP instructions
4859        * or to split CMP(16) instructions into two CMP(8) instructions.
4860        *
4861        * We choose to split into CMP(8) instructions since disabling
4862        * coissuing would affect CMP instructions not otherwise affected by
4863        * the errata.
4864        */
4865       const unsigned max_width = (devinfo->verx10 == 70 &&
4866                                   !inst->dst.is_null() ? 8 : ~0);
4867       return MIN2(max_width, get_fpu_lowered_simd_width(compiler, inst));
4868    }
4869    case BRW_OPCODE_BFI1:
4870    case BRW_OPCODE_BFI2:
4871       /* The Haswell WaForceSIMD8ForBFIInstruction workaround says that we
4872        * should
4873        *  "Force BFI instructions to be executed always in SIMD8."
4874        */
4875       return MIN2(devinfo->platform == INTEL_PLATFORM_HSW ? 8 : ~0u,
4876                   get_fpu_lowered_simd_width(compiler, inst));
4877 
4878    case BRW_OPCODE_IF:
4879       assert(inst->src[0].file == BAD_FILE || inst->exec_size <= 16);
4880       return inst->exec_size;
4881 
4882    case SHADER_OPCODE_RCP:
4883    case SHADER_OPCODE_RSQ:
4884    case SHADER_OPCODE_SQRT:
4885    case SHADER_OPCODE_EXP2:
4886    case SHADER_OPCODE_LOG2:
4887    case SHADER_OPCODE_SIN:
4888    case SHADER_OPCODE_COS: {
4889       /* Unary extended math instructions are limited to SIMD8 on Gfx4 and
4890        * Gfx6. Extended Math Function is limited to SIMD8 with half-float.
4891        */
4892       if (devinfo->ver == 6 || devinfo->verx10 == 40)
4893          return MIN2(8, inst->exec_size);
4894       if (inst->dst.type == BRW_REGISTER_TYPE_HF)
4895          return MIN2(8, inst->exec_size);
4896       return MIN2(16, inst->exec_size);
4897    }
4898 
4899    case SHADER_OPCODE_POW: {
4900       /* SIMD16 is only allowed on Gfx7+. Extended Math Function is limited
4901        * to SIMD8 with half-float
4902        */
4903       if (devinfo->ver < 7)
4904          return MIN2(8, inst->exec_size);
4905       if (inst->dst.type == BRW_REGISTER_TYPE_HF)
4906          return MIN2(8, inst->exec_size);
4907       return MIN2(16, inst->exec_size);
4908    }
4909 
4910    case SHADER_OPCODE_USUB_SAT:
4911    case SHADER_OPCODE_ISUB_SAT:
4912       return get_fpu_lowered_simd_width(compiler, inst);
4913 
4914    case SHADER_OPCODE_INT_QUOTIENT:
4915    case SHADER_OPCODE_INT_REMAINDER:
4916       /* Integer division is limited to SIMD8 on all generations. */
4917       return MIN2(8, inst->exec_size);
4918 
4919    case FS_OPCODE_LINTERP:
4920    case SHADER_OPCODE_GET_BUFFER_SIZE:
4921    case FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD:
4922    case FS_OPCODE_PACK_HALF_2x16_SPLIT:
4923    case FS_OPCODE_INTERPOLATE_AT_SAMPLE:
4924    case FS_OPCODE_INTERPOLATE_AT_SHARED_OFFSET:
4925    case FS_OPCODE_INTERPOLATE_AT_PER_SLOT_OFFSET:
4926       return MIN2(16, inst->exec_size);
4927 
4928    case FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_LOGICAL:
4929       /* Pre-ILK hardware doesn't have a SIMD8 variant of the texel fetch
4930        * message used to implement varying pull constant loads, so expand it
4931        * to SIMD16.  An alternative with longer message payload length but
4932        * shorter return payload would be to use the SIMD8 sampler message that
4933        * takes (header, u, v, r) as parameters instead of (header, u).
4934        */
4935       return (devinfo->ver == 4 ? 16 : MIN2(16, inst->exec_size));
4936 
4937    case FS_OPCODE_DDX_COARSE:
4938    case FS_OPCODE_DDX_FINE:
4939    case FS_OPCODE_DDY_COARSE:
4940    case FS_OPCODE_DDY_FINE:
4941       /* The implementation of this virtual opcode may require emitting
4942        * compressed Align16 instructions, which are severely limited on some
4943        * generations.
4944        *
4945        * From the Ivy Bridge PRM, volume 4 part 3, section 3.3.9 (Register
4946        * Region Restrictions):
4947        *
4948        *  "In Align16 access mode, SIMD16 is not allowed for DW operations
4949        *   and SIMD8 is not allowed for DF operations."
4950        *
4951        * In this context, "DW operations" means "operations acting on 32-bit
4952        * values", so it includes operations on floats.
4953        *
4954        * Gfx4 has a similar restriction.  From the i965 PRM, section 11.5.3
4955        * (Instruction Compression -> Rules and Restrictions):
4956        *
4957        *  "A compressed instruction must be in Align1 access mode. Align16
4958        *   mode instructions cannot be compressed."
4959        *
4960        * Similar text exists in the g45 PRM.
4961        *
4962        * Empirically, compressed align16 instructions using odd register
4963        * numbers don't appear to work on Sandybridge either.
4964        */
4965       return (devinfo->ver == 4 || devinfo->ver == 6 ||
4966               (devinfo->verx10 == 70) ?
4967               MIN2(8, inst->exec_size) : MIN2(16, inst->exec_size));
4968 
4969    case SHADER_OPCODE_MULH:
4970       /* MULH is lowered to the MUL/MACH sequence using the accumulator, which
4971        * is 8-wide on Gfx7+.
4972        */
4973       return (devinfo->ver >= 7 ? 8 :
4974               get_fpu_lowered_simd_width(compiler, inst));
4975 
4976    case FS_OPCODE_FB_WRITE_LOGICAL:
4977       /* Gfx6 doesn't support SIMD16 depth writes but we cannot handle them
4978        * here.
4979        */
4980       assert(devinfo->ver != 6 ||
4981              inst->src[FB_WRITE_LOGICAL_SRC_SRC_DEPTH].file == BAD_FILE ||
4982              inst->exec_size == 8);
4983       /* Dual-source FB writes are unsupported in SIMD16 mode. */
4984       return (inst->src[FB_WRITE_LOGICAL_SRC_COLOR1].file != BAD_FILE ?
4985               8 : MIN2(16, inst->exec_size));
4986 
4987    case FS_OPCODE_FB_READ_LOGICAL:
4988       return MIN2(16, inst->exec_size);
4989 
4990    case SHADER_OPCODE_TEX_LOGICAL:
4991    case SHADER_OPCODE_TXF_CMS_LOGICAL:
4992    case SHADER_OPCODE_TXF_UMS_LOGICAL:
4993    case SHADER_OPCODE_TXF_MCS_LOGICAL:
4994    case SHADER_OPCODE_LOD_LOGICAL:
4995    case SHADER_OPCODE_TG4_LOGICAL:
4996    case SHADER_OPCODE_SAMPLEINFO_LOGICAL:
4997    case SHADER_OPCODE_TXF_CMS_W_LOGICAL:
4998    case SHADER_OPCODE_TG4_OFFSET_LOGICAL:
4999       return get_sampler_lowered_simd_width(devinfo, inst);
5000 
5001    /* On gfx12 parameters are fixed to 16-bit values and therefore they all
5002     * always fit regardless of the execution size.
5003     */
5004    case SHADER_OPCODE_TXF_CMS_W_GFX12_LOGICAL:
5005       return MIN2(16, inst->exec_size);
5006 
5007    case SHADER_OPCODE_TXD_LOGICAL:
5008       /* TXD is unsupported in SIMD16 mode. */
5009       return 8;
5010 
5011    case SHADER_OPCODE_TXL_LOGICAL:
5012    case FS_OPCODE_TXB_LOGICAL:
5013       /* Only one execution size is representable pre-ILK depending on whether
5014        * the shadow reference argument is present.
5015        */
5016       if (devinfo->ver == 4)
5017          return inst->src[TEX_LOGICAL_SRC_SHADOW_C].file == BAD_FILE ? 16 : 8;
5018       else
5019          return get_sampler_lowered_simd_width(devinfo, inst);
5020 
5021    case SHADER_OPCODE_TXF_LOGICAL:
5022    case SHADER_OPCODE_TXS_LOGICAL:
5023       /* Gfx4 doesn't have SIMD8 variants for the RESINFO and LD-with-LOD
5024        * messages.  Use SIMD16 instead.
5025        */
5026       if (devinfo->ver == 4)
5027          return 16;
5028       else
5029          return get_sampler_lowered_simd_width(devinfo, inst);
5030 
5031    case SHADER_OPCODE_TYPED_ATOMIC_LOGICAL:
5032    case SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL:
5033    case SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL:
5034       return 8;
5035 
5036    case SHADER_OPCODE_UNTYPED_ATOMIC_LOGICAL:
5037    case SHADER_OPCODE_UNTYPED_ATOMIC_FLOAT_LOGICAL:
5038    case SHADER_OPCODE_UNTYPED_SURFACE_READ_LOGICAL:
5039    case SHADER_OPCODE_UNTYPED_SURFACE_WRITE_LOGICAL:
5040    case SHADER_OPCODE_BYTE_SCATTERED_WRITE_LOGICAL:
5041    case SHADER_OPCODE_BYTE_SCATTERED_READ_LOGICAL:
5042    case SHADER_OPCODE_DWORD_SCATTERED_WRITE_LOGICAL:
5043    case SHADER_OPCODE_DWORD_SCATTERED_READ_LOGICAL:
5044       return MIN2(16, inst->exec_size);
5045 
5046    case SHADER_OPCODE_A64_UNTYPED_WRITE_LOGICAL:
5047    case SHADER_OPCODE_A64_UNTYPED_READ_LOGICAL:
5048    case SHADER_OPCODE_A64_BYTE_SCATTERED_WRITE_LOGICAL:
5049    case SHADER_OPCODE_A64_BYTE_SCATTERED_READ_LOGICAL:
5050       return devinfo->ver <= 8 ? 8 : MIN2(16, inst->exec_size);
5051 
5052    case SHADER_OPCODE_A64_OWORD_BLOCK_READ_LOGICAL:
5053    case SHADER_OPCODE_A64_UNALIGNED_OWORD_BLOCK_READ_LOGICAL:
5054    case SHADER_OPCODE_A64_OWORD_BLOCK_WRITE_LOGICAL:
5055       assert(inst->exec_size <= 16);
5056       return inst->exec_size;
5057 
5058    case SHADER_OPCODE_A64_UNTYPED_ATOMIC_LOGICAL:
5059    case SHADER_OPCODE_A64_UNTYPED_ATOMIC_INT16_LOGICAL:
5060    case SHADER_OPCODE_A64_UNTYPED_ATOMIC_INT64_LOGICAL:
5061    case SHADER_OPCODE_A64_UNTYPED_ATOMIC_FLOAT16_LOGICAL:
5062    case SHADER_OPCODE_A64_UNTYPED_ATOMIC_FLOAT32_LOGICAL:
5063    case SHADER_OPCODE_A64_UNTYPED_ATOMIC_FLOAT64_LOGICAL:
5064       return 8;
5065 
5066    case SHADER_OPCODE_URB_READ_LOGICAL:
5067    case SHADER_OPCODE_URB_WRITE_LOGICAL:
5068       return MIN2(8, inst->exec_size);
5069 
5070    case SHADER_OPCODE_QUAD_SWIZZLE: {
5071       const unsigned swiz = inst->src[1].ud;
5072       return (is_uniform(inst->src[0]) ?
5073                  get_fpu_lowered_simd_width(compiler, inst) :
5074               devinfo->ver < 11 && type_sz(inst->src[0].type) == 4 ? 8 :
5075               swiz == BRW_SWIZZLE_XYXY || swiz == BRW_SWIZZLE_ZWZW ? 4 :
5076               get_fpu_lowered_simd_width(compiler, inst));
5077    }
5078    case SHADER_OPCODE_MOV_INDIRECT: {
5079       /* From IVB and HSW PRMs:
5080        *
5081        * "2.When the destination requires two registers and the sources are
5082        *  indirect, the sources must use 1x1 regioning mode.
5083        *
5084        * In case of DF instructions in HSW/IVB, the exec_size is limited by
5085        * the EU decompression logic not handling VxH indirect addressing
5086        * correctly.
5087        */
5088       const unsigned max_size = (devinfo->ver >= 8 ? 2 : 1) * REG_SIZE;
5089       /* Prior to Broadwell, we only have 8 address subregisters. */
5090       return MIN3(devinfo->ver >= 8 ? 16 : 8,
5091                   max_size / (inst->dst.stride * type_sz(inst->dst.type)),
5092                   inst->exec_size);
5093    }
5094 
5095    case SHADER_OPCODE_LOAD_PAYLOAD: {
5096       const unsigned reg_count =
5097          DIV_ROUND_UP(inst->dst.component_size(inst->exec_size), REG_SIZE);
5098 
5099       if (reg_count > 2) {
5100          /* Only LOAD_PAYLOAD instructions with per-channel destination region
5101           * can be easily lowered (which excludes headers and heterogeneous
5102           * types).
5103           */
5104          assert(!inst->header_size);
5105          for (unsigned i = 0; i < inst->sources; i++)
5106             assert(type_sz(inst->dst.type) == type_sz(inst->src[i].type) ||
5107                    inst->src[i].file == BAD_FILE);
5108 
5109          return inst->exec_size / DIV_ROUND_UP(reg_count, 2);
5110       } else {
5111          return inst->exec_size;
5112       }
5113    }
5114    default:
5115       return inst->exec_size;
5116    }
5117 }
5118 
5119 /**
5120  * Return true if splitting out the group of channels of instruction \p inst
5121  * given by lbld.group() requires allocating a temporary for the i-th source
5122  * of the lowered instruction.
5123  */
5124 static inline bool
needs_src_copy(const fs_builder & lbld,const fs_inst * inst,unsigned i)5125 needs_src_copy(const fs_builder &lbld, const fs_inst *inst, unsigned i)
5126 {
5127    return !(is_periodic(inst->src[i], lbld.dispatch_width()) ||
5128             (inst->components_read(i) == 1 &&
5129              lbld.dispatch_width() <= inst->exec_size)) ||
5130           (inst->flags_written(lbld.shader->devinfo) &
5131            flag_mask(inst->src[i], type_sz(inst->src[i].type)));
5132 }
5133 
5134 /**
5135  * Extract the data that would be consumed by the channel group given by
5136  * lbld.group() from the i-th source region of instruction \p inst and return
5137  * it as result in packed form.
5138  */
5139 static fs_reg
emit_unzip(const fs_builder & lbld,fs_inst * inst,unsigned i)5140 emit_unzip(const fs_builder &lbld, fs_inst *inst, unsigned i)
5141 {
5142    assert(lbld.group() >= inst->group);
5143 
5144    /* Specified channel group from the source region. */
5145    const fs_reg src = horiz_offset(inst->src[i], lbld.group() - inst->group);
5146 
5147    if (needs_src_copy(lbld, inst, i)) {
5148       /* Builder of the right width to perform the copy avoiding uninitialized
5149        * data if the lowered execution size is greater than the original
5150        * execution size of the instruction.
5151        */
5152       const fs_builder cbld = lbld.group(MIN2(lbld.dispatch_width(),
5153                                               inst->exec_size), 0);
5154       const fs_reg tmp = lbld.vgrf(inst->src[i].type, inst->components_read(i));
5155 
5156       for (unsigned k = 0; k < inst->components_read(i); ++k)
5157          cbld.MOV(offset(tmp, lbld, k), offset(src, inst->exec_size, k));
5158 
5159       return tmp;
5160 
5161    } else if (is_periodic(inst->src[i], lbld.dispatch_width())) {
5162       /* The source is invariant for all dispatch_width-wide groups of the
5163        * original region.
5164        */
5165       return inst->src[i];
5166 
5167    } else {
5168       /* We can just point the lowered instruction at the right channel group
5169        * from the original region.
5170        */
5171       return src;
5172    }
5173 }
5174 
5175 /**
5176  * Return true if splitting out the group of channels of instruction \p inst
5177  * given by lbld.group() requires allocating a temporary for the destination
5178  * of the lowered instruction and copying the data back to the original
5179  * destination region.
5180  */
5181 static inline bool
needs_dst_copy(const fs_builder & lbld,const fs_inst * inst)5182 needs_dst_copy(const fs_builder &lbld, const fs_inst *inst)
5183 {
5184    /* If the instruction writes more than one component we'll have to shuffle
5185     * the results of multiple lowered instructions in order to make sure that
5186     * they end up arranged correctly in the original destination region.
5187     */
5188    if (inst->size_written > inst->dst.component_size(inst->exec_size))
5189       return true;
5190 
5191    /* If the lowered execution size is larger than the original the result of
5192     * the instruction won't fit in the original destination, so we'll have to
5193     * allocate a temporary in any case.
5194     */
5195    if (lbld.dispatch_width() > inst->exec_size)
5196       return true;
5197 
5198    for (unsigned i = 0; i < inst->sources; i++) {
5199       /* If we already made a copy of the source for other reasons there won't
5200        * be any overlap with the destination.
5201        */
5202       if (needs_src_copy(lbld, inst, i))
5203          continue;
5204 
5205       /* In order to keep the logic simple we emit a copy whenever the
5206        * destination region doesn't exactly match an overlapping source, which
5207        * may point at the source and destination not being aligned group by
5208        * group which could cause one of the lowered instructions to overwrite
5209        * the data read from the same source by other lowered instructions.
5210        */
5211       if (regions_overlap(inst->dst, inst->size_written,
5212                           inst->src[i], inst->size_read(i)) &&
5213           !inst->dst.equals(inst->src[i]))
5214         return true;
5215    }
5216 
5217    return false;
5218 }
5219 
5220 /**
5221  * Insert data from a packed temporary into the channel group given by
5222  * lbld.group() of the destination region of instruction \p inst and return
5223  * the temporary as result.  Any copy instructions that are required for
5224  * unzipping the previous value (in the case of partial writes) will be
5225  * inserted using \p lbld_before and any copy instructions required for
5226  * zipping up the destination of \p inst will be inserted using \p lbld_after.
5227  */
5228 static fs_reg
emit_zip(const fs_builder & lbld_before,const fs_builder & lbld_after,fs_inst * inst)5229 emit_zip(const fs_builder &lbld_before, const fs_builder &lbld_after,
5230          fs_inst *inst)
5231 {
5232    assert(lbld_before.dispatch_width() == lbld_after.dispatch_width());
5233    assert(lbld_before.group() == lbld_after.group());
5234    assert(lbld_after.group() >= inst->group);
5235 
5236    /* Specified channel group from the destination region. */
5237    const fs_reg dst = horiz_offset(inst->dst, lbld_after.group() - inst->group);
5238    const unsigned dst_size = inst->size_written /
5239       inst->dst.component_size(inst->exec_size);
5240 
5241    if (needs_dst_copy(lbld_after, inst)) {
5242       const fs_reg tmp = lbld_after.vgrf(inst->dst.type, dst_size);
5243 
5244       if (inst->predicate) {
5245          /* Handle predication by copying the original contents of
5246           * the destination into the temporary before emitting the
5247           * lowered instruction.
5248           */
5249          const fs_builder gbld_before =
5250             lbld_before.group(MIN2(lbld_before.dispatch_width(),
5251                                    inst->exec_size), 0);
5252          for (unsigned k = 0; k < dst_size; ++k) {
5253             gbld_before.MOV(offset(tmp, lbld_before, k),
5254                             offset(dst, inst->exec_size, k));
5255          }
5256       }
5257 
5258       const fs_builder gbld_after =
5259          lbld_after.group(MIN2(lbld_after.dispatch_width(),
5260                                inst->exec_size), 0);
5261       for (unsigned k = 0; k < dst_size; ++k) {
5262          /* Use a builder of the right width to perform the copy avoiding
5263           * uninitialized data if the lowered execution size is greater than
5264           * the original execution size of the instruction.
5265           */
5266          gbld_after.MOV(offset(dst, inst->exec_size, k),
5267                         offset(tmp, lbld_after, k));
5268       }
5269 
5270       return tmp;
5271 
5272    } else {
5273       /* No need to allocate a temporary for the lowered instruction, just
5274        * take the right group of channels from the original region.
5275        */
5276       return dst;
5277    }
5278 }
5279 
5280 bool
lower_simd_width()5281 fs_visitor::lower_simd_width()
5282 {
5283    bool progress = false;
5284 
5285    foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
5286       const unsigned lower_width = get_lowered_simd_width(compiler, inst);
5287 
5288       if (lower_width != inst->exec_size) {
5289          /* Builder matching the original instruction.  We may also need to
5290           * emit an instruction of width larger than the original, set the
5291           * execution size of the builder to the highest of both for now so
5292           * we're sure that both cases can be handled.
5293           */
5294          const unsigned max_width = MAX2(inst->exec_size, lower_width);
5295          const fs_builder ibld = bld.at(block, inst)
5296                                     .exec_all(inst->force_writemask_all)
5297                                     .group(max_width, inst->group / max_width);
5298 
5299          /* Split the copies in chunks of the execution width of either the
5300           * original or the lowered instruction, whichever is lower.
5301           */
5302          const unsigned n = DIV_ROUND_UP(inst->exec_size, lower_width);
5303          const unsigned dst_size = inst->size_written /
5304             inst->dst.component_size(inst->exec_size);
5305 
5306          assert(!inst->writes_accumulator && !inst->mlen);
5307 
5308          /* Inserting the zip, unzip, and duplicated instructions in all of
5309           * the right spots is somewhat tricky.  All of the unzip and any
5310           * instructions from the zip which unzip the destination prior to
5311           * writing need to happen before all of the per-group instructions
5312           * and the zip instructions need to happen after.  In order to sort
5313           * this all out, we insert the unzip instructions before \p inst,
5314           * insert the per-group instructions after \p inst (i.e. before
5315           * inst->next), and insert the zip instructions before the
5316           * instruction after \p inst.  Since we are inserting instructions
5317           * after \p inst, inst->next is a moving target and we need to save
5318           * it off here so that we insert the zip instructions in the right
5319           * place.
5320           *
5321           * Since we're inserting split instructions after after_inst, the
5322           * instructions will end up in the reverse order that we insert them.
5323           * However, certain render target writes require that the low group
5324           * instructions come before the high group.  From the Ivy Bridge PRM
5325           * Vol. 4, Pt. 1, Section 3.9.11:
5326           *
5327           *    "If multiple SIMD8 Dual Source messages are delivered by the
5328           *    pixel shader thread, each SIMD8_DUALSRC_LO message must be
5329           *    issued before the SIMD8_DUALSRC_HI message with the same Slot
5330           *    Group Select setting."
5331           *
5332           * And, from Section 3.9.11.1 of the same PRM:
5333           *
5334           *    "When SIMD32 or SIMD16 PS threads send render target writes
5335           *    with multiple SIMD8 and SIMD16 messages, the following must
5336           *    hold:
5337           *
5338           *    All the slots (as described above) must have a corresponding
5339           *    render target write irrespective of the slot's validity. A slot
5340           *    is considered valid when at least one sample is enabled. For
5341           *    example, a SIMD16 PS thread must send two SIMD8 render target
5342           *    writes to cover all the slots.
5343           *
5344           *    PS thread must send SIMD render target write messages with
5345           *    increasing slot numbers. For example, SIMD16 thread has
5346           *    Slot[15:0] and if two SIMD8 render target writes are used, the
5347           *    first SIMD8 render target write must send Slot[7:0] and the
5348           *    next one must send Slot[15:8]."
5349           *
5350           * In order to make low group instructions come before high group
5351           * instructions (this is required for some render target writes), we
5352           * split from the highest group to lowest.
5353           */
5354          exec_node *const after_inst = inst->next;
5355          for (int i = n - 1; i >= 0; i--) {
5356             /* Emit a copy of the original instruction with the lowered width.
5357              * If the EOT flag was set throw it away except for the last
5358              * instruction to avoid killing the thread prematurely.
5359              */
5360             fs_inst split_inst = *inst;
5361             split_inst.exec_size = lower_width;
5362             split_inst.eot = inst->eot && i == int(n - 1);
5363 
5364             /* Select the correct channel enables for the i-th group, then
5365              * transform the sources and destination and emit the lowered
5366              * instruction.
5367              */
5368             const fs_builder lbld = ibld.group(lower_width, i);
5369 
5370             for (unsigned j = 0; j < inst->sources; j++)
5371                split_inst.src[j] = emit_unzip(lbld.at(block, inst), inst, j);
5372 
5373             split_inst.dst = emit_zip(lbld.at(block, inst),
5374                                       lbld.at(block, after_inst), inst);
5375             split_inst.size_written =
5376                split_inst.dst.component_size(lower_width) * dst_size;
5377 
5378             lbld.at(block, inst->next).emit(split_inst);
5379          }
5380 
5381          inst->remove(block);
5382          progress = true;
5383       }
5384    }
5385 
5386    if (progress)
5387       invalidate_analysis(DEPENDENCY_INSTRUCTIONS | DEPENDENCY_VARIABLES);
5388 
5389    return progress;
5390 }
5391 
5392 /**
5393  * Transform barycentric vectors into the interleaved form expected by the PLN
5394  * instruction and returned by the Gfx7+ PI shared function.
5395  *
5396  * For channels 0-15 in SIMD16 mode they are expected to be laid out as
5397  * follows in the register file:
5398  *
5399  *    rN+0: X[0-7]
5400  *    rN+1: Y[0-7]
5401  *    rN+2: X[8-15]
5402  *    rN+3: Y[8-15]
5403  *
5404  * There is no need to handle SIMD32 here -- This is expected to be run after
5405  * SIMD lowering, since SIMD lowering relies on vectors having the standard
5406  * component layout.
5407  */
5408 bool
lower_barycentrics()5409 fs_visitor::lower_barycentrics()
5410 {
5411    const bool has_interleaved_layout = devinfo->has_pln || devinfo->ver >= 7;
5412    bool progress = false;
5413 
5414    if (stage != MESA_SHADER_FRAGMENT || !has_interleaved_layout)
5415       return false;
5416 
5417    foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
5418       if (inst->exec_size < 16)
5419          continue;
5420 
5421       const fs_builder ibld(this, block, inst);
5422       const fs_builder ubld = ibld.exec_all().group(8, 0);
5423 
5424       switch (inst->opcode) {
5425       case FS_OPCODE_LINTERP : {
5426          assert(inst->exec_size == 16);
5427          const fs_reg tmp = ibld.vgrf(inst->src[0].type, 2);
5428          fs_reg srcs[4];
5429 
5430          for (unsigned i = 0; i < ARRAY_SIZE(srcs); i++)
5431             srcs[i] = horiz_offset(offset(inst->src[0], ibld, i % 2),
5432                                    8 * (i / 2));
5433 
5434          ubld.LOAD_PAYLOAD(tmp, srcs, ARRAY_SIZE(srcs), ARRAY_SIZE(srcs));
5435 
5436          inst->src[0] = tmp;
5437          progress = true;
5438          break;
5439       }
5440       case FS_OPCODE_INTERPOLATE_AT_SAMPLE:
5441       case FS_OPCODE_INTERPOLATE_AT_SHARED_OFFSET:
5442       case FS_OPCODE_INTERPOLATE_AT_PER_SLOT_OFFSET: {
5443          assert(inst->exec_size == 16);
5444          const fs_reg tmp = ibld.vgrf(inst->dst.type, 2);
5445 
5446          for (unsigned i = 0; i < 2; i++) {
5447             for (unsigned g = 0; g < inst->exec_size / 8; g++) {
5448                fs_inst *mov = ibld.at(block, inst->next).group(8, g)
5449                                   .MOV(horiz_offset(offset(inst->dst, ibld, i),
5450                                                     8 * g),
5451                                        offset(tmp, ubld, 2 * g + i));
5452                mov->predicate = inst->predicate;
5453                mov->predicate_inverse = inst->predicate_inverse;
5454                mov->flag_subreg = inst->flag_subreg;
5455             }
5456          }
5457 
5458          inst->dst = tmp;
5459          progress = true;
5460          break;
5461       }
5462       default:
5463          break;
5464       }
5465    }
5466 
5467    if (progress)
5468       invalidate_analysis(DEPENDENCY_INSTRUCTIONS | DEPENDENCY_VARIABLES);
5469 
5470    return progress;
5471 }
5472 
5473 /**
5474  * Lower a derivative instruction as the floating-point difference of two
5475  * swizzles of the source, specified as \p swz0 and \p swz1.
5476  */
5477 static bool
lower_derivative(fs_visitor * v,bblock_t * block,fs_inst * inst,unsigned swz0,unsigned swz1)5478 lower_derivative(fs_visitor *v, bblock_t *block, fs_inst *inst,
5479                  unsigned swz0, unsigned swz1)
5480 {
5481    const fs_builder ibld(v, block, inst);
5482    const fs_reg tmp0 = ibld.vgrf(inst->src[0].type);
5483    const fs_reg tmp1 = ibld.vgrf(inst->src[0].type);
5484 
5485    ibld.emit(SHADER_OPCODE_QUAD_SWIZZLE, tmp0, inst->src[0], brw_imm_ud(swz0));
5486    ibld.emit(SHADER_OPCODE_QUAD_SWIZZLE, tmp1, inst->src[0], brw_imm_ud(swz1));
5487 
5488    inst->resize_sources(2);
5489    inst->src[0] = negate(tmp0);
5490    inst->src[1] = tmp1;
5491    inst->opcode = BRW_OPCODE_ADD;
5492 
5493    return true;
5494 }
5495 
5496 /**
5497  * Lower derivative instructions on platforms where codegen cannot implement
5498  * them efficiently (i.e. XeHP).
5499  */
5500 bool
lower_derivatives()5501 fs_visitor::lower_derivatives()
5502 {
5503    bool progress = false;
5504 
5505    if (devinfo->verx10 < 125)
5506       return false;
5507 
5508    foreach_block_and_inst(block, fs_inst, inst, cfg) {
5509       if (inst->opcode == FS_OPCODE_DDX_COARSE)
5510          progress |= lower_derivative(this, block, inst,
5511                                       BRW_SWIZZLE_XXXX, BRW_SWIZZLE_YYYY);
5512 
5513       else if (inst->opcode == FS_OPCODE_DDX_FINE)
5514          progress |= lower_derivative(this, block, inst,
5515                                       BRW_SWIZZLE_XXZZ, BRW_SWIZZLE_YYWW);
5516 
5517       else if (inst->opcode == FS_OPCODE_DDY_COARSE)
5518          progress |= lower_derivative(this, block, inst,
5519                                       BRW_SWIZZLE_XXXX, BRW_SWIZZLE_ZZZZ);
5520 
5521       else if (inst->opcode == FS_OPCODE_DDY_FINE)
5522          progress |= lower_derivative(this, block, inst,
5523                                       BRW_SWIZZLE_XYXY, BRW_SWIZZLE_ZWZW);
5524    }
5525 
5526    if (progress)
5527       invalidate_analysis(DEPENDENCY_INSTRUCTIONS | DEPENDENCY_VARIABLES);
5528 
5529    return progress;
5530 }
5531 
5532 bool
lower_find_live_channel()5533 fs_visitor::lower_find_live_channel()
5534 {
5535    bool progress = false;
5536 
5537    if (devinfo->ver < 8)
5538       return false;
5539 
5540    bool packed_dispatch =
5541       brw_stage_has_packed_dispatch(devinfo, stage, stage_prog_data);
5542    bool vmask =
5543       stage == MESA_SHADER_FRAGMENT &&
5544       brw_wm_prog_data(stage_prog_data)->uses_vmask;
5545 
5546    foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
5547       if (inst->opcode != SHADER_OPCODE_FIND_LIVE_CHANNEL &&
5548           inst->opcode != SHADER_OPCODE_FIND_LAST_LIVE_CHANNEL)
5549          continue;
5550 
5551       bool first = inst->opcode == SHADER_OPCODE_FIND_LIVE_CHANNEL;
5552 
5553       /* Getting the first active channel index is easy on Gfx8: Just find
5554        * the first bit set in the execution mask.  The register exists on
5555        * HSW already but it reads back as all ones when the current
5556        * instruction has execution masking disabled, so it's kind of
5557        * useless there.
5558        */
5559       fs_reg exec_mask(retype(brw_mask_reg(0), BRW_REGISTER_TYPE_UD));
5560 
5561       const fs_builder ubld = bld.at(block, inst).exec_all().group(1, 0);
5562 
5563       /* ce0 doesn't consider the thread dispatch mask (DMask or VMask),
5564        * so combine the execution and dispatch masks to obtain the true mask.
5565        *
5566        * If we're looking for the first live channel, and we have packed
5567        * dispatch, we can skip this step, as we know all dispatched channels
5568        * will appear at the front of the mask.
5569        */
5570       if (!(first && packed_dispatch)) {
5571          fs_reg mask = ubld.vgrf(BRW_REGISTER_TYPE_UD);
5572          ubld.emit(SHADER_OPCODE_READ_SR_REG, mask, brw_imm_ud(vmask ? 3 : 2));
5573 
5574          /* Quarter control has the effect of magically shifting the value of
5575           * ce0 so you'll get the first/last active channel relative to the
5576           * specified quarter control as result.
5577           */
5578          if (inst->group > 0)
5579             ubld.SHR(mask, mask, brw_imm_ud(ALIGN(inst->group, 8)));
5580 
5581          ubld.AND(mask, exec_mask, mask);
5582          exec_mask = mask;
5583       }
5584 
5585       if (first) {
5586          ubld.FBL(inst->dst, exec_mask);
5587       } else {
5588          fs_reg tmp = ubld.vgrf(BRW_REGISTER_TYPE_UD, 1);
5589          ubld.LZD(tmp, exec_mask);
5590          ubld.ADD(inst->dst, negate(tmp), brw_imm_uw(31));
5591       }
5592 
5593       inst->remove(block);
5594       progress = true;
5595    }
5596 
5597    if (progress)
5598       invalidate_analysis(DEPENDENCY_INSTRUCTIONS | DEPENDENCY_VARIABLES);
5599 
5600    return progress;
5601 }
5602 
5603 void
dump_instructions() const5604 fs_visitor::dump_instructions() const
5605 {
5606    dump_instructions(NULL);
5607 }
5608 
5609 void
dump_instructions(const char * name) const5610 fs_visitor::dump_instructions(const char *name) const
5611 {
5612    FILE *file = stderr;
5613    if (name && geteuid() != 0) {
5614       file = fopen(name, "w");
5615       if (!file)
5616          file = stderr;
5617    }
5618 
5619    if (cfg) {
5620       const register_pressure &rp = regpressure_analysis.require();
5621       unsigned ip = 0, max_pressure = 0;
5622       foreach_block_and_inst(block, backend_instruction, inst, cfg) {
5623          max_pressure = MAX2(max_pressure, rp.regs_live_at_ip[ip]);
5624          fprintf(file, "{%3d} %4d: ", rp.regs_live_at_ip[ip], ip);
5625          dump_instruction(inst, file);
5626          ip++;
5627       }
5628       fprintf(file, "Maximum %3d registers live at once.\n", max_pressure);
5629    } else {
5630       int ip = 0;
5631       foreach_in_list(backend_instruction, inst, &instructions) {
5632          fprintf(file, "%4d: ", ip++);
5633          dump_instruction(inst, file);
5634       }
5635    }
5636 
5637    if (file != stderr) {
5638       fclose(file);
5639    }
5640 }
5641 
5642 void
dump_instruction(const backend_instruction * be_inst) const5643 fs_visitor::dump_instruction(const backend_instruction *be_inst) const
5644 {
5645    dump_instruction(be_inst, stderr);
5646 }
5647 
5648 void
dump_instruction(const backend_instruction * be_inst,FILE * file) const5649 fs_visitor::dump_instruction(const backend_instruction *be_inst, FILE *file) const
5650 {
5651    const fs_inst *inst = (const fs_inst *)be_inst;
5652 
5653    if (inst->predicate) {
5654       fprintf(file, "(%cf%d.%d) ",
5655               inst->predicate_inverse ? '-' : '+',
5656               inst->flag_subreg / 2,
5657               inst->flag_subreg % 2);
5658    }
5659 
5660    fprintf(file, "%s", brw_instruction_name(&compiler->isa, inst->opcode));
5661    if (inst->saturate)
5662       fprintf(file, ".sat");
5663    if (inst->conditional_mod) {
5664       fprintf(file, "%s", conditional_modifier[inst->conditional_mod]);
5665       if (!inst->predicate &&
5666           (devinfo->ver < 5 || (inst->opcode != BRW_OPCODE_SEL &&
5667                                 inst->opcode != BRW_OPCODE_CSEL &&
5668                                 inst->opcode != BRW_OPCODE_IF &&
5669                                 inst->opcode != BRW_OPCODE_WHILE))) {
5670          fprintf(file, ".f%d.%d", inst->flag_subreg / 2,
5671                  inst->flag_subreg % 2);
5672       }
5673    }
5674    fprintf(file, "(%d) ", inst->exec_size);
5675 
5676    if (inst->mlen) {
5677       fprintf(file, "(mlen: %d) ", inst->mlen);
5678    }
5679 
5680    if (inst->ex_mlen) {
5681       fprintf(file, "(ex_mlen: %d) ", inst->ex_mlen);
5682    }
5683 
5684    if (inst->eot) {
5685       fprintf(file, "(EOT) ");
5686    }
5687 
5688    switch (inst->dst.file) {
5689    case VGRF:
5690       fprintf(file, "vgrf%d", inst->dst.nr);
5691       break;
5692    case FIXED_GRF:
5693       fprintf(file, "g%d", inst->dst.nr);
5694       break;
5695    case MRF:
5696       fprintf(file, "m%d", inst->dst.nr);
5697       break;
5698    case BAD_FILE:
5699       fprintf(file, "(null)");
5700       break;
5701    case UNIFORM:
5702       fprintf(file, "***u%d***", inst->dst.nr);
5703       break;
5704    case ATTR:
5705       fprintf(file, "***attr%d***", inst->dst.nr);
5706       break;
5707    case ARF:
5708       switch (inst->dst.nr) {
5709       case BRW_ARF_NULL:
5710          fprintf(file, "null");
5711          break;
5712       case BRW_ARF_ADDRESS:
5713          fprintf(file, "a0.%d", inst->dst.subnr);
5714          break;
5715       case BRW_ARF_ACCUMULATOR:
5716          fprintf(file, "acc%d", inst->dst.subnr);
5717          break;
5718       case BRW_ARF_FLAG:
5719          fprintf(file, "f%d.%d", inst->dst.nr & 0xf, inst->dst.subnr);
5720          break;
5721       default:
5722          fprintf(file, "arf%d.%d", inst->dst.nr & 0xf, inst->dst.subnr);
5723          break;
5724       }
5725       break;
5726    case IMM:
5727       unreachable("not reached");
5728    }
5729 
5730    if (inst->dst.offset ||
5731        (inst->dst.file == VGRF &&
5732         alloc.sizes[inst->dst.nr] * REG_SIZE != inst->size_written)) {
5733       const unsigned reg_size = (inst->dst.file == UNIFORM ? 4 : REG_SIZE);
5734       fprintf(file, "+%d.%d", inst->dst.offset / reg_size,
5735               inst->dst.offset % reg_size);
5736    }
5737 
5738    if (inst->dst.stride != 1)
5739       fprintf(file, "<%u>", inst->dst.stride);
5740    fprintf(file, ":%s, ", brw_reg_type_to_letters(inst->dst.type));
5741 
5742    for (int i = 0; i < inst->sources; i++) {
5743       if (inst->src[i].negate)
5744          fprintf(file, "-");
5745       if (inst->src[i].abs)
5746          fprintf(file, "|");
5747       switch (inst->src[i].file) {
5748       case VGRF:
5749          fprintf(file, "vgrf%d", inst->src[i].nr);
5750          break;
5751       case FIXED_GRF:
5752          fprintf(file, "g%d", inst->src[i].nr);
5753          break;
5754       case MRF:
5755          fprintf(file, "***m%d***", inst->src[i].nr);
5756          break;
5757       case ATTR:
5758          fprintf(file, "attr%d", inst->src[i].nr);
5759          break;
5760       case UNIFORM:
5761          fprintf(file, "u%d", inst->src[i].nr);
5762          break;
5763       case BAD_FILE:
5764          fprintf(file, "(null)");
5765          break;
5766       case IMM:
5767          switch (inst->src[i].type) {
5768          case BRW_REGISTER_TYPE_HF:
5769             fprintf(file, "%-ghf", _mesa_half_to_float(inst->src[i].ud & 0xffff));
5770             break;
5771          case BRW_REGISTER_TYPE_F:
5772             fprintf(file, "%-gf", inst->src[i].f);
5773             break;
5774          case BRW_REGISTER_TYPE_DF:
5775             fprintf(file, "%fdf", inst->src[i].df);
5776             break;
5777          case BRW_REGISTER_TYPE_W:
5778          case BRW_REGISTER_TYPE_D:
5779             fprintf(file, "%dd", inst->src[i].d);
5780             break;
5781          case BRW_REGISTER_TYPE_UW:
5782          case BRW_REGISTER_TYPE_UD:
5783             fprintf(file, "%uu", inst->src[i].ud);
5784             break;
5785          case BRW_REGISTER_TYPE_Q:
5786             fprintf(file, "%" PRId64 "q", inst->src[i].d64);
5787             break;
5788          case BRW_REGISTER_TYPE_UQ:
5789             fprintf(file, "%" PRIu64 "uq", inst->src[i].u64);
5790             break;
5791          case BRW_REGISTER_TYPE_VF:
5792             fprintf(file, "[%-gF, %-gF, %-gF, %-gF]",
5793                     brw_vf_to_float((inst->src[i].ud >>  0) & 0xff),
5794                     brw_vf_to_float((inst->src[i].ud >>  8) & 0xff),
5795                     brw_vf_to_float((inst->src[i].ud >> 16) & 0xff),
5796                     brw_vf_to_float((inst->src[i].ud >> 24) & 0xff));
5797             break;
5798          case BRW_REGISTER_TYPE_V:
5799          case BRW_REGISTER_TYPE_UV:
5800             fprintf(file, "%08x%s", inst->src[i].ud,
5801                     inst->src[i].type == BRW_REGISTER_TYPE_V ? "V" : "UV");
5802             break;
5803          default:
5804             fprintf(file, "???");
5805             break;
5806          }
5807          break;
5808       case ARF:
5809          switch (inst->src[i].nr) {
5810          case BRW_ARF_NULL:
5811             fprintf(file, "null");
5812             break;
5813          case BRW_ARF_ADDRESS:
5814             fprintf(file, "a0.%d", inst->src[i].subnr);
5815             break;
5816          case BRW_ARF_ACCUMULATOR:
5817             fprintf(file, "acc%d", inst->src[i].subnr);
5818             break;
5819          case BRW_ARF_FLAG:
5820             fprintf(file, "f%d.%d", inst->src[i].nr & 0xf, inst->src[i].subnr);
5821             break;
5822          default:
5823             fprintf(file, "arf%d.%d", inst->src[i].nr & 0xf, inst->src[i].subnr);
5824             break;
5825          }
5826          break;
5827       }
5828 
5829       if (inst->src[i].offset ||
5830           (inst->src[i].file == VGRF &&
5831            alloc.sizes[inst->src[i].nr] * REG_SIZE != inst->size_read(i))) {
5832          const unsigned reg_size = (inst->src[i].file == UNIFORM ? 4 : REG_SIZE);
5833          fprintf(file, "+%d.%d", inst->src[i].offset / reg_size,
5834                  inst->src[i].offset % reg_size);
5835       }
5836 
5837       if (inst->src[i].abs)
5838          fprintf(file, "|");
5839 
5840       if (inst->src[i].file != IMM) {
5841          unsigned stride;
5842          if (inst->src[i].file == ARF || inst->src[i].file == FIXED_GRF) {
5843             unsigned hstride = inst->src[i].hstride;
5844             stride = (hstride == 0 ? 0 : (1 << (hstride - 1)));
5845          } else {
5846             stride = inst->src[i].stride;
5847          }
5848          if (stride != 1)
5849             fprintf(file, "<%u>", stride);
5850 
5851          fprintf(file, ":%s", brw_reg_type_to_letters(inst->src[i].type));
5852       }
5853 
5854       if (i < inst->sources - 1 && inst->src[i + 1].file != BAD_FILE)
5855          fprintf(file, ", ");
5856    }
5857 
5858    fprintf(file, " ");
5859 
5860    if (inst->force_writemask_all)
5861       fprintf(file, "NoMask ");
5862 
5863    if (inst->exec_size != dispatch_width)
5864       fprintf(file, "group%d ", inst->group);
5865 
5866    fprintf(file, "\n");
5867 }
5868 
5869 void
setup_fs_payload_gfx6()5870 fs_visitor::setup_fs_payload_gfx6()
5871 {
5872    assert(stage == MESA_SHADER_FRAGMENT);
5873    struct brw_wm_prog_data *prog_data = brw_wm_prog_data(this->prog_data);
5874    const unsigned payload_width = MIN2(16, dispatch_width);
5875    assert(dispatch_width % payload_width == 0);
5876    assert(devinfo->ver >= 6);
5877 
5878    /* R0: PS thread payload header. */
5879    payload.num_regs++;
5880 
5881    for (unsigned j = 0; j < dispatch_width / payload_width; j++) {
5882       /* R1: masks, pixel X/Y coordinates. */
5883       payload.subspan_coord_reg[j] = payload.num_regs++;
5884    }
5885 
5886    for (unsigned j = 0; j < dispatch_width / payload_width; j++) {
5887       /* R3-26: barycentric interpolation coordinates.  These appear in the
5888        * same order that they appear in the brw_barycentric_mode enum.  Each
5889        * set of coordinates occupies 2 registers if dispatch width == 8 and 4
5890        * registers if dispatch width == 16.  Coordinates only appear if they
5891        * were enabled using the "Barycentric Interpolation Mode" bits in
5892        * WM_STATE.
5893        */
5894       for (int i = 0; i < BRW_BARYCENTRIC_MODE_COUNT; ++i) {
5895          if (prog_data->barycentric_interp_modes & (1 << i)) {
5896             payload.barycentric_coord_reg[i][j] = payload.num_regs;
5897             payload.num_regs += payload_width / 4;
5898          }
5899       }
5900 
5901       /* R27-28: interpolated depth if uses source depth */
5902       if (prog_data->uses_src_depth) {
5903          payload.source_depth_reg[j] = payload.num_regs;
5904          payload.num_regs += payload_width / 8;
5905       }
5906 
5907       /* R29-30: interpolated W set if GFX6_WM_USES_SOURCE_W. */
5908       if (prog_data->uses_src_w) {
5909          payload.source_w_reg[j] = payload.num_regs;
5910          payload.num_regs += payload_width / 8;
5911       }
5912 
5913       /* R31: MSAA position offsets. */
5914       if (prog_data->uses_pos_offset) {
5915          payload.sample_pos_reg[j] = payload.num_regs;
5916          payload.num_regs++;
5917       }
5918 
5919       /* R32-33: MSAA input coverage mask */
5920       if (prog_data->uses_sample_mask) {
5921          assert(devinfo->ver >= 7);
5922          payload.sample_mask_in_reg[j] = payload.num_regs;
5923          payload.num_regs += payload_width / 8;
5924       }
5925 
5926       /* R66: Source Depth and/or W Attribute Vertex Deltas */
5927       if (prog_data->uses_depth_w_coefficients) {
5928          payload.depth_w_coef_reg[j] = payload.num_regs;
5929          payload.num_regs++;
5930       }
5931    }
5932 
5933    if (nir->info.outputs_written & BITFIELD64_BIT(FRAG_RESULT_DEPTH)) {
5934       source_depth_to_render_target = true;
5935    }
5936 }
5937 
5938 void
setup_vs_payload()5939 fs_visitor::setup_vs_payload()
5940 {
5941    /* R0: thread header, R1: urb handles */
5942    payload.num_regs = 2;
5943 }
5944 
5945 void
setup_gs_payload()5946 fs_visitor::setup_gs_payload()
5947 {
5948    assert(stage == MESA_SHADER_GEOMETRY);
5949 
5950    struct brw_gs_prog_data *gs_prog_data = brw_gs_prog_data(prog_data);
5951    struct brw_vue_prog_data *vue_prog_data = brw_vue_prog_data(prog_data);
5952 
5953    /* R0: thread header, R1: output URB handles */
5954    payload.num_regs = 2;
5955 
5956    if (gs_prog_data->include_primitive_id) {
5957       /* R2: Primitive ID 0..7 */
5958       payload.num_regs++;
5959    }
5960 
5961    /* Always enable VUE handles so we can safely use pull model if needed.
5962     *
5963     * The push model for a GS uses a ton of register space even for trivial
5964     * scenarios with just a few inputs, so just make things easier and a bit
5965     * safer by always having pull model available.
5966     */
5967    gs_prog_data->base.include_vue_handles = true;
5968 
5969    /* R3..RN: ICP Handles for each incoming vertex (when using pull model) */
5970    payload.num_regs += nir->info.gs.vertices_in;
5971 
5972    /* Use a maximum of 24 registers for push-model inputs. */
5973    const unsigned max_push_components = 24;
5974 
5975    /* If pushing our inputs would take too many registers, reduce the URB read
5976     * length (which is in HWords, or 8 registers), and resort to pulling.
5977     *
5978     * Note that the GS reads <URB Read Length> HWords for every vertex - so we
5979     * have to multiply by VerticesIn to obtain the total storage requirement.
5980     */
5981    if (8 * vue_prog_data->urb_read_length * nir->info.gs.vertices_in >
5982        max_push_components) {
5983       vue_prog_data->urb_read_length =
5984          ROUND_DOWN_TO(max_push_components / nir->info.gs.vertices_in, 8) / 8;
5985    }
5986 }
5987 
5988 void
setup_cs_payload()5989 fs_visitor::setup_cs_payload()
5990 {
5991    assert(devinfo->ver >= 7);
5992    /* TODO: Fill out uses_btd_stack_ids automatically */
5993    payload.num_regs = 1 + brw_cs_prog_data(prog_data)->uses_btd_stack_ids;
5994 }
5995 
register_pressure(const fs_visitor * v)5996 brw::register_pressure::register_pressure(const fs_visitor *v)
5997 {
5998    const fs_live_variables &live = v->live_analysis.require();
5999    const unsigned num_instructions = v->cfg->num_blocks ?
6000       v->cfg->blocks[v->cfg->num_blocks - 1]->end_ip + 1 : 0;
6001 
6002    regs_live_at_ip = new unsigned[num_instructions]();
6003 
6004    for (unsigned reg = 0; reg < v->alloc.count; reg++) {
6005       for (int ip = live.vgrf_start[reg]; ip <= live.vgrf_end[reg]; ip++)
6006          regs_live_at_ip[ip] += v->alloc.sizes[reg];
6007    }
6008 }
6009 
~register_pressure()6010 brw::register_pressure::~register_pressure()
6011 {
6012    delete[] regs_live_at_ip;
6013 }
6014 
6015 void
invalidate_analysis(brw::analysis_dependency_class c)6016 fs_visitor::invalidate_analysis(brw::analysis_dependency_class c)
6017 {
6018    backend_shader::invalidate_analysis(c);
6019    live_analysis.invalidate(c);
6020    regpressure_analysis.invalidate(c);
6021 }
6022 
6023 void
optimize()6024 fs_visitor::optimize()
6025 {
6026    /* Start by validating the shader we currently have. */
6027    validate();
6028 
6029    /* bld is the common builder object pointing at the end of the program we
6030     * used to translate it into i965 IR.  For the optimization and lowering
6031     * passes coming next, any code added after the end of the program without
6032     * having explicitly called fs_builder::at() clearly points at a mistake.
6033     * Ideally optimization passes wouldn't be part of the visitor so they
6034     * wouldn't have access to bld at all, but they do, so just in case some
6035     * pass forgets to ask for a location explicitly set it to NULL here to
6036     * make it trip.  The dispatch width is initialized to a bogus value to
6037     * make sure that optimizations set the execution controls explicitly to
6038     * match the code they are manipulating instead of relying on the defaults.
6039     */
6040    bld = fs_builder(this, 64);
6041 
6042    assign_constant_locations();
6043    lower_constant_loads();
6044 
6045    validate();
6046 
6047 #define OPT(pass, args...) ({                                           \
6048       pass_num++;                                                       \
6049       bool this_progress = pass(args);                                  \
6050                                                                         \
6051       if (INTEL_DEBUG(DEBUG_OPTIMIZER) && this_progress) {              \
6052          char filename[64];                                             \
6053          snprintf(filename, 64, "%s%d-%s-%02d-%02d-" #pass,              \
6054                   stage_abbrev, dispatch_width, nir->info.name, iteration, pass_num); \
6055                                                                         \
6056          backend_shader::dump_instructions(filename);                   \
6057       }                                                                 \
6058                                                                         \
6059       validate();                                                       \
6060                                                                         \
6061       progress = progress || this_progress;                             \
6062       this_progress;                                                    \
6063    })
6064 
6065    if (INTEL_DEBUG(DEBUG_OPTIMIZER)) {
6066       char filename[64];
6067       snprintf(filename, 64, "%s%d-%s-00-00-start",
6068                stage_abbrev, dispatch_width, nir->info.name);
6069 
6070       backend_shader::dump_instructions(filename);
6071    }
6072 
6073    bool progress = false;
6074    int iteration = 0;
6075    int pass_num = 0;
6076 
6077    OPT(split_virtual_grfs);
6078 
6079    /* Before anything else, eliminate dead code.  The results of some NIR
6080     * instructions may effectively be calculated twice.  Once when the
6081     * instruction is encountered, and again when the user of that result is
6082     * encountered.  Wipe those away before algebraic optimizations and
6083     * especially copy propagation can mix things up.
6084     */
6085    OPT(dead_code_eliminate);
6086 
6087    OPT(remove_extra_rounding_modes);
6088 
6089    do {
6090       progress = false;
6091       pass_num = 0;
6092       iteration++;
6093 
6094       OPT(remove_duplicate_mrf_writes);
6095 
6096       OPT(opt_algebraic);
6097       OPT(opt_cse);
6098       OPT(opt_copy_propagation);
6099       OPT(opt_predicated_break, this);
6100       OPT(opt_cmod_propagation);
6101       OPT(dead_code_eliminate);
6102       OPT(opt_peephole_sel);
6103       OPT(dead_control_flow_eliminate, this);
6104       OPT(opt_register_renaming);
6105       OPT(opt_saturate_propagation);
6106       OPT(register_coalesce);
6107       OPT(compute_to_mrf);
6108       OPT(eliminate_find_live_channel);
6109 
6110       OPT(compact_virtual_grfs);
6111    } while (progress);
6112 
6113    progress = false;
6114    pass_num = 0;
6115 
6116    if (OPT(lower_pack)) {
6117       OPT(register_coalesce);
6118       OPT(dead_code_eliminate);
6119    }
6120 
6121    OPT(lower_simd_width);
6122    OPT(lower_barycentrics);
6123    OPT(lower_logical_sends);
6124 
6125    /* After logical SEND lowering. */
6126    OPT(opt_copy_propagation);
6127    OPT(opt_split_sends);
6128    OPT(fixup_nomask_control_flow);
6129 
6130    if (progress) {
6131       OPT(opt_copy_propagation);
6132       /* Only run after logical send lowering because it's easier to implement
6133        * in terms of physical sends.
6134        */
6135       if (OPT(opt_zero_samples))
6136          OPT(opt_copy_propagation);
6137       /* Run after logical send lowering to give it a chance to CSE the
6138        * LOAD_PAYLOAD instructions created to construct the payloads of
6139        * e.g. texturing messages in cases where it wasn't possible to CSE the
6140        * whole logical instruction.
6141        */
6142       OPT(opt_cse);
6143       OPT(register_coalesce);
6144       OPT(compute_to_mrf);
6145       OPT(dead_code_eliminate);
6146       OPT(remove_duplicate_mrf_writes);
6147       OPT(opt_peephole_sel);
6148    }
6149 
6150    OPT(opt_redundant_halt);
6151 
6152    if (OPT(lower_load_payload)) {
6153       OPT(split_virtual_grfs);
6154 
6155       /* Lower 64 bit MOVs generated by payload lowering. */
6156       if (!devinfo->has_64bit_float || !devinfo->has_64bit_int)
6157          OPT(opt_algebraic);
6158 
6159       OPT(register_coalesce);
6160       OPT(lower_simd_width);
6161       OPT(compute_to_mrf);
6162       OPT(dead_code_eliminate);
6163    }
6164 
6165    OPT(opt_combine_constants);
6166    if (OPT(lower_integer_multiplication)) {
6167       /* If lower_integer_multiplication made progress, it may have produced
6168        * some 32x32-bit MULs in the process of lowering 64-bit MULs.  Run it
6169        * one more time to clean those up if they exist.
6170        */
6171       OPT(lower_integer_multiplication);
6172    }
6173    OPT(lower_sub_sat);
6174 
6175    if (devinfo->ver <= 5 && OPT(lower_minmax)) {
6176       OPT(opt_cmod_propagation);
6177       OPT(opt_cse);
6178       OPT(opt_copy_propagation);
6179       OPT(dead_code_eliminate);
6180    }
6181 
6182    progress = false;
6183    OPT(lower_derivatives);
6184    OPT(lower_regioning);
6185    if (progress) {
6186       OPT(opt_copy_propagation);
6187       OPT(dead_code_eliminate);
6188       OPT(lower_simd_width);
6189    }
6190 
6191    OPT(fixup_sends_duplicate_payload);
6192 
6193    lower_uniform_pull_constant_loads();
6194 
6195    lower_find_live_channel();
6196 
6197    validate();
6198 }
6199 
6200 /**
6201  * From the Skylake PRM Vol. 2a docs for sends:
6202  *
6203  *    "It is required that the second block of GRFs does not overlap with the
6204  *    first block."
6205  *
6206  * There are plenty of cases where we may accidentally violate this due to
6207  * having, for instance, both sources be the constant 0.  This little pass
6208  * just adds a new vgrf for the second payload and copies it over.
6209  */
6210 bool
fixup_sends_duplicate_payload()6211 fs_visitor::fixup_sends_duplicate_payload()
6212 {
6213    bool progress = false;
6214 
6215    foreach_block_and_inst_safe (block, fs_inst, inst, cfg) {
6216       if (inst->opcode == SHADER_OPCODE_SEND && inst->ex_mlen > 0 &&
6217           regions_overlap(inst->src[2], inst->mlen * REG_SIZE,
6218                           inst->src[3], inst->ex_mlen * REG_SIZE)) {
6219          fs_reg tmp = fs_reg(VGRF, alloc.allocate(inst->ex_mlen),
6220                              BRW_REGISTER_TYPE_UD);
6221          /* Sadly, we've lost all notion of channels and bit sizes at this
6222           * point.  Just WE_all it.
6223           */
6224          const fs_builder ibld = bld.at(block, inst).exec_all().group(16, 0);
6225          fs_reg copy_src = retype(inst->src[3], BRW_REGISTER_TYPE_UD);
6226          fs_reg copy_dst = tmp;
6227          for (unsigned i = 0; i < inst->ex_mlen; i += 2) {
6228             if (inst->ex_mlen == i + 1) {
6229                /* Only one register left; do SIMD8 */
6230                ibld.group(8, 0).MOV(copy_dst, copy_src);
6231             } else {
6232                ibld.MOV(copy_dst, copy_src);
6233             }
6234             copy_src = offset(copy_src, ibld, 1);
6235             copy_dst = offset(copy_dst, ibld, 1);
6236          }
6237          inst->src[3] = tmp;
6238          progress = true;
6239       }
6240    }
6241 
6242    if (progress)
6243       invalidate_analysis(DEPENDENCY_INSTRUCTIONS | DEPENDENCY_VARIABLES);
6244 
6245    return progress;
6246 }
6247 
6248 /**
6249  * Three source instruction must have a GRF/MRF destination register.
6250  * ARF NULL is not allowed.  Fix that up by allocating a temporary GRF.
6251  */
6252 void
fixup_3src_null_dest()6253 fs_visitor::fixup_3src_null_dest()
6254 {
6255    bool progress = false;
6256 
6257    foreach_block_and_inst_safe (block, fs_inst, inst, cfg) {
6258       if (inst->is_3src(compiler) && inst->dst.is_null()) {
6259          inst->dst = fs_reg(VGRF, alloc.allocate(dispatch_width / 8),
6260                             inst->dst.type);
6261          progress = true;
6262       }
6263    }
6264 
6265    if (progress)
6266       invalidate_analysis(DEPENDENCY_INSTRUCTION_DETAIL |
6267                           DEPENDENCY_VARIABLES);
6268 }
6269 
6270 static bool
needs_dummy_fence(const intel_device_info * devinfo,fs_inst * inst)6271 needs_dummy_fence(const intel_device_info *devinfo, fs_inst *inst)
6272 {
6273    /* This workaround is about making sure that any instruction writing
6274     * through UGM has completed before we hit EOT.
6275     *
6276     * The workaround talks about UGM writes or atomic message but what is
6277     * important is anything that hasn't completed. Usually any SEND
6278     * instruction that has a destination register will be read by something
6279     * else so we don't need to care about those as they will be synchronized
6280     * by other parts of the shader or optimized away. What is left are
6281     * instructions that don't have a destination register.
6282     */
6283    if (inst->sfid != GFX12_SFID_UGM)
6284       return false;
6285 
6286    return inst->dst.file == BAD_FILE;
6287 }
6288 
6289 /* Wa_22013689345
6290  *
6291  * We need to emit UGM fence message before EOT, if shader has any UGM write
6292  * or atomic message.
6293  *
6294  * TODO/FINISHME: According to Curro we could avoid the fence in some cases.
6295  *                We probably need a better criteria in needs_dummy_fence().
6296  */
6297 void
emit_dummy_memory_fence_before_eot()6298 fs_visitor::emit_dummy_memory_fence_before_eot()
6299 {
6300    bool progress = false;
6301    bool has_ugm_write_or_atomic = false;
6302 
6303    if (!intel_device_info_is_dg2(devinfo))
6304       return;
6305 
6306    foreach_block_and_inst_safe (block, fs_inst, inst, cfg) {
6307       if (!inst->eot) {
6308          if (needs_dummy_fence(devinfo, inst))
6309             has_ugm_write_or_atomic = true;
6310          continue;
6311       }
6312 
6313       if (!has_ugm_write_or_atomic)
6314          break;
6315 
6316       const fs_builder ibld(this, block, inst);
6317       const fs_builder ubld = ibld.exec_all().group(1, 0);
6318 
6319       fs_reg dst = ubld.vgrf(BRW_REGISTER_TYPE_UD);
6320       fs_inst *dummy_fence = ubld.emit(SHADER_OPCODE_MEMORY_FENCE,
6321                                        dst, brw_vec8_grf(0, 0),
6322                                        /* commit enable */ brw_imm_ud(1),
6323                                        /* bti */ brw_imm_ud(0));
6324       dummy_fence->sfid = GFX12_SFID_UGM;
6325       dummy_fence->desc = lsc_fence_msg_desc(devinfo, LSC_FENCE_TILE,
6326                                              LSC_FLUSH_TYPE_NONE_6, false);
6327       ubld.emit(FS_OPCODE_SCHEDULING_FENCE, ubld.null_reg_ud(), dst);
6328       progress = true;
6329       /* TODO: remove this break if we ever have shader with multiple EOT. */
6330       break;
6331    }
6332 
6333    if (progress) {
6334       invalidate_analysis(DEPENDENCY_INSTRUCTIONS |
6335                           DEPENDENCY_VARIABLES);
6336    }
6337 }
6338 
6339 /**
6340  * Find the first instruction in the program that might start a region of
6341  * divergent control flow due to a HALT jump.  There is no
6342  * find_halt_control_flow_region_end(), the region of divergence extends until
6343  * the only SHADER_OPCODE_HALT_TARGET in the program.
6344  */
6345 static const fs_inst *
find_halt_control_flow_region_start(const fs_visitor * v)6346 find_halt_control_flow_region_start(const fs_visitor *v)
6347 {
6348    foreach_block_and_inst(block, fs_inst, inst, v->cfg) {
6349       if (inst->opcode == BRW_OPCODE_HALT ||
6350           inst->opcode == SHADER_OPCODE_HALT_TARGET)
6351          return inst;
6352    }
6353 
6354    return NULL;
6355 }
6356 
6357 /**
6358  * Work around the Gfx12 hardware bug filed as Wa_1407528679.  EU fusion
6359  * can cause a BB to be executed with all channels disabled, which will lead
6360  * to the execution of any NoMask instructions in it, even though any
6361  * execution-masked instructions will be correctly shot down.  This may break
6362  * assumptions of some NoMask SEND messages whose descriptor depends on data
6363  * generated by live invocations of the shader.
6364  *
6365  * This avoids the problem by predicating certain instructions on an ANY
6366  * horizontal predicate that makes sure that their execution is omitted when
6367  * all channels of the program are disabled.
6368  */
6369 bool
fixup_nomask_control_flow()6370 fs_visitor::fixup_nomask_control_flow()
6371 {
6372    if (devinfo->ver != 12)
6373       return false;
6374 
6375    const brw_predicate pred = dispatch_width > 16 ? BRW_PREDICATE_ALIGN1_ANY32H :
6376                               dispatch_width > 8 ? BRW_PREDICATE_ALIGN1_ANY16H :
6377                               BRW_PREDICATE_ALIGN1_ANY8H;
6378    const fs_inst *halt_start = find_halt_control_flow_region_start(this);
6379    unsigned depth = 0;
6380    bool progress = false;
6381 
6382    const fs_live_variables &live_vars = live_analysis.require();
6383 
6384    /* Scan the program backwards in order to be able to easily determine
6385     * whether the flag register is live at any point.
6386     */
6387    foreach_block_reverse_safe(block, cfg) {
6388       BITSET_WORD flag_liveout = live_vars.block_data[block->num]
6389                                                .flag_liveout[0];
6390       STATIC_ASSERT(ARRAY_SIZE(live_vars.block_data[0].flag_liveout) == 1);
6391 
6392       foreach_inst_in_block_reverse_safe(fs_inst, inst, block) {
6393          if (!inst->predicate && inst->exec_size >= 8)
6394             flag_liveout &= ~inst->flags_written(devinfo);
6395 
6396          switch (inst->opcode) {
6397          case BRW_OPCODE_DO:
6398          case BRW_OPCODE_IF:
6399             /* Note that this doesn't handle BRW_OPCODE_HALT since only
6400              * the first one in the program closes the region of divergent
6401              * control flow due to any HALT instructions -- Instead this is
6402              * handled with the halt_start check below.
6403              */
6404             depth--;
6405             break;
6406 
6407          case BRW_OPCODE_WHILE:
6408          case BRW_OPCODE_ENDIF:
6409          case SHADER_OPCODE_HALT_TARGET:
6410             depth++;
6411             break;
6412 
6413          default:
6414             /* Note that the vast majority of NoMask SEND instructions in the
6415              * program are harmless while executed in a block with all
6416              * channels disabled, since any instructions with side effects we
6417              * could hit here should be execution-masked.
6418              *
6419              * The main concern is NoMask SEND instructions where the message
6420              * descriptor or header depends on data generated by live
6421              * invocations of the shader (RESINFO and
6422              * FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD with a dynamically
6423              * computed surface index seem to be the only examples right now
6424              * where this could easily lead to GPU hangs).  Unfortunately we
6425              * have no straightforward way to detect that currently, so just
6426              * predicate any NoMask SEND instructions we find under control
6427              * flow.
6428              *
6429              * If this proves to have a measurable performance impact it can
6430              * be easily extended with a whitelist of messages we know we can
6431              * safely omit the predication for.
6432              */
6433             if (depth && inst->force_writemask_all &&
6434                 is_send(inst) && !inst->predicate) {
6435                /* We need to load the execution mask into the flag register by
6436                 * using a builder with channel group matching the whole shader
6437                 * (rather than the default which is derived from the original
6438                 * instruction), in order to avoid getting a right-shifted
6439                 * value.
6440                 */
6441                const fs_builder ubld = fs_builder(this, block, inst)
6442                                        .exec_all().group(dispatch_width, 0);
6443                const fs_reg flag = retype(brw_flag_reg(0, 0),
6444                                           BRW_REGISTER_TYPE_UD);
6445 
6446                /* Due to the lack of flag register allocation we need to save
6447                 * and restore the flag register if it's live.
6448                 */
6449                const bool save_flag = flag_liveout &
6450                                       flag_mask(flag, dispatch_width / 8);
6451                const fs_reg tmp = ubld.group(1, 0).vgrf(flag.type);
6452 
6453                if (save_flag)
6454                   ubld.group(1, 0).MOV(tmp, flag);
6455 
6456                ubld.emit(FS_OPCODE_LOAD_LIVE_CHANNELS);
6457 
6458                set_predicate(pred, inst);
6459                inst->flag_subreg = 0;
6460 
6461                if (save_flag)
6462                   ubld.group(1, 0).at(block, inst->next).MOV(flag, tmp);
6463 
6464                progress = true;
6465             }
6466             break;
6467          }
6468 
6469          if (inst == halt_start)
6470             depth--;
6471 
6472          flag_liveout |= inst->flags_read(devinfo);
6473       }
6474    }
6475 
6476    if (progress)
6477       invalidate_analysis(DEPENDENCY_INSTRUCTIONS | DEPENDENCY_VARIABLES);
6478 
6479    return progress;
6480 }
6481 
6482 void
allocate_registers(bool allow_spilling)6483 fs_visitor::allocate_registers(bool allow_spilling)
6484 {
6485    bool allocated;
6486 
6487    static const enum instruction_scheduler_mode pre_modes[] = {
6488       SCHEDULE_PRE,
6489       SCHEDULE_PRE_NON_LIFO,
6490       SCHEDULE_NONE,
6491       SCHEDULE_PRE_LIFO,
6492    };
6493 
6494    static const char *scheduler_mode_name[] = {
6495       "top-down",
6496       "non-lifo",
6497       "none",
6498       "lifo"
6499    };
6500 
6501    bool spill_all = allow_spilling && INTEL_DEBUG(DEBUG_SPILL_FS);
6502 
6503    /* Before we schedule anything, stash off the instruction order as an array
6504     * of fs_inst *.  This way, we can reset it between scheduling passes to
6505     * prevent dependencies between the different scheduling modes.
6506     */
6507    int num_insts = cfg->last_block()->end_ip + 1;
6508    fs_inst **inst_arr = ralloc_array(mem_ctx, fs_inst *, num_insts);
6509 
6510    int ip = 0;
6511    foreach_block_and_inst(block, fs_inst, inst, cfg) {
6512       assert(ip >= block->start_ip && ip <= block->end_ip);
6513       inst_arr[ip++] = inst;
6514    }
6515    assert(ip == num_insts);
6516 
6517    /* Try each scheduling heuristic to see if it can successfully register
6518     * allocate without spilling.  They should be ordered by decreasing
6519     * performance but increasing likelihood of allocating.
6520     */
6521    for (unsigned i = 0; i < ARRAY_SIZE(pre_modes); i++) {
6522       if (i > 0) {
6523          /* Unless we're the first pass, reset back to the original order */
6524          ip = 0;
6525          foreach_block (block, cfg) {
6526             block->instructions.make_empty();
6527 
6528             assert(ip == block->start_ip);
6529             for (; ip <= block->end_ip; ip++)
6530                block->instructions.push_tail(inst_arr[ip]);
6531          }
6532          assert(ip == num_insts);
6533 
6534          invalidate_analysis(DEPENDENCY_INSTRUCTIONS);
6535       }
6536 
6537       if (pre_modes[i] != SCHEDULE_NONE)
6538          schedule_instructions(pre_modes[i]);
6539       this->shader_stats.scheduler_mode = scheduler_mode_name[i];
6540 
6541       if (0) {
6542          assign_regs_trivial();
6543          allocated = true;
6544          break;
6545       }
6546 
6547       bool can_spill = allow_spilling &&
6548                        (i == ARRAY_SIZE(pre_modes) - 1);
6549 
6550       /* We should only spill registers on the last scheduling. */
6551       assert(!spilled_any_registers);
6552 
6553       allocated = assign_regs(can_spill, spill_all);
6554       if (allocated)
6555          break;
6556    }
6557 
6558    if (!allocated) {
6559       fail("Failure to register allocate.  Reduce number of "
6560            "live scalar values to avoid this.");
6561    } else if (spilled_any_registers) {
6562       brw_shader_perf_log(compiler, log_data,
6563                           "%s shader triggered register spilling.  "
6564                           "Try reducing the number of live scalar "
6565                           "values to improve performance.\n",
6566                           stage_name);
6567    }
6568 
6569    /* This must come after all optimization and register allocation, since
6570     * it inserts dead code that happens to have side effects, and it does
6571     * so based on the actual physical registers in use.
6572     */
6573    insert_gfx4_send_dependency_workarounds();
6574 
6575    if (failed)
6576       return;
6577 
6578    opt_bank_conflicts();
6579 
6580    schedule_instructions(SCHEDULE_POST);
6581 
6582    if (last_scratch > 0) {
6583       ASSERTED unsigned max_scratch_size = 2 * 1024 * 1024;
6584 
6585       /* Take the max of any previously compiled variant of the shader. In the
6586        * case of bindless shaders with return parts, this will also take the
6587        * max of all parts.
6588        */
6589       prog_data->total_scratch = MAX2(brw_get_scratch_size(last_scratch),
6590                                       prog_data->total_scratch);
6591 
6592       if (gl_shader_stage_is_compute(stage)) {
6593          if (devinfo->platform == INTEL_PLATFORM_HSW) {
6594             /* According to the MEDIA_VFE_STATE's "Per Thread Scratch Space"
6595              * field documentation, Haswell supports a minimum of 2kB of
6596              * scratch space for compute shaders, unlike every other stage
6597              * and platform.
6598              */
6599             prog_data->total_scratch = MAX2(prog_data->total_scratch, 2048);
6600          } else if (devinfo->ver <= 7) {
6601             /* According to the MEDIA_VFE_STATE's "Per Thread Scratch Space"
6602              * field documentation, platforms prior to Haswell measure scratch
6603              * size linearly with a range of [1kB, 12kB] and 1kB granularity.
6604              */
6605             prog_data->total_scratch = ALIGN(last_scratch, 1024);
6606             max_scratch_size = 12 * 1024;
6607          }
6608       }
6609 
6610       /* We currently only support up to 2MB of scratch space.  If we
6611        * need to support more eventually, the documentation suggests
6612        * that we could allocate a larger buffer, and partition it out
6613        * ourselves.  We'd just have to undo the hardware's address
6614        * calculation by subtracting (FFTID * Per Thread Scratch Space)
6615        * and then add FFTID * (Larger Per Thread Scratch Space).
6616        *
6617        * See 3D-Media-GPGPU Engine > Media GPGPU Pipeline >
6618        * Thread Group Tracking > Local Memory/Scratch Space.
6619        */
6620       assert(prog_data->total_scratch < max_scratch_size);
6621    }
6622 
6623    lower_scoreboard();
6624 }
6625 
6626 bool
run_vs()6627 fs_visitor::run_vs()
6628 {
6629    assert(stage == MESA_SHADER_VERTEX);
6630 
6631    setup_vs_payload();
6632 
6633    emit_nir_code();
6634 
6635    if (failed)
6636       return false;
6637 
6638    emit_urb_writes();
6639 
6640    calculate_cfg();
6641 
6642    optimize();
6643 
6644    assign_curb_setup();
6645    assign_vs_urb_setup();
6646 
6647    fixup_3src_null_dest();
6648    emit_dummy_memory_fence_before_eot();
6649    allocate_registers(true /* allow_spilling */);
6650 
6651    return !failed;
6652 }
6653 
6654 void
set_tcs_invocation_id()6655 fs_visitor::set_tcs_invocation_id()
6656 {
6657    struct brw_tcs_prog_data *tcs_prog_data = brw_tcs_prog_data(prog_data);
6658    struct brw_vue_prog_data *vue_prog_data = &tcs_prog_data->base;
6659 
6660    const bool dg2_plus =
6661       devinfo->ver > 12 || intel_device_info_is_dg2(devinfo);
6662    const unsigned instance_id_mask =
6663       dg2_plus ? INTEL_MASK(7, 0) :
6664       (devinfo->ver >= 11) ? INTEL_MASK(22, 16) : INTEL_MASK(23, 17);
6665    const unsigned instance_id_shift =
6666       dg2_plus ? 0 : (devinfo->ver >= 11) ? 16 : 17;
6667 
6668    /* Get instance number from g0.2 bits:
6669     *  * 7:0 on DG2+
6670     *  * 22:16 on gfx11+
6671     *  * 23:17 otherwise
6672     */
6673    fs_reg t = bld.vgrf(BRW_REGISTER_TYPE_UD);
6674    bld.AND(t, fs_reg(retype(brw_vec1_grf(0, 2), BRW_REGISTER_TYPE_UD)),
6675            brw_imm_ud(instance_id_mask));
6676 
6677    invocation_id = bld.vgrf(BRW_REGISTER_TYPE_UD);
6678 
6679    if (vue_prog_data->dispatch_mode == DISPATCH_MODE_TCS_8_PATCH) {
6680       /* gl_InvocationID is just the thread number */
6681       bld.SHR(invocation_id, t, brw_imm_ud(instance_id_shift));
6682       return;
6683    }
6684 
6685    assert(vue_prog_data->dispatch_mode == DISPATCH_MODE_TCS_SINGLE_PATCH);
6686 
6687    fs_reg channels_uw = bld.vgrf(BRW_REGISTER_TYPE_UW);
6688    fs_reg channels_ud = bld.vgrf(BRW_REGISTER_TYPE_UD);
6689    bld.MOV(channels_uw, fs_reg(brw_imm_uv(0x76543210)));
6690    bld.MOV(channels_ud, channels_uw);
6691 
6692    if (tcs_prog_data->instances == 1) {
6693       invocation_id = channels_ud;
6694    } else {
6695       fs_reg instance_times_8 = bld.vgrf(BRW_REGISTER_TYPE_UD);
6696       bld.SHR(instance_times_8, t, brw_imm_ud(instance_id_shift - 3));
6697       bld.ADD(invocation_id, instance_times_8, channels_ud);
6698    }
6699 }
6700 
6701 bool
run_tcs()6702 fs_visitor::run_tcs()
6703 {
6704    assert(stage == MESA_SHADER_TESS_CTRL);
6705 
6706    struct brw_vue_prog_data *vue_prog_data = brw_vue_prog_data(prog_data);
6707    struct brw_tcs_prog_data *tcs_prog_data = brw_tcs_prog_data(prog_data);
6708    struct brw_tcs_prog_key *tcs_key = (struct brw_tcs_prog_key *) key;
6709 
6710    assert(vue_prog_data->dispatch_mode == DISPATCH_MODE_TCS_SINGLE_PATCH ||
6711           vue_prog_data->dispatch_mode == DISPATCH_MODE_TCS_8_PATCH);
6712 
6713    if (vue_prog_data->dispatch_mode == DISPATCH_MODE_TCS_SINGLE_PATCH) {
6714       /* r1-r4 contain the ICP handles. */
6715       payload.num_regs = 5;
6716    } else {
6717       assert(vue_prog_data->dispatch_mode == DISPATCH_MODE_TCS_8_PATCH);
6718       assert(tcs_key->input_vertices > 0);
6719       /* r1 contains output handles, r2 may contain primitive ID, then the
6720        * ICP handles occupy the next 1-32 registers.
6721        */
6722       payload.num_regs = 2 + tcs_prog_data->include_primitive_id +
6723                          tcs_key->input_vertices;
6724    }
6725 
6726    /* Initialize gl_InvocationID */
6727    set_tcs_invocation_id();
6728 
6729    const bool fix_dispatch_mask =
6730       vue_prog_data->dispatch_mode == DISPATCH_MODE_TCS_SINGLE_PATCH &&
6731       (nir->info.tess.tcs_vertices_out % 8) != 0;
6732 
6733    /* Fix the disptach mask */
6734    if (fix_dispatch_mask) {
6735       bld.CMP(bld.null_reg_ud(), invocation_id,
6736               brw_imm_ud(nir->info.tess.tcs_vertices_out), BRW_CONDITIONAL_L);
6737       bld.IF(BRW_PREDICATE_NORMAL);
6738    }
6739 
6740    emit_nir_code();
6741 
6742    if (fix_dispatch_mask) {
6743       bld.emit(BRW_OPCODE_ENDIF);
6744    }
6745 
6746    /* Emit EOT write; set TR DS Cache bit */
6747    fs_reg srcs[URB_LOGICAL_NUM_SRCS];
6748    srcs[URB_LOGICAL_SRC_HANDLE] = get_tcs_output_urb_handle();
6749    srcs[URB_LOGICAL_SRC_CHANNEL_MASK] = brw_imm_ud(WRITEMASK_X << 16);
6750    srcs[URB_LOGICAL_SRC_DATA] = brw_imm_ud(0);
6751    fs_inst *inst = bld.emit(SHADER_OPCODE_URB_WRITE_LOGICAL,
6752                             reg_undef, srcs, ARRAY_SIZE(srcs));
6753    inst->mlen = 3;
6754    inst->eot = true;
6755 
6756    if (failed)
6757       return false;
6758 
6759    calculate_cfg();
6760 
6761    optimize();
6762 
6763    assign_curb_setup();
6764    assign_tcs_urb_setup();
6765 
6766    fixup_3src_null_dest();
6767    emit_dummy_memory_fence_before_eot();
6768    allocate_registers(true /* allow_spilling */);
6769 
6770    return !failed;
6771 }
6772 
6773 bool
run_tes()6774 fs_visitor::run_tes()
6775 {
6776    assert(stage == MESA_SHADER_TESS_EVAL);
6777 
6778    /* R0: thread header, R1-3: gl_TessCoord.xyz, R4: URB handles */
6779    payload.num_regs = 5;
6780 
6781    emit_nir_code();
6782 
6783    if (failed)
6784       return false;
6785 
6786    emit_urb_writes();
6787 
6788    calculate_cfg();
6789 
6790    optimize();
6791 
6792    assign_curb_setup();
6793    assign_tes_urb_setup();
6794 
6795    fixup_3src_null_dest();
6796    emit_dummy_memory_fence_before_eot();
6797    allocate_registers(true /* allow_spilling */);
6798 
6799    return !failed;
6800 }
6801 
6802 bool
run_gs()6803 fs_visitor::run_gs()
6804 {
6805    assert(stage == MESA_SHADER_GEOMETRY);
6806 
6807    setup_gs_payload();
6808 
6809    this->final_gs_vertex_count = vgrf(glsl_type::uint_type);
6810 
6811    if (gs_compile->control_data_header_size_bits > 0) {
6812       /* Create a VGRF to store accumulated control data bits. */
6813       this->control_data_bits = vgrf(glsl_type::uint_type);
6814 
6815       /* If we're outputting more than 32 control data bits, then EmitVertex()
6816        * will set control_data_bits to 0 after emitting the first vertex.
6817        * Otherwise, we need to initialize it to 0 here.
6818        */
6819       if (gs_compile->control_data_header_size_bits <= 32) {
6820          const fs_builder abld = bld.annotate("initialize control data bits");
6821          abld.MOV(this->control_data_bits, brw_imm_ud(0u));
6822       }
6823    }
6824 
6825    emit_nir_code();
6826 
6827    emit_gs_thread_end();
6828 
6829    if (failed)
6830       return false;
6831 
6832    calculate_cfg();
6833 
6834    optimize();
6835 
6836    assign_curb_setup();
6837    assign_gs_urb_setup();
6838 
6839    fixup_3src_null_dest();
6840    emit_dummy_memory_fence_before_eot();
6841    allocate_registers(true /* allow_spilling */);
6842 
6843    return !failed;
6844 }
6845 
6846 /* From the SKL PRM, Volume 16, Workarounds:
6847  *
6848  *   0877  3D   Pixel Shader Hang possible when pixel shader dispatched with
6849  *              only header phases (R0-R2)
6850  *
6851  *   WA: Enable a non-header phase (e.g. push constant) when dispatch would
6852  *       have been header only.
6853  *
6854  * Instead of enabling push constants one can alternatively enable one of the
6855  * inputs. Here one simply chooses "layer" which shouldn't impose much
6856  * overhead.
6857  */
6858 static void
gfx9_ps_header_only_workaround(struct brw_wm_prog_data * wm_prog_data)6859 gfx9_ps_header_only_workaround(struct brw_wm_prog_data *wm_prog_data)
6860 {
6861    if (wm_prog_data->num_varying_inputs)
6862       return;
6863 
6864    if (wm_prog_data->base.curb_read_length)
6865       return;
6866 
6867    wm_prog_data->urb_setup[VARYING_SLOT_LAYER] = 0;
6868    wm_prog_data->num_varying_inputs = 1;
6869 
6870    brw_compute_urb_setup_index(wm_prog_data);
6871 }
6872 
6873 bool
run_fs(bool allow_spilling,bool do_rep_send)6874 fs_visitor::run_fs(bool allow_spilling, bool do_rep_send)
6875 {
6876    struct brw_wm_prog_data *wm_prog_data = brw_wm_prog_data(this->prog_data);
6877    brw_wm_prog_key *wm_key = (brw_wm_prog_key *) this->key;
6878 
6879    assert(stage == MESA_SHADER_FRAGMENT);
6880 
6881    if (devinfo->ver >= 6)
6882       setup_fs_payload_gfx6();
6883    else
6884       setup_fs_payload_gfx4();
6885 
6886    if (0) {
6887       emit_dummy_fs();
6888    } else if (do_rep_send) {
6889       assert(dispatch_width == 16);
6890       emit_repclear_shader();
6891    } else {
6892       if (nir->info.inputs_read > 0 ||
6893           BITSET_TEST(nir->info.system_values_read, SYSTEM_VALUE_FRAG_COORD) ||
6894           (nir->info.outputs_read > 0 && !wm_key->coherent_fb_fetch)) {
6895          if (devinfo->ver < 6)
6896             emit_interpolation_setup_gfx4();
6897          else
6898             emit_interpolation_setup_gfx6();
6899       }
6900 
6901       /* We handle discards by keeping track of the still-live pixels in f0.1.
6902        * Initialize it with the dispatched pixels.
6903        */
6904       if (wm_prog_data->uses_kill) {
6905          const unsigned lower_width = MIN2(dispatch_width, 16);
6906          for (unsigned i = 0; i < dispatch_width / lower_width; i++) {
6907             const fs_reg dispatch_mask =
6908                devinfo->ver >= 6 ? brw_vec1_grf((i ? 2 : 1), 7) :
6909                brw_vec1_grf(0, 0);
6910             bld.exec_all().group(1, 0)
6911                .MOV(brw_sample_mask_reg(bld.group(lower_width, i)),
6912                     retype(dispatch_mask, BRW_REGISTER_TYPE_UW));
6913          }
6914       }
6915 
6916       if (nir->info.writes_memory)
6917          wm_prog_data->has_side_effects = true;
6918 
6919       emit_nir_code();
6920 
6921       if (failed)
6922 	 return false;
6923 
6924       if (wm_key->emit_alpha_test)
6925          emit_alpha_test();
6926 
6927       emit_fb_writes();
6928 
6929       calculate_cfg();
6930 
6931       optimize();
6932 
6933       assign_curb_setup();
6934 
6935       if (devinfo->ver == 9)
6936          gfx9_ps_header_only_workaround(wm_prog_data);
6937 
6938       assign_urb_setup();
6939 
6940       fixup_3src_null_dest();
6941       emit_dummy_memory_fence_before_eot();
6942 
6943       allocate_registers(allow_spilling);
6944    }
6945 
6946    return !failed;
6947 }
6948 
6949 bool
run_cs(bool allow_spilling)6950 fs_visitor::run_cs(bool allow_spilling)
6951 {
6952    assert(gl_shader_stage_is_compute(stage));
6953 
6954    setup_cs_payload();
6955 
6956    if (devinfo->platform == INTEL_PLATFORM_HSW && prog_data->total_shared > 0) {
6957       /* Move SLM index from g0.0[27:24] to sr0.1[11:8] */
6958       const fs_builder abld = bld.exec_all().group(1, 0);
6959       abld.MOV(retype(brw_sr0_reg(1), BRW_REGISTER_TYPE_UW),
6960                suboffset(retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_UW), 1));
6961    }
6962 
6963    emit_nir_code();
6964 
6965    if (failed)
6966       return false;
6967 
6968    emit_cs_terminate();
6969 
6970    calculate_cfg();
6971 
6972    optimize();
6973 
6974    assign_curb_setup();
6975 
6976    fixup_3src_null_dest();
6977    emit_dummy_memory_fence_before_eot();
6978    allocate_registers(allow_spilling);
6979 
6980    return !failed;
6981 }
6982 
6983 bool
run_bs(bool allow_spilling)6984 fs_visitor::run_bs(bool allow_spilling)
6985 {
6986    assert(stage >= MESA_SHADER_RAYGEN && stage <= MESA_SHADER_CALLABLE);
6987 
6988    /* R0: thread header, R1: stack IDs, R2: argument addresses */
6989    payload.num_regs = 3;
6990 
6991    emit_nir_code();
6992 
6993    if (failed)
6994       return false;
6995 
6996    /* TODO(RT): Perhaps rename this? */
6997    emit_cs_terminate();
6998 
6999    calculate_cfg();
7000 
7001    optimize();
7002 
7003    assign_curb_setup();
7004 
7005    fixup_3src_null_dest();
7006    emit_dummy_memory_fence_before_eot();
7007    allocate_registers(allow_spilling);
7008 
7009    return !failed;
7010 }
7011 
7012 bool
run_task(bool allow_spilling)7013 fs_visitor::run_task(bool allow_spilling)
7014 {
7015    assert(stage == MESA_SHADER_TASK);
7016 
7017    /* Task Shader Payloads (SIMD8 and SIMD16)
7018     *
7019     *  R0: Header
7020     *  R1: Local_ID.X[0-7 or 0-15]
7021     *  R2: Inline Parameter
7022     *
7023     * Task Shader Payloads (SIMD32)
7024     *
7025     *  R0: Header
7026     *  R1: Local_ID.X[0-15]
7027     *  R2: Local_ID.X[16-31]
7028     *  R3: Inline Parameter
7029     *
7030     * Local_ID.X values are 16 bits.
7031     *
7032     * Inline parameter is optional but always present since we use it to pass
7033     * the address to descriptors.
7034     */
7035    payload.num_regs = dispatch_width == 32 ? 4 : 3;
7036 
7037    emit_nir_code();
7038 
7039    if (failed)
7040       return false;
7041 
7042    emit_urb_fence();
7043 
7044    emit_cs_terminate();
7045 
7046    calculate_cfg();
7047 
7048    optimize();
7049 
7050    assign_curb_setup();
7051 
7052    fixup_3src_null_dest();
7053    emit_dummy_memory_fence_before_eot();
7054    allocate_registers(allow_spilling);
7055 
7056    return !failed;
7057 }
7058 
7059 bool
run_mesh(bool allow_spilling)7060 fs_visitor::run_mesh(bool allow_spilling)
7061 {
7062    assert(stage == MESA_SHADER_MESH);
7063 
7064    /* Mesh Shader Payloads (SIMD8 and SIMD16)
7065     *
7066     *  R0: Header
7067     *  R1: Local_ID.X[0-7 or 0-15]
7068     *  R2: Inline Parameter
7069     *
7070     * Mesh Shader Payloads (SIMD32)
7071     *
7072     *  R0: Header
7073     *  R1: Local_ID.X[0-15]
7074     *  R2: Local_ID.X[16-31]
7075     *  R3: Inline Parameter
7076     *
7077     * Local_ID.X values are 16 bits.
7078     *
7079     * Inline parameter is optional but always present since we use it to pass
7080     * the address to descriptors.
7081     */
7082    payload.num_regs = dispatch_width == 32 ? 4 : 3;
7083 
7084    emit_nir_code();
7085 
7086    if (failed)
7087       return false;
7088 
7089    emit_urb_fence();
7090 
7091    emit_cs_terminate();
7092 
7093    calculate_cfg();
7094 
7095    optimize();
7096 
7097    assign_curb_setup();
7098 
7099    fixup_3src_null_dest();
7100    emit_dummy_memory_fence_before_eot();
7101    allocate_registers(allow_spilling);
7102 
7103    return !failed;
7104 }
7105 
7106 static bool
is_used_in_not_interp_frag_coord(nir_ssa_def * def)7107 is_used_in_not_interp_frag_coord(nir_ssa_def *def)
7108 {
7109    nir_foreach_use(src, def) {
7110       if (src->parent_instr->type != nir_instr_type_intrinsic)
7111          return true;
7112 
7113       nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(src->parent_instr);
7114       if (intrin->intrinsic != nir_intrinsic_load_frag_coord)
7115          return true;
7116    }
7117 
7118    nir_foreach_if_use(src, def)
7119       return true;
7120 
7121    return false;
7122 }
7123 
7124 /**
7125  * Return a bitfield where bit n is set if barycentric interpolation mode n
7126  * (see enum brw_barycentric_mode) is needed by the fragment shader.
7127  *
7128  * We examine the load_barycentric intrinsics rather than looking at input
7129  * variables so that we catch interpolateAtCentroid() messages too, which
7130  * also need the BRW_BARYCENTRIC_[NON]PERSPECTIVE_CENTROID mode set up.
7131  */
7132 static unsigned
brw_compute_barycentric_interp_modes(const struct intel_device_info * devinfo,const nir_shader * shader)7133 brw_compute_barycentric_interp_modes(const struct intel_device_info *devinfo,
7134                                      const nir_shader *shader)
7135 {
7136    unsigned barycentric_interp_modes = 0;
7137 
7138    nir_foreach_function(f, shader) {
7139       if (!f->impl)
7140          continue;
7141 
7142       nir_foreach_block(block, f->impl) {
7143          nir_foreach_instr(instr, block) {
7144             if (instr->type != nir_instr_type_intrinsic)
7145                continue;
7146 
7147             nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
7148             switch (intrin->intrinsic) {
7149             case nir_intrinsic_load_barycentric_pixel:
7150             case nir_intrinsic_load_barycentric_centroid:
7151             case nir_intrinsic_load_barycentric_sample:
7152                break;
7153             default:
7154                continue;
7155             }
7156 
7157             /* Ignore WPOS; it doesn't require interpolation. */
7158             assert(intrin->dest.is_ssa);
7159             if (!is_used_in_not_interp_frag_coord(&intrin->dest.ssa))
7160                continue;
7161 
7162             nir_intrinsic_op bary_op = intrin->intrinsic;
7163             enum brw_barycentric_mode bary =
7164                brw_barycentric_mode(intrin);
7165 
7166             barycentric_interp_modes |= 1 << bary;
7167 
7168             if (devinfo->needs_unlit_centroid_workaround &&
7169                 bary_op == nir_intrinsic_load_barycentric_centroid)
7170                barycentric_interp_modes |= 1 << centroid_to_pixel(bary);
7171          }
7172       }
7173    }
7174 
7175    return barycentric_interp_modes;
7176 }
7177 
7178 static void
brw_compute_flat_inputs(struct brw_wm_prog_data * prog_data,const nir_shader * shader)7179 brw_compute_flat_inputs(struct brw_wm_prog_data *prog_data,
7180                         const nir_shader *shader)
7181 {
7182    prog_data->flat_inputs = 0;
7183 
7184    nir_foreach_shader_in_variable(var, shader) {
7185       /* flat shading */
7186       if (var->data.interpolation != INTERP_MODE_FLAT)
7187          continue;
7188 
7189       if (var->data.per_primitive)
7190          continue;
7191 
7192       unsigned slots = glsl_count_attribute_slots(var->type, false);
7193       for (unsigned s = 0; s < slots; s++) {
7194          int input_index = prog_data->urb_setup[var->data.location + s];
7195 
7196          if (input_index >= 0)
7197             prog_data->flat_inputs |= 1 << input_index;
7198       }
7199    }
7200 }
7201 
7202 static uint8_t
computed_depth_mode(const nir_shader * shader)7203 computed_depth_mode(const nir_shader *shader)
7204 {
7205    if (shader->info.outputs_written & BITFIELD64_BIT(FRAG_RESULT_DEPTH)) {
7206       switch (shader->info.fs.depth_layout) {
7207       case FRAG_DEPTH_LAYOUT_NONE:
7208       case FRAG_DEPTH_LAYOUT_ANY:
7209          return BRW_PSCDEPTH_ON;
7210       case FRAG_DEPTH_LAYOUT_GREATER:
7211          return BRW_PSCDEPTH_ON_GE;
7212       case FRAG_DEPTH_LAYOUT_LESS:
7213          return BRW_PSCDEPTH_ON_LE;
7214       case FRAG_DEPTH_LAYOUT_UNCHANGED:
7215          return BRW_PSCDEPTH_OFF;
7216       }
7217    }
7218    return BRW_PSCDEPTH_OFF;
7219 }
7220 
7221 /**
7222  * Move load_interpolated_input with simple (payload-based) barycentric modes
7223  * to the top of the program so we don't emit multiple PLNs for the same input.
7224  *
7225  * This works around CSE not being able to handle non-dominating cases
7226  * such as:
7227  *
7228  *    if (...) {
7229  *       interpolate input
7230  *    } else {
7231  *       interpolate the same exact input
7232  *    }
7233  *
7234  * This should be replaced by global value numbering someday.
7235  */
7236 bool
brw_nir_move_interpolation_to_top(nir_shader * nir)7237 brw_nir_move_interpolation_to_top(nir_shader *nir)
7238 {
7239    bool progress = false;
7240 
7241    nir_foreach_function(f, nir) {
7242       if (!f->impl)
7243          continue;
7244 
7245       nir_block *top = nir_start_block(f->impl);
7246       exec_node *cursor_node = NULL;
7247 
7248       nir_foreach_block(block, f->impl) {
7249          if (block == top)
7250             continue;
7251 
7252          nir_foreach_instr_safe(instr, block) {
7253             if (instr->type != nir_instr_type_intrinsic)
7254                continue;
7255 
7256             nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
7257             if (intrin->intrinsic != nir_intrinsic_load_interpolated_input)
7258                continue;
7259             nir_intrinsic_instr *bary_intrinsic =
7260                nir_instr_as_intrinsic(intrin->src[0].ssa->parent_instr);
7261             nir_intrinsic_op op = bary_intrinsic->intrinsic;
7262 
7263             /* Leave interpolateAtSample/Offset() where they are. */
7264             if (op == nir_intrinsic_load_barycentric_at_sample ||
7265                 op == nir_intrinsic_load_barycentric_at_offset)
7266                continue;
7267 
7268             nir_instr *move[3] = {
7269                &bary_intrinsic->instr,
7270                intrin->src[1].ssa->parent_instr,
7271                instr
7272             };
7273 
7274             for (unsigned i = 0; i < ARRAY_SIZE(move); i++) {
7275                if (move[i]->block != top) {
7276                   move[i]->block = top;
7277                   exec_node_remove(&move[i]->node);
7278                   if (cursor_node) {
7279                      exec_node_insert_after(cursor_node, &move[i]->node);
7280                   } else {
7281                      exec_list_push_head(&top->instr_list, &move[i]->node);
7282                   }
7283                   cursor_node = &move[i]->node;
7284                   progress = true;
7285                }
7286             }
7287          }
7288       }
7289       nir_metadata_preserve(f->impl, nir_metadata_block_index |
7290                                      nir_metadata_dominance);
7291    }
7292 
7293    return progress;
7294 }
7295 
7296 static void
brw_nir_populate_wm_prog_data(const nir_shader * shader,const struct intel_device_info * devinfo,const struct brw_wm_prog_key * key,struct brw_wm_prog_data * prog_data,const struct brw_mue_map * mue_map)7297 brw_nir_populate_wm_prog_data(const nir_shader *shader,
7298                               const struct intel_device_info *devinfo,
7299                               const struct brw_wm_prog_key *key,
7300                               struct brw_wm_prog_data *prog_data,
7301                               const struct brw_mue_map *mue_map)
7302 {
7303    /* key->alpha_test_func means simulating alpha testing via discards,
7304     * so the shader definitely kills pixels.
7305     */
7306    prog_data->uses_kill = shader->info.fs.uses_discard ||
7307                           shader->info.fs.uses_demote ||
7308                           key->emit_alpha_test;
7309    prog_data->uses_omask = !key->ignore_sample_mask_out &&
7310       (shader->info.outputs_written & BITFIELD64_BIT(FRAG_RESULT_SAMPLE_MASK));
7311    prog_data->color_outputs_written = key->color_outputs_valid;
7312    prog_data->computed_depth_mode = computed_depth_mode(shader);
7313    prog_data->computed_stencil =
7314       shader->info.outputs_written & BITFIELD64_BIT(FRAG_RESULT_STENCIL);
7315 
7316    prog_data->persample_dispatch =
7317       key->multisample_fbo &&
7318       (key->persample_interp ||
7319        shader->info.fs.uses_sample_shading);
7320 
7321    if (devinfo->ver >= 6) {
7322       prog_data->uses_sample_mask =
7323          BITSET_TEST(shader->info.system_values_read, SYSTEM_VALUE_SAMPLE_MASK_IN);
7324 
7325       /* From the Ivy Bridge PRM documentation for 3DSTATE_PS:
7326        *
7327        *    "MSDISPMODE_PERSAMPLE is required in order to select
7328        *    POSOFFSET_SAMPLE"
7329        *
7330        * So we can only really get sample positions if we are doing real
7331        * per-sample dispatch.  If we need gl_SamplePosition and we don't have
7332        * persample dispatch, we hard-code it to 0.5.
7333        */
7334       prog_data->uses_pos_offset = prog_data->persample_dispatch &&
7335          (BITSET_TEST(shader->info.system_values_read,
7336                       SYSTEM_VALUE_SAMPLE_POS) ||
7337           BITSET_TEST(shader->info.system_values_read,
7338                       SYSTEM_VALUE_SAMPLE_POS_OR_CENTER));
7339    }
7340 
7341    prog_data->has_render_target_reads = shader->info.outputs_read != 0ull;
7342 
7343    prog_data->early_fragment_tests = shader->info.fs.early_fragment_tests;
7344    prog_data->post_depth_coverage = shader->info.fs.post_depth_coverage;
7345    prog_data->inner_coverage = shader->info.fs.inner_coverage;
7346 
7347    prog_data->barycentric_interp_modes =
7348       brw_compute_barycentric_interp_modes(devinfo, shader);
7349    prog_data->uses_nonperspective_interp_modes |=
7350       (prog_data->barycentric_interp_modes &
7351       BRW_BARYCENTRIC_NONPERSPECTIVE_BITS) != 0;
7352 
7353    /* You can't be coarse and per-sample */
7354    assert(!key->coarse_pixel || !key->persample_interp);
7355    prog_data->per_coarse_pixel_dispatch =
7356       key->coarse_pixel &&
7357       !shader->info.fs.uses_sample_shading &&
7358       !prog_data->uses_omask &&
7359       !prog_data->uses_sample_mask &&
7360       (prog_data->computed_depth_mode == BRW_PSCDEPTH_OFF) &&
7361       !prog_data->computed_stencil;
7362 
7363    /* We choose to always enable VMask prior to XeHP, as it would cause
7364     * us to lose out on the eliminate_find_live_channel() optimization.
7365     */
7366    prog_data->uses_vmask = devinfo->verx10 < 125 ||
7367                            shader->info.fs.needs_quad_helper_invocations ||
7368                            shader->info.fs.needs_all_helper_invocations ||
7369                            prog_data->per_coarse_pixel_dispatch;
7370 
7371    prog_data->uses_src_w =
7372       BITSET_TEST(shader->info.system_values_read, SYSTEM_VALUE_FRAG_COORD);
7373    prog_data->uses_src_depth =
7374       BITSET_TEST(shader->info.system_values_read, SYSTEM_VALUE_FRAG_COORD) &&
7375       !prog_data->per_coarse_pixel_dispatch;
7376    prog_data->uses_depth_w_coefficients =
7377       BITSET_TEST(shader->info.system_values_read, SYSTEM_VALUE_FRAG_COORD) &&
7378       prog_data->per_coarse_pixel_dispatch;
7379 
7380    calculate_urb_setup(devinfo, key, prog_data, shader, mue_map);
7381    brw_compute_flat_inputs(prog_data, shader);
7382 }
7383 
7384 /**
7385  * Pre-gfx6, the register file of the EUs was shared between threads,
7386  * and each thread used some subset allocated on a 16-register block
7387  * granularity.  The unit states wanted these block counts.
7388  */
7389 static inline int
brw_register_blocks(int reg_count)7390 brw_register_blocks(int reg_count)
7391 {
7392    return ALIGN(reg_count, 16) / 16 - 1;
7393 }
7394 
7395 const unsigned *
brw_compile_fs(const struct brw_compiler * compiler,void * mem_ctx,struct brw_compile_fs_params * params)7396 brw_compile_fs(const struct brw_compiler *compiler,
7397                void *mem_ctx,
7398                struct brw_compile_fs_params *params)
7399 {
7400    struct nir_shader *nir = params->nir;
7401    const struct brw_wm_prog_key *key = params->key;
7402    struct brw_wm_prog_data *prog_data = params->prog_data;
7403    bool allow_spilling = params->allow_spilling;
7404    const bool debug_enabled =
7405       INTEL_DEBUG(params->debug_flag ? params->debug_flag : DEBUG_WM);
7406 
7407    prog_data->base.stage = MESA_SHADER_FRAGMENT;
7408    prog_data->base.ray_queries = nir->info.ray_queries;
7409    prog_data->base.total_scratch = 0;
7410 
7411    const struct intel_device_info *devinfo = compiler->devinfo;
7412    const unsigned max_subgroup_size = compiler->devinfo->ver >= 6 ? 32 : 16;
7413 
7414    brw_nir_apply_key(nir, compiler, &key->base, max_subgroup_size, true);
7415    brw_nir_lower_fs_inputs(nir, devinfo, key);
7416    brw_nir_lower_fs_outputs(nir);
7417 
7418    if (devinfo->ver < 6)
7419       brw_setup_vue_interpolation(params->vue_map, nir, prog_data);
7420 
7421    /* From the SKL PRM, Volume 7, "Alpha Coverage":
7422     *  "If Pixel Shader outputs oMask, AlphaToCoverage is disabled in
7423     *   hardware, regardless of the state setting for this feature."
7424     */
7425    if (devinfo->ver > 6 && key->alpha_to_coverage) {
7426       /* Run constant fold optimization in order to get the correct source
7427        * offset to determine render target 0 store instruction in
7428        * emit_alpha_to_coverage pass.
7429        */
7430       NIR_PASS_V(nir, nir_opt_constant_folding);
7431       NIR_PASS_V(nir, brw_nir_lower_alpha_to_coverage);
7432    }
7433 
7434    NIR_PASS_V(nir, brw_nir_move_interpolation_to_top);
7435    brw_postprocess_nir(nir, compiler, true, debug_enabled,
7436                        key->base.robust_buffer_access);
7437 
7438    brw_nir_populate_wm_prog_data(nir, compiler->devinfo, key, prog_data,
7439                                  params->mue_map);
7440 
7441    fs_visitor *v8 = NULL, *v16 = NULL, *v32 = NULL;
7442    cfg_t *simd8_cfg = NULL, *simd16_cfg = NULL, *simd32_cfg = NULL;
7443    float throughput = 0;
7444    bool has_spilled = false;
7445 
7446    v8 = new fs_visitor(compiler, params->log_data, mem_ctx, &key->base,
7447                        &prog_data->base, nir, 8,
7448                        debug_enabled);
7449    if (!v8->run_fs(allow_spilling, false /* do_rep_send */)) {
7450       params->error_str = ralloc_strdup(mem_ctx, v8->fail_msg);
7451       delete v8;
7452       return NULL;
7453    } else if (!INTEL_DEBUG(DEBUG_NO8)) {
7454       simd8_cfg = v8->cfg;
7455       prog_data->base.dispatch_grf_start_reg = v8->payload.num_regs;
7456       prog_data->reg_blocks_8 = brw_register_blocks(v8->grf_used);
7457       const performance &perf = v8->performance_analysis.require();
7458       throughput = MAX2(throughput, perf.throughput);
7459       has_spilled = v8->spilled_any_registers;
7460       allow_spilling = false;
7461    }
7462 
7463    /* Limit dispatch width to simd8 with dual source blending on gfx8.
7464     * See: https://gitlab.freedesktop.org/mesa/mesa/-/issues/1917
7465     */
7466    if (devinfo->ver == 8 && prog_data->dual_src_blend &&
7467        !INTEL_DEBUG(DEBUG_NO8)) {
7468       assert(!params->use_rep_send);
7469       v8->limit_dispatch_width(8, "gfx8 workaround: "
7470                                "using SIMD8 when dual src blending.\n");
7471    }
7472 
7473    if (key->coarse_pixel) {
7474       if (prog_data->dual_src_blend) {
7475          v8->limit_dispatch_width(8, "SIMD16 coarse pixel shading cannot"
7476                                   " use SIMD8 messages.\n");
7477       }
7478       v8->limit_dispatch_width(16, "SIMD32 not supported with coarse"
7479                                " pixel shading.\n");
7480    }
7481 
7482    if (nir->info.ray_queries > 0)
7483       v8->limit_dispatch_width(16, "SIMD32 with ray queries.\n");
7484 
7485    if (!has_spilled &&
7486        v8->max_dispatch_width >= 16 &&
7487        (!INTEL_DEBUG(DEBUG_NO16) || params->use_rep_send)) {
7488       /* Try a SIMD16 compile */
7489       v16 = new fs_visitor(compiler, params->log_data, mem_ctx, &key->base,
7490                            &prog_data->base, nir, 16,
7491                            debug_enabled);
7492       v16->import_uniforms(v8);
7493       if (!v16->run_fs(allow_spilling, params->use_rep_send)) {
7494          brw_shader_perf_log(compiler, params->log_data,
7495                              "SIMD16 shader failed to compile: %s\n",
7496                              v16->fail_msg);
7497       } else {
7498          simd16_cfg = v16->cfg;
7499          prog_data->dispatch_grf_start_reg_16 = v16->payload.num_regs;
7500          prog_data->reg_blocks_16 = brw_register_blocks(v16->grf_used);
7501          const performance &perf = v16->performance_analysis.require();
7502          throughput = MAX2(throughput, perf.throughput);
7503          has_spilled = v16->spilled_any_registers;
7504          allow_spilling = false;
7505       }
7506    }
7507 
7508    const bool simd16_failed = v16 && !simd16_cfg;
7509 
7510    /* Currently, the compiler only supports SIMD32 on SNB+ */
7511    if (!has_spilled &&
7512        v8->max_dispatch_width >= 32 && !params->use_rep_send &&
7513        devinfo->ver >= 6 && !simd16_failed &&
7514        !INTEL_DEBUG(DEBUG_NO32)) {
7515       /* Try a SIMD32 compile */
7516       v32 = new fs_visitor(compiler, params->log_data, mem_ctx, &key->base,
7517                            &prog_data->base, nir, 32,
7518                            debug_enabled);
7519       v32->import_uniforms(v8);
7520       if (!v32->run_fs(allow_spilling, false)) {
7521          brw_shader_perf_log(compiler, params->log_data,
7522                              "SIMD32 shader failed to compile: %s\n",
7523                              v32->fail_msg);
7524       } else {
7525          const performance &perf = v32->performance_analysis.require();
7526 
7527          if (!INTEL_DEBUG(DEBUG_DO32) && throughput >= perf.throughput) {
7528             brw_shader_perf_log(compiler, params->log_data,
7529                                 "SIMD32 shader inefficient\n");
7530          } else {
7531             simd32_cfg = v32->cfg;
7532             prog_data->dispatch_grf_start_reg_32 = v32->payload.num_regs;
7533             prog_data->reg_blocks_32 = brw_register_blocks(v32->grf_used);
7534             throughput = MAX2(throughput, perf.throughput);
7535          }
7536       }
7537    }
7538 
7539    /* When the caller requests a repclear shader, they want SIMD16-only */
7540    if (params->use_rep_send)
7541       simd8_cfg = NULL;
7542 
7543    /* Prior to Iron Lake, the PS had a single shader offset with a jump table
7544     * at the top to select the shader.  We've never implemented that.
7545     * Instead, we just give them exactly one shader and we pick the widest one
7546     * available.
7547     */
7548    if (compiler->devinfo->ver < 5) {
7549       if (simd32_cfg || simd16_cfg)
7550          simd8_cfg = NULL;
7551       if (simd32_cfg)
7552          simd16_cfg = NULL;
7553    }
7554 
7555    /* If computed depth is enabled SNB only allows SIMD8. */
7556    if (compiler->devinfo->ver == 6 &&
7557        prog_data->computed_depth_mode != BRW_PSCDEPTH_OFF)
7558       assert(simd16_cfg == NULL && simd32_cfg == NULL);
7559 
7560    if (compiler->devinfo->ver <= 5 && !simd8_cfg) {
7561       /* Iron lake and earlier only have one Dispatch GRF start field.  Make
7562        * the data available in the base prog data struct for convenience.
7563        */
7564       if (simd16_cfg) {
7565          prog_data->base.dispatch_grf_start_reg =
7566             prog_data->dispatch_grf_start_reg_16;
7567       } else if (simd32_cfg) {
7568          prog_data->base.dispatch_grf_start_reg =
7569             prog_data->dispatch_grf_start_reg_32;
7570       }
7571    }
7572 
7573    if (prog_data->persample_dispatch) {
7574       /* Starting with SandyBridge (where we first get MSAA), the different
7575        * pixel dispatch combinations are grouped into classifications A
7576        * through F (SNB PRM Vol. 2 Part 1 Section 7.7.1).  On most hardware
7577        * generations, the only configurations supporting persample dispatch
7578        * are those in which only one dispatch width is enabled.
7579        *
7580        * The Gfx12 hardware spec has a similar dispatch grouping table, but
7581        * the following conflicting restriction applies (from the page on
7582        * "Structure_3DSTATE_PS_BODY"), so we need to keep the SIMD16 shader:
7583        *
7584        *  "SIMD32 may only be enabled if SIMD16 or (dual)SIMD8 is also
7585        *   enabled."
7586        */
7587       if (simd32_cfg || simd16_cfg)
7588          simd8_cfg = NULL;
7589       if (simd32_cfg && devinfo->ver < 12)
7590          simd16_cfg = NULL;
7591    }
7592 
7593    fs_generator g(compiler, params->log_data, mem_ctx, &prog_data->base,
7594                   v8->runtime_check_aads_emit, MESA_SHADER_FRAGMENT);
7595 
7596    if (unlikely(debug_enabled)) {
7597       g.enable_debug(ralloc_asprintf(mem_ctx, "%s fragment shader %s",
7598                                      nir->info.label ?
7599                                         nir->info.label : "unnamed",
7600                                      nir->info.name));
7601    }
7602 
7603    struct brw_compile_stats *stats = params->stats;
7604 
7605    if (simd8_cfg) {
7606       prog_data->dispatch_8 = true;
7607       g.generate_code(simd8_cfg, 8, v8->shader_stats,
7608                       v8->performance_analysis.require(), stats);
7609       stats = stats ? stats + 1 : NULL;
7610    }
7611 
7612    if (simd16_cfg) {
7613       prog_data->dispatch_16 = true;
7614       prog_data->prog_offset_16 = g.generate_code(
7615          simd16_cfg, 16, v16->shader_stats,
7616          v16->performance_analysis.require(), stats);
7617       stats = stats ? stats + 1 : NULL;
7618    }
7619 
7620    if (simd32_cfg) {
7621       prog_data->dispatch_32 = true;
7622       prog_data->prog_offset_32 = g.generate_code(
7623          simd32_cfg, 32, v32->shader_stats,
7624          v32->performance_analysis.require(), stats);
7625       stats = stats ? stats + 1 : NULL;
7626    }
7627 
7628    g.add_const_data(nir->constant_data, nir->constant_data_size);
7629 
7630    delete v8;
7631    delete v16;
7632    delete v32;
7633 
7634    return g.get_assembly();
7635 }
7636 
7637 fs_reg
emit_work_group_id_setup()7638 fs_visitor::emit_work_group_id_setup()
7639 {
7640    assert(gl_shader_stage_uses_workgroup(stage));
7641 
7642    fs_reg id = bld.vgrf(BRW_REGISTER_TYPE_UD, 3);
7643 
7644    struct brw_reg r0_1(retype(brw_vec1_grf(0, 1), BRW_REGISTER_TYPE_UD));
7645    bld.MOV(id, r0_1);
7646 
7647    if (gl_shader_stage_is_compute(stage)) {
7648       struct brw_reg r0_6(retype(brw_vec1_grf(0, 6), BRW_REGISTER_TYPE_UD));
7649       struct brw_reg r0_7(retype(brw_vec1_grf(0, 7), BRW_REGISTER_TYPE_UD));
7650       bld.MOV(offset(id, bld, 1), r0_6);
7651       bld.MOV(offset(id, bld, 2), r0_7);
7652    } else {
7653       /* Task/Mesh have a single Workgroup ID dimension in the HW. */
7654       bld.MOV(offset(id, bld, 1), brw_imm_ud(0));
7655       bld.MOV(offset(id, bld, 2), brw_imm_ud(0));
7656    }
7657 
7658    return id;
7659 }
7660 
7661 unsigned
brw_cs_push_const_total_size(const struct brw_cs_prog_data * cs_prog_data,unsigned threads)7662 brw_cs_push_const_total_size(const struct brw_cs_prog_data *cs_prog_data,
7663                              unsigned threads)
7664 {
7665    assert(cs_prog_data->push.per_thread.size % REG_SIZE == 0);
7666    assert(cs_prog_data->push.cross_thread.size % REG_SIZE == 0);
7667    return cs_prog_data->push.per_thread.size * threads +
7668           cs_prog_data->push.cross_thread.size;
7669 }
7670 
7671 static void
fill_push_const_block_info(struct brw_push_const_block * block,unsigned dwords)7672 fill_push_const_block_info(struct brw_push_const_block *block, unsigned dwords)
7673 {
7674    block->dwords = dwords;
7675    block->regs = DIV_ROUND_UP(dwords, 8);
7676    block->size = block->regs * 32;
7677 }
7678 
7679 static void
cs_fill_push_const_info(const struct intel_device_info * devinfo,struct brw_cs_prog_data * cs_prog_data)7680 cs_fill_push_const_info(const struct intel_device_info *devinfo,
7681                         struct brw_cs_prog_data *cs_prog_data)
7682 {
7683    const struct brw_stage_prog_data *prog_data = &cs_prog_data->base;
7684    int subgroup_id_index = get_subgroup_id_param_index(devinfo, prog_data);
7685    bool cross_thread_supported = devinfo->verx10 >= 75;
7686 
7687    /* The thread ID should be stored in the last param dword */
7688    assert(subgroup_id_index == -1 ||
7689           subgroup_id_index == (int)prog_data->nr_params - 1);
7690 
7691    unsigned cross_thread_dwords, per_thread_dwords;
7692    if (!cross_thread_supported) {
7693       cross_thread_dwords = 0u;
7694       per_thread_dwords = prog_data->nr_params;
7695    } else if (subgroup_id_index >= 0) {
7696       /* Fill all but the last register with cross-thread payload */
7697       cross_thread_dwords = 8 * (subgroup_id_index / 8);
7698       per_thread_dwords = prog_data->nr_params - cross_thread_dwords;
7699       assert(per_thread_dwords > 0 && per_thread_dwords <= 8);
7700    } else {
7701       /* Fill all data using cross-thread payload */
7702       cross_thread_dwords = prog_data->nr_params;
7703       per_thread_dwords = 0u;
7704    }
7705 
7706    fill_push_const_block_info(&cs_prog_data->push.cross_thread, cross_thread_dwords);
7707    fill_push_const_block_info(&cs_prog_data->push.per_thread, per_thread_dwords);
7708 
7709    assert(cs_prog_data->push.cross_thread.dwords % 8 == 0 ||
7710           cs_prog_data->push.per_thread.size == 0);
7711    assert(cs_prog_data->push.cross_thread.dwords +
7712           cs_prog_data->push.per_thread.dwords ==
7713              prog_data->nr_params);
7714 }
7715 
7716 static bool
filter_simd(const nir_instr * instr,const void *)7717 filter_simd(const nir_instr *instr, const void * /* options */)
7718 {
7719    if (instr->type != nir_instr_type_intrinsic)
7720       return false;
7721 
7722    switch (nir_instr_as_intrinsic(instr)->intrinsic) {
7723    case nir_intrinsic_load_simd_width_intel:
7724    case nir_intrinsic_load_subgroup_id:
7725       return true;
7726 
7727    default:
7728       return false;
7729    }
7730 }
7731 
7732 static nir_ssa_def *
lower_simd(nir_builder * b,nir_instr * instr,void * options)7733 lower_simd(nir_builder *b, nir_instr *instr, void *options)
7734 {
7735    uintptr_t simd_width = (uintptr_t)options;
7736 
7737    switch (nir_instr_as_intrinsic(instr)->intrinsic) {
7738    case nir_intrinsic_load_simd_width_intel:
7739       return nir_imm_int(b, simd_width);
7740 
7741    case nir_intrinsic_load_subgroup_id:
7742       /* If the whole workgroup fits in one thread, we can lower subgroup_id
7743        * to a constant zero.
7744        */
7745       if (!b->shader->info.workgroup_size_variable) {
7746          unsigned local_workgroup_size = b->shader->info.workgroup_size[0] *
7747                                          b->shader->info.workgroup_size[1] *
7748                                          b->shader->info.workgroup_size[2];
7749          if (local_workgroup_size <= simd_width)
7750             return nir_imm_int(b, 0);
7751       }
7752       return NULL;
7753 
7754    default:
7755       return NULL;
7756    }
7757 }
7758 
7759 bool
brw_nir_lower_simd(nir_shader * nir,unsigned dispatch_width)7760 brw_nir_lower_simd(nir_shader *nir, unsigned dispatch_width)
7761 {
7762    return nir_shader_lower_instructions(nir, filter_simd, lower_simd,
7763                                  (void *)(uintptr_t)dispatch_width);
7764 }
7765 
7766 const unsigned *
brw_compile_cs(const struct brw_compiler * compiler,void * mem_ctx,struct brw_compile_cs_params * params)7767 brw_compile_cs(const struct brw_compiler *compiler,
7768                void *mem_ctx,
7769                struct brw_compile_cs_params *params)
7770 {
7771    const nir_shader *nir = params->nir;
7772    const struct brw_cs_prog_key *key = params->key;
7773    struct brw_cs_prog_data *prog_data = params->prog_data;
7774 
7775    const bool debug_enabled =
7776       INTEL_DEBUG(params->debug_flag ? params->debug_flag : DEBUG_CS);
7777 
7778    prog_data->base.stage = MESA_SHADER_COMPUTE;
7779    prog_data->base.total_shared = nir->info.shared_size;
7780    prog_data->base.ray_queries = nir->info.ray_queries;
7781    prog_data->base.total_scratch = 0;
7782 
7783    if (!nir->info.workgroup_size_variable) {
7784       prog_data->local_size[0] = nir->info.workgroup_size[0];
7785       prog_data->local_size[1] = nir->info.workgroup_size[1];
7786       prog_data->local_size[2] = nir->info.workgroup_size[2];
7787    }
7788 
7789    const unsigned required_dispatch_width =
7790       brw_required_dispatch_width(&nir->info);
7791 
7792    fs_visitor *v[3]     = {0};
7793    const char *error[3] = {0};
7794 
7795    for (unsigned simd = 0; simd < 3; simd++) {
7796       if (!brw_simd_should_compile(mem_ctx, simd, compiler->devinfo, prog_data,
7797                                    required_dispatch_width, &error[simd]))
7798          continue;
7799 
7800       const unsigned dispatch_width = 8u << simd;
7801 
7802       nir_shader *shader = nir_shader_clone(mem_ctx, nir);
7803       brw_nir_apply_key(shader, compiler, &key->base,
7804                         dispatch_width, true /* is_scalar */);
7805 
7806       NIR_PASS(_, shader, brw_nir_lower_simd, dispatch_width);
7807 
7808       /* Clean up after the local index and ID calculations. */
7809       NIR_PASS(_, shader, nir_opt_constant_folding);
7810       NIR_PASS(_, shader, nir_opt_dce);
7811 
7812       brw_postprocess_nir(shader, compiler, true, debug_enabled,
7813                           key->base.robust_buffer_access);
7814 
7815       v[simd] = new fs_visitor(compiler, params->log_data, mem_ctx, &key->base,
7816                                &prog_data->base, shader, dispatch_width,
7817                                debug_enabled);
7818 
7819       if (prog_data->prog_mask) {
7820          unsigned first = ffs(prog_data->prog_mask) - 1;
7821          v[simd]->import_uniforms(v[first]);
7822       }
7823 
7824       const bool allow_spilling = !prog_data->prog_mask ||
7825                                   nir->info.workgroup_size_variable;
7826 
7827       if (v[simd]->run_cs(allow_spilling)) {
7828          /* We should always be able to do SIMD32 for compute shaders. */
7829          assert(v[simd]->max_dispatch_width >= 32);
7830 
7831          cs_fill_push_const_info(compiler->devinfo, prog_data);
7832 
7833          brw_simd_mark_compiled(simd, prog_data, v[simd]->spilled_any_registers);
7834       } else {
7835          error[simd] = ralloc_strdup(mem_ctx, v[simd]->fail_msg);
7836          if (simd > 0) {
7837             brw_shader_perf_log(compiler, params->log_data,
7838                                 "SIMD%u shader failed to compile: %s\n",
7839                                 dispatch_width, v[simd]->fail_msg);
7840          }
7841       }
7842    }
7843 
7844    const int selected_simd = brw_simd_select(prog_data);
7845    if (selected_simd < 0) {
7846       params->error_str = ralloc_asprintf(mem_ctx, "Can't compile shader: %s, %s and %s.\n",
7847                                           error[0], error[1], error[2]);;
7848       return NULL;
7849    }
7850 
7851    assert(selected_simd < 3);
7852    fs_visitor *selected = v[selected_simd];
7853 
7854    if (!nir->info.workgroup_size_variable)
7855       prog_data->prog_mask = 1 << selected_simd;
7856 
7857    const unsigned *ret = NULL;
7858 
7859    fs_generator g(compiler, params->log_data, mem_ctx, &prog_data->base,
7860                   selected->runtime_check_aads_emit, MESA_SHADER_COMPUTE);
7861    if (unlikely(debug_enabled)) {
7862       char *name = ralloc_asprintf(mem_ctx, "%s compute shader %s",
7863                                    nir->info.label ?
7864                                    nir->info.label : "unnamed",
7865                                    nir->info.name);
7866       g.enable_debug(name);
7867    }
7868 
7869    struct brw_compile_stats *stats = params->stats;
7870    for (unsigned simd = 0; simd < 3; simd++) {
7871       if (prog_data->prog_mask & (1u << simd)) {
7872          assert(v[simd]);
7873          prog_data->prog_offset[simd] =
7874             g.generate_code(v[simd]->cfg, 8u << simd, v[simd]->shader_stats,
7875                             v[simd]->performance_analysis.require(), stats);
7876          stats = stats ? stats + 1 : NULL;
7877       }
7878    }
7879 
7880    g.add_const_data(nir->constant_data, nir->constant_data_size);
7881 
7882    ret = g.get_assembly();
7883 
7884    delete v[0];
7885    delete v[1];
7886    delete v[2];
7887 
7888    return ret;
7889 }
7890 
7891 struct brw_cs_dispatch_info
brw_cs_get_dispatch_info(const struct intel_device_info * devinfo,const struct brw_cs_prog_data * prog_data,const unsigned * override_local_size)7892 brw_cs_get_dispatch_info(const struct intel_device_info *devinfo,
7893                          const struct brw_cs_prog_data *prog_data,
7894                          const unsigned *override_local_size)
7895 {
7896    struct brw_cs_dispatch_info info = {};
7897 
7898    const unsigned *sizes =
7899       override_local_size ? override_local_size :
7900                             prog_data->local_size;
7901 
7902    const int simd =
7903       override_local_size ? brw_simd_select_for_workgroup_size(devinfo, prog_data, sizes) :
7904                             brw_simd_select(prog_data);
7905    assert(simd >= 0 && simd < 3);
7906 
7907    info.group_size = sizes[0] * sizes[1] * sizes[2];
7908    info.simd_size = 8u << simd;
7909    info.threads = DIV_ROUND_UP(info.group_size, info.simd_size);
7910 
7911    const uint32_t remainder = info.group_size & (info.simd_size - 1);
7912    if (remainder > 0)
7913       info.right_mask = ~0u >> (32 - remainder);
7914    else
7915       info.right_mask = ~0u >> (32 - info.simd_size);
7916 
7917    return info;
7918 }
7919 
7920 static uint8_t
compile_single_bs(const struct brw_compiler * compiler,void * log_data,void * mem_ctx,const struct brw_bs_prog_key * key,struct brw_bs_prog_data * prog_data,nir_shader * shader,fs_generator * g,struct brw_compile_stats * stats,int * prog_offset,char ** error_str)7921 compile_single_bs(const struct brw_compiler *compiler, void *log_data,
7922                   void *mem_ctx,
7923                   const struct brw_bs_prog_key *key,
7924                   struct brw_bs_prog_data *prog_data,
7925                   nir_shader *shader,
7926                   fs_generator *g,
7927                   struct brw_compile_stats *stats,
7928                   int *prog_offset,
7929                   char **error_str)
7930 {
7931    const bool debug_enabled = INTEL_DEBUG(DEBUG_RT);
7932 
7933    prog_data->base.stage = shader->info.stage;
7934    prog_data->max_stack_size = MAX2(prog_data->max_stack_size,
7935                                     shader->scratch_size);
7936 
7937    const unsigned max_dispatch_width = 16;
7938    brw_nir_apply_key(shader, compiler, &key->base, max_dispatch_width, true);
7939    brw_postprocess_nir(shader, compiler, true, debug_enabled,
7940                        key->base.robust_buffer_access);
7941 
7942    fs_visitor *v = NULL, *v8 = NULL, *v16 = NULL;
7943    bool has_spilled = false;
7944 
7945    uint8_t simd_size = 0;
7946    if (!INTEL_DEBUG(DEBUG_NO8)) {
7947       v8 = new fs_visitor(compiler, log_data, mem_ctx, &key->base,
7948                           &prog_data->base, shader,
7949                           8, debug_enabled);
7950       const bool allow_spilling = true;
7951       if (!v8->run_bs(allow_spilling)) {
7952          if (error_str)
7953             *error_str = ralloc_strdup(mem_ctx, v8->fail_msg);
7954          delete v8;
7955          return 0;
7956       } else {
7957          v = v8;
7958          simd_size = 8;
7959          if (v8->spilled_any_registers)
7960             has_spilled = true;
7961       }
7962    }
7963 
7964    if (!has_spilled && !INTEL_DEBUG(DEBUG_NO16)) {
7965       v16 = new fs_visitor(compiler, log_data, mem_ctx, &key->base,
7966                            &prog_data->base, shader,
7967                            16, debug_enabled);
7968       const bool allow_spilling = (v == NULL);
7969       if (!v16->run_bs(allow_spilling)) {
7970          brw_shader_perf_log(compiler, log_data,
7971                              "SIMD16 shader failed to compile: %s\n",
7972                              v16->fail_msg);
7973          if (v == NULL) {
7974             assert(v8 == NULL);
7975             if (error_str) {
7976                *error_str = ralloc_asprintf(
7977                   mem_ctx, "SIMD8 disabled and couldn't generate SIMD16: %s",
7978                   v16->fail_msg);
7979             }
7980             delete v16;
7981             return 0;
7982          }
7983       } else {
7984          v = v16;
7985          simd_size = 16;
7986          if (v16->spilled_any_registers)
7987             has_spilled = true;
7988       }
7989    }
7990 
7991    if (unlikely(v == NULL)) {
7992       assert(INTEL_DEBUG(DEBUG_NO8 | DEBUG_NO16));
7993       if (error_str) {
7994          *error_str = ralloc_strdup(mem_ctx,
7995             "Cannot satisfy INTEL_DEBUG flags SIMD restrictions");
7996       }
7997       return false;
7998    }
7999 
8000    assert(v);
8001 
8002    int offset = g->generate_code(v->cfg, simd_size, v->shader_stats,
8003                                  v->performance_analysis.require(), stats);
8004    if (prog_offset)
8005       *prog_offset = offset;
8006    else
8007       assert(offset == 0);
8008 
8009    delete v8;
8010    delete v16;
8011 
8012    return simd_size;
8013 }
8014 
8015 uint64_t
brw_bsr(const struct intel_device_info * devinfo,uint32_t offset,uint8_t simd_size,uint8_t local_arg_offset)8016 brw_bsr(const struct intel_device_info *devinfo,
8017         uint32_t offset, uint8_t simd_size, uint8_t local_arg_offset)
8018 {
8019    assert(offset % 64 == 0);
8020    assert(simd_size == 8 || simd_size == 16);
8021    assert(local_arg_offset % 8 == 0);
8022 
8023    return offset |
8024           SET_BITS(simd_size == 8, 4, 4) |
8025           SET_BITS(local_arg_offset / 8, 2, 0);
8026 }
8027 
8028 const unsigned *
brw_compile_bs(const struct brw_compiler * compiler,void * mem_ctx,struct brw_compile_bs_params * params)8029 brw_compile_bs(const struct brw_compiler *compiler,
8030                void *mem_ctx,
8031                struct brw_compile_bs_params *params)
8032 {
8033    nir_shader *shader = params->nir;
8034    struct brw_bs_prog_data *prog_data = params->prog_data;
8035    unsigned num_resume_shaders = params->num_resume_shaders;
8036    nir_shader **resume_shaders = params->resume_shaders;
8037    const bool debug_enabled = INTEL_DEBUG(DEBUG_RT);
8038 
8039    prog_data->base.stage = shader->info.stage;
8040    prog_data->base.ray_queries = shader->info.ray_queries;
8041    prog_data->base.total_scratch = 0;
8042 
8043    prog_data->max_stack_size = 0;
8044 
8045    fs_generator g(compiler, params->log_data, mem_ctx, &prog_data->base,
8046                   false, shader->info.stage);
8047    if (unlikely(debug_enabled)) {
8048       char *name = ralloc_asprintf(mem_ctx, "%s %s shader %s",
8049                                    shader->info.label ?
8050                                       shader->info.label : "unnamed",
8051                                    gl_shader_stage_name(shader->info.stage),
8052                                    shader->info.name);
8053       g.enable_debug(name);
8054    }
8055 
8056    prog_data->simd_size =
8057       compile_single_bs(compiler, params->log_data, mem_ctx,
8058                         params->key, prog_data,
8059                         shader, &g, params->stats, NULL, &params->error_str);
8060    if (prog_data->simd_size == 0)
8061       return NULL;
8062 
8063    uint64_t *resume_sbt = ralloc_array(mem_ctx, uint64_t, num_resume_shaders);
8064    for (unsigned i = 0; i < num_resume_shaders; i++) {
8065       if (INTEL_DEBUG(DEBUG_RT)) {
8066          char *name = ralloc_asprintf(mem_ctx, "%s %s resume(%u) shader %s",
8067                                       shader->info.label ?
8068                                          shader->info.label : "unnamed",
8069                                       gl_shader_stage_name(shader->info.stage),
8070                                       i, shader->info.name);
8071          g.enable_debug(name);
8072       }
8073 
8074       /* TODO: Figure out shader stats etc. for resume shaders */
8075       int offset = 0;
8076       uint8_t simd_size =
8077          compile_single_bs(compiler, params->log_data, mem_ctx, params->key,
8078                            prog_data, resume_shaders[i], &g, NULL, &offset,
8079                            &params->error_str);
8080       if (simd_size == 0)
8081          return NULL;
8082 
8083       assert(offset > 0);
8084       resume_sbt[i] = brw_bsr(compiler->devinfo, offset, simd_size, 0);
8085    }
8086 
8087    /* We only have one constant data so we want to make sure they're all the
8088     * same.
8089     */
8090    for (unsigned i = 0; i < num_resume_shaders; i++) {
8091       assert(resume_shaders[i]->constant_data_size ==
8092              shader->constant_data_size);
8093       assert(memcmp(resume_shaders[i]->constant_data,
8094                     shader->constant_data,
8095                     shader->constant_data_size) == 0);
8096    }
8097 
8098    g.add_const_data(shader->constant_data, shader->constant_data_size);
8099    g.add_resume_sbt(num_resume_shaders, resume_sbt);
8100 
8101    return g.get_assembly();
8102 }
8103 
8104 /**
8105  * Test the dispatch mask packing assumptions of
8106  * brw_stage_has_packed_dispatch().  Call this from e.g. the top of
8107  * fs_visitor::emit_nir_code() to cause a GPU hang if any shader invocation is
8108  * executed with an unexpected dispatch mask.
8109  */
8110 static UNUSED void
brw_fs_test_dispatch_packing(const fs_builder & bld)8111 brw_fs_test_dispatch_packing(const fs_builder &bld)
8112 {
8113    const gl_shader_stage stage = bld.shader->stage;
8114    const bool uses_vmask =
8115       stage == MESA_SHADER_FRAGMENT &&
8116       brw_wm_prog_data(bld.shader->stage_prog_data)->uses_vmask;
8117 
8118    if (brw_stage_has_packed_dispatch(bld.shader->devinfo, stage,
8119                                      bld.shader->stage_prog_data)) {
8120       const fs_builder ubld = bld.exec_all().group(1, 0);
8121       const fs_reg tmp = component(bld.vgrf(BRW_REGISTER_TYPE_UD), 0);
8122       const fs_reg mask = uses_vmask ? brw_vmask_reg() : brw_dmask_reg();
8123 
8124       ubld.ADD(tmp, mask, brw_imm_ud(1));
8125       ubld.AND(tmp, mask, tmp);
8126 
8127       /* This will loop forever if the dispatch mask doesn't have the expected
8128        * form '2^n-1', in which case tmp will be non-zero.
8129        */
8130       bld.emit(BRW_OPCODE_DO);
8131       bld.CMP(bld.null_reg_ud(), tmp, brw_imm_ud(0), BRW_CONDITIONAL_NZ);
8132       set_predicate(BRW_PREDICATE_NORMAL, bld.emit(BRW_OPCODE_WHILE));
8133    }
8134 }
8135 
8136 unsigned
workgroup_size() const8137 fs_visitor::workgroup_size() const
8138 {
8139    assert(gl_shader_stage_uses_workgroup(stage));
8140    const struct brw_cs_prog_data *cs = brw_cs_prog_data(prog_data);
8141    return cs->local_size[0] * cs->local_size[1] * cs->local_size[2];
8142 }
8143