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