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