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