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