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