intel/fs: Add support for bindless image load/store/atomic
[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 component(interp_reg(VARYING_SLOT_POS, 2), 0));
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_integer_multiplication()
3881 {
3882 bool progress = false;
3883
3884 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
3885 const fs_builder ibld(this, block, inst);
3886
3887 if (inst->opcode == BRW_OPCODE_MUL) {
3888 if (inst->dst.is_accumulator() ||
3889 (inst->dst.type != BRW_REGISTER_TYPE_D &&
3890 inst->dst.type != BRW_REGISTER_TYPE_UD))
3891 continue;
3892
3893 if (devinfo->has_integer_dword_mul)
3894 continue;
3895
3896 if (inst->src[1].file == IMM &&
3897 inst->src[1].ud < (1 << 16)) {
3898 /* The MUL instruction isn't commutative. On Gen <= 6, only the low
3899 * 16-bits of src0 are read, and on Gen >= 7 only the low 16-bits of
3900 * src1 are used.
3901 *
3902 * If multiplying by an immediate value that fits in 16-bits, do a
3903 * single MUL instruction with that value in the proper location.
3904 */
3905 if (devinfo->gen < 7) {
3906 fs_reg imm(VGRF, alloc.allocate(dispatch_width / 8),
3907 inst->dst.type);
3908 ibld.MOV(imm, inst->src[1]);
3909 ibld.MUL(inst->dst, imm, inst->src[0]);
3910 } else {
3911 const bool ud = (inst->src[1].type == BRW_REGISTER_TYPE_UD);
3912 ibld.MUL(inst->dst, inst->src[0],
3913 ud ? brw_imm_uw(inst->src[1].ud)
3914 : brw_imm_w(inst->src[1].d));
3915 }
3916 } else {
3917 /* Gen < 8 (and some Gen8+ low-power parts like Cherryview) cannot
3918 * do 32-bit integer multiplication in one instruction, but instead
3919 * must do a sequence (which actually calculates a 64-bit result):
3920 *
3921 * mul(8) acc0<1>D g3<8,8,1>D g4<8,8,1>D
3922 * mach(8) null g3<8,8,1>D g4<8,8,1>D
3923 * mov(8) g2<1>D acc0<8,8,1>D
3924 *
3925 * But on Gen > 6, the ability to use second accumulator register
3926 * (acc1) for non-float data types was removed, preventing a simple
3927 * implementation in SIMD16. A 16-channel result can be calculated by
3928 * executing the three instructions twice in SIMD8, once with quarter
3929 * control of 1Q for the first eight channels and again with 2Q for
3930 * the second eight channels.
3931 *
3932 * Which accumulator register is implicitly accessed (by AccWrEnable
3933 * for instance) is determined by the quarter control. Unfortunately
3934 * Ivybridge (and presumably Baytrail) has a hardware bug in which an
3935 * implicit accumulator access by an instruction with 2Q will access
3936 * acc1 regardless of whether the data type is usable in acc1.
3937 *
3938 * Specifically, the 2Q mach(8) writes acc1 which does not exist for
3939 * integer data types.
3940 *
3941 * Since we only want the low 32-bits of the result, we can do two
3942 * 32-bit x 16-bit multiplies (like the mul and mach are doing), and
3943 * adjust the high result and add them (like the mach is doing):
3944 *
3945 * mul(8) g7<1>D g3<8,8,1>D g4.0<8,8,1>UW
3946 * mul(8) g8<1>D g3<8,8,1>D g4.1<8,8,1>UW
3947 * shl(8) g9<1>D g8<8,8,1>D 16D
3948 * add(8) g2<1>D g7<8,8,1>D g8<8,8,1>D
3949 *
3950 * We avoid the shl instruction by realizing that we only want to add
3951 * the low 16-bits of the "high" result to the high 16-bits of the
3952 * "low" result and using proper regioning on the add:
3953 *
3954 * mul(8) g7<1>D g3<8,8,1>D g4.0<16,8,2>UW
3955 * mul(8) g8<1>D g3<8,8,1>D g4.1<16,8,2>UW
3956 * add(8) g7.1<2>UW g7.1<16,8,2>UW g8<16,8,2>UW
3957 *
3958 * Since it does not use the (single) accumulator register, we can
3959 * schedule multi-component multiplications much better.
3960 */
3961
3962 bool needs_mov = false;
3963 fs_reg orig_dst = inst->dst;
3964
3965 /* Get a new VGRF for the "low" 32x16-bit multiplication result if
3966 * reusing the original destination is impossible due to hardware
3967 * restrictions, source/destination overlap, or it being the null
3968 * register.
3969 */
3970 fs_reg low = inst->dst;
3971 if (orig_dst.is_null() || orig_dst.file == MRF ||
3972 regions_overlap(inst->dst, inst->size_written,
3973 inst->src[0], inst->size_read(0)) ||
3974 regions_overlap(inst->dst, inst->size_written,
3975 inst->src[1], inst->size_read(1)) ||
3976 inst->dst.stride >= 4) {
3977 needs_mov = true;
3978 low = fs_reg(VGRF, alloc.allocate(regs_written(inst)),
3979 inst->dst.type);
3980 }
3981
3982 /* Get a new VGRF but keep the same stride as inst->dst */
3983 fs_reg high(VGRF, alloc.allocate(regs_written(inst)),
3984 inst->dst.type);
3985 high.stride = inst->dst.stride;
3986 high.offset = inst->dst.offset % REG_SIZE;
3987
3988 if (devinfo->gen >= 7) {
3989 if (inst->src[1].abs)
3990 lower_src_modifiers(this, block, inst, 1);
3991
3992 if (inst->src[1].file == IMM) {
3993 ibld.MUL(low, inst->src[0],
3994 brw_imm_uw(inst->src[1].ud & 0xffff));
3995 ibld.MUL(high, inst->src[0],
3996 brw_imm_uw(inst->src[1].ud >> 16));
3997 } else {
3998 ibld.MUL(low, inst->src[0],
3999 subscript(inst->src[1], BRW_REGISTER_TYPE_UW, 0));
4000 ibld.MUL(high, inst->src[0],
4001 subscript(inst->src[1], BRW_REGISTER_TYPE_UW, 1));
4002 }
4003 } else {
4004 if (inst->src[0].abs)
4005 lower_src_modifiers(this, block, inst, 0);
4006
4007 ibld.MUL(low, subscript(inst->src[0], BRW_REGISTER_TYPE_UW, 0),
4008 inst->src[1]);
4009 ibld.MUL(high, subscript(inst->src[0], BRW_REGISTER_TYPE_UW, 1),
4010 inst->src[1]);
4011 }
4012
4013 ibld.ADD(subscript(low, BRW_REGISTER_TYPE_UW, 1),
4014 subscript(low, BRW_REGISTER_TYPE_UW, 1),
4015 subscript(high, BRW_REGISTER_TYPE_UW, 0));
4016
4017 if (needs_mov || inst->conditional_mod) {
4018 set_condmod(inst->conditional_mod,
4019 ibld.MOV(orig_dst, low));
4020 }
4021 }
4022
4023 } else if (inst->opcode == SHADER_OPCODE_MULH) {
4024 /* According to the BDW+ BSpec page for the "Multiply Accumulate
4025 * High" instruction:
4026 *
4027 * "An added preliminary mov is required for source modification on
4028 * src1:
4029 * mov (8) r3.0<1>:d -r3<8;8,1>:d
4030 * mul (8) acc0:d r2.0<8;8,1>:d r3.0<16;8,2>:uw
4031 * mach (8) r5.0<1>:d r2.0<8;8,1>:d r3.0<8;8,1>:d"
4032 */
4033 if (devinfo->gen >= 8 && (inst->src[1].negate || inst->src[1].abs))
4034 lower_src_modifiers(this, block, inst, 1);
4035
4036 /* Should have been lowered to 8-wide. */
4037 assert(inst->exec_size <= get_lowered_simd_width(devinfo, inst));
4038 const fs_reg acc = retype(brw_acc_reg(inst->exec_size),
4039 inst->dst.type);
4040 fs_inst *mul = ibld.MUL(acc, inst->src[0], inst->src[1]);
4041 fs_inst *mach = ibld.MACH(inst->dst, inst->src[0], inst->src[1]);
4042
4043 if (devinfo->gen >= 8) {
4044 /* Until Gen8, integer multiplies read 32-bits from one source,
4045 * and 16-bits from the other, and relying on the MACH instruction
4046 * to generate the high bits of the result.
4047 *
4048 * On Gen8, the multiply instruction does a full 32x32-bit
4049 * multiply, but in order to do a 64-bit multiply we can simulate
4050 * the previous behavior and then use a MACH instruction.
4051 */
4052 assert(mul->src[1].type == BRW_REGISTER_TYPE_D ||
4053 mul->src[1].type == BRW_REGISTER_TYPE_UD);
4054 mul->src[1].type = BRW_REGISTER_TYPE_UW;
4055 mul->src[1].stride *= 2;
4056
4057 } else if (devinfo->gen == 7 && !devinfo->is_haswell &&
4058 inst->group > 0) {
4059 /* Among other things the quarter control bits influence which
4060 * accumulator register is used by the hardware for instructions
4061 * that access the accumulator implicitly (e.g. MACH). A
4062 * second-half instruction would normally map to acc1, which
4063 * doesn't exist on Gen7 and up (the hardware does emulate it for
4064 * floating-point instructions *only* by taking advantage of the
4065 * extra precision of acc0 not normally used for floating point
4066 * arithmetic).
4067 *
4068 * HSW and up are careful enough not to try to access an
4069 * accumulator register that doesn't exist, but on earlier Gen7
4070 * hardware we need to make sure that the quarter control bits are
4071 * zero to avoid non-deterministic behaviour and emit an extra MOV
4072 * to get the result masked correctly according to the current
4073 * channel enables.
4074 */
4075 mach->group = 0;
4076 mach->force_writemask_all = true;
4077 mach->dst = ibld.vgrf(inst->dst.type);
4078 ibld.MOV(inst->dst, mach->dst);
4079 }
4080 } else {
4081 continue;
4082 }
4083
4084 inst->remove(block);
4085 progress = true;
4086 }
4087
4088 if (progress)
4089 invalidate_live_intervals();
4090
4091 return progress;
4092 }
4093
4094 bool
4095 fs_visitor::lower_minmax()
4096 {
4097 assert(devinfo->gen < 6);
4098
4099 bool progress = false;
4100
4101 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
4102 const fs_builder ibld(this, block, inst);
4103
4104 if (inst->opcode == BRW_OPCODE_SEL &&
4105 inst->predicate == BRW_PREDICATE_NONE) {
4106 /* FIXME: Using CMP doesn't preserve the NaN propagation semantics of
4107 * the original SEL.L/GE instruction
4108 */
4109 ibld.CMP(ibld.null_reg_d(), inst->src[0], inst->src[1],
4110 inst->conditional_mod);
4111 inst->predicate = BRW_PREDICATE_NORMAL;
4112 inst->conditional_mod = BRW_CONDITIONAL_NONE;
4113
4114 progress = true;
4115 }
4116 }
4117
4118 if (progress)
4119 invalidate_live_intervals();
4120
4121 return progress;
4122 }
4123
4124 static void
4125 setup_color_payload(const fs_builder &bld, const brw_wm_prog_key *key,
4126 fs_reg *dst, fs_reg color, unsigned components)
4127 {
4128 if (key->clamp_fragment_color) {
4129 fs_reg tmp = bld.vgrf(BRW_REGISTER_TYPE_F, 4);
4130 assert(color.type == BRW_REGISTER_TYPE_F);
4131
4132 for (unsigned i = 0; i < components; i++)
4133 set_saturate(true,
4134 bld.MOV(offset(tmp, bld, i), offset(color, bld, i)));
4135
4136 color = tmp;
4137 }
4138
4139 for (unsigned i = 0; i < components; i++)
4140 dst[i] = offset(color, bld, i);
4141 }
4142
4143 static void
4144 lower_fb_write_logical_send(const fs_builder &bld, fs_inst *inst,
4145 const struct brw_wm_prog_data *prog_data,
4146 const brw_wm_prog_key *key,
4147 const fs_visitor::thread_payload &payload)
4148 {
4149 assert(inst->src[FB_WRITE_LOGICAL_SRC_COMPONENTS].file == IMM);
4150 const gen_device_info *devinfo = bld.shader->devinfo;
4151 const fs_reg &color0 = inst->src[FB_WRITE_LOGICAL_SRC_COLOR0];
4152 const fs_reg &color1 = inst->src[FB_WRITE_LOGICAL_SRC_COLOR1];
4153 const fs_reg &src0_alpha = inst->src[FB_WRITE_LOGICAL_SRC_SRC0_ALPHA];
4154 const fs_reg &src_depth = inst->src[FB_WRITE_LOGICAL_SRC_SRC_DEPTH];
4155 const fs_reg &dst_depth = inst->src[FB_WRITE_LOGICAL_SRC_DST_DEPTH];
4156 const fs_reg &src_stencil = inst->src[FB_WRITE_LOGICAL_SRC_SRC_STENCIL];
4157 fs_reg sample_mask = inst->src[FB_WRITE_LOGICAL_SRC_OMASK];
4158 const unsigned components =
4159 inst->src[FB_WRITE_LOGICAL_SRC_COMPONENTS].ud;
4160
4161 /* We can potentially have a message length of up to 15, so we have to set
4162 * base_mrf to either 0 or 1 in order to fit in m0..m15.
4163 */
4164 fs_reg sources[15];
4165 int header_size = 2, payload_header_size;
4166 unsigned length = 0;
4167
4168 if (devinfo->gen < 6) {
4169 /* TODO: Support SIMD32 on gen4-5 */
4170 assert(bld.group() < 16);
4171
4172 /* For gen4-5, we always have a header consisting of g0 and g1. We have
4173 * an implied MOV from g0,g1 to the start of the message. The MOV from
4174 * g0 is handled by the hardware and the MOV from g1 is provided by the
4175 * generator. This is required because, on gen4-5, the generator may
4176 * generate two write messages with different message lengths in order
4177 * to handle AA data properly.
4178 *
4179 * Also, since the pixel mask goes in the g0 portion of the message and
4180 * since render target writes are the last thing in the shader, we write
4181 * the pixel mask directly into g0 and it will get copied as part of the
4182 * implied write.
4183 */
4184 if (prog_data->uses_kill) {
4185 bld.exec_all().group(1, 0)
4186 .MOV(retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_UW),
4187 brw_flag_reg(0, 1));
4188 }
4189
4190 assert(length == 0);
4191 length = 2;
4192 } else if ((devinfo->gen <= 7 && !devinfo->is_haswell &&
4193 prog_data->uses_kill) ||
4194 color1.file != BAD_FILE ||
4195 key->nr_color_regions > 1) {
4196 /* From the Sandy Bridge PRM, volume 4, page 198:
4197 *
4198 * "Dispatched Pixel Enables. One bit per pixel indicating
4199 * which pixels were originally enabled when the thread was
4200 * dispatched. This field is only required for the end-of-
4201 * thread message and on all dual-source messages."
4202 */
4203 const fs_builder ubld = bld.exec_all().group(8, 0);
4204
4205 fs_reg header = ubld.vgrf(BRW_REGISTER_TYPE_UD, 2);
4206 if (bld.group() < 16) {
4207 /* The header starts off as g0 and g1 for the first half */
4208 ubld.group(16, 0).MOV(header, retype(brw_vec8_grf(0, 0),
4209 BRW_REGISTER_TYPE_UD));
4210 } else {
4211 /* The header starts off as g0 and g2 for the second half */
4212 assert(bld.group() < 32);
4213 const fs_reg header_sources[2] = {
4214 retype(brw_vec8_grf(0, 0), BRW_REGISTER_TYPE_UD),
4215 retype(brw_vec8_grf(2, 0), BRW_REGISTER_TYPE_UD),
4216 };
4217 ubld.LOAD_PAYLOAD(header, header_sources, 2, 0);
4218 }
4219
4220 uint32_t g00_bits = 0;
4221
4222 /* Set "Source0 Alpha Present to RenderTarget" bit in message
4223 * header.
4224 */
4225 if (inst->target > 0 && prog_data->replicate_alpha)
4226 g00_bits |= 1 << 11;
4227
4228 /* Set computes stencil to render target */
4229 if (prog_data->computed_stencil)
4230 g00_bits |= 1 << 14;
4231
4232 if (g00_bits) {
4233 /* OR extra bits into g0.0 */
4234 ubld.group(1, 0).OR(component(header, 0),
4235 retype(brw_vec1_grf(0, 0),
4236 BRW_REGISTER_TYPE_UD),
4237 brw_imm_ud(g00_bits));
4238 }
4239
4240 /* Set the render target index for choosing BLEND_STATE. */
4241 if (inst->target > 0) {
4242 ubld.group(1, 0).MOV(component(header, 2), brw_imm_ud(inst->target));
4243 }
4244
4245 if (prog_data->uses_kill) {
4246 assert(bld.group() < 16);
4247 ubld.group(1, 0).MOV(retype(component(header, 15),
4248 BRW_REGISTER_TYPE_UW),
4249 brw_flag_reg(0, 1));
4250 }
4251
4252 assert(length == 0);
4253 sources[0] = header;
4254 sources[1] = horiz_offset(header, 8);
4255 length = 2;
4256 }
4257 assert(length == 0 || length == 2);
4258 header_size = length;
4259
4260 if (payload.aa_dest_stencil_reg[0]) {
4261 assert(inst->group < 16);
4262 sources[length] = fs_reg(VGRF, bld.shader->alloc.allocate(1));
4263 bld.group(8, 0).exec_all().annotate("FB write stencil/AA alpha")
4264 .MOV(sources[length],
4265 fs_reg(brw_vec8_grf(payload.aa_dest_stencil_reg[0], 0)));
4266 length++;
4267 }
4268
4269 if (src0_alpha.file != BAD_FILE) {
4270 for (unsigned i = 0; i < bld.dispatch_width() / 8; i++) {
4271 const fs_builder &ubld = bld.exec_all().group(8, i)
4272 .annotate("FB write src0 alpha");
4273 const fs_reg tmp = ubld.vgrf(BRW_REGISTER_TYPE_F);
4274 ubld.MOV(tmp, horiz_offset(src0_alpha, i * 8));
4275 setup_color_payload(ubld, key, &sources[length], tmp, 1);
4276 length++;
4277 }
4278 } else if (prog_data->replicate_alpha && inst->target != 0) {
4279 /* Handle the case when fragment shader doesn't write to draw buffer
4280 * zero. No need to call setup_color_payload() for src0_alpha because
4281 * alpha value will be undefined.
4282 */
4283 length += bld.dispatch_width() / 8;
4284 }
4285
4286 if (sample_mask.file != BAD_FILE) {
4287 sources[length] = fs_reg(VGRF, bld.shader->alloc.allocate(1),
4288 BRW_REGISTER_TYPE_UD);
4289
4290 /* Hand over gl_SampleMask. Only the lower 16 bits of each channel are
4291 * relevant. Since it's unsigned single words one vgrf is always
4292 * 16-wide, but only the lower or higher 8 channels will be used by the
4293 * hardware when doing a SIMD8 write depending on whether we have
4294 * selected the subspans for the first or second half respectively.
4295 */
4296 assert(sample_mask.file != BAD_FILE && type_sz(sample_mask.type) == 4);
4297 sample_mask.type = BRW_REGISTER_TYPE_UW;
4298 sample_mask.stride *= 2;
4299
4300 bld.exec_all().annotate("FB write oMask")
4301 .MOV(horiz_offset(retype(sources[length], BRW_REGISTER_TYPE_UW),
4302 inst->group % 16),
4303 sample_mask);
4304 length++;
4305 }
4306
4307 payload_header_size = length;
4308
4309 setup_color_payload(bld, key, &sources[length], color0, components);
4310 length += 4;
4311
4312 if (color1.file != BAD_FILE) {
4313 setup_color_payload(bld, key, &sources[length], color1, components);
4314 length += 4;
4315 }
4316
4317 if (src_depth.file != BAD_FILE) {
4318 sources[length] = src_depth;
4319 length++;
4320 }
4321
4322 if (dst_depth.file != BAD_FILE) {
4323 sources[length] = dst_depth;
4324 length++;
4325 }
4326
4327 if (src_stencil.file != BAD_FILE) {
4328 assert(devinfo->gen >= 9);
4329 assert(bld.dispatch_width() == 8);
4330
4331 /* XXX: src_stencil is only available on gen9+. dst_depth is never
4332 * available on gen9+. As such it's impossible to have both enabled at the
4333 * same time and therefore length cannot overrun the array.
4334 */
4335 assert(length < 15);
4336
4337 sources[length] = bld.vgrf(BRW_REGISTER_TYPE_UD);
4338 bld.exec_all().annotate("FB write OS")
4339 .MOV(retype(sources[length], BRW_REGISTER_TYPE_UB),
4340 subscript(src_stencil, BRW_REGISTER_TYPE_UB, 0));
4341 length++;
4342 }
4343
4344 fs_inst *load;
4345 if (devinfo->gen >= 7) {
4346 /* Send from the GRF */
4347 fs_reg payload = fs_reg(VGRF, -1, BRW_REGISTER_TYPE_F);
4348 load = bld.LOAD_PAYLOAD(payload, sources, length, payload_header_size);
4349 payload.nr = bld.shader->alloc.allocate(regs_written(load));
4350 load->dst = payload;
4351
4352 inst->src[0] = payload;
4353 inst->resize_sources(1);
4354 } else {
4355 /* Send from the MRF */
4356 load = bld.LOAD_PAYLOAD(fs_reg(MRF, 1, BRW_REGISTER_TYPE_F),
4357 sources, length, payload_header_size);
4358
4359 /* On pre-SNB, we have to interlace the color values. LOAD_PAYLOAD
4360 * will do this for us if we just give it a COMPR4 destination.
4361 */
4362 if (devinfo->gen < 6 && bld.dispatch_width() == 16)
4363 load->dst.nr |= BRW_MRF_COMPR4;
4364
4365 if (devinfo->gen < 6) {
4366 /* Set up src[0] for the implied MOV from grf0-1 */
4367 inst->resize_sources(1);
4368 inst->src[0] = brw_vec8_grf(0, 0);
4369 } else {
4370 inst->resize_sources(0);
4371 }
4372 inst->base_mrf = 1;
4373 }
4374
4375 inst->opcode = FS_OPCODE_FB_WRITE;
4376 inst->mlen = regs_written(load);
4377 inst->header_size = header_size;
4378 }
4379
4380 static void
4381 lower_fb_read_logical_send(const fs_builder &bld, fs_inst *inst)
4382 {
4383 const fs_builder &ubld = bld.exec_all().group(8, 0);
4384 const unsigned length = 2;
4385 const fs_reg header = ubld.vgrf(BRW_REGISTER_TYPE_UD, length);
4386
4387 if (bld.group() < 16) {
4388 ubld.group(16, 0).MOV(header, retype(brw_vec8_grf(0, 0),
4389 BRW_REGISTER_TYPE_UD));
4390 } else {
4391 assert(bld.group() < 32);
4392 const fs_reg header_sources[] = {
4393 retype(brw_vec8_grf(0, 0), BRW_REGISTER_TYPE_UD),
4394 retype(brw_vec8_grf(2, 0), BRW_REGISTER_TYPE_UD)
4395 };
4396 ubld.LOAD_PAYLOAD(header, header_sources, ARRAY_SIZE(header_sources), 0);
4397 }
4398
4399 inst->resize_sources(1);
4400 inst->src[0] = header;
4401 inst->opcode = FS_OPCODE_FB_READ;
4402 inst->mlen = length;
4403 inst->header_size = length;
4404 }
4405
4406 static void
4407 lower_sampler_logical_send_gen4(const fs_builder &bld, fs_inst *inst, opcode op,
4408 const fs_reg &coordinate,
4409 const fs_reg &shadow_c,
4410 const fs_reg &lod, const fs_reg &lod2,
4411 const fs_reg &surface,
4412 const fs_reg &sampler,
4413 unsigned coord_components,
4414 unsigned grad_components)
4415 {
4416 const bool has_lod = (op == SHADER_OPCODE_TXL || op == FS_OPCODE_TXB ||
4417 op == SHADER_OPCODE_TXF || op == SHADER_OPCODE_TXS);
4418 fs_reg msg_begin(MRF, 1, BRW_REGISTER_TYPE_F);
4419 fs_reg msg_end = msg_begin;
4420
4421 /* g0 header. */
4422 msg_end = offset(msg_end, bld.group(8, 0), 1);
4423
4424 for (unsigned i = 0; i < coord_components; i++)
4425 bld.MOV(retype(offset(msg_end, bld, i), coordinate.type),
4426 offset(coordinate, bld, i));
4427
4428 msg_end = offset(msg_end, bld, coord_components);
4429
4430 /* Messages other than SAMPLE and RESINFO in SIMD16 and TXD in SIMD8
4431 * require all three components to be present and zero if they are unused.
4432 */
4433 if (coord_components > 0 &&
4434 (has_lod || shadow_c.file != BAD_FILE ||
4435 (op == SHADER_OPCODE_TEX && bld.dispatch_width() == 8))) {
4436 for (unsigned i = coord_components; i < 3; i++)
4437 bld.MOV(offset(msg_end, bld, i), brw_imm_f(0.0f));
4438
4439 msg_end = offset(msg_end, bld, 3 - coord_components);
4440 }
4441
4442 if (op == SHADER_OPCODE_TXD) {
4443 /* TXD unsupported in SIMD16 mode. */
4444 assert(bld.dispatch_width() == 8);
4445
4446 /* the slots for u and v are always present, but r is optional */
4447 if (coord_components < 2)
4448 msg_end = offset(msg_end, bld, 2 - coord_components);
4449
4450 /* P = u, v, r
4451 * dPdx = dudx, dvdx, drdx
4452 * dPdy = dudy, dvdy, drdy
4453 *
4454 * 1-arg: Does not exist.
4455 *
4456 * 2-arg: dudx dvdx dudy dvdy
4457 * dPdx.x dPdx.y dPdy.x dPdy.y
4458 * m4 m5 m6 m7
4459 *
4460 * 3-arg: dudx dvdx drdx dudy dvdy drdy
4461 * dPdx.x dPdx.y dPdx.z dPdy.x dPdy.y dPdy.z
4462 * m5 m6 m7 m8 m9 m10
4463 */
4464 for (unsigned i = 0; i < grad_components; i++)
4465 bld.MOV(offset(msg_end, bld, i), offset(lod, bld, i));
4466
4467 msg_end = offset(msg_end, bld, MAX2(grad_components, 2));
4468
4469 for (unsigned i = 0; i < grad_components; i++)
4470 bld.MOV(offset(msg_end, bld, i), offset(lod2, bld, i));
4471
4472 msg_end = offset(msg_end, bld, MAX2(grad_components, 2));
4473 }
4474
4475 if (has_lod) {
4476 /* Bias/LOD with shadow comparator is unsupported in SIMD16 -- *Without*
4477 * shadow comparator (including RESINFO) it's unsupported in SIMD8 mode.
4478 */
4479 assert(shadow_c.file != BAD_FILE ? bld.dispatch_width() == 8 :
4480 bld.dispatch_width() == 16);
4481
4482 const brw_reg_type type =
4483 (op == SHADER_OPCODE_TXF || op == SHADER_OPCODE_TXS ?
4484 BRW_REGISTER_TYPE_UD : BRW_REGISTER_TYPE_F);
4485 bld.MOV(retype(msg_end, type), lod);
4486 msg_end = offset(msg_end, bld, 1);
4487 }
4488
4489 if (shadow_c.file != BAD_FILE) {
4490 if (op == SHADER_OPCODE_TEX && bld.dispatch_width() == 8) {
4491 /* There's no plain shadow compare message, so we use shadow
4492 * compare with a bias of 0.0.
4493 */
4494 bld.MOV(msg_end, brw_imm_f(0.0f));
4495 msg_end = offset(msg_end, bld, 1);
4496 }
4497
4498 bld.MOV(msg_end, shadow_c);
4499 msg_end = offset(msg_end, bld, 1);
4500 }
4501
4502 inst->opcode = op;
4503 inst->src[0] = reg_undef;
4504 inst->src[1] = surface;
4505 inst->src[2] = sampler;
4506 inst->resize_sources(3);
4507 inst->base_mrf = msg_begin.nr;
4508 inst->mlen = msg_end.nr - msg_begin.nr;
4509 inst->header_size = 1;
4510 }
4511
4512 static void
4513 lower_sampler_logical_send_gen5(const fs_builder &bld, fs_inst *inst, opcode op,
4514 const fs_reg &coordinate,
4515 const fs_reg &shadow_c,
4516 const fs_reg &lod, const fs_reg &lod2,
4517 const fs_reg &sample_index,
4518 const fs_reg &surface,
4519 const fs_reg &sampler,
4520 unsigned coord_components,
4521 unsigned grad_components)
4522 {
4523 fs_reg message(MRF, 2, BRW_REGISTER_TYPE_F);
4524 fs_reg msg_coords = message;
4525 unsigned header_size = 0;
4526
4527 if (inst->offset != 0) {
4528 /* The offsets set up by the visitor are in the m1 header, so we can't
4529 * go headerless.
4530 */
4531 header_size = 1;
4532 message.nr--;
4533 }
4534
4535 for (unsigned i = 0; i < coord_components; i++)
4536 bld.MOV(retype(offset(msg_coords, bld, i), coordinate.type),
4537 offset(coordinate, bld, i));
4538
4539 fs_reg msg_end = offset(msg_coords, bld, coord_components);
4540 fs_reg msg_lod = offset(msg_coords, bld, 4);
4541
4542 if (shadow_c.file != BAD_FILE) {
4543 fs_reg msg_shadow = msg_lod;
4544 bld.MOV(msg_shadow, shadow_c);
4545 msg_lod = offset(msg_shadow, bld, 1);
4546 msg_end = msg_lod;
4547 }
4548
4549 switch (op) {
4550 case SHADER_OPCODE_TXL:
4551 case FS_OPCODE_TXB:
4552 bld.MOV(msg_lod, lod);
4553 msg_end = offset(msg_lod, bld, 1);
4554 break;
4555 case SHADER_OPCODE_TXD:
4556 /**
4557 * P = u, v, r
4558 * dPdx = dudx, dvdx, drdx
4559 * dPdy = dudy, dvdy, drdy
4560 *
4561 * Load up these values:
4562 * - dudx dudy dvdx dvdy drdx drdy
4563 * - dPdx.x dPdy.x dPdx.y dPdy.y dPdx.z dPdy.z
4564 */
4565 msg_end = msg_lod;
4566 for (unsigned i = 0; i < grad_components; i++) {
4567 bld.MOV(msg_end, offset(lod, bld, i));
4568 msg_end = offset(msg_end, bld, 1);
4569
4570 bld.MOV(msg_end, offset(lod2, bld, i));
4571 msg_end = offset(msg_end, bld, 1);
4572 }
4573 break;
4574 case SHADER_OPCODE_TXS:
4575 msg_lod = retype(msg_end, BRW_REGISTER_TYPE_UD);
4576 bld.MOV(msg_lod, lod);
4577 msg_end = offset(msg_lod, bld, 1);
4578 break;
4579 case SHADER_OPCODE_TXF:
4580 msg_lod = offset(msg_coords, bld, 3);
4581 bld.MOV(retype(msg_lod, BRW_REGISTER_TYPE_UD), lod);
4582 msg_end = offset(msg_lod, bld, 1);
4583 break;
4584 case SHADER_OPCODE_TXF_CMS:
4585 msg_lod = offset(msg_coords, bld, 3);
4586 /* lod */
4587 bld.MOV(retype(msg_lod, BRW_REGISTER_TYPE_UD), brw_imm_ud(0u));
4588 /* sample index */
4589 bld.MOV(retype(offset(msg_lod, bld, 1), BRW_REGISTER_TYPE_UD), sample_index);
4590 msg_end = offset(msg_lod, bld, 2);
4591 break;
4592 default:
4593 break;
4594 }
4595
4596 inst->opcode = op;
4597 inst->src[0] = reg_undef;
4598 inst->src[1] = surface;
4599 inst->src[2] = sampler;
4600 inst->resize_sources(3);
4601 inst->base_mrf = message.nr;
4602 inst->mlen = msg_end.nr - message.nr;
4603 inst->header_size = header_size;
4604
4605 /* Message length > MAX_SAMPLER_MESSAGE_SIZE disallowed by hardware. */
4606 assert(inst->mlen <= MAX_SAMPLER_MESSAGE_SIZE);
4607 }
4608
4609 static bool
4610 is_high_sampler(const struct gen_device_info *devinfo, const fs_reg &sampler)
4611 {
4612 if (devinfo->gen < 8 && !devinfo->is_haswell)
4613 return false;
4614
4615 return sampler.file != IMM || sampler.ud >= 16;
4616 }
4617
4618 static unsigned
4619 sampler_msg_type(const gen_device_info *devinfo,
4620 opcode opcode, bool shadow_compare)
4621 {
4622 assert(devinfo->gen >= 5);
4623 switch (opcode) {
4624 case SHADER_OPCODE_TEX:
4625 return shadow_compare ? GEN5_SAMPLER_MESSAGE_SAMPLE_COMPARE :
4626 GEN5_SAMPLER_MESSAGE_SAMPLE;
4627 case FS_OPCODE_TXB:
4628 return shadow_compare ? GEN5_SAMPLER_MESSAGE_SAMPLE_BIAS_COMPARE :
4629 GEN5_SAMPLER_MESSAGE_SAMPLE_BIAS;
4630 case SHADER_OPCODE_TXL:
4631 return shadow_compare ? GEN5_SAMPLER_MESSAGE_SAMPLE_LOD_COMPARE :
4632 GEN5_SAMPLER_MESSAGE_SAMPLE_LOD;
4633 case SHADER_OPCODE_TXL_LZ:
4634 return shadow_compare ? GEN9_SAMPLER_MESSAGE_SAMPLE_C_LZ :
4635 GEN9_SAMPLER_MESSAGE_SAMPLE_LZ;
4636 case SHADER_OPCODE_TXS:
4637 case SHADER_OPCODE_IMAGE_SIZE_LOGICAL:
4638 return GEN5_SAMPLER_MESSAGE_SAMPLE_RESINFO;
4639 case SHADER_OPCODE_TXD:
4640 assert(!shadow_compare || devinfo->gen >= 8 || devinfo->is_haswell);
4641 return shadow_compare ? HSW_SAMPLER_MESSAGE_SAMPLE_DERIV_COMPARE :
4642 GEN5_SAMPLER_MESSAGE_SAMPLE_DERIVS;
4643 case SHADER_OPCODE_TXF:
4644 return GEN5_SAMPLER_MESSAGE_SAMPLE_LD;
4645 case SHADER_OPCODE_TXF_LZ:
4646 assert(devinfo->gen >= 9);
4647 return GEN9_SAMPLER_MESSAGE_SAMPLE_LD_LZ;
4648 case SHADER_OPCODE_TXF_CMS_W:
4649 assert(devinfo->gen >= 9);
4650 return GEN9_SAMPLER_MESSAGE_SAMPLE_LD2DMS_W;
4651 case SHADER_OPCODE_TXF_CMS:
4652 return devinfo->gen >= 7 ? GEN7_SAMPLER_MESSAGE_SAMPLE_LD2DMS :
4653 GEN5_SAMPLER_MESSAGE_SAMPLE_LD;
4654 case SHADER_OPCODE_TXF_UMS:
4655 assert(devinfo->gen >= 7);
4656 return GEN7_SAMPLER_MESSAGE_SAMPLE_LD2DSS;
4657 case SHADER_OPCODE_TXF_MCS:
4658 assert(devinfo->gen >= 7);
4659 return GEN7_SAMPLER_MESSAGE_SAMPLE_LD_MCS;
4660 case SHADER_OPCODE_LOD:
4661 return GEN5_SAMPLER_MESSAGE_LOD;
4662 case SHADER_OPCODE_TG4:
4663 assert(devinfo->gen >= 7);
4664 return shadow_compare ? GEN7_SAMPLER_MESSAGE_SAMPLE_GATHER4_C :
4665 GEN7_SAMPLER_MESSAGE_SAMPLE_GATHER4;
4666 break;
4667 case SHADER_OPCODE_TG4_OFFSET:
4668 assert(devinfo->gen >= 7);
4669 return shadow_compare ? GEN7_SAMPLER_MESSAGE_SAMPLE_GATHER4_PO_C :
4670 GEN7_SAMPLER_MESSAGE_SAMPLE_GATHER4_PO;
4671 case SHADER_OPCODE_SAMPLEINFO:
4672 return GEN6_SAMPLER_MESSAGE_SAMPLE_SAMPLEINFO;
4673 default:
4674 unreachable("not reached");
4675 }
4676 }
4677
4678 static void
4679 lower_sampler_logical_send_gen7(const fs_builder &bld, fs_inst *inst, opcode op,
4680 const fs_reg &coordinate,
4681 const fs_reg &shadow_c,
4682 fs_reg lod, const fs_reg &lod2,
4683 const fs_reg &min_lod,
4684 const fs_reg &sample_index,
4685 const fs_reg &mcs,
4686 const fs_reg &surface,
4687 const fs_reg &sampler,
4688 const fs_reg &surface_handle,
4689 const fs_reg &sampler_handle,
4690 const fs_reg &tg4_offset,
4691 unsigned coord_components,
4692 unsigned grad_components)
4693 {
4694 const gen_device_info *devinfo = bld.shader->devinfo;
4695 const brw_stage_prog_data *prog_data = bld.shader->stage_prog_data;
4696 unsigned reg_width = bld.dispatch_width() / 8;
4697 unsigned header_size = 0, length = 0;
4698 fs_reg sources[MAX_SAMPLER_MESSAGE_SIZE];
4699 for (unsigned i = 0; i < ARRAY_SIZE(sources); i++)
4700 sources[i] = bld.vgrf(BRW_REGISTER_TYPE_F);
4701
4702 /* We must have exactly one of surface/sampler and surface/sampler_handle */
4703 assert((surface.file == BAD_FILE) != (surface_handle.file == BAD_FILE));
4704 assert((sampler.file == BAD_FILE) != (sampler_handle.file == BAD_FILE));
4705
4706 if (op == SHADER_OPCODE_TG4 || op == SHADER_OPCODE_TG4_OFFSET ||
4707 inst->offset != 0 || inst->eot ||
4708 op == SHADER_OPCODE_SAMPLEINFO ||
4709 sampler_handle.file != BAD_FILE ||
4710 is_high_sampler(devinfo, sampler)) {
4711 /* For general texture offsets (no txf workaround), we need a header to
4712 * put them in.
4713 *
4714 * TG4 needs to place its channel select in the header, for interaction
4715 * with ARB_texture_swizzle. The sampler index is only 4-bits, so for
4716 * larger sampler numbers we need to offset the Sampler State Pointer in
4717 * the header.
4718 */
4719 fs_reg header = retype(sources[0], BRW_REGISTER_TYPE_UD);
4720 header_size = 1;
4721 length++;
4722
4723 /* If we're requesting fewer than four channels worth of response,
4724 * and we have an explicit header, we need to set up the sampler
4725 * writemask. It's reversed from normal: 1 means "don't write".
4726 */
4727 if (!inst->eot && regs_written(inst) != 4 * reg_width) {
4728 assert(regs_written(inst) % reg_width == 0);
4729 unsigned mask = ~((1 << (regs_written(inst) / reg_width)) - 1) & 0xf;
4730 inst->offset |= mask << 12;
4731 }
4732
4733 /* Build the actual header */
4734 const fs_builder ubld = bld.exec_all().group(8, 0);
4735 const fs_builder ubld1 = ubld.group(1, 0);
4736 ubld.MOV(header, retype(brw_vec8_grf(0, 0), BRW_REGISTER_TYPE_UD));
4737 if (inst->offset) {
4738 ubld1.MOV(component(header, 2), brw_imm_ud(inst->offset));
4739 } else if (bld.shader->stage != MESA_SHADER_VERTEX &&
4740 bld.shader->stage != MESA_SHADER_FRAGMENT) {
4741 /* The vertex and fragment stages have g0.2 set to 0, so
4742 * header0.2 is 0 when g0 is copied. Other stages may not, so we
4743 * must set it to 0 to avoid setting undesirable bits in the
4744 * message.
4745 */
4746 ubld1.MOV(component(header, 2), brw_imm_ud(0));
4747 }
4748
4749 if (sampler_handle.file != BAD_FILE) {
4750 /* Bindless sampler handles aren't relative to the sampler state
4751 * pointer passed into the shader through SAMPLER_STATE_POINTERS_*.
4752 * Instead, it's an absolute pointer relative to dynamic state base
4753 * address.
4754 *
4755 * Sampler states are 16 bytes each and the pointer we give here has
4756 * to be 32-byte aligned. In order to avoid more indirect messages
4757 * than required, we assume that all bindless sampler states are
4758 * 32-byte aligned. This sacrifices a bit of general state base
4759 * address space but means we can do something more efficient in the
4760 * shader.
4761 */
4762 ubld1.MOV(component(header, 3), sampler_handle);
4763 } else if (is_high_sampler(devinfo, sampler)) {
4764 if (sampler.file == BRW_IMMEDIATE_VALUE) {
4765 assert(sampler.ud >= 16);
4766 const int sampler_state_size = 16; /* 16 bytes */
4767
4768 ubld1.ADD(component(header, 3),
4769 retype(brw_vec1_grf(0, 3), BRW_REGISTER_TYPE_UD),
4770 brw_imm_ud(16 * (sampler.ud / 16) * sampler_state_size));
4771 } else {
4772 fs_reg tmp = ubld1.vgrf(BRW_REGISTER_TYPE_UD);
4773 ubld1.AND(tmp, sampler, brw_imm_ud(0x0f0));
4774 ubld1.SHL(tmp, tmp, brw_imm_ud(4));
4775 ubld1.ADD(component(header, 3),
4776 retype(brw_vec1_grf(0, 3), BRW_REGISTER_TYPE_UD),
4777 tmp);
4778 }
4779 }
4780 }
4781
4782 if (shadow_c.file != BAD_FILE) {
4783 bld.MOV(sources[length], shadow_c);
4784 length++;
4785 }
4786
4787 bool coordinate_done = false;
4788
4789 /* Set up the LOD info */
4790 switch (op) {
4791 case FS_OPCODE_TXB:
4792 case SHADER_OPCODE_TXL:
4793 if (devinfo->gen >= 9 && op == SHADER_OPCODE_TXL && lod.is_zero()) {
4794 op = SHADER_OPCODE_TXL_LZ;
4795 break;
4796 }
4797 bld.MOV(sources[length], lod);
4798 length++;
4799 break;
4800 case SHADER_OPCODE_TXD:
4801 /* TXD should have been lowered in SIMD16 mode. */
4802 assert(bld.dispatch_width() == 8);
4803
4804 /* Load dPdx and the coordinate together:
4805 * [hdr], [ref], x, dPdx.x, dPdy.x, y, dPdx.y, dPdy.y, z, dPdx.z, dPdy.z
4806 */
4807 for (unsigned i = 0; i < coord_components; i++) {
4808 bld.MOV(sources[length++], offset(coordinate, bld, i));
4809
4810 /* For cube map array, the coordinate is (u,v,r,ai) but there are
4811 * only derivatives for (u, v, r).
4812 */
4813 if (i < grad_components) {
4814 bld.MOV(sources[length++], offset(lod, bld, i));
4815 bld.MOV(sources[length++], offset(lod2, bld, i));
4816 }
4817 }
4818
4819 coordinate_done = true;
4820 break;
4821 case SHADER_OPCODE_TXS:
4822 bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_UD), lod);
4823 length++;
4824 break;
4825 case SHADER_OPCODE_IMAGE_SIZE_LOGICAL:
4826 /* We need an LOD; just use 0 */
4827 bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_UD), brw_imm_ud(0));
4828 length++;
4829 break;
4830 case SHADER_OPCODE_TXF:
4831 /* Unfortunately, the parameters for LD are intermixed: u, lod, v, r.
4832 * On Gen9 they are u, v, lod, r
4833 */
4834 bld.MOV(retype(sources[length++], BRW_REGISTER_TYPE_D), coordinate);
4835
4836 if (devinfo->gen >= 9) {
4837 if (coord_components >= 2) {
4838 bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_D),
4839 offset(coordinate, bld, 1));
4840 } else {
4841 sources[length] = brw_imm_d(0);
4842 }
4843 length++;
4844 }
4845
4846 if (devinfo->gen >= 9 && lod.is_zero()) {
4847 op = SHADER_OPCODE_TXF_LZ;
4848 } else {
4849 bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_D), lod);
4850 length++;
4851 }
4852
4853 for (unsigned i = devinfo->gen >= 9 ? 2 : 1; i < coord_components; i++)
4854 bld.MOV(retype(sources[length++], BRW_REGISTER_TYPE_D),
4855 offset(coordinate, bld, i));
4856
4857 coordinate_done = true;
4858 break;
4859
4860 case SHADER_OPCODE_TXF_CMS:
4861 case SHADER_OPCODE_TXF_CMS_W:
4862 case SHADER_OPCODE_TXF_UMS:
4863 case SHADER_OPCODE_TXF_MCS:
4864 if (op == SHADER_OPCODE_TXF_UMS ||
4865 op == SHADER_OPCODE_TXF_CMS ||
4866 op == SHADER_OPCODE_TXF_CMS_W) {
4867 bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_UD), sample_index);
4868 length++;
4869 }
4870
4871 if (op == SHADER_OPCODE_TXF_CMS || op == SHADER_OPCODE_TXF_CMS_W) {
4872 /* Data from the multisample control surface. */
4873 bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_UD), mcs);
4874 length++;
4875
4876 /* On Gen9+ we'll use ld2dms_w instead which has two registers for
4877 * the MCS data.
4878 */
4879 if (op == SHADER_OPCODE_TXF_CMS_W) {
4880 bld.MOV(retype(sources[length], BRW_REGISTER_TYPE_UD),
4881 mcs.file == IMM ?
4882 mcs :
4883 offset(mcs, bld, 1));
4884 length++;
4885 }
4886 }
4887
4888 /* There is no offsetting for this message; just copy in the integer
4889 * texture coordinates.
4890 */
4891 for (unsigned i = 0; i < coord_components; i++)
4892 bld.MOV(retype(sources[length++], BRW_REGISTER_TYPE_D),
4893 offset(coordinate, bld, i));
4894
4895 coordinate_done = true;
4896 break;
4897 case SHADER_OPCODE_TG4_OFFSET:
4898 /* More crazy intermixing */
4899 for (unsigned i = 0; i < 2; i++) /* u, v */
4900 bld.MOV(sources[length++], offset(coordinate, bld, i));
4901
4902 for (unsigned i = 0; i < 2; i++) /* offu, offv */
4903 bld.MOV(retype(sources[length++], BRW_REGISTER_TYPE_D),
4904 offset(tg4_offset, bld, i));
4905
4906 if (coord_components == 3) /* r if present */
4907 bld.MOV(sources[length++], offset(coordinate, bld, 2));
4908
4909 coordinate_done = true;
4910 break;
4911 default:
4912 break;
4913 }
4914
4915 /* Set up the coordinate (except for cases where it was done above) */
4916 if (!coordinate_done) {
4917 for (unsigned i = 0; i < coord_components; i++)
4918 bld.MOV(sources[length++], offset(coordinate, bld, i));
4919 }
4920
4921 if (min_lod.file != BAD_FILE) {
4922 /* Account for all of the missing coordinate sources */
4923 length += 4 - coord_components;
4924 if (op == SHADER_OPCODE_TXD)
4925 length += (3 - grad_components) * 2;
4926
4927 bld.MOV(sources[length++], min_lod);
4928 }
4929
4930 unsigned mlen;
4931 if (reg_width == 2)
4932 mlen = length * reg_width - header_size;
4933 else
4934 mlen = length * reg_width;
4935
4936 const fs_reg src_payload = fs_reg(VGRF, bld.shader->alloc.allocate(mlen),
4937 BRW_REGISTER_TYPE_F);
4938 bld.LOAD_PAYLOAD(src_payload, sources, length, header_size);
4939
4940 /* Generate the SEND. */
4941 inst->opcode = SHADER_OPCODE_SEND;
4942 inst->mlen = mlen;
4943 inst->header_size = header_size;
4944
4945 const unsigned msg_type =
4946 sampler_msg_type(devinfo, op, inst->shadow_compare);
4947 const unsigned simd_mode =
4948 inst->exec_size <= 8 ? BRW_SAMPLER_SIMD_MODE_SIMD8 :
4949 BRW_SAMPLER_SIMD_MODE_SIMD16;
4950
4951 uint32_t base_binding_table_index;
4952 switch (op) {
4953 case SHADER_OPCODE_TG4:
4954 case SHADER_OPCODE_TG4_OFFSET:
4955 base_binding_table_index = prog_data->binding_table.gather_texture_start;
4956 break;
4957 case SHADER_OPCODE_IMAGE_SIZE_LOGICAL:
4958 base_binding_table_index = prog_data->binding_table.image_start;
4959 break;
4960 default:
4961 base_binding_table_index = prog_data->binding_table.texture_start;
4962 break;
4963 }
4964
4965 inst->sfid = BRW_SFID_SAMPLER;
4966 if (surface.file == IMM &&
4967 (sampler.file == IMM || sampler_handle.file != BAD_FILE)) {
4968 inst->desc = brw_sampler_desc(devinfo,
4969 surface.ud + base_binding_table_index,
4970 sampler.file == IMM ? sampler.ud % 16 : 0,
4971 msg_type,
4972 simd_mode,
4973 0 /* return_format unused on gen7+ */);
4974 inst->src[0] = brw_imm_ud(0);
4975 inst->src[1] = brw_imm_ud(0); /* ex_desc */
4976 } else if (surface_handle.file != BAD_FILE) {
4977 /* Bindless surface */
4978 assert(devinfo->gen >= 9);
4979 inst->desc = brw_sampler_desc(devinfo,
4980 GEN9_BTI_BINDLESS,
4981 sampler.file == IMM ? sampler.ud % 16 : 0,
4982 msg_type,
4983 simd_mode,
4984 0 /* return_format unused on gen7+ */);
4985
4986 /* For bindless samplers, the entire address is included in the message
4987 * header so we can leave the portion in the message descriptor 0.
4988 */
4989 if (sampler_handle.file != BAD_FILE || sampler.file == IMM) {
4990 inst->src[0] = brw_imm_ud(0);
4991 } else {
4992 const fs_builder ubld = bld.group(1, 0).exec_all();
4993 fs_reg desc = ubld.vgrf(BRW_REGISTER_TYPE_UD);
4994 ubld.SHL(desc, sampler, brw_imm_ud(8));
4995 inst->src[0] = desc;
4996 }
4997
4998 /* We assume that the driver provided the handle in the top 20 bits so
4999 * we can use the surface handle directly as the extended descriptor.
5000 */
5001 inst->src[1] = retype(surface_handle, BRW_REGISTER_TYPE_UD);
5002 } else {
5003 /* Immediate portion of the descriptor */
5004 inst->desc = brw_sampler_desc(devinfo,
5005 0, /* surface */
5006 0, /* sampler */
5007 msg_type,
5008 simd_mode,
5009 0 /* return_format unused on gen7+ */);
5010 const fs_builder ubld = bld.group(1, 0).exec_all();
5011 fs_reg desc = ubld.vgrf(BRW_REGISTER_TYPE_UD);
5012 if (surface.equals(sampler)) {
5013 /* This case is common in GL */
5014 ubld.MUL(desc, surface, brw_imm_ud(0x101));
5015 } else {
5016 if (sampler_handle.file != BAD_FILE) {
5017 ubld.MOV(desc, surface);
5018 } else if (sampler.file == IMM) {
5019 ubld.OR(desc, surface, brw_imm_ud(sampler.ud << 8));
5020 } else {
5021 ubld.SHL(desc, sampler, brw_imm_ud(8));
5022 ubld.OR(desc, desc, surface);
5023 }
5024 }
5025 if (base_binding_table_index)
5026 ubld.ADD(desc, desc, brw_imm_ud(base_binding_table_index));
5027 ubld.AND(desc, desc, brw_imm_ud(0xfff));
5028
5029 inst->src[0] = component(desc, 0);
5030 inst->src[1] = brw_imm_ud(0); /* ex_desc */
5031 }
5032
5033 inst->src[2] = src_payload;
5034 inst->resize_sources(3);
5035
5036 if (inst->eot) {
5037 /* EOT sampler messages don't make sense to split because it would
5038 * involve ending half of the thread early.
5039 */
5040 assert(inst->group == 0);
5041 /* We need to use SENDC for EOT sampler messages */
5042 inst->check_tdr = true;
5043 inst->send_has_side_effects = true;
5044 }
5045
5046 /* Message length > MAX_SAMPLER_MESSAGE_SIZE disallowed by hardware. */
5047 assert(inst->mlen <= MAX_SAMPLER_MESSAGE_SIZE);
5048 }
5049
5050 static void
5051 lower_sampler_logical_send(const fs_builder &bld, fs_inst *inst, opcode op)
5052 {
5053 const gen_device_info *devinfo = bld.shader->devinfo;
5054 const fs_reg &coordinate = inst->src[TEX_LOGICAL_SRC_COORDINATE];
5055 const fs_reg &shadow_c = inst->src[TEX_LOGICAL_SRC_SHADOW_C];
5056 const fs_reg &lod = inst->src[TEX_LOGICAL_SRC_LOD];
5057 const fs_reg &lod2 = inst->src[TEX_LOGICAL_SRC_LOD2];
5058 const fs_reg &min_lod = inst->src[TEX_LOGICAL_SRC_MIN_LOD];
5059 const fs_reg &sample_index = inst->src[TEX_LOGICAL_SRC_SAMPLE_INDEX];
5060 const fs_reg &mcs = inst->src[TEX_LOGICAL_SRC_MCS];
5061 const fs_reg &surface = inst->src[TEX_LOGICAL_SRC_SURFACE];
5062 const fs_reg &sampler = inst->src[TEX_LOGICAL_SRC_SAMPLER];
5063 const fs_reg &surface_handle = inst->src[TEX_LOGICAL_SRC_SURFACE_HANDLE];
5064 const fs_reg &sampler_handle = inst->src[TEX_LOGICAL_SRC_SAMPLER_HANDLE];
5065 const fs_reg &tg4_offset = inst->src[TEX_LOGICAL_SRC_TG4_OFFSET];
5066 assert(inst->src[TEX_LOGICAL_SRC_COORD_COMPONENTS].file == IMM);
5067 const unsigned coord_components = inst->src[TEX_LOGICAL_SRC_COORD_COMPONENTS].ud;
5068 assert(inst->src[TEX_LOGICAL_SRC_GRAD_COMPONENTS].file == IMM);
5069 const unsigned grad_components = inst->src[TEX_LOGICAL_SRC_GRAD_COMPONENTS].ud;
5070
5071 if (devinfo->gen >= 7) {
5072 lower_sampler_logical_send_gen7(bld, inst, op, coordinate,
5073 shadow_c, lod, lod2, min_lod,
5074 sample_index,
5075 mcs, surface, sampler,
5076 surface_handle, sampler_handle,
5077 tg4_offset,
5078 coord_components, grad_components);
5079 } else if (devinfo->gen >= 5) {
5080 lower_sampler_logical_send_gen5(bld, inst, op, coordinate,
5081 shadow_c, lod, lod2, sample_index,
5082 surface, sampler,
5083 coord_components, grad_components);
5084 } else {
5085 lower_sampler_logical_send_gen4(bld, inst, op, coordinate,
5086 shadow_c, lod, lod2,
5087 surface, sampler,
5088 coord_components, grad_components);
5089 }
5090 }
5091
5092 /**
5093 * Initialize the header present in some typed and untyped surface
5094 * messages.
5095 */
5096 static fs_reg
5097 emit_surface_header(const fs_builder &bld, const fs_reg &sample_mask)
5098 {
5099 fs_builder ubld = bld.exec_all().group(8, 0);
5100 const fs_reg dst = ubld.vgrf(BRW_REGISTER_TYPE_UD);
5101 ubld.MOV(dst, brw_imm_d(0));
5102 ubld.group(1, 0).MOV(component(dst, 7), sample_mask);
5103 return dst;
5104 }
5105
5106 static void
5107 lower_surface_logical_send(const fs_builder &bld, fs_inst *inst)
5108 {
5109 const gen_device_info *devinfo = bld.shader->devinfo;
5110
5111 /* Get the logical send arguments. */
5112 const fs_reg &addr = inst->src[SURFACE_LOGICAL_SRC_ADDRESS];
5113 const fs_reg &src = inst->src[SURFACE_LOGICAL_SRC_DATA];
5114 const fs_reg &surface = inst->src[SURFACE_LOGICAL_SRC_SURFACE];
5115 const fs_reg &surface_handle = inst->src[SURFACE_LOGICAL_SRC_SURFACE_HANDLE];
5116 const UNUSED fs_reg &dims = inst->src[SURFACE_LOGICAL_SRC_IMM_DIMS];
5117 const fs_reg &arg = inst->src[SURFACE_LOGICAL_SRC_IMM_ARG];
5118 assert(arg.file == IMM);
5119
5120 /* We must have exactly one of surface and surface_handle */
5121 assert((surface.file == BAD_FILE) != (surface_handle.file == BAD_FILE));
5122
5123 /* Calculate the total number of components of the payload. */
5124 const unsigned addr_sz = inst->components_read(SURFACE_LOGICAL_SRC_ADDRESS);
5125 const unsigned src_sz = inst->components_read(SURFACE_LOGICAL_SRC_DATA);
5126
5127 const bool is_typed_access =
5128 inst->opcode == SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL ||
5129 inst->opcode == SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL ||
5130 inst->opcode == SHADER_OPCODE_TYPED_ATOMIC_LOGICAL;
5131
5132 /* From the BDW PRM Volume 7, page 147:
5133 *
5134 * "For the Data Cache Data Port*, the header must be present for the
5135 * following message types: [...] Typed read/write/atomics"
5136 *
5137 * Earlier generations have a similar wording. Because of this restriction
5138 * we don't attempt to implement sample masks via predication for such
5139 * messages prior to Gen9, since we have to provide a header anyway. On
5140 * Gen11+ the header has been removed so we can only use predication.
5141 */
5142 const unsigned header_sz = devinfo->gen < 9 && is_typed_access ? 1 : 0;
5143
5144 const bool has_side_effects = inst->has_side_effects();
5145 fs_reg sample_mask = has_side_effects ? bld.sample_mask_reg() :
5146 fs_reg(brw_imm_d(0xffff));
5147
5148 fs_reg payload, payload2;
5149 unsigned mlen, ex_mlen = 0;
5150 if (devinfo->gen >= 9) {
5151 /* We have split sends on gen9 and above */
5152 assert(header_sz == 0);
5153 payload = bld.move_to_vgrf(addr, addr_sz);
5154 payload2 = bld.move_to_vgrf(src, src_sz);
5155 mlen = addr_sz * (inst->exec_size / 8);
5156 ex_mlen = src_sz * (inst->exec_size / 8);
5157 } else {
5158 /* Allocate space for the payload. */
5159 const unsigned sz = header_sz + addr_sz + src_sz;
5160 payload = bld.vgrf(BRW_REGISTER_TYPE_UD, sz);
5161 fs_reg *const components = new fs_reg[sz];
5162 unsigned n = 0;
5163
5164 /* Construct the payload. */
5165 if (header_sz)
5166 components[n++] = emit_surface_header(bld, sample_mask);
5167
5168 for (unsigned i = 0; i < addr_sz; i++)
5169 components[n++] = offset(addr, bld, i);
5170
5171 for (unsigned i = 0; i < src_sz; i++)
5172 components[n++] = offset(src, bld, i);
5173
5174 bld.LOAD_PAYLOAD(payload, components, sz, header_sz);
5175 mlen = header_sz + (addr_sz + src_sz) * inst->exec_size / 8;
5176
5177 delete[] components;
5178 }
5179
5180 /* Predicate the instruction on the sample mask if no header is
5181 * provided.
5182 */
5183 if (!header_sz && sample_mask.file != BAD_FILE &&
5184 sample_mask.file != IMM) {
5185 const fs_builder ubld = bld.group(1, 0).exec_all();
5186 if (inst->predicate) {
5187 assert(inst->predicate == BRW_PREDICATE_NORMAL);
5188 assert(!inst->predicate_inverse);
5189 assert(inst->flag_subreg < 2);
5190 /* Combine the sample mask with the existing predicate by using a
5191 * vertical predication mode.
5192 */
5193 inst->predicate = BRW_PREDICATE_ALIGN1_ALLV;
5194 ubld.MOV(retype(brw_flag_subreg(inst->flag_subreg + 2),
5195 sample_mask.type),
5196 sample_mask);
5197 } else {
5198 inst->flag_subreg = 2;
5199 inst->predicate = BRW_PREDICATE_NORMAL;
5200 inst->predicate_inverse = false;
5201 ubld.MOV(retype(brw_flag_subreg(inst->flag_subreg), sample_mask.type),
5202 sample_mask);
5203 }
5204 }
5205
5206 uint32_t sfid;
5207 switch (inst->opcode) {
5208 case SHADER_OPCODE_BYTE_SCATTERED_WRITE_LOGICAL:
5209 case SHADER_OPCODE_BYTE_SCATTERED_READ_LOGICAL:
5210 /* Byte scattered opcodes go through the normal data cache */
5211 sfid = GEN7_SFID_DATAPORT_DATA_CACHE;
5212 break;
5213
5214 case SHADER_OPCODE_UNTYPED_SURFACE_READ_LOGICAL:
5215 case SHADER_OPCODE_UNTYPED_SURFACE_WRITE_LOGICAL:
5216 case SHADER_OPCODE_UNTYPED_ATOMIC_LOGICAL:
5217 case SHADER_OPCODE_UNTYPED_ATOMIC_FLOAT_LOGICAL:
5218 /* Untyped Surface messages go through the data cache but the SFID value
5219 * changed on Haswell.
5220 */
5221 sfid = (devinfo->gen >= 8 || devinfo->is_haswell ?
5222 HSW_SFID_DATAPORT_DATA_CACHE_1 :
5223 GEN7_SFID_DATAPORT_DATA_CACHE);
5224 break;
5225
5226 case SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL:
5227 case SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL:
5228 case SHADER_OPCODE_TYPED_ATOMIC_LOGICAL:
5229 /* Typed surface messages go through the render cache on IVB and the
5230 * data cache on HSW+.
5231 */
5232 sfid = (devinfo->gen >= 8 || devinfo->is_haswell ?
5233 HSW_SFID_DATAPORT_DATA_CACHE_1 :
5234 GEN6_SFID_DATAPORT_RENDER_CACHE);
5235 break;
5236
5237 default:
5238 unreachable("Unsupported surface opcode");
5239 }
5240
5241 uint32_t desc;
5242 switch (inst->opcode) {
5243 case SHADER_OPCODE_UNTYPED_SURFACE_READ_LOGICAL:
5244 desc = brw_dp_untyped_surface_rw_desc(devinfo, inst->exec_size,
5245 arg.ud, /* num_channels */
5246 false /* write */);
5247 break;
5248
5249 case SHADER_OPCODE_UNTYPED_SURFACE_WRITE_LOGICAL:
5250 desc = brw_dp_untyped_surface_rw_desc(devinfo, inst->exec_size,
5251 arg.ud, /* num_channels */
5252 true /* write */);
5253 break;
5254
5255 case SHADER_OPCODE_BYTE_SCATTERED_READ_LOGICAL:
5256 desc = brw_dp_byte_scattered_rw_desc(devinfo, inst->exec_size,
5257 arg.ud, /* bit_size */
5258 false /* write */);
5259 break;
5260
5261 case SHADER_OPCODE_BYTE_SCATTERED_WRITE_LOGICAL:
5262 desc = brw_dp_byte_scattered_rw_desc(devinfo, inst->exec_size,
5263 arg.ud, /* bit_size */
5264 true /* write */);
5265 break;
5266
5267 case SHADER_OPCODE_UNTYPED_ATOMIC_LOGICAL:
5268 desc = brw_dp_untyped_atomic_desc(devinfo, inst->exec_size,
5269 arg.ud, /* atomic_op */
5270 !inst->dst.is_null());
5271 break;
5272
5273 case SHADER_OPCODE_UNTYPED_ATOMIC_FLOAT_LOGICAL:
5274 desc = brw_dp_untyped_atomic_float_desc(devinfo, inst->exec_size,
5275 arg.ud, /* atomic_op */
5276 !inst->dst.is_null());
5277 break;
5278
5279 case SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL:
5280 desc = brw_dp_typed_surface_rw_desc(devinfo, inst->exec_size, inst->group,
5281 arg.ud, /* num_channels */
5282 false /* write */);
5283 break;
5284
5285 case SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL:
5286 desc = brw_dp_typed_surface_rw_desc(devinfo, inst->exec_size, inst->group,
5287 arg.ud, /* num_channels */
5288 true /* write */);
5289 break;
5290
5291 case SHADER_OPCODE_TYPED_ATOMIC_LOGICAL:
5292 desc = brw_dp_typed_atomic_desc(devinfo, inst->exec_size, inst->group,
5293 arg.ud, /* atomic_op */
5294 !inst->dst.is_null());
5295 break;
5296
5297 default:
5298 unreachable("Unknown surface logical instruction");
5299 }
5300
5301 /* Update the original instruction. */
5302 inst->opcode = SHADER_OPCODE_SEND;
5303 inst->mlen = mlen;
5304 inst->ex_mlen = ex_mlen;
5305 inst->header_size = header_sz;
5306 inst->send_has_side_effects = has_side_effects;
5307 inst->send_is_volatile = !has_side_effects;
5308
5309 /* Set up SFID and descriptors */
5310 inst->sfid = sfid;
5311 inst->desc = desc;
5312 if (surface.file == IMM) {
5313 inst->desc |= surface.ud & 0xff;
5314 inst->src[0] = brw_imm_ud(0);
5315 inst->src[1] = brw_imm_ud(0); /* ex_desc */
5316 } else if (surface_handle.file != BAD_FILE) {
5317 /* Bindless surface */
5318 assert(devinfo->gen >= 9);
5319 inst->desc |= GEN9_BTI_BINDLESS;
5320 inst->src[0] = brw_imm_ud(0);
5321
5322 /* We assume that the driver provided the handle in the top 20 bits so
5323 * we can use the surface handle directly as the extended descriptor.
5324 */
5325 inst->src[1] = retype(surface_handle, BRW_REGISTER_TYPE_UD);
5326 } else {
5327 const fs_builder ubld = bld.exec_all().group(1, 0);
5328 fs_reg tmp = ubld.vgrf(BRW_REGISTER_TYPE_UD);
5329 ubld.AND(tmp, surface, brw_imm_ud(0xff));
5330 inst->src[0] = component(tmp, 0);
5331 inst->src[1] = brw_imm_ud(0); /* ex_desc */
5332 }
5333
5334 /* Finally, the payload */
5335 inst->src[2] = payload;
5336 inst->src[3] = payload2;
5337
5338 inst->resize_sources(4);
5339 }
5340
5341 static void
5342 lower_a64_logical_send(const fs_builder &bld, fs_inst *inst)
5343 {
5344 const gen_device_info *devinfo = bld.shader->devinfo;
5345
5346 const fs_reg &addr = inst->src[0];
5347 const fs_reg &src = inst->src[1];
5348 const unsigned src_comps = inst->components_read(1);
5349 assert(inst->src[2].file == IMM);
5350 const unsigned arg = inst->src[2].ud;
5351 const bool has_side_effects = inst->has_side_effects();
5352
5353 /* If the surface message has side effects and we're a fragment shader, we
5354 * have to predicate with the sample mask to avoid helper invocations.
5355 */
5356 if (has_side_effects && bld.shader->stage == MESA_SHADER_FRAGMENT) {
5357 inst->flag_subreg = 2;
5358 inst->predicate = BRW_PREDICATE_NORMAL;
5359 inst->predicate_inverse = false;
5360
5361 fs_reg sample_mask = bld.sample_mask_reg();
5362 const fs_builder ubld = bld.group(1, 0).exec_all();
5363 ubld.MOV(retype(brw_flag_subreg(inst->flag_subreg), sample_mask.type),
5364 sample_mask);
5365 }
5366
5367 fs_reg payload, payload2;
5368 unsigned mlen, ex_mlen = 0;
5369 if (devinfo->gen >= 9) {
5370 /* On Skylake and above, we have SENDS */
5371 mlen = 2 * (inst->exec_size / 8);
5372 ex_mlen = src_comps * type_sz(src.type) * inst->exec_size / REG_SIZE;
5373 payload = retype(bld.move_to_vgrf(addr, 1), BRW_REGISTER_TYPE_UD);
5374 payload2 = retype(bld.move_to_vgrf(src, src_comps),
5375 BRW_REGISTER_TYPE_UD);
5376 } else {
5377 /* Add two because the address is 64-bit */
5378 const unsigned dwords = 2 + src_comps;
5379 mlen = dwords * (inst->exec_size / 8);
5380
5381 fs_reg sources[5];
5382
5383 sources[0] = addr;
5384
5385 for (unsigned i = 0; i < src_comps; i++)
5386 sources[1 + i] = offset(src, bld, i);
5387
5388 payload = bld.vgrf(BRW_REGISTER_TYPE_UD, dwords);
5389 bld.LOAD_PAYLOAD(payload, sources, 1 + src_comps, 0);
5390 }
5391
5392 uint32_t desc;
5393 switch (inst->opcode) {
5394 case SHADER_OPCODE_A64_UNTYPED_READ_LOGICAL:
5395 desc = brw_dp_a64_untyped_surface_rw_desc(devinfo, inst->exec_size,
5396 arg, /* num_channels */
5397 false /* write */);
5398 break;
5399
5400 case SHADER_OPCODE_A64_UNTYPED_WRITE_LOGICAL:
5401 desc = brw_dp_a64_untyped_surface_rw_desc(devinfo, inst->exec_size,
5402 arg, /* num_channels */
5403 true /* write */);
5404 break;
5405
5406 case SHADER_OPCODE_A64_BYTE_SCATTERED_READ_LOGICAL:
5407 desc = brw_dp_a64_byte_scattered_rw_desc(devinfo, inst->exec_size,
5408 arg, /* bit_size */
5409 false /* write */);
5410 break;
5411
5412 case SHADER_OPCODE_A64_BYTE_SCATTERED_WRITE_LOGICAL:
5413 desc = brw_dp_a64_byte_scattered_rw_desc(devinfo, inst->exec_size,
5414 arg, /* bit_size */
5415 true /* write */);
5416 break;
5417
5418 case SHADER_OPCODE_A64_UNTYPED_ATOMIC_LOGICAL:
5419 desc = brw_dp_a64_untyped_atomic_desc(devinfo, inst->exec_size, 32,
5420 arg, /* atomic_op */
5421 !inst->dst.is_null());
5422 break;
5423
5424 case SHADER_OPCODE_A64_UNTYPED_ATOMIC_INT64_LOGICAL:
5425 desc = brw_dp_a64_untyped_atomic_desc(devinfo, inst->exec_size, 64,
5426 arg, /* atomic_op */
5427 !inst->dst.is_null());
5428 break;
5429
5430
5431 case SHADER_OPCODE_A64_UNTYPED_ATOMIC_FLOAT_LOGICAL:
5432 desc = brw_dp_a64_untyped_atomic_float_desc(devinfo, inst->exec_size,
5433 arg, /* atomic_op */
5434 !inst->dst.is_null());
5435 break;
5436
5437 default:
5438 unreachable("Unknown A64 logical instruction");
5439 }
5440
5441 /* Update the original instruction. */
5442 inst->opcode = SHADER_OPCODE_SEND;
5443 inst->mlen = mlen;
5444 inst->ex_mlen = ex_mlen;
5445 inst->header_size = 0;
5446 inst->send_has_side_effects = has_side_effects;
5447 inst->send_is_volatile = !has_side_effects;
5448
5449 /* Set up SFID and descriptors */
5450 inst->sfid = HSW_SFID_DATAPORT_DATA_CACHE_1;
5451 inst->desc = desc;
5452 inst->resize_sources(4);
5453 inst->src[0] = brw_imm_ud(0); /* desc */
5454 inst->src[1] = brw_imm_ud(0); /* ex_desc */
5455 inst->src[2] = payload;
5456 inst->src[3] = payload2;
5457 }
5458
5459 static void
5460 lower_varying_pull_constant_logical_send(const fs_builder &bld, fs_inst *inst)
5461 {
5462 const gen_device_info *devinfo = bld.shader->devinfo;
5463
5464 if (devinfo->gen >= 7) {
5465 fs_reg index = inst->src[0];
5466 /* We are switching the instruction from an ALU-like instruction to a
5467 * send-from-grf instruction. Since sends can't handle strides or
5468 * source modifiers, we have to make a copy of the offset source.
5469 */
5470 fs_reg offset = bld.vgrf(BRW_REGISTER_TYPE_UD);
5471 bld.MOV(offset, inst->src[1]);
5472
5473 const unsigned simd_mode =
5474 inst->exec_size <= 8 ? BRW_SAMPLER_SIMD_MODE_SIMD8 :
5475 BRW_SAMPLER_SIMD_MODE_SIMD16;
5476
5477 inst->opcode = SHADER_OPCODE_SEND;
5478 inst->mlen = inst->exec_size / 8;
5479 inst->resize_sources(3);
5480
5481 inst->sfid = BRW_SFID_SAMPLER;
5482 inst->desc = brw_sampler_desc(devinfo, 0, 0,
5483 GEN5_SAMPLER_MESSAGE_SAMPLE_LD,
5484 simd_mode, 0);
5485 if (index.file == IMM) {
5486 inst->desc |= index.ud & 0xff;
5487 inst->src[0] = brw_imm_ud(0);
5488 } else {
5489 const fs_builder ubld = bld.exec_all().group(1, 0);
5490 fs_reg tmp = ubld.vgrf(BRW_REGISTER_TYPE_UD);
5491 ubld.AND(tmp, index, brw_imm_ud(0xff));
5492 inst->src[0] = component(tmp, 0);
5493 }
5494 inst->src[1] = brw_imm_ud(0); /* ex_desc */
5495 inst->src[2] = offset; /* payload */
5496 } else {
5497 const fs_reg payload(MRF, FIRST_PULL_LOAD_MRF(devinfo->gen),
5498 BRW_REGISTER_TYPE_UD);
5499
5500 bld.MOV(byte_offset(payload, REG_SIZE), inst->src[1]);
5501
5502 inst->opcode = FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_GEN4;
5503 inst->resize_sources(1);
5504 inst->base_mrf = payload.nr;
5505 inst->header_size = 1;
5506 inst->mlen = 1 + inst->exec_size / 8;
5507 }
5508 }
5509
5510 static void
5511 lower_math_logical_send(const fs_builder &bld, fs_inst *inst)
5512 {
5513 assert(bld.shader->devinfo->gen < 6);
5514
5515 inst->base_mrf = 2;
5516 inst->mlen = inst->sources * inst->exec_size / 8;
5517
5518 if (inst->sources > 1) {
5519 /* From the Ironlake PRM, Volume 4, Part 1, Section 6.1.13
5520 * "Message Payload":
5521 *
5522 * "Operand0[7]. For the INT DIV functions, this operand is the
5523 * denominator."
5524 * ...
5525 * "Operand1[7]. For the INT DIV functions, this operand is the
5526 * numerator."
5527 */
5528 const bool is_int_div = inst->opcode != SHADER_OPCODE_POW;
5529 const fs_reg src0 = is_int_div ? inst->src[1] : inst->src[0];
5530 const fs_reg src1 = is_int_div ? inst->src[0] : inst->src[1];
5531
5532 inst->resize_sources(1);
5533 inst->src[0] = src0;
5534
5535 assert(inst->exec_size == 8);
5536 bld.MOV(fs_reg(MRF, inst->base_mrf + 1, src1.type), src1);
5537 }
5538 }
5539
5540 bool
5541 fs_visitor::lower_logical_sends()
5542 {
5543 bool progress = false;
5544
5545 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
5546 const fs_builder ibld(this, block, inst);
5547
5548 switch (inst->opcode) {
5549 case FS_OPCODE_FB_WRITE_LOGICAL:
5550 assert(stage == MESA_SHADER_FRAGMENT);
5551 lower_fb_write_logical_send(ibld, inst,
5552 brw_wm_prog_data(prog_data),
5553 (const brw_wm_prog_key *)key,
5554 payload);
5555 break;
5556
5557 case FS_OPCODE_FB_READ_LOGICAL:
5558 lower_fb_read_logical_send(ibld, inst);
5559 break;
5560
5561 case SHADER_OPCODE_TEX_LOGICAL:
5562 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TEX);
5563 break;
5564
5565 case SHADER_OPCODE_TXD_LOGICAL:
5566 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXD);
5567 break;
5568
5569 case SHADER_OPCODE_TXF_LOGICAL:
5570 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXF);
5571 break;
5572
5573 case SHADER_OPCODE_TXL_LOGICAL:
5574 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXL);
5575 break;
5576
5577 case SHADER_OPCODE_TXS_LOGICAL:
5578 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXS);
5579 break;
5580
5581 case SHADER_OPCODE_IMAGE_SIZE_LOGICAL:
5582 lower_sampler_logical_send(ibld, inst,
5583 SHADER_OPCODE_IMAGE_SIZE_LOGICAL);
5584 break;
5585
5586 case FS_OPCODE_TXB_LOGICAL:
5587 lower_sampler_logical_send(ibld, inst, FS_OPCODE_TXB);
5588 break;
5589
5590 case SHADER_OPCODE_TXF_CMS_LOGICAL:
5591 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXF_CMS);
5592 break;
5593
5594 case SHADER_OPCODE_TXF_CMS_W_LOGICAL:
5595 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXF_CMS_W);
5596 break;
5597
5598 case SHADER_OPCODE_TXF_UMS_LOGICAL:
5599 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXF_UMS);
5600 break;
5601
5602 case SHADER_OPCODE_TXF_MCS_LOGICAL:
5603 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TXF_MCS);
5604 break;
5605
5606 case SHADER_OPCODE_LOD_LOGICAL:
5607 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_LOD);
5608 break;
5609
5610 case SHADER_OPCODE_TG4_LOGICAL:
5611 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TG4);
5612 break;
5613
5614 case SHADER_OPCODE_TG4_OFFSET_LOGICAL:
5615 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_TG4_OFFSET);
5616 break;
5617
5618 case SHADER_OPCODE_SAMPLEINFO_LOGICAL:
5619 lower_sampler_logical_send(ibld, inst, SHADER_OPCODE_SAMPLEINFO);
5620 break;
5621
5622 case SHADER_OPCODE_UNTYPED_SURFACE_READ_LOGICAL:
5623 case SHADER_OPCODE_UNTYPED_SURFACE_WRITE_LOGICAL:
5624 case SHADER_OPCODE_BYTE_SCATTERED_READ_LOGICAL:
5625 case SHADER_OPCODE_BYTE_SCATTERED_WRITE_LOGICAL:
5626 case SHADER_OPCODE_UNTYPED_ATOMIC_LOGICAL:
5627 case SHADER_OPCODE_UNTYPED_ATOMIC_FLOAT_LOGICAL:
5628 case SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL:
5629 case SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL:
5630 case SHADER_OPCODE_TYPED_ATOMIC_LOGICAL:
5631 lower_surface_logical_send(ibld, inst);
5632 break;
5633
5634 case SHADER_OPCODE_A64_UNTYPED_WRITE_LOGICAL:
5635 case SHADER_OPCODE_A64_UNTYPED_READ_LOGICAL:
5636 case SHADER_OPCODE_A64_BYTE_SCATTERED_WRITE_LOGICAL:
5637 case SHADER_OPCODE_A64_BYTE_SCATTERED_READ_LOGICAL:
5638 case SHADER_OPCODE_A64_UNTYPED_ATOMIC_LOGICAL:
5639 case SHADER_OPCODE_A64_UNTYPED_ATOMIC_INT64_LOGICAL:
5640 case SHADER_OPCODE_A64_UNTYPED_ATOMIC_FLOAT_LOGICAL:
5641 lower_a64_logical_send(ibld, inst);
5642 break;
5643
5644 case FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_LOGICAL:
5645 lower_varying_pull_constant_logical_send(ibld, inst);
5646 break;
5647
5648 case SHADER_OPCODE_RCP:
5649 case SHADER_OPCODE_RSQ:
5650 case SHADER_OPCODE_SQRT:
5651 case SHADER_OPCODE_EXP2:
5652 case SHADER_OPCODE_LOG2:
5653 case SHADER_OPCODE_SIN:
5654 case SHADER_OPCODE_COS:
5655 case SHADER_OPCODE_POW:
5656 case SHADER_OPCODE_INT_QUOTIENT:
5657 case SHADER_OPCODE_INT_REMAINDER:
5658 /* The math opcodes are overloaded for the send-like and
5659 * expression-like instructions which seems kind of icky. Gen6+ has
5660 * a native (but rather quirky) MATH instruction so we don't need to
5661 * do anything here. On Gen4-5 we'll have to lower the Gen6-like
5662 * logical instructions (which we can easily recognize because they
5663 * have mlen = 0) into send-like virtual instructions.
5664 */
5665 if (devinfo->gen < 6 && inst->mlen == 0) {
5666 lower_math_logical_send(ibld, inst);
5667 break;
5668
5669 } else {
5670 continue;
5671 }
5672
5673 default:
5674 continue;
5675 }
5676
5677 progress = true;
5678 }
5679
5680 if (progress)
5681 invalidate_live_intervals();
5682
5683 return progress;
5684 }
5685
5686 static bool
5687 is_mixed_float_with_fp32_dst(const fs_inst *inst)
5688 {
5689 /* This opcode sometimes uses :W type on the source even if the operand is
5690 * a :HF, because in gen7 there is no support for :HF, and thus it uses :W.
5691 */
5692 if (inst->opcode == BRW_OPCODE_F16TO32)
5693 return true;
5694
5695 if (inst->dst.type != BRW_REGISTER_TYPE_F)
5696 return false;
5697
5698 for (int i = 0; i < inst->sources; i++) {
5699 if (inst->src[i].type == BRW_REGISTER_TYPE_HF)
5700 return true;
5701 }
5702
5703 return false;
5704 }
5705
5706 static bool
5707 is_mixed_float_with_packed_fp16_dst(const fs_inst *inst)
5708 {
5709 /* This opcode sometimes uses :W type on the destination even if the
5710 * destination is a :HF, because in gen7 there is no support for :HF, and
5711 * thus it uses :W.
5712 */
5713 if (inst->opcode == BRW_OPCODE_F32TO16 &&
5714 inst->dst.stride == 1)
5715 return true;
5716
5717 if (inst->dst.type != BRW_REGISTER_TYPE_HF ||
5718 inst->dst.stride != 1)
5719 return false;
5720
5721 for (int i = 0; i < inst->sources; i++) {
5722 if (inst->src[i].type == BRW_REGISTER_TYPE_F)
5723 return true;
5724 }
5725
5726 return false;
5727 }
5728
5729 /**
5730 * Get the closest allowed SIMD width for instruction \p inst accounting for
5731 * some common regioning and execution control restrictions that apply to FPU
5732 * instructions. These restrictions don't necessarily have any relevance to
5733 * instructions not executed by the FPU pipeline like extended math, control
5734 * flow or send message instructions.
5735 *
5736 * For virtual opcodes it's really up to the instruction -- In some cases
5737 * (e.g. where a virtual instruction unrolls into a simple sequence of FPU
5738 * instructions) it may simplify virtual instruction lowering if we can
5739 * enforce FPU-like regioning restrictions already on the virtual instruction,
5740 * in other cases (e.g. virtual send-like instructions) this may be
5741 * excessively restrictive.
5742 */
5743 static unsigned
5744 get_fpu_lowered_simd_width(const struct gen_device_info *devinfo,
5745 const fs_inst *inst)
5746 {
5747 /* Maximum execution size representable in the instruction controls. */
5748 unsigned max_width = MIN2(32, inst->exec_size);
5749
5750 /* According to the PRMs:
5751 * "A. In Direct Addressing mode, a source cannot span more than 2
5752 * adjacent GRF registers.
5753 * B. A destination cannot span more than 2 adjacent GRF registers."
5754 *
5755 * Look for the source or destination with the largest register region
5756 * which is the one that is going to limit the overall execution size of
5757 * the instruction due to this rule.
5758 */
5759 unsigned reg_count = DIV_ROUND_UP(inst->size_written, REG_SIZE);
5760
5761 for (unsigned i = 0; i < inst->sources; i++)
5762 reg_count = MAX2(reg_count, DIV_ROUND_UP(inst->size_read(i), REG_SIZE));
5763
5764 /* Calculate the maximum execution size of the instruction based on the
5765 * factor by which it goes over the hardware limit of 2 GRFs.
5766 */
5767 if (reg_count > 2)
5768 max_width = MIN2(max_width, inst->exec_size / DIV_ROUND_UP(reg_count, 2));
5769
5770 /* According to the IVB PRMs:
5771 * "When destination spans two registers, the source MUST span two
5772 * registers. The exception to the above rule:
5773 *
5774 * - When source is scalar, the source registers are not incremented.
5775 * - When source is packed integer Word and destination is packed
5776 * integer DWord, the source register is not incremented but the
5777 * source sub register is incremented."
5778 *
5779 * The hardware specs from Gen4 to Gen7.5 mention similar regioning
5780 * restrictions. The code below intentionally doesn't check whether the
5781 * destination type is integer because empirically the hardware doesn't
5782 * seem to care what the actual type is as long as it's dword-aligned.
5783 */
5784 if (devinfo->gen < 8) {
5785 for (unsigned i = 0; i < inst->sources; i++) {
5786 /* IVB implements DF scalars as <0;2,1> regions. */
5787 const bool is_scalar_exception = is_uniform(inst->src[i]) &&
5788 (devinfo->is_haswell || type_sz(inst->src[i].type) != 8);
5789 const bool is_packed_word_exception =
5790 type_sz(inst->dst.type) == 4 && inst->dst.stride == 1 &&
5791 type_sz(inst->src[i].type) == 2 && inst->src[i].stride == 1;
5792
5793 /* We check size_read(i) against size_written instead of REG_SIZE
5794 * because we want to properly handle SIMD32. In SIMD32, you can end
5795 * up with writes to 4 registers and a source that reads 2 registers
5796 * and we may still need to lower all the way to SIMD8 in that case.
5797 */
5798 if (inst->size_written > REG_SIZE &&
5799 inst->size_read(i) != 0 &&
5800 inst->size_read(i) < inst->size_written &&
5801 !is_scalar_exception && !is_packed_word_exception) {
5802 const unsigned reg_count = DIV_ROUND_UP(inst->size_written, REG_SIZE);
5803 max_width = MIN2(max_width, inst->exec_size / reg_count);
5804 }
5805 }
5806 }
5807
5808 if (devinfo->gen < 6) {
5809 /* From the G45 PRM, Volume 4 Page 361:
5810 *
5811 * "Operand Alignment Rule: With the exceptions listed below, a
5812 * source/destination operand in general should be aligned to even
5813 * 256-bit physical register with a region size equal to two 256-bit
5814 * physical registers."
5815 *
5816 * Normally we enforce this by allocating virtual registers to the
5817 * even-aligned class. But we need to handle payload registers.
5818 */
5819 for (unsigned i = 0; i < inst->sources; i++) {
5820 if (inst->src[i].file == FIXED_GRF && (inst->src[i].nr & 1) &&
5821 inst->size_read(i) > REG_SIZE) {
5822 max_width = MIN2(max_width, 8);
5823 }
5824 }
5825 }
5826
5827 /* From the IVB PRMs:
5828 * "When an instruction is SIMD32, the low 16 bits of the execution mask
5829 * are applied for both halves of the SIMD32 instruction. If different
5830 * execution mask channels are required, split the instruction into two
5831 * SIMD16 instructions."
5832 *
5833 * There is similar text in the HSW PRMs. Gen4-6 don't even implement
5834 * 32-wide control flow support in hardware and will behave similarly.
5835 */
5836 if (devinfo->gen < 8 && !inst->force_writemask_all)
5837 max_width = MIN2(max_width, 16);
5838
5839 /* From the IVB PRMs (applies to HSW too):
5840 * "Instructions with condition modifiers must not use SIMD32."
5841 *
5842 * From the BDW PRMs (applies to later hardware too):
5843 * "Ternary instruction with condition modifiers must not use SIMD32."
5844 */
5845 if (inst->conditional_mod && (devinfo->gen < 8 || inst->is_3src(devinfo)))
5846 max_width = MIN2(max_width, 16);
5847
5848 /* From the IVB PRMs (applies to other devices that don't have the
5849 * gen_device_info::supports_simd16_3src flag set):
5850 * "In Align16 access mode, SIMD16 is not allowed for DW operations and
5851 * SIMD8 is not allowed for DF operations."
5852 */
5853 if (inst->is_3src(devinfo) && !devinfo->supports_simd16_3src)
5854 max_width = MIN2(max_width, inst->exec_size / reg_count);
5855
5856 /* Pre-Gen8 EUs are hardwired to use the QtrCtrl+1 (where QtrCtrl is
5857 * the 8-bit quarter of the execution mask signals specified in the
5858 * instruction control fields) for the second compressed half of any
5859 * single-precision instruction (for double-precision instructions
5860 * it's hardwired to use NibCtrl+1, at least on HSW), which means that
5861 * the EU will apply the wrong execution controls for the second
5862 * sequential GRF write if the number of channels per GRF is not exactly
5863 * eight in single-precision mode (or four in double-float mode).
5864 *
5865 * In this situation we calculate the maximum size of the split
5866 * instructions so they only ever write to a single register.
5867 */
5868 if (devinfo->gen < 8 && inst->size_written > REG_SIZE &&
5869 !inst->force_writemask_all) {
5870 const unsigned channels_per_grf = inst->exec_size /
5871 DIV_ROUND_UP(inst->size_written, REG_SIZE);
5872 const unsigned exec_type_size = get_exec_type_size(inst);
5873 assert(exec_type_size);
5874
5875 /* The hardware shifts exactly 8 channels per compressed half of the
5876 * instruction in single-precision mode and exactly 4 in double-precision.
5877 */
5878 if (channels_per_grf != (exec_type_size == 8 ? 4 : 8))
5879 max_width = MIN2(max_width, channels_per_grf);
5880
5881 /* Lower all non-force_writemask_all DF instructions to SIMD4 on IVB/BYT
5882 * because HW applies the same channel enable signals to both halves of
5883 * the compressed instruction which will be just wrong under
5884 * non-uniform control flow.
5885 */
5886 if (devinfo->gen == 7 && !devinfo->is_haswell &&
5887 (exec_type_size == 8 || type_sz(inst->dst.type) == 8))
5888 max_width = MIN2(max_width, 4);
5889 }
5890
5891 /* From the SKL PRM, Special Restrictions for Handling Mixed Mode
5892 * Float Operations:
5893 *
5894 * "No SIMD16 in mixed mode when destination is f32. Instruction
5895 * execution size must be no more than 8."
5896 *
5897 * FIXME: the simulator doesn't seem to complain if we don't do this and
5898 * empirical testing with existing CTS tests show that they pass just fine
5899 * without implementing this, however, since our interpretation of the PRM
5900 * is that conversion MOVs between HF and F are still mixed-float
5901 * instructions (and therefore subject to this restriction) we decided to
5902 * split them to be safe. Might be useful to do additional investigation to
5903 * lift the restriction if we can ensure that it is safe though, since these
5904 * conversions are common when half-float types are involved since many
5905 * instructions do not support HF types and conversions from/to F are
5906 * required.
5907 */
5908 if (is_mixed_float_with_fp32_dst(inst))
5909 max_width = MIN2(max_width, 8);
5910
5911 /* From the SKL PRM, Special Restrictions for Handling Mixed Mode
5912 * Float Operations:
5913 *
5914 * "No SIMD16 in mixed mode when destination is packed f16 for both
5915 * Align1 and Align16."
5916 */
5917 if (is_mixed_float_with_packed_fp16_dst(inst))
5918 max_width = MIN2(max_width, 8);
5919
5920 /* Only power-of-two execution sizes are representable in the instruction
5921 * control fields.
5922 */
5923 return 1 << _mesa_logbase2(max_width);
5924 }
5925
5926 /**
5927 * Get the maximum allowed SIMD width for instruction \p inst accounting for
5928 * various payload size restrictions that apply to sampler message
5929 * instructions.
5930 *
5931 * This is only intended to provide a maximum theoretical bound for the
5932 * execution size of the message based on the number of argument components
5933 * alone, which in most cases will determine whether the SIMD8 or SIMD16
5934 * variant of the message can be used, though some messages may have
5935 * additional restrictions not accounted for here (e.g. pre-ILK hardware uses
5936 * the message length to determine the exact SIMD width and argument count,
5937 * which makes a number of sampler message combinations impossible to
5938 * represent).
5939 */
5940 static unsigned
5941 get_sampler_lowered_simd_width(const struct gen_device_info *devinfo,
5942 const fs_inst *inst)
5943 {
5944 /* If we have a min_lod parameter on anything other than a simple sample
5945 * message, it will push it over 5 arguments and we have to fall back to
5946 * SIMD8.
5947 */
5948 if (inst->opcode != SHADER_OPCODE_TEX &&
5949 inst->components_read(TEX_LOGICAL_SRC_MIN_LOD))
5950 return 8;
5951
5952 /* Calculate the number of coordinate components that have to be present
5953 * assuming that additional arguments follow the texel coordinates in the
5954 * message payload. On IVB+ there is no need for padding, on ILK-SNB we
5955 * need to pad to four or three components depending on the message,
5956 * pre-ILK we need to pad to at most three components.
5957 */
5958 const unsigned req_coord_components =
5959 (devinfo->gen >= 7 ||
5960 !inst->components_read(TEX_LOGICAL_SRC_COORDINATE)) ? 0 :
5961 (devinfo->gen >= 5 && inst->opcode != SHADER_OPCODE_TXF_LOGICAL &&
5962 inst->opcode != SHADER_OPCODE_TXF_CMS_LOGICAL) ? 4 :
5963 3;
5964
5965 /* On Gen9+ the LOD argument is for free if we're able to use the LZ
5966 * variant of the TXL or TXF message.
5967 */
5968 const bool implicit_lod = devinfo->gen >= 9 &&
5969 (inst->opcode == SHADER_OPCODE_TXL ||
5970 inst->opcode == SHADER_OPCODE_TXF) &&
5971 inst->src[TEX_LOGICAL_SRC_LOD].is_zero();
5972
5973 /* Calculate the total number of argument components that need to be passed
5974 * to the sampler unit.
5975 */
5976 const unsigned num_payload_components =
5977 MAX2(inst->components_read(TEX_LOGICAL_SRC_COORDINATE),
5978 req_coord_components) +
5979 inst->components_read(TEX_LOGICAL_SRC_SHADOW_C) +
5980 (implicit_lod ? 0 : inst->components_read(TEX_LOGICAL_SRC_LOD)) +
5981 inst->components_read(TEX_LOGICAL_SRC_LOD2) +
5982 inst->components_read(TEX_LOGICAL_SRC_SAMPLE_INDEX) +
5983 (inst->opcode == SHADER_OPCODE_TG4_OFFSET_LOGICAL ?
5984 inst->components_read(TEX_LOGICAL_SRC_TG4_OFFSET) : 0) +
5985 inst->components_read(TEX_LOGICAL_SRC_MCS);
5986
5987 /* SIMD16 messages with more than five arguments exceed the maximum message
5988 * size supported by the sampler, regardless of whether a header is
5989 * provided or not.
5990 */
5991 return MIN2(inst->exec_size,
5992 num_payload_components > MAX_SAMPLER_MESSAGE_SIZE / 2 ? 8 : 16);
5993 }
5994
5995 /**
5996 * Get the closest native SIMD width supported by the hardware for instruction
5997 * \p inst. The instruction will be left untouched by
5998 * fs_visitor::lower_simd_width() if the returned value is equal to the
5999 * original execution size.
6000 */
6001 static unsigned
6002 get_lowered_simd_width(const struct gen_device_info *devinfo,
6003 const fs_inst *inst)
6004 {
6005 switch (inst->opcode) {
6006 case BRW_OPCODE_MOV:
6007 case BRW_OPCODE_SEL:
6008 case BRW_OPCODE_NOT:
6009 case BRW_OPCODE_AND:
6010 case BRW_OPCODE_OR:
6011 case BRW_OPCODE_XOR:
6012 case BRW_OPCODE_SHR:
6013 case BRW_OPCODE_SHL:
6014 case BRW_OPCODE_ASR:
6015 case BRW_OPCODE_CMPN:
6016 case BRW_OPCODE_CSEL:
6017 case BRW_OPCODE_F32TO16:
6018 case BRW_OPCODE_F16TO32:
6019 case BRW_OPCODE_BFREV:
6020 case BRW_OPCODE_BFE:
6021 case BRW_OPCODE_ADD:
6022 case BRW_OPCODE_MUL:
6023 case BRW_OPCODE_AVG:
6024 case BRW_OPCODE_FRC:
6025 case BRW_OPCODE_RNDU:
6026 case BRW_OPCODE_RNDD:
6027 case BRW_OPCODE_RNDE:
6028 case BRW_OPCODE_RNDZ:
6029 case BRW_OPCODE_LZD:
6030 case BRW_OPCODE_FBH:
6031 case BRW_OPCODE_FBL:
6032 case BRW_OPCODE_CBIT:
6033 case BRW_OPCODE_SAD2:
6034 case BRW_OPCODE_MAD:
6035 case BRW_OPCODE_LRP:
6036 case FS_OPCODE_PACK:
6037 case SHADER_OPCODE_SEL_EXEC:
6038 case SHADER_OPCODE_CLUSTER_BROADCAST:
6039 return get_fpu_lowered_simd_width(devinfo, inst);
6040
6041 case BRW_OPCODE_CMP: {
6042 /* The Ivybridge/BayTrail WaCMPInstFlagDepClearedEarly workaround says that
6043 * when the destination is a GRF the dependency-clear bit on the flag
6044 * register is cleared early.
6045 *
6046 * Suggested workarounds are to disable coissuing CMP instructions
6047 * or to split CMP(16) instructions into two CMP(8) instructions.
6048 *
6049 * We choose to split into CMP(8) instructions since disabling
6050 * coissuing would affect CMP instructions not otherwise affected by
6051 * the errata.
6052 */
6053 const unsigned max_width = (devinfo->gen == 7 && !devinfo->is_haswell &&
6054 !inst->dst.is_null() ? 8 : ~0);
6055 return MIN2(max_width, get_fpu_lowered_simd_width(devinfo, inst));
6056 }
6057 case BRW_OPCODE_BFI1:
6058 case BRW_OPCODE_BFI2:
6059 /* The Haswell WaForceSIMD8ForBFIInstruction workaround says that we
6060 * should
6061 * "Force BFI instructions to be executed always in SIMD8."
6062 */
6063 return MIN2(devinfo->is_haswell ? 8 : ~0u,
6064 get_fpu_lowered_simd_width(devinfo, inst));
6065
6066 case BRW_OPCODE_IF:
6067 assert(inst->src[0].file == BAD_FILE || inst->exec_size <= 16);
6068 return inst->exec_size;
6069
6070 case SHADER_OPCODE_RCP:
6071 case SHADER_OPCODE_RSQ:
6072 case SHADER_OPCODE_SQRT:
6073 case SHADER_OPCODE_EXP2:
6074 case SHADER_OPCODE_LOG2:
6075 case SHADER_OPCODE_SIN:
6076 case SHADER_OPCODE_COS: {
6077 /* Unary extended math instructions are limited to SIMD8 on Gen4 and
6078 * Gen6. Extended Math Function is limited to SIMD8 with half-float.
6079 */
6080 if (devinfo->gen == 6 || (devinfo->gen == 4 && !devinfo->is_g4x))
6081 return MIN2(8, inst->exec_size);
6082 if (inst->dst.type == BRW_REGISTER_TYPE_HF)
6083 return MIN2(8, inst->exec_size);
6084 return MIN2(16, inst->exec_size);
6085 }
6086
6087 case SHADER_OPCODE_POW: {
6088 /* SIMD16 is only allowed on Gen7+. Extended Math Function is limited
6089 * to SIMD8 with half-float
6090 */
6091 if (devinfo->gen < 7)
6092 return MIN2(8, inst->exec_size);
6093 if (inst->dst.type == BRW_REGISTER_TYPE_HF)
6094 return MIN2(8, inst->exec_size);
6095 return MIN2(16, inst->exec_size);
6096 }
6097
6098 case SHADER_OPCODE_INT_QUOTIENT:
6099 case SHADER_OPCODE_INT_REMAINDER:
6100 /* Integer division is limited to SIMD8 on all generations. */
6101 return MIN2(8, inst->exec_size);
6102
6103 case FS_OPCODE_LINTERP:
6104 case SHADER_OPCODE_GET_BUFFER_SIZE:
6105 case FS_OPCODE_DDX_COARSE:
6106 case FS_OPCODE_DDX_FINE:
6107 case FS_OPCODE_DDY_COARSE:
6108 case FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD:
6109 case FS_OPCODE_PACK_HALF_2x16_SPLIT:
6110 case FS_OPCODE_INTERPOLATE_AT_SAMPLE:
6111 case FS_OPCODE_INTERPOLATE_AT_SHARED_OFFSET:
6112 case FS_OPCODE_INTERPOLATE_AT_PER_SLOT_OFFSET:
6113 return MIN2(16, inst->exec_size);
6114
6115 case FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_LOGICAL:
6116 /* Pre-ILK hardware doesn't have a SIMD8 variant of the texel fetch
6117 * message used to implement varying pull constant loads, so expand it
6118 * to SIMD16. An alternative with longer message payload length but
6119 * shorter return payload would be to use the SIMD8 sampler message that
6120 * takes (header, u, v, r) as parameters instead of (header, u).
6121 */
6122 return (devinfo->gen == 4 ? 16 : MIN2(16, inst->exec_size));
6123
6124 case FS_OPCODE_DDY_FINE:
6125 /* The implementation of this virtual opcode may require emitting
6126 * compressed Align16 instructions, which are severely limited on some
6127 * generations.
6128 *
6129 * From the Ivy Bridge PRM, volume 4 part 3, section 3.3.9 (Register
6130 * Region Restrictions):
6131 *
6132 * "In Align16 access mode, SIMD16 is not allowed for DW operations
6133 * and SIMD8 is not allowed for DF operations."
6134 *
6135 * In this context, "DW operations" means "operations acting on 32-bit
6136 * values", so it includes operations on floats.
6137 *
6138 * Gen4 has a similar restriction. From the i965 PRM, section 11.5.3
6139 * (Instruction Compression -> Rules and Restrictions):
6140 *
6141 * "A compressed instruction must be in Align1 access mode. Align16
6142 * mode instructions cannot be compressed."
6143 *
6144 * Similar text exists in the g45 PRM.
6145 *
6146 * Empirically, compressed align16 instructions using odd register
6147 * numbers don't appear to work on Sandybridge either.
6148 */
6149 return (devinfo->gen == 4 || devinfo->gen == 6 ||
6150 (devinfo->gen == 7 && !devinfo->is_haswell) ?
6151 MIN2(8, inst->exec_size) : MIN2(16, inst->exec_size));
6152
6153 case SHADER_OPCODE_MULH:
6154 /* MULH is lowered to the MUL/MACH sequence using the accumulator, which
6155 * is 8-wide on Gen7+.
6156 */
6157 return (devinfo->gen >= 7 ? 8 :
6158 get_fpu_lowered_simd_width(devinfo, inst));
6159
6160 case FS_OPCODE_FB_WRITE_LOGICAL:
6161 /* Gen6 doesn't support SIMD16 depth writes but we cannot handle them
6162 * here.
6163 */
6164 assert(devinfo->gen != 6 ||
6165 inst->src[FB_WRITE_LOGICAL_SRC_SRC_DEPTH].file == BAD_FILE ||
6166 inst->exec_size == 8);
6167 /* Dual-source FB writes are unsupported in SIMD16 mode. */
6168 return (inst->src[FB_WRITE_LOGICAL_SRC_COLOR1].file != BAD_FILE ?
6169 8 : MIN2(16, inst->exec_size));
6170
6171 case FS_OPCODE_FB_READ_LOGICAL:
6172 return MIN2(16, inst->exec_size);
6173
6174 case SHADER_OPCODE_TEX_LOGICAL:
6175 case SHADER_OPCODE_TXF_CMS_LOGICAL:
6176 case SHADER_OPCODE_TXF_UMS_LOGICAL:
6177 case SHADER_OPCODE_TXF_MCS_LOGICAL:
6178 case SHADER_OPCODE_LOD_LOGICAL:
6179 case SHADER_OPCODE_TG4_LOGICAL:
6180 case SHADER_OPCODE_SAMPLEINFO_LOGICAL:
6181 case SHADER_OPCODE_TXF_CMS_W_LOGICAL:
6182 case SHADER_OPCODE_TG4_OFFSET_LOGICAL:
6183 return get_sampler_lowered_simd_width(devinfo, inst);
6184
6185 case SHADER_OPCODE_TXD_LOGICAL:
6186 /* TXD is unsupported in SIMD16 mode. */
6187 return 8;
6188
6189 case SHADER_OPCODE_TXL_LOGICAL:
6190 case FS_OPCODE_TXB_LOGICAL:
6191 /* Only one execution size is representable pre-ILK depending on whether
6192 * the shadow reference argument is present.
6193 */
6194 if (devinfo->gen == 4)
6195 return inst->src[TEX_LOGICAL_SRC_SHADOW_C].file == BAD_FILE ? 16 : 8;
6196 else
6197 return get_sampler_lowered_simd_width(devinfo, inst);
6198
6199 case SHADER_OPCODE_TXF_LOGICAL:
6200 case SHADER_OPCODE_TXS_LOGICAL:
6201 /* Gen4 doesn't have SIMD8 variants for the RESINFO and LD-with-LOD
6202 * messages. Use SIMD16 instead.
6203 */
6204 if (devinfo->gen == 4)
6205 return 16;
6206 else
6207 return get_sampler_lowered_simd_width(devinfo, inst);
6208
6209 case SHADER_OPCODE_TYPED_ATOMIC_LOGICAL:
6210 case SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL:
6211 case SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL:
6212 return 8;
6213
6214 case SHADER_OPCODE_UNTYPED_ATOMIC_LOGICAL:
6215 case SHADER_OPCODE_UNTYPED_ATOMIC_FLOAT_LOGICAL:
6216 case SHADER_OPCODE_UNTYPED_SURFACE_READ_LOGICAL:
6217 case SHADER_OPCODE_UNTYPED_SURFACE_WRITE_LOGICAL:
6218 case SHADER_OPCODE_BYTE_SCATTERED_WRITE_LOGICAL:
6219 case SHADER_OPCODE_BYTE_SCATTERED_READ_LOGICAL:
6220 return MIN2(16, inst->exec_size);
6221
6222 case SHADER_OPCODE_A64_UNTYPED_WRITE_LOGICAL:
6223 case SHADER_OPCODE_A64_UNTYPED_READ_LOGICAL:
6224 case SHADER_OPCODE_A64_BYTE_SCATTERED_WRITE_LOGICAL:
6225 case SHADER_OPCODE_A64_BYTE_SCATTERED_READ_LOGICAL:
6226 return devinfo->gen <= 8 ? 8 : MIN2(16, inst->exec_size);
6227
6228 case SHADER_OPCODE_A64_UNTYPED_ATOMIC_LOGICAL:
6229 case SHADER_OPCODE_A64_UNTYPED_ATOMIC_INT64_LOGICAL:
6230 case SHADER_OPCODE_A64_UNTYPED_ATOMIC_FLOAT_LOGICAL:
6231 return 8;
6232
6233 case SHADER_OPCODE_URB_READ_SIMD8:
6234 case SHADER_OPCODE_URB_READ_SIMD8_PER_SLOT:
6235 case SHADER_OPCODE_URB_WRITE_SIMD8:
6236 case SHADER_OPCODE_URB_WRITE_SIMD8_PER_SLOT:
6237 case SHADER_OPCODE_URB_WRITE_SIMD8_MASKED:
6238 case SHADER_OPCODE_URB_WRITE_SIMD8_MASKED_PER_SLOT:
6239 return MIN2(8, inst->exec_size);
6240
6241 case SHADER_OPCODE_QUAD_SWIZZLE: {
6242 const unsigned swiz = inst->src[1].ud;
6243 return (is_uniform(inst->src[0]) ?
6244 get_fpu_lowered_simd_width(devinfo, inst) :
6245 devinfo->gen < 11 && type_sz(inst->src[0].type) == 4 ? 8 :
6246 swiz == BRW_SWIZZLE_XYXY || swiz == BRW_SWIZZLE_ZWZW ? 4 :
6247 get_fpu_lowered_simd_width(devinfo, inst));
6248 }
6249 case SHADER_OPCODE_MOV_INDIRECT: {
6250 /* From IVB and HSW PRMs:
6251 *
6252 * "2.When the destination requires two registers and the sources are
6253 * indirect, the sources must use 1x1 regioning mode.
6254 *
6255 * In case of DF instructions in HSW/IVB, the exec_size is limited by
6256 * the EU decompression logic not handling VxH indirect addressing
6257 * correctly.
6258 */
6259 const unsigned max_size = (devinfo->gen >= 8 ? 2 : 1) * REG_SIZE;
6260 /* Prior to Broadwell, we only have 8 address subregisters. */
6261 return MIN3(devinfo->gen >= 8 ? 16 : 8,
6262 max_size / (inst->dst.stride * type_sz(inst->dst.type)),
6263 inst->exec_size);
6264 }
6265
6266 case SHADER_OPCODE_LOAD_PAYLOAD: {
6267 const unsigned reg_count =
6268 DIV_ROUND_UP(inst->dst.component_size(inst->exec_size), REG_SIZE);
6269
6270 if (reg_count > 2) {
6271 /* Only LOAD_PAYLOAD instructions with per-channel destination region
6272 * can be easily lowered (which excludes headers and heterogeneous
6273 * types).
6274 */
6275 assert(!inst->header_size);
6276 for (unsigned i = 0; i < inst->sources; i++)
6277 assert(type_sz(inst->dst.type) == type_sz(inst->src[i].type) ||
6278 inst->src[i].file == BAD_FILE);
6279
6280 return inst->exec_size / DIV_ROUND_UP(reg_count, 2);
6281 } else {
6282 return inst->exec_size;
6283 }
6284 }
6285 default:
6286 return inst->exec_size;
6287 }
6288 }
6289
6290 /**
6291 * Return true if splitting out the group of channels of instruction \p inst
6292 * given by lbld.group() requires allocating a temporary for the i-th source
6293 * of the lowered instruction.
6294 */
6295 static inline bool
6296 needs_src_copy(const fs_builder &lbld, const fs_inst *inst, unsigned i)
6297 {
6298 return !(is_periodic(inst->src[i], lbld.dispatch_width()) ||
6299 (inst->components_read(i) == 1 &&
6300 lbld.dispatch_width() <= inst->exec_size)) ||
6301 (inst->flags_written() &
6302 flag_mask(inst->src[i], type_sz(inst->src[i].type)));
6303 }
6304
6305 /**
6306 * Extract the data that would be consumed by the channel group given by
6307 * lbld.group() from the i-th source region of instruction \p inst and return
6308 * it as result in packed form.
6309 */
6310 static fs_reg
6311 emit_unzip(const fs_builder &lbld, fs_inst *inst, unsigned i)
6312 {
6313 assert(lbld.group() >= inst->group);
6314
6315 /* Specified channel group from the source region. */
6316 const fs_reg src = horiz_offset(inst->src[i], lbld.group() - inst->group);
6317
6318 if (needs_src_copy(lbld, inst, i)) {
6319 /* Builder of the right width to perform the copy avoiding uninitialized
6320 * data if the lowered execution size is greater than the original
6321 * execution size of the instruction.
6322 */
6323 const fs_builder cbld = lbld.group(MIN2(lbld.dispatch_width(),
6324 inst->exec_size), 0);
6325 const fs_reg tmp = lbld.vgrf(inst->src[i].type, inst->components_read(i));
6326
6327 for (unsigned k = 0; k < inst->components_read(i); ++k)
6328 cbld.MOV(offset(tmp, lbld, k), offset(src, inst->exec_size, k));
6329
6330 return tmp;
6331
6332 } else if (is_periodic(inst->src[i], lbld.dispatch_width())) {
6333 /* The source is invariant for all dispatch_width-wide groups of the
6334 * original region.
6335 */
6336 return inst->src[i];
6337
6338 } else {
6339 /* We can just point the lowered instruction at the right channel group
6340 * from the original region.
6341 */
6342 return src;
6343 }
6344 }
6345
6346 /**
6347 * Return true if splitting out the group of channels of instruction \p inst
6348 * given by lbld.group() requires allocating a temporary for the destination
6349 * of the lowered instruction and copying the data back to the original
6350 * destination region.
6351 */
6352 static inline bool
6353 needs_dst_copy(const fs_builder &lbld, const fs_inst *inst)
6354 {
6355 /* If the instruction writes more than one component we'll have to shuffle
6356 * the results of multiple lowered instructions in order to make sure that
6357 * they end up arranged correctly in the original destination region.
6358 */
6359 if (inst->size_written > inst->dst.component_size(inst->exec_size))
6360 return true;
6361
6362 /* If the lowered execution size is larger than the original the result of
6363 * the instruction won't fit in the original destination, so we'll have to
6364 * allocate a temporary in any case.
6365 */
6366 if (lbld.dispatch_width() > inst->exec_size)
6367 return true;
6368
6369 for (unsigned i = 0; i < inst->sources; i++) {
6370 /* If we already made a copy of the source for other reasons there won't
6371 * be any overlap with the destination.
6372 */
6373 if (needs_src_copy(lbld, inst, i))
6374 continue;
6375
6376 /* In order to keep the logic simple we emit a copy whenever the
6377 * destination region doesn't exactly match an overlapping source, which
6378 * may point at the source and destination not being aligned group by
6379 * group which could cause one of the lowered instructions to overwrite
6380 * the data read from the same source by other lowered instructions.
6381 */
6382 if (regions_overlap(inst->dst, inst->size_written,
6383 inst->src[i], inst->size_read(i)) &&
6384 !inst->dst.equals(inst->src[i]))
6385 return true;
6386 }
6387
6388 return false;
6389 }
6390
6391 /**
6392 * Insert data from a packed temporary into the channel group given by
6393 * lbld.group() of the destination region of instruction \p inst and return
6394 * the temporary as result. Any copy instructions that are required for
6395 * unzipping the previous value (in the case of partial writes) will be
6396 * inserted using \p lbld_before and any copy instructions required for
6397 * zipping up the destination of \p inst will be inserted using \p lbld_after.
6398 */
6399 static fs_reg
6400 emit_zip(const fs_builder &lbld_before, const fs_builder &lbld_after,
6401 fs_inst *inst)
6402 {
6403 assert(lbld_before.dispatch_width() == lbld_after.dispatch_width());
6404 assert(lbld_before.group() == lbld_after.group());
6405 assert(lbld_after.group() >= inst->group);
6406
6407 /* Specified channel group from the destination region. */
6408 const fs_reg dst = horiz_offset(inst->dst, lbld_after.group() - inst->group);
6409 const unsigned dst_size = inst->size_written /
6410 inst->dst.component_size(inst->exec_size);
6411
6412 if (needs_dst_copy(lbld_after, inst)) {
6413 const fs_reg tmp = lbld_after.vgrf(inst->dst.type, dst_size);
6414
6415 if (inst->predicate) {
6416 /* Handle predication by copying the original contents of
6417 * the destination into the temporary before emitting the
6418 * lowered instruction.
6419 */
6420 const fs_builder gbld_before =
6421 lbld_before.group(MIN2(lbld_before.dispatch_width(),
6422 inst->exec_size), 0);
6423 for (unsigned k = 0; k < dst_size; ++k) {
6424 gbld_before.MOV(offset(tmp, lbld_before, k),
6425 offset(dst, inst->exec_size, k));
6426 }
6427 }
6428
6429 const fs_builder gbld_after =
6430 lbld_after.group(MIN2(lbld_after.dispatch_width(),
6431 inst->exec_size), 0);
6432 for (unsigned k = 0; k < dst_size; ++k) {
6433 /* Use a builder of the right width to perform the copy avoiding
6434 * uninitialized data if the lowered execution size is greater than
6435 * the original execution size of the instruction.
6436 */
6437 gbld_after.MOV(offset(dst, inst->exec_size, k),
6438 offset(tmp, lbld_after, k));
6439 }
6440
6441 return tmp;
6442
6443 } else {
6444 /* No need to allocate a temporary for the lowered instruction, just
6445 * take the right group of channels from the original region.
6446 */
6447 return dst;
6448 }
6449 }
6450
6451 bool
6452 fs_visitor::lower_simd_width()
6453 {
6454 bool progress = false;
6455
6456 foreach_block_and_inst_safe(block, fs_inst, inst, cfg) {
6457 const unsigned lower_width = get_lowered_simd_width(devinfo, inst);
6458
6459 if (lower_width != inst->exec_size) {
6460 /* Builder matching the original instruction. We may also need to
6461 * emit an instruction of width larger than the original, set the
6462 * execution size of the builder to the highest of both for now so
6463 * we're sure that both cases can be handled.
6464 */
6465 const unsigned max_width = MAX2(inst->exec_size, lower_width);
6466 const fs_builder ibld = bld.at(block, inst)
6467 .exec_all(inst->force_writemask_all)
6468 .group(max_width, inst->group / max_width);
6469
6470 /* Split the copies in chunks of the execution width of either the
6471 * original or the lowered instruction, whichever is lower.
6472 */
6473 const unsigned n = DIV_ROUND_UP(inst->exec_size, lower_width);
6474 const unsigned dst_size = inst->size_written /
6475 inst->dst.component_size(inst->exec_size);
6476
6477 assert(!inst->writes_accumulator && !inst->mlen);
6478
6479 /* Inserting the zip, unzip, and duplicated instructions in all of
6480 * the right spots is somewhat tricky. All of the unzip and any
6481 * instructions from the zip which unzip the destination prior to
6482 * writing need to happen before all of the per-group instructions
6483 * and the zip instructions need to happen after. In order to sort
6484 * this all out, we insert the unzip instructions before \p inst,
6485 * insert the per-group instructions after \p inst (i.e. before
6486 * inst->next), and insert the zip instructions before the
6487 * instruction after \p inst. Since we are inserting instructions
6488 * after \p inst, inst->next is a moving target and we need to save
6489 * it off here so that we insert the zip instructions in the right
6490 * place.
6491 *
6492 * Since we're inserting split instructions after after_inst, the
6493 * instructions will end up in the reverse order that we insert them.
6494 * However, certain render target writes require that the low group
6495 * instructions come before the high group. From the Ivy Bridge PRM
6496 * Vol. 4, Pt. 1, Section 3.9.11:
6497 *
6498 * "If multiple SIMD8 Dual Source messages are delivered by the
6499 * pixel shader thread, each SIMD8_DUALSRC_LO message must be
6500 * issued before the SIMD8_DUALSRC_HI message with the same Slot
6501 * Group Select setting."
6502 *
6503 * And, from Section 3.9.11.1 of the same PRM:
6504 *
6505 * "When SIMD32 or SIMD16 PS threads send render target writes
6506 * with multiple SIMD8 and SIMD16 messages, the following must
6507 * hold:
6508 *
6509 * All the slots (as described above) must have a corresponding
6510 * render target write irrespective of the slot's validity. A slot
6511 * is considered valid when at least one sample is enabled. For
6512 * example, a SIMD16 PS thread must send two SIMD8 render target
6513 * writes to cover all the slots.
6514 *
6515 * PS thread must send SIMD render target write messages with
6516 * increasing slot numbers. For example, SIMD16 thread has
6517 * Slot[15:0] and if two SIMD8 render target writes are used, the
6518 * first SIMD8 render target write must send Slot[7:0] and the
6519 * next one must send Slot[15:8]."
6520 *
6521 * In order to make low group instructions come before high group
6522 * instructions (this is required for some render target writes), we
6523 * split from the highest group to lowest.
6524 */
6525 exec_node *const after_inst = inst->next;
6526 for (int i = n - 1; i >= 0; i--) {
6527 /* Emit a copy of the original instruction with the lowered width.
6528 * If the EOT flag was set throw it away except for the last
6529 * instruction to avoid killing the thread prematurely.
6530 */
6531 fs_inst split_inst = *inst;
6532 split_inst.exec_size = lower_width;
6533 split_inst.eot = inst->eot && i == int(n - 1);
6534
6535 /* Select the correct channel enables for the i-th group, then
6536 * transform the sources and destination and emit the lowered
6537 * instruction.
6538 */
6539 const fs_builder lbld = ibld.group(lower_width, i);
6540
6541 for (unsigned j = 0; j < inst->sources; j++)
6542 split_inst.src[j] = emit_unzip(lbld.at(block, inst), inst, j);
6543
6544 split_inst.dst = emit_zip(lbld.at(block, inst),
6545 lbld.at(block, after_inst), inst);
6546 split_inst.size_written =
6547 split_inst.dst.component_size(lower_width) * dst_size;
6548
6549 lbld.at(block, inst->next).emit(split_inst);
6550 }
6551
6552 inst->remove(block);
6553 progress = true;
6554 }
6555 }
6556
6557 if (progress)
6558 invalidate_live_intervals();
6559
6560 return progress;
6561 }
6562
6563 void
6564 fs_visitor::dump_instructions()
6565 {
6566 dump_instructions(NULL);
6567 }
6568
6569 void
6570 fs_visitor::dump_instructions(const char *name)
6571 {
6572 FILE *file = stderr;
6573 if (name && geteuid() != 0) {
6574 file = fopen(name, "w");
6575 if (!file)
6576 file = stderr;
6577 }
6578
6579 if (cfg) {
6580 calculate_register_pressure();
6581 int ip = 0, max_pressure = 0;
6582 foreach_block_and_inst(block, backend_instruction, inst, cfg) {
6583 max_pressure = MAX2(max_pressure, regs_live_at_ip[ip]);
6584 fprintf(file, "{%3d} %4d: ", regs_live_at_ip[ip], ip);
6585 dump_instruction(inst, file);
6586 ip++;
6587 }
6588 fprintf(file, "Maximum %3d registers live at once.\n", max_pressure);
6589 } else {
6590 int ip = 0;
6591 foreach_in_list(backend_instruction, inst, &instructions) {
6592 fprintf(file, "%4d: ", ip++);
6593 dump_instruction(inst, file);
6594 }
6595 }
6596
6597 if (file != stderr) {
6598 fclose(file);
6599 }
6600 }
6601
6602 void
6603 fs_visitor::dump_instruction(backend_instruction *be_inst)
6604 {
6605 dump_instruction(be_inst, stderr);
6606 }
6607
6608 void
6609 fs_visitor::dump_instruction(backend_instruction *be_inst, FILE *file)
6610 {
6611 fs_inst *inst = (fs_inst *)be_inst;
6612
6613 if (inst->predicate) {
6614 fprintf(file, "(%cf%d.%d) ",
6615 inst->predicate_inverse ? '-' : '+',
6616 inst->flag_subreg / 2,
6617 inst->flag_subreg % 2);
6618 }
6619
6620 fprintf(file, "%s", brw_instruction_name(devinfo, inst->opcode));
6621 if (inst->saturate)
6622 fprintf(file, ".sat");
6623 if (inst->conditional_mod) {
6624 fprintf(file, "%s", conditional_modifier[inst->conditional_mod]);
6625 if (!inst->predicate &&
6626 (devinfo->gen < 5 || (inst->opcode != BRW_OPCODE_SEL &&
6627 inst->opcode != BRW_OPCODE_CSEL &&
6628 inst->opcode != BRW_OPCODE_IF &&
6629 inst->opcode != BRW_OPCODE_WHILE))) {
6630 fprintf(file, ".f%d.%d", inst->flag_subreg / 2,
6631 inst->flag_subreg % 2);
6632 }
6633 }
6634 fprintf(file, "(%d) ", inst->exec_size);
6635
6636 if (inst->mlen) {
6637 fprintf(file, "(mlen: %d) ", inst->mlen);
6638 }
6639
6640 if (inst->ex_mlen) {
6641 fprintf(file, "(ex_mlen: %d) ", inst->ex_mlen);
6642 }
6643
6644 if (inst->eot) {
6645 fprintf(file, "(EOT) ");
6646 }
6647
6648 switch (inst->dst.file) {
6649 case VGRF:
6650 fprintf(file, "vgrf%d", inst->dst.nr);
6651 break;
6652 case FIXED_GRF:
6653 fprintf(file, "g%d", inst->dst.nr);
6654 break;
6655 case MRF:
6656 fprintf(file, "m%d", inst->dst.nr);
6657 break;
6658 case BAD_FILE:
6659 fprintf(file, "(null)");
6660 break;
6661 case UNIFORM:
6662 fprintf(file, "***u%d***", inst->dst.nr);
6663 break;
6664 case ATTR:
6665 fprintf(file, "***attr%d***", inst->dst.nr);
6666 break;
6667 case ARF:
6668 switch (inst->dst.nr) {
6669 case BRW_ARF_NULL:
6670 fprintf(file, "null");
6671 break;
6672 case BRW_ARF_ADDRESS:
6673 fprintf(file, "a0.%d", inst->dst.subnr);
6674 break;
6675 case BRW_ARF_ACCUMULATOR:
6676 fprintf(file, "acc%d", inst->dst.subnr);
6677 break;
6678 case BRW_ARF_FLAG:
6679 fprintf(file, "f%d.%d", inst->dst.nr & 0xf, inst->dst.subnr);
6680 break;
6681 default:
6682 fprintf(file, "arf%d.%d", inst->dst.nr & 0xf, inst->dst.subnr);
6683 break;
6684 }
6685 break;
6686 case IMM:
6687 unreachable("not reached");
6688 }
6689
6690 if (inst->dst.offset ||
6691 (inst->dst.file == VGRF &&
6692 alloc.sizes[inst->dst.nr] * REG_SIZE != inst->size_written)) {
6693 const unsigned reg_size = (inst->dst.file == UNIFORM ? 4 : REG_SIZE);
6694 fprintf(file, "+%d.%d", inst->dst.offset / reg_size,
6695 inst->dst.offset % reg_size);
6696 }
6697
6698 if (inst->dst.stride != 1)
6699 fprintf(file, "<%u>", inst->dst.stride);
6700 fprintf(file, ":%s, ", brw_reg_type_to_letters(inst->dst.type));
6701
6702 for (int i = 0; i < inst->sources; i++) {
6703 if (inst->src[i].negate)
6704 fprintf(file, "-");
6705 if (inst->src[i].abs)
6706 fprintf(file, "|");
6707 switch (inst->src[i].file) {
6708 case VGRF:
6709 fprintf(file, "vgrf%d", inst->src[i].nr);
6710 break;
6711 case FIXED_GRF:
6712 fprintf(file, "g%d", inst->src[i].nr);
6713 break;
6714 case MRF:
6715 fprintf(file, "***m%d***", inst->src[i].nr);
6716 break;
6717 case ATTR:
6718 fprintf(file, "attr%d", inst->src[i].nr);
6719 break;
6720 case UNIFORM:
6721 fprintf(file, "u%d", inst->src[i].nr);
6722 break;
6723 case BAD_FILE:
6724 fprintf(file, "(null)");
6725 break;
6726 case IMM:
6727 switch (inst->src[i].type) {
6728 case BRW_REGISTER_TYPE_F:
6729 fprintf(file, "%-gf", inst->src[i].f);
6730 break;
6731 case BRW_REGISTER_TYPE_DF:
6732 fprintf(file, "%fdf", inst->src[i].df);
6733 break;
6734 case BRW_REGISTER_TYPE_W:
6735 case BRW_REGISTER_TYPE_D:
6736 fprintf(file, "%dd", inst->src[i].d);
6737 break;
6738 case BRW_REGISTER_TYPE_UW:
6739 case BRW_REGISTER_TYPE_UD:
6740 fprintf(file, "%uu", inst->src[i].ud);
6741 break;
6742 case BRW_REGISTER_TYPE_Q:
6743 fprintf(file, "%" PRId64 "q", inst->src[i].d64);
6744 break;
6745 case BRW_REGISTER_TYPE_UQ:
6746 fprintf(file, "%" PRIu64 "uq", inst->src[i].u64);
6747 break;
6748 case BRW_REGISTER_TYPE_VF:
6749 fprintf(file, "[%-gF, %-gF, %-gF, %-gF]",
6750 brw_vf_to_float((inst->src[i].ud >> 0) & 0xff),
6751 brw_vf_to_float((inst->src[i].ud >> 8) & 0xff),
6752 brw_vf_to_float((inst->src[i].ud >> 16) & 0xff),
6753 brw_vf_to_float((inst->src[i].ud >> 24) & 0xff));
6754 break;
6755 case BRW_REGISTER_TYPE_V:
6756 case BRW_REGISTER_TYPE_UV:
6757 fprintf(file, "%08x%s", inst->src[i].ud,
6758 inst->src[i].type == BRW_REGISTER_TYPE_V ? "V" : "UV");
6759 break;
6760 default:
6761 fprintf(file, "???");
6762 break;
6763 }
6764 break;
6765 case ARF:
6766 switch (inst->src[i].nr) {
6767 case BRW_ARF_NULL:
6768 fprintf(file, "null");
6769 break;
6770 case BRW_ARF_ADDRESS:
6771 fprintf(file, "a0.%d", inst->src[i].subnr);
6772 break;
6773 case BRW_ARF_ACCUMULATOR:
6774 fprintf(file, "acc%d", inst->src[i].subnr);
6775 break;
6776 case BRW_ARF_FLAG:
6777 fprintf(file, "f%d.%d", inst->src[i].nr & 0xf, inst->src[i].subnr);
6778 break;
6779 default:
6780 fprintf(file, "arf%d.%d", inst->src[i].nr & 0xf, inst->src[i].subnr);
6781 break;
6782 }
6783 break;
6784 }
6785
6786 if (inst->src[i].offset ||
6787 (inst->src[i].file == VGRF &&
6788 alloc.sizes[inst->src[i].nr] * REG_SIZE != inst->size_read(i))) {
6789 const unsigned reg_size = (inst->src[i].file == UNIFORM ? 4 : REG_SIZE);
6790 fprintf(file, "+%d.%d", inst->src[i].offset / reg_size,
6791 inst->src[i].offset % reg_size);
6792 }
6793
6794 if (inst->src[i].abs)
6795 fprintf(file, "|");
6796
6797 if (inst->src[i].file != IMM) {
6798 unsigned stride;
6799 if (inst->src[i].file == ARF || inst->src[i].file == FIXED_GRF) {
6800 unsigned hstride = inst->src[i].hstride;
6801 stride = (hstride == 0 ? 0 : (1 << (hstride - 1)));
6802 } else {
6803 stride = inst->src[i].stride;
6804 }
6805 if (stride != 1)
6806 fprintf(file, "<%u>", stride);
6807
6808 fprintf(file, ":%s", brw_reg_type_to_letters(inst->src[i].type));
6809 }
6810
6811 if (i < inst->sources - 1 && inst->src[i + 1].file != BAD_FILE)
6812 fprintf(file, ", ");
6813 }
6814
6815 fprintf(file, " ");
6816
6817 if (inst->force_writemask_all)
6818 fprintf(file, "NoMask ");
6819
6820 if (inst->exec_size != dispatch_width)
6821 fprintf(file, "group%d ", inst->group);
6822
6823 fprintf(file, "\n");
6824 }
6825
6826 void
6827 fs_visitor::setup_fs_payload_gen6()
6828 {
6829 assert(stage == MESA_SHADER_FRAGMENT);
6830 struct brw_wm_prog_data *prog_data = brw_wm_prog_data(this->prog_data);
6831 const unsigned payload_width = MIN2(16, dispatch_width);
6832 assert(dispatch_width % payload_width == 0);
6833 assert(devinfo->gen >= 6);
6834
6835 prog_data->uses_src_depth = prog_data->uses_src_w =
6836 (nir->info.inputs_read & (1 << VARYING_SLOT_POS)) != 0;
6837
6838 prog_data->uses_sample_mask =
6839 (nir->info.system_values_read & SYSTEM_BIT_SAMPLE_MASK_IN) != 0;
6840
6841 /* From the Ivy Bridge PRM documentation for 3DSTATE_PS:
6842 *
6843 * "MSDISPMODE_PERSAMPLE is required in order to select
6844 * POSOFFSET_SAMPLE"
6845 *
6846 * So we can only really get sample positions if we are doing real
6847 * per-sample dispatch. If we need gl_SamplePosition and we don't have
6848 * persample dispatch, we hard-code it to 0.5.
6849 */
6850 prog_data->uses_pos_offset = prog_data->persample_dispatch &&
6851 (nir->info.system_values_read & SYSTEM_BIT_SAMPLE_POS);
6852
6853 /* R0: PS thread payload header. */
6854 payload.num_regs++;
6855
6856 for (unsigned j = 0; j < dispatch_width / payload_width; j++) {
6857 /* R1: masks, pixel X/Y coordinates. */
6858 payload.subspan_coord_reg[j] = payload.num_regs++;
6859 }
6860
6861 for (unsigned j = 0; j < dispatch_width / payload_width; j++) {
6862 /* R3-26: barycentric interpolation coordinates. These appear in the
6863 * same order that they appear in the brw_barycentric_mode enum. Each
6864 * set of coordinates occupies 2 registers if dispatch width == 8 and 4
6865 * registers if dispatch width == 16. Coordinates only appear if they
6866 * were enabled using the "Barycentric Interpolation Mode" bits in
6867 * WM_STATE.
6868 */
6869 for (int i = 0; i < BRW_BARYCENTRIC_MODE_COUNT; ++i) {
6870 if (prog_data->barycentric_interp_modes & (1 << i)) {
6871 payload.barycentric_coord_reg[i][j] = payload.num_regs;
6872 payload.num_regs += payload_width / 4;
6873 }
6874 }
6875
6876 /* R27-28: interpolated depth if uses source depth */
6877 if (prog_data->uses_src_depth) {
6878 payload.source_depth_reg[j] = payload.num_regs;
6879 payload.num_regs += payload_width / 8;
6880 }
6881
6882 /* R29-30: interpolated W set if GEN6_WM_USES_SOURCE_W. */
6883 if (prog_data->uses_src_w) {
6884 payload.source_w_reg[j] = payload.num_regs;
6885 payload.num_regs += payload_width / 8;
6886 }
6887
6888 /* R31: MSAA position offsets. */
6889 if (prog_data->uses_pos_offset) {
6890 payload.sample_pos_reg[j] = payload.num_regs;
6891 payload.num_regs++;
6892 }
6893
6894 /* R32-33: MSAA input coverage mask */
6895 if (prog_data->uses_sample_mask) {
6896 assert(devinfo->gen >= 7);
6897 payload.sample_mask_in_reg[j] = payload.num_regs;
6898 payload.num_regs += payload_width / 8;
6899 }
6900 }
6901
6902 if (nir->info.outputs_written & BITFIELD64_BIT(FRAG_RESULT_DEPTH)) {
6903 source_depth_to_render_target = true;
6904 }
6905 }
6906
6907 void
6908 fs_visitor::setup_vs_payload()
6909 {
6910 /* R0: thread header, R1: urb handles */
6911 payload.num_regs = 2;
6912 }
6913
6914 void
6915 fs_visitor::setup_gs_payload()
6916 {
6917 assert(stage == MESA_SHADER_GEOMETRY);
6918
6919 struct brw_gs_prog_data *gs_prog_data = brw_gs_prog_data(prog_data);
6920 struct brw_vue_prog_data *vue_prog_data = brw_vue_prog_data(prog_data);
6921
6922 /* R0: thread header, R1: output URB handles */
6923 payload.num_regs = 2;
6924
6925 if (gs_prog_data->include_primitive_id) {
6926 /* R2: Primitive ID 0..7 */
6927 payload.num_regs++;
6928 }
6929
6930 /* Always enable VUE handles so we can safely use pull model if needed.
6931 *
6932 * The push model for a GS uses a ton of register space even for trivial
6933 * scenarios with just a few inputs, so just make things easier and a bit
6934 * safer by always having pull model available.
6935 */
6936 gs_prog_data->base.include_vue_handles = true;
6937
6938 /* R3..RN: ICP Handles for each incoming vertex (when using pull model) */
6939 payload.num_regs += nir->info.gs.vertices_in;
6940
6941 /* Use a maximum of 24 registers for push-model inputs. */
6942 const unsigned max_push_components = 24;
6943
6944 /* If pushing our inputs would take too many registers, reduce the URB read
6945 * length (which is in HWords, or 8 registers), and resort to pulling.
6946 *
6947 * Note that the GS reads <URB Read Length> HWords for every vertex - so we
6948 * have to multiply by VerticesIn to obtain the total storage requirement.
6949 */
6950 if (8 * vue_prog_data->urb_read_length * nir->info.gs.vertices_in >
6951 max_push_components) {
6952 vue_prog_data->urb_read_length =
6953 ROUND_DOWN_TO(max_push_components / nir->info.gs.vertices_in, 8) / 8;
6954 }
6955 }
6956
6957 void
6958 fs_visitor::setup_cs_payload()
6959 {
6960 assert(devinfo->gen >= 7);
6961 payload.num_regs = 1;
6962 }
6963
6964 void
6965 fs_visitor::calculate_register_pressure()
6966 {
6967 invalidate_live_intervals();
6968 calculate_live_intervals();
6969
6970 unsigned num_instructions = 0;
6971 foreach_block(block, cfg)
6972 num_instructions += block->instructions.length();
6973
6974 regs_live_at_ip = rzalloc_array(mem_ctx, int, num_instructions);
6975
6976 for (unsigned reg = 0; reg < alloc.count; reg++) {
6977 for (int ip = virtual_grf_start[reg]; ip <= virtual_grf_end[reg]; ip++)
6978 regs_live_at_ip[ip] += alloc.sizes[reg];
6979 }
6980 }
6981
6982 void
6983 fs_visitor::optimize()
6984 {
6985 /* Start by validating the shader we currently have. */
6986 validate();
6987
6988 /* bld is the common builder object pointing at the end of the program we
6989 * used to translate it into i965 IR. For the optimization and lowering
6990 * passes coming next, any code added after the end of the program without
6991 * having explicitly called fs_builder::at() clearly points at a mistake.
6992 * Ideally optimization passes wouldn't be part of the visitor so they
6993 * wouldn't have access to bld at all, but they do, so just in case some
6994 * pass forgets to ask for a location explicitly set it to NULL here to
6995 * make it trip. The dispatch width is initialized to a bogus value to
6996 * make sure that optimizations set the execution controls explicitly to
6997 * match the code they are manipulating instead of relying on the defaults.
6998 */
6999 bld = fs_builder(this, 64);
7000
7001 assign_constant_locations();
7002 lower_constant_loads();
7003
7004 validate();
7005
7006 split_virtual_grfs();
7007 validate();
7008
7009 #define OPT(pass, args...) ({ \
7010 pass_num++; \
7011 bool this_progress = pass(args); \
7012 \
7013 if (unlikely(INTEL_DEBUG & DEBUG_OPTIMIZER) && this_progress) { \
7014 char filename[64]; \
7015 snprintf(filename, 64, "%s%d-%s-%02d-%02d-" #pass, \
7016 stage_abbrev, dispatch_width, nir->info.name, iteration, pass_num); \
7017 \
7018 backend_shader::dump_instructions(filename); \
7019 } \
7020 \
7021 validate(); \
7022 \
7023 progress = progress || this_progress; \
7024 this_progress; \
7025 })
7026
7027 if (unlikely(INTEL_DEBUG & DEBUG_OPTIMIZER)) {
7028 char filename[64];
7029 snprintf(filename, 64, "%s%d-%s-00-00-start",
7030 stage_abbrev, dispatch_width, nir->info.name);
7031
7032 backend_shader::dump_instructions(filename);
7033 }
7034
7035 bool progress = false;
7036 int iteration = 0;
7037 int pass_num = 0;
7038
7039 /* Before anything else, eliminate dead code. The results of some NIR
7040 * instructions may effectively be calculated twice. Once when the
7041 * instruction is encountered, and again when the user of that result is
7042 * encountered. Wipe those away before algebraic optimizations and
7043 * especially copy propagation can mix things up.
7044 */
7045 OPT(dead_code_eliminate);
7046
7047 OPT(remove_extra_rounding_modes);
7048
7049 do {
7050 progress = false;
7051 pass_num = 0;
7052 iteration++;
7053
7054 OPT(remove_duplicate_mrf_writes);
7055
7056 OPT(opt_algebraic);
7057 OPT(opt_cse);
7058 OPT(opt_copy_propagation);
7059 OPT(opt_predicated_break, this);
7060 OPT(opt_cmod_propagation);
7061 OPT(dead_code_eliminate);
7062 OPT(opt_peephole_sel);
7063 OPT(dead_control_flow_eliminate, this);
7064 OPT(opt_register_renaming);
7065 OPT(opt_saturate_propagation);
7066 OPT(register_coalesce);
7067 OPT(compute_to_mrf);
7068 OPT(eliminate_find_live_channel);
7069
7070 OPT(compact_virtual_grfs);
7071 } while (progress);
7072
7073 /* Do this after cmod propagation has had every possible opportunity to
7074 * propagate results into SEL instructions.
7075 */
7076 if (OPT(opt_peephole_csel))
7077 OPT(dead_code_eliminate);
7078
7079 progress = false;
7080 pass_num = 0;
7081
7082 if (OPT(lower_pack)) {
7083 OPT(register_coalesce);
7084 OPT(dead_code_eliminate);
7085 }
7086
7087 OPT(lower_simd_width);
7088
7089 /* After SIMD lowering just in case we had to unroll the EOT send. */
7090 OPT(opt_sampler_eot);
7091
7092 OPT(lower_logical_sends);
7093
7094 if (progress) {
7095 OPT(opt_copy_propagation);
7096 /* Only run after logical send lowering because it's easier to implement
7097 * in terms of physical sends.
7098 */
7099 if (OPT(opt_zero_samples))
7100 OPT(opt_copy_propagation);
7101 /* Run after logical send lowering to give it a chance to CSE the
7102 * LOAD_PAYLOAD instructions created to construct the payloads of
7103 * e.g. texturing messages in cases where it wasn't possible to CSE the
7104 * whole logical instruction.
7105 */
7106 OPT(opt_cse);
7107 OPT(register_coalesce);
7108 OPT(compute_to_mrf);
7109 OPT(dead_code_eliminate);
7110 OPT(remove_duplicate_mrf_writes);
7111 OPT(opt_peephole_sel);
7112 }
7113
7114 OPT(opt_redundant_discard_jumps);
7115
7116 if (OPT(lower_load_payload)) {
7117 split_virtual_grfs();
7118 OPT(register_coalesce);
7119 OPT(lower_simd_width);
7120 OPT(compute_to_mrf);
7121 OPT(dead_code_eliminate);
7122 }
7123
7124 OPT(opt_combine_constants);
7125 OPT(lower_integer_multiplication);
7126
7127 if (devinfo->gen <= 5 && OPT(lower_minmax)) {
7128 OPT(opt_cmod_propagation);
7129 OPT(opt_cse);
7130 OPT(opt_copy_propagation);
7131 OPT(dead_code_eliminate);
7132 }
7133
7134 if (OPT(lower_regioning)) {
7135 OPT(opt_copy_propagation);
7136 OPT(dead_code_eliminate);
7137 OPT(lower_simd_width);
7138 }
7139
7140 OPT(fixup_sends_duplicate_payload);
7141
7142 lower_uniform_pull_constant_loads();
7143
7144 validate();
7145 }
7146
7147 /**
7148 * From the Skylake PRM Vol. 2a docs for sends:
7149 *
7150 * "It is required that the second block of GRFs does not overlap with the
7151 * first block."
7152 *
7153 * There are plenty of cases where we may accidentally violate this due to
7154 * having, for instance, both sources be the constant 0. This little pass
7155 * just adds a new vgrf for the second payload and copies it over.
7156 */
7157 bool
7158 fs_visitor::fixup_sends_duplicate_payload()
7159 {
7160 bool progress = false;
7161
7162 foreach_block_and_inst_safe (block, fs_inst, inst, cfg) {
7163 if (inst->opcode == SHADER_OPCODE_SEND && inst->ex_mlen > 0 &&
7164 regions_overlap(inst->src[2], inst->mlen * REG_SIZE,
7165 inst->src[3], inst->ex_mlen * REG_SIZE)) {
7166 fs_reg tmp = fs_reg(VGRF, alloc.allocate(inst->ex_mlen),
7167 BRW_REGISTER_TYPE_UD);
7168 /* Sadly, we've lost all notion of channels and bit sizes at this
7169 * point. Just WE_all it.
7170 */
7171 const fs_builder ibld = bld.at(block, inst).exec_all().group(16, 0);
7172 fs_reg copy_src = retype(inst->src[3], BRW_REGISTER_TYPE_UD);
7173 fs_reg copy_dst = tmp;
7174 for (unsigned i = 0; i < inst->ex_mlen; i += 2) {
7175 if (inst->ex_mlen == i + 1) {
7176 /* Only one register left; do SIMD8 */
7177 ibld.group(8, 0).MOV(copy_dst, copy_src);
7178 } else {
7179 ibld.MOV(copy_dst, copy_src);
7180 }
7181 copy_src = offset(copy_src, ibld, 1);
7182 copy_dst = offset(copy_dst, ibld, 1);
7183 }
7184 inst->src[3] = tmp;
7185 progress = true;
7186 }
7187 }
7188
7189 if (progress)
7190 invalidate_live_intervals();
7191
7192 return progress;
7193 }
7194
7195 /**
7196 * Three source instruction must have a GRF/MRF destination register.
7197 * ARF NULL is not allowed. Fix that up by allocating a temporary GRF.
7198 */
7199 void
7200 fs_visitor::fixup_3src_null_dest()
7201 {
7202 bool progress = false;
7203
7204 foreach_block_and_inst_safe (block, fs_inst, inst, cfg) {
7205 if (inst->is_3src(devinfo) && inst->dst.is_null()) {
7206 inst->dst = fs_reg(VGRF, alloc.allocate(dispatch_width / 8),
7207 inst->dst.type);
7208 progress = true;
7209 }
7210 }
7211
7212 if (progress)
7213 invalidate_live_intervals();
7214 }
7215
7216 void
7217 fs_visitor::allocate_registers(unsigned min_dispatch_width, bool allow_spilling)
7218 {
7219 bool allocated_without_spills;
7220
7221 static const enum instruction_scheduler_mode pre_modes[] = {
7222 SCHEDULE_PRE,
7223 SCHEDULE_PRE_NON_LIFO,
7224 SCHEDULE_PRE_LIFO,
7225 };
7226
7227 bool spill_all = allow_spilling && (INTEL_DEBUG & DEBUG_SPILL_FS);
7228
7229 /* Try each scheduling heuristic to see if it can successfully register
7230 * allocate without spilling. They should be ordered by decreasing
7231 * performance but increasing likelihood of allocating.
7232 */
7233 for (unsigned i = 0; i < ARRAY_SIZE(pre_modes); i++) {
7234 schedule_instructions(pre_modes[i]);
7235
7236 if (0) {
7237 assign_regs_trivial();
7238 allocated_without_spills = true;
7239 } else {
7240 allocated_without_spills = assign_regs(false, spill_all);
7241 }
7242 if (allocated_without_spills)
7243 break;
7244 }
7245
7246 if (!allocated_without_spills) {
7247 if (!allow_spilling)
7248 fail("Failure to register allocate and spilling is not allowed.");
7249
7250 /* We assume that any spilling is worse than just dropping back to
7251 * SIMD8. There's probably actually some intermediate point where
7252 * SIMD16 with a couple of spills is still better.
7253 */
7254 if (dispatch_width > min_dispatch_width) {
7255 fail("Failure to register allocate. Reduce number of "
7256 "live scalar values to avoid this.");
7257 } else {
7258 compiler->shader_perf_log(log_data,
7259 "%s shader triggered register spilling. "
7260 "Try reducing the number of live scalar "
7261 "values to improve performance.\n",
7262 stage_name);
7263 }
7264
7265 /* Since we're out of heuristics, just go spill registers until we
7266 * get an allocation.
7267 */
7268 while (!assign_regs(true, spill_all)) {
7269 if (failed)
7270 break;
7271 }
7272 }
7273
7274 /* This must come after all optimization and register allocation, since
7275 * it inserts dead code that happens to have side effects, and it does
7276 * so based on the actual physical registers in use.
7277 */
7278 insert_gen4_send_dependency_workarounds();
7279
7280 if (failed)
7281 return;
7282
7283 opt_bank_conflicts();
7284
7285 schedule_instructions(SCHEDULE_POST);
7286
7287 if (last_scratch > 0) {
7288 MAYBE_UNUSED unsigned max_scratch_size = 2 * 1024 * 1024;
7289
7290 prog_data->total_scratch = brw_get_scratch_size(last_scratch);
7291
7292 if (stage == MESA_SHADER_COMPUTE) {
7293 if (devinfo->is_haswell) {
7294 /* According to the MEDIA_VFE_STATE's "Per Thread Scratch Space"
7295 * field documentation, Haswell supports a minimum of 2kB of
7296 * scratch space for compute shaders, unlike every other stage
7297 * and platform.
7298 */
7299 prog_data->total_scratch = MAX2(prog_data->total_scratch, 2048);
7300 } else if (devinfo->gen <= 7) {
7301 /* According to the MEDIA_VFE_STATE's "Per Thread Scratch Space"
7302 * field documentation, platforms prior to Haswell measure scratch
7303 * size linearly with a range of [1kB, 12kB] and 1kB granularity.
7304 */
7305 prog_data->total_scratch = ALIGN(last_scratch, 1024);
7306 max_scratch_size = 12 * 1024;
7307 }
7308 }
7309
7310 /* We currently only support up to 2MB of scratch space. If we
7311 * need to support more eventually, the documentation suggests
7312 * that we could allocate a larger buffer, and partition it out
7313 * ourselves. We'd just have to undo the hardware's address
7314 * calculation by subtracting (FFTID * Per Thread Scratch Space)
7315 * and then add FFTID * (Larger Per Thread Scratch Space).
7316 *
7317 * See 3D-Media-GPGPU Engine > Media GPGPU Pipeline >
7318 * Thread Group Tracking > Local Memory/Scratch Space.
7319 */
7320 assert(prog_data->total_scratch < max_scratch_size);
7321 }
7322 }
7323
7324 bool
7325 fs_visitor::run_vs()
7326 {
7327 assert(stage == MESA_SHADER_VERTEX);
7328
7329 setup_vs_payload();
7330
7331 if (shader_time_index >= 0)
7332 emit_shader_time_begin();
7333
7334 emit_nir_code();
7335
7336 if (failed)
7337 return false;
7338
7339 compute_clip_distance();
7340
7341 emit_urb_writes();
7342
7343 if (shader_time_index >= 0)
7344 emit_shader_time_end();
7345
7346 calculate_cfg();
7347
7348 optimize();
7349
7350 assign_curb_setup();
7351 assign_vs_urb_setup();
7352
7353 fixup_3src_null_dest();
7354 allocate_registers(8, true);
7355
7356 return !failed;
7357 }
7358
7359 bool
7360 fs_visitor::run_tcs_single_patch()
7361 {
7362 assert(stage == MESA_SHADER_TESS_CTRL);
7363
7364 struct brw_tcs_prog_data *tcs_prog_data = brw_tcs_prog_data(prog_data);
7365
7366 /* r1-r4 contain the ICP handles. */
7367 payload.num_regs = 5;
7368
7369 if (shader_time_index >= 0)
7370 emit_shader_time_begin();
7371
7372 /* Initialize gl_InvocationID */
7373 fs_reg channels_uw = bld.vgrf(BRW_REGISTER_TYPE_UW);
7374 fs_reg channels_ud = bld.vgrf(BRW_REGISTER_TYPE_UD);
7375 bld.MOV(channels_uw, fs_reg(brw_imm_uv(0x76543210)));
7376 bld.MOV(channels_ud, channels_uw);
7377
7378 if (tcs_prog_data->instances == 1) {
7379 invocation_id = channels_ud;
7380 } else {
7381 const unsigned invocation_id_mask = devinfo->gen >= 11 ?
7382 INTEL_MASK(22, 16) : INTEL_MASK(23, 17);
7383 const unsigned invocation_id_shift = devinfo->gen >= 11 ? 16 : 17;
7384
7385 invocation_id = bld.vgrf(BRW_REGISTER_TYPE_UD);
7386
7387 /* Get instance number from g0.2 bits 23:17, and multiply it by 8. */
7388 fs_reg t = bld.vgrf(BRW_REGISTER_TYPE_UD);
7389 fs_reg instance_times_8 = bld.vgrf(BRW_REGISTER_TYPE_UD);
7390 bld.AND(t, fs_reg(retype(brw_vec1_grf(0, 2), BRW_REGISTER_TYPE_UD)),
7391 brw_imm_ud(invocation_id_mask));
7392 bld.SHR(instance_times_8, t, brw_imm_ud(invocation_id_shift - 3));
7393
7394 bld.ADD(invocation_id, instance_times_8, channels_ud);
7395 }
7396
7397 /* Fix the disptach mask */
7398 if (nir->info.tess.tcs_vertices_out % 8) {
7399 bld.CMP(bld.null_reg_ud(), invocation_id,
7400 brw_imm_ud(nir->info.tess.tcs_vertices_out), BRW_CONDITIONAL_L);
7401 bld.IF(BRW_PREDICATE_NORMAL);
7402 }
7403
7404 emit_nir_code();
7405
7406 if (nir->info.tess.tcs_vertices_out % 8) {
7407 bld.emit(BRW_OPCODE_ENDIF);
7408 }
7409
7410 /* Emit EOT write; set TR DS Cache bit */
7411 fs_reg srcs[3] = {
7412 fs_reg(retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_UD)),
7413 fs_reg(brw_imm_ud(WRITEMASK_X << 16)),
7414 fs_reg(brw_imm_ud(0)),
7415 };
7416 fs_reg payload = bld.vgrf(BRW_REGISTER_TYPE_UD, 3);
7417 bld.LOAD_PAYLOAD(payload, srcs, 3, 2);
7418
7419 fs_inst *inst = bld.emit(SHADER_OPCODE_URB_WRITE_SIMD8_MASKED,
7420 bld.null_reg_ud(), payload);
7421 inst->mlen = 3;
7422 inst->eot = true;
7423
7424 if (shader_time_index >= 0)
7425 emit_shader_time_end();
7426
7427 if (failed)
7428 return false;
7429
7430 calculate_cfg();
7431
7432 optimize();
7433
7434 assign_curb_setup();
7435 assign_tcs_single_patch_urb_setup();
7436
7437 fixup_3src_null_dest();
7438 allocate_registers(8, true);
7439
7440 return !failed;
7441 }
7442
7443 bool
7444 fs_visitor::run_tes()
7445 {
7446 assert(stage == MESA_SHADER_TESS_EVAL);
7447
7448 /* R0: thread header, R1-3: gl_TessCoord.xyz, R4: URB handles */
7449 payload.num_regs = 5;
7450
7451 if (shader_time_index >= 0)
7452 emit_shader_time_begin();
7453
7454 emit_nir_code();
7455
7456 if (failed)
7457 return false;
7458
7459 emit_urb_writes();
7460
7461 if (shader_time_index >= 0)
7462 emit_shader_time_end();
7463
7464 calculate_cfg();
7465
7466 optimize();
7467
7468 assign_curb_setup();
7469 assign_tes_urb_setup();
7470
7471 fixup_3src_null_dest();
7472 allocate_registers(8, true);
7473
7474 return !failed;
7475 }
7476
7477 bool
7478 fs_visitor::run_gs()
7479 {
7480 assert(stage == MESA_SHADER_GEOMETRY);
7481
7482 setup_gs_payload();
7483
7484 this->final_gs_vertex_count = vgrf(glsl_type::uint_type);
7485
7486 if (gs_compile->control_data_header_size_bits > 0) {
7487 /* Create a VGRF to store accumulated control data bits. */
7488 this->control_data_bits = vgrf(glsl_type::uint_type);
7489
7490 /* If we're outputting more than 32 control data bits, then EmitVertex()
7491 * will set control_data_bits to 0 after emitting the first vertex.
7492 * Otherwise, we need to initialize it to 0 here.
7493 */
7494 if (gs_compile->control_data_header_size_bits <= 32) {
7495 const fs_builder abld = bld.annotate("initialize control data bits");
7496 abld.MOV(this->control_data_bits, brw_imm_ud(0u));
7497 }
7498 }
7499
7500 if (shader_time_index >= 0)
7501 emit_shader_time_begin();
7502
7503 emit_nir_code();
7504
7505 emit_gs_thread_end();
7506
7507 if (shader_time_index >= 0)
7508 emit_shader_time_end();
7509
7510 if (failed)
7511 return false;
7512
7513 calculate_cfg();
7514
7515 optimize();
7516
7517 assign_curb_setup();
7518 assign_gs_urb_setup();
7519
7520 fixup_3src_null_dest();
7521 allocate_registers(8, true);
7522
7523 return !failed;
7524 }
7525
7526 /* From the SKL PRM, Volume 16, Workarounds:
7527 *
7528 * 0877 3D Pixel Shader Hang possible when pixel shader dispatched with
7529 * only header phases (R0-R2)
7530 *
7531 * WA: Enable a non-header phase (e.g. push constant) when dispatch would
7532 * have been header only.
7533 *
7534 * Instead of enabling push constants one can alternatively enable one of the
7535 * inputs. Here one simply chooses "layer" which shouldn't impose much
7536 * overhead.
7537 */
7538 static void
7539 gen9_ps_header_only_workaround(struct brw_wm_prog_data *wm_prog_data)
7540 {
7541 if (wm_prog_data->num_varying_inputs)
7542 return;
7543
7544 if (wm_prog_data->base.curb_read_length)
7545 return;
7546
7547 wm_prog_data->urb_setup[VARYING_SLOT_LAYER] = 0;
7548 wm_prog_data->num_varying_inputs = 1;
7549 }
7550
7551 bool
7552 fs_visitor::run_fs(bool allow_spilling, bool do_rep_send)
7553 {
7554 struct brw_wm_prog_data *wm_prog_data = brw_wm_prog_data(this->prog_data);
7555 brw_wm_prog_key *wm_key = (brw_wm_prog_key *) this->key;
7556
7557 assert(stage == MESA_SHADER_FRAGMENT);
7558
7559 if (devinfo->gen >= 6)
7560 setup_fs_payload_gen6();
7561 else
7562 setup_fs_payload_gen4();
7563
7564 if (0) {
7565 emit_dummy_fs();
7566 } else if (do_rep_send) {
7567 assert(dispatch_width == 16);
7568 emit_repclear_shader();
7569 } else {
7570 if (shader_time_index >= 0)
7571 emit_shader_time_begin();
7572
7573 calculate_urb_setup();
7574 if (nir->info.inputs_read > 0 ||
7575 (nir->info.outputs_read > 0 && !wm_key->coherent_fb_fetch)) {
7576 if (devinfo->gen < 6)
7577 emit_interpolation_setup_gen4();
7578 else
7579 emit_interpolation_setup_gen6();
7580 }
7581
7582 /* We handle discards by keeping track of the still-live pixels in f0.1.
7583 * Initialize it with the dispatched pixels.
7584 */
7585 if (wm_prog_data->uses_kill) {
7586 const fs_reg dispatch_mask =
7587 devinfo->gen >= 6 ? brw_vec1_grf(1, 7) : brw_vec1_grf(0, 0);
7588 bld.exec_all().group(1, 0)
7589 .MOV(retype(brw_flag_reg(0, 1), BRW_REGISTER_TYPE_UW),
7590 retype(dispatch_mask, BRW_REGISTER_TYPE_UW));
7591 }
7592
7593 emit_nir_code();
7594
7595 if (failed)
7596 return false;
7597
7598 if (wm_prog_data->uses_kill)
7599 bld.emit(FS_OPCODE_PLACEHOLDER_HALT);
7600
7601 if (wm_key->alpha_test_func)
7602 emit_alpha_test();
7603
7604 emit_fb_writes();
7605
7606 if (shader_time_index >= 0)
7607 emit_shader_time_end();
7608
7609 calculate_cfg();
7610
7611 optimize();
7612
7613 assign_curb_setup();
7614
7615 if (devinfo->gen >= 9)
7616 gen9_ps_header_only_workaround(wm_prog_data);
7617
7618 assign_urb_setup();
7619
7620 fixup_3src_null_dest();
7621 allocate_registers(8, allow_spilling);
7622
7623 if (failed)
7624 return false;
7625 }
7626
7627 return !failed;
7628 }
7629
7630 bool
7631 fs_visitor::run_cs(unsigned min_dispatch_width)
7632 {
7633 assert(stage == MESA_SHADER_COMPUTE);
7634 assert(dispatch_width >= min_dispatch_width);
7635
7636 setup_cs_payload();
7637
7638 if (shader_time_index >= 0)
7639 emit_shader_time_begin();
7640
7641 if (devinfo->is_haswell && prog_data->total_shared > 0) {
7642 /* Move SLM index from g0.0[27:24] to sr0.1[11:8] */
7643 const fs_builder abld = bld.exec_all().group(1, 0);
7644 abld.MOV(retype(brw_sr0_reg(1), BRW_REGISTER_TYPE_UW),
7645 suboffset(retype(brw_vec1_grf(0, 0), BRW_REGISTER_TYPE_UW), 1));
7646 }
7647
7648 emit_nir_code();
7649
7650 if (failed)
7651 return false;
7652
7653 emit_cs_terminate();
7654
7655 if (shader_time_index >= 0)
7656 emit_shader_time_end();
7657
7658 calculate_cfg();
7659
7660 optimize();
7661
7662 assign_curb_setup();
7663
7664 fixup_3src_null_dest();
7665 allocate_registers(min_dispatch_width, true);
7666
7667 if (failed)
7668 return false;
7669
7670 return !failed;
7671 }
7672
7673 /**
7674 * Return a bitfield where bit n is set if barycentric interpolation mode n
7675 * (see enum brw_barycentric_mode) is needed by the fragment shader.
7676 *
7677 * We examine the load_barycentric intrinsics rather than looking at input
7678 * variables so that we catch interpolateAtCentroid() messages too, which
7679 * also need the BRW_BARYCENTRIC_[NON]PERSPECTIVE_CENTROID mode set up.
7680 */
7681 static unsigned
7682 brw_compute_barycentric_interp_modes(const struct gen_device_info *devinfo,
7683 const nir_shader *shader)
7684 {
7685 unsigned barycentric_interp_modes = 0;
7686
7687 nir_foreach_function(f, shader) {
7688 if (!f->impl)
7689 continue;
7690
7691 nir_foreach_block(block, f->impl) {
7692 nir_foreach_instr(instr, block) {
7693 if (instr->type != nir_instr_type_intrinsic)
7694 continue;
7695
7696 nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
7697 if (intrin->intrinsic != nir_intrinsic_load_interpolated_input)
7698 continue;
7699
7700 /* Ignore WPOS; it doesn't require interpolation. */
7701 if (nir_intrinsic_base(intrin) == VARYING_SLOT_POS)
7702 continue;
7703
7704 intrin = nir_instr_as_intrinsic(intrin->src[0].ssa->parent_instr);
7705 enum glsl_interp_mode interp = (enum glsl_interp_mode)
7706 nir_intrinsic_interp_mode(intrin);
7707 nir_intrinsic_op bary_op = intrin->intrinsic;
7708 enum brw_barycentric_mode bary =
7709 brw_barycentric_mode(interp, bary_op);
7710
7711 barycentric_interp_modes |= 1 << bary;
7712
7713 if (devinfo->needs_unlit_centroid_workaround &&
7714 bary_op == nir_intrinsic_load_barycentric_centroid)
7715 barycentric_interp_modes |= 1 << centroid_to_pixel(bary);
7716 }
7717 }
7718 }
7719
7720 return barycentric_interp_modes;
7721 }
7722
7723 static void
7724 brw_compute_flat_inputs(struct brw_wm_prog_data *prog_data,
7725 const nir_shader *shader)
7726 {
7727 prog_data->flat_inputs = 0;
7728
7729 nir_foreach_variable(var, &shader->inputs) {
7730 unsigned slots = glsl_count_attribute_slots(var->type, false);
7731 for (unsigned s = 0; s < slots; s++) {
7732 int input_index = prog_data->urb_setup[var->data.location + s];
7733
7734 if (input_index < 0)
7735 continue;
7736
7737 /* flat shading */
7738 if (var->data.interpolation == INTERP_MODE_FLAT)
7739 prog_data->flat_inputs |= 1 << input_index;
7740 }
7741 }
7742 }
7743
7744 static uint8_t
7745 computed_depth_mode(const nir_shader *shader)
7746 {
7747 if (shader->info.outputs_written & BITFIELD64_BIT(FRAG_RESULT_DEPTH)) {
7748 switch (shader->info.fs.depth_layout) {
7749 case FRAG_DEPTH_LAYOUT_NONE:
7750 case FRAG_DEPTH_LAYOUT_ANY:
7751 return BRW_PSCDEPTH_ON;
7752 case FRAG_DEPTH_LAYOUT_GREATER:
7753 return BRW_PSCDEPTH_ON_GE;
7754 case FRAG_DEPTH_LAYOUT_LESS:
7755 return BRW_PSCDEPTH_ON_LE;
7756 case FRAG_DEPTH_LAYOUT_UNCHANGED:
7757 return BRW_PSCDEPTH_OFF;
7758 }
7759 }
7760 return BRW_PSCDEPTH_OFF;
7761 }
7762
7763 /**
7764 * Move load_interpolated_input with simple (payload-based) barycentric modes
7765 * to the top of the program so we don't emit multiple PLNs for the same input.
7766 *
7767 * This works around CSE not being able to handle non-dominating cases
7768 * such as:
7769 *
7770 * if (...) {
7771 * interpolate input
7772 * } else {
7773 * interpolate the same exact input
7774 * }
7775 *
7776 * This should be replaced by global value numbering someday.
7777 */
7778 static bool
7779 move_interpolation_to_top(nir_shader *nir)
7780 {
7781 bool progress = false;
7782
7783 nir_foreach_function(f, nir) {
7784 if (!f->impl)
7785 continue;
7786
7787 nir_block *top = nir_start_block(f->impl);
7788 exec_node *cursor_node = NULL;
7789
7790 nir_foreach_block(block, f->impl) {
7791 if (block == top)
7792 continue;
7793
7794 nir_foreach_instr_safe(instr, block) {
7795 if (instr->type != nir_instr_type_intrinsic)
7796 continue;
7797
7798 nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
7799 if (intrin->intrinsic != nir_intrinsic_load_interpolated_input)
7800 continue;
7801 nir_intrinsic_instr *bary_intrinsic =
7802 nir_instr_as_intrinsic(intrin->src[0].ssa->parent_instr);
7803 nir_intrinsic_op op = bary_intrinsic->intrinsic;
7804
7805 /* Leave interpolateAtSample/Offset() where they are. */
7806 if (op == nir_intrinsic_load_barycentric_at_sample ||
7807 op == nir_intrinsic_load_barycentric_at_offset)
7808 continue;
7809
7810 nir_instr *move[3] = {
7811 &bary_intrinsic->instr,
7812 intrin->src[1].ssa->parent_instr,
7813 instr
7814 };
7815
7816 for (unsigned i = 0; i < ARRAY_SIZE(move); i++) {
7817 if (move[i]->block != top) {
7818 move[i]->block = top;
7819 exec_node_remove(&move[i]->node);
7820 if (cursor_node) {
7821 exec_node_insert_after(cursor_node, &move[i]->node);
7822 } else {
7823 exec_list_push_head(&top->instr_list, &move[i]->node);
7824 }
7825 cursor_node = &move[i]->node;
7826 progress = true;
7827 }
7828 }
7829 }
7830 }
7831 nir_metadata_preserve(f->impl, (nir_metadata)
7832 ((unsigned) nir_metadata_block_index |
7833 (unsigned) nir_metadata_dominance));
7834 }
7835
7836 return progress;
7837 }
7838
7839 /**
7840 * Demote per-sample barycentric intrinsics to centroid.
7841 *
7842 * Useful when rendering to a non-multisampled buffer.
7843 */
7844 static bool
7845 demote_sample_qualifiers(nir_shader *nir)
7846 {
7847 bool progress = true;
7848
7849 nir_foreach_function(f, nir) {
7850 if (!f->impl)
7851 continue;
7852
7853 nir_builder b;
7854 nir_builder_init(&b, f->impl);
7855
7856 nir_foreach_block(block, f->impl) {
7857 nir_foreach_instr_safe(instr, block) {
7858 if (instr->type != nir_instr_type_intrinsic)
7859 continue;
7860
7861 nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
7862 if (intrin->intrinsic != nir_intrinsic_load_barycentric_sample &&
7863 intrin->intrinsic != nir_intrinsic_load_barycentric_at_sample)
7864 continue;
7865
7866 b.cursor = nir_before_instr(instr);
7867 nir_ssa_def *centroid =
7868 nir_load_barycentric(&b, nir_intrinsic_load_barycentric_centroid,
7869 nir_intrinsic_interp_mode(intrin));
7870 nir_ssa_def_rewrite_uses(&intrin->dest.ssa,
7871 nir_src_for_ssa(centroid));
7872 nir_instr_remove(instr);
7873 progress = true;
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 * Pre-gen6, the register file of the EUs was shared between threads,
7887 * and each thread used some subset allocated on a 16-register block
7888 * granularity. The unit states wanted these block counts.
7889 */
7890 static inline int
7891 brw_register_blocks(int reg_count)
7892 {
7893 return ALIGN(reg_count, 16) / 16 - 1;
7894 }
7895
7896 const unsigned *
7897 brw_compile_fs(const struct brw_compiler *compiler, void *log_data,
7898 void *mem_ctx,
7899 const struct brw_wm_prog_key *key,
7900 struct brw_wm_prog_data *prog_data,
7901 nir_shader *shader,
7902 struct gl_program *prog,
7903 int shader_time_index8, int shader_time_index16,
7904 int shader_time_index32, bool allow_spilling,
7905 bool use_rep_send, struct brw_vue_map *vue_map,
7906 char **error_str)
7907 {
7908 const struct gen_device_info *devinfo = compiler->devinfo;
7909
7910 shader = brw_nir_apply_sampler_key(shader, compiler, &key->tex, true);
7911 brw_nir_lower_fs_inputs(shader, devinfo, key);
7912 brw_nir_lower_fs_outputs(shader);
7913
7914 if (devinfo->gen < 6)
7915 brw_setup_vue_interpolation(vue_map, shader, prog_data);
7916
7917 if (!key->multisample_fbo)
7918 NIR_PASS_V(shader, demote_sample_qualifiers);
7919 NIR_PASS_V(shader, move_interpolation_to_top);
7920 shader = brw_postprocess_nir(shader, compiler, true);
7921
7922 /* key->alpha_test_func means simulating alpha testing via discards,
7923 * so the shader definitely kills pixels.
7924 */
7925 prog_data->uses_kill = shader->info.fs.uses_discard ||
7926 key->alpha_test_func;
7927 prog_data->uses_omask = key->multisample_fbo &&
7928 shader->info.outputs_written & BITFIELD64_BIT(FRAG_RESULT_SAMPLE_MASK);
7929 prog_data->computed_depth_mode = computed_depth_mode(shader);
7930 prog_data->computed_stencil =
7931 shader->info.outputs_written & BITFIELD64_BIT(FRAG_RESULT_STENCIL);
7932
7933 prog_data->persample_dispatch =
7934 key->multisample_fbo &&
7935 (key->persample_interp ||
7936 (shader->info.system_values_read & (SYSTEM_BIT_SAMPLE_ID |
7937 SYSTEM_BIT_SAMPLE_POS)) ||
7938 shader->info.fs.uses_sample_qualifier ||
7939 shader->info.outputs_read);
7940
7941 prog_data->has_render_target_reads = shader->info.outputs_read != 0ull;
7942
7943 prog_data->early_fragment_tests = shader->info.fs.early_fragment_tests;
7944 prog_data->post_depth_coverage = shader->info.fs.post_depth_coverage;
7945 prog_data->inner_coverage = shader->info.fs.inner_coverage;
7946
7947 prog_data->barycentric_interp_modes =
7948 brw_compute_barycentric_interp_modes(compiler->devinfo, shader);
7949
7950 cfg_t *simd8_cfg = NULL, *simd16_cfg = NULL, *simd32_cfg = NULL;
7951
7952 fs_visitor v8(compiler, log_data, mem_ctx, key,
7953 &prog_data->base, prog, shader, 8,
7954 shader_time_index8);
7955 if (!v8.run_fs(allow_spilling, false /* do_rep_send */)) {
7956 if (error_str)
7957 *error_str = ralloc_strdup(mem_ctx, v8.fail_msg);
7958
7959 return NULL;
7960 } else if (likely(!(INTEL_DEBUG & DEBUG_NO8))) {
7961 simd8_cfg = v8.cfg;
7962 prog_data->base.dispatch_grf_start_reg = v8.payload.num_regs;
7963 prog_data->reg_blocks_8 = brw_register_blocks(v8.grf_used);
7964 }
7965
7966 if (v8.max_dispatch_width >= 16 &&
7967 likely(!(INTEL_DEBUG & DEBUG_NO16) || use_rep_send)) {
7968 /* Try a SIMD16 compile */
7969 fs_visitor v16(compiler, log_data, mem_ctx, key,
7970 &prog_data->base, prog, shader, 16,
7971 shader_time_index16);
7972 v16.import_uniforms(&v8);
7973 if (!v16.run_fs(allow_spilling, use_rep_send)) {
7974 compiler->shader_perf_log(log_data,
7975 "SIMD16 shader failed to compile: %s",
7976 v16.fail_msg);
7977 } else {
7978 simd16_cfg = v16.cfg;
7979 prog_data->dispatch_grf_start_reg_16 = v16.payload.num_regs;
7980 prog_data->reg_blocks_16 = brw_register_blocks(v16.grf_used);
7981 }
7982 }
7983
7984 /* Currently, the compiler only supports SIMD32 on SNB+ */
7985 if (v8.max_dispatch_width >= 32 && !use_rep_send &&
7986 compiler->devinfo->gen >= 6 &&
7987 unlikely(INTEL_DEBUG & DEBUG_DO32)) {
7988 /* Try a SIMD32 compile */
7989 fs_visitor v32(compiler, log_data, mem_ctx, key,
7990 &prog_data->base, prog, shader, 32,
7991 shader_time_index32);
7992 v32.import_uniforms(&v8);
7993 if (!v32.run_fs(allow_spilling, false)) {
7994 compiler->shader_perf_log(log_data,
7995 "SIMD32 shader failed to compile: %s",
7996 v32.fail_msg);
7997 } else {
7998 simd32_cfg = v32.cfg;
7999 prog_data->dispatch_grf_start_reg_32 = v32.payload.num_regs;
8000 prog_data->reg_blocks_32 = brw_register_blocks(v32.grf_used);
8001 }
8002 }
8003
8004 /* When the caller requests a repclear shader, they want SIMD16-only */
8005 if (use_rep_send)
8006 simd8_cfg = NULL;
8007
8008 /* Prior to Iron Lake, the PS had a single shader offset with a jump table
8009 * at the top to select the shader. We've never implemented that.
8010 * Instead, we just give them exactly one shader and we pick the widest one
8011 * available.
8012 */
8013 if (compiler->devinfo->gen < 5) {
8014 if (simd32_cfg || simd16_cfg)
8015 simd8_cfg = NULL;
8016 if (simd32_cfg)
8017 simd16_cfg = NULL;
8018 }
8019
8020 /* If computed depth is enabled SNB only allows SIMD8. */
8021 if (compiler->devinfo->gen == 6 &&
8022 prog_data->computed_depth_mode != BRW_PSCDEPTH_OFF)
8023 assert(simd16_cfg == NULL && simd32_cfg == NULL);
8024
8025 if (compiler->devinfo->gen <= 5 && !simd8_cfg) {
8026 /* Iron lake and earlier only have one Dispatch GRF start field. Make
8027 * the data available in the base prog data struct for convenience.
8028 */
8029 if (simd16_cfg) {
8030 prog_data->base.dispatch_grf_start_reg =
8031 prog_data->dispatch_grf_start_reg_16;
8032 } else if (simd32_cfg) {
8033 prog_data->base.dispatch_grf_start_reg =
8034 prog_data->dispatch_grf_start_reg_32;
8035 }
8036 }
8037
8038 if (prog_data->persample_dispatch) {
8039 /* Starting with SandyBridge (where we first get MSAA), the different
8040 * pixel dispatch combinations are grouped into classifications A
8041 * through F (SNB PRM Vol. 2 Part 1 Section 7.7.1). On all hardware
8042 * generations, the only configurations supporting persample dispatch
8043 * are are this in which only one dispatch width is enabled.
8044 */
8045 if (simd32_cfg || simd16_cfg)
8046 simd8_cfg = NULL;
8047 if (simd32_cfg)
8048 simd16_cfg = NULL;
8049 }
8050
8051 /* We have to compute the flat inputs after the visitor is finished running
8052 * because it relies on prog_data->urb_setup which is computed in
8053 * fs_visitor::calculate_urb_setup().
8054 */
8055 brw_compute_flat_inputs(prog_data, shader);
8056
8057 fs_generator g(compiler, log_data, mem_ctx, &prog_data->base,
8058 v8.promoted_constants, v8.runtime_check_aads_emit,
8059 MESA_SHADER_FRAGMENT);
8060
8061 if (unlikely(INTEL_DEBUG & DEBUG_WM)) {
8062 g.enable_debug(ralloc_asprintf(mem_ctx, "%s fragment shader %s",
8063 shader->info.label ?
8064 shader->info.label : "unnamed",
8065 shader->info.name));
8066 }
8067
8068 if (simd8_cfg) {
8069 prog_data->dispatch_8 = true;
8070 g.generate_code(simd8_cfg, 8);
8071 }
8072
8073 if (simd16_cfg) {
8074 prog_data->dispatch_16 = true;
8075 prog_data->prog_offset_16 = g.generate_code(simd16_cfg, 16);
8076 }
8077
8078 if (simd32_cfg) {
8079 prog_data->dispatch_32 = true;
8080 prog_data->prog_offset_32 = g.generate_code(simd32_cfg, 32);
8081 }
8082
8083 return g.get_assembly();
8084 }
8085
8086 fs_reg *
8087 fs_visitor::emit_cs_work_group_id_setup()
8088 {
8089 assert(stage == MESA_SHADER_COMPUTE);
8090
8091 fs_reg *reg = new(this->mem_ctx) fs_reg(vgrf(glsl_type::uvec3_type));
8092
8093 struct brw_reg r0_1(retype(brw_vec1_grf(0, 1), BRW_REGISTER_TYPE_UD));
8094 struct brw_reg r0_6(retype(brw_vec1_grf(0, 6), BRW_REGISTER_TYPE_UD));
8095 struct brw_reg r0_7(retype(brw_vec1_grf(0, 7), BRW_REGISTER_TYPE_UD));
8096
8097 bld.MOV(*reg, r0_1);
8098 bld.MOV(offset(*reg, bld, 1), r0_6);
8099 bld.MOV(offset(*reg, bld, 2), r0_7);
8100
8101 return reg;
8102 }
8103
8104 static void
8105 fill_push_const_block_info(struct brw_push_const_block *block, unsigned dwords)
8106 {
8107 block->dwords = dwords;
8108 block->regs = DIV_ROUND_UP(dwords, 8);
8109 block->size = block->regs * 32;
8110 }
8111
8112 static void
8113 cs_fill_push_const_info(const struct gen_device_info *devinfo,
8114 struct brw_cs_prog_data *cs_prog_data)
8115 {
8116 const struct brw_stage_prog_data *prog_data = &cs_prog_data->base;
8117 int subgroup_id_index = get_subgroup_id_param_index(prog_data);
8118 bool cross_thread_supported = devinfo->gen > 7 || devinfo->is_haswell;
8119
8120 /* The thread ID should be stored in the last param dword */
8121 assert(subgroup_id_index == -1 ||
8122 subgroup_id_index == (int)prog_data->nr_params - 1);
8123
8124 unsigned cross_thread_dwords, per_thread_dwords;
8125 if (!cross_thread_supported) {
8126 cross_thread_dwords = 0u;
8127 per_thread_dwords = prog_data->nr_params;
8128 } else if (subgroup_id_index >= 0) {
8129 /* Fill all but the last register with cross-thread payload */
8130 cross_thread_dwords = 8 * (subgroup_id_index / 8);
8131 per_thread_dwords = prog_data->nr_params - cross_thread_dwords;
8132 assert(per_thread_dwords > 0 && per_thread_dwords <= 8);
8133 } else {
8134 /* Fill all data using cross-thread payload */
8135 cross_thread_dwords = prog_data->nr_params;
8136 per_thread_dwords = 0u;
8137 }
8138
8139 fill_push_const_block_info(&cs_prog_data->push.cross_thread, cross_thread_dwords);
8140 fill_push_const_block_info(&cs_prog_data->push.per_thread, per_thread_dwords);
8141
8142 unsigned total_dwords =
8143 (cs_prog_data->push.per_thread.size * cs_prog_data->threads +
8144 cs_prog_data->push.cross_thread.size) / 4;
8145 fill_push_const_block_info(&cs_prog_data->push.total, total_dwords);
8146
8147 assert(cs_prog_data->push.cross_thread.dwords % 8 == 0 ||
8148 cs_prog_data->push.per_thread.size == 0);
8149 assert(cs_prog_data->push.cross_thread.dwords +
8150 cs_prog_data->push.per_thread.dwords ==
8151 prog_data->nr_params);
8152 }
8153
8154 static void
8155 cs_set_simd_size(struct brw_cs_prog_data *cs_prog_data, unsigned size)
8156 {
8157 cs_prog_data->simd_size = size;
8158 unsigned group_size = cs_prog_data->local_size[0] *
8159 cs_prog_data->local_size[1] * cs_prog_data->local_size[2];
8160 cs_prog_data->threads = (group_size + size - 1) / size;
8161 }
8162
8163 static nir_shader *
8164 compile_cs_to_nir(const struct brw_compiler *compiler,
8165 void *mem_ctx,
8166 const struct brw_cs_prog_key *key,
8167 const nir_shader *src_shader,
8168 unsigned dispatch_width)
8169 {
8170 nir_shader *shader = nir_shader_clone(mem_ctx, src_shader);
8171 shader = brw_nir_apply_sampler_key(shader, compiler, &key->tex, true);
8172
8173 NIR_PASS_V(shader, brw_nir_lower_cs_intrinsics, dispatch_width);
8174
8175 /* Clean up after the local index and ID calculations. */
8176 NIR_PASS_V(shader, nir_opt_constant_folding);
8177 NIR_PASS_V(shader, nir_opt_dce);
8178
8179 return brw_postprocess_nir(shader, compiler, true);
8180 }
8181
8182 const unsigned *
8183 brw_compile_cs(const struct brw_compiler *compiler, void *log_data,
8184 void *mem_ctx,
8185 const struct brw_cs_prog_key *key,
8186 struct brw_cs_prog_data *prog_data,
8187 const nir_shader *src_shader,
8188 int shader_time_index,
8189 char **error_str)
8190 {
8191 prog_data->local_size[0] = src_shader->info.cs.local_size[0];
8192 prog_data->local_size[1] = src_shader->info.cs.local_size[1];
8193 prog_data->local_size[2] = src_shader->info.cs.local_size[2];
8194 unsigned local_workgroup_size =
8195 src_shader->info.cs.local_size[0] * src_shader->info.cs.local_size[1] *
8196 src_shader->info.cs.local_size[2];
8197
8198 unsigned min_dispatch_width =
8199 DIV_ROUND_UP(local_workgroup_size, compiler->devinfo->max_cs_threads);
8200 min_dispatch_width = MAX2(8, min_dispatch_width);
8201 min_dispatch_width = util_next_power_of_two(min_dispatch_width);
8202 assert(min_dispatch_width <= 32);
8203
8204 fs_visitor *v8 = NULL, *v16 = NULL, *v32 = NULL;
8205 cfg_t *cfg = NULL;
8206 const char *fail_msg = NULL;
8207 unsigned promoted_constants = 0;
8208
8209 /* Now the main event: Visit the shader IR and generate our CS IR for it.
8210 */
8211 if (min_dispatch_width <= 8) {
8212 nir_shader *nir8 = compile_cs_to_nir(compiler, mem_ctx, key,
8213 src_shader, 8);
8214 v8 = new fs_visitor(compiler, log_data, mem_ctx, key, &prog_data->base,
8215 NULL, /* Never used in core profile */
8216 nir8, 8, shader_time_index);
8217 if (!v8->run_cs(min_dispatch_width)) {
8218 fail_msg = v8->fail_msg;
8219 } else {
8220 /* We should always be able to do SIMD32 for compute shaders */
8221 assert(v8->max_dispatch_width >= 32);
8222
8223 cfg = v8->cfg;
8224 cs_set_simd_size(prog_data, 8);
8225 cs_fill_push_const_info(compiler->devinfo, prog_data);
8226 promoted_constants = v8->promoted_constants;
8227 }
8228 }
8229
8230 if (likely(!(INTEL_DEBUG & DEBUG_NO16)) &&
8231 !fail_msg && min_dispatch_width <= 16) {
8232 /* Try a SIMD16 compile */
8233 nir_shader *nir16 = compile_cs_to_nir(compiler, mem_ctx, key,
8234 src_shader, 16);
8235 v16 = new fs_visitor(compiler, log_data, mem_ctx, key, &prog_data->base,
8236 NULL, /* Never used in core profile */
8237 nir16, 16, shader_time_index);
8238 if (v8)
8239 v16->import_uniforms(v8);
8240
8241 if (!v16->run_cs(min_dispatch_width)) {
8242 compiler->shader_perf_log(log_data,
8243 "SIMD16 shader failed to compile: %s",
8244 v16->fail_msg);
8245 if (!cfg) {
8246 fail_msg =
8247 "Couldn't generate SIMD16 program and not "
8248 "enough threads for SIMD8";
8249 }
8250 } else {
8251 /* We should always be able to do SIMD32 for compute shaders */
8252 assert(v16->max_dispatch_width >= 32);
8253
8254 cfg = v16->cfg;
8255 cs_set_simd_size(prog_data, 16);
8256 cs_fill_push_const_info(compiler->devinfo, prog_data);
8257 promoted_constants = v16->promoted_constants;
8258 }
8259 }
8260
8261 /* We should always be able to do SIMD32 for compute shaders */
8262 assert(!v16 || v16->max_dispatch_width >= 32);
8263
8264 if (!fail_msg && (min_dispatch_width > 16 || (INTEL_DEBUG & DEBUG_DO32))) {
8265 /* Try a SIMD32 compile */
8266 nir_shader *nir32 = compile_cs_to_nir(compiler, mem_ctx, key,
8267 src_shader, 32);
8268 v32 = new fs_visitor(compiler, log_data, mem_ctx, key, &prog_data->base,
8269 NULL, /* Never used in core profile */
8270 nir32, 32, shader_time_index);
8271 if (v8)
8272 v32->import_uniforms(v8);
8273 else if (v16)
8274 v32->import_uniforms(v16);
8275
8276 if (!v32->run_cs(min_dispatch_width)) {
8277 compiler->shader_perf_log(log_data,
8278 "SIMD32 shader failed to compile: %s",
8279 v16->fail_msg);
8280 if (!cfg) {
8281 fail_msg =
8282 "Couldn't generate SIMD32 program and not "
8283 "enough threads for SIMD16";
8284 }
8285 } else {
8286 cfg = v32->cfg;
8287 cs_set_simd_size(prog_data, 32);
8288 cs_fill_push_const_info(compiler->devinfo, prog_data);
8289 promoted_constants = v32->promoted_constants;
8290 }
8291 }
8292
8293 const unsigned *ret = NULL;
8294 if (unlikely(cfg == NULL)) {
8295 assert(fail_msg);
8296 if (error_str)
8297 *error_str = ralloc_strdup(mem_ctx, fail_msg);
8298 } else {
8299 fs_generator g(compiler, log_data, mem_ctx, &prog_data->base,
8300 promoted_constants, false, MESA_SHADER_COMPUTE);
8301 if (INTEL_DEBUG & DEBUG_CS) {
8302 char *name = ralloc_asprintf(mem_ctx, "%s compute shader %s",
8303 src_shader->info.label ?
8304 src_shader->info.label : "unnamed",
8305 src_shader->info.name);
8306 g.enable_debug(name);
8307 }
8308
8309 g.generate_code(cfg, prog_data->simd_size);
8310
8311 ret = g.get_assembly();
8312 }
8313
8314 delete v8;
8315 delete v16;
8316 delete v32;
8317
8318 return ret;
8319 }
8320
8321 /**
8322 * Test the dispatch mask packing assumptions of
8323 * brw_stage_has_packed_dispatch(). Call this from e.g. the top of
8324 * fs_visitor::emit_nir_code() to cause a GPU hang if any shader invocation is
8325 * executed with an unexpected dispatch mask.
8326 */
8327 static UNUSED void
8328 brw_fs_test_dispatch_packing(const fs_builder &bld)
8329 {
8330 const gl_shader_stage stage = bld.shader->stage;
8331
8332 if (brw_stage_has_packed_dispatch(bld.shader->devinfo, stage,
8333 bld.shader->stage_prog_data)) {
8334 const fs_builder ubld = bld.exec_all().group(1, 0);
8335 const fs_reg tmp = component(bld.vgrf(BRW_REGISTER_TYPE_UD), 0);
8336 const fs_reg mask = (stage == MESA_SHADER_FRAGMENT ? brw_vmask_reg() :
8337 brw_dmask_reg());
8338
8339 ubld.ADD(tmp, mask, brw_imm_ud(1));
8340 ubld.AND(tmp, mask, tmp);
8341
8342 /* This will loop forever if the dispatch mask doesn't have the expected
8343 * form '2^n-1', in which case tmp will be non-zero.
8344 */
8345 bld.emit(BRW_OPCODE_DO);
8346 bld.CMP(bld.null_reg_ud(), tmp, brw_imm_ud(0), BRW_CONDITIONAL_NZ);
8347 set_predicate(BRW_PREDICATE_NORMAL, bld.emit(BRW_OPCODE_WHILE));
8348 }
8349 }