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