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