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