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