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