pan/midgard: Fix bundle dynarray leak
[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
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 free(last_read);
171 free(last_write);
172 }
173
174 /* Does the mask cover more than a scalar? */
175
176 static bool
177 is_single_component_mask(unsigned mask)
178 {
179 int components = 0;
180
181 for (int c = 0; c < 8; ++c) {
182 if (mask & (1 << c))
183 components++;
184 }
185
186 return components == 1;
187 }
188
189 /* Helpers for scheudling */
190
191 static bool
192 mir_is_scalar(midgard_instruction *ains)
193 {
194 /* Do we try to use it as a vector op? */
195 if (!is_single_component_mask(ains->mask))
196 return false;
197
198 /* Otherwise, check mode hazards */
199 bool could_scalar = true;
200
201 /* Only 16/32-bit can run on a scalar unit */
202 could_scalar &= ains->alu.reg_mode != midgard_reg_mode_8;
203 could_scalar &= ains->alu.reg_mode != midgard_reg_mode_64;
204 could_scalar &= ains->alu.dest_override == midgard_dest_override_none;
205
206 if (ains->alu.reg_mode == midgard_reg_mode_16) {
207 /* If we're running in 16-bit mode, we
208 * can't have any 8-bit sources on the
209 * scalar unit (since the scalar unit
210 * doesn't understand 8-bit) */
211
212 midgard_vector_alu_src s1 =
213 vector_alu_from_unsigned(ains->alu.src1);
214
215 could_scalar &= !s1.half;
216
217 midgard_vector_alu_src s2 =
218 vector_alu_from_unsigned(ains->alu.src2);
219
220 could_scalar &= !s2.half;
221 }
222
223 return could_scalar;
224 }
225
226 /* How many bytes does this ALU instruction add to the bundle? */
227
228 static unsigned
229 bytes_for_instruction(midgard_instruction *ains)
230 {
231 if (ains->unit & UNITS_ANY_VECTOR)
232 return sizeof(midgard_reg_info) + sizeof(midgard_vector_alu);
233 else if (ains->unit == ALU_ENAB_BRANCH)
234 return sizeof(midgard_branch_extended);
235 else if (ains->compact_branch)
236 return sizeof(ains->br_compact);
237 else
238 return sizeof(midgard_reg_info) + sizeof(midgard_scalar_alu);
239 }
240
241 /* We would like to flatten the linked list of midgard_instructions in a bundle
242 * to an array of pointers on the heap for easy indexing */
243
244 static midgard_instruction **
245 flatten_mir(midgard_block *block, unsigned *len)
246 {
247 *len = list_length(&block->instructions);
248
249 if (!(*len))
250 return NULL;
251
252 midgard_instruction **instructions =
253 calloc(sizeof(midgard_instruction *), *len);
254
255 unsigned i = 0;
256
257 mir_foreach_instr_in_block(block, ins)
258 instructions[i++] = ins;
259
260 return instructions;
261 }
262
263 /* The worklist is the set of instructions that can be scheduled now; that is,
264 * the set of instructions with no remaining dependencies */
265
266 static void
267 mir_initialize_worklist(BITSET_WORD *worklist, midgard_instruction **instructions, unsigned count)
268 {
269 for (unsigned i = 0; i < count; ++i) {
270 if (instructions[i]->nr_dependencies == 0)
271 BITSET_SET(worklist, i);
272 }
273 }
274
275 /* Update the worklist after an instruction terminates. Remove its edges from
276 * the graph and if that causes any node to have no dependencies, add it to the
277 * worklist */
278
279 static void
280 mir_update_worklist(
281 BITSET_WORD *worklist, unsigned count,
282 midgard_instruction **instructions, midgard_instruction *done)
283 {
284 /* Sanity check: if no instruction terminated, there is nothing to do.
285 * If the instruction that terminated had dependencies, that makes no
286 * sense and means we messed up the worklist. Finally, as the purpose
287 * of this routine is to update dependents, we abort early if there are
288 * no dependents defined. */
289
290 if (!done)
291 return;
292
293 assert(done->nr_dependencies == 0);
294
295 if (!done->dependents)
296 return;
297
298 /* We have an instruction with dependents. Iterate each dependent to
299 * remove one dependency (`done`), adding dependents to the worklist
300 * where possible. */
301
302 unsigned i;
303 BITSET_FOREACH_SET(i, done->dependents, count) {
304 assert(instructions[i]->nr_dependencies);
305
306 if (!(--instructions[i]->nr_dependencies))
307 BITSET_SET(worklist, i);
308 }
309
310 free(done->dependents);
311 }
312
313 /* While scheduling, we need to choose instructions satisfying certain
314 * criteria. As we schedule backwards, we choose the *last* instruction in the
315 * worklist to simulate in-order scheduling. Chosen instructions must satisfy a
316 * given predicate. */
317
318 struct midgard_predicate {
319 /* TAG or ~0 for dont-care */
320 unsigned tag;
321
322 /* True if we want to pop off the chosen instruction */
323 bool destructive;
324
325 /* For ALU, choose only this unit */
326 unsigned unit;
327
328 /* State for bundle constants. constants is the actual constants
329 * for the bundle. constant_count is the number of bytes (up to
330 * 16) currently in use for constants. When picking in destructive
331 * mode, the constants array will be updated, and the instruction
332 * will be adjusted to index into the constants array */
333
334 midgard_constants *constants;
335 unsigned constant_mask;
336 bool blend_constant;
337
338 /* Exclude this destination (if not ~0) */
339 unsigned exclude;
340
341 /* Don't schedule instructions consuming conditionals (since we already
342 * scheduled one). Excludes conditional branches and csel */
343 bool no_cond;
344
345 /* Require a minimal mask and (if nonzero) given destination. Used for
346 * writeout optimizations */
347
348 unsigned mask;
349 unsigned dest;
350 };
351
352 /* For an instruction that can fit, adjust it to fit and update the constants
353 * array, in destructive mode. Returns whether the fitting was successful. */
354
355 static bool
356 mir_adjust_constants(midgard_instruction *ins,
357 struct midgard_predicate *pred,
358 bool destructive)
359 {
360 /* Blend constants dominate */
361 if (ins->has_blend_constant) {
362 if (pred->constant_mask)
363 return false;
364 else if (destructive) {
365 pred->blend_constant = true;
366 pred->constant_mask = 0xffff;
367 return true;
368 }
369 }
370
371 /* No constant, nothing to adjust */
372 if (!ins->has_constants)
373 return true;
374
375 unsigned r_constant = SSA_FIXED_REGISTER(REGISTER_CONSTANT);
376 midgard_reg_mode reg_mode = ins->alu.reg_mode;
377
378 midgard_vector_alu_src const_src = { };
379
380 if (ins->src[0] == r_constant)
381 const_src = vector_alu_from_unsigned(ins->alu.src1);
382 else if (ins->src[1] == r_constant)
383 const_src = vector_alu_from_unsigned(ins->alu.src2);
384
385 unsigned type_size = mir_bytes_for_mode(reg_mode);
386
387 /* If the ALU is converting up we need to divide type_size by 2 */
388 if (const_src.half)
389 type_size /= 2;
390
391 unsigned max_comp = 16 / type_size;
392 unsigned comp_mask = mir_from_bytemask(mir_bytemask_of_read_components(ins, r_constant),
393 reg_mode);
394 unsigned type_mask = (1 << type_size) - 1;
395 unsigned bundle_constant_mask = pred->constant_mask;
396 unsigned comp_mapping[16] = { };
397 uint8_t bundle_constants[16];
398
399 memcpy(bundle_constants, pred->constants, 16);
400
401 /* Let's try to find a place for each active component of the constant
402 * register.
403 */
404 for (unsigned comp = 0; comp < max_comp; comp++) {
405 if (!(comp_mask & (1 << comp)))
406 continue;
407
408 uint8_t *constantp = ins->constants.u8 + (type_size * comp);
409 unsigned best_reuse_bytes = 0;
410 signed best_place = -1;
411 unsigned i, j;
412
413 for (i = 0; i < 16; i += type_size) {
414 unsigned reuse_bytes = 0;
415
416 for (j = 0; j < type_size; j++) {
417 if (!(bundle_constant_mask & (1 << (i + j))))
418 continue;
419 if (constantp[j] != bundle_constants[i + j])
420 break;
421
422 reuse_bytes++;
423 }
424
425 /* Select the place where existing bytes can be
426 * reused so we leave empty slots to others
427 */
428 if (j == type_size &&
429 (reuse_bytes > best_reuse_bytes || best_place < 0)) {
430 best_reuse_bytes = reuse_bytes;
431 best_place = i;
432 break;
433 }
434 }
435
436 /* This component couldn't fit in the remaining constant slot,
437 * no need check the remaining components, bail out now
438 */
439 if (best_place < 0)
440 return false;
441
442 memcpy(&bundle_constants[i], constantp, type_size);
443 bundle_constant_mask |= type_mask << best_place;
444 comp_mapping[comp] = best_place / type_size;
445 }
446
447 /* If non-destructive, we're done */
448 if (!destructive)
449 return true;
450
451 /* Otherwise update the constant_mask and constant values */
452 pred->constant_mask = bundle_constant_mask;
453 memcpy(pred->constants, bundle_constants, 16);
454
455 /* Use comp_mapping as a swizzle */
456 mir_foreach_src(ins, s) {
457 if (ins->src[s] == r_constant)
458 mir_compose_swizzle(ins->swizzle[s], comp_mapping, ins->swizzle[s]);
459 }
460
461 return true;
462 }
463
464 static midgard_instruction *
465 mir_choose_instruction(
466 midgard_instruction **instructions,
467 BITSET_WORD *worklist, unsigned count,
468 struct midgard_predicate *predicate)
469 {
470 /* Parse the predicate */
471 unsigned tag = predicate->tag;
472 bool alu = tag == TAG_ALU_4;
473 unsigned unit = predicate->unit;
474 bool branch = alu && (unit == ALU_ENAB_BR_COMPACT);
475 bool scalar = (unit != ~0) && (unit & UNITS_SCALAR);
476 bool no_cond = predicate->no_cond;
477
478 unsigned mask = predicate->mask;
479 unsigned dest = predicate->dest;
480 bool needs_dest = mask & 0xF;
481
482 /* Iterate to find the best instruction satisfying the predicate */
483 unsigned i;
484
485 signed best_index = -1;
486 bool best_conditional = false;
487
488 /* Enforce a simple metric limiting distance to keep down register
489 * pressure. TOOD: replace with liveness tracking for much better
490 * results */
491
492 unsigned max_active = 0;
493 unsigned max_distance = 6;
494
495 BITSET_FOREACH_SET(i, worklist, count) {
496 max_active = MAX2(max_active, i);
497 }
498
499 BITSET_FOREACH_SET(i, worklist, count) {
500 if ((max_active - i) >= max_distance)
501 continue;
502
503 if (tag != ~0 && instructions[i]->type != tag)
504 continue;
505
506 if (predicate->exclude != ~0 && instructions[i]->dest == predicate->exclude)
507 continue;
508
509 if (alu && !branch && !(alu_opcode_props[instructions[i]->alu.op].props & unit))
510 continue;
511
512 if (branch && !instructions[i]->compact_branch)
513 continue;
514
515 if (alu && scalar && !mir_is_scalar(instructions[i]))
516 continue;
517
518 if (alu && !mir_adjust_constants(instructions[i], predicate, false))
519 continue;
520
521 if (needs_dest && instructions[i]->dest != dest)
522 continue;
523
524 if (mask && ((~instructions[i]->mask) & mask))
525 continue;
526
527 bool conditional = alu && !branch && OP_IS_CSEL(instructions[i]->alu.op);
528 conditional |= (branch && instructions[i]->branch.conditional);
529
530 if (conditional && no_cond)
531 continue;
532
533 /* Simulate in-order scheduling */
534 if ((signed) i < best_index)
535 continue;
536
537 best_index = i;
538 best_conditional = conditional;
539 }
540
541
542 /* Did we find anything? */
543
544 if (best_index < 0)
545 return NULL;
546
547 /* If we found something, remove it from the worklist */
548 assert(best_index < count);
549
550 if (predicate->destructive) {
551 BITSET_CLEAR(worklist, best_index);
552
553 if (alu)
554 mir_adjust_constants(instructions[best_index], predicate, true);
555
556 /* Once we schedule a conditional, we can't again */
557 predicate->no_cond |= best_conditional;
558 }
559
560 return instructions[best_index];
561 }
562
563 /* Still, we don't choose instructions in a vacuum. We need a way to choose the
564 * best bundle type (ALU, load/store, texture). Nondestructive. */
565
566 static unsigned
567 mir_choose_bundle(
568 midgard_instruction **instructions,
569 BITSET_WORD *worklist, unsigned count)
570 {
571 /* At the moment, our algorithm is very simple - use the bundle of the
572 * best instruction, regardless of what else could be scheduled
573 * alongside it. This is not optimal but it works okay for in-order */
574
575 struct midgard_predicate predicate = {
576 .tag = ~0,
577 .destructive = false,
578 .exclude = ~0
579 };
580
581 midgard_instruction *chosen = mir_choose_instruction(instructions, worklist, count, &predicate);
582
583 if (chosen)
584 return chosen->type;
585 else
586 return ~0;
587 }
588
589 /* We want to choose an ALU instruction filling a given unit */
590 static void
591 mir_choose_alu(midgard_instruction **slot,
592 midgard_instruction **instructions,
593 BITSET_WORD *worklist, unsigned len,
594 struct midgard_predicate *predicate,
595 unsigned unit)
596 {
597 /* Did we already schedule to this slot? */
598 if ((*slot) != NULL)
599 return;
600
601 /* Try to schedule something, if not */
602 predicate->unit = unit;
603 *slot = mir_choose_instruction(instructions, worklist, len, predicate);
604
605 /* Store unit upon scheduling */
606 if (*slot && !((*slot)->compact_branch))
607 (*slot)->unit = unit;
608 }
609
610 /* When we are scheduling a branch/csel, we need the consumed condition in the
611 * same block as a pipeline register. There are two options to enable this:
612 *
613 * - Move the conditional into the bundle. Preferred, but only works if the
614 * conditional is used only once and is from this block.
615 * - Copy the conditional.
616 *
617 * We search for the conditional. If it's in this block, single-use, and
618 * without embedded constants, we schedule it immediately. Otherwise, we
619 * schedule a move for it.
620 *
621 * mir_comparison_mobile is a helper to find the moveable condition.
622 */
623
624 static unsigned
625 mir_comparison_mobile(
626 compiler_context *ctx,
627 midgard_instruction **instructions,
628 struct midgard_predicate *predicate,
629 unsigned count,
630 unsigned cond)
631 {
632 if (!mir_single_use(ctx, cond))
633 return ~0;
634
635 unsigned ret = ~0;
636
637 for (unsigned i = 0; i < count; ++i) {
638 if (instructions[i]->dest != cond)
639 continue;
640
641 /* Must fit in an ALU bundle */
642 if (instructions[i]->type != TAG_ALU_4)
643 return ~0;
644
645 /* If it would itself require a condition, that's recursive */
646 if (OP_IS_CSEL(instructions[i]->alu.op))
647 return ~0;
648
649 /* We'll need to rewrite to .w but that doesn't work for vector
650 * ops that don't replicate (ball/bany), so bail there */
651
652 if (GET_CHANNEL_COUNT(alu_opcode_props[instructions[i]->alu.op].props))
653 return ~0;
654
655 /* Ensure it will fit with constants */
656
657 if (!mir_adjust_constants(instructions[i], predicate, false))
658 return ~0;
659
660 /* Ensure it is written only once */
661
662 if (ret != ~0)
663 return ~0;
664 else
665 ret = i;
666 }
667
668 /* Inject constants now that we are sure we want to */
669 if (ret != ~0)
670 mir_adjust_constants(instructions[ret], predicate, true);
671
672 return ret;
673 }
674
675 /* Using the information about the moveable conditional itself, we either pop
676 * that condition off the worklist for use now, or create a move to
677 * artificially schedule instead as a fallback */
678
679 static midgard_instruction *
680 mir_schedule_comparison(
681 compiler_context *ctx,
682 midgard_instruction **instructions,
683 struct midgard_predicate *predicate,
684 BITSET_WORD *worklist, unsigned count,
685 unsigned cond, bool vector, unsigned *swizzle,
686 midgard_instruction *user)
687 {
688 /* TODO: swizzle when scheduling */
689 unsigned comp_i =
690 (!vector && (swizzle[0] == 0)) ?
691 mir_comparison_mobile(ctx, instructions, predicate, count, cond) : ~0;
692
693 /* If we can, schedule the condition immediately */
694 if ((comp_i != ~0) && BITSET_TEST(worklist, comp_i)) {
695 assert(comp_i < count);
696 BITSET_CLEAR(worklist, comp_i);
697 return instructions[comp_i];
698 }
699
700 /* Otherwise, we insert a move */
701
702 midgard_instruction mov = v_mov(cond, cond);
703 mov.mask = vector ? 0xF : 0x1;
704 memcpy(mov.swizzle[1], swizzle, sizeof(mov.swizzle[1]));
705
706 return mir_insert_instruction_before(ctx, user, mov);
707 }
708
709 /* Most generally, we need instructions writing to r31 in the appropriate
710 * components */
711
712 static midgard_instruction *
713 mir_schedule_condition(compiler_context *ctx,
714 struct midgard_predicate *predicate,
715 BITSET_WORD *worklist, unsigned count,
716 midgard_instruction **instructions,
717 midgard_instruction *last)
718 {
719 /* For a branch, the condition is the only argument; for csel, third */
720 bool branch = last->compact_branch;
721 unsigned condition_index = branch ? 0 : 2;
722
723 /* csel_v is vector; otherwise, conditions are scalar */
724 bool vector = !branch && OP_IS_CSEL_V(last->alu.op);
725
726 /* Grab the conditional instruction */
727
728 midgard_instruction *cond = mir_schedule_comparison(
729 ctx, instructions, predicate, worklist, count, last->src[condition_index],
730 vector, last->swizzle[2], last);
731
732 /* We have exclusive reign over this (possibly move) conditional
733 * instruction. We can rewrite into a pipeline conditional register */
734
735 predicate->exclude = cond->dest;
736 cond->dest = SSA_FIXED_REGISTER(31);
737
738 if (!vector) {
739 cond->mask = (1 << COMPONENT_W);
740
741 mir_foreach_src(cond, s) {
742 if (cond->src[s] == ~0)
743 continue;
744
745 for (unsigned q = 0; q < 4; ++q)
746 cond->swizzle[s][q + COMPONENT_W] = cond->swizzle[s][q];
747 }
748 }
749
750 /* Schedule the unit: csel is always in the latter pipeline, so a csel
751 * condition must be in the former pipeline stage (vmul/sadd),
752 * depending on scalar/vector of the instruction itself. A branch must
753 * be written from the latter pipeline stage and a branch condition is
754 * always scalar, so it is always in smul (exception: ball/bany, which
755 * will be vadd) */
756
757 if (branch)
758 cond->unit = UNIT_SMUL;
759 else
760 cond->unit = vector ? UNIT_VMUL : UNIT_SADD;
761
762 return cond;
763 }
764
765 /* Schedules a single bundle of the given type */
766
767 static midgard_bundle
768 mir_schedule_texture(
769 midgard_instruction **instructions,
770 BITSET_WORD *worklist, unsigned len)
771 {
772 struct midgard_predicate predicate = {
773 .tag = TAG_TEXTURE_4,
774 .destructive = true,
775 .exclude = ~0
776 };
777
778 midgard_instruction *ins =
779 mir_choose_instruction(instructions, worklist, len, &predicate);
780
781 mir_update_worklist(worklist, len, instructions, ins);
782
783 struct midgard_bundle out = {
784 .tag = TAG_TEXTURE_4,
785 .instruction_count = 1,
786 .instructions = { ins }
787 };
788
789 return out;
790 }
791
792 static midgard_bundle
793 mir_schedule_ldst(
794 midgard_instruction **instructions,
795 BITSET_WORD *worklist, unsigned len)
796 {
797 struct midgard_predicate predicate = {
798 .tag = TAG_LOAD_STORE_4,
799 .destructive = true,
800 .exclude = ~0
801 };
802
803 /* Try to pick two load/store ops. Second not gauranteed to exist */
804
805 midgard_instruction *ins =
806 mir_choose_instruction(instructions, worklist, len, &predicate);
807
808 midgard_instruction *pair =
809 mir_choose_instruction(instructions, worklist, len, &predicate);
810
811 struct midgard_bundle out = {
812 .tag = TAG_LOAD_STORE_4,
813 .instruction_count = pair ? 2 : 1,
814 .instructions = { ins, pair }
815 };
816
817 /* We have to update the worklist atomically, since the two
818 * instructions run concurrently (TODO: verify it's not pipelined) */
819
820 mir_update_worklist(worklist, len, instructions, ins);
821 mir_update_worklist(worklist, len, instructions, pair);
822
823 return out;
824 }
825
826 static midgard_bundle
827 mir_schedule_alu(
828 compiler_context *ctx,
829 midgard_instruction **instructions,
830 BITSET_WORD *worklist, unsigned len)
831 {
832 struct midgard_bundle bundle = {};
833
834 unsigned bytes_emitted = sizeof(bundle.control);
835
836 struct midgard_predicate predicate = {
837 .tag = TAG_ALU_4,
838 .destructive = true,
839 .exclude = ~0,
840 .constants = &bundle.constants
841 };
842
843 midgard_instruction *vmul = NULL;
844 midgard_instruction *vadd = NULL;
845 midgard_instruction *vlut = NULL;
846 midgard_instruction *smul = NULL;
847 midgard_instruction *sadd = NULL;
848 midgard_instruction *branch = NULL;
849
850 mir_choose_alu(&branch, instructions, worklist, len, &predicate, ALU_ENAB_BR_COMPACT);
851 mir_update_worklist(worklist, len, instructions, branch);
852 bool writeout = branch && branch->writeout;
853
854 if (branch && branch->branch.conditional) {
855 midgard_instruction *cond = mir_schedule_condition(ctx, &predicate, worklist, len, instructions, branch);
856
857 if (cond->unit == UNIT_VADD)
858 vadd = cond;
859 else if (cond->unit == UNIT_SMUL)
860 smul = cond;
861 else
862 unreachable("Bad condition");
863 }
864
865 mir_choose_alu(&smul, instructions, worklist, len, &predicate, UNIT_SMUL);
866
867 if (!writeout)
868 mir_choose_alu(&vlut, instructions, worklist, len, &predicate, UNIT_VLUT);
869
870 if (writeout) {
871 /* Propagate up */
872 bundle.last_writeout = branch->last_writeout;
873
874 midgard_instruction add = v_mov(~0, make_compiler_temp(ctx));
875
876 if (!ctx->is_blend) {
877 add.alu.op = midgard_alu_op_iadd;
878 add.src[0] = SSA_FIXED_REGISTER(31);
879
880 for (unsigned c = 0; c < 16; ++c)
881 add.swizzle[0][c] = COMPONENT_X;
882
883 add.has_inline_constant = true;
884 add.inline_constant = 0;
885 } else {
886 add.src[1] = SSA_FIXED_REGISTER(1);
887
888 for (unsigned c = 0; c < 16; ++c)
889 add.swizzle[1][c] = COMPONENT_W;
890 }
891
892 vadd = mem_dup(&add, sizeof(midgard_instruction));
893
894 vadd->unit = UNIT_VADD;
895 vadd->mask = 0x1;
896 branch->src[2] = add.dest;
897 }
898
899 mir_choose_alu(&vadd, instructions, worklist, len, &predicate, UNIT_VADD);
900
901 mir_update_worklist(worklist, len, instructions, vlut);
902 mir_update_worklist(worklist, len, instructions, vadd);
903 mir_update_worklist(worklist, len, instructions, smul);
904
905 bool vadd_csel = vadd && OP_IS_CSEL(vadd->alu.op);
906 bool smul_csel = smul && OP_IS_CSEL(smul->alu.op);
907
908 if (vadd_csel || smul_csel) {
909 midgard_instruction *ins = vadd_csel ? vadd : smul;
910 midgard_instruction *cond = mir_schedule_condition(ctx, &predicate, worklist, len, instructions, ins);
911
912 if (cond->unit == UNIT_VMUL)
913 vmul = cond;
914 else if (cond->unit == UNIT_SADD)
915 sadd = cond;
916 else
917 unreachable("Bad condition");
918 }
919
920 /* If we have a render target reference, schedule a move for it */
921
922 if (branch && branch->writeout && (branch->constants.u32[0] || ctx->is_blend)) {
923 midgard_instruction mov = v_mov(~0, make_compiler_temp(ctx));
924 sadd = mem_dup(&mov, sizeof(midgard_instruction));
925 sadd->unit = UNIT_SADD;
926 sadd->mask = 0x1;
927 sadd->has_inline_constant = true;
928 sadd->inline_constant = branch->constants.u32[0];
929 branch->src[1] = mov.dest;
930 /* TODO: Don't leak */
931 }
932
933 /* Stage 2, let's schedule sadd before vmul for writeout */
934 mir_choose_alu(&sadd, instructions, worklist, len, &predicate, UNIT_SADD);
935
936 /* Check if writeout reads its own register */
937
938 if (branch && branch->writeout) {
939 midgard_instruction *stages[] = { sadd, vadd, smul };
940 unsigned src = (branch->src[0] == ~0) ? SSA_FIXED_REGISTER(0) : branch->src[0];
941 unsigned writeout_mask = 0x0;
942 bool bad_writeout = false;
943
944 for (unsigned i = 0; i < ARRAY_SIZE(stages); ++i) {
945 if (!stages[i])
946 continue;
947
948 if (stages[i]->dest != src)
949 continue;
950
951 writeout_mask |= stages[i]->mask;
952 bad_writeout |= mir_has_arg(stages[i], branch->src[0]);
953 }
954
955 /* It's possible we'll be able to schedule something into vmul
956 * to fill r0. Let's peak into the future, trying to schedule
957 * vmul specially that way. */
958
959 if (!bad_writeout && writeout_mask != 0xF) {
960 predicate.unit = UNIT_VMUL;
961 predicate.dest = src;
962 predicate.mask = writeout_mask ^ 0xF;
963
964 struct midgard_instruction *peaked =
965 mir_choose_instruction(instructions, worklist, len, &predicate);
966
967 if (peaked) {
968 vmul = peaked;
969 vmul->unit = UNIT_VMUL;
970 writeout_mask |= predicate.mask;
971 assert(writeout_mask == 0xF);
972 }
973
974 /* Cleanup */
975 predicate.dest = predicate.mask = 0;
976 }
977
978 /* Finally, add a move if necessary */
979 if (bad_writeout || writeout_mask != 0xF) {
980 unsigned temp = (branch->src[0] == ~0) ? SSA_FIXED_REGISTER(0) : make_compiler_temp(ctx);
981 midgard_instruction mov = v_mov(src, temp);
982 vmul = mem_dup(&mov, sizeof(midgard_instruction));
983 vmul->unit = UNIT_VMUL;
984 vmul->mask = 0xF ^ writeout_mask;
985 /* TODO: Don't leak */
986
987 /* Rewrite to use our temp */
988
989 for (unsigned i = 0; i < ARRAY_SIZE(stages); ++i) {
990 if (stages[i])
991 mir_rewrite_index_dst_single(stages[i], src, temp);
992 }
993
994 mir_rewrite_index_src_single(branch, src, temp);
995 }
996 }
997
998 mir_choose_alu(&vmul, instructions, worklist, len, &predicate, UNIT_VMUL);
999
1000 mir_update_worklist(worklist, len, instructions, vmul);
1001 mir_update_worklist(worklist, len, instructions, sadd);
1002
1003 bundle.has_blend_constant = predicate.blend_constant;
1004 bundle.has_embedded_constants = predicate.constant_mask != 0;
1005
1006 unsigned padding = 0;
1007
1008 /* Now that we have finished scheduling, build up the bundle */
1009 midgard_instruction *stages[] = { vmul, sadd, vadd, smul, vlut, branch };
1010
1011 for (unsigned i = 0; i < ARRAY_SIZE(stages); ++i) {
1012 if (stages[i]) {
1013 bundle.control |= stages[i]->unit;
1014 bytes_emitted += bytes_for_instruction(stages[i]);
1015 bundle.instructions[bundle.instruction_count++] = stages[i];
1016 }
1017 }
1018
1019 /* Pad ALU op to nearest word */
1020
1021 if (bytes_emitted & 15) {
1022 padding = 16 - (bytes_emitted & 15);
1023 bytes_emitted += padding;
1024 }
1025
1026 /* Constants must always be quadwords */
1027 if (bundle.has_embedded_constants)
1028 bytes_emitted += 16;
1029
1030 /* Size ALU instruction for tag */
1031 bundle.tag = (TAG_ALU_4) + (bytes_emitted / 16) - 1;
1032
1033 /* MRT capable GPUs use a special writeout procedure */
1034 if (writeout && !(ctx->quirks & MIDGARD_NO_UPPER_ALU))
1035 bundle.tag += 4;
1036
1037 bundle.padding = padding;
1038 bundle.control |= bundle.tag;
1039
1040 return bundle;
1041 }
1042
1043 /* Schedule a single block by iterating its instruction to create bundles.
1044 * While we go, tally about the bundle sizes to compute the block size. */
1045
1046
1047 static void
1048 schedule_block(compiler_context *ctx, midgard_block *block)
1049 {
1050 /* Copy list to dynamic array */
1051 unsigned len = 0;
1052 midgard_instruction **instructions = flatten_mir(block, &len);
1053
1054 if (!len)
1055 return;
1056
1057 /* Calculate dependencies and initial worklist */
1058 unsigned node_count = ctx->temp_count + 1;
1059 mir_create_dependency_graph(instructions, len, node_count);
1060
1061 /* Allocate the worklist */
1062 size_t sz = BITSET_WORDS(len) * sizeof(BITSET_WORD);
1063 BITSET_WORD *worklist = calloc(sz, 1);
1064 mir_initialize_worklist(worklist, instructions, len);
1065
1066 struct util_dynarray bundles;
1067 util_dynarray_init(&bundles, NULL);
1068
1069 block->quadword_count = 0;
1070 unsigned blend_offset = 0;
1071
1072 for (;;) {
1073 unsigned tag = mir_choose_bundle(instructions, worklist, len);
1074 midgard_bundle bundle;
1075
1076 if (tag == TAG_TEXTURE_4)
1077 bundle = mir_schedule_texture(instructions, worklist, len);
1078 else if (tag == TAG_LOAD_STORE_4)
1079 bundle = mir_schedule_ldst(instructions, worklist, len);
1080 else if (tag == TAG_ALU_4)
1081 bundle = mir_schedule_alu(ctx, instructions, worklist, len);
1082 else
1083 break;
1084
1085 util_dynarray_append(&bundles, midgard_bundle, bundle);
1086
1087 if (bundle.has_blend_constant)
1088 blend_offset = block->quadword_count;
1089
1090 block->quadword_count += midgard_word_size[bundle.tag];
1091 }
1092
1093 /* We emitted bundles backwards; copy into the block in reverse-order */
1094
1095 util_dynarray_init(&block->bundles, block);
1096 util_dynarray_foreach_reverse(&bundles, midgard_bundle, bundle) {
1097 util_dynarray_append(&block->bundles, midgard_bundle, *bundle);
1098 }
1099 util_dynarray_fini(&bundles);
1100
1101 /* Blend constant was backwards as well. blend_offset if set is
1102 * strictly positive, as an offset of zero would imply constants before
1103 * any instructions which is invalid in Midgard. TODO: blend constants
1104 * are broken if you spill since then quadword_count becomes invalid
1105 * XXX */
1106
1107 if (blend_offset)
1108 ctx->blend_constant_offset = ((ctx->quadword_count + block->quadword_count) - blend_offset - 1) * 0x10;
1109
1110 block->is_scheduled = true;
1111 ctx->quadword_count += block->quadword_count;
1112
1113 /* Reorder instructions to match bundled. First remove existing
1114 * instructions and then recreate the list */
1115
1116 mir_foreach_instr_in_block_safe(block, ins) {
1117 list_del(&ins->link);
1118 }
1119
1120 mir_foreach_instr_in_block_scheduled_rev(block, ins) {
1121 list_add(&ins->link, &block->instructions);
1122 }
1123
1124 free(instructions); /* Allocated by flatten_mir() */
1125 free(worklist);
1126 }
1127
1128 void
1129 midgard_schedule_program(compiler_context *ctx)
1130 {
1131 midgard_promote_uniforms(ctx);
1132
1133 /* Must be lowered right before scheduling */
1134 mir_squeeze_index(ctx);
1135 mir_lower_special_reads(ctx);
1136 mir_squeeze_index(ctx);
1137
1138 /* Lowering can introduce some dead moves */
1139
1140 mir_foreach_block(ctx, block) {
1141 midgard_opt_dead_move_eliminate(ctx, block);
1142 schedule_block(ctx, block);
1143 }
1144
1145 }