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