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