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