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