pan/mdg: Skip r1.w write where possible
[mesa.git] / src / panfrost / midgard / midgard_schedule.c
1 /*
2 * Copyright (C) 2018-2019 Alyssa Rosenzweig <alyssa@rosenzweig.io>
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 FROM,
20 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 * SOFTWARE.
22 */
23
24 #include "compiler.h"
25 #include "midgard_ops.h"
26 #include "midgard_quirks.h"
27 #include "util/u_memory.h"
28 #include "util/u_math.h"
29 #include "util/half_float.h"
30
31 /* Scheduling for Midgard is complicated, to say the least. ALU instructions
32 * must be grouped into VLIW bundles according to following model:
33 *
34 * [VMUL] [SADD]
35 * [VADD] [SMUL] [VLUT]
36 *
37 * A given instruction can execute on some subset of the units (or a few can
38 * execute on all). Instructions can be either vector or scalar; only scalar
39 * instructions can execute on SADD/SMUL units. Units on a given line execute
40 * in parallel. Subsequent lines execute separately and can pass results
41 * directly via pipeline registers r24/r25, bypassing the register file.
42 *
43 * A bundle can optionally have 128-bits of embedded constants, shared across
44 * all of the instructions within a bundle.
45 *
46 * Instructions consuming conditionals (branches and conditional selects)
47 * require their condition to be written into the conditional register (r31)
48 * within the same bundle they are consumed.
49 *
50 * Fragment writeout requires its argument to be written in full within the
51 * same bundle as the branch, with no hanging dependencies.
52 *
53 * Load/store instructions are also in bundles of simply two instructions, and
54 * texture instructions have no bundling.
55 *
56 * -------------------------------------------------------------------------
57 *
58 */
59
60 /* We create the dependency graph with per-byte granularity */
61
62 #define BYTE_COUNT 16
63
64 static void
65 add_dependency(struct util_dynarray *table, unsigned index, uint16_t mask, midgard_instruction **instructions, unsigned child)
66 {
67 for (unsigned i = 0; i < BYTE_COUNT; ++i) {
68 if (!(mask & (1 << i)))
69 continue;
70
71 struct util_dynarray *parents = &table[(BYTE_COUNT * index) + i];
72
73 util_dynarray_foreach(parents, unsigned, parent) {
74 BITSET_WORD *dependents = instructions[*parent]->dependents;
75
76 /* Already have the dependency */
77 if (BITSET_TEST(dependents, child))
78 continue;
79
80 BITSET_SET(dependents, child);
81 instructions[child]->nr_dependencies++;
82 }
83 }
84 }
85
86 static void
87 mark_access(struct util_dynarray *table, unsigned index, uint16_t mask, unsigned parent)
88 {
89 for (unsigned i = 0; i < BYTE_COUNT; ++i) {
90 if (!(mask & (1 << i)))
91 continue;
92
93 util_dynarray_append(&table[(BYTE_COUNT * index) + i], unsigned, parent);
94 }
95 }
96
97 static void
98 mir_create_dependency_graph(midgard_instruction **instructions, unsigned count, unsigned node_count)
99 {
100 size_t sz = node_count * BYTE_COUNT;
101
102 struct util_dynarray *last_read = calloc(sizeof(struct util_dynarray), sz);
103 struct util_dynarray *last_write = calloc(sizeof(struct util_dynarray), sz);
104
105 for (unsigned i = 0; i < sz; ++i) {
106 util_dynarray_init(&last_read[i], NULL);
107 util_dynarray_init(&last_write[i], NULL);
108 }
109
110 /* Initialize dependency graph */
111 for (unsigned i = 0; i < count; ++i) {
112 instructions[i]->dependents =
113 calloc(BITSET_WORDS(count), sizeof(BITSET_WORD));
114
115 instructions[i]->nr_dependencies = 0;
116 }
117
118 /* Populate dependency graph */
119 for (signed i = count - 1; i >= 0; --i) {
120 if (instructions[i]->compact_branch)
121 continue;
122
123 unsigned dest = instructions[i]->dest;
124 unsigned mask = mir_bytemask(instructions[i]);
125
126 mir_foreach_src((*instructions), s) {
127 unsigned src = instructions[i]->src[s];
128
129 if (src < node_count) {
130 unsigned readmask = mir_bytemask_of_read_components(instructions[i], src);
131 add_dependency(last_write, src, readmask, instructions, i);
132 }
133 }
134
135 if (dest < node_count) {
136 add_dependency(last_read, dest, mask, instructions, i);
137 add_dependency(last_write, dest, mask, instructions, i);
138 mark_access(last_write, dest, mask, i);
139 }
140
141 mir_foreach_src((*instructions), s) {
142 unsigned src = instructions[i]->src[s];
143
144 if (src < node_count) {
145 unsigned readmask = mir_bytemask_of_read_components(instructions[i], src);
146 mark_access(last_read, src, readmask, i);
147 }
148 }
149 }
150
151 /* If there is a branch, all instructions depend on it, as interblock
152 * execution must be purely in-order */
153
154 if (instructions[count - 1]->compact_branch) {
155 BITSET_WORD *dependents = instructions[count - 1]->dependents;
156
157 for (signed i = count - 2; i >= 0; --i) {
158 if (BITSET_TEST(dependents, i))
159 continue;
160
161 BITSET_SET(dependents, i);
162 instructions[i]->nr_dependencies++;
163 }
164 }
165
166 /* Free the intermediate structures */
167 for (unsigned i = 0; i < sz; ++i) {
168 util_dynarray_fini(&last_read[i]);
169 util_dynarray_fini(&last_write[i]);
170 }
171
172 free(last_read);
173 free(last_write);
174 }
175
176 /* Does the mask cover more than a scalar? */
177
178 static bool
179 is_single_component_mask(unsigned mask)
180 {
181 int components = 0;
182
183 for (int c = 0; c < 8; ++c) {
184 if (mask & (1 << c))
185 components++;
186 }
187
188 return components == 1;
189 }
190
191 /* Helpers for scheudling */
192
193 static bool
194 mir_is_scalar(midgard_instruction *ains)
195 {
196 /* Do we try to use it as a vector op? */
197 if (!is_single_component_mask(ains->mask))
198 return false;
199
200 /* Otherwise, check mode hazards */
201 bool could_scalar = true;
202 unsigned szd = nir_alu_type_get_type_size(ains->dest_type);
203 unsigned sz0 = nir_alu_type_get_type_size(ains->src_types[0]);
204 unsigned sz1 = nir_alu_type_get_type_size(ains->src_types[1]);
205
206 /* Only 16/32-bit can run on a scalar unit */
207 could_scalar &= (szd == 16) || (szd == 32);
208
209 if (ains->src[0] != ~0)
210 could_scalar &= (sz0 == 16) || (sz0 == 32);
211
212 if (ains->src[1] != ~0)
213 could_scalar &= (sz1 == 16) || (sz1 == 32);
214
215 return could_scalar;
216 }
217
218 /* How many bytes does this ALU instruction add to the bundle? */
219
220 static unsigned
221 bytes_for_instruction(midgard_instruction *ains)
222 {
223 if (ains->unit & UNITS_ANY_VECTOR)
224 return sizeof(midgard_reg_info) + sizeof(midgard_vector_alu);
225 else if (ains->unit == ALU_ENAB_BRANCH)
226 return sizeof(midgard_branch_extended);
227 else if (ains->compact_branch)
228 return sizeof(ains->br_compact);
229 else
230 return sizeof(midgard_reg_info) + sizeof(midgard_scalar_alu);
231 }
232
233 /* We would like to flatten the linked list of midgard_instructions in a bundle
234 * to an array of pointers on the heap for easy indexing */
235
236 static midgard_instruction **
237 flatten_mir(midgard_block *block, unsigned *len)
238 {
239 *len = list_length(&block->base.instructions);
240
241 if (!(*len))
242 return NULL;
243
244 midgard_instruction **instructions =
245 calloc(sizeof(midgard_instruction *), *len);
246
247 unsigned i = 0;
248
249 mir_foreach_instr_in_block(block, ins)
250 instructions[i++] = ins;
251
252 return instructions;
253 }
254
255 /* The worklist is the set of instructions that can be scheduled now; that is,
256 * the set of instructions with no remaining dependencies */
257
258 static void
259 mir_initialize_worklist(BITSET_WORD *worklist, midgard_instruction **instructions, unsigned count)
260 {
261 for (unsigned i = 0; i < count; ++i) {
262 if (instructions[i]->nr_dependencies == 0)
263 BITSET_SET(worklist, i);
264 }
265 }
266
267 /* Update the worklist after an instruction terminates. Remove its edges from
268 * the graph and if that causes any node to have no dependencies, add it to the
269 * worklist */
270
271 static void
272 mir_update_worklist(
273 BITSET_WORD *worklist, unsigned count,
274 midgard_instruction **instructions, midgard_instruction *done)
275 {
276 /* Sanity check: if no instruction terminated, there is nothing to do.
277 * If the instruction that terminated had dependencies, that makes no
278 * sense and means we messed up the worklist. Finally, as the purpose
279 * of this routine is to update dependents, we abort early if there are
280 * no dependents defined. */
281
282 if (!done)
283 return;
284
285 assert(done->nr_dependencies == 0);
286
287 if (!done->dependents)
288 return;
289
290 /* We have an instruction with dependents. Iterate each dependent to
291 * remove one dependency (`done`), adding dependents to the worklist
292 * where possible. */
293
294 unsigned i;
295 BITSET_FOREACH_SET(i, done->dependents, count) {
296 assert(instructions[i]->nr_dependencies);
297
298 if (!(--instructions[i]->nr_dependencies))
299 BITSET_SET(worklist, i);
300 }
301
302 free(done->dependents);
303 }
304
305 /* While scheduling, we need to choose instructions satisfying certain
306 * criteria. As we schedule backwards, we choose the *last* instruction in the
307 * worklist to simulate in-order scheduling. Chosen instructions must satisfy a
308 * given predicate. */
309
310 struct midgard_predicate {
311 /* TAG or ~0 for dont-care */
312 unsigned tag;
313
314 /* True if we want to pop off the chosen instruction */
315 bool destructive;
316
317 /* For ALU, choose only this unit */
318 unsigned unit;
319
320 /* State for bundle constants. constants is the actual constants
321 * for the bundle. constant_count is the number of bytes (up to
322 * 16) currently in use for constants. When picking in destructive
323 * mode, the constants array will be updated, and the instruction
324 * will be adjusted to index into the constants array */
325
326 midgard_constants *constants;
327 unsigned constant_mask;
328 bool blend_constant;
329
330 /* Exclude this destination (if not ~0) */
331 unsigned exclude;
332
333 /* Don't schedule instructions consuming conditionals (since we already
334 * scheduled one). Excludes conditional branches and csel */
335 bool no_cond;
336
337 /* Require (or reject) a minimal mask and (if nonzero) given
338 * destination. Used for writeout optimizations */
339
340 unsigned mask;
341 unsigned no_mask;
342 unsigned dest;
343
344 /* For VADD/VLUT whether to only/never schedule imov/fmov instructions
345 * This allows non-move instructions to get priority on each unit */
346 bool moves;
347
348 /* For load/store: how many pipeline registers are in use? The two
349 * scheduled instructions cannot use more than the 256-bits of pipeline
350 * space available or RA will fail (as it would run out of pipeline
351 * registers and fail to spill without breaking the schedule) */
352
353 unsigned pipeline_count;
354 };
355
356 static bool
357 mir_adjust_constant(midgard_instruction *ins, unsigned src,
358 unsigned *bundle_constant_mask,
359 unsigned *comp_mapping,
360 uint8_t *bundle_constants,
361 bool upper)
362 {
363 unsigned type_size = nir_alu_type_get_type_size(ins->src_types[src]) / 8;
364 unsigned type_shift = util_logbase2(type_size);
365 unsigned max_comp = mir_components_for_type(ins->src_types[src]);
366 unsigned comp_mask = mir_from_bytemask(mir_round_bytemask_up(
367 mir_bytemask_of_read_components_index(ins, src),
368 type_size * 8),
369 type_size * 8);
370 unsigned type_mask = (1 << type_size) - 1;
371
372 /* Upper only makes sense for 16-bit */
373 if (type_size != 16 && upper)
374 return false;
375
376 /* For 16-bit, we need to stay on either upper or lower halves to avoid
377 * disrupting the swizzle */
378 unsigned start = upper ? 8 : 0;
379 unsigned length = (type_size == 2) ? 8 : 16;
380
381 for (unsigned comp = 0; comp < max_comp; comp++) {
382 if (!(comp_mask & (1 << comp)))
383 continue;
384
385 uint8_t *constantp = ins->constants.u8 + (type_size * comp);
386 unsigned best_reuse_bytes = 0;
387 signed best_place = -1;
388 unsigned i, j;
389
390 for (i = start; i < (start + length); i += type_size) {
391 unsigned reuse_bytes = 0;
392
393 for (j = 0; j < type_size; j++) {
394 if (!(*bundle_constant_mask & (1 << (i + j))))
395 continue;
396 if (constantp[j] != bundle_constants[i + j])
397 break;
398 if ((i + j) > (start + length))
399 break;
400
401 reuse_bytes++;
402 }
403
404 /* Select the place where existing bytes can be
405 * reused so we leave empty slots to others
406 */
407 if (j == type_size &&
408 (reuse_bytes > best_reuse_bytes || best_place < 0)) {
409 best_reuse_bytes = reuse_bytes;
410 best_place = i;
411 break;
412 }
413 }
414
415 /* This component couldn't fit in the remaining constant slot,
416 * no need check the remaining components, bail out now
417 */
418 if (best_place < 0)
419 return false;
420
421 memcpy(&bundle_constants[i], constantp, type_size);
422 *bundle_constant_mask |= type_mask << best_place;
423 comp_mapping[comp] = best_place >> type_shift;
424 }
425
426 return true;
427 }
428
429 /* For an instruction that can fit, adjust it to fit and update the constants
430 * array, in destructive mode. Returns whether the fitting was successful. */
431
432 static bool
433 mir_adjust_constants(midgard_instruction *ins,
434 struct midgard_predicate *pred,
435 bool destructive)
436 {
437 /* Blend constants dominate */
438 if (ins->has_blend_constant) {
439 if (pred->constant_mask)
440 return false;
441 else if (destructive) {
442 pred->blend_constant = true;
443 pred->constant_mask = 0xffff;
444 return true;
445 }
446 }
447
448 /* No constant, nothing to adjust */
449 if (!ins->has_constants)
450 return true;
451
452 unsigned r_constant = SSA_FIXED_REGISTER(REGISTER_CONSTANT);
453 unsigned bundle_constant_mask = pred->constant_mask;
454 unsigned comp_mapping[2][16] = { };
455 uint8_t bundle_constants[16];
456
457 memcpy(bundle_constants, pred->constants, 16);
458
459 /* Let's try to find a place for each active component of the constant
460 * register.
461 */
462 for (unsigned src = 0; src < 2; ++src) {
463 if (ins->src[src] != SSA_FIXED_REGISTER(REGISTER_CONSTANT))
464 continue;
465
466 /* First, try lower half (or whole for !16) */
467 if (mir_adjust_constant(ins, src, &bundle_constant_mask,
468 comp_mapping[src], bundle_constants, false))
469 continue;
470
471 /* Next, try upper half */
472 if (mir_adjust_constant(ins, src, &bundle_constant_mask,
473 comp_mapping[src], bundle_constants, true))
474 continue;
475
476 /* Otherwise bail */
477 return false;
478 }
479
480 /* If non-destructive, we're done */
481 if (!destructive)
482 return true;
483
484 /* Otherwise update the constant_mask and constant values */
485 pred->constant_mask = bundle_constant_mask;
486 memcpy(pred->constants, bundle_constants, 16);
487
488 /* Use comp_mapping as a swizzle */
489 mir_foreach_src(ins, s) {
490 if (ins->src[s] == r_constant)
491 mir_compose_swizzle(ins->swizzle[s], comp_mapping[s], ins->swizzle[s]);
492 }
493
494 return true;
495 }
496
497 /* Conservative estimate of the pipeline registers required for load/store */
498
499 static unsigned
500 mir_pipeline_count(midgard_instruction *ins)
501 {
502 unsigned bytecount = 0;
503
504 mir_foreach_src(ins, i) {
505 /* Skip empty source */
506 if (ins->src[i] == ~0) continue;
507
508 unsigned bytemask = mir_bytemask_of_read_components_index(ins, i);
509
510 unsigned max = util_logbase2(bytemask) + 1;
511 bytecount += max;
512 }
513
514 return DIV_ROUND_UP(bytecount, 16);
515 }
516
517 /* Matches FADD x, x with modifiers compatible. Since x + x = x * 2, for
518 * any x including of the form f(y) for some swizzle/abs/neg function f */
519
520 static bool
521 mir_is_add_2(midgard_instruction *ins)
522 {
523 if (ins->alu.op != midgard_alu_op_fadd)
524 return false;
525
526 if (ins->src[0] != ins->src[1])
527 return false;
528
529 if (ins->src_types[0] != ins->src_types[1])
530 return false;
531
532 for (unsigned i = 0; i < MIR_VEC_COMPONENTS; ++i) {
533 if (ins->swizzle[0][i] != ins->swizzle[1][i])
534 return false;
535 }
536
537 if (ins->src_abs[0] != ins->src_abs[1])
538 return false;
539
540 if (ins->src_neg[0] != ins->src_neg[1])
541 return false;
542
543 return true;
544 }
545
546 static void
547 mir_adjust_unit(midgard_instruction *ins, unsigned unit)
548 {
549 /* FADD x, x = FMUL x, #2 */
550 if (mir_is_add_2(ins) && (unit & (UNITS_MUL | UNIT_VLUT))) {
551 ins->alu.op = midgard_alu_op_fmul;
552
553 ins->src[1] = ~0;
554 ins->src_abs[1] = false;
555 ins->src_neg[1] = false;
556
557 ins->has_inline_constant = true;
558 ins->inline_constant = _mesa_float_to_half(2.0);
559 }
560 }
561
562 static unsigned
563 mir_has_unit(midgard_instruction *ins, unsigned unit)
564 {
565 if (alu_opcode_props[ins->alu.op].props & unit)
566 return true;
567
568 /* FADD x, x can run on any adder or any multiplier */
569 if (mir_is_add_2(ins))
570 return true;
571
572 return false;
573 }
574
575 static midgard_instruction *
576 mir_choose_instruction(
577 midgard_instruction **instructions,
578 BITSET_WORD *worklist, unsigned count,
579 struct midgard_predicate *predicate)
580 {
581 /* Parse the predicate */
582 unsigned tag = predicate->tag;
583 bool alu = tag == TAG_ALU_4;
584 bool ldst = tag == TAG_LOAD_STORE_4;
585 unsigned unit = predicate->unit;
586 bool branch = alu && (unit == ALU_ENAB_BR_COMPACT);
587 bool scalar = (unit != ~0) && (unit & UNITS_SCALAR);
588 bool no_cond = predicate->no_cond;
589
590 unsigned mask = predicate->mask;
591 unsigned dest = predicate->dest;
592 bool needs_dest = mask & 0xF;
593
594 /* Iterate to find the best instruction satisfying the predicate */
595 unsigned i;
596
597 signed best_index = -1;
598 bool best_conditional = false;
599
600 /* Enforce a simple metric limiting distance to keep down register
601 * pressure. TOOD: replace with liveness tracking for much better
602 * results */
603
604 unsigned max_active = 0;
605 unsigned max_distance = 6;
606
607 BITSET_FOREACH_SET(i, worklist, count) {
608 max_active = MAX2(max_active, i);
609 }
610
611 BITSET_FOREACH_SET(i, worklist, count) {
612 bool is_move = alu &&
613 (instructions[i]->alu.op == midgard_alu_op_imov ||
614 instructions[i]->alu.op == midgard_alu_op_fmov);
615
616 if ((max_active - i) >= max_distance)
617 continue;
618
619 if (tag != ~0 && instructions[i]->type != tag)
620 continue;
621
622 if (predicate->exclude != ~0 && instructions[i]->dest == predicate->exclude)
623 continue;
624
625 if (alu && !branch && !(mir_has_unit(instructions[i], unit)))
626 continue;
627
628 if ((unit == UNIT_VLUT || unit == UNIT_VADD) && (predicate->moves != is_move))
629 continue;
630
631 if (branch && !instructions[i]->compact_branch)
632 continue;
633
634 if (alu && scalar && !mir_is_scalar(instructions[i]))
635 continue;
636
637 if (alu && !mir_adjust_constants(instructions[i], predicate, false))
638 continue;
639
640 if (needs_dest && instructions[i]->dest != dest)
641 continue;
642
643 if (mask && ((~instructions[i]->mask) & mask))
644 continue;
645
646 if (instructions[i]->mask & predicate->no_mask)
647 continue;
648
649 if (ldst && mir_pipeline_count(instructions[i]) + predicate->pipeline_count > 2)
650 continue;
651
652 bool conditional = alu && !branch && OP_IS_CSEL(instructions[i]->alu.op);
653 conditional |= (branch && instructions[i]->branch.conditional);
654
655 if (conditional && no_cond)
656 continue;
657
658 /* Simulate in-order scheduling */
659 if ((signed) i < best_index)
660 continue;
661
662 best_index = i;
663 best_conditional = conditional;
664 }
665
666
667 /* Did we find anything? */
668
669 if (best_index < 0)
670 return NULL;
671
672 /* If we found something, remove it from the worklist */
673 assert(best_index < count);
674
675 if (predicate->destructive) {
676 BITSET_CLEAR(worklist, best_index);
677
678 if (alu)
679 mir_adjust_constants(instructions[best_index], predicate, true);
680
681 if (ldst)
682 predicate->pipeline_count += mir_pipeline_count(instructions[best_index]);
683
684 if (alu)
685 mir_adjust_unit(instructions[best_index], unit);
686
687 /* Once we schedule a conditional, we can't again */
688 predicate->no_cond |= best_conditional;
689 }
690
691 return instructions[best_index];
692 }
693
694 /* Still, we don't choose instructions in a vacuum. We need a way to choose the
695 * best bundle type (ALU, load/store, texture). Nondestructive. */
696
697 static unsigned
698 mir_choose_bundle(
699 midgard_instruction **instructions,
700 BITSET_WORD *worklist, unsigned count)
701 {
702 /* At the moment, our algorithm is very simple - use the bundle of the
703 * best instruction, regardless of what else could be scheduled
704 * alongside it. This is not optimal but it works okay for in-order */
705
706 struct midgard_predicate predicate = {
707 .tag = ~0,
708 .destructive = false,
709 .exclude = ~0
710 };
711
712 midgard_instruction *chosen = mir_choose_instruction(instructions, worklist, count, &predicate);
713
714 if (chosen)
715 return chosen->type;
716 else
717 return ~0;
718 }
719
720 /* We want to choose an ALU instruction filling a given unit */
721 static void
722 mir_choose_alu(midgard_instruction **slot,
723 midgard_instruction **instructions,
724 BITSET_WORD *worklist, unsigned len,
725 struct midgard_predicate *predicate,
726 unsigned unit)
727 {
728 /* Did we already schedule to this slot? */
729 if ((*slot) != NULL)
730 return;
731
732 /* Try to schedule something, if not */
733 predicate->unit = unit;
734 *slot = mir_choose_instruction(instructions, worklist, len, predicate);
735
736 /* Store unit upon scheduling */
737 if (*slot && !((*slot)->compact_branch))
738 (*slot)->unit = unit;
739 }
740
741 /* When we are scheduling a branch/csel, we need the consumed condition in the
742 * same block as a pipeline register. There are two options to enable this:
743 *
744 * - Move the conditional into the bundle. Preferred, but only works if the
745 * conditional is used only once and is from this block.
746 * - Copy the conditional.
747 *
748 * We search for the conditional. If it's in this block, single-use, and
749 * without embedded constants, we schedule it immediately. Otherwise, we
750 * schedule a move for it.
751 *
752 * mir_comparison_mobile is a helper to find the moveable condition.
753 */
754
755 static unsigned
756 mir_comparison_mobile(
757 compiler_context *ctx,
758 midgard_instruction **instructions,
759 struct midgard_predicate *predicate,
760 unsigned count,
761 unsigned cond)
762 {
763 if (!mir_single_use(ctx, cond))
764 return ~0;
765
766 unsigned ret = ~0;
767
768 for (unsigned i = 0; i < count; ++i) {
769 if (instructions[i]->dest != cond)
770 continue;
771
772 /* Must fit in an ALU bundle */
773 if (instructions[i]->type != TAG_ALU_4)
774 return ~0;
775
776 /* If it would itself require a condition, that's recursive */
777 if (OP_IS_CSEL(instructions[i]->alu.op))
778 return ~0;
779
780 /* We'll need to rewrite to .w but that doesn't work for vector
781 * ops that don't replicate (ball/bany), so bail there */
782
783 if (GET_CHANNEL_COUNT(alu_opcode_props[instructions[i]->alu.op].props))
784 return ~0;
785
786 /* Ensure it will fit with constants */
787
788 if (!mir_adjust_constants(instructions[i], predicate, false))
789 return ~0;
790
791 /* Ensure it is written only once */
792
793 if (ret != ~0)
794 return ~0;
795 else
796 ret = i;
797 }
798
799 /* Inject constants now that we are sure we want to */
800 if (ret != ~0)
801 mir_adjust_constants(instructions[ret], predicate, true);
802
803 return ret;
804 }
805
806 /* Using the information about the moveable conditional itself, we either pop
807 * that condition off the worklist for use now, or create a move to
808 * artificially schedule instead as a fallback */
809
810 static midgard_instruction *
811 mir_schedule_comparison(
812 compiler_context *ctx,
813 midgard_instruction **instructions,
814 struct midgard_predicate *predicate,
815 BITSET_WORD *worklist, unsigned count,
816 unsigned cond, bool vector, unsigned *swizzle,
817 midgard_instruction *user)
818 {
819 /* TODO: swizzle when scheduling */
820 unsigned comp_i =
821 (!vector && (swizzle[0] == 0)) ?
822 mir_comparison_mobile(ctx, instructions, predicate, count, cond) : ~0;
823
824 /* If we can, schedule the condition immediately */
825 if ((comp_i != ~0) && BITSET_TEST(worklist, comp_i)) {
826 assert(comp_i < count);
827 BITSET_CLEAR(worklist, comp_i);
828 return instructions[comp_i];
829 }
830
831 /* Otherwise, we insert a move */
832
833 midgard_instruction mov = v_mov(cond, cond);
834 mov.mask = vector ? 0xF : 0x1;
835 memcpy(mov.swizzle[1], swizzle, sizeof(mov.swizzle[1]));
836
837 return mir_insert_instruction_before(ctx, user, mov);
838 }
839
840 /* Most generally, we need instructions writing to r31 in the appropriate
841 * components */
842
843 static midgard_instruction *
844 mir_schedule_condition(compiler_context *ctx,
845 struct midgard_predicate *predicate,
846 BITSET_WORD *worklist, unsigned count,
847 midgard_instruction **instructions,
848 midgard_instruction *last)
849 {
850 /* For a branch, the condition is the only argument; for csel, third */
851 bool branch = last->compact_branch;
852 unsigned condition_index = branch ? 0 : 2;
853
854 /* csel_v is vector; otherwise, conditions are scalar */
855 bool vector = !branch && OP_IS_CSEL_V(last->alu.op);
856
857 /* Grab the conditional instruction */
858
859 midgard_instruction *cond = mir_schedule_comparison(
860 ctx, instructions, predicate, worklist, count, last->src[condition_index],
861 vector, last->swizzle[2], last);
862
863 /* We have exclusive reign over this (possibly move) conditional
864 * instruction. We can rewrite into a pipeline conditional register */
865
866 predicate->exclude = cond->dest;
867 cond->dest = SSA_FIXED_REGISTER(31);
868
869 if (!vector) {
870 cond->mask = (1 << COMPONENT_W);
871
872 mir_foreach_src(cond, s) {
873 if (cond->src[s] == ~0)
874 continue;
875
876 for (unsigned q = 0; q < 4; ++q)
877 cond->swizzle[s][q + COMPONENT_W] = cond->swizzle[s][q];
878 }
879 }
880
881 /* Schedule the unit: csel is always in the latter pipeline, so a csel
882 * condition must be in the former pipeline stage (vmul/sadd),
883 * depending on scalar/vector of the instruction itself. A branch must
884 * be written from the latter pipeline stage and a branch condition is
885 * always scalar, so it is always in smul (exception: ball/bany, which
886 * will be vadd) */
887
888 if (branch)
889 cond->unit = UNIT_SMUL;
890 else
891 cond->unit = vector ? UNIT_VMUL : UNIT_SADD;
892
893 return cond;
894 }
895
896 /* Schedules a single bundle of the given type */
897
898 static midgard_bundle
899 mir_schedule_texture(
900 midgard_instruction **instructions,
901 BITSET_WORD *worklist, unsigned len,
902 bool is_vertex)
903 {
904 struct midgard_predicate predicate = {
905 .tag = TAG_TEXTURE_4,
906 .destructive = true,
907 .exclude = ~0
908 };
909
910 midgard_instruction *ins =
911 mir_choose_instruction(instructions, worklist, len, &predicate);
912
913 mir_update_worklist(worklist, len, instructions, ins);
914
915 struct midgard_bundle out = {
916 .tag = ins->texture.op == TEXTURE_OP_BARRIER ?
917 TAG_TEXTURE_4_BARRIER : is_vertex ?
918 TAG_TEXTURE_4_VTX : TAG_TEXTURE_4,
919 .instruction_count = 1,
920 .instructions = { ins }
921 };
922
923 return out;
924 }
925
926 static midgard_bundle
927 mir_schedule_ldst(
928 midgard_instruction **instructions,
929 BITSET_WORD *worklist, unsigned len)
930 {
931 struct midgard_predicate predicate = {
932 .tag = TAG_LOAD_STORE_4,
933 .destructive = true,
934 .exclude = ~0
935 };
936
937 /* Try to pick two load/store ops. Second not gauranteed to exist */
938
939 midgard_instruction *ins =
940 mir_choose_instruction(instructions, worklist, len, &predicate);
941
942 midgard_instruction *pair =
943 mir_choose_instruction(instructions, worklist, len, &predicate);
944
945 struct midgard_bundle out = {
946 .tag = TAG_LOAD_STORE_4,
947 .instruction_count = pair ? 2 : 1,
948 .instructions = { ins, pair }
949 };
950
951 /* We have to update the worklist atomically, since the two
952 * instructions run concurrently (TODO: verify it's not pipelined) */
953
954 mir_update_worklist(worklist, len, instructions, ins);
955 mir_update_worklist(worklist, len, instructions, pair);
956
957 return out;
958 }
959
960 static void
961 mir_schedule_zs_write(
962 compiler_context *ctx,
963 struct midgard_predicate *predicate,
964 midgard_instruction **instructions,
965 BITSET_WORD *worklist, unsigned len,
966 midgard_instruction *branch,
967 midgard_instruction **smul,
968 midgard_instruction **vadd,
969 midgard_instruction **vlut,
970 bool stencil)
971 {
972 bool success = false;
973 unsigned idx = stencil ? 3 : 2;
974 unsigned src = (branch->src[0] == ~0) ? SSA_FIXED_REGISTER(1) : branch->src[idx];
975
976 predicate->dest = src;
977 predicate->mask = 0x1;
978
979 midgard_instruction **units[] = { smul, vadd, vlut };
980 unsigned unit_names[] = { UNIT_SMUL, UNIT_VADD, UNIT_VLUT };
981
982 for (unsigned i = 0; i < 3; ++i) {
983 if (*(units[i]))
984 continue;
985
986 predicate->unit = unit_names[i];
987 midgard_instruction *ins =
988 mir_choose_instruction(instructions, worklist, len, predicate);
989
990 if (ins) {
991 ins->unit = unit_names[i];
992 *(units[i]) = ins;
993 success |= true;
994 break;
995 }
996 }
997
998 predicate->dest = predicate->mask = 0;
999
1000 if (success)
1001 return;
1002
1003 midgard_instruction *mov = ralloc(ctx, midgard_instruction);
1004 *mov = v_mov(src, make_compiler_temp(ctx));
1005 mov->mask = 0x1;
1006
1007 branch->src[idx] = mov->dest;
1008
1009 if (stencil) {
1010 unsigned swizzle = (branch->src[0] == ~0) ? COMPONENT_Y : COMPONENT_X;
1011
1012 for (unsigned c = 0; c < 16; ++c)
1013 mov->swizzle[1][c] = swizzle;
1014 }
1015
1016 for (unsigned i = 0; i < 3; ++i) {
1017 if (!(*(units[i]))) {
1018 *(units[i]) = mov;
1019 mov->unit = unit_names[i];
1020 return;
1021 }
1022 }
1023
1024 unreachable("Could not schedule Z/S move to any unit");
1025 }
1026
1027 static midgard_bundle
1028 mir_schedule_alu(
1029 compiler_context *ctx,
1030 midgard_instruction **instructions,
1031 BITSET_WORD *worklist, unsigned len)
1032 {
1033 struct midgard_bundle bundle = {};
1034
1035 unsigned bytes_emitted = sizeof(bundle.control);
1036
1037 struct midgard_predicate predicate = {
1038 .tag = TAG_ALU_4,
1039 .destructive = true,
1040 .exclude = ~0,
1041 .constants = &bundle.constants
1042 };
1043
1044 midgard_instruction *vmul = NULL;
1045 midgard_instruction *vadd = NULL;
1046 midgard_instruction *vlut = NULL;
1047 midgard_instruction *smul = NULL;
1048 midgard_instruction *sadd = NULL;
1049 midgard_instruction *branch = NULL;
1050
1051 mir_choose_alu(&branch, instructions, worklist, len, &predicate, ALU_ENAB_BR_COMPACT);
1052 mir_update_worklist(worklist, len, instructions, branch);
1053 unsigned writeout = branch ? branch->writeout : 0;
1054
1055 if (branch && branch->branch.conditional) {
1056 midgard_instruction *cond = mir_schedule_condition(ctx, &predicate, worklist, len, instructions, branch);
1057
1058 if (cond->unit == UNIT_VADD)
1059 vadd = cond;
1060 else if (cond->unit == UNIT_SMUL)
1061 smul = cond;
1062 else
1063 unreachable("Bad condition");
1064 }
1065
1066 /* If we have a render target reference, schedule a move for it. Since
1067 * this will be in sadd, we boost this to prevent scheduling csel into
1068 * smul */
1069
1070 if (writeout && (branch->constants.u32[0] || ctx->is_blend)) {
1071 sadd = ralloc(ctx, midgard_instruction);
1072 *sadd = v_mov(~0, make_compiler_temp(ctx));
1073 sadd->unit = UNIT_SADD;
1074 sadd->mask = 0x1;
1075 sadd->has_inline_constant = true;
1076 sadd->inline_constant = branch->constants.u32[0];
1077 branch->src[1] = sadd->dest;
1078 branch->src_types[1] = sadd->dest_type;
1079
1080 /* Mask off any conditionals. Could be optimized to just scalar
1081 * conditionals TODO */
1082 predicate.no_cond = true;
1083 }
1084
1085 if (writeout) {
1086 /* Propagate up */
1087 bundle.last_writeout = branch->last_writeout;
1088 }
1089
1090 /* When MRT is in use, writeout loops require r1.w to be filled (with a
1091 * return address? by symmetry with Bifrost, etc), at least for blend
1092 * shaders to work properly. When MRT is not in use (including on SFBD
1093 * GPUs), this is not needed. Blend shaders themselves don't know if
1094 * they are paired with MRT or not so they always need this, at least
1095 * on MFBD GPUs. */
1096
1097 if (writeout && (ctx->is_blend || ctx->writeout_branch[1])) {
1098 vadd = ralloc(ctx, midgard_instruction);
1099 *vadd = v_mov(~0, make_compiler_temp(ctx));
1100
1101 if (!ctx->is_blend) {
1102 vadd->alu.op = midgard_alu_op_iadd;
1103 vadd->src[0] = SSA_FIXED_REGISTER(31);
1104 vadd->src_types[0] = nir_type_uint32;
1105
1106 for (unsigned c = 0; c < 16; ++c)
1107 vadd->swizzle[0][c] = COMPONENT_X;
1108
1109 vadd->has_inline_constant = true;
1110 vadd->inline_constant = 0;
1111 } else {
1112 vadd->src[1] = SSA_FIXED_REGISTER(1);
1113 vadd->src_types[0] = nir_type_uint32;
1114
1115 for (unsigned c = 0; c < 16; ++c)
1116 vadd->swizzle[1][c] = COMPONENT_W;
1117 }
1118
1119 vadd->unit = UNIT_VADD;
1120 vadd->mask = 0x1;
1121 branch->dest = vadd->dest;
1122 branch->dest_type = vadd->dest_type;
1123 }
1124
1125 if (writeout & PAN_WRITEOUT_Z)
1126 mir_schedule_zs_write(ctx, &predicate, instructions, worklist, len, branch, &smul, &vadd, &vlut, false);
1127
1128 if (writeout & PAN_WRITEOUT_S)
1129 mir_schedule_zs_write(ctx, &predicate, instructions, worklist, len, branch, &smul, &vadd, &vlut, true);
1130
1131 mir_choose_alu(&smul, instructions, worklist, len, &predicate, UNIT_SMUL);
1132
1133 for (unsigned moves = 0; moves < 2; ++moves) {
1134 predicate.moves = moves;
1135 predicate.no_mask = writeout ? (1 << 3) : 0;
1136 mir_choose_alu(&vlut, instructions, worklist, len, &predicate, UNIT_VLUT);
1137 predicate.no_mask = 0;
1138 mir_choose_alu(&vadd, instructions, worklist, len, &predicate, UNIT_VADD);
1139 }
1140
1141 mir_update_worklist(worklist, len, instructions, vlut);
1142 mir_update_worklist(worklist, len, instructions, vadd);
1143 mir_update_worklist(worklist, len, instructions, smul);
1144
1145 bool vadd_csel = vadd && OP_IS_CSEL(vadd->alu.op);
1146 bool smul_csel = smul && OP_IS_CSEL(smul->alu.op);
1147
1148 if (vadd_csel || smul_csel) {
1149 midgard_instruction *ins = vadd_csel ? vadd : smul;
1150 midgard_instruction *cond = mir_schedule_condition(ctx, &predicate, worklist, len, instructions, ins);
1151
1152 if (cond->unit == UNIT_VMUL)
1153 vmul = cond;
1154 else if (cond->unit == UNIT_SADD)
1155 sadd = cond;
1156 else
1157 unreachable("Bad condition");
1158 }
1159
1160 /* Stage 2, let's schedule sadd before vmul for writeout */
1161 mir_choose_alu(&sadd, instructions, worklist, len, &predicate, UNIT_SADD);
1162
1163 /* Check if writeout reads its own register */
1164
1165 if (writeout) {
1166 midgard_instruction *stages[] = { sadd, vadd, smul, vlut };
1167 unsigned src = (branch->src[0] == ~0) ? SSA_FIXED_REGISTER(0) : branch->src[0];
1168 unsigned writeout_mask = 0x0;
1169 bool bad_writeout = false;
1170
1171 for (unsigned i = 0; i < ARRAY_SIZE(stages); ++i) {
1172 if (!stages[i])
1173 continue;
1174
1175 if (stages[i]->dest != src)
1176 continue;
1177
1178 writeout_mask |= stages[i]->mask;
1179 bad_writeout |= mir_has_arg(stages[i], branch->src[0]);
1180 }
1181
1182 /* It's possible we'll be able to schedule something into vmul
1183 * to fill r0. Let's peak into the future, trying to schedule
1184 * vmul specially that way. */
1185
1186 unsigned full_mask = 0xF;
1187
1188 if (!bad_writeout && writeout_mask != full_mask) {
1189 predicate.unit = UNIT_VMUL;
1190 predicate.dest = src;
1191 predicate.mask = writeout_mask ^ full_mask;
1192
1193 struct midgard_instruction *peaked =
1194 mir_choose_instruction(instructions, worklist, len, &predicate);
1195
1196 if (peaked) {
1197 vmul = peaked;
1198 vmul->unit = UNIT_VMUL;
1199 writeout_mask |= predicate.mask;
1200 assert(writeout_mask == full_mask);
1201 }
1202
1203 /* Cleanup */
1204 predicate.dest = predicate.mask = 0;
1205 }
1206
1207 /* Finally, add a move if necessary */
1208 if (bad_writeout || writeout_mask != full_mask) {
1209 unsigned temp = (branch->src[0] == ~0) ? SSA_FIXED_REGISTER(0) : make_compiler_temp(ctx);
1210
1211 vmul = ralloc(ctx, midgard_instruction);
1212 *vmul = v_mov(src, temp);
1213 vmul->unit = UNIT_VMUL;
1214 vmul->mask = full_mask ^ writeout_mask;
1215
1216 /* Rewrite to use our temp */
1217
1218 for (unsigned i = 0; i < ARRAY_SIZE(stages); ++i) {
1219 if (stages[i])
1220 mir_rewrite_index_dst_single(stages[i], src, temp);
1221 }
1222
1223 mir_rewrite_index_src_single(branch, src, temp);
1224 }
1225 }
1226
1227 mir_choose_alu(&vmul, instructions, worklist, len, &predicate, UNIT_VMUL);
1228
1229 mir_update_worklist(worklist, len, instructions, vmul);
1230 mir_update_worklist(worklist, len, instructions, sadd);
1231
1232 bundle.has_blend_constant = predicate.blend_constant;
1233 bundle.has_embedded_constants = predicate.constant_mask != 0;
1234
1235 unsigned padding = 0;
1236
1237 /* Now that we have finished scheduling, build up the bundle */
1238 midgard_instruction *stages[] = { vmul, sadd, vadd, smul, vlut, branch };
1239
1240 for (unsigned i = 0; i < ARRAY_SIZE(stages); ++i) {
1241 if (stages[i]) {
1242 bundle.control |= stages[i]->unit;
1243 bytes_emitted += bytes_for_instruction(stages[i]);
1244 bundle.instructions[bundle.instruction_count++] = stages[i];
1245
1246 /* If we branch, we can't spill to TLS since the store
1247 * instruction will never get executed. We could try to
1248 * break the bundle but this is probably easier for
1249 * now. */
1250
1251 if (branch)
1252 stages[i]->no_spill |= (1 << REG_CLASS_WORK);
1253 }
1254 }
1255
1256 /* Pad ALU op to nearest word */
1257
1258 if (bytes_emitted & 15) {
1259 padding = 16 - (bytes_emitted & 15);
1260 bytes_emitted += padding;
1261 }
1262
1263 /* Constants must always be quadwords */
1264 if (bundle.has_embedded_constants)
1265 bytes_emitted += 16;
1266
1267 /* Size ALU instruction for tag */
1268 bundle.tag = (TAG_ALU_4) + (bytes_emitted / 16) - 1;
1269
1270 /* MRT capable GPUs use a special writeout procedure */
1271 if (writeout && !(ctx->quirks & MIDGARD_NO_UPPER_ALU))
1272 bundle.tag += 4;
1273
1274 bundle.padding = padding;
1275 bundle.control |= bundle.tag;
1276
1277 return bundle;
1278 }
1279
1280 /* Schedule a single block by iterating its instruction to create bundles.
1281 * While we go, tally about the bundle sizes to compute the block size. */
1282
1283
1284 static void
1285 schedule_block(compiler_context *ctx, midgard_block *block)
1286 {
1287 /* Copy list to dynamic array */
1288 unsigned len = 0;
1289 midgard_instruction **instructions = flatten_mir(block, &len);
1290
1291 if (!len)
1292 return;
1293
1294 /* Calculate dependencies and initial worklist */
1295 unsigned node_count = ctx->temp_count + 1;
1296 mir_create_dependency_graph(instructions, len, node_count);
1297
1298 /* Allocate the worklist */
1299 size_t sz = BITSET_WORDS(len) * sizeof(BITSET_WORD);
1300 BITSET_WORD *worklist = calloc(sz, 1);
1301 mir_initialize_worklist(worklist, instructions, len);
1302
1303 struct util_dynarray bundles;
1304 util_dynarray_init(&bundles, NULL);
1305
1306 block->quadword_count = 0;
1307 unsigned blend_offset = 0;
1308
1309 for (;;) {
1310 unsigned tag = mir_choose_bundle(instructions, worklist, len);
1311 midgard_bundle bundle;
1312
1313 if (tag == TAG_TEXTURE_4)
1314 bundle = mir_schedule_texture(instructions, worklist, len, ctx->stage != MESA_SHADER_FRAGMENT);
1315 else if (tag == TAG_LOAD_STORE_4)
1316 bundle = mir_schedule_ldst(instructions, worklist, len);
1317 else if (tag == TAG_ALU_4)
1318 bundle = mir_schedule_alu(ctx, instructions, worklist, len);
1319 else
1320 break;
1321
1322 util_dynarray_append(&bundles, midgard_bundle, bundle);
1323
1324 if (bundle.has_blend_constant)
1325 blend_offset = block->quadword_count;
1326
1327 block->quadword_count += midgard_tag_props[bundle.tag].size;
1328 }
1329
1330 /* We emitted bundles backwards; copy into the block in reverse-order */
1331
1332 util_dynarray_init(&block->bundles, block);
1333 util_dynarray_foreach_reverse(&bundles, midgard_bundle, bundle) {
1334 util_dynarray_append(&block->bundles, midgard_bundle, *bundle);
1335 }
1336 util_dynarray_fini(&bundles);
1337
1338 /* Blend constant was backwards as well. blend_offset if set is
1339 * strictly positive, as an offset of zero would imply constants before
1340 * any instructions which is invalid in Midgard. TODO: blend constants
1341 * are broken if you spill since then quadword_count becomes invalid
1342 * XXX */
1343
1344 if (blend_offset)
1345 ctx->blend_constant_offset = ((ctx->quadword_count + block->quadword_count) - blend_offset - 1) * 0x10;
1346
1347 block->scheduled = true;
1348 ctx->quadword_count += block->quadword_count;
1349
1350 /* Reorder instructions to match bundled. First remove existing
1351 * instructions and then recreate the list */
1352
1353 mir_foreach_instr_in_block_safe(block, ins) {
1354 list_del(&ins->link);
1355 }
1356
1357 mir_foreach_instr_in_block_scheduled_rev(block, ins) {
1358 list_add(&ins->link, &block->base.instructions);
1359 }
1360
1361 free(instructions); /* Allocated by flatten_mir() */
1362 free(worklist);
1363 }
1364
1365 void
1366 midgard_schedule_program(compiler_context *ctx)
1367 {
1368 midgard_promote_uniforms(ctx);
1369
1370 /* Must be lowered right before scheduling */
1371 mir_squeeze_index(ctx);
1372 mir_lower_special_reads(ctx);
1373 mir_squeeze_index(ctx);
1374
1375 /* Lowering can introduce some dead moves */
1376
1377 mir_foreach_block(ctx, _block) {
1378 midgard_block *block = (midgard_block *) _block;
1379 midgard_opt_dead_move_eliminate(ctx, block);
1380 schedule_block(ctx, block);
1381 }
1382
1383 }