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