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