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