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