i965/fs: Merge CMP and SEL into CSEL on Gen8+
[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::opt_peephole_csel()
2848 {
2849 if (devinfo->gen < 8)
2850 return false;
2851
2852 bool progress = false;
2853
2854 foreach_block_reverse(block, cfg) {
2855 int ip = block->end_ip + 1;
2856
2857 foreach_inst_in_block_reverse_safe(fs_inst, inst, block) {
2858 ip--;
2859
2860 if (inst->opcode != BRW_OPCODE_SEL ||
2861 inst->predicate != BRW_PREDICATE_NORMAL ||
2862 (inst->dst.type != BRW_REGISTER_TYPE_F &&
2863 inst->dst.type != BRW_REGISTER_TYPE_D &&
2864 inst->dst.type != BRW_REGISTER_TYPE_UD))
2865 continue;
2866
2867 /* Because it is a 3-src instruction, CSEL cannot have an immediate
2868 * value as a source, but we can sometimes handle zero.
2869 */
2870 if ((inst->src[0].file != VGRF && inst->src[0].file != ATTR &&
2871 inst->src[0].file != UNIFORM) ||
2872 (inst->src[1].file != VGRF && inst->src[1].file != ATTR &&
2873 inst->src[1].file != UNIFORM && !inst->src[1].is_zero()))
2874 continue;
2875
2876 foreach_inst_in_block_reverse_starting_from(fs_inst, scan_inst, inst) {
2877 if (!scan_inst->flags_written())
2878 continue;
2879
2880 if ((scan_inst->opcode != BRW_OPCODE_CMP &&
2881 scan_inst->opcode != BRW_OPCODE_MOV) ||
2882 scan_inst->predicate != BRW_PREDICATE_NONE ||
2883 (scan_inst->src[0].file != VGRF &&
2884 scan_inst->src[0].file != ATTR &&
2885 scan_inst->src[0].file != UNIFORM) ||
2886 scan_inst->src[0].type != BRW_REGISTER_TYPE_F)
2887 break;
2888
2889 if (scan_inst->opcode == BRW_OPCODE_CMP && !scan_inst->src[1].is_zero())
2890 break;
2891
2892 const brw::fs_builder ibld(this, block, inst);
2893
2894 const enum brw_conditional_mod cond =
2895 inst->predicate_inverse
2896 ? brw_negate_cmod(scan_inst->conditional_mod)
2897 : scan_inst->conditional_mod;
2898
2899 fs_inst *csel_inst = NULL;
2900
2901 if (inst->src[1].file != IMM) {
2902 csel_inst = ibld.CSEL(inst->dst,
2903 inst->src[0],
2904 inst->src[1],
2905 scan_inst->src[0],
2906 cond);
2907 } else if (cond == BRW_CONDITIONAL_NZ) {
2908 /* Consider the sequence
2909 *
2910 * cmp.nz.f0 null<1>F g3<8,8,1>F 0F
2911 * (+f0) sel g124<1>UD g2<8,8,1>UD 0x00000000UD
2912 *
2913 * The sel will pick the immediate value 0 if r0 is ±0.0.
2914 * Therefore, this sequence is equivalent:
2915 *
2916 * cmp.nz.f0 null<1>F g3<8,8,1>F 0F
2917 * (+f0) sel g124<1>F g2<8,8,1>F (abs)g3<8,8,1>F
2918 *
2919 * The abs is ensures that the result is 0UD when g3 is -0.0F.
2920 * By normal cmp-sel merging, this is also equivalent:
2921 *
2922 * csel.nz g124<1>F g2<4,4,1>F (abs)g3<4,4,1>F g3<4,4,1>F
2923 */
2924 csel_inst = ibld.CSEL(inst->dst,
2925 inst->src[0],
2926 scan_inst->src[0],
2927 scan_inst->src[0],
2928 cond);
2929
2930 csel_inst->src[1].abs = true;
2931 }
2932
2933 if (csel_inst != NULL) {
2934 progress = true;
2935 inst->remove(block);
2936 }
2937
2938 break;
2939 }
2940 }
2941 }
2942
2943 return progress;
2944 }
2945
2946 bool
2947 fs_visitor::compute_to_mrf()
2948 {
2949 bool progress = false;
2950 int next_ip = 0;
2951
2952 /* No MRFs on Gen >= 7. */
2953 if (devinfo->gen >= 7)
2954 return false;
2955
2956 calculate_live_intervals();
2957
2958 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
2959 int ip = next_ip;
2960 next_ip++;
2961
2962 if (inst->opcode != BRW_OPCODE_MOV ||
2963 inst->is_partial_write() ||
2964 inst->dst.file != MRF || inst->src[0].file != VGRF ||
2965 inst->dst.type != inst->src[0].type ||
2966 inst->src[0].abs || inst->src[0].negate ||
2967 !inst->src[0].is_contiguous() ||
2968 inst->src[0].offset % REG_SIZE != 0)
2969 continue;
2970
2971 /* Can't compute-to-MRF this GRF if someone else was going to
2972 * read it later.
2973 */
2974 if (this->virtual_grf_end[inst->src[0].nr] > ip)
2975 continue;
2976
2977 /* Found a move of a GRF to a MRF. Let's see if we can go rewrite the
2978 * things that computed the value of all GRFs of the source region. The
2979 * regs_left bitset keeps track of the registers we haven't yet found a
2980 * generating instruction for.
2981 */
2982 unsigned regs_left = (1 << regs_read(inst, 0)) - 1;
2983
2984 foreach_inst_in_block_reverse_starting_from(fs_inst, scan_inst, inst) {
2985 if (regions_overlap(scan_inst->dst, scan_inst->size_written,
2986 inst->src[0], inst->size_read(0))) {
2987 /* Found the last thing to write our reg we want to turn
2988 * into a compute-to-MRF.
2989 */
2990
2991 /* If this one instruction didn't populate all the
2992 * channels, bail. We might be able to rewrite everything
2993 * that writes that reg, but it would require smarter
2994 * tracking.
2995 */
2996 if (scan_inst->is_partial_write())
2997 break;
2998
2999 /* Handling things not fully contained in the source of the copy
3000 * would need us to understand coalescing out more than one MOV at
3001 * a time.
3002 */
3003 if (!region_contained_in(scan_inst->dst, scan_inst->size_written,
3004 inst->src[0], inst->size_read(0)))
3005 break;
3006
3007 /* SEND instructions can't have MRF as a destination. */
3008 if (scan_inst->mlen)
3009 break;
3010
3011 if (devinfo->gen == 6) {
3012 /* gen6 math instructions must have the destination be
3013 * GRF, so no compute-to-MRF for them.
3014 */
3015 if (scan_inst->is_math()) {
3016 break;
3017 }
3018 }
3019
3020 /* Clear the bits for any registers this instruction overwrites. */
3021 regs_left &= ~mask_relative_to(
3022 inst->src[0], scan_inst->dst, scan_inst->size_written);
3023 if (!regs_left)
3024 break;
3025 }
3026
3027 /* We don't handle control flow here. Most computation of
3028 * values that end up in MRFs are shortly before the MRF
3029 * write anyway.
3030 */
3031 if (block->start() == scan_inst)
3032 break;
3033
3034 /* You can't read from an MRF, so if someone else reads our
3035 * MRF's source GRF that we wanted to rewrite, that stops us.
3036 */
3037 bool interfered = false;
3038 for (int i = 0; i < scan_inst->sources; i++) {
3039 if (regions_overlap(scan_inst->src[i], scan_inst->size_read(i),
3040 inst->src[0], inst->size_read(0))) {
3041 interfered = true;
3042 }
3043 }
3044 if (interfered)
3045 break;
3046
3047 if (regions_overlap(scan_inst->dst, scan_inst->size_written,
3048 inst->dst, inst->size_written)) {
3049 /* If somebody else writes our MRF here, we can't
3050 * compute-to-MRF before that.
3051 */
3052 break;
3053 }
3054
3055 if (scan_inst->mlen > 0 && scan_inst->base_mrf != -1 &&
3056 regions_overlap(fs_reg(MRF, scan_inst->base_mrf), scan_inst->mlen * REG_SIZE,
3057 inst->dst, inst->size_written)) {
3058 /* Found a SEND instruction, which means that there are
3059 * live values in MRFs from base_mrf to base_mrf +
3060 * scan_inst->mlen - 1. Don't go pushing our MRF write up
3061 * above it.
3062 */
3063 break;
3064 }
3065 }
3066
3067 if (regs_left)
3068 continue;
3069
3070 /* Found all generating instructions of our MRF's source value, so it
3071 * should be safe to rewrite them to point to the MRF directly.
3072 */
3073 regs_left = (1 << regs_read(inst, 0)) - 1;
3074
3075 foreach_inst_in_block_reverse_starting_from(fs_inst, scan_inst, inst) {
3076 if (regions_overlap(scan_inst->dst, scan_inst->size_written,
3077 inst->src[0], inst->size_read(0))) {
3078 /* Clear the bits for any registers this instruction overwrites. */
3079 regs_left &= ~mask_relative_to(
3080 inst->src[0], scan_inst->dst, scan_inst->size_written);
3081
3082 const unsigned rel_offset = reg_offset(scan_inst->dst) -
3083 reg_offset(inst->src[0]);
3084
3085 if (inst->dst.nr & BRW_MRF_COMPR4) {
3086 /* Apply the same address transformation done by the hardware
3087 * for COMPR4 MRF writes.
3088 */
3089 assert(rel_offset < 2 * REG_SIZE);
3090 scan_inst->dst.nr = inst->dst.nr + rel_offset / REG_SIZE * 4;
3091
3092 /* Clear the COMPR4 bit if the generating instruction is not
3093 * compressed.
3094 */
3095 if (scan_inst->size_written < 2 * REG_SIZE)
3096 scan_inst->dst.nr &= ~BRW_MRF_COMPR4;
3097
3098 } else {
3099 /* Calculate the MRF number the result of this instruction is
3100 * ultimately written to.
3101 */
3102 scan_inst->dst.nr = inst->dst.nr + rel_offset / REG_SIZE;
3103 }
3104
3105 scan_inst->dst.file = MRF;
3106 scan_inst->dst.offset = inst->dst.offset + rel_offset % REG_SIZE;
3107 scan_inst->saturate |= inst->saturate;
3108 if (!regs_left)
3109 break;
3110 }
3111 }
3112
3113 assert(!regs_left);
3114 inst->remove(block);
3115 progress = true;
3116 }
3117
3118 if (progress)
3119 invalidate_live_intervals();
3120
3121 return progress;
3122 }
3123
3124 /**
3125 * Eliminate FIND_LIVE_CHANNEL instructions occurring outside any control
3126 * flow. We could probably do better here with some form of divergence
3127 * analysis.
3128 */
3129 bool
3130 fs_visitor::eliminate_find_live_channel()
3131 {
3132 bool progress = false;
3133 unsigned depth = 0;
3134
3135 if (!brw_stage_has_packed_dispatch(devinfo, stage, stage_prog_data)) {
3136 /* The optimization below assumes that channel zero is live on thread
3137 * dispatch, which may not be the case if the fixed function dispatches
3138 * threads sparsely.
3139 */
3140 return false;
3141 }
3142
3143 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
3144 switch (inst->opcode) {
3145 case BRW_OPCODE_IF:
3146 case BRW_OPCODE_DO:
3147 depth++;
3148 break;
3149
3150 case BRW_OPCODE_ENDIF:
3151 case BRW_OPCODE_WHILE:
3152 depth--;
3153 break;
3154
3155 case FS_OPCODE_DISCARD_JUMP:
3156 /* This can potentially make control flow non-uniform until the end
3157 * of the program.
3158 */
3159 return progress;
3160
3161 case SHADER_OPCODE_FIND_LIVE_CHANNEL:
3162 if (depth == 0) {
3163 inst->opcode = BRW_OPCODE_MOV;
3164 inst->src[0] = brw_imm_ud(0u);
3165 inst->sources = 1;
3166 inst->force_writemask_all = true;
3167 progress = true;
3168 }
3169 break;
3170
3171 default:
3172 break;
3173 }
3174 }
3175
3176 return progress;
3177 }
3178
3179 /**
3180 * Once we've generated code, try to convert normal FS_OPCODE_FB_WRITE
3181 * instructions to FS_OPCODE_REP_FB_WRITE.
3182 */
3183 void
3184 fs_visitor::emit_repclear_shader()
3185 {
3186 brw_wm_prog_key *key = (brw_wm_prog_key*) this->key;
3187 int base_mrf = 0;
3188 int color_mrf = base_mrf + 2;
3189 fs_inst *mov;
3190
3191 if (uniforms > 0) {
3192 mov = bld.exec_all().group(4, 0)
3193 .MOV(brw_message_reg(color_mrf),
3194 fs_reg(UNIFORM, 0, BRW_REGISTER_TYPE_F));
3195 } else {
3196 struct brw_reg reg =
3197 brw_reg(BRW_GENERAL_REGISTER_FILE, 2, 3, 0, 0, BRW_REGISTER_TYPE_F,
3198 BRW_VERTICAL_STRIDE_8, BRW_WIDTH_2, BRW_HORIZONTAL_STRIDE_4,
3199 BRW_SWIZZLE_XYZW, WRITEMASK_XYZW);
3200
3201 mov = bld.exec_all().group(4, 0)
3202 .MOV(vec4(brw_message_reg(color_mrf)), fs_reg(reg));
3203 }
3204
3205 fs_inst *write = NULL;
3206 if (key->nr_color_regions == 1) {
3207 write = bld.emit(FS_OPCODE_REP_FB_WRITE);
3208 write->saturate = key->clamp_fragment_color;
3209 write->base_mrf = color_mrf;
3210 write->target = 0;
3211 write->header_size = 0;
3212 write->mlen = 1;
3213 } else {
3214 assume(key->nr_color_regions > 0);
3215 for (int i = 0; i < key->nr_color_regions; ++i) {
3216 write = bld.emit(FS_OPCODE_REP_FB_WRITE);
3217 write->saturate = key->clamp_fragment_color;
3218 write->base_mrf = base_mrf;
3219 write->target = i;
3220 write->header_size = 2;
3221 write->mlen = 3;
3222 }
3223 }
3224 write->eot = true;
3225
3226 calculate_cfg();
3227
3228 assign_constant_locations();
3229 assign_curb_setup();
3230
3231 /* Now that we have the uniform assigned, go ahead and force it to a vec4. */
3232 if (uniforms > 0) {
3233 assert(mov->src[0].file == FIXED_GRF);
3234 mov->src[0] = brw_vec4_grf(mov->src[0].nr, 0);
3235 }
3236 }
3237
3238 /**
3239 * Walks through basic blocks, looking for repeated MRF writes and
3240 * removing the later ones.
3241 */
3242 bool
3243 fs_visitor::remove_duplicate_mrf_writes()
3244 {
3245 fs_inst *last_mrf_move[BRW_MAX_MRF(devinfo->gen)];
3246 bool progress = false;
3247
3248 /* Need to update the MRF tracking for compressed instructions. */
3249 if (dispatch_width >= 16)
3250 return false;
3251
3252 memset(last_mrf_move, 0, sizeof(last_mrf_move));
3253
3254 foreach_block_and_inst_safe (block, fs_inst, inst, cfg) {
3255 if (inst->is_control_flow()) {
3256 memset(last_mrf_move, 0, sizeof(last_mrf_move));
3257 }
3258
3259 if (inst->opcode == BRW_OPCODE_MOV &&
3260 inst->dst.file == MRF) {
3261 fs_inst *prev_inst = last_mrf_move[inst->dst.nr];
3262 if (prev_inst && inst->equals(prev_inst)) {
3263 inst->remove(block);
3264 progress = true;
3265 continue;
3266 }
3267 }
3268
3269 /* Clear out the last-write records for MRFs that were overwritten. */
3270 if (inst->dst.file == MRF) {
3271 last_mrf_move[inst->dst.nr] = NULL;
3272 }
3273
3274 if (inst->mlen > 0 && inst->base_mrf != -1) {
3275 /* Found a SEND instruction, which will include two or fewer
3276 * implied MRF writes. We could do better here.
3277 */
3278 for (int i = 0; i < implied_mrf_writes(inst); i++) {
3279 last_mrf_move[inst->base_mrf + i] = NULL;
3280 }
3281 }
3282
3283 /* Clear out any MRF move records whose sources got overwritten. */
3284 for (unsigned i = 0; i < ARRAY_SIZE(last_mrf_move); i++) {
3285 if (last_mrf_move[i] &&
3286 regions_overlap(inst->dst, inst->size_written,
3287 last_mrf_move[i]->src[0],
3288 last_mrf_move[i]->size_read(0))) {
3289 last_mrf_move[i] = NULL;
3290 }
3291 }
3292
3293 if (inst->opcode == BRW_OPCODE_MOV &&
3294 inst->dst.file == MRF &&
3295 inst->src[0].file != ARF &&
3296 !inst->is_partial_write()) {
3297 last_mrf_move[inst->dst.nr] = inst;
3298 }
3299 }
3300
3301 if (progress)
3302 invalidate_live_intervals();
3303
3304 return progress;
3305 }
3306
3307 /**
3308 * Rounding modes for conversion instructions are included for each
3309 * conversion, but right now it is a state. So once it is set,
3310 * we don't need to call it again for subsequent calls.
3311 *
3312 * This is useful for vector/matrices conversions, as setting the
3313 * mode once is enough for the full vector/matrix
3314 */
3315 bool
3316 fs_visitor::remove_extra_rounding_modes()
3317 {
3318 bool progress = false;
3319
3320 foreach_block (block, cfg) {
3321 brw_rnd_mode prev_mode = BRW_RND_MODE_UNSPECIFIED;
3322
3323 foreach_inst_in_block_safe (fs_inst, inst, block) {
3324 if (inst->opcode == SHADER_OPCODE_RND_MODE) {
3325 assert(inst->src[0].file == BRW_IMMEDIATE_VALUE);
3326 const brw_rnd_mode mode = (brw_rnd_mode) inst->src[0].d;
3327 if (mode == prev_mode) {
3328 inst->remove(block);
3329 progress = true;
3330 } else {
3331 prev_mode = mode;
3332 }
3333 }
3334 }
3335 }
3336
3337 if (progress)
3338 invalidate_live_intervals();
3339
3340 return progress;
3341 }
3342
3343 static void
3344 clear_deps_for_inst_src(fs_inst *inst, bool *deps, int first_grf, int grf_len)
3345 {
3346 /* Clear the flag for registers that actually got read (as expected). */
3347 for (int i = 0; i < inst->sources; i++) {
3348 int grf;
3349 if (inst->src[i].file == VGRF || inst->src[i].file == FIXED_GRF) {
3350 grf = inst->src[i].nr;
3351 } else {
3352 continue;
3353 }
3354
3355 if (grf >= first_grf &&
3356 grf < first_grf + grf_len) {
3357 deps[grf - first_grf] = false;
3358 if (inst->exec_size == 16)
3359 deps[grf - first_grf + 1] = false;
3360 }
3361 }
3362 }
3363
3364 /**
3365 * Implements this workaround for the original 965:
3366 *
3367 * "[DevBW, DevCL] Implementation Restrictions: As the hardware does not
3368 * check for post destination dependencies on this instruction, software
3369 * must ensure that there is no destination hazard for the case of ‘write
3370 * followed by a posted write’ shown in the following example.
3371 *
3372 * 1. mov r3 0
3373 * 2. send r3.xy <rest of send instruction>
3374 * 3. mov r2 r3
3375 *
3376 * Due to no post-destination dependency check on the ‘send’, the above
3377 * code sequence could have two instructions (1 and 2) in flight at the
3378 * same time that both consider ‘r3’ as the target of their final writes.
3379 */
3380 void
3381 fs_visitor::insert_gen4_pre_send_dependency_workarounds(bblock_t *block,
3382 fs_inst *inst)
3383 {
3384 int write_len = regs_written(inst);
3385 int first_write_grf = inst->dst.nr;
3386 bool needs_dep[BRW_MAX_MRF(devinfo->gen)];
3387 assert(write_len < (int)sizeof(needs_dep) - 1);
3388
3389 memset(needs_dep, false, sizeof(needs_dep));
3390 memset(needs_dep, true, write_len);
3391
3392 clear_deps_for_inst_src(inst, needs_dep, first_write_grf, write_len);
3393
3394 /* Walk backwards looking for writes to registers we're writing which
3395 * aren't read since being written. If we hit the start of the program,
3396 * we assume that there are no outstanding dependencies on entry to the
3397 * program.
3398 */
3399 foreach_inst_in_block_reverse_starting_from(fs_inst, scan_inst, inst) {
3400 /* If we hit control flow, assume that there *are* outstanding
3401 * dependencies, and force their cleanup before our instruction.
3402 */
3403 if (block->start() == scan_inst && block->num != 0) {
3404 for (int i = 0; i < write_len; i++) {
3405 if (needs_dep[i])
3406 DEP_RESOLVE_MOV(fs_builder(this, block, inst),
3407 first_write_grf + i);
3408 }
3409 return;
3410 }
3411
3412 /* We insert our reads as late as possible on the assumption that any
3413 * instruction but a MOV that might have left us an outstanding
3414 * dependency has more latency than a MOV.
3415 */
3416 if (scan_inst->dst.file == VGRF) {
3417 for (unsigned i = 0; i < regs_written(scan_inst); i++) {
3418 int reg = scan_inst->dst.nr + i;
3419
3420 if (reg >= first_write_grf &&
3421 reg < first_write_grf + write_len &&
3422 needs_dep[reg - first_write_grf]) {
3423 DEP_RESOLVE_MOV(fs_builder(this, block, inst), reg);
3424 needs_dep[reg - first_write_grf] = false;
3425 if (scan_inst->exec_size == 16)
3426 needs_dep[reg - first_write_grf + 1] = false;
3427 }
3428 }
3429 }
3430
3431 /* Clear the flag for registers that actually got read (as expected). */
3432 clear_deps_for_inst_src(scan_inst, needs_dep, first_write_grf, write_len);
3433
3434 /* Continue the loop only if we haven't resolved all the dependencies */
3435 int i;
3436 for (i = 0; i < write_len; i++) {
3437 if (needs_dep[i])
3438 break;
3439 }
3440 if (i == write_len)
3441 return;
3442 }
3443 }
3444
3445 /**
3446 * Implements this workaround for the original 965:
3447 *
3448 * "[DevBW, DevCL] Errata: A destination register from a send can not be
3449 * used as a destination register until after it has been sourced by an
3450 * instruction with a different destination register.
3451 */
3452 void
3453 fs_visitor::insert_gen4_post_send_dependency_workarounds(bblock_t *block, fs_inst *inst)
3454 {
3455 int write_len = regs_written(inst);
3456 int first_write_grf = inst->dst.nr;
3457 bool needs_dep[BRW_MAX_MRF(devinfo->gen)];
3458 assert(write_len < (int)sizeof(needs_dep) - 1);
3459
3460 memset(needs_dep, false, sizeof(needs_dep));
3461 memset(needs_dep, true, write_len);
3462 /* Walk forwards looking for writes to registers we're writing which aren't
3463 * read before being written.
3464 */
3465 foreach_inst_in_block_starting_from(fs_inst, scan_inst, inst) {
3466 /* If we hit control flow, force resolve all remaining dependencies. */
3467 if (block->end() == scan_inst && block->num != cfg->num_blocks - 1) {
3468 for (int i = 0; i < write_len; i++) {
3469 if (needs_dep[i])
3470 DEP_RESOLVE_MOV(fs_builder(this, block, scan_inst),
3471 first_write_grf + i);
3472 }
3473 return;
3474 }
3475
3476 /* Clear the flag for registers that actually got read (as expected). */
3477 clear_deps_for_inst_src(scan_inst, needs_dep, first_write_grf, write_len);
3478
3479 /* We insert our reads as late as possible since they're reading the
3480 * result of a SEND, which has massive latency.
3481 */
3482 if (scan_inst->dst.file == VGRF &&
3483 scan_inst->dst.nr >= first_write_grf &&
3484 scan_inst->dst.nr < first_write_grf + write_len &&
3485 needs_dep[scan_inst->dst.nr - first_write_grf]) {
3486 DEP_RESOLVE_MOV(fs_builder(this, block, scan_inst),
3487 scan_inst->dst.nr);
3488 needs_dep[scan_inst->dst.nr - first_write_grf] = false;
3489 }
3490
3491 /* Continue the loop only if we haven't resolved all the dependencies */
3492 int i;
3493 for (i = 0; i < write_len; i++) {
3494 if (needs_dep[i])
3495 break;
3496 }
3497 if (i == write_len)
3498 return;
3499 }
3500 }
3501
3502 void
3503 fs_visitor::insert_gen4_send_dependency_workarounds()
3504 {
3505 if (devinfo->gen != 4 || devinfo->is_g4x)
3506 return;
3507
3508 bool progress = false;
3509
3510 foreach_block_and_inst(block, fs_inst, inst, cfg) {
3511 if (inst->mlen != 0 && inst->dst.file == VGRF) {
3512 insert_gen4_pre_send_dependency_workarounds(block, inst);
3513 insert_gen4_post_send_dependency_workarounds(block, inst);
3514 progress = true;
3515 }
3516 }
3517
3518 if (progress)
3519 invalidate_live_intervals();
3520 }
3521
3522 /**
3523 * Turns the generic expression-style uniform pull constant load instruction
3524 * into a hardware-specific series of instructions for loading a pull
3525 * constant.
3526 *
3527 * The expression style allows the CSE pass before this to optimize out
3528 * repeated loads from the same offset, and gives the pre-register-allocation
3529 * scheduling full flexibility, while the conversion to native instructions
3530 * allows the post-register-allocation scheduler the best information
3531 * possible.
3532 *
3533 * Note that execution masking for setting up pull constant loads is special:
3534 * the channels that need to be written are unrelated to the current execution
3535 * mask, since a later instruction will use one of the result channels as a
3536 * source operand for all 8 or 16 of its channels.
3537 */
3538 void
3539 fs_visitor::lower_uniform_pull_constant_loads()
3540 {
3541 foreach_block_and_inst (block, fs_inst, inst, cfg) {
3542 if (inst->opcode != FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD)
3543 continue;
3544
3545 if (devinfo->gen >= 7) {
3546 const fs_builder ubld = fs_builder(this, block, inst).exec_all();
3547 const fs_reg payload = ubld.group(8, 0).vgrf(BRW_REGISTER_TYPE_UD);
3548
3549 ubld.group(8, 0).MOV(payload,
3550 retype(brw_vec8_grf(0, 0), BRW_REGISTER_TYPE_UD));
3551 ubld.group(1, 0).MOV(component(payload, 2),
3552 brw_imm_ud(inst->src[1].ud / 16));
3553
3554 inst->opcode = FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD_GEN7;
3555 inst->src[1] = payload;
3556 inst->header_size = 1;
3557 inst->mlen = 1;
3558
3559 invalidate_live_intervals();
3560 } else {
3561 /* Before register allocation, we didn't tell the scheduler about the
3562 * MRF we use. We know it's safe to use this MRF because nothing
3563 * else does except for register spill/unspill, which generates and
3564 * uses its MRF within a single IR instruction.
3565 */
3566 inst->base_mrf = FIRST_PULL_LOAD_MRF(devinfo->gen) + 1;
3567 inst->mlen = 1;
3568 }
3569 }
3570 }
3571
3572 bool
3573 fs_visitor::lower_load_payload()
3574 {
3575 bool progress = false;
3576
3577 foreach_block_and_inst_safe (block, fs_inst, inst, cfg) {
3578 if (inst->opcode != SHADER_OPCODE_LOAD_PAYLOAD)
3579 continue;
3580
3581 assert(inst->dst.file == MRF || inst->dst.file == VGRF);
3582 assert(inst->saturate == false);
3583 fs_reg dst = inst->dst;
3584
3585 /* Get rid of COMPR4. We'll add it back in if we need it */
3586 if (dst.file == MRF)
3587 dst.nr = dst.nr & ~BRW_MRF_COMPR4;
3588
3589 const fs_builder ibld(this, block, inst);
3590 const fs_builder hbld = ibld.exec_all().group(8, 0);
3591
3592 for (uint8_t i = 0; i < inst->header_size; i++) {
3593 if (inst->src[i].file != BAD_FILE) {
3594 fs_reg mov_dst = retype(dst, BRW_REGISTER_TYPE_UD);
3595 fs_reg mov_src = retype(inst->src[i], BRW_REGISTER_TYPE_UD);
3596 hbld.MOV(mov_dst, mov_src);
3597 }
3598 dst = offset(dst, hbld, 1);
3599 }
3600
3601 if (inst->dst.file == MRF && (inst->dst.nr & BRW_MRF_COMPR4) &&
3602 inst->exec_size > 8) {
3603 /* In this case, the payload portion of the LOAD_PAYLOAD isn't
3604 * a straightforward copy. Instead, the result of the
3605 * LOAD_PAYLOAD is treated as interleaved and the first four
3606 * non-header sources are unpacked as:
3607 *
3608 * m + 0: r0
3609 * m + 1: g0
3610 * m + 2: b0
3611 * m + 3: a0
3612 * m + 4: r1
3613 * m + 5: g1
3614 * m + 6: b1
3615 * m + 7: a1
3616 *
3617 * This is used for gen <= 5 fb writes.
3618 */
3619 assert(inst->exec_size == 16);
3620 assert(inst->header_size + 4 <= inst->sources);
3621 for (uint8_t i = inst->header_size; i < inst->header_size + 4; i++) {
3622 if (inst->src[i].file != BAD_FILE) {
3623 if (devinfo->has_compr4) {
3624 fs_reg compr4_dst = retype(dst, inst->src[i].type);
3625 compr4_dst.nr |= BRW_MRF_COMPR4;
3626 ibld.MOV(compr4_dst, inst->src[i]);
3627 } else {
3628 /* Platform doesn't have COMPR4. We have to fake it */
3629 fs_reg mov_dst = retype(dst, inst->src[i].type);
3630 ibld.half(0).MOV(mov_dst, half(inst->src[i], 0));
3631 mov_dst.nr += 4;
3632 ibld.half(1).MOV(mov_dst, half(inst->src[i], 1));
3633 }
3634 }
3635
3636 dst.nr++;
3637 }
3638
3639 /* The loop above only ever incremented us through the first set
3640 * of 4 registers. However, thanks to the magic of COMPR4, we
3641 * actually wrote to the first 8 registers, so we need to take
3642 * that into account now.
3643 */
3644 dst.nr += 4;
3645
3646 /* The COMPR4 code took care of the first 4 sources. We'll let
3647 * the regular path handle any remaining sources. Yes, we are
3648 * modifying the instruction but we're about to delete it so
3649 * this really doesn't hurt anything.
3650 */
3651 inst->header_size += 4;
3652 }
3653
3654 for (uint8_t i = inst->header_size; i < inst->sources; i++) {
3655 if (inst->src[i].file != BAD_FILE)
3656 ibld.MOV(retype(dst, inst->src[i].type), inst->src[i]);
3657 dst = offset(dst, ibld, 1);
3658 }
3659
3660 inst->remove(block);
3661 progress = true;
3662 }
3663
3664 if (progress)
3665 invalidate_live_intervals();
3666
3667 return progress;
3668 }
3669
3670 bool
3671 fs_visitor::lower_integer_multiplication()
3672 {
3673 bool progress = false;
3674
3675 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
3676 const fs_builder ibld(this, block, inst);
3677
3678 if (inst->opcode == BRW_OPCODE_MUL) {
3679 if (inst->dst.is_accumulator() ||
3680 (inst->dst.type != BRW_REGISTER_TYPE_D &&
3681 inst->dst.type != BRW_REGISTER_TYPE_UD))
3682 continue;
3683
3684 if (devinfo->has_integer_dword_mul)
3685 continue;
3686
3687 if (inst->src[1].file == IMM &&
3688 inst->src[1].ud < (1 << 16)) {
3689 /* The MUL instruction isn't commutative. On Gen <= 6, only the low
3690 * 16-bits of src0 are read, and on Gen >= 7 only the low 16-bits of
3691 * src1 are used.
3692 *
3693 * If multiplying by an immediate value that fits in 16-bits, do a
3694 * single MUL instruction with that value in the proper location.
3695 */
3696 if (devinfo->gen < 7) {
3697 fs_reg imm(VGRF, alloc.allocate(dispatch_width / 8),
3698 inst->dst.type);
3699 ibld.MOV(imm, inst->src[1]);
3700 ibld.MUL(inst->dst, imm, inst->src[0]);
3701 } else {
3702 const bool ud = (inst->src[1].type == BRW_REGISTER_TYPE_UD);
3703 ibld.MUL(inst->dst, inst->src[0],
3704 ud ? brw_imm_uw(inst->src[1].ud)
3705 : brw_imm_w(inst->src[1].d));
3706 }
3707 } else {
3708 /* Gen < 8 (and some Gen8+ low-power parts like Cherryview) cannot
3709 * do 32-bit integer multiplication in one instruction, but instead
3710 * must do a sequence (which actually calculates a 64-bit result):
3711 *
3712 * mul(8) acc0<1>D g3<8,8,1>D g4<8,8,1>D
3713 * mach(8) null g3<8,8,1>D g4<8,8,1>D
3714 * mov(8) g2<1>D acc0<8,8,1>D
3715 *
3716 * But on Gen > 6, the ability to use second accumulator register
3717 * (acc1) for non-float data types was removed, preventing a simple
3718 * implementation in SIMD16. A 16-channel result can be calculated by
3719 * executing the three instructions twice in SIMD8, once with quarter
3720 * control of 1Q for the first eight channels and again with 2Q for
3721 * the second eight channels.
3722 *
3723 * Which accumulator register is implicitly accessed (by AccWrEnable
3724 * for instance) is determined by the quarter control. Unfortunately
3725 * Ivybridge (and presumably Baytrail) has a hardware bug in which an
3726 * implicit accumulator access by an instruction with 2Q will access
3727 * acc1 regardless of whether the data type is usable in acc1.
3728 *
3729 * Specifically, the 2Q mach(8) writes acc1 which does not exist for
3730 * integer data types.
3731 *
3732 * Since we only want the low 32-bits of the result, we can do two
3733 * 32-bit x 16-bit multiplies (like the mul and mach are doing), and
3734 * adjust the high result and add them (like the mach is doing):
3735 *
3736 * mul(8) g7<1>D g3<8,8,1>D g4.0<8,8,1>UW
3737 * mul(8) g8<1>D g3<8,8,1>D g4.1<8,8,1>UW
3738 * shl(8) g9<1>D g8<8,8,1>D 16D
3739 * add(8) g2<1>D g7<8,8,1>D g8<8,8,1>D
3740 *
3741 * We avoid the shl instruction by realizing that we only want to add
3742 * the low 16-bits of the "high" result to the high 16-bits of the
3743 * "low" result and using proper regioning on the add:
3744 *
3745 * mul(8) g7<1>D g3<8,8,1>D g4.0<16,8,2>UW
3746 * mul(8) g8<1>D g3<8,8,1>D g4.1<16,8,2>UW
3747 * add(8) g7.1<2>UW g7.1<16,8,2>UW g8<16,8,2>UW
3748 *
3749 * Since it does not use the (single) accumulator register, we can
3750 * schedule multi-component multiplications much better.
3751 */
3752
3753 bool needs_mov = false;
3754 fs_reg orig_dst = inst->dst;
3755 fs_reg low = inst->dst;
3756 if (orig_dst.is_null() || orig_dst.file == MRF ||
3757 regions_overlap(inst->dst, inst->size_written,
3758 inst->src[0], inst->size_read(0)) ||
3759 regions_overlap(inst->dst, inst->size_written,
3760 inst->src[1], inst->size_read(1))) {
3761 needs_mov = true;
3762 /* Get a new VGRF but keep the same stride as inst->dst */
3763 low = fs_reg(VGRF, alloc.allocate(regs_written(inst)),
3764 inst->dst.type);
3765 low.stride = inst->dst.stride;
3766 low.offset = inst->dst.offset % REG_SIZE;
3767 }
3768
3769 /* Get a new VGRF but keep the same stride as inst->dst */
3770 fs_reg high(VGRF, alloc.allocate(regs_written(inst)),
3771 inst->dst.type);
3772 high.stride = inst->dst.stride;
3773 high.offset = inst->dst.offset % REG_SIZE;
3774
3775 if (devinfo->gen >= 7) {
3776 if (inst->src[1].file == IMM) {
3777 ibld.MUL(low, inst->src[0],
3778 brw_imm_uw(inst->src[1].ud & 0xffff));
3779 ibld.MUL(high, inst->src[0],
3780 brw_imm_uw(inst->src[1].ud >> 16));
3781 } else {
3782 ibld.MUL(low, inst->src[0],
3783 subscript(inst->src[1], BRW_REGISTER_TYPE_UW, 0));
3784 ibld.MUL(high, inst->src[0],
3785 subscript(inst->src[1], BRW_REGISTER_TYPE_UW, 1));
3786 }
3787 } else {
3788 ibld.MUL(low, subscript(inst->src[0], BRW_REGISTER_TYPE_UW, 0),
3789 inst->src[1]);
3790 ibld.MUL(high, subscript(inst->src[0], BRW_REGISTER_TYPE_UW, 1),
3791 inst->src[1]);
3792 }
3793
3794 ibld.ADD(subscript(low, BRW_REGISTER_TYPE_UW, 1),
3795 subscript(low, BRW_REGISTER_TYPE_UW, 1),
3796 subscript(high, BRW_REGISTER_TYPE_UW, 0));
3797
3798 if (needs_mov || inst->conditional_mod) {
3799 set_condmod(inst->conditional_mod,
3800 ibld.MOV(orig_dst, low));
3801 }
3802 }
3803
3804 } else if (inst->opcode == SHADER_OPCODE_MULH) {
3805 /* Should have been lowered to 8-wide. */
3806 assert(inst->exec_size <= get_lowered_simd_width(devinfo, inst));
3807 const fs_reg acc = retype(brw_acc_reg(inst->exec_size),
3808 inst->dst.type);
3809 fs_inst *mul = ibld.MUL(acc, inst->src[0], inst->src[1]);
3810 fs_inst *mach = ibld.MACH(inst->dst, inst->src[0], inst->src[1]);
3811
3812 if (devinfo->gen >= 8) {
3813 /* Until Gen8, integer multiplies read 32-bits from one source,
3814 * and 16-bits from the other, and relying on the MACH instruction
3815 * to generate the high bits of the result.
3816 *
3817 * On Gen8, the multiply instruction does a full 32x32-bit
3818 * multiply, but in order to do a 64-bit multiply we can simulate
3819 * the previous behavior and then use a MACH instruction.
3820 *
3821 * FINISHME: Don't use source modifiers on src1.
3822 */
3823 assert(mul->src[1].type == BRW_REGISTER_TYPE_D ||
3824 mul->src[1].type == BRW_REGISTER_TYPE_UD);
3825 mul->src[1].type = BRW_REGISTER_TYPE_UW;
3826 mul->src[1].stride *= 2;
3827
3828 } else if (devinfo->gen == 7 && !devinfo->is_haswell &&
3829 inst->group > 0) {
3830 /* Among other things the quarter control bits influence which
3831 * accumulator register is used by the hardware for instructions
3832 * that access the accumulator implicitly (e.g. MACH). A
3833 * second-half instruction would normally map to acc1, which
3834 * doesn't exist on Gen7 and up (the hardware does emulate it for
3835 * floating-point instructions *only* by taking advantage of the
3836 * extra precision of acc0 not normally used for floating point
3837 * arithmetic).
3838 *
3839 * HSW and up are careful enough not to try to access an
3840 * accumulator register that doesn't exist, but on earlier Gen7
3841 * hardware we need to make sure that the quarter control bits are
3842 * zero to avoid non-deterministic behaviour and emit an extra MOV
3843 * to get the result masked correctly according to the current
3844 * channel enables.
3845 */
3846 mach->group = 0;
3847 mach->force_writemask_all = true;
3848 mach->dst = ibld.vgrf(inst->dst.type);
3849 ibld.MOV(inst->dst, mach->dst);
3850 }
3851 } else {
3852 continue;
3853 }
3854
3855 inst->remove(block);
3856 progress = true;
3857 }
3858
3859 if (progress)
3860 invalidate_live_intervals();
3861
3862 return progress;
3863 }
3864
3865 bool
3866 fs_visitor::lower_minmax()
3867 {
3868 assert(devinfo->gen < 6);
3869
3870 bool progress = false;
3871
3872 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
3873 const fs_builder ibld(this, block, inst);
3874
3875 if (inst->opcode == BRW_OPCODE_SEL &&
3876 inst->predicate == BRW_PREDICATE_NONE) {
3877 /* FIXME: Using CMP doesn't preserve the NaN propagation semantics of
3878 * the original SEL.L/GE instruction
3879 */
3880 ibld.CMP(ibld.null_reg_d(), inst->src[0], inst->src[1],
3881 inst->conditional_mod);
3882 inst->predicate = BRW_PREDICATE_NORMAL;
3883 inst->conditional_mod = BRW_CONDITIONAL_NONE;
3884
3885 progress = true;
3886 }
3887 }
3888
3889 if (progress)
3890 invalidate_live_intervals();
3891
3892 return progress;
3893 }
3894
3895 static void
3896 setup_color_payload(const fs_builder &bld, const brw_wm_prog_key *key,
3897 fs_reg *dst, fs_reg color, unsigned components)
3898 {
3899 if (key->clamp_fragment_color) {
3900 fs_reg tmp = bld.vgrf(BRW_REGISTER_TYPE_F, 4);
3901 assert(color.type == BRW_REGISTER_TYPE_F);
3902
3903 for (unsigned i = 0; i < components; i++)
3904 set_saturate(true,
3905 bld.MOV(offset(tmp, bld, i), offset(color, bld, i)));
3906
3907 color = tmp;
3908 }
3909
3910 for (unsigned i = 0; i < components; i++)
3911 dst[i] = offset(color, bld, i);
3912 }
3913
3914 static void
3915 lower_fb_write_logical_send(const fs_builder &bld, fs_inst *inst,
3916 const struct brw_wm_prog_data *prog_data,
3917 const brw_wm_prog_key *key,
3918 const fs_visitor::thread_payload &payload)
3919 {
3920 assert(inst->src[FB_WRITE_LOGICAL_SRC_COMPONENTS].file == IMM);
3921 const gen_device_info *devinfo = bld.shader->devinfo;
3922 const fs_reg &color0 = inst->src[FB_WRITE_LOGICAL_SRC_COLOR0];
3923 const fs_reg &color1 = inst->src[FB_WRITE_LOGICAL_SRC_COLOR1];
3924 const fs_reg &src0_alpha = inst->src[FB_WRITE_LOGICAL_SRC_SRC0_ALPHA];
3925 const fs_reg &src_depth = inst->src[FB_WRITE_LOGICAL_SRC_SRC_DEPTH];
3926 const fs_reg &dst_depth = inst->src[FB_WRITE_LOGICAL_SRC_DST_DEPTH];
3927 const fs_reg &src_stencil = inst->src[FB_WRITE_LOGICAL_SRC_SRC_STENCIL];
3928 fs_reg sample_mask = inst->src[FB_WRITE_LOGICAL_SRC_OMASK];
3929 const unsigned components =
3930 inst->src[FB_WRITE_LOGICAL_SRC_COMPONENTS].ud;
3931
3932 /* We can potentially have a message length of up to 15, so we have to set
3933 * base_mrf to either 0 or 1 in order to fit in m0..m15.
3934 */
3935 fs_reg sources[15];
3936 int header_size = 2, payload_header_size;
3937 unsigned length = 0;
3938
3939 /* From the Sandy Bridge PRM, volume 4, page 198:
3940 *
3941 * "Dispatched Pixel Enables. One bit per pixel indicating
3942 * which pixels were originally enabled when the thread was
3943 * dispatched. This field is only required for the end-of-
3944 * thread message and on all dual-source messages."
3945 */
3946 if (devinfo->gen >= 6 &&
3947 (devinfo->is_haswell || devinfo->gen >= 8 || !prog_data->uses_kill) &&
3948 color1.file == BAD_FILE &&
3949 key->nr_color_regions == 1) {
3950 header_size = 0;
3951 }
3952
3953 if (header_size != 0) {
3954 assert(header_size == 2);
3955 /* Allocate 2 registers for a header */
3956 length += 2;
3957 }
3958
3959 if (payload.aa_dest_stencil_reg) {
3960 sources[length] = fs_reg(VGRF, bld.shader->alloc.allocate(1));
3961 bld.group(8, 0).exec_all().annotate("FB write stencil/AA alpha")
3962 .MOV(sources[length],
3963 fs_reg(brw_vec8_grf(payload.aa_dest_stencil_reg, 0)));
3964 length++;
3965 }
3966
3967 if (sample_mask.file != BAD_FILE) {
3968 sources[length] = fs_reg(VGRF, bld.shader->alloc.allocate(1),
3969 BRW_REGISTER_TYPE_UD);
3970
3971 /* Hand over gl_SampleMask. Only the lower 16 bits of each channel are
3972 * relevant. Since it's unsigned single words one vgrf is always
3973 * 16-wide, but only the lower or higher 8 channels will be used by the
3974 * hardware when doing a SIMD8 write depending on whether we have
3975 * selected the subspans for the first or second half respectively.
3976 */
3977 assert(sample_mask.file != BAD_FILE && type_sz(sample_mask.type) == 4);
3978 sample_mask.type = BRW_REGISTER_TYPE_UW;
3979 sample_mask.stride *= 2;
3980
3981 bld.exec_all().annotate("FB write oMask")
3982 .MOV(horiz_offset(retype(sources[length], BRW_REGISTER_TYPE_UW),
3983 inst->group),
3984 sample_mask);
3985 length++;
3986 }
3987
3988 payload_header_size = length;
3989
3990 if (src0_alpha.file != BAD_FILE) {
3991 /* FIXME: This is being passed at the wrong location in the payload and
3992 * doesn't work when gl_SampleMask and MRTs are used simultaneously.
3993 * It's supposed to be immediately before oMask but there seems to be no
3994 * reasonable way to pass them in the correct order because LOAD_PAYLOAD
3995 * requires header sources to form a contiguous segment at the beginning
3996 * of the message and src0_alpha has per-channel semantics.
3997 */
3998 setup_color_payload(bld, key, &sources[length], src0_alpha, 1);
3999 length++;
4000 } else if (key->replicate_alpha && inst->target != 0) {
4001 /* Handle the case when fragment shader doesn't write to draw buffer
4002 * zero. No need to call setup_color_payload() for src0_alpha because
4003 * alpha value will be undefined.
4004 */
4005 length++;
4006 }
4007
4008 setup_color_payload(bld, key, &sources[length], color0, components);
4009 length += 4;
4010
4011 if (color1.file != BAD_FILE) {
4012 setup_color_payload(bld, key, &sources[length], color1, components);
4013 length += 4;
4014 }
4015
4016 if (src_depth.file != BAD_FILE) {
4017 sources[length] = src_depth;
4018 length++;
4019 }
4020
4021 if (dst_depth.file != BAD_FILE) {
4022 sources[length] = dst_depth;
4023 length++;
4024 }
4025
4026 if (src_stencil.file != BAD_FILE) {
4027 assert(devinfo->gen >= 9);
4028 assert(bld.dispatch_width() != 16);
4029
4030 /* XXX: src_stencil is only available on gen9+. dst_depth is never
4031 * available on gen9+. As such it's impossible to have both enabled at the
4032 * same time and therefore length cannot overrun the array.
4033 */
4034 assert(length < 15);
4035
4036 sources[length] = bld.vgrf(BRW_REGISTER_TYPE_UD);
4037 bld.exec_all().annotate("FB write OS")
4038 .MOV(retype(sources[length], BRW_REGISTER_TYPE_UB),
4039 subscript(src_stencil, BRW_REGISTER_TYPE_UB, 0));
4040 length++;
4041 }
4042
4043 fs_inst *load;
4044 if (devinfo->gen >= 7) {
4045 /* Send from the GRF */
4046 fs_reg payload = fs_reg(VGRF, -1, BRW_REGISTER_TYPE_F);
4047 load = bld.LOAD_PAYLOAD(payload, sources, length, payload_header_size);
4048 payload.nr = bld.shader->alloc.allocate(regs_written(load));
4049 load->dst = payload;
4050
4051 inst->src[0] = payload;
4052 inst->resize_sources(1);
4053 } else {
4054 /* Send from the MRF */
4055 load = bld.LOAD_PAYLOAD(fs_reg(MRF, 1, BRW_REGISTER_TYPE_F),
4056 sources, length, payload_header_size);
4057
4058 /* On pre-SNB, we have to interlace the color values. LOAD_PAYLOAD
4059 * will do this for us if we just give it a COMPR4 destination.
4060 */
4061 if (devinfo->gen < 6 && bld.dispatch_width() == 16)
4062 load->dst.nr |= BRW_MRF_COMPR4;
4063
4064 inst->resize_sources(0);
4065 inst->base_mrf = 1;
4066 }
4067
4068 inst->opcode = FS_OPCODE_FB_WRITE;
4069 inst->mlen = regs_written(load);
4070 inst->header_size = header_size;
4071 }
4072
4073 static void
4074 lower_fb_read_logical_send(const fs_builder &bld, fs_inst *inst)
4075 {
4076 const fs_builder &ubld = bld.exec_all();
4077 const unsigned length = 2;
4078 const fs_reg header = ubld.group(8, 0).vgrf(BRW_REGISTER_TYPE_UD, length);
4079
4080 ubld.group(16, 0)
4081 .MOV(header, retype(brw_vec8_grf(0, 0), BRW_REGISTER_TYPE_UD));
4082
4083 inst->resize_sources(1);
4084 inst->src[0] = header;
4085 inst->opcode = FS_OPCODE_FB_READ;
4086 inst->mlen = length;
4087 inst->header_size = length;
4088 }
4089
4090 static void
4091 lower_sampler_logical_send_gen4(const fs_builder &bld, fs_inst *inst, opcode op,
4092 const fs_reg &coordinate,
4093 const fs_reg &shadow_c,
4094 const fs_reg &lod, const fs_reg &lod2,
4095 const fs_reg &surface,
4096 const fs_reg &sampler,
4097 unsigned coord_components,
4098 unsigned grad_components)
4099 {
4100 const bool has_lod = (op == SHADER_OPCODE_TXL || op == FS_OPCODE_TXB ||
4101 op == SHADER_OPCODE_TXF || op == SHADER_OPCODE_TXS);
4102 fs_reg msg_begin(MRF, 1, BRW_REGISTER_TYPE_F);
4103 fs_reg msg_end = msg_begin;
4104
4105 /* g0 header. */
4106 msg_end = offset(msg_end, bld.group(8, 0), 1);
4107
4108 for (unsigned i = 0; i < coord_components; i++)
4109 bld.MOV(retype(offset(msg_end, bld, i), coordinate.type),
4110 offset(coordinate, bld, i));
4111
4112 msg_end = offset(msg_end, bld, coord_components);
4113
4114 /* Messages other than SAMPLE and RESINFO in SIMD16 and TXD in SIMD8
4115 * require all three components to be present and zero if they are unused.
4116 */
4117 if (coord_components > 0 &&
4118 (has_lod || shadow_c.file != BAD_FILE ||
4119 (op == SHADER_OPCODE_TEX && bld.dispatch_width() == 8))) {
4120 for (unsigned i = coord_components; i < 3; i++)
4121 bld.MOV(offset(msg_end, bld, i), brw_imm_f(0.0f));
4122
4123 msg_end = offset(msg_end, bld, 3 - coord_components);
4124 }
4125
4126 if (op == SHADER_OPCODE_TXD) {
4127 /* TXD unsupported in SIMD16 mode. */
4128 assert(bld.dispatch_width() == 8);
4129
4130 /* the slots for u and v are always present, but r is optional */
4131 if (coord_components < 2)
4132 msg_end = offset(msg_end, bld, 2 - coord_components);
4133
4134 /* P = u, v, r
4135 * dPdx = dudx, dvdx, drdx
4136 * dPdy = dudy, dvdy, drdy
4137 *
4138 * 1-arg: Does not exist.
4139 *
4140 * 2-arg: dudx dvdx dudy dvdy
4141 * dPdx.x dPdx.y dPdy.x dPdy.y
4142 * m4 m5 m6 m7
4143 *
4144 * 3-arg: dudx dvdx drdx dudy dvdy drdy
4145 * dPdx.x dPdx.y dPdx.z dPdy.x dPdy.y dPdy.z
4146 * m5 m6 m7 m8 m9 m10
4147 */
4148 for (unsigned i = 0; i < grad_components; i++)
4149 bld.MOV(offset(msg_end, bld, i), offset(lod, bld, i));
4150
4151 msg_end = offset(msg_end, bld, MAX2(grad_components, 2));
4152
4153 for (unsigned i = 0; i < grad_components; i++)
4154 bld.MOV(offset(msg_end, bld, i), offset(lod2, bld, i));
4155
4156 msg_end = offset(msg_end, bld, MAX2(grad_components, 2));
4157 }
4158
4159 if (has_lod) {
4160 /* Bias/LOD with shadow comparator is unsupported in SIMD16 -- *Without*
4161 * shadow comparator (including RESINFO) it's unsupported in SIMD8 mode.
4162 */
4163 assert(shadow_c.file != BAD_FILE ? bld.dispatch_width() == 8 :
4164 bld.dispatch_width() == 16);
4165
4166 const brw_reg_type type =
4167 (op == SHADER_OPCODE_TXF || op == SHADER_OPCODE_TXS ?
4168 BRW_REGISTER_TYPE_UD : BRW_REGISTER_TYPE_F);
4169 bld.MOV(retype(msg_end, type), lod);
4170 msg_end = offset(msg_end, bld, 1);
4171 }
4172
4173 if (shadow_c.file != BAD_FILE) {
4174 if (op == SHADER_OPCODE_TEX && bld.dispatch_width() == 8) {
4175 /* There's no plain shadow compare message, so we use shadow
4176 * compare with a bias of 0.0.
4177 */
4178 bld.MOV(msg_end, brw_imm_f(0.0f));
4179 msg_end = offset(msg_end, bld, 1);
4180 }
4181
4182 bld.MOV(msg_end, shadow_c);
4183 msg_end = offset(msg_end, bld, 1);
4184 }
4185
4186 inst->opcode = op;
4187 inst->src[0] = reg_undef;
4188 inst->src[1] = surface;
4189 inst->src[2] = sampler;
4190 inst->resize_sources(3);
4191 inst->base_mrf = msg_begin.nr;
4192 inst->mlen = msg_end.nr - msg_begin.nr;
4193 inst->header_size = 1;
4194 }
4195
4196 static void
4197 lower_sampler_logical_send_gen5(const fs_builder &bld, fs_inst *inst, opcode op,
4198 const fs_reg &coordinate,
4199 const fs_reg &shadow_c,
4200 const fs_reg &lod, const fs_reg &lod2,
4201 const fs_reg &sample_index,
4202 const fs_reg &surface,
4203 const fs_reg &sampler,
4204 unsigned coord_components,
4205 unsigned grad_components)
4206 {
4207 fs_reg message(MRF, 2, BRW_REGISTER_TYPE_F);
4208 fs_reg msg_coords = message;
4209 unsigned header_size = 0;
4210
4211 if (inst->offset != 0) {
4212 /* The offsets set up by the visitor are in the m1 header, so we can't
4213 * go headerless.
4214 */
4215 header_size = 1;
4216 message.nr--;
4217 }
4218
4219 for (unsigned i = 0; i < coord_components; i++)
4220 bld.MOV(retype(offset(msg_coords, bld, i), coordinate.type),
4221 offset(coordinate, bld, i));
4222
4223 fs_reg msg_end = offset(msg_coords, bld, coord_components);
4224 fs_reg msg_lod = offset(msg_coords, bld, 4);
4225
4226 if (shadow_c.file != BAD_FILE) {
4227 fs_reg msg_shadow = msg_lod;
4228 bld.MOV(msg_shadow, shadow_c);
4229 msg_lod = offset(msg_shadow, bld, 1);
4230 msg_end = msg_lod;
4231 }
4232
4233 switch (op) {
4234 case SHADER_OPCODE_TXL:
4235 case FS_OPCODE_TXB:
4236 bld.MOV(msg_lod, lod);
4237 msg_end = offset(msg_lod, bld, 1);
4238 break;
4239 case SHADER_OPCODE_TXD:
4240 /**
4241 * P = u, v, r
4242 * dPdx = dudx, dvdx, drdx
4243 * dPdy = dudy, dvdy, drdy
4244 *
4245 * Load up these values:
4246 * - dudx dudy dvdx dvdy drdx drdy
4247 * - dPdx.x dPdy.x dPdx.y dPdy.y dPdx.z dPdy.z
4248 */
4249 msg_end = msg_lod;
4250 for (unsigned i = 0; i < grad_components; i++) {
4251 bld.MOV(msg_end, offset(lod, bld, i));
4252 msg_end = offset(msg_end, bld, 1);
4253
4254 bld.MOV(msg_end, offset(lod2, bld, i));
4255 msg_end = offset(msg_end, bld, 1);
4256 }
4257 break;
4258 case SHADER_OPCODE_TXS:
4259 msg_lod = retype(msg_end, BRW_REGISTER_TYPE_UD);
4260 bld.MOV(msg_lod, lod);
4261 msg_end = offset(msg_lod, bld, 1);
4262 break;
4263 case SHADER_OPCODE_TXF:
4264 msg_lod = offset(msg_coords, bld, 3);
4265 bld.MOV(retype(msg_lod, BRW_REGISTER_TYPE_UD), lod);
4266 msg_end = offset(msg_lod, bld, 1);
4267 break;
4268 case SHADER_OPCODE_TXF_CMS:
4269 msg_lod = offset(msg_coords, bld, 3);
4270 /* lod */
4271 bld.MOV(retype(msg_lod, BRW_REGISTER_TYPE_UD), brw_imm_ud(0u));
4272 /* sample index */
4273 bld.MOV(retype(offset(msg_lod, bld, 1), BRW_REGISTER_TYPE_UD), sample_index);
4274 msg_end = offset(msg_lod, bld, 2);
4275 break;
4276 default:
4277 break;
4278 }
4279
4280 inst->opcode = op;
4281 inst->src[0] = reg_undef;
4282 inst->src[1] = surface;
4283 inst->src[2] = sampler;
4284 inst->resize_sources(3);
4285 inst->base_mrf = message.nr;
4286 inst->mlen = msg_end.nr - message.nr;
4287 inst->header_size = header_size;
4288
4289 /* Message length > MAX_SAMPLER_MESSAGE_SIZE disallowed by hardware. */
4290 assert(inst->mlen <= MAX_SAMPLER_MESSAGE_SIZE);
4291 }
4292
4293 static bool
4294 is_high_sampler(const struct gen_device_info *devinfo, const fs_reg &sampler)
4295 {
4296 if (devinfo->gen < 8 && !devinfo->is_haswell)
4297 return false;
4298
4299 return sampler.file != IMM || sampler.ud >= 16;
4300 }
4301
4302 static void
4303 lower_sampler_logical_send_gen7(const fs_builder &bld, fs_inst *inst, opcode op,
4304 const fs_reg &coordinate,
4305 const fs_reg &shadow_c,
4306 fs_reg lod, const fs_reg &lod2,
4307 const fs_reg &sample_index,
4308 const fs_reg &mcs,
4309 const fs_reg &surface,
4310 const fs_reg &sampler,
4311 const fs_reg &tg4_offset,
4312 unsigned coord_components,
4313 unsigned grad_components)
4314 {
4315 const gen_device_info *devinfo = bld.shader->devinfo;
4316 unsigned reg_width = bld.dispatch_width() / 8;
4317 unsigned header_size = 0, length = 0;
4318 fs_reg sources[MAX_SAMPLER_MESSAGE_SIZE];
4319 for (unsigned i = 0; i < ARRAY_SIZE(sources); i++)
4320 sources[i] = bld.vgrf(BRW_REGISTER_TYPE_F);
4321
4322 if (op == SHADER_OPCODE_TG4 || op == SHADER_OPCODE_TG4_OFFSET ||
4323 inst->offset != 0 || inst->eot ||
4324 op == SHADER_OPCODE_SAMPLEINFO ||
4325 is_high_sampler(devinfo, sampler)) {
4326 /* For general texture offsets (no txf workaround), we need a header to
4327 * put them in.
4328 *
4329 * TG4 needs to place its channel select in the header, for interaction
4330 * with ARB_texture_swizzle. The sampler index is only 4-bits, so for
4331 * larger sampler numbers we need to offset the Sampler State Pointer in
4332 * the header.
4333 */
4334 fs_reg header = retype(sources[0], BRW_REGISTER_TYPE_UD);
4335 header_size = 1;
4336 length++;
4337
4338 /* If we're requesting fewer than four channels worth of response,
4339 * and we have an explicit header, we need to set up the sampler
4340 * writemask. It's reversed from normal: 1 means "don't write".
4341 */
4342 if (!inst->eot && regs_written(inst) != 4 * reg_width) {
4343 assert(regs_written(inst) % reg_width == 0);
4344 unsigned mask = ~((1 << (regs_written(inst) / reg_width)) - 1) & 0xf;
4345 inst->offset |= mask << 12;
4346 }
4347
4348 /* Build the actual header */
4349 const fs_builder ubld = bld.exec_all().group(8, 0);
4350 const fs_builder ubld1 = ubld.group(1, 0);
4351 ubld.MOV(header, retype(brw_vec8_grf(0, 0), BRW_REGISTER_TYPE_UD));
4352 if (inst->offset) {
4353 ubld1.MOV(component(header, 2), brw_imm_ud(inst->offset));
4354 } else if (bld.shader->stage != MESA_SHADER_VERTEX &&
4355 bld.shader->stage != MESA_SHADER_FRAGMENT) {
4356 /* The vertex and fragment stages have g0.2 set to 0, so
4357 * header0.2 is 0 when g0 is copied. Other stages may not, so we
4358 * must set it to 0 to avoid setting undesirable bits in the
4359 * message.
4360 */
4361 ubld1.MOV(component(header, 2), brw_imm_ud(0));
4362 }
4363
4364 if (is_high_sampler(devinfo, sampler)) {
4365 if (sampler.file == BRW_IMMEDIATE_VALUE) {
4366 assert(sampler.ud >= 16);
4367 const int sampler_state_size = 16; /* 16 bytes */
4368
4369 ubld1.ADD(component(header, 3),
4370 retype(brw_vec1_grf(0, 3), BRW_REGISTER_TYPE_UD),
4371 brw_imm_ud(16 * (sampler.ud / 16) * sampler_state_size));
4372 } else {
4373 fs_reg tmp = ubld1.vgrf(BRW_REGISTER_TYPE_UD);
4374 ubld1.AND(tmp, sampler, brw_imm_ud(0x0f0));
4375 ubld1.SHL(tmp, tmp, brw_imm_ud(4));
4376 ubld1.ADD(component(header, 3),
4377 retype(brw_vec1_grf(0, 3), BRW_REGISTER_TYPE_UD),
4378 tmp);
4379 }
4380 }
4381 }
4382
4383 if (shadow_c.file != BAD_FILE) {
4384 bld.MOV(sources[length], shadow_c);
4385 length++;
4386 }
4387
4388 bool coordinate_done = false;
4389
4390 /* Set up the LOD info */
4391 switch (op) {
4392 case FS_OPCODE_TXB:
4393 case SHADER_OPCODE_TXL:
4394 if (devinfo->gen >= 9 && op == SHADER_OPCODE_TXL && lod.is_zero()) {
4395 op = SHADER_OPCODE_TXL_LZ;
4396 break;
4397 }
4398 bld.MOV(sources[length], lod);
4399 length++;
4400 break;
4401 case SHADER_OPCODE_TXD:
4402 /* TXD should have been lowered in SIMD16 mode. */
4403 assert(bld.dispatch_width() == 8);
4404
4405 /* Load dPdx and the coordinate together:
4406 * [hdr], [ref], x, dPdx.x, dPdy.x, y, dPdx.y, dPdy.y, z, dPdx.z, dPdy.z
4407 */
4408 for (unsigned i = 0; i < coord_components; i++) {
4409 bld.MOV(sources[length++], offset(coordinate, bld, i));
4410
4411 /* For cube map array, the coordinate is (u,v,r,ai) but there are
4412 * only derivatives for (u, v, r).
4413 */
4414 if (i < grad_components) {
4415 bld.MOV(sources[length++], offset(lod, bld, i));
4416 bld.MOV(sources[length++], offset(lod2, bld, i));
4417 }
4418 }
4419
4420 coordinate_done = true;
4421 break;
4422 case SHADER_OPCODE_TXS:
4423 bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_UD), lod);
4424 length++;
4425 break;
4426 case SHADER_OPCODE_TXF:
4427 /* Unfortunately, the parameters for LD are intermixed: u, lod, v, r.
4428 * On Gen9 they are u, v, lod, r
4429 */
4430 bld.MOV(retype(sources[length++], BRW_REGISTER_TYPE_D), coordinate);
4431
4432 if (devinfo->gen >= 9) {
4433 if (coord_components >= 2) {
4434 bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_D),
4435 offset(coordinate, bld, 1));
4436 } else {
4437 sources[length] = brw_imm_d(0);
4438 }
4439 length++;
4440 }
4441
4442 if (devinfo->gen >= 9 && lod.is_zero()) {
4443 op = SHADER_OPCODE_TXF_LZ;
4444 } else {
4445 bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_D), lod);
4446 length++;
4447 }
4448
4449 for (unsigned i = devinfo->gen >= 9 ? 2 : 1; i < coord_components; i++)
4450 bld.MOV(retype(sources[length++], BRW_REGISTER_TYPE_D),
4451 offset(coordinate, bld, i));
4452
4453 coordinate_done = true;
4454 break;
4455
4456 case SHADER_OPCODE_TXF_CMS:
4457 case SHADER_OPCODE_TXF_CMS_W:
4458 case SHADER_OPCODE_TXF_UMS:
4459 case SHADER_OPCODE_TXF_MCS:
4460 if (op == SHADER_OPCODE_TXF_UMS ||
4461 op == SHADER_OPCODE_TXF_CMS ||
4462 op == SHADER_OPCODE_TXF_CMS_W) {
4463 bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_UD), sample_index);
4464 length++;
4465 }
4466
4467 if (op == SHADER_OPCODE_TXF_CMS || op == SHADER_OPCODE_TXF_CMS_W) {
4468 /* Data from the multisample control surface. */
4469 bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_UD), mcs);
4470 length++;
4471
4472 /* On Gen9+ we'll use ld2dms_w instead which has two registers for
4473 * the MCS data.
4474 */
4475 if (op == SHADER_OPCODE_TXF_CMS_W) {
4476 bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_UD),
4477 mcs.file == IMM ?
4478 mcs :
4479 offset(mcs, bld, 1));
4480 length++;
4481 }
4482 }
4483
4484 /* There is no offsetting for this message; just copy in the integer
4485 * texture coordinates.
4486 */
4487 for (unsigned i = 0; i < coord_components; i++)
4488 bld.MOV(retype(sources[length++], BRW_REGISTER_TYPE_D),
4489 offset(coordinate, bld, i));
4490
4491 coordinate_done = true;
4492 break;
4493 case SHADER_OPCODE_TG4_OFFSET:
4494 /* More crazy intermixing */
4495 for (unsigned i = 0; i < 2; i++) /* u, v */
4496 bld.MOV(sources[length++], offset(coordinate, bld, i));
4497
4498 for (unsigned i = 0; i < 2; i++) /* offu, offv */
4499 bld.MOV(retype(sources[length++], BRW_REGISTER_TYPE_D),
4500 offset(tg4_offset, bld, i));
4501
4502 if (coord_components == 3) /* r if present */
4503 bld.MOV(sources[length++], offset(coordinate, bld, 2));
4504
4505 coordinate_done = true;
4506 break;
4507 default:
4508 break;
4509 }
4510
4511 /* Set up the coordinate (except for cases where it was done above) */
4512 if (!coordinate_done) {
4513 for (unsigned i = 0; i < coord_components; i++)
4514 bld.MOV(sources[length++], offset(coordinate, bld, i));
4515 }
4516
4517 int mlen;
4518 if (reg_width == 2)
4519 mlen = length * reg_width - header_size;
4520 else
4521 mlen = length * reg_width;
4522
4523 const fs_reg src_payload = fs_reg(VGRF, bld.shader->alloc.allocate(mlen),
4524 BRW_REGISTER_TYPE_F);
4525 bld.LOAD_PAYLOAD(src_payload, sources, length, header_size);
4526
4527 /* Generate the SEND. */
4528 inst->opcode = op;
4529 inst->src[0] = src_payload;
4530 inst->src[1] = surface;
4531 inst->src[2] = sampler;
4532 inst->resize_sources(3);
4533 inst->mlen = mlen;
4534 inst->header_size = header_size;
4535
4536 /* Message length > MAX_SAMPLER_MESSAGE_SIZE disallowed by hardware. */
4537 assert(inst->mlen <= MAX_SAMPLER_MESSAGE_SIZE);
4538 }
4539
4540 static void
4541 lower_sampler_logical_send(const fs_builder &bld, fs_inst *inst, opcode op)
4542 {
4543 const gen_device_info *devinfo = bld.shader->devinfo;
4544 const fs_reg &coordinate = inst->src[TEX_LOGICAL_SRC_COORDINATE];
4545 const fs_reg &shadow_c = inst->src[TEX_LOGICAL_SRC_SHADOW_C];
4546 const fs_reg &lod = inst->src[TEX_LOGICAL_SRC_LOD];
4547 const fs_reg &lod2 = inst->src[TEX_LOGICAL_SRC_LOD2];
4548 const fs_reg &sample_index = inst->src[TEX_LOGICAL_SRC_SAMPLE_INDEX];
4549 const fs_reg &mcs = inst->src[TEX_LOGICAL_SRC_MCS];
4550 const fs_reg &surface = inst->src[TEX_LOGICAL_SRC_SURFACE];
4551 const fs_reg &sampler = inst->src[TEX_LOGICAL_SRC_SAMPLER];
4552 const fs_reg &tg4_offset = inst->src[TEX_LOGICAL_SRC_TG4_OFFSET];
4553 assert(inst->src[TEX_LOGICAL_SRC_COORD_COMPONENTS].file == IMM);
4554 const unsigned coord_components = inst->src[TEX_LOGICAL_SRC_COORD_COMPONENTS].ud;
4555 assert(inst->src[TEX_LOGICAL_SRC_GRAD_COMPONENTS].file == IMM);
4556 const unsigned grad_components = inst->src[TEX_LOGICAL_SRC_GRAD_COMPONENTS].ud;
4557
4558 if (devinfo->gen >= 7) {
4559 lower_sampler_logical_send_gen7(bld, inst, op, coordinate,
4560 shadow_c, lod, lod2, sample_index,
4561 mcs, surface, sampler, tg4_offset,
4562 coord_components, grad_components);
4563 } else if (devinfo->gen >= 5) {
4564 lower_sampler_logical_send_gen5(bld, inst, op, coordinate,
4565 shadow_c, lod, lod2, sample_index,
4566 surface, sampler,
4567 coord_components, grad_components);
4568 } else {
4569 lower_sampler_logical_send_gen4(bld, inst, op, coordinate,
4570 shadow_c, lod, lod2,
4571 surface, sampler,
4572 coord_components, grad_components);
4573 }
4574 }
4575
4576 /**
4577 * Initialize the header present in some typed and untyped surface
4578 * messages.
4579 */
4580 static fs_reg
4581 emit_surface_header(const fs_builder &bld, const fs_reg &sample_mask)
4582 {
4583 fs_builder ubld = bld.exec_all().group(8, 0);
4584 const fs_reg dst = ubld.vgrf(BRW_REGISTER_TYPE_UD);
4585 ubld.MOV(dst, brw_imm_d(0));
4586 ubld.group(1, 0).MOV(component(dst, 7), sample_mask);
4587 return dst;
4588 }
4589
4590 static void
4591 lower_surface_logical_send(const fs_builder &bld, fs_inst *inst, opcode op,
4592 const fs_reg &sample_mask)
4593 {
4594 const gen_device_info *devinfo = bld.shader->devinfo;
4595
4596 /* Get the logical send arguments. */
4597 const fs_reg &addr = inst->src[0];
4598 const fs_reg &src = inst->src[1];
4599 const fs_reg &surface = inst->src[2];
4600 const UNUSED fs_reg &dims = inst->src[3];
4601 const fs_reg &arg = inst->src[4];
4602
4603 /* Calculate the total number of components of the payload. */
4604 const unsigned addr_sz = inst->components_read(0);
4605 const unsigned src_sz = inst->components_read(1);
4606 /* From the BDW PRM Volume 7, page 147:
4607 *
4608 * "For the Data Cache Data Port*, the header must be present for the
4609 * following message types: [...] Typed read/write/atomics"
4610 *
4611 * Earlier generations have a similar wording. Because of this restriction
4612 * we don't attempt to implement sample masks via predication for such
4613 * messages prior to Gen9, since we have to provide a header anyway. On
4614 * Gen11+ the header has been removed so we can only use predication.
4615 */
4616 const unsigned header_sz = devinfo->gen < 9 &&
4617 (op == SHADER_OPCODE_TYPED_SURFACE_READ ||
4618 op == SHADER_OPCODE_TYPED_SURFACE_WRITE ||
4619 op == SHADER_OPCODE_TYPED_ATOMIC) ? 1 : 0;
4620 const unsigned sz = header_sz + addr_sz + src_sz;
4621
4622 /* Allocate space for the payload. */
4623 fs_reg *const components = new fs_reg[sz];
4624 const fs_reg payload = bld.vgrf(BRW_REGISTER_TYPE_UD, sz);
4625 unsigned n = 0;
4626
4627 /* Construct the payload. */
4628 if (header_sz)
4629 components[n++] = emit_surface_header(bld, sample_mask);
4630
4631 for (unsigned i = 0; i < addr_sz; i++)
4632 components[n++] = offset(addr, bld, i);
4633
4634 for (unsigned i = 0; i < src_sz; i++)
4635 components[n++] = offset(src, bld, i);
4636
4637 bld.LOAD_PAYLOAD(payload, components, sz, header_sz);
4638
4639 /* Predicate the instruction on the sample mask if no header is
4640 * provided.
4641 */
4642 if (!header_sz && sample_mask.file != BAD_FILE &&
4643 sample_mask.file != IMM) {
4644 const fs_builder ubld = bld.group(1, 0).exec_all();
4645 if (inst->predicate) {
4646 assert(inst->predicate == BRW_PREDICATE_NORMAL);
4647 assert(!inst->predicate_inverse);
4648 assert(inst->flag_subreg < 2);
4649 /* Combine the sample mask with the existing predicate by using a
4650 * vertical predication mode.
4651 */
4652 inst->predicate = BRW_PREDICATE_ALIGN1_ALLV;
4653 ubld.MOV(retype(brw_flag_subreg(inst->flag_subreg + 2),
4654 sample_mask.type),
4655 sample_mask);
4656 } else {
4657 inst->flag_subreg = 2;
4658 inst->predicate = BRW_PREDICATE_NORMAL;
4659 inst->predicate_inverse = false;
4660 ubld.MOV(retype(brw_flag_subreg(inst->flag_subreg), sample_mask.type),
4661 sample_mask);
4662 }
4663 }
4664
4665 /* Update the original instruction. */
4666 inst->opcode = op;
4667 inst->mlen = header_sz + (addr_sz + src_sz) * inst->exec_size / 8;
4668 inst->header_size = header_sz;
4669
4670 inst->src[0] = payload;
4671 inst->src[1] = surface;
4672 inst->src[2] = arg;
4673 inst->resize_sources(3);
4674
4675 delete[] components;
4676 }
4677
4678 static void
4679 lower_varying_pull_constant_logical_send(const fs_builder &bld, fs_inst *inst)
4680 {
4681 const gen_device_info *devinfo = bld.shader->devinfo;
4682
4683 if (devinfo->gen >= 7) {
4684 /* We are switching the instruction from an ALU-like instruction to a
4685 * send-from-grf instruction. Since sends can't handle strides or
4686 * source modifiers, we have to make a copy of the offset source.
4687 */
4688 fs_reg tmp = bld.vgrf(BRW_REGISTER_TYPE_UD);
4689 bld.MOV(tmp, inst->src[1]);
4690 inst->src[1] = tmp;
4691
4692 inst->opcode = FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_GEN7;
4693
4694 } else {
4695 const fs_reg payload(MRF, FIRST_PULL_LOAD_MRF(devinfo->gen),
4696 BRW_REGISTER_TYPE_UD);
4697
4698 bld.MOV(byte_offset(payload, REG_SIZE), inst->src[1]);
4699
4700 inst->opcode = FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_GEN4;
4701 inst->resize_sources(1);
4702 inst->base_mrf = payload.nr;
4703 inst->header_size = 1;
4704 inst->mlen = 1 + inst->exec_size / 8;
4705 }
4706 }
4707
4708 static void
4709 lower_math_logical_send(const fs_builder &bld, fs_inst *inst)
4710 {
4711 assert(bld.shader->devinfo->gen < 6);
4712
4713 inst->base_mrf = 2;
4714 inst->mlen = inst->sources * inst->exec_size / 8;
4715
4716 if (inst->sources > 1) {
4717 /* From the Ironlake PRM, Volume 4, Part 1, Section 6.1.13
4718 * "Message Payload":
4719 *
4720 * "Operand0[7]. For the INT DIV functions, this operand is the
4721 * denominator."
4722 * ...
4723 * "Operand1[7]. For the INT DIV functions, this operand is the
4724 * numerator."
4725 */
4726 const bool is_int_div = inst->opcode != SHADER_OPCODE_POW;
4727 const fs_reg src0 = is_int_div ? inst->src[1] : inst->src[0];
4728 const fs_reg src1 = is_int_div ? inst->src[0] : inst->src[1];
4729
4730 inst->resize_sources(1);
4731 inst->src[0] = src0;
4732
4733 assert(inst->exec_size == 8);
4734 bld.MOV(fs_reg(MRF, inst->base_mrf + 1, src1.type), src1);
4735 }
4736 }
4737
4738 bool
4739 fs_visitor::lower_logical_sends()
4740 {
4741 bool progress = false;
4742
4743 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
4744 const fs_builder ibld(this, block, inst);
4745
4746 switch (inst->opcode) {
4747 case FS_OPCODE_FB_WRITE_LOGICAL:
4748 assert(stage == MESA_SHADER_FRAGMENT);
4749 lower_fb_write_logical_send(ibld, inst,
4750 brw_wm_prog_data(prog_data),
4751 (const brw_wm_prog_key *)key,
4752 payload);
4753 break;
4754
4755 case FS_OPCODE_FB_READ_LOGICAL:
4756 lower_fb_read_logical_send(ibld, inst);
4757 break;
4758
4759 case SHADER_OPCODE_TEX_LOGICAL:
4760 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TEX);
4761 break;
4762
4763 case SHADER_OPCODE_TXD_LOGICAL:
4764 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXD);
4765 break;
4766
4767 case SHADER_OPCODE_TXF_LOGICAL:
4768 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXF);
4769 break;
4770
4771 case SHADER_OPCODE_TXL_LOGICAL:
4772 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXL);
4773 break;
4774
4775 case SHADER_OPCODE_TXS_LOGICAL:
4776 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXS);
4777 break;
4778
4779 case FS_OPCODE_TXB_LOGICAL:
4780 lower_sampler_logical_send(ibld, inst, FS_OPCODE_TXB);
4781 break;
4782
4783 case SHADER_OPCODE_TXF_CMS_LOGICAL:
4784 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXF_CMS);
4785 break;
4786
4787 case SHADER_OPCODE_TXF_CMS_W_LOGICAL:
4788 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXF_CMS_W);
4789 break;
4790
4791 case SHADER_OPCODE_TXF_UMS_LOGICAL:
4792 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXF_UMS);
4793 break;
4794
4795 case SHADER_OPCODE_TXF_MCS_LOGICAL:
4796 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXF_MCS);
4797 break;
4798
4799 case SHADER_OPCODE_LOD_LOGICAL:
4800 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_LOD);
4801 break;
4802
4803 case SHADER_OPCODE_TG4_LOGICAL:
4804 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TG4);
4805 break;
4806
4807 case SHADER_OPCODE_TG4_OFFSET_LOGICAL:
4808 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TG4_OFFSET);
4809 break;
4810
4811 case SHADER_OPCODE_SAMPLEINFO_LOGICAL:
4812 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_SAMPLEINFO);
4813 break;
4814
4815 case SHADER_OPCODE_UNTYPED_SURFACE_READ_LOGICAL:
4816 lower_surface_logical_send(ibld, inst,
4817 SHADER_OPCODE_UNTYPED_SURFACE_READ,
4818 fs_reg());
4819 break;
4820
4821 case SHADER_OPCODE_UNTYPED_SURFACE_WRITE_LOGICAL:
4822 lower_surface_logical_send(ibld, inst,
4823 SHADER_OPCODE_UNTYPED_SURFACE_WRITE,
4824 ibld.sample_mask_reg());
4825 break;
4826
4827 case SHADER_OPCODE_BYTE_SCATTERED_READ_LOGICAL:
4828 lower_surface_logical_send(ibld, inst,
4829 SHADER_OPCODE_BYTE_SCATTERED_READ,
4830 fs_reg());
4831 break;
4832
4833 case SHADER_OPCODE_BYTE_SCATTERED_WRITE_LOGICAL:
4834 lower_surface_logical_send(ibld, inst,
4835 SHADER_OPCODE_BYTE_SCATTERED_WRITE,
4836 ibld.sample_mask_reg());
4837 break;
4838
4839 case SHADER_OPCODE_UNTYPED_ATOMIC_LOGICAL:
4840 lower_surface_logical_send(ibld, inst,
4841 SHADER_OPCODE_UNTYPED_ATOMIC,
4842 ibld.sample_mask_reg());
4843 break;
4844
4845 case SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL:
4846 lower_surface_logical_send(ibld, inst,
4847 SHADER_OPCODE_TYPED_SURFACE_READ,
4848 brw_imm_d(0xffff));
4849 break;
4850
4851 case SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL:
4852 lower_surface_logical_send(ibld, inst,
4853 SHADER_OPCODE_TYPED_SURFACE_WRITE,
4854 ibld.sample_mask_reg());
4855 break;
4856
4857 case SHADER_OPCODE_TYPED_ATOMIC_LOGICAL:
4858 lower_surface_logical_send(ibld, inst,
4859 SHADER_OPCODE_TYPED_ATOMIC,
4860 ibld.sample_mask_reg());
4861 break;
4862
4863 case FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_LOGICAL:
4864 lower_varying_pull_constant_logical_send(ibld, inst);
4865 break;
4866
4867 case SHADER_OPCODE_RCP:
4868 case SHADER_OPCODE_RSQ:
4869 case SHADER_OPCODE_SQRT:
4870 case SHADER_OPCODE_EXP2:
4871 case SHADER_OPCODE_LOG2:
4872 case SHADER_OPCODE_SIN:
4873 case SHADER_OPCODE_COS:
4874 case SHADER_OPCODE_POW:
4875 case SHADER_OPCODE_INT_QUOTIENT:
4876 case SHADER_OPCODE_INT_REMAINDER:
4877 /* The math opcodes are overloaded for the send-like and
4878 * expression-like instructions which seems kind of icky. Gen6+ has
4879 * a native (but rather quirky) MATH instruction so we don't need to
4880 * do anything here. On Gen4-5 we'll have to lower the Gen6-like
4881 * logical instructions (which we can easily recognize because they
4882 * have mlen = 0) into send-like virtual instructions.
4883 */
4884 if (devinfo->gen < 6 && inst->mlen == 0) {
4885 lower_math_logical_send(ibld, inst);
4886 break;
4887
4888 } else {
4889 continue;
4890 }
4891
4892 default:
4893 continue;
4894 }
4895
4896 progress = true;
4897 }
4898
4899 if (progress)
4900 invalidate_live_intervals();
4901
4902 return progress;
4903 }
4904
4905 /**
4906 * Get the closest allowed SIMD width for instruction \p inst accounting for
4907 * some common regioning and execution control restrictions that apply to FPU
4908 * instructions. These restrictions don't necessarily have any relevance to
4909 * instructions not executed by the FPU pipeline like extended math, control
4910 * flow or send message instructions.
4911 *
4912 * For virtual opcodes it's really up to the instruction -- In some cases
4913 * (e.g. where a virtual instruction unrolls into a simple sequence of FPU
4914 * instructions) it may simplify virtual instruction lowering if we can
4915 * enforce FPU-like regioning restrictions already on the virtual instruction,
4916 * in other cases (e.g. virtual send-like instructions) this may be
4917 * excessively restrictive.
4918 */
4919 static unsigned
4920 get_fpu_lowered_simd_width(const struct gen_device_info *devinfo,
4921 const fs_inst *inst)
4922 {
4923 /* Maximum execution size representable in the instruction controls. */
4924 unsigned max_width = MIN2(32, inst->exec_size);
4925
4926 /* According to the PRMs:
4927 * "A. In Direct Addressing mode, a source cannot span more than 2
4928 * adjacent GRF registers.
4929 * B. A destination cannot span more than 2 adjacent GRF registers."
4930 *
4931 * Look for the source or destination with the largest register region
4932 * which is the one that is going to limit the overall execution size of
4933 * the instruction due to this rule.
4934 */
4935 unsigned reg_count = DIV_ROUND_UP(inst->size_written, REG_SIZE);
4936
4937 for (unsigned i = 0; i < inst->sources; i++)
4938 reg_count = MAX2(reg_count, DIV_ROUND_UP(inst->size_read(i), REG_SIZE));
4939
4940 /* Calculate the maximum execution size of the instruction based on the
4941 * factor by which it goes over the hardware limit of 2 GRFs.
4942 */
4943 if (reg_count > 2)
4944 max_width = MIN2(max_width, inst->exec_size / DIV_ROUND_UP(reg_count, 2));
4945
4946 /* According to the IVB PRMs:
4947 * "When destination spans two registers, the source MUST span two
4948 * registers. The exception to the above rule:
4949 *
4950 * - When source is scalar, the source registers are not incremented.
4951 * - When source is packed integer Word and destination is packed
4952 * integer DWord, the source register is not incremented but the
4953 * source sub register is incremented."
4954 *
4955 * The hardware specs from Gen4 to Gen7.5 mention similar regioning
4956 * restrictions. The code below intentionally doesn't check whether the
4957 * destination type is integer because empirically the hardware doesn't
4958 * seem to care what the actual type is as long as it's dword-aligned.
4959 */
4960 if (devinfo->gen < 8) {
4961 for (unsigned i = 0; i < inst->sources; i++) {
4962 /* IVB implements DF scalars as <0;2,1> regions. */
4963 const bool is_scalar_exception = is_uniform(inst->src[i]) &&
4964 (devinfo->is_haswell || type_sz(inst->src[i].type) != 8);
4965 const bool is_packed_word_exception =
4966 type_sz(inst->dst.type) == 4 && inst->dst.stride == 1 &&
4967 type_sz(inst->src[i].type) == 2 && inst->src[i].stride == 1;
4968
4969 if (inst->size_written > REG_SIZE &&
4970 inst->size_read(i) != 0 && inst->size_read(i) <= REG_SIZE &&
4971 !is_scalar_exception && !is_packed_word_exception) {
4972 const unsigned reg_count = DIV_ROUND_UP(inst->size_written, REG_SIZE);
4973 max_width = MIN2(max_width, inst->exec_size / reg_count);
4974 }
4975 }
4976 }
4977
4978 /* From the IVB PRMs:
4979 * "When an instruction is SIMD32, the low 16 bits of the execution mask
4980 * are applied for both halves of the SIMD32 instruction. If different
4981 * execution mask channels are required, split the instruction into two
4982 * SIMD16 instructions."
4983 *
4984 * There is similar text in the HSW PRMs. Gen4-6 don't even implement
4985 * 32-wide control flow support in hardware and will behave similarly.
4986 */
4987 if (devinfo->gen < 8 && !inst->force_writemask_all)
4988 max_width = MIN2(max_width, 16);
4989
4990 /* From the IVB PRMs (applies to HSW too):
4991 * "Instructions with condition modifiers must not use SIMD32."
4992 *
4993 * From the BDW PRMs (applies to later hardware too):
4994 * "Ternary instruction with condition modifiers must not use SIMD32."
4995 */
4996 if (inst->conditional_mod && (devinfo->gen < 8 || inst->is_3src(devinfo)))
4997 max_width = MIN2(max_width, 16);
4998
4999 /* From the IVB PRMs (applies to other devices that don't have the
5000 * gen_device_info::supports_simd16_3src flag set):
5001 * "In Align16 access mode, SIMD16 is not allowed for DW operations and
5002 * SIMD8 is not allowed for DF operations."
5003 */
5004 if (inst->is_3src(devinfo) && !devinfo->supports_simd16_3src)
5005 max_width = MIN2(max_width, inst->exec_size / reg_count);
5006
5007 /* Pre-Gen8 EUs are hardwired to use the QtrCtrl+1 (where QtrCtrl is
5008 * the 8-bit quarter of the execution mask signals specified in the
5009 * instruction control fields) for the second compressed half of any
5010 * single-precision instruction (for double-precision instructions
5011 * it's hardwired to use NibCtrl+1, at least on HSW), which means that
5012 * the EU will apply the wrong execution controls for the second
5013 * sequential GRF write if the number of channels per GRF is not exactly
5014 * eight in single-precision mode (or four in double-float mode).
5015 *
5016 * In this situation we calculate the maximum size of the split
5017 * instructions so they only ever write to a single register.
5018 */
5019 if (devinfo->gen < 8 && inst->size_written > REG_SIZE &&
5020 !inst->force_writemask_all) {
5021 const unsigned channels_per_grf = inst->exec_size /
5022 DIV_ROUND_UP(inst->size_written, REG_SIZE);
5023 const unsigned exec_type_size = get_exec_type_size(inst);
5024 assert(exec_type_size);
5025
5026 /* The hardware shifts exactly 8 channels per compressed half of the
5027 * instruction in single-precision mode and exactly 4 in double-precision.
5028 */
5029 if (channels_per_grf != (exec_type_size == 8 ? 4 : 8))
5030 max_width = MIN2(max_width, channels_per_grf);
5031
5032 /* Lower all non-force_writemask_all DF instructions to SIMD4 on IVB/BYT
5033 * because HW applies the same channel enable signals to both halves of
5034 * the compressed instruction which will be just wrong under
5035 * non-uniform control flow.
5036 */
5037 if (devinfo->gen == 7 && !devinfo->is_haswell &&
5038 (exec_type_size == 8 || type_sz(inst->dst.type) == 8))
5039 max_width = MIN2(max_width, 4);
5040 }
5041
5042 /* Only power-of-two execution sizes are representable in the instruction
5043 * control fields.
5044 */
5045 return 1 << _mesa_logbase2(max_width);
5046 }
5047
5048 /**
5049 * Get the maximum allowed SIMD width for instruction \p inst accounting for
5050 * various payload size restrictions that apply to sampler message
5051 * instructions.
5052 *
5053 * This is only intended to provide a maximum theoretical bound for the
5054 * execution size of the message based on the number of argument components
5055 * alone, which in most cases will determine whether the SIMD8 or SIMD16
5056 * variant of the message can be used, though some messages may have
5057 * additional restrictions not accounted for here (e.g. pre-ILK hardware uses
5058 * the message length to determine the exact SIMD width and argument count,
5059 * which makes a number of sampler message combinations impossible to
5060 * represent).
5061 */
5062 static unsigned
5063 get_sampler_lowered_simd_width(const struct gen_device_info *devinfo,
5064 const fs_inst *inst)
5065 {
5066 /* Calculate the number of coordinate components that have to be present
5067 * assuming that additional arguments follow the texel coordinates in the
5068 * message payload. On IVB+ there is no need for padding, on ILK-SNB we
5069 * need to pad to four or three components depending on the message,
5070 * pre-ILK we need to pad to at most three components.
5071 */
5072 const unsigned req_coord_components =
5073 (devinfo->gen >= 7 ||
5074 !inst->components_read(TEX_LOGICAL_SRC_COORDINATE)) ? 0 :
5075 (devinfo->gen >= 5 && inst->opcode != SHADER_OPCODE_TXF_LOGICAL &&
5076 inst->opcode != SHADER_OPCODE_TXF_CMS_LOGICAL) ? 4 :
5077 3;
5078
5079 /* On Gen9+ the LOD argument is for free if we're able to use the LZ
5080 * variant of the TXL or TXF message.
5081 */
5082 const bool implicit_lod = devinfo->gen >= 9 &&
5083 (inst->opcode == SHADER_OPCODE_TXL ||
5084 inst->opcode == SHADER_OPCODE_TXF) &&
5085 inst->src[TEX_LOGICAL_SRC_LOD].is_zero();
5086
5087 /* Calculate the total number of argument components that need to be passed
5088 * to the sampler unit.
5089 */
5090 const unsigned num_payload_components =
5091 MAX2(inst->components_read(TEX_LOGICAL_SRC_COORDINATE),
5092 req_coord_components) +
5093 inst->components_read(TEX_LOGICAL_SRC_SHADOW_C) +
5094 (implicit_lod ? 0 : inst->components_read(TEX_LOGICAL_SRC_LOD)) +
5095 inst->components_read(TEX_LOGICAL_SRC_LOD2) +
5096 inst->components_read(TEX_LOGICAL_SRC_SAMPLE_INDEX) +
5097 (inst->opcode == SHADER_OPCODE_TG4_OFFSET_LOGICAL ?
5098 inst->components_read(TEX_LOGICAL_SRC_TG4_OFFSET) : 0) +
5099 inst->components_read(TEX_LOGICAL_SRC_MCS);
5100
5101 /* SIMD16 messages with more than five arguments exceed the maximum message
5102 * size supported by the sampler, regardless of whether a header is
5103 * provided or not.
5104 */
5105 return MIN2(inst->exec_size,
5106 num_payload_components > MAX_SAMPLER_MESSAGE_SIZE / 2 ? 8 : 16);
5107 }
5108
5109 /**
5110 * Get the closest native SIMD width supported by the hardware for instruction
5111 * \p inst. The instruction will be left untouched by
5112 * fs_visitor::lower_simd_width() if the returned value is equal to the
5113 * original execution size.
5114 */
5115 static unsigned
5116 get_lowered_simd_width(const struct gen_device_info *devinfo,
5117 const fs_inst *inst)
5118 {
5119 switch (inst->opcode) {
5120 case BRW_OPCODE_MOV:
5121 case BRW_OPCODE_SEL:
5122 case BRW_OPCODE_NOT:
5123 case BRW_OPCODE_AND:
5124 case BRW_OPCODE_OR:
5125 case BRW_OPCODE_XOR:
5126 case BRW_OPCODE_SHR:
5127 case BRW_OPCODE_SHL:
5128 case BRW_OPCODE_ASR:
5129 case BRW_OPCODE_CMPN:
5130 case BRW_OPCODE_CSEL:
5131 case BRW_OPCODE_F32TO16:
5132 case BRW_OPCODE_F16TO32:
5133 case BRW_OPCODE_BFREV:
5134 case BRW_OPCODE_BFE:
5135 case BRW_OPCODE_ADD:
5136 case BRW_OPCODE_MUL:
5137 case BRW_OPCODE_AVG:
5138 case BRW_OPCODE_FRC:
5139 case BRW_OPCODE_RNDU:
5140 case BRW_OPCODE_RNDD:
5141 case BRW_OPCODE_RNDE:
5142 case BRW_OPCODE_RNDZ:
5143 case BRW_OPCODE_LZD:
5144 case BRW_OPCODE_FBH:
5145 case BRW_OPCODE_FBL:
5146 case BRW_OPCODE_CBIT:
5147 case BRW_OPCODE_SAD2:
5148 case BRW_OPCODE_MAD:
5149 case BRW_OPCODE_LRP:
5150 case FS_OPCODE_PACK:
5151 case SHADER_OPCODE_SEL_EXEC:
5152 case SHADER_OPCODE_CLUSTER_BROADCAST:
5153 return get_fpu_lowered_simd_width(devinfo, inst);
5154
5155 case BRW_OPCODE_CMP: {
5156 /* The Ivybridge/BayTrail WaCMPInstFlagDepClearedEarly workaround says that
5157 * when the destination is a GRF the dependency-clear bit on the flag
5158 * register is cleared early.
5159 *
5160 * Suggested workarounds are to disable coissuing CMP instructions
5161 * or to split CMP(16) instructions into two CMP(8) instructions.
5162 *
5163 * We choose to split into CMP(8) instructions since disabling
5164 * coissuing would affect CMP instructions not otherwise affected by
5165 * the errata.
5166 */
5167 const unsigned max_width = (devinfo->gen == 7 && !devinfo->is_haswell &&
5168 !inst->dst.is_null() ? 8 : ~0);
5169 return MIN2(max_width, get_fpu_lowered_simd_width(devinfo, inst));
5170 }
5171 case BRW_OPCODE_BFI1:
5172 case BRW_OPCODE_BFI2:
5173 /* The Haswell WaForceSIMD8ForBFIInstruction workaround says that we
5174 * should
5175 * "Force BFI instructions to be executed always in SIMD8."
5176 */
5177 return MIN2(devinfo->is_haswell ? 8 : ~0u,
5178 get_fpu_lowered_simd_width(devinfo, inst));
5179
5180 case BRW_OPCODE_IF:
5181 assert(inst->src[0].file == BAD_FILE || inst->exec_size <= 16);
5182 return inst->exec_size;
5183
5184 case SHADER_OPCODE_RCP:
5185 case SHADER_OPCODE_RSQ:
5186 case SHADER_OPCODE_SQRT:
5187 case SHADER_OPCODE_EXP2:
5188 case SHADER_OPCODE_LOG2:
5189 case SHADER_OPCODE_SIN:
5190 case SHADER_OPCODE_COS:
5191 /* Unary extended math instructions are limited to SIMD8 on Gen4 and
5192 * Gen6.
5193 */
5194 return (devinfo->gen >= 7 ? MIN2(16, inst->exec_size) :
5195 devinfo->gen == 5 || devinfo->is_g4x ? MIN2(16, inst->exec_size) :
5196 MIN2(8, inst->exec_size));
5197
5198 case SHADER_OPCODE_POW:
5199 /* SIMD16 is only allowed on Gen7+. */
5200 return (devinfo->gen >= 7 ? MIN2(16, inst->exec_size) :
5201 MIN2(8, inst->exec_size));
5202
5203 case SHADER_OPCODE_INT_QUOTIENT:
5204 case SHADER_OPCODE_INT_REMAINDER:
5205 /* Integer division is limited to SIMD8 on all generations. */
5206 return MIN2(8, inst->exec_size);
5207
5208 case FS_OPCODE_LINTERP:
5209 case SHADER_OPCODE_GET_BUFFER_SIZE:
5210 case FS_OPCODE_DDX_COARSE:
5211 case FS_OPCODE_DDX_FINE:
5212 case FS_OPCODE_DDY_COARSE:
5213 case FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD:
5214 case FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_GEN7:
5215 case FS_OPCODE_PACK_HALF_2x16_SPLIT:
5216 case FS_OPCODE_UNPACK_HALF_2x16_SPLIT_X:
5217 case FS_OPCODE_UNPACK_HALF_2x16_SPLIT_Y:
5218 case FS_OPCODE_INTERPOLATE_AT_SAMPLE:
5219 case FS_OPCODE_INTERPOLATE_AT_SHARED_OFFSET:
5220 case FS_OPCODE_INTERPOLATE_AT_PER_SLOT_OFFSET:
5221 return MIN2(16, inst->exec_size);
5222
5223 case FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_LOGICAL:
5224 /* Pre-ILK hardware doesn't have a SIMD8 variant of the texel fetch
5225 * message used to implement varying pull constant loads, so expand it
5226 * to SIMD16. An alternative with longer message payload length but
5227 * shorter return payload would be to use the SIMD8 sampler message that
5228 * takes (header, u, v, r) as parameters instead of (header, u).
5229 */
5230 return (devinfo->gen == 4 ? 16 : MIN2(16, inst->exec_size));
5231
5232 case FS_OPCODE_DDY_FINE:
5233 /* The implementation of this virtual opcode may require emitting
5234 * compressed Align16 instructions, which are severely limited on some
5235 * generations.
5236 *
5237 * From the Ivy Bridge PRM, volume 4 part 3, section 3.3.9 (Register
5238 * Region Restrictions):
5239 *
5240 * "In Align16 access mode, SIMD16 is not allowed for DW operations
5241 * and SIMD8 is not allowed for DF operations."
5242 *
5243 * In this context, "DW operations" means "operations acting on 32-bit
5244 * values", so it includes operations on floats.
5245 *
5246 * Gen4 has a similar restriction. From the i965 PRM, section 11.5.3
5247 * (Instruction Compression -> Rules and Restrictions):
5248 *
5249 * "A compressed instruction must be in Align1 access mode. Align16
5250 * mode instructions cannot be compressed."
5251 *
5252 * Similar text exists in the g45 PRM.
5253 *
5254 * Empirically, compressed align16 instructions using odd register
5255 * numbers don't appear to work on Sandybridge either.
5256 */
5257 return (devinfo->gen == 4 || devinfo->gen == 6 ||
5258 (devinfo->gen == 7 && !devinfo->is_haswell) ?
5259 MIN2(8, inst->exec_size) : MIN2(16, inst->exec_size));
5260
5261 case SHADER_OPCODE_MULH:
5262 /* MULH is lowered to the MUL/MACH sequence using the accumulator, which
5263 * is 8-wide on Gen7+.
5264 */
5265 return (devinfo->gen >= 7 ? 8 :
5266 get_fpu_lowered_simd_width(devinfo, inst));
5267
5268 case FS_OPCODE_FB_WRITE_LOGICAL:
5269 /* Gen6 doesn't support SIMD16 depth writes but we cannot handle them
5270 * here.
5271 */
5272 assert(devinfo->gen != 6 ||
5273 inst->src[FB_WRITE_LOGICAL_SRC_SRC_DEPTH].file == BAD_FILE ||
5274 inst->exec_size == 8);
5275 /* Dual-source FB writes are unsupported in SIMD16 mode. */
5276 return (inst->src[FB_WRITE_LOGICAL_SRC_COLOR1].file != BAD_FILE ?
5277 8 : MIN2(16, inst->exec_size));
5278
5279 case FS_OPCODE_FB_READ_LOGICAL:
5280 return MIN2(16, inst->exec_size);
5281
5282 case SHADER_OPCODE_TEX_LOGICAL:
5283 case SHADER_OPCODE_TXF_CMS_LOGICAL:
5284 case SHADER_OPCODE_TXF_UMS_LOGICAL:
5285 case SHADER_OPCODE_TXF_MCS_LOGICAL:
5286 case SHADER_OPCODE_LOD_LOGICAL:
5287 case SHADER_OPCODE_TG4_LOGICAL:
5288 case SHADER_OPCODE_SAMPLEINFO_LOGICAL:
5289 case SHADER_OPCODE_TXF_CMS_W_LOGICAL:
5290 case SHADER_OPCODE_TG4_OFFSET_LOGICAL:
5291 return get_sampler_lowered_simd_width(devinfo, inst);
5292
5293 case SHADER_OPCODE_TXD_LOGICAL:
5294 /* TXD is unsupported in SIMD16 mode. */
5295 return 8;
5296
5297 case SHADER_OPCODE_TXL_LOGICAL:
5298 case FS_OPCODE_TXB_LOGICAL:
5299 /* Only one execution size is representable pre-ILK depending on whether
5300 * the shadow reference argument is present.
5301 */
5302 if (devinfo->gen == 4)
5303 return inst->src[TEX_LOGICAL_SRC_SHADOW_C].file == BAD_FILE ? 16 : 8;
5304 else
5305 return get_sampler_lowered_simd_width(devinfo, inst);
5306
5307 case SHADER_OPCODE_TXF_LOGICAL:
5308 case SHADER_OPCODE_TXS_LOGICAL:
5309 /* Gen4 doesn't have SIMD8 variants for the RESINFO and LD-with-LOD
5310 * messages. Use SIMD16 instead.
5311 */
5312 if (devinfo->gen == 4)
5313 return 16;
5314 else
5315 return get_sampler_lowered_simd_width(devinfo, inst);
5316
5317 case SHADER_OPCODE_TYPED_ATOMIC_LOGICAL:
5318 case SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL:
5319 case SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL:
5320 return 8;
5321
5322 case SHADER_OPCODE_UNTYPED_ATOMIC_LOGICAL:
5323 case SHADER_OPCODE_UNTYPED_SURFACE_READ_LOGICAL:
5324 case SHADER_OPCODE_UNTYPED_SURFACE_WRITE_LOGICAL:
5325 case SHADER_OPCODE_BYTE_SCATTERED_WRITE_LOGICAL:
5326 case SHADER_OPCODE_BYTE_SCATTERED_READ_LOGICAL:
5327 return MIN2(16, inst->exec_size);
5328
5329 case SHADER_OPCODE_URB_READ_SIMD8:
5330 case SHADER_OPCODE_URB_READ_SIMD8_PER_SLOT:
5331 case SHADER_OPCODE_URB_WRITE_SIMD8:
5332 case SHADER_OPCODE_URB_WRITE_SIMD8_PER_SLOT:
5333 case SHADER_OPCODE_URB_WRITE_SIMD8_MASKED:
5334 case SHADER_OPCODE_URB_WRITE_SIMD8_MASKED_PER_SLOT:
5335 return MIN2(8, inst->exec_size);
5336
5337 case SHADER_OPCODE_QUAD_SWIZZLE:
5338 return 8;
5339
5340 case SHADER_OPCODE_MOV_INDIRECT: {
5341 /* From IVB and HSW PRMs:
5342 *
5343 * "2.When the destination requires two registers and the sources are
5344 * indirect, the sources must use 1x1 regioning mode.
5345 *
5346 * In case of DF instructions in HSW/IVB, the exec_size is limited by
5347 * the EU decompression logic not handling VxH indirect addressing
5348 * correctly.
5349 */
5350 const unsigned max_size = (devinfo->gen >= 8 ? 2 : 1) * REG_SIZE;
5351 /* Prior to Broadwell, we only have 8 address subregisters. */
5352 return MIN3(devinfo->gen >= 8 ? 16 : 8,
5353 max_size / (inst->dst.stride * type_sz(inst->dst.type)),
5354 inst->exec_size);
5355 }
5356
5357 case SHADER_OPCODE_LOAD_PAYLOAD: {
5358 const unsigned reg_count =
5359 DIV_ROUND_UP(inst->dst.component_size(inst->exec_size), REG_SIZE);
5360
5361 if (reg_count > 2) {
5362 /* Only LOAD_PAYLOAD instructions with per-channel destination region
5363 * can be easily lowered (which excludes headers and heterogeneous
5364 * types).
5365 */
5366 assert(!inst->header_size);
5367 for (unsigned i = 0; i < inst->sources; i++)
5368 assert(type_sz(inst->dst.type) == type_sz(inst->src[i].type) ||
5369 inst->src[i].file == BAD_FILE);
5370
5371 return inst->exec_size / DIV_ROUND_UP(reg_count, 2);
5372 } else {
5373 return inst->exec_size;
5374 }
5375 }
5376 default:
5377 return inst->exec_size;
5378 }
5379 }
5380
5381 /**
5382 * Return true if splitting out the group of channels of instruction \p inst
5383 * given by lbld.group() requires allocating a temporary for the i-th source
5384 * of the lowered instruction.
5385 */
5386 static inline bool
5387 needs_src_copy(const fs_builder &lbld, const fs_inst *inst, unsigned i)
5388 {
5389 return !(is_periodic(inst->src[i], lbld.dispatch_width()) ||
5390 (inst->components_read(i) == 1 &&
5391 lbld.dispatch_width() <= inst->exec_size)) ||
5392 (inst->flags_written() &
5393 flag_mask(inst->src[i], type_sz(inst->src[i].type)));
5394 }
5395
5396 /**
5397 * Extract the data that would be consumed by the channel group given by
5398 * lbld.group() from the i-th source region of instruction \p inst and return
5399 * it as result in packed form.
5400 */
5401 static fs_reg
5402 emit_unzip(const fs_builder &lbld, fs_inst *inst, unsigned i)
5403 {
5404 /* Specified channel group from the source region. */
5405 const fs_reg src = horiz_offset(inst->src[i], lbld.group());
5406
5407 if (needs_src_copy(lbld, inst, i)) {
5408 /* Builder of the right width to perform the copy avoiding uninitialized
5409 * data if the lowered execution size is greater than the original
5410 * execution size of the instruction.
5411 */
5412 const fs_builder cbld = lbld.group(MIN2(lbld.dispatch_width(),
5413 inst->exec_size), 0);
5414 const fs_reg tmp = lbld.vgrf(inst->src[i].type, inst->components_read(i));
5415
5416 for (unsigned k = 0; k < inst->components_read(i); ++k)
5417 cbld.MOV(offset(tmp, lbld, k), offset(src, inst->exec_size, k));
5418
5419 return tmp;
5420
5421 } else if (is_periodic(inst->src[i], lbld.dispatch_width())) {
5422 /* The source is invariant for all dispatch_width-wide groups of the
5423 * original region.
5424 */
5425 return inst->src[i];
5426
5427 } else {
5428 /* We can just point the lowered instruction at the right channel group
5429 * from the original region.
5430 */
5431 return src;
5432 }
5433 }
5434
5435 /**
5436 * Return true if splitting out the group of channels of instruction \p inst
5437 * given by lbld.group() requires allocating a temporary for the destination
5438 * of the lowered instruction and copying the data back to the original
5439 * destination region.
5440 */
5441 static inline bool
5442 needs_dst_copy(const fs_builder &lbld, const fs_inst *inst)
5443 {
5444 /* If the instruction writes more than one component we'll have to shuffle
5445 * the results of multiple lowered instructions in order to make sure that
5446 * they end up arranged correctly in the original destination region.
5447 */
5448 if (inst->size_written > inst->dst.component_size(inst->exec_size))
5449 return true;
5450
5451 /* If the lowered execution size is larger than the original the result of
5452 * the instruction won't fit in the original destination, so we'll have to
5453 * allocate a temporary in any case.
5454 */
5455 if (lbld.dispatch_width() > inst->exec_size)
5456 return true;
5457
5458 for (unsigned i = 0; i < inst->sources; i++) {
5459 /* If we already made a copy of the source for other reasons there won't
5460 * be any overlap with the destination.
5461 */
5462 if (needs_src_copy(lbld, inst, i))
5463 continue;
5464
5465 /* In order to keep the logic simple we emit a copy whenever the
5466 * destination region doesn't exactly match an overlapping source, which
5467 * may point at the source and destination not being aligned group by
5468 * group which could cause one of the lowered instructions to overwrite
5469 * the data read from the same source by other lowered instructions.
5470 */
5471 if (regions_overlap(inst->dst, inst->size_written,
5472 inst->src[i], inst->size_read(i)) &&
5473 !inst->dst.equals(inst->src[i]))
5474 return true;
5475 }
5476
5477 return false;
5478 }
5479
5480 /**
5481 * Insert data from a packed temporary into the channel group given by
5482 * lbld.group() of the destination region of instruction \p inst and return
5483 * the temporary as result. Any copy instructions that are required for
5484 * unzipping the previous value (in the case of partial writes) will be
5485 * inserted using \p lbld_before and any copy instructions required for
5486 * zipping up the destination of \p inst will be inserted using \p lbld_after.
5487 */
5488 static fs_reg
5489 emit_zip(const fs_builder &lbld_before, const fs_builder &lbld_after,
5490 fs_inst *inst)
5491 {
5492 assert(lbld_before.dispatch_width() == lbld_after.dispatch_width());
5493 assert(lbld_before.group() == lbld_after.group());
5494
5495 /* Specified channel group from the destination region. */
5496 const fs_reg dst = horiz_offset(inst->dst, lbld_after.group());
5497 const unsigned dst_size = inst->size_written /
5498 inst->dst.component_size(inst->exec_size);
5499
5500 if (needs_dst_copy(lbld_after, inst)) {
5501 const fs_reg tmp = lbld_after.vgrf(inst->dst.type, dst_size);
5502
5503 if (inst->predicate) {
5504 /* Handle predication by copying the original contents of
5505 * the destination into the temporary before emitting the
5506 * lowered instruction.
5507 */
5508 const fs_builder gbld_before =
5509 lbld_before.group(MIN2(lbld_before.dispatch_width(),
5510 inst->exec_size), 0);
5511 for (unsigned k = 0; k < dst_size; ++k) {
5512 gbld_before.MOV(offset(tmp, lbld_before, k),
5513 offset(dst, inst->exec_size, k));
5514 }
5515 }
5516
5517 const fs_builder gbld_after =
5518 lbld_after.group(MIN2(lbld_after.dispatch_width(),
5519 inst->exec_size), 0);
5520 for (unsigned k = 0; k < dst_size; ++k) {
5521 /* Use a builder of the right width to perform the copy avoiding
5522 * uninitialized data if the lowered execution size is greater than
5523 * the original execution size of the instruction.
5524 */
5525 gbld_after.MOV(offset(dst, inst->exec_size, k),
5526 offset(tmp, lbld_after, k));
5527 }
5528
5529 return tmp;
5530
5531 } else {
5532 /* No need to allocate a temporary for the lowered instruction, just
5533 * take the right group of channels from the original region.
5534 */
5535 return dst;
5536 }
5537 }
5538
5539 bool
5540 fs_visitor::lower_simd_width()
5541 {
5542 bool progress = false;
5543
5544 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
5545 const unsigned lower_width = get_lowered_simd_width(devinfo, inst);
5546
5547 if (lower_width != inst->exec_size) {
5548 /* Builder matching the original instruction. We may also need to
5549 * emit an instruction of width larger than the original, set the
5550 * execution size of the builder to the highest of both for now so
5551 * we're sure that both cases can be handled.
5552 */
5553 const unsigned max_width = MAX2(inst->exec_size, lower_width);
5554 const fs_builder ibld = bld.at(block, inst)
5555 .exec_all(inst->force_writemask_all)
5556 .group(max_width, inst->group / max_width);
5557
5558 /* Split the copies in chunks of the execution width of either the
5559 * original or the lowered instruction, whichever is lower.
5560 */
5561 const unsigned n = DIV_ROUND_UP(inst->exec_size, lower_width);
5562 const unsigned dst_size = inst->size_written /
5563 inst->dst.component_size(inst->exec_size);
5564
5565 assert(!inst->writes_accumulator && !inst->mlen);
5566
5567 /* Inserting the zip, unzip, and duplicated instructions in all of
5568 * the right spots is somewhat tricky. All of the unzip and any
5569 * instructions from the zip which unzip the destination prior to
5570 * writing need to happen before all of the per-group instructions
5571 * and the zip instructions need to happen after. In order to sort
5572 * this all out, we insert the unzip instructions before \p inst,
5573 * insert the per-group instructions after \p inst (i.e. before
5574 * inst->next), and insert the zip instructions before the
5575 * instruction after \p inst. Since we are inserting instructions
5576 * after \p inst, inst->next is a moving target and we need to save
5577 * it off here so that we insert the zip instructions in the right
5578 * place.
5579 */
5580 exec_node *const after_inst = inst->next;
5581 for (unsigned i = 0; i < n; i++) {
5582 /* Emit a copy of the original instruction with the lowered width.
5583 * If the EOT flag was set throw it away except for the last
5584 * instruction to avoid killing the thread prematurely.
5585 */
5586 fs_inst split_inst = *inst;
5587 split_inst.exec_size = lower_width;
5588 split_inst.eot = inst->eot && i == 0;
5589
5590 /* Select the correct channel enables for the i-th group, then
5591 * transform the sources and destination and emit the lowered
5592 * instruction.
5593 */
5594 const fs_builder lbld = ibld.group(lower_width, i);
5595
5596 for (unsigned j = 0; j < inst->sources; j++)
5597 split_inst.src[j] = emit_unzip(lbld.at(block, inst), inst, j);
5598
5599 split_inst.dst = emit_zip(lbld.at(block, inst),
5600 lbld.at(block, after_inst), inst);
5601 split_inst.size_written =
5602 split_inst.dst.component_size(lower_width) * dst_size;
5603
5604 lbld.at(block, inst->next).emit(split_inst);
5605 }
5606
5607 inst->remove(block);
5608 progress = true;
5609 }
5610 }
5611
5612 if (progress)
5613 invalidate_live_intervals();
5614
5615 return progress;
5616 }
5617
5618 void
5619 fs_visitor::dump_instructions()
5620 {
5621 dump_instructions(NULL);
5622 }
5623
5624 void
5625 fs_visitor::dump_instructions(const char *name)
5626 {
5627 FILE *file = stderr;
5628 if (name && geteuid() != 0) {
5629 file = fopen(name, "w");
5630 if (!file)
5631 file = stderr;
5632 }
5633
5634 if (cfg) {
5635 calculate_register_pressure();
5636 int ip = 0, max_pressure = 0;
5637 foreach_block_and_inst(block, backend_instruction, inst, cfg) {
5638 max_pressure = MAX2(max_pressure, regs_live_at_ip[ip]);
5639 fprintf(file, "{%3d} %4d: ", regs_live_at_ip[ip], ip);
5640 dump_instruction(inst, file);
5641 ip++;
5642 }
5643 fprintf(file, "Maximum %3d registers live at once.\n", max_pressure);
5644 } else {
5645 int ip = 0;
5646 foreach_in_list(backend_instruction, inst, &instructions) {
5647 fprintf(file, "%4d: ", ip++);
5648 dump_instruction(inst, file);
5649 }
5650 }
5651
5652 if (file != stderr) {
5653 fclose(file);
5654 }
5655 }
5656
5657 void
5658 fs_visitor::dump_instruction(backend_instruction *be_inst)
5659 {
5660 dump_instruction(be_inst, stderr);
5661 }
5662
5663 void
5664 fs_visitor::dump_instruction(backend_instruction *be_inst, FILE *file)
5665 {
5666 fs_inst *inst = (fs_inst *)be_inst;
5667
5668 if (inst->predicate) {
5669 fprintf(file, "(%cf%d.%d) ",
5670 inst->predicate_inverse ? '-' : '+',
5671 inst->flag_subreg / 2,
5672 inst->flag_subreg % 2);
5673 }
5674
5675 fprintf(file, "%s", brw_instruction_name(devinfo, inst->opcode));
5676 if (inst->saturate)
5677 fprintf(file, ".sat");
5678 if (inst->conditional_mod) {
5679 fprintf(file, "%s", conditional_modifier[inst->conditional_mod]);
5680 if (!inst->predicate &&
5681 (devinfo->gen < 5 || (inst->opcode != BRW_OPCODE_SEL &&
5682 inst->opcode != BRW_OPCODE_CSEL &&
5683 inst->opcode != BRW_OPCODE_IF &&
5684 inst->opcode != BRW_OPCODE_WHILE))) {
5685 fprintf(file, ".f%d.%d", inst->flag_subreg / 2,
5686 inst->flag_subreg % 2);
5687 }
5688 }
5689 fprintf(file, "(%d) ", inst->exec_size);
5690
5691 if (inst->mlen) {
5692 fprintf(file, "(mlen: %d) ", inst->mlen);
5693 }
5694
5695 if (inst->eot) {
5696 fprintf(file, "(EOT) ");
5697 }
5698
5699 switch (inst->dst.file) {
5700 case VGRF:
5701 fprintf(file, "vgrf%d", inst->dst.nr);
5702 break;
5703 case FIXED_GRF:
5704 fprintf(file, "g%d", inst->dst.nr);
5705 break;
5706 case MRF:
5707 fprintf(file, "m%d", inst->dst.nr);
5708 break;
5709 case BAD_FILE:
5710 fprintf(file, "(null)");
5711 break;
5712 case UNIFORM:
5713 fprintf(file, "***u%d***", inst->dst.nr);
5714 break;
5715 case ATTR:
5716 fprintf(file, "***attr%d***", inst->dst.nr);
5717 break;
5718 case ARF:
5719 switch (inst->dst.nr) {
5720 case BRW_ARF_NULL:
5721 fprintf(file, "null");
5722 break;
5723 case BRW_ARF_ADDRESS:
5724 fprintf(file, "a0.%d", inst->dst.subnr);
5725 break;
5726 case BRW_ARF_ACCUMULATOR:
5727 fprintf(file, "acc%d", inst->dst.subnr);
5728 break;
5729 case BRW_ARF_FLAG:
5730 fprintf(file, "f%d.%d", inst->dst.nr & 0xf, inst->dst.subnr);
5731 break;
5732 default:
5733 fprintf(file, "arf%d.%d", inst->dst.nr & 0xf, inst->dst.subnr);
5734 break;
5735 }
5736 break;
5737 case IMM:
5738 unreachable("not reached");
5739 }
5740
5741 if (inst->dst.offset ||
5742 (inst->dst.file == VGRF &&
5743 alloc.sizes[inst->dst.nr] * REG_SIZE != inst->size_written)) {
5744 const unsigned reg_size = (inst->dst.file == UNIFORM ? 4 : REG_SIZE);
5745 fprintf(file, "+%d.%d", inst->dst.offset / reg_size,
5746 inst->dst.offset % reg_size);
5747 }
5748
5749 if (inst->dst.stride != 1)
5750 fprintf(file, "<%u>", inst->dst.stride);
5751 fprintf(file, ":%s, ", brw_reg_type_to_letters(inst->dst.type));
5752
5753 for (int i = 0; i < inst->sources; i++) {
5754 if (inst->src[i].negate)
5755 fprintf(file, "-");
5756 if (inst->src[i].abs)
5757 fprintf(file, "|");
5758 switch (inst->src[i].file) {
5759 case VGRF:
5760 fprintf(file, "vgrf%d", inst->src[i].nr);
5761 break;
5762 case FIXED_GRF:
5763 fprintf(file, "g%d", inst->src[i].nr);
5764 break;
5765 case MRF:
5766 fprintf(file, "***m%d***", inst->src[i].nr);
5767 break;
5768 case ATTR:
5769 fprintf(file, "attr%d", inst->src[i].nr);
5770 break;
5771 case UNIFORM:
5772 fprintf(file, "u%d", inst->src[i].nr);
5773 break;
5774 case BAD_FILE:
5775 fprintf(file, "(null)");
5776 break;
5777 case IMM:
5778 switch (inst->src[i].type) {
5779 case BRW_REGISTER_TYPE_F:
5780 fprintf(file, "%-gf", inst->src[i].f);
5781 break;
5782 case BRW_REGISTER_TYPE_DF:
5783 fprintf(file, "%fdf", inst->src[i].df);
5784 break;
5785 case BRW_REGISTER_TYPE_W:
5786 case BRW_REGISTER_TYPE_D:
5787 fprintf(file, "%dd", inst->src[i].d);
5788 break;
5789 case BRW_REGISTER_TYPE_UW:
5790 case BRW_REGISTER_TYPE_UD:
5791 fprintf(file, "%uu", inst->src[i].ud);
5792 break;
5793 case BRW_REGISTER_TYPE_VF:
5794 fprintf(file, "[%-gF, %-gF, %-gF, %-gF]",
5795 brw_vf_to_float((inst->src[i].ud >> 0) & 0xff),
5796 brw_vf_to_float((inst->src[i].ud >> 8) & 0xff),
5797 brw_vf_to_float((inst->src[i].ud >> 16) & 0xff),
5798 brw_vf_to_float((inst->src[i].ud >> 24) & 0xff));
5799 break;
5800 default:
5801 fprintf(file, "???");
5802 break;
5803 }
5804 break;
5805 case ARF:
5806 switch (inst->src[i].nr) {
5807 case BRW_ARF_NULL:
5808 fprintf(file, "null");
5809 break;
5810 case BRW_ARF_ADDRESS:
5811 fprintf(file, "a0.%d", inst->src[i].subnr);
5812 break;
5813 case BRW_ARF_ACCUMULATOR:
5814 fprintf(file, "acc%d", inst->src[i].subnr);
5815 break;
5816 case BRW_ARF_FLAG:
5817 fprintf(file, "f%d.%d", inst->src[i].nr & 0xf, inst->src[i].subnr);
5818 break;
5819 default:
5820 fprintf(file, "arf%d.%d", inst->src[i].nr & 0xf, inst->src[i].subnr);
5821 break;
5822 }
5823 break;
5824 }
5825
5826 if (inst->src[i].offset ||
5827 (inst->src[i].file == VGRF &&
5828 alloc.sizes[inst->src[i].nr] * REG_SIZE != inst->size_read(i))) {
5829 const unsigned reg_size = (inst->src[i].file == UNIFORM ? 4 : REG_SIZE);
5830 fprintf(file, "+%d.%d", inst->src[i].offset / reg_size,
5831 inst->src[i].offset % reg_size);
5832 }
5833
5834 if (inst->src[i].abs)
5835 fprintf(file, "|");
5836
5837 if (inst->src[i].file != IMM) {
5838 unsigned stride;
5839 if (inst->src[i].file == ARF || inst->src[i].file == FIXED_GRF) {
5840 unsigned hstride = inst->src[i].hstride;
5841 stride = (hstride == 0 ? 0 : (1 << (hstride - 1)));
5842 } else {
5843 stride = inst->src[i].stride;
5844 }
5845 if (stride != 1)
5846 fprintf(file, "<%u>", stride);
5847
5848 fprintf(file, ":%s", brw_reg_type_to_letters(inst->src[i].type));
5849 }
5850
5851 if (i < inst->sources - 1 && inst->src[i + 1].file != BAD_FILE)
5852 fprintf(file, ", ");
5853 }
5854
5855 fprintf(file, " ");
5856
5857 if (inst->force_writemask_all)
5858 fprintf(file, "NoMask ");
5859
5860 if (inst->exec_size != dispatch_width)
5861 fprintf(file, "group%d ", inst->group);
5862
5863 fprintf(file, "\n");
5864 }
5865
5866 /**
5867 * Possibly returns an instruction that set up @param reg.
5868 *
5869 * Sometimes we want to take the result of some expression/variable
5870 * dereference tree and rewrite the instruction generating the result
5871 * of the tree. When processing the tree, we know that the
5872 * instructions generated are all writing temporaries that are dead
5873 * outside of this tree. So, if we have some instructions that write
5874 * a temporary, we're free to point that temp write somewhere else.
5875 *
5876 * Note that this doesn't guarantee that the instruction generated
5877 * only reg -- it might be the size=4 destination of a texture instruction.
5878 */
5879 fs_inst *
5880 fs_visitor::get_instruction_generating_reg(fs_inst *start,
5881 fs_inst *end,
5882 const fs_reg &reg)
5883 {
5884 if (end == start ||
5885 end->is_partial_write() ||
5886 !reg.equals(end->dst)) {
5887 return NULL;
5888 } else {
5889 return end;
5890 }
5891 }
5892
5893 void
5894 fs_visitor::setup_fs_payload_gen6()
5895 {
5896 assert(stage == MESA_SHADER_FRAGMENT);
5897 struct brw_wm_prog_data *prog_data = brw_wm_prog_data(this->prog_data);
5898
5899 assert(devinfo->gen >= 6);
5900
5901 /* R0-1: masks, pixel X/Y coordinates. */
5902 payload.num_regs = 2;
5903 /* R2: only for 32-pixel dispatch.*/
5904
5905 /* R3-26: barycentric interpolation coordinates. These appear in the
5906 * same order that they appear in the brw_barycentric_mode
5907 * enum. Each set of coordinates occupies 2 registers if dispatch width
5908 * == 8 and 4 registers if dispatch width == 16. Coordinates only
5909 * appear if they were enabled using the "Barycentric Interpolation
5910 * Mode" bits in WM_STATE.
5911 */
5912 for (int i = 0; i < BRW_BARYCENTRIC_MODE_COUNT; ++i) {
5913 if (prog_data->barycentric_interp_modes & (1 << i)) {
5914 payload.barycentric_coord_reg[i] = payload.num_regs;
5915 payload.num_regs += 2;
5916 if (dispatch_width == 16) {
5917 payload.num_regs += 2;
5918 }
5919 }
5920 }
5921
5922 /* R27: interpolated depth if uses source depth */
5923 prog_data->uses_src_depth =
5924 (nir->info.inputs_read & (1 << VARYING_SLOT_POS)) != 0;
5925 if (prog_data->uses_src_depth) {
5926 payload.source_depth_reg = payload.num_regs;
5927 payload.num_regs++;
5928 if (dispatch_width == 16) {
5929 /* R28: interpolated depth if not SIMD8. */
5930 payload.num_regs++;
5931 }
5932 }
5933
5934 /* R29: interpolated W set if GEN6_WM_USES_SOURCE_W. */
5935 prog_data->uses_src_w =
5936 (nir->info.inputs_read & (1 << VARYING_SLOT_POS)) != 0;
5937 if (prog_data->uses_src_w) {
5938 payload.source_w_reg = payload.num_regs;
5939 payload.num_regs++;
5940 if (dispatch_width == 16) {
5941 /* R30: interpolated W if not SIMD8. */
5942 payload.num_regs++;
5943 }
5944 }
5945
5946 /* R31: MSAA position offsets. */
5947 if (prog_data->persample_dispatch &&
5948 (nir->info.system_values_read & SYSTEM_BIT_SAMPLE_POS)) {
5949 /* From the Ivy Bridge PRM documentation for 3DSTATE_PS:
5950 *
5951 * "MSDISPMODE_PERSAMPLE is required in order to select
5952 * POSOFFSET_SAMPLE"
5953 *
5954 * So we can only really get sample positions if we are doing real
5955 * per-sample dispatch. If we need gl_SamplePosition and we don't have
5956 * persample dispatch, we hard-code it to 0.5.
5957 */
5958 prog_data->uses_pos_offset = true;
5959 payload.sample_pos_reg = payload.num_regs;
5960 payload.num_regs++;
5961 }
5962
5963 /* R32: MSAA input coverage mask */
5964 prog_data->uses_sample_mask =
5965 (nir->info.system_values_read & SYSTEM_BIT_SAMPLE_MASK_IN) != 0;
5966 if (prog_data->uses_sample_mask) {
5967 assert(devinfo->gen >= 7);
5968 payload.sample_mask_in_reg = payload.num_regs;
5969 payload.num_regs++;
5970 if (dispatch_width == 16) {
5971 /* R33: input coverage mask if not SIMD8. */
5972 payload.num_regs++;
5973 }
5974 }
5975
5976 /* R34-: bary for 32-pixel. */
5977 /* R58-59: interp W for 32-pixel. */
5978
5979 if (nir->info.outputs_written & BITFIELD64_BIT(FRAG_RESULT_DEPTH)) {
5980 source_depth_to_render_target = true;
5981 }
5982 }
5983
5984 void
5985 fs_visitor::setup_vs_payload()
5986 {
5987 /* R0: thread header, R1: urb handles */
5988 payload.num_regs = 2;
5989 }
5990
5991 void
5992 fs_visitor::setup_gs_payload()
5993 {
5994 assert(stage == MESA_SHADER_GEOMETRY);
5995
5996 struct brw_gs_prog_data *gs_prog_data = brw_gs_prog_data(prog_data);
5997 struct brw_vue_prog_data *vue_prog_data = brw_vue_prog_data(prog_data);
5998
5999 /* R0: thread header, R1: output URB handles */
6000 payload.num_regs = 2;
6001
6002 if (gs_prog_data->include_primitive_id) {
6003 /* R2: Primitive ID 0..7 */
6004 payload.num_regs++;
6005 }
6006
6007 /* Always enable VUE handles so we can safely use pull model if needed.
6008 *
6009 * The push model for a GS uses a ton of register space even for trivial
6010 * scenarios with just a few inputs, so just make things easier and a bit
6011 * safer by always having pull model available.
6012 */
6013 gs_prog_data->base.include_vue_handles = true;
6014
6015 /* R3..RN: ICP Handles for each incoming vertex (when using pull model) */
6016 payload.num_regs += nir->info.gs.vertices_in;
6017
6018 /* Use a maximum of 24 registers for push-model inputs. */
6019 const unsigned max_push_components = 24;
6020
6021 /* If pushing our inputs would take too many registers, reduce the URB read
6022 * length (which is in HWords, or 8 registers), and resort to pulling.
6023 *
6024 * Note that the GS reads <URB Read Length> HWords for every vertex - so we
6025 * have to multiply by VerticesIn to obtain the total storage requirement.
6026 */
6027 if (8 * vue_prog_data->urb_read_length * nir->info.gs.vertices_in >
6028 max_push_components) {
6029 vue_prog_data->urb_read_length =
6030 ROUND_DOWN_TO(max_push_components / nir->info.gs.vertices_in, 8) / 8;
6031 }
6032 }
6033
6034 void
6035 fs_visitor::setup_cs_payload()
6036 {
6037 assert(devinfo->gen >= 7);
6038 payload.num_regs = 1;
6039 }
6040
6041 void
6042 fs_visitor::calculate_register_pressure()
6043 {
6044 invalidate_live_intervals();
6045 calculate_live_intervals();
6046
6047 unsigned num_instructions = 0;
6048 foreach_block(block, cfg)
6049 num_instructions += block->instructions.length();
6050
6051 regs_live_at_ip = rzalloc_array(mem_ctx, int, num_instructions);
6052
6053 for (unsigned reg = 0; reg < alloc.count; reg++) {
6054 for (int ip = virtual_grf_start[reg]; ip <= virtual_grf_end[reg]; ip++)
6055 regs_live_at_ip[ip] += alloc.sizes[reg];
6056 }
6057 }
6058
6059 /**
6060 * Look for repeated FS_OPCODE_MOV_DISPATCH_TO_FLAGS and drop the later ones.
6061 *
6062 * The needs_unlit_centroid_workaround ends up producing one of these per
6063 * channel of centroid input, so it's good to clean them up.
6064 *
6065 * An assumption here is that nothing ever modifies the dispatched pixels
6066 * value that FS_OPCODE_MOV_DISPATCH_TO_FLAGS reads from, but the hardware
6067 * dictates that anyway.
6068 */
6069 bool
6070 fs_visitor::opt_drop_redundant_mov_to_flags()
6071 {
6072 bool flag_mov_found[4] = {false};
6073 bool progress = false;
6074
6075 /* Instructions removed by this pass can only be added if this were true */
6076 if (!devinfo->needs_unlit_centroid_workaround)
6077 return false;
6078
6079 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
6080 if (inst->is_control_flow()) {
6081 memset(flag_mov_found, 0, sizeof(flag_mov_found));
6082 } else if (inst->opcode == FS_OPCODE_MOV_DISPATCH_TO_FLAGS) {
6083 if (!flag_mov_found[inst->flag_subreg]) {
6084 flag_mov_found[inst->flag_subreg] = true;
6085 } else {
6086 inst->remove(block);
6087 progress = true;
6088 }
6089 } else if (inst->flags_written()) {
6090 flag_mov_found[inst->flag_subreg] = false;
6091 }
6092 }
6093
6094 return progress;
6095 }
6096
6097 void
6098 fs_visitor::optimize()
6099 {
6100 /* Start by validating the shader we currently have. */
6101 validate();
6102
6103 /* bld is the common builder object pointing at the end of the program we
6104 * used to translate it into i965 IR. For the optimization and lowering
6105 * passes coming next, any code added after the end of the program without
6106 * having explicitly called fs_builder::at() clearly points at a mistake.
6107 * Ideally optimization passes wouldn't be part of the visitor so they
6108 * wouldn't have access to bld at all, but they do, so just in case some
6109 * pass forgets to ask for a location explicitly set it to NULL here to
6110 * make it trip. The dispatch width is initialized to a bogus value to
6111 * make sure that optimizations set the execution controls explicitly to
6112 * match the code they are manipulating instead of relying on the defaults.
6113 */
6114 bld = fs_builder(this, 64);
6115
6116 assign_constant_locations();
6117 lower_constant_loads();
6118
6119 validate();
6120
6121 split_virtual_grfs();
6122 validate();
6123
6124 #define OPT(pass, args...) ({ \
6125 pass_num++; \
6126 bool this_progress = pass(args); \
6127 \
6128 if (unlikely(INTEL_DEBUG & DEBUG_OPTIMIZER) && this_progress) { \
6129 char filename[64]; \
6130 snprintf(filename, 64, "%s%d-%s-%02d-%02d-" #pass, \
6131 stage_abbrev, dispatch_width, nir->info.name, iteration, pass_num); \
6132 \
6133 backend_shader::dump_instructions(filename); \
6134 } \
6135 \
6136 validate(); \
6137 \
6138 progress = progress || this_progress; \
6139 this_progress; \
6140 })
6141
6142 if (unlikely(INTEL_DEBUG & DEBUG_OPTIMIZER)) {
6143 char filename[64];
6144 snprintf(filename, 64, "%s%d-%s-00-00-start",
6145 stage_abbrev, dispatch_width, nir->info.name);
6146
6147 backend_shader::dump_instructions(filename);
6148 }
6149
6150 bool progress = false;
6151 int iteration = 0;
6152 int pass_num = 0;
6153
6154 OPT(opt_drop_redundant_mov_to_flags);
6155 OPT(remove_extra_rounding_modes);
6156
6157 do {
6158 progress = false;
6159 pass_num = 0;
6160 iteration++;
6161
6162 OPT(remove_duplicate_mrf_writes);
6163
6164 OPT(opt_algebraic);
6165 OPT(opt_cse);
6166 OPT(opt_copy_propagation);
6167 OPT(opt_predicated_break, this);
6168 OPT(opt_cmod_propagation);
6169 OPT(dead_code_eliminate);
6170 OPT(opt_peephole_sel);
6171 OPT(dead_control_flow_eliminate, this);
6172 OPT(opt_register_renaming);
6173 OPT(opt_saturate_propagation);
6174 OPT(register_coalesce);
6175 OPT(compute_to_mrf);
6176 OPT(eliminate_find_live_channel);
6177
6178 OPT(compact_virtual_grfs);
6179 } while (progress);
6180
6181 /* Do this after cmod propagation has had every possible opportunity to
6182 * propagate results into SEL instructions.
6183 */
6184 if (OPT(opt_peephole_csel))
6185 OPT(dead_code_eliminate);
6186
6187 progress = false;
6188 pass_num = 0;
6189
6190 if (OPT(lower_pack)) {
6191 OPT(register_coalesce);
6192 OPT(dead_code_eliminate);
6193 }
6194
6195 OPT(lower_simd_width);
6196
6197 /* After SIMD lowering just in case we had to unroll the EOT send. */
6198 OPT(opt_sampler_eot);
6199
6200 OPT(lower_logical_sends);
6201
6202 if (progress) {
6203 OPT(opt_copy_propagation);
6204 /* Only run after logical send lowering because it's easier to implement
6205 * in terms of physical sends.
6206 */
6207 if (OPT(opt_zero_samples))
6208 OPT(opt_copy_propagation);
6209 /* Run after logical send lowering to give it a chance to CSE the
6210 * LOAD_PAYLOAD instructions created to construct the payloads of
6211 * e.g. texturing messages in cases where it wasn't possible to CSE the
6212 * whole logical instruction.
6213 */
6214 OPT(opt_cse);
6215 OPT(register_coalesce);
6216 OPT(compute_to_mrf);
6217 OPT(dead_code_eliminate);
6218 OPT(remove_duplicate_mrf_writes);
6219 OPT(opt_peephole_sel);
6220 }
6221
6222 OPT(opt_redundant_discard_jumps);
6223
6224 if (OPT(lower_load_payload)) {
6225 split_virtual_grfs();
6226 OPT(register_coalesce);
6227 OPT(compute_to_mrf);
6228 OPT(dead_code_eliminate);
6229 }
6230
6231 OPT(opt_combine_constants);
6232 OPT(lower_integer_multiplication);
6233
6234 if (devinfo->gen <= 5 && OPT(lower_minmax)) {
6235 OPT(opt_cmod_propagation);
6236 OPT(opt_cse);
6237 OPT(opt_copy_propagation);
6238 OPT(dead_code_eliminate);
6239 }
6240
6241 if (OPT(lower_conversions)) {
6242 OPT(opt_copy_propagation);
6243 OPT(dead_code_eliminate);
6244 OPT(lower_simd_width);
6245 }
6246
6247 lower_uniform_pull_constant_loads();
6248
6249 validate();
6250 }
6251
6252 /**
6253 * Three source instruction must have a GRF/MRF destination register.
6254 * ARF NULL is not allowed. Fix that up by allocating a temporary GRF.
6255 */
6256 void
6257 fs_visitor::fixup_3src_null_dest()
6258 {
6259 bool progress = false;
6260
6261 foreach_block_and_inst_safe (block, fs_inst, inst, cfg) {
6262 if (inst->is_3src(devinfo) && inst->dst.is_null()) {
6263 inst->dst = fs_reg(VGRF, alloc.allocate(dispatch_width / 8),
6264 inst->dst.type);
6265 progress = true;
6266 }
6267 }
6268
6269 if (progress)
6270 invalidate_live_intervals();
6271 }
6272
6273 void
6274 fs_visitor::allocate_registers(unsigned min_dispatch_width, bool allow_spilling)
6275 {
6276 bool allocated_without_spills;
6277
6278 static const enum instruction_scheduler_mode pre_modes[] = {
6279 SCHEDULE_PRE,
6280 SCHEDULE_PRE_NON_LIFO,
6281 SCHEDULE_PRE_LIFO,
6282 };
6283
6284 bool spill_all = allow_spilling && (INTEL_DEBUG & DEBUG_SPILL_FS);
6285
6286 /* Try each scheduling heuristic to see if it can successfully register
6287 * allocate without spilling. They should be ordered by decreasing
6288 * performance but increasing likelihood of allocating.
6289 */
6290 for (unsigned i = 0; i < ARRAY_SIZE(pre_modes); i++) {
6291 schedule_instructions(pre_modes[i]);
6292
6293 if (0) {
6294 assign_regs_trivial();
6295 allocated_without_spills = true;
6296 } else {
6297 allocated_without_spills = assign_regs(false, spill_all);
6298 }
6299 if (allocated_without_spills)
6300 break;
6301 }
6302
6303 if (!allocated_without_spills) {
6304 if (!allow_spilling)
6305 fail("Failure to register allocate and spilling is not allowed.");
6306
6307 /* We assume that any spilling is worse than just dropping back to
6308 * SIMD8. There's probably actually some intermediate point where
6309 * SIMD16 with a couple of spills is still better.
6310 */
6311 if (dispatch_width > min_dispatch_width) {
6312 fail("Failure to register allocate. Reduce number of "
6313 "live scalar values to avoid this.");
6314 } else {
6315 compiler->shader_perf_log(log_data,
6316 "%s shader triggered register spilling. "
6317 "Try reducing the number of live scalar "
6318 "values to improve performance.\n",
6319 stage_name);
6320 }
6321
6322 /* Since we're out of heuristics, just go spill registers until we
6323 * get an allocation.
6324 */
6325 while (!assign_regs(true, spill_all)) {
6326 if (failed)
6327 break;
6328 }
6329 }
6330
6331 /* This must come after all optimization and register allocation, since
6332 * it inserts dead code that happens to have side effects, and it does
6333 * so based on the actual physical registers in use.
6334 */
6335 insert_gen4_send_dependency_workarounds();
6336
6337 if (failed)
6338 return;
6339
6340 opt_bank_conflicts();
6341
6342 schedule_instructions(SCHEDULE_POST);
6343
6344 if (last_scratch > 0) {
6345 MAYBE_UNUSED unsigned max_scratch_size = 2 * 1024 * 1024;
6346
6347 prog_data->total_scratch = brw_get_scratch_size(last_scratch);
6348
6349 if (stage == MESA_SHADER_COMPUTE) {
6350 if (devinfo->is_haswell) {
6351 /* According to the MEDIA_VFE_STATE's "Per Thread Scratch Space"
6352 * field documentation, Haswell supports a minimum of 2kB of
6353 * scratch space for compute shaders, unlike every other stage
6354 * and platform.
6355 */
6356 prog_data->total_scratch = MAX2(prog_data->total_scratch, 2048);
6357 } else if (devinfo->gen <= 7) {
6358 /* According to the MEDIA_VFE_STATE's "Per Thread Scratch Space"
6359 * field documentation, platforms prior to Haswell measure scratch
6360 * size linearly with a range of [1kB, 12kB] and 1kB granularity.
6361 */
6362 prog_data->total_scratch = ALIGN(last_scratch, 1024);
6363 max_scratch_size = 12 * 1024;
6364 }
6365 }
6366
6367 /* We currently only support up to 2MB of scratch space. If we
6368 * need to support more eventually, the documentation suggests
6369 * that we could allocate a larger buffer, and partition it out
6370 * ourselves. We'd just have to undo the hardware's address
6371 * calculation by subtracting (FFTID * Per Thread Scratch Space)
6372 * and then add FFTID * (Larger Per Thread Scratch Space).
6373 *
6374 * See 3D-Media-GPGPU Engine > Media GPGPU Pipeline >
6375 * Thread Group Tracking > Local Memory/Scratch Space.
6376 */
6377 assert(prog_data->total_scratch < max_scratch_size);
6378 }
6379 }
6380
6381 bool
6382 fs_visitor::run_vs()
6383 {
6384 assert(stage == MESA_SHADER_VERTEX);
6385
6386 setup_vs_payload();
6387
6388 if (shader_time_index >= 0)
6389 emit_shader_time_begin();
6390
6391 emit_nir_code();
6392
6393 if (failed)
6394 return false;
6395
6396 compute_clip_distance();
6397
6398 emit_urb_writes();
6399
6400 if (shader_time_index >= 0)
6401 emit_shader_time_end();
6402
6403 calculate_cfg();
6404
6405 optimize();
6406
6407 assign_curb_setup();
6408 assign_vs_urb_setup();
6409
6410 fixup_3src_null_dest();
6411 allocate_registers(8, true);
6412
6413 return !failed;
6414 }
6415
6416 bool
6417 fs_visitor::run_tcs_single_patch()
6418 {
6419 assert(stage == MESA_SHADER_TESS_CTRL);
6420
6421 struct brw_tcs_prog_data *tcs_prog_data = brw_tcs_prog_data(prog_data);
6422
6423 /* r1-r4 contain the ICP handles. */
6424 payload.num_regs = 5;
6425
6426 if (shader_time_index >= 0)
6427 emit_shader_time_begin();
6428
6429 /* Initialize gl_InvocationID */
6430 fs_reg channels_uw = bld.vgrf(BRW_REGISTER_TYPE_UW);
6431 fs_reg channels_ud = bld.vgrf(BRW_REGISTER_TYPE_UD);
6432 bld.MOV(channels_uw, fs_reg(brw_imm_uv(0x76543210)));
6433 bld.MOV(channels_ud, channels_uw);
6434
6435 if (tcs_prog_data->instances == 1) {
6436 invocation_id = channels_ud;
6437 } else {
6438 invocation_id = bld.vgrf(BRW_REGISTER_TYPE_UD);
6439
6440 /* Get instance number from g0.2 bits 23:17, and multiply it by 8. */
6441 fs_reg t = bld.vgrf(BRW_REGISTER_TYPE_UD);
6442 fs_reg instance_times_8 = bld.vgrf(BRW_REGISTER_TYPE_UD);
6443 bld.AND(t, fs_reg(retype(brw_vec1_grf(0, 2), BRW_REGISTER_TYPE_UD)),
6444 brw_imm_ud(INTEL_MASK(23, 17)));
6445 bld.SHR(instance_times_8, t, brw_imm_ud(17 - 3));
6446
6447 bld.ADD(invocation_id, instance_times_8, channels_ud);
6448 }
6449
6450 /* Fix the disptach mask */
6451 if (nir->info.tess.tcs_vertices_out % 8) {
6452 bld.CMP(bld.null_reg_ud(), invocation_id,
6453 brw_imm_ud(nir->info.tess.tcs_vertices_out), BRW_CONDITIONAL_L);
6454 bld.IF(BRW_PREDICATE_NORMAL);
6455 }
6456
6457 emit_nir_code();
6458
6459 if (nir->info.tess.tcs_vertices_out % 8) {
6460 bld.emit(BRW_OPCODE_ENDIF);
6461 }
6462
6463 /* Emit EOT write; set TR DS Cache bit */
6464 fs_reg srcs[3] = {
6465 fs_reg(retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_UD)),
6466 fs_reg(brw_imm_ud(WRITEMASK_X << 16)),
6467 fs_reg(brw_imm_ud(0)),
6468 };
6469 fs_reg payload = bld.vgrf(BRW_REGISTER_TYPE_UD, 3);
6470 bld.LOAD_PAYLOAD(payload, srcs, 3, 2);
6471
6472 fs_inst *inst = bld.emit(SHADER_OPCODE_URB_WRITE_SIMD8_MASKED,
6473 bld.null_reg_ud(), payload);
6474 inst->mlen = 3;
6475 inst->eot = true;
6476
6477 if (shader_time_index >= 0)
6478 emit_shader_time_end();
6479
6480 if (failed)
6481 return false;
6482
6483 calculate_cfg();
6484
6485 optimize();
6486
6487 assign_curb_setup();
6488 assign_tcs_single_patch_urb_setup();
6489
6490 fixup_3src_null_dest();
6491 allocate_registers(8, true);
6492
6493 return !failed;
6494 }
6495
6496 bool
6497 fs_visitor::run_tes()
6498 {
6499 assert(stage == MESA_SHADER_TESS_EVAL);
6500
6501 /* R0: thread header, R1-3: gl_TessCoord.xyz, R4: URB handles */
6502 payload.num_regs = 5;
6503
6504 if (shader_time_index >= 0)
6505 emit_shader_time_begin();
6506
6507 emit_nir_code();
6508
6509 if (failed)
6510 return false;
6511
6512 emit_urb_writes();
6513
6514 if (shader_time_index >= 0)
6515 emit_shader_time_end();
6516
6517 calculate_cfg();
6518
6519 optimize();
6520
6521 assign_curb_setup();
6522 assign_tes_urb_setup();
6523
6524 fixup_3src_null_dest();
6525 allocate_registers(8, true);
6526
6527 return !failed;
6528 }
6529
6530 bool
6531 fs_visitor::run_gs()
6532 {
6533 assert(stage == MESA_SHADER_GEOMETRY);
6534
6535 setup_gs_payload();
6536
6537 this->final_gs_vertex_count = vgrf(glsl_type::uint_type);
6538
6539 if (gs_compile->control_data_header_size_bits > 0) {
6540 /* Create a VGRF to store accumulated control data bits. */
6541 this->control_data_bits = vgrf(glsl_type::uint_type);
6542
6543 /* If we're outputting more than 32 control data bits, then EmitVertex()
6544 * will set control_data_bits to 0 after emitting the first vertex.
6545 * Otherwise, we need to initialize it to 0 here.
6546 */
6547 if (gs_compile->control_data_header_size_bits <= 32) {
6548 const fs_builder abld = bld.annotate("initialize control data bits");
6549 abld.MOV(this->control_data_bits, brw_imm_ud(0u));
6550 }
6551 }
6552
6553 if (shader_time_index >= 0)
6554 emit_shader_time_begin();
6555
6556 emit_nir_code();
6557
6558 emit_gs_thread_end();
6559
6560 if (shader_time_index >= 0)
6561 emit_shader_time_end();
6562
6563 if (failed)
6564 return false;
6565
6566 calculate_cfg();
6567
6568 optimize();
6569
6570 assign_curb_setup();
6571 assign_gs_urb_setup();
6572
6573 fixup_3src_null_dest();
6574 allocate_registers(8, true);
6575
6576 return !failed;
6577 }
6578
6579 /* From the SKL PRM, Volume 16, Workarounds:
6580 *
6581 * 0877 3D Pixel Shader Hang possible when pixel shader dispatched with
6582 * only header phases (R0-R2)
6583 *
6584 * WA: Enable a non-header phase (e.g. push constant) when dispatch would
6585 * have been header only.
6586 *
6587 * Instead of enabling push constants one can alternatively enable one of the
6588 * inputs. Here one simply chooses "layer" which shouldn't impose much
6589 * overhead.
6590 */
6591 static void
6592 gen9_ps_header_only_workaround(struct brw_wm_prog_data *wm_prog_data)
6593 {
6594 if (wm_prog_data->num_varying_inputs)
6595 return;
6596
6597 if (wm_prog_data->base.curb_read_length)
6598 return;
6599
6600 wm_prog_data->urb_setup[VARYING_SLOT_LAYER] = 0;
6601 wm_prog_data->num_varying_inputs = 1;
6602 }
6603
6604 bool
6605 fs_visitor::run_fs(bool allow_spilling, bool do_rep_send)
6606 {
6607 struct brw_wm_prog_data *wm_prog_data = brw_wm_prog_data(this->prog_data);
6608 brw_wm_prog_key *wm_key = (brw_wm_prog_key *) this->key;
6609
6610 assert(stage == MESA_SHADER_FRAGMENT);
6611
6612 if (devinfo->gen >= 6)
6613 setup_fs_payload_gen6();
6614 else
6615 setup_fs_payload_gen4();
6616
6617 if (0) {
6618 emit_dummy_fs();
6619 } else if (do_rep_send) {
6620 assert(dispatch_width == 16);
6621 emit_repclear_shader();
6622 } else {
6623 if (shader_time_index >= 0)
6624 emit_shader_time_begin();
6625
6626 calculate_urb_setup();
6627 if (nir->info.inputs_read > 0 ||
6628 (nir->info.outputs_read > 0 && !wm_key->coherent_fb_fetch)) {
6629 if (devinfo->gen < 6)
6630 emit_interpolation_setup_gen4();
6631 else
6632 emit_interpolation_setup_gen6();
6633 }
6634
6635 /* We handle discards by keeping track of the still-live pixels in f0.1.
6636 * Initialize it with the dispatched pixels.
6637 */
6638 if (wm_prog_data->uses_kill) {
6639 fs_inst *discard_init = bld.emit(FS_OPCODE_MOV_DISPATCH_TO_FLAGS);
6640 discard_init->flag_subreg = 1;
6641 }
6642
6643 /* Generate FS IR for main(). (the visitor only descends into
6644 * functions called "main").
6645 */
6646 emit_nir_code();
6647
6648 if (failed)
6649 return false;
6650
6651 if (wm_prog_data->uses_kill)
6652 bld.emit(FS_OPCODE_PLACEHOLDER_HALT);
6653
6654 if (wm_key->alpha_test_func)
6655 emit_alpha_test();
6656
6657 emit_fb_writes();
6658
6659 if (shader_time_index >= 0)
6660 emit_shader_time_end();
6661
6662 calculate_cfg();
6663
6664 optimize();
6665
6666 assign_curb_setup();
6667
6668 if (devinfo->gen >= 9)
6669 gen9_ps_header_only_workaround(wm_prog_data);
6670
6671 assign_urb_setup();
6672
6673 fixup_3src_null_dest();
6674 allocate_registers(8, allow_spilling);
6675
6676 if (failed)
6677 return false;
6678 }
6679
6680 return !failed;
6681 }
6682
6683 bool
6684 fs_visitor::run_cs(unsigned min_dispatch_width)
6685 {
6686 assert(stage == MESA_SHADER_COMPUTE);
6687 assert(dispatch_width >= min_dispatch_width);
6688
6689 setup_cs_payload();
6690
6691 if (shader_time_index >= 0)
6692 emit_shader_time_begin();
6693
6694 if (devinfo->is_haswell && prog_data->total_shared > 0) {
6695 /* Move SLM index from g0.0[27:24] to sr0.1[11:8] */
6696 const fs_builder abld = bld.exec_all().group(1, 0);
6697 abld.MOV(retype(brw_sr0_reg(1), BRW_REGISTER_TYPE_UW),
6698 suboffset(retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_UW), 1));
6699 }
6700
6701 emit_nir_code();
6702
6703 if (failed)
6704 return false;
6705
6706 emit_cs_terminate();
6707
6708 if (shader_time_index >= 0)
6709 emit_shader_time_end();
6710
6711 calculate_cfg();
6712
6713 optimize();
6714
6715 assign_curb_setup();
6716
6717 fixup_3src_null_dest();
6718 allocate_registers(min_dispatch_width, true);
6719
6720 if (failed)
6721 return false;
6722
6723 return !failed;
6724 }
6725
6726 /**
6727 * Return a bitfield where bit n is set if barycentric interpolation mode n
6728 * (see enum brw_barycentric_mode) is needed by the fragment shader.
6729 *
6730 * We examine the load_barycentric intrinsics rather than looking at input
6731 * variables so that we catch interpolateAtCentroid() messages too, which
6732 * also need the BRW_BARYCENTRIC_[NON]PERSPECTIVE_CENTROID mode set up.
6733 */
6734 static unsigned
6735 brw_compute_barycentric_interp_modes(const struct gen_device_info *devinfo,
6736 const nir_shader *shader)
6737 {
6738 unsigned barycentric_interp_modes = 0;
6739
6740 nir_foreach_function(f, shader) {
6741 if (!f->impl)
6742 continue;
6743
6744 nir_foreach_block(block, f->impl) {
6745 nir_foreach_instr(instr, block) {
6746 if (instr->type != nir_instr_type_intrinsic)
6747 continue;
6748
6749 nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
6750 if (intrin->intrinsic != nir_intrinsic_load_interpolated_input)
6751 continue;
6752
6753 /* Ignore WPOS; it doesn't require interpolation. */
6754 if (nir_intrinsic_base(intrin) == VARYING_SLOT_POS)
6755 continue;
6756
6757 intrin = nir_instr_as_intrinsic(intrin->src[0].ssa->parent_instr);
6758 enum glsl_interp_mode interp = (enum glsl_interp_mode)
6759 nir_intrinsic_interp_mode(intrin);
6760 nir_intrinsic_op bary_op = intrin->intrinsic;
6761 enum brw_barycentric_mode bary =
6762 brw_barycentric_mode(interp, bary_op);
6763
6764 barycentric_interp_modes |= 1 << bary;
6765
6766 if (devinfo->needs_unlit_centroid_workaround &&
6767 bary_op == nir_intrinsic_load_barycentric_centroid)
6768 barycentric_interp_modes |= 1 << centroid_to_pixel(bary);
6769 }
6770 }
6771 }
6772
6773 return barycentric_interp_modes;
6774 }
6775
6776 static void
6777 brw_compute_flat_inputs(struct brw_wm_prog_data *prog_data,
6778 const nir_shader *shader)
6779 {
6780 prog_data->flat_inputs = 0;
6781
6782 nir_foreach_variable(var, &shader->inputs) {
6783 int input_index = prog_data->urb_setup[var->data.location];
6784
6785 if (input_index < 0)
6786 continue;
6787
6788 /* flat shading */
6789 if (var->data.interpolation == INTERP_MODE_FLAT)
6790 prog_data->flat_inputs |= (1 << input_index);
6791 }
6792 }
6793
6794 static uint8_t
6795 computed_depth_mode(const nir_shader *shader)
6796 {
6797 if (shader->info.outputs_written & BITFIELD64_BIT(FRAG_RESULT_DEPTH)) {
6798 switch (shader->info.fs.depth_layout) {
6799 case FRAG_DEPTH_LAYOUT_NONE:
6800 case FRAG_DEPTH_LAYOUT_ANY:
6801 return BRW_PSCDEPTH_ON;
6802 case FRAG_DEPTH_LAYOUT_GREATER:
6803 return BRW_PSCDEPTH_ON_GE;
6804 case FRAG_DEPTH_LAYOUT_LESS:
6805 return BRW_PSCDEPTH_ON_LE;
6806 case FRAG_DEPTH_LAYOUT_UNCHANGED:
6807 return BRW_PSCDEPTH_OFF;
6808 }
6809 }
6810 return BRW_PSCDEPTH_OFF;
6811 }
6812
6813 /**
6814 * Move load_interpolated_input with simple (payload-based) barycentric modes
6815 * to the top of the program so we don't emit multiple PLNs for the same input.
6816 *
6817 * This works around CSE not being able to handle non-dominating cases
6818 * such as:
6819 *
6820 * if (...) {
6821 * interpolate input
6822 * } else {
6823 * interpolate the same exact input
6824 * }
6825 *
6826 * This should be replaced by global value numbering someday.
6827 */
6828 static bool
6829 move_interpolation_to_top(nir_shader *nir)
6830 {
6831 bool progress = false;
6832
6833 nir_foreach_function(f, nir) {
6834 if (!f->impl)
6835 continue;
6836
6837 nir_block *top = nir_start_block(f->impl);
6838 exec_node *cursor_node = NULL;
6839
6840 nir_foreach_block(block, f->impl) {
6841 if (block == top)
6842 continue;
6843
6844 nir_foreach_instr_safe(instr, block) {
6845 if (instr->type != nir_instr_type_intrinsic)
6846 continue;
6847
6848 nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
6849 if (intrin->intrinsic != nir_intrinsic_load_interpolated_input)
6850 continue;
6851 nir_intrinsic_instr *bary_intrinsic =
6852 nir_instr_as_intrinsic(intrin->src[0].ssa->parent_instr);
6853 nir_intrinsic_op op = bary_intrinsic->intrinsic;
6854
6855 /* Leave interpolateAtSample/Offset() where they are. */
6856 if (op == nir_intrinsic_load_barycentric_at_sample ||
6857 op == nir_intrinsic_load_barycentric_at_offset)
6858 continue;
6859
6860 nir_instr *move[3] = {
6861 &bary_intrinsic->instr,
6862 intrin->src[1].ssa->parent_instr,
6863 instr
6864 };
6865
6866 for (unsigned i = 0; i < ARRAY_SIZE(move); i++) {
6867 if (move[i]->block != top) {
6868 move[i]->block = top;
6869 exec_node_remove(&move[i]->node);
6870 if (cursor_node) {
6871 exec_node_insert_after(cursor_node, &move[i]->node);
6872 } else {
6873 exec_list_push_head(&top->instr_list, &move[i]->node);
6874 }
6875 cursor_node = &move[i]->node;
6876 progress = true;
6877 }
6878 }
6879 }
6880 }
6881 nir_metadata_preserve(f->impl, (nir_metadata)
6882 ((unsigned) nir_metadata_block_index |
6883 (unsigned) nir_metadata_dominance));
6884 }
6885
6886 return progress;
6887 }
6888
6889 /**
6890 * Demote per-sample barycentric intrinsics to centroid.
6891 *
6892 * Useful when rendering to a non-multisampled buffer.
6893 */
6894 static bool
6895 demote_sample_qualifiers(nir_shader *nir)
6896 {
6897 bool progress = true;
6898
6899 nir_foreach_function(f, nir) {
6900 if (!f->impl)
6901 continue;
6902
6903 nir_builder b;
6904 nir_builder_init(&b, f->impl);
6905
6906 nir_foreach_block(block, f->impl) {
6907 nir_foreach_instr_safe(instr, block) {
6908 if (instr->type != nir_instr_type_intrinsic)
6909 continue;
6910
6911 nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
6912 if (intrin->intrinsic != nir_intrinsic_load_barycentric_sample &&
6913 intrin->intrinsic != nir_intrinsic_load_barycentric_at_sample)
6914 continue;
6915
6916 b.cursor = nir_before_instr(instr);
6917 nir_ssa_def *centroid =
6918 nir_load_barycentric(&b, nir_intrinsic_load_barycentric_centroid,
6919 nir_intrinsic_interp_mode(intrin));
6920 nir_ssa_def_rewrite_uses(&intrin->dest.ssa,
6921 nir_src_for_ssa(centroid));
6922 nir_instr_remove(instr);
6923 progress = true;
6924 }
6925 }
6926
6927 nir_metadata_preserve(f->impl, (nir_metadata)
6928 ((unsigned) nir_metadata_block_index |
6929 (unsigned) nir_metadata_dominance));
6930 }
6931
6932 return progress;
6933 }
6934
6935 /**
6936 * Pre-gen6, the register file of the EUs was shared between threads,
6937 * and each thread used some subset allocated on a 16-register block
6938 * granularity. The unit states wanted these block counts.
6939 */
6940 static inline int
6941 brw_register_blocks(int reg_count)
6942 {
6943 return ALIGN(reg_count, 16) / 16 - 1;
6944 }
6945
6946 const unsigned *
6947 brw_compile_fs(const struct brw_compiler *compiler, void *log_data,
6948 void *mem_ctx,
6949 const struct brw_wm_prog_key *key,
6950 struct brw_wm_prog_data *prog_data,
6951 const nir_shader *src_shader,
6952 struct gl_program *prog,
6953 int shader_time_index8, int shader_time_index16,
6954 bool allow_spilling,
6955 bool use_rep_send, struct brw_vue_map *vue_map,
6956 char **error_str)
6957 {
6958 const struct gen_device_info *devinfo = compiler->devinfo;
6959
6960 nir_shader *shader = nir_shader_clone(mem_ctx, src_shader);
6961 shader = brw_nir_apply_sampler_key(shader, compiler, &key->tex, true);
6962 brw_nir_lower_fs_inputs(shader, devinfo, key);
6963 brw_nir_lower_fs_outputs(shader);
6964
6965 if (devinfo->gen < 6) {
6966 brw_setup_vue_interpolation(vue_map, shader, prog_data, devinfo);
6967 }
6968
6969 if (!key->multisample_fbo)
6970 NIR_PASS_V(shader, demote_sample_qualifiers);
6971 NIR_PASS_V(shader, move_interpolation_to_top);
6972 shader = brw_postprocess_nir(shader, compiler, true);
6973
6974 /* key->alpha_test_func means simulating alpha testing via discards,
6975 * so the shader definitely kills pixels.
6976 */
6977 prog_data->uses_kill = shader->info.fs.uses_discard ||
6978 key->alpha_test_func;
6979 prog_data->uses_omask = key->multisample_fbo &&
6980 shader->info.outputs_written & BITFIELD64_BIT(FRAG_RESULT_SAMPLE_MASK);
6981 prog_data->computed_depth_mode = computed_depth_mode(shader);
6982 prog_data->computed_stencil =
6983 shader->info.outputs_written & BITFIELD64_BIT(FRAG_RESULT_STENCIL);
6984
6985 prog_data->persample_dispatch =
6986 key->multisample_fbo &&
6987 (key->persample_interp ||
6988 (shader->info.system_values_read & (SYSTEM_BIT_SAMPLE_ID |
6989 SYSTEM_BIT_SAMPLE_POS)) ||
6990 shader->info.fs.uses_sample_qualifier ||
6991 shader->info.outputs_read);
6992
6993 prog_data->has_render_target_reads = shader->info.outputs_read != 0ull;
6994
6995 prog_data->early_fragment_tests = shader->info.fs.early_fragment_tests;
6996 prog_data->post_depth_coverage = shader->info.fs.post_depth_coverage;
6997 prog_data->inner_coverage = shader->info.fs.inner_coverage;
6998
6999 prog_data->barycentric_interp_modes =
7000 brw_compute_barycentric_interp_modes(compiler->devinfo, shader);
7001
7002 cfg_t *simd8_cfg = NULL, *simd16_cfg = NULL;
7003 uint8_t simd8_grf_start = 0, simd16_grf_start = 0;
7004 unsigned simd8_grf_used = 0, simd16_grf_used = 0;
7005
7006 fs_visitor v8(compiler, log_data, mem_ctx, key,
7007 &prog_data->base, prog, shader, 8,
7008 shader_time_index8);
7009 if (!v8.run_fs(allow_spilling, false /* do_rep_send */)) {
7010 if (error_str)
7011 *error_str = ralloc_strdup(mem_ctx, v8.fail_msg);
7012
7013 return NULL;
7014 } else if (likely(!(INTEL_DEBUG & DEBUG_NO8))) {
7015 simd8_cfg = v8.cfg;
7016 simd8_grf_start = v8.payload.num_regs;
7017 simd8_grf_used = v8.grf_used;
7018 }
7019
7020 if (v8.max_dispatch_width >= 16 &&
7021 likely(!(INTEL_DEBUG & DEBUG_NO16) || use_rep_send)) {
7022 /* Try a SIMD16 compile */
7023 fs_visitor v16(compiler, log_data, mem_ctx, key,
7024 &prog_data->base, prog, shader, 16,
7025 shader_time_index16);
7026 v16.import_uniforms(&v8);
7027 if (!v16.run_fs(allow_spilling, use_rep_send)) {
7028 compiler->shader_perf_log(log_data,
7029 "SIMD16 shader failed to compile: %s",
7030 v16.fail_msg);
7031 } else {
7032 simd16_cfg = v16.cfg;
7033 simd16_grf_start = v16.payload.num_regs;
7034 simd16_grf_used = v16.grf_used;
7035 }
7036 }
7037
7038 /* When the caller requests a repclear shader, they want SIMD16-only */
7039 if (use_rep_send)
7040 simd8_cfg = NULL;
7041
7042 /* Prior to Iron Lake, the PS had a single shader offset with a jump table
7043 * at the top to select the shader. We've never implemented that.
7044 * Instead, we just give them exactly one shader and we pick the widest one
7045 * available.
7046 */
7047 if (compiler->devinfo->gen < 5 && simd16_cfg)
7048 simd8_cfg = NULL;
7049
7050 if (prog_data->persample_dispatch) {
7051 /* Starting with SandyBridge (where we first get MSAA), the different
7052 * pixel dispatch combinations are grouped into classifications A
7053 * through F (SNB PRM Vol. 2 Part 1 Section 7.7.1). On all hardware
7054 * generations, the only configurations supporting persample dispatch
7055 * are are this in which only one dispatch width is enabled.
7056 *
7057 * If computed depth is enabled, SNB only allows SIMD8 while IVB+
7058 * allow SIMD8 or SIMD16 so we choose SIMD16 if available.
7059 */
7060 if (compiler->devinfo->gen == 6 &&
7061 prog_data->computed_depth_mode != BRW_PSCDEPTH_OFF) {
7062 simd16_cfg = NULL;
7063 } else if (simd16_cfg) {
7064 simd8_cfg = NULL;
7065 }
7066 }
7067
7068 /* We have to compute the flat inputs after the visitor is finished running
7069 * because it relies on prog_data->urb_setup which is computed in
7070 * fs_visitor::calculate_urb_setup().
7071 */
7072 brw_compute_flat_inputs(prog_data, shader);
7073
7074 fs_generator g(compiler, log_data, mem_ctx, (void *) key, &prog_data->base,
7075 v8.promoted_constants, v8.runtime_check_aads_emit,
7076 MESA_SHADER_FRAGMENT);
7077
7078 if (unlikely(INTEL_DEBUG & DEBUG_WM)) {
7079 g.enable_debug(ralloc_asprintf(mem_ctx, "%s fragment shader %s",
7080 shader->info.label ?
7081 shader->info.label : "unnamed",
7082 shader->info.name));
7083 }
7084
7085 if (simd8_cfg) {
7086 prog_data->dispatch_8 = true;
7087 g.generate_code(simd8_cfg, 8);
7088 prog_data->base.dispatch_grf_start_reg = simd8_grf_start;
7089 prog_data->reg_blocks_0 = brw_register_blocks(simd8_grf_used);
7090
7091 if (simd16_cfg) {
7092 prog_data->dispatch_16 = true;
7093 prog_data->prog_offset_2 = g.generate_code(simd16_cfg, 16);
7094 prog_data->dispatch_grf_start_reg_2 = simd16_grf_start;
7095 prog_data->reg_blocks_2 = brw_register_blocks(simd16_grf_used);
7096 }
7097 } else if (simd16_cfg) {
7098 prog_data->dispatch_16 = true;
7099 g.generate_code(simd16_cfg, 16);
7100 prog_data->base.dispatch_grf_start_reg = simd16_grf_start;
7101 prog_data->reg_blocks_0 = brw_register_blocks(simd16_grf_used);
7102 }
7103
7104 return g.get_assembly();
7105 }
7106
7107 fs_reg *
7108 fs_visitor::emit_cs_work_group_id_setup()
7109 {
7110 assert(stage == MESA_SHADER_COMPUTE);
7111
7112 fs_reg *reg = new(this->mem_ctx) fs_reg(vgrf(glsl_type::uvec3_type));
7113
7114 struct brw_reg r0_1(retype(brw_vec1_grf(0, 1), BRW_REGISTER_TYPE_UD));
7115 struct brw_reg r0_6(retype(brw_vec1_grf(0, 6), BRW_REGISTER_TYPE_UD));
7116 struct brw_reg r0_7(retype(brw_vec1_grf(0, 7), BRW_REGISTER_TYPE_UD));
7117
7118 bld.MOV(*reg, r0_1);
7119 bld.MOV(offset(*reg, bld, 1), r0_6);
7120 bld.MOV(offset(*reg, bld, 2), r0_7);
7121
7122 return reg;
7123 }
7124
7125 static void
7126 fill_push_const_block_info(struct brw_push_const_block *block, unsigned dwords)
7127 {
7128 block->dwords = dwords;
7129 block->regs = DIV_ROUND_UP(dwords, 8);
7130 block->size = block->regs * 32;
7131 }
7132
7133 static void
7134 cs_fill_push_const_info(const struct gen_device_info *devinfo,
7135 struct brw_cs_prog_data *cs_prog_data)
7136 {
7137 const struct brw_stage_prog_data *prog_data = &cs_prog_data->base;
7138 int subgroup_id_index = get_subgroup_id_param_index(prog_data);
7139 bool cross_thread_supported = devinfo->gen > 7 || devinfo->is_haswell;
7140
7141 /* The thread ID should be stored in the last param dword */
7142 assert(subgroup_id_index == -1 ||
7143 subgroup_id_index == (int)prog_data->nr_params - 1);
7144
7145 unsigned cross_thread_dwords, per_thread_dwords;
7146 if (!cross_thread_supported) {
7147 cross_thread_dwords = 0u;
7148 per_thread_dwords = prog_data->nr_params;
7149 } else if (subgroup_id_index >= 0) {
7150 /* Fill all but the last register with cross-thread payload */
7151 cross_thread_dwords = 8 * (subgroup_id_index / 8);
7152 per_thread_dwords = prog_data->nr_params - cross_thread_dwords;
7153 assert(per_thread_dwords > 0 && per_thread_dwords <= 8);
7154 } else {
7155 /* Fill all data using cross-thread payload */
7156 cross_thread_dwords = prog_data->nr_params;
7157 per_thread_dwords = 0u;
7158 }
7159
7160 fill_push_const_block_info(&cs_prog_data->push.cross_thread, cross_thread_dwords);
7161 fill_push_const_block_info(&cs_prog_data->push.per_thread, per_thread_dwords);
7162
7163 unsigned total_dwords =
7164 (cs_prog_data->push.per_thread.size * cs_prog_data->threads +
7165 cs_prog_data->push.cross_thread.size) / 4;
7166 fill_push_const_block_info(&cs_prog_data->push.total, total_dwords);
7167
7168 assert(cs_prog_data->push.cross_thread.dwords % 8 == 0 ||
7169 cs_prog_data->push.per_thread.size == 0);
7170 assert(cs_prog_data->push.cross_thread.dwords +
7171 cs_prog_data->push.per_thread.dwords ==
7172 prog_data->nr_params);
7173 }
7174
7175 static void
7176 cs_set_simd_size(struct brw_cs_prog_data *cs_prog_data, unsigned size)
7177 {
7178 cs_prog_data->simd_size = size;
7179 unsigned group_size = cs_prog_data->local_size[0] *
7180 cs_prog_data->local_size[1] * cs_prog_data->local_size[2];
7181 cs_prog_data->threads = (group_size + size - 1) / size;
7182 }
7183
7184 static nir_shader *
7185 compile_cs_to_nir(const struct brw_compiler *compiler,
7186 void *mem_ctx,
7187 const struct brw_cs_prog_key *key,
7188 struct brw_cs_prog_data *prog_data,
7189 const nir_shader *src_shader,
7190 unsigned dispatch_width)
7191 {
7192 nir_shader *shader = nir_shader_clone(mem_ctx, src_shader);
7193 shader = brw_nir_apply_sampler_key(shader, compiler, &key->tex, true);
7194 brw_nir_lower_cs_intrinsics(shader, dispatch_width);
7195 return brw_postprocess_nir(shader, compiler, true);
7196 }
7197
7198 const unsigned *
7199 brw_compile_cs(const struct brw_compiler *compiler, void *log_data,
7200 void *mem_ctx,
7201 const struct brw_cs_prog_key *key,
7202 struct brw_cs_prog_data *prog_data,
7203 const nir_shader *src_shader,
7204 int shader_time_index,
7205 char **error_str)
7206 {
7207 prog_data->local_size[0] = src_shader->info.cs.local_size[0];
7208 prog_data->local_size[1] = src_shader->info.cs.local_size[1];
7209 prog_data->local_size[2] = src_shader->info.cs.local_size[2];
7210 unsigned local_workgroup_size =
7211 src_shader->info.cs.local_size[0] * src_shader->info.cs.local_size[1] *
7212 src_shader->info.cs.local_size[2];
7213
7214 unsigned min_dispatch_width =
7215 DIV_ROUND_UP(local_workgroup_size, compiler->devinfo->max_cs_threads);
7216 min_dispatch_width = MAX2(8, min_dispatch_width);
7217 min_dispatch_width = util_next_power_of_two(min_dispatch_width);
7218 assert(min_dispatch_width <= 32);
7219
7220 fs_visitor *v8 = NULL, *v16 = NULL, *v32 = NULL;
7221 cfg_t *cfg = NULL;
7222 const char *fail_msg = NULL;
7223 unsigned promoted_constants;
7224
7225 /* Now the main event: Visit the shader IR and generate our CS IR for it.
7226 */
7227 if (min_dispatch_width <= 8) {
7228 nir_shader *nir8 = compile_cs_to_nir(compiler, mem_ctx, key,
7229 prog_data, src_shader, 8);
7230 v8 = new fs_visitor(compiler, log_data, mem_ctx, key, &prog_data->base,
7231 NULL, /* Never used in core profile */
7232 nir8, 8, shader_time_index);
7233 if (!v8->run_cs(min_dispatch_width)) {
7234 fail_msg = v8->fail_msg;
7235 } else {
7236 /* We should always be able to do SIMD32 for compute shaders */
7237 assert(v8->max_dispatch_width >= 32);
7238
7239 cfg = v8->cfg;
7240 cs_set_simd_size(prog_data, 8);
7241 cs_fill_push_const_info(compiler->devinfo, prog_data);
7242 promoted_constants = v8->promoted_constants;
7243 }
7244 }
7245
7246 if (likely(!(INTEL_DEBUG & DEBUG_NO16)) &&
7247 !fail_msg && min_dispatch_width <= 16) {
7248 /* Try a SIMD16 compile */
7249 nir_shader *nir16 = compile_cs_to_nir(compiler, mem_ctx, key,
7250 prog_data, src_shader, 16);
7251 v16 = new fs_visitor(compiler, log_data, mem_ctx, key, &prog_data->base,
7252 NULL, /* Never used in core profile */
7253 nir16, 16, shader_time_index);
7254 if (v8)
7255 v16->import_uniforms(v8);
7256
7257 if (!v16->run_cs(min_dispatch_width)) {
7258 compiler->shader_perf_log(log_data,
7259 "SIMD16 shader failed to compile: %s",
7260 v16->fail_msg);
7261 if (!cfg) {
7262 fail_msg =
7263 "Couldn't generate SIMD16 program and not "
7264 "enough threads for SIMD8";
7265 }
7266 } else {
7267 /* We should always be able to do SIMD32 for compute shaders */
7268 assert(v16->max_dispatch_width >= 32);
7269
7270 cfg = v16->cfg;
7271 cs_set_simd_size(prog_data, 16);
7272 cs_fill_push_const_info(compiler->devinfo, prog_data);
7273 promoted_constants = v16->promoted_constants;
7274 }
7275 }
7276
7277 /* We should always be able to do SIMD32 for compute shaders */
7278 assert(!v16 || v16->max_dispatch_width >= 32);
7279
7280 if (!fail_msg && (min_dispatch_width > 16 || (INTEL_DEBUG & DEBUG_DO32))) {
7281 /* Try a SIMD32 compile */
7282 nir_shader *nir32 = compile_cs_to_nir(compiler, mem_ctx, key,
7283 prog_data, src_shader, 32);
7284 v32 = new fs_visitor(compiler, log_data, mem_ctx, key, &prog_data->base,
7285 NULL, /* Never used in core profile */
7286 nir32, 32, shader_time_index);
7287 if (v8)
7288 v32->import_uniforms(v8);
7289 else if (v16)
7290 v32->import_uniforms(v16);
7291
7292 if (!v32->run_cs(min_dispatch_width)) {
7293 compiler->shader_perf_log(log_data,
7294 "SIMD32 shader failed to compile: %s",
7295 v16->fail_msg);
7296 if (!cfg) {
7297 fail_msg =
7298 "Couldn't generate SIMD32 program and not "
7299 "enough threads for SIMD16";
7300 }
7301 } else {
7302 cfg = v32->cfg;
7303 cs_set_simd_size(prog_data, 32);
7304 cs_fill_push_const_info(compiler->devinfo, prog_data);
7305 promoted_constants = v32->promoted_constants;
7306 }
7307 }
7308
7309 const unsigned *ret = NULL;
7310 if (unlikely(cfg == NULL)) {
7311 assert(fail_msg);
7312 if (error_str)
7313 *error_str = ralloc_strdup(mem_ctx, fail_msg);
7314 } else {
7315 fs_generator g(compiler, log_data, mem_ctx, (void*) key, &prog_data->base,
7316 promoted_constants, false, MESA_SHADER_COMPUTE);
7317 if (INTEL_DEBUG & DEBUG_CS) {
7318 char *name = ralloc_asprintf(mem_ctx, "%s compute shader %s",
7319 src_shader->info.label ?
7320 src_shader->info.label : "unnamed",
7321 src_shader->info.name);
7322 g.enable_debug(name);
7323 }
7324
7325 g.generate_code(cfg, prog_data->simd_size);
7326
7327 ret = g.get_assembly();
7328 }
7329
7330 delete v8;
7331 delete v16;
7332 delete v32;
7333
7334 return ret;
7335 }
7336
7337 /**
7338 * Test the dispatch mask packing assumptions of
7339 * brw_stage_has_packed_dispatch(). Call this from e.g. the top of
7340 * fs_visitor::emit_nir_code() to cause a GPU hang if any shader invocation is
7341 * executed with an unexpected dispatch mask.
7342 */
7343 static UNUSED void
7344 brw_fs_test_dispatch_packing(const fs_builder &bld)
7345 {
7346 const gl_shader_stage stage = bld.shader->stage;
7347
7348 if (brw_stage_has_packed_dispatch(bld.shader->devinfo, stage,
7349 bld.shader->stage_prog_data)) {
7350 const fs_builder ubld = bld.exec_all().group(1, 0);
7351 const fs_reg tmp = component(bld.vgrf(BRW_REGISTER_TYPE_UD), 0);
7352 const fs_reg mask = (stage == MESA_SHADER_FRAGMENT ? brw_vmask_reg() :
7353 brw_dmask_reg());
7354
7355 ubld.ADD(tmp, mask, brw_imm_ud(1));
7356 ubld.AND(tmp, mask, tmp);
7357
7358 /* This will loop forever if the dispatch mask doesn't have the expected
7359 * form '2^n-1', in which case tmp will be non-zero.
7360 */
7361 bld.emit(BRW_OPCODE_DO);
7362 bld.CMP(bld.null_reg_ud(), tmp, brw_imm_ud(0), BRW_CONDITIONAL_NZ);
7363 set_predicate(BRW_PREDICATE_NORMAL, bld.emit(BRW_OPCODE_WHILE));
7364 }
7365 }