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