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