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