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