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