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