Replace uses of _mesa_bitcount with util_bitcount
[mesa.git] / src / intel / compiler / brw_vec4.cpp
1 /*
2 * Copyright © 2011 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 #include "brw_vec4.h"
25 #include "brw_fs.h"
26 #include "brw_cfg.h"
27 #include "brw_nir.h"
28 #include "brw_vec4_builder.h"
29 #include "brw_vec4_live_variables.h"
30 #include "brw_vec4_vs.h"
31 #include "brw_dead_control_flow.h"
32 #include "common/gen_debug.h"
33 #include "program/prog_parameter.h"
34 #include "util/u_math.h"
35
36 #define MAX_INSTRUCTION (1 << 30)
37
38 using namespace brw;
39
40 namespace brw {
41
42 void
43 src_reg::init()
44 {
45 memset((void*)this, 0, sizeof(*this));
46 this->file = BAD_FILE;
47 this->type = BRW_REGISTER_TYPE_UD;
48 }
49
50 src_reg::src_reg(enum brw_reg_file file, int nr, const glsl_type *type)
51 {
52 init();
53
54 this->file = file;
55 this->nr = nr;
56 if (type && (type->is_scalar() || type->is_vector() || type->is_matrix()))
57 this->swizzle = brw_swizzle_for_size(type->vector_elements);
58 else
59 this->swizzle = BRW_SWIZZLE_XYZW;
60 if (type)
61 this->type = brw_type_for_base_type(type);
62 }
63
64 /** Generic unset register constructor. */
65 src_reg::src_reg()
66 {
67 init();
68 }
69
70 src_reg::src_reg(struct ::brw_reg reg) :
71 backend_reg(reg)
72 {
73 this->offset = 0;
74 this->reladdr = NULL;
75 }
76
77 src_reg::src_reg(const dst_reg &reg) :
78 backend_reg(reg)
79 {
80 this->reladdr = reg.reladdr;
81 this->swizzle = brw_swizzle_for_mask(reg.writemask);
82 }
83
84 void
85 dst_reg::init()
86 {
87 memset((void*)this, 0, sizeof(*this));
88 this->file = BAD_FILE;
89 this->type = BRW_REGISTER_TYPE_UD;
90 this->writemask = WRITEMASK_XYZW;
91 }
92
93 dst_reg::dst_reg()
94 {
95 init();
96 }
97
98 dst_reg::dst_reg(enum brw_reg_file file, int nr)
99 {
100 init();
101
102 this->file = file;
103 this->nr = nr;
104 }
105
106 dst_reg::dst_reg(enum brw_reg_file file, int nr, const glsl_type *type,
107 unsigned writemask)
108 {
109 init();
110
111 this->file = file;
112 this->nr = nr;
113 this->type = brw_type_for_base_type(type);
114 this->writemask = writemask;
115 }
116
117 dst_reg::dst_reg(enum brw_reg_file file, int nr, brw_reg_type type,
118 unsigned writemask)
119 {
120 init();
121
122 this->file = file;
123 this->nr = nr;
124 this->type = type;
125 this->writemask = writemask;
126 }
127
128 dst_reg::dst_reg(struct ::brw_reg reg) :
129 backend_reg(reg)
130 {
131 this->offset = 0;
132 this->reladdr = NULL;
133 }
134
135 dst_reg::dst_reg(const src_reg &reg) :
136 backend_reg(reg)
137 {
138 this->writemask = brw_mask_for_swizzle(reg.swizzle);
139 this->reladdr = reg.reladdr;
140 }
141
142 bool
143 dst_reg::equals(const dst_reg &r) const
144 {
145 return (this->backend_reg::equals(r) &&
146 (reladdr == r.reladdr ||
147 (reladdr && r.reladdr && reladdr->equals(*r.reladdr))));
148 }
149
150 bool
151 vec4_instruction::is_send_from_grf()
152 {
153 switch (opcode) {
154 case SHADER_OPCODE_SHADER_TIME_ADD:
155 case VS_OPCODE_PULL_CONSTANT_LOAD_GEN7:
156 case SHADER_OPCODE_UNTYPED_ATOMIC:
157 case SHADER_OPCODE_UNTYPED_SURFACE_READ:
158 case SHADER_OPCODE_UNTYPED_SURFACE_WRITE:
159 case SHADER_OPCODE_TYPED_ATOMIC:
160 case SHADER_OPCODE_TYPED_SURFACE_READ:
161 case SHADER_OPCODE_TYPED_SURFACE_WRITE:
162 case VEC4_OPCODE_URB_READ:
163 case TCS_OPCODE_URB_WRITE:
164 case TCS_OPCODE_RELEASE_INPUT:
165 case SHADER_OPCODE_BARRIER:
166 return true;
167 default:
168 return false;
169 }
170 }
171
172 /**
173 * Returns true if this instruction's sources and destinations cannot
174 * safely be the same register.
175 *
176 * In most cases, a register can be written over safely by the same
177 * instruction that is its last use. For a single instruction, the
178 * sources are dereferenced before writing of the destination starts
179 * (naturally).
180 *
181 * However, there are a few cases where this can be problematic:
182 *
183 * - Virtual opcodes that translate to multiple instructions in the
184 * code generator: if src == dst and one instruction writes the
185 * destination before a later instruction reads the source, then
186 * src will have been clobbered.
187 *
188 * The register allocator uses this information to set up conflicts between
189 * GRF sources and the destination.
190 */
191 bool
192 vec4_instruction::has_source_and_destination_hazard() const
193 {
194 switch (opcode) {
195 case TCS_OPCODE_SET_INPUT_URB_OFFSETS:
196 case TCS_OPCODE_SET_OUTPUT_URB_OFFSETS:
197 case TES_OPCODE_ADD_INDIRECT_URB_OFFSET:
198 return true;
199 default:
200 /* 8-wide compressed DF operations are executed as two 4-wide operations,
201 * so we have a src/dst hazard if the first half of the instruction
202 * overwrites the source of the second half. Prevent this by marking
203 * compressed instructions as having src/dst hazards, so the register
204 * allocator assigns safe register regions for dst and srcs.
205 */
206 return size_written > REG_SIZE;
207 }
208 }
209
210 unsigned
211 vec4_instruction::size_read(unsigned arg) const
212 {
213 switch (opcode) {
214 case SHADER_OPCODE_SHADER_TIME_ADD:
215 case SHADER_OPCODE_UNTYPED_ATOMIC:
216 case SHADER_OPCODE_UNTYPED_SURFACE_READ:
217 case SHADER_OPCODE_UNTYPED_SURFACE_WRITE:
218 case SHADER_OPCODE_TYPED_ATOMIC:
219 case SHADER_OPCODE_TYPED_SURFACE_READ:
220 case SHADER_OPCODE_TYPED_SURFACE_WRITE:
221 case TCS_OPCODE_URB_WRITE:
222 if (arg == 0)
223 return mlen * REG_SIZE;
224 break;
225 case VS_OPCODE_PULL_CONSTANT_LOAD_GEN7:
226 if (arg == 1)
227 return mlen * REG_SIZE;
228 break;
229 default:
230 break;
231 }
232
233 switch (src[arg].file) {
234 case BAD_FILE:
235 return 0;
236 case IMM:
237 case UNIFORM:
238 return 4 * type_sz(src[arg].type);
239 default:
240 /* XXX - Represent actual vertical stride. */
241 return exec_size * type_sz(src[arg].type);
242 }
243 }
244
245 bool
246 vec4_instruction::can_do_source_mods(const struct gen_device_info *devinfo)
247 {
248 if (devinfo->gen == 6 && is_math())
249 return false;
250
251 if (is_send_from_grf())
252 return false;
253
254 if (!backend_instruction::can_do_source_mods())
255 return false;
256
257 return true;
258 }
259
260 bool
261 vec4_instruction::can_do_writemask(const struct gen_device_info *devinfo)
262 {
263 switch (opcode) {
264 case SHADER_OPCODE_GEN4_SCRATCH_READ:
265 case VEC4_OPCODE_DOUBLE_TO_F32:
266 case VEC4_OPCODE_DOUBLE_TO_D32:
267 case VEC4_OPCODE_DOUBLE_TO_U32:
268 case VEC4_OPCODE_TO_DOUBLE:
269 case VEC4_OPCODE_PICK_LOW_32BIT:
270 case VEC4_OPCODE_PICK_HIGH_32BIT:
271 case VEC4_OPCODE_SET_LOW_32BIT:
272 case VEC4_OPCODE_SET_HIGH_32BIT:
273 case VS_OPCODE_PULL_CONSTANT_LOAD:
274 case VS_OPCODE_PULL_CONSTANT_LOAD_GEN7:
275 case VS_OPCODE_SET_SIMD4X2_HEADER_GEN9:
276 case TCS_OPCODE_SET_INPUT_URB_OFFSETS:
277 case TCS_OPCODE_SET_OUTPUT_URB_OFFSETS:
278 case TES_OPCODE_CREATE_INPUT_READ_HEADER:
279 case TES_OPCODE_ADD_INDIRECT_URB_OFFSET:
280 case VEC4_OPCODE_URB_READ:
281 case SHADER_OPCODE_MOV_INDIRECT:
282 return false;
283 default:
284 /* The MATH instruction on Gen6 only executes in align1 mode, which does
285 * not support writemasking.
286 */
287 if (devinfo->gen == 6 && is_math())
288 return false;
289
290 if (is_tex())
291 return false;
292
293 return true;
294 }
295 }
296
297 bool
298 vec4_instruction::can_change_types() const
299 {
300 return dst.type == src[0].type &&
301 !src[0].abs && !src[0].negate && !saturate &&
302 (opcode == BRW_OPCODE_MOV ||
303 (opcode == BRW_OPCODE_SEL &&
304 dst.type == src[1].type &&
305 predicate != BRW_PREDICATE_NONE &&
306 !src[1].abs && !src[1].negate));
307 }
308
309 /**
310 * Returns how many MRFs an opcode will write over.
311 *
312 * Note that this is not the 0 or 1 implied writes in an actual gen
313 * instruction -- the generate_* functions generate additional MOVs
314 * for setup.
315 */
316 int
317 vec4_visitor::implied_mrf_writes(vec4_instruction *inst)
318 {
319 if (inst->mlen == 0 || inst->is_send_from_grf())
320 return 0;
321
322 switch (inst->opcode) {
323 case SHADER_OPCODE_RCP:
324 case SHADER_OPCODE_RSQ:
325 case SHADER_OPCODE_SQRT:
326 case SHADER_OPCODE_EXP2:
327 case SHADER_OPCODE_LOG2:
328 case SHADER_OPCODE_SIN:
329 case SHADER_OPCODE_COS:
330 return 1;
331 case SHADER_OPCODE_INT_QUOTIENT:
332 case SHADER_OPCODE_INT_REMAINDER:
333 case SHADER_OPCODE_POW:
334 case TCS_OPCODE_THREAD_END:
335 return 2;
336 case VS_OPCODE_URB_WRITE:
337 return 1;
338 case VS_OPCODE_PULL_CONSTANT_LOAD:
339 return 2;
340 case SHADER_OPCODE_GEN4_SCRATCH_READ:
341 return 2;
342 case SHADER_OPCODE_GEN4_SCRATCH_WRITE:
343 return 3;
344 case GS_OPCODE_URB_WRITE:
345 case GS_OPCODE_URB_WRITE_ALLOCATE:
346 case GS_OPCODE_THREAD_END:
347 return 0;
348 case GS_OPCODE_FF_SYNC:
349 return 1;
350 case TCS_OPCODE_URB_WRITE:
351 return 0;
352 case SHADER_OPCODE_SHADER_TIME_ADD:
353 return 0;
354 case SHADER_OPCODE_TEX:
355 case SHADER_OPCODE_TXL:
356 case SHADER_OPCODE_TXD:
357 case SHADER_OPCODE_TXF:
358 case SHADER_OPCODE_TXF_CMS:
359 case SHADER_OPCODE_TXF_CMS_W:
360 case SHADER_OPCODE_TXF_MCS:
361 case SHADER_OPCODE_TXS:
362 case SHADER_OPCODE_TG4:
363 case SHADER_OPCODE_TG4_OFFSET:
364 case SHADER_OPCODE_SAMPLEINFO:
365 case SHADER_OPCODE_GET_BUFFER_SIZE:
366 return inst->header_size;
367 default:
368 unreachable("not reached");
369 }
370 }
371
372 bool
373 src_reg::equals(const src_reg &r) const
374 {
375 return (this->backend_reg::equals(r) &&
376 !reladdr && !r.reladdr);
377 }
378
379 bool
380 src_reg::negative_equals(const src_reg &r) const
381 {
382 return this->backend_reg::negative_equals(r) &&
383 !reladdr && !r.reladdr;
384 }
385
386 bool
387 vec4_visitor::opt_vector_float()
388 {
389 bool progress = false;
390
391 foreach_block(block, cfg) {
392 int last_reg = -1, last_offset = -1;
393 enum brw_reg_file last_reg_file = BAD_FILE;
394
395 uint8_t imm[4] = { 0 };
396 int inst_count = 0;
397 vec4_instruction *imm_inst[4];
398 unsigned writemask = 0;
399 enum brw_reg_type dest_type = BRW_REGISTER_TYPE_F;
400
401 foreach_inst_in_block_safe(vec4_instruction, inst, block) {
402 int vf = -1;
403 enum brw_reg_type need_type;
404
405 /* Look for unconditional MOVs from an immediate with a partial
406 * writemask. Skip type-conversion MOVs other than integer 0,
407 * where the type doesn't matter. See if the immediate can be
408 * represented as a VF.
409 */
410 if (inst->opcode == BRW_OPCODE_MOV &&
411 inst->src[0].file == IMM &&
412 inst->predicate == BRW_PREDICATE_NONE &&
413 inst->dst.writemask != WRITEMASK_XYZW &&
414 type_sz(inst->src[0].type) < 8 &&
415 (inst->src[0].type == inst->dst.type || inst->src[0].d == 0)) {
416
417 vf = brw_float_to_vf(inst->src[0].d);
418 need_type = BRW_REGISTER_TYPE_D;
419
420 if (vf == -1) {
421 vf = brw_float_to_vf(inst->src[0].f);
422 need_type = BRW_REGISTER_TYPE_F;
423 }
424 } else {
425 last_reg = -1;
426 }
427
428 /* If this wasn't a MOV, or the destination register doesn't match,
429 * or we have to switch destination types, then this breaks our
430 * sequence. Combine anything we've accumulated so far.
431 */
432 if (last_reg != inst->dst.nr ||
433 last_offset != inst->dst.offset ||
434 last_reg_file != inst->dst.file ||
435 (vf > 0 && dest_type != need_type)) {
436
437 if (inst_count > 1) {
438 unsigned vf;
439 memcpy(&vf, imm, sizeof(vf));
440 vec4_instruction *mov = MOV(imm_inst[0]->dst, brw_imm_vf(vf));
441 mov->dst.type = dest_type;
442 mov->dst.writemask = writemask;
443 inst->insert_before(block, mov);
444
445 for (int i = 0; i < inst_count; i++) {
446 imm_inst[i]->remove(block);
447 }
448
449 progress = true;
450 }
451
452 inst_count = 0;
453 last_reg = -1;
454 writemask = 0;
455 dest_type = BRW_REGISTER_TYPE_F;
456
457 for (int i = 0; i < 4; i++) {
458 imm[i] = 0;
459 }
460 }
461
462 /* Record this instruction's value (if it was representable). */
463 if (vf != -1) {
464 if ((inst->dst.writemask & WRITEMASK_X) != 0)
465 imm[0] = vf;
466 if ((inst->dst.writemask & WRITEMASK_Y) != 0)
467 imm[1] = vf;
468 if ((inst->dst.writemask & WRITEMASK_Z) != 0)
469 imm[2] = vf;
470 if ((inst->dst.writemask & WRITEMASK_W) != 0)
471 imm[3] = vf;
472
473 writemask |= inst->dst.writemask;
474 imm_inst[inst_count++] = inst;
475
476 last_reg = inst->dst.nr;
477 last_offset = inst->dst.offset;
478 last_reg_file = inst->dst.file;
479 if (vf > 0)
480 dest_type = need_type;
481 }
482 }
483 }
484
485 if (progress)
486 invalidate_live_intervals();
487
488 return progress;
489 }
490
491 /* Replaces unused channels of a swizzle with channels that are used.
492 *
493 * For instance, this pass transforms
494 *
495 * mov vgrf4.yz, vgrf5.wxzy
496 *
497 * into
498 *
499 * mov vgrf4.yz, vgrf5.xxzx
500 *
501 * This eliminates false uses of some channels, letting dead code elimination
502 * remove the instructions that wrote them.
503 */
504 bool
505 vec4_visitor::opt_reduce_swizzle()
506 {
507 bool progress = false;
508
509 foreach_block_and_inst_safe(block, vec4_instruction, inst, cfg) {
510 if (inst->dst.file == BAD_FILE ||
511 inst->dst.file == ARF ||
512 inst->dst.file == FIXED_GRF ||
513 inst->is_send_from_grf())
514 continue;
515
516 unsigned swizzle;
517
518 /* Determine which channels of the sources are read. */
519 switch (inst->opcode) {
520 case VEC4_OPCODE_PACK_BYTES:
521 case BRW_OPCODE_DP4:
522 case BRW_OPCODE_DPH: /* FINISHME: DPH reads only three channels of src0,
523 * but all four of src1.
524 */
525 swizzle = brw_swizzle_for_size(4);
526 break;
527 case BRW_OPCODE_DP3:
528 swizzle = brw_swizzle_for_size(3);
529 break;
530 case BRW_OPCODE_DP2:
531 swizzle = brw_swizzle_for_size(2);
532 break;
533
534 case VEC4_OPCODE_TO_DOUBLE:
535 case VEC4_OPCODE_DOUBLE_TO_F32:
536 case VEC4_OPCODE_DOUBLE_TO_D32:
537 case VEC4_OPCODE_DOUBLE_TO_U32:
538 case VEC4_OPCODE_PICK_LOW_32BIT:
539 case VEC4_OPCODE_PICK_HIGH_32BIT:
540 case VEC4_OPCODE_SET_LOW_32BIT:
541 case VEC4_OPCODE_SET_HIGH_32BIT:
542 swizzle = brw_swizzle_for_size(4);
543 break;
544
545 default:
546 swizzle = brw_swizzle_for_mask(inst->dst.writemask);
547 break;
548 }
549
550 /* Update sources' swizzles. */
551 for (int i = 0; i < 3; i++) {
552 if (inst->src[i].file != VGRF &&
553 inst->src[i].file != ATTR &&
554 inst->src[i].file != UNIFORM)
555 continue;
556
557 const unsigned new_swizzle =
558 brw_compose_swizzle(swizzle, inst->src[i].swizzle);
559 if (inst->src[i].swizzle != new_swizzle) {
560 inst->src[i].swizzle = new_swizzle;
561 progress = true;
562 }
563 }
564 }
565
566 if (progress)
567 invalidate_live_intervals();
568
569 return progress;
570 }
571
572 void
573 vec4_visitor::split_uniform_registers()
574 {
575 /* Prior to this, uniforms have been in an array sized according to
576 * the number of vector uniforms present, sparsely filled (so an
577 * aggregate results in reg indices being skipped over). Now we're
578 * going to cut those aggregates up so each .nr index is one
579 * vector. The goal is to make elimination of unused uniform
580 * components easier later.
581 */
582 foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
583 for (int i = 0 ; i < 3; i++) {
584 if (inst->src[i].file != UNIFORM)
585 continue;
586
587 assert(!inst->src[i].reladdr);
588
589 inst->src[i].nr += inst->src[i].offset / 16;
590 inst->src[i].offset %= 16;
591 }
592 }
593 }
594
595 /* This function returns the register number where we placed the uniform */
596 static int
597 set_push_constant_loc(const int nr_uniforms, int *new_uniform_count,
598 const int src, const int size, const int channel_size,
599 int *new_loc, int *new_chan,
600 int *new_chans_used)
601 {
602 int dst;
603 /* Find the lowest place we can slot this uniform in. */
604 for (dst = 0; dst < nr_uniforms; dst++) {
605 if (ALIGN(new_chans_used[dst], channel_size) + size <= 4)
606 break;
607 }
608
609 assert(dst < nr_uniforms);
610
611 new_loc[src] = dst;
612 new_chan[src] = ALIGN(new_chans_used[dst], channel_size);
613 new_chans_used[dst] = ALIGN(new_chans_used[dst], channel_size) + size;
614
615 *new_uniform_count = MAX2(*new_uniform_count, dst + 1);
616 return dst;
617 }
618
619 void
620 vec4_visitor::pack_uniform_registers()
621 {
622 uint8_t chans_used[this->uniforms];
623 int new_loc[this->uniforms];
624 int new_chan[this->uniforms];
625 bool is_aligned_to_dvec4[this->uniforms];
626 int new_chans_used[this->uniforms];
627 int channel_sizes[this->uniforms];
628
629 memset(chans_used, 0, sizeof(chans_used));
630 memset(new_loc, 0, sizeof(new_loc));
631 memset(new_chan, 0, sizeof(new_chan));
632 memset(new_chans_used, 0, sizeof(new_chans_used));
633 memset(is_aligned_to_dvec4, 0, sizeof(is_aligned_to_dvec4));
634 memset(channel_sizes, 0, sizeof(channel_sizes));
635
636 /* Find which uniform vectors are actually used by the program. We
637 * expect unused vector elements when we've moved array access out
638 * to pull constants, and from some GLSL code generators like wine.
639 */
640 foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
641 unsigned readmask;
642 switch (inst->opcode) {
643 case VEC4_OPCODE_PACK_BYTES:
644 case BRW_OPCODE_DP4:
645 case BRW_OPCODE_DPH:
646 readmask = 0xf;
647 break;
648 case BRW_OPCODE_DP3:
649 readmask = 0x7;
650 break;
651 case BRW_OPCODE_DP2:
652 readmask = 0x3;
653 break;
654 default:
655 readmask = inst->dst.writemask;
656 break;
657 }
658
659 for (int i = 0 ; i < 3; i++) {
660 if (inst->src[i].file != UNIFORM)
661 continue;
662
663 assert(type_sz(inst->src[i].type) % 4 == 0);
664 int channel_size = type_sz(inst->src[i].type) / 4;
665
666 int reg = inst->src[i].nr;
667 for (int c = 0; c < 4; c++) {
668 if (!(readmask & (1 << c)))
669 continue;
670
671 unsigned channel = BRW_GET_SWZ(inst->src[i].swizzle, c) + 1;
672 unsigned used = MAX2(chans_used[reg], channel * channel_size);
673 if (used <= 4) {
674 chans_used[reg] = used;
675 channel_sizes[reg] = MAX2(channel_sizes[reg], channel_size);
676 } else {
677 is_aligned_to_dvec4[reg] = true;
678 is_aligned_to_dvec4[reg + 1] = true;
679 chans_used[reg + 1] = used - 4;
680 channel_sizes[reg + 1] = MAX2(channel_sizes[reg + 1], channel_size);
681 }
682 }
683 }
684
685 if (inst->opcode == SHADER_OPCODE_MOV_INDIRECT &&
686 inst->src[0].file == UNIFORM) {
687 assert(inst->src[2].file == BRW_IMMEDIATE_VALUE);
688 assert(inst->src[0].subnr == 0);
689
690 unsigned bytes_read = inst->src[2].ud;
691 assert(bytes_read % 4 == 0);
692 unsigned vec4s_read = DIV_ROUND_UP(bytes_read, 16);
693
694 /* We just mark every register touched by a MOV_INDIRECT as being
695 * fully used. This ensures that it doesn't broken up piecewise by
696 * the next part of our packing algorithm.
697 */
698 int reg = inst->src[0].nr;
699 int channel_size = type_sz(inst->src[0].type) / 4;
700 for (unsigned i = 0; i < vec4s_read; i++) {
701 chans_used[reg + i] = 4;
702 channel_sizes[reg + i] = MAX2(channel_sizes[reg + i], channel_size);
703 }
704 }
705 }
706
707 int new_uniform_count = 0;
708
709 /* As the uniforms are going to be reordered, take the data from a temporary
710 * copy of the original param[].
711 */
712 uint32_t *param = ralloc_array(NULL, uint32_t, stage_prog_data->nr_params);
713 memcpy(param, stage_prog_data->param,
714 sizeof(uint32_t) * stage_prog_data->nr_params);
715
716 /* Now, figure out a packing of the live uniform vectors into our
717 * push constants. Start with dvec{3,4} because they are aligned to
718 * dvec4 size (2 vec4).
719 */
720 for (int src = 0; src < uniforms; src++) {
721 int size = chans_used[src];
722
723 if (size == 0 || !is_aligned_to_dvec4[src])
724 continue;
725
726 /* dvec3 are aligned to dvec4 size, apply the alignment of the size
727 * to 4 to avoid moving last component of a dvec3 to the available
728 * location at the end of a previous dvec3. These available locations
729 * could be filled by smaller variables in next loop.
730 */
731 size = ALIGN(size, 4);
732 int dst = set_push_constant_loc(uniforms, &new_uniform_count,
733 src, size, channel_sizes[src],
734 new_loc, new_chan,
735 new_chans_used);
736 /* Move the references to the data */
737 for (int j = 0; j < size; j++) {
738 stage_prog_data->param[dst * 4 + new_chan[src] + j] =
739 param[src * 4 + j];
740 }
741 }
742
743 /* Continue with the rest of data, which is aligned to vec4. */
744 for (int src = 0; src < uniforms; src++) {
745 int size = chans_used[src];
746
747 if (size == 0 || is_aligned_to_dvec4[src])
748 continue;
749
750 int dst = set_push_constant_loc(uniforms, &new_uniform_count,
751 src, size, channel_sizes[src],
752 new_loc, new_chan,
753 new_chans_used);
754 /* Move the references to the data */
755 for (int j = 0; j < size; j++) {
756 stage_prog_data->param[dst * 4 + new_chan[src] + j] =
757 param[src * 4 + j];
758 }
759 }
760
761 ralloc_free(param);
762 this->uniforms = new_uniform_count;
763
764 /* Now, update the instructions for our repacked uniforms. */
765 foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
766 for (int i = 0 ; i < 3; i++) {
767 int src = inst->src[i].nr;
768
769 if (inst->src[i].file != UNIFORM)
770 continue;
771
772 int chan = new_chan[src] / channel_sizes[src];
773 inst->src[i].nr = new_loc[src];
774 inst->src[i].swizzle += BRW_SWIZZLE4(chan, chan, chan, chan);
775 }
776 }
777 }
778
779 /**
780 * Does algebraic optimizations (0 * a = 0, 1 * a = a, a + 0 = a).
781 *
782 * While GLSL IR also performs this optimization, we end up with it in
783 * our instruction stream for a couple of reasons. One is that we
784 * sometimes generate silly instructions, for example in array access
785 * where we'll generate "ADD offset, index, base" even if base is 0.
786 * The other is that GLSL IR's constant propagation doesn't track the
787 * components of aggregates, so some VS patterns (initialize matrix to
788 * 0, accumulate in vertex blending factors) end up breaking down to
789 * instructions involving 0.
790 */
791 bool
792 vec4_visitor::opt_algebraic()
793 {
794 bool progress = false;
795
796 foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
797 switch (inst->opcode) {
798 case BRW_OPCODE_MOV:
799 if (inst->src[0].file != IMM)
800 break;
801
802 if (inst->saturate) {
803 /* Full mixed-type saturates don't happen. However, we can end up
804 * with things like:
805 *
806 * mov.sat(8) g21<1>DF -1F
807 *
808 * Other mixed-size-but-same-base-type cases may also be possible.
809 */
810 if (inst->dst.type != inst->src[0].type &&
811 inst->dst.type != BRW_REGISTER_TYPE_DF &&
812 inst->src[0].type != BRW_REGISTER_TYPE_F)
813 assert(!"unimplemented: saturate mixed types");
814
815 if (brw_saturate_immediate(inst->src[0].type,
816 &inst->src[0].as_brw_reg())) {
817 inst->saturate = false;
818 progress = true;
819 }
820 }
821 break;
822
823 case BRW_OPCODE_OR:
824 if (inst->src[1].is_zero()) {
825 inst->opcode = BRW_OPCODE_MOV;
826 inst->src[1] = src_reg();
827 progress = true;
828 }
829 break;
830
831 case VEC4_OPCODE_UNPACK_UNIFORM:
832 if (inst->src[0].file != UNIFORM) {
833 inst->opcode = BRW_OPCODE_MOV;
834 progress = true;
835 }
836 break;
837
838 case BRW_OPCODE_ADD:
839 if (inst->src[1].is_zero()) {
840 inst->opcode = BRW_OPCODE_MOV;
841 inst->src[1] = src_reg();
842 progress = true;
843 }
844 break;
845
846 case BRW_OPCODE_MUL:
847 if (inst->src[1].is_zero()) {
848 inst->opcode = BRW_OPCODE_MOV;
849 switch (inst->src[0].type) {
850 case BRW_REGISTER_TYPE_F:
851 inst->src[0] = brw_imm_f(0.0f);
852 break;
853 case BRW_REGISTER_TYPE_D:
854 inst->src[0] = brw_imm_d(0);
855 break;
856 case BRW_REGISTER_TYPE_UD:
857 inst->src[0] = brw_imm_ud(0u);
858 break;
859 default:
860 unreachable("not reached");
861 }
862 inst->src[1] = src_reg();
863 progress = true;
864 } else if (inst->src[1].is_one()) {
865 inst->opcode = BRW_OPCODE_MOV;
866 inst->src[1] = src_reg();
867 progress = true;
868 } else if (inst->src[1].is_negative_one()) {
869 inst->opcode = BRW_OPCODE_MOV;
870 inst->src[0].negate = !inst->src[0].negate;
871 inst->src[1] = src_reg();
872 progress = true;
873 }
874 break;
875 case BRW_OPCODE_CMP:
876 if (inst->conditional_mod == BRW_CONDITIONAL_GE &&
877 inst->src[0].abs &&
878 inst->src[0].negate &&
879 inst->src[1].is_zero()) {
880 inst->src[0].abs = false;
881 inst->src[0].negate = false;
882 inst->conditional_mod = BRW_CONDITIONAL_Z;
883 progress = true;
884 break;
885 }
886 break;
887 case SHADER_OPCODE_BROADCAST:
888 if (is_uniform(inst->src[0]) ||
889 inst->src[1].is_zero()) {
890 inst->opcode = BRW_OPCODE_MOV;
891 inst->src[1] = src_reg();
892 inst->force_writemask_all = true;
893 progress = true;
894 }
895 break;
896
897 default:
898 break;
899 }
900 }
901
902 if (progress)
903 invalidate_live_intervals();
904
905 return progress;
906 }
907
908 /**
909 * Only a limited number of hardware registers may be used for push
910 * constants, so this turns access to the overflowed constants into
911 * pull constants.
912 */
913 void
914 vec4_visitor::move_push_constants_to_pull_constants()
915 {
916 int pull_constant_loc[this->uniforms];
917
918 /* Only allow 32 registers (256 uniform components) as push constants,
919 * which is the limit on gen6.
920 *
921 * If changing this value, note the limitation about total_regs in
922 * brw_curbe.c.
923 */
924 int max_uniform_components = 32 * 8;
925 if (this->uniforms * 4 <= max_uniform_components)
926 return;
927
928 /* Make some sort of choice as to which uniforms get sent to pull
929 * constants. We could potentially do something clever here like
930 * look for the most infrequently used uniform vec4s, but leave
931 * that for later.
932 */
933 for (int i = 0; i < this->uniforms * 4; i += 4) {
934 pull_constant_loc[i / 4] = -1;
935
936 if (i >= max_uniform_components) {
937 uint32_t *values = &stage_prog_data->param[i];
938
939 /* Try to find an existing copy of this uniform in the pull
940 * constants if it was part of an array access already.
941 */
942 for (unsigned int j = 0; j < stage_prog_data->nr_pull_params; j += 4) {
943 int matches;
944
945 for (matches = 0; matches < 4; matches++) {
946 if (stage_prog_data->pull_param[j + matches] != values[matches])
947 break;
948 }
949
950 if (matches == 4) {
951 pull_constant_loc[i / 4] = j / 4;
952 break;
953 }
954 }
955
956 if (pull_constant_loc[i / 4] == -1) {
957 assert(stage_prog_data->nr_pull_params % 4 == 0);
958 pull_constant_loc[i / 4] = stage_prog_data->nr_pull_params / 4;
959
960 for (int j = 0; j < 4; j++) {
961 stage_prog_data->pull_param[stage_prog_data->nr_pull_params++] =
962 values[j];
963 }
964 }
965 }
966 }
967
968 /* Now actually rewrite usage of the things we've moved to pull
969 * constants.
970 */
971 foreach_block_and_inst_safe(block, vec4_instruction, inst, cfg) {
972 for (int i = 0 ; i < 3; i++) {
973 if (inst->src[i].file != UNIFORM ||
974 pull_constant_loc[inst->src[i].nr] == -1)
975 continue;
976
977 int uniform = inst->src[i].nr;
978
979 const glsl_type *temp_type = type_sz(inst->src[i].type) == 8 ?
980 glsl_type::dvec4_type : glsl_type::vec4_type;
981 dst_reg temp = dst_reg(this, temp_type);
982
983 emit_pull_constant_load(block, inst, temp, inst->src[i],
984 pull_constant_loc[uniform], src_reg());
985
986 inst->src[i].file = temp.file;
987 inst->src[i].nr = temp.nr;
988 inst->src[i].offset %= 16;
989 inst->src[i].reladdr = NULL;
990 }
991 }
992
993 /* Repack push constants to remove the now-unused ones. */
994 pack_uniform_registers();
995 }
996
997 /* Conditions for which we want to avoid setting the dependency control bits */
998 bool
999 vec4_visitor::is_dep_ctrl_unsafe(const vec4_instruction *inst)
1000 {
1001 #define IS_DWORD(reg) \
1002 (reg.type == BRW_REGISTER_TYPE_UD || \
1003 reg.type == BRW_REGISTER_TYPE_D)
1004
1005 #define IS_64BIT(reg) (reg.file != BAD_FILE && type_sz(reg.type) == 8)
1006
1007 /* From the Cherryview and Broadwell PRMs:
1008 *
1009 * "When source or destination datatype is 64b or operation is integer DWord
1010 * multiply, DepCtrl must not be used."
1011 *
1012 * SKL PRMs don't include this restriction, however, gen7 seems to be
1013 * affected, at least by the 64b restriction, since DepCtrl with double
1014 * precision instructions seems to produce GPU hangs in some cases.
1015 */
1016 if (devinfo->gen == 8 || gen_device_info_is_9lp(devinfo)) {
1017 if (inst->opcode == BRW_OPCODE_MUL &&
1018 IS_DWORD(inst->src[0]) &&
1019 IS_DWORD(inst->src[1]))
1020 return true;
1021 }
1022
1023 if (devinfo->gen >= 7 && devinfo->gen <= 8) {
1024 if (IS_64BIT(inst->dst) || IS_64BIT(inst->src[0]) ||
1025 IS_64BIT(inst->src[1]) || IS_64BIT(inst->src[2]))
1026 return true;
1027 }
1028
1029 #undef IS_64BIT
1030 #undef IS_DWORD
1031
1032 if (devinfo->gen >= 8) {
1033 if (inst->opcode == BRW_OPCODE_F32TO16)
1034 return true;
1035 }
1036
1037 /*
1038 * mlen:
1039 * In the presence of send messages, totally interrupt dependency
1040 * control. They're long enough that the chance of dependency
1041 * control around them just doesn't matter.
1042 *
1043 * predicate:
1044 * From the Ivy Bridge PRM, volume 4 part 3.7, page 80:
1045 * When a sequence of NoDDChk and NoDDClr are used, the last instruction that
1046 * completes the scoreboard clear must have a non-zero execution mask. This
1047 * means, if any kind of predication can change the execution mask or channel
1048 * enable of the last instruction, the optimization must be avoided. This is
1049 * to avoid instructions being shot down the pipeline when no writes are
1050 * required.
1051 *
1052 * math:
1053 * Dependency control does not work well over math instructions.
1054 * NB: Discovered empirically
1055 */
1056 return (inst->mlen || inst->predicate || inst->is_math());
1057 }
1058
1059 /**
1060 * Sets the dependency control fields on instructions after register
1061 * allocation and before the generator is run.
1062 *
1063 * When you have a sequence of instructions like:
1064 *
1065 * DP4 temp.x vertex uniform[0]
1066 * DP4 temp.y vertex uniform[0]
1067 * DP4 temp.z vertex uniform[0]
1068 * DP4 temp.w vertex uniform[0]
1069 *
1070 * The hardware doesn't know that it can actually run the later instructions
1071 * while the previous ones are in flight, producing stalls. However, we have
1072 * manual fields we can set in the instructions that let it do so.
1073 */
1074 void
1075 vec4_visitor::opt_set_dependency_control()
1076 {
1077 vec4_instruction *last_grf_write[BRW_MAX_GRF];
1078 uint8_t grf_channels_written[BRW_MAX_GRF];
1079 vec4_instruction *last_mrf_write[BRW_MAX_GRF];
1080 uint8_t mrf_channels_written[BRW_MAX_GRF];
1081
1082 assert(prog_data->total_grf ||
1083 !"Must be called after register allocation");
1084
1085 foreach_block (block, cfg) {
1086 memset(last_grf_write, 0, sizeof(last_grf_write));
1087 memset(last_mrf_write, 0, sizeof(last_mrf_write));
1088
1089 foreach_inst_in_block (vec4_instruction, inst, block) {
1090 /* If we read from a register that we were doing dependency control
1091 * on, don't do dependency control across the read.
1092 */
1093 for (int i = 0; i < 3; i++) {
1094 int reg = inst->src[i].nr + inst->src[i].offset / REG_SIZE;
1095 if (inst->src[i].file == VGRF) {
1096 last_grf_write[reg] = NULL;
1097 } else if (inst->src[i].file == FIXED_GRF) {
1098 memset(last_grf_write, 0, sizeof(last_grf_write));
1099 break;
1100 }
1101 assert(inst->src[i].file != MRF);
1102 }
1103
1104 if (is_dep_ctrl_unsafe(inst)) {
1105 memset(last_grf_write, 0, sizeof(last_grf_write));
1106 memset(last_mrf_write, 0, sizeof(last_mrf_write));
1107 continue;
1108 }
1109
1110 /* Now, see if we can do dependency control for this instruction
1111 * against a previous one writing to its destination.
1112 */
1113 int reg = inst->dst.nr + inst->dst.offset / REG_SIZE;
1114 if (inst->dst.file == VGRF || inst->dst.file == FIXED_GRF) {
1115 if (last_grf_write[reg] &&
1116 last_grf_write[reg]->dst.offset == inst->dst.offset &&
1117 !(inst->dst.writemask & grf_channels_written[reg])) {
1118 last_grf_write[reg]->no_dd_clear = true;
1119 inst->no_dd_check = true;
1120 } else {
1121 grf_channels_written[reg] = 0;
1122 }
1123
1124 last_grf_write[reg] = inst;
1125 grf_channels_written[reg] |= inst->dst.writemask;
1126 } else if (inst->dst.file == MRF) {
1127 if (last_mrf_write[reg] &&
1128 last_mrf_write[reg]->dst.offset == inst->dst.offset &&
1129 !(inst->dst.writemask & mrf_channels_written[reg])) {
1130 last_mrf_write[reg]->no_dd_clear = true;
1131 inst->no_dd_check = true;
1132 } else {
1133 mrf_channels_written[reg] = 0;
1134 }
1135
1136 last_mrf_write[reg] = inst;
1137 mrf_channels_written[reg] |= inst->dst.writemask;
1138 }
1139 }
1140 }
1141 }
1142
1143 bool
1144 vec4_instruction::can_reswizzle(const struct gen_device_info *devinfo,
1145 int dst_writemask,
1146 int swizzle,
1147 int swizzle_mask)
1148 {
1149 /* Gen6 MATH instructions can not execute in align16 mode, so swizzles
1150 * are not allowed.
1151 */
1152 if (devinfo->gen == 6 && is_math() && swizzle != BRW_SWIZZLE_XYZW)
1153 return false;
1154
1155 /* We can't swizzle implicit accumulator access. We'd have to
1156 * reswizzle the producer of the accumulator value in addition
1157 * to the consumer (i.e. both MUL and MACH). Just skip this.
1158 */
1159 if (reads_accumulator_implicitly())
1160 return false;
1161
1162 if (!can_do_writemask(devinfo) && dst_writemask != WRITEMASK_XYZW)
1163 return false;
1164
1165 /* If this instruction sets anything not referenced by swizzle, then we'd
1166 * totally break it when we reswizzle.
1167 */
1168 if (dst.writemask & ~swizzle_mask)
1169 return false;
1170
1171 if (mlen > 0)
1172 return false;
1173
1174 for (int i = 0; i < 3; i++) {
1175 if (src[i].is_accumulator())
1176 return false;
1177 }
1178
1179 return true;
1180 }
1181
1182 /**
1183 * For any channels in the swizzle's source that were populated by this
1184 * instruction, rewrite the instruction to put the appropriate result directly
1185 * in those channels.
1186 *
1187 * e.g. for swizzle=yywx, MUL a.xy b c -> MUL a.yy_x b.yy z.yy_x
1188 */
1189 void
1190 vec4_instruction::reswizzle(int dst_writemask, int swizzle)
1191 {
1192 /* Destination write mask doesn't correspond to source swizzle for the dot
1193 * product and pack_bytes instructions.
1194 */
1195 if (opcode != BRW_OPCODE_DP4 && opcode != BRW_OPCODE_DPH &&
1196 opcode != BRW_OPCODE_DP3 && opcode != BRW_OPCODE_DP2 &&
1197 opcode != VEC4_OPCODE_PACK_BYTES) {
1198 for (int i = 0; i < 3; i++) {
1199 if (src[i].file == BAD_FILE || src[i].file == IMM)
1200 continue;
1201
1202 src[i].swizzle = brw_compose_swizzle(swizzle, src[i].swizzle);
1203 }
1204 }
1205
1206 /* Apply the specified swizzle and writemask to the original mask of
1207 * written components.
1208 */
1209 dst.writemask = dst_writemask &
1210 brw_apply_swizzle_to_mask(swizzle, dst.writemask);
1211 }
1212
1213 /*
1214 * Tries to reduce extra MOV instructions by taking temporary GRFs that get
1215 * just written and then MOVed into another reg and making the original write
1216 * of the GRF write directly to the final destination instead.
1217 */
1218 bool
1219 vec4_visitor::opt_register_coalesce()
1220 {
1221 bool progress = false;
1222 int next_ip = 0;
1223
1224 calculate_live_intervals();
1225
1226 foreach_block_and_inst_safe (block, vec4_instruction, inst, cfg) {
1227 int ip = next_ip;
1228 next_ip++;
1229
1230 if (inst->opcode != BRW_OPCODE_MOV ||
1231 (inst->dst.file != VGRF && inst->dst.file != MRF) ||
1232 inst->predicate ||
1233 inst->src[0].file != VGRF ||
1234 inst->dst.type != inst->src[0].type ||
1235 inst->src[0].abs || inst->src[0].negate || inst->src[0].reladdr)
1236 continue;
1237
1238 /* Remove no-op MOVs */
1239 if (inst->dst.file == inst->src[0].file &&
1240 inst->dst.nr == inst->src[0].nr &&
1241 inst->dst.offset == inst->src[0].offset) {
1242 bool is_nop_mov = true;
1243
1244 for (unsigned c = 0; c < 4; c++) {
1245 if ((inst->dst.writemask & (1 << c)) == 0)
1246 continue;
1247
1248 if (BRW_GET_SWZ(inst->src[0].swizzle, c) != c) {
1249 is_nop_mov = false;
1250 break;
1251 }
1252 }
1253
1254 if (is_nop_mov) {
1255 inst->remove(block);
1256 progress = true;
1257 continue;
1258 }
1259 }
1260
1261 bool to_mrf = (inst->dst.file == MRF);
1262
1263 /* Can't coalesce this GRF if someone else was going to
1264 * read it later.
1265 */
1266 if (var_range_end(var_from_reg(alloc, dst_reg(inst->src[0])), 8) > ip)
1267 continue;
1268
1269 /* We need to check interference with the final destination between this
1270 * instruction and the earliest instruction involved in writing the GRF
1271 * we're eliminating. To do that, keep track of which of our source
1272 * channels we've seen initialized.
1273 */
1274 const unsigned chans_needed =
1275 brw_apply_inv_swizzle_to_mask(inst->src[0].swizzle,
1276 inst->dst.writemask);
1277 unsigned chans_remaining = chans_needed;
1278
1279 /* Now walk up the instruction stream trying to see if we can rewrite
1280 * everything writing to the temporary to write into the destination
1281 * instead.
1282 */
1283 vec4_instruction *_scan_inst = (vec4_instruction *)inst->prev;
1284 foreach_inst_in_block_reverse_starting_from(vec4_instruction, scan_inst,
1285 inst) {
1286 _scan_inst = scan_inst;
1287
1288 if (regions_overlap(inst->src[0], inst->size_read(0),
1289 scan_inst->dst, scan_inst->size_written)) {
1290 /* Found something writing to the reg we want to coalesce away. */
1291 if (to_mrf) {
1292 /* SEND instructions can't have MRF as a destination. */
1293 if (scan_inst->mlen)
1294 break;
1295
1296 if (devinfo->gen == 6) {
1297 /* gen6 math instructions must have the destination be
1298 * VGRF, so no compute-to-MRF for them.
1299 */
1300 if (scan_inst->is_math()) {
1301 break;
1302 }
1303 }
1304 }
1305
1306 /* VS_OPCODE_UNPACK_FLAGS_SIMD4X2 generates a bunch of mov(1)
1307 * instructions, and this optimization pass is not capable of
1308 * handling that. Bail on these instructions and hope that some
1309 * later optimization pass can do the right thing after they are
1310 * expanded.
1311 */
1312 if (scan_inst->opcode == VS_OPCODE_UNPACK_FLAGS_SIMD4X2)
1313 break;
1314
1315 /* This doesn't handle saturation on the instruction we
1316 * want to coalesce away if the register types do not match.
1317 * But if scan_inst is a non type-converting 'mov', we can fix
1318 * the types later.
1319 */
1320 if (inst->saturate &&
1321 inst->dst.type != scan_inst->dst.type &&
1322 !(scan_inst->opcode == BRW_OPCODE_MOV &&
1323 scan_inst->dst.type == scan_inst->src[0].type))
1324 break;
1325
1326 /* Only allow coalescing between registers of the same type size.
1327 * Otherwise we would need to make the pass aware of the fact that
1328 * channel sizes are different for single and double precision.
1329 */
1330 if (type_sz(inst->src[0].type) != type_sz(scan_inst->src[0].type))
1331 break;
1332
1333 /* Check that scan_inst writes the same amount of data as the
1334 * instruction, otherwise coalescing would lead to writing a
1335 * different (larger or smaller) region of the destination
1336 */
1337 if (scan_inst->size_written != inst->size_written)
1338 break;
1339
1340 /* If we can't handle the swizzle, bail. */
1341 if (!scan_inst->can_reswizzle(devinfo, inst->dst.writemask,
1342 inst->src[0].swizzle,
1343 chans_needed)) {
1344 break;
1345 }
1346
1347 /* This only handles coalescing writes of 8 channels (1 register
1348 * for single-precision and 2 registers for double-precision)
1349 * starting at the source offset of the copy instruction.
1350 */
1351 if (DIV_ROUND_UP(scan_inst->size_written,
1352 type_sz(scan_inst->dst.type)) > 8 ||
1353 scan_inst->dst.offset != inst->src[0].offset)
1354 break;
1355
1356 /* Mark which channels we found unconditional writes for. */
1357 if (!scan_inst->predicate)
1358 chans_remaining &= ~scan_inst->dst.writemask;
1359
1360 if (chans_remaining == 0)
1361 break;
1362 }
1363
1364 /* You can't read from an MRF, so if someone else reads our MRF's
1365 * source GRF that we wanted to rewrite, that stops us. If it's a
1366 * GRF we're trying to coalesce to, we don't actually handle
1367 * rewriting sources so bail in that case as well.
1368 */
1369 bool interfered = false;
1370 for (int i = 0; i < 3; i++) {
1371 if (regions_overlap(inst->src[0], inst->size_read(0),
1372 scan_inst->src[i], scan_inst->size_read(i)))
1373 interfered = true;
1374 }
1375 if (interfered)
1376 break;
1377
1378 /* If somebody else writes the same channels of our destination here,
1379 * we can't coalesce before that.
1380 */
1381 if (regions_overlap(inst->dst, inst->size_written,
1382 scan_inst->dst, scan_inst->size_written) &&
1383 (inst->dst.writemask & scan_inst->dst.writemask) != 0) {
1384 break;
1385 }
1386
1387 /* Check for reads of the register we're trying to coalesce into. We
1388 * can't go rewriting instructions above that to put some other value
1389 * in the register instead.
1390 */
1391 if (to_mrf && scan_inst->mlen > 0) {
1392 if (inst->dst.nr >= scan_inst->base_mrf &&
1393 inst->dst.nr < scan_inst->base_mrf + scan_inst->mlen) {
1394 break;
1395 }
1396 } else {
1397 for (int i = 0; i < 3; i++) {
1398 if (regions_overlap(inst->dst, inst->size_written,
1399 scan_inst->src[i], scan_inst->size_read(i)))
1400 interfered = true;
1401 }
1402 if (interfered)
1403 break;
1404 }
1405 }
1406
1407 if (chans_remaining == 0) {
1408 /* If we've made it here, we have an MOV we want to coalesce out, and
1409 * a scan_inst pointing to the earliest instruction involved in
1410 * computing the value. Now go rewrite the instruction stream
1411 * between the two.
1412 */
1413 vec4_instruction *scan_inst = _scan_inst;
1414 while (scan_inst != inst) {
1415 if (scan_inst->dst.file == VGRF &&
1416 scan_inst->dst.nr == inst->src[0].nr &&
1417 scan_inst->dst.offset == inst->src[0].offset) {
1418 scan_inst->reswizzle(inst->dst.writemask,
1419 inst->src[0].swizzle);
1420 scan_inst->dst.file = inst->dst.file;
1421 scan_inst->dst.nr = inst->dst.nr;
1422 scan_inst->dst.offset = inst->dst.offset;
1423 if (inst->saturate &&
1424 inst->dst.type != scan_inst->dst.type) {
1425 /* If we have reached this point, scan_inst is a non
1426 * type-converting 'mov' and we can modify its register types
1427 * to match the ones in inst. Otherwise, we could have an
1428 * incorrect saturation result.
1429 */
1430 scan_inst->dst.type = inst->dst.type;
1431 scan_inst->src[0].type = inst->src[0].type;
1432 }
1433 scan_inst->saturate |= inst->saturate;
1434 }
1435 scan_inst = (vec4_instruction *)scan_inst->next;
1436 }
1437 inst->remove(block);
1438 progress = true;
1439 }
1440 }
1441
1442 if (progress)
1443 invalidate_live_intervals();
1444
1445 return progress;
1446 }
1447
1448 /**
1449 * Eliminate FIND_LIVE_CHANNEL instructions occurring outside any control
1450 * flow. We could probably do better here with some form of divergence
1451 * analysis.
1452 */
1453 bool
1454 vec4_visitor::eliminate_find_live_channel()
1455 {
1456 bool progress = false;
1457 unsigned depth = 0;
1458
1459 if (!brw_stage_has_packed_dispatch(devinfo, stage, stage_prog_data)) {
1460 /* The optimization below assumes that channel zero is live on thread
1461 * dispatch, which may not be the case if the fixed function dispatches
1462 * threads sparsely.
1463 */
1464 return false;
1465 }
1466
1467 foreach_block_and_inst_safe(block, vec4_instruction, inst, cfg) {
1468 switch (inst->opcode) {
1469 case BRW_OPCODE_IF:
1470 case BRW_OPCODE_DO:
1471 depth++;
1472 break;
1473
1474 case BRW_OPCODE_ENDIF:
1475 case BRW_OPCODE_WHILE:
1476 depth--;
1477 break;
1478
1479 case SHADER_OPCODE_FIND_LIVE_CHANNEL:
1480 if (depth == 0) {
1481 inst->opcode = BRW_OPCODE_MOV;
1482 inst->src[0] = brw_imm_d(0);
1483 inst->force_writemask_all = true;
1484 progress = true;
1485 }
1486 break;
1487
1488 default:
1489 break;
1490 }
1491 }
1492
1493 return progress;
1494 }
1495
1496 /**
1497 * Splits virtual GRFs requesting more than one contiguous physical register.
1498 *
1499 * We initially create large virtual GRFs for temporary structures, arrays,
1500 * and matrices, so that the visitor functions can add offsets to work their
1501 * way down to the actual member being accessed. But when it comes to
1502 * optimization, we'd like to treat each register as individual storage if
1503 * possible.
1504 *
1505 * So far, the only thing that might prevent splitting is a send message from
1506 * a GRF on IVB.
1507 */
1508 void
1509 vec4_visitor::split_virtual_grfs()
1510 {
1511 int num_vars = this->alloc.count;
1512 int new_virtual_grf[num_vars];
1513 bool split_grf[num_vars];
1514
1515 memset(new_virtual_grf, 0, sizeof(new_virtual_grf));
1516
1517 /* Try to split anything > 0 sized. */
1518 for (int i = 0; i < num_vars; i++) {
1519 split_grf[i] = this->alloc.sizes[i] != 1;
1520 }
1521
1522 /* Check that the instructions are compatible with the registers we're trying
1523 * to split.
1524 */
1525 foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
1526 if (inst->dst.file == VGRF && regs_written(inst) > 1)
1527 split_grf[inst->dst.nr] = false;
1528
1529 for (int i = 0; i < 3; i++) {
1530 if (inst->src[i].file == VGRF && regs_read(inst, i) > 1)
1531 split_grf[inst->src[i].nr] = false;
1532 }
1533 }
1534
1535 /* Allocate new space for split regs. Note that the virtual
1536 * numbers will be contiguous.
1537 */
1538 for (int i = 0; i < num_vars; i++) {
1539 if (!split_grf[i])
1540 continue;
1541
1542 new_virtual_grf[i] = alloc.allocate(1);
1543 for (unsigned j = 2; j < this->alloc.sizes[i]; j++) {
1544 unsigned reg = alloc.allocate(1);
1545 assert(reg == new_virtual_grf[i] + j - 1);
1546 (void) reg;
1547 }
1548 this->alloc.sizes[i] = 1;
1549 }
1550
1551 foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
1552 if (inst->dst.file == VGRF && split_grf[inst->dst.nr] &&
1553 inst->dst.offset / REG_SIZE != 0) {
1554 inst->dst.nr = (new_virtual_grf[inst->dst.nr] +
1555 inst->dst.offset / REG_SIZE - 1);
1556 inst->dst.offset %= REG_SIZE;
1557 }
1558 for (int i = 0; i < 3; i++) {
1559 if (inst->src[i].file == VGRF && split_grf[inst->src[i].nr] &&
1560 inst->src[i].offset / REG_SIZE != 0) {
1561 inst->src[i].nr = (new_virtual_grf[inst->src[i].nr] +
1562 inst->src[i].offset / REG_SIZE - 1);
1563 inst->src[i].offset %= REG_SIZE;
1564 }
1565 }
1566 }
1567 invalidate_live_intervals();
1568 }
1569
1570 void
1571 vec4_visitor::dump_instruction(backend_instruction *be_inst)
1572 {
1573 dump_instruction(be_inst, stderr);
1574 }
1575
1576 void
1577 vec4_visitor::dump_instruction(backend_instruction *be_inst, FILE *file)
1578 {
1579 vec4_instruction *inst = (vec4_instruction *)be_inst;
1580
1581 if (inst->predicate) {
1582 fprintf(file, "(%cf%d.%d%s) ",
1583 inst->predicate_inverse ? '-' : '+',
1584 inst->flag_subreg / 2,
1585 inst->flag_subreg % 2,
1586 pred_ctrl_align16[inst->predicate]);
1587 }
1588
1589 fprintf(file, "%s(%d)", brw_instruction_name(devinfo, inst->opcode),
1590 inst->exec_size);
1591 if (inst->saturate)
1592 fprintf(file, ".sat");
1593 if (inst->conditional_mod) {
1594 fprintf(file, "%s", conditional_modifier[inst->conditional_mod]);
1595 if (!inst->predicate &&
1596 (devinfo->gen < 5 || (inst->opcode != BRW_OPCODE_SEL &&
1597 inst->opcode != BRW_OPCODE_CSEL &&
1598 inst->opcode != BRW_OPCODE_IF &&
1599 inst->opcode != BRW_OPCODE_WHILE))) {
1600 fprintf(file, ".f%d.%d", inst->flag_subreg / 2, inst->flag_subreg % 2);
1601 }
1602 }
1603 fprintf(file, " ");
1604
1605 switch (inst->dst.file) {
1606 case VGRF:
1607 fprintf(file, "vgrf%d", inst->dst.nr);
1608 break;
1609 case FIXED_GRF:
1610 fprintf(file, "g%d", inst->dst.nr);
1611 break;
1612 case MRF:
1613 fprintf(file, "m%d", inst->dst.nr);
1614 break;
1615 case ARF:
1616 switch (inst->dst.nr) {
1617 case BRW_ARF_NULL:
1618 fprintf(file, "null");
1619 break;
1620 case BRW_ARF_ADDRESS:
1621 fprintf(file, "a0.%d", inst->dst.subnr);
1622 break;
1623 case BRW_ARF_ACCUMULATOR:
1624 fprintf(file, "acc%d", inst->dst.subnr);
1625 break;
1626 case BRW_ARF_FLAG:
1627 fprintf(file, "f%d.%d", inst->dst.nr & 0xf, inst->dst.subnr);
1628 break;
1629 default:
1630 fprintf(file, "arf%d.%d", inst->dst.nr & 0xf, inst->dst.subnr);
1631 break;
1632 }
1633 break;
1634 case BAD_FILE:
1635 fprintf(file, "(null)");
1636 break;
1637 case IMM:
1638 case ATTR:
1639 case UNIFORM:
1640 unreachable("not reached");
1641 }
1642 if (inst->dst.offset ||
1643 (inst->dst.file == VGRF &&
1644 alloc.sizes[inst->dst.nr] * REG_SIZE != inst->size_written)) {
1645 const unsigned reg_size = (inst->dst.file == UNIFORM ? 16 : REG_SIZE);
1646 fprintf(file, "+%d.%d", inst->dst.offset / reg_size,
1647 inst->dst.offset % reg_size);
1648 }
1649 if (inst->dst.writemask != WRITEMASK_XYZW) {
1650 fprintf(file, ".");
1651 if (inst->dst.writemask & 1)
1652 fprintf(file, "x");
1653 if (inst->dst.writemask & 2)
1654 fprintf(file, "y");
1655 if (inst->dst.writemask & 4)
1656 fprintf(file, "z");
1657 if (inst->dst.writemask & 8)
1658 fprintf(file, "w");
1659 }
1660 fprintf(file, ":%s", brw_reg_type_to_letters(inst->dst.type));
1661
1662 if (inst->src[0].file != BAD_FILE)
1663 fprintf(file, ", ");
1664
1665 for (int i = 0; i < 3 && inst->src[i].file != BAD_FILE; i++) {
1666 if (inst->src[i].negate)
1667 fprintf(file, "-");
1668 if (inst->src[i].abs)
1669 fprintf(file, "|");
1670 switch (inst->src[i].file) {
1671 case VGRF:
1672 fprintf(file, "vgrf%d", inst->src[i].nr);
1673 break;
1674 case FIXED_GRF:
1675 fprintf(file, "g%d.%d", inst->src[i].nr, inst->src[i].subnr);
1676 break;
1677 case ATTR:
1678 fprintf(file, "attr%d", inst->src[i].nr);
1679 break;
1680 case UNIFORM:
1681 fprintf(file, "u%d", inst->src[i].nr);
1682 break;
1683 case IMM:
1684 switch (inst->src[i].type) {
1685 case BRW_REGISTER_TYPE_F:
1686 fprintf(file, "%fF", inst->src[i].f);
1687 break;
1688 case BRW_REGISTER_TYPE_DF:
1689 fprintf(file, "%fDF", inst->src[i].df);
1690 break;
1691 case BRW_REGISTER_TYPE_D:
1692 fprintf(file, "%dD", inst->src[i].d);
1693 break;
1694 case BRW_REGISTER_TYPE_UD:
1695 fprintf(file, "%uU", inst->src[i].ud);
1696 break;
1697 case BRW_REGISTER_TYPE_VF:
1698 fprintf(file, "[%-gF, %-gF, %-gF, %-gF]",
1699 brw_vf_to_float((inst->src[i].ud >> 0) & 0xff),
1700 brw_vf_to_float((inst->src[i].ud >> 8) & 0xff),
1701 brw_vf_to_float((inst->src[i].ud >> 16) & 0xff),
1702 brw_vf_to_float((inst->src[i].ud >> 24) & 0xff));
1703 break;
1704 default:
1705 fprintf(file, "???");
1706 break;
1707 }
1708 break;
1709 case ARF:
1710 switch (inst->src[i].nr) {
1711 case BRW_ARF_NULL:
1712 fprintf(file, "null");
1713 break;
1714 case BRW_ARF_ADDRESS:
1715 fprintf(file, "a0.%d", inst->src[i].subnr);
1716 break;
1717 case BRW_ARF_ACCUMULATOR:
1718 fprintf(file, "acc%d", inst->src[i].subnr);
1719 break;
1720 case BRW_ARF_FLAG:
1721 fprintf(file, "f%d.%d", inst->src[i].nr & 0xf, inst->src[i].subnr);
1722 break;
1723 default:
1724 fprintf(file, "arf%d.%d", inst->src[i].nr & 0xf, inst->src[i].subnr);
1725 break;
1726 }
1727 break;
1728 case BAD_FILE:
1729 fprintf(file, "(null)");
1730 break;
1731 case MRF:
1732 unreachable("not reached");
1733 }
1734
1735 if (inst->src[i].offset ||
1736 (inst->src[i].file == VGRF &&
1737 alloc.sizes[inst->src[i].nr] * REG_SIZE != inst->size_read(i))) {
1738 const unsigned reg_size = (inst->src[i].file == UNIFORM ? 16 : REG_SIZE);
1739 fprintf(file, "+%d.%d", inst->src[i].offset / reg_size,
1740 inst->src[i].offset % reg_size);
1741 }
1742
1743 if (inst->src[i].file != IMM) {
1744 static const char *chans[4] = {"x", "y", "z", "w"};
1745 fprintf(file, ".");
1746 for (int c = 0; c < 4; c++) {
1747 fprintf(file, "%s", chans[BRW_GET_SWZ(inst->src[i].swizzle, c)]);
1748 }
1749 }
1750
1751 if (inst->src[i].abs)
1752 fprintf(file, "|");
1753
1754 if (inst->src[i].file != IMM) {
1755 fprintf(file, ":%s", brw_reg_type_to_letters(inst->src[i].type));
1756 }
1757
1758 if (i < 2 && inst->src[i + 1].file != BAD_FILE)
1759 fprintf(file, ", ");
1760 }
1761
1762 if (inst->force_writemask_all)
1763 fprintf(file, " NoMask");
1764
1765 if (inst->exec_size != 8)
1766 fprintf(file, " group%d", inst->group);
1767
1768 fprintf(file, "\n");
1769 }
1770
1771
1772 int
1773 vec4_vs_visitor::setup_attributes(int payload_reg)
1774 {
1775 foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
1776 for (int i = 0; i < 3; i++) {
1777 if (inst->src[i].file == ATTR) {
1778 assert(inst->src[i].offset % REG_SIZE == 0);
1779 int grf = payload_reg + inst->src[i].nr +
1780 inst->src[i].offset / REG_SIZE;
1781
1782 struct brw_reg reg = brw_vec8_grf(grf, 0);
1783 reg.swizzle = inst->src[i].swizzle;
1784 reg.type = inst->src[i].type;
1785 reg.abs = inst->src[i].abs;
1786 reg.negate = inst->src[i].negate;
1787 inst->src[i] = reg;
1788 }
1789 }
1790 }
1791
1792 return payload_reg + vs_prog_data->nr_attribute_slots;
1793 }
1794
1795 int
1796 vec4_visitor::setup_uniforms(int reg)
1797 {
1798 prog_data->base.dispatch_grf_start_reg = reg;
1799
1800 /* The pre-gen6 VS requires that some push constants get loaded no
1801 * matter what, or the GPU would hang.
1802 */
1803 if (devinfo->gen < 6 && this->uniforms == 0) {
1804 brw_stage_prog_data_add_params(stage_prog_data, 4);
1805 for (unsigned int i = 0; i < 4; i++) {
1806 unsigned int slot = this->uniforms * 4 + i;
1807 stage_prog_data->param[slot] = BRW_PARAM_BUILTIN_ZERO;
1808 }
1809
1810 this->uniforms++;
1811 reg++;
1812 } else {
1813 reg += ALIGN(uniforms, 2) / 2;
1814 }
1815
1816 for (int i = 0; i < 4; i++)
1817 reg += stage_prog_data->ubo_ranges[i].length;
1818
1819 stage_prog_data->nr_params = this->uniforms * 4;
1820
1821 prog_data->base.curb_read_length =
1822 reg - prog_data->base.dispatch_grf_start_reg;
1823
1824 return reg;
1825 }
1826
1827 void
1828 vec4_vs_visitor::setup_payload(void)
1829 {
1830 int reg = 0;
1831
1832 /* The payload always contains important data in g0, which contains
1833 * the URB handles that are passed on to the URB write at the end
1834 * of the thread. So, we always start push constants at g1.
1835 */
1836 reg++;
1837
1838 reg = setup_uniforms(reg);
1839
1840 reg = setup_attributes(reg);
1841
1842 this->first_non_payload_grf = reg;
1843 }
1844
1845 bool
1846 vec4_visitor::lower_minmax()
1847 {
1848 assert(devinfo->gen < 6);
1849
1850 bool progress = false;
1851
1852 foreach_block_and_inst_safe(block, vec4_instruction, inst, cfg) {
1853 const vec4_builder ibld(this, block, inst);
1854
1855 if (inst->opcode == BRW_OPCODE_SEL &&
1856 inst->predicate == BRW_PREDICATE_NONE) {
1857 /* FIXME: Using CMP doesn't preserve the NaN propagation semantics of
1858 * the original SEL.L/GE instruction
1859 */
1860 ibld.CMP(ibld.null_reg_d(), inst->src[0], inst->src[1],
1861 inst->conditional_mod);
1862 inst->predicate = BRW_PREDICATE_NORMAL;
1863 inst->conditional_mod = BRW_CONDITIONAL_NONE;
1864
1865 progress = true;
1866 }
1867 }
1868
1869 if (progress)
1870 invalidate_live_intervals();
1871
1872 return progress;
1873 }
1874
1875 src_reg
1876 vec4_visitor::get_timestamp()
1877 {
1878 assert(devinfo->gen >= 7);
1879
1880 src_reg ts = src_reg(brw_reg(BRW_ARCHITECTURE_REGISTER_FILE,
1881 BRW_ARF_TIMESTAMP,
1882 0,
1883 0,
1884 0,
1885 BRW_REGISTER_TYPE_UD,
1886 BRW_VERTICAL_STRIDE_0,
1887 BRW_WIDTH_4,
1888 BRW_HORIZONTAL_STRIDE_4,
1889 BRW_SWIZZLE_XYZW,
1890 WRITEMASK_XYZW));
1891
1892 dst_reg dst = dst_reg(this, glsl_type::uvec4_type);
1893
1894 vec4_instruction *mov = emit(MOV(dst, ts));
1895 /* We want to read the 3 fields we care about (mostly field 0, but also 2)
1896 * even if it's not enabled in the dispatch.
1897 */
1898 mov->force_writemask_all = true;
1899
1900 return src_reg(dst);
1901 }
1902
1903 void
1904 vec4_visitor::emit_shader_time_begin()
1905 {
1906 current_annotation = "shader time start";
1907 shader_start_time = get_timestamp();
1908 }
1909
1910 void
1911 vec4_visitor::emit_shader_time_end()
1912 {
1913 current_annotation = "shader time end";
1914 src_reg shader_end_time = get_timestamp();
1915
1916
1917 /* Check that there weren't any timestamp reset events (assuming these
1918 * were the only two timestamp reads that happened).
1919 */
1920 src_reg reset_end = shader_end_time;
1921 reset_end.swizzle = BRW_SWIZZLE_ZZZZ;
1922 vec4_instruction *test = emit(AND(dst_null_ud(), reset_end, brw_imm_ud(1u)));
1923 test->conditional_mod = BRW_CONDITIONAL_Z;
1924
1925 emit(IF(BRW_PREDICATE_NORMAL));
1926
1927 /* Take the current timestamp and get the delta. */
1928 shader_start_time.negate = true;
1929 dst_reg diff = dst_reg(this, glsl_type::uint_type);
1930 emit(ADD(diff, shader_start_time, shader_end_time));
1931
1932 /* If there were no instructions between the two timestamp gets, the diff
1933 * is 2 cycles. Remove that overhead, so I can forget about that when
1934 * trying to determine the time taken for single instructions.
1935 */
1936 emit(ADD(diff, src_reg(diff), brw_imm_ud(-2u)));
1937
1938 emit_shader_time_write(0, src_reg(diff));
1939 emit_shader_time_write(1, brw_imm_ud(1u));
1940 emit(BRW_OPCODE_ELSE);
1941 emit_shader_time_write(2, brw_imm_ud(1u));
1942 emit(BRW_OPCODE_ENDIF);
1943 }
1944
1945 void
1946 vec4_visitor::emit_shader_time_write(int shader_time_subindex, src_reg value)
1947 {
1948 dst_reg dst =
1949 dst_reg(this, glsl_type::get_array_instance(glsl_type::vec4_type, 2));
1950
1951 dst_reg offset = dst;
1952 dst_reg time = dst;
1953 time.offset += REG_SIZE;
1954
1955 offset.type = BRW_REGISTER_TYPE_UD;
1956 int index = shader_time_index * 3 + shader_time_subindex;
1957 emit(MOV(offset, brw_imm_d(index * BRW_SHADER_TIME_STRIDE)));
1958
1959 time.type = BRW_REGISTER_TYPE_UD;
1960 emit(MOV(time, value));
1961
1962 vec4_instruction *inst =
1963 emit(SHADER_OPCODE_SHADER_TIME_ADD, dst_reg(), src_reg(dst));
1964 inst->mlen = 2;
1965 }
1966
1967 static bool
1968 is_align1_df(vec4_instruction *inst)
1969 {
1970 switch (inst->opcode) {
1971 case VEC4_OPCODE_DOUBLE_TO_F32:
1972 case VEC4_OPCODE_DOUBLE_TO_D32:
1973 case VEC4_OPCODE_DOUBLE_TO_U32:
1974 case VEC4_OPCODE_TO_DOUBLE:
1975 case VEC4_OPCODE_PICK_LOW_32BIT:
1976 case VEC4_OPCODE_PICK_HIGH_32BIT:
1977 case VEC4_OPCODE_SET_LOW_32BIT:
1978 case VEC4_OPCODE_SET_HIGH_32BIT:
1979 return true;
1980 default:
1981 return false;
1982 }
1983 }
1984
1985 /**
1986 * Three source instruction must have a GRF/MRF destination register.
1987 * ARF NULL is not allowed. Fix that up by allocating a temporary GRF.
1988 */
1989 void
1990 vec4_visitor::fixup_3src_null_dest()
1991 {
1992 bool progress = false;
1993
1994 foreach_block_and_inst_safe (block, vec4_instruction, inst, cfg) {
1995 if (inst->is_3src(devinfo) && inst->dst.is_null()) {
1996 const unsigned size_written = type_sz(inst->dst.type);
1997 const unsigned num_regs = DIV_ROUND_UP(size_written, REG_SIZE);
1998
1999 inst->dst = retype(dst_reg(VGRF, alloc.allocate(num_regs)),
2000 inst->dst.type);
2001 progress = true;
2002 }
2003 }
2004
2005 if (progress)
2006 invalidate_live_intervals();
2007 }
2008
2009 void
2010 vec4_visitor::convert_to_hw_regs()
2011 {
2012 foreach_block_and_inst(block, vec4_instruction, inst, cfg) {
2013 for (int i = 0; i < 3; i++) {
2014 class src_reg &src = inst->src[i];
2015 struct brw_reg reg;
2016 switch (src.file) {
2017 case VGRF: {
2018 reg = byte_offset(brw_vecn_grf(4, src.nr, 0), src.offset);
2019 reg.type = src.type;
2020 reg.abs = src.abs;
2021 reg.negate = src.negate;
2022 break;
2023 }
2024
2025 case UNIFORM: {
2026 reg = stride(byte_offset(brw_vec4_grf(
2027 prog_data->base.dispatch_grf_start_reg +
2028 src.nr / 2, src.nr % 2 * 4),
2029 src.offset),
2030 0, 4, 1);
2031 reg.type = src.type;
2032 reg.abs = src.abs;
2033 reg.negate = src.negate;
2034
2035 /* This should have been moved to pull constants. */
2036 assert(!src.reladdr);
2037 break;
2038 }
2039
2040 case FIXED_GRF:
2041 if (type_sz(src.type) == 8) {
2042 reg = src.as_brw_reg();
2043 break;
2044 }
2045 /* fallthrough */
2046 case ARF:
2047 case IMM:
2048 continue;
2049
2050 case BAD_FILE:
2051 /* Probably unused. */
2052 reg = brw_null_reg();
2053 reg = retype(reg, src.type);
2054 break;
2055
2056 case MRF:
2057 case ATTR:
2058 unreachable("not reached");
2059 }
2060
2061 apply_logical_swizzle(&reg, inst, i);
2062 src = reg;
2063
2064 /* From IVB PRM, vol4, part3, "General Restrictions on Regioning
2065 * Parameters":
2066 *
2067 * "If ExecSize = Width and HorzStride ≠ 0, VertStride must be set
2068 * to Width * HorzStride."
2069 *
2070 * We can break this rule with DF sources on DF align1
2071 * instructions, because the exec_size would be 4 and width is 4.
2072 * As we know we are not accessing to next GRF, it is safe to
2073 * set vstride to the formula given by the rule itself.
2074 */
2075 if (is_align1_df(inst) && (cvt(inst->exec_size) - 1) == src.width)
2076 src.vstride = src.width + src.hstride;
2077 }
2078
2079 if (inst->is_3src(devinfo)) {
2080 /* 3-src instructions with scalar sources support arbitrary subnr,
2081 * but don't actually use swizzles. Convert swizzle into subnr.
2082 * Skip this for double-precision instructions: RepCtrl=1 is not
2083 * allowed for them and needs special handling.
2084 */
2085 for (int i = 0; i < 3; i++) {
2086 if (inst->src[i].vstride == BRW_VERTICAL_STRIDE_0 &&
2087 type_sz(inst->src[i].type) < 8) {
2088 assert(brw_is_single_value_swizzle(inst->src[i].swizzle));
2089 inst->src[i].subnr += 4 * BRW_GET_SWZ(inst->src[i].swizzle, 0);
2090 }
2091 }
2092 }
2093
2094 dst_reg &dst = inst->dst;
2095 struct brw_reg reg;
2096
2097 switch (inst->dst.file) {
2098 case VGRF:
2099 reg = byte_offset(brw_vec8_grf(dst.nr, 0), dst.offset);
2100 reg.type = dst.type;
2101 reg.writemask = dst.writemask;
2102 break;
2103
2104 case MRF:
2105 reg = byte_offset(brw_message_reg(dst.nr), dst.offset);
2106 assert((reg.nr & ~BRW_MRF_COMPR4) < BRW_MAX_MRF(devinfo->gen));
2107 reg.type = dst.type;
2108 reg.writemask = dst.writemask;
2109 break;
2110
2111 case ARF:
2112 case FIXED_GRF:
2113 reg = dst.as_brw_reg();
2114 break;
2115
2116 case BAD_FILE:
2117 reg = brw_null_reg();
2118 reg = retype(reg, dst.type);
2119 break;
2120
2121 case IMM:
2122 case ATTR:
2123 case UNIFORM:
2124 unreachable("not reached");
2125 }
2126
2127 dst = reg;
2128 }
2129 }
2130
2131 static bool
2132 stage_uses_interleaved_attributes(unsigned stage,
2133 enum shader_dispatch_mode dispatch_mode)
2134 {
2135 switch (stage) {
2136 case MESA_SHADER_TESS_EVAL:
2137 return true;
2138 case MESA_SHADER_GEOMETRY:
2139 return dispatch_mode != DISPATCH_MODE_4X2_DUAL_OBJECT;
2140 default:
2141 return false;
2142 }
2143 }
2144
2145 /**
2146 * Get the closest native SIMD width supported by the hardware for instruction
2147 * \p inst. The instruction will be left untouched by
2148 * vec4_visitor::lower_simd_width() if the returned value matches the
2149 * instruction's original execution size.
2150 */
2151 static unsigned
2152 get_lowered_simd_width(const struct gen_device_info *devinfo,
2153 enum shader_dispatch_mode dispatch_mode,
2154 unsigned stage, const vec4_instruction *inst)
2155 {
2156 /* Do not split some instructions that require special handling */
2157 switch (inst->opcode) {
2158 case SHADER_OPCODE_GEN4_SCRATCH_READ:
2159 case SHADER_OPCODE_GEN4_SCRATCH_WRITE:
2160 return inst->exec_size;
2161 default:
2162 break;
2163 }
2164
2165 unsigned lowered_width = MIN2(16, inst->exec_size);
2166
2167 /* We need to split some cases of double-precision instructions that write
2168 * 2 registers. We only need to care about this in gen7 because that is the
2169 * only hardware that implements fp64 in Align16.
2170 */
2171 if (devinfo->gen == 7 && inst->size_written > REG_SIZE) {
2172 /* Align16 8-wide double-precision SEL does not work well. Verified
2173 * empirically.
2174 */
2175 if (inst->opcode == BRW_OPCODE_SEL && type_sz(inst->dst.type) == 8)
2176 lowered_width = MIN2(lowered_width, 4);
2177
2178 /* HSW PRM, 3D Media GPGPU Engine, Region Alignment Rules for Direct
2179 * Register Addressing:
2180 *
2181 * "When destination spans two registers, the source MUST span two
2182 * registers."
2183 */
2184 for (unsigned i = 0; i < 3; i++) {
2185 if (inst->src[i].file == BAD_FILE)
2186 continue;
2187 if (inst->size_read(i) <= REG_SIZE)
2188 lowered_width = MIN2(lowered_width, 4);
2189
2190 /* Interleaved attribute setups use a vertical stride of 0, which
2191 * makes them hit the associated instruction decompression bug in gen7.
2192 * Split them to prevent this.
2193 */
2194 if (inst->src[i].file == ATTR &&
2195 stage_uses_interleaved_attributes(stage, dispatch_mode))
2196 lowered_width = MIN2(lowered_width, 4);
2197 }
2198 }
2199
2200 /* IvyBridge can manage a maximum of 4 DFs per SIMD4x2 instruction, since
2201 * it doesn't support compression in Align16 mode, no matter if it has
2202 * force_writemask_all enabled or disabled (the latter is affected by the
2203 * compressed instruction bug in gen7, which is another reason to enforce
2204 * this limit).
2205 */
2206 if (devinfo->gen == 7 && !devinfo->is_haswell &&
2207 (get_exec_type_size(inst) == 8 || type_sz(inst->dst.type) == 8))
2208 lowered_width = MIN2(lowered_width, 4);
2209
2210 return lowered_width;
2211 }
2212
2213 static bool
2214 dst_src_regions_overlap(vec4_instruction *inst)
2215 {
2216 if (inst->size_written == 0)
2217 return false;
2218
2219 unsigned dst_start = inst->dst.offset;
2220 unsigned dst_end = dst_start + inst->size_written - 1;
2221 for (int i = 0; i < 3; i++) {
2222 if (inst->src[i].file == BAD_FILE)
2223 continue;
2224
2225 if (inst->dst.file != inst->src[i].file ||
2226 inst->dst.nr != inst->src[i].nr)
2227 continue;
2228
2229 unsigned src_start = inst->src[i].offset;
2230 unsigned src_end = src_start + inst->size_read(i) - 1;
2231
2232 if ((dst_start >= src_start && dst_start <= src_end) ||
2233 (dst_end >= src_start && dst_end <= src_end) ||
2234 (dst_start <= src_start && dst_end >= src_end)) {
2235 return true;
2236 }
2237 }
2238
2239 return false;
2240 }
2241
2242 bool
2243 vec4_visitor::lower_simd_width()
2244 {
2245 bool progress = false;
2246
2247 foreach_block_and_inst_safe(block, vec4_instruction, inst, cfg) {
2248 const unsigned lowered_width =
2249 get_lowered_simd_width(devinfo, prog_data->dispatch_mode, stage, inst);
2250 assert(lowered_width <= inst->exec_size);
2251 if (lowered_width == inst->exec_size)
2252 continue;
2253
2254 /* We need to deal with source / destination overlaps when splitting.
2255 * The hardware supports reading from and writing to the same register
2256 * in the same instruction, but we need to be careful that each split
2257 * instruction we produce does not corrupt the source of the next.
2258 *
2259 * The easiest way to handle this is to make the split instructions write
2260 * to temporaries if there is an src/dst overlap and then move from the
2261 * temporaries to the original destination. We also need to consider
2262 * instructions that do partial writes via align1 opcodes, in which case
2263 * we need to make sure that the we initialize the temporary with the
2264 * value of the instruction's dst.
2265 */
2266 bool needs_temp = dst_src_regions_overlap(inst);
2267 for (unsigned n = 0; n < inst->exec_size / lowered_width; n++) {
2268 unsigned channel_offset = lowered_width * n;
2269
2270 unsigned size_written = lowered_width * type_sz(inst->dst.type);
2271
2272 /* Create the split instruction from the original so that we copy all
2273 * relevant instruction fields, then set the width and calculate the
2274 * new dst/src regions.
2275 */
2276 vec4_instruction *linst = new(mem_ctx) vec4_instruction(*inst);
2277 linst->exec_size = lowered_width;
2278 linst->group = channel_offset;
2279 linst->size_written = size_written;
2280
2281 /* Compute split dst region */
2282 dst_reg dst;
2283 if (needs_temp) {
2284 unsigned num_regs = DIV_ROUND_UP(size_written, REG_SIZE);
2285 dst = retype(dst_reg(VGRF, alloc.allocate(num_regs)),
2286 inst->dst.type);
2287 if (inst->is_align1_partial_write()) {
2288 vec4_instruction *copy = MOV(dst, src_reg(inst->dst));
2289 copy->exec_size = lowered_width;
2290 copy->group = channel_offset;
2291 copy->size_written = size_written;
2292 inst->insert_before(block, copy);
2293 }
2294 } else {
2295 dst = horiz_offset(inst->dst, channel_offset);
2296 }
2297 linst->dst = dst;
2298
2299 /* Compute split source regions */
2300 for (int i = 0; i < 3; i++) {
2301 if (linst->src[i].file == BAD_FILE)
2302 continue;
2303
2304 bool is_interleaved_attr =
2305 linst->src[i].file == ATTR &&
2306 stage_uses_interleaved_attributes(stage,
2307 prog_data->dispatch_mode);
2308
2309 if (!is_uniform(linst->src[i]) && !is_interleaved_attr)
2310 linst->src[i] = horiz_offset(linst->src[i], channel_offset);
2311 }
2312
2313 inst->insert_before(block, linst);
2314
2315 /* If we used a temporary to store the result of the split
2316 * instruction, copy the result to the original destination
2317 */
2318 if (needs_temp) {
2319 vec4_instruction *mov =
2320 MOV(offset(inst->dst, lowered_width, n), src_reg(dst));
2321 mov->exec_size = lowered_width;
2322 mov->group = channel_offset;
2323 mov->size_written = size_written;
2324 mov->predicate = inst->predicate;
2325 inst->insert_before(block, mov);
2326 }
2327 }
2328
2329 inst->remove(block);
2330 progress = true;
2331 }
2332
2333 if (progress)
2334 invalidate_live_intervals();
2335
2336 return progress;
2337 }
2338
2339 static brw_predicate
2340 scalarize_predicate(brw_predicate predicate, unsigned writemask)
2341 {
2342 if (predicate != BRW_PREDICATE_NORMAL)
2343 return predicate;
2344
2345 switch (writemask) {
2346 case WRITEMASK_X:
2347 return BRW_PREDICATE_ALIGN16_REPLICATE_X;
2348 case WRITEMASK_Y:
2349 return BRW_PREDICATE_ALIGN16_REPLICATE_Y;
2350 case WRITEMASK_Z:
2351 return BRW_PREDICATE_ALIGN16_REPLICATE_Z;
2352 case WRITEMASK_W:
2353 return BRW_PREDICATE_ALIGN16_REPLICATE_W;
2354 default:
2355 unreachable("invalid writemask");
2356 }
2357 }
2358
2359 /* Gen7 has a hardware decompression bug that we can exploit to represent
2360 * handful of additional swizzles natively.
2361 */
2362 static bool
2363 is_gen7_supported_64bit_swizzle(vec4_instruction *inst, unsigned arg)
2364 {
2365 switch (inst->src[arg].swizzle) {
2366 case BRW_SWIZZLE_XXXX:
2367 case BRW_SWIZZLE_YYYY:
2368 case BRW_SWIZZLE_ZZZZ:
2369 case BRW_SWIZZLE_WWWW:
2370 case BRW_SWIZZLE_XYXY:
2371 case BRW_SWIZZLE_YXYX:
2372 case BRW_SWIZZLE_ZWZW:
2373 case BRW_SWIZZLE_WZWZ:
2374 return true;
2375 default:
2376 return false;
2377 }
2378 }
2379
2380 /* 64-bit sources use regions with a width of 2. These 2 elements in each row
2381 * can be addressed using 32-bit swizzles (which is what the hardware supports)
2382 * but it also means that the swizzle we apply on the first two components of a
2383 * dvec4 is coupled with the swizzle we use for the last 2. In other words,
2384 * only some specific swizzle combinations can be natively supported.
2385 *
2386 * FIXME: we can go an step further and implement even more swizzle
2387 * variations using only partial scalarization.
2388 *
2389 * For more details see:
2390 * https://bugs.freedesktop.org/show_bug.cgi?id=92760#c82
2391 */
2392 bool
2393 vec4_visitor::is_supported_64bit_region(vec4_instruction *inst, unsigned arg)
2394 {
2395 const src_reg &src = inst->src[arg];
2396 assert(type_sz(src.type) == 8);
2397
2398 /* Uniform regions have a vstride=0. Because we use 2-wide rows with
2399 * 64-bit regions it means that we cannot access components Z/W, so
2400 * return false for any such case. Interleaved attributes will also be
2401 * mapped to GRF registers with a vstride of 0, so apply the same
2402 * treatment.
2403 */
2404 if ((is_uniform(src) ||
2405 (stage_uses_interleaved_attributes(stage, prog_data->dispatch_mode) &&
2406 src.file == ATTR)) &&
2407 (brw_mask_for_swizzle(src.swizzle) & 12))
2408 return false;
2409
2410 switch (src.swizzle) {
2411 case BRW_SWIZZLE_XYZW:
2412 case BRW_SWIZZLE_XXZZ:
2413 case BRW_SWIZZLE_YYWW:
2414 case BRW_SWIZZLE_YXWZ:
2415 return true;
2416 default:
2417 return devinfo->gen == 7 && is_gen7_supported_64bit_swizzle(inst, arg);
2418 }
2419 }
2420
2421 bool
2422 vec4_visitor::scalarize_df()
2423 {
2424 bool progress = false;
2425
2426 foreach_block_and_inst_safe(block, vec4_instruction, inst, cfg) {
2427 /* Skip DF instructions that operate in Align1 mode */
2428 if (is_align1_df(inst))
2429 continue;
2430
2431 /* Check if this is a double-precision instruction */
2432 bool is_double = type_sz(inst->dst.type) == 8;
2433 for (int arg = 0; !is_double && arg < 3; arg++) {
2434 is_double = inst->src[arg].file != BAD_FILE &&
2435 type_sz(inst->src[arg].type) == 8;
2436 }
2437
2438 if (!is_double)
2439 continue;
2440
2441 /* Skip the lowering for specific regioning scenarios that we can
2442 * support natively.
2443 */
2444 bool skip_lowering = true;
2445
2446 /* XY and ZW writemasks operate in 32-bit, which means that they don't
2447 * have a native 64-bit representation and they should always be split.
2448 */
2449 if (inst->dst.writemask == WRITEMASK_XY ||
2450 inst->dst.writemask == WRITEMASK_ZW) {
2451 skip_lowering = false;
2452 } else {
2453 for (unsigned i = 0; i < 3; i++) {
2454 if (inst->src[i].file == BAD_FILE || type_sz(inst->src[i].type) < 8)
2455 continue;
2456 skip_lowering = skip_lowering && is_supported_64bit_region(inst, i);
2457 }
2458 }
2459
2460 if (skip_lowering)
2461 continue;
2462
2463 /* Generate scalar instructions for each enabled channel */
2464 for (unsigned chan = 0; chan < 4; chan++) {
2465 unsigned chan_mask = 1 << chan;
2466 if (!(inst->dst.writemask & chan_mask))
2467 continue;
2468
2469 vec4_instruction *scalar_inst = new(mem_ctx) vec4_instruction(*inst);
2470
2471 for (unsigned i = 0; i < 3; i++) {
2472 unsigned swz = BRW_GET_SWZ(inst->src[i].swizzle, chan);
2473 scalar_inst->src[i].swizzle = BRW_SWIZZLE4(swz, swz, swz, swz);
2474 }
2475
2476 scalar_inst->dst.writemask = chan_mask;
2477
2478 if (inst->predicate != BRW_PREDICATE_NONE) {
2479 scalar_inst->predicate =
2480 scalarize_predicate(inst->predicate, chan_mask);
2481 }
2482
2483 inst->insert_before(block, scalar_inst);
2484 }
2485
2486 inst->remove(block);
2487 progress = true;
2488 }
2489
2490 if (progress)
2491 invalidate_live_intervals();
2492
2493 return progress;
2494 }
2495
2496 bool
2497 vec4_visitor::lower_64bit_mad_to_mul_add()
2498 {
2499 bool progress = false;
2500
2501 foreach_block_and_inst_safe(block, vec4_instruction, inst, cfg) {
2502 if (inst->opcode != BRW_OPCODE_MAD)
2503 continue;
2504
2505 if (type_sz(inst->dst.type) != 8)
2506 continue;
2507
2508 dst_reg mul_dst = dst_reg(this, glsl_type::dvec4_type);
2509
2510 /* Use the copy constructor so we copy all relevant instruction fields
2511 * from the original mad into the add and mul instructions
2512 */
2513 vec4_instruction *mul = new(mem_ctx) vec4_instruction(*inst);
2514 mul->opcode = BRW_OPCODE_MUL;
2515 mul->dst = mul_dst;
2516 mul->src[0] = inst->src[1];
2517 mul->src[1] = inst->src[2];
2518 mul->src[2].file = BAD_FILE;
2519
2520 vec4_instruction *add = new(mem_ctx) vec4_instruction(*inst);
2521 add->opcode = BRW_OPCODE_ADD;
2522 add->src[0] = src_reg(mul_dst);
2523 add->src[1] = inst->src[0];
2524 add->src[2].file = BAD_FILE;
2525
2526 inst->insert_before(block, mul);
2527 inst->insert_before(block, add);
2528 inst->remove(block);
2529
2530 progress = true;
2531 }
2532
2533 if (progress)
2534 invalidate_live_intervals();
2535
2536 return progress;
2537 }
2538
2539 /* The align16 hardware can only do 32-bit swizzle channels, so we need to
2540 * translate the logical 64-bit swizzle channels that we use in the Vec4 IR
2541 * to 32-bit swizzle channels in hardware registers.
2542 *
2543 * @inst and @arg identify the original vec4 IR source operand we need to
2544 * translate the swizzle for and @hw_reg is the hardware register where we
2545 * will write the hardware swizzle to use.
2546 *
2547 * This pass assumes that Align16/DF instructions have been fully scalarized
2548 * previously so there is just one 64-bit swizzle channel to deal with for any
2549 * given Vec4 IR source.
2550 */
2551 void
2552 vec4_visitor::apply_logical_swizzle(struct brw_reg *hw_reg,
2553 vec4_instruction *inst, int arg)
2554 {
2555 src_reg reg = inst->src[arg];
2556
2557 if (reg.file == BAD_FILE || reg.file == BRW_IMMEDIATE_VALUE)
2558 return;
2559
2560 /* If this is not a 64-bit operand or this is a scalar instruction we don't
2561 * need to do anything about the swizzles.
2562 */
2563 if(type_sz(reg.type) < 8 || is_align1_df(inst)) {
2564 hw_reg->swizzle = reg.swizzle;
2565 return;
2566 }
2567
2568 /* Take the 64-bit logical swizzle channel and translate it to 32-bit */
2569 assert(brw_is_single_value_swizzle(reg.swizzle) ||
2570 is_supported_64bit_region(inst, arg));
2571
2572 /* Apply the region <2, 2, 1> for GRF or <0, 2, 1> for uniforms, as align16
2573 * HW can only do 32-bit swizzle channels.
2574 */
2575 hw_reg->width = BRW_WIDTH_2;
2576
2577 if (is_supported_64bit_region(inst, arg) &&
2578 !is_gen7_supported_64bit_swizzle(inst, arg)) {
2579 /* Supported 64-bit swizzles are those such that their first two
2580 * components, when expanded to 32-bit swizzles, match the semantics
2581 * of the original 64-bit swizzle with 2-wide row regioning.
2582 */
2583 unsigned swizzle0 = BRW_GET_SWZ(reg.swizzle, 0);
2584 unsigned swizzle1 = BRW_GET_SWZ(reg.swizzle, 1);
2585 hw_reg->swizzle = BRW_SWIZZLE4(swizzle0 * 2, swizzle0 * 2 + 1,
2586 swizzle1 * 2, swizzle1 * 2 + 1);
2587 } else {
2588 /* If we got here then we have one of the following:
2589 *
2590 * 1. An unsupported swizzle, which should be single-value thanks to the
2591 * scalarization pass.
2592 *
2593 * 2. A gen7 supported swizzle. These can be single-value or double-value
2594 * swizzles. If the latter, they are never cross-dvec2 channels. For
2595 * these we always need to activate the gen7 vstride=0 exploit.
2596 */
2597 unsigned swizzle0 = BRW_GET_SWZ(reg.swizzle, 0);
2598 unsigned swizzle1 = BRW_GET_SWZ(reg.swizzle, 1);
2599 assert((swizzle0 < 2) == (swizzle1 < 2));
2600
2601 /* To gain access to Z/W components we need to select the second half
2602 * of the register and then use a X/Y swizzle to select Z/W respectively.
2603 */
2604 if (swizzle0 >= 2) {
2605 *hw_reg = suboffset(*hw_reg, 2);
2606 swizzle0 -= 2;
2607 swizzle1 -= 2;
2608 }
2609
2610 /* All gen7-specific supported swizzles require the vstride=0 exploit */
2611 if (devinfo->gen == 7 && is_gen7_supported_64bit_swizzle(inst, arg))
2612 hw_reg->vstride = BRW_VERTICAL_STRIDE_0;
2613
2614 /* Any 64-bit source with an offset at 16B is intended to address the
2615 * second half of a register and needs a vertical stride of 0 so we:
2616 *
2617 * 1. Don't violate register region restrictions.
2618 * 2. Activate the gen7 instruction decompresion bug exploit when
2619 * execsize > 4
2620 */
2621 if (hw_reg->subnr % REG_SIZE == 16) {
2622 assert(devinfo->gen == 7);
2623 hw_reg->vstride = BRW_VERTICAL_STRIDE_0;
2624 }
2625
2626 hw_reg->swizzle = BRW_SWIZZLE4(swizzle0 * 2, swizzle0 * 2 + 1,
2627 swizzle1 * 2, swizzle1 * 2 + 1);
2628 }
2629 }
2630
2631 bool
2632 vec4_visitor::run()
2633 {
2634 if (shader_time_index >= 0)
2635 emit_shader_time_begin();
2636
2637 emit_prolog();
2638
2639 emit_nir_code();
2640 if (failed)
2641 return false;
2642 base_ir = NULL;
2643
2644 emit_thread_end();
2645
2646 calculate_cfg();
2647
2648 /* Before any optimization, push array accesses out to scratch
2649 * space where we need them to be. This pass may allocate new
2650 * virtual GRFs, so we want to do it early. It also makes sure
2651 * that we have reladdr computations available for CSE, since we'll
2652 * often do repeated subexpressions for those.
2653 */
2654 move_grf_array_access_to_scratch();
2655 move_uniform_array_access_to_pull_constants();
2656
2657 pack_uniform_registers();
2658 move_push_constants_to_pull_constants();
2659 split_virtual_grfs();
2660
2661 #define OPT(pass, args...) ({ \
2662 pass_num++; \
2663 bool this_progress = pass(args); \
2664 \
2665 if (unlikely(INTEL_DEBUG & DEBUG_OPTIMIZER) && this_progress) { \
2666 char filename[64]; \
2667 snprintf(filename, 64, "%s-%s-%02d-%02d-" #pass, \
2668 stage_abbrev, nir->info.name, iteration, pass_num); \
2669 \
2670 backend_shader::dump_instructions(filename); \
2671 } \
2672 \
2673 progress = progress || this_progress; \
2674 this_progress; \
2675 })
2676
2677
2678 if (unlikely(INTEL_DEBUG & DEBUG_OPTIMIZER)) {
2679 char filename[64];
2680 snprintf(filename, 64, "%s-%s-00-00-start",
2681 stage_abbrev, nir->info.name);
2682
2683 backend_shader::dump_instructions(filename);
2684 }
2685
2686 bool progress;
2687 int iteration = 0;
2688 int pass_num = 0;
2689 do {
2690 progress = false;
2691 pass_num = 0;
2692 iteration++;
2693
2694 OPT(opt_predicated_break, this);
2695 OPT(opt_reduce_swizzle);
2696 OPT(dead_code_eliminate);
2697 OPT(dead_control_flow_eliminate, this);
2698 OPT(opt_copy_propagation);
2699 OPT(opt_cmod_propagation);
2700 OPT(opt_cse);
2701 OPT(opt_algebraic);
2702 OPT(opt_register_coalesce);
2703 OPT(eliminate_find_live_channel);
2704 } while (progress);
2705
2706 pass_num = 0;
2707
2708 if (OPT(opt_vector_float)) {
2709 OPT(opt_cse);
2710 OPT(opt_copy_propagation, false);
2711 OPT(opt_copy_propagation, true);
2712 OPT(dead_code_eliminate);
2713 }
2714
2715 if (devinfo->gen <= 5 && OPT(lower_minmax)) {
2716 OPT(opt_cmod_propagation);
2717 OPT(opt_cse);
2718 OPT(opt_copy_propagation);
2719 OPT(dead_code_eliminate);
2720 }
2721
2722 if (OPT(lower_simd_width)) {
2723 OPT(opt_copy_propagation);
2724 OPT(dead_code_eliminate);
2725 }
2726
2727 if (failed)
2728 return false;
2729
2730 OPT(lower_64bit_mad_to_mul_add);
2731
2732 /* Run this before payload setup because tesselation shaders
2733 * rely on it to prevent cross dvec2 regioning on DF attributes
2734 * that are setup so that XY are on the second half of register and
2735 * ZW are in the first half of the next.
2736 */
2737 OPT(scalarize_df);
2738
2739 setup_payload();
2740
2741 if (unlikely(INTEL_DEBUG & DEBUG_SPILL_VEC4)) {
2742 /* Debug of register spilling: Go spill everything. */
2743 const int grf_count = alloc.count;
2744 float spill_costs[alloc.count];
2745 bool no_spill[alloc.count];
2746 evaluate_spill_costs(spill_costs, no_spill);
2747 for (int i = 0; i < grf_count; i++) {
2748 if (no_spill[i])
2749 continue;
2750 spill_reg(i);
2751 }
2752
2753 /* We want to run this after spilling because 64-bit (un)spills need to
2754 * emit code to shuffle 64-bit data for the 32-bit scratch read/write
2755 * messages that can produce unsupported 64-bit swizzle regions.
2756 */
2757 OPT(scalarize_df);
2758 }
2759
2760 fixup_3src_null_dest();
2761
2762 bool allocated_without_spills = reg_allocate();
2763
2764 if (!allocated_without_spills) {
2765 compiler->shader_perf_log(log_data,
2766 "%s shader triggered register spilling. "
2767 "Try reducing the number of live vec4 values "
2768 "to improve performance.\n",
2769 stage_name);
2770
2771 while (!reg_allocate()) {
2772 if (failed)
2773 return false;
2774 }
2775
2776 /* We want to run this after spilling because 64-bit (un)spills need to
2777 * emit code to shuffle 64-bit data for the 32-bit scratch read/write
2778 * messages that can produce unsupported 64-bit swizzle regions.
2779 */
2780 OPT(scalarize_df);
2781 }
2782
2783 opt_schedule_instructions();
2784
2785 opt_set_dependency_control();
2786
2787 convert_to_hw_regs();
2788
2789 if (last_scratch > 0) {
2790 prog_data->base.total_scratch =
2791 brw_get_scratch_size(last_scratch * REG_SIZE);
2792 }
2793
2794 return !failed;
2795 }
2796
2797 } /* namespace brw */
2798
2799 extern "C" {
2800
2801 /**
2802 * Compile a vertex shader.
2803 *
2804 * Returns the final assembly and the program's size.
2805 */
2806 const unsigned *
2807 brw_compile_vs(const struct brw_compiler *compiler, void *log_data,
2808 void *mem_ctx,
2809 const struct brw_vs_prog_key *key,
2810 struct brw_vs_prog_data *prog_data,
2811 const nir_shader *src_shader,
2812 int shader_time_index,
2813 char **error_str)
2814 {
2815 const bool is_scalar = compiler->scalar_stage[MESA_SHADER_VERTEX];
2816 nir_shader *shader = nir_shader_clone(mem_ctx, src_shader);
2817 shader = brw_nir_apply_sampler_key(shader, compiler, &key->tex, is_scalar);
2818
2819 const unsigned *assembly = NULL;
2820
2821 if (prog_data->base.vue_map.varying_to_slot[VARYING_SLOT_EDGE] != -1) {
2822 /* If the output VUE map contains VARYING_SLOT_EDGE then we need to copy
2823 * the edge flag from VERT_ATTRIB_EDGEFLAG. This will be done
2824 * automatically by brw_vec4_visitor::emit_urb_slot but we need to
2825 * ensure that prog_data->inputs_read is accurate.
2826 *
2827 * In order to make late NIR passes aware of the change, we actually
2828 * whack shader->info.inputs_read instead. This is safe because we just
2829 * made a copy of the shader.
2830 */
2831 assert(!is_scalar);
2832 assert(key->copy_edgeflag);
2833 shader->info.inputs_read |= VERT_BIT_EDGEFLAG;
2834 }
2835
2836 prog_data->inputs_read = shader->info.inputs_read;
2837 prog_data->double_inputs_read = shader->info.vs.double_inputs;
2838
2839 brw_nir_lower_vs_inputs(shader, key->gl_attrib_wa_flags);
2840 brw_nir_lower_vue_outputs(shader);
2841 shader = brw_postprocess_nir(shader, compiler, is_scalar);
2842
2843 prog_data->base.clip_distance_mask =
2844 ((1 << shader->info.clip_distance_array_size) - 1);
2845 prog_data->base.cull_distance_mask =
2846 ((1 << shader->info.cull_distance_array_size) - 1) <<
2847 shader->info.clip_distance_array_size;
2848
2849 unsigned nr_attribute_slots = util_bitcount64(prog_data->inputs_read);
2850
2851 /* gl_VertexID and gl_InstanceID are system values, but arrive via an
2852 * incoming vertex attribute. So, add an extra slot.
2853 */
2854 if (shader->info.system_values_read &
2855 (BITFIELD64_BIT(SYSTEM_VALUE_FIRST_VERTEX) |
2856 BITFIELD64_BIT(SYSTEM_VALUE_BASE_INSTANCE) |
2857 BITFIELD64_BIT(SYSTEM_VALUE_VERTEX_ID_ZERO_BASE) |
2858 BITFIELD64_BIT(SYSTEM_VALUE_INSTANCE_ID))) {
2859 nr_attribute_slots++;
2860 }
2861
2862 /* gl_DrawID and IsIndexedDraw share its very own vec4 */
2863 if (shader->info.system_values_read &
2864 (BITFIELD64_BIT(SYSTEM_VALUE_DRAW_ID) |
2865 BITFIELD64_BIT(SYSTEM_VALUE_IS_INDEXED_DRAW))) {
2866 nr_attribute_slots++;
2867 }
2868
2869 if (shader->info.system_values_read &
2870 BITFIELD64_BIT(SYSTEM_VALUE_IS_INDEXED_DRAW))
2871 prog_data->uses_is_indexed_draw = true;
2872
2873 if (shader->info.system_values_read &
2874 BITFIELD64_BIT(SYSTEM_VALUE_FIRST_VERTEX))
2875 prog_data->uses_firstvertex = true;
2876
2877 if (shader->info.system_values_read &
2878 BITFIELD64_BIT(SYSTEM_VALUE_BASE_INSTANCE))
2879 prog_data->uses_baseinstance = true;
2880
2881 if (shader->info.system_values_read &
2882 BITFIELD64_BIT(SYSTEM_VALUE_VERTEX_ID_ZERO_BASE))
2883 prog_data->uses_vertexid = true;
2884
2885 if (shader->info.system_values_read &
2886 BITFIELD64_BIT(SYSTEM_VALUE_INSTANCE_ID))
2887 prog_data->uses_instanceid = true;
2888
2889 if (shader->info.system_values_read &
2890 BITFIELD64_BIT(SYSTEM_VALUE_DRAW_ID))
2891 prog_data->uses_drawid = true;
2892
2893 /* The 3DSTATE_VS documentation lists the lower bound on "Vertex URB Entry
2894 * Read Length" as 1 in vec4 mode, and 0 in SIMD8 mode. Empirically, in
2895 * vec4 mode, the hardware appears to wedge unless we read something.
2896 */
2897 if (is_scalar)
2898 prog_data->base.urb_read_length =
2899 DIV_ROUND_UP(nr_attribute_slots, 2);
2900 else
2901 prog_data->base.urb_read_length =
2902 DIV_ROUND_UP(MAX2(nr_attribute_slots, 1), 2);
2903
2904 prog_data->nr_attribute_slots = nr_attribute_slots;
2905
2906 /* Since vertex shaders reuse the same VUE entry for inputs and outputs
2907 * (overwriting the original contents), we need to make sure the size is
2908 * the larger of the two.
2909 */
2910 const unsigned vue_entries =
2911 MAX2(nr_attribute_slots, (unsigned)prog_data->base.vue_map.num_slots);
2912
2913 if (compiler->devinfo->gen == 6) {
2914 prog_data->base.urb_entry_size = DIV_ROUND_UP(vue_entries, 8);
2915 } else {
2916 prog_data->base.urb_entry_size = DIV_ROUND_UP(vue_entries, 4);
2917 /* On Cannonlake software shall not program an allocation size that
2918 * specifies a size that is a multiple of 3 64B (512-bit) cachelines.
2919 */
2920 if (compiler->devinfo->gen == 10 &&
2921 prog_data->base.urb_entry_size % 3 == 0)
2922 prog_data->base.urb_entry_size++;
2923 }
2924
2925 if (INTEL_DEBUG & DEBUG_VS) {
2926 fprintf(stderr, "VS Output ");
2927 brw_print_vue_map(stderr, &prog_data->base.vue_map);
2928 }
2929
2930 if (is_scalar) {
2931 prog_data->base.dispatch_mode = DISPATCH_MODE_SIMD8;
2932
2933 fs_visitor v(compiler, log_data, mem_ctx, key, &prog_data->base.base,
2934 NULL, /* prog; Only used for TEXTURE_RECTANGLE on gen < 8 */
2935 shader, 8, shader_time_index);
2936 if (!v.run_vs()) {
2937 if (error_str)
2938 *error_str = ralloc_strdup(mem_ctx, v.fail_msg);
2939
2940 return NULL;
2941 }
2942
2943 prog_data->base.base.dispatch_grf_start_reg = v.payload.num_regs;
2944
2945 fs_generator g(compiler, log_data, mem_ctx,
2946 &prog_data->base.base, v.promoted_constants,
2947 v.runtime_check_aads_emit, MESA_SHADER_VERTEX);
2948 if (INTEL_DEBUG & DEBUG_VS) {
2949 const char *debug_name =
2950 ralloc_asprintf(mem_ctx, "%s vertex shader %s",
2951 shader->info.label ? shader->info.label :
2952 "unnamed",
2953 shader->info.name);
2954
2955 g.enable_debug(debug_name);
2956 }
2957 g.generate_code(v.cfg, 8);
2958 assembly = g.get_assembly();
2959 }
2960
2961 if (!assembly) {
2962 prog_data->base.dispatch_mode = DISPATCH_MODE_4X2_DUAL_OBJECT;
2963
2964 vec4_vs_visitor v(compiler, log_data, key, prog_data,
2965 shader, mem_ctx, shader_time_index);
2966 if (!v.run()) {
2967 if (error_str)
2968 *error_str = ralloc_strdup(mem_ctx, v.fail_msg);
2969
2970 return NULL;
2971 }
2972
2973 assembly = brw_vec4_generate_assembly(compiler, log_data, mem_ctx,
2974 shader, &prog_data->base, v.cfg);
2975 }
2976
2977 return assembly;
2978 }
2979
2980 } /* extern "C" */