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 "dev/intel_debug.h"
40 #include "compiler/glsl_types.h"
41 #include "compiler/nir/nir_builder.h"
42 #include "program/prog_parameter.h"
43 #include "util/u_math.h"
44 
45 using namespace brw;
46 
47 static unsigned get_lowered_simd_width(const struct intel_device_info *devinfo,
48                                        const fs_inst *inst);
49 
50 void
init(enum opcode opcode,uint8_t exec_size,const fs_reg & dst,const fs_reg * src,unsigned sources)51 fs_inst::init(enum opcode opcode, uint8_t exec_size, const fs_reg &dst,
52               const fs_reg *src, unsigned sources)
53 {
54    memset((void*)this, 0, sizeof(*this));
55 
56    this->src = new fs_reg[MAX2(sources, 3)];
57    for (unsigned i = 0; i < sources; i++)
58       this->src[i] = src[i];
59 
60    this->opcode = opcode;
61    this->dst = dst;
62    this->sources = sources;
63    this->exec_size = exec_size;
64    this->base_mrf = -1;
65 
66    assert(dst.file != IMM && dst.file != UNIFORM);
67 
68    assert(this->exec_size != 0);
69 
70    this->conditional_mod = BRW_CONDITIONAL_NONE;
71 
72    /* This will be the case for almost all instructions. */
73    switch (dst.file) {
74    case VGRF:
75    case ARF:
76    case FIXED_GRF:
77    case MRF:
78    case ATTR:
79       this->size_written = dst.component_size(exec_size);
80       break;
81    case BAD_FILE:
82       this->size_written = 0;
83       break;
84    case IMM:
85    case UNIFORM:
86       unreachable("Invalid destination register file");
87    }
88 
89    this->writes_accumulator = false;
90 }
91 
fs_inst()92 fs_inst::fs_inst()
93 {
94    init(BRW_OPCODE_NOP, 8, dst, NULL, 0);
95 }
96 
fs_inst(enum opcode opcode,uint8_t exec_size)97 fs_inst::fs_inst(enum opcode opcode, uint8_t exec_size)
98 {
99    init(opcode, exec_size, reg_undef, NULL, 0);
100 }
101 
fs_inst(enum opcode opcode,uint8_t exec_size,const fs_reg & dst)102 fs_inst::fs_inst(enum opcode opcode, uint8_t exec_size, const fs_reg &dst)
103 {
104    init(opcode, exec_size, dst, NULL, 0);
105 }
106 
fs_inst(enum opcode opcode,uint8_t exec_size,const fs_reg & dst,const fs_reg & src0)107 fs_inst::fs_inst(enum opcode opcode, uint8_t exec_size, const fs_reg &dst,
108                  const fs_reg &src0)
109 {
110    const fs_reg src[1] = { src0 };
111    init(opcode, exec_size, dst, src, 1);
112 }
113 
fs_inst(enum opcode opcode,uint8_t exec_size,const fs_reg & dst,const fs_reg & src0,const fs_reg & src1)114 fs_inst::fs_inst(enum opcode opcode, uint8_t exec_size, const fs_reg &dst,
115                  const fs_reg &src0, const fs_reg &src1)
116 {
117    const fs_reg src[2] = { src0, src1 };
118    init(opcode, exec_size, dst, src, 2);
119 }
120 
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)121 fs_inst::fs_inst(enum opcode opcode, uint8_t exec_size, const fs_reg &dst,
122                  const fs_reg &src0, const fs_reg &src1, const fs_reg &src2)
123 {
124    const fs_reg src[3] = { src0, src1, src2 };
125    init(opcode, exec_size, dst, src, 3);
126 }
127 
fs_inst(enum opcode opcode,uint8_t exec_width,const fs_reg & dst,const fs_reg src[],unsigned sources)128 fs_inst::fs_inst(enum opcode opcode, uint8_t exec_width, const fs_reg &dst,
129                  const fs_reg src[], unsigned sources)
130 {
131    init(opcode, exec_width, dst, src, sources);
132 }
133 
fs_inst(const fs_inst & that)134 fs_inst::fs_inst(const fs_inst &that)
135 {
136    memcpy((void*)this, &that, sizeof(that));
137 
138    this->src = new fs_reg[MAX2(that.sources, 3)];
139 
140    for (unsigned i = 0; i < that.sources; i++)
141       this->src[i] = that.src[i];
142 }
143 
~fs_inst()144 fs_inst::~fs_inst()
145 {
146    delete[] this->src;
147 }
148 
149 void
resize_sources(uint8_t num_sources)150 fs_inst::resize_sources(uint8_t num_sources)
151 {
152    if (this->sources != num_sources) {
153       fs_reg *src = new fs_reg[MAX2(num_sources, 3)];
154 
155       for (unsigned i = 0; i < MIN2(this->sources, num_sources); ++i)
156          src[i] = this->src[i];
157 
158       delete[] this->src;
159       this->src = src;
160       this->sources = num_sources;
161    }
162 }
163 
164 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)165 fs_visitor::VARYING_PULL_CONSTANT_LOAD(const fs_builder &bld,
166                                        const fs_reg &dst,
167                                        const fs_reg &surf_index,
168                                        const fs_reg &varying_offset,
169                                        uint32_t const_offset,
170                                        uint8_t alignment)
171 {
172    /* We have our constant surface use a pitch of 4 bytes, so our index can
173     * be any component of a vector, and then we load 4 contiguous
174     * components starting from that.
175     *
176     * We break down the const_offset to a portion added to the variable offset
177     * and a portion done using fs_reg::offset, which means that if you have
178     * GLSL using something like "uniform vec4 a[20]; gl_FragColor = a[i]",
179     * we'll temporarily generate 4 vec4 loads from offset i * 4, and CSE can
180     * later notice that those loads are all the same and eliminate the
181     * redundant ones.
182     */
183    fs_reg vec4_offset = vgrf(glsl_type::uint_type);
184    bld.ADD(vec4_offset, varying_offset, brw_imm_ud(const_offset & ~0xf));
185 
186    /* The pull load message will load a vec4 (16 bytes). If we are loading
187     * a double this means we are only loading 2 elements worth of data.
188     * We also want to use a 32-bit data type for the dst of the load operation
189     * so other parts of the driver don't get confused about the size of the
190     * result.
191     */
192    fs_reg vec4_result = bld.vgrf(BRW_REGISTER_TYPE_F, 4);
193    fs_inst *inst = bld.emit(FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_LOGICAL,
194                             vec4_result, surf_index, vec4_offset,
195                             brw_imm_ud(alignment));
196    inst->size_written = 4 * vec4_result.component_size(inst->exec_size);
197 
198    shuffle_from_32bit_read(bld, dst, vec4_result,
199                            (const_offset & 0xf) / type_sz(dst.type), 1);
200 }
201 
202 /**
203  * A helper for MOV generation for fixing up broken hardware SEND dependency
204  * handling.
205  */
206 void
DEP_RESOLVE_MOV(const fs_builder & bld,int grf)207 fs_visitor::DEP_RESOLVE_MOV(const fs_builder &bld, int grf)
208 {
209    /* The caller always wants uncompressed to emit the minimal extra
210     * dependencies, and to avoid having to deal with aligning its regs to 2.
211     */
212    const fs_builder ubld = bld.annotate("send dependency resolve")
213                               .quarter(0);
214 
215    ubld.MOV(ubld.null_reg_f(), fs_reg(VGRF, grf, BRW_REGISTER_TYPE_F));
216 }
217 
218 bool
is_send_from_grf() const219 fs_inst::is_send_from_grf() const
220 {
221    switch (opcode) {
222    case SHADER_OPCODE_SEND:
223    case SHADER_OPCODE_SHADER_TIME_ADD:
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_URB_WRITE_SIMD8:
228    case SHADER_OPCODE_URB_WRITE_SIMD8_PER_SLOT:
229    case SHADER_OPCODE_URB_WRITE_SIMD8_MASKED:
230    case SHADER_OPCODE_URB_WRITE_SIMD8_MASKED_PER_SLOT:
231    case SHADER_OPCODE_URB_READ_SIMD8:
232    case SHADER_OPCODE_URB_READ_SIMD8_PER_SLOT:
233    case SHADER_OPCODE_INTERLOCK:
234    case SHADER_OPCODE_MEMORY_FENCE:
235    case SHADER_OPCODE_BARRIER:
236       return true;
237    case FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD:
238       return src[1].file == VGRF;
239    case FS_OPCODE_FB_WRITE:
240    case FS_OPCODE_FB_READ:
241       return src[0].file == VGRF;
242    default:
243       if (is_tex())
244          return src[0].file == VGRF;
245 
246       return false;
247    }
248 }
249 
250 bool
is_control_source(unsigned arg) const251 fs_inst::is_control_source(unsigned arg) const
252 {
253    switch (opcode) {
254    case FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD:
255    case FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD_GFX7:
256    case FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_GFX4:
257       return arg == 0;
258 
259    case SHADER_OPCODE_BROADCAST:
260    case SHADER_OPCODE_SHUFFLE:
261    case SHADER_OPCODE_QUAD_SWIZZLE:
262    case FS_OPCODE_INTERPOLATE_AT_SAMPLE:
263    case FS_OPCODE_INTERPOLATE_AT_SHARED_OFFSET:
264    case FS_OPCODE_INTERPOLATE_AT_PER_SLOT_OFFSET:
265    case SHADER_OPCODE_GET_BUFFER_SIZE:
266       return arg == 1;
267 
268    case SHADER_OPCODE_MOV_INDIRECT:
269    case SHADER_OPCODE_CLUSTER_BROADCAST:
270    case SHADER_OPCODE_TEX:
271    case FS_OPCODE_TXB:
272    case SHADER_OPCODE_TXD:
273    case SHADER_OPCODE_TXF:
274    case SHADER_OPCODE_TXF_LZ:
275    case SHADER_OPCODE_TXF_CMS:
276    case SHADER_OPCODE_TXF_CMS_W:
277    case SHADER_OPCODE_TXF_UMS:
278    case SHADER_OPCODE_TXF_MCS:
279    case SHADER_OPCODE_TXL:
280    case SHADER_OPCODE_TXL_LZ:
281    case SHADER_OPCODE_TXS:
282    case SHADER_OPCODE_LOD:
283    case SHADER_OPCODE_TG4:
284    case SHADER_OPCODE_TG4_OFFSET:
285    case SHADER_OPCODE_SAMPLEINFO:
286       return arg == 1 || arg == 2;
287 
288    case SHADER_OPCODE_SEND:
289       return arg == 0 || arg == 1;
290 
291    default:
292       return false;
293    }
294 }
295 
296 bool
is_payload(unsigned arg) const297 fs_inst::is_payload(unsigned arg) const
298 {
299    switch (opcode) {
300    case FS_OPCODE_FB_WRITE:
301    case FS_OPCODE_FB_READ:
302    case SHADER_OPCODE_URB_WRITE_SIMD8:
303    case SHADER_OPCODE_URB_WRITE_SIMD8_PER_SLOT:
304    case SHADER_OPCODE_URB_WRITE_SIMD8_MASKED:
305    case SHADER_OPCODE_URB_WRITE_SIMD8_MASKED_PER_SLOT:
306    case SHADER_OPCODE_URB_READ_SIMD8:
307    case SHADER_OPCODE_URB_READ_SIMD8_PER_SLOT:
308    case VEC4_OPCODE_UNTYPED_ATOMIC:
309    case VEC4_OPCODE_UNTYPED_SURFACE_READ:
310    case VEC4_OPCODE_UNTYPED_SURFACE_WRITE:
311    case FS_OPCODE_INTERPOLATE_AT_PER_SLOT_OFFSET:
312    case SHADER_OPCODE_SHADER_TIME_ADD:
313    case FS_OPCODE_INTERPOLATE_AT_SAMPLE:
314    case FS_OPCODE_INTERPOLATE_AT_SHARED_OFFSET:
315    case SHADER_OPCODE_INTERLOCK:
316    case SHADER_OPCODE_MEMORY_FENCE:
317    case SHADER_OPCODE_BARRIER:
318       return arg == 0;
319 
320    case FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD_GFX7:
321       return arg == 1;
322 
323    case SHADER_OPCODE_SEND:
324       return arg == 2 || arg == 3;
325 
326    default:
327       if (is_tex())
328          return arg == 0;
329       else
330          return false;
331    }
332 }
333 
334 /**
335  * Returns true if this instruction's sources and destinations cannot
336  * safely be the same register.
337  *
338  * In most cases, a register can be written over safely by the same
339  * instruction that is its last use.  For a single instruction, the
340  * sources are dereferenced before writing of the destination starts
341  * (naturally).
342  *
343  * However, there are a few cases where this can be problematic:
344  *
345  * - Virtual opcodes that translate to multiple instructions in the
346  *   code generator: if src == dst and one instruction writes the
347  *   destination before a later instruction reads the source, then
348  *   src will have been clobbered.
349  *
350  * - SIMD16 compressed instructions with certain regioning (see below).
351  *
352  * The register allocator uses this information to set up conflicts between
353  * GRF sources and the destination.
354  */
355 bool
has_source_and_destination_hazard() const356 fs_inst::has_source_and_destination_hazard() const
357 {
358    switch (opcode) {
359    case FS_OPCODE_PACK_HALF_2x16_SPLIT:
360       /* Multiple partial writes to the destination */
361       return true;
362    case SHADER_OPCODE_SHUFFLE:
363       /* This instruction returns an arbitrary channel from the source and
364        * gets split into smaller instructions in the generator.  It's possible
365        * that one of the instructions will read from a channel corresponding
366        * to an earlier instruction.
367        */
368    case SHADER_OPCODE_SEL_EXEC:
369       /* This is implemented as
370        *
371        * mov(16)      g4<1>D      0D            { align1 WE_all 1H };
372        * mov(16)      g4<1>D      g5<8,8,1>D    { align1 1H }
373        *
374        * Because the source is only read in the second instruction, the first
375        * may stomp all over it.
376        */
377       return true;
378    case SHADER_OPCODE_QUAD_SWIZZLE:
379       switch (src[1].ud) {
380       case BRW_SWIZZLE_XXXX:
381       case BRW_SWIZZLE_YYYY:
382       case BRW_SWIZZLE_ZZZZ:
383       case BRW_SWIZZLE_WWWW:
384       case BRW_SWIZZLE_XXZZ:
385       case BRW_SWIZZLE_YYWW:
386       case BRW_SWIZZLE_XYXY:
387       case BRW_SWIZZLE_ZWZW:
388          /* These can be implemented as a single Align1 region on all
389           * platforms, so there's never a hazard between source and
390           * destination.  C.f. fs_generator::generate_quad_swizzle().
391           */
392          return false;
393       default:
394          return !is_uniform(src[0]);
395       }
396    default:
397       /* The SIMD16 compressed instruction
398        *
399        * add(16)      g4<1>F      g4<8,8,1>F   g6<8,8,1>F
400        *
401        * is actually decoded in hardware as:
402        *
403        * add(8)       g4<1>F      g4<8,8,1>F   g6<8,8,1>F
404        * add(8)       g5<1>F      g5<8,8,1>F   g7<8,8,1>F
405        *
406        * Which is safe.  However, if we have uniform accesses
407        * happening, we get into trouble:
408        *
409        * add(8)       g4<1>F      g4<0,1,0>F   g6<8,8,1>F
410        * add(8)       g5<1>F      g4<0,1,0>F   g7<8,8,1>F
411        *
412        * Now our destination for the first instruction overwrote the
413        * second instruction's src0, and we get garbage for those 8
414        * pixels.  There's a similar issue for the pre-gfx6
415        * pixel_x/pixel_y, which are registers of 16-bit values and thus
416        * would get stomped by the first decode as well.
417        */
418       if (exec_size == 16) {
419          for (int i = 0; i < sources; i++) {
420             if (src[i].file == VGRF && (src[i].stride == 0 ||
421                                         src[i].type == BRW_REGISTER_TYPE_UW ||
422                                         src[i].type == BRW_REGISTER_TYPE_W ||
423                                         src[i].type == BRW_REGISTER_TYPE_UB ||
424                                         src[i].type == BRW_REGISTER_TYPE_B)) {
425                return true;
426             }
427          }
428       }
429       return false;
430    }
431 }
432 
433 bool
can_do_source_mods(const struct intel_device_info * devinfo) const434 fs_inst::can_do_source_mods(const struct intel_device_info *devinfo) const
435 {
436    if (devinfo->ver == 6 && is_math())
437       return false;
438 
439    if (is_send_from_grf())
440       return false;
441 
442    /* From Wa_1604601757:
443     *
444     * "When multiplying a DW and any lower precision integer, source modifier
445     *  is not supported."
446     */
447    if (devinfo->ver >= 12 && (opcode == BRW_OPCODE_MUL ||
448                               opcode == BRW_OPCODE_MAD)) {
449       const brw_reg_type exec_type = get_exec_type(this);
450       const unsigned min_type_sz = opcode == BRW_OPCODE_MAD ?
451          MIN2(type_sz(src[1].type), type_sz(src[2].type)) :
452          MIN2(type_sz(src[0].type), type_sz(src[1].type));
453 
454       if (brw_reg_type_is_integer(exec_type) &&
455           type_sz(exec_type) >= 4 &&
456           type_sz(exec_type) != min_type_sz)
457          return false;
458    }
459 
460    if (!backend_instruction::can_do_source_mods())
461       return false;
462 
463    return true;
464 }
465 
466 bool
can_do_cmod()467 fs_inst::can_do_cmod()
468 {
469    if (!backend_instruction::can_do_cmod())
470       return false;
471 
472    /* The accumulator result appears to get used for the conditional modifier
473     * generation.  When negating a UD value, there is a 33rd bit generated for
474     * the sign in the accumulator value, so now you can't check, for example,
475     * equality with a 32-bit value.  See piglit fs-op-neg-uvec4.
476     */
477    for (unsigned i = 0; i < sources; i++) {
478       if (brw_reg_type_is_unsigned_integer(src[i].type) && src[i].negate)
479          return false;
480    }
481 
482    return true;
483 }
484 
485 bool
can_change_types() const486 fs_inst::can_change_types() const
487 {
488    return dst.type == src[0].type &&
489           !src[0].abs && !src[0].negate && !saturate &&
490           (opcode == BRW_OPCODE_MOV ||
491            (opcode == BRW_OPCODE_SEL &&
492             dst.type == src[1].type &&
493             predicate != BRW_PREDICATE_NONE &&
494             !src[1].abs && !src[1].negate));
495 }
496 
497 void
init()498 fs_reg::init()
499 {
500    memset((void*)this, 0, sizeof(*this));
501    type = BRW_REGISTER_TYPE_UD;
502    stride = 1;
503 }
504 
505 /** Generic unset register constructor. */
fs_reg()506 fs_reg::fs_reg()
507 {
508    init();
509    this->file = BAD_FILE;
510 }
511 
fs_reg(struct::brw_reg reg)512 fs_reg::fs_reg(struct ::brw_reg reg) :
513    backend_reg(reg)
514 {
515    this->offset = 0;
516    this->stride = 1;
517    if (this->file == IMM &&
518        (this->type != BRW_REGISTER_TYPE_V &&
519         this->type != BRW_REGISTER_TYPE_UV &&
520         this->type != BRW_REGISTER_TYPE_VF)) {
521       this->stride = 0;
522    }
523 }
524 
525 bool
equals(const fs_reg & r) const526 fs_reg::equals(const fs_reg &r) const
527 {
528    return (this->backend_reg::equals(r) &&
529            stride == r.stride);
530 }
531 
532 bool
negative_equals(const fs_reg & r) const533 fs_reg::negative_equals(const fs_reg &r) const
534 {
535    return (this->backend_reg::negative_equals(r) &&
536            stride == r.stride);
537 }
538 
539 bool
is_contiguous() const540 fs_reg::is_contiguous() const
541 {
542    switch (file) {
543    case ARF:
544    case FIXED_GRF:
545       return hstride == BRW_HORIZONTAL_STRIDE_1 &&
546              vstride == width + hstride;
547    case MRF:
548    case VGRF:
549    case ATTR:
550       return stride == 1;
551    case UNIFORM:
552    case IMM:
553    case BAD_FILE:
554       return true;
555    }
556 
557    unreachable("Invalid register file");
558 }
559 
560 unsigned
component_size(unsigned width) const561 fs_reg::component_size(unsigned width) const
562 {
563    const unsigned stride = ((file != ARF && file != FIXED_GRF) ? this->stride :
564                             hstride == 0 ? 0 :
565                             1 << (hstride - 1));
566    return MAX2(width * stride, 1) * type_sz(type);
567 }
568 
569 /**
570  * Create a MOV to read the timestamp register.
571  */
572 fs_reg
get_timestamp(const fs_builder & bld)573 fs_visitor::get_timestamp(const fs_builder &bld)
574 {
575    assert(devinfo->ver >= 7);
576 
577    fs_reg ts = fs_reg(retype(brw_vec4_reg(BRW_ARCHITECTURE_REGISTER_FILE,
578                                           BRW_ARF_TIMESTAMP,
579                                           0),
580                              BRW_REGISTER_TYPE_UD));
581 
582    fs_reg dst = fs_reg(VGRF, alloc.allocate(1), BRW_REGISTER_TYPE_UD);
583 
584    /* We want to read the 3 fields we care about even if it's not enabled in
585     * the dispatch.
586     */
587    bld.group(4, 0).exec_all().MOV(dst, ts);
588 
589    return dst;
590 }
591 
592 void
emit_shader_time_begin()593 fs_visitor::emit_shader_time_begin()
594 {
595    /* We want only the low 32 bits of the timestamp.  Since it's running
596     * at the GPU clock rate of ~1.2ghz, it will roll over every ~3 seconds,
597     * which is plenty of time for our purposes.  It is identical across the
598     * EUs, but since it's tracking GPU core speed it will increment at a
599     * varying rate as render P-states change.
600     */
601    shader_start_time = component(
602       get_timestamp(bld.annotate("shader time start")), 0);
603 }
604 
605 void
emit_shader_time_end()606 fs_visitor::emit_shader_time_end()
607 {
608    /* Insert our code just before the final SEND with EOT. */
609    exec_node *end = this->instructions.get_tail();
610    assert(end && ((fs_inst *) end)->eot);
611    const fs_builder ibld = bld.annotate("shader time end")
612                               .exec_all().at(NULL, end);
613    const fs_reg timestamp = get_timestamp(ibld);
614 
615    /* We only use the low 32 bits of the timestamp - see
616     * emit_shader_time_begin()).
617     *
618     * We could also check if render P-states have changed (or anything
619     * else that might disrupt timing) by setting smear to 2 and checking if
620     * that field is != 0.
621     */
622    const fs_reg shader_end_time = component(timestamp, 0);
623 
624    /* Check that there weren't any timestamp reset events (assuming these
625     * were the only two timestamp reads that happened).
626     */
627    const fs_reg reset = component(timestamp, 2);
628    set_condmod(BRW_CONDITIONAL_Z,
629                ibld.AND(ibld.null_reg_ud(), reset, brw_imm_ud(1u)));
630    ibld.IF(BRW_PREDICATE_NORMAL);
631 
632    fs_reg start = shader_start_time;
633    start.negate = true;
634    const fs_reg diff = component(fs_reg(VGRF, alloc.allocate(1),
635                                         BRW_REGISTER_TYPE_UD),
636                                  0);
637    const fs_builder cbld = ibld.group(1, 0);
638    cbld.group(1, 0).ADD(diff, start, shader_end_time);
639 
640    /* If there were no instructions between the two timestamp gets, the diff
641     * is 2 cycles.  Remove that overhead, so I can forget about that when
642     * trying to determine the time taken for single instructions.
643     */
644    cbld.ADD(diff, diff, brw_imm_ud(-2u));
645    SHADER_TIME_ADD(cbld, 0, diff);
646    SHADER_TIME_ADD(cbld, 1, brw_imm_ud(1u));
647    ibld.emit(BRW_OPCODE_ELSE);
648    SHADER_TIME_ADD(cbld, 2, brw_imm_ud(1u));
649    ibld.emit(BRW_OPCODE_ENDIF);
650 }
651 
652 void
SHADER_TIME_ADD(const fs_builder & bld,int shader_time_subindex,fs_reg value)653 fs_visitor::SHADER_TIME_ADD(const fs_builder &bld,
654                             int shader_time_subindex,
655                             fs_reg value)
656 {
657    int index = shader_time_index * 3 + shader_time_subindex;
658    struct brw_reg offset = brw_imm_d(index * BRW_SHADER_TIME_STRIDE);
659 
660    fs_reg payload;
661    if (dispatch_width == 8)
662       payload = vgrf(glsl_type::uvec2_type);
663    else
664       payload = vgrf(glsl_type::uint_type);
665 
666    bld.emit(SHADER_OPCODE_SHADER_TIME_ADD, fs_reg(), payload, offset, value);
667 }
668 
669 void
vfail(const char * format,va_list va)670 fs_visitor::vfail(const char *format, va_list va)
671 {
672    char *msg;
673 
674    if (failed)
675       return;
676 
677    failed = true;
678 
679    msg = ralloc_vasprintf(mem_ctx, format, va);
680    msg = ralloc_asprintf(mem_ctx, "SIMD%d %s compile failed: %s\n",
681          dispatch_width, stage_abbrev, msg);
682 
683    this->fail_msg = msg;
684 
685    if (unlikely(debug_enabled)) {
686       fprintf(stderr, "%s",  msg);
687    }
688 }
689 
690 void
fail(const char * format,...)691 fs_visitor::fail(const char *format, ...)
692 {
693    va_list va;
694 
695    va_start(va, format);
696    vfail(format, va);
697    va_end(va);
698 }
699 
700 /**
701  * Mark this program as impossible to compile with dispatch width greater
702  * than n.
703  *
704  * During the SIMD8 compile (which happens first), we can detect and flag
705  * things that are unsupported in SIMD16+ mode, so the compiler can skip the
706  * SIMD16+ compile altogether.
707  *
708  * During a compile of dispatch width greater than n (if one happens anyway),
709  * this just calls fail().
710  */
711 void
limit_dispatch_width(unsigned n,const char * msg)712 fs_visitor::limit_dispatch_width(unsigned n, const char *msg)
713 {
714    if (dispatch_width > n) {
715       fail("%s", msg);
716    } else {
717       max_dispatch_width = MIN2(max_dispatch_width, n);
718       brw_shader_perf_log(compiler, log_data,
719                           "Shader dispatch width limited to SIMD%d: %s\n",
720                           n, msg);
721    }
722 }
723 
724 /**
725  * Returns true if the instruction has a flag that means it won't
726  * update an entire destination register.
727  *
728  * For example, dead code elimination and live variable analysis want to know
729  * when a write to a variable screens off any preceding values that were in
730  * it.
731  */
732 bool
is_partial_write() const733 fs_inst::is_partial_write() const
734 {
735    return ((this->predicate && this->opcode != BRW_OPCODE_SEL) ||
736            (this->exec_size * type_sz(this->dst.type)) < 32 ||
737            !this->dst.is_contiguous() ||
738            this->dst.offset % REG_SIZE != 0);
739 }
740 
741 unsigned
components_read(unsigned i) const742 fs_inst::components_read(unsigned i) const
743 {
744    /* Return zero if the source is not present. */
745    if (src[i].file == BAD_FILE)
746       return 0;
747 
748    switch (opcode) {
749    case FS_OPCODE_LINTERP:
750       if (i == 0)
751          return 2;
752       else
753          return 1;
754 
755    case FS_OPCODE_PIXEL_X:
756    case FS_OPCODE_PIXEL_Y:
757       assert(i < 2);
758       if (i == 0)
759          return 2;
760       else
761          return 1;
762 
763    case FS_OPCODE_FB_WRITE_LOGICAL:
764       assert(src[FB_WRITE_LOGICAL_SRC_COMPONENTS].file == IMM);
765       /* First/second FB write color. */
766       if (i < 2)
767          return src[FB_WRITE_LOGICAL_SRC_COMPONENTS].ud;
768       else
769          return 1;
770 
771    case SHADER_OPCODE_TEX_LOGICAL:
772    case SHADER_OPCODE_TXD_LOGICAL:
773    case SHADER_OPCODE_TXF_LOGICAL:
774    case SHADER_OPCODE_TXL_LOGICAL:
775    case SHADER_OPCODE_TXS_LOGICAL:
776    case SHADER_OPCODE_IMAGE_SIZE_LOGICAL:
777    case FS_OPCODE_TXB_LOGICAL:
778    case SHADER_OPCODE_TXF_CMS_LOGICAL:
779    case SHADER_OPCODE_TXF_CMS_W_LOGICAL:
780    case SHADER_OPCODE_TXF_UMS_LOGICAL:
781    case SHADER_OPCODE_TXF_MCS_LOGICAL:
782    case SHADER_OPCODE_LOD_LOGICAL:
783    case SHADER_OPCODE_TG4_LOGICAL:
784    case SHADER_OPCODE_TG4_OFFSET_LOGICAL:
785    case SHADER_OPCODE_SAMPLEINFO_LOGICAL:
786       assert(src[TEX_LOGICAL_SRC_COORD_COMPONENTS].file == IMM &&
787              src[TEX_LOGICAL_SRC_GRAD_COMPONENTS].file == IMM);
788       /* Texture coordinates. */
789       if (i == TEX_LOGICAL_SRC_COORDINATE)
790          return src[TEX_LOGICAL_SRC_COORD_COMPONENTS].ud;
791       /* Texture derivatives. */
792       else if ((i == TEX_LOGICAL_SRC_LOD || i == TEX_LOGICAL_SRC_LOD2) &&
793                opcode == SHADER_OPCODE_TXD_LOGICAL)
794          return src[TEX_LOGICAL_SRC_GRAD_COMPONENTS].ud;
795       /* Texture offset. */
796       else if (i == TEX_LOGICAL_SRC_TG4_OFFSET)
797          return 2;
798       /* MCS */
799       else if (i == TEX_LOGICAL_SRC_MCS && opcode == SHADER_OPCODE_TXF_CMS_W_LOGICAL)
800          return 2;
801       else
802          return 1;
803 
804    case SHADER_OPCODE_UNTYPED_SURFACE_READ_LOGICAL:
805    case SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL:
806       assert(src[SURFACE_LOGICAL_SRC_IMM_DIMS].file == IMM);
807       /* Surface coordinates. */
808       if (i == SURFACE_LOGICAL_SRC_ADDRESS)
809          return src[SURFACE_LOGICAL_SRC_IMM_DIMS].ud;
810       /* Surface operation source (ignored for reads). */
811       else if (i == SURFACE_LOGICAL_SRC_DATA)
812          return 0;
813       else
814          return 1;
815 
816    case SHADER_OPCODE_UNTYPED_SURFACE_WRITE_LOGICAL:
817    case SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL:
818       assert(src[SURFACE_LOGICAL_SRC_IMM_DIMS].file == IMM &&
819              src[SURFACE_LOGICAL_SRC_IMM_ARG].file == IMM);
820       /* Surface coordinates. */
821       if (i == SURFACE_LOGICAL_SRC_ADDRESS)
822          return src[SURFACE_LOGICAL_SRC_IMM_DIMS].ud;
823       /* Surface operation source. */
824       else if (i == SURFACE_LOGICAL_SRC_DATA)
825          return src[SURFACE_LOGICAL_SRC_IMM_ARG].ud;
826       else
827          return 1;
828 
829    case SHADER_OPCODE_A64_UNTYPED_READ_LOGICAL:
830    case SHADER_OPCODE_A64_OWORD_BLOCK_READ_LOGICAL:
831    case SHADER_OPCODE_A64_UNALIGNED_OWORD_BLOCK_READ_LOGICAL:
832       assert(src[2].file == IMM);
833       return 1;
834 
835    case SHADER_OPCODE_A64_OWORD_BLOCK_WRITE_LOGICAL:
836       assert(src[2].file == IMM);
837       if (i == 1) { /* data to write */
838          const unsigned comps = src[2].ud / exec_size;
839          assert(comps > 0);
840          return comps;
841       } else {
842          return 1;
843       }
844 
845    case SHADER_OPCODE_OWORD_BLOCK_READ_LOGICAL:
846    case SHADER_OPCODE_UNALIGNED_OWORD_BLOCK_READ_LOGICAL:
847       assert(src[SURFACE_LOGICAL_SRC_IMM_ARG].file == IMM);
848       return 1;
849 
850    case SHADER_OPCODE_OWORD_BLOCK_WRITE_LOGICAL:
851       assert(src[SURFACE_LOGICAL_SRC_IMM_ARG].file == IMM);
852       if (i == SURFACE_LOGICAL_SRC_DATA) {
853          const unsigned comps = src[SURFACE_LOGICAL_SRC_IMM_ARG].ud / exec_size;
854          assert(comps > 0);
855          return comps;
856       } else {
857          return 1;
858       }
859 
860    case SHADER_OPCODE_A64_UNTYPED_WRITE_LOGICAL:
861       assert(src[2].file == IMM);
862       return i == 1 ? src[2].ud : 1;
863 
864    case SHADER_OPCODE_A64_UNTYPED_ATOMIC_LOGICAL:
865    case SHADER_OPCODE_A64_UNTYPED_ATOMIC_INT16_LOGICAL:
866    case SHADER_OPCODE_A64_UNTYPED_ATOMIC_INT64_LOGICAL:
867       assert(src[2].file == IMM);
868       if (i == 1) {
869          /* Data source */
870          const unsigned op = src[2].ud;
871          switch (op) {
872          case BRW_AOP_INC:
873          case BRW_AOP_DEC:
874          case BRW_AOP_PREDEC:
875             return 0;
876          case BRW_AOP_CMPWR:
877             return 2;
878          default:
879             return 1;
880          }
881       } else {
882          return 1;
883       }
884 
885    case SHADER_OPCODE_A64_UNTYPED_ATOMIC_FLOAT16_LOGICAL:
886    case SHADER_OPCODE_A64_UNTYPED_ATOMIC_FLOAT32_LOGICAL:
887    case SHADER_OPCODE_A64_UNTYPED_ATOMIC_FLOAT64_LOGICAL:
888       assert(src[2].file == IMM);
889       if (i == 1) {
890          /* Data source */
891          const unsigned op = src[2].ud;
892          return op == BRW_AOP_FCMPWR ? 2 : 1;
893       } else {
894          return 1;
895       }
896 
897    case SHADER_OPCODE_BYTE_SCATTERED_READ_LOGICAL:
898    case SHADER_OPCODE_DWORD_SCATTERED_READ_LOGICAL:
899       /* Scattered logical opcodes use the following params:
900        * src[0] Surface coordinates
901        * src[1] Surface operation source (ignored for reads)
902        * src[2] Surface
903        * src[3] IMM with always 1 dimension.
904        * src[4] IMM with arg bitsize for scattered read/write 8, 16, 32
905        */
906       assert(src[SURFACE_LOGICAL_SRC_IMM_DIMS].file == IMM &&
907              src[SURFACE_LOGICAL_SRC_IMM_ARG].file == IMM);
908       return i == SURFACE_LOGICAL_SRC_DATA ? 0 : 1;
909 
910    case SHADER_OPCODE_BYTE_SCATTERED_WRITE_LOGICAL:
911    case SHADER_OPCODE_DWORD_SCATTERED_WRITE_LOGICAL:
912       assert(src[SURFACE_LOGICAL_SRC_IMM_DIMS].file == IMM &&
913              src[SURFACE_LOGICAL_SRC_IMM_ARG].file == IMM);
914       return 1;
915 
916    case SHADER_OPCODE_UNTYPED_ATOMIC_LOGICAL:
917    case SHADER_OPCODE_TYPED_ATOMIC_LOGICAL: {
918       assert(src[SURFACE_LOGICAL_SRC_IMM_DIMS].file == IMM &&
919              src[SURFACE_LOGICAL_SRC_IMM_ARG].file == IMM);
920       const unsigned op = src[SURFACE_LOGICAL_SRC_IMM_ARG].ud;
921       /* Surface coordinates. */
922       if (i == SURFACE_LOGICAL_SRC_ADDRESS)
923          return src[SURFACE_LOGICAL_SRC_IMM_DIMS].ud;
924       /* Surface operation source. */
925       else if (i == SURFACE_LOGICAL_SRC_DATA && op == BRW_AOP_CMPWR)
926          return 2;
927       else if (i == SURFACE_LOGICAL_SRC_DATA &&
928                (op == BRW_AOP_INC || op == BRW_AOP_DEC || op == BRW_AOP_PREDEC))
929          return 0;
930       else
931          return 1;
932    }
933    case FS_OPCODE_INTERPOLATE_AT_PER_SLOT_OFFSET:
934       return (i == 0 ? 2 : 1);
935 
936    case SHADER_OPCODE_UNTYPED_ATOMIC_FLOAT_LOGICAL: {
937       assert(src[SURFACE_LOGICAL_SRC_IMM_DIMS].file == IMM &&
938              src[SURFACE_LOGICAL_SRC_IMM_ARG].file == IMM);
939       const unsigned op = src[SURFACE_LOGICAL_SRC_IMM_ARG].ud;
940       /* Surface coordinates. */
941       if (i == SURFACE_LOGICAL_SRC_ADDRESS)
942          return src[SURFACE_LOGICAL_SRC_IMM_DIMS].ud;
943       /* Surface operation source. */
944       else if (i == SURFACE_LOGICAL_SRC_DATA && op == BRW_AOP_FCMPWR)
945          return 2;
946       else
947          return 1;
948    }
949 
950    default:
951       return 1;
952    }
953 }
954 
955 unsigned
size_read(int arg) const956 fs_inst::size_read(int arg) const
957 {
958    switch (opcode) {
959    case SHADER_OPCODE_SEND:
960       if (arg == 2) {
961          return mlen * REG_SIZE;
962       } else if (arg == 3) {
963          return ex_mlen * REG_SIZE;
964       }
965       break;
966 
967    case FS_OPCODE_FB_WRITE:
968    case FS_OPCODE_REP_FB_WRITE:
969       if (arg == 0) {
970          if (base_mrf >= 0)
971             return src[0].file == BAD_FILE ? 0 : 2 * REG_SIZE;
972          else
973             return mlen * REG_SIZE;
974       }
975       break;
976 
977    case FS_OPCODE_FB_READ:
978    case SHADER_OPCODE_URB_WRITE_SIMD8:
979    case SHADER_OPCODE_URB_WRITE_SIMD8_PER_SLOT:
980    case SHADER_OPCODE_URB_WRITE_SIMD8_MASKED:
981    case SHADER_OPCODE_URB_WRITE_SIMD8_MASKED_PER_SLOT:
982    case SHADER_OPCODE_URB_READ_SIMD8:
983    case SHADER_OPCODE_URB_READ_SIMD8_PER_SLOT:
984    case FS_OPCODE_INTERPOLATE_AT_SAMPLE:
985    case FS_OPCODE_INTERPOLATE_AT_SHARED_OFFSET:
986       if (arg == 0)
987          return mlen * REG_SIZE;
988       break;
989 
990    case FS_OPCODE_SET_SAMPLE_ID:
991       if (arg == 1)
992          return 1;
993       break;
994 
995    case FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD_GFX7:
996       /* The payload is actually stored in src1 */
997       if (arg == 1)
998          return mlen * REG_SIZE;
999       break;
1000 
1001    case FS_OPCODE_LINTERP:
1002       if (arg == 1)
1003          return 16;
1004       break;
1005 
1006    case SHADER_OPCODE_LOAD_PAYLOAD:
1007       if (arg < this->header_size)
1008          return REG_SIZE;
1009       break;
1010 
1011    case CS_OPCODE_CS_TERMINATE:
1012    case SHADER_OPCODE_BARRIER:
1013       return REG_SIZE;
1014 
1015    case SHADER_OPCODE_MOV_INDIRECT:
1016       if (arg == 0) {
1017          assert(src[2].file == IMM);
1018          return src[2].ud;
1019       }
1020       break;
1021 
1022    default:
1023       if (is_tex() && arg == 0 && src[0].file == VGRF)
1024          return mlen * REG_SIZE;
1025       break;
1026    }
1027 
1028    switch (src[arg].file) {
1029    case UNIFORM:
1030    case IMM:
1031       return components_read(arg) * type_sz(src[arg].type);
1032    case BAD_FILE:
1033    case ARF:
1034    case FIXED_GRF:
1035    case VGRF:
1036    case ATTR:
1037       return components_read(arg) * src[arg].component_size(exec_size);
1038    case MRF:
1039       unreachable("MRF registers are not allowed as sources");
1040    }
1041    return 0;
1042 }
1043 
1044 namespace {
1045    unsigned
predicate_width(brw_predicate predicate)1046    predicate_width(brw_predicate predicate)
1047    {
1048       switch (predicate) {
1049       case BRW_PREDICATE_NONE:            return 1;
1050       case BRW_PREDICATE_NORMAL:          return 1;
1051       case BRW_PREDICATE_ALIGN1_ANY2H:    return 2;
1052       case BRW_PREDICATE_ALIGN1_ALL2H:    return 2;
1053       case BRW_PREDICATE_ALIGN1_ANY4H:    return 4;
1054       case BRW_PREDICATE_ALIGN1_ALL4H:    return 4;
1055       case BRW_PREDICATE_ALIGN1_ANY8H:    return 8;
1056       case BRW_PREDICATE_ALIGN1_ALL8H:    return 8;
1057       case BRW_PREDICATE_ALIGN1_ANY16H:   return 16;
1058       case BRW_PREDICATE_ALIGN1_ALL16H:   return 16;
1059       case BRW_PREDICATE_ALIGN1_ANY32H:   return 32;
1060       case BRW_PREDICATE_ALIGN1_ALL32H:   return 32;
1061       default: unreachable("Unsupported predicate");
1062       }
1063    }
1064 
1065    /* Return the subset of flag registers that an instruction could
1066     * potentially read or write based on the execution controls and flag
1067     * subregister number of the instruction.
1068     */
1069    unsigned
flag_mask(const fs_inst * inst,unsigned width)1070    flag_mask(const fs_inst *inst, unsigned width)
1071    {
1072       assert(util_is_power_of_two_nonzero(width));
1073       const unsigned start = (inst->flag_subreg * 16 + inst->group) &
1074                              ~(width - 1);
1075       const unsigned end = start + ALIGN(inst->exec_size, width);
1076       return ((1 << DIV_ROUND_UP(end, 8)) - 1) & ~((1 << (start / 8)) - 1);
1077    }
1078 
1079    unsigned
bit_mask(unsigned n)1080    bit_mask(unsigned n)
1081    {
1082       return (n >= CHAR_BIT * sizeof(bit_mask(n)) ? ~0u : (1u << n) - 1);
1083    }
1084 
1085    unsigned
flag_mask(const fs_reg & r,unsigned sz)1086    flag_mask(const fs_reg &r, unsigned sz)
1087    {
1088       if (r.file == ARF) {
1089          const unsigned start = (r.nr - BRW_ARF_FLAG) * 4 + r.subnr;
1090          const unsigned end = start + sz;
1091          return bit_mask(end) & ~bit_mask(start);
1092       } else {
1093          return 0;
1094       }
1095    }
1096 }
1097 
1098 unsigned
flags_read(const intel_device_info * devinfo) const1099 fs_inst::flags_read(const intel_device_info *devinfo) const
1100 {
1101    if (predicate == BRW_PREDICATE_ALIGN1_ANYV ||
1102        predicate == BRW_PREDICATE_ALIGN1_ALLV) {
1103       /* The vertical predication modes combine corresponding bits from
1104        * f0.0 and f1.0 on Gfx7+, and f0.0 and f0.1 on older hardware.
1105        */
1106       const unsigned shift = devinfo->ver >= 7 ? 4 : 2;
1107       return flag_mask(this, 1) << shift | flag_mask(this, 1);
1108    } else if (predicate) {
1109       return flag_mask(this, predicate_width(predicate));
1110    } else {
1111       unsigned mask = 0;
1112       for (int i = 0; i < sources; i++) {
1113          mask |= flag_mask(src[i], size_read(i));
1114       }
1115       return mask;
1116    }
1117 }
1118 
1119 unsigned
flags_written(const intel_device_info * devinfo) const1120 fs_inst::flags_written(const intel_device_info *devinfo) const
1121 {
1122    /* On Gfx4 and Gfx5, sel.l (for min) and sel.ge (for max) are implemented
1123     * using a separte cmpn and sel instruction.  This lowering occurs in
1124     * fs_vistor::lower_minmax which is called very, very late.
1125     */
1126    if ((conditional_mod && ((opcode != BRW_OPCODE_SEL || devinfo->ver <= 5) &&
1127                             opcode != BRW_OPCODE_CSEL &&
1128                             opcode != BRW_OPCODE_IF &&
1129                             opcode != BRW_OPCODE_WHILE)) ||
1130        opcode == FS_OPCODE_FB_WRITE) {
1131       return flag_mask(this, 1);
1132    } else if (opcode == SHADER_OPCODE_FIND_LIVE_CHANNEL ||
1133               opcode == FS_OPCODE_LOAD_LIVE_CHANNELS) {
1134       return flag_mask(this, 32);
1135    } else {
1136       return flag_mask(dst, size_written);
1137    }
1138 }
1139 
1140 /**
1141  * Returns how many MRFs an FS opcode will write over.
1142  *
1143  * Note that this is not the 0 or 1 implied writes in an actual gen
1144  * instruction -- the FS opcodes often generate MOVs in addition.
1145  */
1146 unsigned
implied_mrf_writes() const1147 fs_inst::implied_mrf_writes() const
1148 {
1149    if (mlen == 0)
1150       return 0;
1151 
1152    if (base_mrf == -1)
1153       return 0;
1154 
1155    switch (opcode) {
1156    case SHADER_OPCODE_RCP:
1157    case SHADER_OPCODE_RSQ:
1158    case SHADER_OPCODE_SQRT:
1159    case SHADER_OPCODE_EXP2:
1160    case SHADER_OPCODE_LOG2:
1161    case SHADER_OPCODE_SIN:
1162    case SHADER_OPCODE_COS:
1163       return 1 * exec_size / 8;
1164    case SHADER_OPCODE_POW:
1165    case SHADER_OPCODE_INT_QUOTIENT:
1166    case SHADER_OPCODE_INT_REMAINDER:
1167       return 2 * exec_size / 8;
1168    case SHADER_OPCODE_TEX:
1169    case FS_OPCODE_TXB:
1170    case SHADER_OPCODE_TXD:
1171    case SHADER_OPCODE_TXF:
1172    case SHADER_OPCODE_TXF_CMS:
1173    case SHADER_OPCODE_TXF_MCS:
1174    case SHADER_OPCODE_TG4:
1175    case SHADER_OPCODE_TG4_OFFSET:
1176    case SHADER_OPCODE_TXL:
1177    case SHADER_OPCODE_TXS:
1178    case SHADER_OPCODE_LOD:
1179    case SHADER_OPCODE_SAMPLEINFO:
1180       return 1;
1181    case FS_OPCODE_FB_WRITE:
1182    case FS_OPCODE_REP_FB_WRITE:
1183       return src[0].file == BAD_FILE ? 0 : 2;
1184    case FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD:
1185    case SHADER_OPCODE_GFX4_SCRATCH_READ:
1186       return 1;
1187    case FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_GFX4:
1188       return mlen;
1189    case SHADER_OPCODE_GFX4_SCRATCH_WRITE:
1190       return mlen;
1191    default:
1192       unreachable("not reached");
1193    }
1194 }
1195 
1196 fs_reg
vgrf(const glsl_type * const type)1197 fs_visitor::vgrf(const glsl_type *const type)
1198 {
1199    int reg_width = dispatch_width / 8;
1200    return fs_reg(VGRF,
1201                  alloc.allocate(glsl_count_dword_slots(type, false) * reg_width),
1202                  brw_type_for_base_type(type));
1203 }
1204 
fs_reg(enum brw_reg_file file,int nr)1205 fs_reg::fs_reg(enum brw_reg_file file, int nr)
1206 {
1207    init();
1208    this->file = file;
1209    this->nr = nr;
1210    this->type = BRW_REGISTER_TYPE_F;
1211    this->stride = (file == UNIFORM ? 0 : 1);
1212 }
1213 
fs_reg(enum brw_reg_file file,int nr,enum brw_reg_type type)1214 fs_reg::fs_reg(enum brw_reg_file file, int nr, enum brw_reg_type type)
1215 {
1216    init();
1217    this->file = file;
1218    this->nr = nr;
1219    this->type = type;
1220    this->stride = (file == UNIFORM ? 0 : 1);
1221 }
1222 
1223 /* For SIMD16, we need to follow from the uniform setup of SIMD8 dispatch.
1224  * This brings in those uniform definitions
1225  */
1226 void
import_uniforms(fs_visitor * v)1227 fs_visitor::import_uniforms(fs_visitor *v)
1228 {
1229    this->push_constant_loc = v->push_constant_loc;
1230    this->pull_constant_loc = v->pull_constant_loc;
1231    this->uniforms = v->uniforms;
1232    this->subgroup_id = v->subgroup_id;
1233    for (unsigned i = 0; i < ARRAY_SIZE(this->group_size); i++)
1234       this->group_size[i] = v->group_size[i];
1235 }
1236 
1237 void
emit_fragcoord_interpolation(fs_reg wpos)1238 fs_visitor::emit_fragcoord_interpolation(fs_reg wpos)
1239 {
1240    assert(stage == MESA_SHADER_FRAGMENT);
1241 
1242    /* gl_FragCoord.x */
1243    bld.MOV(wpos, this->pixel_x);
1244    wpos = offset(wpos, bld, 1);
1245 
1246    /* gl_FragCoord.y */
1247    bld.MOV(wpos, this->pixel_y);
1248    wpos = offset(wpos, bld, 1);
1249 
1250    /* gl_FragCoord.z */
1251    if (devinfo->ver >= 6) {
1252       bld.MOV(wpos, this->pixel_z);
1253    } else {
1254       bld.emit(FS_OPCODE_LINTERP, wpos,
1255                this->delta_xy[BRW_BARYCENTRIC_PERSPECTIVE_PIXEL],
1256                component(interp_reg(VARYING_SLOT_POS, 2), 0));
1257    }
1258    wpos = offset(wpos, bld, 1);
1259 
1260    /* gl_FragCoord.w: Already set up in emit_interpolation */
1261    bld.MOV(wpos, this->wpos_w);
1262 }
1263 
1264 enum brw_barycentric_mode
brw_barycentric_mode(enum glsl_interp_mode mode,nir_intrinsic_op op)1265 brw_barycentric_mode(enum glsl_interp_mode mode, nir_intrinsic_op op)
1266 {
1267    /* Barycentric modes don't make sense for flat inputs. */
1268    assert(mode != INTERP_MODE_FLAT);
1269 
1270    unsigned bary;
1271    switch (op) {
1272    case nir_intrinsic_load_barycentric_pixel:
1273    case nir_intrinsic_load_barycentric_at_offset:
1274       bary = BRW_BARYCENTRIC_PERSPECTIVE_PIXEL;
1275       break;
1276    case nir_intrinsic_load_barycentric_centroid:
1277       bary = BRW_BARYCENTRIC_PERSPECTIVE_CENTROID;
1278       break;
1279    case nir_intrinsic_load_barycentric_sample:
1280    case nir_intrinsic_load_barycentric_at_sample:
1281       bary = BRW_BARYCENTRIC_PERSPECTIVE_SAMPLE;
1282       break;
1283    default:
1284       unreachable("invalid intrinsic");
1285    }
1286 
1287    if (mode == INTERP_MODE_NOPERSPECTIVE)
1288       bary += 3;
1289 
1290    return (enum brw_barycentric_mode) bary;
1291 }
1292 
1293 /**
1294  * Turn one of the two CENTROID barycentric modes into PIXEL mode.
1295  */
1296 static enum brw_barycentric_mode
centroid_to_pixel(enum brw_barycentric_mode bary)1297 centroid_to_pixel(enum brw_barycentric_mode bary)
1298 {
1299    assert(bary == BRW_BARYCENTRIC_PERSPECTIVE_CENTROID ||
1300           bary == BRW_BARYCENTRIC_NONPERSPECTIVE_CENTROID);
1301    return (enum brw_barycentric_mode) ((unsigned) bary - 1);
1302 }
1303 
1304 fs_reg *
emit_frontfacing_interpolation()1305 fs_visitor::emit_frontfacing_interpolation()
1306 {
1307    fs_reg *reg = new(this->mem_ctx) fs_reg(vgrf(glsl_type::bool_type));
1308 
1309    if (devinfo->ver >= 12) {
1310       fs_reg g1 = fs_reg(retype(brw_vec1_grf(1, 1), BRW_REGISTER_TYPE_W));
1311 
1312       fs_reg tmp = bld.vgrf(BRW_REGISTER_TYPE_W);
1313       bld.ASR(tmp, g1, brw_imm_d(15));
1314       bld.NOT(*reg, tmp);
1315    } else if (devinfo->ver >= 6) {
1316       /* Bit 15 of g0.0 is 0 if the polygon is front facing. We want to create
1317        * a boolean result from this (~0/true or 0/false).
1318        *
1319        * We can use the fact that bit 15 is the MSB of g0.0:W to accomplish
1320        * this task in only one instruction:
1321        *    - a negation source modifier will flip the bit; and
1322        *    - a W -> D type conversion will sign extend the bit into the high
1323        *      word of the destination.
1324        *
1325        * An ASR 15 fills the low word of the destination.
1326        */
1327       fs_reg g0 = fs_reg(retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_W));
1328       g0.negate = true;
1329 
1330       bld.ASR(*reg, g0, brw_imm_d(15));
1331    } else {
1332       /* Bit 31 of g1.6 is 0 if the polygon is front facing. We want to create
1333        * a boolean result from this (1/true or 0/false).
1334        *
1335        * Like in the above case, since the bit is the MSB of g1.6:UD we can use
1336        * the negation source modifier to flip it. Unfortunately the SHR
1337        * instruction only operates on UD (or D with an abs source modifier)
1338        * sources without negation.
1339        *
1340        * Instead, use ASR (which will give ~0/true or 0/false).
1341        */
1342       fs_reg g1_6 = fs_reg(retype(brw_vec1_grf(1, 6), BRW_REGISTER_TYPE_D));
1343       g1_6.negate = true;
1344 
1345       bld.ASR(*reg, g1_6, brw_imm_d(31));
1346    }
1347 
1348    return reg;
1349 }
1350 
1351 void
compute_sample_position(fs_reg dst,fs_reg int_sample_pos)1352 fs_visitor::compute_sample_position(fs_reg dst, fs_reg int_sample_pos)
1353 {
1354    assert(stage == MESA_SHADER_FRAGMENT);
1355    struct brw_wm_prog_data *wm_prog_data = brw_wm_prog_data(this->prog_data);
1356    assert(dst.type == BRW_REGISTER_TYPE_F);
1357 
1358    if (wm_prog_data->persample_dispatch) {
1359       /* Convert int_sample_pos to floating point */
1360       bld.MOV(dst, int_sample_pos);
1361       /* Scale to the range [0, 1] */
1362       bld.MUL(dst, dst, brw_imm_f(1 / 16.0f));
1363    }
1364    else {
1365       /* From ARB_sample_shading specification:
1366        * "When rendering to a non-multisample buffer, or if multisample
1367        *  rasterization is disabled, gl_SamplePosition will always be
1368        *  (0.5, 0.5).
1369        */
1370       bld.MOV(dst, brw_imm_f(0.5f));
1371    }
1372 }
1373 
1374 fs_reg *
emit_samplepos_setup()1375 fs_visitor::emit_samplepos_setup()
1376 {
1377    assert(devinfo->ver >= 6);
1378 
1379    const fs_builder abld = bld.annotate("compute sample position");
1380    fs_reg *reg = new(this->mem_ctx) fs_reg(vgrf(glsl_type::vec2_type));
1381    fs_reg pos = *reg;
1382    fs_reg int_sample_x = vgrf(glsl_type::int_type);
1383    fs_reg int_sample_y = vgrf(glsl_type::int_type);
1384 
1385    /* WM will be run in MSDISPMODE_PERSAMPLE. So, only one of SIMD8 or SIMD16
1386     * mode will be enabled.
1387     *
1388     * From the Ivy Bridge PRM, volume 2 part 1, page 344:
1389     * R31.1:0         Position Offset X/Y for Slot[3:0]
1390     * R31.3:2         Position Offset X/Y for Slot[7:4]
1391     * .....
1392     *
1393     * The X, Y sample positions come in as bytes in  thread payload. So, read
1394     * the positions using vstride=16, width=8, hstride=2.
1395     */
1396    const fs_reg sample_pos_reg =
1397       fetch_payload_reg(abld, payload.sample_pos_reg, BRW_REGISTER_TYPE_W);
1398 
1399    /* Compute gl_SamplePosition.x */
1400    abld.MOV(int_sample_x, subscript(sample_pos_reg, BRW_REGISTER_TYPE_B, 0));
1401    compute_sample_position(offset(pos, abld, 0), int_sample_x);
1402 
1403    /* Compute gl_SamplePosition.y */
1404    abld.MOV(int_sample_y, subscript(sample_pos_reg, BRW_REGISTER_TYPE_B, 1));
1405    compute_sample_position(offset(pos, abld, 1), int_sample_y);
1406    return reg;
1407 }
1408 
1409 fs_reg *
emit_sampleid_setup()1410 fs_visitor::emit_sampleid_setup()
1411 {
1412    assert(stage == MESA_SHADER_FRAGMENT);
1413    brw_wm_prog_key *key = (brw_wm_prog_key*) this->key;
1414    assert(devinfo->ver >= 6);
1415 
1416    const fs_builder abld = bld.annotate("compute sample id");
1417    fs_reg *reg = new(this->mem_ctx) fs_reg(vgrf(glsl_type::uint_type));
1418 
1419    if (!key->multisample_fbo) {
1420       /* As per GL_ARB_sample_shading specification:
1421        * "When rendering to a non-multisample buffer, or if multisample
1422        *  rasterization is disabled, gl_SampleID will always be zero."
1423        */
1424       abld.MOV(*reg, brw_imm_d(0));
1425    } else if (devinfo->ver >= 8) {
1426       /* Sample ID comes in as 4-bit numbers in g1.0:
1427        *
1428        *    15:12 Slot 3 SampleID (only used in SIMD16)
1429        *     11:8 Slot 2 SampleID (only used in SIMD16)
1430        *      7:4 Slot 1 SampleID
1431        *      3:0 Slot 0 SampleID
1432        *
1433        * Each slot corresponds to four channels, so we want to replicate each
1434        * half-byte value to 4 channels in a row:
1435        *
1436        *    dst+0:    .7    .6    .5    .4    .3    .2    .1    .0
1437        *             7:4   7:4   7:4   7:4   3:0   3:0   3:0   3:0
1438        *
1439        *    dst+1:    .7    .6    .5    .4    .3    .2    .1    .0  (if SIMD16)
1440        *           15:12 15:12 15:12 15:12  11:8  11:8  11:8  11:8
1441        *
1442        * First, we read g1.0 with a <1,8,0>UB region, causing the first 8
1443        * channels to read the first byte (7:0), and the second group of 8
1444        * channels to read the second byte (15:8).  Then, we shift right by
1445        * a vector immediate of <4, 4, 4, 4, 0, 0, 0, 0>, moving the slot 1 / 3
1446        * values into place.  Finally, we AND with 0xf to keep the low nibble.
1447        *
1448        *    shr(16) tmp<1>W g1.0<1,8,0>B 0x44440000:V
1449        *    and(16) dst<1>D tmp<8,8,1>W  0xf:W
1450        *
1451        * TODO: These payload bits exist on Gfx7 too, but they appear to always
1452        *       be zero, so this code fails to work.  We should find out why.
1453        */
1454       const fs_reg tmp = abld.vgrf(BRW_REGISTER_TYPE_UW);
1455 
1456       for (unsigned i = 0; i < DIV_ROUND_UP(dispatch_width, 16); i++) {
1457          const fs_builder hbld = abld.group(MIN2(16, dispatch_width), i);
1458          hbld.SHR(offset(tmp, hbld, i),
1459                   stride(retype(brw_vec1_grf(1 + i, 0), BRW_REGISTER_TYPE_UB),
1460                          1, 8, 0),
1461                   brw_imm_v(0x44440000));
1462       }
1463 
1464       abld.AND(*reg, tmp, brw_imm_w(0xf));
1465    } else {
1466       const fs_reg t1 = component(abld.vgrf(BRW_REGISTER_TYPE_UD), 0);
1467       const fs_reg t2 = abld.vgrf(BRW_REGISTER_TYPE_UW);
1468 
1469       /* The PS will be run in MSDISPMODE_PERSAMPLE. For example with
1470        * 8x multisampling, subspan 0 will represent sample N (where N
1471        * is 0, 2, 4 or 6), subspan 1 will represent sample 1, 3, 5 or
1472        * 7. We can find the value of N by looking at R0.0 bits 7:6
1473        * ("Starting Sample Pair Index (SSPI)") and multiplying by two
1474        * (since samples are always delivered in pairs). That is, we
1475        * compute 2*((R0.0 & 0xc0) >> 6) == (R0.0 & 0xc0) >> 5. Then
1476        * we need to add N to the sequence (0, 0, 0, 0, 1, 1, 1, 1) in
1477        * case of SIMD8 and sequence (0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2,
1478        * 2, 3, 3, 3, 3) in case of SIMD16. We compute this sequence by
1479        * populating a temporary variable with the sequence (0, 1, 2, 3),
1480        * and then reading from it using vstride=1, width=4, hstride=0.
1481        * These computations hold good for 4x multisampling as well.
1482        *
1483        * For 2x MSAA and SIMD16, we want to use the sequence (0, 1, 0, 1):
1484        * the first four slots are sample 0 of subspan 0; the next four
1485        * are sample 1 of subspan 0; the third group is sample 0 of
1486        * subspan 1, and finally sample 1 of subspan 1.
1487        */
1488 
1489       /* SKL+ has an extra bit for the Starting Sample Pair Index to
1490        * accomodate 16x MSAA.
1491        */
1492       abld.exec_all().group(1, 0)
1493           .AND(t1, fs_reg(retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_UD)),
1494                brw_imm_ud(0xc0));
1495       abld.exec_all().group(1, 0).SHR(t1, t1, brw_imm_d(5));
1496 
1497       /* This works for SIMD8-SIMD16.  It also works for SIMD32 but only if we
1498        * can assume 4x MSAA.  Disallow it on IVB+
1499        *
1500        * FINISHME: One day, we could come up with a way to do this that
1501        * actually works on gfx7.
1502        */
1503       if (devinfo->ver >= 7)
1504          limit_dispatch_width(16, "gl_SampleId is unsupported in SIMD32 on gfx7");
1505       abld.exec_all().group(8, 0).MOV(t2, brw_imm_v(0x32103210));
1506 
1507       /* This special instruction takes care of setting vstride=1,
1508        * width=4, hstride=0 of t2 during an ADD instruction.
1509        */
1510       abld.emit(FS_OPCODE_SET_SAMPLE_ID, *reg, t1, t2);
1511    }
1512 
1513    return reg;
1514 }
1515 
1516 fs_reg *
emit_samplemaskin_setup()1517 fs_visitor::emit_samplemaskin_setup()
1518 {
1519    assert(stage == MESA_SHADER_FRAGMENT);
1520    struct brw_wm_prog_data *wm_prog_data = brw_wm_prog_data(this->prog_data);
1521    assert(devinfo->ver >= 6);
1522 
1523    fs_reg *reg = new(this->mem_ctx) fs_reg(vgrf(glsl_type::int_type));
1524 
1525    /* The HW doesn't provide us with expected values. */
1526    assert(!wm_prog_data->per_coarse_pixel_dispatch);
1527 
1528    fs_reg coverage_mask =
1529       fetch_payload_reg(bld, payload.sample_mask_in_reg, BRW_REGISTER_TYPE_D);
1530 
1531    if (wm_prog_data->persample_dispatch) {
1532       /* gl_SampleMaskIn[] comes from two sources: the input coverage mask,
1533        * and a mask representing which sample is being processed by the
1534        * current shader invocation.
1535        *
1536        * From the OES_sample_variables specification:
1537        * "When per-sample shading is active due to the use of a fragment input
1538        *  qualified by "sample" or due to the use of the gl_SampleID or
1539        *  gl_SamplePosition variables, only the bit for the current sample is
1540        *  set in gl_SampleMaskIn."
1541        */
1542       const fs_builder abld = bld.annotate("compute gl_SampleMaskIn");
1543 
1544       if (nir_system_values[SYSTEM_VALUE_SAMPLE_ID].file == BAD_FILE)
1545          nir_system_values[SYSTEM_VALUE_SAMPLE_ID] = *emit_sampleid_setup();
1546 
1547       fs_reg one = vgrf(glsl_type::int_type);
1548       fs_reg enabled_mask = vgrf(glsl_type::int_type);
1549       abld.MOV(one, brw_imm_d(1));
1550       abld.SHL(enabled_mask, one, nir_system_values[SYSTEM_VALUE_SAMPLE_ID]);
1551       abld.AND(*reg, enabled_mask, coverage_mask);
1552    } else {
1553       /* In per-pixel mode, the coverage mask is sufficient. */
1554       *reg = coverage_mask;
1555    }
1556    return reg;
1557 }
1558 
1559 fs_reg *
emit_shading_rate_setup()1560 fs_visitor::emit_shading_rate_setup()
1561 {
1562    assert(devinfo->ver >= 11);
1563 
1564    const fs_builder abld = bld.annotate("compute fragment shading rate");
1565 
1566    fs_reg *reg = new(this->mem_ctx) fs_reg(bld.vgrf(BRW_REGISTER_TYPE_UD));
1567 
1568    struct brw_wm_prog_data *wm_prog_data =
1569       brw_wm_prog_data(bld.shader->stage_prog_data);
1570 
1571    /* Coarse pixel shading size fields overlap with other fields of not in
1572     * coarse pixel dispatch mode, so report 0 when that's not the case.
1573     */
1574    if (wm_prog_data->per_coarse_pixel_dispatch) {
1575       /* The shading rates provided in the shader are the actual 2D shading
1576        * rate while the SPIR-V built-in is the enum value that has the shading
1577        * rate encoded as a bitfield.  Fortunately, the bitfield value is just
1578        * the shading rate divided by two and shifted.
1579        */
1580 
1581       /* r1.0 - 0:7 ActualCoarsePixelShadingSize.X */
1582       fs_reg actual_x = fs_reg(retype(brw_vec1_grf(1, 0), BRW_REGISTER_TYPE_UB));
1583       /* r1.0 - 15:8 ActualCoarsePixelShadingSize.Y */
1584       fs_reg actual_y = byte_offset(actual_x, 1);
1585 
1586       fs_reg int_rate_x = bld.vgrf(BRW_REGISTER_TYPE_UD);
1587       fs_reg int_rate_y = bld.vgrf(BRW_REGISTER_TYPE_UD);
1588 
1589       abld.SHR(int_rate_y, actual_y, brw_imm_ud(1));
1590       abld.SHR(int_rate_x, actual_x, brw_imm_ud(1));
1591       abld.SHL(int_rate_x, int_rate_x, brw_imm_ud(2));
1592       abld.OR(*reg, int_rate_x, int_rate_y);
1593    } else {
1594       abld.MOV(*reg, brw_imm_ud(0));
1595    }
1596 
1597    return reg;
1598 }
1599 
1600 fs_reg
resolve_source_modifiers(const fs_reg & src)1601 fs_visitor::resolve_source_modifiers(const fs_reg &src)
1602 {
1603    if (!src.abs && !src.negate)
1604       return src;
1605 
1606    fs_reg temp = bld.vgrf(src.type);
1607    bld.MOV(temp, src);
1608 
1609    return temp;
1610 }
1611 
1612 void
emit_gs_thread_end()1613 fs_visitor::emit_gs_thread_end()
1614 {
1615    assert(stage == MESA_SHADER_GEOMETRY);
1616 
1617    struct brw_gs_prog_data *gs_prog_data = brw_gs_prog_data(prog_data);
1618 
1619    if (gs_compile->control_data_header_size_bits > 0) {
1620       emit_gs_control_data_bits(this->final_gs_vertex_count);
1621    }
1622 
1623    const fs_builder abld = bld.annotate("thread end");
1624    fs_inst *inst;
1625 
1626    if (gs_prog_data->static_vertex_count != -1) {
1627       foreach_in_list_reverse(fs_inst, prev, &this->instructions) {
1628          if (prev->opcode == SHADER_OPCODE_URB_WRITE_SIMD8 ||
1629              prev->opcode == SHADER_OPCODE_URB_WRITE_SIMD8_MASKED ||
1630              prev->opcode == SHADER_OPCODE_URB_WRITE_SIMD8_PER_SLOT ||
1631              prev->opcode == SHADER_OPCODE_URB_WRITE_SIMD8_MASKED_PER_SLOT) {
1632             prev->eot = true;
1633 
1634             /* Delete now dead instructions. */
1635             foreach_in_list_reverse_safe(exec_node, dead, &this->instructions) {
1636                if (dead == prev)
1637                   break;
1638                dead->remove();
1639             }
1640             return;
1641          } else if (prev->is_control_flow() || prev->has_side_effects()) {
1642             break;
1643          }
1644       }
1645       fs_reg hdr = abld.vgrf(BRW_REGISTER_TYPE_UD, 1);
1646       abld.MOV(hdr, fs_reg(retype(brw_vec8_grf(1, 0), BRW_REGISTER_TYPE_UD)));
1647       inst = abld.emit(SHADER_OPCODE_URB_WRITE_SIMD8, reg_undef, hdr);
1648       inst->mlen = 1;
1649    } else {
1650       fs_reg payload = abld.vgrf(BRW_REGISTER_TYPE_UD, 2);
1651       fs_reg *sources = ralloc_array(mem_ctx, fs_reg, 2);
1652       sources[0] = fs_reg(retype(brw_vec8_grf(1, 0), BRW_REGISTER_TYPE_UD));
1653       sources[1] = this->final_gs_vertex_count;
1654       abld.LOAD_PAYLOAD(payload, sources, 2, 2);
1655       inst = abld.emit(SHADER_OPCODE_URB_WRITE_SIMD8, reg_undef, payload);
1656       inst->mlen = 2;
1657    }
1658    inst->eot = true;
1659    inst->offset = 0;
1660 }
1661 
1662 void
assign_curb_setup()1663 fs_visitor::assign_curb_setup()
1664 {
1665    unsigned uniform_push_length = DIV_ROUND_UP(stage_prog_data->nr_params, 8);
1666 
1667    unsigned ubo_push_length = 0;
1668    unsigned ubo_push_start[4];
1669    for (int i = 0; i < 4; i++) {
1670       ubo_push_start[i] = 8 * (ubo_push_length + uniform_push_length);
1671       ubo_push_length += stage_prog_data->ubo_ranges[i].length;
1672    }
1673 
1674    prog_data->curb_read_length = uniform_push_length + ubo_push_length;
1675 
1676    uint64_t used = 0;
1677 
1678    if (stage == MESA_SHADER_COMPUTE &&
1679        brw_cs_prog_data(prog_data)->uses_inline_data) {
1680       /* With COMPUTE_WALKER, we can push up to one register worth of data via
1681        * the inline data parameter in the COMPUTE_WALKER command itself.
1682        *
1683        * TODO: Support inline data and push at the same time.
1684        */
1685       assert(devinfo->verx10 >= 125);
1686       assert(uniform_push_length <= 1);
1687    } else if (stage == MESA_SHADER_COMPUTE && devinfo->verx10 >= 125) {
1688       fs_builder ubld = bld.exec_all().group(8, 0).at(
1689          cfg->first_block(), cfg->first_block()->start());
1690 
1691       /* The base address for our push data is passed in as R0.0[31:6].  We
1692        * have to mask off the bottom 6 bits.
1693        */
1694       fs_reg base_addr = ubld.vgrf(BRW_REGISTER_TYPE_UD);
1695       ubld.group(1, 0).AND(base_addr,
1696                            retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_UD),
1697                            brw_imm_ud(INTEL_MASK(31, 6)));
1698 
1699       fs_reg header0 = ubld.vgrf(BRW_REGISTER_TYPE_UD);
1700       ubld.MOV(header0, brw_imm_ud(0));
1701       ubld.group(1, 0).SHR(component(header0, 2), base_addr, brw_imm_ud(4));
1702 
1703       /* On Gfx12-HP we load constants at the start of the program using A32
1704        * stateless messages.
1705        */
1706       for (unsigned i = 0; i < uniform_push_length;) {
1707          /* Limit ourselves to HW limit of 8 Owords (8 * 16bytes = 128 bytes
1708           * or 4 registers).
1709           */
1710          unsigned num_regs = MIN2(uniform_push_length - i, 4);
1711          assert(num_regs > 0);
1712          num_regs = 1 << util_logbase2(num_regs);
1713 
1714          fs_reg header;
1715          if (i == 0) {
1716             header = header0;
1717          } else {
1718             header = ubld.vgrf(BRW_REGISTER_TYPE_UD);
1719             ubld.MOV(header, brw_imm_ud(0));
1720             ubld.group(1, 0).ADD(component(header, 2),
1721                                  component(header0, 2),
1722                                  brw_imm_ud(i * 2));
1723          }
1724 
1725          fs_reg srcs[4] = {
1726             brw_imm_ud(0), /* desc */
1727             brw_imm_ud(0), /* ex_desc */
1728             header, /* payload */
1729             fs_reg(), /* payload2 */
1730          };
1731 
1732          fs_reg dest = retype(brw_vec8_grf(payload.num_regs + i, 0),
1733                               BRW_REGISTER_TYPE_UD);
1734 
1735          /* This instruction has to be run SIMD16 if we're filling more than a
1736           * single register.
1737           */
1738          unsigned send_width = MIN2(16, num_regs * 8);
1739 
1740          fs_inst *send = ubld.group(send_width, 0).emit(SHADER_OPCODE_SEND,
1741                                                         dest, srcs, 4);
1742          send->sfid = GFX7_SFID_DATAPORT_DATA_CACHE;
1743          send->desc = brw_dp_desc(devinfo, GFX8_BTI_STATELESS_NON_COHERENT,
1744                                   GFX7_DATAPORT_DC_OWORD_BLOCK_READ,
1745                                   BRW_DATAPORT_OWORD_BLOCK_OWORDS(num_regs * 2));
1746          send->header_size = 1;
1747          send->mlen = 1;
1748          send->size_written = num_regs * REG_SIZE;
1749          send->send_is_volatile = true;
1750 
1751          i += num_regs;
1752       }
1753 
1754       invalidate_analysis(DEPENDENCY_INSTRUCTIONS);
1755    }
1756 
1757    /* Map the offsets in the UNIFORM file to fixed HW regs. */
1758    foreach_block_and_inst(block, fs_inst, inst, cfg) {
1759       for (unsigned int i = 0; i < inst->sources; i++) {
1760 	 if (inst->src[i].file == UNIFORM) {
1761             int uniform_nr = inst->src[i].nr + inst->src[i].offset / 4;
1762             int constant_nr;
1763             if (inst->src[i].nr >= UBO_START) {
1764                /* constant_nr is in 32-bit units, the rest are in bytes */
1765                constant_nr = ubo_push_start[inst->src[i].nr - UBO_START] +
1766                              inst->src[i].offset / 4;
1767             } else if (uniform_nr >= 0 && uniform_nr < (int) uniforms) {
1768                constant_nr = push_constant_loc[uniform_nr];
1769             } else {
1770                /* Section 5.11 of the OpenGL 4.1 spec says:
1771                 * "Out-of-bounds reads return undefined values, which include
1772                 *  values from other variables of the active program or zero."
1773                 * Just return the first push constant.
1774                 */
1775                constant_nr = 0;
1776             }
1777 
1778             assert(constant_nr / 8 < 64);
1779             used |= BITFIELD64_BIT(constant_nr / 8);
1780 
1781 	    struct brw_reg brw_reg = brw_vec1_grf(payload.num_regs +
1782 						  constant_nr / 8,
1783 						  constant_nr % 8);
1784             brw_reg.abs = inst->src[i].abs;
1785             brw_reg.negate = inst->src[i].negate;
1786 
1787             assert(inst->src[i].stride == 0);
1788             inst->src[i] = byte_offset(
1789                retype(brw_reg, inst->src[i].type),
1790                inst->src[i].offset % 4);
1791 	 }
1792       }
1793    }
1794 
1795    uint64_t want_zero = used & stage_prog_data->zero_push_reg;
1796    if (want_zero) {
1797       assert(!compiler->compact_params);
1798       fs_builder ubld = bld.exec_all().group(8, 0).at(
1799          cfg->first_block(), cfg->first_block()->start());
1800 
1801       /* push_reg_mask_param is in 32-bit units */
1802       unsigned mask_param = stage_prog_data->push_reg_mask_param;
1803       struct brw_reg mask = brw_vec1_grf(payload.num_regs + mask_param / 8,
1804                                                             mask_param % 8);
1805 
1806       fs_reg b32;
1807       for (unsigned i = 0; i < 64; i++) {
1808          if (i % 16 == 0 && (want_zero & BITFIELD64_RANGE(i, 16))) {
1809             fs_reg shifted = ubld.vgrf(BRW_REGISTER_TYPE_W, 2);
1810             ubld.SHL(horiz_offset(shifted, 8),
1811                      byte_offset(retype(mask, BRW_REGISTER_TYPE_W), i / 8),
1812                      brw_imm_v(0x01234567));
1813             ubld.SHL(shifted, horiz_offset(shifted, 8), brw_imm_w(8));
1814 
1815             fs_builder ubld16 = ubld.group(16, 0);
1816             b32 = ubld16.vgrf(BRW_REGISTER_TYPE_D);
1817             ubld16.group(16, 0).ASR(b32, shifted, brw_imm_w(15));
1818          }
1819 
1820          if (want_zero & BITFIELD64_BIT(i)) {
1821             assert(i < prog_data->curb_read_length);
1822             struct brw_reg push_reg =
1823                retype(brw_vec8_grf(payload.num_regs + i, 0),
1824                       BRW_REGISTER_TYPE_D);
1825 
1826             ubld.AND(push_reg, push_reg, component(b32, i % 16));
1827          }
1828       }
1829 
1830       invalidate_analysis(DEPENDENCY_INSTRUCTIONS);
1831    }
1832 
1833    /* This may be updated in assign_urb_setup or assign_vs_urb_setup. */
1834    this->first_non_payload_grf = payload.num_regs + prog_data->curb_read_length;
1835 }
1836 
1837 /*
1838  * Build up an array of indices into the urb_setup array that
1839  * references the active entries of the urb_setup array.
1840  * Used to accelerate walking the active entries of the urb_setup array
1841  * on each upload.
1842  */
1843 void
brw_compute_urb_setup_index(struct brw_wm_prog_data * wm_prog_data)1844 brw_compute_urb_setup_index(struct brw_wm_prog_data *wm_prog_data)
1845 {
1846    /* Make sure uint8_t is sufficient */
1847    STATIC_ASSERT(VARYING_SLOT_MAX <= 0xff);
1848    uint8_t index = 0;
1849    for (uint8_t attr = 0; attr < VARYING_SLOT_MAX; attr++) {
1850       if (wm_prog_data->urb_setup[attr] >= 0) {
1851          wm_prog_data->urb_setup_attribs[index++] = attr;
1852       }
1853    }
1854    wm_prog_data->urb_setup_attribs_count = index;
1855 }
1856 
1857 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)1858 calculate_urb_setup(const struct intel_device_info *devinfo,
1859                     const struct brw_wm_prog_key *key,
1860                     struct brw_wm_prog_data *prog_data,
1861                     const nir_shader *nir)
1862 {
1863    memset(prog_data->urb_setup, -1,
1864           sizeof(prog_data->urb_setup[0]) * VARYING_SLOT_MAX);
1865 
1866    int urb_next = 0;
1867    /* Figure out where each of the incoming setup attributes lands. */
1868    if (devinfo->ver >= 6) {
1869       if (util_bitcount64(nir->info.inputs_read &
1870                             BRW_FS_VARYING_INPUT_MASK) <= 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          for (unsigned int i = 0; i < VARYING_SLOT_MAX; i++) {
1881             if (nir->info.inputs_read & BRW_FS_VARYING_INPUT_MASK &
1882                 BITFIELD64_BIT(i)) {
1883                prog_data->urb_setup[i] = urb_next++;
1884             }
1885          }
1886       } else {
1887          /* We have enough input varyings that the SF/SBE pipeline stage can't
1888           * arbitrarily rearrange them to suit our whim; we have to put them
1889           * in an order that matches the output of the previous pipeline stage
1890           * (geometry or vertex shader).
1891           */
1892 
1893          /* Re-compute the VUE map here in the case that the one coming from
1894           * geometry has more than one position slot (used for Primitive
1895           * Replication).
1896           */
1897          struct brw_vue_map prev_stage_vue_map;
1898          brw_compute_vue_map(devinfo, &prev_stage_vue_map,
1899                              key->input_slots_valid,
1900                              nir->info.separate_shader, 1);
1901 
1902          int first_slot =
1903             brw_compute_first_urb_slot_required(nir->info.inputs_read,
1904                                                 &prev_stage_vue_map);
1905 
1906          assert(prev_stage_vue_map.num_slots <= first_slot + 32);
1907          for (int slot = first_slot; slot < prev_stage_vue_map.num_slots;
1908               slot++) {
1909             int varying = prev_stage_vue_map.slot_to_varying[slot];
1910             if (varying != BRW_VARYING_SLOT_PAD &&
1911                 (nir->info.inputs_read & BRW_FS_VARYING_INPUT_MASK &
1912                  BITFIELD64_BIT(varying))) {
1913                prog_data->urb_setup[varying] = slot - first_slot;
1914             }
1915          }
1916          urb_next = prev_stage_vue_map.num_slots - first_slot;
1917       }
1918    } else {
1919       /* FINISHME: The sf doesn't map VS->FS inputs for us very well. */
1920       for (unsigned int i = 0; i < VARYING_SLOT_MAX; i++) {
1921          /* Point size is packed into the header, not as a general attribute */
1922          if (i == VARYING_SLOT_PSIZ)
1923             continue;
1924 
1925 	 if (key->input_slots_valid & BITFIELD64_BIT(i)) {
1926 	    /* The back color slot is skipped when the front color is
1927 	     * also written to.  In addition, some slots can be
1928 	     * written in the vertex shader and not read in the
1929 	     * fragment shader.  So the register number must always be
1930 	     * incremented, mapped or not.
1931 	     */
1932 	    if (_mesa_varying_slot_in_fs((gl_varying_slot) i))
1933 	       prog_data->urb_setup[i] = urb_next;
1934             urb_next++;
1935 	 }
1936       }
1937 
1938       /*
1939        * It's a FS only attribute, and we did interpolation for this attribute
1940        * in SF thread. So, count it here, too.
1941        *
1942        * See compile_sf_prog() for more info.
1943        */
1944       if (nir->info.inputs_read & BITFIELD64_BIT(VARYING_SLOT_PNTC))
1945          prog_data->urb_setup[VARYING_SLOT_PNTC] = urb_next++;
1946    }
1947 
1948    prog_data->num_varying_inputs = urb_next;
1949    prog_data->inputs = nir->info.inputs_read;
1950 
1951    brw_compute_urb_setup_index(prog_data);
1952 }
1953 
1954 void
assign_urb_setup()1955 fs_visitor::assign_urb_setup()
1956 {
1957    assert(stage == MESA_SHADER_FRAGMENT);
1958    struct brw_wm_prog_data *prog_data = brw_wm_prog_data(this->prog_data);
1959 
1960    int urb_start = payload.num_regs + prog_data->base.curb_read_length;
1961 
1962    /* Offset all the urb_setup[] index by the actual position of the
1963     * setup regs, now that the location of the constants has been chosen.
1964     */
1965    foreach_block_and_inst(block, fs_inst, inst, cfg) {
1966       for (int i = 0; i < inst->sources; i++) {
1967          if (inst->src[i].file == ATTR) {
1968             /* ATTR regs in the FS are in units of logical scalar inputs each
1969              * of which consumes half of a GRF register.
1970              */
1971             assert(inst->src[i].offset < REG_SIZE / 2);
1972             const unsigned grf = urb_start + inst->src[i].nr / 2;
1973             const unsigned offset = (inst->src[i].nr % 2) * (REG_SIZE / 2) +
1974                                     inst->src[i].offset;
1975             const unsigned width = inst->src[i].stride == 0 ?
1976                                    1 : MIN2(inst->exec_size, 8);
1977             struct brw_reg reg = stride(
1978                byte_offset(retype(brw_vec8_grf(grf, 0), inst->src[i].type),
1979                            offset),
1980                width * inst->src[i].stride,
1981                width, inst->src[i].stride);
1982             reg.abs = inst->src[i].abs;
1983             reg.negate = inst->src[i].negate;
1984             inst->src[i] = reg;
1985          }
1986       }
1987    }
1988 
1989    /* Each attribute is 4 setup channels, each of which is half a reg. */
1990    this->first_non_payload_grf += prog_data->num_varying_inputs * 2;
1991 }
1992 
1993 void
convert_attr_sources_to_hw_regs(fs_inst * inst)1994 fs_visitor::convert_attr_sources_to_hw_regs(fs_inst *inst)
1995 {
1996    for (int i = 0; i < inst->sources; i++) {
1997       if (inst->src[i].file == ATTR) {
1998          int grf = payload.num_regs +
1999                    prog_data->curb_read_length +
2000                    inst->src[i].nr +
2001                    inst->src[i].offset / REG_SIZE;
2002 
2003          /* As explained at brw_reg_from_fs_reg, From the Haswell PRM:
2004           *
2005           * VertStride must be used to cross GRF register boundaries. This
2006           * rule implies that elements within a 'Width' cannot cross GRF
2007           * boundaries.
2008           *
2009           * So, for registers that are large enough, we have to split the exec
2010           * size in two and trust the compression state to sort it out.
2011           */
2012          unsigned total_size = inst->exec_size *
2013                                inst->src[i].stride *
2014                                type_sz(inst->src[i].type);
2015 
2016          assert(total_size <= 2 * REG_SIZE);
2017          const unsigned exec_size =
2018             (total_size <= REG_SIZE) ? inst->exec_size : inst->exec_size / 2;
2019 
2020          unsigned width = inst->src[i].stride == 0 ? 1 : exec_size;
2021          struct brw_reg reg =
2022             stride(byte_offset(retype(brw_vec8_grf(grf, 0), inst->src[i].type),
2023                                inst->src[i].offset % REG_SIZE),
2024                    exec_size * inst->src[i].stride,
2025                    width, inst->src[i].stride);
2026          reg.abs = inst->src[i].abs;
2027          reg.negate = inst->src[i].negate;
2028 
2029          inst->src[i] = reg;
2030       }
2031    }
2032 }
2033 
2034 void
assign_vs_urb_setup()2035 fs_visitor::assign_vs_urb_setup()
2036 {
2037    struct brw_vs_prog_data *vs_prog_data = brw_vs_prog_data(prog_data);
2038 
2039    assert(stage == MESA_SHADER_VERTEX);
2040 
2041    /* Each attribute is 4 regs. */
2042    this->first_non_payload_grf += 4 * vs_prog_data->nr_attribute_slots;
2043 
2044    assert(vs_prog_data->base.urb_read_length <= 15);
2045 
2046    /* Rewrite all ATTR file references to the hw grf that they land in. */
2047    foreach_block_and_inst(block, fs_inst, inst, cfg) {
2048       convert_attr_sources_to_hw_regs(inst);
2049    }
2050 }
2051 
2052 void
assign_tcs_urb_setup()2053 fs_visitor::assign_tcs_urb_setup()
2054 {
2055    assert(stage == MESA_SHADER_TESS_CTRL);
2056 
2057    /* Rewrite all ATTR file references to HW_REGs. */
2058    foreach_block_and_inst(block, fs_inst, inst, cfg) {
2059       convert_attr_sources_to_hw_regs(inst);
2060    }
2061 }
2062 
2063 void
assign_tes_urb_setup()2064 fs_visitor::assign_tes_urb_setup()
2065 {
2066    assert(stage == MESA_SHADER_TESS_EVAL);
2067 
2068    struct brw_vue_prog_data *vue_prog_data = brw_vue_prog_data(prog_data);
2069 
2070    first_non_payload_grf += 8 * vue_prog_data->urb_read_length;
2071 
2072    /* Rewrite all ATTR file references to HW_REGs. */
2073    foreach_block_and_inst(block, fs_inst, inst, cfg) {
2074       convert_attr_sources_to_hw_regs(inst);
2075    }
2076 }
2077 
2078 void
assign_gs_urb_setup()2079 fs_visitor::assign_gs_urb_setup()
2080 {
2081    assert(stage == MESA_SHADER_GEOMETRY);
2082 
2083    struct brw_vue_prog_data *vue_prog_data = brw_vue_prog_data(prog_data);
2084 
2085    first_non_payload_grf +=
2086       8 * vue_prog_data->urb_read_length * nir->info.gs.vertices_in;
2087 
2088    foreach_block_and_inst(block, fs_inst, inst, cfg) {
2089       /* Rewrite all ATTR file references to GRFs. */
2090       convert_attr_sources_to_hw_regs(inst);
2091    }
2092 }
2093 
2094 
2095 /**
2096  * Split large virtual GRFs into separate components if we can.
2097  *
2098  * This is mostly duplicated with what brw_fs_vector_splitting does,
2099  * but that's really conservative because it's afraid of doing
2100  * splitting that doesn't result in real progress after the rest of
2101  * the optimization phases, which would cause infinite looping in
2102  * optimization.  We can do it once here, safely.  This also has the
2103  * opportunity to split interpolated values, or maybe even uniforms,
2104  * which we don't have at the IR level.
2105  *
2106  * We want to split, because virtual GRFs are what we register
2107  * allocate and spill (due to contiguousness requirements for some
2108  * instructions), and they're what we naturally generate in the
2109  * codegen process, but most virtual GRFs don't actually need to be
2110  * contiguous sets of GRFs.  If we split, we'll end up with reduced
2111  * live intervals and better dead code elimination and coalescing.
2112  */
2113 void
split_virtual_grfs()2114 fs_visitor::split_virtual_grfs()
2115 {
2116    /* Compact the register file so we eliminate dead vgrfs.  This
2117     * only defines split points for live registers, so if we have
2118     * too large dead registers they will hit assertions later.
2119     */
2120    compact_virtual_grfs();
2121 
2122    int num_vars = this->alloc.count;
2123 
2124    /* Count the total number of registers */
2125    int reg_count = 0;
2126    int vgrf_to_reg[num_vars];
2127    for (int i = 0; i < num_vars; i++) {
2128       vgrf_to_reg[i] = reg_count;
2129       reg_count += alloc.sizes[i];
2130    }
2131 
2132    /* An array of "split points".  For each register slot, this indicates
2133     * if this slot can be separated from the previous slot.  Every time an
2134     * instruction uses multiple elements of a register (as a source or
2135     * destination), we mark the used slots as inseparable.  Then we go
2136     * through and split the registers into the smallest pieces we can.
2137     */
2138    bool *split_points = new bool[reg_count];
2139    memset(split_points, 0, reg_count * sizeof(*split_points));
2140 
2141    /* Mark all used registers as fully splittable */
2142    foreach_block_and_inst(block, fs_inst, inst, cfg) {
2143       if (inst->dst.file == VGRF) {
2144          int reg = vgrf_to_reg[inst->dst.nr];
2145          for (unsigned j = 1; j < this->alloc.sizes[inst->dst.nr]; j++)
2146             split_points[reg + j] = true;
2147       }
2148 
2149       for (int i = 0; i < inst->sources; i++) {
2150          if (inst->src[i].file == VGRF) {
2151             int reg = vgrf_to_reg[inst->src[i].nr];
2152             for (unsigned j = 1; j < this->alloc.sizes[inst->src[i].nr]; j++)
2153                split_points[reg + j] = true;
2154          }
2155       }
2156    }
2157 
2158    foreach_block_and_inst(block, fs_inst, inst, cfg) {
2159       /* We fix up undef instructions later */
2160       if (inst->opcode == SHADER_OPCODE_UNDEF) {
2161          /* UNDEF instructions are currently only used to undef entire
2162           * registers.  We need this invariant later when we split them.
2163           */
2164          assert(inst->dst.file == VGRF);
2165          assert(inst->dst.offset == 0);
2166          assert(inst->size_written == alloc.sizes[inst->dst.nr] * REG_SIZE);
2167          continue;
2168       }
2169 
2170       if (inst->dst.file == VGRF) {
2171          int reg = vgrf_to_reg[inst->dst.nr] + inst->dst.offset / REG_SIZE;
2172          for (unsigned j = 1; j < regs_written(inst); j++)
2173             split_points[reg + j] = false;
2174       }
2175       for (int i = 0; i < inst->sources; i++) {
2176          if (inst->src[i].file == VGRF) {
2177             int reg = vgrf_to_reg[inst->src[i].nr] + inst->src[i].offset / REG_SIZE;
2178             for (unsigned j = 1; j < regs_read(inst, i); j++)
2179                split_points[reg + j] = false;
2180          }
2181       }
2182    }
2183 
2184    int *new_virtual_grf = new int[reg_count];
2185    int *new_reg_offset = new int[reg_count];
2186 
2187    int reg = 0;
2188    for (int i = 0; i < num_vars; i++) {
2189       /* The first one should always be 0 as a quick sanity check. */
2190       assert(split_points[reg] == false);
2191 
2192       /* j = 0 case */
2193       new_reg_offset[reg] = 0;
2194       reg++;
2195       int offset = 1;
2196 
2197       /* j > 0 case */
2198       for (unsigned j = 1; j < alloc.sizes[i]; j++) {
2199          /* If this is a split point, reset the offset to 0 and allocate a
2200           * new virtual GRF for the previous offset many registers
2201           */
2202          if (split_points[reg]) {
2203             assert(offset <= MAX_VGRF_SIZE);
2204             int grf = alloc.allocate(offset);
2205             for (int k = reg - offset; k < reg; k++)
2206                new_virtual_grf[k] = grf;
2207             offset = 0;
2208          }
2209          new_reg_offset[reg] = offset;
2210          offset++;
2211          reg++;
2212       }
2213 
2214       /* The last one gets the original register number */
2215       assert(offset <= MAX_VGRF_SIZE);
2216       alloc.sizes[i] = offset;
2217       for (int k = reg - offset; k < reg; k++)
2218          new_virtual_grf[k] = i;
2219    }
2220    assert(reg == reg_count);
2221 
2222    foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
2223       if (inst->opcode == SHADER_OPCODE_UNDEF) {
2224          const fs_builder ibld(this, block, inst);
2225          assert(inst->size_written % REG_SIZE == 0);
2226          unsigned reg_offset = 0;
2227          while (reg_offset < inst->size_written / REG_SIZE) {
2228             reg = vgrf_to_reg[inst->dst.nr] + reg_offset;
2229             ibld.UNDEF(fs_reg(VGRF, new_virtual_grf[reg], inst->dst.type));
2230             reg_offset += alloc.sizes[new_virtual_grf[reg]];
2231          }
2232          inst->remove(block);
2233          continue;
2234       }
2235 
2236       if (inst->dst.file == VGRF) {
2237          reg = vgrf_to_reg[inst->dst.nr] + inst->dst.offset / REG_SIZE;
2238          inst->dst.nr = new_virtual_grf[reg];
2239          inst->dst.offset = new_reg_offset[reg] * REG_SIZE +
2240                             inst->dst.offset % REG_SIZE;
2241          assert((unsigned)new_reg_offset[reg] < alloc.sizes[new_virtual_grf[reg]]);
2242       }
2243       for (int i = 0; i < inst->sources; i++) {
2244 	 if (inst->src[i].file == VGRF) {
2245             reg = vgrf_to_reg[inst->src[i].nr] + inst->src[i].offset / REG_SIZE;
2246             inst->src[i].nr = new_virtual_grf[reg];
2247             inst->src[i].offset = new_reg_offset[reg] * REG_SIZE +
2248                                   inst->src[i].offset % REG_SIZE;
2249             assert((unsigned)new_reg_offset[reg] < alloc.sizes[new_virtual_grf[reg]]);
2250          }
2251       }
2252    }
2253    invalidate_analysis(DEPENDENCY_INSTRUCTION_DETAIL | DEPENDENCY_VARIABLES);
2254 
2255    delete[] split_points;
2256    delete[] new_virtual_grf;
2257    delete[] new_reg_offset;
2258 }
2259 
2260 /**
2261  * Remove unused virtual GRFs and compact the vgrf_* arrays.
2262  *
2263  * During code generation, we create tons of temporary variables, many of
2264  * which get immediately killed and are never used again.  Yet, in later
2265  * optimization and analysis passes, such as compute_live_intervals, we need
2266  * to loop over all the virtual GRFs.  Compacting them can save a lot of
2267  * overhead.
2268  */
2269 bool
compact_virtual_grfs()2270 fs_visitor::compact_virtual_grfs()
2271 {
2272    bool progress = false;
2273    int *remap_table = new int[this->alloc.count];
2274    memset(remap_table, -1, this->alloc.count * sizeof(int));
2275 
2276    /* Mark which virtual GRFs are used. */
2277    foreach_block_and_inst(block, const fs_inst, inst, cfg) {
2278       if (inst->dst.file == VGRF)
2279          remap_table[inst->dst.nr] = 0;
2280 
2281       for (int i = 0; i < inst->sources; i++) {
2282          if (inst->src[i].file == VGRF)
2283             remap_table[inst->src[i].nr] = 0;
2284       }
2285    }
2286 
2287    /* Compact the GRF arrays. */
2288    int new_index = 0;
2289    for (unsigned i = 0; i < this->alloc.count; i++) {
2290       if (remap_table[i] == -1) {
2291          /* We just found an unused register.  This means that we are
2292           * actually going to compact something.
2293           */
2294          progress = true;
2295       } else {
2296          remap_table[i] = new_index;
2297          alloc.sizes[new_index] = alloc.sizes[i];
2298          invalidate_analysis(DEPENDENCY_INSTRUCTION_DETAIL | DEPENDENCY_VARIABLES);
2299          ++new_index;
2300       }
2301    }
2302 
2303    this->alloc.count = new_index;
2304 
2305    /* Patch all the instructions to use the newly renumbered registers */
2306    foreach_block_and_inst(block, fs_inst, inst, cfg) {
2307       if (inst->dst.file == VGRF)
2308          inst->dst.nr = remap_table[inst->dst.nr];
2309 
2310       for (int i = 0; i < inst->sources; i++) {
2311          if (inst->src[i].file == VGRF)
2312             inst->src[i].nr = remap_table[inst->src[i].nr];
2313       }
2314    }
2315 
2316    /* Patch all the references to delta_xy, since they're used in register
2317     * allocation.  If they're unused, switch them to BAD_FILE so we don't
2318     * think some random VGRF is delta_xy.
2319     */
2320    for (unsigned i = 0; i < ARRAY_SIZE(delta_xy); i++) {
2321       if (delta_xy[i].file == VGRF) {
2322          if (remap_table[delta_xy[i].nr] != -1) {
2323             delta_xy[i].nr = remap_table[delta_xy[i].nr];
2324          } else {
2325             delta_xy[i].file = BAD_FILE;
2326          }
2327       }
2328    }
2329 
2330    delete[] remap_table;
2331 
2332    return progress;
2333 }
2334 
2335 static int
get_subgroup_id_param_index(const intel_device_info * devinfo,const brw_stage_prog_data * prog_data)2336 get_subgroup_id_param_index(const intel_device_info *devinfo,
2337                             const brw_stage_prog_data *prog_data)
2338 {
2339    if (prog_data->nr_params == 0)
2340       return -1;
2341 
2342    if (devinfo->verx10 >= 125)
2343       return -1;
2344 
2345    /* The local thread id is always the last parameter in the list */
2346    uint32_t last_param = prog_data->param[prog_data->nr_params - 1];
2347    if (last_param == BRW_PARAM_BUILTIN_SUBGROUP_ID)
2348       return prog_data->nr_params - 1;
2349 
2350    return -1;
2351 }
2352 
2353 /**
2354  * Struct for handling complex alignments.
2355  *
2356  * A complex alignment is stored as multiplier and an offset.  A value is
2357  * considered to be aligned if it is {offset} larger than a multiple of {mul}.
2358  * For instance, with an alignment of {8, 2}, cplx_align_apply would do the
2359  * following:
2360  *
2361  *  N  | cplx_align_apply({8, 2}, N)
2362  * ----+-----------------------------
2363  *  4  | 6
2364  *  6  | 6
2365  *  8  | 14
2366  *  10 | 14
2367  *  12 | 14
2368  *  14 | 14
2369  *  16 | 22
2370  */
2371 struct cplx_align {
2372    unsigned mul:4;
2373    unsigned offset:4;
2374 };
2375 
2376 #define CPLX_ALIGN_MAX_MUL 8
2377 
2378 static void
cplx_align_assert_sane(struct cplx_align a)2379 cplx_align_assert_sane(struct cplx_align a)
2380 {
2381    assert(a.mul > 0 && util_is_power_of_two_nonzero(a.mul));
2382    assert(a.offset < a.mul);
2383 }
2384 
2385 /**
2386  * Combines two alignments to produce a least multiple of sorts.
2387  *
2388  * The returned alignment is the smallest (in terms of multiplier) such that
2389  * anything aligned to both a and b will be aligned to the new alignment.
2390  * This function will assert-fail if a and b are not compatible, i.e. if the
2391  * offset parameters are such that no common alignment is possible.
2392  */
2393 static struct cplx_align
cplx_align_combine(struct cplx_align a,struct cplx_align b)2394 cplx_align_combine(struct cplx_align a, struct cplx_align b)
2395 {
2396    cplx_align_assert_sane(a);
2397    cplx_align_assert_sane(b);
2398 
2399    /* Assert that the alignments agree. */
2400    assert((a.offset & (b.mul - 1)) == (b.offset & (a.mul - 1)));
2401 
2402    return a.mul > b.mul ? a : b;
2403 }
2404 
2405 /**
2406  * Apply a complex alignment
2407  *
2408  * This function will return the smallest number greater than or equal to
2409  * offset that is aligned to align.
2410  */
2411 static unsigned
cplx_align_apply(struct cplx_align align,unsigned offset)2412 cplx_align_apply(struct cplx_align align, unsigned offset)
2413 {
2414    return ALIGN(offset - align.offset, align.mul) + align.offset;
2415 }
2416 
2417 #define UNIFORM_SLOT_SIZE 4
2418 
2419 struct uniform_slot_info {
2420    /** True if the given uniform slot is live */
2421    unsigned is_live:1;
2422 
2423    /** True if this slot and the next slot must remain contiguous */
2424    unsigned contiguous:1;
2425 
2426    struct cplx_align align;
2427 };
2428 
2429 static void
mark_uniform_slots_read(struct uniform_slot_info * slots,unsigned num_slots,unsigned alignment)2430 mark_uniform_slots_read(struct uniform_slot_info *slots,
2431                         unsigned num_slots, unsigned alignment)
2432 {
2433    assert(alignment > 0 && util_is_power_of_two_nonzero(alignment));
2434    assert(alignment <= CPLX_ALIGN_MAX_MUL);
2435 
2436    /* We can't align a slot to anything less than the slot size */
2437    alignment = MAX2(alignment, UNIFORM_SLOT_SIZE);
2438 
2439    struct cplx_align align = {alignment, 0};
2440    cplx_align_assert_sane(align);
2441 
2442    for (unsigned i = 0; i < num_slots; i++) {
2443       slots[i].is_live = true;
2444       if (i < num_slots - 1)
2445          slots[i].contiguous = true;
2446 
2447       align.offset = (i * UNIFORM_SLOT_SIZE) & (align.mul - 1);
2448       if (slots[i].align.mul == 0) {
2449          slots[i].align = align;
2450       } else {
2451          slots[i].align = cplx_align_combine(slots[i].align, align);
2452       }
2453    }
2454 }
2455 
2456 /**
2457  * Assign UNIFORM file registers to either push constants or pull constants.
2458  *
2459  * We allow a fragment shader to have more than the specified minimum
2460  * maximum number of fragment shader uniform components (64).  If
2461  * there are too many of these, they'd fill up all of register space.
2462  * So, this will push some of them out to the pull constant buffer and
2463  * update the program to load them.
2464  */
2465 void
assign_constant_locations()2466 fs_visitor::assign_constant_locations()
2467 {
2468    /* Only the first compile gets to decide on locations. */
2469    if (push_constant_loc) {
2470       assert(pull_constant_loc);
2471       return;
2472    }
2473 
2474    if (compiler->compact_params) {
2475       struct uniform_slot_info slots[uniforms + 1];
2476       memset(slots, 0, sizeof(slots));
2477 
2478       foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
2479          for (int i = 0 ; i < inst->sources; i++) {
2480             if (inst->src[i].file != UNIFORM)
2481                continue;
2482 
2483             /* NIR tightly packs things so the uniform number might not be
2484              * aligned (if we have a double right after a float, for
2485              * instance).  This is fine because the process of re-arranging
2486              * them will ensure that things are properly aligned.  The offset
2487              * into that uniform, however, must be aligned.
2488              *
2489              * In Vulkan, we have explicit offsets but everything is crammed
2490              * into a single "variable" so inst->src[i].nr will always be 0.
2491              * Everything will be properly aligned relative to that one base.
2492              */
2493             assert(inst->src[i].offset % type_sz(inst->src[i].type) == 0);
2494 
2495             unsigned u = inst->src[i].nr +
2496                          inst->src[i].offset / UNIFORM_SLOT_SIZE;
2497 
2498             if (u >= uniforms)
2499                continue;
2500 
2501             unsigned slots_read;
2502             if (inst->opcode == SHADER_OPCODE_MOV_INDIRECT && i == 0) {
2503                slots_read = DIV_ROUND_UP(inst->src[2].ud, UNIFORM_SLOT_SIZE);
2504             } else {
2505                unsigned bytes_read = inst->components_read(i) *
2506                                      type_sz(inst->src[i].type);
2507                slots_read = DIV_ROUND_UP(bytes_read, UNIFORM_SLOT_SIZE);
2508             }
2509 
2510             assert(u + slots_read <= uniforms);
2511             mark_uniform_slots_read(&slots[u], slots_read,
2512                                     type_sz(inst->src[i].type));
2513          }
2514       }
2515 
2516       int subgroup_id_index = get_subgroup_id_param_index(devinfo,
2517                                                           stage_prog_data);
2518 
2519       /* Only allow 16 registers (128 uniform components) as push constants.
2520        *
2521        * Just demote the end of the list.  We could probably do better
2522        * here, demoting things that are rarely used in the program first.
2523        *
2524        * If changing this value, note the limitation about total_regs in
2525        * brw_curbe.c.
2526        */
2527       unsigned int max_push_components = 16 * 8;
2528       if (subgroup_id_index >= 0)
2529          max_push_components--; /* Save a slot for the thread ID */
2530 
2531       /* We push small arrays, but no bigger than 16 floats.  This is big
2532        * enough for a vec4 but hopefully not large enough to push out other
2533        * stuff.  We should probably use a better heuristic at some point.
2534        */
2535       const unsigned int max_chunk_size = 16;
2536 
2537       unsigned int num_push_constants = 0;
2538       unsigned int num_pull_constants = 0;
2539 
2540       push_constant_loc = ralloc_array(mem_ctx, int, uniforms);
2541       pull_constant_loc = ralloc_array(mem_ctx, int, uniforms);
2542 
2543       /* Default to -1 meaning no location */
2544       memset(push_constant_loc, -1, uniforms * sizeof(*push_constant_loc));
2545       memset(pull_constant_loc, -1, uniforms * sizeof(*pull_constant_loc));
2546 
2547       int chunk_start = -1;
2548       struct cplx_align align;
2549       for (unsigned u = 0; u < uniforms; u++) {
2550          if (!slots[u].is_live) {
2551             assert(chunk_start == -1);
2552             continue;
2553          }
2554 
2555          /* Skip subgroup_id_index to put it in the last push register. */
2556          if (subgroup_id_index == (int)u)
2557             continue;
2558 
2559          if (chunk_start == -1) {
2560             chunk_start = u;
2561             align = slots[u].align;
2562          } else {
2563             /* Offset into the chunk */
2564             unsigned chunk_offset = (u - chunk_start) * UNIFORM_SLOT_SIZE;
2565 
2566             /* Shift the slot alignment down by the chunk offset so it is
2567              * comparable with the base chunk alignment.
2568              */
2569             struct cplx_align slot_align = slots[u].align;
2570             slot_align.offset =
2571                (slot_align.offset - chunk_offset) & (align.mul - 1);
2572 
2573             align = cplx_align_combine(align, slot_align);
2574          }
2575 
2576          /* Sanity check the alignment */
2577          cplx_align_assert_sane(align);
2578 
2579          if (slots[u].contiguous)
2580             continue;
2581 
2582          /* Adjust the alignment to be in terms of slots, not bytes */
2583          assert((align.mul & (UNIFORM_SLOT_SIZE - 1)) == 0);
2584          assert((align.offset & (UNIFORM_SLOT_SIZE - 1)) == 0);
2585          align.mul /= UNIFORM_SLOT_SIZE;
2586          align.offset /= UNIFORM_SLOT_SIZE;
2587 
2588          unsigned push_start_align = cplx_align_apply(align, num_push_constants);
2589          unsigned chunk_size = u - chunk_start + 1;
2590          if ((!compiler->supports_pull_constants && u < UBO_START) ||
2591              (chunk_size < max_chunk_size &&
2592               push_start_align + chunk_size <= max_push_components)) {
2593             /* Align up the number of push constants */
2594             num_push_constants = push_start_align;
2595             for (unsigned i = 0; i < chunk_size; i++)
2596                push_constant_loc[chunk_start + i] = num_push_constants++;
2597          } else {
2598             /* We need to pull this one */
2599             num_pull_constants = cplx_align_apply(align, num_pull_constants);
2600             for (unsigned i = 0; i < chunk_size; i++)
2601                pull_constant_loc[chunk_start + i] = num_pull_constants++;
2602          }
2603 
2604          /* Reset the chunk and start again */
2605          chunk_start = -1;
2606       }
2607 
2608       /* Add the CS local thread ID uniform at the end of the push constants */
2609       if (subgroup_id_index >= 0)
2610          push_constant_loc[subgroup_id_index] = num_push_constants++;
2611 
2612       /* As the uniforms are going to be reordered, stash the old array and
2613        * create two new arrays for push/pull params.
2614        */
2615       uint32_t *param = stage_prog_data->param;
2616       stage_prog_data->nr_params = num_push_constants;
2617       if (num_push_constants) {
2618          stage_prog_data->param = rzalloc_array(mem_ctx, uint32_t,
2619                                                 num_push_constants);
2620       } else {
2621          stage_prog_data->param = NULL;
2622       }
2623       assert(stage_prog_data->nr_pull_params == 0);
2624       assert(stage_prog_data->pull_param == NULL);
2625       if (num_pull_constants > 0) {
2626          stage_prog_data->nr_pull_params = num_pull_constants;
2627          stage_prog_data->pull_param = rzalloc_array(mem_ctx, uint32_t,
2628                                                      num_pull_constants);
2629       }
2630 
2631       /* Up until now, the param[] array has been indexed by reg + offset
2632        * of UNIFORM registers.  Move pull constants into pull_param[] and
2633        * condense param[] to only contain the uniforms we chose to push.
2634        *
2635        * NOTE: Because we are condensing the params[] array, we know that
2636        * push_constant_loc[i] <= i and we can do it in one smooth loop without
2637        * having to make a copy.
2638        */
2639       for (unsigned int i = 0; i < uniforms; i++) {
2640          uint32_t value = param[i];
2641          if (pull_constant_loc[i] != -1) {
2642             stage_prog_data->pull_param[pull_constant_loc[i]] = value;
2643          } else if (push_constant_loc[i] != -1) {
2644             stage_prog_data->param[push_constant_loc[i]] = value;
2645          }
2646       }
2647       ralloc_free(param);
2648    } else {
2649       /* If we don't want to compact anything, just set up dummy push/pull
2650        * arrays.  All the rest of the compiler cares about are these arrays.
2651        */
2652       push_constant_loc = ralloc_array(mem_ctx, int, uniforms);
2653       pull_constant_loc = ralloc_array(mem_ctx, int, uniforms);
2654 
2655       for (unsigned u = 0; u < uniforms; u++)
2656          push_constant_loc[u] = u;
2657 
2658       memset(pull_constant_loc, -1, uniforms * sizeof(*pull_constant_loc));
2659    }
2660 
2661    /* Now that we know how many regular uniforms we'll push, reduce the
2662     * UBO push ranges so we don't exceed the 3DSTATE_CONSTANT limits.
2663     */
2664    /* For gen4/5:
2665     * Only allow 16 registers (128 uniform components) as push constants.
2666     *
2667     * If changing this value, note the limitation about total_regs in
2668     * brw_curbe.c/crocus_state.c
2669     */
2670    const unsigned max_push_length = compiler->devinfo->ver < 6 ? 16 : 64;
2671    unsigned push_length = DIV_ROUND_UP(stage_prog_data->nr_params, 8);
2672    for (int i = 0; i < 4; i++) {
2673       struct brw_ubo_range *range = &prog_data->ubo_ranges[i];
2674 
2675       if (push_length + range->length > max_push_length)
2676          range->length = max_push_length - push_length;
2677 
2678       push_length += range->length;
2679    }
2680    assert(push_length <= max_push_length);
2681 }
2682 
2683 bool
get_pull_locs(const fs_reg & src,unsigned * out_surf_index,unsigned * out_pull_index)2684 fs_visitor::get_pull_locs(const fs_reg &src,
2685                           unsigned *out_surf_index,
2686                           unsigned *out_pull_index)
2687 {
2688    assert(src.file == UNIFORM);
2689 
2690    if (src.nr >= UBO_START) {
2691       const struct brw_ubo_range *range =
2692          &prog_data->ubo_ranges[src.nr - UBO_START];
2693 
2694       /* If this access is in our (reduced) range, use the push data. */
2695       if (src.offset / 32 < range->length)
2696          return false;
2697 
2698       *out_surf_index = prog_data->binding_table.ubo_start + range->block;
2699       *out_pull_index = (32 * range->start + src.offset) / 4;
2700 
2701       prog_data->has_ubo_pull = true;
2702       return true;
2703    }
2704 
2705    const unsigned location = src.nr + src.offset / 4;
2706 
2707    if (location < uniforms && pull_constant_loc[location] != -1) {
2708       /* A regular uniform push constant */
2709       *out_surf_index = stage_prog_data->binding_table.pull_constants_start;
2710       *out_pull_index = pull_constant_loc[location];
2711 
2712       prog_data->has_ubo_pull = true;
2713       return true;
2714    }
2715 
2716    return false;
2717 }
2718 
2719 /**
2720  * Replace UNIFORM register file access with either UNIFORM_PULL_CONSTANT_LOAD
2721  * or VARYING_PULL_CONSTANT_LOAD instructions which load values into VGRFs.
2722  */
2723 void
lower_constant_loads()2724 fs_visitor::lower_constant_loads()
2725 {
2726    unsigned index, pull_index;
2727 
2728    foreach_block_and_inst_safe (block, fs_inst, inst, cfg) {
2729       /* Set up the annotation tracking for new generated instructions. */
2730       const fs_builder ibld(this, block, inst);
2731 
2732       for (int i = 0; i < inst->sources; i++) {
2733 	 if (inst->src[i].file != UNIFORM)
2734 	    continue;
2735 
2736          /* We'll handle this case later */
2737          if (inst->opcode == SHADER_OPCODE_MOV_INDIRECT && i == 0)
2738             continue;
2739 
2740          if (!get_pull_locs(inst->src[i], &index, &pull_index))
2741 	    continue;
2742 
2743          assert(inst->src[i].stride == 0);
2744 
2745          const unsigned block_sz = 64; /* Fetch one cacheline at a time. */
2746          const fs_builder ubld = ibld.exec_all().group(block_sz / 4, 0);
2747          const fs_reg dst = ubld.vgrf(BRW_REGISTER_TYPE_UD);
2748          const unsigned base = pull_index * 4;
2749 
2750          ubld.emit(FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD,
2751                    dst, brw_imm_ud(index), brw_imm_ud(base & ~(block_sz - 1)));
2752 
2753          /* Rewrite the instruction to use the temporary VGRF. */
2754          inst->src[i].file = VGRF;
2755          inst->src[i].nr = dst.nr;
2756          inst->src[i].offset = (base & (block_sz - 1)) +
2757                                inst->src[i].offset % 4;
2758       }
2759 
2760       if (inst->opcode == SHADER_OPCODE_MOV_INDIRECT &&
2761           inst->src[0].file == UNIFORM) {
2762 
2763          if (!get_pull_locs(inst->src[0], &index, &pull_index))
2764             continue;
2765 
2766          VARYING_PULL_CONSTANT_LOAD(ibld, inst->dst,
2767                                     brw_imm_ud(index),
2768                                     inst->src[1],
2769                                     pull_index * 4, 4);
2770          inst->remove(block);
2771       }
2772    }
2773    invalidate_analysis(DEPENDENCY_INSTRUCTIONS);
2774 }
2775 
2776 bool
opt_algebraic()2777 fs_visitor::opt_algebraic()
2778 {
2779    bool progress = false;
2780 
2781    foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
2782       switch (inst->opcode) {
2783       case BRW_OPCODE_MOV:
2784          if (!devinfo->has_64bit_float &&
2785              !devinfo->has_64bit_int &&
2786              (inst->dst.type == BRW_REGISTER_TYPE_DF ||
2787               inst->dst.type == BRW_REGISTER_TYPE_UQ ||
2788               inst->dst.type == BRW_REGISTER_TYPE_Q)) {
2789             assert(inst->dst.type == inst->src[0].type);
2790             assert(!inst->saturate);
2791             assert(!inst->src[0].abs);
2792             assert(!inst->src[0].negate);
2793             const brw::fs_builder ibld(this, block, inst);
2794 
2795             ibld.MOV(subscript(inst->dst, BRW_REGISTER_TYPE_UD, 1),
2796                      subscript(inst->src[0], BRW_REGISTER_TYPE_UD, 1));
2797             ibld.MOV(subscript(inst->dst, BRW_REGISTER_TYPE_UD, 0),
2798                      subscript(inst->src[0], BRW_REGISTER_TYPE_UD, 0));
2799 
2800             inst->remove(block);
2801             progress = true;
2802          }
2803 
2804          if ((inst->conditional_mod == BRW_CONDITIONAL_Z ||
2805               inst->conditional_mod == BRW_CONDITIONAL_NZ) &&
2806              inst->dst.is_null() &&
2807              (inst->src[0].abs || inst->src[0].negate)) {
2808             inst->src[0].abs = false;
2809             inst->src[0].negate = false;
2810             progress = true;
2811             break;
2812          }
2813 
2814          if (inst->src[0].file != IMM)
2815             break;
2816 
2817          if (inst->saturate) {
2818             /* Full mixed-type saturates don't happen.  However, we can end up
2819              * with things like:
2820              *
2821              *    mov.sat(8) g21<1>DF       -1F
2822              *
2823              * Other mixed-size-but-same-base-type cases may also be possible.
2824              */
2825             if (inst->dst.type != inst->src[0].type &&
2826                 inst->dst.type != BRW_REGISTER_TYPE_DF &&
2827                 inst->src[0].type != BRW_REGISTER_TYPE_F)
2828                assert(!"unimplemented: saturate mixed types");
2829 
2830             if (brw_saturate_immediate(inst->src[0].type,
2831                                        &inst->src[0].as_brw_reg())) {
2832                inst->saturate = false;
2833                progress = true;
2834             }
2835          }
2836          break;
2837 
2838       case BRW_OPCODE_MUL:
2839          if (inst->src[1].file != IMM)
2840             continue;
2841 
2842          /* a * 1.0 = a */
2843          if (inst->src[1].is_one()) {
2844             inst->opcode = BRW_OPCODE_MOV;
2845             inst->src[1] = reg_undef;
2846             progress = true;
2847             break;
2848          }
2849 
2850          /* a * -1.0 = -a */
2851          if (inst->src[1].is_negative_one()) {
2852             inst->opcode = BRW_OPCODE_MOV;
2853             inst->src[0].negate = !inst->src[0].negate;
2854             inst->src[1] = reg_undef;
2855             progress = true;
2856             break;
2857          }
2858 
2859          break;
2860       case BRW_OPCODE_ADD:
2861          if (inst->src[1].file != IMM)
2862             continue;
2863 
2864          if (brw_reg_type_is_integer(inst->src[1].type) &&
2865              inst->src[1].is_zero()) {
2866             inst->opcode = BRW_OPCODE_MOV;
2867             inst->src[1] = reg_undef;
2868             progress = true;
2869             break;
2870          }
2871 
2872          if (inst->src[0].file == IMM) {
2873             assert(inst->src[0].type == BRW_REGISTER_TYPE_F);
2874             inst->opcode = BRW_OPCODE_MOV;
2875             inst->src[0].f += inst->src[1].f;
2876             inst->src[1] = reg_undef;
2877             progress = true;
2878             break;
2879          }
2880          break;
2881       case BRW_OPCODE_OR:
2882          if (inst->src[0].equals(inst->src[1]) ||
2883              inst->src[1].is_zero()) {
2884             /* On Gfx8+, the OR instruction can have a source modifier that
2885              * performs logical not on the operand.  Cases of 'OR r0, ~r1, 0'
2886              * or 'OR r0, ~r1, ~r1' should become a NOT instead of a MOV.
2887              */
2888             if (inst->src[0].negate) {
2889                inst->opcode = BRW_OPCODE_NOT;
2890                inst->src[0].negate = false;
2891             } else {
2892                inst->opcode = BRW_OPCODE_MOV;
2893             }
2894             inst->src[1] = reg_undef;
2895             progress = true;
2896             break;
2897          }
2898          break;
2899       case BRW_OPCODE_CMP:
2900          if ((inst->conditional_mod == BRW_CONDITIONAL_Z ||
2901               inst->conditional_mod == BRW_CONDITIONAL_NZ) &&
2902              inst->src[1].is_zero() &&
2903              (inst->src[0].abs || inst->src[0].negate)) {
2904             inst->src[0].abs = false;
2905             inst->src[0].negate = false;
2906             progress = true;
2907             break;
2908          }
2909          break;
2910       case BRW_OPCODE_SEL:
2911          if (!devinfo->has_64bit_float &&
2912              !devinfo->has_64bit_int &&
2913              (inst->dst.type == BRW_REGISTER_TYPE_DF ||
2914               inst->dst.type == BRW_REGISTER_TYPE_UQ ||
2915               inst->dst.type == BRW_REGISTER_TYPE_Q)) {
2916             assert(inst->dst.type == inst->src[0].type);
2917             assert(!inst->saturate);
2918             assert(!inst->src[0].abs && !inst->src[0].negate);
2919             assert(!inst->src[1].abs && !inst->src[1].negate);
2920             const brw::fs_builder ibld(this, block, inst);
2921 
2922             set_predicate(inst->predicate,
2923                           ibld.SEL(subscript(inst->dst, BRW_REGISTER_TYPE_UD, 0),
2924                                    subscript(inst->src[0], BRW_REGISTER_TYPE_UD, 0),
2925                                    subscript(inst->src[1], BRW_REGISTER_TYPE_UD, 0)));
2926             set_predicate(inst->predicate,
2927                           ibld.SEL(subscript(inst->dst, BRW_REGISTER_TYPE_UD, 1),
2928                                    subscript(inst->src[0], BRW_REGISTER_TYPE_UD, 1),
2929                                    subscript(inst->src[1], BRW_REGISTER_TYPE_UD, 1)));
2930 
2931             inst->remove(block);
2932             progress = true;
2933          }
2934          if (inst->src[0].equals(inst->src[1])) {
2935             inst->opcode = BRW_OPCODE_MOV;
2936             inst->src[1] = reg_undef;
2937             inst->predicate = BRW_PREDICATE_NONE;
2938             inst->predicate_inverse = false;
2939             progress = true;
2940          } else if (inst->saturate && inst->src[1].file == IMM) {
2941             switch (inst->conditional_mod) {
2942             case BRW_CONDITIONAL_LE:
2943             case BRW_CONDITIONAL_L:
2944                switch (inst->src[1].type) {
2945                case BRW_REGISTER_TYPE_F:
2946                   if (inst->src[1].f >= 1.0f) {
2947                      inst->opcode = BRW_OPCODE_MOV;
2948                      inst->src[1] = reg_undef;
2949                      inst->conditional_mod = BRW_CONDITIONAL_NONE;
2950                      progress = true;
2951                   }
2952                   break;
2953                default:
2954                   break;
2955                }
2956                break;
2957             case BRW_CONDITIONAL_GE:
2958             case BRW_CONDITIONAL_G:
2959                switch (inst->src[1].type) {
2960                case BRW_REGISTER_TYPE_F:
2961                   if (inst->src[1].f <= 0.0f) {
2962                      inst->opcode = BRW_OPCODE_MOV;
2963                      inst->src[1] = reg_undef;
2964                      inst->conditional_mod = BRW_CONDITIONAL_NONE;
2965                      progress = true;
2966                   }
2967                   break;
2968                default:
2969                   break;
2970                }
2971             default:
2972                break;
2973             }
2974          }
2975          break;
2976       case BRW_OPCODE_MAD:
2977          if (inst->src[0].type != BRW_REGISTER_TYPE_F ||
2978              inst->src[1].type != BRW_REGISTER_TYPE_F ||
2979              inst->src[2].type != BRW_REGISTER_TYPE_F)
2980             break;
2981          if (inst->src[1].is_one()) {
2982             inst->opcode = BRW_OPCODE_ADD;
2983             inst->src[1] = inst->src[2];
2984             inst->src[2] = reg_undef;
2985             progress = true;
2986          } else if (inst->src[2].is_one()) {
2987             inst->opcode = BRW_OPCODE_ADD;
2988             inst->src[2] = reg_undef;
2989             progress = true;
2990          }
2991          break;
2992       case SHADER_OPCODE_BROADCAST:
2993          if (is_uniform(inst->src[0])) {
2994             inst->opcode = BRW_OPCODE_MOV;
2995             inst->sources = 1;
2996             inst->force_writemask_all = true;
2997             progress = true;
2998          } else if (inst->src[1].file == IMM) {
2999             inst->opcode = BRW_OPCODE_MOV;
3000             /* It's possible that the selected component will be too large and
3001              * overflow the register.  This can happen if someone does a
3002              * readInvocation() from GLSL or SPIR-V and provides an OOB
3003              * invocationIndex.  If this happens and we some how manage
3004              * to constant fold it in and get here, then component() may cause
3005              * us to start reading outside of the VGRF which will lead to an
3006              * assert later.  Instead, just let it wrap around if it goes over
3007              * exec_size.
3008              */
3009             const unsigned comp = inst->src[1].ud & (inst->exec_size - 1);
3010             inst->src[0] = component(inst->src[0], comp);
3011             inst->sources = 1;
3012             inst->force_writemask_all = true;
3013             progress = true;
3014          }
3015          break;
3016 
3017       case SHADER_OPCODE_SHUFFLE:
3018          if (is_uniform(inst->src[0])) {
3019             inst->opcode = BRW_OPCODE_MOV;
3020             inst->sources = 1;
3021             progress = true;
3022          } else if (inst->src[1].file == IMM) {
3023             inst->opcode = BRW_OPCODE_MOV;
3024             inst->src[0] = component(inst->src[0],
3025                                      inst->src[1].ud);
3026             inst->sources = 1;
3027             progress = true;
3028          }
3029          break;
3030 
3031       default:
3032 	 break;
3033       }
3034 
3035       /* Swap if src[0] is immediate. */
3036       if (progress && inst->is_commutative()) {
3037          if (inst->src[0].file == IMM) {
3038             fs_reg tmp = inst->src[1];
3039             inst->src[1] = inst->src[0];
3040             inst->src[0] = tmp;
3041          }
3042       }
3043    }
3044 
3045    if (progress)
3046       invalidate_analysis(DEPENDENCY_INSTRUCTION_DATA_FLOW |
3047                           DEPENDENCY_INSTRUCTION_DETAIL);
3048 
3049    return progress;
3050 }
3051 
3052 /**
3053  * Optimize sample messages that have constant zero values for the trailing
3054  * texture coordinates. We can just reduce the message length for these
3055  * instructions instead of reserving a register for it. Trailing parameters
3056  * that aren't sent default to zero anyway. This will cause the dead code
3057  * eliminator to remove the MOV instruction that would otherwise be emitted to
3058  * set up the zero value.
3059  */
3060 bool
opt_zero_samples()3061 fs_visitor::opt_zero_samples()
3062 {
3063    /* Gfx4 infers the texturing opcode based on the message length so we can't
3064     * change it.  Gfx12.5 has restrictions on the number of coordinate
3065     * parameters that have to be provided for some texture types
3066     * (Wa_14013363432).
3067     */
3068    if (devinfo->ver < 5 || devinfo->verx10 == 125)
3069       return false;
3070 
3071    bool progress = false;
3072 
3073    foreach_block_and_inst(block, fs_inst, inst, cfg) {
3074       if (!inst->is_tex())
3075          continue;
3076 
3077       fs_inst *load_payload = (fs_inst *) inst->prev;
3078 
3079       if (load_payload->is_head_sentinel() ||
3080           load_payload->opcode != SHADER_OPCODE_LOAD_PAYLOAD)
3081          continue;
3082 
3083       /* We don't want to remove the message header or the first parameter.
3084        * Removing the first parameter is not allowed, see the Haswell PRM
3085        * volume 7, page 149:
3086        *
3087        *     "Parameter 0 is required except for the sampleinfo message, which
3088        *      has no parameter 0"
3089        */
3090       while (inst->mlen > inst->header_size + inst->exec_size / 8 &&
3091              load_payload->src[(inst->mlen - inst->header_size) /
3092                                (inst->exec_size / 8) +
3093                                inst->header_size - 1].is_zero()) {
3094          inst->mlen -= inst->exec_size / 8;
3095          progress = true;
3096       }
3097    }
3098 
3099    if (progress)
3100       invalidate_analysis(DEPENDENCY_INSTRUCTION_DETAIL);
3101 
3102    return progress;
3103 }
3104 
3105 bool
opt_register_renaming()3106 fs_visitor::opt_register_renaming()
3107 {
3108    bool progress = false;
3109    int depth = 0;
3110 
3111    unsigned remap[alloc.count];
3112    memset(remap, ~0u, sizeof(unsigned) * alloc.count);
3113 
3114    foreach_block_and_inst(block, fs_inst, inst, cfg) {
3115       if (inst->opcode == BRW_OPCODE_IF || inst->opcode == BRW_OPCODE_DO) {
3116          depth++;
3117       } else if (inst->opcode == BRW_OPCODE_ENDIF ||
3118                  inst->opcode == BRW_OPCODE_WHILE) {
3119          depth--;
3120       }
3121 
3122       /* Rewrite instruction sources. */
3123       for (int i = 0; i < inst->sources; i++) {
3124          if (inst->src[i].file == VGRF &&
3125              remap[inst->src[i].nr] != ~0u &&
3126              remap[inst->src[i].nr] != inst->src[i].nr) {
3127             inst->src[i].nr = remap[inst->src[i].nr];
3128             progress = true;
3129          }
3130       }
3131 
3132       const unsigned dst = inst->dst.nr;
3133 
3134       if (depth == 0 &&
3135           inst->dst.file == VGRF &&
3136           alloc.sizes[inst->dst.nr] * REG_SIZE == inst->size_written &&
3137           !inst->is_partial_write()) {
3138          if (remap[dst] == ~0u) {
3139             remap[dst] = dst;
3140          } else {
3141             remap[dst] = alloc.allocate(regs_written(inst));
3142             inst->dst.nr = remap[dst];
3143             progress = true;
3144          }
3145       } else if (inst->dst.file == VGRF &&
3146                  remap[dst] != ~0u &&
3147                  remap[dst] != dst) {
3148          inst->dst.nr = remap[dst];
3149          progress = true;
3150       }
3151    }
3152 
3153    if (progress) {
3154       invalidate_analysis(DEPENDENCY_INSTRUCTION_DETAIL |
3155                           DEPENDENCY_VARIABLES);
3156 
3157       for (unsigned i = 0; i < ARRAY_SIZE(delta_xy); i++) {
3158          if (delta_xy[i].file == VGRF && remap[delta_xy[i].nr] != ~0u) {
3159             delta_xy[i].nr = remap[delta_xy[i].nr];
3160          }
3161       }
3162    }
3163 
3164    return progress;
3165 }
3166 
3167 /**
3168  * Remove redundant or useless halts.
3169  *
3170  * For example, we can eliminate halts in the following sequence:
3171  *
3172  * halt        (redundant with the next halt)
3173  * halt        (useless; jumps to the next instruction)
3174  * halt-target
3175  */
3176 bool
opt_redundant_halt()3177 fs_visitor::opt_redundant_halt()
3178 {
3179    bool progress = false;
3180 
3181    unsigned halt_count = 0;
3182    fs_inst *halt_target = NULL;
3183    bblock_t *halt_target_block = NULL;
3184    foreach_block_and_inst(block, fs_inst, inst, cfg) {
3185       if (inst->opcode == BRW_OPCODE_HALT)
3186          halt_count++;
3187 
3188       if (inst->opcode == SHADER_OPCODE_HALT_TARGET) {
3189          halt_target = inst;
3190          halt_target_block = block;
3191          break;
3192       }
3193    }
3194 
3195    if (!halt_target) {
3196       assert(halt_count == 0);
3197       return false;
3198    }
3199 
3200    /* Delete any HALTs immediately before the halt target. */
3201    for (fs_inst *prev = (fs_inst *) halt_target->prev;
3202         !prev->is_head_sentinel() && prev->opcode == BRW_OPCODE_HALT;
3203         prev = (fs_inst *) halt_target->prev) {
3204       prev->remove(halt_target_block);
3205       halt_count--;
3206       progress = true;
3207    }
3208 
3209    if (halt_count == 0) {
3210       halt_target->remove(halt_target_block);
3211       progress = true;
3212    }
3213 
3214    if (progress)
3215       invalidate_analysis(DEPENDENCY_INSTRUCTIONS);
3216 
3217    return progress;
3218 }
3219 
3220 /**
3221  * Compute a bitmask with GRF granularity with a bit set for each GRF starting
3222  * from \p r.offset which overlaps the region starting at \p s.offset and
3223  * spanning \p ds bytes.
3224  */
3225 static inline unsigned
mask_relative_to(const fs_reg & r,const fs_reg & s,unsigned ds)3226 mask_relative_to(const fs_reg &r, const fs_reg &s, unsigned ds)
3227 {
3228    const int rel_offset = reg_offset(s) - reg_offset(r);
3229    const int shift = rel_offset / REG_SIZE;
3230    const unsigned n = DIV_ROUND_UP(rel_offset % REG_SIZE + ds, REG_SIZE);
3231    assert(reg_space(r) == reg_space(s) &&
3232           shift >= 0 && shift < int(8 * sizeof(unsigned)));
3233    return ((1 << n) - 1) << shift;
3234 }
3235 
3236 bool
compute_to_mrf()3237 fs_visitor::compute_to_mrf()
3238 {
3239    bool progress = false;
3240    int next_ip = 0;
3241 
3242    /* No MRFs on Gen >= 7. */
3243    if (devinfo->ver >= 7)
3244       return false;
3245 
3246    const fs_live_variables &live = live_analysis.require();
3247 
3248    foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
3249       int ip = next_ip;
3250       next_ip++;
3251 
3252       if (inst->opcode != BRW_OPCODE_MOV ||
3253 	  inst->is_partial_write() ||
3254 	  inst->dst.file != MRF || inst->src[0].file != VGRF ||
3255 	  inst->dst.type != inst->src[0].type ||
3256 	  inst->src[0].abs || inst->src[0].negate ||
3257           !inst->src[0].is_contiguous() ||
3258           inst->src[0].offset % REG_SIZE != 0)
3259 	 continue;
3260 
3261       /* Can't compute-to-MRF this GRF if someone else was going to
3262        * read it later.
3263        */
3264       if (live.vgrf_end[inst->src[0].nr] > ip)
3265 	 continue;
3266 
3267       /* Found a move of a GRF to a MRF.  Let's see if we can go rewrite the
3268        * things that computed the value of all GRFs of the source region.  The
3269        * regs_left bitset keeps track of the registers we haven't yet found a
3270        * generating instruction for.
3271        */
3272       unsigned regs_left = (1 << regs_read(inst, 0)) - 1;
3273 
3274       foreach_inst_in_block_reverse_starting_from(fs_inst, scan_inst, inst) {
3275          if (regions_overlap(scan_inst->dst, scan_inst->size_written,
3276                              inst->src[0], inst->size_read(0))) {
3277 	    /* Found the last thing to write our reg we want to turn
3278 	     * into a compute-to-MRF.
3279 	     */
3280 
3281 	    /* If this one instruction didn't populate all the
3282 	     * channels, bail.  We might be able to rewrite everything
3283 	     * that writes that reg, but it would require smarter
3284 	     * tracking.
3285 	     */
3286 	    if (scan_inst->is_partial_write())
3287 	       break;
3288 
3289             /* Handling things not fully contained in the source of the copy
3290              * would need us to understand coalescing out more than one MOV at
3291              * a time.
3292              */
3293             if (!region_contained_in(scan_inst->dst, scan_inst->size_written,
3294                                      inst->src[0], inst->size_read(0)))
3295                break;
3296 
3297 	    /* SEND instructions can't have MRF as a destination. */
3298 	    if (scan_inst->mlen)
3299 	       break;
3300 
3301 	    if (devinfo->ver == 6) {
3302 	       /* gfx6 math instructions must have the destination be
3303 		* GRF, so no compute-to-MRF for them.
3304 		*/
3305 	       if (scan_inst->is_math()) {
3306 		  break;
3307 	       }
3308 	    }
3309 
3310             /* Clear the bits for any registers this instruction overwrites. */
3311             regs_left &= ~mask_relative_to(
3312                inst->src[0], scan_inst->dst, scan_inst->size_written);
3313             if (!regs_left)
3314                break;
3315 	 }
3316 
3317 	 /* We don't handle control flow here.  Most computation of
3318 	  * values that end up in MRFs are shortly before the MRF
3319 	  * write anyway.
3320 	  */
3321 	 if (block->start() == scan_inst)
3322 	    break;
3323 
3324 	 /* You can't read from an MRF, so if someone else reads our
3325 	  * MRF's source GRF that we wanted to rewrite, that stops us.
3326 	  */
3327 	 bool interfered = false;
3328 	 for (int i = 0; i < scan_inst->sources; i++) {
3329             if (regions_overlap(scan_inst->src[i], scan_inst->size_read(i),
3330                                 inst->src[0], inst->size_read(0))) {
3331 	       interfered = true;
3332 	    }
3333 	 }
3334 	 if (interfered)
3335 	    break;
3336 
3337          if (regions_overlap(scan_inst->dst, scan_inst->size_written,
3338                              inst->dst, inst->size_written)) {
3339 	    /* If somebody else writes our MRF here, we can't
3340 	     * compute-to-MRF before that.
3341 	     */
3342             break;
3343          }
3344 
3345          if (scan_inst->mlen > 0 && scan_inst->base_mrf != -1 &&
3346              regions_overlap(fs_reg(MRF, scan_inst->base_mrf), scan_inst->mlen * REG_SIZE,
3347                              inst->dst, inst->size_written)) {
3348 	    /* Found a SEND instruction, which means that there are
3349 	     * live values in MRFs from base_mrf to base_mrf +
3350 	     * scan_inst->mlen - 1.  Don't go pushing our MRF write up
3351 	     * above it.
3352 	     */
3353             break;
3354          }
3355       }
3356 
3357       if (regs_left)
3358          continue;
3359 
3360       /* Found all generating instructions of our MRF's source value, so it
3361        * should be safe to rewrite them to point to the MRF directly.
3362        */
3363       regs_left = (1 << regs_read(inst, 0)) - 1;
3364 
3365       foreach_inst_in_block_reverse_starting_from(fs_inst, scan_inst, inst) {
3366          if (regions_overlap(scan_inst->dst, scan_inst->size_written,
3367                              inst->src[0], inst->size_read(0))) {
3368             /* Clear the bits for any registers this instruction overwrites. */
3369             regs_left &= ~mask_relative_to(
3370                inst->src[0], scan_inst->dst, scan_inst->size_written);
3371 
3372             const unsigned rel_offset = reg_offset(scan_inst->dst) -
3373                                         reg_offset(inst->src[0]);
3374 
3375             if (inst->dst.nr & BRW_MRF_COMPR4) {
3376                /* Apply the same address transformation done by the hardware
3377                 * for COMPR4 MRF writes.
3378                 */
3379                assert(rel_offset < 2 * REG_SIZE);
3380                scan_inst->dst.nr = inst->dst.nr + rel_offset / REG_SIZE * 4;
3381 
3382                /* Clear the COMPR4 bit if the generating instruction is not
3383                 * compressed.
3384                 */
3385                if (scan_inst->size_written < 2 * REG_SIZE)
3386                   scan_inst->dst.nr &= ~BRW_MRF_COMPR4;
3387 
3388             } else {
3389                /* Calculate the MRF number the result of this instruction is
3390                 * ultimately written to.
3391                 */
3392                scan_inst->dst.nr = inst->dst.nr + rel_offset / REG_SIZE;
3393             }
3394 
3395             scan_inst->dst.file = MRF;
3396             scan_inst->dst.offset = inst->dst.offset + rel_offset % REG_SIZE;
3397             scan_inst->saturate |= inst->saturate;
3398             if (!regs_left)
3399                break;
3400          }
3401       }
3402 
3403       assert(!regs_left);
3404       inst->remove(block);
3405       progress = true;
3406    }
3407 
3408    if (progress)
3409       invalidate_analysis(DEPENDENCY_INSTRUCTIONS);
3410 
3411    return progress;
3412 }
3413 
3414 /**
3415  * Eliminate FIND_LIVE_CHANNEL instructions occurring outside any control
3416  * flow.  We could probably do better here with some form of divergence
3417  * analysis.
3418  */
3419 bool
eliminate_find_live_channel()3420 fs_visitor::eliminate_find_live_channel()
3421 {
3422    bool progress = false;
3423    unsigned depth = 0;
3424 
3425    if (!brw_stage_has_packed_dispatch(devinfo, stage, stage_prog_data)) {
3426       /* The optimization below assumes that channel zero is live on thread
3427        * dispatch, which may not be the case if the fixed function dispatches
3428        * threads sparsely.
3429        */
3430       return false;
3431    }
3432 
3433    foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
3434       switch (inst->opcode) {
3435       case BRW_OPCODE_IF:
3436       case BRW_OPCODE_DO:
3437          depth++;
3438          break;
3439 
3440       case BRW_OPCODE_ENDIF:
3441       case BRW_OPCODE_WHILE:
3442          depth--;
3443          break;
3444 
3445       case BRW_OPCODE_HALT:
3446          /* This can potentially make control flow non-uniform until the end
3447           * of the program.
3448           */
3449          return progress;
3450 
3451       case SHADER_OPCODE_FIND_LIVE_CHANNEL:
3452          if (depth == 0) {
3453             inst->opcode = BRW_OPCODE_MOV;
3454             inst->src[0] = brw_imm_ud(0u);
3455             inst->sources = 1;
3456             inst->force_writemask_all = true;
3457             progress = true;
3458          }
3459          break;
3460 
3461       default:
3462          break;
3463       }
3464    }
3465 
3466    if (progress)
3467       invalidate_analysis(DEPENDENCY_INSTRUCTION_DETAIL);
3468 
3469    return progress;
3470 }
3471 
3472 /**
3473  * Once we've generated code, try to convert normal FS_OPCODE_FB_WRITE
3474  * instructions to FS_OPCODE_REP_FB_WRITE.
3475  */
3476 void
emit_repclear_shader()3477 fs_visitor::emit_repclear_shader()
3478 {
3479    brw_wm_prog_key *key = (brw_wm_prog_key*) this->key;
3480    int base_mrf = 0;
3481    int color_mrf = base_mrf + 2;
3482    fs_inst *mov;
3483 
3484    if (uniforms > 0) {
3485       mov = bld.exec_all().group(4, 0)
3486                .MOV(brw_message_reg(color_mrf),
3487                     fs_reg(UNIFORM, 0, BRW_REGISTER_TYPE_F));
3488    } else {
3489       struct brw_reg reg =
3490          brw_reg(BRW_GENERAL_REGISTER_FILE, 2, 3, 0, 0, BRW_REGISTER_TYPE_UD,
3491                  BRW_VERTICAL_STRIDE_8, BRW_WIDTH_2, BRW_HORIZONTAL_STRIDE_4,
3492                  BRW_SWIZZLE_XYZW, WRITEMASK_XYZW);
3493 
3494       mov = bld.exec_all().group(4, 0)
3495                .MOV(brw_uvec_mrf(4, color_mrf, 0), fs_reg(reg));
3496    }
3497 
3498    fs_inst *write = NULL;
3499    if (key->nr_color_regions == 1) {
3500       write = bld.emit(FS_OPCODE_REP_FB_WRITE);
3501       write->saturate = key->clamp_fragment_color;
3502       write->base_mrf = color_mrf;
3503       write->target = 0;
3504       write->header_size = 0;
3505       write->mlen = 1;
3506    } else {
3507       assume(key->nr_color_regions > 0);
3508 
3509       struct brw_reg header =
3510          retype(brw_message_reg(base_mrf), BRW_REGISTER_TYPE_UD);
3511       bld.exec_all().group(16, 0)
3512          .MOV(header, retype(brw_vec8_grf(0, 0), BRW_REGISTER_TYPE_UD));
3513 
3514       for (int i = 0; i < key->nr_color_regions; ++i) {
3515          if (i > 0) {
3516             bld.exec_all().group(1, 0)
3517                .MOV(component(header, 2), brw_imm_ud(i));
3518          }
3519 
3520          write = bld.emit(FS_OPCODE_REP_FB_WRITE);
3521          write->saturate = key->clamp_fragment_color;
3522          write->base_mrf = base_mrf;
3523          write->target = i;
3524          write->header_size = 2;
3525          write->mlen = 3;
3526       }
3527    }
3528    write->eot = true;
3529    write->last_rt = true;
3530 
3531    calculate_cfg();
3532 
3533    assign_constant_locations();
3534    assign_curb_setup();
3535 
3536    /* Now that we have the uniform assigned, go ahead and force it to a vec4. */
3537    if (uniforms > 0) {
3538       assert(mov->src[0].file == FIXED_GRF);
3539       mov->src[0] = brw_vec4_grf(mov->src[0].nr, 0);
3540    }
3541 
3542    lower_scoreboard();
3543 }
3544 
3545 /**
3546  * Walks through basic blocks, looking for repeated MRF writes and
3547  * removing the later ones.
3548  */
3549 bool
remove_duplicate_mrf_writes()3550 fs_visitor::remove_duplicate_mrf_writes()
3551 {
3552    fs_inst *last_mrf_move[BRW_MAX_MRF(devinfo->ver)];
3553    bool progress = false;
3554 
3555    /* Need to update the MRF tracking for compressed instructions. */
3556    if (dispatch_width >= 16)
3557       return false;
3558 
3559    memset(last_mrf_move, 0, sizeof(last_mrf_move));
3560 
3561    foreach_block_and_inst_safe (block, fs_inst, inst, cfg) {
3562       if (inst->is_control_flow()) {
3563 	 memset(last_mrf_move, 0, sizeof(last_mrf_move));
3564       }
3565 
3566       if (inst->opcode == BRW_OPCODE_MOV &&
3567 	  inst->dst.file == MRF) {
3568          fs_inst *prev_inst = last_mrf_move[inst->dst.nr];
3569 	 if (prev_inst && prev_inst->opcode == BRW_OPCODE_MOV &&
3570              inst->dst.equals(prev_inst->dst) &&
3571              inst->src[0].equals(prev_inst->src[0]) &&
3572              inst->saturate == prev_inst->saturate &&
3573              inst->predicate == prev_inst->predicate &&
3574              inst->conditional_mod == prev_inst->conditional_mod &&
3575              inst->exec_size == prev_inst->exec_size) {
3576 	    inst->remove(block);
3577 	    progress = true;
3578 	    continue;
3579 	 }
3580       }
3581 
3582       /* Clear out the last-write records for MRFs that were overwritten. */
3583       if (inst->dst.file == MRF) {
3584          last_mrf_move[inst->dst.nr] = NULL;
3585       }
3586 
3587       if (inst->mlen > 0 && inst->base_mrf != -1) {
3588 	 /* Found a SEND instruction, which will include two or fewer
3589 	  * implied MRF writes.  We could do better here.
3590 	  */
3591 	 for (unsigned i = 0; i < inst->implied_mrf_writes(); i++) {
3592 	    last_mrf_move[inst->base_mrf + i] = NULL;
3593 	 }
3594       }
3595 
3596       /* Clear out any MRF move records whose sources got overwritten. */
3597       for (unsigned i = 0; i < ARRAY_SIZE(last_mrf_move); i++) {
3598          if (last_mrf_move[i] &&
3599              regions_overlap(inst->dst, inst->size_written,
3600                              last_mrf_move[i]->src[0],
3601                              last_mrf_move[i]->size_read(0))) {
3602             last_mrf_move[i] = NULL;
3603          }
3604       }
3605 
3606       if (inst->opcode == BRW_OPCODE_MOV &&
3607 	  inst->dst.file == MRF &&
3608 	  inst->src[0].file != ARF &&
3609 	  !inst->is_partial_write()) {
3610          last_mrf_move[inst->dst.nr] = inst;
3611       }
3612    }
3613 
3614    if (progress)
3615       invalidate_analysis(DEPENDENCY_INSTRUCTIONS);
3616 
3617    return progress;
3618 }
3619 
3620 /**
3621  * Rounding modes for conversion instructions are included for each
3622  * conversion, but right now it is a state. So once it is set,
3623  * we don't need to call it again for subsequent calls.
3624  *
3625  * This is useful for vector/matrices conversions, as setting the
3626  * mode once is enough for the full vector/matrix
3627  */
3628 bool
remove_extra_rounding_modes()3629 fs_visitor::remove_extra_rounding_modes()
3630 {
3631    bool progress = false;
3632    unsigned execution_mode = this->nir->info.float_controls_execution_mode;
3633 
3634    brw_rnd_mode base_mode = BRW_RND_MODE_UNSPECIFIED;
3635    if ((FLOAT_CONTROLS_ROUNDING_MODE_RTE_FP16 |
3636         FLOAT_CONTROLS_ROUNDING_MODE_RTE_FP32 |
3637         FLOAT_CONTROLS_ROUNDING_MODE_RTE_FP64) &
3638        execution_mode)
3639       base_mode = BRW_RND_MODE_RTNE;
3640    if ((FLOAT_CONTROLS_ROUNDING_MODE_RTZ_FP16 |
3641         FLOAT_CONTROLS_ROUNDING_MODE_RTZ_FP32 |
3642         FLOAT_CONTROLS_ROUNDING_MODE_RTZ_FP64) &
3643        execution_mode)
3644       base_mode = BRW_RND_MODE_RTZ;
3645 
3646    foreach_block (block, cfg) {
3647       brw_rnd_mode prev_mode = base_mode;
3648 
3649       foreach_inst_in_block_safe (fs_inst, inst, block) {
3650          if (inst->opcode == SHADER_OPCODE_RND_MODE) {
3651             assert(inst->src[0].file == BRW_IMMEDIATE_VALUE);
3652             const brw_rnd_mode mode = (brw_rnd_mode) inst->src[0].d;
3653             if (mode == prev_mode) {
3654                inst->remove(block);
3655                progress = true;
3656             } else {
3657                prev_mode = mode;
3658             }
3659          }
3660       }
3661    }
3662 
3663    if (progress)
3664       invalidate_analysis(DEPENDENCY_INSTRUCTIONS);
3665 
3666    return progress;
3667 }
3668 
3669 static void
clear_deps_for_inst_src(fs_inst * inst,bool * deps,int first_grf,int grf_len)3670 clear_deps_for_inst_src(fs_inst *inst, bool *deps, int first_grf, int grf_len)
3671 {
3672    /* Clear the flag for registers that actually got read (as expected). */
3673    for (int i = 0; i < inst->sources; i++) {
3674       int grf;
3675       if (inst->src[i].file == VGRF || inst->src[i].file == FIXED_GRF) {
3676          grf = inst->src[i].nr;
3677       } else {
3678          continue;
3679       }
3680 
3681       if (grf >= first_grf &&
3682           grf < first_grf + grf_len) {
3683          deps[grf - first_grf] = false;
3684          if (inst->exec_size == 16)
3685             deps[grf - first_grf + 1] = false;
3686       }
3687    }
3688 }
3689 
3690 /**
3691  * Implements this workaround for the original 965:
3692  *
3693  *     "[DevBW, DevCL] Implementation Restrictions: As the hardware does not
3694  *      check for post destination dependencies on this instruction, software
3695  *      must ensure that there is no destination hazard for the case of ‘write
3696  *      followed by a posted write’ shown in the following example.
3697  *
3698  *      1. mov r3 0
3699  *      2. send r3.xy <rest of send instruction>
3700  *      3. mov r2 r3
3701  *
3702  *      Due to no post-destination dependency check on the ‘send’, the above
3703  *      code sequence could have two instructions (1 and 2) in flight at the
3704  *      same time that both consider ‘r3’ as the target of their final writes.
3705  */
3706 void
insert_gfx4_pre_send_dependency_workarounds(bblock_t * block,fs_inst * inst)3707 fs_visitor::insert_gfx4_pre_send_dependency_workarounds(bblock_t *block,
3708                                                         fs_inst *inst)
3709 {
3710    int write_len = regs_written(inst);
3711    int first_write_grf = inst->dst.nr;
3712    bool needs_dep[BRW_MAX_MRF(devinfo->ver)];
3713    assert(write_len < (int)sizeof(needs_dep) - 1);
3714 
3715    memset(needs_dep, false, sizeof(needs_dep));
3716    memset(needs_dep, true, write_len);
3717 
3718    clear_deps_for_inst_src(inst, needs_dep, first_write_grf, write_len);
3719 
3720    /* Walk backwards looking for writes to registers we're writing which
3721     * aren't read since being written.  If we hit the start of the program,
3722     * we assume that there are no outstanding dependencies on entry to the
3723     * program.
3724     */
3725    foreach_inst_in_block_reverse_starting_from(fs_inst, scan_inst, inst) {
3726       /* If we hit control flow, assume that there *are* outstanding
3727        * dependencies, and force their cleanup before our instruction.
3728        */
3729       if (block->start() == scan_inst && block->num != 0) {
3730          for (int i = 0; i < write_len; i++) {
3731             if (needs_dep[i])
3732                DEP_RESOLVE_MOV(fs_builder(this, block, inst),
3733                                first_write_grf + i);
3734          }
3735          return;
3736       }
3737 
3738       /* We insert our reads as late as possible on the assumption that any
3739        * instruction but a MOV that might have left us an outstanding
3740        * dependency has more latency than a MOV.
3741        */
3742       if (scan_inst->dst.file == VGRF) {
3743          for (unsigned i = 0; i < regs_written(scan_inst); i++) {
3744             int reg = scan_inst->dst.nr + i;
3745 
3746             if (reg >= first_write_grf &&
3747                 reg < first_write_grf + write_len &&
3748                 needs_dep[reg - first_write_grf]) {
3749                DEP_RESOLVE_MOV(fs_builder(this, block, inst), reg);
3750                needs_dep[reg - first_write_grf] = false;
3751                if (scan_inst->exec_size == 16)
3752                   needs_dep[reg - first_write_grf + 1] = false;
3753             }
3754          }
3755       }
3756 
3757       /* Clear the flag for registers that actually got read (as expected). */
3758       clear_deps_for_inst_src(scan_inst, needs_dep, first_write_grf, write_len);
3759 
3760       /* Continue the loop only if we haven't resolved all the dependencies */
3761       int i;
3762       for (i = 0; i < write_len; i++) {
3763          if (needs_dep[i])
3764             break;
3765       }
3766       if (i == write_len)
3767          return;
3768    }
3769 }
3770 
3771 /**
3772  * Implements this workaround for the original 965:
3773  *
3774  *     "[DevBW, DevCL] Errata: A destination register from a send can not be
3775  *      used as a destination register until after it has been sourced by an
3776  *      instruction with a different destination register.
3777  */
3778 void
insert_gfx4_post_send_dependency_workarounds(bblock_t * block,fs_inst * inst)3779 fs_visitor::insert_gfx4_post_send_dependency_workarounds(bblock_t *block, fs_inst *inst)
3780 {
3781    int write_len = regs_written(inst);
3782    unsigned first_write_grf = inst->dst.nr;
3783    bool needs_dep[BRW_MAX_MRF(devinfo->ver)];
3784    assert(write_len < (int)sizeof(needs_dep) - 1);
3785 
3786    memset(needs_dep, false, sizeof(needs_dep));
3787    memset(needs_dep, true, write_len);
3788    /* Walk forwards looking for writes to registers we're writing which aren't
3789     * read before being written.
3790     */
3791    foreach_inst_in_block_starting_from(fs_inst, scan_inst, inst) {
3792       /* If we hit control flow, force resolve all remaining dependencies. */
3793       if (block->end() == scan_inst && block->num != cfg->num_blocks - 1) {
3794          for (int i = 0; i < write_len; i++) {
3795             if (needs_dep[i])
3796                DEP_RESOLVE_MOV(fs_builder(this, block, scan_inst),
3797                                first_write_grf + i);
3798          }
3799          return;
3800       }
3801 
3802       /* Clear the flag for registers that actually got read (as expected). */
3803       clear_deps_for_inst_src(scan_inst, needs_dep, first_write_grf, write_len);
3804 
3805       /* We insert our reads as late as possible since they're reading the
3806        * result of a SEND, which has massive latency.
3807        */
3808       if (scan_inst->dst.file == VGRF &&
3809           scan_inst->dst.nr >= first_write_grf &&
3810           scan_inst->dst.nr < first_write_grf + write_len &&
3811           needs_dep[scan_inst->dst.nr - first_write_grf]) {
3812          DEP_RESOLVE_MOV(fs_builder(this, block, scan_inst),
3813                          scan_inst->dst.nr);
3814          needs_dep[scan_inst->dst.nr - first_write_grf] = false;
3815       }
3816 
3817       /* Continue the loop only if we haven't resolved all the dependencies */
3818       int i;
3819       for (i = 0; i < write_len; i++) {
3820          if (needs_dep[i])
3821             break;
3822       }
3823       if (i == write_len)
3824          return;
3825    }
3826 }
3827 
3828 void
insert_gfx4_send_dependency_workarounds()3829 fs_visitor::insert_gfx4_send_dependency_workarounds()
3830 {
3831    if (devinfo->ver != 4 || devinfo->is_g4x)
3832       return;
3833 
3834    bool progress = false;
3835 
3836    foreach_block_and_inst(block, fs_inst, inst, cfg) {
3837       if (inst->mlen != 0 && inst->dst.file == VGRF) {
3838          insert_gfx4_pre_send_dependency_workarounds(block, inst);
3839          insert_gfx4_post_send_dependency_workarounds(block, inst);
3840          progress = true;
3841       }
3842    }
3843 
3844    if (progress)
3845       invalidate_analysis(DEPENDENCY_INSTRUCTIONS);
3846 }
3847 
3848 /**
3849  * Turns the generic expression-style uniform pull constant load instruction
3850  * into a hardware-specific series of instructions for loading a pull
3851  * constant.
3852  *
3853  * The expression style allows the CSE pass before this to optimize out
3854  * repeated loads from the same offset, and gives the pre-register-allocation
3855  * scheduling full flexibility, while the conversion to native instructions
3856  * allows the post-register-allocation scheduler the best information
3857  * possible.
3858  *
3859  * Note that execution masking for setting up pull constant loads is special:
3860  * the channels that need to be written are unrelated to the current execution
3861  * mask, since a later instruction will use one of the result channels as a
3862  * source operand for all 8 or 16 of its channels.
3863  */
3864 void
lower_uniform_pull_constant_loads()3865 fs_visitor::lower_uniform_pull_constant_loads()
3866 {
3867    foreach_block_and_inst (block, fs_inst, inst, cfg) {
3868       if (inst->opcode != FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD)
3869          continue;
3870 
3871       const fs_reg& surface = inst->src[0];
3872       const fs_reg& offset_B = inst->src[1];
3873       assert(offset_B.file == IMM);
3874 
3875       if (devinfo->has_lsc) {
3876          const fs_builder ubld =
3877             fs_builder(this, block, inst).group(8, 0).exec_all();
3878 
3879          const fs_reg payload = ubld.vgrf(BRW_REGISTER_TYPE_UD);
3880          ubld.MOV(payload, offset_B);
3881 
3882          inst->sfid = GFX12_SFID_UGM;
3883          inst->desc = lsc_msg_desc(devinfo, LSC_OP_LOAD,
3884                                    1 /* simd_size */,
3885                                    LSC_ADDR_SURFTYPE_BTI,
3886                                    LSC_ADDR_SIZE_A32,
3887                                    1 /* num_coordinates */,
3888                                    LSC_DATA_SIZE_D32,
3889                                    inst->size_written / 4,
3890                                    true /* transpose */,
3891                                    LSC_CACHE_LOAD_L1STATE_L3MOCS,
3892                                    true /* has_dest */);
3893 
3894          fs_reg ex_desc;
3895          if (surface.file == IMM) {
3896             ex_desc = brw_imm_ud(lsc_bti_ex_desc(devinfo, surface.ud));
3897          } else {
3898             /* We only need the first component for the payload so we can use
3899              * one of the other components for the extended descriptor
3900              */
3901             ex_desc = component(payload, 1);
3902             ubld.group(1, 0).SHL(ex_desc, surface, brw_imm_ud(24));
3903          }
3904 
3905          /* Update the original instruction. */
3906          inst->opcode = SHADER_OPCODE_SEND;
3907          inst->mlen = lsc_msg_desc_src0_len(devinfo, inst->desc);
3908          inst->ex_mlen = 0;
3909          inst->header_size = 0;
3910          inst->send_has_side_effects = false;
3911          inst->send_is_volatile = true;
3912          inst->exec_size = 1;
3913 
3914          /* Finally, the payload */
3915          inst->resize_sources(3);
3916          inst->src[0] = brw_imm_ud(0); /* desc */
3917          inst->src[1] = ex_desc;
3918          inst->src[2] = payload;
3919 
3920          invalidate_analysis(DEPENDENCY_INSTRUCTIONS | DEPENDENCY_VARIABLES);
3921       } else if (devinfo->ver >= 7) {
3922          const fs_builder ubld = fs_builder(this, block, inst).exec_all();
3923          const fs_reg payload = ubld.group(8, 0).vgrf(BRW_REGISTER_TYPE_UD);
3924 
3925          ubld.group(8, 0).MOV(payload,
3926                               retype(brw_vec8_grf(0, 0), BRW_REGISTER_TYPE_UD));
3927          ubld.group(1, 0).MOV(component(payload, 2),
3928                               brw_imm_ud(offset_B.ud / 16));
3929 
3930          inst->opcode = FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD_GFX7;
3931          inst->src[1] = payload;
3932          inst->header_size = 1;
3933          inst->mlen = 1;
3934 
3935          invalidate_analysis(DEPENDENCY_INSTRUCTIONS | DEPENDENCY_VARIABLES);
3936       } else {
3937          /* Before register allocation, we didn't tell the scheduler about the
3938           * MRF we use.  We know it's safe to use this MRF because nothing
3939           * else does except for register spill/unspill, which generates and
3940           * uses its MRF within a single IR instruction.
3941           */
3942          inst->base_mrf = FIRST_PULL_LOAD_MRF(devinfo->ver) + 1;
3943          inst->mlen = 1;
3944       }
3945    }
3946 }
3947 
3948 bool
lower_load_payload()3949 fs_visitor::lower_load_payload()
3950 {
3951    bool progress = false;
3952 
3953    foreach_block_and_inst_safe (block, fs_inst, inst, cfg) {
3954       if (inst->opcode != SHADER_OPCODE_LOAD_PAYLOAD)
3955          continue;
3956 
3957       assert(inst->dst.file == MRF || inst->dst.file == VGRF);
3958       assert(inst->saturate == false);
3959       fs_reg dst = inst->dst;
3960 
3961       /* Get rid of COMPR4.  We'll add it back in if we need it */
3962       if (dst.file == MRF)
3963          dst.nr = dst.nr & ~BRW_MRF_COMPR4;
3964 
3965       const fs_builder ibld(this, block, inst);
3966       const fs_builder ubld = ibld.exec_all();
3967 
3968       for (uint8_t i = 0; i < inst->header_size;) {
3969          /* Number of header GRFs to initialize at once with a single MOV
3970           * instruction.
3971           */
3972          const unsigned n =
3973             (i + 1 < inst->header_size && inst->src[i].stride == 1 &&
3974              inst->src[i + 1].equals(byte_offset(inst->src[i], REG_SIZE))) ?
3975             2 : 1;
3976 
3977          if (inst->src[i].file != BAD_FILE)
3978             ubld.group(8 * n, 0).MOV(retype(dst, BRW_REGISTER_TYPE_UD),
3979                                      retype(inst->src[i], BRW_REGISTER_TYPE_UD));
3980 
3981          dst = byte_offset(dst, n * REG_SIZE);
3982          i += n;
3983       }
3984 
3985       if (inst->dst.file == MRF && (inst->dst.nr & BRW_MRF_COMPR4) &&
3986           inst->exec_size > 8) {
3987          /* In this case, the payload portion of the LOAD_PAYLOAD isn't
3988           * a straightforward copy.  Instead, the result of the
3989           * LOAD_PAYLOAD is treated as interleaved and the first four
3990           * non-header sources are unpacked as:
3991           *
3992           * m + 0: r0
3993           * m + 1: g0
3994           * m + 2: b0
3995           * m + 3: a0
3996           * m + 4: r1
3997           * m + 5: g1
3998           * m + 6: b1
3999           * m + 7: a1
4000           *
4001           * This is used for gen <= 5 fb writes.
4002           */
4003          assert(inst->exec_size == 16);
4004          assert(inst->header_size + 4 <= inst->sources);
4005          for (uint8_t i = inst->header_size; i < inst->header_size + 4; i++) {
4006             if (inst->src[i].file != BAD_FILE) {
4007                if (devinfo->has_compr4) {
4008                   fs_reg compr4_dst = retype(dst, inst->src[i].type);
4009                   compr4_dst.nr |= BRW_MRF_COMPR4;
4010                   ibld.MOV(compr4_dst, inst->src[i]);
4011                } else {
4012                   /* Platform doesn't have COMPR4.  We have to fake it */
4013                   fs_reg mov_dst = retype(dst, inst->src[i].type);
4014                   ibld.quarter(0).MOV(mov_dst, quarter(inst->src[i], 0));
4015                   mov_dst.nr += 4;
4016                   ibld.quarter(1).MOV(mov_dst, quarter(inst->src[i], 1));
4017                }
4018             }
4019 
4020             dst.nr++;
4021          }
4022 
4023          /* The loop above only ever incremented us through the first set
4024           * of 4 registers.  However, thanks to the magic of COMPR4, we
4025           * actually wrote to the first 8 registers, so we need to take
4026           * that into account now.
4027           */
4028          dst.nr += 4;
4029 
4030          /* The COMPR4 code took care of the first 4 sources.  We'll let
4031           * the regular path handle any remaining sources.  Yes, we are
4032           * modifying the instruction but we're about to delete it so
4033           * this really doesn't hurt anything.
4034           */
4035          inst->header_size += 4;
4036       }
4037 
4038       for (uint8_t i = inst->header_size; i < inst->sources; i++) {
4039          if (inst->src[i].file != BAD_FILE) {
4040             dst.type = inst->src[i].type;
4041             ibld.MOV(dst, inst->src[i]);
4042          } else {
4043             dst.type = BRW_REGISTER_TYPE_UD;
4044          }
4045          dst = offset(dst, ibld, 1);
4046       }
4047 
4048       inst->remove(block);
4049       progress = true;
4050    }
4051 
4052    if (progress)
4053       invalidate_analysis(DEPENDENCY_INSTRUCTIONS);
4054 
4055    return progress;
4056 }
4057 
4058 void
lower_mul_dword_inst(fs_inst * inst,bblock_t * block)4059 fs_visitor::lower_mul_dword_inst(fs_inst *inst, bblock_t *block)
4060 {
4061    const fs_builder ibld(this, block, inst);
4062 
4063    const bool ud = (inst->src[1].type == BRW_REGISTER_TYPE_UD);
4064    if (inst->src[1].file == IMM &&
4065        (( ud && inst->src[1].ud <= UINT16_MAX) ||
4066         (!ud && inst->src[1].d <= INT16_MAX && inst->src[1].d >= INT16_MIN))) {
4067       /* The MUL instruction isn't commutative. On Gen <= 6, only the low
4068        * 16-bits of src0 are read, and on Gen >= 7 only the low 16-bits of
4069        * src1 are used.
4070        *
4071        * If multiplying by an immediate value that fits in 16-bits, do a
4072        * single MUL instruction with that value in the proper location.
4073        */
4074       if (devinfo->ver < 7) {
4075          fs_reg imm(VGRF, alloc.allocate(dispatch_width / 8), inst->dst.type);
4076          ibld.MOV(imm, inst->src[1]);
4077          ibld.MUL(inst->dst, imm, inst->src[0]);
4078       } else {
4079          ibld.MUL(inst->dst, inst->src[0],
4080                   ud ? brw_imm_uw(inst->src[1].ud)
4081                      : brw_imm_w(inst->src[1].d));
4082       }
4083    } else {
4084       /* Gen < 8 (and some Gfx8+ low-power parts like Cherryview) cannot
4085        * do 32-bit integer multiplication in one instruction, but instead
4086        * must do a sequence (which actually calculates a 64-bit result):
4087        *
4088        *    mul(8)  acc0<1>D   g3<8,8,1>D      g4<8,8,1>D
4089        *    mach(8) null       g3<8,8,1>D      g4<8,8,1>D
4090        *    mov(8)  g2<1>D     acc0<8,8,1>D
4091        *
4092        * But on Gen > 6, the ability to use second accumulator register
4093        * (acc1) for non-float data types was removed, preventing a simple
4094        * implementation in SIMD16. A 16-channel result can be calculated by
4095        * executing the three instructions twice in SIMD8, once with quarter
4096        * control of 1Q for the first eight channels and again with 2Q for
4097        * the second eight channels.
4098        *
4099        * Which accumulator register is implicitly accessed (by AccWrEnable
4100        * for instance) is determined by the quarter control. Unfortunately
4101        * Ivybridge (and presumably Baytrail) has a hardware bug in which an
4102        * implicit accumulator access by an instruction with 2Q will access
4103        * acc1 regardless of whether the data type is usable in acc1.
4104        *
4105        * Specifically, the 2Q mach(8) writes acc1 which does not exist for
4106        * integer data types.
4107        *
4108        * Since we only want the low 32-bits of the result, we can do two
4109        * 32-bit x 16-bit multiplies (like the mul and mach are doing), and
4110        * adjust the high result and add them (like the mach is doing):
4111        *
4112        *    mul(8)  g7<1>D     g3<8,8,1>D      g4.0<8,8,1>UW
4113        *    mul(8)  g8<1>D     g3<8,8,1>D      g4.1<8,8,1>UW
4114        *    shl(8)  g9<1>D     g8<8,8,1>D      16D
4115        *    add(8)  g2<1>D     g7<8,8,1>D      g8<8,8,1>D
4116        *
4117        * We avoid the shl instruction by realizing that we only want to add
4118        * the low 16-bits of the "high" result to the high 16-bits of the
4119        * "low" result and using proper regioning on the add:
4120        *
4121        *    mul(8)  g7<1>D     g3<8,8,1>D      g4.0<16,8,2>UW
4122        *    mul(8)  g8<1>D     g3<8,8,1>D      g4.1<16,8,2>UW
4123        *    add(8)  g7.1<2>UW  g7.1<16,8,2>UW  g8<16,8,2>UW
4124        *
4125        * Since it does not use the (single) accumulator register, we can
4126        * schedule multi-component multiplications much better.
4127        */
4128 
4129       bool needs_mov = false;
4130       fs_reg orig_dst = inst->dst;
4131 
4132       /* Get a new VGRF for the "low" 32x16-bit multiplication result if
4133        * reusing the original destination is impossible due to hardware
4134        * restrictions, source/destination overlap, or it being the null
4135        * register.
4136        */
4137       fs_reg low = inst->dst;
4138       if (orig_dst.is_null() || orig_dst.file == MRF ||
4139           regions_overlap(inst->dst, inst->size_written,
4140                           inst->src[0], inst->size_read(0)) ||
4141           regions_overlap(inst->dst, inst->size_written,
4142                           inst->src[1], inst->size_read(1)) ||
4143           inst->dst.stride >= 4) {
4144          needs_mov = true;
4145          low = fs_reg(VGRF, alloc.allocate(regs_written(inst)),
4146                       inst->dst.type);
4147       }
4148 
4149       /* Get a new VGRF but keep the same stride as inst->dst */
4150       fs_reg high(VGRF, alloc.allocate(regs_written(inst)), inst->dst.type);
4151       high.stride = inst->dst.stride;
4152       high.offset = inst->dst.offset % REG_SIZE;
4153 
4154       if (devinfo->ver >= 7) {
4155          /* From Wa_1604601757:
4156           *
4157           * "When multiplying a DW and any lower precision integer, source modifier
4158           *  is not supported."
4159           *
4160           * An unsupported negate modifier on src[1] would ordinarily be
4161           * lowered by the subsequent lower_regioning pass.  In this case that
4162           * pass would spawn another dword multiply.  Instead, lower the
4163           * modifier first.
4164           */
4165          const bool source_mods_unsupported = (devinfo->ver >= 12);
4166 
4167          if (inst->src[1].abs || (inst->src[1].negate &&
4168                                   source_mods_unsupported))
4169             lower_src_modifiers(this, block, inst, 1);
4170 
4171          if (inst->src[1].file == IMM) {
4172             ibld.MUL(low, inst->src[0],
4173                      brw_imm_uw(inst->src[1].ud & 0xffff));
4174             ibld.MUL(high, inst->src[0],
4175                      brw_imm_uw(inst->src[1].ud >> 16));
4176          } else {
4177             ibld.MUL(low, inst->src[0],
4178                      subscript(inst->src[1], BRW_REGISTER_TYPE_UW, 0));
4179             ibld.MUL(high, inst->src[0],
4180                      subscript(inst->src[1], BRW_REGISTER_TYPE_UW, 1));
4181          }
4182       } else {
4183          if (inst->src[0].abs)
4184             lower_src_modifiers(this, block, inst, 0);
4185 
4186          ibld.MUL(low, subscript(inst->src[0], BRW_REGISTER_TYPE_UW, 0),
4187                   inst->src[1]);
4188          ibld.MUL(high, subscript(inst->src[0], BRW_REGISTER_TYPE_UW, 1),
4189                   inst->src[1]);
4190       }
4191 
4192       ibld.ADD(subscript(low, BRW_REGISTER_TYPE_UW, 1),
4193                subscript(low, BRW_REGISTER_TYPE_UW, 1),
4194                subscript(high, BRW_REGISTER_TYPE_UW, 0));
4195 
4196       if (needs_mov || inst->conditional_mod)
4197          set_condmod(inst->conditional_mod, ibld.MOV(orig_dst, low));
4198    }
4199 }
4200 
4201 void
lower_mul_qword_inst(fs_inst * inst,bblock_t * block)4202 fs_visitor::lower_mul_qword_inst(fs_inst *inst, bblock_t *block)
4203 {
4204    const fs_builder ibld(this, block, inst);
4205 
4206    /* Considering two 64-bit integers ab and cd where each letter        ab
4207     * corresponds to 32 bits, we get a 128-bit result WXYZ. We         * cd
4208     * only need to provide the YZ part of the result.               -------
4209     *                                                                    BD
4210     *  Only BD needs to be 64 bits. For AD and BC we only care       +  AD
4211     *  about the lower 32 bits (since they are part of the upper     +  BC
4212     *  32 bits of our result). AC is not needed since it starts      + AC
4213     *  on the 65th bit of the result.                               -------
4214     *                                                                  WXYZ
4215     */
4216    unsigned int q_regs = regs_written(inst);
4217    unsigned int d_regs = (q_regs + 1) / 2;
4218 
4219    fs_reg bd(VGRF, alloc.allocate(q_regs), BRW_REGISTER_TYPE_UQ);
4220    fs_reg ad(VGRF, alloc.allocate(d_regs), BRW_REGISTER_TYPE_UD);
4221    fs_reg bc(VGRF, alloc.allocate(d_regs), BRW_REGISTER_TYPE_UD);
4222 
4223    /* Here we need the full 64 bit result for 32b * 32b. */
4224    if (devinfo->has_integer_dword_mul) {
4225       ibld.MUL(bd, subscript(inst->src[0], BRW_REGISTER_TYPE_UD, 0),
4226                subscript(inst->src[1], BRW_REGISTER_TYPE_UD, 0));
4227    } else {
4228       fs_reg bd_high(VGRF, alloc.allocate(d_regs), BRW_REGISTER_TYPE_UD);
4229       fs_reg bd_low(VGRF, alloc.allocate(d_regs), BRW_REGISTER_TYPE_UD);
4230       fs_reg acc = retype(brw_acc_reg(inst->exec_size), BRW_REGISTER_TYPE_UD);
4231 
4232       fs_inst *mul = ibld.MUL(acc,
4233                             subscript(inst->src[0], BRW_REGISTER_TYPE_UD, 0),
4234                             subscript(inst->src[1], BRW_REGISTER_TYPE_UW, 0));
4235       mul->writes_accumulator = true;
4236 
4237       ibld.MACH(bd_high, subscript(inst->src[0], BRW_REGISTER_TYPE_UD, 0),
4238                 subscript(inst->src[1], BRW_REGISTER_TYPE_UD, 0));
4239       ibld.MOV(bd_low, acc);
4240 
4241       ibld.MOV(subscript(bd, BRW_REGISTER_TYPE_UD, 0), bd_low);
4242       ibld.MOV(subscript(bd, BRW_REGISTER_TYPE_UD, 1), bd_high);
4243    }
4244 
4245    ibld.MUL(ad, subscript(inst->src[0], BRW_REGISTER_TYPE_UD, 1),
4246             subscript(inst->src[1], BRW_REGISTER_TYPE_UD, 0));
4247    ibld.MUL(bc, subscript(inst->src[0], BRW_REGISTER_TYPE_UD, 0),
4248             subscript(inst->src[1], BRW_REGISTER_TYPE_UD, 1));
4249 
4250    ibld.ADD(ad, ad, bc);
4251    ibld.ADD(subscript(bd, BRW_REGISTER_TYPE_UD, 1),
4252             subscript(bd, BRW_REGISTER_TYPE_UD, 1), ad);
4253 
4254    if (devinfo->has_64bit_int) {
4255       ibld.MOV(inst->dst, bd);
4256    } else {
4257       ibld.MOV(subscript(inst->dst, BRW_REGISTER_TYPE_UD, 0),
4258                subscript(bd, BRW_REGISTER_TYPE_UD, 0));
4259       ibld.MOV(subscript(inst->dst, BRW_REGISTER_TYPE_UD, 1),
4260                subscript(bd, BRW_REGISTER_TYPE_UD, 1));
4261    }
4262 }
4263 
4264 void
lower_mulh_inst(fs_inst * inst,bblock_t * block)4265 fs_visitor::lower_mulh_inst(fs_inst *inst, bblock_t *block)
4266 {
4267    const fs_builder ibld(this, block, inst);
4268 
4269    /* According to the BDW+ BSpec page for the "Multiply Accumulate
4270     * High" instruction:
4271     *
4272     *  "An added preliminary mov is required for source modification on
4273     *   src1:
4274     *      mov (8) r3.0<1>:d -r3<8;8,1>:d
4275     *      mul (8) acc0:d r2.0<8;8,1>:d r3.0<16;8,2>:uw
4276     *      mach (8) r5.0<1>:d r2.0<8;8,1>:d r3.0<8;8,1>:d"
4277     */
4278    if (devinfo->ver >= 8 && (inst->src[1].negate || inst->src[1].abs))
4279       lower_src_modifiers(this, block, inst, 1);
4280 
4281    /* Should have been lowered to 8-wide. */
4282    assert(inst->exec_size <= get_lowered_simd_width(devinfo, inst));
4283    const fs_reg acc = retype(brw_acc_reg(inst->exec_size), inst->dst.type);
4284    fs_inst *mul = ibld.MUL(acc, inst->src[0], inst->src[1]);
4285    fs_inst *mach = ibld.MACH(inst->dst, inst->src[0], inst->src[1]);
4286 
4287    if (devinfo->ver >= 8) {
4288       /* Until Gfx8, integer multiplies read 32-bits from one source,
4289        * and 16-bits from the other, and relying on the MACH instruction
4290        * to generate the high bits of the result.
4291        *
4292        * On Gfx8, the multiply instruction does a full 32x32-bit
4293        * multiply, but in order to do a 64-bit multiply we can simulate
4294        * the previous behavior and then use a MACH instruction.
4295        */
4296       assert(mul->src[1].type == BRW_REGISTER_TYPE_D ||
4297              mul->src[1].type == BRW_REGISTER_TYPE_UD);
4298       mul->src[1].type = BRW_REGISTER_TYPE_UW;
4299       mul->src[1].stride *= 2;
4300 
4301       if (mul->src[1].file == IMM) {
4302          mul->src[1] = brw_imm_uw(mul->src[1].ud);
4303       }
4304    } else if (devinfo->verx10 == 70 &&
4305               inst->group > 0) {
4306       /* Among other things the quarter control bits influence which
4307        * accumulator register is used by the hardware for instructions
4308        * that access the accumulator implicitly (e.g. MACH).  A
4309        * second-half instruction would normally map to acc1, which
4310        * doesn't exist on Gfx7 and up (the hardware does emulate it for
4311        * floating-point instructions *only* by taking advantage of the
4312        * extra precision of acc0 not normally used for floating point
4313        * arithmetic).
4314        *
4315        * HSW and up are careful enough not to try to access an
4316        * accumulator register that doesn't exist, but on earlier Gfx7
4317        * hardware we need to make sure that the quarter control bits are
4318        * zero to avoid non-deterministic behaviour and emit an extra MOV
4319        * to get the result masked correctly according to the current
4320        * channel enables.
4321        */
4322       mach->group = 0;
4323       mach->force_writemask_all = true;
4324       mach->dst = ibld.vgrf(inst->dst.type);
4325       ibld.MOV(inst->dst, mach->dst);
4326    }
4327 }
4328 
4329 bool
lower_integer_multiplication()4330 fs_visitor::lower_integer_multiplication()
4331 {
4332    bool progress = false;
4333 
4334    foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
4335       if (inst->opcode == BRW_OPCODE_MUL) {
4336          /* If the instruction is already in a form that does not need lowering,
4337           * return early.
4338           */
4339          if (devinfo->ver >= 7) {
4340             if (type_sz(inst->src[1].type) < 4 && type_sz(inst->src[0].type) <= 4)
4341                continue;
4342          } else {
4343             if (type_sz(inst->src[0].type) < 4 && type_sz(inst->src[1].type) <= 4)
4344                continue;
4345          }
4346 
4347          if ((inst->dst.type == BRW_REGISTER_TYPE_Q ||
4348               inst->dst.type == BRW_REGISTER_TYPE_UQ) &&
4349              (inst->src[0].type == BRW_REGISTER_TYPE_Q ||
4350               inst->src[0].type == BRW_REGISTER_TYPE_UQ) &&
4351              (inst->src[1].type == BRW_REGISTER_TYPE_Q ||
4352               inst->src[1].type == BRW_REGISTER_TYPE_UQ)) {
4353             lower_mul_qword_inst(inst, block);
4354             inst->remove(block);
4355             progress = true;
4356          } else if (!inst->dst.is_accumulator() &&
4357                     (inst->dst.type == BRW_REGISTER_TYPE_D ||
4358                      inst->dst.type == BRW_REGISTER_TYPE_UD) &&
4359                     (!devinfo->has_integer_dword_mul ||
4360                      devinfo->verx10 >= 125)) {
4361             lower_mul_dword_inst(inst, block);
4362             inst->remove(block);
4363             progress = true;
4364          }
4365       } else if (inst->opcode == SHADER_OPCODE_MULH) {
4366          lower_mulh_inst(inst, block);
4367          inst->remove(block);
4368          progress = true;
4369       }
4370 
4371    }
4372 
4373    if (progress)
4374       invalidate_analysis(DEPENDENCY_INSTRUCTIONS | DEPENDENCY_VARIABLES);
4375 
4376    return progress;
4377 }
4378 
4379 bool
lower_minmax()4380 fs_visitor::lower_minmax()
4381 {
4382    assert(devinfo->ver < 6);
4383 
4384    bool progress = false;
4385 
4386    foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
4387       const fs_builder ibld(this, block, inst);
4388 
4389       if (inst->opcode == BRW_OPCODE_SEL &&
4390           inst->predicate == BRW_PREDICATE_NONE) {
4391          /* If src1 is an immediate value that is not NaN, then it can't be
4392           * NaN.  In that case, emit CMP because it is much better for cmod
4393           * propagation.  Likewise if src1 is not float.  Gfx4 and Gfx5 don't
4394           * support HF or DF, so it is not necessary to check for those.
4395           */
4396          if (inst->src[1].type != BRW_REGISTER_TYPE_F ||
4397              (inst->src[1].file == IMM && !isnan(inst->src[1].f))) {
4398             ibld.CMP(ibld.null_reg_d(), inst->src[0], inst->src[1],
4399                      inst->conditional_mod);
4400          } else {
4401             ibld.CMPN(ibld.null_reg_d(), inst->src[0], inst->src[1],
4402                       inst->conditional_mod);
4403          }
4404          inst->predicate = BRW_PREDICATE_NORMAL;
4405          inst->conditional_mod = BRW_CONDITIONAL_NONE;
4406 
4407          progress = true;
4408       }
4409    }
4410 
4411    if (progress)
4412       invalidate_analysis(DEPENDENCY_INSTRUCTIONS);
4413 
4414    return progress;
4415 }
4416 
4417 bool
lower_sub_sat()4418 fs_visitor::lower_sub_sat()
4419 {
4420    bool progress = false;
4421 
4422    foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
4423       const fs_builder ibld(this, block, inst);
4424 
4425       if (inst->opcode == SHADER_OPCODE_USUB_SAT ||
4426           inst->opcode == SHADER_OPCODE_ISUB_SAT) {
4427          /* The fundamental problem is the hardware performs source negation
4428           * at the bit width of the source.  If the source is 0x80000000D, the
4429           * negation is 0x80000000D.  As a result, subtractSaturate(0,
4430           * 0x80000000) will produce 0x80000000 instead of 0x7fffffff.  There
4431           * are at least three ways to resolve this:
4432           *
4433           * 1. Use the accumulator for the negated source.  The accumulator is
4434           *    33 bits, so our source 0x80000000 is sign-extended to
4435           *    0x1800000000.  The negation of which is 0x080000000.  This
4436           *    doesn't help for 64-bit integers (which are already bigger than
4437           *    33 bits).  There are also only 8 accumulators, so SIMD16 or
4438           *    SIMD32 instructions would have to be split into multiple SIMD8
4439           *    instructions.
4440           *
4441           * 2. Use slightly different math.  For any n-bit value x, we know (x
4442           *    >> 1) != -(x >> 1).  We can use this fact to only do
4443           *    subtractions involving (x >> 1).  subtractSaturate(a, b) ==
4444           *    subtractSaturate(subtractSaturate(a, (b >> 1)), b - (b >> 1)).
4445           *
4446           * 3. For unsigned sources, it is sufficient to replace the
4447           *    subtractSaturate with (a > b) ? a - b : 0.
4448           *
4449           * It may also be possible to use the SUBB instruction.  This
4450           * implicitly writes the accumulator, so it could only be used in the
4451           * same situations as #1 above.  It is further limited by only
4452           * allowing UD sources.
4453           */
4454          if (inst->exec_size == 8 && inst->src[0].type != BRW_REGISTER_TYPE_Q &&
4455              inst->src[0].type != BRW_REGISTER_TYPE_UQ) {
4456             fs_reg acc(ARF, BRW_ARF_ACCUMULATOR, inst->src[1].type);
4457 
4458             ibld.MOV(acc, inst->src[1]);
4459             fs_inst *add = ibld.ADD(inst->dst, acc, inst->src[0]);
4460             add->saturate = true;
4461             add->src[0].negate = true;
4462          } else if (inst->opcode == SHADER_OPCODE_ISUB_SAT) {
4463             /* tmp = src1 >> 1;
4464              * dst = add.sat(add.sat(src0, -tmp), -(src1 - tmp));
4465              */
4466             fs_reg tmp1 = ibld.vgrf(inst->src[0].type);
4467             fs_reg tmp2 = ibld.vgrf(inst->src[0].type);
4468             fs_reg tmp3 = ibld.vgrf(inst->src[0].type);
4469             fs_inst *add;
4470 
4471             ibld.SHR(tmp1, inst->src[1], brw_imm_d(1));
4472 
4473             add = ibld.ADD(tmp2, inst->src[1], tmp1);
4474             add->src[1].negate = true;
4475 
4476             add = ibld.ADD(tmp3, inst->src[0], tmp1);
4477             add->src[1].negate = true;
4478             add->saturate = true;
4479 
4480             add = ibld.ADD(inst->dst, tmp3, tmp2);
4481             add->src[1].negate = true;
4482             add->saturate = true;
4483          } else {
4484             /* a > b ? a - b : 0 */
4485             ibld.CMP(ibld.null_reg_d(), inst->src[0], inst->src[1],
4486                      BRW_CONDITIONAL_G);
4487 
4488             fs_inst *add = ibld.ADD(inst->dst, inst->src[0], inst->src[1]);
4489             add->src[1].negate = !add->src[1].negate;
4490 
4491             ibld.SEL(inst->dst, inst->dst, brw_imm_ud(0))
4492                ->predicate = BRW_PREDICATE_NORMAL;
4493          }
4494 
4495          inst->remove(block);
4496          progress = true;
4497       }
4498    }
4499 
4500    if (progress)
4501       invalidate_analysis(DEPENDENCY_INSTRUCTIONS | DEPENDENCY_VARIABLES);
4502 
4503    return progress;
4504 }
4505 
4506 /**
4507  * Get the mask of SIMD channels enabled during dispatch and not yet disabled
4508  * by discard.  Due to the layout of the sample mask in the fragment shader
4509  * thread payload, \p bld is required to have a dispatch_width() not greater
4510  * than 16 for fragment shaders.
4511  */
4512 static fs_reg
sample_mask_reg(const fs_builder & bld)4513 sample_mask_reg(const fs_builder &bld)
4514 {
4515    const fs_visitor *v = static_cast<const fs_visitor *>(bld.shader);
4516 
4517    if (v->stage != MESA_SHADER_FRAGMENT) {
4518       return brw_imm_ud(0xffffffff);
4519    } else if (brw_wm_prog_data(v->stage_prog_data)->uses_kill) {
4520       assert(bld.dispatch_width() <= 16);
4521       return brw_flag_subreg(sample_mask_flag_subreg(v) + bld.group() / 16);
4522    } else {
4523       assert(v->devinfo->ver >= 6 && bld.dispatch_width() <= 16);
4524       return retype(brw_vec1_grf((bld.group() >= 16 ? 2 : 1), 7),
4525                     BRW_REGISTER_TYPE_UW);
4526    }
4527 }
4528 
4529 static void
setup_color_payload(const fs_builder & bld,const brw_wm_prog_key * key,fs_reg * dst,fs_reg color,unsigned components)4530 setup_color_payload(const fs_builder &bld, const brw_wm_prog_key *key,
4531                     fs_reg *dst, fs_reg color, unsigned components)
4532 {
4533    if (key->clamp_fragment_color) {
4534       fs_reg tmp = bld.vgrf(BRW_REGISTER_TYPE_F, 4);
4535       assert(color.type == BRW_REGISTER_TYPE_F);
4536 
4537       for (unsigned i = 0; i < components; i++)
4538          set_saturate(true,
4539                       bld.MOV(offset(tmp, bld, i), offset(color, bld, i)));
4540 
4541       color = tmp;
4542    }
4543 
4544    for (unsigned i = 0; i < components; i++)
4545       dst[i] = offset(color, bld, i);
4546 }
4547 
4548 uint32_t
brw_fb_write_msg_control(const fs_inst * inst,const struct brw_wm_prog_data * prog_data)4549 brw_fb_write_msg_control(const fs_inst *inst,
4550                          const struct brw_wm_prog_data *prog_data)
4551 {
4552    uint32_t mctl;
4553 
4554    if (inst->opcode == FS_OPCODE_REP_FB_WRITE) {
4555       assert(inst->group == 0 && inst->exec_size == 16);
4556       mctl = BRW_DATAPORT_RENDER_TARGET_WRITE_SIMD16_SINGLE_SOURCE_REPLICATED;
4557    } else if (prog_data->dual_src_blend) {
4558       assert(inst->exec_size == 8);
4559 
4560       if (inst->group % 16 == 0)
4561          mctl = BRW_DATAPORT_RENDER_TARGET_WRITE_SIMD8_DUAL_SOURCE_SUBSPAN01;
4562       else if (inst->group % 16 == 8)
4563          mctl = BRW_DATAPORT_RENDER_TARGET_WRITE_SIMD8_DUAL_SOURCE_SUBSPAN23;
4564       else
4565          unreachable("Invalid dual-source FB write instruction group");
4566    } else {
4567       assert(inst->group == 0 || (inst->group == 16 && inst->exec_size == 16));
4568 
4569       if (inst->exec_size == 16)
4570          mctl = BRW_DATAPORT_RENDER_TARGET_WRITE_SIMD16_SINGLE_SOURCE;
4571       else if (inst->exec_size == 8)
4572          mctl = BRW_DATAPORT_RENDER_TARGET_WRITE_SIMD8_SINGLE_SOURCE_SUBSPAN01;
4573       else
4574          unreachable("Invalid FB write execution size");
4575    }
4576 
4577    return mctl;
4578 }
4579 
4580 static void
lower_fb_write_logical_send(const fs_builder & bld,fs_inst * inst,const struct brw_wm_prog_data * prog_data,const brw_wm_prog_key * key,const fs_visitor::thread_payload & payload)4581 lower_fb_write_logical_send(const fs_builder &bld, fs_inst *inst,
4582                             const struct brw_wm_prog_data *prog_data,
4583                             const brw_wm_prog_key *key,
4584                             const fs_visitor::thread_payload &payload)
4585 {
4586    assert(inst->src[FB_WRITE_LOGICAL_SRC_COMPONENTS].file == IMM);
4587    const intel_device_info *devinfo = bld.shader->devinfo;
4588    const fs_reg &color0 = inst->src[FB_WRITE_LOGICAL_SRC_COLOR0];
4589    const fs_reg &color1 = inst->src[FB_WRITE_LOGICAL_SRC_COLOR1];
4590    const fs_reg &src0_alpha = inst->src[FB_WRITE_LOGICAL_SRC_SRC0_ALPHA];
4591    const fs_reg &src_depth = inst->src[FB_WRITE_LOGICAL_SRC_SRC_DEPTH];
4592    const fs_reg &dst_depth = inst->src[FB_WRITE_LOGICAL_SRC_DST_DEPTH];
4593    const fs_reg &src_stencil = inst->src[FB_WRITE_LOGICAL_SRC_SRC_STENCIL];
4594    fs_reg sample_mask = inst->src[FB_WRITE_LOGICAL_SRC_OMASK];
4595    const unsigned components =
4596       inst->src[FB_WRITE_LOGICAL_SRC_COMPONENTS].ud;
4597 
4598    assert(inst->target != 0 || src0_alpha.file == BAD_FILE);
4599 
4600    /* We can potentially have a message length of up to 15, so we have to set
4601     * base_mrf to either 0 or 1 in order to fit in m0..m15.
4602     */
4603    fs_reg sources[15];
4604    int header_size = 2, payload_header_size;
4605    unsigned length = 0;
4606 
4607    if (devinfo->ver < 6) {
4608       /* TODO: Support SIMD32 on gfx4-5 */
4609       assert(bld.group() < 16);
4610 
4611       /* For gfx4-5, we always have a header consisting of g0 and g1.  We have
4612        * an implied MOV from g0,g1 to the start of the message.  The MOV from
4613        * g0 is handled by the hardware and the MOV from g1 is provided by the
4614        * generator.  This is required because, on gfx4-5, the generator may
4615        * generate two write messages with different message lengths in order
4616        * to handle AA data properly.
4617        *
4618        * Also, since the pixel mask goes in the g0 portion of the message and
4619        * since render target writes are the last thing in the shader, we write
4620        * the pixel mask directly into g0 and it will get copied as part of the
4621        * implied write.
4622        */
4623       if (prog_data->uses_kill) {
4624          bld.exec_all().group(1, 0)
4625             .MOV(retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_UW),
4626                  sample_mask_reg(bld));
4627       }
4628 
4629       assert(length == 0);
4630       length = 2;
4631    } else if ((devinfo->verx10 <= 70 &&
4632                prog_data->uses_kill) ||
4633               (devinfo->ver < 11 &&
4634                (color1.file != BAD_FILE || key->nr_color_regions > 1))) {
4635       /* From the Sandy Bridge PRM, volume 4, page 198:
4636        *
4637        *     "Dispatched Pixel Enables. One bit per pixel indicating
4638        *      which pixels were originally enabled when the thread was
4639        *      dispatched. This field is only required for the end-of-
4640        *      thread message and on all dual-source messages."
4641        */
4642       const fs_builder ubld = bld.exec_all().group(8, 0);
4643 
4644       fs_reg header = ubld.vgrf(BRW_REGISTER_TYPE_UD, 2);
4645       if (bld.group() < 16) {
4646          /* The header starts off as g0 and g1 for the first half */
4647          ubld.group(16, 0).MOV(header, retype(brw_vec8_grf(0, 0),
4648                                               BRW_REGISTER_TYPE_UD));
4649       } else {
4650          /* The header starts off as g0 and g2 for the second half */
4651          assert(bld.group() < 32);
4652          const fs_reg header_sources[2] = {
4653             retype(brw_vec8_grf(0, 0), BRW_REGISTER_TYPE_UD),
4654             retype(brw_vec8_grf(2, 0), BRW_REGISTER_TYPE_UD),
4655          };
4656          ubld.LOAD_PAYLOAD(header, header_sources, 2, 0);
4657 
4658          /* Gfx12 will require additional fix-ups if we ever hit this path. */
4659          assert(devinfo->ver < 12);
4660       }
4661 
4662       uint32_t g00_bits = 0;
4663 
4664       /* Set "Source0 Alpha Present to RenderTarget" bit in message
4665        * header.
4666        */
4667       if (src0_alpha.file != BAD_FILE)
4668          g00_bits |= 1 << 11;
4669 
4670       /* Set computes stencil to render target */
4671       if (prog_data->computed_stencil)
4672          g00_bits |= 1 << 14;
4673 
4674       if (g00_bits) {
4675          /* OR extra bits into g0.0 */
4676          ubld.group(1, 0).OR(component(header, 0),
4677                              retype(brw_vec1_grf(0, 0),
4678                                     BRW_REGISTER_TYPE_UD),
4679                              brw_imm_ud(g00_bits));
4680       }
4681 
4682       /* Set the render target index for choosing BLEND_STATE. */
4683       if (inst->target > 0) {
4684          ubld.group(1, 0).MOV(component(header, 2), brw_imm_ud(inst->target));
4685       }
4686 
4687       if (prog_data->uses_kill) {
4688          ubld.group(1, 0).MOV(retype(component(header, 15),
4689                                      BRW_REGISTER_TYPE_UW),
4690                               sample_mask_reg(bld));
4691       }
4692 
4693       assert(length == 0);
4694       sources[0] = header;
4695       sources[1] = horiz_offset(header, 8);
4696       length = 2;
4697    }
4698    assert(length == 0 || length == 2);
4699    header_size = length;
4700 
4701    if (payload.aa_dest_stencil_reg[0]) {
4702       assert(inst->group < 16);
4703       sources[length] = fs_reg(VGRF, bld.shader->alloc.allocate(1));
4704       bld.group(8, 0).exec_all().annotate("FB write stencil/AA alpha")
4705          .MOV(sources[length],
4706               fs_reg(brw_vec8_grf(payload.aa_dest_stencil_reg[0], 0)));
4707       length++;
4708    }
4709 
4710    if (src0_alpha.file != BAD_FILE) {
4711       for (unsigned i = 0; i < bld.dispatch_width() / 8; i++) {
4712          const fs_builder &ubld = bld.exec_all().group(8, i)
4713                                     .annotate("FB write src0 alpha");
4714          const fs_reg tmp = ubld.vgrf(BRW_REGISTER_TYPE_F);
4715          ubld.MOV(tmp, horiz_offset(src0_alpha, i * 8));
4716          setup_color_payload(ubld, key, &sources[length], tmp, 1);
4717          length++;
4718       }
4719    }
4720 
4721    if (sample_mask.file != BAD_FILE) {
4722       sources[length] = fs_reg(VGRF, bld.shader->alloc.allocate(1),
4723                                BRW_REGISTER_TYPE_UD);
4724 
4725       /* Hand over gl_SampleMask.  Only the lower 16 bits of each channel are
4726        * relevant.  Since it's unsigned single words one vgrf is always
4727        * 16-wide, but only the lower or higher 8 channels will be used by the
4728        * hardware when doing a SIMD8 write depending on whether we have
4729        * selected the subspans for the first or second half respectively.
4730        */
4731       assert(sample_mask.file != BAD_FILE && type_sz(sample_mask.type) == 4);
4732       sample_mask.type = BRW_REGISTER_TYPE_UW;
4733       sample_mask.stride *= 2;
4734 
4735       bld.exec_all().annotate("FB write oMask")
4736          .MOV(horiz_offset(retype(sources[length], BRW_REGISTER_TYPE_UW),
4737                            inst->group % 16),
4738               sample_mask);
4739       length++;
4740    }
4741 
4742    payload_header_size = length;
4743 
4744    setup_color_payload(bld, key, &sources[length], color0, components);
4745    length += 4;
4746 
4747    if (color1.file != BAD_FILE) {
4748       setup_color_payload(bld, key, &sources[length], color1, components);
4749       length += 4;
4750    }
4751 
4752    if (src_depth.file != BAD_FILE) {
4753       sources[length] = src_depth;
4754       length++;
4755    }
4756 
4757    if (dst_depth.file != BAD_FILE) {
4758       sources[length] = dst_depth;
4759       length++;
4760    }
4761 
4762    if (src_stencil.file != BAD_FILE) {
4763       assert(devinfo->ver >= 9);
4764       assert(bld.dispatch_width() == 8);
4765 
4766       /* XXX: src_stencil is only available on gfx9+. dst_depth is never
4767        * available on gfx9+. As such it's impossible to have both enabled at the
4768        * same time and therefore length cannot overrun the array.
4769        */
4770       assert(length < 15);
4771 
4772       sources[length] = bld.vgrf(BRW_REGISTER_TYPE_UD);
4773       bld.exec_all().annotate("FB write OS")
4774          .MOV(retype(sources[length], BRW_REGISTER_TYPE_UB),
4775               subscript(src_stencil, BRW_REGISTER_TYPE_UB, 0));
4776       length++;
4777    }
4778 
4779    fs_inst *load;
4780    if (devinfo->ver >= 7) {
4781       /* Send from the GRF */
4782       fs_reg payload = fs_reg(VGRF, -1, BRW_REGISTER_TYPE_F);
4783       load = bld.LOAD_PAYLOAD(payload, sources, length, payload_header_size);
4784       payload.nr = bld.shader->alloc.allocate(regs_written(load));
4785       load->dst = payload;
4786 
4787       uint32_t msg_ctl = brw_fb_write_msg_control(inst, prog_data);
4788 
4789       inst->desc =
4790          (inst->group / 16) << 11 | /* rt slot group */
4791          brw_fb_write_desc(devinfo, inst->target, msg_ctl, inst->last_rt,
4792                            prog_data->per_coarse_pixel_dispatch);
4793 
4794       uint32_t ex_desc = 0;
4795       if (devinfo->ver >= 11) {
4796          /* Set the "Render Target Index" and "Src0 Alpha Present" fields
4797           * in the extended message descriptor, in lieu of using a header.
4798           */
4799          ex_desc = inst->target << 12 | (src0_alpha.file != BAD_FILE) << 15;
4800 
4801          if (key->nr_color_regions == 0)
4802             ex_desc |= 1 << 20; /* Null Render Target */
4803       }
4804       inst->ex_desc = ex_desc;
4805 
4806       inst->opcode = SHADER_OPCODE_SEND;
4807       inst->resize_sources(3);
4808       inst->sfid = GFX6_SFID_DATAPORT_RENDER_CACHE;
4809       inst->src[0] = brw_imm_ud(0);
4810       inst->src[1] = brw_imm_ud(0);
4811       inst->src[2] = payload;
4812       inst->mlen = regs_written(load);
4813       inst->ex_mlen = 0;
4814       inst->header_size = header_size;
4815       inst->check_tdr = true;
4816       inst->send_has_side_effects = true;
4817    } else {
4818       /* Send from the MRF */
4819       load = bld.LOAD_PAYLOAD(fs_reg(MRF, 1, BRW_REGISTER_TYPE_F),
4820                               sources, length, payload_header_size);
4821 
4822       /* On pre-SNB, we have to interlace the color values.  LOAD_PAYLOAD
4823        * will do this for us if we just give it a COMPR4 destination.
4824        */
4825       if (devinfo->ver < 6 && bld.dispatch_width() == 16)
4826          load->dst.nr |= BRW_MRF_COMPR4;
4827 
4828       if (devinfo->ver < 6) {
4829          /* Set up src[0] for the implied MOV from grf0-1 */
4830          inst->resize_sources(1);
4831          inst->src[0] = brw_vec8_grf(0, 0);
4832       } else {
4833          inst->resize_sources(0);
4834       }
4835       inst->base_mrf = 1;
4836       inst->opcode = FS_OPCODE_FB_WRITE;
4837       inst->mlen = regs_written(load);
4838       inst->header_size = header_size;
4839    }
4840 }
4841 
4842 static void
lower_fb_read_logical_send(const fs_builder & bld,fs_inst * inst)4843 lower_fb_read_logical_send(const fs_builder &bld, fs_inst *inst)
4844 {
4845    const intel_device_info *devinfo = bld.shader->devinfo;
4846    const fs_builder &ubld = bld.exec_all().group(8, 0);
4847    const unsigned length = 2;
4848    const fs_reg header = ubld.vgrf(BRW_REGISTER_TYPE_UD, length);
4849 
4850    if (bld.group() < 16) {
4851       ubld.group(16, 0).MOV(header, retype(brw_vec8_grf(0, 0),
4852                                            BRW_REGISTER_TYPE_UD));
4853    } else {
4854       assert(bld.group() < 32);
4855       const fs_reg header_sources[] = {
4856          retype(brw_vec8_grf(0, 0), BRW_REGISTER_TYPE_UD),
4857          retype(brw_vec8_grf(2, 0), BRW_REGISTER_TYPE_UD)
4858       };
4859       ubld.LOAD_PAYLOAD(header, header_sources, ARRAY_SIZE(header_sources), 0);
4860 
4861       if (devinfo->ver >= 12) {
4862          /* On Gfx12 the Viewport and Render Target Array Index fields (AKA
4863           * Poly 0 Info) are provided in r1.1 instead of r0.0, and the render
4864           * target message header format was updated accordingly -- However
4865           * the updated format only works for the lower 16 channels in a
4866           * SIMD32 thread, since the higher 16 channels want the subspan data
4867           * from r2 instead of r1, so we need to copy over the contents of
4868           * r1.1 in order to fix things up.
4869           */
4870          ubld.group(1, 0).MOV(component(header, 9),
4871                               retype(brw_vec1_grf(1, 1), BRW_REGISTER_TYPE_UD));
4872       }
4873    }
4874 
4875    /* BSpec 12470 (Gfx8-11), BSpec 47842 (Gfx12+) :
4876     *
4877     *   "Must be zero for Render Target Read message."
4878     *
4879     * For bits :
4880     *   - 14 : Stencil Present to Render Target
4881     *   - 13 : Source Depth Present to Render Target
4882     *   - 12 : oMask to Render Target
4883     *   - 11 : Source0 Alpha Present to Render Target
4884     */
4885    ubld.group(1, 0).AND(component(header, 0),
4886                         component(header, 0),
4887                         brw_imm_ud(~INTEL_MASK(14, 11)));
4888 
4889    inst->resize_sources(1);
4890    inst->src[0] = header;
4891    inst->opcode = FS_OPCODE_FB_READ;
4892    inst->mlen = length;
4893    inst->header_size = length;
4894 }
4895 
4896 static void
lower_sampler_logical_send_gfx4(const fs_builder & bld,fs_inst * inst,opcode op,const fs_reg & coordinate,const fs_reg & shadow_c,const fs_reg & lod,const fs_reg & lod2,const fs_reg & surface,const fs_reg & sampler,unsigned coord_components,unsigned grad_components)4897 lower_sampler_logical_send_gfx4(const fs_builder &bld, fs_inst *inst, opcode op,
4898                                 const fs_reg &coordinate,
4899                                 const fs_reg &shadow_c,
4900                                 const fs_reg &lod, const fs_reg &lod2,
4901                                 const fs_reg &surface,
4902                                 const fs_reg &sampler,
4903                                 unsigned coord_components,
4904                                 unsigned grad_components)
4905 {
4906    const bool has_lod = (op == SHADER_OPCODE_TXL || op == FS_OPCODE_TXB ||
4907                          op == SHADER_OPCODE_TXF || op == SHADER_OPCODE_TXS);
4908    fs_reg msg_begin(MRF, 1, BRW_REGISTER_TYPE_F);
4909    fs_reg msg_end = msg_begin;
4910 
4911    /* g0 header. */
4912    msg_end = offset(msg_end, bld.group(8, 0), 1);
4913 
4914    for (unsigned i = 0; i < coord_components; i++)
4915       bld.MOV(retype(offset(msg_end, bld, i), coordinate.type),
4916               offset(coordinate, bld, i));
4917 
4918    msg_end = offset(msg_end, bld, coord_components);
4919 
4920    /* Messages other than SAMPLE and RESINFO in SIMD16 and TXD in SIMD8
4921     * require all three components to be present and zero if they are unused.
4922     */
4923    if (coord_components > 0 &&
4924        (has_lod || shadow_c.file != BAD_FILE ||
4925         (op == SHADER_OPCODE_TEX && bld.dispatch_width() == 8))) {
4926       assert(coord_components <= 3);
4927       for (unsigned i = 0; i < 3 - coord_components; i++)
4928          bld.MOV(offset(msg_end, bld, i), brw_imm_f(0.0f));
4929 
4930       msg_end = offset(msg_end, bld, 3 - coord_components);
4931    }
4932 
4933    if (op == SHADER_OPCODE_TXD) {
4934       /* TXD unsupported in SIMD16 mode. */
4935       assert(bld.dispatch_width() == 8);
4936 
4937       /* the slots for u and v are always present, but r is optional */
4938       if (coord_components < 2)
4939          msg_end = offset(msg_end, bld, 2 - coord_components);
4940 
4941       /*  P   = u, v, r
4942        * dPdx = dudx, dvdx, drdx
4943        * dPdy = dudy, dvdy, drdy
4944        *
4945        * 1-arg: Does not exist.
4946        *
4947        * 2-arg: dudx   dvdx   dudy   dvdy
4948        *        dPdx.x dPdx.y dPdy.x dPdy.y
4949        *        m4     m5     m6     m7
4950        *
4951        * 3-arg: dudx   dvdx   drdx   dudy   dvdy   drdy
4952        *        dPdx.x dPdx.y dPdx.z dPdy.x dPdy.y dPdy.z
4953        *        m5     m6     m7     m8     m9     m10
4954        */
4955       for (unsigned i = 0; i < grad_components; i++)
4956          bld.MOV(offset(msg_end, bld, i), offset(lod, bld, i));
4957 
4958       msg_end = offset(msg_end, bld, MAX2(grad_components, 2));
4959 
4960       for (unsigned i = 0; i < grad_components; i++)
4961          bld.MOV(offset(msg_end, bld, i), offset(lod2, bld, i));
4962 
4963       msg_end = offset(msg_end, bld, MAX2(grad_components, 2));
4964    }
4965 
4966    if (has_lod) {
4967       /* Bias/LOD with shadow comparator is unsupported in SIMD16 -- *Without*
4968        * shadow comparator (including RESINFO) it's unsupported in SIMD8 mode.
4969        */
4970       assert(shadow_c.file != BAD_FILE ? bld.dispatch_width() == 8 :
4971              bld.dispatch_width() == 16);
4972 
4973       const brw_reg_type type =
4974          (op == SHADER_OPCODE_TXF || op == SHADER_OPCODE_TXS ?
4975           BRW_REGISTER_TYPE_UD : BRW_REGISTER_TYPE_F);
4976       bld.MOV(retype(msg_end, type), lod);
4977       msg_end = offset(msg_end, bld, 1);
4978    }
4979 
4980    if (shadow_c.file != BAD_FILE) {
4981       if (op == SHADER_OPCODE_TEX && bld.dispatch_width() == 8) {
4982          /* There's no plain shadow compare message, so we use shadow
4983           * compare with a bias of 0.0.
4984           */
4985          bld.MOV(msg_end, brw_imm_f(0.0f));
4986          msg_end = offset(msg_end, bld, 1);
4987       }
4988 
4989       bld.MOV(msg_end, shadow_c);
4990       msg_end = offset(msg_end, bld, 1);
4991    }
4992 
4993    inst->opcode = op;
4994    inst->src[0] = reg_undef;
4995    inst->src[1] = surface;
4996    inst->src[2] = sampler;
4997    inst->resize_sources(3);
4998    inst->base_mrf = msg_begin.nr;
4999    inst->mlen = msg_end.nr - msg_begin.nr;
5000    inst->header_size = 1;
5001 }
5002 
5003 static void
lower_sampler_logical_send_gfx5(const fs_builder & bld,fs_inst * inst,opcode op,const fs_reg & coordinate,const fs_reg & shadow_c,const fs_reg & lod,const fs_reg & lod2,const fs_reg & sample_index,const fs_reg & surface,const fs_reg & sampler,unsigned coord_components,unsigned grad_components)5004 lower_sampler_logical_send_gfx5(const fs_builder &bld, fs_inst *inst, opcode op,
5005                                 const fs_reg &coordinate,
5006                                 const fs_reg &shadow_c,
5007                                 const fs_reg &lod, const fs_reg &lod2,
5008                                 const fs_reg &sample_index,
5009                                 const fs_reg &surface,
5010                                 const fs_reg &sampler,
5011                                 unsigned coord_components,
5012                                 unsigned grad_components)
5013 {
5014    fs_reg message(MRF, 2, BRW_REGISTER_TYPE_F);
5015    fs_reg msg_coords = message;
5016    unsigned header_size = 0;
5017 
5018    if (inst->offset != 0) {
5019       /* The offsets set up by the visitor are in the m1 header, so we can't
5020        * go headerless.
5021        */
5022       header_size = 1;
5023       message.nr--;
5024    }
5025 
5026    for (unsigned i = 0; i < coord_components; i++)
5027       bld.MOV(retype(offset(msg_coords, bld, i), coordinate.type),
5028               offset(coordinate, bld, i));
5029 
5030    fs_reg msg_end = offset(msg_coords, bld, coord_components);
5031    fs_reg msg_lod = offset(msg_coords, bld, 4);
5032 
5033    if (shadow_c.file != BAD_FILE) {
5034       fs_reg msg_shadow = msg_lod;
5035       bld.MOV(msg_shadow, shadow_c);
5036       msg_lod = offset(msg_shadow, bld, 1);
5037       msg_end = msg_lod;
5038    }
5039 
5040    switch (op) {
5041    case SHADER_OPCODE_TXL:
5042    case FS_OPCODE_TXB:
5043       bld.MOV(msg_lod, lod);
5044       msg_end = offset(msg_lod, bld, 1);
5045       break;
5046    case SHADER_OPCODE_TXD:
5047       /**
5048        *  P   =  u,    v,    r
5049        * dPdx = dudx, dvdx, drdx
5050        * dPdy = dudy, dvdy, drdy
5051        *
5052        * Load up these values:
5053        * - dudx   dudy   dvdx   dvdy   drdx   drdy
5054        * - dPdx.x dPdy.x dPdx.y dPdy.y dPdx.z dPdy.z
5055        */
5056       msg_end = msg_lod;
5057       for (unsigned i = 0; i < grad_components; i++) {
5058          bld.MOV(msg_end, offset(lod, bld, i));
5059          msg_end = offset(msg_end, bld, 1);
5060 
5061          bld.MOV(msg_end, offset(lod2, bld, i));
5062          msg_end = offset(msg_end, bld, 1);
5063       }
5064       break;
5065    case SHADER_OPCODE_TXS:
5066       msg_lod = retype(msg_end, BRW_REGISTER_TYPE_UD);
5067       bld.MOV(msg_lod, lod);
5068       msg_end = offset(msg_lod, bld, 1);
5069       break;
5070    case SHADER_OPCODE_TXF:
5071       msg_lod = offset(msg_coords, bld, 3);
5072       bld.MOV(retype(msg_lod, BRW_REGISTER_TYPE_UD), lod);
5073       msg_end = offset(msg_lod, bld, 1);
5074       break;
5075    case SHADER_OPCODE_TXF_CMS:
5076       msg_lod = offset(msg_coords, bld, 3);
5077       /* lod */
5078       bld.MOV(retype(msg_lod, BRW_REGISTER_TYPE_UD), brw_imm_ud(0u));
5079       /* sample index */
5080       bld.MOV(retype(offset(msg_lod, bld, 1), BRW_REGISTER_TYPE_UD), sample_index);
5081       msg_end = offset(msg_lod, bld, 2);
5082       break;
5083    default:
5084       break;
5085    }
5086 
5087    inst->opcode = op;
5088    inst->src[0] = reg_undef;
5089    inst->src[1] = surface;
5090    inst->src[2] = sampler;
5091    inst->resize_sources(3);
5092    inst->base_mrf = message.nr;
5093    inst->mlen = msg_end.nr - message.nr;
5094    inst->header_size = header_size;
5095 
5096    /* Message length > MAX_SAMPLER_MESSAGE_SIZE disallowed by hardware. */
5097    assert(inst->mlen <= MAX_SAMPLER_MESSAGE_SIZE);
5098 }
5099 
5100 static bool
is_high_sampler(const struct intel_device_info * devinfo,const fs_reg & sampler)5101 is_high_sampler(const struct intel_device_info *devinfo, const fs_reg &sampler)
5102 {
5103    if (devinfo->verx10 <= 70)
5104       return false;
5105 
5106    return sampler.file != IMM || sampler.ud >= 16;
5107 }
5108 
5109 static unsigned
sampler_msg_type(const intel_device_info * devinfo,opcode opcode,bool shadow_compare)5110 sampler_msg_type(const intel_device_info *devinfo,
5111                  opcode opcode, bool shadow_compare)
5112 {
5113    assert(devinfo->ver >= 5);
5114    switch (opcode) {
5115    case SHADER_OPCODE_TEX:
5116       return shadow_compare ? GFX5_SAMPLER_MESSAGE_SAMPLE_COMPARE :
5117                               GFX5_SAMPLER_MESSAGE_SAMPLE;
5118    case FS_OPCODE_TXB:
5119       return shadow_compare ? GFX5_SAMPLER_MESSAGE_SAMPLE_BIAS_COMPARE :
5120                               GFX5_SAMPLER_MESSAGE_SAMPLE_BIAS;
5121    case SHADER_OPCODE_TXL:
5122       return shadow_compare ? GFX5_SAMPLER_MESSAGE_SAMPLE_LOD_COMPARE :
5123                               GFX5_SAMPLER_MESSAGE_SAMPLE_LOD;
5124    case SHADER_OPCODE_TXL_LZ:
5125       return shadow_compare ? GFX9_SAMPLER_MESSAGE_SAMPLE_C_LZ :
5126                               GFX9_SAMPLER_MESSAGE_SAMPLE_LZ;
5127    case SHADER_OPCODE_TXS:
5128    case SHADER_OPCODE_IMAGE_SIZE_LOGICAL:
5129       return GFX5_SAMPLER_MESSAGE_SAMPLE_RESINFO;
5130    case SHADER_OPCODE_TXD:
5131       assert(!shadow_compare || devinfo->verx10 >= 75);
5132       return shadow_compare ? HSW_SAMPLER_MESSAGE_SAMPLE_DERIV_COMPARE :
5133                               GFX5_SAMPLER_MESSAGE_SAMPLE_DERIVS;
5134    case SHADER_OPCODE_TXF:
5135       return GFX5_SAMPLER_MESSAGE_SAMPLE_LD;
5136    case SHADER_OPCODE_TXF_LZ:
5137       assert(devinfo->ver >= 9);
5138       return GFX9_SAMPLER_MESSAGE_SAMPLE_LD_LZ;
5139    case SHADER_OPCODE_TXF_CMS_W:
5140       assert(devinfo->ver >= 9);
5141       return GFX9_SAMPLER_MESSAGE_SAMPLE_LD2DMS_W;
5142    case SHADER_OPCODE_TXF_CMS:
5143       return devinfo->ver >= 7 ? GFX7_SAMPLER_MESSAGE_SAMPLE_LD2DMS :
5144                                  GFX5_SAMPLER_MESSAGE_SAMPLE_LD;
5145    case SHADER_OPCODE_TXF_UMS:
5146       assert(devinfo->ver >= 7);
5147       return GFX7_SAMPLER_MESSAGE_SAMPLE_LD2DSS;
5148    case SHADER_OPCODE_TXF_MCS:
5149       assert(devinfo->ver >= 7);
5150       return GFX7_SAMPLER_MESSAGE_SAMPLE_LD_MCS;
5151    case SHADER_OPCODE_LOD:
5152       return GFX5_SAMPLER_MESSAGE_LOD;
5153    case SHADER_OPCODE_TG4:
5154       assert(devinfo->ver >= 7);
5155       return shadow_compare ? GFX7_SAMPLER_MESSAGE_SAMPLE_GATHER4_C :
5156                               GFX7_SAMPLER_MESSAGE_SAMPLE_GATHER4;
5157       break;
5158    case SHADER_OPCODE_TG4_OFFSET:
5159       assert(devinfo->ver >= 7);
5160       return shadow_compare ? GFX7_SAMPLER_MESSAGE_SAMPLE_GATHER4_PO_C :
5161                               GFX7_SAMPLER_MESSAGE_SAMPLE_GATHER4_PO;
5162    case SHADER_OPCODE_SAMPLEINFO:
5163       return GFX6_SAMPLER_MESSAGE_SAMPLE_SAMPLEINFO;
5164    default:
5165       unreachable("not reached");
5166    }
5167 }
5168 
5169 static void
lower_sampler_logical_send_gfx7(const fs_builder & bld,fs_inst * inst,opcode op,const fs_reg & coordinate,const fs_reg & shadow_c,fs_reg lod,const fs_reg & lod2,const fs_reg & min_lod,const fs_reg & sample_index,const fs_reg & mcs,const fs_reg & surface,const fs_reg & sampler,const fs_reg & surface_handle,const fs_reg & sampler_handle,const fs_reg & tg4_offset,unsigned coord_components,unsigned grad_components)5170 lower_sampler_logical_send_gfx7(const fs_builder &bld, fs_inst *inst, opcode op,
5171                                 const fs_reg &coordinate,
5172                                 const fs_reg &shadow_c,
5173                                 fs_reg lod, const fs_reg &lod2,
5174                                 const fs_reg &min_lod,
5175                                 const fs_reg &sample_index,
5176                                 const fs_reg &mcs,
5177                                 const fs_reg &surface,
5178                                 const fs_reg &sampler,
5179                                 const fs_reg &surface_handle,
5180                                 const fs_reg &sampler_handle,
5181                                 const fs_reg &tg4_offset,
5182                                 unsigned coord_components,
5183                                 unsigned grad_components)
5184 {
5185    const intel_device_info *devinfo = bld.shader->devinfo;
5186    const brw_stage_prog_data *prog_data = bld.shader->stage_prog_data;
5187    unsigned reg_width = bld.dispatch_width() / 8;
5188    unsigned header_size = 0, length = 0;
5189    fs_reg sources[MAX_SAMPLER_MESSAGE_SIZE];
5190    for (unsigned i = 0; i < ARRAY_SIZE(sources); i++)
5191       sources[i] = bld.vgrf(BRW_REGISTER_TYPE_F);
5192 
5193    /* We must have exactly one of surface/sampler and surface/sampler_handle */
5194    assert((surface.file == BAD_FILE) != (surface_handle.file == BAD_FILE));
5195    assert((sampler.file == BAD_FILE) != (sampler_handle.file == BAD_FILE));
5196 
5197    if (op == SHADER_OPCODE_TG4 || op == SHADER_OPCODE_TG4_OFFSET ||
5198        inst->offset != 0 || inst->eot ||
5199        op == SHADER_OPCODE_SAMPLEINFO ||
5200        sampler_handle.file != BAD_FILE ||
5201        is_high_sampler(devinfo, sampler)) {
5202       /* For general texture offsets (no txf workaround), we need a header to
5203        * put them in.
5204        *
5205        * TG4 needs to place its channel select in the header, for interaction
5206        * with ARB_texture_swizzle.  The sampler index is only 4-bits, so for
5207        * larger sampler numbers we need to offset the Sampler State Pointer in
5208        * the header.
5209        */
5210       fs_reg header = retype(sources[0], BRW_REGISTER_TYPE_UD);
5211       header_size = 1;
5212       length++;
5213 
5214       /* If we're requesting fewer than four channels worth of response,
5215        * and we have an explicit header, we need to set up the sampler
5216        * writemask.  It's reversed from normal: 1 means "don't write".
5217        */
5218       if (!inst->eot && regs_written(inst) != 4 * reg_width) {
5219          assert(regs_written(inst) % reg_width == 0);
5220          unsigned mask = ~((1 << (regs_written(inst) / reg_width)) - 1) & 0xf;
5221          inst->offset |= mask << 12;
5222       }
5223 
5224       /* Build the actual header */
5225       const fs_builder ubld = bld.exec_all().group(8, 0);
5226       const fs_builder ubld1 = ubld.group(1, 0);
5227       ubld.MOV(header, retype(brw_vec8_grf(0, 0), BRW_REGISTER_TYPE_UD));
5228       if (inst->offset) {
5229          ubld1.MOV(component(header, 2), brw_imm_ud(inst->offset));
5230       } else if (bld.shader->stage != MESA_SHADER_VERTEX &&
5231                  bld.shader->stage != MESA_SHADER_FRAGMENT) {
5232          /* The vertex and fragment stages have g0.2 set to 0, so
5233           * header0.2 is 0 when g0 is copied. Other stages may not, so we
5234           * must set it to 0 to avoid setting undesirable bits in the
5235           * message.
5236           */
5237          ubld1.MOV(component(header, 2), brw_imm_ud(0));
5238       }
5239 
5240       if (sampler_handle.file != BAD_FILE) {
5241          /* Bindless sampler handles aren't relative to the sampler state
5242           * pointer passed into the shader through SAMPLER_STATE_POINTERS_*.
5243           * Instead, it's an absolute pointer relative to dynamic state base
5244           * address.
5245           *
5246           * Sampler states are 16 bytes each and the pointer we give here has
5247           * to be 32-byte aligned.  In order to avoid more indirect messages
5248           * than required, we assume that all bindless sampler states are
5249           * 32-byte aligned.  This sacrifices a bit of general state base
5250           * address space but means we can do something more efficient in the
5251           * shader.
5252           */
5253          ubld1.MOV(component(header, 3), sampler_handle);
5254       } else if (is_high_sampler(devinfo, sampler)) {
5255          fs_reg sampler_state_ptr =
5256             retype(brw_vec1_grf(0, 3), BRW_REGISTER_TYPE_UD);
5257 
5258          /* Gfx11+ sampler message headers include bits in 4:0 which conflict
5259           * with the ones included in g0.3 bits 4:0.  Mask them out.
5260           */
5261          if (devinfo->ver >= 11) {
5262             sampler_state_ptr = ubld1.vgrf(BRW_REGISTER_TYPE_UD);
5263             ubld1.AND(sampler_state_ptr,
5264                       retype(brw_vec1_grf(0, 3), BRW_REGISTER_TYPE_UD),
5265                       brw_imm_ud(INTEL_MASK(31, 5)));
5266          }
5267 
5268          if (sampler.file == BRW_IMMEDIATE_VALUE) {
5269             assert(sampler.ud >= 16);
5270             const int sampler_state_size = 16; /* 16 bytes */
5271 
5272             ubld1.ADD(component(header, 3), sampler_state_ptr,
5273                       brw_imm_ud(16 * (sampler.ud / 16) * sampler_state_size));
5274          } else {
5275             fs_reg tmp = ubld1.vgrf(BRW_REGISTER_TYPE_UD);
5276             ubld1.AND(tmp, sampler, brw_imm_ud(0x0f0));
5277             ubld1.SHL(tmp, tmp, brw_imm_ud(4));
5278             ubld1.ADD(component(header, 3), sampler_state_ptr, tmp);
5279          }
5280       } else if (devinfo->ver >= 11) {
5281          /* Gfx11+ sampler message headers include bits in 4:0 which conflict
5282           * with the ones included in g0.3 bits 4:0.  Mask them out.
5283           */
5284          ubld1.AND(component(header, 3),
5285                    retype(brw_vec1_grf(0, 3), BRW_REGISTER_TYPE_UD),
5286                    brw_imm_ud(INTEL_MASK(31, 5)));
5287       }
5288    }
5289 
5290    if (shadow_c.file != BAD_FILE) {
5291       bld.MOV(sources[length], shadow_c);
5292       length++;
5293    }
5294 
5295    bool coordinate_done = false;
5296 
5297    /* Set up the LOD info */
5298    switch (op) {
5299    case FS_OPCODE_TXB:
5300    case SHADER_OPCODE_TXL:
5301       if (devinfo->ver >= 9 && op == SHADER_OPCODE_TXL && lod.is_zero()) {
5302          op = SHADER_OPCODE_TXL_LZ;
5303          break;
5304       }
5305       bld.MOV(sources[length], lod);
5306       length++;
5307       break;
5308    case SHADER_OPCODE_TXD:
5309       /* TXD should have been lowered in SIMD16 mode. */
5310       assert(bld.dispatch_width() == 8);
5311 
5312       /* Load dPdx and the coordinate together:
5313        * [hdr], [ref], x, dPdx.x, dPdy.x, y, dPdx.y, dPdy.y, z, dPdx.z, dPdy.z
5314        */
5315       for (unsigned i = 0; i < coord_components; i++) {
5316          bld.MOV(sources[length++], offset(coordinate, bld, i));
5317 
5318          /* For cube map array, the coordinate is (u,v,r,ai) but there are
5319           * only derivatives for (u, v, r).
5320           */
5321          if (i < grad_components) {
5322             bld.MOV(sources[length++], offset(lod, bld, i));
5323             bld.MOV(sources[length++], offset(lod2, bld, i));
5324          }
5325       }
5326 
5327       coordinate_done = true;
5328       break;
5329    case SHADER_OPCODE_TXS:
5330       bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_UD), lod);
5331       length++;
5332       break;
5333    case SHADER_OPCODE_IMAGE_SIZE_LOGICAL:
5334       /* We need an LOD; just use 0 */
5335       bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_UD), brw_imm_ud(0));
5336       length++;
5337       break;
5338    case SHADER_OPCODE_TXF:
5339       /* Unfortunately, the parameters for LD are intermixed: u, lod, v, r.
5340        * On Gfx9 they are u, v, lod, r
5341        */
5342       bld.MOV(retype(sources[length++], BRW_REGISTER_TYPE_D), coordinate);
5343 
5344       if (devinfo->ver >= 9) {
5345          if (coord_components >= 2) {
5346             bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_D),
5347                     offset(coordinate, bld, 1));
5348          } else {
5349             sources[length] = brw_imm_d(0);
5350          }
5351          length++;
5352       }
5353 
5354       if (devinfo->ver >= 9 && lod.is_zero()) {
5355          op = SHADER_OPCODE_TXF_LZ;
5356       } else {
5357          bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_D), lod);
5358          length++;
5359       }
5360 
5361       for (unsigned i = devinfo->ver >= 9 ? 2 : 1; i < coord_components; i++)
5362          bld.MOV(retype(sources[length++], BRW_REGISTER_TYPE_D),
5363                  offset(coordinate, bld, i));
5364 
5365       coordinate_done = true;
5366       break;
5367 
5368    case SHADER_OPCODE_TXF_CMS:
5369    case SHADER_OPCODE_TXF_CMS_W:
5370    case SHADER_OPCODE_TXF_UMS:
5371    case SHADER_OPCODE_TXF_MCS:
5372       if (op == SHADER_OPCODE_TXF_UMS ||
5373           op == SHADER_OPCODE_TXF_CMS ||
5374           op == SHADER_OPCODE_TXF_CMS_W) {
5375          bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_UD), sample_index);
5376          length++;
5377       }
5378 
5379       if (op == SHADER_OPCODE_TXF_CMS || op == SHADER_OPCODE_TXF_CMS_W) {
5380          /* Data from the multisample control surface. */
5381          bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_UD), mcs);
5382          length++;
5383 
5384          /* On Gfx9+ we'll use ld2dms_w instead which has two registers for
5385           * the MCS data.
5386           */
5387          if (op == SHADER_OPCODE_TXF_CMS_W) {
5388             bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_UD),
5389                     mcs.file == IMM ?
5390                     mcs :
5391                     offset(mcs, bld, 1));
5392             length++;
5393          }
5394       }
5395 
5396       /* There is no offsetting for this message; just copy in the integer
5397        * texture coordinates.
5398        */
5399       for (unsigned i = 0; i < coord_components; i++)
5400          bld.MOV(retype(sources[length++], BRW_REGISTER_TYPE_D),
5401                  offset(coordinate, bld, i));
5402 
5403       coordinate_done = true;
5404       break;
5405    case SHADER_OPCODE_TG4_OFFSET:
5406       /* More crazy intermixing */
5407       for (unsigned i = 0; i < 2; i++) /* u, v */
5408          bld.MOV(sources[length++], offset(coordinate, bld, i));
5409 
5410       for (unsigned i = 0; i < 2; i++) /* offu, offv */
5411          bld.MOV(retype(sources[length++], BRW_REGISTER_TYPE_D),
5412                  offset(tg4_offset, bld, i));
5413 
5414       if (coord_components == 3) /* r if present */
5415          bld.MOV(sources[length++], offset(coordinate, bld, 2));
5416 
5417       coordinate_done = true;
5418       break;
5419    default:
5420       break;
5421    }
5422 
5423    /* Set up the coordinate (except for cases where it was done above) */
5424    if (!coordinate_done) {
5425       for (unsigned i = 0; i < coord_components; i++)
5426          bld.MOV(sources[length++], offset(coordinate, bld, i));
5427    }
5428 
5429    if (min_lod.file != BAD_FILE) {
5430       /* Account for all of the missing coordinate sources */
5431       length += 4 - coord_components;
5432       if (op == SHADER_OPCODE_TXD)
5433          length += (3 - grad_components) * 2;
5434 
5435       bld.MOV(sources[length++], min_lod);
5436    }
5437 
5438    unsigned mlen;
5439    if (reg_width == 2)
5440       mlen = length * reg_width - header_size;
5441    else
5442       mlen = length * reg_width;
5443 
5444    const fs_reg src_payload = fs_reg(VGRF, bld.shader->alloc.allocate(mlen),
5445                                      BRW_REGISTER_TYPE_F);
5446    bld.LOAD_PAYLOAD(src_payload, sources, length, header_size);
5447 
5448    /* Generate the SEND. */
5449    inst->opcode = SHADER_OPCODE_SEND;
5450    inst->mlen = mlen;
5451    inst->header_size = header_size;
5452 
5453    const unsigned msg_type =
5454       sampler_msg_type(devinfo, op, inst->shadow_compare);
5455    const unsigned simd_mode =
5456       inst->exec_size <= 8 ? BRW_SAMPLER_SIMD_MODE_SIMD8 :
5457                              BRW_SAMPLER_SIMD_MODE_SIMD16;
5458 
5459    uint32_t base_binding_table_index;
5460    switch (op) {
5461    case SHADER_OPCODE_TG4:
5462    case SHADER_OPCODE_TG4_OFFSET:
5463       base_binding_table_index = prog_data->binding_table.gather_texture_start;
5464       break;
5465    case SHADER_OPCODE_IMAGE_SIZE_LOGICAL:
5466       base_binding_table_index = prog_data->binding_table.image_start;
5467       break;
5468    default:
5469       base_binding_table_index = prog_data->binding_table.texture_start;
5470       break;
5471    }
5472 
5473    inst->sfid = BRW_SFID_SAMPLER;
5474    if (surface.file == IMM &&
5475        (sampler.file == IMM || sampler_handle.file != BAD_FILE)) {
5476       inst->desc = brw_sampler_desc(devinfo,
5477                                     surface.ud + base_binding_table_index,
5478                                     sampler.file == IMM ? sampler.ud % 16 : 0,
5479                                     msg_type,
5480                                     simd_mode,
5481                                     0 /* return_format unused on gfx7+ */);
5482       inst->src[0] = brw_imm_ud(0);
5483       inst->src[1] = brw_imm_ud(0);
5484    } else if (surface_handle.file != BAD_FILE) {
5485       /* Bindless surface */
5486       assert(devinfo->ver >= 9);
5487       inst->desc = brw_sampler_desc(devinfo,
5488                                     GFX9_BTI_BINDLESS,
5489                                     sampler.file == IMM ? sampler.ud % 16 : 0,
5490                                     msg_type,
5491                                     simd_mode,
5492                                     0 /* return_format unused on gfx7+ */);
5493 
5494       /* For bindless samplers, the entire address is included in the message
5495        * header so we can leave the portion in the message descriptor 0.
5496        */
5497       if (sampler_handle.file != BAD_FILE || sampler.file == IMM) {
5498          inst->src[0] = brw_imm_ud(0);
5499       } else {
5500          const fs_builder ubld = bld.group(1, 0).exec_all();
5501          fs_reg desc = ubld.vgrf(BRW_REGISTER_TYPE_UD);
5502          ubld.SHL(desc, sampler, brw_imm_ud(8));
5503          inst->src[0] = desc;
5504       }
5505 
5506       /* We assume that the driver provided the handle in the top 20 bits so
5507        * we can use the surface handle directly as the extended descriptor.
5508        */
5509       inst->src[1] = retype(surface_handle, BRW_REGISTER_TYPE_UD);
5510    } else {
5511       /* Immediate portion of the descriptor */
5512       inst->desc = brw_sampler_desc(devinfo,
5513                                     0, /* surface */
5514                                     0, /* sampler */
5515                                     msg_type,
5516                                     simd_mode,
5517                                     0 /* return_format unused on gfx7+ */);
5518       const fs_builder ubld = bld.group(1, 0).exec_all();
5519       fs_reg desc = ubld.vgrf(BRW_REGISTER_TYPE_UD);
5520       if (surface.equals(sampler)) {
5521          /* This case is common in GL */
5522          ubld.MUL(desc, surface, brw_imm_ud(0x101));
5523       } else {
5524          if (sampler_handle.file != BAD_FILE) {
5525             ubld.MOV(desc, surface);
5526          } else if (sampler.file == IMM) {
5527             ubld.OR(desc, surface, brw_imm_ud(sampler.ud << 8));
5528          } else {
5529             ubld.SHL(desc, sampler, brw_imm_ud(8));
5530             ubld.OR(desc, desc, surface);
5531          }
5532       }
5533       if (base_binding_table_index)
5534          ubld.ADD(desc, desc, brw_imm_ud(base_binding_table_index));
5535       ubld.AND(desc, desc, brw_imm_ud(0xfff));
5536 
5537       inst->src[0] = component(desc, 0);
5538       inst->src[1] = brw_imm_ud(0); /* ex_desc */
5539    }
5540 
5541    inst->ex_desc = 0;
5542 
5543    inst->src[2] = src_payload;
5544    inst->resize_sources(3);
5545 
5546    if (inst->eot) {
5547       /* EOT sampler messages don't make sense to split because it would
5548        * involve ending half of the thread early.
5549        */
5550       assert(inst->group == 0);
5551       /* We need to use SENDC for EOT sampler messages */
5552       inst->check_tdr = true;
5553       inst->send_has_side_effects = true;
5554    }
5555 
5556    /* Message length > MAX_SAMPLER_MESSAGE_SIZE disallowed by hardware. */
5557    assert(inst->mlen <= MAX_SAMPLER_MESSAGE_SIZE);
5558 }
5559 
5560 static void
lower_sampler_logical_send(const fs_builder & bld,fs_inst * inst,opcode op)5561 lower_sampler_logical_send(const fs_builder &bld, fs_inst *inst, opcode op)
5562 {
5563    const intel_device_info *devinfo = bld.shader->devinfo;
5564    const fs_reg &coordinate = inst->src[TEX_LOGICAL_SRC_COORDINATE];
5565    const fs_reg &shadow_c = inst->src[TEX_LOGICAL_SRC_SHADOW_C];
5566    const fs_reg &lod = inst->src[TEX_LOGICAL_SRC_LOD];
5567    const fs_reg &lod2 = inst->src[TEX_LOGICAL_SRC_LOD2];
5568    const fs_reg &min_lod = inst->src[TEX_LOGICAL_SRC_MIN_LOD];
5569    const fs_reg &sample_index = inst->src[TEX_LOGICAL_SRC_SAMPLE_INDEX];
5570    const fs_reg &mcs = inst->src[TEX_LOGICAL_SRC_MCS];
5571    const fs_reg &surface = inst->src[TEX_LOGICAL_SRC_SURFACE];
5572    const fs_reg &sampler = inst->src[TEX_LOGICAL_SRC_SAMPLER];
5573    const fs_reg &surface_handle = inst->src[TEX_LOGICAL_SRC_SURFACE_HANDLE];
5574    const fs_reg &sampler_handle = inst->src[TEX_LOGICAL_SRC_SAMPLER_HANDLE];
5575    const fs_reg &tg4_offset = inst->src[TEX_LOGICAL_SRC_TG4_OFFSET];
5576    assert(inst->src[TEX_LOGICAL_SRC_COORD_COMPONENTS].file == IMM);
5577    const unsigned coord_components = inst->src[TEX_LOGICAL_SRC_COORD_COMPONENTS].ud;
5578    assert(inst->src[TEX_LOGICAL_SRC_GRAD_COMPONENTS].file == IMM);
5579    const unsigned grad_components = inst->src[TEX_LOGICAL_SRC_GRAD_COMPONENTS].ud;
5580 
5581    if (devinfo->ver >= 7) {
5582       lower_sampler_logical_send_gfx7(bld, inst, op, coordinate,
5583                                       shadow_c, lod, lod2, min_lod,
5584                                       sample_index,
5585                                       mcs, surface, sampler,
5586                                       surface_handle, sampler_handle,
5587                                       tg4_offset,
5588                                       coord_components, grad_components);
5589    } else if (devinfo->ver >= 5) {
5590       lower_sampler_logical_send_gfx5(bld, inst, op, coordinate,
5591                                       shadow_c, lod, lod2, sample_index,
5592                                       surface, sampler,
5593                                       coord_components, grad_components);
5594    } else {
5595       lower_sampler_logical_send_gfx4(bld, inst, op, coordinate,
5596                                       shadow_c, lod, lod2,
5597                                       surface, sampler,
5598                                       coord_components, grad_components);
5599    }
5600 }
5601 
5602 /**
5603  * Predicate the specified instruction on the sample mask.
5604  */
5605 static void
emit_predicate_on_sample_mask(const fs_builder & bld,fs_inst * inst)5606 emit_predicate_on_sample_mask(const fs_builder &bld, fs_inst *inst)
5607 {
5608    assert(bld.shader->stage == MESA_SHADER_FRAGMENT &&
5609           bld.group() == inst->group &&
5610           bld.dispatch_width() == inst->exec_size);
5611 
5612    const fs_visitor *v = static_cast<const fs_visitor *>(bld.shader);
5613    const fs_reg sample_mask = sample_mask_reg(bld);
5614    const unsigned subreg = sample_mask_flag_subreg(v);
5615 
5616    if (brw_wm_prog_data(v->stage_prog_data)->uses_kill) {
5617       assert(sample_mask.file == ARF &&
5618              sample_mask.nr == brw_flag_subreg(subreg).nr &&
5619              sample_mask.subnr == brw_flag_subreg(
5620                 subreg + inst->group / 16).subnr);
5621    } else {
5622       bld.group(1, 0).exec_all()
5623          .MOV(brw_flag_subreg(subreg + inst->group / 16), sample_mask);
5624    }
5625 
5626    if (inst->predicate) {
5627       assert(inst->predicate == BRW_PREDICATE_NORMAL);
5628       assert(!inst->predicate_inverse);
5629       assert(inst->flag_subreg == 0);
5630       /* Combine the sample mask with the existing predicate by using a
5631        * vertical predication mode.
5632        */
5633       inst->predicate = BRW_PREDICATE_ALIGN1_ALLV;
5634    } else {
5635       inst->flag_subreg = subreg;
5636       inst->predicate = BRW_PREDICATE_NORMAL;
5637       inst->predicate_inverse = false;
5638    }
5639 }
5640 
5641 static void
setup_surface_descriptors(const fs_builder & bld,fs_inst * inst,uint32_t desc,const fs_reg & surface,const fs_reg & surface_handle)5642 setup_surface_descriptors(const fs_builder &bld, fs_inst *inst, uint32_t desc,
5643                           const fs_reg &surface, const fs_reg &surface_handle)
5644 {
5645    const ASSERTED intel_device_info *devinfo = bld.shader->devinfo;
5646 
5647    /* We must have exactly one of surface and surface_handle */
5648    assert((surface.file == BAD_FILE) != (surface_handle.file == BAD_FILE));
5649 
5650    if (surface.file == IMM) {
5651       inst->desc = desc | (surface.ud & 0xff);
5652       inst->src[0] = brw_imm_ud(0);
5653       inst->src[1] = brw_imm_ud(0); /* ex_desc */
5654    } else if (surface_handle.file != BAD_FILE) {
5655       /* Bindless surface */
5656       assert(devinfo->ver >= 9);
5657       inst->desc = desc | GFX9_BTI_BINDLESS;
5658       inst->src[0] = brw_imm_ud(0);
5659 
5660       /* We assume that the driver provided the handle in the top 20 bits so
5661        * we can use the surface handle directly as the extended descriptor.
5662        */
5663       inst->src[1] = retype(surface_handle, BRW_REGISTER_TYPE_UD);
5664    } else {
5665       inst->desc = desc;
5666       const fs_builder ubld = bld.exec_all().group(1, 0);
5667       fs_reg tmp = ubld.vgrf(BRW_REGISTER_TYPE_UD);
5668       ubld.AND(tmp, surface, brw_imm_ud(0xff));
5669       inst->src[0] = component(tmp, 0);
5670       inst->src[1] = brw_imm_ud(0); /* ex_desc */
5671    }
5672 }
5673 
5674 static void
lower_surface_logical_send(const fs_builder & bld,fs_inst * inst)5675 lower_surface_logical_send(const fs_builder &bld, fs_inst *inst)
5676 {
5677    const intel_device_info *devinfo = bld.shader->devinfo;
5678 
5679    /* Get the logical send arguments. */
5680    const fs_reg &addr = inst->src[SURFACE_LOGICAL_SRC_ADDRESS];
5681    const fs_reg &src = inst->src[SURFACE_LOGICAL_SRC_DATA];
5682    const fs_reg &surface = inst->src[SURFACE_LOGICAL_SRC_SURFACE];
5683    const fs_reg &surface_handle = inst->src[SURFACE_LOGICAL_SRC_SURFACE_HANDLE];
5684    const UNUSED fs_reg &dims = inst->src[SURFACE_LOGICAL_SRC_IMM_DIMS];
5685    const fs_reg &arg = inst->src[SURFACE_LOGICAL_SRC_IMM_ARG];
5686    const fs_reg &allow_sample_mask =
5687       inst->src[SURFACE_LOGICAL_SRC_ALLOW_SAMPLE_MASK];
5688    assert(arg.file == IMM);
5689    assert(allow_sample_mask.file == IMM);
5690 
5691    /* Calculate the total number of components of the payload. */
5692    const unsigned addr_sz = inst->components_read(SURFACE_LOGICAL_SRC_ADDRESS);
5693    const unsigned src_sz = inst->components_read(SURFACE_LOGICAL_SRC_DATA);
5694 
5695    const bool is_typed_access =
5696       inst->opcode == SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL ||
5697       inst->opcode == SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL ||
5698       inst->opcode == SHADER_OPCODE_TYPED_ATOMIC_LOGICAL;
5699 
5700    const bool is_surface_access = is_typed_access ||
5701       inst->opcode == SHADER_OPCODE_UNTYPED_SURFACE_READ_LOGICAL ||
5702       inst->opcode == SHADER_OPCODE_UNTYPED_SURFACE_WRITE_LOGICAL ||
5703       inst->opcode == SHADER_OPCODE_UNTYPED_ATOMIC_LOGICAL;
5704 
5705    const bool is_stateless =
5706       surface.file == IMM && (surface.ud == BRW_BTI_STATELESS ||
5707                               surface.ud == GFX8_BTI_STATELESS_NON_COHERENT);
5708 
5709    const bool has_side_effects = inst->has_side_effects();
5710 
5711    fs_reg sample_mask = allow_sample_mask.ud ? sample_mask_reg(bld) :
5712                                                fs_reg(brw_imm_d(0xffff));
5713 
5714    /* From the BDW PRM Volume 7, page 147:
5715     *
5716     *  "For the Data Cache Data Port*, the header must be present for the
5717     *   following message types: [...] Typed read/write/atomics"
5718     *
5719     * Earlier generations have a similar wording.  Because of this restriction
5720     * we don't attempt to implement sample masks via predication for such
5721     * messages prior to Gfx9, since we have to provide a header anyway.  On
5722     * Gfx11+ the header has been removed so we can only use predication.
5723     *
5724     * For all stateless A32 messages, we also need a header
5725     */
5726    fs_reg header;
5727    if ((devinfo->ver < 9 && is_typed_access) || is_stateless) {
5728       fs_builder ubld = bld.exec_all().group(8, 0);
5729       header = ubld.vgrf(BRW_REGISTER_TYPE_UD);
5730       if (is_stateless) {
5731          assert(!is_surface_access);
5732          ubld.emit(SHADER_OPCODE_SCRATCH_HEADER, header);
5733       } else {
5734          ubld.MOV(header, brw_imm_d(0));
5735          if (is_surface_access)
5736             ubld.group(1, 0).MOV(component(header, 7), sample_mask);
5737       }
5738    }
5739    const unsigned header_sz = header.file != BAD_FILE ? 1 : 0;
5740 
5741    fs_reg payload, payload2;
5742    unsigned mlen, ex_mlen = 0;
5743    if (devinfo->ver >= 9 &&
5744        (src.file == BAD_FILE || header.file == BAD_FILE)) {
5745       /* We have split sends on gfx9 and above */
5746       if (header.file == BAD_FILE) {
5747          payload = bld.move_to_vgrf(addr, addr_sz);
5748          payload2 = bld.move_to_vgrf(src, src_sz);
5749          mlen = addr_sz * (inst->exec_size / 8);
5750          ex_mlen = src_sz * (inst->exec_size / 8);
5751       } else {
5752          assert(src.file == BAD_FILE);
5753          payload = header;
5754          payload2 = bld.move_to_vgrf(addr, addr_sz);
5755          mlen = header_sz;
5756          ex_mlen = addr_sz * (inst->exec_size / 8);
5757       }
5758    } else {
5759       /* Allocate space for the payload. */
5760       const unsigned sz = header_sz + addr_sz + src_sz;
5761       payload = bld.vgrf(BRW_REGISTER_TYPE_UD, sz);
5762       fs_reg *const components = new fs_reg[sz];
5763       unsigned n = 0;
5764 
5765       /* Construct the payload. */
5766       if (header.file != BAD_FILE)
5767          components[n++] = header;
5768 
5769       for (unsigned i = 0; i < addr_sz; i++)
5770          components[n++] = offset(addr, bld, i);
5771 
5772       for (unsigned i = 0; i < src_sz; i++)
5773          components[n++] = offset(src, bld, i);
5774 
5775       bld.LOAD_PAYLOAD(payload, components, sz, header_sz);
5776       mlen = header_sz + (addr_sz + src_sz) * inst->exec_size / 8;
5777 
5778       delete[] components;
5779    }
5780 
5781    /* Predicate the instruction on the sample mask if no header is
5782     * provided.
5783     */
5784    if ((header.file == BAD_FILE || !is_surface_access) &&
5785        sample_mask.file != BAD_FILE && sample_mask.file != IMM)
5786       emit_predicate_on_sample_mask(bld, inst);
5787 
5788    uint32_t sfid;
5789    switch (inst->opcode) {
5790    case SHADER_OPCODE_BYTE_SCATTERED_WRITE_LOGICAL:
5791    case SHADER_OPCODE_BYTE_SCATTERED_READ_LOGICAL:
5792       /* Byte scattered opcodes go through the normal data cache */
5793       sfid = GFX7_SFID_DATAPORT_DATA_CACHE;
5794       break;
5795 
5796    case SHADER_OPCODE_DWORD_SCATTERED_READ_LOGICAL:
5797    case SHADER_OPCODE_DWORD_SCATTERED_WRITE_LOGICAL:
5798       sfid =  devinfo->ver >= 7 ? GFX7_SFID_DATAPORT_DATA_CACHE :
5799               devinfo->ver >= 6 ? GFX6_SFID_DATAPORT_RENDER_CACHE :
5800                                   BRW_DATAPORT_READ_TARGET_RENDER_CACHE;
5801       break;
5802 
5803    case SHADER_OPCODE_UNTYPED_SURFACE_READ_LOGICAL:
5804    case SHADER_OPCODE_UNTYPED_SURFACE_WRITE_LOGICAL:
5805    case SHADER_OPCODE_UNTYPED_ATOMIC_LOGICAL:
5806    case SHADER_OPCODE_UNTYPED_ATOMIC_FLOAT_LOGICAL:
5807       /* Untyped Surface messages go through the data cache but the SFID value
5808        * changed on Haswell.
5809        */
5810       sfid = (devinfo->verx10 >= 75 ?
5811               HSW_SFID_DATAPORT_DATA_CACHE_1 :
5812               GFX7_SFID_DATAPORT_DATA_CACHE);
5813       break;
5814 
5815    case SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL:
5816    case SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL:
5817    case SHADER_OPCODE_TYPED_ATOMIC_LOGICAL:
5818       /* Typed surface messages go through the render cache on IVB and the
5819        * data cache on HSW+.
5820        */
5821       sfid = (devinfo->verx10 >= 75 ?
5822               HSW_SFID_DATAPORT_DATA_CACHE_1 :
5823               GFX6_SFID_DATAPORT_RENDER_CACHE);
5824       break;
5825 
5826    default:
5827       unreachable("Unsupported surface opcode");
5828    }
5829 
5830    uint32_t desc;
5831    switch (inst->opcode) {
5832    case SHADER_OPCODE_UNTYPED_SURFACE_READ_LOGICAL:
5833       desc = brw_dp_untyped_surface_rw_desc(devinfo, inst->exec_size,
5834                                             arg.ud, /* num_channels */
5835                                             false   /* write */);
5836       break;
5837 
5838    case SHADER_OPCODE_UNTYPED_SURFACE_WRITE_LOGICAL:
5839       desc = brw_dp_untyped_surface_rw_desc(devinfo, inst->exec_size,
5840                                             arg.ud, /* num_channels */
5841                                             true    /* write */);
5842       break;
5843 
5844    case SHADER_OPCODE_BYTE_SCATTERED_READ_LOGICAL:
5845       desc = brw_dp_byte_scattered_rw_desc(devinfo, inst->exec_size,
5846                                            arg.ud, /* bit_size */
5847                                            false   /* write */);
5848       break;
5849 
5850    case SHADER_OPCODE_BYTE_SCATTERED_WRITE_LOGICAL:
5851       desc = brw_dp_byte_scattered_rw_desc(devinfo, inst->exec_size,
5852                                            arg.ud, /* bit_size */
5853                                            true    /* write */);
5854       break;
5855 
5856    case SHADER_OPCODE_DWORD_SCATTERED_READ_LOGICAL:
5857       assert(arg.ud == 32); /* bit_size */
5858       desc = brw_dp_dword_scattered_rw_desc(devinfo, inst->exec_size,
5859                                             false  /* write */);
5860       break;
5861 
5862    case SHADER_OPCODE_DWORD_SCATTERED_WRITE_LOGICAL:
5863       assert(arg.ud == 32); /* bit_size */
5864       desc = brw_dp_dword_scattered_rw_desc(devinfo, inst->exec_size,
5865                                             true   /* write */);
5866       break;
5867 
5868    case SHADER_OPCODE_UNTYPED_ATOMIC_LOGICAL:
5869       desc = brw_dp_untyped_atomic_desc(devinfo, inst->exec_size,
5870                                         arg.ud, /* atomic_op */
5871                                         !inst->dst.is_null());
5872       break;
5873 
5874    case SHADER_OPCODE_UNTYPED_ATOMIC_FLOAT_LOGICAL:
5875       desc = brw_dp_untyped_atomic_float_desc(devinfo, inst->exec_size,
5876                                               arg.ud, /* atomic_op */
5877                                               !inst->dst.is_null());
5878       break;
5879 
5880    case SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL:
5881       desc = brw_dp_typed_surface_rw_desc(devinfo, inst->exec_size, inst->group,
5882                                           arg.ud, /* num_channels */
5883                                           false   /* write */);
5884       break;
5885 
5886    case SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL:
5887       desc = brw_dp_typed_surface_rw_desc(devinfo, inst->exec_size, inst->group,
5888                                           arg.ud, /* num_channels */
5889                                           true    /* write */);
5890       break;
5891 
5892    case SHADER_OPCODE_TYPED_ATOMIC_LOGICAL:
5893       desc = brw_dp_typed_atomic_desc(devinfo, inst->exec_size, inst->group,
5894                                       arg.ud, /* atomic_op */
5895                                       !inst->dst.is_null());
5896       break;
5897 
5898    default:
5899       unreachable("Unknown surface logical instruction");
5900    }
5901 
5902    /* Update the original instruction. */
5903    inst->opcode = SHADER_OPCODE_SEND;
5904    inst->mlen = mlen;
5905    inst->ex_mlen = ex_mlen;
5906    inst->header_size = header_sz;
5907    inst->send_has_side_effects = has_side_effects;
5908    inst->send_is_volatile = !has_side_effects;
5909 
5910    /* Set up SFID and descriptors */
5911    inst->sfid = sfid;
5912    setup_surface_descriptors(bld, inst, desc, surface, surface_handle);
5913 
5914    /* Finally, the payload */
5915    inst->src[2] = payload;
5916    inst->src[3] = payload2;
5917 
5918    inst->resize_sources(4);
5919 }
5920 
5921 static enum lsc_opcode
brw_atomic_op_to_lsc_atomic_op(unsigned op)5922 brw_atomic_op_to_lsc_atomic_op(unsigned op)
5923 {
5924    switch(op) {
5925    case BRW_AOP_AND:
5926       return LSC_OP_ATOMIC_AND;
5927    case BRW_AOP_OR:
5928       return LSC_OP_ATOMIC_OR;
5929    case BRW_AOP_XOR:
5930       return LSC_OP_ATOMIC_XOR;
5931    case BRW_AOP_MOV:
5932       return LSC_OP_ATOMIC_STORE;
5933    case BRW_AOP_INC:
5934       return LSC_OP_ATOMIC_INC;
5935    case BRW_AOP_DEC:
5936       return LSC_OP_ATOMIC_DEC;
5937    case BRW_AOP_ADD:
5938       return LSC_OP_ATOMIC_ADD;
5939    case BRW_AOP_SUB:
5940       return LSC_OP_ATOMIC_SUB;
5941    case BRW_AOP_IMAX:
5942       return LSC_OP_ATOMIC_MAX;
5943    case BRW_AOP_IMIN:
5944       return LSC_OP_ATOMIC_MIN;
5945    case BRW_AOP_UMAX:
5946       return LSC_OP_ATOMIC_UMAX;
5947    case BRW_AOP_UMIN:
5948       return LSC_OP_ATOMIC_UMIN;
5949    case BRW_AOP_CMPWR:
5950       return LSC_OP_ATOMIC_CMPXCHG;
5951    default:
5952       assert(false);
5953       unreachable("invalid atomic opcode");
5954    }
5955 }
5956 
5957 static enum lsc_opcode
brw_atomic_op_to_lsc_fatomic_op(uint32_t aop)5958 brw_atomic_op_to_lsc_fatomic_op(uint32_t aop)
5959 {
5960    switch(aop) {
5961    case BRW_AOP_FMAX:
5962       return LSC_OP_ATOMIC_FMAX;
5963    case BRW_AOP_FMIN:
5964       return LSC_OP_ATOMIC_FMIN;
5965    case BRW_AOP_FCMPWR:
5966       return LSC_OP_ATOMIC_FCMPXCHG;
5967    case BRW_AOP_FADD:
5968       return LSC_OP_ATOMIC_FADD;
5969    default:
5970       unreachable("Unsupported float atomic opcode");
5971    }
5972 }
5973 
5974 static enum lsc_data_size
lsc_bits_to_data_size(unsigned bit_size)5975 lsc_bits_to_data_size(unsigned bit_size)
5976 {
5977    switch (bit_size / 8) {
5978    case 1:  return LSC_DATA_SIZE_D8U32;
5979    case 2:  return LSC_DATA_SIZE_D16U32;
5980    case 4:  return LSC_DATA_SIZE_D32;
5981    case 8:  return LSC_DATA_SIZE_D64;
5982    default:
5983       unreachable("Unsupported data size.");
5984    }
5985 }
5986 
5987 static void
lower_lsc_surface_logical_send(const fs_builder & bld,fs_inst * inst)5988 lower_lsc_surface_logical_send(const fs_builder &bld, fs_inst *inst)
5989 {
5990    const intel_device_info *devinfo = bld.shader->devinfo;
5991    assert(devinfo->has_lsc);
5992 
5993    /* Get the logical send arguments. */
5994    const fs_reg addr = inst->src[SURFACE_LOGICAL_SRC_ADDRESS];
5995    const fs_reg src = inst->src[SURFACE_LOGICAL_SRC_DATA];
5996    const fs_reg surface = inst->src[SURFACE_LOGICAL_SRC_SURFACE];
5997    const fs_reg surface_handle = inst->src[SURFACE_LOGICAL_SRC_SURFACE_HANDLE];
5998    const UNUSED fs_reg &dims = inst->src[SURFACE_LOGICAL_SRC_IMM_DIMS];
5999    const fs_reg arg = inst->src[SURFACE_LOGICAL_SRC_IMM_ARG];
6000    const fs_reg allow_sample_mask =
6001       inst->src[SURFACE_LOGICAL_SRC_ALLOW_SAMPLE_MASK];
6002    assert(arg.file == IMM);
6003    assert(allow_sample_mask.file == IMM);
6004 
6005    /* Calculate the total number of components of the payload. */
6006    const unsigned addr_sz = inst->components_read(SURFACE_LOGICAL_SRC_ADDRESS);
6007    const unsigned src_comps = inst->components_read(SURFACE_LOGICAL_SRC_DATA);
6008    const unsigned src_sz = type_sz(src.type);
6009 
6010    const bool has_side_effects = inst->has_side_effects();
6011 
6012    unsigned ex_mlen = 0;
6013    fs_reg payload, payload2;
6014    payload = bld.move_to_vgrf(addr, addr_sz);
6015    if (src.file != BAD_FILE) {
6016       payload2 = bld.move_to_vgrf(src, src_comps);
6017       ex_mlen = (src_comps * src_sz * inst->exec_size) / REG_SIZE;
6018    }
6019 
6020    /* Predicate the instruction on the sample mask if needed */
6021    fs_reg sample_mask = allow_sample_mask.ud ? sample_mask_reg(bld) :
6022                                                fs_reg(brw_imm_d(0xffff));
6023    if (sample_mask.file != BAD_FILE && sample_mask.file != IMM)
6024       emit_predicate_on_sample_mask(bld, inst);
6025 
6026    if (surface.file == IMM && surface.ud == GFX7_BTI_SLM)
6027       inst->sfid = GFX12_SFID_SLM;
6028    else
6029       inst->sfid = GFX12_SFID_UGM;
6030 
6031    /* We must have exactly one of surface and surface_handle */
6032    assert((surface.file == BAD_FILE) != (surface_handle.file == BAD_FILE));
6033 
6034    enum lsc_addr_surface_type surf_type;
6035    if (surface_handle.file != BAD_FILE)
6036       surf_type = LSC_ADDR_SURFTYPE_BSS;
6037    else if (surface.file == IMM && surface.ud == GFX7_BTI_SLM)
6038       surf_type = LSC_ADDR_SURFTYPE_FLAT;
6039    else
6040       surf_type = LSC_ADDR_SURFTYPE_BTI;
6041 
6042    switch (inst->opcode) {
6043    case SHADER_OPCODE_UNTYPED_SURFACE_READ_LOGICAL:
6044       inst->desc = lsc_msg_desc(devinfo, LSC_OP_LOAD_CMASK, inst->exec_size,
6045                                 surf_type, LSC_ADDR_SIZE_A32,
6046                                 1 /* num_coordinates */,
6047                                 LSC_DATA_SIZE_D32, arg.ud /* num_channels */,
6048                                 false /* transpose */,
6049                                 LSC_CACHE_LOAD_L1STATE_L3MOCS,
6050                                 true /* has_dest */);
6051       break;
6052    case SHADER_OPCODE_UNTYPED_SURFACE_WRITE_LOGICAL:
6053       inst->desc = lsc_msg_desc(devinfo, LSC_OP_STORE_CMASK, inst->exec_size,
6054                                 surf_type, LSC_ADDR_SIZE_A32,
6055                                 1 /* num_coordinates */,
6056                                 LSC_DATA_SIZE_D32, arg.ud /* num_channels */,
6057                                 false /* transpose */,
6058                                 LSC_CACHE_STORE_L1STATE_L3MOCS,
6059                                 false /* has_dest */);
6060       break;
6061    case SHADER_OPCODE_UNTYPED_ATOMIC_LOGICAL:
6062    case SHADER_OPCODE_UNTYPED_ATOMIC_FLOAT_LOGICAL: {
6063       /* Bspec: Atomic instruction -> Cache section:
6064        *
6065        *    Atomic messages are always forced to "un-cacheable" in the L1
6066        *    cache.
6067        */
6068       enum lsc_opcode opcode =
6069          inst->opcode == SHADER_OPCODE_UNTYPED_ATOMIC_FLOAT_LOGICAL ?
6070          brw_atomic_op_to_lsc_fatomic_op(arg.ud) :
6071          brw_atomic_op_to_lsc_atomic_op(arg.ud);
6072       inst->desc = lsc_msg_desc(devinfo, opcode, inst->exec_size,
6073                                 surf_type, LSC_ADDR_SIZE_A32,
6074                                 1 /* num_coordinates */,
6075                                 lsc_bits_to_data_size(src_sz * 8),
6076                                 1 /* num_channels */,
6077                                 false /* transpose */,
6078                                 LSC_CACHE_STORE_L1UC_L3WB,
6079                                 !inst->dst.is_null());
6080       break;
6081    }
6082    case SHADER_OPCODE_BYTE_SCATTERED_READ_LOGICAL:
6083       inst->desc = lsc_msg_desc(devinfo, LSC_OP_LOAD, inst->exec_size,
6084                                 surf_type, LSC_ADDR_SIZE_A32,
6085                                 1 /* num_coordinates */,
6086                                 lsc_bits_to_data_size(arg.ud),
6087                                 1 /* num_channels */,
6088                                 false /* transpose */,
6089                                 LSC_CACHE_LOAD_L1STATE_L3MOCS,
6090                                 true /* has_dest */);
6091       break;
6092    case SHADER_OPCODE_BYTE_SCATTERED_WRITE_LOGICAL:
6093       inst->desc = lsc_msg_desc(devinfo, LSC_OP_STORE, inst->exec_size,
6094                                 surf_type, LSC_ADDR_SIZE_A32,
6095                                 1 /* num_coordinates */,
6096                                 lsc_bits_to_data_size(arg.ud),
6097                                 1 /* num_channels */,
6098                                 false /* transpose */,
6099                                 LSC_CACHE_STORE_L1STATE_L3MOCS,
6100                                 false /* has_dest */);
6101       break;
6102    default:
6103       unreachable("Unknown surface logical instruction");
6104    }
6105 
6106    inst->src[0] = brw_imm_ud(0);
6107 
6108    /* Set up extended descriptors */
6109    switch (surf_type) {
6110    case LSC_ADDR_SURFTYPE_FLAT:
6111       inst->src[1] = brw_imm_ud(0);
6112       break;
6113    case LSC_ADDR_SURFTYPE_BSS:
6114       /* We assume that the driver provided the handle in the top 20 bits so
6115        * we can use the surface handle directly as the extended descriptor.
6116        */
6117       inst->src[1] = retype(surface_handle, BRW_REGISTER_TYPE_UD);
6118       break;
6119    case LSC_ADDR_SURFTYPE_BTI:
6120       if (surface.file == IMM) {
6121          inst->src[1] = brw_imm_ud(lsc_bti_ex_desc(devinfo, surface.ud));
6122       } else {
6123          const fs_builder ubld = bld.exec_all().group(1, 0);
6124          fs_reg tmp = ubld.vgrf(BRW_REGISTER_TYPE_UD);
6125          ubld.SHL(tmp, surface, brw_imm_ud(24));
6126          inst->src[1] = component(tmp, 0);
6127       }
6128       break;
6129    default:
6130       unreachable("Unknown surface type");
6131    }
6132 
6133    /* Update the original instruction. */
6134    inst->opcode = SHADER_OPCODE_SEND;
6135    inst->mlen = lsc_msg_desc_src0_len(devinfo, inst->desc);
6136    inst->ex_mlen = ex_mlen;
6137    inst->header_size = 0;
6138    inst->send_has_side_effects = has_side_effects;
6139    inst->send_is_volatile = !has_side_effects;
6140 
6141    /* Finally, the payload */
6142    inst->src[2] = payload;
6143    inst->src[3] = payload2;
6144 
6145    inst->resize_sources(4);
6146 }
6147 
6148 static void
lower_surface_block_logical_send(const fs_builder & bld,fs_inst * inst)6149 lower_surface_block_logical_send(const fs_builder &bld, fs_inst *inst)
6150 {
6151    const intel_device_info *devinfo = bld.shader->devinfo;
6152    assert(devinfo->ver >= 9);
6153 
6154    /* Get the logical send arguments. */
6155    const fs_reg &addr = inst->src[SURFACE_LOGICAL_SRC_ADDRESS];
6156    const fs_reg &src = inst->src[SURFACE_LOGICAL_SRC_DATA];
6157    const fs_reg &surface = inst->src[SURFACE_LOGICAL_SRC_SURFACE];
6158    const fs_reg &surface_handle = inst->src[SURFACE_LOGICAL_SRC_SURFACE_HANDLE];
6159    const fs_reg &arg = inst->src[SURFACE_LOGICAL_SRC_IMM_ARG];
6160    assert(arg.file == IMM);
6161    assert(inst->src[SURFACE_LOGICAL_SRC_IMM_DIMS].file == BAD_FILE);
6162    assert(inst->src[SURFACE_LOGICAL_SRC_ALLOW_SAMPLE_MASK].file == BAD_FILE);
6163 
6164    const bool is_stateless =
6165       surface.file == IMM && (surface.ud == BRW_BTI_STATELESS ||
6166                               surface.ud == GFX8_BTI_STATELESS_NON_COHERENT);
6167 
6168    const bool has_side_effects = inst->has_side_effects();
6169 
6170    const bool align_16B =
6171       inst->opcode != SHADER_OPCODE_UNALIGNED_OWORD_BLOCK_READ_LOGICAL;
6172 
6173    const bool write = inst->opcode == SHADER_OPCODE_OWORD_BLOCK_WRITE_LOGICAL;
6174 
6175    /* The address is stored in the header.  See MH_A32_GO and MH_BTS_GO. */
6176    fs_builder ubld = bld.exec_all().group(8, 0);
6177    fs_reg header = ubld.vgrf(BRW_REGISTER_TYPE_UD);
6178 
6179    if (is_stateless)
6180       ubld.emit(SHADER_OPCODE_SCRATCH_HEADER, header);
6181    else
6182       ubld.MOV(header, brw_imm_d(0));
6183 
6184    /* Address in OWord units when aligned to OWords. */
6185    if (align_16B)
6186       ubld.group(1, 0).SHR(component(header, 2), addr, brw_imm_ud(4));
6187    else
6188       ubld.group(1, 0).MOV(component(header, 2), addr);
6189 
6190    fs_reg data;
6191    unsigned ex_mlen = 0;
6192    if (write) {
6193       const unsigned src_sz = inst->components_read(SURFACE_LOGICAL_SRC_DATA);
6194       data = retype(bld.move_to_vgrf(src, src_sz), BRW_REGISTER_TYPE_UD);
6195       ex_mlen = src_sz * type_sz(src.type) * inst->exec_size / REG_SIZE;
6196    }
6197 
6198    inst->opcode = SHADER_OPCODE_SEND;
6199    inst->mlen = 1;
6200    inst->ex_mlen = ex_mlen;
6201    inst->header_size = 1;
6202    inst->send_has_side_effects = has_side_effects;
6203    inst->send_is_volatile = !has_side_effects;
6204 
6205    inst->sfid = GFX7_SFID_DATAPORT_DATA_CACHE;
6206 
6207    const uint32_t desc = brw_dp_oword_block_rw_desc(devinfo, align_16B,
6208                                                     arg.ud, write);
6209    setup_surface_descriptors(bld, inst, desc, surface, surface_handle);
6210 
6211    inst->src[2] = header;
6212    inst->src[3] = data;
6213 
6214    inst->resize_sources(4);
6215 }
6216 
6217 static fs_reg
emit_a64_oword_block_header(const fs_builder & bld,const fs_reg & addr)6218 emit_a64_oword_block_header(const fs_builder &bld, const fs_reg &addr)
6219 {
6220    const fs_builder ubld = bld.exec_all().group(8, 0);
6221    fs_reg header = ubld.vgrf(BRW_REGISTER_TYPE_UD);
6222    ubld.MOV(header, brw_imm_ud(0));
6223 
6224    /* Use a 2-wide MOV to fill out the address */
6225    assert(type_sz(addr.type) == 8 && addr.stride == 0);
6226    fs_reg addr_vec2 = addr;
6227    addr_vec2.type = BRW_REGISTER_TYPE_UD;
6228    addr_vec2.stride = 1;
6229    ubld.group(2, 0).MOV(header, addr_vec2);
6230 
6231    return header;
6232 }
6233 
6234 static void
lower_lsc_a64_logical_send(const fs_builder & bld,fs_inst * inst)6235 lower_lsc_a64_logical_send(const fs_builder &bld, fs_inst *inst)
6236 {
6237    const intel_device_info *devinfo = bld.shader->devinfo;
6238 
6239    /* Get the logical send arguments. */
6240    const fs_reg &addr = inst->src[0];
6241    const fs_reg &src = inst->src[1];
6242    const unsigned src_sz = type_sz(src.type);
6243 
6244    const unsigned src_comps = inst->components_read(1);
6245    assert(inst->src[2].file == IMM);
6246    const unsigned arg = inst->src[2].ud;
6247    const bool has_side_effects = inst->has_side_effects();
6248 
6249    /* If the surface message has side effects and we're a fragment shader, we
6250     * have to predicate with the sample mask to avoid helper invocations.
6251     */
6252    if (has_side_effects && bld.shader->stage == MESA_SHADER_FRAGMENT)
6253       emit_predicate_on_sample_mask(bld, inst);
6254 
6255    fs_reg payload = retype(bld.move_to_vgrf(addr, 1), BRW_REGISTER_TYPE_UD);
6256    fs_reg payload2 = retype(bld.move_to_vgrf(src, src_comps),
6257                             BRW_REGISTER_TYPE_UD);
6258    unsigned ex_mlen = src_comps * src_sz * inst->exec_size / REG_SIZE;
6259 
6260    switch (inst->opcode) {
6261    case SHADER_OPCODE_A64_UNTYPED_READ_LOGICAL:
6262       inst->desc = lsc_msg_desc(devinfo, LSC_OP_LOAD_CMASK, inst->exec_size,
6263                                 LSC_ADDR_SURFTYPE_FLAT, LSC_ADDR_SIZE_A64,
6264                                 1 /* num_coordinates */,
6265                                 LSC_DATA_SIZE_D32, arg /* num_channels */,
6266                                 false /* transpose */,
6267                                 LSC_CACHE_LOAD_L1STATE_L3MOCS,
6268                                 true /* has_dest */);
6269       break;
6270    case SHADER_OPCODE_A64_UNTYPED_WRITE_LOGICAL:
6271       inst->desc = lsc_msg_desc(devinfo, LSC_OP_STORE_CMASK, inst->exec_size,
6272                                 LSC_ADDR_SURFTYPE_FLAT, LSC_ADDR_SIZE_A64,
6273                                 1 /* num_coordinates */,
6274                                 LSC_DATA_SIZE_D32, arg /* num_channels */,
6275                                 false /* transpose */,
6276                                 LSC_CACHE_STORE_L1STATE_L3MOCS,
6277                                 false /* has_dest */);
6278       break;
6279    case SHADER_OPCODE_A64_BYTE_SCATTERED_READ_LOGICAL:
6280       inst->desc = lsc_msg_desc(devinfo, LSC_OP_LOAD, inst->exec_size,
6281                                 LSC_ADDR_SURFTYPE_FLAT, LSC_ADDR_SIZE_A64,
6282                                 1 /* num_coordinates */,
6283                                 lsc_bits_to_data_size(arg),
6284                                 1 /* num_channels */,
6285                                 false /* transpose */,
6286                                 LSC_CACHE_STORE_L1STATE_L3MOCS,
6287                                 true /* has_dest */);
6288       break;
6289    case SHADER_OPCODE_A64_BYTE_SCATTERED_WRITE_LOGICAL:
6290       inst->desc = lsc_msg_desc(devinfo, LSC_OP_STORE, inst->exec_size,
6291                                 LSC_ADDR_SURFTYPE_FLAT, LSC_ADDR_SIZE_A64,
6292                                 1 /* num_coordinates */,
6293                                 lsc_bits_to_data_size(arg),
6294                                 1 /* num_channels */,
6295                                 false /* transpose */,
6296                                 LSC_CACHE_STORE_L1STATE_L3MOCS,
6297                                 false /* has_dest */);
6298       break;
6299    case SHADER_OPCODE_A64_UNTYPED_ATOMIC_LOGICAL:
6300    case SHADER_OPCODE_A64_UNTYPED_ATOMIC_INT16_LOGICAL:
6301    case SHADER_OPCODE_A64_UNTYPED_ATOMIC_INT64_LOGICAL: {
6302    case SHADER_OPCODE_A64_UNTYPED_ATOMIC_FLOAT16_LOGICAL:
6303    case SHADER_OPCODE_A64_UNTYPED_ATOMIC_FLOAT32_LOGICAL:
6304    case SHADER_OPCODE_A64_UNTYPED_ATOMIC_FLOAT64_LOGICAL:
6305       /* Bspec: Atomic instruction -> Cache section:
6306        *
6307        *    Atomic messages are always forced to "un-cacheable" in the L1
6308        *    cache.
6309        */
6310       enum lsc_opcode opcode =
6311          (inst->opcode == SHADER_OPCODE_A64_UNTYPED_ATOMIC_LOGICAL ||
6312           inst->opcode == SHADER_OPCODE_A64_UNTYPED_ATOMIC_INT16_LOGICAL ||
6313           inst->opcode == SHADER_OPCODE_A64_UNTYPED_ATOMIC_INT64_LOGICAL) ?
6314          brw_atomic_op_to_lsc_atomic_op(arg) :
6315          brw_atomic_op_to_lsc_fatomic_op(arg);
6316       inst->desc = lsc_msg_desc(devinfo, opcode, inst->exec_size,
6317                                 LSC_ADDR_SURFTYPE_FLAT, LSC_ADDR_SIZE_A64,
6318                                 1 /* num_coordinates */,
6319                                 lsc_bits_to_data_size(src_sz * 8),
6320                                 1 /* num_channels */,
6321                                 false /* transpose */,
6322                                 LSC_CACHE_STORE_L1UC_L3WB,
6323                                 !inst->dst.is_null());
6324       break;
6325    }
6326    default:
6327       unreachable("Unknown A64 logical instruction");
6328    }
6329 
6330    /* Update the original instruction. */
6331    inst->opcode = SHADER_OPCODE_SEND;
6332    inst->mlen = lsc_msg_desc_src0_len(devinfo, inst->desc);
6333    inst->ex_mlen = ex_mlen;
6334    inst->header_size = 0;
6335    inst->send_has_side_effects = has_side_effects;
6336    inst->send_is_volatile = !has_side_effects;
6337 
6338    /* Set up SFID and descriptors */
6339    inst->sfid = GFX12_SFID_UGM;
6340    inst->resize_sources(4);
6341    inst->src[0] = brw_imm_ud(0); /* desc */
6342    inst->src[1] = brw_imm_ud(0); /* ex_desc */
6343    inst->src[2] = payload;
6344    inst->src[3] = payload2;
6345 }
6346 
6347 static void
lower_a64_logical_send(const fs_builder & bld,fs_inst * inst)6348 lower_a64_logical_send(const fs_builder &bld, fs_inst *inst)
6349 {
6350    const intel_device_info *devinfo = bld.shader->devinfo;
6351 
6352    const fs_reg &addr = inst->src[0];
6353    const fs_reg &src = inst->src[1];
6354    const unsigned src_comps = inst->components_read(1);
6355    assert(inst->src[2].file == IMM);
6356    const unsigned arg = inst->src[2].ud;
6357    const bool has_side_effects = inst->has_side_effects();
6358 
6359    /* If the surface message has side effects and we're a fragment shader, we
6360     * have to predicate with the sample mask to avoid helper invocations.
6361     */
6362    if (has_side_effects && bld.shader->stage == MESA_SHADER_FRAGMENT)
6363       emit_predicate_on_sample_mask(bld, inst);
6364 
6365    fs_reg payload, payload2;
6366    unsigned mlen, ex_mlen = 0, header_size = 0;
6367    if (inst->opcode == SHADER_OPCODE_A64_OWORD_BLOCK_READ_LOGICAL ||
6368        inst->opcode == SHADER_OPCODE_A64_OWORD_BLOCK_WRITE_LOGICAL ||
6369        inst->opcode == SHADER_OPCODE_A64_UNALIGNED_OWORD_BLOCK_READ_LOGICAL) {
6370       assert(devinfo->ver >= 9);
6371 
6372       /* OWORD messages only take a scalar address in a header */
6373       mlen = 1;
6374       header_size = 1;
6375       payload = emit_a64_oword_block_header(bld, addr);
6376 
6377       if (inst->opcode == SHADER_OPCODE_A64_OWORD_BLOCK_WRITE_LOGICAL) {
6378          ex_mlen = src_comps * type_sz(src.type) * inst->exec_size / REG_SIZE;
6379          payload2 = retype(bld.move_to_vgrf(src, src_comps),
6380                            BRW_REGISTER_TYPE_UD);
6381       }
6382    } else if (devinfo->ver >= 9) {
6383       /* On Skylake and above, we have SENDS */
6384       mlen = 2 * (inst->exec_size / 8);
6385       ex_mlen = src_comps * type_sz(src.type) * inst->exec_size / REG_SIZE;
6386       payload = retype(bld.move_to_vgrf(addr, 1), BRW_REGISTER_TYPE_UD);
6387       payload2 = retype(bld.move_to_vgrf(src, src_comps),
6388                         BRW_REGISTER_TYPE_UD);
6389    } else {
6390       /* Add two because the address is 64-bit */
6391       const unsigned dwords = 2 + src_comps;
6392       mlen = dwords * (inst->exec_size / 8);
6393 
6394       fs_reg sources[5];
6395 
6396       sources[0] = addr;
6397 
6398       for (unsigned i = 0; i < src_comps; i++)
6399          sources[1 + i] = offset(src, bld, i);
6400 
6401       payload = bld.vgrf(BRW_REGISTER_TYPE_UD, dwords);
6402       bld.LOAD_PAYLOAD(payload, sources, 1 + src_comps, 0);
6403    }
6404 
6405    uint32_t desc;
6406    switch (inst->opcode) {
6407    case SHADER_OPCODE_A64_UNTYPED_READ_LOGICAL:
6408       desc = brw_dp_a64_untyped_surface_rw_desc(devinfo, inst->exec_size,
6409                                                 arg,   /* num_channels */
6410                                                 false  /* write */);
6411       break;
6412 
6413    case SHADER_OPCODE_A64_UNTYPED_WRITE_LOGICAL:
6414       desc = brw_dp_a64_untyped_surface_rw_desc(devinfo, inst->exec_size,
6415                                                 arg,   /* num_channels */
6416                                                 true   /* write */);
6417       break;
6418 
6419    case SHADER_OPCODE_A64_OWORD_BLOCK_READ_LOGICAL:
6420       desc = brw_dp_a64_oword_block_rw_desc(devinfo,
6421                                             true,    /* align_16B */
6422                                             arg,     /* num_dwords */
6423                                             false    /* write */);
6424       break;
6425 
6426    case SHADER_OPCODE_A64_UNALIGNED_OWORD_BLOCK_READ_LOGICAL:
6427       desc = brw_dp_a64_oword_block_rw_desc(devinfo,
6428                                             false,   /* align_16B */
6429                                             arg,     /* num_dwords */
6430                                             false    /* write */);
6431       break;
6432 
6433    case SHADER_OPCODE_A64_OWORD_BLOCK_WRITE_LOGICAL:
6434       desc = brw_dp_a64_oword_block_rw_desc(devinfo,
6435                                             true,    /* align_16B */
6436                                             arg,     /* num_dwords */
6437                                             true     /* write */);
6438       break;
6439 
6440    case SHADER_OPCODE_A64_BYTE_SCATTERED_READ_LOGICAL:
6441       desc = brw_dp_a64_byte_scattered_rw_desc(devinfo, inst->exec_size,
6442                                                arg,   /* bit_size */
6443                                                false  /* write */);
6444       break;
6445 
6446    case SHADER_OPCODE_A64_BYTE_SCATTERED_WRITE_LOGICAL:
6447       desc = brw_dp_a64_byte_scattered_rw_desc(devinfo, inst->exec_size,
6448                                                arg,   /* bit_size */
6449                                                true   /* write */);
6450       break;
6451 
6452    case SHADER_OPCODE_A64_UNTYPED_ATOMIC_LOGICAL:
6453       desc = brw_dp_a64_untyped_atomic_desc(devinfo, inst->exec_size, 32,
6454                                             arg,   /* atomic_op */
6455                                             !inst->dst.is_null());
6456       break;
6457 
6458    case SHADER_OPCODE_A64_UNTYPED_ATOMIC_INT16_LOGICAL:
6459       desc = brw_dp_a64_untyped_atomic_desc(devinfo, inst->exec_size, 16,
6460                                             arg,   /* atomic_op */
6461                                             !inst->dst.is_null());
6462       break;
6463 
6464    case SHADER_OPCODE_A64_UNTYPED_ATOMIC_INT64_LOGICAL:
6465       desc = brw_dp_a64_untyped_atomic_desc(devinfo, inst->exec_size, 64,
6466                                             arg,   /* atomic_op */
6467                                             !inst->dst.is_null());
6468       break;
6469 
6470    case SHADER_OPCODE_A64_UNTYPED_ATOMIC_FLOAT16_LOGICAL:
6471       desc = brw_dp_a64_untyped_atomic_float_desc(devinfo, inst->exec_size,
6472                                                   16, /* bit_size */
6473                                                   arg,   /* atomic_op */
6474                                                   !inst->dst.is_null());
6475       break;
6476 
6477    case SHADER_OPCODE_A64_UNTYPED_ATOMIC_FLOAT32_LOGICAL:
6478       desc = brw_dp_a64_untyped_atomic_float_desc(devinfo, inst->exec_size,
6479                                                   32, /* bit_size */
6480                                                   arg,   /* atomic_op */
6481                                                   !inst->dst.is_null());
6482       break;
6483 
6484    default:
6485       unreachable("Unknown A64 logical instruction");
6486    }
6487 
6488    /* Update the original instruction. */
6489    inst->opcode = SHADER_OPCODE_SEND;
6490    inst->mlen = mlen;
6491    inst->ex_mlen = ex_mlen;
6492    inst->header_size = header_size;
6493    inst->send_has_side_effects = has_side_effects;
6494    inst->send_is_volatile = !has_side_effects;
6495 
6496    /* Set up SFID and descriptors */
6497    inst->sfid = HSW_SFID_DATAPORT_DATA_CACHE_1;
6498    inst->desc = desc;
6499    inst->resize_sources(4);
6500    inst->src[0] = brw_imm_ud(0); /* desc */
6501    inst->src[1] = brw_imm_ud(0); /* ex_desc */
6502    inst->src[2] = payload;
6503    inst->src[3] = payload2;
6504 }
6505 
6506 static void
lower_lsc_varying_pull_constant_logical_send(const fs_builder & bld,fs_inst * inst)6507 lower_lsc_varying_pull_constant_logical_send(const fs_builder &bld,
6508                                              fs_inst *inst)
6509 {
6510    const intel_device_info *devinfo = bld.shader->devinfo;
6511    ASSERTED const brw_compiler *compiler = bld.shader->compiler;
6512 
6513    fs_reg index = inst->src[0];
6514 
6515    /* We are switching the instruction from an ALU-like instruction to a
6516     * send-from-grf instruction.  Since sends can't handle strides or
6517     * source modifiers, we have to make a copy of the offset source.
6518     */
6519    fs_reg ubo_offset = bld.move_to_vgrf(inst->src[1], 1);
6520 
6521    assert(inst->src[2].file == BRW_IMMEDIATE_VALUE);
6522    unsigned alignment = inst->src[2].ud;
6523 
6524    inst->opcode = SHADER_OPCODE_SEND;
6525    inst->sfid = GFX12_SFID_UGM;
6526    inst->resize_sources(3);
6527    inst->src[0] = brw_imm_ud(0);
6528 
6529    if (index.file == IMM) {
6530       inst->src[1] = brw_imm_ud(lsc_bti_ex_desc(devinfo, index.ud));
6531    } else {
6532       const fs_builder ubld = bld.exec_all().group(1, 0);
6533       fs_reg tmp = ubld.vgrf(BRW_REGISTER_TYPE_UD);
6534       ubld.SHL(tmp, index, brw_imm_ud(24));
6535       inst->src[1] = component(tmp, 0);
6536    }
6537 
6538    assert(!compiler->indirect_ubos_use_sampler);
6539 
6540    inst->src[2] = ubo_offset; /* payload */
6541    if (alignment >= 4) {
6542       inst->desc = lsc_msg_desc(devinfo, LSC_OP_LOAD_CMASK, inst->exec_size,
6543                                 LSC_ADDR_SURFTYPE_BTI, LSC_ADDR_SIZE_A32,
6544                                 1 /* num_coordinates */,
6545                                 LSC_DATA_SIZE_D32,
6546                                 4 /* num_channels */,
6547                                 false /* transpose */,
6548                                 LSC_CACHE_LOAD_L1STATE_L3MOCS,
6549                                 true /* has_dest */);
6550       inst->mlen = lsc_msg_desc_src0_len(devinfo, inst->desc);
6551    } else {
6552       inst->desc = lsc_msg_desc(devinfo, LSC_OP_LOAD, inst->exec_size,
6553                                 LSC_ADDR_SURFTYPE_BTI, LSC_ADDR_SIZE_A32,
6554                                 1 /* num_coordinates */,
6555                                 LSC_DATA_SIZE_D32,
6556                                 1 /* num_channels */,
6557                                 false /* transpose */,
6558                                 LSC_CACHE_LOAD_L1STATE_L3MOCS,
6559                                 true /* has_dest */);
6560       inst->mlen = lsc_msg_desc_src0_len(devinfo, inst->desc);
6561       /* The byte scattered messages can only read one dword at a time so
6562        * we have to duplicate the message 4 times to read the full vec4.
6563        * Hopefully, dead code will clean up the mess if some of them aren't
6564        * needed.
6565        */
6566       assert(inst->size_written == 16 * inst->exec_size);
6567       inst->size_written /= 4;
6568       for (unsigned c = 1; c < 4; c++) {
6569          /* Emit a copy of the instruction because we're about to modify
6570           * it.  Because this loop starts at 1, we will emit copies for the
6571           * first 3 and the final one will be the modified instruction.
6572           */
6573          bld.emit(*inst);
6574 
6575          /* Offset the source */
6576          inst->src[2] = bld.vgrf(BRW_REGISTER_TYPE_UD);
6577          bld.ADD(inst->src[2], ubo_offset, brw_imm_ud(c * 4));
6578 
6579          /* Offset the destination */
6580          inst->dst = offset(inst->dst, bld, 1);
6581       }
6582    }
6583 }
6584 
6585 static void
lower_varying_pull_constant_logical_send(const fs_builder & bld,fs_inst * inst)6586 lower_varying_pull_constant_logical_send(const fs_builder &bld, fs_inst *inst)
6587 {
6588    const intel_device_info *devinfo = bld.shader->devinfo;
6589    const brw_compiler *compiler = bld.shader->compiler;
6590 
6591    if (devinfo->ver >= 7) {
6592       fs_reg index = inst->src[0];
6593       /* We are switching the instruction from an ALU-like instruction to a
6594        * send-from-grf instruction.  Since sends can't handle strides or
6595        * source modifiers, we have to make a copy of the offset source.
6596        */
6597       fs_reg ubo_offset = bld.vgrf(BRW_REGISTER_TYPE_UD);
6598       bld.MOV(ubo_offset, inst->src[1]);
6599 
6600       assert(inst->src[2].file == BRW_IMMEDIATE_VALUE);
6601       unsigned alignment = inst->src[2].ud;
6602 
6603       inst->opcode = SHADER_OPCODE_SEND;
6604       inst->mlen = inst->exec_size / 8;
6605       inst->resize_sources(3);
6606 
6607       if (index.file == IMM) {
6608          inst->desc = index.ud & 0xff;
6609          inst->src[0] = brw_imm_ud(0);
6610       } else {
6611          inst->desc = 0;
6612          const fs_builder ubld = bld.exec_all().group(1, 0);
6613          fs_reg tmp = ubld.vgrf(BRW_REGISTER_TYPE_UD);
6614          ubld.AND(tmp, index, brw_imm_ud(0xff));
6615          inst->src[0] = component(tmp, 0);
6616       }
6617       inst->src[1] = brw_imm_ud(0); /* ex_desc */
6618       inst->src[2] = ubo_offset; /* payload */
6619 
6620       if (compiler->indirect_ubos_use_sampler) {
6621          const unsigned simd_mode =
6622             inst->exec_size <= 8 ? BRW_SAMPLER_SIMD_MODE_SIMD8 :
6623                                    BRW_SAMPLER_SIMD_MODE_SIMD16;
6624 
6625          inst->sfid = BRW_SFID_SAMPLER;
6626          inst->desc |= brw_sampler_desc(devinfo, 0, 0,
6627                                         GFX5_SAMPLER_MESSAGE_SAMPLE_LD,
6628                                         simd_mode, 0);
6629       } else if (alignment >= 4) {
6630          inst->sfid = (devinfo->verx10 >= 75 ?
6631                        HSW_SFID_DATAPORT_DATA_CACHE_1 :
6632                        GFX7_SFID_DATAPORT_DATA_CACHE);
6633          inst->desc |= brw_dp_untyped_surface_rw_desc(devinfo, inst->exec_size,
6634                                                       4, /* num_channels */
6635                                                       false   /* write */);
6636       } else {
6637          inst->sfid = GFX7_SFID_DATAPORT_DATA_CACHE;
6638          inst->desc |= brw_dp_byte_scattered_rw_desc(devinfo, inst->exec_size,
6639                                                      32,     /* bit_size */
6640                                                      false   /* write */);
6641          /* The byte scattered messages can only read one dword at a time so
6642           * we have to duplicate the message 4 times to read the full vec4.
6643           * Hopefully, dead code will clean up the mess if some of them aren't
6644           * needed.
6645           */
6646          assert(inst->size_written == 16 * inst->exec_size);
6647          inst->size_written /= 4;
6648          for (unsigned c = 1; c < 4; c++) {
6649             /* Emit a copy of the instruction because we're about to modify
6650              * it.  Because this loop starts at 1, we will emit copies for the
6651              * first 3 and the final one will be the modified instruction.
6652              */
6653             bld.emit(*inst);
6654 
6655             /* Offset the source */
6656             inst->src[2] = bld.vgrf(BRW_REGISTER_TYPE_UD);
6657             bld.ADD(inst->src[2], ubo_offset, brw_imm_ud(c * 4));
6658 
6659             /* Offset the destination */
6660             inst->dst = offset(inst->dst, bld, 1);
6661          }
6662       }
6663    } else {
6664       const fs_reg payload(MRF, FIRST_PULL_LOAD_MRF(devinfo->ver),
6665                            BRW_REGISTER_TYPE_UD);
6666 
6667       bld.MOV(byte_offset(payload, REG_SIZE), inst->src[1]);
6668 
6669       inst->opcode = FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_GFX4;
6670       inst->resize_sources(1);
6671       inst->base_mrf = payload.nr;
6672       inst->header_size = 1;
6673       inst->mlen = 1 + inst->exec_size / 8;
6674    }
6675 }
6676 
6677 static void
lower_math_logical_send(const fs_builder & bld,fs_inst * inst)6678 lower_math_logical_send(const fs_builder &bld, fs_inst *inst)
6679 {
6680    assert(bld.shader->devinfo->ver < 6);
6681 
6682    inst->base_mrf = 2;
6683    inst->mlen = inst->sources * inst->exec_size / 8;
6684 
6685    if (inst->sources > 1) {
6686       /* From the Ironlake PRM, Volume 4, Part 1, Section 6.1.13
6687        * "Message Payload":
6688        *
6689        * "Operand0[7].  For the INT DIV functions, this operand is the
6690        *  denominator."
6691        *  ...
6692        * "Operand1[7].  For the INT DIV functions, this operand is the
6693        *  numerator."
6694        */
6695       const bool is_int_div = inst->opcode != SHADER_OPCODE_POW;
6696       const fs_reg src0 = is_int_div ? inst->src[1] : inst->src[0];
6697       const fs_reg src1 = is_int_div ? inst->src[0] : inst->src[1];
6698 
6699       inst->resize_sources(1);
6700       inst->src[0] = src0;
6701 
6702       assert(inst->exec_size == 8);
6703       bld.MOV(fs_reg(MRF, inst->base_mrf + 1, src1.type), src1);
6704    }
6705 }
6706 
6707 static void
lower_btd_logical_send(const fs_builder & bld,fs_inst * inst)6708 lower_btd_logical_send(const fs_builder &bld, fs_inst *inst)
6709 {
6710    const intel_device_info *devinfo = bld.shader->devinfo;
6711    fs_reg global_addr = inst->src[0];
6712    const fs_reg &btd_record = inst->src[1];
6713 
6714    const unsigned mlen = 2;
6715    const fs_builder ubld = bld.exec_all().group(8, 0);
6716    fs_reg header = ubld.vgrf(BRW_REGISTER_TYPE_UD, 2);
6717 
6718    ubld.MOV(header, brw_imm_ud(0));
6719    switch (inst->opcode) {
6720    case SHADER_OPCODE_BTD_SPAWN_LOGICAL:
6721       assert(type_sz(global_addr.type) == 8 && global_addr.stride == 0);
6722       global_addr.type = BRW_REGISTER_TYPE_UD;
6723       global_addr.stride = 1;
6724       ubld.group(2, 0).MOV(header, global_addr);
6725       break;
6726 
6727    case SHADER_OPCODE_BTD_RETIRE_LOGICAL:
6728       /* The bottom bit is the Stack ID release bit */
6729       ubld.group(1, 0).MOV(header, brw_imm_ud(1));
6730       break;
6731 
6732    default:
6733       unreachable("Invalid BTD message");
6734    }
6735 
6736    /* Stack IDs are always in R1 regardless of whether we're coming from a
6737     * bindless shader or a regular compute shader.
6738     */
6739    fs_reg stack_ids =
6740       retype(byte_offset(header, REG_SIZE), BRW_REGISTER_TYPE_UW);
6741    bld.MOV(stack_ids, retype(brw_vec8_grf(1, 0), BRW_REGISTER_TYPE_UW));
6742 
6743    unsigned ex_mlen = 0;
6744    fs_reg payload;
6745    if (inst->opcode == SHADER_OPCODE_BTD_SPAWN_LOGICAL) {
6746       ex_mlen = 2 * (inst->exec_size / 8);
6747       payload = bld.move_to_vgrf(btd_record, 1);
6748    } else {
6749       assert(inst->opcode == SHADER_OPCODE_BTD_RETIRE_LOGICAL);
6750       /* All these messages take a BTD and things complain if we don't provide
6751        * one for RETIRE.  However, it shouldn't ever actually get used so fill
6752        * it with zero.
6753        */
6754       ex_mlen = 2 * (inst->exec_size / 8);
6755       payload = bld.move_to_vgrf(brw_imm_uq(0), 1);
6756    }
6757 
6758    /* Update the original instruction. */
6759    inst->opcode = SHADER_OPCODE_SEND;
6760    inst->mlen = mlen;
6761    inst->ex_mlen = ex_mlen;
6762    inst->header_size = 0; /* HW docs require has_header = false */
6763    inst->send_has_side_effects = true;
6764    inst->send_is_volatile = false;
6765 
6766    /* Set up SFID and descriptors */
6767    inst->sfid = GEN_RT_SFID_BINDLESS_THREAD_DISPATCH;
6768    inst->desc = brw_btd_spawn_desc(devinfo, inst->exec_size,
6769                                    GEN_RT_BTD_MESSAGE_SPAWN);
6770    inst->resize_sources(4);
6771    inst->src[0] = brw_imm_ud(0); /* desc */
6772    inst->src[1] = brw_imm_ud(0); /* ex_desc */
6773    inst->src[2] = header;
6774    inst->src[3] = payload;
6775 }
6776 
6777 static void
lower_trace_ray_logical_send(const fs_builder & bld,fs_inst * inst)6778 lower_trace_ray_logical_send(const fs_builder &bld, fs_inst *inst)
6779 {
6780    const intel_device_info *devinfo = bld.shader->devinfo;
6781    const fs_reg &bvh_level = inst->src[0];
6782    assert(inst->src[1].file == BRW_IMMEDIATE_VALUE);
6783    const uint32_t trace_ray_control = inst->src[1].ud;
6784 
6785    const unsigned mlen = 1;
6786    const fs_builder ubld = bld.exec_all().group(8, 0);
6787    fs_reg header = ubld.vgrf(BRW_REGISTER_TYPE_UD);
6788    ubld.MOV(header, brw_imm_ud(0));
6789    ubld.group(2, 0).MOV(header,
6790       retype(brw_vec2_grf(2, 0), BRW_REGISTER_TYPE_UD));
6791    /* TODO: Bit 128 is ray_query */
6792 
6793    const unsigned ex_mlen = inst->exec_size / 8;
6794    fs_reg payload = bld.vgrf(BRW_REGISTER_TYPE_UD);
6795    const uint32_t trc_bits = SET_BITS(trace_ray_control, 9, 8);
6796    if (bvh_level.file == BRW_IMMEDIATE_VALUE) {
6797       bld.MOV(payload, brw_imm_ud(trc_bits | (bvh_level.ud & 0x7)));
6798    } else {
6799       bld.AND(payload, bvh_level, brw_imm_ud(0x7));
6800       if (trc_bits != 0)
6801          bld.OR(payload, payload, brw_imm_ud(trc_bits));
6802    }
6803    bld.AND(subscript(payload, BRW_REGISTER_TYPE_UW, 1),
6804            retype(brw_vec8_grf(1, 0), BRW_REGISTER_TYPE_UW),
6805            brw_imm_uw(0x7ff));
6806 
6807    /* Update the original instruction. */
6808    inst->opcode = SHADER_OPCODE_SEND;
6809    inst->mlen = mlen;
6810    inst->ex_mlen = ex_mlen;
6811    inst->header_size = 0; /* HW docs require has_header = false */
6812    inst->send_has_side_effects = true;
6813    inst->send_is_volatile = false;
6814 
6815    /* Set up SFID and descriptors */
6816    inst->sfid = GEN_RT_SFID_RAY_TRACE_ACCELERATOR;
6817    inst->desc = brw_rt_trace_ray_desc(devinfo, inst->exec_size);
6818    inst->resize_sources(4);
6819    inst->src[0] = brw_imm_ud(0); /* desc */
6820    inst->src[1] = brw_imm_ud(0); /* ex_desc */
6821    inst->src[2] = header;
6822    inst->src[3] = payload;
6823 }
6824 
6825 bool
lower_logical_sends()6826 fs_visitor::lower_logical_sends()
6827 {
6828    bool progress = false;
6829 
6830    foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
6831       const fs_builder ibld(this, block, inst);
6832 
6833       switch (inst->opcode) {
6834       case FS_OPCODE_FB_WRITE_LOGICAL:
6835          assert(stage == MESA_SHADER_FRAGMENT);
6836          lower_fb_write_logical_send(ibld, inst,
6837                                      brw_wm_prog_data(prog_data),
6838                                      (const brw_wm_prog_key *)key,
6839                                      payload);
6840          break;
6841 
6842       case FS_OPCODE_FB_READ_LOGICAL:
6843          lower_fb_read_logical_send(ibld, inst);
6844          break;
6845 
6846       case SHADER_OPCODE_TEX_LOGICAL:
6847          lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TEX);
6848          break;
6849 
6850       case SHADER_OPCODE_TXD_LOGICAL:
6851          lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXD);
6852          break;
6853 
6854       case SHADER_OPCODE_TXF_LOGICAL:
6855          lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXF);
6856          break;
6857 
6858       case SHADER_OPCODE_TXL_LOGICAL:
6859          lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXL);
6860          break;
6861 
6862       case SHADER_OPCODE_TXS_LOGICAL:
6863          lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXS);
6864          break;
6865 
6866       case SHADER_OPCODE_IMAGE_SIZE_LOGICAL:
6867          lower_sampler_logical_send(ibld, inst,
6868                                     SHADER_OPCODE_IMAGE_SIZE_LOGICAL);
6869          break;
6870 
6871       case FS_OPCODE_TXB_LOGICAL:
6872          lower_sampler_logical_send(ibld, inst, FS_OPCODE_TXB);
6873          break;
6874 
6875       case SHADER_OPCODE_TXF_CMS_LOGICAL:
6876          lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXF_CMS);
6877          break;
6878 
6879       case SHADER_OPCODE_TXF_CMS_W_LOGICAL:
6880          lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXF_CMS_W);
6881          break;
6882 
6883       case SHADER_OPCODE_TXF_UMS_LOGICAL:
6884          lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXF_UMS);
6885          break;
6886 
6887       case SHADER_OPCODE_TXF_MCS_LOGICAL:
6888          lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXF_MCS);
6889          break;
6890 
6891       case SHADER_OPCODE_LOD_LOGICAL:
6892          lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_LOD);
6893          break;
6894 
6895       case SHADER_OPCODE_TG4_LOGICAL:
6896          lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TG4);
6897          break;
6898 
6899       case SHADER_OPCODE_TG4_OFFSET_LOGICAL:
6900          lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TG4_OFFSET);
6901          break;
6902 
6903       case SHADER_OPCODE_SAMPLEINFO_LOGICAL:
6904          lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_SAMPLEINFO);
6905          break;
6906 
6907       case SHADER_OPCODE_UNTYPED_SURFACE_READ_LOGICAL:
6908       case SHADER_OPCODE_UNTYPED_SURFACE_WRITE_LOGICAL:
6909       case SHADER_OPCODE_UNTYPED_ATOMIC_LOGICAL:
6910       case SHADER_OPCODE_UNTYPED_ATOMIC_FLOAT_LOGICAL:
6911       case SHADER_OPCODE_BYTE_SCATTERED_READ_LOGICAL:
6912       case SHADER_OPCODE_BYTE_SCATTERED_WRITE_LOGICAL:
6913          if (devinfo->has_lsc) {
6914             lower_lsc_surface_logical_send(ibld, inst);
6915             break;
6916          }
6917       case SHADER_OPCODE_DWORD_SCATTERED_READ_LOGICAL:
6918       case SHADER_OPCODE_DWORD_SCATTERED_WRITE_LOGICAL:
6919       case SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL:
6920       case SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL:
6921       case SHADER_OPCODE_TYPED_ATOMIC_LOGICAL:
6922          lower_surface_logical_send(ibld, inst);
6923          break;
6924 
6925       case SHADER_OPCODE_OWORD_BLOCK_READ_LOGICAL:
6926       case SHADER_OPCODE_UNALIGNED_OWORD_BLOCK_READ_LOGICAL:
6927       case SHADER_OPCODE_OWORD_BLOCK_WRITE_LOGICAL:
6928          lower_surface_block_logical_send(ibld, inst);
6929          break;
6930 
6931       case SHADER_OPCODE_A64_UNTYPED_WRITE_LOGICAL:
6932       case SHADER_OPCODE_A64_UNTYPED_READ_LOGICAL:
6933       case SHADER_OPCODE_A64_BYTE_SCATTERED_WRITE_LOGICAL:
6934       case SHADER_OPCODE_A64_BYTE_SCATTERED_READ_LOGICAL:
6935       case SHADER_OPCODE_A64_UNTYPED_ATOMIC_LOGICAL:
6936       case SHADER_OPCODE_A64_UNTYPED_ATOMIC_INT16_LOGICAL:
6937       case SHADER_OPCODE_A64_UNTYPED_ATOMIC_INT64_LOGICAL:
6938       case SHADER_OPCODE_A64_UNTYPED_ATOMIC_FLOAT16_LOGICAL:
6939       case SHADER_OPCODE_A64_UNTYPED_ATOMIC_FLOAT32_LOGICAL:
6940       case SHADER_OPCODE_A64_UNTYPED_ATOMIC_FLOAT64_LOGICAL:
6941          if (devinfo->has_lsc) {
6942             lower_lsc_a64_logical_send(ibld, inst);
6943             break;
6944          }
6945       case SHADER_OPCODE_A64_OWORD_BLOCK_READ_LOGICAL:
6946       case SHADER_OPCODE_A64_UNALIGNED_OWORD_BLOCK_READ_LOGICAL:
6947       case SHADER_OPCODE_A64_OWORD_BLOCK_WRITE_LOGICAL:
6948          lower_a64_logical_send(ibld, inst);
6949          break;
6950 
6951       case FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_LOGICAL:
6952          if (devinfo->has_lsc && !compiler->indirect_ubos_use_sampler)
6953             lower_lsc_varying_pull_constant_logical_send(ibld, inst);
6954          else
6955             lower_varying_pull_constant_logical_send(ibld, inst);
6956          break;
6957 
6958       case SHADER_OPCODE_RCP:
6959       case SHADER_OPCODE_RSQ:
6960       case SHADER_OPCODE_SQRT:
6961       case SHADER_OPCODE_EXP2:
6962       case SHADER_OPCODE_LOG2:
6963       case SHADER_OPCODE_SIN:
6964       case SHADER_OPCODE_COS:
6965       case SHADER_OPCODE_POW:
6966       case SHADER_OPCODE_INT_QUOTIENT:
6967       case SHADER_OPCODE_INT_REMAINDER:
6968          /* The math opcodes are overloaded for the send-like and
6969           * expression-like instructions which seems kind of icky.  Gfx6+ has
6970           * a native (but rather quirky) MATH instruction so we don't need to
6971           * do anything here.  On Gfx4-5 we'll have to lower the Gfx6-like
6972           * logical instructions (which we can easily recognize because they
6973           * have mlen = 0) into send-like virtual instructions.
6974           */
6975          if (devinfo->ver < 6 && inst->mlen == 0) {
6976             lower_math_logical_send(ibld, inst);
6977             break;
6978 
6979          } else {
6980             continue;
6981          }
6982 
6983       case SHADER_OPCODE_BTD_SPAWN_LOGICAL:
6984       case SHADER_OPCODE_BTD_RETIRE_LOGICAL:
6985          lower_btd_logical_send(ibld, inst);
6986          break;
6987 
6988       case RT_OPCODE_TRACE_RAY_LOGICAL:
6989          lower_trace_ray_logical_send(ibld, inst);
6990          break;
6991 
6992       default:
6993          continue;
6994       }
6995 
6996       progress = true;
6997    }
6998 
6999    if (progress)
7000       invalidate_analysis(DEPENDENCY_INSTRUCTIONS | DEPENDENCY_VARIABLES);
7001 
7002    return progress;
7003 }
7004 
7005 static bool
is_mixed_float_with_fp32_dst(const fs_inst * inst)7006 is_mixed_float_with_fp32_dst(const fs_inst *inst)
7007 {
7008    /* This opcode sometimes uses :W type on the source even if the operand is
7009     * a :HF, because in gfx7 there is no support for :HF, and thus it uses :W.
7010     */
7011    if (inst->opcode == BRW_OPCODE_F16TO32)
7012       return true;
7013 
7014    if (inst->dst.type != BRW_REGISTER_TYPE_F)
7015       return false;
7016 
7017    for (int i = 0; i < inst->sources; i++) {
7018       if (inst->src[i].type == BRW_REGISTER_TYPE_HF)
7019          return true;
7020    }
7021 
7022    return false;
7023 }
7024 
7025 static bool
is_mixed_float_with_packed_fp16_dst(const fs_inst * inst)7026 is_mixed_float_with_packed_fp16_dst(const fs_inst *inst)
7027 {
7028    /* This opcode sometimes uses :W type on the destination even if the
7029     * destination is a :HF, because in gfx7 there is no support for :HF, and
7030     * thus it uses :W.
7031     */
7032    if (inst->opcode == BRW_OPCODE_F32TO16 &&
7033        inst->dst.stride == 1)
7034       return true;
7035 
7036    if (inst->dst.type != BRW_REGISTER_TYPE_HF ||
7037        inst->dst.stride != 1)
7038       return false;
7039 
7040    for (int i = 0; i < inst->sources; i++) {
7041       if (inst->src[i].type == BRW_REGISTER_TYPE_F)
7042          return true;
7043    }
7044 
7045    return false;
7046 }
7047 
7048 /**
7049  * Get the closest allowed SIMD width for instruction \p inst accounting for
7050  * some common regioning and execution control restrictions that apply to FPU
7051  * instructions.  These restrictions don't necessarily have any relevance to
7052  * instructions not executed by the FPU pipeline like extended math, control
7053  * flow or send message instructions.
7054  *
7055  * For virtual opcodes it's really up to the instruction -- In some cases
7056  * (e.g. where a virtual instruction unrolls into a simple sequence of FPU
7057  * instructions) it may simplify virtual instruction lowering if we can
7058  * enforce FPU-like regioning restrictions already on the virtual instruction,
7059  * in other cases (e.g. virtual send-like instructions) this may be
7060  * excessively restrictive.
7061  */
7062 static unsigned
get_fpu_lowered_simd_width(const struct intel_device_info * devinfo,const fs_inst * inst)7063 get_fpu_lowered_simd_width(const struct intel_device_info *devinfo,
7064                            const fs_inst *inst)
7065 {
7066    /* Maximum execution size representable in the instruction controls. */
7067    unsigned max_width = MIN2(32, inst->exec_size);
7068 
7069    /* According to the PRMs:
7070     *  "A. In Direct Addressing mode, a source cannot span more than 2
7071     *      adjacent GRF registers.
7072     *   B. A destination cannot span more than 2 adjacent GRF registers."
7073     *
7074     * Look for the source or destination with the largest register region
7075     * which is the one that is going to limit the overall execution size of
7076     * the instruction due to this rule.
7077     */
7078    unsigned reg_count = DIV_ROUND_UP(inst->size_written, REG_SIZE);
7079 
7080    for (unsigned i = 0; i < inst->sources; i++)
7081       reg_count = MAX2(reg_count, DIV_ROUND_UP(inst->size_read(i), REG_SIZE));
7082 
7083    /* Calculate the maximum execution size of the instruction based on the
7084     * factor by which it goes over the hardware limit of 2 GRFs.
7085     */
7086    if (reg_count > 2)
7087       max_width = MIN2(max_width, inst->exec_size / DIV_ROUND_UP(reg_count, 2));
7088 
7089    /* According to the IVB PRMs:
7090     *  "When destination spans two registers, the source MUST span two
7091     *   registers. The exception to the above rule:
7092     *
7093     *    - When source is scalar, the source registers are not incremented.
7094     *    - When source is packed integer Word and destination is packed
7095     *      integer DWord, the source register is not incremented but the
7096     *      source sub register is incremented."
7097     *
7098     * The hardware specs from Gfx4 to Gfx7.5 mention similar regioning
7099     * restrictions.  The code below intentionally doesn't check whether the
7100     * destination type is integer because empirically the hardware doesn't
7101     * seem to care what the actual type is as long as it's dword-aligned.
7102     */
7103    if (devinfo->ver < 8) {
7104       for (unsigned i = 0; i < inst->sources; i++) {
7105          /* IVB implements DF scalars as <0;2,1> regions. */
7106          const bool is_scalar_exception = is_uniform(inst->src[i]) &&
7107             (devinfo->is_haswell || type_sz(inst->src[i].type) != 8);
7108          const bool is_packed_word_exception =
7109             type_sz(inst->dst.type) == 4 && inst->dst.stride == 1 &&
7110             type_sz(inst->src[i].type) == 2 && inst->src[i].stride == 1;
7111 
7112          /* We check size_read(i) against size_written instead of REG_SIZE
7113           * because we want to properly handle SIMD32.  In SIMD32, you can end
7114           * up with writes to 4 registers and a source that reads 2 registers
7115           * and we may still need to lower all the way to SIMD8 in that case.
7116           */
7117          if (inst->size_written > REG_SIZE &&
7118              inst->size_read(i) != 0 &&
7119              inst->size_read(i) < inst->size_written &&
7120              !is_scalar_exception && !is_packed_word_exception) {
7121             const unsigned reg_count = DIV_ROUND_UP(inst->size_written, REG_SIZE);
7122             max_width = MIN2(max_width, inst->exec_size / reg_count);
7123          }
7124       }
7125    }
7126 
7127    if (devinfo->ver < 6) {
7128       /* From the G45 PRM, Volume 4 Page 361:
7129        *
7130        *    "Operand Alignment Rule: With the exceptions listed below, a
7131        *     source/destination operand in general should be aligned to even
7132        *     256-bit physical register with a region size equal to two 256-bit
7133        *     physical registers."
7134        *
7135        * Normally we enforce this by allocating virtual registers to the
7136        * even-aligned class.  But we need to handle payload registers.
7137        */
7138       for (unsigned i = 0; i < inst->sources; i++) {
7139          if (inst->src[i].file == FIXED_GRF && (inst->src[i].nr & 1) &&
7140              inst->size_read(i) > REG_SIZE) {
7141             max_width = MIN2(max_width, 8);
7142          }
7143       }
7144    }
7145 
7146    /* From the IVB PRMs:
7147     *  "When an instruction is SIMD32, the low 16 bits of the execution mask
7148     *   are applied for both halves of the SIMD32 instruction. If different
7149     *   execution mask channels are required, split the instruction into two
7150     *   SIMD16 instructions."
7151     *
7152     * There is similar text in the HSW PRMs.  Gfx4-6 don't even implement
7153     * 32-wide control flow support in hardware and will behave similarly.
7154     */
7155    if (devinfo->ver < 8 && !inst->force_writemask_all)
7156       max_width = MIN2(max_width, 16);
7157 
7158    /* From the IVB PRMs (applies to HSW too):
7159     *  "Instructions with condition modifiers must not use SIMD32."
7160     *
7161     * From the BDW PRMs (applies to later hardware too):
7162     *  "Ternary instruction with condition modifiers must not use SIMD32."
7163     */
7164    if (inst->conditional_mod && (devinfo->ver < 8 || inst->is_3src(devinfo)))
7165       max_width = MIN2(max_width, 16);
7166 
7167    /* From the IVB PRMs (applies to other devices that don't have the
7168     * intel_device_info::supports_simd16_3src flag set):
7169     *  "In Align16 access mode, SIMD16 is not allowed for DW operations and
7170     *   SIMD8 is not allowed for DF operations."
7171     */
7172    if (inst->is_3src(devinfo) && !devinfo->supports_simd16_3src)
7173       max_width = MIN2(max_width, inst->exec_size / reg_count);
7174 
7175    /* Pre-Gfx8 EUs are hardwired to use the QtrCtrl+1 (where QtrCtrl is
7176     * the 8-bit quarter of the execution mask signals specified in the
7177     * instruction control fields) for the second compressed half of any
7178     * single-precision instruction (for double-precision instructions
7179     * it's hardwired to use NibCtrl+1, at least on HSW), which means that
7180     * the EU will apply the wrong execution controls for the second
7181     * sequential GRF write if the number of channels per GRF is not exactly
7182     * eight in single-precision mode (or four in double-float mode).
7183     *
7184     * In this situation we calculate the maximum size of the split
7185     * instructions so they only ever write to a single register.
7186     */
7187    if (devinfo->ver < 8 && inst->size_written > REG_SIZE &&
7188        !inst->force_writemask_all) {
7189       const unsigned channels_per_grf = inst->exec_size /
7190          DIV_ROUND_UP(inst->size_written, REG_SIZE);
7191       const unsigned exec_type_size = get_exec_type_size(inst);
7192       assert(exec_type_size);
7193 
7194       /* The hardware shifts exactly 8 channels per compressed half of the
7195        * instruction in single-precision mode and exactly 4 in double-precision.
7196        */
7197       if (channels_per_grf != (exec_type_size == 8 ? 4 : 8))
7198          max_width = MIN2(max_width, channels_per_grf);
7199 
7200       /* Lower all non-force_writemask_all DF instructions to SIMD4 on IVB/BYT
7201        * because HW applies the same channel enable signals to both halves of
7202        * the compressed instruction which will be just wrong under
7203        * non-uniform control flow.
7204        */
7205       if (devinfo->verx10 == 70 &&
7206           (exec_type_size == 8 || type_sz(inst->dst.type) == 8))
7207          max_width = MIN2(max_width, 4);
7208    }
7209 
7210    /* From the SKL PRM, Special Restrictions for Handling Mixed Mode
7211     * Float Operations:
7212     *
7213     *    "No SIMD16 in mixed mode when destination is f32. Instruction
7214     *     execution size must be no more than 8."
7215     *
7216     * FIXME: the simulator doesn't seem to complain if we don't do this and
7217     * empirical testing with existing CTS tests show that they pass just fine
7218     * without implementing this, however, since our interpretation of the PRM
7219     * is that conversion MOVs between HF and F are still mixed-float
7220     * instructions (and therefore subject to this restriction) we decided to
7221     * split them to be safe. Might be useful to do additional investigation to
7222     * lift the restriction if we can ensure that it is safe though, since these
7223     * conversions are common when half-float types are involved since many
7224     * instructions do not support HF types and conversions from/to F are
7225     * required.
7226     */
7227    if (is_mixed_float_with_fp32_dst(inst))
7228       max_width = MIN2(max_width, 8);
7229 
7230    /* From the SKL PRM, Special Restrictions for Handling Mixed Mode
7231     * Float Operations:
7232     *
7233     *    "No SIMD16 in mixed mode when destination is packed f16 for both
7234     *     Align1 and Align16."
7235     */
7236    if (is_mixed_float_with_packed_fp16_dst(inst))
7237       max_width = MIN2(max_width, 8);
7238 
7239    /* Only power-of-two execution sizes are representable in the instruction
7240     * control fields.
7241     */
7242    return 1 << util_logbase2(max_width);
7243 }
7244 
7245 /**
7246  * Get the maximum allowed SIMD width for instruction \p inst accounting for
7247  * various payload size restrictions that apply to sampler message
7248  * instructions.
7249  *
7250  * This is only intended to provide a maximum theoretical bound for the
7251  * execution size of the message based on the number of argument components
7252  * alone, which in most cases will determine whether the SIMD8 or SIMD16
7253  * variant of the message can be used, though some messages may have
7254  * additional restrictions not accounted for here (e.g. pre-ILK hardware uses
7255  * the message length to determine the exact SIMD width and argument count,
7256  * which makes a number of sampler message combinations impossible to
7257  * represent).
7258  */
7259 static unsigned
get_sampler_lowered_simd_width(const struct intel_device_info * devinfo,const fs_inst * inst)7260 get_sampler_lowered_simd_width(const struct intel_device_info *devinfo,
7261                                const fs_inst *inst)
7262 {
7263    /* If we have a min_lod parameter on anything other than a simple sample
7264     * message, it will push it over 5 arguments and we have to fall back to
7265     * SIMD8.
7266     */
7267    if (inst->opcode != SHADER_OPCODE_TEX &&
7268        inst->components_read(TEX_LOGICAL_SRC_MIN_LOD))
7269       return 8;
7270 
7271    /* Calculate the number of coordinate components that have to be present
7272     * assuming that additional arguments follow the texel coordinates in the
7273     * message payload.  On IVB+ there is no need for padding, on ILK-SNB we
7274     * need to pad to four or three components depending on the message,
7275     * pre-ILK we need to pad to at most three components.
7276     */
7277    const unsigned req_coord_components =
7278       (devinfo->ver >= 7 ||
7279        !inst->components_read(TEX_LOGICAL_SRC_COORDINATE)) ? 0 :
7280       (devinfo->ver >= 5 && inst->opcode != SHADER_OPCODE_TXF_LOGICAL &&
7281                             inst->opcode != SHADER_OPCODE_TXF_CMS_LOGICAL) ? 4 :
7282       3;
7283 
7284    /* On Gfx9+ the LOD argument is for free if we're able to use the LZ
7285     * variant of the TXL or TXF message.
7286     */
7287    const bool implicit_lod = devinfo->ver >= 9 &&
7288                              (inst->opcode == SHADER_OPCODE_TXL ||
7289                               inst->opcode == SHADER_OPCODE_TXF) &&
7290                              inst->src[TEX_LOGICAL_SRC_LOD].is_zero();
7291 
7292    /* Calculate the total number of argument components that need to be passed
7293     * to the sampler unit.
7294     */
7295    const unsigned num_payload_components =
7296       MAX2(inst->components_read(TEX_LOGICAL_SRC_COORDINATE),
7297            req_coord_components) +
7298       inst->components_read(TEX_LOGICAL_SRC_SHADOW_C) +
7299       (implicit_lod ? 0 : inst->components_read(TEX_LOGICAL_SRC_LOD)) +
7300       inst->components_read(TEX_LOGICAL_SRC_LOD2) +
7301       inst->components_read(TEX_LOGICAL_SRC_SAMPLE_INDEX) +
7302       (inst->opcode == SHADER_OPCODE_TG4_OFFSET_LOGICAL ?
7303        inst->components_read(TEX_LOGICAL_SRC_TG4_OFFSET) : 0) +
7304       inst->components_read(TEX_LOGICAL_SRC_MCS);
7305 
7306    /* SIMD16 messages with more than five arguments exceed the maximum message
7307     * size supported by the sampler, regardless of whether a header is
7308     * provided or not.
7309     */
7310    return MIN2(inst->exec_size,
7311                num_payload_components > MAX_SAMPLER_MESSAGE_SIZE / 2 ? 8 : 16);
7312 }
7313 
7314 /**
7315  * Get the closest native SIMD width supported by the hardware for instruction
7316  * \p inst.  The instruction will be left untouched by
7317  * fs_visitor::lower_simd_width() if the returned value is equal to the
7318  * original execution size.
7319  */
7320 static unsigned
get_lowered_simd_width(const struct intel_device_info * devinfo,const fs_inst * inst)7321 get_lowered_simd_width(const struct intel_device_info *devinfo,
7322                        const fs_inst *inst)
7323 {
7324    switch (inst->opcode) {
7325    case BRW_OPCODE_MOV:
7326    case BRW_OPCODE_SEL:
7327    case BRW_OPCODE_NOT:
7328    case BRW_OPCODE_AND:
7329    case BRW_OPCODE_OR:
7330    case BRW_OPCODE_XOR:
7331    case BRW_OPCODE_SHR:
7332    case BRW_OPCODE_SHL:
7333    case BRW_OPCODE_ASR:
7334    case BRW_OPCODE_ROR:
7335    case BRW_OPCODE_ROL:
7336    case BRW_OPCODE_CMPN:
7337    case BRW_OPCODE_CSEL:
7338    case BRW_OPCODE_F32TO16:
7339    case BRW_OPCODE_F16TO32:
7340    case BRW_OPCODE_BFREV:
7341    case BRW_OPCODE_BFE:
7342    case BRW_OPCODE_ADD:
7343    case BRW_OPCODE_MUL:
7344    case BRW_OPCODE_AVG:
7345    case BRW_OPCODE_FRC:
7346    case BRW_OPCODE_RNDU:
7347    case BRW_OPCODE_RNDD:
7348    case BRW_OPCODE_RNDE:
7349    case BRW_OPCODE_RNDZ:
7350    case BRW_OPCODE_LZD:
7351    case BRW_OPCODE_FBH:
7352    case BRW_OPCODE_FBL:
7353    case BRW_OPCODE_CBIT:
7354    case BRW_OPCODE_SAD2:
7355    case BRW_OPCODE_MAD:
7356    case BRW_OPCODE_LRP:
7357    case BRW_OPCODE_ADD3:
7358    case FS_OPCODE_PACK:
7359    case SHADER_OPCODE_SEL_EXEC:
7360    case SHADER_OPCODE_CLUSTER_BROADCAST:
7361    case SHADER_OPCODE_MOV_RELOC_IMM:
7362       return get_fpu_lowered_simd_width(devinfo, inst);
7363 
7364    case BRW_OPCODE_CMP: {
7365       /* The Ivybridge/BayTrail WaCMPInstFlagDepClearedEarly workaround says that
7366        * when the destination is a GRF the dependency-clear bit on the flag
7367        * register is cleared early.
7368        *
7369        * Suggested workarounds are to disable coissuing CMP instructions
7370        * or to split CMP(16) instructions into two CMP(8) instructions.
7371        *
7372        * We choose to split into CMP(8) instructions since disabling
7373        * coissuing would affect CMP instructions not otherwise affected by
7374        * the errata.
7375        */
7376       const unsigned max_width = (devinfo->verx10 == 70 &&
7377                                   !inst->dst.is_null() ? 8 : ~0);
7378       return MIN2(max_width, get_fpu_lowered_simd_width(devinfo, inst));
7379    }
7380    case BRW_OPCODE_BFI1:
7381    case BRW_OPCODE_BFI2:
7382       /* The Haswell WaForceSIMD8ForBFIInstruction workaround says that we
7383        * should
7384        *  "Force BFI instructions to be executed always in SIMD8."
7385        */
7386       return MIN2(devinfo->is_haswell ? 8 : ~0u,
7387                   get_fpu_lowered_simd_width(devinfo, inst));
7388 
7389    case BRW_OPCODE_IF:
7390       assert(inst->src[0].file == BAD_FILE || inst->exec_size <= 16);
7391       return inst->exec_size;
7392 
7393    case SHADER_OPCODE_RCP:
7394    case SHADER_OPCODE_RSQ:
7395    case SHADER_OPCODE_SQRT:
7396    case SHADER_OPCODE_EXP2:
7397    case SHADER_OPCODE_LOG2:
7398    case SHADER_OPCODE_SIN:
7399    case SHADER_OPCODE_COS: {
7400       /* Unary extended math instructions are limited to SIMD8 on Gfx4 and
7401        * Gfx6. Extended Math Function is limited to SIMD8 with half-float.
7402        */
7403       if (devinfo->ver == 6 || (devinfo->ver == 4 && !devinfo->is_g4x))
7404          return MIN2(8, inst->exec_size);
7405       if (inst->dst.type == BRW_REGISTER_TYPE_HF)
7406          return MIN2(8, inst->exec_size);
7407       return MIN2(16, inst->exec_size);
7408    }
7409 
7410    case SHADER_OPCODE_POW: {
7411       /* SIMD16 is only allowed on Gfx7+. Extended Math Function is limited
7412        * to SIMD8 with half-float
7413        */
7414       if (devinfo->ver < 7)
7415          return MIN2(8, inst->exec_size);
7416       if (inst->dst.type == BRW_REGISTER_TYPE_HF)
7417          return MIN2(8, inst->exec_size);
7418       return MIN2(16, inst->exec_size);
7419    }
7420 
7421    case SHADER_OPCODE_USUB_SAT:
7422    case SHADER_OPCODE_ISUB_SAT:
7423       return get_fpu_lowered_simd_width(devinfo, inst);
7424 
7425    case SHADER_OPCODE_INT_QUOTIENT:
7426    case SHADER_OPCODE_INT_REMAINDER:
7427       /* Integer division is limited to SIMD8 on all generations. */
7428       return MIN2(8, inst->exec_size);
7429 
7430    case FS_OPCODE_LINTERP:
7431    case SHADER_OPCODE_GET_BUFFER_SIZE:
7432    case FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD:
7433    case FS_OPCODE_PACK_HALF_2x16_SPLIT:
7434    case FS_OPCODE_INTERPOLATE_AT_SAMPLE:
7435    case FS_OPCODE_INTERPOLATE_AT_SHARED_OFFSET:
7436    case FS_OPCODE_INTERPOLATE_AT_PER_SLOT_OFFSET:
7437       return MIN2(16, inst->exec_size);
7438 
7439    case FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_LOGICAL:
7440       /* Pre-ILK hardware doesn't have a SIMD8 variant of the texel fetch
7441        * message used to implement varying pull constant loads, so expand it
7442        * to SIMD16.  An alternative with longer message payload length but
7443        * shorter return payload would be to use the SIMD8 sampler message that
7444        * takes (header, u, v, r) as parameters instead of (header, u).
7445        */
7446       return (devinfo->ver == 4 ? 16 : MIN2(16, inst->exec_size));
7447 
7448    case FS_OPCODE_DDX_COARSE:
7449    case FS_OPCODE_DDX_FINE:
7450    case FS_OPCODE_DDY_COARSE:
7451    case FS_OPCODE_DDY_FINE:
7452       /* The implementation of this virtual opcode may require emitting
7453        * compressed Align16 instructions, which are severely limited on some
7454        * generations.
7455        *
7456        * From the Ivy Bridge PRM, volume 4 part 3, section 3.3.9 (Register
7457        * Region Restrictions):
7458        *
7459        *  "In Align16 access mode, SIMD16 is not allowed for DW operations
7460        *   and SIMD8 is not allowed for DF operations."
7461        *
7462        * In this context, "DW operations" means "operations acting on 32-bit
7463        * values", so it includes operations on floats.
7464        *
7465        * Gfx4 has a similar restriction.  From the i965 PRM, section 11.5.3
7466        * (Instruction Compression -> Rules and Restrictions):
7467        *
7468        *  "A compressed instruction must be in Align1 access mode. Align16
7469        *   mode instructions cannot be compressed."
7470        *
7471        * Similar text exists in the g45 PRM.
7472        *
7473        * Empirically, compressed align16 instructions using odd register
7474        * numbers don't appear to work on Sandybridge either.
7475        */
7476       return (devinfo->ver == 4 || devinfo->ver == 6 ||
7477               (devinfo->verx10 == 70) ?
7478               MIN2(8, inst->exec_size) : MIN2(16, inst->exec_size));
7479 
7480    case SHADER_OPCODE_MULH:
7481       /* MULH is lowered to the MUL/MACH sequence using the accumulator, which
7482        * is 8-wide on Gfx7+.
7483        */
7484       return (devinfo->ver >= 7 ? 8 :
7485               get_fpu_lowered_simd_width(devinfo, inst));
7486 
7487    case FS_OPCODE_FB_WRITE_LOGICAL:
7488       /* Gfx6 doesn't support SIMD16 depth writes but we cannot handle them
7489        * here.
7490        */
7491       assert(devinfo->ver != 6 ||
7492              inst->src[FB_WRITE_LOGICAL_SRC_SRC_DEPTH].file == BAD_FILE ||
7493              inst->exec_size == 8);
7494       /* Dual-source FB writes are unsupported in SIMD16 mode. */
7495       return (inst->src[FB_WRITE_LOGICAL_SRC_COLOR1].file != BAD_FILE ?
7496               8 : MIN2(16, inst->exec_size));
7497 
7498    case FS_OPCODE_FB_READ_LOGICAL:
7499       return MIN2(16, inst->exec_size);
7500 
7501    case SHADER_OPCODE_TEX_LOGICAL:
7502    case SHADER_OPCODE_TXF_CMS_LOGICAL:
7503    case SHADER_OPCODE_TXF_UMS_LOGICAL:
7504    case SHADER_OPCODE_TXF_MCS_LOGICAL:
7505    case SHADER_OPCODE_LOD_LOGICAL:
7506    case SHADER_OPCODE_TG4_LOGICAL:
7507    case SHADER_OPCODE_SAMPLEINFO_LOGICAL:
7508    case SHADER_OPCODE_TXF_CMS_W_LOGICAL:
7509    case SHADER_OPCODE_TG4_OFFSET_LOGICAL:
7510       return get_sampler_lowered_simd_width(devinfo, inst);
7511 
7512    case SHADER_OPCODE_TXD_LOGICAL:
7513       /* TXD is unsupported in SIMD16 mode. */
7514       return 8;
7515 
7516    case SHADER_OPCODE_TXL_LOGICAL:
7517    case FS_OPCODE_TXB_LOGICAL:
7518       /* Only one execution size is representable pre-ILK depending on whether
7519        * the shadow reference argument is present.
7520        */
7521       if (devinfo->ver == 4)
7522          return inst->src[TEX_LOGICAL_SRC_SHADOW_C].file == BAD_FILE ? 16 : 8;
7523       else
7524          return get_sampler_lowered_simd_width(devinfo, inst);
7525 
7526    case SHADER_OPCODE_TXF_LOGICAL:
7527    case SHADER_OPCODE_TXS_LOGICAL:
7528       /* Gfx4 doesn't have SIMD8 variants for the RESINFO and LD-with-LOD
7529        * messages.  Use SIMD16 instead.
7530        */
7531       if (devinfo->ver == 4)
7532          return 16;
7533       else
7534          return get_sampler_lowered_simd_width(devinfo, inst);
7535 
7536    case SHADER_OPCODE_TYPED_ATOMIC_LOGICAL:
7537    case SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL:
7538    case SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL:
7539       return 8;
7540 
7541    case SHADER_OPCODE_UNTYPED_ATOMIC_LOGICAL:
7542    case SHADER_OPCODE_UNTYPED_ATOMIC_FLOAT_LOGICAL:
7543    case SHADER_OPCODE_UNTYPED_SURFACE_READ_LOGICAL:
7544    case SHADER_OPCODE_UNTYPED_SURFACE_WRITE_LOGICAL:
7545    case SHADER_OPCODE_BYTE_SCATTERED_WRITE_LOGICAL:
7546    case SHADER_OPCODE_BYTE_SCATTERED_READ_LOGICAL:
7547    case SHADER_OPCODE_DWORD_SCATTERED_WRITE_LOGICAL:
7548    case SHADER_OPCODE_DWORD_SCATTERED_READ_LOGICAL:
7549       return MIN2(16, inst->exec_size);
7550 
7551    case SHADER_OPCODE_A64_UNTYPED_WRITE_LOGICAL:
7552    case SHADER_OPCODE_A64_UNTYPED_READ_LOGICAL:
7553    case SHADER_OPCODE_A64_BYTE_SCATTERED_WRITE_LOGICAL:
7554    case SHADER_OPCODE_A64_BYTE_SCATTERED_READ_LOGICAL:
7555       return devinfo->ver <= 8 ? 8 : MIN2(16, inst->exec_size);
7556 
7557    case SHADER_OPCODE_A64_OWORD_BLOCK_READ_LOGICAL:
7558    case SHADER_OPCODE_A64_UNALIGNED_OWORD_BLOCK_READ_LOGICAL:
7559    case SHADER_OPCODE_A64_OWORD_BLOCK_WRITE_LOGICAL:
7560       assert(inst->exec_size <= 16);
7561       return inst->exec_size;
7562 
7563    case SHADER_OPCODE_A64_UNTYPED_ATOMIC_LOGICAL:
7564    case SHADER_OPCODE_A64_UNTYPED_ATOMIC_INT16_LOGICAL:
7565    case SHADER_OPCODE_A64_UNTYPED_ATOMIC_INT64_LOGICAL:
7566    case SHADER_OPCODE_A64_UNTYPED_ATOMIC_FLOAT16_LOGICAL:
7567    case SHADER_OPCODE_A64_UNTYPED_ATOMIC_FLOAT32_LOGICAL:
7568    case SHADER_OPCODE_A64_UNTYPED_ATOMIC_FLOAT64_LOGICAL:
7569       return 8;
7570 
7571    case SHADER_OPCODE_URB_READ_SIMD8:
7572    case SHADER_OPCODE_URB_READ_SIMD8_PER_SLOT:
7573    case SHADER_OPCODE_URB_WRITE_SIMD8:
7574    case SHADER_OPCODE_URB_WRITE_SIMD8_PER_SLOT:
7575    case SHADER_OPCODE_URB_WRITE_SIMD8_MASKED:
7576    case SHADER_OPCODE_URB_WRITE_SIMD8_MASKED_PER_SLOT:
7577       return MIN2(8, inst->exec_size);
7578 
7579    case SHADER_OPCODE_QUAD_SWIZZLE: {
7580       const unsigned swiz = inst->src[1].ud;
7581       return (is_uniform(inst->src[0]) ?
7582                  get_fpu_lowered_simd_width(devinfo, inst) :
7583               devinfo->ver < 11 && type_sz(inst->src[0].type) == 4 ? 8 :
7584               swiz == BRW_SWIZZLE_XYXY || swiz == BRW_SWIZZLE_ZWZW ? 4 :
7585               get_fpu_lowered_simd_width(devinfo, inst));
7586    }
7587    case SHADER_OPCODE_MOV_INDIRECT: {
7588       /* From IVB and HSW PRMs:
7589        *
7590        * "2.When the destination requires two registers and the sources are
7591        *  indirect, the sources must use 1x1 regioning mode.
7592        *
7593        * In case of DF instructions in HSW/IVB, the exec_size is limited by
7594        * the EU decompression logic not handling VxH indirect addressing
7595        * correctly.
7596        */
7597       const unsigned max_size = (devinfo->ver >= 8 ? 2 : 1) * REG_SIZE;
7598       /* Prior to Broadwell, we only have 8 address subregisters. */
7599       return MIN3(devinfo->ver >= 8 ? 16 : 8,
7600                   max_size / (inst->dst.stride * type_sz(inst->dst.type)),
7601                   inst->exec_size);
7602    }
7603 
7604    case SHADER_OPCODE_LOAD_PAYLOAD: {
7605       const unsigned reg_count =
7606          DIV_ROUND_UP(inst->dst.component_size(inst->exec_size), REG_SIZE);
7607 
7608       if (reg_count > 2) {
7609          /* Only LOAD_PAYLOAD instructions with per-channel destination region
7610           * can be easily lowered (which excludes headers and heterogeneous
7611           * types).
7612           */
7613          assert(!inst->header_size);
7614          for (unsigned i = 0; i < inst->sources; i++)
7615             assert(type_sz(inst->dst.type) == type_sz(inst->src[i].type) ||
7616                    inst->src[i].file == BAD_FILE);
7617 
7618          return inst->exec_size / DIV_ROUND_UP(reg_count, 2);
7619       } else {
7620          return inst->exec_size;
7621       }
7622    }
7623    default:
7624       return inst->exec_size;
7625    }
7626 }
7627 
7628 /**
7629  * Return true if splitting out the group of channels of instruction \p inst
7630  * given by lbld.group() requires allocating a temporary for the i-th source
7631  * of the lowered instruction.
7632  */
7633 static inline bool
needs_src_copy(const fs_builder & lbld,const fs_inst * inst,unsigned i)7634 needs_src_copy(const fs_builder &lbld, const fs_inst *inst, unsigned i)
7635 {
7636    return !(is_periodic(inst->src[i], lbld.dispatch_width()) ||
7637             (inst->components_read(i) == 1 &&
7638              lbld.dispatch_width() <= inst->exec_size)) ||
7639           (inst->flags_written(lbld.shader->devinfo) &
7640            flag_mask(inst->src[i], type_sz(inst->src[i].type)));
7641 }
7642 
7643 /**
7644  * Extract the data that would be consumed by the channel group given by
7645  * lbld.group() from the i-th source region of instruction \p inst and return
7646  * it as result in packed form.
7647  */
7648 static fs_reg
emit_unzip(const fs_builder & lbld,fs_inst * inst,unsigned i)7649 emit_unzip(const fs_builder &lbld, fs_inst *inst, unsigned i)
7650 {
7651    assert(lbld.group() >= inst->group);
7652 
7653    /* Specified channel group from the source region. */
7654    const fs_reg src = horiz_offset(inst->src[i], lbld.group() - inst->group);
7655 
7656    if (needs_src_copy(lbld, inst, i)) {
7657       /* Builder of the right width to perform the copy avoiding uninitialized
7658        * data if the lowered execution size is greater than the original
7659        * execution size of the instruction.
7660        */
7661       const fs_builder cbld = lbld.group(MIN2(lbld.dispatch_width(),
7662                                               inst->exec_size), 0);
7663       const fs_reg tmp = lbld.vgrf(inst->src[i].type, inst->components_read(i));
7664 
7665       for (unsigned k = 0; k < inst->components_read(i); ++k)
7666          cbld.MOV(offset(tmp, lbld, k), offset(src, inst->exec_size, k));
7667 
7668       return tmp;
7669 
7670    } else if (is_periodic(inst->src[i], lbld.dispatch_width())) {
7671       /* The source is invariant for all dispatch_width-wide groups of the
7672        * original region.
7673        */
7674       return inst->src[i];
7675 
7676    } else {
7677       /* We can just point the lowered instruction at the right channel group
7678        * from the original region.
7679        */
7680       return src;
7681    }
7682 }
7683 
7684 /**
7685  * Return true if splitting out the group of channels of instruction \p inst
7686  * given by lbld.group() requires allocating a temporary for the destination
7687  * of the lowered instruction and copying the data back to the original
7688  * destination region.
7689  */
7690 static inline bool
needs_dst_copy(const fs_builder & lbld,const fs_inst * inst)7691 needs_dst_copy(const fs_builder &lbld, const fs_inst *inst)
7692 {
7693    /* If the instruction writes more than one component we'll have to shuffle
7694     * the results of multiple lowered instructions in order to make sure that
7695     * they end up arranged correctly in the original destination region.
7696     */
7697    if (inst->size_written > inst->dst.component_size(inst->exec_size))
7698       return true;
7699 
7700    /* If the lowered execution size is larger than the original the result of
7701     * the instruction won't fit in the original destination, so we'll have to
7702     * allocate a temporary in any case.
7703     */
7704    if (lbld.dispatch_width() > inst->exec_size)
7705       return true;
7706 
7707    for (unsigned i = 0; i < inst->sources; i++) {
7708       /* If we already made a copy of the source for other reasons there won't
7709        * be any overlap with the destination.
7710        */
7711       if (needs_src_copy(lbld, inst, i))
7712          continue;
7713 
7714       /* In order to keep the logic simple we emit a copy whenever the
7715        * destination region doesn't exactly match an overlapping source, which
7716        * may point at the source and destination not being aligned group by
7717        * group which could cause one of the lowered instructions to overwrite
7718        * the data read from the same source by other lowered instructions.
7719        */
7720       if (regions_overlap(inst->dst, inst->size_written,
7721                           inst->src[i], inst->size_read(i)) &&
7722           !inst->dst.equals(inst->src[i]))
7723         return true;
7724    }
7725 
7726    return false;
7727 }
7728 
7729 /**
7730  * Insert data from a packed temporary into the channel group given by
7731  * lbld.group() of the destination region of instruction \p inst and return
7732  * the temporary as result.  Any copy instructions that are required for
7733  * unzipping the previous value (in the case of partial writes) will be
7734  * inserted using \p lbld_before and any copy instructions required for
7735  * zipping up the destination of \p inst will be inserted using \p lbld_after.
7736  */
7737 static fs_reg
emit_zip(const fs_builder & lbld_before,const fs_builder & lbld_after,fs_inst * inst)7738 emit_zip(const fs_builder &lbld_before, const fs_builder &lbld_after,
7739          fs_inst *inst)
7740 {
7741    assert(lbld_before.dispatch_width() == lbld_after.dispatch_width());
7742    assert(lbld_before.group() == lbld_after.group());
7743    assert(lbld_after.group() >= inst->group);
7744 
7745    /* Specified channel group from the destination region. */
7746    const fs_reg dst = horiz_offset(inst->dst, lbld_after.group() - inst->group);
7747    const unsigned dst_size = inst->size_written /
7748       inst->dst.component_size(inst->exec_size);
7749 
7750    if (needs_dst_copy(lbld_after, inst)) {
7751       const fs_reg tmp = lbld_after.vgrf(inst->dst.type, dst_size);
7752 
7753       if (inst->predicate) {
7754          /* Handle predication by copying the original contents of
7755           * the destination into the temporary before emitting the
7756           * lowered instruction.
7757           */
7758          const fs_builder gbld_before =
7759             lbld_before.group(MIN2(lbld_before.dispatch_width(),
7760                                    inst->exec_size), 0);
7761          for (unsigned k = 0; k < dst_size; ++k) {
7762             gbld_before.MOV(offset(tmp, lbld_before, k),
7763                             offset(dst, inst->exec_size, k));
7764          }
7765       }
7766 
7767       const fs_builder gbld_after =
7768          lbld_after.group(MIN2(lbld_after.dispatch_width(),
7769                                inst->exec_size), 0);
7770       for (unsigned k = 0; k < dst_size; ++k) {
7771          /* Use a builder of the right width to perform the copy avoiding
7772           * uninitialized data if the lowered execution size is greater than
7773           * the original execution size of the instruction.
7774           */
7775          gbld_after.MOV(offset(dst, inst->exec_size, k),
7776                         offset(tmp, lbld_after, k));
7777       }
7778 
7779       return tmp;
7780 
7781    } else {
7782       /* No need to allocate a temporary for the lowered instruction, just
7783        * take the right group of channels from the original region.
7784        */
7785       return dst;
7786    }
7787 }
7788 
7789 bool
lower_simd_width()7790 fs_visitor::lower_simd_width()
7791 {
7792    bool progress = false;
7793 
7794    foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
7795       const unsigned lower_width = get_lowered_simd_width(devinfo, inst);
7796 
7797       if (lower_width != inst->exec_size) {
7798          /* Builder matching the original instruction.  We may also need to
7799           * emit an instruction of width larger than the original, set the
7800           * execution size of the builder to the highest of both for now so
7801           * we're sure that both cases can be handled.
7802           */
7803          const unsigned max_width = MAX2(inst->exec_size, lower_width);
7804          const fs_builder ibld = bld.at(block, inst)
7805                                     .exec_all(inst->force_writemask_all)
7806                                     .group(max_width, inst->group / max_width);
7807 
7808          /* Split the copies in chunks of the execution width of either the
7809           * original or the lowered instruction, whichever is lower.
7810           */
7811          const unsigned n = DIV_ROUND_UP(inst->exec_size, lower_width);
7812          const unsigned dst_size = inst->size_written /
7813             inst->dst.component_size(inst->exec_size);
7814 
7815          assert(!inst->writes_accumulator && !inst->mlen);
7816 
7817          /* Inserting the zip, unzip, and duplicated instructions in all of
7818           * the right spots is somewhat tricky.  All of the unzip and any
7819           * instructions from the zip which unzip the destination prior to
7820           * writing need to happen before all of the per-group instructions
7821           * and the zip instructions need to happen after.  In order to sort
7822           * this all out, we insert the unzip instructions before \p inst,
7823           * insert the per-group instructions after \p inst (i.e. before
7824           * inst->next), and insert the zip instructions before the
7825           * instruction after \p inst.  Since we are inserting instructions
7826           * after \p inst, inst->next is a moving target and we need to save
7827           * it off here so that we insert the zip instructions in the right
7828           * place.
7829           *
7830           * Since we're inserting split instructions after after_inst, the
7831           * instructions will end up in the reverse order that we insert them.
7832           * However, certain render target writes require that the low group
7833           * instructions come before the high group.  From the Ivy Bridge PRM
7834           * Vol. 4, Pt. 1, Section 3.9.11:
7835           *
7836           *    "If multiple SIMD8 Dual Source messages are delivered by the
7837           *    pixel shader thread, each SIMD8_DUALSRC_LO message must be
7838           *    issued before the SIMD8_DUALSRC_HI message with the same Slot
7839           *    Group Select setting."
7840           *
7841           * And, from Section 3.9.11.1 of the same PRM:
7842           *
7843           *    "When SIMD32 or SIMD16 PS threads send render target writes
7844           *    with multiple SIMD8 and SIMD16 messages, the following must
7845           *    hold:
7846           *
7847           *    All the slots (as described above) must have a corresponding
7848           *    render target write irrespective of the slot's validity. A slot
7849           *    is considered valid when at least one sample is enabled. For
7850           *    example, a SIMD16 PS thread must send two SIMD8 render target
7851           *    writes to cover all the slots.
7852           *
7853           *    PS thread must send SIMD render target write messages with
7854           *    increasing slot numbers. For example, SIMD16 thread has
7855           *    Slot[15:0] and if two SIMD8 render target writes are used, the
7856           *    first SIMD8 render target write must send Slot[7:0] and the
7857           *    next one must send Slot[15:8]."
7858           *
7859           * In order to make low group instructions come before high group
7860           * instructions (this is required for some render target writes), we
7861           * split from the highest group to lowest.
7862           */
7863          exec_node *const after_inst = inst->next;
7864          for (int i = n - 1; i >= 0; i--) {
7865             /* Emit a copy of the original instruction with the lowered width.
7866              * If the EOT flag was set throw it away except for the last
7867              * instruction to avoid killing the thread prematurely.
7868              */
7869             fs_inst split_inst = *inst;
7870             split_inst.exec_size = lower_width;
7871             split_inst.eot = inst->eot && i == int(n - 1);
7872 
7873             /* Select the correct channel enables for the i-th group, then
7874              * transform the sources and destination and emit the lowered
7875              * instruction.
7876              */
7877             const fs_builder lbld = ibld.group(lower_width, i);
7878 
7879             for (unsigned j = 0; j < inst->sources; j++)
7880                split_inst.src[j] = emit_unzip(lbld.at(block, inst), inst, j);
7881 
7882             split_inst.dst = emit_zip(lbld.at(block, inst),
7883                                       lbld.at(block, after_inst), inst);
7884             split_inst.size_written =
7885                split_inst.dst.component_size(lower_width) * dst_size;
7886 
7887             lbld.at(block, inst->next).emit(split_inst);
7888          }
7889 
7890          inst->remove(block);
7891          progress = true;
7892       }
7893    }
7894 
7895    if (progress)
7896       invalidate_analysis(DEPENDENCY_INSTRUCTIONS | DEPENDENCY_VARIABLES);
7897 
7898    return progress;
7899 }
7900 
7901 /**
7902  * Transform barycentric vectors into the interleaved form expected by the PLN
7903  * instruction and returned by the Gfx7+ PI shared function.
7904  *
7905  * For channels 0-15 in SIMD16 mode they are expected to be laid out as
7906  * follows in the register file:
7907  *
7908  *    rN+0: X[0-7]
7909  *    rN+1: Y[0-7]
7910  *    rN+2: X[8-15]
7911  *    rN+3: Y[8-15]
7912  *
7913  * There is no need to handle SIMD32 here -- This is expected to be run after
7914  * SIMD lowering, since SIMD lowering relies on vectors having the standard
7915  * component layout.
7916  */
7917 bool
lower_barycentrics()7918 fs_visitor::lower_barycentrics()
7919 {
7920    const bool has_interleaved_layout = devinfo->has_pln || devinfo->ver >= 7;
7921    bool progress = false;
7922 
7923    if (stage != MESA_SHADER_FRAGMENT || !has_interleaved_layout)
7924       return false;
7925 
7926    foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
7927       if (inst->exec_size < 16)
7928          continue;
7929 
7930       const fs_builder ibld(this, block, inst);
7931       const fs_builder ubld = ibld.exec_all().group(8, 0);
7932 
7933       switch (inst->opcode) {
7934       case FS_OPCODE_LINTERP : {
7935          assert(inst->exec_size == 16);
7936          const fs_reg tmp = ibld.vgrf(inst->src[0].type, 2);
7937          fs_reg srcs[4];
7938 
7939          for (unsigned i = 0; i < ARRAY_SIZE(srcs); i++)
7940             srcs[i] = horiz_offset(offset(inst->src[0], ibld, i % 2),
7941                                    8 * (i / 2));
7942 
7943          ubld.LOAD_PAYLOAD(tmp, srcs, ARRAY_SIZE(srcs), ARRAY_SIZE(srcs));
7944 
7945          inst->src[0] = tmp;
7946          progress = true;
7947          break;
7948       }
7949       case FS_OPCODE_INTERPOLATE_AT_SAMPLE:
7950       case FS_OPCODE_INTERPOLATE_AT_SHARED_OFFSET:
7951       case FS_OPCODE_INTERPOLATE_AT_PER_SLOT_OFFSET: {
7952          assert(inst->exec_size == 16);
7953          const fs_reg tmp = ibld.vgrf(inst->dst.type, 2);
7954 
7955          for (unsigned i = 0; i < 2; i++) {
7956             for (unsigned g = 0; g < inst->exec_size / 8; g++) {
7957                fs_inst *mov = ibld.at(block, inst->next).group(8, g)
7958                                   .MOV(horiz_offset(offset(inst->dst, ibld, i),
7959                                                     8 * g),
7960                                        offset(tmp, ubld, 2 * g + i));
7961                mov->predicate = inst->predicate;
7962                mov->predicate_inverse = inst->predicate_inverse;
7963                mov->flag_subreg = inst->flag_subreg;
7964             }
7965          }
7966 
7967          inst->dst = tmp;
7968          progress = true;
7969          break;
7970       }
7971       default:
7972          break;
7973       }
7974    }
7975 
7976    if (progress)
7977       invalidate_analysis(DEPENDENCY_INSTRUCTIONS | DEPENDENCY_VARIABLES);
7978 
7979    return progress;
7980 }
7981 
7982 /**
7983  * Lower a derivative instruction as the floating-point difference of two
7984  * swizzles of the source, specified as \p swz0 and \p swz1.
7985  */
7986 static bool
lower_derivative(fs_visitor * v,bblock_t * block,fs_inst * inst,unsigned swz0,unsigned swz1)7987 lower_derivative(fs_visitor *v, bblock_t *block, fs_inst *inst,
7988                  unsigned swz0, unsigned swz1)
7989 {
7990    const fs_builder ibld(v, block, inst);
7991    const fs_reg tmp0 = ibld.vgrf(inst->src[0].type);
7992    const fs_reg tmp1 = ibld.vgrf(inst->src[0].type);
7993 
7994    ibld.emit(SHADER_OPCODE_QUAD_SWIZZLE, tmp0, inst->src[0], brw_imm_ud(swz0));
7995    ibld.emit(SHADER_OPCODE_QUAD_SWIZZLE, tmp1, inst->src[0], brw_imm_ud(swz1));
7996 
7997    inst->resize_sources(2);
7998    inst->src[0] = negate(tmp0);
7999    inst->src[1] = tmp1;
8000    inst->opcode = BRW_OPCODE_ADD;
8001 
8002    return true;
8003 }
8004 
8005 /**
8006  * Lower derivative instructions on platforms where codegen cannot implement
8007  * them efficiently (i.e. XeHP).
8008  */
8009 bool
lower_derivatives()8010 fs_visitor::lower_derivatives()
8011 {
8012    bool progress = false;
8013 
8014    if (devinfo->verx10 < 125)
8015       return false;
8016 
8017    foreach_block_and_inst(block, fs_inst, inst, cfg) {
8018       if (inst->opcode == FS_OPCODE_DDX_COARSE)
8019          progress |= lower_derivative(this, block, inst,
8020                                       BRW_SWIZZLE_XXXX, BRW_SWIZZLE_YYYY);
8021 
8022       else if (inst->opcode == FS_OPCODE_DDX_FINE)
8023          progress |= lower_derivative(this, block, inst,
8024                                       BRW_SWIZZLE_XXZZ, BRW_SWIZZLE_YYWW);
8025 
8026       else if (inst->opcode == FS_OPCODE_DDY_COARSE)
8027          progress |= lower_derivative(this, block, inst,
8028                                       BRW_SWIZZLE_XXXX, BRW_SWIZZLE_ZZZZ);
8029 
8030       else if (inst->opcode == FS_OPCODE_DDY_FINE)
8031          progress |= lower_derivative(this, block, inst,
8032                                       BRW_SWIZZLE_XYXY, BRW_SWIZZLE_ZWZW);
8033    }
8034 
8035    if (progress)
8036       invalidate_analysis(DEPENDENCY_INSTRUCTIONS | DEPENDENCY_VARIABLES);
8037 
8038    return progress;
8039 }
8040 
8041 void
dump_instructions() const8042 fs_visitor::dump_instructions() const
8043 {
8044    dump_instructions(NULL);
8045 }
8046 
8047 void
dump_instructions(const char * name) const8048 fs_visitor::dump_instructions(const char *name) const
8049 {
8050    FILE *file = stderr;
8051    if (name && geteuid() != 0) {
8052       file = fopen(name, "w");
8053       if (!file)
8054          file = stderr;
8055    }
8056 
8057    if (cfg) {
8058       const register_pressure &rp = regpressure_analysis.require();
8059       unsigned ip = 0, max_pressure = 0;
8060       foreach_block_and_inst(block, backend_instruction, inst, cfg) {
8061          max_pressure = MAX2(max_pressure, rp.regs_live_at_ip[ip]);
8062          fprintf(file, "{%3d} %4d: ", rp.regs_live_at_ip[ip], ip);
8063          dump_instruction(inst, file);
8064          ip++;
8065       }
8066       fprintf(file, "Maximum %3d registers live at once.\n", max_pressure);
8067    } else {
8068       int ip = 0;
8069       foreach_in_list(backend_instruction, inst, &instructions) {
8070          fprintf(file, "%4d: ", ip++);
8071          dump_instruction(inst, file);
8072       }
8073    }
8074 
8075    if (file != stderr) {
8076       fclose(file);
8077    }
8078 }
8079 
8080 void
dump_instruction(const backend_instruction * be_inst) const8081 fs_visitor::dump_instruction(const backend_instruction *be_inst) const
8082 {
8083    dump_instruction(be_inst, stderr);
8084 }
8085 
8086 void
dump_instruction(const backend_instruction * be_inst,FILE * file) const8087 fs_visitor::dump_instruction(const backend_instruction *be_inst, FILE *file) const
8088 {
8089    const fs_inst *inst = (const fs_inst *)be_inst;
8090 
8091    if (inst->predicate) {
8092       fprintf(file, "(%cf%d.%d) ",
8093               inst->predicate_inverse ? '-' : '+',
8094               inst->flag_subreg / 2,
8095               inst->flag_subreg % 2);
8096    }
8097 
8098    fprintf(file, "%s", brw_instruction_name(devinfo, inst->opcode));
8099    if (inst->saturate)
8100       fprintf(file, ".sat");
8101    if (inst->conditional_mod) {
8102       fprintf(file, "%s", conditional_modifier[inst->conditional_mod]);
8103       if (!inst->predicate &&
8104           (devinfo->ver < 5 || (inst->opcode != BRW_OPCODE_SEL &&
8105                                 inst->opcode != BRW_OPCODE_CSEL &&
8106                                 inst->opcode != BRW_OPCODE_IF &&
8107                                 inst->opcode != BRW_OPCODE_WHILE))) {
8108          fprintf(file, ".f%d.%d", inst->flag_subreg / 2,
8109                  inst->flag_subreg % 2);
8110       }
8111    }
8112    fprintf(file, "(%d) ", inst->exec_size);
8113 
8114    if (inst->mlen) {
8115       fprintf(file, "(mlen: %d) ", inst->mlen);
8116    }
8117 
8118    if (inst->ex_mlen) {
8119       fprintf(file, "(ex_mlen: %d) ", inst->ex_mlen);
8120    }
8121 
8122    if (inst->eot) {
8123       fprintf(file, "(EOT) ");
8124    }
8125 
8126    switch (inst->dst.file) {
8127    case VGRF:
8128       fprintf(file, "vgrf%d", inst->dst.nr);
8129       break;
8130    case FIXED_GRF:
8131       fprintf(file, "g%d", inst->dst.nr);
8132       break;
8133    case MRF:
8134       fprintf(file, "m%d", inst->dst.nr);
8135       break;
8136    case BAD_FILE:
8137       fprintf(file, "(null)");
8138       break;
8139    case UNIFORM:
8140       fprintf(file, "***u%d***", inst->dst.nr);
8141       break;
8142    case ATTR:
8143       fprintf(file, "***attr%d***", inst->dst.nr);
8144       break;
8145    case ARF:
8146       switch (inst->dst.nr) {
8147       case BRW_ARF_NULL:
8148          fprintf(file, "null");
8149          break;
8150       case BRW_ARF_ADDRESS:
8151          fprintf(file, "a0.%d", inst->dst.subnr);
8152          break;
8153       case BRW_ARF_ACCUMULATOR:
8154          fprintf(file, "acc%d", inst->dst.subnr);
8155          break;
8156       case BRW_ARF_FLAG:
8157          fprintf(file, "f%d.%d", inst->dst.nr & 0xf, inst->dst.subnr);
8158          break;
8159       default:
8160          fprintf(file, "arf%d.%d", inst->dst.nr & 0xf, inst->dst.subnr);
8161          break;
8162       }
8163       break;
8164    case IMM:
8165       unreachable("not reached");
8166    }
8167 
8168    if (inst->dst.offset ||
8169        (inst->dst.file == VGRF &&
8170         alloc.sizes[inst->dst.nr] * REG_SIZE != inst->size_written)) {
8171       const unsigned reg_size = (inst->dst.file == UNIFORM ? 4 : REG_SIZE);
8172       fprintf(file, "+%d.%d", inst->dst.offset / reg_size,
8173               inst->dst.offset % reg_size);
8174    }
8175 
8176    if (inst->dst.stride != 1)
8177       fprintf(file, "<%u>", inst->dst.stride);
8178    fprintf(file, ":%s, ", brw_reg_type_to_letters(inst->dst.type));
8179 
8180    for (int i = 0; i < inst->sources; i++) {
8181       if (inst->src[i].negate)
8182          fprintf(file, "-");
8183       if (inst->src[i].abs)
8184          fprintf(file, "|");
8185       switch (inst->src[i].file) {
8186       case VGRF:
8187          fprintf(file, "vgrf%d", inst->src[i].nr);
8188          break;
8189       case FIXED_GRF:
8190          fprintf(file, "g%d", inst->src[i].nr);
8191          break;
8192       case MRF:
8193          fprintf(file, "***m%d***", inst->src[i].nr);
8194          break;
8195       case ATTR:
8196          fprintf(file, "attr%d", inst->src[i].nr);
8197          break;
8198       case UNIFORM:
8199          fprintf(file, "u%d", inst->src[i].nr);
8200          break;
8201       case BAD_FILE:
8202          fprintf(file, "(null)");
8203          break;
8204       case IMM:
8205          switch (inst->src[i].type) {
8206          case BRW_REGISTER_TYPE_HF:
8207             fprintf(file, "%-ghf", _mesa_half_to_float(inst->src[i].ud & 0xffff));
8208             break;
8209          case BRW_REGISTER_TYPE_F:
8210             fprintf(file, "%-gf", inst->src[i].f);
8211             break;
8212          case BRW_REGISTER_TYPE_DF:
8213             fprintf(file, "%fdf", inst->src[i].df);
8214             break;
8215          case BRW_REGISTER_TYPE_W:
8216          case BRW_REGISTER_TYPE_D:
8217             fprintf(file, "%dd", inst->src[i].d);
8218             break;
8219          case BRW_REGISTER_TYPE_UW:
8220          case BRW_REGISTER_TYPE_UD:
8221             fprintf(file, "%uu", inst->src[i].ud);
8222             break;
8223          case BRW_REGISTER_TYPE_Q:
8224             fprintf(file, "%" PRId64 "q", inst->src[i].d64);
8225             break;
8226          case BRW_REGISTER_TYPE_UQ:
8227             fprintf(file, "%" PRIu64 "uq", inst->src[i].u64);
8228             break;
8229          case BRW_REGISTER_TYPE_VF:
8230             fprintf(file, "[%-gF, %-gF, %-gF, %-gF]",
8231                     brw_vf_to_float((inst->src[i].ud >>  0) & 0xff),
8232                     brw_vf_to_float((inst->src[i].ud >>  8) & 0xff),
8233                     brw_vf_to_float((inst->src[i].ud >> 16) & 0xff),
8234                     brw_vf_to_float((inst->src[i].ud >> 24) & 0xff));
8235             break;
8236          case BRW_REGISTER_TYPE_V:
8237          case BRW_REGISTER_TYPE_UV:
8238             fprintf(file, "%08x%s", inst->src[i].ud,
8239                     inst->src[i].type == BRW_REGISTER_TYPE_V ? "V" : "UV");
8240             break;
8241          default:
8242             fprintf(file, "???");
8243             break;
8244          }
8245          break;
8246       case ARF:
8247          switch (inst->src[i].nr) {
8248          case BRW_ARF_NULL:
8249             fprintf(file, "null");
8250             break;
8251          case BRW_ARF_ADDRESS:
8252             fprintf(file, "a0.%d", inst->src[i].subnr);
8253             break;
8254          case BRW_ARF_ACCUMULATOR:
8255             fprintf(file, "acc%d", inst->src[i].subnr);
8256             break;
8257          case BRW_ARF_FLAG:
8258             fprintf(file, "f%d.%d", inst->src[i].nr & 0xf, inst->src[i].subnr);
8259             break;
8260          default:
8261             fprintf(file, "arf%d.%d", inst->src[i].nr & 0xf, inst->src[i].subnr);
8262             break;
8263          }
8264          break;
8265       }
8266 
8267       if (inst->src[i].offset ||
8268           (inst->src[i].file == VGRF &&
8269            alloc.sizes[inst->src[i].nr] * REG_SIZE != inst->size_read(i))) {
8270          const unsigned reg_size = (inst->src[i].file == UNIFORM ? 4 : REG_SIZE);
8271          fprintf(file, "+%d.%d", inst->src[i].offset / reg_size,
8272                  inst->src[i].offset % reg_size);
8273       }
8274 
8275       if (inst->src[i].abs)
8276          fprintf(file, "|");
8277 
8278       if (inst->src[i].file != IMM) {
8279          unsigned stride;
8280          if (inst->src[i].file == ARF || inst->src[i].file == FIXED_GRF) {
8281             unsigned hstride = inst->src[i].hstride;
8282             stride = (hstride == 0 ? 0 : (1 << (hstride - 1)));
8283          } else {
8284             stride = inst->src[i].stride;
8285          }
8286          if (stride != 1)
8287             fprintf(file, "<%u>", stride);
8288 
8289          fprintf(file, ":%s", brw_reg_type_to_letters(inst->src[i].type));
8290       }
8291 
8292       if (i < inst->sources - 1 && inst->src[i + 1].file != BAD_FILE)
8293          fprintf(file, ", ");
8294    }
8295 
8296    fprintf(file, " ");
8297 
8298    if (inst->force_writemask_all)
8299       fprintf(file, "NoMask ");
8300 
8301    if (inst->exec_size != dispatch_width)
8302       fprintf(file, "group%d ", inst->group);
8303 
8304    fprintf(file, "\n");
8305 }
8306 
8307 void
setup_fs_payload_gfx6()8308 fs_visitor::setup_fs_payload_gfx6()
8309 {
8310    assert(stage == MESA_SHADER_FRAGMENT);
8311    struct brw_wm_prog_data *prog_data = brw_wm_prog_data(this->prog_data);
8312    const unsigned payload_width = MIN2(16, dispatch_width);
8313    assert(dispatch_width % payload_width == 0);
8314    assert(devinfo->ver >= 6);
8315 
8316    /* R0: PS thread payload header. */
8317    payload.num_regs++;
8318 
8319    for (unsigned j = 0; j < dispatch_width / payload_width; j++) {
8320       /* R1: masks, pixel X/Y coordinates. */
8321       payload.subspan_coord_reg[j] = payload.num_regs++;
8322    }
8323 
8324    for (unsigned j = 0; j < dispatch_width / payload_width; j++) {
8325       /* R3-26: barycentric interpolation coordinates.  These appear in the
8326        * same order that they appear in the brw_barycentric_mode enum.  Each
8327        * set of coordinates occupies 2 registers if dispatch width == 8 and 4
8328        * registers if dispatch width == 16.  Coordinates only appear if they
8329        * were enabled using the "Barycentric Interpolation Mode" bits in
8330        * WM_STATE.
8331        */
8332       for (int i = 0; i < BRW_BARYCENTRIC_MODE_COUNT; ++i) {
8333          if (prog_data->barycentric_interp_modes & (1 << i)) {
8334             payload.barycentric_coord_reg[i][j] = payload.num_regs;
8335             payload.num_regs += payload_width / 4;
8336          }
8337       }
8338 
8339       /* R27-28: interpolated depth if uses source depth */
8340       if (prog_data->uses_src_depth) {
8341          payload.source_depth_reg[j] = payload.num_regs;
8342          payload.num_regs += payload_width / 8;
8343       }
8344 
8345       /* R29-30: interpolated W set if GFX6_WM_USES_SOURCE_W. */
8346       if (prog_data->uses_src_w) {
8347          payload.source_w_reg[j] = payload.num_regs;
8348          payload.num_regs += payload_width / 8;
8349       }
8350 
8351       /* R31: MSAA position offsets. */
8352       if (prog_data->uses_pos_offset) {
8353          payload.sample_pos_reg[j] = payload.num_regs;
8354          payload.num_regs++;
8355       }
8356 
8357       /* R32-33: MSAA input coverage mask */
8358       if (prog_data->uses_sample_mask) {
8359          assert(devinfo->ver >= 7);
8360          payload.sample_mask_in_reg[j] = payload.num_regs;
8361          payload.num_regs += payload_width / 8;
8362       }
8363 
8364       /* R66: Source Depth and/or W Attribute Vertex Deltas */
8365       if (prog_data->uses_depth_w_coefficients) {
8366          payload.depth_w_coef_reg[j] = payload.num_regs;
8367          payload.num_regs++;
8368       }
8369    }
8370 
8371    if (nir->info.outputs_written & BITFIELD64_BIT(FRAG_RESULT_DEPTH)) {
8372       source_depth_to_render_target = true;
8373    }
8374 }
8375 
8376 void
setup_vs_payload()8377 fs_visitor::setup_vs_payload()
8378 {
8379    /* R0: thread header, R1: urb handles */
8380    payload.num_regs = 2;
8381 }
8382 
8383 void
setup_gs_payload()8384 fs_visitor::setup_gs_payload()
8385 {
8386    assert(stage == MESA_SHADER_GEOMETRY);
8387 
8388    struct brw_gs_prog_data *gs_prog_data = brw_gs_prog_data(prog_data);
8389    struct brw_vue_prog_data *vue_prog_data = brw_vue_prog_data(prog_data);
8390 
8391    /* R0: thread header, R1: output URB handles */
8392    payload.num_regs = 2;
8393 
8394    if (gs_prog_data->include_primitive_id) {
8395       /* R2: Primitive ID 0..7 */
8396       payload.num_regs++;
8397    }
8398 
8399    /* Always enable VUE handles so we can safely use pull model if needed.
8400     *
8401     * The push model for a GS uses a ton of register space even for trivial
8402     * scenarios with just a few inputs, so just make things easier and a bit
8403     * safer by always having pull model available.
8404     */
8405    gs_prog_data->base.include_vue_handles = true;
8406 
8407    /* R3..RN: ICP Handles for each incoming vertex (when using pull model) */
8408    payload.num_regs += nir->info.gs.vertices_in;
8409 
8410    /* Use a maximum of 24 registers for push-model inputs. */
8411    const unsigned max_push_components = 24;
8412 
8413    /* If pushing our inputs would take too many registers, reduce the URB read
8414     * length (which is in HWords, or 8 registers), and resort to pulling.
8415     *
8416     * Note that the GS reads <URB Read Length> HWords for every vertex - so we
8417     * have to multiply by VerticesIn to obtain the total storage requirement.
8418     */
8419    if (8 * vue_prog_data->urb_read_length * nir->info.gs.vertices_in >
8420        max_push_components) {
8421       vue_prog_data->urb_read_length =
8422          ROUND_DOWN_TO(max_push_components / nir->info.gs.vertices_in, 8) / 8;
8423    }
8424 }
8425 
8426 void
setup_cs_payload()8427 fs_visitor::setup_cs_payload()
8428 {
8429    assert(devinfo->ver >= 7);
8430    /* TODO: Fill out uses_btd_stack_ids automatically */
8431    payload.num_regs = 1 + brw_cs_prog_data(prog_data)->uses_btd_stack_ids;
8432 }
8433 
register_pressure(const fs_visitor * v)8434 brw::register_pressure::register_pressure(const fs_visitor *v)
8435 {
8436    const fs_live_variables &live = v->live_analysis.require();
8437    const unsigned num_instructions = v->cfg->num_blocks ?
8438       v->cfg->blocks[v->cfg->num_blocks - 1]->end_ip + 1 : 0;
8439 
8440    regs_live_at_ip = new unsigned[num_instructions]();
8441 
8442    for (unsigned reg = 0; reg < v->alloc.count; reg++) {
8443       for (int ip = live.vgrf_start[reg]; ip <= live.vgrf_end[reg]; ip++)
8444          regs_live_at_ip[ip] += v->alloc.sizes[reg];
8445    }
8446 }
8447 
~register_pressure()8448 brw::register_pressure::~register_pressure()
8449 {
8450    delete[] regs_live_at_ip;
8451 }
8452 
8453 void
invalidate_analysis(brw::analysis_dependency_class c)8454 fs_visitor::invalidate_analysis(brw::analysis_dependency_class c)
8455 {
8456    backend_shader::invalidate_analysis(c);
8457    live_analysis.invalidate(c);
8458    regpressure_analysis.invalidate(c);
8459 }
8460 
8461 void
optimize()8462 fs_visitor::optimize()
8463 {
8464    /* Start by validating the shader we currently have. */
8465    validate();
8466 
8467    /* bld is the common builder object pointing at the end of the program we
8468     * used to translate it into i965 IR.  For the optimization and lowering
8469     * passes coming next, any code added after the end of the program without
8470     * having explicitly called fs_builder::at() clearly points at a mistake.
8471     * Ideally optimization passes wouldn't be part of the visitor so they
8472     * wouldn't have access to bld at all, but they do, so just in case some
8473     * pass forgets to ask for a location explicitly set it to NULL here to
8474     * make it trip.  The dispatch width is initialized to a bogus value to
8475     * make sure that optimizations set the execution controls explicitly to
8476     * match the code they are manipulating instead of relying on the defaults.
8477     */
8478    bld = fs_builder(this, 64);
8479 
8480    assign_constant_locations();
8481    lower_constant_loads();
8482 
8483    validate();
8484 
8485    split_virtual_grfs();
8486    validate();
8487 
8488 #define OPT(pass, args...) ({                                           \
8489       pass_num++;                                                       \
8490       bool this_progress = pass(args);                                  \
8491                                                                         \
8492       if (INTEL_DEBUG(DEBUG_OPTIMIZER) && this_progress) {              \
8493          char filename[64];                                             \
8494          snprintf(filename, 64, "%s%d-%s-%02d-%02d-" #pass,              \
8495                   stage_abbrev, dispatch_width, nir->info.name, iteration, pass_num); \
8496                                                                         \
8497          backend_shader::dump_instructions(filename);                   \
8498       }                                                                 \
8499                                                                         \
8500       validate();                                                       \
8501                                                                         \
8502       progress = progress || this_progress;                             \
8503       this_progress;                                                    \
8504    })
8505 
8506    if (INTEL_DEBUG(DEBUG_OPTIMIZER)) {
8507       char filename[64];
8508       snprintf(filename, 64, "%s%d-%s-00-00-start",
8509                stage_abbrev, dispatch_width, nir->info.name);
8510 
8511       backend_shader::dump_instructions(filename);
8512    }
8513 
8514    bool progress = false;
8515    int iteration = 0;
8516    int pass_num = 0;
8517 
8518    /* Before anything else, eliminate dead code.  The results of some NIR
8519     * instructions may effectively be calculated twice.  Once when the
8520     * instruction is encountered, and again when the user of that result is
8521     * encountered.  Wipe those away before algebraic optimizations and
8522     * especially copy propagation can mix things up.
8523     */
8524    OPT(dead_code_eliminate);
8525 
8526    OPT(remove_extra_rounding_modes);
8527 
8528    do {
8529       progress = false;
8530       pass_num = 0;
8531       iteration++;
8532 
8533       OPT(remove_duplicate_mrf_writes);
8534 
8535       OPT(opt_algebraic);
8536       OPT(opt_cse);
8537       OPT(opt_copy_propagation);
8538       OPT(opt_predicated_break, this);
8539       OPT(opt_cmod_propagation);
8540       OPT(dead_code_eliminate);
8541       OPT(opt_peephole_sel);
8542       OPT(dead_control_flow_eliminate, this);
8543       OPT(opt_register_renaming);
8544       OPT(opt_saturate_propagation);
8545       OPT(register_coalesce);
8546       OPT(compute_to_mrf);
8547       OPT(eliminate_find_live_channel);
8548 
8549       OPT(compact_virtual_grfs);
8550    } while (progress);
8551 
8552    progress = false;
8553    pass_num = 0;
8554 
8555    if (OPT(lower_pack)) {
8556       OPT(register_coalesce);
8557       OPT(dead_code_eliminate);
8558    }
8559 
8560    OPT(lower_simd_width);
8561    OPT(lower_barycentrics);
8562    OPT(lower_logical_sends);
8563 
8564    /* After logical SEND lowering. */
8565    OPT(fixup_nomask_control_flow);
8566 
8567    if (progress) {
8568       OPT(opt_copy_propagation);
8569       /* Only run after logical send lowering because it's easier to implement
8570        * in terms of physical sends.
8571        */
8572       if (OPT(opt_zero_samples))
8573          OPT(opt_copy_propagation);
8574       /* Run after logical send lowering to give it a chance to CSE the
8575        * LOAD_PAYLOAD instructions created to construct the payloads of
8576        * e.g. texturing messages in cases where it wasn't possible to CSE the
8577        * whole logical instruction.
8578        */
8579       OPT(opt_cse);
8580       OPT(register_coalesce);
8581       OPT(compute_to_mrf);
8582       OPT(dead_code_eliminate);
8583       OPT(remove_duplicate_mrf_writes);
8584       OPT(opt_peephole_sel);
8585    }
8586 
8587    OPT(opt_redundant_halt);
8588 
8589    if (OPT(lower_load_payload)) {
8590       split_virtual_grfs();
8591 
8592       /* Lower 64 bit MOVs generated by payload lowering. */
8593       if (!devinfo->has_64bit_float && !devinfo->has_64bit_int)
8594          OPT(opt_algebraic);
8595 
8596       OPT(register_coalesce);
8597       OPT(lower_simd_width);
8598       OPT(compute_to_mrf);
8599       OPT(dead_code_eliminate);
8600    }
8601 
8602    OPT(opt_combine_constants);
8603    if (OPT(lower_integer_multiplication)) {
8604       /* If lower_integer_multiplication made progress, it may have produced
8605        * some 32x32-bit MULs in the process of lowering 64-bit MULs.  Run it
8606        * one more time to clean those up if they exist.
8607        */
8608       OPT(lower_integer_multiplication);
8609    }
8610    OPT(lower_sub_sat);
8611 
8612    if (devinfo->ver <= 5 && OPT(lower_minmax)) {
8613       OPT(opt_cmod_propagation);
8614       OPT(opt_cse);
8615       OPT(opt_copy_propagation);
8616       OPT(dead_code_eliminate);
8617    }
8618 
8619    progress = false;
8620    OPT(lower_derivatives);
8621    OPT(lower_regioning);
8622    if (progress) {
8623       OPT(opt_copy_propagation);
8624       OPT(dead_code_eliminate);
8625       OPT(lower_simd_width);
8626    }
8627 
8628    OPT(fixup_sends_duplicate_payload);
8629 
8630    lower_uniform_pull_constant_loads();
8631 
8632    validate();
8633 }
8634 
8635 /**
8636  * From the Skylake PRM Vol. 2a docs for sends:
8637  *
8638  *    "It is required that the second block of GRFs does not overlap with the
8639  *    first block."
8640  *
8641  * There are plenty of cases where we may accidentally violate this due to
8642  * having, for instance, both sources be the constant 0.  This little pass
8643  * just adds a new vgrf for the second payload and copies it over.
8644  */
8645 bool
fixup_sends_duplicate_payload()8646 fs_visitor::fixup_sends_duplicate_payload()
8647 {
8648    bool progress = false;
8649 
8650    foreach_block_and_inst_safe (block, fs_inst, inst, cfg) {
8651       if (inst->opcode == SHADER_OPCODE_SEND && inst->ex_mlen > 0 &&
8652           regions_overlap(inst->src[2], inst->mlen * REG_SIZE,
8653                           inst->src[3], inst->ex_mlen * REG_SIZE)) {
8654          fs_reg tmp = fs_reg(VGRF, alloc.allocate(inst->ex_mlen),
8655                              BRW_REGISTER_TYPE_UD);
8656          /* Sadly, we've lost all notion of channels and bit sizes at this
8657           * point.  Just WE_all it.
8658           */
8659          const fs_builder ibld = bld.at(block, inst).exec_all().group(16, 0);
8660          fs_reg copy_src = retype(inst->src[3], BRW_REGISTER_TYPE_UD);
8661          fs_reg copy_dst = tmp;
8662          for (unsigned i = 0; i < inst->ex_mlen; i += 2) {
8663             if (inst->ex_mlen == i + 1) {
8664                /* Only one register left; do SIMD8 */
8665                ibld.group(8, 0).MOV(copy_dst, copy_src);
8666             } else {
8667                ibld.MOV(copy_dst, copy_src);
8668             }
8669             copy_src = offset(copy_src, ibld, 1);
8670             copy_dst = offset(copy_dst, ibld, 1);
8671          }
8672          inst->src[3] = tmp;
8673          progress = true;
8674       }
8675    }
8676 
8677    if (progress)
8678       invalidate_analysis(DEPENDENCY_INSTRUCTIONS | DEPENDENCY_VARIABLES);
8679 
8680    return progress;
8681 }
8682 
8683 /**
8684  * Three source instruction must have a GRF/MRF destination register.
8685  * ARF NULL is not allowed.  Fix that up by allocating a temporary GRF.
8686  */
8687 void
fixup_3src_null_dest()8688 fs_visitor::fixup_3src_null_dest()
8689 {
8690    bool progress = false;
8691 
8692    foreach_block_and_inst_safe (block, fs_inst, inst, cfg) {
8693       if (inst->is_3src(devinfo) && inst->dst.is_null()) {
8694          inst->dst = fs_reg(VGRF, alloc.allocate(dispatch_width / 8),
8695                             inst->dst.type);
8696          progress = true;
8697       }
8698    }
8699 
8700    if (progress)
8701       invalidate_analysis(DEPENDENCY_INSTRUCTION_DETAIL |
8702                           DEPENDENCY_VARIABLES);
8703 }
8704 
8705 /**
8706  * Find the first instruction in the program that might start a region of
8707  * divergent control flow due to a HALT jump.  There is no
8708  * find_halt_control_flow_region_end(), the region of divergence extends until
8709  * the only SHADER_OPCODE_HALT_TARGET in the program.
8710  */
8711 static const fs_inst *
find_halt_control_flow_region_start(const fs_visitor * v)8712 find_halt_control_flow_region_start(const fs_visitor *v)
8713 {
8714    foreach_block_and_inst(block, fs_inst, inst, v->cfg) {
8715       if (inst->opcode == BRW_OPCODE_HALT ||
8716           inst->opcode == SHADER_OPCODE_HALT_TARGET)
8717          return inst;
8718    }
8719 
8720    return NULL;
8721 }
8722 
8723 /**
8724  * Work around the Gfx12 hardware bug filed as Wa_1407528679.  EU fusion
8725  * can cause a BB to be executed with all channels disabled, which will lead
8726  * to the execution of any NoMask instructions in it, even though any
8727  * execution-masked instructions will be correctly shot down.  This may break
8728  * assumptions of some NoMask SEND messages whose descriptor depends on data
8729  * generated by live invocations of the shader.
8730  *
8731  * This avoids the problem by predicating certain instructions on an ANY
8732  * horizontal predicate that makes sure that their execution is omitted when
8733  * all channels of the program are disabled.
8734  */
8735 bool
fixup_nomask_control_flow()8736 fs_visitor::fixup_nomask_control_flow()
8737 {
8738    if (devinfo->ver != 12)
8739       return false;
8740 
8741    const brw_predicate pred = dispatch_width > 16 ? BRW_PREDICATE_ALIGN1_ANY32H :
8742                               dispatch_width > 8 ? BRW_PREDICATE_ALIGN1_ANY16H :
8743                               BRW_PREDICATE_ALIGN1_ANY8H;
8744    const fs_inst *halt_start = find_halt_control_flow_region_start(this);
8745    unsigned depth = 0;
8746    bool progress = false;
8747 
8748    const fs_live_variables &live_vars = live_analysis.require();
8749 
8750    /* Scan the program backwards in order to be able to easily determine
8751     * whether the flag register is live at any point.
8752     */
8753    foreach_block_reverse_safe(block, cfg) {
8754       BITSET_WORD flag_liveout = live_vars.block_data[block->num]
8755                                                .flag_liveout[0];
8756       STATIC_ASSERT(ARRAY_SIZE(live_vars.block_data[0].flag_liveout) == 1);
8757 
8758       foreach_inst_in_block_reverse_safe(fs_inst, inst, block) {
8759          if (!inst->predicate && inst->exec_size >= 8)
8760             flag_liveout &= ~inst->flags_written(devinfo);
8761 
8762          switch (inst->opcode) {
8763          case BRW_OPCODE_DO:
8764          case BRW_OPCODE_IF:
8765             /* Note that this doesn't handle BRW_OPCODE_HALT since only
8766              * the first one in the program closes the region of divergent
8767              * control flow due to any HALT instructions -- Instead this is
8768              * handled with the halt_start check below.
8769              */
8770             depth--;
8771             break;
8772 
8773          case BRW_OPCODE_WHILE:
8774          case BRW_OPCODE_ENDIF:
8775          case SHADER_OPCODE_HALT_TARGET:
8776             depth++;
8777             break;
8778 
8779          default:
8780             /* Note that the vast majority of NoMask SEND instructions in the
8781              * program are harmless while executed in a block with all
8782              * channels disabled, since any instructions with side effects we
8783              * could hit here should be execution-masked.
8784              *
8785              * The main concern is NoMask SEND instructions where the message
8786              * descriptor or header depends on data generated by live
8787              * invocations of the shader (RESINFO and
8788              * FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD with a dynamically
8789              * computed surface index seem to be the only examples right now
8790              * where this could easily lead to GPU hangs).  Unfortunately we
8791              * have no straightforward way to detect that currently, so just
8792              * predicate any NoMask SEND instructions we find under control
8793              * flow.
8794              *
8795              * If this proves to have a measurable performance impact it can
8796              * be easily extended with a whitelist of messages we know we can
8797              * safely omit the predication for.
8798              */
8799             if (depth && inst->force_writemask_all &&
8800                 is_send(inst) && !inst->predicate) {
8801                /* We need to load the execution mask into the flag register by
8802                 * using a builder with channel group matching the whole shader
8803                 * (rather than the default which is derived from the original
8804                 * instruction), in order to avoid getting a right-shifted
8805                 * value.
8806                 */
8807                const fs_builder ubld = fs_builder(this, block, inst)
8808                                        .exec_all().group(dispatch_width, 0);
8809                const fs_reg flag = retype(brw_flag_reg(0, 0),
8810                                           BRW_REGISTER_TYPE_UD);
8811 
8812                /* Due to the lack of flag register allocation we need to save
8813                 * and restore the flag register if it's live.
8814                 */
8815                const bool save_flag = flag_liveout &
8816                                       flag_mask(flag, dispatch_width / 8);
8817                const fs_reg tmp = ubld.group(1, 0).vgrf(flag.type);
8818 
8819                if (save_flag)
8820                   ubld.group(1, 0).MOV(tmp, flag);
8821 
8822                ubld.emit(FS_OPCODE_LOAD_LIVE_CHANNELS);
8823 
8824                set_predicate(pred, inst);
8825                inst->flag_subreg = 0;
8826 
8827                if (save_flag)
8828                   ubld.group(1, 0).at(block, inst->next).MOV(flag, tmp);
8829 
8830                progress = true;
8831             }
8832             break;
8833          }
8834 
8835          if (inst == halt_start)
8836             depth--;
8837 
8838          flag_liveout |= inst->flags_read(devinfo);
8839       }
8840    }
8841 
8842    if (progress)
8843       invalidate_analysis(DEPENDENCY_INSTRUCTIONS | DEPENDENCY_VARIABLES);
8844 
8845    return progress;
8846 }
8847 
8848 void
allocate_registers(bool allow_spilling)8849 fs_visitor::allocate_registers(bool allow_spilling)
8850 {
8851    bool allocated;
8852 
8853    static const enum instruction_scheduler_mode pre_modes[] = {
8854       SCHEDULE_PRE,
8855       SCHEDULE_PRE_NON_LIFO,
8856       SCHEDULE_PRE_LIFO,
8857    };
8858 
8859    static const char *scheduler_mode_name[] = {
8860       "top-down",
8861       "non-lifo",
8862       "lifo"
8863    };
8864 
8865    bool spill_all = allow_spilling && INTEL_DEBUG(DEBUG_SPILL_FS);
8866 
8867    /* Try each scheduling heuristic to see if it can successfully register
8868     * allocate without spilling.  They should be ordered by decreasing
8869     * performance but increasing likelihood of allocating.
8870     */
8871    for (unsigned i = 0; i < ARRAY_SIZE(pre_modes); i++) {
8872       schedule_instructions(pre_modes[i]);
8873       this->shader_stats.scheduler_mode = scheduler_mode_name[i];
8874 
8875       if (0) {
8876          assign_regs_trivial();
8877          allocated = true;
8878          break;
8879       }
8880 
8881       /* Scheduling may create additional opportunities for CMOD propagation,
8882        * so let's do it again.  If CMOD propagation made any progress,
8883        * eliminate dead code one more time.
8884        */
8885       bool progress = false;
8886       const int iteration = 99;
8887       int pass_num = 0;
8888 
8889       if (OPT(opt_cmod_propagation)) {
8890          /* dead_code_eliminate "undoes" the fixing done by
8891           * fixup_3src_null_dest, so we have to do it again if
8892           * dead_code_eliminiate makes any progress.
8893           */
8894          if (OPT(dead_code_eliminate))
8895             fixup_3src_null_dest();
8896       }
8897 
8898       bool can_spill = allow_spilling &&
8899                        (i == ARRAY_SIZE(pre_modes) - 1);
8900 
8901       /* We should only spill registers on the last scheduling. */
8902       assert(!spilled_any_registers);
8903 
8904       allocated = assign_regs(can_spill, spill_all);
8905       if (allocated)
8906          break;
8907    }
8908 
8909    if (!allocated) {
8910       fail("Failure to register allocate.  Reduce number of "
8911            "live scalar values to avoid this.");
8912    } else if (spilled_any_registers) {
8913       brw_shader_perf_log(compiler, log_data,
8914                           "%s shader triggered register spilling.  "
8915                           "Try reducing the number of live scalar "
8916                           "values to improve performance.\n",
8917                           stage_name);
8918    }
8919 
8920    /* This must come after all optimization and register allocation, since
8921     * it inserts dead code that happens to have side effects, and it does
8922     * so based on the actual physical registers in use.
8923     */
8924    insert_gfx4_send_dependency_workarounds();
8925 
8926    if (failed)
8927       return;
8928 
8929    opt_bank_conflicts();
8930 
8931    schedule_instructions(SCHEDULE_POST);
8932 
8933    if (last_scratch > 0) {
8934       ASSERTED unsigned max_scratch_size = 2 * 1024 * 1024;
8935 
8936       prog_data->total_scratch = brw_get_scratch_size(last_scratch);
8937 
8938       if (stage == MESA_SHADER_COMPUTE || stage == MESA_SHADER_KERNEL) {
8939          if (devinfo->is_haswell) {
8940             /* According to the MEDIA_VFE_STATE's "Per Thread Scratch Space"
8941              * field documentation, Haswell supports a minimum of 2kB of
8942              * scratch space for compute shaders, unlike every other stage
8943              * and platform.
8944              */
8945             prog_data->total_scratch = MAX2(prog_data->total_scratch, 2048);
8946          } else if (devinfo->ver <= 7) {
8947             /* According to the MEDIA_VFE_STATE's "Per Thread Scratch Space"
8948              * field documentation, platforms prior to Haswell measure scratch
8949              * size linearly with a range of [1kB, 12kB] and 1kB granularity.
8950              */
8951             prog_data->total_scratch = ALIGN(last_scratch, 1024);
8952             max_scratch_size = 12 * 1024;
8953          }
8954       }
8955 
8956       /* We currently only support up to 2MB of scratch space.  If we
8957        * need to support more eventually, the documentation suggests
8958        * that we could allocate a larger buffer, and partition it out
8959        * ourselves.  We'd just have to undo the hardware's address
8960        * calculation by subtracting (FFTID * Per Thread Scratch Space)
8961        * and then add FFTID * (Larger Per Thread Scratch Space).
8962        *
8963        * See 3D-Media-GPGPU Engine > Media GPGPU Pipeline >
8964        * Thread Group Tracking > Local Memory/Scratch Space.
8965        */
8966       assert(prog_data->total_scratch < max_scratch_size);
8967    }
8968 
8969    lower_scoreboard();
8970 }
8971 
8972 bool
run_vs()8973 fs_visitor::run_vs()
8974 {
8975    assert(stage == MESA_SHADER_VERTEX);
8976 
8977    setup_vs_payload();
8978 
8979    if (shader_time_index >= 0)
8980       emit_shader_time_begin();
8981 
8982    emit_nir_code();
8983 
8984    if (failed)
8985       return false;
8986 
8987    emit_urb_writes();
8988 
8989    if (shader_time_index >= 0)
8990       emit_shader_time_end();
8991 
8992    calculate_cfg();
8993 
8994    optimize();
8995 
8996    assign_curb_setup();
8997    assign_vs_urb_setup();
8998 
8999    fixup_3src_null_dest();
9000    allocate_registers(true /* allow_spilling */);
9001 
9002    return !failed;
9003 }
9004 
9005 void
set_tcs_invocation_id()9006 fs_visitor::set_tcs_invocation_id()
9007 {
9008    struct brw_tcs_prog_data *tcs_prog_data = brw_tcs_prog_data(prog_data);
9009    struct brw_vue_prog_data *vue_prog_data = &tcs_prog_data->base;
9010 
9011    const unsigned instance_id_mask =
9012       devinfo->ver >= 11 ? INTEL_MASK(22, 16) : INTEL_MASK(23, 17);
9013    const unsigned instance_id_shift =
9014       devinfo->ver >= 11 ? 16 : 17;
9015 
9016    /* Get instance number from g0.2 bits 22:16 or 23:17 */
9017    fs_reg t = bld.vgrf(BRW_REGISTER_TYPE_UD);
9018    bld.AND(t, fs_reg(retype(brw_vec1_grf(0, 2), BRW_REGISTER_TYPE_UD)),
9019            brw_imm_ud(instance_id_mask));
9020 
9021    invocation_id = bld.vgrf(BRW_REGISTER_TYPE_UD);
9022 
9023    if (vue_prog_data->dispatch_mode == DISPATCH_MODE_TCS_8_PATCH) {
9024       /* gl_InvocationID is just the thread number */
9025       bld.SHR(invocation_id, t, brw_imm_ud(instance_id_shift));
9026       return;
9027    }
9028 
9029    assert(vue_prog_data->dispatch_mode == DISPATCH_MODE_TCS_SINGLE_PATCH);
9030 
9031    fs_reg channels_uw = bld.vgrf(BRW_REGISTER_TYPE_UW);
9032    fs_reg channels_ud = bld.vgrf(BRW_REGISTER_TYPE_UD);
9033    bld.MOV(channels_uw, fs_reg(brw_imm_uv(0x76543210)));
9034    bld.MOV(channels_ud, channels_uw);
9035 
9036    if (tcs_prog_data->instances == 1) {
9037       invocation_id = channels_ud;
9038    } else {
9039       fs_reg instance_times_8 = bld.vgrf(BRW_REGISTER_TYPE_UD);
9040       bld.SHR(instance_times_8, t, brw_imm_ud(instance_id_shift - 3));
9041       bld.ADD(invocation_id, instance_times_8, channels_ud);
9042    }
9043 }
9044 
9045 bool
run_tcs()9046 fs_visitor::run_tcs()
9047 {
9048    assert(stage == MESA_SHADER_TESS_CTRL);
9049 
9050    struct brw_vue_prog_data *vue_prog_data = brw_vue_prog_data(prog_data);
9051    struct brw_tcs_prog_data *tcs_prog_data = brw_tcs_prog_data(prog_data);
9052    struct brw_tcs_prog_key *tcs_key = (struct brw_tcs_prog_key *) key;
9053 
9054    assert(vue_prog_data->dispatch_mode == DISPATCH_MODE_TCS_SINGLE_PATCH ||
9055           vue_prog_data->dispatch_mode == DISPATCH_MODE_TCS_8_PATCH);
9056 
9057    if (vue_prog_data->dispatch_mode == DISPATCH_MODE_TCS_SINGLE_PATCH) {
9058       /* r1-r4 contain the ICP handles. */
9059       payload.num_regs = 5;
9060    } else {
9061       assert(vue_prog_data->dispatch_mode == DISPATCH_MODE_TCS_8_PATCH);
9062       assert(tcs_key->input_vertices > 0);
9063       /* r1 contains output handles, r2 may contain primitive ID, then the
9064        * ICP handles occupy the next 1-32 registers.
9065        */
9066       payload.num_regs = 2 + tcs_prog_data->include_primitive_id +
9067                          tcs_key->input_vertices;
9068    }
9069 
9070    if (shader_time_index >= 0)
9071       emit_shader_time_begin();
9072 
9073    /* Initialize gl_InvocationID */
9074    set_tcs_invocation_id();
9075 
9076    const bool fix_dispatch_mask =
9077       vue_prog_data->dispatch_mode == DISPATCH_MODE_TCS_SINGLE_PATCH &&
9078       (nir->info.tess.tcs_vertices_out % 8) != 0;
9079 
9080    /* Fix the disptach mask */
9081    if (fix_dispatch_mask) {
9082       bld.CMP(bld.null_reg_ud(), invocation_id,
9083               brw_imm_ud(nir->info.tess.tcs_vertices_out), BRW_CONDITIONAL_L);
9084       bld.IF(BRW_PREDICATE_NORMAL);
9085    }
9086 
9087    emit_nir_code();
9088 
9089    if (fix_dispatch_mask) {
9090       bld.emit(BRW_OPCODE_ENDIF);
9091    }
9092 
9093    /* Emit EOT write; set TR DS Cache bit */
9094    fs_reg srcs[3] = {
9095       fs_reg(get_tcs_output_urb_handle()),
9096       fs_reg(brw_imm_ud(WRITEMASK_X << 16)),
9097       fs_reg(brw_imm_ud(0)),
9098    };
9099    fs_reg payload = bld.vgrf(BRW_REGISTER_TYPE_UD, 3);
9100    bld.LOAD_PAYLOAD(payload, srcs, 3, 2);
9101 
9102    fs_inst *inst = bld.emit(SHADER_OPCODE_URB_WRITE_SIMD8_MASKED,
9103                             bld.null_reg_ud(), payload);
9104    inst->mlen = 3;
9105    inst->eot = true;
9106 
9107    if (shader_time_index >= 0)
9108       emit_shader_time_end();
9109 
9110    if (failed)
9111       return false;
9112 
9113    calculate_cfg();
9114 
9115    optimize();
9116 
9117    assign_curb_setup();
9118    assign_tcs_urb_setup();
9119 
9120    fixup_3src_null_dest();
9121    allocate_registers(true /* allow_spilling */);
9122 
9123    return !failed;
9124 }
9125 
9126 bool
run_tes()9127 fs_visitor::run_tes()
9128 {
9129    assert(stage == MESA_SHADER_TESS_EVAL);
9130 
9131    /* R0: thread header, R1-3: gl_TessCoord.xyz, R4: URB handles */
9132    payload.num_regs = 5;
9133 
9134    if (shader_time_index >= 0)
9135       emit_shader_time_begin();
9136 
9137    emit_nir_code();
9138 
9139    if (failed)
9140       return false;
9141 
9142    emit_urb_writes();
9143 
9144    if (shader_time_index >= 0)
9145       emit_shader_time_end();
9146 
9147    calculate_cfg();
9148 
9149    optimize();
9150 
9151    assign_curb_setup();
9152    assign_tes_urb_setup();
9153 
9154    fixup_3src_null_dest();
9155    allocate_registers(true /* allow_spilling */);
9156 
9157    return !failed;
9158 }
9159 
9160 bool
run_gs()9161 fs_visitor::run_gs()
9162 {
9163    assert(stage == MESA_SHADER_GEOMETRY);
9164 
9165    setup_gs_payload();
9166 
9167    this->final_gs_vertex_count = vgrf(glsl_type::uint_type);
9168 
9169    if (gs_compile->control_data_header_size_bits > 0) {
9170       /* Create a VGRF to store accumulated control data bits. */
9171       this->control_data_bits = vgrf(glsl_type::uint_type);
9172 
9173       /* If we're outputting more than 32 control data bits, then EmitVertex()
9174        * will set control_data_bits to 0 after emitting the first vertex.
9175        * Otherwise, we need to initialize it to 0 here.
9176        */
9177       if (gs_compile->control_data_header_size_bits <= 32) {
9178          const fs_builder abld = bld.annotate("initialize control data bits");
9179          abld.MOV(this->control_data_bits, brw_imm_ud(0u));
9180       }
9181    }
9182 
9183    if (shader_time_index >= 0)
9184       emit_shader_time_begin();
9185 
9186    emit_nir_code();
9187 
9188    emit_gs_thread_end();
9189 
9190    if (shader_time_index >= 0)
9191       emit_shader_time_end();
9192 
9193    if (failed)
9194       return false;
9195 
9196    calculate_cfg();
9197 
9198    optimize();
9199 
9200    assign_curb_setup();
9201    assign_gs_urb_setup();
9202 
9203    fixup_3src_null_dest();
9204    allocate_registers(true /* allow_spilling */);
9205 
9206    return !failed;
9207 }
9208 
9209 /* From the SKL PRM, Volume 16, Workarounds:
9210  *
9211  *   0877  3D   Pixel Shader Hang possible when pixel shader dispatched with
9212  *              only header phases (R0-R2)
9213  *
9214  *   WA: Enable a non-header phase (e.g. push constant) when dispatch would
9215  *       have been header only.
9216  *
9217  * Instead of enabling push constants one can alternatively enable one of the
9218  * inputs. Here one simply chooses "layer" which shouldn't impose much
9219  * overhead.
9220  */
9221 static void
gfx9_ps_header_only_workaround(struct brw_wm_prog_data * wm_prog_data)9222 gfx9_ps_header_only_workaround(struct brw_wm_prog_data *wm_prog_data)
9223 {
9224    if (wm_prog_data->num_varying_inputs)
9225       return;
9226 
9227    if (wm_prog_data->base.curb_read_length)
9228       return;
9229 
9230    wm_prog_data->urb_setup[VARYING_SLOT_LAYER] = 0;
9231    wm_prog_data->num_varying_inputs = 1;
9232 
9233    brw_compute_urb_setup_index(wm_prog_data);
9234 }
9235 
9236 bool
run_fs(bool allow_spilling,bool do_rep_send)9237 fs_visitor::run_fs(bool allow_spilling, bool do_rep_send)
9238 {
9239    struct brw_wm_prog_data *wm_prog_data = brw_wm_prog_data(this->prog_data);
9240    brw_wm_prog_key *wm_key = (brw_wm_prog_key *) this->key;
9241 
9242    assert(stage == MESA_SHADER_FRAGMENT);
9243 
9244    if (devinfo->ver >= 6)
9245       setup_fs_payload_gfx6();
9246    else
9247       setup_fs_payload_gfx4();
9248 
9249    if (0) {
9250       emit_dummy_fs();
9251    } else if (do_rep_send) {
9252       assert(dispatch_width == 16);
9253       emit_repclear_shader();
9254    } else {
9255       if (shader_time_index >= 0)
9256          emit_shader_time_begin();
9257 
9258       if (nir->info.inputs_read > 0 ||
9259           BITSET_TEST(nir->info.system_values_read, SYSTEM_VALUE_FRAG_COORD) ||
9260           (nir->info.outputs_read > 0 && !wm_key->coherent_fb_fetch)) {
9261          if (devinfo->ver < 6)
9262             emit_interpolation_setup_gfx4();
9263          else
9264             emit_interpolation_setup_gfx6();
9265       }
9266 
9267       /* We handle discards by keeping track of the still-live pixels in f0.1.
9268        * Initialize it with the dispatched pixels.
9269        */
9270       if (wm_prog_data->uses_kill) {
9271          const unsigned lower_width = MIN2(dispatch_width, 16);
9272          for (unsigned i = 0; i < dispatch_width / lower_width; i++) {
9273             const fs_reg dispatch_mask =
9274                devinfo->ver >= 6 ? brw_vec1_grf((i ? 2 : 1), 7) :
9275                brw_vec1_grf(0, 0);
9276             bld.exec_all().group(1, 0)
9277                .MOV(sample_mask_reg(bld.group(lower_width, i)),
9278                     retype(dispatch_mask, BRW_REGISTER_TYPE_UW));
9279          }
9280       }
9281 
9282       if (nir->info.writes_memory)
9283          wm_prog_data->has_side_effects = true;
9284 
9285       emit_nir_code();
9286 
9287       if (failed)
9288 	 return false;
9289 
9290       if (wm_key->alpha_test_func)
9291          emit_alpha_test();
9292 
9293       emit_fb_writes();
9294 
9295       if (shader_time_index >= 0)
9296          emit_shader_time_end();
9297 
9298       calculate_cfg();
9299 
9300       optimize();
9301 
9302       assign_curb_setup();
9303 
9304       if (devinfo->ver >= 9)
9305          gfx9_ps_header_only_workaround(wm_prog_data);
9306 
9307       assign_urb_setup();
9308 
9309       fixup_3src_null_dest();
9310 
9311       allocate_registers(allow_spilling);
9312 
9313       if (failed)
9314          return false;
9315    }
9316 
9317    return !failed;
9318 }
9319 
9320 bool
run_cs(bool allow_spilling)9321 fs_visitor::run_cs(bool allow_spilling)
9322 {
9323    assert(stage == MESA_SHADER_COMPUTE || stage == MESA_SHADER_KERNEL);
9324 
9325    setup_cs_payload();
9326 
9327    if (shader_time_index >= 0)
9328       emit_shader_time_begin();
9329 
9330    if (devinfo->is_haswell && prog_data->total_shared > 0) {
9331       /* Move SLM index from g0.0[27:24] to sr0.1[11:8] */
9332       const fs_builder abld = bld.exec_all().group(1, 0);
9333       abld.MOV(retype(brw_sr0_reg(1), BRW_REGISTER_TYPE_UW),
9334                suboffset(retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_UW), 1));
9335    }
9336 
9337    emit_nir_code();
9338 
9339    if (failed)
9340       return false;
9341 
9342    emit_cs_terminate();
9343 
9344    if (shader_time_index >= 0)
9345       emit_shader_time_end();
9346 
9347    calculate_cfg();
9348 
9349    optimize();
9350 
9351    assign_curb_setup();
9352 
9353    fixup_3src_null_dest();
9354    allocate_registers(allow_spilling);
9355 
9356    if (failed)
9357       return false;
9358 
9359    return !failed;
9360 }
9361 
9362 bool
run_bs(bool allow_spilling)9363 fs_visitor::run_bs(bool allow_spilling)
9364 {
9365    assert(stage >= MESA_SHADER_RAYGEN && stage <= MESA_SHADER_CALLABLE);
9366 
9367    /* R0: thread header, R1: stack IDs, R2: argument addresses */
9368    payload.num_regs = 3;
9369 
9370    if (shader_time_index >= 0)
9371       emit_shader_time_begin();
9372 
9373    emit_nir_code();
9374 
9375    if (failed)
9376       return false;
9377 
9378    /* TODO(RT): Perhaps rename this? */
9379    emit_cs_terminate();
9380 
9381    if (shader_time_index >= 0)
9382       emit_shader_time_end();
9383 
9384    calculate_cfg();
9385 
9386    optimize();
9387 
9388    assign_curb_setup();
9389 
9390    fixup_3src_null_dest();
9391    allocate_registers(allow_spilling);
9392 
9393    if (failed)
9394       return false;
9395 
9396    return !failed;
9397 }
9398 
9399 static bool
is_used_in_not_interp_frag_coord(nir_ssa_def * def)9400 is_used_in_not_interp_frag_coord(nir_ssa_def *def)
9401 {
9402    nir_foreach_use(src, def) {
9403       if (src->parent_instr->type != nir_instr_type_intrinsic)
9404          return true;
9405 
9406       nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(src->parent_instr);
9407       if (intrin->intrinsic != nir_intrinsic_load_frag_coord)
9408          return true;
9409    }
9410 
9411    nir_foreach_if_use(src, def)
9412       return true;
9413 
9414    return false;
9415 }
9416 
9417 /**
9418  * Return a bitfield where bit n is set if barycentric interpolation mode n
9419  * (see enum brw_barycentric_mode) is needed by the fragment shader.
9420  *
9421  * We examine the load_barycentric intrinsics rather than looking at input
9422  * variables so that we catch interpolateAtCentroid() messages too, which
9423  * also need the BRW_BARYCENTRIC_[NON]PERSPECTIVE_CENTROID mode set up.
9424  */
9425 static unsigned
brw_compute_barycentric_interp_modes(const struct intel_device_info * devinfo,const nir_shader * shader)9426 brw_compute_barycentric_interp_modes(const struct intel_device_info *devinfo,
9427                                      const nir_shader *shader)
9428 {
9429    unsigned barycentric_interp_modes = 0;
9430 
9431    nir_foreach_function(f, shader) {
9432       if (!f->impl)
9433          continue;
9434 
9435       nir_foreach_block(block, f->impl) {
9436          nir_foreach_instr(instr, block) {
9437             if (instr->type != nir_instr_type_intrinsic)
9438                continue;
9439 
9440             nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
9441             switch (intrin->intrinsic) {
9442             case nir_intrinsic_load_barycentric_pixel:
9443             case nir_intrinsic_load_barycentric_centroid:
9444             case nir_intrinsic_load_barycentric_sample:
9445                break;
9446             default:
9447                continue;
9448             }
9449 
9450             /* Ignore WPOS; it doesn't require interpolation. */
9451             assert(intrin->dest.is_ssa);
9452             if (!is_used_in_not_interp_frag_coord(&intrin->dest.ssa))
9453                continue;
9454 
9455             enum glsl_interp_mode interp = (enum glsl_interp_mode)
9456                nir_intrinsic_interp_mode(intrin);
9457             nir_intrinsic_op bary_op = intrin->intrinsic;
9458             enum brw_barycentric_mode bary =
9459                brw_barycentric_mode(interp, bary_op);
9460 
9461             barycentric_interp_modes |= 1 << bary;
9462 
9463             if (devinfo->needs_unlit_centroid_workaround &&
9464                 bary_op == nir_intrinsic_load_barycentric_centroid)
9465                barycentric_interp_modes |= 1 << centroid_to_pixel(bary);
9466          }
9467       }
9468    }
9469 
9470    return barycentric_interp_modes;
9471 }
9472 
9473 static void
brw_compute_flat_inputs(struct brw_wm_prog_data * prog_data,const nir_shader * shader)9474 brw_compute_flat_inputs(struct brw_wm_prog_data *prog_data,
9475                         const nir_shader *shader)
9476 {
9477    prog_data->flat_inputs = 0;
9478 
9479    nir_foreach_shader_in_variable(var, shader) {
9480       unsigned slots = glsl_count_attribute_slots(var->type, false);
9481       for (unsigned s = 0; s < slots; s++) {
9482          int input_index = prog_data->urb_setup[var->data.location + s];
9483 
9484          if (input_index < 0)
9485             continue;
9486 
9487          /* flat shading */
9488          if (var->data.interpolation == INTERP_MODE_FLAT)
9489             prog_data->flat_inputs |= 1 << input_index;
9490       }
9491    }
9492 }
9493 
9494 static uint8_t
computed_depth_mode(const nir_shader * shader)9495 computed_depth_mode(const nir_shader *shader)
9496 {
9497    if (shader->info.outputs_written & BITFIELD64_BIT(FRAG_RESULT_DEPTH)) {
9498       switch (shader->info.fs.depth_layout) {
9499       case FRAG_DEPTH_LAYOUT_NONE:
9500       case FRAG_DEPTH_LAYOUT_ANY:
9501          return BRW_PSCDEPTH_ON;
9502       case FRAG_DEPTH_LAYOUT_GREATER:
9503          return BRW_PSCDEPTH_ON_GE;
9504       case FRAG_DEPTH_LAYOUT_LESS:
9505          return BRW_PSCDEPTH_ON_LE;
9506       case FRAG_DEPTH_LAYOUT_UNCHANGED:
9507          return BRW_PSCDEPTH_OFF;
9508       }
9509    }
9510    return BRW_PSCDEPTH_OFF;
9511 }
9512 
9513 /**
9514  * Move load_interpolated_input with simple (payload-based) barycentric modes
9515  * to the top of the program so we don't emit multiple PLNs for the same input.
9516  *
9517  * This works around CSE not being able to handle non-dominating cases
9518  * such as:
9519  *
9520  *    if (...) {
9521  *       interpolate input
9522  *    } else {
9523  *       interpolate the same exact input
9524  *    }
9525  *
9526  * This should be replaced by global value numbering someday.
9527  */
9528 bool
brw_nir_move_interpolation_to_top(nir_shader * nir)9529 brw_nir_move_interpolation_to_top(nir_shader *nir)
9530 {
9531    bool progress = false;
9532 
9533    nir_foreach_function(f, nir) {
9534       if (!f->impl)
9535          continue;
9536 
9537       nir_block *top = nir_start_block(f->impl);
9538       exec_node *cursor_node = NULL;
9539 
9540       nir_foreach_block(block, f->impl) {
9541          if (block == top)
9542             continue;
9543 
9544          nir_foreach_instr_safe(instr, block) {
9545             if (instr->type != nir_instr_type_intrinsic)
9546                continue;
9547 
9548             nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
9549             if (intrin->intrinsic != nir_intrinsic_load_interpolated_input)
9550                continue;
9551             nir_intrinsic_instr *bary_intrinsic =
9552                nir_instr_as_intrinsic(intrin->src[0].ssa->parent_instr);
9553             nir_intrinsic_op op = bary_intrinsic->intrinsic;
9554 
9555             /* Leave interpolateAtSample/Offset() where they are. */
9556             if (op == nir_intrinsic_load_barycentric_at_sample ||
9557                 op == nir_intrinsic_load_barycentric_at_offset)
9558                continue;
9559 
9560             nir_instr *move[3] = {
9561                &bary_intrinsic->instr,
9562                intrin->src[1].ssa->parent_instr,
9563                instr
9564             };
9565 
9566             for (unsigned i = 0; i < ARRAY_SIZE(move); i++) {
9567                if (move[i]->block != top) {
9568                   move[i]->block = top;
9569                   exec_node_remove(&move[i]->node);
9570                   if (cursor_node) {
9571                      exec_node_insert_after(cursor_node, &move[i]->node);
9572                   } else {
9573                      exec_list_push_head(&top->instr_list, &move[i]->node);
9574                   }
9575                   cursor_node = &move[i]->node;
9576                   progress = true;
9577                }
9578             }
9579          }
9580       }
9581       nir_metadata_preserve(f->impl, nir_metadata_block_index |
9582                                      nir_metadata_dominance);
9583    }
9584 
9585    return progress;
9586 }
9587 
9588 static bool
brw_nir_demote_sample_qualifiers_instr(nir_builder * b,nir_instr * instr,UNUSED void * cb_data)9589 brw_nir_demote_sample_qualifiers_instr(nir_builder *b,
9590                                        nir_instr *instr,
9591                                        UNUSED void *cb_data)
9592 {
9593    if (instr->type != nir_instr_type_intrinsic)
9594       return false;
9595 
9596    nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
9597    if (intrin->intrinsic != nir_intrinsic_load_barycentric_sample &&
9598        intrin->intrinsic != nir_intrinsic_load_barycentric_at_sample)
9599       return false;
9600 
9601    b->cursor = nir_before_instr(instr);
9602    nir_ssa_def *centroid =
9603       nir_load_barycentric(b, nir_intrinsic_load_barycentric_centroid,
9604                            nir_intrinsic_interp_mode(intrin));
9605    nir_ssa_def_rewrite_uses(&intrin->dest.ssa, centroid);
9606    nir_instr_remove(instr);
9607    return true;
9608 }
9609 
9610 /**
9611  * Demote per-sample barycentric intrinsics to centroid.
9612  *
9613  * Useful when rendering to a non-multisampled buffer.
9614  */
9615 bool
brw_nir_demote_sample_qualifiers(nir_shader * nir)9616 brw_nir_demote_sample_qualifiers(nir_shader *nir)
9617 {
9618    return nir_shader_instructions_pass(nir,
9619                                        brw_nir_demote_sample_qualifiers_instr,
9620                                        nir_metadata_block_index |
9621                                        nir_metadata_dominance,
9622                                        NULL);
9623 }
9624 
9625 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)9626 brw_nir_populate_wm_prog_data(const nir_shader *shader,
9627                               const struct intel_device_info *devinfo,
9628                               const struct brw_wm_prog_key *key,
9629                               struct brw_wm_prog_data *prog_data)
9630 {
9631    /* key->alpha_test_func means simulating alpha testing via discards,
9632     * so the shader definitely kills pixels.
9633     */
9634    prog_data->uses_kill = shader->info.fs.uses_discard ||
9635       key->alpha_test_func;
9636    prog_data->uses_omask = !key->ignore_sample_mask_out &&
9637       (shader->info.outputs_written & BITFIELD64_BIT(FRAG_RESULT_SAMPLE_MASK));
9638    prog_data->computed_depth_mode = computed_depth_mode(shader);
9639    prog_data->computed_stencil =
9640       shader->info.outputs_written & BITFIELD64_BIT(FRAG_RESULT_STENCIL);
9641 
9642    prog_data->persample_dispatch =
9643       key->multisample_fbo &&
9644       (key->persample_interp ||
9645        BITSET_TEST(shader->info.system_values_read, SYSTEM_VALUE_SAMPLE_ID) ||
9646        BITSET_TEST(shader->info.system_values_read, SYSTEM_VALUE_SAMPLE_POS) ||
9647        shader->info.fs.uses_sample_qualifier ||
9648        shader->info.outputs_read);
9649 
9650    if (devinfo->ver >= 6) {
9651       prog_data->uses_sample_mask =
9652          BITSET_TEST(shader->info.system_values_read, SYSTEM_VALUE_SAMPLE_MASK_IN);
9653 
9654       /* From the Ivy Bridge PRM documentation for 3DSTATE_PS:
9655        *
9656        *    "MSDISPMODE_PERSAMPLE is required in order to select
9657        *    POSOFFSET_SAMPLE"
9658        *
9659        * So we can only really get sample positions if we are doing real
9660        * per-sample dispatch.  If we need gl_SamplePosition and we don't have
9661        * persample dispatch, we hard-code it to 0.5.
9662        */
9663       prog_data->uses_pos_offset = prog_data->persample_dispatch &&
9664          BITSET_TEST(shader->info.system_values_read, SYSTEM_VALUE_SAMPLE_POS);
9665    }
9666 
9667    prog_data->has_render_target_reads = shader->info.outputs_read != 0ull;
9668 
9669    prog_data->early_fragment_tests = shader->info.fs.early_fragment_tests;
9670    prog_data->post_depth_coverage = shader->info.fs.post_depth_coverage;
9671    prog_data->inner_coverage = shader->info.fs.inner_coverage;
9672 
9673    prog_data->barycentric_interp_modes =
9674       brw_compute_barycentric_interp_modes(devinfo, shader);
9675 
9676    prog_data->per_coarse_pixel_dispatch =
9677       key->coarse_pixel &&
9678       !prog_data->uses_omask &&
9679       !prog_data->persample_dispatch &&
9680       !prog_data->uses_sample_mask &&
9681       (prog_data->computed_depth_mode == BRW_PSCDEPTH_OFF) &&
9682       !prog_data->computed_stencil;
9683 
9684    prog_data->uses_src_w =
9685       BITSET_TEST(shader->info.system_values_read, SYSTEM_VALUE_FRAG_COORD);
9686    prog_data->uses_src_depth =
9687       BITSET_TEST(shader->info.system_values_read, SYSTEM_VALUE_FRAG_COORD) &&
9688       !prog_data->per_coarse_pixel_dispatch;
9689    prog_data->uses_depth_w_coefficients =
9690       BITSET_TEST(shader->info.system_values_read, SYSTEM_VALUE_FRAG_COORD) &&
9691       prog_data->per_coarse_pixel_dispatch;
9692 
9693    calculate_urb_setup(devinfo, key, prog_data, shader);
9694    brw_compute_flat_inputs(prog_data, shader);
9695 }
9696 
9697 /**
9698  * Pre-gfx6, the register file of the EUs was shared between threads,
9699  * and each thread used some subset allocated on a 16-register block
9700  * granularity.  The unit states wanted these block counts.
9701  */
9702 static inline int
brw_register_blocks(int reg_count)9703 brw_register_blocks(int reg_count)
9704 {
9705    return ALIGN(reg_count, 16) / 16 - 1;
9706 }
9707 
9708 const unsigned *
brw_compile_fs(const struct brw_compiler * compiler,void * mem_ctx,struct brw_compile_fs_params * params)9709 brw_compile_fs(const struct brw_compiler *compiler,
9710                void *mem_ctx,
9711                struct brw_compile_fs_params *params)
9712 {
9713    struct nir_shader *nir = params->nir;
9714    const struct brw_wm_prog_key *key = params->key;
9715    struct brw_wm_prog_data *prog_data = params->prog_data;
9716    bool allow_spilling = params->allow_spilling;
9717    const bool debug_enabled =
9718       INTEL_DEBUG(params->debug_flag ? params->debug_flag : DEBUG_WM);
9719 
9720    prog_data->base.stage = MESA_SHADER_FRAGMENT;
9721 
9722    const struct intel_device_info *devinfo = compiler->devinfo;
9723    const unsigned max_subgroup_size = compiler->devinfo->ver >= 6 ? 32 : 16;
9724 
9725    brw_nir_apply_key(nir, compiler, &key->base, max_subgroup_size, true);
9726    brw_nir_lower_fs_inputs(nir, devinfo, key);
9727    brw_nir_lower_fs_outputs(nir);
9728 
9729    if (devinfo->ver < 6)
9730       brw_setup_vue_interpolation(params->vue_map, nir, prog_data);
9731 
9732    /* From the SKL PRM, Volume 7, "Alpha Coverage":
9733     *  "If Pixel Shader outputs oMask, AlphaToCoverage is disabled in
9734     *   hardware, regardless of the state setting for this feature."
9735     */
9736    if (devinfo->ver > 6 && key->alpha_to_coverage) {
9737       /* Run constant fold optimization in order to get the correct source
9738        * offset to determine render target 0 store instruction in
9739        * emit_alpha_to_coverage pass.
9740        */
9741       NIR_PASS_V(nir, nir_opt_constant_folding);
9742       NIR_PASS_V(nir, brw_nir_lower_alpha_to_coverage);
9743    }
9744 
9745    if (!key->multisample_fbo)
9746       NIR_PASS_V(nir, brw_nir_demote_sample_qualifiers);
9747    NIR_PASS_V(nir, brw_nir_move_interpolation_to_top);
9748    brw_postprocess_nir(nir, compiler, true, debug_enabled,
9749                        key->base.robust_buffer_access);
9750 
9751    brw_nir_populate_wm_prog_data(nir, compiler->devinfo, key, prog_data);
9752 
9753    fs_visitor *v8 = NULL, *v16 = NULL, *v32 = NULL;
9754    cfg_t *simd8_cfg = NULL, *simd16_cfg = NULL, *simd32_cfg = NULL;
9755    float throughput = 0;
9756    bool has_spilled = false;
9757 
9758    v8 = new fs_visitor(compiler, params->log_data, mem_ctx, &key->base,
9759                        &prog_data->base, nir, 8,
9760                        params->shader_time ? params->shader_time_index8 : -1,
9761                        debug_enabled);
9762    if (!v8->run_fs(allow_spilling, false /* do_rep_send */)) {
9763       params->error_str = ralloc_strdup(mem_ctx, v8->fail_msg);
9764       delete v8;
9765       return NULL;
9766    } else if (!INTEL_DEBUG(DEBUG_NO8)) {
9767       simd8_cfg = v8->cfg;
9768       prog_data->base.dispatch_grf_start_reg = v8->payload.num_regs;
9769       prog_data->reg_blocks_8 = brw_register_blocks(v8->grf_used);
9770       const performance &perf = v8->performance_analysis.require();
9771       throughput = MAX2(throughput, perf.throughput);
9772       has_spilled = v8->spilled_any_registers;
9773       allow_spilling = false;
9774    }
9775 
9776    /* Limit dispatch width to simd8 with dual source blending on gfx8.
9777     * See: https://gitlab.freedesktop.org/mesa/mesa/-/issues/1917
9778     */
9779    if (devinfo->ver == 8 && prog_data->dual_src_blend &&
9780        !INTEL_DEBUG(DEBUG_NO8)) {
9781       assert(!params->use_rep_send);
9782       v8->limit_dispatch_width(8, "gfx8 workaround: "
9783                                "using SIMD8 when dual src blending.\n");
9784    }
9785 
9786    if (key->coarse_pixel) {
9787       if (prog_data->dual_src_blend) {
9788          v8->limit_dispatch_width(8, "SIMD16 coarse pixel shading cannot"
9789                                   " use SIMD8 messages.\n");
9790       }
9791       v8->limit_dispatch_width(16, "SIMD32 not supported with coarse"
9792                                " pixel shading.\n");
9793    }
9794 
9795    if (!has_spilled &&
9796        v8->max_dispatch_width >= 16 &&
9797        (!INTEL_DEBUG(DEBUG_NO16) || params->use_rep_send)) {
9798       /* Try a SIMD16 compile */
9799       v16 = new fs_visitor(compiler, params->log_data, mem_ctx, &key->base,
9800                            &prog_data->base, nir, 16,
9801                            params->shader_time ? params->shader_time_index16 : -1,
9802                            debug_enabled);
9803       v16->import_uniforms(v8);
9804       if (!v16->run_fs(allow_spilling, params->use_rep_send)) {
9805          brw_shader_perf_log(compiler, params->log_data,
9806                              "SIMD16 shader failed to compile: %s\n",
9807                              v16->fail_msg);
9808       } else {
9809          simd16_cfg = v16->cfg;
9810          prog_data->dispatch_grf_start_reg_16 = v16->payload.num_regs;
9811          prog_data->reg_blocks_16 = brw_register_blocks(v16->grf_used);
9812          const performance &perf = v16->performance_analysis.require();
9813          throughput = MAX2(throughput, perf.throughput);
9814          has_spilled = v16->spilled_any_registers;
9815          allow_spilling = false;
9816       }
9817    }
9818 
9819    const bool simd16_failed = v16 && !simd16_cfg;
9820 
9821    /* Currently, the compiler only supports SIMD32 on SNB+ */
9822    if (!has_spilled &&
9823        v8->max_dispatch_width >= 32 && !params->use_rep_send &&
9824        devinfo->ver >= 6 && !simd16_failed &&
9825        !INTEL_DEBUG(DEBUG_NO32)) {
9826       /* Try a SIMD32 compile */
9827       v32 = new fs_visitor(compiler, params->log_data, mem_ctx, &key->base,
9828                            &prog_data->base, nir, 32,
9829                            params->shader_time ? params->shader_time_index32 : -1,
9830                            debug_enabled);
9831       v32->import_uniforms(v8);
9832       if (!v32->run_fs(allow_spilling, false)) {
9833          brw_shader_perf_log(compiler, params->log_data,
9834                              "SIMD32 shader failed to compile: %s\n",
9835                              v32->fail_msg);
9836       } else {
9837          const performance &perf = v32->performance_analysis.require();
9838 
9839          if (!INTEL_DEBUG(DEBUG_DO32) && throughput >= perf.throughput) {
9840             brw_shader_perf_log(compiler, params->log_data,
9841                                 "SIMD32 shader inefficient\n");
9842          } else {
9843             simd32_cfg = v32->cfg;
9844             prog_data->dispatch_grf_start_reg_32 = v32->payload.num_regs;
9845             prog_data->reg_blocks_32 = brw_register_blocks(v32->grf_used);
9846             throughput = MAX2(throughput, perf.throughput);
9847          }
9848       }
9849    }
9850 
9851    /* When the caller requests a repclear shader, they want SIMD16-only */
9852    if (params->use_rep_send)
9853       simd8_cfg = NULL;
9854 
9855    /* Prior to Iron Lake, the PS had a single shader offset with a jump table
9856     * at the top to select the shader.  We've never implemented that.
9857     * Instead, we just give them exactly one shader and we pick the widest one
9858     * available.
9859     */
9860    if (compiler->devinfo->ver < 5) {
9861       if (simd32_cfg || simd16_cfg)
9862          simd8_cfg = NULL;
9863       if (simd32_cfg)
9864          simd16_cfg = NULL;
9865    }
9866 
9867    /* If computed depth is enabled SNB only allows SIMD8. */
9868    if (compiler->devinfo->ver == 6 &&
9869        prog_data->computed_depth_mode != BRW_PSCDEPTH_OFF)
9870       assert(simd16_cfg == NULL && simd32_cfg == NULL);
9871 
9872    if (compiler->devinfo->ver <= 5 && !simd8_cfg) {
9873       /* Iron lake and earlier only have one Dispatch GRF start field.  Make
9874        * the data available in the base prog data struct for convenience.
9875        */
9876       if (simd16_cfg) {
9877          prog_data->base.dispatch_grf_start_reg =
9878             prog_data->dispatch_grf_start_reg_16;
9879       } else if (simd32_cfg) {
9880          prog_data->base.dispatch_grf_start_reg =
9881             prog_data->dispatch_grf_start_reg_32;
9882       }
9883    }
9884 
9885    if (prog_data->persample_dispatch) {
9886       /* Starting with SandyBridge (where we first get MSAA), the different
9887        * pixel dispatch combinations are grouped into classifications A
9888        * through F (SNB PRM Vol. 2 Part 1 Section 7.7.1).  On most hardware
9889        * generations, the only configurations supporting persample dispatch
9890        * are those in which only one dispatch width is enabled.
9891        *
9892        * The Gfx12 hardware spec has a similar dispatch grouping table, but
9893        * the following conflicting restriction applies (from the page on
9894        * "Structure_3DSTATE_PS_BODY"), so we need to keep the SIMD16 shader:
9895        *
9896        *  "SIMD32 may only be enabled if SIMD16 or (dual)SIMD8 is also
9897        *   enabled."
9898        */
9899       if (simd32_cfg || simd16_cfg)
9900          simd8_cfg = NULL;
9901       if (simd32_cfg && devinfo->ver < 12)
9902          simd16_cfg = NULL;
9903    }
9904 
9905    fs_generator g(compiler, params->log_data, mem_ctx, &prog_data->base,
9906                   v8->runtime_check_aads_emit, MESA_SHADER_FRAGMENT);
9907 
9908    if (unlikely(debug_enabled)) {
9909       g.enable_debug(ralloc_asprintf(mem_ctx, "%s fragment shader %s",
9910                                      nir->info.label ?
9911                                         nir->info.label : "unnamed",
9912                                      nir->info.name));
9913    }
9914 
9915    struct brw_compile_stats *stats = params->stats;
9916 
9917    if (simd8_cfg) {
9918       prog_data->dispatch_8 = true;
9919       g.generate_code(simd8_cfg, 8, v8->shader_stats,
9920                       v8->performance_analysis.require(), stats);
9921       stats = stats ? stats + 1 : NULL;
9922    }
9923 
9924    if (simd16_cfg) {
9925       prog_data->dispatch_16 = true;
9926       prog_data->prog_offset_16 = g.generate_code(
9927          simd16_cfg, 16, v16->shader_stats,
9928          v16->performance_analysis.require(), stats);
9929       stats = stats ? stats + 1 : NULL;
9930    }
9931 
9932    if (simd32_cfg) {
9933       prog_data->dispatch_32 = true;
9934       prog_data->prog_offset_32 = g.generate_code(
9935          simd32_cfg, 32, v32->shader_stats,
9936          v32->performance_analysis.require(), stats);
9937       stats = stats ? stats + 1 : NULL;
9938    }
9939 
9940    g.add_const_data(nir->constant_data, nir->constant_data_size);
9941 
9942    delete v8;
9943    delete v16;
9944    delete v32;
9945 
9946    return g.get_assembly();
9947 }
9948 
9949 fs_reg *
emit_cs_work_group_id_setup()9950 fs_visitor::emit_cs_work_group_id_setup()
9951 {
9952    assert(stage == MESA_SHADER_COMPUTE || stage == MESA_SHADER_KERNEL);
9953 
9954    fs_reg *reg = new(this->mem_ctx) fs_reg(vgrf(glsl_type::uvec3_type));
9955 
9956    struct brw_reg r0_1(retype(brw_vec1_grf(0, 1), BRW_REGISTER_TYPE_UD));
9957    struct brw_reg r0_6(retype(brw_vec1_grf(0, 6), BRW_REGISTER_TYPE_UD));
9958    struct brw_reg r0_7(retype(brw_vec1_grf(0, 7), BRW_REGISTER_TYPE_UD));
9959 
9960    bld.MOV(*reg, r0_1);
9961    bld.MOV(offset(*reg, bld, 1), r0_6);
9962    bld.MOV(offset(*reg, bld, 2), r0_7);
9963 
9964    return reg;
9965 }
9966 
9967 unsigned
brw_cs_push_const_total_size(const struct brw_cs_prog_data * cs_prog_data,unsigned threads)9968 brw_cs_push_const_total_size(const struct brw_cs_prog_data *cs_prog_data,
9969                              unsigned threads)
9970 {
9971    assert(cs_prog_data->push.per_thread.size % REG_SIZE == 0);
9972    assert(cs_prog_data->push.cross_thread.size % REG_SIZE == 0);
9973    return cs_prog_data->push.per_thread.size * threads +
9974           cs_prog_data->push.cross_thread.size;
9975 }
9976 
9977 static void
fill_push_const_block_info(struct brw_push_const_block * block,unsigned dwords)9978 fill_push_const_block_info(struct brw_push_const_block *block, unsigned dwords)
9979 {
9980    block->dwords = dwords;
9981    block->regs = DIV_ROUND_UP(dwords, 8);
9982    block->size = block->regs * 32;
9983 }
9984 
9985 static void
cs_fill_push_const_info(const struct intel_device_info * devinfo,struct brw_cs_prog_data * cs_prog_data)9986 cs_fill_push_const_info(const struct intel_device_info *devinfo,
9987                         struct brw_cs_prog_data *cs_prog_data)
9988 {
9989    const struct brw_stage_prog_data *prog_data = &cs_prog_data->base;
9990    int subgroup_id_index = get_subgroup_id_param_index(devinfo, prog_data);
9991    bool cross_thread_supported = devinfo->verx10 >= 75;
9992 
9993    /* The thread ID should be stored in the last param dword */
9994    assert(subgroup_id_index == -1 ||
9995           subgroup_id_index == (int)prog_data->nr_params - 1);
9996 
9997    unsigned cross_thread_dwords, per_thread_dwords;
9998    if (!cross_thread_supported) {
9999       cross_thread_dwords = 0u;
10000       per_thread_dwords = prog_data->nr_params;
10001    } else if (subgroup_id_index >= 0) {
10002       /* Fill all but the last register with cross-thread payload */
10003       cross_thread_dwords = 8 * (subgroup_id_index / 8);
10004       per_thread_dwords = prog_data->nr_params - cross_thread_dwords;
10005       assert(per_thread_dwords > 0 && per_thread_dwords <= 8);
10006    } else {
10007       /* Fill all data using cross-thread payload */
10008       cross_thread_dwords = prog_data->nr_params;
10009       per_thread_dwords = 0u;
10010    }
10011 
10012    fill_push_const_block_info(&cs_prog_data->push.cross_thread, cross_thread_dwords);
10013    fill_push_const_block_info(&cs_prog_data->push.per_thread, per_thread_dwords);
10014 
10015    assert(cs_prog_data->push.cross_thread.dwords % 8 == 0 ||
10016           cs_prog_data->push.per_thread.size == 0);
10017    assert(cs_prog_data->push.cross_thread.dwords +
10018           cs_prog_data->push.per_thread.dwords ==
10019              prog_data->nr_params);
10020 }
10021 
10022 static bool
filter_simd(const nir_instr * instr,const void *)10023 filter_simd(const nir_instr *instr, const void * /* options */)
10024 {
10025    if (instr->type != nir_instr_type_intrinsic)
10026       return false;
10027 
10028    switch (nir_instr_as_intrinsic(instr)->intrinsic) {
10029    case nir_intrinsic_load_simd_width_intel:
10030    case nir_intrinsic_load_subgroup_id:
10031       return true;
10032 
10033    default:
10034       return false;
10035    }
10036 }
10037 
10038 static nir_ssa_def *
lower_simd(nir_builder * b,nir_instr * instr,void * options)10039 lower_simd(nir_builder *b, nir_instr *instr, void *options)
10040 {
10041    uintptr_t simd_width = (uintptr_t)options;
10042 
10043    switch (nir_instr_as_intrinsic(instr)->intrinsic) {
10044    case nir_intrinsic_load_simd_width_intel:
10045       return nir_imm_int(b, simd_width);
10046 
10047    case nir_intrinsic_load_subgroup_id:
10048       /* If the whole workgroup fits in one thread, we can lower subgroup_id
10049        * to a constant zero.
10050        */
10051       if (!b->shader->info.workgroup_size_variable) {
10052          unsigned local_workgroup_size = b->shader->info.workgroup_size[0] *
10053                                          b->shader->info.workgroup_size[1] *
10054                                          b->shader->info.workgroup_size[2];
10055          if (local_workgroup_size <= simd_width)
10056             return nir_imm_int(b, 0);
10057       }
10058       return NULL;
10059 
10060    default:
10061       return NULL;
10062    }
10063 }
10064 
10065 static void
brw_nir_lower_simd(nir_shader * nir,unsigned dispatch_width)10066 brw_nir_lower_simd(nir_shader *nir, unsigned dispatch_width)
10067 {
10068    nir_shader_lower_instructions(nir, filter_simd, lower_simd,
10069                                  (void *)(uintptr_t)dispatch_width);
10070 }
10071 
10072 static nir_shader *
compile_cs_to_nir(const struct brw_compiler * compiler,void * mem_ctx,const struct brw_cs_prog_key * key,const nir_shader * src_shader,unsigned dispatch_width,bool debug_enabled)10073 compile_cs_to_nir(const struct brw_compiler *compiler,
10074                   void *mem_ctx,
10075                   const struct brw_cs_prog_key *key,
10076                   const nir_shader *src_shader,
10077                   unsigned dispatch_width,
10078                   bool debug_enabled)
10079 {
10080    nir_shader *shader = nir_shader_clone(mem_ctx, src_shader);
10081    brw_nir_apply_key(shader, compiler, &key->base, dispatch_width, true);
10082 
10083    NIR_PASS_V(shader, brw_nir_lower_simd, dispatch_width);
10084 
10085    /* Clean up after the local index and ID calculations. */
10086    NIR_PASS_V(shader, nir_opt_constant_folding);
10087    NIR_PASS_V(shader, nir_opt_dce);
10088 
10089    brw_postprocess_nir(shader, compiler, true, debug_enabled,
10090                        key->base.robust_buffer_access);
10091 
10092    return shader;
10093 }
10094 
10095 const unsigned *
brw_compile_cs(const struct brw_compiler * compiler,void * mem_ctx,struct brw_compile_cs_params * params)10096 brw_compile_cs(const struct brw_compiler *compiler,
10097                void *mem_ctx,
10098                struct brw_compile_cs_params *params)
10099 {
10100    const nir_shader *nir = params->nir;
10101    const struct brw_cs_prog_key *key = params->key;
10102    struct brw_cs_prog_data *prog_data = params->prog_data;
10103    int shader_time_index = params->shader_time ? params->shader_time_index : -1;
10104 
10105    const bool debug_enabled =
10106       INTEL_DEBUG(params->debug_flag ? params->debug_flag : DEBUG_CS);
10107 
10108    prog_data->base.stage = MESA_SHADER_COMPUTE;
10109    prog_data->base.total_shared = nir->info.shared_size;
10110 
10111    /* Generate code for all the possible SIMD variants. */
10112    bool generate_all;
10113 
10114    unsigned min_dispatch_width;
10115    unsigned max_dispatch_width;
10116 
10117    if (nir->info.workgroup_size_variable) {
10118       generate_all = true;
10119       min_dispatch_width = 8;
10120       max_dispatch_width = 32;
10121    } else {
10122       generate_all = false;
10123       prog_data->local_size[0] = nir->info.workgroup_size[0];
10124       prog_data->local_size[1] = nir->info.workgroup_size[1];
10125       prog_data->local_size[2] = nir->info.workgroup_size[2];
10126       unsigned local_workgroup_size = prog_data->local_size[0] *
10127                                       prog_data->local_size[1] *
10128                                       prog_data->local_size[2];
10129 
10130       /* Limit max_threads to 64 for the GPGPU_WALKER command */
10131       const uint32_t max_threads = compiler->devinfo->max_cs_workgroup_threads;
10132       min_dispatch_width = util_next_power_of_two(
10133          MAX2(8, DIV_ROUND_UP(local_workgroup_size, max_threads)));
10134       assert(min_dispatch_width <= 32);
10135       max_dispatch_width = 32;
10136    }
10137 
10138    unsigned required_dispatch_width = 0;
10139    if ((int)key->base.subgroup_size_type >= (int)BRW_SUBGROUP_SIZE_REQUIRE_8) {
10140       /* These enum values are expressly chosen to be equal to the subgroup
10141        * size that they require.
10142        */
10143       required_dispatch_width = (unsigned)key->base.subgroup_size_type;
10144    }
10145 
10146    if (nir->info.cs.subgroup_size > 0) {
10147       assert(required_dispatch_width == 0 ||
10148              required_dispatch_width == nir->info.cs.subgroup_size);
10149       required_dispatch_width = nir->info.cs.subgroup_size;
10150    }
10151 
10152    if (required_dispatch_width > 0) {
10153       assert(required_dispatch_width == 8 ||
10154              required_dispatch_width == 16 ||
10155              required_dispatch_width == 32);
10156       if (required_dispatch_width < min_dispatch_width ||
10157           required_dispatch_width > max_dispatch_width) {
10158          params->error_str = ralloc_strdup(mem_ctx,
10159                                            "Cannot satisfy explicit subgroup size");
10160          return NULL;
10161       }
10162       min_dispatch_width = max_dispatch_width = required_dispatch_width;
10163    }
10164 
10165    assert(min_dispatch_width <= max_dispatch_width);
10166 
10167    fs_visitor *v8 = NULL, *v16 = NULL, *v32 = NULL;
10168    fs_visitor *v = NULL;
10169 
10170    if (!INTEL_DEBUG(DEBUG_NO8) &&
10171        min_dispatch_width <= 8 && max_dispatch_width >= 8) {
10172       nir_shader *nir8 = compile_cs_to_nir(compiler, mem_ctx, key,
10173                                            nir, 8, debug_enabled);
10174       v8 = new fs_visitor(compiler, params->log_data, mem_ctx, &key->base,
10175                           &prog_data->base,
10176                           nir8, 8, shader_time_index, debug_enabled);
10177       if (!v8->run_cs(true /* allow_spilling */)) {
10178          params->error_str = ralloc_strdup(mem_ctx, v8->fail_msg);
10179          delete v8;
10180          return NULL;
10181       }
10182 
10183       /* We should always be able to do SIMD32 for compute shaders */
10184       assert(v8->max_dispatch_width >= 32);
10185 
10186       v = v8;
10187       prog_data->prog_mask |= 1 << 0;
10188       if (v8->spilled_any_registers)
10189          prog_data->prog_spilled |= 1 << 0;
10190       cs_fill_push_const_info(compiler->devinfo, prog_data);
10191    }
10192 
10193    if (!INTEL_DEBUG(DEBUG_NO16) &&
10194        (generate_all || !prog_data->prog_spilled) &&
10195        min_dispatch_width <= 16 && max_dispatch_width >= 16) {
10196       /* Try a SIMD16 compile */
10197       nir_shader *nir16 = compile_cs_to_nir(compiler, mem_ctx, key,
10198                                             nir, 16, debug_enabled);
10199       v16 = new fs_visitor(compiler, params->log_data, mem_ctx, &key->base,
10200                            &prog_data->base,
10201                            nir16, 16, shader_time_index, debug_enabled);
10202       if (v8)
10203          v16->import_uniforms(v8);
10204 
10205       const bool allow_spilling = generate_all || v == NULL;
10206       if (!v16->run_cs(allow_spilling)) {
10207          brw_shader_perf_log(compiler, params->log_data,
10208                              "SIMD16 shader failed to compile: %s\n",
10209                              v16->fail_msg);
10210          if (!v) {
10211             assert(v8 == NULL);
10212             params->error_str = ralloc_asprintf(
10213                mem_ctx, "Not enough threads for SIMD8 and "
10214                "couldn't generate SIMD16: %s", v16->fail_msg);
10215             delete v16;
10216             return NULL;
10217          }
10218       } else {
10219          /* We should always be able to do SIMD32 for compute shaders */
10220          assert(v16->max_dispatch_width >= 32);
10221 
10222          v = v16;
10223          prog_data->prog_mask |= 1 << 1;
10224          if (v16->spilled_any_registers)
10225             prog_data->prog_spilled |= 1 << 1;
10226          cs_fill_push_const_info(compiler->devinfo, prog_data);
10227       }
10228    }
10229 
10230    /* The SIMD32 is only enabled for cases it is needed unless forced.
10231     *
10232     * TODO: Use performance_analysis and drop this boolean.
10233     */
10234    const bool needs_32 = v == NULL ||
10235                          INTEL_DEBUG(DEBUG_DO32) ||
10236                          generate_all;
10237 
10238    if (!INTEL_DEBUG(DEBUG_NO32) &&
10239        (generate_all || !prog_data->prog_spilled) &&
10240        needs_32 &&
10241        min_dispatch_width <= 32 && max_dispatch_width >= 32) {
10242       /* Try a SIMD32 compile */
10243       nir_shader *nir32 = compile_cs_to_nir(compiler, mem_ctx, key,
10244                                             nir, 32, debug_enabled);
10245       v32 = new fs_visitor(compiler, params->log_data, mem_ctx, &key->base,
10246                            &prog_data->base,
10247                            nir32, 32, shader_time_index, debug_enabled);
10248       if (v8)
10249          v32->import_uniforms(v8);
10250       else if (v16)
10251          v32->import_uniforms(v16);
10252 
10253       const bool allow_spilling = generate_all || v == NULL;
10254       if (!v32->run_cs(allow_spilling)) {
10255          brw_shader_perf_log(compiler, params->log_data,
10256                              "SIMD32 shader failed to compile: %s\n",
10257                              v32->fail_msg);
10258          if (!v) {
10259             assert(v8 == NULL);
10260             assert(v16 == NULL);
10261             params->error_str = ralloc_asprintf(
10262                mem_ctx, "Not enough threads for SIMD16 and "
10263                "couldn't generate SIMD32: %s", v32->fail_msg);
10264             delete v32;
10265             return NULL;
10266          }
10267       } else {
10268          v = v32;
10269          prog_data->prog_mask |= 1 << 2;
10270          if (v32->spilled_any_registers)
10271             prog_data->prog_spilled |= 1 << 2;
10272          cs_fill_push_const_info(compiler->devinfo, prog_data);
10273       }
10274    }
10275 
10276    if (unlikely(!v) && INTEL_DEBUG(DEBUG_NO8 | DEBUG_NO16 | DEBUG_NO32)) {
10277       params->error_str =
10278          ralloc_strdup(mem_ctx,
10279                        "Cannot satisfy INTEL_DEBUG flags SIMD restrictions");
10280       return NULL;
10281    }
10282 
10283    assert(v);
10284 
10285    const unsigned *ret = NULL;
10286 
10287    fs_generator g(compiler, params->log_data, mem_ctx, &prog_data->base,
10288                   v->runtime_check_aads_emit, MESA_SHADER_COMPUTE);
10289    if (unlikely(debug_enabled)) {
10290       char *name = ralloc_asprintf(mem_ctx, "%s compute shader %s",
10291                                    nir->info.label ?
10292                                    nir->info.label : "unnamed",
10293                                    nir->info.name);
10294       g.enable_debug(name);
10295    }
10296 
10297    struct brw_compile_stats *stats = params->stats;
10298    if (generate_all) {
10299       if (prog_data->prog_mask & (1 << 0)) {
10300          assert(v8);
10301          prog_data->prog_offset[0] =
10302             g.generate_code(v8->cfg, 8, v8->shader_stats,
10303                             v8->performance_analysis.require(), stats);
10304          stats = stats ? stats + 1 : NULL;
10305       }
10306 
10307       if (prog_data->prog_mask & (1 << 1)) {
10308          assert(v16);
10309          prog_data->prog_offset[1] =
10310             g.generate_code(v16->cfg, 16, v16->shader_stats,
10311                             v16->performance_analysis.require(), stats);
10312          stats = stats ? stats + 1 : NULL;
10313       }
10314 
10315       if (prog_data->prog_mask & (1 << 2)) {
10316          assert(v32);
10317          prog_data->prog_offset[2] =
10318             g.generate_code(v32->cfg, 32, v32->shader_stats,
10319                             v32->performance_analysis.require(), stats);
10320          stats = stats ? stats + 1 : NULL;
10321       }
10322    } else {
10323       /* Only one dispatch width will be valid, and will be at offset 0,
10324        * which is already the default value of prog_offset_* fields.
10325        */
10326       prog_data->prog_mask = 1 << (v->dispatch_width / 16);
10327       g.generate_code(v->cfg, v->dispatch_width, v->shader_stats,
10328                       v->performance_analysis.require(), stats);
10329    }
10330 
10331    g.add_const_data(nir->constant_data, nir->constant_data_size);
10332 
10333    ret = g.get_assembly();
10334 
10335    delete v8;
10336    delete v16;
10337    delete v32;
10338 
10339    return ret;
10340 }
10341 
10342 static unsigned
brw_cs_simd_size_for_group_size(const struct intel_device_info * devinfo,const struct brw_cs_prog_data * cs_prog_data,unsigned group_size)10343 brw_cs_simd_size_for_group_size(const struct intel_device_info *devinfo,
10344                                 const struct brw_cs_prog_data *cs_prog_data,
10345                                 unsigned group_size)
10346 {
10347    const unsigned mask = cs_prog_data->prog_mask;
10348    assert(mask != 0);
10349 
10350    static const unsigned simd8  = 1 << 0;
10351    static const unsigned simd16 = 1 << 1;
10352    static const unsigned simd32 = 1 << 2;
10353 
10354    if (INTEL_DEBUG(DEBUG_DO32) && (mask & simd32))
10355       return 32;
10356 
10357    const uint32_t max_threads = devinfo->max_cs_workgroup_threads;
10358 
10359    if ((mask & simd8) && group_size <= 8 * max_threads) {
10360       /* Prefer SIMD16 if can do without spilling.  Matches logic in
10361        * brw_compile_cs.
10362        */
10363       if ((mask & simd16) && (~cs_prog_data->prog_spilled & simd16))
10364          return 16;
10365       return 8;
10366    }
10367 
10368    if ((mask & simd16) && group_size <= 16 * max_threads)
10369       return 16;
10370 
10371    assert(mask & simd32);
10372    assert(group_size <= 32 * max_threads);
10373    return 32;
10374 }
10375 
10376 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)10377 brw_cs_get_dispatch_info(const struct intel_device_info *devinfo,
10378                          const struct brw_cs_prog_data *prog_data,
10379                          const unsigned *override_local_size)
10380 {
10381    struct brw_cs_dispatch_info info = {};
10382 
10383    const unsigned *sizes =
10384       override_local_size ? override_local_size :
10385                             prog_data->local_size;
10386 
10387    info.group_size = sizes[0] * sizes[1] * sizes[2];
10388    info.simd_size =
10389       brw_cs_simd_size_for_group_size(devinfo, prog_data, info.group_size);
10390    info.threads = DIV_ROUND_UP(info.group_size, info.simd_size);
10391 
10392    const uint32_t remainder = info.group_size & (info.simd_size - 1);
10393    if (remainder > 0)
10394       info.right_mask = ~0u >> (32 - remainder);
10395    else
10396       info.right_mask = ~0u >> (32 - info.simd_size);
10397 
10398    return info;
10399 }
10400 
10401 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)10402 compile_single_bs(const struct brw_compiler *compiler, void *log_data,
10403                   void *mem_ctx,
10404                   const struct brw_bs_prog_key *key,
10405                   struct brw_bs_prog_data *prog_data,
10406                   nir_shader *shader,
10407                   fs_generator *g,
10408                   struct brw_compile_stats *stats,
10409                   int *prog_offset,
10410                   char **error_str)
10411 {
10412    const bool debug_enabled = INTEL_DEBUG(DEBUG_RT);
10413 
10414    prog_data->base.stage = shader->info.stage;
10415    prog_data->max_stack_size = MAX2(prog_data->max_stack_size,
10416                                     shader->scratch_size);
10417 
10418    const unsigned max_dispatch_width = 16;
10419    brw_nir_apply_key(shader, compiler, &key->base, max_dispatch_width, true);
10420    brw_postprocess_nir(shader, compiler, true, debug_enabled,
10421                        key->base.robust_buffer_access);
10422 
10423    fs_visitor *v = NULL, *v8 = NULL, *v16 = NULL;
10424    bool has_spilled = false;
10425 
10426    uint8_t simd_size = 0;
10427    if (!INTEL_DEBUG(DEBUG_NO8)) {
10428       v8 = new fs_visitor(compiler, log_data, mem_ctx, &key->base,
10429                           &prog_data->base, shader,
10430                           8, -1 /* shader time */, debug_enabled);
10431       const bool allow_spilling = true;
10432       if (!v8->run_bs(allow_spilling)) {
10433          if (error_str)
10434             *error_str = ralloc_strdup(mem_ctx, v8->fail_msg);
10435          delete v8;
10436          return 0;
10437       } else {
10438          v = v8;
10439          simd_size = 8;
10440          if (v8->spilled_any_registers)
10441             has_spilled = true;
10442       }
10443    }
10444 
10445    if (!has_spilled && !INTEL_DEBUG(DEBUG_NO16)) {
10446       v16 = new fs_visitor(compiler, log_data, mem_ctx, &key->base,
10447                            &prog_data->base, shader,
10448                            16, -1 /* shader time */, debug_enabled);
10449       const bool allow_spilling = (v == NULL);
10450       if (!v16->run_bs(allow_spilling)) {
10451          brw_shader_perf_log(compiler, log_data,
10452                              "SIMD16 shader failed to compile: %s\n",
10453                              v16->fail_msg);
10454          if (v == NULL) {
10455             assert(v8 == NULL);
10456             if (error_str) {
10457                *error_str = ralloc_asprintf(
10458                   mem_ctx, "SIMD8 disabled and couldn't generate SIMD16: %s",
10459                   v16->fail_msg);
10460             }
10461             delete v16;
10462             return 0;
10463          }
10464       } else {
10465          v = v16;
10466          simd_size = 16;
10467          if (v16->spilled_any_registers)
10468             has_spilled = true;
10469       }
10470    }
10471 
10472    if (unlikely(v == NULL)) {
10473       assert(INTEL_DEBUG(DEBUG_NO8 | DEBUG_NO16));
10474       if (error_str) {
10475          *error_str = ralloc_strdup(mem_ctx,
10476             "Cannot satisfy INTEL_DEBUG flags SIMD restrictions");
10477       }
10478       return false;
10479    }
10480 
10481    assert(v);
10482 
10483    int offset = g->generate_code(v->cfg, simd_size, v->shader_stats,
10484                                  v->performance_analysis.require(), stats);
10485    if (prog_offset)
10486       *prog_offset = offset;
10487    else
10488       assert(offset == 0);
10489 
10490    delete v8;
10491    delete v16;
10492 
10493    return simd_size;
10494 }
10495 
10496 uint64_t
brw_bsr(const struct intel_device_info * devinfo,uint32_t offset,uint8_t simd_size,uint8_t local_arg_offset)10497 brw_bsr(const struct intel_device_info *devinfo,
10498         uint32_t offset, uint8_t simd_size, uint8_t local_arg_offset)
10499 {
10500    assert(offset % 64 == 0);
10501    assert(simd_size == 8 || simd_size == 16);
10502    assert(local_arg_offset % 8 == 0);
10503 
10504    return offset |
10505           SET_BITS(simd_size > 8, 4, 4) |
10506           SET_BITS(local_arg_offset / 8, 2, 0);
10507 }
10508 
10509 const unsigned *
brw_compile_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,unsigned num_resume_shaders,struct nir_shader ** resume_shaders,struct brw_compile_stats * stats,char ** error_str)10510 brw_compile_bs(const struct brw_compiler *compiler, void *log_data,
10511                void *mem_ctx,
10512                const struct brw_bs_prog_key *key,
10513                struct brw_bs_prog_data *prog_data,
10514                nir_shader *shader,
10515                unsigned num_resume_shaders,
10516                struct nir_shader **resume_shaders,
10517                struct brw_compile_stats *stats,
10518                char **error_str)
10519 {
10520    const bool debug_enabled = INTEL_DEBUG(DEBUG_RT);
10521 
10522    prog_data->base.stage = shader->info.stage;
10523    prog_data->max_stack_size = 0;
10524 
10525    fs_generator g(compiler, log_data, mem_ctx, &prog_data->base,
10526                   false, shader->info.stage);
10527    if (unlikely(debug_enabled)) {
10528       char *name = ralloc_asprintf(mem_ctx, "%s %s shader %s",
10529                                    shader->info.label ?
10530                                       shader->info.label : "unnamed",
10531                                    gl_shader_stage_name(shader->info.stage),
10532                                    shader->info.name);
10533       g.enable_debug(name);
10534    }
10535 
10536    prog_data->simd_size =
10537       compile_single_bs(compiler, log_data, mem_ctx, key, prog_data,
10538                         shader, &g, stats, NULL, error_str);
10539    if (prog_data->simd_size == 0)
10540       return NULL;
10541 
10542    uint64_t *resume_sbt = ralloc_array(mem_ctx, uint64_t, num_resume_shaders);
10543    for (unsigned i = 0; i < num_resume_shaders; i++) {
10544       if (INTEL_DEBUG(DEBUG_RT)) {
10545          char *name = ralloc_asprintf(mem_ctx, "%s %s resume(%u) shader %s",
10546                                       shader->info.label ?
10547                                          shader->info.label : "unnamed",
10548                                       gl_shader_stage_name(shader->info.stage),
10549                                       i, shader->info.name);
10550          g.enable_debug(name);
10551       }
10552 
10553       /* TODO: Figure out shader stats etc. for resume shaders */
10554       int offset = 0;
10555       uint8_t simd_size =
10556          compile_single_bs(compiler, log_data, mem_ctx, key, prog_data,
10557                            resume_shaders[i], &g, NULL, &offset, error_str);
10558       if (simd_size == 0)
10559          return NULL;
10560 
10561       assert(offset > 0);
10562       resume_sbt[i] = brw_bsr(compiler->devinfo, offset, simd_size, 0);
10563    }
10564 
10565    /* We only have one constant data so we want to make sure they're all the
10566     * same.
10567     */
10568    for (unsigned i = 0; i < num_resume_shaders; i++) {
10569       assert(resume_shaders[i]->constant_data_size ==
10570              shader->constant_data_size);
10571       assert(memcmp(resume_shaders[i]->constant_data,
10572                     shader->constant_data,
10573                     shader->constant_data_size) == 0);
10574    }
10575 
10576    g.add_const_data(shader->constant_data, shader->constant_data_size);
10577    g.add_resume_sbt(num_resume_shaders, resume_sbt);
10578 
10579    return g.get_assembly();
10580 }
10581 
10582 /**
10583  * Test the dispatch mask packing assumptions of
10584  * brw_stage_has_packed_dispatch().  Call this from e.g. the top of
10585  * fs_visitor::emit_nir_code() to cause a GPU hang if any shader invocation is
10586  * executed with an unexpected dispatch mask.
10587  */
10588 static UNUSED void
brw_fs_test_dispatch_packing(const fs_builder & bld)10589 brw_fs_test_dispatch_packing(const fs_builder &bld)
10590 {
10591    const gl_shader_stage stage = bld.shader->stage;
10592 
10593    if (brw_stage_has_packed_dispatch(bld.shader->devinfo, stage,
10594                                      bld.shader->stage_prog_data)) {
10595       const fs_builder ubld = bld.exec_all().group(1, 0);
10596       const fs_reg tmp = component(bld.vgrf(BRW_REGISTER_TYPE_UD), 0);
10597       const fs_reg mask = (stage == MESA_SHADER_FRAGMENT ? brw_vmask_reg() :
10598                            brw_dmask_reg());
10599 
10600       ubld.ADD(tmp, mask, brw_imm_ud(1));
10601       ubld.AND(tmp, mask, tmp);
10602 
10603       /* This will loop forever if the dispatch mask doesn't have the expected
10604        * form '2^n-1', in which case tmp will be non-zero.
10605        */
10606       bld.emit(BRW_OPCODE_DO);
10607       bld.CMP(bld.null_reg_ud(), tmp, brw_imm_ud(0), BRW_CONDITIONAL_NZ);
10608       set_predicate(BRW_PREDICATE_NORMAL, bld.emit(BRW_OPCODE_WHILE));
10609    }
10610 }
10611 
10612 unsigned
workgroup_size() const10613 fs_visitor::workgroup_size() const
10614 {
10615    assert(stage == MESA_SHADER_COMPUTE);
10616    const struct brw_cs_prog_data *cs = brw_cs_prog_data(prog_data);
10617    return cs->local_size[0] * cs->local_size[1] * cs->local_size[2];
10618 }
10619