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