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