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