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