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