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