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