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