2 * Copyright © 2010 Intel Corporation
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:
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
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
26 * This file drives the GLSL IR -> LIR translation, contains the
27 * optimizations on the LIR, and drives the generation of native code
31 #include "main/macros.h"
35 #include "brw_vec4_gs_visitor.h"
37 #include "brw_dead_control_flow.h"
38 #include "common/gen_debug.h"
39 #include "compiler/glsl_types.h"
40 #include "compiler/nir/nir_builder.h"
41 #include "program/prog_parameter.h"
45 static unsigned get_lowered_simd_width(const struct gen_device_info *devinfo,
49 fs_inst::init(enum opcode opcode, uint8_t exec_size, const fs_reg &dst,
50 const fs_reg *src, unsigned sources)
52 memset(this, 0, sizeof(*this));
54 this->src = new fs_reg[MAX2(sources, 3)];
55 for (unsigned i = 0; i < sources; i++)
56 this->src[i] = src[i];
58 this->opcode = opcode;
60 this->sources = sources;
61 this->exec_size = exec_size;
64 assert(dst.file != IMM && dst.file != UNIFORM);
66 assert(this->exec_size != 0);
68 this->conditional_mod = BRW_CONDITIONAL_NONE;
70 /* This will be the case for almost all instructions. */
77 this->size_written = dst.component_size(exec_size);
80 this->size_written = 0;
84 unreachable("Invalid destination register file");
87 this->writes_accumulator = false;
92 init(BRW_OPCODE_NOP, 8, dst, NULL, 0);
95 fs_inst::fs_inst(enum opcode opcode, uint8_t exec_size)
97 init(opcode, exec_size, reg_undef, NULL, 0);
100 fs_inst::fs_inst(enum opcode opcode, uint8_t exec_size, const fs_reg &dst)
102 init(opcode, exec_size, dst, NULL, 0);
105 fs_inst::fs_inst(enum opcode opcode, uint8_t exec_size, const fs_reg &dst,
108 const fs_reg src[1] = { src0 };
109 init(opcode, exec_size, dst, src, 1);
112 fs_inst::fs_inst(enum opcode opcode, uint8_t exec_size, const fs_reg &dst,
113 const fs_reg &src0, const fs_reg &src1)
115 const fs_reg src[2] = { src0, src1 };
116 init(opcode, exec_size, dst, src, 2);
119 fs_inst::fs_inst(enum opcode opcode, uint8_t exec_size, const fs_reg &dst,
120 const fs_reg &src0, const fs_reg &src1, const fs_reg &src2)
122 const fs_reg src[3] = { src0, src1, src2 };
123 init(opcode, exec_size, dst, src, 3);
126 fs_inst::fs_inst(enum opcode opcode, uint8_t exec_width, const fs_reg &dst,
127 const fs_reg src[], unsigned sources)
129 init(opcode, exec_width, dst, src, sources);
132 fs_inst::fs_inst(const fs_inst &that)
134 memcpy(this, &that, sizeof(that));
136 this->src = new fs_reg[MAX2(that.sources, 3)];
138 for (unsigned i = 0; i < that.sources; i++)
139 this->src[i] = that.src[i];
148 fs_inst::resize_sources(uint8_t num_sources)
150 if (this->sources != num_sources) {
151 fs_reg *src = new fs_reg[MAX2(num_sources, 3)];
153 for (unsigned i = 0; i < MIN2(this->sources, num_sources); ++i)
154 src[i] = this->src[i];
158 this->sources = num_sources;
163 fs_visitor::VARYING_PULL_CONSTANT_LOAD(const fs_builder &bld,
165 const fs_reg &surf_index,
166 const fs_reg &varying_offset,
167 uint32_t const_offset)
169 /* We have our constant surface use a pitch of 4 bytes, so our index can
170 * be any component of a vector, and then we load 4 contiguous
171 * components starting from that.
173 * We break down the const_offset to a portion added to the variable offset
174 * and a portion done using fs_reg::offset, which means that if you have
175 * GLSL using something like "uniform vec4 a[20]; gl_FragColor = a[i]",
176 * we'll temporarily generate 4 vec4 loads from offset i * 4, and CSE can
177 * later notice that those loads are all the same and eliminate the
180 fs_reg vec4_offset = vgrf(glsl_type::uint_type);
181 bld.ADD(vec4_offset, varying_offset, brw_imm_ud(const_offset & ~0xf));
183 /* The pull load message will load a vec4 (16 bytes). If we are loading
184 * a double this means we are only loading 2 elements worth of data.
185 * We also want to use a 32-bit data type for the dst of the load operation
186 * so other parts of the driver don't get confused about the size of the
189 fs_reg vec4_result = bld.vgrf(BRW_REGISTER_TYPE_F, 4);
190 fs_inst *inst = bld.emit(FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_LOGICAL,
191 vec4_result, surf_index, vec4_offset);
192 inst->size_written = 4 * vec4_result.component_size(inst->exec_size);
194 shuffle_from_32bit_read(bld, dst, vec4_result,
195 (const_offset & 0xf) / type_sz(dst.type), 1);
199 * A helper for MOV generation for fixing up broken hardware SEND dependency
203 fs_visitor::DEP_RESOLVE_MOV(const fs_builder &bld, int grf)
205 /* The caller always wants uncompressed to emit the minimal extra
206 * dependencies, and to avoid having to deal with aligning its regs to 2.
208 const fs_builder ubld = bld.annotate("send dependency resolve")
211 ubld.MOV(ubld.null_reg_f(), fs_reg(VGRF, grf, BRW_REGISTER_TYPE_F));
215 fs_inst::equals(fs_inst *inst) const
217 return (opcode == inst->opcode &&
218 dst.equals(inst->dst) &&
219 src[0].equals(inst->src[0]) &&
220 src[1].equals(inst->src[1]) &&
221 src[2].equals(inst->src[2]) &&
222 saturate == inst->saturate &&
223 predicate == inst->predicate &&
224 conditional_mod == inst->conditional_mod &&
225 mlen == inst->mlen &&
226 base_mrf == inst->base_mrf &&
227 target == inst->target &&
229 header_size == inst->header_size &&
230 shadow_compare == inst->shadow_compare &&
231 exec_size == inst->exec_size &&
232 offset == inst->offset);
236 fs_inst::is_send_from_grf() const
239 case FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_GEN7:
240 case SHADER_OPCODE_SHADER_TIME_ADD:
241 case FS_OPCODE_INTERPOLATE_AT_SAMPLE:
242 case FS_OPCODE_INTERPOLATE_AT_SHARED_OFFSET:
243 case FS_OPCODE_INTERPOLATE_AT_PER_SLOT_OFFSET:
244 case SHADER_OPCODE_UNTYPED_ATOMIC:
245 case SHADER_OPCODE_UNTYPED_SURFACE_READ:
246 case SHADER_OPCODE_UNTYPED_SURFACE_WRITE:
247 case SHADER_OPCODE_BYTE_SCATTERED_WRITE:
248 case SHADER_OPCODE_BYTE_SCATTERED_READ:
249 case SHADER_OPCODE_TYPED_ATOMIC:
250 case SHADER_OPCODE_TYPED_SURFACE_READ:
251 case SHADER_OPCODE_TYPED_SURFACE_WRITE:
252 case SHADER_OPCODE_URB_WRITE_SIMD8:
253 case SHADER_OPCODE_URB_WRITE_SIMD8_PER_SLOT:
254 case SHADER_OPCODE_URB_WRITE_SIMD8_MASKED:
255 case SHADER_OPCODE_URB_WRITE_SIMD8_MASKED_PER_SLOT:
256 case SHADER_OPCODE_URB_READ_SIMD8:
257 case SHADER_OPCODE_URB_READ_SIMD8_PER_SLOT:
259 case FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD:
260 return src[1].file == VGRF;
261 case FS_OPCODE_FB_WRITE:
262 case FS_OPCODE_FB_READ:
263 return src[0].file == VGRF;
266 return src[0].file == VGRF;
273 * Returns true if this instruction's sources and destinations cannot
274 * safely be the same register.
276 * In most cases, a register can be written over safely by the same
277 * instruction that is its last use. For a single instruction, the
278 * sources are dereferenced before writing of the destination starts
281 * However, there are a few cases where this can be problematic:
283 * - Virtual opcodes that translate to multiple instructions in the
284 * code generator: if src == dst and one instruction writes the
285 * destination before a later instruction reads the source, then
286 * src will have been clobbered.
288 * - SIMD16 compressed instructions with certain regioning (see below).
290 * The register allocator uses this information to set up conflicts between
291 * GRF sources and the destination.
294 fs_inst::has_source_and_destination_hazard() const
297 case FS_OPCODE_PACK_HALF_2x16_SPLIT:
298 /* Multiple partial writes to the destination */
300 case SHADER_OPCODE_SHUFFLE:
301 /* This instruction returns an arbitrary channel from the source and
302 * gets split into smaller instructions in the generator. It's possible
303 * that one of the instructions will read from a channel corresponding
304 * to an earlier instruction.
306 case SHADER_OPCODE_SEL_EXEC:
307 /* This is implemented as
309 * mov(16) g4<1>D 0D { align1 WE_all 1H };
310 * mov(16) g4<1>D g5<8,8,1>D { align1 1H }
312 * Because the source is only read in the second instruction, the first
313 * may stomp all over it.
317 /* The SIMD16 compressed instruction
319 * add(16) g4<1>F g4<8,8,1>F g6<8,8,1>F
321 * is actually decoded in hardware as:
323 * add(8) g4<1>F g4<8,8,1>F g6<8,8,1>F
324 * add(8) g5<1>F g5<8,8,1>F g7<8,8,1>F
326 * Which is safe. However, if we have uniform accesses
327 * happening, we get into trouble:
329 * add(8) g4<1>F g4<0,1,0>F g6<8,8,1>F
330 * add(8) g5<1>F g4<0,1,0>F g7<8,8,1>F
332 * Now our destination for the first instruction overwrote the
333 * second instruction's src0, and we get garbage for those 8
334 * pixels. There's a similar issue for the pre-gen6
335 * pixel_x/pixel_y, which are registers of 16-bit values and thus
336 * would get stomped by the first decode as well.
338 if (exec_size == 16) {
339 for (int i = 0; i < sources; i++) {
340 if (src[i].file == VGRF && (src[i].stride == 0 ||
341 src[i].type == BRW_REGISTER_TYPE_UW ||
342 src[i].type == BRW_REGISTER_TYPE_W ||
343 src[i].type == BRW_REGISTER_TYPE_UB ||
344 src[i].type == BRW_REGISTER_TYPE_B)) {
354 fs_inst::is_copy_payload(const brw::simple_allocator &grf_alloc) const
356 if (this->opcode != SHADER_OPCODE_LOAD_PAYLOAD)
359 fs_reg reg = this->src[0];
360 if (reg.file != VGRF || reg.offset != 0 || reg.stride != 1)
363 if (grf_alloc.sizes[reg.nr] * REG_SIZE != this->size_written)
366 for (int i = 0; i < this->sources; i++) {
367 reg.type = this->src[i].type;
368 if (!this->src[i].equals(reg))
371 if (i < this->header_size) {
372 reg.offset += REG_SIZE;
374 reg = horiz_offset(reg, this->exec_size);
382 fs_inst::can_do_source_mods(const struct gen_device_info *devinfo)
384 if (devinfo->gen == 6 && is_math())
387 if (is_send_from_grf())
390 if (!backend_instruction::can_do_source_mods())
397 fs_inst::can_change_types() const
399 return dst.type == src[0].type &&
400 !src[0].abs && !src[0].negate && !saturate &&
401 (opcode == BRW_OPCODE_MOV ||
402 (opcode == BRW_OPCODE_SEL &&
403 dst.type == src[1].type &&
404 predicate != BRW_PREDICATE_NONE &&
405 !src[1].abs && !src[1].negate));
411 memset(this, 0, sizeof(*this));
412 type = BRW_REGISTER_TYPE_UD;
416 /** Generic unset register constructor. */
420 this->file = BAD_FILE;
423 fs_reg::fs_reg(struct ::brw_reg reg) :
428 if (this->file == IMM &&
429 (this->type != BRW_REGISTER_TYPE_V &&
430 this->type != BRW_REGISTER_TYPE_UV &&
431 this->type != BRW_REGISTER_TYPE_VF)) {
437 fs_reg::equals(const fs_reg &r) const
439 return (this->backend_reg::equals(r) &&
444 fs_reg::negative_equals(const fs_reg &r) const
446 return (this->backend_reg::negative_equals(r) &&
451 fs_reg::is_contiguous() const
457 fs_reg::component_size(unsigned width) const
459 const unsigned stride = ((file != ARF && file != FIXED_GRF) ? this->stride :
462 return MAX2(width * stride, 1) * type_sz(type);
466 type_size_scalar(const struct glsl_type *type)
468 unsigned int size, i;
470 switch (type->base_type) {
473 case GLSL_TYPE_FLOAT:
475 return type->components();
476 case GLSL_TYPE_UINT16:
477 case GLSL_TYPE_INT16:
478 case GLSL_TYPE_FLOAT16:
479 return DIV_ROUND_UP(type->components(), 2);
480 case GLSL_TYPE_UINT8:
482 return DIV_ROUND_UP(type->components(), 4);
483 case GLSL_TYPE_DOUBLE:
484 case GLSL_TYPE_UINT64:
485 case GLSL_TYPE_INT64:
486 return type->components() * 2;
487 case GLSL_TYPE_ARRAY:
488 return type_size_scalar(type->fields.array) * type->length;
489 case GLSL_TYPE_STRUCT:
491 for (i = 0; i < type->length; i++) {
492 size += type_size_scalar(type->fields.structure[i].type);
495 case GLSL_TYPE_SAMPLER:
496 /* Samplers take up no register space, since they're baked in at
500 case GLSL_TYPE_ATOMIC_UINT:
502 case GLSL_TYPE_SUBROUTINE:
504 case GLSL_TYPE_IMAGE:
505 return BRW_IMAGE_PARAM_SIZE;
507 case GLSL_TYPE_ERROR:
508 case GLSL_TYPE_INTERFACE:
509 case GLSL_TYPE_FUNCTION:
510 unreachable("not reached");
517 * Create a MOV to read the timestamp register.
519 * The caller is responsible for emitting the MOV. The return value is
520 * the destination of the MOV, with extra parameters set.
523 fs_visitor::get_timestamp(const fs_builder &bld)
525 assert(devinfo->gen >= 7);
527 fs_reg ts = fs_reg(retype(brw_vec4_reg(BRW_ARCHITECTURE_REGISTER_FILE,
530 BRW_REGISTER_TYPE_UD));
532 fs_reg dst = fs_reg(VGRF, alloc.allocate(1), BRW_REGISTER_TYPE_UD);
534 /* We want to read the 3 fields we care about even if it's not enabled in
537 bld.group(4, 0).exec_all().MOV(dst, ts);
543 fs_visitor::emit_shader_time_begin()
545 /* We want only the low 32 bits of the timestamp. Since it's running
546 * at the GPU clock rate of ~1.2ghz, it will roll over every ~3 seconds,
547 * which is plenty of time for our purposes. It is identical across the
548 * EUs, but since it's tracking GPU core speed it will increment at a
549 * varying rate as render P-states change.
551 shader_start_time = component(
552 get_timestamp(bld.annotate("shader time start")), 0);
556 fs_visitor::emit_shader_time_end()
558 /* Insert our code just before the final SEND with EOT. */
559 exec_node *end = this->instructions.get_tail();
560 assert(end && ((fs_inst *) end)->eot);
561 const fs_builder ibld = bld.annotate("shader time end")
562 .exec_all().at(NULL, end);
563 const fs_reg timestamp = get_timestamp(ibld);
565 /* We only use the low 32 bits of the timestamp - see
566 * emit_shader_time_begin()).
568 * We could also check if render P-states have changed (or anything
569 * else that might disrupt timing) by setting smear to 2 and checking if
570 * that field is != 0.
572 const fs_reg shader_end_time = component(timestamp, 0);
574 /* Check that there weren't any timestamp reset events (assuming these
575 * were the only two timestamp reads that happened).
577 const fs_reg reset = component(timestamp, 2);
578 set_condmod(BRW_CONDITIONAL_Z,
579 ibld.AND(ibld.null_reg_ud(), reset, brw_imm_ud(1u)));
580 ibld.IF(BRW_PREDICATE_NORMAL);
582 fs_reg start = shader_start_time;
584 const fs_reg diff = component(fs_reg(VGRF, alloc.allocate(1),
585 BRW_REGISTER_TYPE_UD),
587 const fs_builder cbld = ibld.group(1, 0);
588 cbld.group(1, 0).ADD(diff, start, shader_end_time);
590 /* If there were no instructions between the two timestamp gets, the diff
591 * is 2 cycles. Remove that overhead, so I can forget about that when
592 * trying to determine the time taken for single instructions.
594 cbld.ADD(diff, diff, brw_imm_ud(-2u));
595 SHADER_TIME_ADD(cbld, 0, diff);
596 SHADER_TIME_ADD(cbld, 1, brw_imm_ud(1u));
597 ibld.emit(BRW_OPCODE_ELSE);
598 SHADER_TIME_ADD(cbld, 2, brw_imm_ud(1u));
599 ibld.emit(BRW_OPCODE_ENDIF);
603 fs_visitor::SHADER_TIME_ADD(const fs_builder &bld,
604 int shader_time_subindex,
607 int index = shader_time_index * 3 + shader_time_subindex;
608 struct brw_reg offset = brw_imm_d(index * BRW_SHADER_TIME_STRIDE);
611 if (dispatch_width == 8)
612 payload = vgrf(glsl_type::uvec2_type);
614 payload = vgrf(glsl_type::uint_type);
616 bld.emit(SHADER_OPCODE_SHADER_TIME_ADD, fs_reg(), payload, offset, value);
620 fs_visitor::vfail(const char *format, va_list va)
629 msg = ralloc_vasprintf(mem_ctx, format, va);
630 msg = ralloc_asprintf(mem_ctx, "%s compile failed: %s\n", stage_abbrev, msg);
632 this->fail_msg = msg;
635 fprintf(stderr, "%s", msg);
640 fs_visitor::fail(const char *format, ...)
644 va_start(va, format);
650 * Mark this program as impossible to compile with dispatch width greater
653 * During the SIMD8 compile (which happens first), we can detect and flag
654 * things that are unsupported in SIMD16+ mode, so the compiler can skip the
655 * SIMD16+ compile altogether.
657 * During a compile of dispatch width greater than n (if one happens anyway),
658 * this just calls fail().
661 fs_visitor::limit_dispatch_width(unsigned n, const char *msg)
663 if (dispatch_width > n) {
666 max_dispatch_width = n;
667 compiler->shader_perf_log(log_data,
668 "Shader dispatch width limited to SIMD%d: %s",
674 * Returns true if the instruction has a flag that means it won't
675 * update an entire destination register.
677 * For example, dead code elimination and live variable analysis want to know
678 * when a write to a variable screens off any preceding values that were in
682 fs_inst::is_partial_write() const
684 return ((this->predicate && this->opcode != BRW_OPCODE_SEL) ||
685 (this->exec_size * type_sz(this->dst.type)) < 32 ||
686 !this->dst.is_contiguous() ||
687 this->dst.offset % REG_SIZE != 0);
691 fs_inst::components_read(unsigned i) const
693 /* Return zero if the source is not present. */
694 if (src[i].file == BAD_FILE)
698 case FS_OPCODE_LINTERP:
704 case FS_OPCODE_PIXEL_X:
705 case FS_OPCODE_PIXEL_Y:
709 case FS_OPCODE_FB_WRITE_LOGICAL:
710 assert(src[FB_WRITE_LOGICAL_SRC_COMPONENTS].file == IMM);
711 /* First/second FB write color. */
713 return src[FB_WRITE_LOGICAL_SRC_COMPONENTS].ud;
717 case SHADER_OPCODE_TEX_LOGICAL:
718 case SHADER_OPCODE_TXD_LOGICAL:
719 case SHADER_OPCODE_TXF_LOGICAL:
720 case SHADER_OPCODE_TXL_LOGICAL:
721 case SHADER_OPCODE_TXS_LOGICAL:
722 case FS_OPCODE_TXB_LOGICAL:
723 case SHADER_OPCODE_TXF_CMS_LOGICAL:
724 case SHADER_OPCODE_TXF_CMS_W_LOGICAL:
725 case SHADER_OPCODE_TXF_UMS_LOGICAL:
726 case SHADER_OPCODE_TXF_MCS_LOGICAL:
727 case SHADER_OPCODE_LOD_LOGICAL:
728 case SHADER_OPCODE_TG4_LOGICAL:
729 case SHADER_OPCODE_TG4_OFFSET_LOGICAL:
730 case SHADER_OPCODE_SAMPLEINFO_LOGICAL:
731 assert(src[TEX_LOGICAL_SRC_COORD_COMPONENTS].file == IMM &&
732 src[TEX_LOGICAL_SRC_GRAD_COMPONENTS].file == IMM);
733 /* Texture coordinates. */
734 if (i == TEX_LOGICAL_SRC_COORDINATE)
735 return src[TEX_LOGICAL_SRC_COORD_COMPONENTS].ud;
736 /* Texture derivatives. */
737 else if ((i == TEX_LOGICAL_SRC_LOD || i == TEX_LOGICAL_SRC_LOD2) &&
738 opcode == SHADER_OPCODE_TXD_LOGICAL)
739 return src[TEX_LOGICAL_SRC_GRAD_COMPONENTS].ud;
740 /* Texture offset. */
741 else if (i == TEX_LOGICAL_SRC_TG4_OFFSET)
744 else if (i == TEX_LOGICAL_SRC_MCS && opcode == SHADER_OPCODE_TXF_CMS_W_LOGICAL)
749 case SHADER_OPCODE_UNTYPED_SURFACE_READ_LOGICAL:
750 case SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL:
751 assert(src[3].file == IMM);
752 /* Surface coordinates. */
755 /* Surface operation source (ignored for reads). */
761 case SHADER_OPCODE_UNTYPED_SURFACE_WRITE_LOGICAL:
762 case SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL:
763 assert(src[3].file == IMM &&
765 /* Surface coordinates. */
768 /* Surface operation source. */
774 case SHADER_OPCODE_BYTE_SCATTERED_READ_LOGICAL:
775 /* Scattered logical opcodes use the following params:
776 * src[0] Surface coordinates
777 * src[1] Surface operation source (ignored for reads)
779 * src[3] IMM with always 1 dimension.
780 * src[4] IMM with arg bitsize for scattered read/write 8, 16, 32
782 assert(src[3].file == IMM &&
784 return i == 1 ? 0 : 1;
786 case SHADER_OPCODE_BYTE_SCATTERED_WRITE_LOGICAL:
787 assert(src[3].file == IMM &&
791 case SHADER_OPCODE_UNTYPED_ATOMIC_LOGICAL:
792 case SHADER_OPCODE_TYPED_ATOMIC_LOGICAL: {
793 assert(src[3].file == IMM &&
795 const unsigned op = src[4].ud;
796 /* Surface coordinates. */
799 /* Surface operation source. */
800 else if (i == 1 && op == BRW_AOP_CMPWR)
802 else if (i == 1 && (op == BRW_AOP_INC || op == BRW_AOP_DEC ||
803 op == BRW_AOP_PREDEC))
808 case FS_OPCODE_INTERPOLATE_AT_PER_SLOT_OFFSET:
809 return (i == 0 ? 2 : 1);
817 fs_inst::size_read(int arg) const
820 case FS_OPCODE_FB_WRITE:
821 case FS_OPCODE_REP_FB_WRITE:
824 return src[0].file == BAD_FILE ? 0 : 2 * REG_SIZE;
826 return mlen * REG_SIZE;
830 case FS_OPCODE_FB_READ:
831 case SHADER_OPCODE_URB_WRITE_SIMD8:
832 case SHADER_OPCODE_URB_WRITE_SIMD8_PER_SLOT:
833 case SHADER_OPCODE_URB_WRITE_SIMD8_MASKED:
834 case SHADER_OPCODE_URB_WRITE_SIMD8_MASKED_PER_SLOT:
835 case SHADER_OPCODE_URB_READ_SIMD8:
836 case SHADER_OPCODE_URB_READ_SIMD8_PER_SLOT:
837 case SHADER_OPCODE_UNTYPED_ATOMIC:
838 case SHADER_OPCODE_UNTYPED_SURFACE_READ:
839 case SHADER_OPCODE_UNTYPED_SURFACE_WRITE:
840 case SHADER_OPCODE_TYPED_ATOMIC:
841 case SHADER_OPCODE_TYPED_SURFACE_READ:
842 case SHADER_OPCODE_TYPED_SURFACE_WRITE:
843 case FS_OPCODE_INTERPOLATE_AT_SAMPLE:
844 case FS_OPCODE_INTERPOLATE_AT_SHARED_OFFSET:
845 case SHADER_OPCODE_BYTE_SCATTERED_WRITE:
846 case SHADER_OPCODE_BYTE_SCATTERED_READ:
848 return mlen * REG_SIZE;
851 case FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD_GEN7:
852 /* The payload is actually stored in src1 */
854 return mlen * REG_SIZE;
857 case FS_OPCODE_LINTERP:
862 case SHADER_OPCODE_LOAD_PAYLOAD:
863 if (arg < this->header_size)
867 case CS_OPCODE_CS_TERMINATE:
868 case SHADER_OPCODE_BARRIER:
871 case SHADER_OPCODE_MOV_INDIRECT:
873 assert(src[2].file == IMM);
879 if (is_tex() && arg == 0 && src[0].file == VGRF)
880 return mlen * REG_SIZE;
884 switch (src[arg].file) {
887 return components_read(arg) * type_sz(src[arg].type);
893 return components_read(arg) * src[arg].component_size(exec_size);
895 unreachable("MRF registers are not allowed as sources");
901 /* Return the subset of flag registers that an instruction could
902 * potentially read or write based on the execution controls and flag
903 * subregister number of the instruction.
906 flag_mask(const fs_inst *inst)
908 const unsigned start = inst->flag_subreg * 16 + inst->group;
909 const unsigned end = start + inst->exec_size;
910 return ((1 << DIV_ROUND_UP(end, 8)) - 1) & ~((1 << (start / 8)) - 1);
916 return (n >= CHAR_BIT * sizeof(bit_mask(n)) ? ~0u : (1u << n) - 1);
920 flag_mask(const fs_reg &r, unsigned sz)
923 const unsigned start = (r.nr - BRW_ARF_FLAG) * 4 + r.subnr;
924 const unsigned end = start + sz;
925 return bit_mask(end) & ~bit_mask(start);
933 fs_inst::flags_read(const gen_device_info *devinfo) const
935 if (predicate == BRW_PREDICATE_ALIGN1_ANYV ||
936 predicate == BRW_PREDICATE_ALIGN1_ALLV) {
937 /* The vertical predication modes combine corresponding bits from
938 * f0.0 and f1.0 on Gen7+, and f0.0 and f0.1 on older hardware.
940 const unsigned shift = devinfo->gen >= 7 ? 4 : 2;
941 return flag_mask(this) << shift | flag_mask(this);
942 } else if (predicate) {
943 return flag_mask(this);
946 for (int i = 0; i < sources; i++) {
947 mask |= flag_mask(src[i], size_read(i));
954 fs_inst::flags_written() const
956 if ((conditional_mod && (opcode != BRW_OPCODE_SEL &&
957 opcode != BRW_OPCODE_CSEL &&
958 opcode != BRW_OPCODE_IF &&
959 opcode != BRW_OPCODE_WHILE)) ||
960 opcode == FS_OPCODE_MOV_DISPATCH_TO_FLAGS ||
961 opcode == SHADER_OPCODE_FIND_LIVE_CHANNEL ||
962 opcode == FS_OPCODE_FB_WRITE) {
963 return flag_mask(this);
965 return flag_mask(dst, size_written);
970 * Returns how many MRFs an FS opcode will write over.
972 * Note that this is not the 0 or 1 implied writes in an actual gen
973 * instruction -- the FS opcodes often generate MOVs in addition.
976 fs_visitor::implied_mrf_writes(fs_inst *inst) const
981 if (inst->base_mrf == -1)
984 switch (inst->opcode) {
985 case SHADER_OPCODE_RCP:
986 case SHADER_OPCODE_RSQ:
987 case SHADER_OPCODE_SQRT:
988 case SHADER_OPCODE_EXP2:
989 case SHADER_OPCODE_LOG2:
990 case SHADER_OPCODE_SIN:
991 case SHADER_OPCODE_COS:
992 return 1 * dispatch_width / 8;
993 case SHADER_OPCODE_POW:
994 case SHADER_OPCODE_INT_QUOTIENT:
995 case SHADER_OPCODE_INT_REMAINDER:
996 return 2 * dispatch_width / 8;
997 case SHADER_OPCODE_TEX:
999 case SHADER_OPCODE_TXD:
1000 case SHADER_OPCODE_TXF:
1001 case SHADER_OPCODE_TXF_CMS:
1002 case SHADER_OPCODE_TXF_MCS:
1003 case SHADER_OPCODE_TG4:
1004 case SHADER_OPCODE_TG4_OFFSET:
1005 case SHADER_OPCODE_TXL:
1006 case SHADER_OPCODE_TXS:
1007 case SHADER_OPCODE_LOD:
1008 case SHADER_OPCODE_SAMPLEINFO:
1010 case FS_OPCODE_FB_WRITE:
1011 case FS_OPCODE_REP_FB_WRITE:
1012 return inst->src[0].file == BAD_FILE ? 0 : 2;
1013 case FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD:
1014 case SHADER_OPCODE_GEN4_SCRATCH_READ:
1016 case FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_GEN4:
1018 case SHADER_OPCODE_GEN4_SCRATCH_WRITE:
1021 unreachable("not reached");
1026 fs_visitor::vgrf(const glsl_type *const type)
1028 int reg_width = dispatch_width / 8;
1029 return fs_reg(VGRF, alloc.allocate(type_size_scalar(type) * reg_width),
1030 brw_type_for_base_type(type));
1033 fs_reg::fs_reg(enum brw_reg_file file, int nr)
1038 this->type = BRW_REGISTER_TYPE_F;
1039 this->stride = (file == UNIFORM ? 0 : 1);
1042 fs_reg::fs_reg(enum brw_reg_file file, int nr, enum brw_reg_type type)
1048 this->stride = (file == UNIFORM ? 0 : 1);
1051 /* For SIMD16, we need to follow from the uniform setup of SIMD8 dispatch.
1052 * This brings in those uniform definitions
1055 fs_visitor::import_uniforms(fs_visitor *v)
1057 this->push_constant_loc = v->push_constant_loc;
1058 this->pull_constant_loc = v->pull_constant_loc;
1059 this->uniforms = v->uniforms;
1060 this->subgroup_id = v->subgroup_id;
1064 fs_visitor::emit_fragcoord_interpolation(fs_reg wpos)
1066 assert(stage == MESA_SHADER_FRAGMENT);
1068 /* gl_FragCoord.x */
1069 bld.MOV(wpos, this->pixel_x);
1070 wpos = offset(wpos, bld, 1);
1072 /* gl_FragCoord.y */
1073 bld.MOV(wpos, this->pixel_y);
1074 wpos = offset(wpos, bld, 1);
1076 /* gl_FragCoord.z */
1077 if (devinfo->gen >= 6) {
1078 bld.MOV(wpos, fetch_payload_reg(bld, payload.source_depth_reg));
1080 bld.emit(FS_OPCODE_LINTERP, wpos,
1081 this->delta_xy[BRW_BARYCENTRIC_PERSPECTIVE_PIXEL],
1082 component(interp_reg(VARYING_SLOT_POS, 2), 0));
1084 wpos = offset(wpos, bld, 1);
1086 /* gl_FragCoord.w: Already set up in emit_interpolation */
1087 bld.MOV(wpos, this->wpos_w);
1090 enum brw_barycentric_mode
1091 brw_barycentric_mode(enum glsl_interp_mode mode, nir_intrinsic_op op)
1093 /* Barycentric modes don't make sense for flat inputs. */
1094 assert(mode != INTERP_MODE_FLAT);
1098 case nir_intrinsic_load_barycentric_pixel:
1099 case nir_intrinsic_load_barycentric_at_offset:
1100 bary = BRW_BARYCENTRIC_PERSPECTIVE_PIXEL;
1102 case nir_intrinsic_load_barycentric_centroid:
1103 bary = BRW_BARYCENTRIC_PERSPECTIVE_CENTROID;
1105 case nir_intrinsic_load_barycentric_sample:
1106 case nir_intrinsic_load_barycentric_at_sample:
1107 bary = BRW_BARYCENTRIC_PERSPECTIVE_SAMPLE;
1110 unreachable("invalid intrinsic");
1113 if (mode == INTERP_MODE_NOPERSPECTIVE)
1116 return (enum brw_barycentric_mode) bary;
1120 * Turn one of the two CENTROID barycentric modes into PIXEL mode.
1122 static enum brw_barycentric_mode
1123 centroid_to_pixel(enum brw_barycentric_mode bary)
1125 assert(bary == BRW_BARYCENTRIC_PERSPECTIVE_CENTROID ||
1126 bary == BRW_BARYCENTRIC_NONPERSPECTIVE_CENTROID);
1127 return (enum brw_barycentric_mode) ((unsigned) bary - 1);
1131 fs_visitor::emit_frontfacing_interpolation()
1133 fs_reg *reg = new(this->mem_ctx) fs_reg(vgrf(glsl_type::bool_type));
1135 if (devinfo->gen >= 6) {
1136 /* Bit 15 of g0.0 is 0 if the polygon is front facing. We want to create
1137 * a boolean result from this (~0/true or 0/false).
1139 * We can use the fact that bit 15 is the MSB of g0.0:W to accomplish
1140 * this task in only one instruction:
1141 * - a negation source modifier will flip the bit; and
1142 * - a W -> D type conversion will sign extend the bit into the high
1143 * word of the destination.
1145 * An ASR 15 fills the low word of the destination.
1147 fs_reg g0 = fs_reg(retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_W));
1150 bld.ASR(*reg, g0, brw_imm_d(15));
1152 /* Bit 31 of g1.6 is 0 if the polygon is front facing. We want to create
1153 * a boolean result from this (1/true or 0/false).
1155 * Like in the above case, since the bit is the MSB of g1.6:UD we can use
1156 * the negation source modifier to flip it. Unfortunately the SHR
1157 * instruction only operates on UD (or D with an abs source modifier)
1158 * sources without negation.
1160 * Instead, use ASR (which will give ~0/true or 0/false).
1162 fs_reg g1_6 = fs_reg(retype(brw_vec1_grf(1, 6), BRW_REGISTER_TYPE_D));
1165 bld.ASR(*reg, g1_6, brw_imm_d(31));
1172 fs_visitor::compute_sample_position(fs_reg dst, fs_reg int_sample_pos)
1174 assert(stage == MESA_SHADER_FRAGMENT);
1175 struct brw_wm_prog_data *wm_prog_data = brw_wm_prog_data(this->prog_data);
1176 assert(dst.type == BRW_REGISTER_TYPE_F);
1178 if (wm_prog_data->persample_dispatch) {
1179 /* Convert int_sample_pos to floating point */
1180 bld.MOV(dst, int_sample_pos);
1181 /* Scale to the range [0, 1] */
1182 bld.MUL(dst, dst, brw_imm_f(1 / 16.0f));
1185 /* From ARB_sample_shading specification:
1186 * "When rendering to a non-multisample buffer, or if multisample
1187 * rasterization is disabled, gl_SamplePosition will always be
1190 bld.MOV(dst, brw_imm_f(0.5f));
1195 fs_visitor::emit_samplepos_setup()
1197 assert(devinfo->gen >= 6);
1199 const fs_builder abld = bld.annotate("compute sample position");
1200 fs_reg *reg = new(this->mem_ctx) fs_reg(vgrf(glsl_type::vec2_type));
1202 fs_reg int_sample_x = vgrf(glsl_type::int_type);
1203 fs_reg int_sample_y = vgrf(glsl_type::int_type);
1205 /* WM will be run in MSDISPMODE_PERSAMPLE. So, only one of SIMD8 or SIMD16
1206 * mode will be enabled.
1208 * From the Ivy Bridge PRM, volume 2 part 1, page 344:
1209 * R31.1:0 Position Offset X/Y for Slot[3:0]
1210 * R31.3:2 Position Offset X/Y for Slot[7:4]
1213 * The X, Y sample positions come in as bytes in thread payload. So, read
1214 * the positions using vstride=16, width=8, hstride=2.
1216 const fs_reg sample_pos_reg =
1217 fetch_payload_reg(abld, payload.sample_pos_reg, BRW_REGISTER_TYPE_W);
1219 /* Compute gl_SamplePosition.x */
1220 abld.MOV(int_sample_x, subscript(sample_pos_reg, BRW_REGISTER_TYPE_B, 0));
1221 compute_sample_position(offset(pos, abld, 0), int_sample_x);
1223 /* Compute gl_SamplePosition.y */
1224 abld.MOV(int_sample_y, subscript(sample_pos_reg, BRW_REGISTER_TYPE_B, 1));
1225 compute_sample_position(offset(pos, abld, 1), int_sample_y);
1230 fs_visitor::emit_sampleid_setup()
1232 assert(stage == MESA_SHADER_FRAGMENT);
1233 brw_wm_prog_key *key = (brw_wm_prog_key*) this->key;
1234 assert(devinfo->gen >= 6);
1236 const fs_builder abld = bld.annotate("compute sample id");
1237 fs_reg *reg = new(this->mem_ctx) fs_reg(vgrf(glsl_type::uint_type));
1239 if (!key->multisample_fbo) {
1240 /* As per GL_ARB_sample_shading specification:
1241 * "When rendering to a non-multisample buffer, or if multisample
1242 * rasterization is disabled, gl_SampleID will always be zero."
1244 abld.MOV(*reg, brw_imm_d(0));
1245 } else if (devinfo->gen >= 8) {
1246 /* Sample ID comes in as 4-bit numbers in g1.0:
1248 * 15:12 Slot 3 SampleID (only used in SIMD16)
1249 * 11:8 Slot 2 SampleID (only used in SIMD16)
1250 * 7:4 Slot 1 SampleID
1251 * 3:0 Slot 0 SampleID
1253 * Each slot corresponds to four channels, so we want to replicate each
1254 * half-byte value to 4 channels in a row:
1256 * dst+0: .7 .6 .5 .4 .3 .2 .1 .0
1257 * 7:4 7:4 7:4 7:4 3:0 3:0 3:0 3:0
1259 * dst+1: .7 .6 .5 .4 .3 .2 .1 .0 (if SIMD16)
1260 * 15:12 15:12 15:12 15:12 11:8 11:8 11:8 11:8
1262 * First, we read g1.0 with a <1,8,0>UB region, causing the first 8
1263 * channels to read the first byte (7:0), and the second group of 8
1264 * channels to read the second byte (15:8). Then, we shift right by
1265 * a vector immediate of <4, 4, 4, 4, 0, 0, 0, 0>, moving the slot 1 / 3
1266 * values into place. Finally, we AND with 0xf to keep the low nibble.
1268 * shr(16) tmp<1>W g1.0<1,8,0>B 0x44440000:V
1269 * and(16) dst<1>D tmp<8,8,1>W 0xf:W
1271 * TODO: These payload bits exist on Gen7 too, but they appear to always
1272 * be zero, so this code fails to work. We should find out why.
1274 fs_reg tmp(VGRF, alloc.allocate(1), BRW_REGISTER_TYPE_UW);
1276 abld.SHR(tmp, fs_reg(stride(retype(brw_vec1_grf(1, 0),
1277 BRW_REGISTER_TYPE_UB), 1, 8, 0)),
1278 brw_imm_v(0x44440000));
1279 abld.AND(*reg, tmp, brw_imm_w(0xf));
1281 const fs_reg t1 = component(fs_reg(VGRF, alloc.allocate(1),
1282 BRW_REGISTER_TYPE_UD), 0);
1283 const fs_reg t2(VGRF, alloc.allocate(1), BRW_REGISTER_TYPE_UW);
1285 /* The PS will be run in MSDISPMODE_PERSAMPLE. For example with
1286 * 8x multisampling, subspan 0 will represent sample N (where N
1287 * is 0, 2, 4 or 6), subspan 1 will represent sample 1, 3, 5 or
1288 * 7. We can find the value of N by looking at R0.0 bits 7:6
1289 * ("Starting Sample Pair Index (SSPI)") and multiplying by two
1290 * (since samples are always delivered in pairs). That is, we
1291 * compute 2*((R0.0 & 0xc0) >> 6) == (R0.0 & 0xc0) >> 5. Then
1292 * we need to add N to the sequence (0, 0, 0, 0, 1, 1, 1, 1) in
1293 * case of SIMD8 and sequence (0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2,
1294 * 2, 3, 3, 3, 3) in case of SIMD16. We compute this sequence by
1295 * populating a temporary variable with the sequence (0, 1, 2, 3),
1296 * and then reading from it using vstride=1, width=4, hstride=0.
1297 * These computations hold good for 4x multisampling as well.
1299 * For 2x MSAA and SIMD16, we want to use the sequence (0, 1, 0, 1):
1300 * the first four slots are sample 0 of subspan 0; the next four
1301 * are sample 1 of subspan 0; the third group is sample 0 of
1302 * subspan 1, and finally sample 1 of subspan 1.
1305 /* SKL+ has an extra bit for the Starting Sample Pair Index to
1306 * accomodate 16x MSAA.
1308 abld.exec_all().group(1, 0)
1309 .AND(t1, fs_reg(retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_UD)),
1311 abld.exec_all().group(1, 0).SHR(t1, t1, brw_imm_d(5));
1313 /* This works for both SIMD8 and SIMD16 */
1314 abld.exec_all().group(4, 0).MOV(t2, brw_imm_v(0x3210));
1316 /* This special instruction takes care of setting vstride=1,
1317 * width=4, hstride=0 of t2 during an ADD instruction.
1319 abld.emit(FS_OPCODE_SET_SAMPLE_ID, *reg, t1, t2);
1326 fs_visitor::emit_samplemaskin_setup()
1328 assert(stage == MESA_SHADER_FRAGMENT);
1329 struct brw_wm_prog_data *wm_prog_data = brw_wm_prog_data(this->prog_data);
1330 assert(devinfo->gen >= 6);
1332 fs_reg *reg = new(this->mem_ctx) fs_reg(vgrf(glsl_type::int_type));
1334 fs_reg coverage_mask =
1335 fetch_payload_reg(bld, payload.sample_mask_in_reg, BRW_REGISTER_TYPE_D);
1337 if (wm_prog_data->persample_dispatch) {
1338 /* gl_SampleMaskIn[] comes from two sources: the input coverage mask,
1339 * and a mask representing which sample is being processed by the
1340 * current shader invocation.
1342 * From the OES_sample_variables specification:
1343 * "When per-sample shading is active due to the use of a fragment input
1344 * qualified by "sample" or due to the use of the gl_SampleID or
1345 * gl_SamplePosition variables, only the bit for the current sample is
1346 * set in gl_SampleMaskIn."
1348 const fs_builder abld = bld.annotate("compute gl_SampleMaskIn");
1350 if (nir_system_values[SYSTEM_VALUE_SAMPLE_ID].file == BAD_FILE)
1351 nir_system_values[SYSTEM_VALUE_SAMPLE_ID] = *emit_sampleid_setup();
1353 fs_reg one = vgrf(glsl_type::int_type);
1354 fs_reg enabled_mask = vgrf(glsl_type::int_type);
1355 abld.MOV(one, brw_imm_d(1));
1356 abld.SHL(enabled_mask, one, nir_system_values[SYSTEM_VALUE_SAMPLE_ID]);
1357 abld.AND(*reg, enabled_mask, coverage_mask);
1359 /* In per-pixel mode, the coverage mask is sufficient. */
1360 *reg = coverage_mask;
1366 fs_visitor::resolve_source_modifiers(const fs_reg &src)
1368 if (!src.abs && !src.negate)
1371 fs_reg temp = bld.vgrf(src.type);
1378 fs_visitor::emit_discard_jump()
1380 assert(brw_wm_prog_data(this->prog_data)->uses_kill);
1382 /* For performance, after a discard, jump to the end of the
1383 * shader if all relevant channels have been discarded.
1385 fs_inst *discard_jump = bld.emit(FS_OPCODE_DISCARD_JUMP);
1386 discard_jump->flag_subreg = 1;
1388 discard_jump->predicate = BRW_PREDICATE_ALIGN1_ANY4H;
1389 discard_jump->predicate_inverse = true;
1393 fs_visitor::emit_gs_thread_end()
1395 assert(stage == MESA_SHADER_GEOMETRY);
1397 struct brw_gs_prog_data *gs_prog_data = brw_gs_prog_data(prog_data);
1399 if (gs_compile->control_data_header_size_bits > 0) {
1400 emit_gs_control_data_bits(this->final_gs_vertex_count);
1403 const fs_builder abld = bld.annotate("thread end");
1406 if (gs_prog_data->static_vertex_count != -1) {
1407 foreach_in_list_reverse(fs_inst, prev, &this->instructions) {
1408 if (prev->opcode == SHADER_OPCODE_URB_WRITE_SIMD8 ||
1409 prev->opcode == SHADER_OPCODE_URB_WRITE_SIMD8_MASKED ||
1410 prev->opcode == SHADER_OPCODE_URB_WRITE_SIMD8_PER_SLOT ||
1411 prev->opcode == SHADER_OPCODE_URB_WRITE_SIMD8_MASKED_PER_SLOT) {
1414 /* Delete now dead instructions. */
1415 foreach_in_list_reverse_safe(exec_node, dead, &this->instructions) {
1421 } else if (prev->is_control_flow() || prev->has_side_effects()) {
1425 fs_reg hdr = abld.vgrf(BRW_REGISTER_TYPE_UD, 1);
1426 abld.MOV(hdr, fs_reg(retype(brw_vec8_grf(1, 0), BRW_REGISTER_TYPE_UD)));
1427 inst = abld.emit(SHADER_OPCODE_URB_WRITE_SIMD8, reg_undef, hdr);
1430 fs_reg payload = abld.vgrf(BRW_REGISTER_TYPE_UD, 2);
1431 fs_reg *sources = ralloc_array(mem_ctx, fs_reg, 2);
1432 sources[0] = fs_reg(retype(brw_vec8_grf(1, 0), BRW_REGISTER_TYPE_UD));
1433 sources[1] = this->final_gs_vertex_count;
1434 abld.LOAD_PAYLOAD(payload, sources, 2, 2);
1435 inst = abld.emit(SHADER_OPCODE_URB_WRITE_SIMD8, reg_undef, payload);
1443 fs_visitor::assign_curb_setup()
1445 unsigned uniform_push_length = DIV_ROUND_UP(stage_prog_data->nr_params, 8);
1447 unsigned ubo_push_length = 0;
1448 unsigned ubo_push_start[4];
1449 for (int i = 0; i < 4; i++) {
1450 ubo_push_start[i] = 8 * (ubo_push_length + uniform_push_length);
1451 ubo_push_length += stage_prog_data->ubo_ranges[i].length;
1454 prog_data->curb_read_length = uniform_push_length + ubo_push_length;
1456 /* Map the offsets in the UNIFORM file to fixed HW regs. */
1457 foreach_block_and_inst(block, fs_inst, inst, cfg) {
1458 for (unsigned int i = 0; i < inst->sources; i++) {
1459 if (inst->src[i].file == UNIFORM) {
1460 int uniform_nr = inst->src[i].nr + inst->src[i].offset / 4;
1462 if (inst->src[i].nr >= UBO_START) {
1463 /* constant_nr is in 32-bit units, the rest are in bytes */
1464 constant_nr = ubo_push_start[inst->src[i].nr - UBO_START] +
1465 inst->src[i].offset / 4;
1466 } else if (uniform_nr >= 0 && uniform_nr < (int) uniforms) {
1467 constant_nr = push_constant_loc[uniform_nr];
1469 /* Section 5.11 of the OpenGL 4.1 spec says:
1470 * "Out-of-bounds reads return undefined values, which include
1471 * values from other variables of the active program or zero."
1472 * Just return the first push constant.
1477 struct brw_reg brw_reg = brw_vec1_grf(payload.num_regs +
1480 brw_reg.abs = inst->src[i].abs;
1481 brw_reg.negate = inst->src[i].negate;
1483 assert(inst->src[i].stride == 0);
1484 inst->src[i] = byte_offset(
1485 retype(brw_reg, inst->src[i].type),
1486 inst->src[i].offset % 4);
1491 /* This may be updated in assign_urb_setup or assign_vs_urb_setup. */
1492 this->first_non_payload_grf = payload.num_regs + prog_data->curb_read_length;
1496 fs_visitor::calculate_urb_setup()
1498 assert(stage == MESA_SHADER_FRAGMENT);
1499 struct brw_wm_prog_data *prog_data = brw_wm_prog_data(this->prog_data);
1500 brw_wm_prog_key *key = (brw_wm_prog_key*) this->key;
1502 memset(prog_data->urb_setup, -1,
1503 sizeof(prog_data->urb_setup[0]) * VARYING_SLOT_MAX);
1506 /* Figure out where each of the incoming setup attributes lands. */
1507 if (devinfo->gen >= 6) {
1508 if (_mesa_bitcount_64(nir->info.inputs_read &
1509 BRW_FS_VARYING_INPUT_MASK) <= 16) {
1510 /* The SF/SBE pipeline stage can do arbitrary rearrangement of the
1511 * first 16 varying inputs, so we can put them wherever we want.
1512 * Just put them in order.
1514 * This is useful because it means that (a) inputs not used by the
1515 * fragment shader won't take up valuable register space, and (b) we
1516 * won't have to recompile the fragment shader if it gets paired with
1517 * a different vertex (or geometry) shader.
1519 for (unsigned int i = 0; i < VARYING_SLOT_MAX; i++) {
1520 if (nir->info.inputs_read & BRW_FS_VARYING_INPUT_MASK &
1521 BITFIELD64_BIT(i)) {
1522 prog_data->urb_setup[i] = urb_next++;
1526 /* We have enough input varyings that the SF/SBE pipeline stage can't
1527 * arbitrarily rearrange them to suit our whim; we have to put them
1528 * in an order that matches the output of the previous pipeline stage
1529 * (geometry or vertex shader).
1531 struct brw_vue_map prev_stage_vue_map;
1532 brw_compute_vue_map(devinfo, &prev_stage_vue_map,
1533 key->input_slots_valid,
1534 nir->info.separate_shader);
1537 brw_compute_first_urb_slot_required(nir->info.inputs_read,
1538 &prev_stage_vue_map);
1540 assert(prev_stage_vue_map.num_slots <= first_slot + 32);
1541 for (int slot = first_slot; slot < prev_stage_vue_map.num_slots;
1543 int varying = prev_stage_vue_map.slot_to_varying[slot];
1544 if (varying != BRW_VARYING_SLOT_PAD &&
1545 (nir->info.inputs_read & BRW_FS_VARYING_INPUT_MASK &
1546 BITFIELD64_BIT(varying))) {
1547 prog_data->urb_setup[varying] = slot - first_slot;
1550 urb_next = prev_stage_vue_map.num_slots - first_slot;
1553 /* FINISHME: The sf doesn't map VS->FS inputs for us very well. */
1554 for (unsigned int i = 0; i < VARYING_SLOT_MAX; i++) {
1555 /* Point size is packed into the header, not as a general attribute */
1556 if (i == VARYING_SLOT_PSIZ)
1559 if (key->input_slots_valid & BITFIELD64_BIT(i)) {
1560 /* The back color slot is skipped when the front color is
1561 * also written to. In addition, some slots can be
1562 * written in the vertex shader and not read in the
1563 * fragment shader. So the register number must always be
1564 * incremented, mapped or not.
1566 if (_mesa_varying_slot_in_fs((gl_varying_slot) i))
1567 prog_data->urb_setup[i] = urb_next;
1573 * It's a FS only attribute, and we did interpolation for this attribute
1574 * in SF thread. So, count it here, too.
1576 * See compile_sf_prog() for more info.
1578 if (nir->info.inputs_read & BITFIELD64_BIT(VARYING_SLOT_PNTC))
1579 prog_data->urb_setup[VARYING_SLOT_PNTC] = urb_next++;
1582 prog_data->num_varying_inputs = urb_next;
1586 fs_visitor::assign_urb_setup()
1588 assert(stage == MESA_SHADER_FRAGMENT);
1589 struct brw_wm_prog_data *prog_data = brw_wm_prog_data(this->prog_data);
1591 int urb_start = payload.num_regs + prog_data->base.curb_read_length;
1593 /* Offset all the urb_setup[] index by the actual position of the
1594 * setup regs, now that the location of the constants has been chosen.
1596 foreach_block_and_inst(block, fs_inst, inst, cfg) {
1597 for (int i = 0; i < inst->sources; i++) {
1598 if (inst->src[i].file == ATTR) {
1599 /* ATTR regs in the FS are in units of logical scalar inputs each
1600 * of which consumes half of a GRF register.
1602 assert(inst->src[i].offset < REG_SIZE / 2);
1603 const unsigned grf = urb_start + inst->src[i].nr / 2;
1604 const unsigned offset = (inst->src[i].nr % 2) * (REG_SIZE / 2) +
1605 inst->src[i].offset;
1606 const unsigned width = inst->src[i].stride == 0 ?
1607 1 : MIN2(inst->exec_size, 8);
1608 struct brw_reg reg = stride(
1609 byte_offset(retype(brw_vec8_grf(grf, 0), inst->src[i].type),
1611 width * inst->src[i].stride,
1612 width, inst->src[i].stride);
1613 reg.abs = inst->src[i].abs;
1614 reg.negate = inst->src[i].negate;
1620 /* Each attribute is 4 setup channels, each of which is half a reg. */
1621 this->first_non_payload_grf += prog_data->num_varying_inputs * 2;
1625 fs_visitor::convert_attr_sources_to_hw_regs(fs_inst *inst)
1627 for (int i = 0; i < inst->sources; i++) {
1628 if (inst->src[i].file == ATTR) {
1629 int grf = payload.num_regs +
1630 prog_data->curb_read_length +
1632 inst->src[i].offset / REG_SIZE;
1634 /* As explained at brw_reg_from_fs_reg, From the Haswell PRM:
1636 * VertStride must be used to cross GRF register boundaries. This
1637 * rule implies that elements within a 'Width' cannot cross GRF
1640 * So, for registers that are large enough, we have to split the exec
1641 * size in two and trust the compression state to sort it out.
1643 unsigned total_size = inst->exec_size *
1644 inst->src[i].stride *
1645 type_sz(inst->src[i].type);
1647 assert(total_size <= 2 * REG_SIZE);
1648 const unsigned exec_size =
1649 (total_size <= REG_SIZE) ? inst->exec_size : inst->exec_size / 2;
1651 unsigned width = inst->src[i].stride == 0 ? 1 : exec_size;
1652 struct brw_reg reg =
1653 stride(byte_offset(retype(brw_vec8_grf(grf, 0), inst->src[i].type),
1654 inst->src[i].offset % REG_SIZE),
1655 exec_size * inst->src[i].stride,
1656 width, inst->src[i].stride);
1657 reg.abs = inst->src[i].abs;
1658 reg.negate = inst->src[i].negate;
1666 fs_visitor::assign_vs_urb_setup()
1668 struct brw_vs_prog_data *vs_prog_data = brw_vs_prog_data(prog_data);
1670 assert(stage == MESA_SHADER_VERTEX);
1672 /* Each attribute is 4 regs. */
1673 this->first_non_payload_grf += 4 * vs_prog_data->nr_attribute_slots;
1675 assert(vs_prog_data->base.urb_read_length <= 15);
1677 /* Rewrite all ATTR file references to the hw grf that they land in. */
1678 foreach_block_and_inst(block, fs_inst, inst, cfg) {
1679 convert_attr_sources_to_hw_regs(inst);
1684 fs_visitor::assign_tcs_single_patch_urb_setup()
1686 assert(stage == MESA_SHADER_TESS_CTRL);
1688 /* Rewrite all ATTR file references to HW_REGs. */
1689 foreach_block_and_inst(block, fs_inst, inst, cfg) {
1690 convert_attr_sources_to_hw_regs(inst);
1695 fs_visitor::assign_tes_urb_setup()
1697 assert(stage == MESA_SHADER_TESS_EVAL);
1699 struct brw_vue_prog_data *vue_prog_data = brw_vue_prog_data(prog_data);
1701 first_non_payload_grf += 8 * vue_prog_data->urb_read_length;
1703 /* Rewrite all ATTR file references to HW_REGs. */
1704 foreach_block_and_inst(block, fs_inst, inst, cfg) {
1705 convert_attr_sources_to_hw_regs(inst);
1710 fs_visitor::assign_gs_urb_setup()
1712 assert(stage == MESA_SHADER_GEOMETRY);
1714 struct brw_vue_prog_data *vue_prog_data = brw_vue_prog_data(prog_data);
1716 first_non_payload_grf +=
1717 8 * vue_prog_data->urb_read_length * nir->info.gs.vertices_in;
1719 foreach_block_and_inst(block, fs_inst, inst, cfg) {
1720 /* Rewrite all ATTR file references to GRFs. */
1721 convert_attr_sources_to_hw_regs(inst);
1727 * Split large virtual GRFs into separate components if we can.
1729 * This is mostly duplicated with what brw_fs_vector_splitting does,
1730 * but that's really conservative because it's afraid of doing
1731 * splitting that doesn't result in real progress after the rest of
1732 * the optimization phases, which would cause infinite looping in
1733 * optimization. We can do it once here, safely. This also has the
1734 * opportunity to split interpolated values, or maybe even uniforms,
1735 * which we don't have at the IR level.
1737 * We want to split, because virtual GRFs are what we register
1738 * allocate and spill (due to contiguousness requirements for some
1739 * instructions), and they're what we naturally generate in the
1740 * codegen process, but most virtual GRFs don't actually need to be
1741 * contiguous sets of GRFs. If we split, we'll end up with reduced
1742 * live intervals and better dead code elimination and coalescing.
1745 fs_visitor::split_virtual_grfs()
1747 /* Compact the register file so we eliminate dead vgrfs. This
1748 * only defines split points for live registers, so if we have
1749 * too large dead registers they will hit assertions later.
1751 compact_virtual_grfs();
1753 int num_vars = this->alloc.count;
1755 /* Count the total number of registers */
1757 int vgrf_to_reg[num_vars];
1758 for (int i = 0; i < num_vars; i++) {
1759 vgrf_to_reg[i] = reg_count;
1760 reg_count += alloc.sizes[i];
1763 /* An array of "split points". For each register slot, this indicates
1764 * if this slot can be separated from the previous slot. Every time an
1765 * instruction uses multiple elements of a register (as a source or
1766 * destination), we mark the used slots as inseparable. Then we go
1767 * through and split the registers into the smallest pieces we can.
1769 bool split_points[reg_count];
1770 memset(split_points, 0, sizeof(split_points));
1772 /* Mark all used registers as fully splittable */
1773 foreach_block_and_inst(block, fs_inst, inst, cfg) {
1774 if (inst->dst.file == VGRF) {
1775 int reg = vgrf_to_reg[inst->dst.nr];
1776 for (unsigned j = 1; j < this->alloc.sizes[inst->dst.nr]; j++)
1777 split_points[reg + j] = true;
1780 for (int i = 0; i < inst->sources; i++) {
1781 if (inst->src[i].file == VGRF) {
1782 int reg = vgrf_to_reg[inst->src[i].nr];
1783 for (unsigned j = 1; j < this->alloc.sizes[inst->src[i].nr]; j++)
1784 split_points[reg + j] = true;
1789 foreach_block_and_inst(block, fs_inst, inst, cfg) {
1790 if (inst->dst.file == VGRF) {
1791 int reg = vgrf_to_reg[inst->dst.nr] + inst->dst.offset / REG_SIZE;
1792 for (unsigned j = 1; j < regs_written(inst); j++)
1793 split_points[reg + j] = false;
1795 for (int i = 0; i < inst->sources; i++) {
1796 if (inst->src[i].file == VGRF) {
1797 int reg = vgrf_to_reg[inst->src[i].nr] + inst->src[i].offset / REG_SIZE;
1798 for (unsigned j = 1; j < regs_read(inst, i); j++)
1799 split_points[reg + j] = false;
1804 int new_virtual_grf[reg_count];
1805 int new_reg_offset[reg_count];
1808 for (int i = 0; i < num_vars; i++) {
1809 /* The first one should always be 0 as a quick sanity check. */
1810 assert(split_points[reg] == false);
1813 new_reg_offset[reg] = 0;
1818 for (unsigned j = 1; j < alloc.sizes[i]; j++) {
1819 /* If this is a split point, reset the offset to 0 and allocate a
1820 * new virtual GRF for the previous offset many registers
1822 if (split_points[reg]) {
1823 assert(offset <= MAX_VGRF_SIZE);
1824 int grf = alloc.allocate(offset);
1825 for (int k = reg - offset; k < reg; k++)
1826 new_virtual_grf[k] = grf;
1829 new_reg_offset[reg] = offset;
1834 /* The last one gets the original register number */
1835 assert(offset <= MAX_VGRF_SIZE);
1836 alloc.sizes[i] = offset;
1837 for (int k = reg - offset; k < reg; k++)
1838 new_virtual_grf[k] = i;
1840 assert(reg == reg_count);
1842 foreach_block_and_inst(block, fs_inst, inst, cfg) {
1843 if (inst->dst.file == VGRF) {
1844 reg = vgrf_to_reg[inst->dst.nr] + inst->dst.offset / REG_SIZE;
1845 inst->dst.nr = new_virtual_grf[reg];
1846 inst->dst.offset = new_reg_offset[reg] * REG_SIZE +
1847 inst->dst.offset % REG_SIZE;
1848 assert((unsigned)new_reg_offset[reg] < alloc.sizes[new_virtual_grf[reg]]);
1850 for (int i = 0; i < inst->sources; i++) {
1851 if (inst->src[i].file == VGRF) {
1852 reg = vgrf_to_reg[inst->src[i].nr] + inst->src[i].offset / REG_SIZE;
1853 inst->src[i].nr = new_virtual_grf[reg];
1854 inst->src[i].offset = new_reg_offset[reg] * REG_SIZE +
1855 inst->src[i].offset % REG_SIZE;
1856 assert((unsigned)new_reg_offset[reg] < alloc.sizes[new_virtual_grf[reg]]);
1860 invalidate_live_intervals();
1864 * Remove unused virtual GRFs and compact the virtual_grf_* arrays.
1866 * During code generation, we create tons of temporary variables, many of
1867 * which get immediately killed and are never used again. Yet, in later
1868 * optimization and analysis passes, such as compute_live_intervals, we need
1869 * to loop over all the virtual GRFs. Compacting them can save a lot of
1873 fs_visitor::compact_virtual_grfs()
1875 bool progress = false;
1876 int remap_table[this->alloc.count];
1877 memset(remap_table, -1, sizeof(remap_table));
1879 /* Mark which virtual GRFs are used. */
1880 foreach_block_and_inst(block, const fs_inst, inst, cfg) {
1881 if (inst->dst.file == VGRF)
1882 remap_table[inst->dst.nr] = 0;
1884 for (int i = 0; i < inst->sources; i++) {
1885 if (inst->src[i].file == VGRF)
1886 remap_table[inst->src[i].nr] = 0;
1890 /* Compact the GRF arrays. */
1892 for (unsigned i = 0; i < this->alloc.count; i++) {
1893 if (remap_table[i] == -1) {
1894 /* We just found an unused register. This means that we are
1895 * actually going to compact something.
1899 remap_table[i] = new_index;
1900 alloc.sizes[new_index] = alloc.sizes[i];
1901 invalidate_live_intervals();
1906 this->alloc.count = new_index;
1908 /* Patch all the instructions to use the newly renumbered registers */
1909 foreach_block_and_inst(block, fs_inst, inst, cfg) {
1910 if (inst->dst.file == VGRF)
1911 inst->dst.nr = remap_table[inst->dst.nr];
1913 for (int i = 0; i < inst->sources; i++) {
1914 if (inst->src[i].file == VGRF)
1915 inst->src[i].nr = remap_table[inst->src[i].nr];
1919 /* Patch all the references to delta_xy, since they're used in register
1920 * allocation. If they're unused, switch them to BAD_FILE so we don't
1921 * think some random VGRF is delta_xy.
1923 for (unsigned i = 0; i < ARRAY_SIZE(delta_xy); i++) {
1924 if (delta_xy[i].file == VGRF) {
1925 if (remap_table[delta_xy[i].nr] != -1) {
1926 delta_xy[i].nr = remap_table[delta_xy[i].nr];
1928 delta_xy[i].file = BAD_FILE;
1937 get_subgroup_id_param_index(const brw_stage_prog_data *prog_data)
1939 if (prog_data->nr_params == 0)
1942 /* The local thread id is always the last parameter in the list */
1943 uint32_t last_param = prog_data->param[prog_data->nr_params - 1];
1944 if (last_param == BRW_PARAM_BUILTIN_SUBGROUP_ID)
1945 return prog_data->nr_params - 1;
1951 * Struct for handling complex alignments.
1953 * A complex alignment is stored as multiplier and an offset. A value is
1954 * considered to be aligned if it is {offset} larger than a multiple of {mul}.
1955 * For instance, with an alignment of {8, 2}, cplx_align_apply would do the
1958 * N | cplx_align_apply({8, 2}, N)
1959 * ----+-----------------------------
1973 #define CPLX_ALIGN_MAX_MUL 8
1976 cplx_align_assert_sane(struct cplx_align a)
1978 assert(a.mul > 0 && util_is_power_of_two_nonzero(a.mul));
1979 assert(a.offset < a.mul);
1983 * Combines two alignments to produce a least multiple of sorts.
1985 * The returned alignment is the smallest (in terms of multiplier) such that
1986 * anything aligned to both a and b will be aligned to the new alignment.
1987 * This function will assert-fail if a and b are not compatible, i.e. if the
1988 * offset parameters are such that no common alignment is possible.
1990 static struct cplx_align
1991 cplx_align_combine(struct cplx_align a, struct cplx_align b)
1993 cplx_align_assert_sane(a);
1994 cplx_align_assert_sane(b);
1996 /* Assert that the alignments agree. */
1997 assert((a.offset & (b.mul - 1)) == (b.offset & (a.mul - 1)));
1999 return a.mul > b.mul ? a : b;
2003 * Apply a complex alignment
2005 * This function will return the smallest number greater than or equal to
2006 * offset that is aligned to align.
2009 cplx_align_apply(struct cplx_align align, unsigned offset)
2011 return ALIGN(offset - align.offset, align.mul) + align.offset;
2014 #define UNIFORM_SLOT_SIZE 4
2016 struct uniform_slot_info {
2017 /** True if the given uniform slot is live */
2020 /** True if this slot and the next slot must remain contiguous */
2021 unsigned contiguous:1;
2023 struct cplx_align align;
2027 mark_uniform_slots_read(struct uniform_slot_info *slots,
2028 unsigned num_slots, unsigned alignment)
2030 assert(alignment > 0 && util_is_power_of_two_nonzero(alignment));
2031 assert(alignment <= CPLX_ALIGN_MAX_MUL);
2033 /* We can't align a slot to anything less than the slot size */
2034 alignment = MAX2(alignment, UNIFORM_SLOT_SIZE);
2036 struct cplx_align align = {alignment, 0};
2037 cplx_align_assert_sane(align);
2039 for (unsigned i = 0; i < num_slots; i++) {
2040 slots[i].is_live = true;
2041 if (i < num_slots - 1)
2042 slots[i].contiguous = true;
2044 align.offset = (i * UNIFORM_SLOT_SIZE) & (align.mul - 1);
2045 if (slots[i].align.mul == 0) {
2046 slots[i].align = align;
2048 slots[i].align = cplx_align_combine(slots[i].align, align);
2054 * Assign UNIFORM file registers to either push constants or pull constants.
2056 * We allow a fragment shader to have more than the specified minimum
2057 * maximum number of fragment shader uniform components (64). If
2058 * there are too many of these, they'd fill up all of register space.
2059 * So, this will push some of them out to the pull constant buffer and
2060 * update the program to load them.
2063 fs_visitor::assign_constant_locations()
2065 /* Only the first compile gets to decide on locations. */
2066 if (push_constant_loc) {
2067 assert(pull_constant_loc);
2071 struct uniform_slot_info slots[uniforms];
2072 memset(slots, 0, sizeof(slots));
2074 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
2075 for (int i = 0 ; i < inst->sources; i++) {
2076 if (inst->src[i].file != UNIFORM)
2079 /* NIR tightly packs things so the uniform number might not be
2080 * aligned (if we have a double right after a float, for instance).
2081 * This is fine because the process of re-arranging them will ensure
2082 * that things are properly aligned. The offset into that uniform,
2083 * however, must be aligned.
2085 * In Vulkan, we have explicit offsets but everything is crammed
2086 * into a single "variable" so inst->src[i].nr will always be 0.
2087 * Everything will be properly aligned relative to that one base.
2089 assert(inst->src[i].offset % type_sz(inst->src[i].type) == 0);
2091 unsigned u = inst->src[i].nr +
2092 inst->src[i].offset / UNIFORM_SLOT_SIZE;
2097 unsigned slots_read;
2098 if (inst->opcode == SHADER_OPCODE_MOV_INDIRECT && i == 0) {
2099 slots_read = DIV_ROUND_UP(inst->src[2].ud, UNIFORM_SLOT_SIZE);
2101 unsigned bytes_read = inst->components_read(i) *
2102 type_sz(inst->src[i].type);
2103 slots_read = DIV_ROUND_UP(bytes_read, UNIFORM_SLOT_SIZE);
2106 assert(u + slots_read <= uniforms);
2107 mark_uniform_slots_read(&slots[u], slots_read,
2108 type_sz(inst->src[i].type));
2112 int subgroup_id_index = get_subgroup_id_param_index(stage_prog_data);
2114 /* Only allow 16 registers (128 uniform components) as push constants.
2116 * Just demote the end of the list. We could probably do better
2117 * here, demoting things that are rarely used in the program first.
2119 * If changing this value, note the limitation about total_regs in
2122 unsigned int max_push_components = 16 * 8;
2123 if (subgroup_id_index >= 0)
2124 max_push_components--; /* Save a slot for the thread ID */
2126 /* We push small arrays, but no bigger than 16 floats. This is big enough
2127 * for a vec4 but hopefully not large enough to push out other stuff. We
2128 * should probably use a better heuristic at some point.
2130 const unsigned int max_chunk_size = 16;
2132 unsigned int num_push_constants = 0;
2133 unsigned int num_pull_constants = 0;
2135 push_constant_loc = ralloc_array(mem_ctx, int, uniforms);
2136 pull_constant_loc = ralloc_array(mem_ctx, int, uniforms);
2138 /* Default to -1 meaning no location */
2139 memset(push_constant_loc, -1, uniforms * sizeof(*push_constant_loc));
2140 memset(pull_constant_loc, -1, uniforms * sizeof(*pull_constant_loc));
2142 int chunk_start = -1;
2143 struct cplx_align align;
2144 for (unsigned u = 0; u < uniforms; u++) {
2145 if (!slots[u].is_live) {
2146 assert(chunk_start == -1);
2150 /* Skip subgroup_id_index to put it in the last push register. */
2151 if (subgroup_id_index == (int)u)
2154 if (chunk_start == -1) {
2156 align = slots[u].align;
2158 /* Offset into the chunk */
2159 unsigned chunk_offset = (u - chunk_start) * UNIFORM_SLOT_SIZE;
2161 /* Shift the slot alignment down by the chunk offset so it is
2162 * comparable with the base chunk alignment.
2164 struct cplx_align slot_align = slots[u].align;
2166 (slot_align.offset - chunk_offset) & (align.mul - 1);
2168 align = cplx_align_combine(align, slot_align);
2171 /* Sanity check the alignment */
2172 cplx_align_assert_sane(align);
2174 if (slots[u].contiguous)
2177 /* Adjust the alignment to be in terms of slots, not bytes */
2178 assert((align.mul & (UNIFORM_SLOT_SIZE - 1)) == 0);
2179 assert((align.offset & (UNIFORM_SLOT_SIZE - 1)) == 0);
2180 align.mul /= UNIFORM_SLOT_SIZE;
2181 align.offset /= UNIFORM_SLOT_SIZE;
2183 unsigned push_start_align = cplx_align_apply(align, num_push_constants);
2184 unsigned chunk_size = u - chunk_start + 1;
2185 if ((!compiler->supports_pull_constants && u < UBO_START) ||
2186 (chunk_size < max_chunk_size &&
2187 push_start_align + chunk_size <= max_push_components)) {
2188 /* Align up the number of push constants */
2189 num_push_constants = push_start_align;
2190 for (unsigned i = 0; i < chunk_size; i++)
2191 push_constant_loc[chunk_start + i] = num_push_constants++;
2193 /* We need to pull this one */
2194 num_pull_constants = cplx_align_apply(align, num_pull_constants);
2195 for (unsigned i = 0; i < chunk_size; i++)
2196 pull_constant_loc[chunk_start + i] = num_pull_constants++;
2199 /* Reset the chunk and start again */
2203 /* Add the CS local thread ID uniform at the end of the push constants */
2204 if (subgroup_id_index >= 0)
2205 push_constant_loc[subgroup_id_index] = num_push_constants++;
2207 /* As the uniforms are going to be reordered, stash the old array and
2208 * create two new arrays for push/pull params.
2210 uint32_t *param = stage_prog_data->param;
2211 stage_prog_data->nr_params = num_push_constants;
2212 if (num_push_constants) {
2213 stage_prog_data->param = rzalloc_array(mem_ctx, uint32_t,
2214 num_push_constants);
2216 stage_prog_data->param = NULL;
2218 assert(stage_prog_data->nr_pull_params == 0);
2219 assert(stage_prog_data->pull_param == NULL);
2220 if (num_pull_constants > 0) {
2221 stage_prog_data->nr_pull_params = num_pull_constants;
2222 stage_prog_data->pull_param = rzalloc_array(mem_ctx, uint32_t,
2223 num_pull_constants);
2226 /* Now that we know how many regular uniforms we'll push, reduce the
2227 * UBO push ranges so we don't exceed the 3DSTATE_CONSTANT limits.
2229 unsigned push_length = DIV_ROUND_UP(stage_prog_data->nr_params, 8);
2230 for (int i = 0; i < 4; i++) {
2231 struct brw_ubo_range *range = &prog_data->ubo_ranges[i];
2233 if (push_length + range->length > 64)
2234 range->length = 64 - push_length;
2236 push_length += range->length;
2238 assert(push_length <= 64);
2240 /* Up until now, the param[] array has been indexed by reg + offset
2241 * of UNIFORM registers. Move pull constants into pull_param[] and
2242 * condense param[] to only contain the uniforms we chose to push.
2244 * NOTE: Because we are condensing the params[] array, we know that
2245 * push_constant_loc[i] <= i and we can do it in one smooth loop without
2246 * having to make a copy.
2248 for (unsigned int i = 0; i < uniforms; i++) {
2249 uint32_t value = param[i];
2250 if (pull_constant_loc[i] != -1) {
2251 stage_prog_data->pull_param[pull_constant_loc[i]] = value;
2252 } else if (push_constant_loc[i] != -1) {
2253 stage_prog_data->param[push_constant_loc[i]] = value;
2260 fs_visitor::get_pull_locs(const fs_reg &src,
2261 unsigned *out_surf_index,
2262 unsigned *out_pull_index)
2264 assert(src.file == UNIFORM);
2266 if (src.nr >= UBO_START) {
2267 const struct brw_ubo_range *range =
2268 &prog_data->ubo_ranges[src.nr - UBO_START];
2270 /* If this access is in our (reduced) range, use the push data. */
2271 if (src.offset / 32 < range->length)
2274 *out_surf_index = prog_data->binding_table.ubo_start + range->block;
2275 *out_pull_index = (32 * range->start + src.offset) / 4;
2279 const unsigned location = src.nr + src.offset / 4;
2281 if (location < uniforms && pull_constant_loc[location] != -1) {
2282 /* A regular uniform push constant */
2283 *out_surf_index = stage_prog_data->binding_table.pull_constants_start;
2284 *out_pull_index = pull_constant_loc[location];
2292 * Replace UNIFORM register file access with either UNIFORM_PULL_CONSTANT_LOAD
2293 * or VARYING_PULL_CONSTANT_LOAD instructions which load values into VGRFs.
2296 fs_visitor::lower_constant_loads()
2298 unsigned index, pull_index;
2300 foreach_block_and_inst_safe (block, fs_inst, inst, cfg) {
2301 /* Set up the annotation tracking for new generated instructions. */
2302 const fs_builder ibld(this, block, inst);
2304 for (int i = 0; i < inst->sources; i++) {
2305 if (inst->src[i].file != UNIFORM)
2308 /* We'll handle this case later */
2309 if (inst->opcode == SHADER_OPCODE_MOV_INDIRECT && i == 0)
2312 if (!get_pull_locs(inst->src[i], &index, &pull_index))
2315 assert(inst->src[i].stride == 0);
2317 const unsigned block_sz = 64; /* Fetch one cacheline at a time. */
2318 const fs_builder ubld = ibld.exec_all().group(block_sz / 4, 0);
2319 const fs_reg dst = ubld.vgrf(BRW_REGISTER_TYPE_UD);
2320 const unsigned base = pull_index * 4;
2322 ubld.emit(FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD,
2323 dst, brw_imm_ud(index), brw_imm_ud(base & ~(block_sz - 1)));
2325 /* Rewrite the instruction to use the temporary VGRF. */
2326 inst->src[i].file = VGRF;
2327 inst->src[i].nr = dst.nr;
2328 inst->src[i].offset = (base & (block_sz - 1)) +
2329 inst->src[i].offset % 4;
2331 brw_mark_surface_used(prog_data, index);
2334 if (inst->opcode == SHADER_OPCODE_MOV_INDIRECT &&
2335 inst->src[0].file == UNIFORM) {
2337 if (!get_pull_locs(inst->src[0], &index, &pull_index))
2340 VARYING_PULL_CONSTANT_LOAD(ibld, inst->dst,
2344 inst->remove(block);
2346 brw_mark_surface_used(prog_data, index);
2349 invalidate_live_intervals();
2353 fs_visitor::opt_algebraic()
2355 bool progress = false;
2357 foreach_block_and_inst(block, fs_inst, inst, cfg) {
2358 switch (inst->opcode) {
2359 case BRW_OPCODE_MOV:
2360 if (inst->src[0].file != IMM)
2363 if (inst->saturate) {
2364 if (inst->dst.type != inst->src[0].type)
2365 assert(!"unimplemented: saturate mixed types");
2367 if (brw_saturate_immediate(inst->dst.type,
2368 &inst->src[0].as_brw_reg())) {
2369 inst->saturate = false;
2375 case BRW_OPCODE_MUL:
2376 if (inst->src[1].file != IMM)
2380 if (inst->src[1].is_one()) {
2381 inst->opcode = BRW_OPCODE_MOV;
2382 inst->src[1] = reg_undef;
2388 if (inst->src[1].is_negative_one()) {
2389 inst->opcode = BRW_OPCODE_MOV;
2390 inst->src[0].negate = !inst->src[0].negate;
2391 inst->src[1] = reg_undef;
2397 if (inst->src[1].is_zero()) {
2398 inst->opcode = BRW_OPCODE_MOV;
2399 inst->src[0] = inst->src[1];
2400 inst->src[1] = reg_undef;
2405 if (inst->src[0].file == IMM) {
2406 assert(inst->src[0].type == BRW_REGISTER_TYPE_F);
2407 inst->opcode = BRW_OPCODE_MOV;
2408 inst->src[0].f *= inst->src[1].f;
2409 inst->src[1] = reg_undef;
2414 case BRW_OPCODE_ADD:
2415 if (inst->src[1].file != IMM)
2419 if (inst->src[1].is_zero()) {
2420 inst->opcode = BRW_OPCODE_MOV;
2421 inst->src[1] = reg_undef;
2426 if (inst->src[0].file == IMM) {
2427 assert(inst->src[0].type == BRW_REGISTER_TYPE_F);
2428 inst->opcode = BRW_OPCODE_MOV;
2429 inst->src[0].f += inst->src[1].f;
2430 inst->src[1] = reg_undef;
2436 if (inst->src[0].equals(inst->src[1]) ||
2437 inst->src[1].is_zero()) {
2438 inst->opcode = BRW_OPCODE_MOV;
2439 inst->src[1] = reg_undef;
2444 case BRW_OPCODE_LRP:
2445 if (inst->src[1].equals(inst->src[2])) {
2446 inst->opcode = BRW_OPCODE_MOV;
2447 inst->src[0] = inst->src[1];
2448 inst->src[1] = reg_undef;
2449 inst->src[2] = reg_undef;
2454 case BRW_OPCODE_CMP:
2455 if (inst->conditional_mod == BRW_CONDITIONAL_GE &&
2457 inst->src[0].negate &&
2458 inst->src[1].is_zero()) {
2459 inst->src[0].abs = false;
2460 inst->src[0].negate = false;
2461 inst->conditional_mod = BRW_CONDITIONAL_Z;
2466 case BRW_OPCODE_SEL:
2467 if (inst->src[0].equals(inst->src[1])) {
2468 inst->opcode = BRW_OPCODE_MOV;
2469 inst->src[1] = reg_undef;
2470 inst->predicate = BRW_PREDICATE_NONE;
2471 inst->predicate_inverse = false;
2473 } else if (inst->saturate && inst->src[1].file == IMM) {
2474 switch (inst->conditional_mod) {
2475 case BRW_CONDITIONAL_LE:
2476 case BRW_CONDITIONAL_L:
2477 switch (inst->src[1].type) {
2478 case BRW_REGISTER_TYPE_F:
2479 if (inst->src[1].f >= 1.0f) {
2480 inst->opcode = BRW_OPCODE_MOV;
2481 inst->src[1] = reg_undef;
2482 inst->conditional_mod = BRW_CONDITIONAL_NONE;
2490 case BRW_CONDITIONAL_GE:
2491 case BRW_CONDITIONAL_G:
2492 switch (inst->src[1].type) {
2493 case BRW_REGISTER_TYPE_F:
2494 if (inst->src[1].f <= 0.0f) {
2495 inst->opcode = BRW_OPCODE_MOV;
2496 inst->src[1] = reg_undef;
2497 inst->conditional_mod = BRW_CONDITIONAL_NONE;
2509 case BRW_OPCODE_MAD:
2510 if (inst->src[1].is_zero() || inst->src[2].is_zero()) {
2511 inst->opcode = BRW_OPCODE_MOV;
2512 inst->src[1] = reg_undef;
2513 inst->src[2] = reg_undef;
2515 } else if (inst->src[0].is_zero()) {
2516 inst->opcode = BRW_OPCODE_MUL;
2517 inst->src[0] = inst->src[2];
2518 inst->src[2] = reg_undef;
2520 } else if (inst->src[1].is_one()) {
2521 inst->opcode = BRW_OPCODE_ADD;
2522 inst->src[1] = inst->src[2];
2523 inst->src[2] = reg_undef;
2525 } else if (inst->src[2].is_one()) {
2526 inst->opcode = BRW_OPCODE_ADD;
2527 inst->src[2] = reg_undef;
2529 } else if (inst->src[1].file == IMM && inst->src[2].file == IMM) {
2530 inst->opcode = BRW_OPCODE_ADD;
2531 inst->src[1].f *= inst->src[2].f;
2532 inst->src[2] = reg_undef;
2536 case SHADER_OPCODE_BROADCAST:
2537 if (is_uniform(inst->src[0])) {
2538 inst->opcode = BRW_OPCODE_MOV;
2540 inst->force_writemask_all = true;
2542 } else if (inst->src[1].file == IMM) {
2543 inst->opcode = BRW_OPCODE_MOV;
2544 /* It's possible that the selected component will be too large and
2545 * overflow the register. This can happen if someone does a
2546 * readInvocation() from GLSL or SPIR-V and provides an OOB
2547 * invocationIndex. If this happens and we some how manage
2548 * to constant fold it in and get here, then component() may cause
2549 * us to start reading outside of the VGRF which will lead to an
2550 * assert later. Instead, just let it wrap around if it goes over
2553 const unsigned comp = inst->src[1].ud & (inst->exec_size - 1);
2554 inst->src[0] = component(inst->src[0], comp);
2556 inst->force_writemask_all = true;
2561 case SHADER_OPCODE_SHUFFLE:
2562 if (is_uniform(inst->src[0])) {
2563 inst->opcode = BRW_OPCODE_MOV;
2566 } else if (inst->src[1].file == IMM) {
2567 inst->opcode = BRW_OPCODE_MOV;
2568 inst->src[0] = component(inst->src[0],
2579 /* Swap if src[0] is immediate. */
2580 if (progress && inst->is_commutative()) {
2581 if (inst->src[0].file == IMM) {
2582 fs_reg tmp = inst->src[1];
2583 inst->src[1] = inst->src[0];
2592 * Optimize sample messages that have constant zero values for the trailing
2593 * texture coordinates. We can just reduce the message length for these
2594 * instructions instead of reserving a register for it. Trailing parameters
2595 * that aren't sent default to zero anyway. This will cause the dead code
2596 * eliminator to remove the MOV instruction that would otherwise be emitted to
2597 * set up the zero value.
2600 fs_visitor::opt_zero_samples()
2602 /* Gen4 infers the texturing opcode based on the message length so we can't
2605 if (devinfo->gen < 5)
2608 bool progress = false;
2610 foreach_block_and_inst(block, fs_inst, inst, cfg) {
2611 if (!inst->is_tex())
2614 fs_inst *load_payload = (fs_inst *) inst->prev;
2616 if (load_payload->is_head_sentinel() ||
2617 load_payload->opcode != SHADER_OPCODE_LOAD_PAYLOAD)
2620 /* We don't want to remove the message header or the first parameter.
2621 * Removing the first parameter is not allowed, see the Haswell PRM
2622 * volume 7, page 149:
2624 * "Parameter 0 is required except for the sampleinfo message, which
2625 * has no parameter 0"
2627 while (inst->mlen > inst->header_size + inst->exec_size / 8 &&
2628 load_payload->src[(inst->mlen - inst->header_size) /
2629 (inst->exec_size / 8) +
2630 inst->header_size - 1].is_zero()) {
2631 inst->mlen -= inst->exec_size / 8;
2637 invalidate_live_intervals();
2643 * Optimize sample messages which are followed by the final RT write.
2645 * CHV, and GEN9+ can mark a texturing SEND instruction with EOT to have its
2646 * results sent directly to the framebuffer, bypassing the EU. Recognize the
2647 * final texturing results copied to the framebuffer write payload and modify
2648 * them to write to the framebuffer directly.
2651 fs_visitor::opt_sampler_eot()
2653 brw_wm_prog_key *key = (brw_wm_prog_key*) this->key;
2655 if (stage != MESA_SHADER_FRAGMENT || dispatch_width > 16)
2658 if (devinfo->gen != 9 && !devinfo->is_cherryview)
2661 /* FINISHME: It should be possible to implement this optimization when there
2662 * are multiple drawbuffers.
2664 if (key->nr_color_regions != 1)
2667 /* Requires emitting a bunch of saturating MOV instructions during logical
2668 * send lowering to clamp the color payload, which the sampler unit isn't
2669 * going to do for us.
2671 if (key->clamp_fragment_color)
2674 /* Look for a texturing instruction immediately before the final FB_WRITE. */
2675 bblock_t *block = cfg->blocks[cfg->num_blocks - 1];
2676 fs_inst *fb_write = (fs_inst *)block->end();
2677 assert(fb_write->eot);
2678 assert(fb_write->opcode == FS_OPCODE_FB_WRITE_LOGICAL);
2680 /* There wasn't one; nothing to do. */
2681 if (unlikely(fb_write->prev->is_head_sentinel()))
2684 fs_inst *tex_inst = (fs_inst *) fb_write->prev;
2686 /* 3D Sampler » Messages » Message Format
2688 * “Response Length of zero is allowed on all SIMD8* and SIMD16* sampler
2689 * messages except sample+killpix, resinfo, sampleinfo, LOD, and gather4*”
2691 if (tex_inst->opcode != SHADER_OPCODE_TEX_LOGICAL &&
2692 tex_inst->opcode != SHADER_OPCODE_TXD_LOGICAL &&
2693 tex_inst->opcode != SHADER_OPCODE_TXF_LOGICAL &&
2694 tex_inst->opcode != SHADER_OPCODE_TXL_LOGICAL &&
2695 tex_inst->opcode != FS_OPCODE_TXB_LOGICAL &&
2696 tex_inst->opcode != SHADER_OPCODE_TXF_CMS_LOGICAL &&
2697 tex_inst->opcode != SHADER_OPCODE_TXF_CMS_W_LOGICAL &&
2698 tex_inst->opcode != SHADER_OPCODE_TXF_UMS_LOGICAL)
2701 /* XXX - This shouldn't be necessary. */
2702 if (tex_inst->prev->is_head_sentinel())
2705 /* Check that the FB write sources are fully initialized by the single
2706 * texturing instruction.
2708 for (unsigned i = 0; i < FB_WRITE_LOGICAL_NUM_SRCS; i++) {
2709 if (i == FB_WRITE_LOGICAL_SRC_COLOR0) {
2710 if (!fb_write->src[i].equals(tex_inst->dst) ||
2711 fb_write->size_read(i) != tex_inst->size_written)
2713 } else if (i != FB_WRITE_LOGICAL_SRC_COMPONENTS) {
2714 if (fb_write->src[i].file != BAD_FILE)
2719 assert(!tex_inst->eot); /* We can't get here twice */
2720 assert((tex_inst->offset & (0xff << 24)) == 0);
2722 const fs_builder ibld(this, block, tex_inst);
2724 tex_inst->offset |= fb_write->target << 24;
2725 tex_inst->eot = true;
2726 tex_inst->dst = ibld.null_reg_ud();
2727 tex_inst->size_written = 0;
2728 fb_write->remove(cfg->blocks[cfg->num_blocks - 1]);
2730 /* Marking EOT is sufficient, lower_logical_sends() will notice the EOT
2731 * flag and submit a header together with the sampler message as required
2734 invalidate_live_intervals();
2739 fs_visitor::opt_register_renaming()
2741 bool progress = false;
2744 int remap[alloc.count];
2745 memset(remap, -1, sizeof(int) * alloc.count);
2747 foreach_block_and_inst(block, fs_inst, inst, cfg) {
2748 if (inst->opcode == BRW_OPCODE_IF || inst->opcode == BRW_OPCODE_DO) {
2750 } else if (inst->opcode == BRW_OPCODE_ENDIF ||
2751 inst->opcode == BRW_OPCODE_WHILE) {
2755 /* Rewrite instruction sources. */
2756 for (int i = 0; i < inst->sources; i++) {
2757 if (inst->src[i].file == VGRF &&
2758 remap[inst->src[i].nr] != -1 &&
2759 remap[inst->src[i].nr] != inst->src[i].nr) {
2760 inst->src[i].nr = remap[inst->src[i].nr];
2765 const int dst = inst->dst.nr;
2768 inst->dst.file == VGRF &&
2769 alloc.sizes[inst->dst.nr] * REG_SIZE == inst->size_written &&
2770 !inst->is_partial_write()) {
2771 if (remap[dst] == -1) {
2774 remap[dst] = alloc.allocate(regs_written(inst));
2775 inst->dst.nr = remap[dst];
2778 } else if (inst->dst.file == VGRF &&
2780 remap[dst] != dst) {
2781 inst->dst.nr = remap[dst];
2787 invalidate_live_intervals();
2789 for (unsigned i = 0; i < ARRAY_SIZE(delta_xy); i++) {
2790 if (delta_xy[i].file == VGRF && remap[delta_xy[i].nr] != -1) {
2791 delta_xy[i].nr = remap[delta_xy[i].nr];
2800 * Remove redundant or useless discard jumps.
2802 * For example, we can eliminate jumps in the following sequence:
2804 * discard-jump (redundant with the next jump)
2805 * discard-jump (useless; jumps to the next instruction)
2809 fs_visitor::opt_redundant_discard_jumps()
2811 bool progress = false;
2813 bblock_t *last_bblock = cfg->blocks[cfg->num_blocks - 1];
2815 fs_inst *placeholder_halt = NULL;
2816 foreach_inst_in_block_reverse(fs_inst, inst, last_bblock) {
2817 if (inst->opcode == FS_OPCODE_PLACEHOLDER_HALT) {
2818 placeholder_halt = inst;
2823 if (!placeholder_halt)
2826 /* Delete any HALTs immediately before the placeholder halt. */
2827 for (fs_inst *prev = (fs_inst *) placeholder_halt->prev;
2828 !prev->is_head_sentinel() && prev->opcode == FS_OPCODE_DISCARD_JUMP;
2829 prev = (fs_inst *) placeholder_halt->prev) {
2830 prev->remove(last_bblock);
2835 invalidate_live_intervals();
2841 * Compute a bitmask with GRF granularity with a bit set for each GRF starting
2842 * from \p r.offset which overlaps the region starting at \p s.offset and
2843 * spanning \p ds bytes.
2845 static inline unsigned
2846 mask_relative_to(const fs_reg &r, const fs_reg &s, unsigned ds)
2848 const int rel_offset = reg_offset(s) - reg_offset(r);
2849 const int shift = rel_offset / REG_SIZE;
2850 const unsigned n = DIV_ROUND_UP(rel_offset % REG_SIZE + ds, REG_SIZE);
2851 assert(reg_space(r) == reg_space(s) &&
2852 shift >= 0 && shift < int(8 * sizeof(unsigned)));
2853 return ((1 << n) - 1) << shift;
2857 fs_visitor::opt_peephole_csel()
2859 if (devinfo->gen < 8)
2862 bool progress = false;
2864 foreach_block_reverse(block, cfg) {
2865 int ip = block->end_ip + 1;
2867 foreach_inst_in_block_reverse_safe(fs_inst, inst, block) {
2870 if (inst->opcode != BRW_OPCODE_SEL ||
2871 inst->predicate != BRW_PREDICATE_NORMAL ||
2872 (inst->dst.type != BRW_REGISTER_TYPE_F &&
2873 inst->dst.type != BRW_REGISTER_TYPE_D &&
2874 inst->dst.type != BRW_REGISTER_TYPE_UD))
2877 /* Because it is a 3-src instruction, CSEL cannot have an immediate
2878 * value as a source, but we can sometimes handle zero.
2880 if ((inst->src[0].file != VGRF && inst->src[0].file != ATTR &&
2881 inst->src[0].file != UNIFORM) ||
2882 (inst->src[1].file != VGRF && inst->src[1].file != ATTR &&
2883 inst->src[1].file != UNIFORM && !inst->src[1].is_zero()))
2886 foreach_inst_in_block_reverse_starting_from(fs_inst, scan_inst, inst) {
2887 if (!scan_inst->flags_written())
2890 if ((scan_inst->opcode != BRW_OPCODE_CMP &&
2891 scan_inst->opcode != BRW_OPCODE_MOV) ||
2892 scan_inst->predicate != BRW_PREDICATE_NONE ||
2893 (scan_inst->src[0].file != VGRF &&
2894 scan_inst->src[0].file != ATTR &&
2895 scan_inst->src[0].file != UNIFORM) ||
2896 scan_inst->src[0].type != BRW_REGISTER_TYPE_F)
2899 if (scan_inst->opcode == BRW_OPCODE_CMP && !scan_inst->src[1].is_zero())
2902 const brw::fs_builder ibld(this, block, inst);
2904 const enum brw_conditional_mod cond =
2905 inst->predicate_inverse
2906 ? brw_negate_cmod(scan_inst->conditional_mod)
2907 : scan_inst->conditional_mod;
2909 fs_inst *csel_inst = NULL;
2911 if (inst->src[1].file != IMM) {
2912 csel_inst = ibld.CSEL(inst->dst,
2917 } else if (cond == BRW_CONDITIONAL_NZ) {
2918 /* Consider the sequence
2920 * cmp.nz.f0 null<1>F g3<8,8,1>F 0F
2921 * (+f0) sel g124<1>UD g2<8,8,1>UD 0x00000000UD
2923 * The sel will pick the immediate value 0 if r0 is ±0.0.
2924 * Therefore, this sequence is equivalent:
2926 * cmp.nz.f0 null<1>F g3<8,8,1>F 0F
2927 * (+f0) sel g124<1>F g2<8,8,1>F (abs)g3<8,8,1>F
2929 * The abs is ensures that the result is 0UD when g3 is -0.0F.
2930 * By normal cmp-sel merging, this is also equivalent:
2932 * csel.nz g124<1>F g2<4,4,1>F (abs)g3<4,4,1>F g3<4,4,1>F
2934 csel_inst = ibld.CSEL(inst->dst,
2940 csel_inst->src[1].abs = true;
2943 if (csel_inst != NULL) {
2945 inst->remove(block);
2957 fs_visitor::compute_to_mrf()
2959 bool progress = false;
2962 /* No MRFs on Gen >= 7. */
2963 if (devinfo->gen >= 7)
2966 calculate_live_intervals();
2968 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
2972 if (inst->opcode != BRW_OPCODE_MOV ||
2973 inst->is_partial_write() ||
2974 inst->dst.file != MRF || inst->src[0].file != VGRF ||
2975 inst->dst.type != inst->src[0].type ||
2976 inst->src[0].abs || inst->src[0].negate ||
2977 !inst->src[0].is_contiguous() ||
2978 inst->src[0].offset % REG_SIZE != 0)
2981 /* Can't compute-to-MRF this GRF if someone else was going to
2984 if (this->virtual_grf_end[inst->src[0].nr] > ip)
2987 /* Found a move of a GRF to a MRF. Let's see if we can go rewrite the
2988 * things that computed the value of all GRFs of the source region. The
2989 * regs_left bitset keeps track of the registers we haven't yet found a
2990 * generating instruction for.
2992 unsigned regs_left = (1 << regs_read(inst, 0)) - 1;
2994 foreach_inst_in_block_reverse_starting_from(fs_inst, scan_inst, inst) {
2995 if (regions_overlap(scan_inst->dst, scan_inst->size_written,
2996 inst->src[0], inst->size_read(0))) {
2997 /* Found the last thing to write our reg we want to turn
2998 * into a compute-to-MRF.
3001 /* If this one instruction didn't populate all the
3002 * channels, bail. We might be able to rewrite everything
3003 * that writes that reg, but it would require smarter
3006 if (scan_inst->is_partial_write())
3009 /* Handling things not fully contained in the source of the copy
3010 * would need us to understand coalescing out more than one MOV at
3013 if (!region_contained_in(scan_inst->dst, scan_inst->size_written,
3014 inst->src[0], inst->size_read(0)))
3017 /* SEND instructions can't have MRF as a destination. */
3018 if (scan_inst->mlen)
3021 if (devinfo->gen == 6) {
3022 /* gen6 math instructions must have the destination be
3023 * GRF, so no compute-to-MRF for them.
3025 if (scan_inst->is_math()) {
3030 /* Clear the bits for any registers this instruction overwrites. */
3031 regs_left &= ~mask_relative_to(
3032 inst->src[0], scan_inst->dst, scan_inst->size_written);
3037 /* We don't handle control flow here. Most computation of
3038 * values that end up in MRFs are shortly before the MRF
3041 if (block->start() == scan_inst)
3044 /* You can't read from an MRF, so if someone else reads our
3045 * MRF's source GRF that we wanted to rewrite, that stops us.
3047 bool interfered = false;
3048 for (int i = 0; i < scan_inst->sources; i++) {
3049 if (regions_overlap(scan_inst->src[i], scan_inst->size_read(i),
3050 inst->src[0], inst->size_read(0))) {
3057 if (regions_overlap(scan_inst->dst, scan_inst->size_written,
3058 inst->dst, inst->size_written)) {
3059 /* If somebody else writes our MRF here, we can't
3060 * compute-to-MRF before that.
3065 if (scan_inst->mlen > 0 && scan_inst->base_mrf != -1 &&
3066 regions_overlap(fs_reg(MRF, scan_inst->base_mrf), scan_inst->mlen * REG_SIZE,
3067 inst->dst, inst->size_written)) {
3068 /* Found a SEND instruction, which means that there are
3069 * live values in MRFs from base_mrf to base_mrf +
3070 * scan_inst->mlen - 1. Don't go pushing our MRF write up
3080 /* Found all generating instructions of our MRF's source value, so it
3081 * should be safe to rewrite them to point to the MRF directly.
3083 regs_left = (1 << regs_read(inst, 0)) - 1;
3085 foreach_inst_in_block_reverse_starting_from(fs_inst, scan_inst, inst) {
3086 if (regions_overlap(scan_inst->dst, scan_inst->size_written,
3087 inst->src[0], inst->size_read(0))) {
3088 /* Clear the bits for any registers this instruction overwrites. */
3089 regs_left &= ~mask_relative_to(
3090 inst->src[0], scan_inst->dst, scan_inst->size_written);
3092 const unsigned rel_offset = reg_offset(scan_inst->dst) -
3093 reg_offset(inst->src[0]);
3095 if (inst->dst.nr & BRW_MRF_COMPR4) {
3096 /* Apply the same address transformation done by the hardware
3097 * for COMPR4 MRF writes.
3099 assert(rel_offset < 2 * REG_SIZE);
3100 scan_inst->dst.nr = inst->dst.nr + rel_offset / REG_SIZE * 4;
3102 /* Clear the COMPR4 bit if the generating instruction is not
3105 if (scan_inst->size_written < 2 * REG_SIZE)
3106 scan_inst->dst.nr &= ~BRW_MRF_COMPR4;
3109 /* Calculate the MRF number the result of this instruction is
3110 * ultimately written to.
3112 scan_inst->dst.nr = inst->dst.nr + rel_offset / REG_SIZE;
3115 scan_inst->dst.file = MRF;
3116 scan_inst->dst.offset = inst->dst.offset + rel_offset % REG_SIZE;
3117 scan_inst->saturate |= inst->saturate;
3124 inst->remove(block);
3129 invalidate_live_intervals();
3135 * Eliminate FIND_LIVE_CHANNEL instructions occurring outside any control
3136 * flow. We could probably do better here with some form of divergence
3140 fs_visitor::eliminate_find_live_channel()
3142 bool progress = false;
3145 if (!brw_stage_has_packed_dispatch(devinfo, stage, stage_prog_data)) {
3146 /* The optimization below assumes that channel zero is live on thread
3147 * dispatch, which may not be the case if the fixed function dispatches
3153 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
3154 switch (inst->opcode) {
3160 case BRW_OPCODE_ENDIF:
3161 case BRW_OPCODE_WHILE:
3165 case FS_OPCODE_DISCARD_JUMP:
3166 /* This can potentially make control flow non-uniform until the end
3171 case SHADER_OPCODE_FIND_LIVE_CHANNEL:
3173 inst->opcode = BRW_OPCODE_MOV;
3174 inst->src[0] = brw_imm_ud(0u);
3176 inst->force_writemask_all = true;
3190 * Once we've generated code, try to convert normal FS_OPCODE_FB_WRITE
3191 * instructions to FS_OPCODE_REP_FB_WRITE.
3194 fs_visitor::emit_repclear_shader()
3196 brw_wm_prog_key *key = (brw_wm_prog_key*) this->key;
3198 int color_mrf = base_mrf + 2;
3202 mov = bld.exec_all().group(4, 0)
3203 .MOV(brw_message_reg(color_mrf),
3204 fs_reg(UNIFORM, 0, BRW_REGISTER_TYPE_F));
3206 struct brw_reg reg =
3207 brw_reg(BRW_GENERAL_REGISTER_FILE, 2, 3, 0, 0, BRW_REGISTER_TYPE_F,
3208 BRW_VERTICAL_STRIDE_8, BRW_WIDTH_2, BRW_HORIZONTAL_STRIDE_4,
3209 BRW_SWIZZLE_XYZW, WRITEMASK_XYZW);
3211 mov = bld.exec_all().group(4, 0)
3212 .MOV(vec4(brw_message_reg(color_mrf)), fs_reg(reg));
3215 fs_inst *write = NULL;
3216 if (key->nr_color_regions == 1) {
3217 write = bld.emit(FS_OPCODE_REP_FB_WRITE);
3218 write->saturate = key->clamp_fragment_color;
3219 write->base_mrf = color_mrf;
3221 write->header_size = 0;
3224 assume(key->nr_color_regions > 0);
3226 struct brw_reg header =
3227 retype(brw_message_reg(base_mrf), BRW_REGISTER_TYPE_UD);
3228 bld.exec_all().group(16, 0)
3229 .MOV(header, retype(brw_vec8_grf(0, 0), BRW_REGISTER_TYPE_UD));
3231 for (int i = 0; i < key->nr_color_regions; ++i) {
3233 bld.exec_all().group(1, 0)
3234 .MOV(component(header, 2), brw_imm_ud(i));
3237 write = bld.emit(FS_OPCODE_REP_FB_WRITE);
3238 write->saturate = key->clamp_fragment_color;
3239 write->base_mrf = base_mrf;
3241 write->header_size = 2;
3246 write->last_rt = true;
3250 assign_constant_locations();
3251 assign_curb_setup();
3253 /* Now that we have the uniform assigned, go ahead and force it to a vec4. */
3255 assert(mov->src[0].file == FIXED_GRF);
3256 mov->src[0] = brw_vec4_grf(mov->src[0].nr, 0);
3261 * Walks through basic blocks, looking for repeated MRF writes and
3262 * removing the later ones.
3265 fs_visitor::remove_duplicate_mrf_writes()
3267 fs_inst *last_mrf_move[BRW_MAX_MRF(devinfo->gen)];
3268 bool progress = false;
3270 /* Need to update the MRF tracking for compressed instructions. */
3271 if (dispatch_width >= 16)
3274 memset(last_mrf_move, 0, sizeof(last_mrf_move));
3276 foreach_block_and_inst_safe (block, fs_inst, inst, cfg) {
3277 if (inst->is_control_flow()) {
3278 memset(last_mrf_move, 0, sizeof(last_mrf_move));
3281 if (inst->opcode == BRW_OPCODE_MOV &&
3282 inst->dst.file == MRF) {
3283 fs_inst *prev_inst = last_mrf_move[inst->dst.nr];
3284 if (prev_inst && inst->equals(prev_inst)) {
3285 inst->remove(block);
3291 /* Clear out the last-write records for MRFs that were overwritten. */
3292 if (inst->dst.file == MRF) {
3293 last_mrf_move[inst->dst.nr] = NULL;
3296 if (inst->mlen > 0 && inst->base_mrf != -1) {
3297 /* Found a SEND instruction, which will include two or fewer
3298 * implied MRF writes. We could do better here.
3300 for (int i = 0; i < implied_mrf_writes(inst); i++) {
3301 last_mrf_move[inst->base_mrf + i] = NULL;
3305 /* Clear out any MRF move records whose sources got overwritten. */
3306 for (unsigned i = 0; i < ARRAY_SIZE(last_mrf_move); i++) {
3307 if (last_mrf_move[i] &&
3308 regions_overlap(inst->dst, inst->size_written,
3309 last_mrf_move[i]->src[0],
3310 last_mrf_move[i]->size_read(0))) {
3311 last_mrf_move[i] = NULL;
3315 if (inst->opcode == BRW_OPCODE_MOV &&
3316 inst->dst.file == MRF &&
3317 inst->src[0].file != ARF &&
3318 !inst->is_partial_write()) {
3319 last_mrf_move[inst->dst.nr] = inst;
3324 invalidate_live_intervals();
3330 * Rounding modes for conversion instructions are included for each
3331 * conversion, but right now it is a state. So once it is set,
3332 * we don't need to call it again for subsequent calls.
3334 * This is useful for vector/matrices conversions, as setting the
3335 * mode once is enough for the full vector/matrix
3338 fs_visitor::remove_extra_rounding_modes()
3340 bool progress = false;
3342 foreach_block (block, cfg) {
3343 brw_rnd_mode prev_mode = BRW_RND_MODE_UNSPECIFIED;
3345 foreach_inst_in_block_safe (fs_inst, inst, block) {
3346 if (inst->opcode == SHADER_OPCODE_RND_MODE) {
3347 assert(inst->src[0].file == BRW_IMMEDIATE_VALUE);
3348 const brw_rnd_mode mode = (brw_rnd_mode) inst->src[0].d;
3349 if (mode == prev_mode) {
3350 inst->remove(block);
3360 invalidate_live_intervals();
3366 clear_deps_for_inst_src(fs_inst *inst, bool *deps, int first_grf, int grf_len)
3368 /* Clear the flag for registers that actually got read (as expected). */
3369 for (int i = 0; i < inst->sources; i++) {
3371 if (inst->src[i].file == VGRF || inst->src[i].file == FIXED_GRF) {
3372 grf = inst->src[i].nr;
3377 if (grf >= first_grf &&
3378 grf < first_grf + grf_len) {
3379 deps[grf - first_grf] = false;
3380 if (inst->exec_size == 16)
3381 deps[grf - first_grf + 1] = false;
3387 * Implements this workaround for the original 965:
3389 * "[DevBW, DevCL] Implementation Restrictions: As the hardware does not
3390 * check for post destination dependencies on this instruction, software
3391 * must ensure that there is no destination hazard for the case of ‘write
3392 * followed by a posted write’ shown in the following example.
3395 * 2. send r3.xy <rest of send instruction>
3398 * Due to no post-destination dependency check on the ‘send’, the above
3399 * code sequence could have two instructions (1 and 2) in flight at the
3400 * same time that both consider ‘r3’ as the target of their final writes.
3403 fs_visitor::insert_gen4_pre_send_dependency_workarounds(bblock_t *block,
3406 int write_len = regs_written(inst);
3407 int first_write_grf = inst->dst.nr;
3408 bool needs_dep[BRW_MAX_MRF(devinfo->gen)];
3409 assert(write_len < (int)sizeof(needs_dep) - 1);
3411 memset(needs_dep, false, sizeof(needs_dep));
3412 memset(needs_dep, true, write_len);
3414 clear_deps_for_inst_src(inst, needs_dep, first_write_grf, write_len);
3416 /* Walk backwards looking for writes to registers we're writing which
3417 * aren't read since being written. If we hit the start of the program,
3418 * we assume that there are no outstanding dependencies on entry to the
3421 foreach_inst_in_block_reverse_starting_from(fs_inst, scan_inst, inst) {
3422 /* If we hit control flow, assume that there *are* outstanding
3423 * dependencies, and force their cleanup before our instruction.
3425 if (block->start() == scan_inst && block->num != 0) {
3426 for (int i = 0; i < write_len; i++) {
3428 DEP_RESOLVE_MOV(fs_builder(this, block, inst),
3429 first_write_grf + i);
3434 /* We insert our reads as late as possible on the assumption that any
3435 * instruction but a MOV that might have left us an outstanding
3436 * dependency has more latency than a MOV.
3438 if (scan_inst->dst.file == VGRF) {
3439 for (unsigned i = 0; i < regs_written(scan_inst); i++) {
3440 int reg = scan_inst->dst.nr + i;
3442 if (reg >= first_write_grf &&
3443 reg < first_write_grf + write_len &&
3444 needs_dep[reg - first_write_grf]) {
3445 DEP_RESOLVE_MOV(fs_builder(this, block, inst), reg);
3446 needs_dep[reg - first_write_grf] = false;
3447 if (scan_inst->exec_size == 16)
3448 needs_dep[reg - first_write_grf + 1] = false;
3453 /* Clear the flag for registers that actually got read (as expected). */
3454 clear_deps_for_inst_src(scan_inst, needs_dep, first_write_grf, write_len);
3456 /* Continue the loop only if we haven't resolved all the dependencies */
3458 for (i = 0; i < write_len; i++) {
3468 * Implements this workaround for the original 965:
3470 * "[DevBW, DevCL] Errata: A destination register from a send can not be
3471 * used as a destination register until after it has been sourced by an
3472 * instruction with a different destination register.
3475 fs_visitor::insert_gen4_post_send_dependency_workarounds(bblock_t *block, fs_inst *inst)
3477 int write_len = regs_written(inst);
3478 int first_write_grf = inst->dst.nr;
3479 bool needs_dep[BRW_MAX_MRF(devinfo->gen)];
3480 assert(write_len < (int)sizeof(needs_dep) - 1);
3482 memset(needs_dep, false, sizeof(needs_dep));
3483 memset(needs_dep, true, write_len);
3484 /* Walk forwards looking for writes to registers we're writing which aren't
3485 * read before being written.
3487 foreach_inst_in_block_starting_from(fs_inst, scan_inst, inst) {
3488 /* If we hit control flow, force resolve all remaining dependencies. */
3489 if (block->end() == scan_inst && block->num != cfg->num_blocks - 1) {
3490 for (int i = 0; i < write_len; i++) {
3492 DEP_RESOLVE_MOV(fs_builder(this, block, scan_inst),
3493 first_write_grf + i);
3498 /* Clear the flag for registers that actually got read (as expected). */
3499 clear_deps_for_inst_src(scan_inst, needs_dep, first_write_grf, write_len);
3501 /* We insert our reads as late as possible since they're reading the
3502 * result of a SEND, which has massive latency.
3504 if (scan_inst->dst.file == VGRF &&
3505 scan_inst->dst.nr >= first_write_grf &&
3506 scan_inst->dst.nr < first_write_grf + write_len &&
3507 needs_dep[scan_inst->dst.nr - first_write_grf]) {
3508 DEP_RESOLVE_MOV(fs_builder(this, block, scan_inst),
3510 needs_dep[scan_inst->dst.nr - first_write_grf] = false;
3513 /* Continue the loop only if we haven't resolved all the dependencies */
3515 for (i = 0; i < write_len; i++) {
3525 fs_visitor::insert_gen4_send_dependency_workarounds()
3527 if (devinfo->gen != 4 || devinfo->is_g4x)
3530 bool progress = false;
3532 foreach_block_and_inst(block, fs_inst, inst, cfg) {
3533 if (inst->mlen != 0 && inst->dst.file == VGRF) {
3534 insert_gen4_pre_send_dependency_workarounds(block, inst);
3535 insert_gen4_post_send_dependency_workarounds(block, inst);
3541 invalidate_live_intervals();
3545 * Turns the generic expression-style uniform pull constant load instruction
3546 * into a hardware-specific series of instructions for loading a pull
3549 * The expression style allows the CSE pass before this to optimize out
3550 * repeated loads from the same offset, and gives the pre-register-allocation
3551 * scheduling full flexibility, while the conversion to native instructions
3552 * allows the post-register-allocation scheduler the best information
3555 * Note that execution masking for setting up pull constant loads is special:
3556 * the channels that need to be written are unrelated to the current execution
3557 * mask, since a later instruction will use one of the result channels as a
3558 * source operand for all 8 or 16 of its channels.
3561 fs_visitor::lower_uniform_pull_constant_loads()
3563 foreach_block_and_inst (block, fs_inst, inst, cfg) {
3564 if (inst->opcode != FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD)
3567 if (devinfo->gen >= 7) {
3568 const fs_builder ubld = fs_builder(this, block, inst).exec_all();
3569 const fs_reg payload = ubld.group(8, 0).vgrf(BRW_REGISTER_TYPE_UD);
3571 ubld.group(8, 0).MOV(payload,
3572 retype(brw_vec8_grf(0, 0), BRW_REGISTER_TYPE_UD));
3573 ubld.group(1, 0).MOV(component(payload, 2),
3574 brw_imm_ud(inst->src[1].ud / 16));
3576 inst->opcode = FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD_GEN7;
3577 inst->src[1] = payload;
3578 inst->header_size = 1;
3581 invalidate_live_intervals();
3583 /* Before register allocation, we didn't tell the scheduler about the
3584 * MRF we use. We know it's safe to use this MRF because nothing
3585 * else does except for register spill/unspill, which generates and
3586 * uses its MRF within a single IR instruction.
3588 inst->base_mrf = FIRST_PULL_LOAD_MRF(devinfo->gen) + 1;
3595 fs_visitor::lower_load_payload()
3597 bool progress = false;
3599 foreach_block_and_inst_safe (block, fs_inst, inst, cfg) {
3600 if (inst->opcode != SHADER_OPCODE_LOAD_PAYLOAD)
3603 assert(inst->dst.file == MRF || inst->dst.file == VGRF);
3604 assert(inst->saturate == false);
3605 fs_reg dst = inst->dst;
3607 /* Get rid of COMPR4. We'll add it back in if we need it */
3608 if (dst.file == MRF)
3609 dst.nr = dst.nr & ~BRW_MRF_COMPR4;
3611 const fs_builder ibld(this, block, inst);
3612 const fs_builder hbld = ibld.exec_all().group(8, 0);
3614 for (uint8_t i = 0; i < inst->header_size; i++) {
3615 if (inst->src[i].file != BAD_FILE) {
3616 fs_reg mov_dst = retype(dst, BRW_REGISTER_TYPE_UD);
3617 fs_reg mov_src = retype(inst->src[i], BRW_REGISTER_TYPE_UD);
3618 hbld.MOV(mov_dst, mov_src);
3620 dst = offset(dst, hbld, 1);
3623 if (inst->dst.file == MRF && (inst->dst.nr & BRW_MRF_COMPR4) &&
3624 inst->exec_size > 8) {
3625 /* In this case, the payload portion of the LOAD_PAYLOAD isn't
3626 * a straightforward copy. Instead, the result of the
3627 * LOAD_PAYLOAD is treated as interleaved and the first four
3628 * non-header sources are unpacked as:
3639 * This is used for gen <= 5 fb writes.
3641 assert(inst->exec_size == 16);
3642 assert(inst->header_size + 4 <= inst->sources);
3643 for (uint8_t i = inst->header_size; i < inst->header_size + 4; i++) {
3644 if (inst->src[i].file != BAD_FILE) {
3645 if (devinfo->has_compr4) {
3646 fs_reg compr4_dst = retype(dst, inst->src[i].type);
3647 compr4_dst.nr |= BRW_MRF_COMPR4;
3648 ibld.MOV(compr4_dst, inst->src[i]);
3650 /* Platform doesn't have COMPR4. We have to fake it */
3651 fs_reg mov_dst = retype(dst, inst->src[i].type);
3652 ibld.half(0).MOV(mov_dst, half(inst->src[i], 0));
3654 ibld.half(1).MOV(mov_dst, half(inst->src[i], 1));
3661 /* The loop above only ever incremented us through the first set
3662 * of 4 registers. However, thanks to the magic of COMPR4, we
3663 * actually wrote to the first 8 registers, so we need to take
3664 * that into account now.
3668 /* The COMPR4 code took care of the first 4 sources. We'll let
3669 * the regular path handle any remaining sources. Yes, we are
3670 * modifying the instruction but we're about to delete it so
3671 * this really doesn't hurt anything.
3673 inst->header_size += 4;
3676 for (uint8_t i = inst->header_size; i < inst->sources; i++) {
3677 if (inst->src[i].file != BAD_FILE)
3678 ibld.MOV(retype(dst, inst->src[i].type), inst->src[i]);
3679 dst = offset(dst, ibld, 1);
3682 inst->remove(block);
3687 invalidate_live_intervals();
3693 fs_visitor::lower_integer_multiplication()
3695 bool progress = false;
3697 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
3698 const fs_builder ibld(this, block, inst);
3700 if (inst->opcode == BRW_OPCODE_MUL) {
3701 if (inst->dst.is_accumulator() ||
3702 (inst->dst.type != BRW_REGISTER_TYPE_D &&
3703 inst->dst.type != BRW_REGISTER_TYPE_UD))
3706 if (devinfo->has_integer_dword_mul)
3709 if (inst->src[1].file == IMM &&
3710 inst->src[1].ud < (1 << 16)) {
3711 /* The MUL instruction isn't commutative. On Gen <= 6, only the low
3712 * 16-bits of src0 are read, and on Gen >= 7 only the low 16-bits of
3715 * If multiplying by an immediate value that fits in 16-bits, do a
3716 * single MUL instruction with that value in the proper location.
3718 if (devinfo->gen < 7) {
3719 fs_reg imm(VGRF, alloc.allocate(dispatch_width / 8),
3721 ibld.MOV(imm, inst->src[1]);
3722 ibld.MUL(inst->dst, imm, inst->src[0]);
3724 const bool ud = (inst->src[1].type == BRW_REGISTER_TYPE_UD);
3725 ibld.MUL(inst->dst, inst->src[0],
3726 ud ? brw_imm_uw(inst->src[1].ud)
3727 : brw_imm_w(inst->src[1].d));
3730 /* Gen < 8 (and some Gen8+ low-power parts like Cherryview) cannot
3731 * do 32-bit integer multiplication in one instruction, but instead
3732 * must do a sequence (which actually calculates a 64-bit result):
3734 * mul(8) acc0<1>D g3<8,8,1>D g4<8,8,1>D
3735 * mach(8) null g3<8,8,1>D g4<8,8,1>D
3736 * mov(8) g2<1>D acc0<8,8,1>D
3738 * But on Gen > 6, the ability to use second accumulator register
3739 * (acc1) for non-float data types was removed, preventing a simple
3740 * implementation in SIMD16. A 16-channel result can be calculated by
3741 * executing the three instructions twice in SIMD8, once with quarter
3742 * control of 1Q for the first eight channels and again with 2Q for
3743 * the second eight channels.
3745 * Which accumulator register is implicitly accessed (by AccWrEnable
3746 * for instance) is determined by the quarter control. Unfortunately
3747 * Ivybridge (and presumably Baytrail) has a hardware bug in which an
3748 * implicit accumulator access by an instruction with 2Q will access
3749 * acc1 regardless of whether the data type is usable in acc1.
3751 * Specifically, the 2Q mach(8) writes acc1 which does not exist for
3752 * integer data types.
3754 * Since we only want the low 32-bits of the result, we can do two
3755 * 32-bit x 16-bit multiplies (like the mul and mach are doing), and
3756 * adjust the high result and add them (like the mach is doing):
3758 * mul(8) g7<1>D g3<8,8,1>D g4.0<8,8,1>UW
3759 * mul(8) g8<1>D g3<8,8,1>D g4.1<8,8,1>UW
3760 * shl(8) g9<1>D g8<8,8,1>D 16D
3761 * add(8) g2<1>D g7<8,8,1>D g8<8,8,1>D
3763 * We avoid the shl instruction by realizing that we only want to add
3764 * the low 16-bits of the "high" result to the high 16-bits of the
3765 * "low" result and using proper regioning on the add:
3767 * mul(8) g7<1>D g3<8,8,1>D g4.0<16,8,2>UW
3768 * mul(8) g8<1>D g3<8,8,1>D g4.1<16,8,2>UW
3769 * add(8) g7.1<2>UW g7.1<16,8,2>UW g8<16,8,2>UW
3771 * Since it does not use the (single) accumulator register, we can
3772 * schedule multi-component multiplications much better.
3775 bool needs_mov = false;
3776 fs_reg orig_dst = inst->dst;
3777 fs_reg low = inst->dst;
3778 if (orig_dst.is_null() || orig_dst.file == MRF ||
3779 regions_overlap(inst->dst, inst->size_written,
3780 inst->src[0], inst->size_read(0)) ||
3781 regions_overlap(inst->dst, inst->size_written,
3782 inst->src[1], inst->size_read(1))) {
3784 /* Get a new VGRF but keep the same stride as inst->dst */
3785 low = fs_reg(VGRF, alloc.allocate(regs_written(inst)),
3787 low.stride = inst->dst.stride;
3788 low.offset = inst->dst.offset % REG_SIZE;
3791 /* Get a new VGRF but keep the same stride as inst->dst */
3792 fs_reg high(VGRF, alloc.allocate(regs_written(inst)),
3794 high.stride = inst->dst.stride;
3795 high.offset = inst->dst.offset % REG_SIZE;
3797 if (devinfo->gen >= 7) {
3798 if (inst->src[1].file == IMM) {
3799 ibld.MUL(low, inst->src[0],
3800 brw_imm_uw(inst->src[1].ud & 0xffff));
3801 ibld.MUL(high, inst->src[0],
3802 brw_imm_uw(inst->src[1].ud >> 16));
3804 ibld.MUL(low, inst->src[0],
3805 subscript(inst->src[1], BRW_REGISTER_TYPE_UW, 0));
3806 ibld.MUL(high, inst->src[0],
3807 subscript(inst->src[1], BRW_REGISTER_TYPE_UW, 1));
3810 ibld.MUL(low, subscript(inst->src[0], BRW_REGISTER_TYPE_UW, 0),
3812 ibld.MUL(high, subscript(inst->src[0], BRW_REGISTER_TYPE_UW, 1),
3816 ibld.ADD(subscript(low, BRW_REGISTER_TYPE_UW, 1),
3817 subscript(low, BRW_REGISTER_TYPE_UW, 1),
3818 subscript(high, BRW_REGISTER_TYPE_UW, 0));
3820 if (needs_mov || inst->conditional_mod) {
3821 set_condmod(inst->conditional_mod,
3822 ibld.MOV(orig_dst, low));
3826 } else if (inst->opcode == SHADER_OPCODE_MULH) {
3827 /* Should have been lowered to 8-wide. */
3828 assert(inst->exec_size <= get_lowered_simd_width(devinfo, inst));
3829 const fs_reg acc = retype(brw_acc_reg(inst->exec_size),
3831 fs_inst *mul = ibld.MUL(acc, inst->src[0], inst->src[1]);
3832 fs_inst *mach = ibld.MACH(inst->dst, inst->src[0], inst->src[1]);
3834 if (devinfo->gen >= 8) {
3835 /* Until Gen8, integer multiplies read 32-bits from one source,
3836 * and 16-bits from the other, and relying on the MACH instruction
3837 * to generate the high bits of the result.
3839 * On Gen8, the multiply instruction does a full 32x32-bit
3840 * multiply, but in order to do a 64-bit multiply we can simulate
3841 * the previous behavior and then use a MACH instruction.
3843 * FINISHME: Don't use source modifiers on src1.
3845 assert(mul->src[1].type == BRW_REGISTER_TYPE_D ||
3846 mul->src[1].type == BRW_REGISTER_TYPE_UD);
3847 mul->src[1].type = BRW_REGISTER_TYPE_UW;
3848 mul->src[1].stride *= 2;
3850 } else if (devinfo->gen == 7 && !devinfo->is_haswell &&
3852 /* Among other things the quarter control bits influence which
3853 * accumulator register is used by the hardware for instructions
3854 * that access the accumulator implicitly (e.g. MACH). A
3855 * second-half instruction would normally map to acc1, which
3856 * doesn't exist on Gen7 and up (the hardware does emulate it for
3857 * floating-point instructions *only* by taking advantage of the
3858 * extra precision of acc0 not normally used for floating point
3861 * HSW and up are careful enough not to try to access an
3862 * accumulator register that doesn't exist, but on earlier Gen7
3863 * hardware we need to make sure that the quarter control bits are
3864 * zero to avoid non-deterministic behaviour and emit an extra MOV
3865 * to get the result masked correctly according to the current
3869 mach->force_writemask_all = true;
3870 mach->dst = ibld.vgrf(inst->dst.type);
3871 ibld.MOV(inst->dst, mach->dst);
3877 inst->remove(block);
3882 invalidate_live_intervals();
3888 fs_visitor::lower_minmax()
3890 assert(devinfo->gen < 6);
3892 bool progress = false;
3894 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
3895 const fs_builder ibld(this, block, inst);
3897 if (inst->opcode == BRW_OPCODE_SEL &&
3898 inst->predicate == BRW_PREDICATE_NONE) {
3899 /* FIXME: Using CMP doesn't preserve the NaN propagation semantics of
3900 * the original SEL.L/GE instruction
3902 ibld.CMP(ibld.null_reg_d(), inst->src[0], inst->src[1],
3903 inst->conditional_mod);
3904 inst->predicate = BRW_PREDICATE_NORMAL;
3905 inst->conditional_mod = BRW_CONDITIONAL_NONE;
3912 invalidate_live_intervals();
3918 setup_color_payload(const fs_builder &bld, const brw_wm_prog_key *key,
3919 fs_reg *dst, fs_reg color, unsigned components)
3921 if (key->clamp_fragment_color) {
3922 fs_reg tmp = bld.vgrf(BRW_REGISTER_TYPE_F, 4);
3923 assert(color.type == BRW_REGISTER_TYPE_F);
3925 for (unsigned i = 0; i < components; i++)
3927 bld.MOV(offset(tmp, bld, i), offset(color, bld, i)));
3932 for (unsigned i = 0; i < components; i++)
3933 dst[i] = offset(color, bld, i);
3937 lower_fb_write_logical_send(const fs_builder &bld, fs_inst *inst,
3938 const struct brw_wm_prog_data *prog_data,
3939 const brw_wm_prog_key *key,
3940 const fs_visitor::thread_payload &payload)
3942 assert(inst->src[FB_WRITE_LOGICAL_SRC_COMPONENTS].file == IMM);
3943 const gen_device_info *devinfo = bld.shader->devinfo;
3944 const fs_reg &color0 = inst->src[FB_WRITE_LOGICAL_SRC_COLOR0];
3945 const fs_reg &color1 = inst->src[FB_WRITE_LOGICAL_SRC_COLOR1];
3946 const fs_reg &src0_alpha = inst->src[FB_WRITE_LOGICAL_SRC_SRC0_ALPHA];
3947 const fs_reg &src_depth = inst->src[FB_WRITE_LOGICAL_SRC_SRC_DEPTH];
3948 const fs_reg &dst_depth = inst->src[FB_WRITE_LOGICAL_SRC_DST_DEPTH];
3949 const fs_reg &src_stencil = inst->src[FB_WRITE_LOGICAL_SRC_SRC_STENCIL];
3950 fs_reg sample_mask = inst->src[FB_WRITE_LOGICAL_SRC_OMASK];
3951 const unsigned components =
3952 inst->src[FB_WRITE_LOGICAL_SRC_COMPONENTS].ud;
3954 /* We can potentially have a message length of up to 15, so we have to set
3955 * base_mrf to either 0 or 1 in order to fit in m0..m15.
3958 int header_size = 2, payload_header_size;
3959 unsigned length = 0;
3961 if (devinfo->gen < 6) {
3962 /* TODO: Support SIMD32 on gen4-5 */
3963 assert(bld.group() < 16);
3965 /* For gen4-5, we always have a header consisting of g0 and g1. We have
3966 * an implied MOV from g0,g1 to the start of the message. The MOV from
3967 * g0 is handled by the hardware and the MOV from g1 is provided by the
3968 * generator. This is required because, on gen4-5, the generator may
3969 * generate two write messages with different message lengths in order
3970 * to handle AA data properly.
3972 * Also, since the pixel mask goes in the g0 portion of the message and
3973 * since render target writes are the last thing in the shader, we write
3974 * the pixel mask directly into g0 and it will get copied as part of the
3977 if (prog_data->uses_kill) {
3978 bld.exec_all().group(1, 0)
3979 .MOV(retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_UW),
3980 brw_flag_reg(0, 1));
3983 assert(length == 0);
3985 } else if ((devinfo->gen <= 7 && !devinfo->is_haswell &&
3986 prog_data->uses_kill) ||
3987 color1.file != BAD_FILE ||
3988 key->nr_color_regions > 1) {
3989 /* From the Sandy Bridge PRM, volume 4, page 198:
3991 * "Dispatched Pixel Enables. One bit per pixel indicating
3992 * which pixels were originally enabled when the thread was
3993 * dispatched. This field is only required for the end-of-
3994 * thread message and on all dual-source messages."
3996 const fs_builder ubld = bld.exec_all().group(8, 0);
3998 fs_reg header = ubld.vgrf(BRW_REGISTER_TYPE_UD, 2);
3999 if (bld.group() < 16) {
4000 /* The header starts off as g0 and g1 for the first half */
4001 ubld.group(16, 0).MOV(header, retype(brw_vec8_grf(0, 0),
4002 BRW_REGISTER_TYPE_UD));
4004 /* The header starts off as g0 and g2 for the second half */
4005 assert(bld.group() < 32);
4006 const fs_reg header_sources[2] = {
4007 retype(brw_vec8_grf(0, 0), BRW_REGISTER_TYPE_UD),
4008 retype(brw_vec8_grf(2, 0), BRW_REGISTER_TYPE_UD),
4010 ubld.LOAD_PAYLOAD(header, header_sources, 2, 0);
4013 uint32_t g00_bits = 0;
4015 /* Set "Source0 Alpha Present to RenderTarget" bit in message
4018 if (inst->target > 0 && key->replicate_alpha)
4019 g00_bits |= 1 << 11;
4021 /* Set computes stencil to render target */
4022 if (prog_data->computed_stencil)
4023 g00_bits |= 1 << 14;
4026 /* OR extra bits into g0.0 */
4027 ubld.group(1, 0).OR(component(header, 0),
4028 retype(brw_vec1_grf(0, 0),
4029 BRW_REGISTER_TYPE_UD),
4030 brw_imm_ud(g00_bits));
4033 /* Set the render target index for choosing BLEND_STATE. */
4034 if (inst->target > 0) {
4035 ubld.group(1, 0).MOV(component(header, 2), brw_imm_ud(inst->target));
4038 if (prog_data->uses_kill) {
4039 assert(bld.group() < 16);
4040 ubld.group(1, 0).MOV(retype(component(header, 15),
4041 BRW_REGISTER_TYPE_UW),
4042 brw_flag_reg(0, 1));
4045 assert(length == 0);
4046 sources[0] = header;
4047 sources[1] = horiz_offset(header, 8);
4050 assert(length == 0 || length == 2);
4051 header_size = length;
4053 if (payload.aa_dest_stencil_reg[0]) {
4054 assert(inst->group < 16);
4055 sources[length] = fs_reg(VGRF, bld.shader->alloc.allocate(1));
4056 bld.group(8, 0).exec_all().annotate("FB write stencil/AA alpha")
4057 .MOV(sources[length],
4058 fs_reg(brw_vec8_grf(payload.aa_dest_stencil_reg[0], 0)));
4062 if (sample_mask.file != BAD_FILE) {
4063 sources[length] = fs_reg(VGRF, bld.shader->alloc.allocate(1),
4064 BRW_REGISTER_TYPE_UD);
4066 /* Hand over gl_SampleMask. Only the lower 16 bits of each channel are
4067 * relevant. Since it's unsigned single words one vgrf is always
4068 * 16-wide, but only the lower or higher 8 channels will be used by the
4069 * hardware when doing a SIMD8 write depending on whether we have
4070 * selected the subspans for the first or second half respectively.
4072 assert(sample_mask.file != BAD_FILE && type_sz(sample_mask.type) == 4);
4073 sample_mask.type = BRW_REGISTER_TYPE_UW;
4074 sample_mask.stride *= 2;
4076 bld.exec_all().annotate("FB write oMask")
4077 .MOV(horiz_offset(retype(sources[length], BRW_REGISTER_TYPE_UW),
4083 payload_header_size = length;
4085 if (src0_alpha.file != BAD_FILE) {
4086 /* FIXME: This is being passed at the wrong location in the payload and
4087 * doesn't work when gl_SampleMask and MRTs are used simultaneously.
4088 * It's supposed to be immediately before oMask but there seems to be no
4089 * reasonable way to pass them in the correct order because LOAD_PAYLOAD
4090 * requires header sources to form a contiguous segment at the beginning
4091 * of the message and src0_alpha has per-channel semantics.
4093 setup_color_payload(bld, key, &sources[length], src0_alpha, 1);
4095 } else if (key->replicate_alpha && inst->target != 0) {
4096 /* Handle the case when fragment shader doesn't write to draw buffer
4097 * zero. No need to call setup_color_payload() for src0_alpha because
4098 * alpha value will be undefined.
4103 setup_color_payload(bld, key, &sources[length], color0, components);
4106 if (color1.file != BAD_FILE) {
4107 setup_color_payload(bld, key, &sources[length], color1, components);
4111 if (src_depth.file != BAD_FILE) {
4112 sources[length] = src_depth;
4116 if (dst_depth.file != BAD_FILE) {
4117 sources[length] = dst_depth;
4121 if (src_stencil.file != BAD_FILE) {
4122 assert(devinfo->gen >= 9);
4123 assert(bld.dispatch_width() == 8);
4125 /* XXX: src_stencil is only available on gen9+. dst_depth is never
4126 * available on gen9+. As such it's impossible to have both enabled at the
4127 * same time and therefore length cannot overrun the array.
4129 assert(length < 15);
4131 sources[length] = bld.vgrf(BRW_REGISTER_TYPE_UD);
4132 bld.exec_all().annotate("FB write OS")
4133 .MOV(retype(sources[length], BRW_REGISTER_TYPE_UB),
4134 subscript(src_stencil, BRW_REGISTER_TYPE_UB, 0));
4139 if (devinfo->gen >= 7) {
4140 /* Send from the GRF */
4141 fs_reg payload = fs_reg(VGRF, -1, BRW_REGISTER_TYPE_F);
4142 load = bld.LOAD_PAYLOAD(payload, sources, length, payload_header_size);
4143 payload.nr = bld.shader->alloc.allocate(regs_written(load));
4144 load->dst = payload;
4146 inst->src[0] = payload;
4147 inst->resize_sources(1);
4149 /* Send from the MRF */
4150 load = bld.LOAD_PAYLOAD(fs_reg(MRF, 1, BRW_REGISTER_TYPE_F),
4151 sources, length, payload_header_size);
4153 /* On pre-SNB, we have to interlace the color values. LOAD_PAYLOAD
4154 * will do this for us if we just give it a COMPR4 destination.
4156 if (devinfo->gen < 6 && bld.dispatch_width() == 16)
4157 load->dst.nr |= BRW_MRF_COMPR4;
4159 if (devinfo->gen < 6) {
4160 /* Set up src[0] for the implied MOV from grf0-1 */
4161 inst->resize_sources(1);
4162 inst->src[0] = brw_vec8_grf(0, 0);
4164 inst->resize_sources(0);
4169 inst->opcode = FS_OPCODE_FB_WRITE;
4170 inst->mlen = regs_written(load);
4171 inst->header_size = header_size;
4175 lower_fb_read_logical_send(const fs_builder &bld, fs_inst *inst)
4177 const fs_builder &ubld = bld.exec_all().group(8, 0);
4178 const unsigned length = 2;
4179 const fs_reg header = ubld.vgrf(BRW_REGISTER_TYPE_UD, length);
4181 if (bld.group() < 16) {
4182 ubld.group(16, 0).MOV(header, retype(brw_vec8_grf(0, 0),
4183 BRW_REGISTER_TYPE_UD));
4185 assert(bld.group() < 32);
4186 const fs_reg header_sources[] = {
4187 retype(brw_vec8_grf(0, 0), BRW_REGISTER_TYPE_UD),
4188 retype(brw_vec8_grf(2, 0), BRW_REGISTER_TYPE_UD)
4190 ubld.LOAD_PAYLOAD(header, header_sources, ARRAY_SIZE(header_sources), 0);
4193 inst->resize_sources(1);
4194 inst->src[0] = header;
4195 inst->opcode = FS_OPCODE_FB_READ;
4196 inst->mlen = length;
4197 inst->header_size = length;
4201 lower_sampler_logical_send_gen4(const fs_builder &bld, fs_inst *inst, opcode op,
4202 const fs_reg &coordinate,
4203 const fs_reg &shadow_c,
4204 const fs_reg &lod, const fs_reg &lod2,
4205 const fs_reg &surface,
4206 const fs_reg &sampler,
4207 unsigned coord_components,
4208 unsigned grad_components)
4210 const bool has_lod = (op == SHADER_OPCODE_TXL || op == FS_OPCODE_TXB ||
4211 op == SHADER_OPCODE_TXF || op == SHADER_OPCODE_TXS);
4212 fs_reg msg_begin(MRF, 1, BRW_REGISTER_TYPE_F);
4213 fs_reg msg_end = msg_begin;
4216 msg_end = offset(msg_end, bld.group(8, 0), 1);
4218 for (unsigned i = 0; i < coord_components; i++)
4219 bld.MOV(retype(offset(msg_end, bld, i), coordinate.type),
4220 offset(coordinate, bld, i));
4222 msg_end = offset(msg_end, bld, coord_components);
4224 /* Messages other than SAMPLE and RESINFO in SIMD16 and TXD in SIMD8
4225 * require all three components to be present and zero if they are unused.
4227 if (coord_components > 0 &&
4228 (has_lod || shadow_c.file != BAD_FILE ||
4229 (op == SHADER_OPCODE_TEX && bld.dispatch_width() == 8))) {
4230 for (unsigned i = coord_components; i < 3; i++)
4231 bld.MOV(offset(msg_end, bld, i), brw_imm_f(0.0f));
4233 msg_end = offset(msg_end, bld, 3 - coord_components);
4236 if (op == SHADER_OPCODE_TXD) {
4237 /* TXD unsupported in SIMD16 mode. */
4238 assert(bld.dispatch_width() == 8);
4240 /* the slots for u and v are always present, but r is optional */
4241 if (coord_components < 2)
4242 msg_end = offset(msg_end, bld, 2 - coord_components);
4245 * dPdx = dudx, dvdx, drdx
4246 * dPdy = dudy, dvdy, drdy
4248 * 1-arg: Does not exist.
4250 * 2-arg: dudx dvdx dudy dvdy
4251 * dPdx.x dPdx.y dPdy.x dPdy.y
4254 * 3-arg: dudx dvdx drdx dudy dvdy drdy
4255 * dPdx.x dPdx.y dPdx.z dPdy.x dPdy.y dPdy.z
4256 * m5 m6 m7 m8 m9 m10
4258 for (unsigned i = 0; i < grad_components; i++)
4259 bld.MOV(offset(msg_end, bld, i), offset(lod, bld, i));
4261 msg_end = offset(msg_end, bld, MAX2(grad_components, 2));
4263 for (unsigned i = 0; i < grad_components; i++)
4264 bld.MOV(offset(msg_end, bld, i), offset(lod2, bld, i));
4266 msg_end = offset(msg_end, bld, MAX2(grad_components, 2));
4270 /* Bias/LOD with shadow comparator is unsupported in SIMD16 -- *Without*
4271 * shadow comparator (including RESINFO) it's unsupported in SIMD8 mode.
4273 assert(shadow_c.file != BAD_FILE ? bld.dispatch_width() == 8 :
4274 bld.dispatch_width() == 16);
4276 const brw_reg_type type =
4277 (op == SHADER_OPCODE_TXF || op == SHADER_OPCODE_TXS ?
4278 BRW_REGISTER_TYPE_UD : BRW_REGISTER_TYPE_F);
4279 bld.MOV(retype(msg_end, type), lod);
4280 msg_end = offset(msg_end, bld, 1);
4283 if (shadow_c.file != BAD_FILE) {
4284 if (op == SHADER_OPCODE_TEX && bld.dispatch_width() == 8) {
4285 /* There's no plain shadow compare message, so we use shadow
4286 * compare with a bias of 0.0.
4288 bld.MOV(msg_end, brw_imm_f(0.0f));
4289 msg_end = offset(msg_end, bld, 1);
4292 bld.MOV(msg_end, shadow_c);
4293 msg_end = offset(msg_end, bld, 1);
4297 inst->src[0] = reg_undef;
4298 inst->src[1] = surface;
4299 inst->src[2] = sampler;
4300 inst->resize_sources(3);
4301 inst->base_mrf = msg_begin.nr;
4302 inst->mlen = msg_end.nr - msg_begin.nr;
4303 inst->header_size = 1;
4307 lower_sampler_logical_send_gen5(const fs_builder &bld, fs_inst *inst, opcode op,
4308 const fs_reg &coordinate,
4309 const fs_reg &shadow_c,
4310 const fs_reg &lod, const fs_reg &lod2,
4311 const fs_reg &sample_index,
4312 const fs_reg &surface,
4313 const fs_reg &sampler,
4314 unsigned coord_components,
4315 unsigned grad_components)
4317 fs_reg message(MRF, 2, BRW_REGISTER_TYPE_F);
4318 fs_reg msg_coords = message;
4319 unsigned header_size = 0;
4321 if (inst->offset != 0) {
4322 /* The offsets set up by the visitor are in the m1 header, so we can't
4329 for (unsigned i = 0; i < coord_components; i++)
4330 bld.MOV(retype(offset(msg_coords, bld, i), coordinate.type),
4331 offset(coordinate, bld, i));
4333 fs_reg msg_end = offset(msg_coords, bld, coord_components);
4334 fs_reg msg_lod = offset(msg_coords, bld, 4);
4336 if (shadow_c.file != BAD_FILE) {
4337 fs_reg msg_shadow = msg_lod;
4338 bld.MOV(msg_shadow, shadow_c);
4339 msg_lod = offset(msg_shadow, bld, 1);
4344 case SHADER_OPCODE_TXL:
4346 bld.MOV(msg_lod, lod);
4347 msg_end = offset(msg_lod, bld, 1);
4349 case SHADER_OPCODE_TXD:
4352 * dPdx = dudx, dvdx, drdx
4353 * dPdy = dudy, dvdy, drdy
4355 * Load up these values:
4356 * - dudx dudy dvdx dvdy drdx drdy
4357 * - dPdx.x dPdy.x dPdx.y dPdy.y dPdx.z dPdy.z
4360 for (unsigned i = 0; i < grad_components; i++) {
4361 bld.MOV(msg_end, offset(lod, bld, i));
4362 msg_end = offset(msg_end, bld, 1);
4364 bld.MOV(msg_end, offset(lod2, bld, i));
4365 msg_end = offset(msg_end, bld, 1);
4368 case SHADER_OPCODE_TXS:
4369 msg_lod = retype(msg_end, BRW_REGISTER_TYPE_UD);
4370 bld.MOV(msg_lod, lod);
4371 msg_end = offset(msg_lod, bld, 1);
4373 case SHADER_OPCODE_TXF:
4374 msg_lod = offset(msg_coords, bld, 3);
4375 bld.MOV(retype(msg_lod, BRW_REGISTER_TYPE_UD), lod);
4376 msg_end = offset(msg_lod, bld, 1);
4378 case SHADER_OPCODE_TXF_CMS:
4379 msg_lod = offset(msg_coords, bld, 3);
4381 bld.MOV(retype(msg_lod, BRW_REGISTER_TYPE_UD), brw_imm_ud(0u));
4383 bld.MOV(retype(offset(msg_lod, bld, 1), BRW_REGISTER_TYPE_UD), sample_index);
4384 msg_end = offset(msg_lod, bld, 2);
4391 inst->src[0] = reg_undef;
4392 inst->src[1] = surface;
4393 inst->src[2] = sampler;
4394 inst->resize_sources(3);
4395 inst->base_mrf = message.nr;
4396 inst->mlen = msg_end.nr - message.nr;
4397 inst->header_size = header_size;
4399 /* Message length > MAX_SAMPLER_MESSAGE_SIZE disallowed by hardware. */
4400 assert(inst->mlen <= MAX_SAMPLER_MESSAGE_SIZE);
4404 is_high_sampler(const struct gen_device_info *devinfo, const fs_reg &sampler)
4406 if (devinfo->gen < 8 && !devinfo->is_haswell)
4409 return sampler.file != IMM || sampler.ud >= 16;
4413 lower_sampler_logical_send_gen7(const fs_builder &bld, fs_inst *inst, opcode op,
4414 const fs_reg &coordinate,
4415 const fs_reg &shadow_c,
4416 fs_reg lod, const fs_reg &lod2,
4417 const fs_reg &sample_index,
4419 const fs_reg &surface,
4420 const fs_reg &sampler,
4421 const fs_reg &tg4_offset,
4422 unsigned coord_components,
4423 unsigned grad_components)
4425 const gen_device_info *devinfo = bld.shader->devinfo;
4426 unsigned reg_width = bld.dispatch_width() / 8;
4427 unsigned header_size = 0, length = 0;
4428 fs_reg sources[MAX_SAMPLER_MESSAGE_SIZE];
4429 for (unsigned i = 0; i < ARRAY_SIZE(sources); i++)
4430 sources[i] = bld.vgrf(BRW_REGISTER_TYPE_F);
4432 if (op == SHADER_OPCODE_TG4 || op == SHADER_OPCODE_TG4_OFFSET ||
4433 inst->offset != 0 || inst->eot ||
4434 op == SHADER_OPCODE_SAMPLEINFO ||
4435 is_high_sampler(devinfo, sampler)) {
4436 /* For general texture offsets (no txf workaround), we need a header to
4439 * TG4 needs to place its channel select in the header, for interaction
4440 * with ARB_texture_swizzle. The sampler index is only 4-bits, so for
4441 * larger sampler numbers we need to offset the Sampler State Pointer in
4444 fs_reg header = retype(sources[0], BRW_REGISTER_TYPE_UD);
4448 /* If we're requesting fewer than four channels worth of response,
4449 * and we have an explicit header, we need to set up the sampler
4450 * writemask. It's reversed from normal: 1 means "don't write".
4452 if (!inst->eot && regs_written(inst) != 4 * reg_width) {
4453 assert(regs_written(inst) % reg_width == 0);
4454 unsigned mask = ~((1 << (regs_written(inst) / reg_width)) - 1) & 0xf;
4455 inst->offset |= mask << 12;
4458 /* Build the actual header */
4459 const fs_builder ubld = bld.exec_all().group(8, 0);
4460 const fs_builder ubld1 = ubld.group(1, 0);
4461 ubld.MOV(header, retype(brw_vec8_grf(0, 0), BRW_REGISTER_TYPE_UD));
4463 ubld1.MOV(component(header, 2), brw_imm_ud(inst->offset));
4464 } else if (bld.shader->stage != MESA_SHADER_VERTEX &&
4465 bld.shader->stage != MESA_SHADER_FRAGMENT) {
4466 /* The vertex and fragment stages have g0.2 set to 0, so
4467 * header0.2 is 0 when g0 is copied. Other stages may not, so we
4468 * must set it to 0 to avoid setting undesirable bits in the
4471 ubld1.MOV(component(header, 2), brw_imm_ud(0));
4474 if (is_high_sampler(devinfo, sampler)) {
4475 if (sampler.file == BRW_IMMEDIATE_VALUE) {
4476 assert(sampler.ud >= 16);
4477 const int sampler_state_size = 16; /* 16 bytes */
4479 ubld1.ADD(component(header, 3),
4480 retype(brw_vec1_grf(0, 3), BRW_REGISTER_TYPE_UD),
4481 brw_imm_ud(16 * (sampler.ud / 16) * sampler_state_size));
4483 fs_reg tmp = ubld1.vgrf(BRW_REGISTER_TYPE_UD);
4484 ubld1.AND(tmp, sampler, brw_imm_ud(0x0f0));
4485 ubld1.SHL(tmp, tmp, brw_imm_ud(4));
4486 ubld1.ADD(component(header, 3),
4487 retype(brw_vec1_grf(0, 3), BRW_REGISTER_TYPE_UD),
4493 if (shadow_c.file != BAD_FILE) {
4494 bld.MOV(sources[length], shadow_c);
4498 bool coordinate_done = false;
4500 /* Set up the LOD info */
4503 case SHADER_OPCODE_TXL:
4504 if (devinfo->gen >= 9 && op == SHADER_OPCODE_TXL && lod.is_zero()) {
4505 op = SHADER_OPCODE_TXL_LZ;
4508 bld.MOV(sources[length], lod);
4511 case SHADER_OPCODE_TXD:
4512 /* TXD should have been lowered in SIMD16 mode. */
4513 assert(bld.dispatch_width() == 8);
4515 /* Load dPdx and the coordinate together:
4516 * [hdr], [ref], x, dPdx.x, dPdy.x, y, dPdx.y, dPdy.y, z, dPdx.z, dPdy.z
4518 for (unsigned i = 0; i < coord_components; i++) {
4519 bld.MOV(sources[length++], offset(coordinate, bld, i));
4521 /* For cube map array, the coordinate is (u,v,r,ai) but there are
4522 * only derivatives for (u, v, r).
4524 if (i < grad_components) {
4525 bld.MOV(sources[length++], offset(lod, bld, i));
4526 bld.MOV(sources[length++], offset(lod2, bld, i));
4530 coordinate_done = true;
4532 case SHADER_OPCODE_TXS:
4533 bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_UD), lod);
4536 case SHADER_OPCODE_TXF:
4537 /* Unfortunately, the parameters for LD are intermixed: u, lod, v, r.
4538 * On Gen9 they are u, v, lod, r
4540 bld.MOV(retype(sources[length++], BRW_REGISTER_TYPE_D), coordinate);
4542 if (devinfo->gen >= 9) {
4543 if (coord_components >= 2) {
4544 bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_D),
4545 offset(coordinate, bld, 1));
4547 sources[length] = brw_imm_d(0);
4552 if (devinfo->gen >= 9 && lod.is_zero()) {
4553 op = SHADER_OPCODE_TXF_LZ;
4555 bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_D), lod);
4559 for (unsigned i = devinfo->gen >= 9 ? 2 : 1; i < coord_components; i++)
4560 bld.MOV(retype(sources[length++], BRW_REGISTER_TYPE_D),
4561 offset(coordinate, bld, i));
4563 coordinate_done = true;
4566 case SHADER_OPCODE_TXF_CMS:
4567 case SHADER_OPCODE_TXF_CMS_W:
4568 case SHADER_OPCODE_TXF_UMS:
4569 case SHADER_OPCODE_TXF_MCS:
4570 if (op == SHADER_OPCODE_TXF_UMS ||
4571 op == SHADER_OPCODE_TXF_CMS ||
4572 op == SHADER_OPCODE_TXF_CMS_W) {
4573 bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_UD), sample_index);
4577 if (op == SHADER_OPCODE_TXF_CMS || op == SHADER_OPCODE_TXF_CMS_W) {
4578 /* Data from the multisample control surface. */
4579 bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_UD), mcs);
4582 /* On Gen9+ we'll use ld2dms_w instead which has two registers for
4585 if (op == SHADER_OPCODE_TXF_CMS_W) {
4586 bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_UD),
4589 offset(mcs, bld, 1));
4594 /* There is no offsetting for this message; just copy in the integer
4595 * texture coordinates.
4597 for (unsigned i = 0; i < coord_components; i++)
4598 bld.MOV(retype(sources[length++], BRW_REGISTER_TYPE_D),
4599 offset(coordinate, bld, i));
4601 coordinate_done = true;
4603 case SHADER_OPCODE_TG4_OFFSET:
4604 /* More crazy intermixing */
4605 for (unsigned i = 0; i < 2; i++) /* u, v */
4606 bld.MOV(sources[length++], offset(coordinate, bld, i));
4608 for (unsigned i = 0; i < 2; i++) /* offu, offv */
4609 bld.MOV(retype(sources[length++], BRW_REGISTER_TYPE_D),
4610 offset(tg4_offset, bld, i));
4612 if (coord_components == 3) /* r if present */
4613 bld.MOV(sources[length++], offset(coordinate, bld, 2));
4615 coordinate_done = true;
4621 /* Set up the coordinate (except for cases where it was done above) */
4622 if (!coordinate_done) {
4623 for (unsigned i = 0; i < coord_components; i++)
4624 bld.MOV(sources[length++], offset(coordinate, bld, i));
4629 mlen = length * reg_width - header_size;
4631 mlen = length * reg_width;
4633 const fs_reg src_payload = fs_reg(VGRF, bld.shader->alloc.allocate(mlen),
4634 BRW_REGISTER_TYPE_F);
4635 bld.LOAD_PAYLOAD(src_payload, sources, length, header_size);
4637 /* Generate the SEND. */
4639 inst->src[0] = src_payload;
4640 inst->src[1] = surface;
4641 inst->src[2] = sampler;
4642 inst->resize_sources(3);
4644 inst->header_size = header_size;
4646 /* Message length > MAX_SAMPLER_MESSAGE_SIZE disallowed by hardware. */
4647 assert(inst->mlen <= MAX_SAMPLER_MESSAGE_SIZE);
4651 lower_sampler_logical_send(const fs_builder &bld, fs_inst *inst, opcode op)
4653 const gen_device_info *devinfo = bld.shader->devinfo;
4654 const fs_reg &coordinate = inst->src[TEX_LOGICAL_SRC_COORDINATE];
4655 const fs_reg &shadow_c = inst->src[TEX_LOGICAL_SRC_SHADOW_C];
4656 const fs_reg &lod = inst->src[TEX_LOGICAL_SRC_LOD];
4657 const fs_reg &lod2 = inst->src[TEX_LOGICAL_SRC_LOD2];
4658 const fs_reg &sample_index = inst->src[TEX_LOGICAL_SRC_SAMPLE_INDEX];
4659 const fs_reg &mcs = inst->src[TEX_LOGICAL_SRC_MCS];
4660 const fs_reg &surface = inst->src[TEX_LOGICAL_SRC_SURFACE];
4661 const fs_reg &sampler = inst->src[TEX_LOGICAL_SRC_SAMPLER];
4662 const fs_reg &tg4_offset = inst->src[TEX_LOGICAL_SRC_TG4_OFFSET];
4663 assert(inst->src[TEX_LOGICAL_SRC_COORD_COMPONENTS].file == IMM);
4664 const unsigned coord_components = inst->src[TEX_LOGICAL_SRC_COORD_COMPONENTS].ud;
4665 assert(inst->src[TEX_LOGICAL_SRC_GRAD_COMPONENTS].file == IMM);
4666 const unsigned grad_components = inst->src[TEX_LOGICAL_SRC_GRAD_COMPONENTS].ud;
4668 if (devinfo->gen >= 7) {
4669 lower_sampler_logical_send_gen7(bld, inst, op, coordinate,
4670 shadow_c, lod, lod2, sample_index,
4671 mcs, surface, sampler, tg4_offset,
4672 coord_components, grad_components);
4673 } else if (devinfo->gen >= 5) {
4674 lower_sampler_logical_send_gen5(bld, inst, op, coordinate,
4675 shadow_c, lod, lod2, sample_index,
4677 coord_components, grad_components);
4679 lower_sampler_logical_send_gen4(bld, inst, op, coordinate,
4680 shadow_c, lod, lod2,
4682 coord_components, grad_components);
4687 * Initialize the header present in some typed and untyped surface
4691 emit_surface_header(const fs_builder &bld, const fs_reg &sample_mask)
4693 fs_builder ubld = bld.exec_all().group(8, 0);
4694 const fs_reg dst = ubld.vgrf(BRW_REGISTER_TYPE_UD);
4695 ubld.MOV(dst, brw_imm_d(0));
4696 ubld.group(1, 0).MOV(component(dst, 7), sample_mask);
4701 lower_surface_logical_send(const fs_builder &bld, fs_inst *inst, opcode op,
4702 const fs_reg &sample_mask)
4704 const gen_device_info *devinfo = bld.shader->devinfo;
4706 /* Get the logical send arguments. */
4707 const fs_reg &addr = inst->src[0];
4708 const fs_reg &src = inst->src[1];
4709 const fs_reg &surface = inst->src[2];
4710 const UNUSED fs_reg &dims = inst->src[3];
4711 const fs_reg &arg = inst->src[4];
4713 /* Calculate the total number of components of the payload. */
4714 const unsigned addr_sz = inst->components_read(0);
4715 const unsigned src_sz = inst->components_read(1);
4716 /* From the BDW PRM Volume 7, page 147:
4718 * "For the Data Cache Data Port*, the header must be present for the
4719 * following message types: [...] Typed read/write/atomics"
4721 * Earlier generations have a similar wording. Because of this restriction
4722 * we don't attempt to implement sample masks via predication for such
4723 * messages prior to Gen9, since we have to provide a header anyway. On
4724 * Gen11+ the header has been removed so we can only use predication.
4726 const unsigned header_sz = devinfo->gen < 9 &&
4727 (op == SHADER_OPCODE_TYPED_SURFACE_READ ||
4728 op == SHADER_OPCODE_TYPED_SURFACE_WRITE ||
4729 op == SHADER_OPCODE_TYPED_ATOMIC) ? 1 : 0;
4730 const unsigned sz = header_sz + addr_sz + src_sz;
4732 /* Allocate space for the payload. */
4733 fs_reg *const components = new fs_reg[sz];
4734 const fs_reg payload = bld.vgrf(BRW_REGISTER_TYPE_UD, sz);
4737 /* Construct the payload. */
4739 components[n++] = emit_surface_header(bld, sample_mask);
4741 for (unsigned i = 0; i < addr_sz; i++)
4742 components[n++] = offset(addr, bld, i);
4744 for (unsigned i = 0; i < src_sz; i++)
4745 components[n++] = offset(src, bld, i);
4747 bld.LOAD_PAYLOAD(payload, components, sz, header_sz);
4749 /* Predicate the instruction on the sample mask if no header is
4752 if (!header_sz && sample_mask.file != BAD_FILE &&
4753 sample_mask.file != IMM) {
4754 const fs_builder ubld = bld.group(1, 0).exec_all();
4755 if (inst->predicate) {
4756 assert(inst->predicate == BRW_PREDICATE_NORMAL);
4757 assert(!inst->predicate_inverse);
4758 assert(inst->flag_subreg < 2);
4759 /* Combine the sample mask with the existing predicate by using a
4760 * vertical predication mode.
4762 inst->predicate = BRW_PREDICATE_ALIGN1_ALLV;
4763 ubld.MOV(retype(brw_flag_subreg(inst->flag_subreg + 2),
4767 inst->flag_subreg = 2;
4768 inst->predicate = BRW_PREDICATE_NORMAL;
4769 inst->predicate_inverse = false;
4770 ubld.MOV(retype(brw_flag_subreg(inst->flag_subreg), sample_mask.type),
4775 /* Update the original instruction. */
4777 inst->mlen = header_sz + (addr_sz + src_sz) * inst->exec_size / 8;
4778 inst->header_size = header_sz;
4780 inst->src[0] = payload;
4781 inst->src[1] = surface;
4783 inst->resize_sources(3);
4785 delete[] components;
4789 lower_varying_pull_constant_logical_send(const fs_builder &bld, fs_inst *inst)
4791 const gen_device_info *devinfo = bld.shader->devinfo;
4793 if (devinfo->gen >= 7) {
4794 /* We are switching the instruction from an ALU-like instruction to a
4795 * send-from-grf instruction. Since sends can't handle strides or
4796 * source modifiers, we have to make a copy of the offset source.
4798 fs_reg tmp = bld.vgrf(BRW_REGISTER_TYPE_UD);
4799 bld.MOV(tmp, inst->src[1]);
4802 inst->opcode = FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_GEN7;
4805 const fs_reg payload(MRF, FIRST_PULL_LOAD_MRF(devinfo->gen),
4806 BRW_REGISTER_TYPE_UD);
4808 bld.MOV(byte_offset(payload, REG_SIZE), inst->src[1]);
4810 inst->opcode = FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_GEN4;
4811 inst->resize_sources(1);
4812 inst->base_mrf = payload.nr;
4813 inst->header_size = 1;
4814 inst->mlen = 1 + inst->exec_size / 8;
4819 lower_math_logical_send(const fs_builder &bld, fs_inst *inst)
4821 assert(bld.shader->devinfo->gen < 6);
4824 inst->mlen = inst->sources * inst->exec_size / 8;
4826 if (inst->sources > 1) {
4827 /* From the Ironlake PRM, Volume 4, Part 1, Section 6.1.13
4828 * "Message Payload":
4830 * "Operand0[7]. For the INT DIV functions, this operand is the
4833 * "Operand1[7]. For the INT DIV functions, this operand is the
4836 const bool is_int_div = inst->opcode != SHADER_OPCODE_POW;
4837 const fs_reg src0 = is_int_div ? inst->src[1] : inst->src[0];
4838 const fs_reg src1 = is_int_div ? inst->src[0] : inst->src[1];
4840 inst->resize_sources(1);
4841 inst->src[0] = src0;
4843 assert(inst->exec_size == 8);
4844 bld.MOV(fs_reg(MRF, inst->base_mrf + 1, src1.type), src1);
4849 fs_visitor::lower_logical_sends()
4851 bool progress = false;
4853 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
4854 const fs_builder ibld(this, block, inst);
4856 switch (inst->opcode) {
4857 case FS_OPCODE_FB_WRITE_LOGICAL:
4858 assert(stage == MESA_SHADER_FRAGMENT);
4859 lower_fb_write_logical_send(ibld, inst,
4860 brw_wm_prog_data(prog_data),
4861 (const brw_wm_prog_key *)key,
4865 case FS_OPCODE_FB_READ_LOGICAL:
4866 lower_fb_read_logical_send(ibld, inst);
4869 case SHADER_OPCODE_TEX_LOGICAL:
4870 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TEX);
4873 case SHADER_OPCODE_TXD_LOGICAL:
4874 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXD);
4877 case SHADER_OPCODE_TXF_LOGICAL:
4878 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXF);
4881 case SHADER_OPCODE_TXL_LOGICAL:
4882 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXL);
4885 case SHADER_OPCODE_TXS_LOGICAL:
4886 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXS);
4889 case FS_OPCODE_TXB_LOGICAL:
4890 lower_sampler_logical_send(ibld, inst, FS_OPCODE_TXB);
4893 case SHADER_OPCODE_TXF_CMS_LOGICAL:
4894 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXF_CMS);
4897 case SHADER_OPCODE_TXF_CMS_W_LOGICAL:
4898 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXF_CMS_W);
4901 case SHADER_OPCODE_TXF_UMS_LOGICAL:
4902 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXF_UMS);
4905 case SHADER_OPCODE_TXF_MCS_LOGICAL:
4906 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXF_MCS);
4909 case SHADER_OPCODE_LOD_LOGICAL:
4910 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_LOD);
4913 case SHADER_OPCODE_TG4_LOGICAL:
4914 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TG4);
4917 case SHADER_OPCODE_TG4_OFFSET_LOGICAL:
4918 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TG4_OFFSET);
4921 case SHADER_OPCODE_SAMPLEINFO_LOGICAL:
4922 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_SAMPLEINFO);
4925 case SHADER_OPCODE_UNTYPED_SURFACE_READ_LOGICAL:
4926 lower_surface_logical_send(ibld, inst,
4927 SHADER_OPCODE_UNTYPED_SURFACE_READ,
4931 case SHADER_OPCODE_UNTYPED_SURFACE_WRITE_LOGICAL:
4932 lower_surface_logical_send(ibld, inst,
4933 SHADER_OPCODE_UNTYPED_SURFACE_WRITE,
4934 ibld.sample_mask_reg());
4937 case SHADER_OPCODE_BYTE_SCATTERED_READ_LOGICAL:
4938 lower_surface_logical_send(ibld, inst,
4939 SHADER_OPCODE_BYTE_SCATTERED_READ,
4943 case SHADER_OPCODE_BYTE_SCATTERED_WRITE_LOGICAL:
4944 lower_surface_logical_send(ibld, inst,
4945 SHADER_OPCODE_BYTE_SCATTERED_WRITE,
4946 ibld.sample_mask_reg());
4949 case SHADER_OPCODE_UNTYPED_ATOMIC_LOGICAL:
4950 lower_surface_logical_send(ibld, inst,
4951 SHADER_OPCODE_UNTYPED_ATOMIC,
4952 ibld.sample_mask_reg());
4955 case SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL:
4956 lower_surface_logical_send(ibld, inst,
4957 SHADER_OPCODE_TYPED_SURFACE_READ,
4961 case SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL:
4962 lower_surface_logical_send(ibld, inst,
4963 SHADER_OPCODE_TYPED_SURFACE_WRITE,
4964 ibld.sample_mask_reg());
4967 case SHADER_OPCODE_TYPED_ATOMIC_LOGICAL:
4968 lower_surface_logical_send(ibld, inst,
4969 SHADER_OPCODE_TYPED_ATOMIC,
4970 ibld.sample_mask_reg());
4973 case FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_LOGICAL:
4974 lower_varying_pull_constant_logical_send(ibld, inst);
4977 case SHADER_OPCODE_RCP:
4978 case SHADER_OPCODE_RSQ:
4979 case SHADER_OPCODE_SQRT:
4980 case SHADER_OPCODE_EXP2:
4981 case SHADER_OPCODE_LOG2:
4982 case SHADER_OPCODE_SIN:
4983 case SHADER_OPCODE_COS:
4984 case SHADER_OPCODE_POW:
4985 case SHADER_OPCODE_INT_QUOTIENT:
4986 case SHADER_OPCODE_INT_REMAINDER:
4987 /* The math opcodes are overloaded for the send-like and
4988 * expression-like instructions which seems kind of icky. Gen6+ has
4989 * a native (but rather quirky) MATH instruction so we don't need to
4990 * do anything here. On Gen4-5 we'll have to lower the Gen6-like
4991 * logical instructions (which we can easily recognize because they
4992 * have mlen = 0) into send-like virtual instructions.
4994 if (devinfo->gen < 6 && inst->mlen == 0) {
4995 lower_math_logical_send(ibld, inst);
5010 invalidate_live_intervals();
5016 * Get the closest allowed SIMD width for instruction \p inst accounting for
5017 * some common regioning and execution control restrictions that apply to FPU
5018 * instructions. These restrictions don't necessarily have any relevance to
5019 * instructions not executed by the FPU pipeline like extended math, control
5020 * flow or send message instructions.
5022 * For virtual opcodes it's really up to the instruction -- In some cases
5023 * (e.g. where a virtual instruction unrolls into a simple sequence of FPU
5024 * instructions) it may simplify virtual instruction lowering if we can
5025 * enforce FPU-like regioning restrictions already on the virtual instruction,
5026 * in other cases (e.g. virtual send-like instructions) this may be
5027 * excessively restrictive.
5030 get_fpu_lowered_simd_width(const struct gen_device_info *devinfo,
5031 const fs_inst *inst)
5033 /* Maximum execution size representable in the instruction controls. */
5034 unsigned max_width = MIN2(32, inst->exec_size);
5036 /* According to the PRMs:
5037 * "A. In Direct Addressing mode, a source cannot span more than 2
5038 * adjacent GRF registers.
5039 * B. A destination cannot span more than 2 adjacent GRF registers."
5041 * Look for the source or destination with the largest register region
5042 * which is the one that is going to limit the overall execution size of
5043 * the instruction due to this rule.
5045 unsigned reg_count = DIV_ROUND_UP(inst->size_written, REG_SIZE);
5047 for (unsigned i = 0; i < inst->sources; i++)
5048 reg_count = MAX2(reg_count, DIV_ROUND_UP(inst->size_read(i), REG_SIZE));
5050 /* Calculate the maximum execution size of the instruction based on the
5051 * factor by which it goes over the hardware limit of 2 GRFs.
5054 max_width = MIN2(max_width, inst->exec_size / DIV_ROUND_UP(reg_count, 2));
5056 /* According to the IVB PRMs:
5057 * "When destination spans two registers, the source MUST span two
5058 * registers. The exception to the above rule:
5060 * - When source is scalar, the source registers are not incremented.
5061 * - When source is packed integer Word and destination is packed
5062 * integer DWord, the source register is not incremented but the
5063 * source sub register is incremented."
5065 * The hardware specs from Gen4 to Gen7.5 mention similar regioning
5066 * restrictions. The code below intentionally doesn't check whether the
5067 * destination type is integer because empirically the hardware doesn't
5068 * seem to care what the actual type is as long as it's dword-aligned.
5070 if (devinfo->gen < 8) {
5071 for (unsigned i = 0; i < inst->sources; i++) {
5072 /* IVB implements DF scalars as <0;2,1> regions. */
5073 const bool is_scalar_exception = is_uniform(inst->src[i]) &&
5074 (devinfo->is_haswell || type_sz(inst->src[i].type) != 8);
5075 const bool is_packed_word_exception =
5076 type_sz(inst->dst.type) == 4 && inst->dst.stride == 1 &&
5077 type_sz(inst->src[i].type) == 2 && inst->src[i].stride == 1;
5079 if (inst->size_written > REG_SIZE &&
5080 inst->size_read(i) != 0 && inst->size_read(i) <= REG_SIZE &&
5081 !is_scalar_exception && !is_packed_word_exception) {
5082 const unsigned reg_count = DIV_ROUND_UP(inst->size_written, REG_SIZE);
5083 max_width = MIN2(max_width, inst->exec_size / reg_count);
5088 /* From the IVB PRMs:
5089 * "When an instruction is SIMD32, the low 16 bits of the execution mask
5090 * are applied for both halves of the SIMD32 instruction. If different
5091 * execution mask channels are required, split the instruction into two
5092 * SIMD16 instructions."
5094 * There is similar text in the HSW PRMs. Gen4-6 don't even implement
5095 * 32-wide control flow support in hardware and will behave similarly.
5097 if (devinfo->gen < 8 && !inst->force_writemask_all)
5098 max_width = MIN2(max_width, 16);
5100 /* From the IVB PRMs (applies to HSW too):
5101 * "Instructions with condition modifiers must not use SIMD32."
5103 * From the BDW PRMs (applies to later hardware too):
5104 * "Ternary instruction with condition modifiers must not use SIMD32."
5106 if (inst->conditional_mod && (devinfo->gen < 8 || inst->is_3src(devinfo)))
5107 max_width = MIN2(max_width, 16);
5109 /* From the IVB PRMs (applies to other devices that don't have the
5110 * gen_device_info::supports_simd16_3src flag set):
5111 * "In Align16 access mode, SIMD16 is not allowed for DW operations and
5112 * SIMD8 is not allowed for DF operations."
5114 if (inst->is_3src(devinfo) && !devinfo->supports_simd16_3src)
5115 max_width = MIN2(max_width, inst->exec_size / reg_count);
5117 /* Pre-Gen8 EUs are hardwired to use the QtrCtrl+1 (where QtrCtrl is
5118 * the 8-bit quarter of the execution mask signals specified in the
5119 * instruction control fields) for the second compressed half of any
5120 * single-precision instruction (for double-precision instructions
5121 * it's hardwired to use NibCtrl+1, at least on HSW), which means that
5122 * the EU will apply the wrong execution controls for the second
5123 * sequential GRF write if the number of channels per GRF is not exactly
5124 * eight in single-precision mode (or four in double-float mode).
5126 * In this situation we calculate the maximum size of the split
5127 * instructions so they only ever write to a single register.
5129 if (devinfo->gen < 8 && inst->size_written > REG_SIZE &&
5130 !inst->force_writemask_all) {
5131 const unsigned channels_per_grf = inst->exec_size /
5132 DIV_ROUND_UP(inst->size_written, REG_SIZE);
5133 const unsigned exec_type_size = get_exec_type_size(inst);
5134 assert(exec_type_size);
5136 /* The hardware shifts exactly 8 channels per compressed half of the
5137 * instruction in single-precision mode and exactly 4 in double-precision.
5139 if (channels_per_grf != (exec_type_size == 8 ? 4 : 8))
5140 max_width = MIN2(max_width, channels_per_grf);
5142 /* Lower all non-force_writemask_all DF instructions to SIMD4 on IVB/BYT
5143 * because HW applies the same channel enable signals to both halves of
5144 * the compressed instruction which will be just wrong under
5145 * non-uniform control flow.
5147 if (devinfo->gen == 7 && !devinfo->is_haswell &&
5148 (exec_type_size == 8 || type_sz(inst->dst.type) == 8))
5149 max_width = MIN2(max_width, 4);
5152 /* Only power-of-two execution sizes are representable in the instruction
5155 return 1 << _mesa_logbase2(max_width);
5159 * Get the maximum allowed SIMD width for instruction \p inst accounting for
5160 * various payload size restrictions that apply to sampler message
5163 * This is only intended to provide a maximum theoretical bound for the
5164 * execution size of the message based on the number of argument components
5165 * alone, which in most cases will determine whether the SIMD8 or SIMD16
5166 * variant of the message can be used, though some messages may have
5167 * additional restrictions not accounted for here (e.g. pre-ILK hardware uses
5168 * the message length to determine the exact SIMD width and argument count,
5169 * which makes a number of sampler message combinations impossible to
5173 get_sampler_lowered_simd_width(const struct gen_device_info *devinfo,
5174 const fs_inst *inst)
5176 /* Calculate the number of coordinate components that have to be present
5177 * assuming that additional arguments follow the texel coordinates in the
5178 * message payload. On IVB+ there is no need for padding, on ILK-SNB we
5179 * need to pad to four or three components depending on the message,
5180 * pre-ILK we need to pad to at most three components.
5182 const unsigned req_coord_components =
5183 (devinfo->gen >= 7 ||
5184 !inst->components_read(TEX_LOGICAL_SRC_COORDINATE)) ? 0 :
5185 (devinfo->gen >= 5 && inst->opcode != SHADER_OPCODE_TXF_LOGICAL &&
5186 inst->opcode != SHADER_OPCODE_TXF_CMS_LOGICAL) ? 4 :
5189 /* On Gen9+ the LOD argument is for free if we're able to use the LZ
5190 * variant of the TXL or TXF message.
5192 const bool implicit_lod = devinfo->gen >= 9 &&
5193 (inst->opcode == SHADER_OPCODE_TXL ||
5194 inst->opcode == SHADER_OPCODE_TXF) &&
5195 inst->src[TEX_LOGICAL_SRC_LOD].is_zero();
5197 /* Calculate the total number of argument components that need to be passed
5198 * to the sampler unit.
5200 const unsigned num_payload_components =
5201 MAX2(inst->components_read(TEX_LOGICAL_SRC_COORDINATE),
5202 req_coord_components) +
5203 inst->components_read(TEX_LOGICAL_SRC_SHADOW_C) +
5204 (implicit_lod ? 0 : inst->components_read(TEX_LOGICAL_SRC_LOD)) +
5205 inst->components_read(TEX_LOGICAL_SRC_LOD2) +
5206 inst->components_read(TEX_LOGICAL_SRC_SAMPLE_INDEX) +
5207 (inst->opcode == SHADER_OPCODE_TG4_OFFSET_LOGICAL ?
5208 inst->components_read(TEX_LOGICAL_SRC_TG4_OFFSET) : 0) +
5209 inst->components_read(TEX_LOGICAL_SRC_MCS);
5211 /* SIMD16 messages with more than five arguments exceed the maximum message
5212 * size supported by the sampler, regardless of whether a header is
5215 return MIN2(inst->exec_size,
5216 num_payload_components > MAX_SAMPLER_MESSAGE_SIZE / 2 ? 8 : 16);
5220 * Get the closest native SIMD width supported by the hardware for instruction
5221 * \p inst. The instruction will be left untouched by
5222 * fs_visitor::lower_simd_width() if the returned value is equal to the
5223 * original execution size.
5226 get_lowered_simd_width(const struct gen_device_info *devinfo,
5227 const fs_inst *inst)
5229 switch (inst->opcode) {
5230 case BRW_OPCODE_MOV:
5231 case BRW_OPCODE_SEL:
5232 case BRW_OPCODE_NOT:
5233 case BRW_OPCODE_AND:
5235 case BRW_OPCODE_XOR:
5236 case BRW_OPCODE_SHR:
5237 case BRW_OPCODE_SHL:
5238 case BRW_OPCODE_ASR:
5239 case BRW_OPCODE_CMPN:
5240 case BRW_OPCODE_CSEL:
5241 case BRW_OPCODE_F32TO16:
5242 case BRW_OPCODE_F16TO32:
5243 case BRW_OPCODE_BFREV:
5244 case BRW_OPCODE_BFE:
5245 case BRW_OPCODE_ADD:
5246 case BRW_OPCODE_MUL:
5247 case BRW_OPCODE_AVG:
5248 case BRW_OPCODE_FRC:
5249 case BRW_OPCODE_RNDU:
5250 case BRW_OPCODE_RNDD:
5251 case BRW_OPCODE_RNDE:
5252 case BRW_OPCODE_RNDZ:
5253 case BRW_OPCODE_LZD:
5254 case BRW_OPCODE_FBH:
5255 case BRW_OPCODE_FBL:
5256 case BRW_OPCODE_CBIT:
5257 case BRW_OPCODE_SAD2:
5258 case BRW_OPCODE_MAD:
5259 case BRW_OPCODE_LRP:
5260 case FS_OPCODE_PACK:
5261 case SHADER_OPCODE_SEL_EXEC:
5262 case SHADER_OPCODE_CLUSTER_BROADCAST:
5263 return get_fpu_lowered_simd_width(devinfo, inst);
5265 case BRW_OPCODE_CMP: {
5266 /* The Ivybridge/BayTrail WaCMPInstFlagDepClearedEarly workaround says that
5267 * when the destination is a GRF the dependency-clear bit on the flag
5268 * register is cleared early.
5270 * Suggested workarounds are to disable coissuing CMP instructions
5271 * or to split CMP(16) instructions into two CMP(8) instructions.
5273 * We choose to split into CMP(8) instructions since disabling
5274 * coissuing would affect CMP instructions not otherwise affected by
5277 const unsigned max_width = (devinfo->gen == 7 && !devinfo->is_haswell &&
5278 !inst->dst.is_null() ? 8 : ~0);
5279 return MIN2(max_width, get_fpu_lowered_simd_width(devinfo, inst));
5281 case BRW_OPCODE_BFI1:
5282 case BRW_OPCODE_BFI2:
5283 /* The Haswell WaForceSIMD8ForBFIInstruction workaround says that we
5285 * "Force BFI instructions to be executed always in SIMD8."
5287 return MIN2(devinfo->is_haswell ? 8 : ~0u,
5288 get_fpu_lowered_simd_width(devinfo, inst));
5291 assert(inst->src[0].file == BAD_FILE || inst->exec_size <= 16);
5292 return inst->exec_size;
5294 case SHADER_OPCODE_RCP:
5295 case SHADER_OPCODE_RSQ:
5296 case SHADER_OPCODE_SQRT:
5297 case SHADER_OPCODE_EXP2:
5298 case SHADER_OPCODE_LOG2:
5299 case SHADER_OPCODE_SIN:
5300 case SHADER_OPCODE_COS:
5301 /* Unary extended math instructions are limited to SIMD8 on Gen4 and
5304 return (devinfo->gen >= 7 ? MIN2(16, inst->exec_size) :
5305 devinfo->gen == 5 || devinfo->is_g4x ? MIN2(16, inst->exec_size) :
5306 MIN2(8, inst->exec_size));
5308 case SHADER_OPCODE_POW:
5309 /* SIMD16 is only allowed on Gen7+. */
5310 return (devinfo->gen >= 7 ? MIN2(16, inst->exec_size) :
5311 MIN2(8, inst->exec_size));
5313 case SHADER_OPCODE_INT_QUOTIENT:
5314 case SHADER_OPCODE_INT_REMAINDER:
5315 /* Integer division is limited to SIMD8 on all generations. */
5316 return MIN2(8, inst->exec_size);
5318 case FS_OPCODE_LINTERP:
5319 case SHADER_OPCODE_GET_BUFFER_SIZE:
5320 case FS_OPCODE_DDX_COARSE:
5321 case FS_OPCODE_DDX_FINE:
5322 case FS_OPCODE_DDY_COARSE:
5323 case FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD:
5324 case FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_GEN7:
5325 case FS_OPCODE_PACK_HALF_2x16_SPLIT:
5326 case FS_OPCODE_UNPACK_HALF_2x16_SPLIT_X:
5327 case FS_OPCODE_UNPACK_HALF_2x16_SPLIT_Y:
5328 case FS_OPCODE_INTERPOLATE_AT_SAMPLE:
5329 case FS_OPCODE_INTERPOLATE_AT_SHARED_OFFSET:
5330 case FS_OPCODE_INTERPOLATE_AT_PER_SLOT_OFFSET:
5331 return MIN2(16, inst->exec_size);
5333 case FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_LOGICAL:
5334 /* Pre-ILK hardware doesn't have a SIMD8 variant of the texel fetch
5335 * message used to implement varying pull constant loads, so expand it
5336 * to SIMD16. An alternative with longer message payload length but
5337 * shorter return payload would be to use the SIMD8 sampler message that
5338 * takes (header, u, v, r) as parameters instead of (header, u).
5340 return (devinfo->gen == 4 ? 16 : MIN2(16, inst->exec_size));
5342 case FS_OPCODE_DDY_FINE:
5343 /* The implementation of this virtual opcode may require emitting
5344 * compressed Align16 instructions, which are severely limited on some
5347 * From the Ivy Bridge PRM, volume 4 part 3, section 3.3.9 (Register
5348 * Region Restrictions):
5350 * "In Align16 access mode, SIMD16 is not allowed for DW operations
5351 * and SIMD8 is not allowed for DF operations."
5353 * In this context, "DW operations" means "operations acting on 32-bit
5354 * values", so it includes operations on floats.
5356 * Gen4 has a similar restriction. From the i965 PRM, section 11.5.3
5357 * (Instruction Compression -> Rules and Restrictions):
5359 * "A compressed instruction must be in Align1 access mode. Align16
5360 * mode instructions cannot be compressed."
5362 * Similar text exists in the g45 PRM.
5364 * Empirically, compressed align16 instructions using odd register
5365 * numbers don't appear to work on Sandybridge either.
5367 return (devinfo->gen == 4 || devinfo->gen == 6 ||
5368 (devinfo->gen == 7 && !devinfo->is_haswell) ?
5369 MIN2(8, inst->exec_size) : MIN2(16, inst->exec_size));
5371 case SHADER_OPCODE_MULH:
5372 /* MULH is lowered to the MUL/MACH sequence using the accumulator, which
5373 * is 8-wide on Gen7+.
5375 return (devinfo->gen >= 7 ? 8 :
5376 get_fpu_lowered_simd_width(devinfo, inst));
5378 case FS_OPCODE_FB_WRITE_LOGICAL:
5379 /* Gen6 doesn't support SIMD16 depth writes but we cannot handle them
5382 assert(devinfo->gen != 6 ||
5383 inst->src[FB_WRITE_LOGICAL_SRC_SRC_DEPTH].file == BAD_FILE ||
5384 inst->exec_size == 8);
5385 /* Dual-source FB writes are unsupported in SIMD16 mode. */
5386 return (inst->src[FB_WRITE_LOGICAL_SRC_COLOR1].file != BAD_FILE ?
5387 8 : MIN2(16, inst->exec_size));
5389 case FS_OPCODE_FB_READ_LOGICAL:
5390 return MIN2(16, inst->exec_size);
5392 case SHADER_OPCODE_TEX_LOGICAL:
5393 case SHADER_OPCODE_TXF_CMS_LOGICAL:
5394 case SHADER_OPCODE_TXF_UMS_LOGICAL:
5395 case SHADER_OPCODE_TXF_MCS_LOGICAL:
5396 case SHADER_OPCODE_LOD_LOGICAL:
5397 case SHADER_OPCODE_TG4_LOGICAL:
5398 case SHADER_OPCODE_SAMPLEINFO_LOGICAL:
5399 case SHADER_OPCODE_TXF_CMS_W_LOGICAL:
5400 case SHADER_OPCODE_TG4_OFFSET_LOGICAL:
5401 return get_sampler_lowered_simd_width(devinfo, inst);
5403 case SHADER_OPCODE_TXD_LOGICAL:
5404 /* TXD is unsupported in SIMD16 mode. */
5407 case SHADER_OPCODE_TXL_LOGICAL:
5408 case FS_OPCODE_TXB_LOGICAL:
5409 /* Only one execution size is representable pre-ILK depending on whether
5410 * the shadow reference argument is present.
5412 if (devinfo->gen == 4)
5413 return inst->src[TEX_LOGICAL_SRC_SHADOW_C].file == BAD_FILE ? 16 : 8;
5415 return get_sampler_lowered_simd_width(devinfo, inst);
5417 case SHADER_OPCODE_TXF_LOGICAL:
5418 case SHADER_OPCODE_TXS_LOGICAL:
5419 /* Gen4 doesn't have SIMD8 variants for the RESINFO and LD-with-LOD
5420 * messages. Use SIMD16 instead.
5422 if (devinfo->gen == 4)
5425 return get_sampler_lowered_simd_width(devinfo, inst);
5427 case SHADER_OPCODE_TYPED_ATOMIC_LOGICAL:
5428 case SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL:
5429 case SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL:
5432 case SHADER_OPCODE_UNTYPED_ATOMIC_LOGICAL:
5433 case SHADER_OPCODE_UNTYPED_SURFACE_READ_LOGICAL:
5434 case SHADER_OPCODE_UNTYPED_SURFACE_WRITE_LOGICAL:
5435 case SHADER_OPCODE_BYTE_SCATTERED_WRITE_LOGICAL:
5436 case SHADER_OPCODE_BYTE_SCATTERED_READ_LOGICAL:
5437 return MIN2(16, inst->exec_size);
5439 case SHADER_OPCODE_URB_READ_SIMD8:
5440 case SHADER_OPCODE_URB_READ_SIMD8_PER_SLOT:
5441 case SHADER_OPCODE_URB_WRITE_SIMD8:
5442 case SHADER_OPCODE_URB_WRITE_SIMD8_PER_SLOT:
5443 case SHADER_OPCODE_URB_WRITE_SIMD8_MASKED:
5444 case SHADER_OPCODE_URB_WRITE_SIMD8_MASKED_PER_SLOT:
5445 return MIN2(8, inst->exec_size);
5447 case SHADER_OPCODE_QUAD_SWIZZLE:
5450 case SHADER_OPCODE_MOV_INDIRECT: {
5451 /* From IVB and HSW PRMs:
5453 * "2.When the destination requires two registers and the sources are
5454 * indirect, the sources must use 1x1 regioning mode.
5456 * In case of DF instructions in HSW/IVB, the exec_size is limited by
5457 * the EU decompression logic not handling VxH indirect addressing
5460 const unsigned max_size = (devinfo->gen >= 8 ? 2 : 1) * REG_SIZE;
5461 /* Prior to Broadwell, we only have 8 address subregisters. */
5462 return MIN3(devinfo->gen >= 8 ? 16 : 8,
5463 max_size / (inst->dst.stride * type_sz(inst->dst.type)),
5467 case SHADER_OPCODE_LOAD_PAYLOAD: {
5468 const unsigned reg_count =
5469 DIV_ROUND_UP(inst->dst.component_size(inst->exec_size), REG_SIZE);
5471 if (reg_count > 2) {
5472 /* Only LOAD_PAYLOAD instructions with per-channel destination region
5473 * can be easily lowered (which excludes headers and heterogeneous
5476 assert(!inst->header_size);
5477 for (unsigned i = 0; i < inst->sources; i++)
5478 assert(type_sz(inst->dst.type) == type_sz(inst->src[i].type) ||
5479 inst->src[i].file == BAD_FILE);
5481 return inst->exec_size / DIV_ROUND_UP(reg_count, 2);
5483 return inst->exec_size;
5487 return inst->exec_size;
5492 * Return true if splitting out the group of channels of instruction \p inst
5493 * given by lbld.group() requires allocating a temporary for the i-th source
5494 * of the lowered instruction.
5497 needs_src_copy(const fs_builder &lbld, const fs_inst *inst, unsigned i)
5499 return !(is_periodic(inst->src[i], lbld.dispatch_width()) ||
5500 (inst->components_read(i) == 1 &&
5501 lbld.dispatch_width() <= inst->exec_size)) ||
5502 (inst->flags_written() &
5503 flag_mask(inst->src[i], type_sz(inst->src[i].type)));
5507 * Extract the data that would be consumed by the channel group given by
5508 * lbld.group() from the i-th source region of instruction \p inst and return
5509 * it as result in packed form.
5512 emit_unzip(const fs_builder &lbld, fs_inst *inst, unsigned i)
5514 /* Specified channel group from the source region. */
5515 const fs_reg src = horiz_offset(inst->src[i], lbld.group());
5517 if (needs_src_copy(lbld, inst, i)) {
5518 /* Builder of the right width to perform the copy avoiding uninitialized
5519 * data if the lowered execution size is greater than the original
5520 * execution size of the instruction.
5522 const fs_builder cbld = lbld.group(MIN2(lbld.dispatch_width(),
5523 inst->exec_size), 0);
5524 const fs_reg tmp = lbld.vgrf(inst->src[i].type, inst->components_read(i));
5526 for (unsigned k = 0; k < inst->components_read(i); ++k)
5527 cbld.MOV(offset(tmp, lbld, k), offset(src, inst->exec_size, k));
5531 } else if (is_periodic(inst->src[i], lbld.dispatch_width())) {
5532 /* The source is invariant for all dispatch_width-wide groups of the
5535 return inst->src[i];
5538 /* We can just point the lowered instruction at the right channel group
5539 * from the original region.
5546 * Return true if splitting out the group of channels of instruction \p inst
5547 * given by lbld.group() requires allocating a temporary for the destination
5548 * of the lowered instruction and copying the data back to the original
5549 * destination region.
5552 needs_dst_copy(const fs_builder &lbld, const fs_inst *inst)
5554 /* If the instruction writes more than one component we'll have to shuffle
5555 * the results of multiple lowered instructions in order to make sure that
5556 * they end up arranged correctly in the original destination region.
5558 if (inst->size_written > inst->dst.component_size(inst->exec_size))
5561 /* If the lowered execution size is larger than the original the result of
5562 * the instruction won't fit in the original destination, so we'll have to
5563 * allocate a temporary in any case.
5565 if (lbld.dispatch_width() > inst->exec_size)
5568 for (unsigned i = 0; i < inst->sources; i++) {
5569 /* If we already made a copy of the source for other reasons there won't
5570 * be any overlap with the destination.
5572 if (needs_src_copy(lbld, inst, i))
5575 /* In order to keep the logic simple we emit a copy whenever the
5576 * destination region doesn't exactly match an overlapping source, which
5577 * may point at the source and destination not being aligned group by
5578 * group which could cause one of the lowered instructions to overwrite
5579 * the data read from the same source by other lowered instructions.
5581 if (regions_overlap(inst->dst, inst->size_written,
5582 inst->src[i], inst->size_read(i)) &&
5583 !inst->dst.equals(inst->src[i]))
5591 * Insert data from a packed temporary into the channel group given by
5592 * lbld.group() of the destination region of instruction \p inst and return
5593 * the temporary as result. Any copy instructions that are required for
5594 * unzipping the previous value (in the case of partial writes) will be
5595 * inserted using \p lbld_before and any copy instructions required for
5596 * zipping up the destination of \p inst will be inserted using \p lbld_after.
5599 emit_zip(const fs_builder &lbld_before, const fs_builder &lbld_after,
5602 assert(lbld_before.dispatch_width() == lbld_after.dispatch_width());
5603 assert(lbld_before.group() == lbld_after.group());
5605 /* Specified channel group from the destination region. */
5606 const fs_reg dst = horiz_offset(inst->dst, lbld_after.group());
5607 const unsigned dst_size = inst->size_written /
5608 inst->dst.component_size(inst->exec_size);
5610 if (needs_dst_copy(lbld_after, inst)) {
5611 const fs_reg tmp = lbld_after.vgrf(inst->dst.type, dst_size);
5613 if (inst->predicate) {
5614 /* Handle predication by copying the original contents of
5615 * the destination into the temporary before emitting the
5616 * lowered instruction.
5618 const fs_builder gbld_before =
5619 lbld_before.group(MIN2(lbld_before.dispatch_width(),
5620 inst->exec_size), 0);
5621 for (unsigned k = 0; k < dst_size; ++k) {
5622 gbld_before.MOV(offset(tmp, lbld_before, k),
5623 offset(dst, inst->exec_size, k));
5627 const fs_builder gbld_after =
5628 lbld_after.group(MIN2(lbld_after.dispatch_width(),
5629 inst->exec_size), 0);
5630 for (unsigned k = 0; k < dst_size; ++k) {
5631 /* Use a builder of the right width to perform the copy avoiding
5632 * uninitialized data if the lowered execution size is greater than
5633 * the original execution size of the instruction.
5635 gbld_after.MOV(offset(dst, inst->exec_size, k),
5636 offset(tmp, lbld_after, k));
5642 /* No need to allocate a temporary for the lowered instruction, just
5643 * take the right group of channels from the original region.
5650 fs_visitor::lower_simd_width()
5652 bool progress = false;
5654 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
5655 const unsigned lower_width = get_lowered_simd_width(devinfo, inst);
5657 if (lower_width != inst->exec_size) {
5658 /* Builder matching the original instruction. We may also need to
5659 * emit an instruction of width larger than the original, set the
5660 * execution size of the builder to the highest of both for now so
5661 * we're sure that both cases can be handled.
5663 const unsigned max_width = MAX2(inst->exec_size, lower_width);
5664 const fs_builder ibld = bld.at(block, inst)
5665 .exec_all(inst->force_writemask_all)
5666 .group(max_width, inst->group / max_width);
5668 /* Split the copies in chunks of the execution width of either the
5669 * original or the lowered instruction, whichever is lower.
5671 const unsigned n = DIV_ROUND_UP(inst->exec_size, lower_width);
5672 const unsigned dst_size = inst->size_written /
5673 inst->dst.component_size(inst->exec_size);
5675 assert(!inst->writes_accumulator && !inst->mlen);
5677 /* Inserting the zip, unzip, and duplicated instructions in all of
5678 * the right spots is somewhat tricky. All of the unzip and any
5679 * instructions from the zip which unzip the destination prior to
5680 * writing need to happen before all of the per-group instructions
5681 * and the zip instructions need to happen after. In order to sort
5682 * this all out, we insert the unzip instructions before \p inst,
5683 * insert the per-group instructions after \p inst (i.e. before
5684 * inst->next), and insert the zip instructions before the
5685 * instruction after \p inst. Since we are inserting instructions
5686 * after \p inst, inst->next is a moving target and we need to save
5687 * it off here so that we insert the zip instructions in the right
5690 * Since we're inserting split instructions after after_inst, the
5691 * instructions will end up in the reverse order that we insert them.
5692 * However, certain render target writes require that the low group
5693 * instructions come before the high group. From the Ivy Bridge PRM
5694 * Vol. 4, Pt. 1, Section 3.9.11:
5696 * "If multiple SIMD8 Dual Source messages are delivered by the
5697 * pixel shader thread, each SIMD8_DUALSRC_LO message must be
5698 * issued before the SIMD8_DUALSRC_HI message with the same Slot
5699 * Group Select setting."
5701 * And, from Section 3.9.11.1 of the same PRM:
5703 * "When SIMD32 or SIMD16 PS threads send render target writes
5704 * with multiple SIMD8 and SIMD16 messages, the following must
5707 * All the slots (as described above) must have a corresponding
5708 * render target write irrespective of the slot's validity. A slot
5709 * is considered valid when at least one sample is enabled. For
5710 * example, a SIMD16 PS thread must send two SIMD8 render target
5711 * writes to cover all the slots.
5713 * PS thread must send SIMD render target write messages with
5714 * increasing slot numbers. For example, SIMD16 thread has
5715 * Slot[15:0] and if two SIMD8 render target writes are used, the
5716 * first SIMD8 render target write must send Slot[7:0] and the
5717 * next one must send Slot[15:8]."
5719 * In order to make low group instructions come before high group
5720 * instructions (this is required for some render target writes), we
5721 * split from the highest group to lowest.
5723 exec_node *const after_inst = inst->next;
5724 for (int i = n - 1; i >= 0; i--) {
5725 /* Emit a copy of the original instruction with the lowered width.
5726 * If the EOT flag was set throw it away except for the last
5727 * instruction to avoid killing the thread prematurely.
5729 fs_inst split_inst = *inst;
5730 split_inst.exec_size = lower_width;
5731 split_inst.eot = inst->eot && i == n - 1;
5733 /* Select the correct channel enables for the i-th group, then
5734 * transform the sources and destination and emit the lowered
5737 const fs_builder lbld = ibld.group(lower_width, i);
5739 for (unsigned j = 0; j < inst->sources; j++)
5740 split_inst.src[j] = emit_unzip(lbld.at(block, inst), inst, j);
5742 split_inst.dst = emit_zip(lbld.at(block, inst),
5743 lbld.at(block, after_inst), inst);
5744 split_inst.size_written =
5745 split_inst.dst.component_size(lower_width) * dst_size;
5747 lbld.at(block, inst->next).emit(split_inst);
5750 inst->remove(block);
5756 invalidate_live_intervals();
5762 fs_visitor::dump_instructions()
5764 dump_instructions(NULL);
5768 fs_visitor::dump_instructions(const char *name)
5770 FILE *file = stderr;
5771 if (name && geteuid() != 0) {
5772 file = fopen(name, "w");
5778 calculate_register_pressure();
5779 int ip = 0, max_pressure = 0;
5780 foreach_block_and_inst(block, backend_instruction, inst, cfg) {
5781 max_pressure = MAX2(max_pressure, regs_live_at_ip[ip]);
5782 fprintf(file, "{%3d} %4d: ", regs_live_at_ip[ip], ip);
5783 dump_instruction(inst, file);
5786 fprintf(file, "Maximum %3d registers live at once.\n", max_pressure);
5789 foreach_in_list(backend_instruction, inst, &instructions) {
5790 fprintf(file, "%4d: ", ip++);
5791 dump_instruction(inst, file);
5795 if (file != stderr) {
5801 fs_visitor::dump_instruction(backend_instruction *be_inst)
5803 dump_instruction(be_inst, stderr);
5807 fs_visitor::dump_instruction(backend_instruction *be_inst, FILE *file)
5809 fs_inst *inst = (fs_inst *)be_inst;
5811 if (inst->predicate) {
5812 fprintf(file, "(%cf%d.%d) ",
5813 inst->predicate_inverse ? '-' : '+',
5814 inst->flag_subreg / 2,
5815 inst->flag_subreg % 2);
5818 fprintf(file, "%s", brw_instruction_name(devinfo, inst->opcode));
5820 fprintf(file, ".sat");
5821 if (inst->conditional_mod) {
5822 fprintf(file, "%s", conditional_modifier[inst->conditional_mod]);
5823 if (!inst->predicate &&
5824 (devinfo->gen < 5 || (inst->opcode != BRW_OPCODE_SEL &&
5825 inst->opcode != BRW_OPCODE_CSEL &&
5826 inst->opcode != BRW_OPCODE_IF &&
5827 inst->opcode != BRW_OPCODE_WHILE))) {
5828 fprintf(file, ".f%d.%d", inst->flag_subreg / 2,
5829 inst->flag_subreg % 2);
5832 fprintf(file, "(%d) ", inst->exec_size);
5835 fprintf(file, "(mlen: %d) ", inst->mlen);
5839 fprintf(file, "(EOT) ");
5842 switch (inst->dst.file) {
5844 fprintf(file, "vgrf%d", inst->dst.nr);
5847 fprintf(file, "g%d", inst->dst.nr);
5850 fprintf(file, "m%d", inst->dst.nr);
5853 fprintf(file, "(null)");
5856 fprintf(file, "***u%d***", inst->dst.nr);
5859 fprintf(file, "***attr%d***", inst->dst.nr);
5862 switch (inst->dst.nr) {
5864 fprintf(file, "null");
5866 case BRW_ARF_ADDRESS:
5867 fprintf(file, "a0.%d", inst->dst.subnr);
5869 case BRW_ARF_ACCUMULATOR:
5870 fprintf(file, "acc%d", inst->dst.subnr);
5873 fprintf(file, "f%d.%d", inst->dst.nr & 0xf, inst->dst.subnr);
5876 fprintf(file, "arf%d.%d", inst->dst.nr & 0xf, inst->dst.subnr);
5881 unreachable("not reached");
5884 if (inst->dst.offset ||
5885 (inst->dst.file == VGRF &&
5886 alloc.sizes[inst->dst.nr] * REG_SIZE != inst->size_written)) {
5887 const unsigned reg_size = (inst->dst.file == UNIFORM ? 4 : REG_SIZE);
5888 fprintf(file, "+%d.%d", inst->dst.offset / reg_size,
5889 inst->dst.offset % reg_size);
5892 if (inst->dst.stride != 1)
5893 fprintf(file, "<%u>", inst->dst.stride);
5894 fprintf(file, ":%s, ", brw_reg_type_to_letters(inst->dst.type));
5896 for (int i = 0; i < inst->sources; i++) {
5897 if (inst->src[i].negate)
5899 if (inst->src[i].abs)
5901 switch (inst->src[i].file) {
5903 fprintf(file, "vgrf%d", inst->src[i].nr);
5906 fprintf(file, "g%d", inst->src[i].nr);
5909 fprintf(file, "***m%d***", inst->src[i].nr);
5912 fprintf(file, "attr%d", inst->src[i].nr);
5915 fprintf(file, "u%d", inst->src[i].nr);
5918 fprintf(file, "(null)");
5921 switch (inst->src[i].type) {
5922 case BRW_REGISTER_TYPE_F:
5923 fprintf(file, "%-gf", inst->src[i].f);
5925 case BRW_REGISTER_TYPE_DF:
5926 fprintf(file, "%fdf", inst->src[i].df);
5928 case BRW_REGISTER_TYPE_W:
5929 case BRW_REGISTER_TYPE_D:
5930 fprintf(file, "%dd", inst->src[i].d);
5932 case BRW_REGISTER_TYPE_UW:
5933 case BRW_REGISTER_TYPE_UD:
5934 fprintf(file, "%uu", inst->src[i].ud);
5936 case BRW_REGISTER_TYPE_VF:
5937 fprintf(file, "[%-gF, %-gF, %-gF, %-gF]",
5938 brw_vf_to_float((inst->src[i].ud >> 0) & 0xff),
5939 brw_vf_to_float((inst->src[i].ud >> 8) & 0xff),
5940 brw_vf_to_float((inst->src[i].ud >> 16) & 0xff),
5941 brw_vf_to_float((inst->src[i].ud >> 24) & 0xff));
5944 fprintf(file, "???");
5949 switch (inst->src[i].nr) {
5951 fprintf(file, "null");
5953 case BRW_ARF_ADDRESS:
5954 fprintf(file, "a0.%d", inst->src[i].subnr);
5956 case BRW_ARF_ACCUMULATOR:
5957 fprintf(file, "acc%d", inst->src[i].subnr);
5960 fprintf(file, "f%d.%d", inst->src[i].nr & 0xf, inst->src[i].subnr);
5963 fprintf(file, "arf%d.%d", inst->src[i].nr & 0xf, inst->src[i].subnr);
5969 if (inst->src[i].offset ||
5970 (inst->src[i].file == VGRF &&
5971 alloc.sizes[inst->src[i].nr] * REG_SIZE != inst->size_read(i))) {
5972 const unsigned reg_size = (inst->src[i].file == UNIFORM ? 4 : REG_SIZE);
5973 fprintf(file, "+%d.%d", inst->src[i].offset / reg_size,
5974 inst->src[i].offset % reg_size);
5977 if (inst->src[i].abs)
5980 if (inst->src[i].file != IMM) {
5982 if (inst->src[i].file == ARF || inst->src[i].file == FIXED_GRF) {
5983 unsigned hstride = inst->src[i].hstride;
5984 stride = (hstride == 0 ? 0 : (1 << (hstride - 1)));
5986 stride = inst->src[i].stride;
5989 fprintf(file, "<%u>", stride);
5991 fprintf(file, ":%s", brw_reg_type_to_letters(inst->src[i].type));
5994 if (i < inst->sources - 1 && inst->src[i + 1].file != BAD_FILE)
5995 fprintf(file, ", ");
6000 if (inst->force_writemask_all)
6001 fprintf(file, "NoMask ");
6003 if (inst->exec_size != dispatch_width)
6004 fprintf(file, "group%d ", inst->group);
6006 fprintf(file, "\n");
6010 * Possibly returns an instruction that set up @param reg.
6012 * Sometimes we want to take the result of some expression/variable
6013 * dereference tree and rewrite the instruction generating the result
6014 * of the tree. When processing the tree, we know that the
6015 * instructions generated are all writing temporaries that are dead
6016 * outside of this tree. So, if we have some instructions that write
6017 * a temporary, we're free to point that temp write somewhere else.
6019 * Note that this doesn't guarantee that the instruction generated
6020 * only reg -- it might be the size=4 destination of a texture instruction.
6023 fs_visitor::get_instruction_generating_reg(fs_inst *start,
6028 end->is_partial_write() ||
6029 !reg.equals(end->dst)) {
6037 fs_visitor::setup_fs_payload_gen6()
6039 assert(stage == MESA_SHADER_FRAGMENT);
6040 struct brw_wm_prog_data *prog_data = brw_wm_prog_data(this->prog_data);
6042 assert(devinfo->gen >= 6);
6044 /* R0-1: masks, pixel X/Y coordinates. */
6045 payload.num_regs = 2;
6046 /* R2: only for 32-pixel dispatch.*/
6048 /* R3-26: barycentric interpolation coordinates. These appear in the
6049 * same order that they appear in the brw_barycentric_mode
6050 * enum. Each set of coordinates occupies 2 registers if dispatch width
6051 * == 8 and 4 registers if dispatch width == 16. Coordinates only
6052 * appear if they were enabled using the "Barycentric Interpolation
6053 * Mode" bits in WM_STATE.
6055 for (int i = 0; i < BRW_BARYCENTRIC_MODE_COUNT; ++i) {
6056 if (prog_data->barycentric_interp_modes & (1 << i)) {
6057 payload.barycentric_coord_reg[i][0] = payload.num_regs;
6058 payload.num_regs += 2;
6059 if (dispatch_width == 16) {
6060 payload.num_regs += 2;
6065 /* R27: interpolated depth if uses source depth */
6066 prog_data->uses_src_depth =
6067 (nir->info.inputs_read & (1 << VARYING_SLOT_POS)) != 0;
6068 if (prog_data->uses_src_depth) {
6069 payload.source_depth_reg[0] = payload.num_regs;
6071 if (dispatch_width == 16) {
6072 /* R28: interpolated depth if not SIMD8. */
6077 /* R29: interpolated W set if GEN6_WM_USES_SOURCE_W. */
6078 prog_data->uses_src_w =
6079 (nir->info.inputs_read & (1 << VARYING_SLOT_POS)) != 0;
6080 if (prog_data->uses_src_w) {
6081 payload.source_w_reg[0] = payload.num_regs;
6083 if (dispatch_width == 16) {
6084 /* R30: interpolated W if not SIMD8. */
6089 /* R31: MSAA position offsets. */
6090 if (prog_data->persample_dispatch &&
6091 (nir->info.system_values_read & SYSTEM_BIT_SAMPLE_POS)) {
6092 /* From the Ivy Bridge PRM documentation for 3DSTATE_PS:
6094 * "MSDISPMODE_PERSAMPLE is required in order to select
6097 * So we can only really get sample positions if we are doing real
6098 * per-sample dispatch. If we need gl_SamplePosition and we don't have
6099 * persample dispatch, we hard-code it to 0.5.
6101 prog_data->uses_pos_offset = true;
6102 payload.sample_pos_reg[0] = payload.num_regs;
6106 /* R32: MSAA input coverage mask */
6107 prog_data->uses_sample_mask =
6108 (nir->info.system_values_read & SYSTEM_BIT_SAMPLE_MASK_IN) != 0;
6109 if (prog_data->uses_sample_mask) {
6110 assert(devinfo->gen >= 7);
6111 payload.sample_mask_in_reg[0] = payload.num_regs;
6113 if (dispatch_width == 16) {
6114 /* R33: input coverage mask if not SIMD8. */
6119 /* R34-: bary for 32-pixel. */
6120 /* R58-59: interp W for 32-pixel. */
6122 if (nir->info.outputs_written & BITFIELD64_BIT(FRAG_RESULT_DEPTH)) {
6123 source_depth_to_render_target = true;
6128 fs_visitor::setup_vs_payload()
6130 /* R0: thread header, R1: urb handles */
6131 payload.num_regs = 2;
6135 fs_visitor::setup_gs_payload()
6137 assert(stage == MESA_SHADER_GEOMETRY);
6139 struct brw_gs_prog_data *gs_prog_data = brw_gs_prog_data(prog_data);
6140 struct brw_vue_prog_data *vue_prog_data = brw_vue_prog_data(prog_data);
6142 /* R0: thread header, R1: output URB handles */
6143 payload.num_regs = 2;
6145 if (gs_prog_data->include_primitive_id) {
6146 /* R2: Primitive ID 0..7 */
6150 /* Always enable VUE handles so we can safely use pull model if needed.
6152 * The push model for a GS uses a ton of register space even for trivial
6153 * scenarios with just a few inputs, so just make things easier and a bit
6154 * safer by always having pull model available.
6156 gs_prog_data->base.include_vue_handles = true;
6158 /* R3..RN: ICP Handles for each incoming vertex (when using pull model) */
6159 payload.num_regs += nir->info.gs.vertices_in;
6161 /* Use a maximum of 24 registers for push-model inputs. */
6162 const unsigned max_push_components = 24;
6164 /* If pushing our inputs would take too many registers, reduce the URB read
6165 * length (which is in HWords, or 8 registers), and resort to pulling.
6167 * Note that the GS reads <URB Read Length> HWords for every vertex - so we
6168 * have to multiply by VerticesIn to obtain the total storage requirement.
6170 if (8 * vue_prog_data->urb_read_length * nir->info.gs.vertices_in >
6171 max_push_components) {
6172 vue_prog_data->urb_read_length =
6173 ROUND_DOWN_TO(max_push_components / nir->info.gs.vertices_in, 8) / 8;
6178 fs_visitor::setup_cs_payload()
6180 assert(devinfo->gen >= 7);
6181 payload.num_regs = 1;
6185 fs_visitor::calculate_register_pressure()
6187 invalidate_live_intervals();
6188 calculate_live_intervals();
6190 unsigned num_instructions = 0;
6191 foreach_block(block, cfg)
6192 num_instructions += block->instructions.length();
6194 regs_live_at_ip = rzalloc_array(mem_ctx, int, num_instructions);
6196 for (unsigned reg = 0; reg < alloc.count; reg++) {
6197 for (int ip = virtual_grf_start[reg]; ip <= virtual_grf_end[reg]; ip++)
6198 regs_live_at_ip[ip] += alloc.sizes[reg];
6203 * Look for repeated FS_OPCODE_MOV_DISPATCH_TO_FLAGS and drop the later ones.
6205 * The needs_unlit_centroid_workaround ends up producing one of these per
6206 * channel of centroid input, so it's good to clean them up.
6208 * An assumption here is that nothing ever modifies the dispatched pixels
6209 * value that FS_OPCODE_MOV_DISPATCH_TO_FLAGS reads from, but the hardware
6210 * dictates that anyway.
6213 fs_visitor::opt_drop_redundant_mov_to_flags()
6215 bool flag_mov_found[4] = {false};
6216 bool progress = false;
6218 /* Instructions removed by this pass can only be added if this were true */
6219 if (!devinfo->needs_unlit_centroid_workaround)
6222 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
6223 if (inst->is_control_flow()) {
6224 memset(flag_mov_found, 0, sizeof(flag_mov_found));
6225 } else if (inst->opcode == FS_OPCODE_MOV_DISPATCH_TO_FLAGS) {
6226 if (!flag_mov_found[inst->flag_subreg]) {
6227 flag_mov_found[inst->flag_subreg] = true;
6229 inst->remove(block);
6232 } else if (inst->flags_written()) {
6233 flag_mov_found[inst->flag_subreg] = false;
6241 fs_visitor::optimize()
6243 /* Start by validating the shader we currently have. */
6246 /* bld is the common builder object pointing at the end of the program we
6247 * used to translate it into i965 IR. For the optimization and lowering
6248 * passes coming next, any code added after the end of the program without
6249 * having explicitly called fs_builder::at() clearly points at a mistake.
6250 * Ideally optimization passes wouldn't be part of the visitor so they
6251 * wouldn't have access to bld at all, but they do, so just in case some
6252 * pass forgets to ask for a location explicitly set it to NULL here to
6253 * make it trip. The dispatch width is initialized to a bogus value to
6254 * make sure that optimizations set the execution controls explicitly to
6255 * match the code they are manipulating instead of relying on the defaults.
6257 bld = fs_builder(this, 64);
6259 assign_constant_locations();
6260 lower_constant_loads();
6264 split_virtual_grfs();
6267 #define OPT(pass, args...) ({ \
6269 bool this_progress = pass(args); \
6271 if (unlikely(INTEL_DEBUG & DEBUG_OPTIMIZER) && this_progress) { \
6272 char filename[64]; \
6273 snprintf(filename, 64, "%s%d-%s-%02d-%02d-" #pass, \
6274 stage_abbrev, dispatch_width, nir->info.name, iteration, pass_num); \
6276 backend_shader::dump_instructions(filename); \
6281 progress = progress || this_progress; \
6285 if (unlikely(INTEL_DEBUG & DEBUG_OPTIMIZER)) {
6287 snprintf(filename, 64, "%s%d-%s-00-00-start",
6288 stage_abbrev, dispatch_width, nir->info.name);
6290 backend_shader::dump_instructions(filename);
6293 bool progress = false;
6297 OPT(opt_drop_redundant_mov_to_flags);
6298 OPT(remove_extra_rounding_modes);
6305 OPT(remove_duplicate_mrf_writes);
6309 OPT(opt_copy_propagation);
6310 OPT(opt_predicated_break, this);
6311 OPT(opt_cmod_propagation);
6312 OPT(dead_code_eliminate);
6313 OPT(opt_peephole_sel);
6314 OPT(dead_control_flow_eliminate, this);
6315 OPT(opt_register_renaming);
6316 OPT(opt_saturate_propagation);
6317 OPT(register_coalesce);
6318 OPT(compute_to_mrf);
6319 OPT(eliminate_find_live_channel);
6321 OPT(compact_virtual_grfs);
6324 /* Do this after cmod propagation has had every possible opportunity to
6325 * propagate results into SEL instructions.
6327 if (OPT(opt_peephole_csel))
6328 OPT(dead_code_eliminate);
6333 if (OPT(lower_pack)) {
6334 OPT(register_coalesce);
6335 OPT(dead_code_eliminate);
6338 OPT(lower_simd_width);
6340 /* After SIMD lowering just in case we had to unroll the EOT send. */
6341 OPT(opt_sampler_eot);
6343 OPT(lower_logical_sends);
6346 OPT(opt_copy_propagation);
6347 /* Only run after logical send lowering because it's easier to implement
6348 * in terms of physical sends.
6350 if (OPT(opt_zero_samples))
6351 OPT(opt_copy_propagation);
6352 /* Run after logical send lowering to give it a chance to CSE the
6353 * LOAD_PAYLOAD instructions created to construct the payloads of
6354 * e.g. texturing messages in cases where it wasn't possible to CSE the
6355 * whole logical instruction.
6358 OPT(register_coalesce);
6359 OPT(compute_to_mrf);
6360 OPT(dead_code_eliminate);
6361 OPT(remove_duplicate_mrf_writes);
6362 OPT(opt_peephole_sel);
6365 OPT(opt_redundant_discard_jumps);
6367 if (OPT(lower_load_payload)) {
6368 split_virtual_grfs();
6369 OPT(register_coalesce);
6370 OPT(compute_to_mrf);
6371 OPT(dead_code_eliminate);
6374 OPT(opt_combine_constants);
6375 OPT(lower_integer_multiplication);
6377 if (devinfo->gen <= 5 && OPT(lower_minmax)) {
6378 OPT(opt_cmod_propagation);
6380 OPT(opt_copy_propagation);
6381 OPT(dead_code_eliminate);
6384 if (OPT(lower_conversions)) {
6385 OPT(opt_copy_propagation);
6386 OPT(dead_code_eliminate);
6387 OPT(lower_simd_width);
6390 lower_uniform_pull_constant_loads();
6396 * Three source instruction must have a GRF/MRF destination register.
6397 * ARF NULL is not allowed. Fix that up by allocating a temporary GRF.
6400 fs_visitor::fixup_3src_null_dest()
6402 bool progress = false;
6404 foreach_block_and_inst_safe (block, fs_inst, inst, cfg) {
6405 if (inst->is_3src(devinfo) && inst->dst.is_null()) {
6406 inst->dst = fs_reg(VGRF, alloc.allocate(dispatch_width / 8),
6413 invalidate_live_intervals();
6417 fs_visitor::allocate_registers(unsigned min_dispatch_width, bool allow_spilling)
6419 bool allocated_without_spills;
6421 static const enum instruction_scheduler_mode pre_modes[] = {
6423 SCHEDULE_PRE_NON_LIFO,
6427 bool spill_all = allow_spilling && (INTEL_DEBUG & DEBUG_SPILL_FS);
6429 /* Try each scheduling heuristic to see if it can successfully register
6430 * allocate without spilling. They should be ordered by decreasing
6431 * performance but increasing likelihood of allocating.
6433 for (unsigned i = 0; i < ARRAY_SIZE(pre_modes); i++) {
6434 schedule_instructions(pre_modes[i]);
6437 assign_regs_trivial();
6438 allocated_without_spills = true;
6440 allocated_without_spills = assign_regs(false, spill_all);
6442 if (allocated_without_spills)
6446 if (!allocated_without_spills) {
6447 if (!allow_spilling)
6448 fail("Failure to register allocate and spilling is not allowed.");
6450 /* We assume that any spilling is worse than just dropping back to
6451 * SIMD8. There's probably actually some intermediate point where
6452 * SIMD16 with a couple of spills is still better.
6454 if (dispatch_width > min_dispatch_width) {
6455 fail("Failure to register allocate. Reduce number of "
6456 "live scalar values to avoid this.");
6458 compiler->shader_perf_log(log_data,
6459 "%s shader triggered register spilling. "
6460 "Try reducing the number of live scalar "
6461 "values to improve performance.\n",
6465 /* Since we're out of heuristics, just go spill registers until we
6466 * get an allocation.
6468 while (!assign_regs(true, spill_all)) {
6474 /* This must come after all optimization and register allocation, since
6475 * it inserts dead code that happens to have side effects, and it does
6476 * so based on the actual physical registers in use.
6478 insert_gen4_send_dependency_workarounds();
6483 opt_bank_conflicts();
6485 schedule_instructions(SCHEDULE_POST);
6487 if (last_scratch > 0) {
6488 MAYBE_UNUSED unsigned max_scratch_size = 2 * 1024 * 1024;
6490 prog_data->total_scratch = brw_get_scratch_size(last_scratch);
6492 if (stage == MESA_SHADER_COMPUTE) {
6493 if (devinfo->is_haswell) {
6494 /* According to the MEDIA_VFE_STATE's "Per Thread Scratch Space"
6495 * field documentation, Haswell supports a minimum of 2kB of
6496 * scratch space for compute shaders, unlike every other stage
6499 prog_data->total_scratch = MAX2(prog_data->total_scratch, 2048);
6500 } else if (devinfo->gen <= 7) {
6501 /* According to the MEDIA_VFE_STATE's "Per Thread Scratch Space"
6502 * field documentation, platforms prior to Haswell measure scratch
6503 * size linearly with a range of [1kB, 12kB] and 1kB granularity.
6505 prog_data->total_scratch = ALIGN(last_scratch, 1024);
6506 max_scratch_size = 12 * 1024;
6510 /* We currently only support up to 2MB of scratch space. If we
6511 * need to support more eventually, the documentation suggests
6512 * that we could allocate a larger buffer, and partition it out
6513 * ourselves. We'd just have to undo the hardware's address
6514 * calculation by subtracting (FFTID * Per Thread Scratch Space)
6515 * and then add FFTID * (Larger Per Thread Scratch Space).
6517 * See 3D-Media-GPGPU Engine > Media GPGPU Pipeline >
6518 * Thread Group Tracking > Local Memory/Scratch Space.
6520 assert(prog_data->total_scratch < max_scratch_size);
6525 fs_visitor::run_vs()
6527 assert(stage == MESA_SHADER_VERTEX);
6531 if (shader_time_index >= 0)
6532 emit_shader_time_begin();
6539 compute_clip_distance();
6543 if (shader_time_index >= 0)
6544 emit_shader_time_end();
6550 assign_curb_setup();
6551 assign_vs_urb_setup();
6553 fixup_3src_null_dest();
6554 allocate_registers(8, true);
6560 fs_visitor::run_tcs_single_patch()
6562 assert(stage == MESA_SHADER_TESS_CTRL);
6564 struct brw_tcs_prog_data *tcs_prog_data = brw_tcs_prog_data(prog_data);
6566 /* r1-r4 contain the ICP handles. */
6567 payload.num_regs = 5;
6569 if (shader_time_index >= 0)
6570 emit_shader_time_begin();
6572 /* Initialize gl_InvocationID */
6573 fs_reg channels_uw = bld.vgrf(BRW_REGISTER_TYPE_UW);
6574 fs_reg channels_ud = bld.vgrf(BRW_REGISTER_TYPE_UD);
6575 bld.MOV(channels_uw, fs_reg(brw_imm_uv(0x76543210)));
6576 bld.MOV(channels_ud, channels_uw);
6578 if (tcs_prog_data->instances == 1) {
6579 invocation_id = channels_ud;
6581 invocation_id = bld.vgrf(BRW_REGISTER_TYPE_UD);
6583 /* Get instance number from g0.2 bits 23:17, and multiply it by 8. */
6584 fs_reg t = bld.vgrf(BRW_REGISTER_TYPE_UD);
6585 fs_reg instance_times_8 = bld.vgrf(BRW_REGISTER_TYPE_UD);
6586 bld.AND(t, fs_reg(retype(brw_vec1_grf(0, 2), BRW_REGISTER_TYPE_UD)),
6587 brw_imm_ud(INTEL_MASK(23, 17)));
6588 bld.SHR(instance_times_8, t, brw_imm_ud(17 - 3));
6590 bld.ADD(invocation_id, instance_times_8, channels_ud);
6593 /* Fix the disptach mask */
6594 if (nir->info.tess.tcs_vertices_out % 8) {
6595 bld.CMP(bld.null_reg_ud(), invocation_id,
6596 brw_imm_ud(nir->info.tess.tcs_vertices_out), BRW_CONDITIONAL_L);
6597 bld.IF(BRW_PREDICATE_NORMAL);
6602 if (nir->info.tess.tcs_vertices_out % 8) {
6603 bld.emit(BRW_OPCODE_ENDIF);
6606 /* Emit EOT write; set TR DS Cache bit */
6608 fs_reg(retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_UD)),
6609 fs_reg(brw_imm_ud(WRITEMASK_X << 16)),
6610 fs_reg(brw_imm_ud(0)),
6612 fs_reg payload = bld.vgrf(BRW_REGISTER_TYPE_UD, 3);
6613 bld.LOAD_PAYLOAD(payload, srcs, 3, 2);
6615 fs_inst *inst = bld.emit(SHADER_OPCODE_URB_WRITE_SIMD8_MASKED,
6616 bld.null_reg_ud(), payload);
6620 if (shader_time_index >= 0)
6621 emit_shader_time_end();
6630 assign_curb_setup();
6631 assign_tcs_single_patch_urb_setup();
6633 fixup_3src_null_dest();
6634 allocate_registers(8, true);
6640 fs_visitor::run_tes()
6642 assert(stage == MESA_SHADER_TESS_EVAL);
6644 /* R0: thread header, R1-3: gl_TessCoord.xyz, R4: URB handles */
6645 payload.num_regs = 5;
6647 if (shader_time_index >= 0)
6648 emit_shader_time_begin();
6657 if (shader_time_index >= 0)
6658 emit_shader_time_end();
6664 assign_curb_setup();
6665 assign_tes_urb_setup();
6667 fixup_3src_null_dest();
6668 allocate_registers(8, true);
6674 fs_visitor::run_gs()
6676 assert(stage == MESA_SHADER_GEOMETRY);
6680 this->final_gs_vertex_count = vgrf(glsl_type::uint_type);
6682 if (gs_compile->control_data_header_size_bits > 0) {
6683 /* Create a VGRF to store accumulated control data bits. */
6684 this->control_data_bits = vgrf(glsl_type::uint_type);
6686 /* If we're outputting more than 32 control data bits, then EmitVertex()
6687 * will set control_data_bits to 0 after emitting the first vertex.
6688 * Otherwise, we need to initialize it to 0 here.
6690 if (gs_compile->control_data_header_size_bits <= 32) {
6691 const fs_builder abld = bld.annotate("initialize control data bits");
6692 abld.MOV(this->control_data_bits, brw_imm_ud(0u));
6696 if (shader_time_index >= 0)
6697 emit_shader_time_begin();
6701 emit_gs_thread_end();
6703 if (shader_time_index >= 0)
6704 emit_shader_time_end();
6713 assign_curb_setup();
6714 assign_gs_urb_setup();
6716 fixup_3src_null_dest();
6717 allocate_registers(8, true);
6722 /* From the SKL PRM, Volume 16, Workarounds:
6724 * 0877 3D Pixel Shader Hang possible when pixel shader dispatched with
6725 * only header phases (R0-R2)
6727 * WA: Enable a non-header phase (e.g. push constant) when dispatch would
6728 * have been header only.
6730 * Instead of enabling push constants one can alternatively enable one of the
6731 * inputs. Here one simply chooses "layer" which shouldn't impose much
6735 gen9_ps_header_only_workaround(struct brw_wm_prog_data *wm_prog_data)
6737 if (wm_prog_data->num_varying_inputs)
6740 if (wm_prog_data->base.curb_read_length)
6743 wm_prog_data->urb_setup[VARYING_SLOT_LAYER] = 0;
6744 wm_prog_data->num_varying_inputs = 1;
6748 fs_visitor::run_fs(bool allow_spilling, bool do_rep_send)
6750 struct brw_wm_prog_data *wm_prog_data = brw_wm_prog_data(this->prog_data);
6751 brw_wm_prog_key *wm_key = (brw_wm_prog_key *) this->key;
6753 assert(stage == MESA_SHADER_FRAGMENT);
6755 if (devinfo->gen >= 6)
6756 setup_fs_payload_gen6();
6758 setup_fs_payload_gen4();
6762 } else if (do_rep_send) {
6763 assert(dispatch_width == 16);
6764 emit_repclear_shader();
6766 if (shader_time_index >= 0)
6767 emit_shader_time_begin();
6769 calculate_urb_setup();
6770 if (nir->info.inputs_read > 0 ||
6771 (nir->info.outputs_read > 0 && !wm_key->coherent_fb_fetch)) {
6772 if (devinfo->gen < 6)
6773 emit_interpolation_setup_gen4();
6775 emit_interpolation_setup_gen6();
6778 /* We handle discards by keeping track of the still-live pixels in f0.1.
6779 * Initialize it with the dispatched pixels.
6781 if (wm_prog_data->uses_kill) {
6782 fs_inst *discard_init = bld.emit(FS_OPCODE_MOV_DISPATCH_TO_FLAGS);
6783 discard_init->flag_subreg = 1;
6786 /* Generate FS IR for main(). (the visitor only descends into
6787 * functions called "main").
6794 if (wm_prog_data->uses_kill)
6795 bld.emit(FS_OPCODE_PLACEHOLDER_HALT);
6797 if (wm_key->alpha_test_func)
6802 if (shader_time_index >= 0)
6803 emit_shader_time_end();
6809 assign_curb_setup();
6811 if (devinfo->gen >= 9)
6812 gen9_ps_header_only_workaround(wm_prog_data);
6816 fixup_3src_null_dest();
6817 allocate_registers(8, allow_spilling);
6827 fs_visitor::run_cs(unsigned min_dispatch_width)
6829 assert(stage == MESA_SHADER_COMPUTE);
6830 assert(dispatch_width >= min_dispatch_width);
6834 if (shader_time_index >= 0)
6835 emit_shader_time_begin();
6837 if (devinfo->is_haswell && prog_data->total_shared > 0) {
6838 /* Move SLM index from g0.0[27:24] to sr0.1[11:8] */
6839 const fs_builder abld = bld.exec_all().group(1, 0);
6840 abld.MOV(retype(brw_sr0_reg(1), BRW_REGISTER_TYPE_UW),
6841 suboffset(retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_UW), 1));
6849 emit_cs_terminate();
6851 if (shader_time_index >= 0)
6852 emit_shader_time_end();
6858 assign_curb_setup();
6860 fixup_3src_null_dest();
6861 allocate_registers(min_dispatch_width, true);
6870 * Return a bitfield where bit n is set if barycentric interpolation mode n
6871 * (see enum brw_barycentric_mode) is needed by the fragment shader.
6873 * We examine the load_barycentric intrinsics rather than looking at input
6874 * variables so that we catch interpolateAtCentroid() messages too, which
6875 * also need the BRW_BARYCENTRIC_[NON]PERSPECTIVE_CENTROID mode set up.
6878 brw_compute_barycentric_interp_modes(const struct gen_device_info *devinfo,
6879 const nir_shader *shader)
6881 unsigned barycentric_interp_modes = 0;
6883 nir_foreach_function(f, shader) {
6887 nir_foreach_block(block, f->impl) {
6888 nir_foreach_instr(instr, block) {
6889 if (instr->type != nir_instr_type_intrinsic)
6892 nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
6893 if (intrin->intrinsic != nir_intrinsic_load_interpolated_input)
6896 /* Ignore WPOS; it doesn't require interpolation. */
6897 if (nir_intrinsic_base(intrin) == VARYING_SLOT_POS)
6900 intrin = nir_instr_as_intrinsic(intrin->src[0].ssa->parent_instr);
6901 enum glsl_interp_mode interp = (enum glsl_interp_mode)
6902 nir_intrinsic_interp_mode(intrin);
6903 nir_intrinsic_op bary_op = intrin->intrinsic;
6904 enum brw_barycentric_mode bary =
6905 brw_barycentric_mode(interp, bary_op);
6907 barycentric_interp_modes |= 1 << bary;
6909 if (devinfo->needs_unlit_centroid_workaround &&
6910 bary_op == nir_intrinsic_load_barycentric_centroid)
6911 barycentric_interp_modes |= 1 << centroid_to_pixel(bary);
6916 return barycentric_interp_modes;
6920 brw_compute_flat_inputs(struct brw_wm_prog_data *prog_data,
6921 const nir_shader *shader)
6923 prog_data->flat_inputs = 0;
6925 nir_foreach_variable(var, &shader->inputs) {
6926 int input_index = prog_data->urb_setup[var->data.location];
6928 if (input_index < 0)
6932 if (var->data.interpolation == INTERP_MODE_FLAT)
6933 prog_data->flat_inputs |= (1 << input_index);
6938 computed_depth_mode(const nir_shader *shader)
6940 if (shader->info.outputs_written & BITFIELD64_BIT(FRAG_RESULT_DEPTH)) {
6941 switch (shader->info.fs.depth_layout) {
6942 case FRAG_DEPTH_LAYOUT_NONE:
6943 case FRAG_DEPTH_LAYOUT_ANY:
6944 return BRW_PSCDEPTH_ON;
6945 case FRAG_DEPTH_LAYOUT_GREATER:
6946 return BRW_PSCDEPTH_ON_GE;
6947 case FRAG_DEPTH_LAYOUT_LESS:
6948 return BRW_PSCDEPTH_ON_LE;
6949 case FRAG_DEPTH_LAYOUT_UNCHANGED:
6950 return BRW_PSCDEPTH_OFF;
6953 return BRW_PSCDEPTH_OFF;
6957 * Move load_interpolated_input with simple (payload-based) barycentric modes
6958 * to the top of the program so we don't emit multiple PLNs for the same input.
6960 * This works around CSE not being able to handle non-dominating cases
6966 * interpolate the same exact input
6969 * This should be replaced by global value numbering someday.
6972 move_interpolation_to_top(nir_shader *nir)
6974 bool progress = false;
6976 nir_foreach_function(f, nir) {
6980 nir_block *top = nir_start_block(f->impl);
6981 exec_node *cursor_node = NULL;
6983 nir_foreach_block(block, f->impl) {
6987 nir_foreach_instr_safe(instr, block) {
6988 if (instr->type != nir_instr_type_intrinsic)
6991 nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
6992 if (intrin->intrinsic != nir_intrinsic_load_interpolated_input)
6994 nir_intrinsic_instr *bary_intrinsic =
6995 nir_instr_as_intrinsic(intrin->src[0].ssa->parent_instr);
6996 nir_intrinsic_op op = bary_intrinsic->intrinsic;
6998 /* Leave interpolateAtSample/Offset() where they are. */
6999 if (op == nir_intrinsic_load_barycentric_at_sample ||
7000 op == nir_intrinsic_load_barycentric_at_offset)
7003 nir_instr *move[3] = {
7004 &bary_intrinsic->instr,
7005 intrin->src[1].ssa->parent_instr,
7009 for (unsigned i = 0; i < ARRAY_SIZE(move); i++) {
7010 if (move[i]->block != top) {
7011 move[i]->block = top;
7012 exec_node_remove(&move[i]->node);
7014 exec_node_insert_after(cursor_node, &move[i]->node);
7016 exec_list_push_head(&top->instr_list, &move[i]->node);
7018 cursor_node = &move[i]->node;
7024 nir_metadata_preserve(f->impl, (nir_metadata)
7025 ((unsigned) nir_metadata_block_index |
7026 (unsigned) nir_metadata_dominance));
7033 * Demote per-sample barycentric intrinsics to centroid.
7035 * Useful when rendering to a non-multisampled buffer.
7038 demote_sample_qualifiers(nir_shader *nir)
7040 bool progress = true;
7042 nir_foreach_function(f, nir) {
7047 nir_builder_init(&b, f->impl);
7049 nir_foreach_block(block, f->impl) {
7050 nir_foreach_instr_safe(instr, block) {
7051 if (instr->type != nir_instr_type_intrinsic)
7054 nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
7055 if (intrin->intrinsic != nir_intrinsic_load_barycentric_sample &&
7056 intrin->intrinsic != nir_intrinsic_load_barycentric_at_sample)
7059 b.cursor = nir_before_instr(instr);
7060 nir_ssa_def *centroid =
7061 nir_load_barycentric(&b, nir_intrinsic_load_barycentric_centroid,
7062 nir_intrinsic_interp_mode(intrin));
7063 nir_ssa_def_rewrite_uses(&intrin->dest.ssa,
7064 nir_src_for_ssa(centroid));
7065 nir_instr_remove(instr);
7070 nir_metadata_preserve(f->impl, (nir_metadata)
7071 ((unsigned) nir_metadata_block_index |
7072 (unsigned) nir_metadata_dominance));
7079 * Pre-gen6, the register file of the EUs was shared between threads,
7080 * and each thread used some subset allocated on a 16-register block
7081 * granularity. The unit states wanted these block counts.
7084 brw_register_blocks(int reg_count)
7086 return ALIGN(reg_count, 16) / 16 - 1;
7090 brw_compile_fs(const struct brw_compiler *compiler, void *log_data,
7092 const struct brw_wm_prog_key *key,
7093 struct brw_wm_prog_data *prog_data,
7094 const nir_shader *src_shader,
7095 struct gl_program *prog,
7096 int shader_time_index8, int shader_time_index16,
7097 int shader_time_index32, bool allow_spilling,
7098 bool use_rep_send, struct brw_vue_map *vue_map,
7101 const struct gen_device_info *devinfo = compiler->devinfo;
7103 nir_shader *shader = nir_shader_clone(mem_ctx, src_shader);
7104 shader = brw_nir_apply_sampler_key(shader, compiler, &key->tex, true);
7105 brw_nir_lower_fs_inputs(shader, devinfo, key);
7106 brw_nir_lower_fs_outputs(shader);
7108 if (devinfo->gen < 6) {
7109 brw_setup_vue_interpolation(vue_map, shader, prog_data, devinfo);
7112 if (!key->multisample_fbo)
7113 NIR_PASS_V(shader, demote_sample_qualifiers);
7114 NIR_PASS_V(shader, move_interpolation_to_top);
7115 shader = brw_postprocess_nir(shader, compiler, true);
7117 /* key->alpha_test_func means simulating alpha testing via discards,
7118 * so the shader definitely kills pixels.
7120 prog_data->uses_kill = shader->info.fs.uses_discard ||
7121 key->alpha_test_func;
7122 prog_data->uses_omask = key->multisample_fbo &&
7123 shader->info.outputs_written & BITFIELD64_BIT(FRAG_RESULT_SAMPLE_MASK);
7124 prog_data->computed_depth_mode = computed_depth_mode(shader);
7125 prog_data->computed_stencil =
7126 shader->info.outputs_written & BITFIELD64_BIT(FRAG_RESULT_STENCIL);
7128 prog_data->persample_dispatch =
7129 key->multisample_fbo &&
7130 (key->persample_interp ||
7131 (shader->info.system_values_read & (SYSTEM_BIT_SAMPLE_ID |
7132 SYSTEM_BIT_SAMPLE_POS)) ||
7133 shader->info.fs.uses_sample_qualifier ||
7134 shader->info.outputs_read);
7136 prog_data->has_render_target_reads = shader->info.outputs_read != 0ull;
7138 prog_data->early_fragment_tests = shader->info.fs.early_fragment_tests;
7139 prog_data->post_depth_coverage = shader->info.fs.post_depth_coverage;
7140 prog_data->inner_coverage = shader->info.fs.inner_coverage;
7142 prog_data->barycentric_interp_modes =
7143 brw_compute_barycentric_interp_modes(compiler->devinfo, shader);
7145 cfg_t *simd8_cfg = NULL, *simd16_cfg = NULL;
7147 fs_visitor v8(compiler, log_data, mem_ctx, key,
7148 &prog_data->base, prog, shader, 8,
7149 shader_time_index8);
7150 if (!v8.run_fs(allow_spilling, false /* do_rep_send */)) {
7152 *error_str = ralloc_strdup(mem_ctx, v8.fail_msg);
7155 } else if (likely(!(INTEL_DEBUG & DEBUG_NO8))) {
7157 prog_data->base.dispatch_grf_start_reg = v8.payload.num_regs;
7158 prog_data->reg_blocks_8 = brw_register_blocks(v8.grf_used);
7161 if (v8.max_dispatch_width >= 16 &&
7162 likely(!(INTEL_DEBUG & DEBUG_NO16) || use_rep_send)) {
7163 /* Try a SIMD16 compile */
7164 fs_visitor v16(compiler, log_data, mem_ctx, key,
7165 &prog_data->base, prog, shader, 16,
7166 shader_time_index16);
7167 v16.import_uniforms(&v8);
7168 if (!v16.run_fs(allow_spilling, use_rep_send)) {
7169 compiler->shader_perf_log(log_data,
7170 "SIMD16 shader failed to compile: %s",
7173 simd16_cfg = v16.cfg;
7174 prog_data->dispatch_grf_start_reg_16 = v16.payload.num_regs;
7175 prog_data->reg_blocks_16 = brw_register_blocks(v16.grf_used);
7179 /* When the caller requests a repclear shader, they want SIMD16-only */
7183 /* Prior to Iron Lake, the PS had a single shader offset with a jump table
7184 * at the top to select the shader. We've never implemented that.
7185 * Instead, we just give them exactly one shader and we pick the widest one
7188 if (compiler->devinfo->gen < 5 && simd16_cfg)
7191 if (compiler->devinfo->gen <= 5 && !simd8_cfg) {
7192 /* Iron lake and earlier only have one Dispatch GRF start field. Make
7193 * the data available in the base prog data struct for convenience.
7196 prog_data->base.dispatch_grf_start_reg =
7197 prog_data->dispatch_grf_start_reg_16;
7201 if (prog_data->persample_dispatch) {
7202 /* Starting with SandyBridge (where we first get MSAA), the different
7203 * pixel dispatch combinations are grouped into classifications A
7204 * through F (SNB PRM Vol. 2 Part 1 Section 7.7.1). On all hardware
7205 * generations, the only configurations supporting persample dispatch
7206 * are are this in which only one dispatch width is enabled.
7208 * If computed depth is enabled, SNB only allows SIMD8 while IVB+
7209 * allow SIMD8 or SIMD16 so we choose SIMD16 if available.
7211 if (compiler->devinfo->gen == 6 &&
7212 prog_data->computed_depth_mode != BRW_PSCDEPTH_OFF) {
7214 } else if (simd16_cfg) {
7219 /* We have to compute the flat inputs after the visitor is finished running
7220 * because it relies on prog_data->urb_setup which is computed in
7221 * fs_visitor::calculate_urb_setup().
7223 brw_compute_flat_inputs(prog_data, shader);
7225 fs_generator g(compiler, log_data, mem_ctx, &prog_data->base,
7226 v8.promoted_constants, v8.runtime_check_aads_emit,
7227 MESA_SHADER_FRAGMENT);
7229 if (unlikely(INTEL_DEBUG & DEBUG_WM)) {
7230 g.enable_debug(ralloc_asprintf(mem_ctx, "%s fragment shader %s",
7231 shader->info.label ?
7232 shader->info.label : "unnamed",
7233 shader->info.name));
7237 prog_data->dispatch_8 = true;
7238 g.generate_code(simd8_cfg, 8);
7242 prog_data->dispatch_16 = true;
7243 prog_data->prog_offset_16 = g.generate_code(simd16_cfg, 16);
7246 return g.get_assembly();
7250 fs_visitor::emit_cs_work_group_id_setup()
7252 assert(stage == MESA_SHADER_COMPUTE);
7254 fs_reg *reg = new(this->mem_ctx) fs_reg(vgrf(glsl_type::uvec3_type));
7256 struct brw_reg r0_1(retype(brw_vec1_grf(0, 1), BRW_REGISTER_TYPE_UD));
7257 struct brw_reg r0_6(retype(brw_vec1_grf(0, 6), BRW_REGISTER_TYPE_UD));
7258 struct brw_reg r0_7(retype(brw_vec1_grf(0, 7), BRW_REGISTER_TYPE_UD));
7260 bld.MOV(*reg, r0_1);
7261 bld.MOV(offset(*reg, bld, 1), r0_6);
7262 bld.MOV(offset(*reg, bld, 2), r0_7);
7268 fill_push_const_block_info(struct brw_push_const_block *block, unsigned dwords)
7270 block->dwords = dwords;
7271 block->regs = DIV_ROUND_UP(dwords, 8);
7272 block->size = block->regs * 32;
7276 cs_fill_push_const_info(const struct gen_device_info *devinfo,
7277 struct brw_cs_prog_data *cs_prog_data)
7279 const struct brw_stage_prog_data *prog_data = &cs_prog_data->base;
7280 int subgroup_id_index = get_subgroup_id_param_index(prog_data);
7281 bool cross_thread_supported = devinfo->gen > 7 || devinfo->is_haswell;
7283 /* The thread ID should be stored in the last param dword */
7284 assert(subgroup_id_index == -1 ||
7285 subgroup_id_index == (int)prog_data->nr_params - 1);
7287 unsigned cross_thread_dwords, per_thread_dwords;
7288 if (!cross_thread_supported) {
7289 cross_thread_dwords = 0u;
7290 per_thread_dwords = prog_data->nr_params;
7291 } else if (subgroup_id_index >= 0) {
7292 /* Fill all but the last register with cross-thread payload */
7293 cross_thread_dwords = 8 * (subgroup_id_index / 8);
7294 per_thread_dwords = prog_data->nr_params - cross_thread_dwords;
7295 assert(per_thread_dwords > 0 && per_thread_dwords <= 8);
7297 /* Fill all data using cross-thread payload */
7298 cross_thread_dwords = prog_data->nr_params;
7299 per_thread_dwords = 0u;
7302 fill_push_const_block_info(&cs_prog_data->push.cross_thread, cross_thread_dwords);
7303 fill_push_const_block_info(&cs_prog_data->push.per_thread, per_thread_dwords);
7305 unsigned total_dwords =
7306 (cs_prog_data->push.per_thread.size * cs_prog_data->threads +
7307 cs_prog_data->push.cross_thread.size) / 4;
7308 fill_push_const_block_info(&cs_prog_data->push.total, total_dwords);
7310 assert(cs_prog_data->push.cross_thread.dwords % 8 == 0 ||
7311 cs_prog_data->push.per_thread.size == 0);
7312 assert(cs_prog_data->push.cross_thread.dwords +
7313 cs_prog_data->push.per_thread.dwords ==
7314 prog_data->nr_params);
7318 cs_set_simd_size(struct brw_cs_prog_data *cs_prog_data, unsigned size)
7320 cs_prog_data->simd_size = size;
7321 unsigned group_size = cs_prog_data->local_size[0] *
7322 cs_prog_data->local_size[1] * cs_prog_data->local_size[2];
7323 cs_prog_data->threads = (group_size + size - 1) / size;
7327 compile_cs_to_nir(const struct brw_compiler *compiler,
7329 const struct brw_cs_prog_key *key,
7330 const nir_shader *src_shader,
7331 unsigned dispatch_width)
7333 nir_shader *shader = nir_shader_clone(mem_ctx, src_shader);
7334 shader = brw_nir_apply_sampler_key(shader, compiler, &key->tex, true);
7335 brw_nir_lower_cs_intrinsics(shader, dispatch_width);
7336 return brw_postprocess_nir(shader, compiler, true);
7340 brw_compile_cs(const struct brw_compiler *compiler, void *log_data,
7342 const struct brw_cs_prog_key *key,
7343 struct brw_cs_prog_data *prog_data,
7344 const nir_shader *src_shader,
7345 int shader_time_index,
7348 prog_data->local_size[0] = src_shader->info.cs.local_size[0];
7349 prog_data->local_size[1] = src_shader->info.cs.local_size[1];
7350 prog_data->local_size[2] = src_shader->info.cs.local_size[2];
7351 unsigned local_workgroup_size =
7352 src_shader->info.cs.local_size[0] * src_shader->info.cs.local_size[1] *
7353 src_shader->info.cs.local_size[2];
7355 unsigned min_dispatch_width =
7356 DIV_ROUND_UP(local_workgroup_size, compiler->devinfo->max_cs_threads);
7357 min_dispatch_width = MAX2(8, min_dispatch_width);
7358 min_dispatch_width = util_next_power_of_two(min_dispatch_width);
7359 assert(min_dispatch_width <= 32);
7361 fs_visitor *v8 = NULL, *v16 = NULL, *v32 = NULL;
7363 const char *fail_msg = NULL;
7364 unsigned promoted_constants = 0;
7366 /* Now the main event: Visit the shader IR and generate our CS IR for it.
7368 if (min_dispatch_width <= 8) {
7369 nir_shader *nir8 = compile_cs_to_nir(compiler, mem_ctx, key,
7371 v8 = new fs_visitor(compiler, log_data, mem_ctx, key, &prog_data->base,
7372 NULL, /* Never used in core profile */
7373 nir8, 8, shader_time_index);
7374 if (!v8->run_cs(min_dispatch_width)) {
7375 fail_msg = v8->fail_msg;
7377 /* We should always be able to do SIMD32 for compute shaders */
7378 assert(v8->max_dispatch_width >= 32);
7381 cs_set_simd_size(prog_data, 8);
7382 cs_fill_push_const_info(compiler->devinfo, prog_data);
7383 promoted_constants = v8->promoted_constants;
7387 if (likely(!(INTEL_DEBUG & DEBUG_NO16)) &&
7388 !fail_msg && min_dispatch_width <= 16) {
7389 /* Try a SIMD16 compile */
7390 nir_shader *nir16 = compile_cs_to_nir(compiler, mem_ctx, key,
7392 v16 = new fs_visitor(compiler, log_data, mem_ctx, key, &prog_data->base,
7393 NULL, /* Never used in core profile */
7394 nir16, 16, shader_time_index);
7396 v16->import_uniforms(v8);
7398 if (!v16->run_cs(min_dispatch_width)) {
7399 compiler->shader_perf_log(log_data,
7400 "SIMD16 shader failed to compile: %s",
7404 "Couldn't generate SIMD16 program and not "
7405 "enough threads for SIMD8";
7408 /* We should always be able to do SIMD32 for compute shaders */
7409 assert(v16->max_dispatch_width >= 32);
7412 cs_set_simd_size(prog_data, 16);
7413 cs_fill_push_const_info(compiler->devinfo, prog_data);
7414 promoted_constants = v16->promoted_constants;
7418 /* We should always be able to do SIMD32 for compute shaders */
7419 assert(!v16 || v16->max_dispatch_width >= 32);
7421 if (!fail_msg && (min_dispatch_width > 16 || (INTEL_DEBUG & DEBUG_DO32))) {
7422 /* Try a SIMD32 compile */
7423 nir_shader *nir32 = compile_cs_to_nir(compiler, mem_ctx, key,
7425 v32 = new fs_visitor(compiler, log_data, mem_ctx, key, &prog_data->base,
7426 NULL, /* Never used in core profile */
7427 nir32, 32, shader_time_index);
7429 v32->import_uniforms(v8);
7431 v32->import_uniforms(v16);
7433 if (!v32->run_cs(min_dispatch_width)) {
7434 compiler->shader_perf_log(log_data,
7435 "SIMD32 shader failed to compile: %s",
7439 "Couldn't generate SIMD32 program and not "
7440 "enough threads for SIMD16";
7444 cs_set_simd_size(prog_data, 32);
7445 cs_fill_push_const_info(compiler->devinfo, prog_data);
7446 promoted_constants = v32->promoted_constants;
7450 const unsigned *ret = NULL;
7451 if (unlikely(cfg == NULL)) {
7454 *error_str = ralloc_strdup(mem_ctx, fail_msg);
7456 fs_generator g(compiler, log_data, mem_ctx, &prog_data->base,
7457 promoted_constants, false, MESA_SHADER_COMPUTE);
7458 if (INTEL_DEBUG & DEBUG_CS) {
7459 char *name = ralloc_asprintf(mem_ctx, "%s compute shader %s",
7460 src_shader->info.label ?
7461 src_shader->info.label : "unnamed",
7462 src_shader->info.name);
7463 g.enable_debug(name);
7466 g.generate_code(cfg, prog_data->simd_size);
7468 ret = g.get_assembly();
7479 * Test the dispatch mask packing assumptions of
7480 * brw_stage_has_packed_dispatch(). Call this from e.g. the top of
7481 * fs_visitor::emit_nir_code() to cause a GPU hang if any shader invocation is
7482 * executed with an unexpected dispatch mask.
7485 brw_fs_test_dispatch_packing(const fs_builder &bld)
7487 const gl_shader_stage stage = bld.shader->stage;
7489 if (brw_stage_has_packed_dispatch(bld.shader->devinfo, stage,
7490 bld.shader->stage_prog_data)) {
7491 const fs_builder ubld = bld.exec_all().group(1, 0);
7492 const fs_reg tmp = component(bld.vgrf(BRW_REGISTER_TYPE_UD), 0);
7493 const fs_reg mask = (stage == MESA_SHADER_FRAGMENT ? brw_vmask_reg() :
7496 ubld.ADD(tmp, mask, brw_imm_ud(1));
7497 ubld.AND(tmp, mask, tmp);
7499 /* This will loop forever if the dispatch mask doesn't have the expected
7500 * form '2^n-1', in which case tmp will be non-zero.
7502 bld.emit(BRW_OPCODE_DO);
7503 bld.CMP(bld.null_reg_ud(), tmp, brw_imm_ud(0), BRW_CONDITIONAL_NZ);
7504 set_predicate(BRW_PREDICATE_NORMAL, bld.emit(BRW_OPCODE_WHILE));