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