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