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