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