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