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