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