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