pan/mdg: Pass through some types from scheduling
[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 midgard_reg_mode dst_mode = mir_typesize(ins);
385
386 unsigned bundle_constant_mask = pred->constant_mask;
387 unsigned comp_mapping[2][16] = { };
388 uint8_t bundle_constants[16];
389
390 memcpy(bundle_constants, pred->constants, 16);
391
392 /* Let's try to find a place for each active component of the constant
393 * register.
394 */
395 for (unsigned src = 0; src < 2; ++src) {
396 if (ins->src[src] != SSA_FIXED_REGISTER(REGISTER_CONSTANT))
397 continue;
398
399 midgard_reg_mode src_mode = mir_srcsize(ins, src);
400 unsigned type_size = mir_bytes_for_mode(src_mode);
401 unsigned max_comp = 16 / type_size;
402 unsigned comp_mask = mir_from_bytemask(mir_bytemask_of_read_components_index(ins, src),
403 dst_mode);
404 unsigned type_mask = (1 << type_size) - 1;
405
406 for (unsigned comp = 0; comp < max_comp; comp++) {
407 if (!(comp_mask & (1 << comp)))
408 continue;
409
410 uint8_t *constantp = ins->constants.u8 + (type_size * comp);
411 unsigned best_reuse_bytes = 0;
412 signed best_place = -1;
413 unsigned i, j;
414
415 for (i = 0; i < 16; i += type_size) {
416 unsigned reuse_bytes = 0;
417
418 for (j = 0; j < type_size; j++) {
419 if (!(bundle_constant_mask & (1 << (i + j))))
420 continue;
421 if (constantp[j] != bundle_constants[i + j])
422 break;
423
424 reuse_bytes++;
425 }
426
427 /* Select the place where existing bytes can be
428 * reused so we leave empty slots to others
429 */
430 if (j == type_size &&
431 (reuse_bytes > best_reuse_bytes || best_place < 0)) {
432 best_reuse_bytes = reuse_bytes;
433 best_place = i;
434 break;
435 }
436 }
437
438 /* This component couldn't fit in the remaining constant slot,
439 * no need check the remaining components, bail out now
440 */
441 if (best_place < 0)
442 return false;
443
444 memcpy(&bundle_constants[i], constantp, type_size);
445 bundle_constant_mask |= type_mask << best_place;
446 comp_mapping[src][comp] = best_place / type_size;
447 }
448 }
449
450 /* If non-destructive, we're done */
451 if (!destructive)
452 return true;
453
454 /* Otherwise update the constant_mask and constant values */
455 pred->constant_mask = bundle_constant_mask;
456 memcpy(pred->constants, bundle_constants, 16);
457
458 /* Use comp_mapping as a swizzle */
459 mir_foreach_src(ins, s) {
460 if (ins->src[s] == r_constant)
461 mir_compose_swizzle(ins->swizzle[s], comp_mapping[s], ins->swizzle[s]);
462 }
463
464 return true;
465 }
466
467 /* Conservative estimate of the pipeline registers required for load/store */
468
469 static unsigned
470 mir_pipeline_count(midgard_instruction *ins)
471 {
472 unsigned bytecount = 0;
473
474 mir_foreach_src(ins, i) {
475 /* Skip empty source */
476 if (ins->src[i] == ~0) continue;
477
478 unsigned bytemask = mir_bytemask_of_read_components_index(ins, i);
479
480 unsigned max = util_logbase2(bytemask) + 1;
481 bytecount += max;
482 }
483
484 return DIV_ROUND_UP(bytecount, 16);
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 bool ldst = tag == TAG_LOAD_STORE_4;
497 unsigned unit = predicate->unit;
498 bool branch = alu && (unit == ALU_ENAB_BR_COMPACT);
499 bool scalar = (unit != ~0) && (unit & UNITS_SCALAR);
500 bool no_cond = predicate->no_cond;
501
502 unsigned mask = predicate->mask;
503 unsigned dest = predicate->dest;
504 bool needs_dest = mask & 0xF;
505
506 /* Iterate to find the best instruction satisfying the predicate */
507 unsigned i;
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, worklist, count) {
520 max_active = MAX2(max_active, i);
521 }
522
523 BITSET_FOREACH_SET(i, 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 if (ldst && mir_pipeline_count(instructions[i]) + predicate->pipeline_count > 2)
552 continue;
553
554 bool conditional = alu && !branch && OP_IS_CSEL(instructions[i]->alu.op);
555 conditional |= (branch && instructions[i]->branch.conditional);
556
557 if (conditional && no_cond)
558 continue;
559
560 /* Simulate in-order scheduling */
561 if ((signed) i < best_index)
562 continue;
563
564 best_index = i;
565 best_conditional = conditional;
566 }
567
568
569 /* Did we find anything? */
570
571 if (best_index < 0)
572 return NULL;
573
574 /* If we found something, remove it from the worklist */
575 assert(best_index < count);
576
577 if (predicate->destructive) {
578 BITSET_CLEAR(worklist, best_index);
579
580 if (alu)
581 mir_adjust_constants(instructions[best_index], predicate, true);
582
583 if (ldst)
584 predicate->pipeline_count += mir_pipeline_count(instructions[best_index]);
585
586 /* Once we schedule a conditional, we can't again */
587 predicate->no_cond |= best_conditional;
588 }
589
590 return instructions[best_index];
591 }
592
593 /* Still, we don't choose instructions in a vacuum. We need a way to choose the
594 * best bundle type (ALU, load/store, texture). Nondestructive. */
595
596 static unsigned
597 mir_choose_bundle(
598 midgard_instruction **instructions,
599 BITSET_WORD *worklist, unsigned count)
600 {
601 /* At the moment, our algorithm is very simple - use the bundle of the
602 * best instruction, regardless of what else could be scheduled
603 * alongside it. This is not optimal but it works okay for in-order */
604
605 struct midgard_predicate predicate = {
606 .tag = ~0,
607 .destructive = false,
608 .exclude = ~0
609 };
610
611 midgard_instruction *chosen = mir_choose_instruction(instructions, worklist, count, &predicate);
612
613 if (chosen)
614 return chosen->type;
615 else
616 return ~0;
617 }
618
619 /* We want to choose an ALU instruction filling a given unit */
620 static void
621 mir_choose_alu(midgard_instruction **slot,
622 midgard_instruction **instructions,
623 BITSET_WORD *worklist, unsigned len,
624 struct midgard_predicate *predicate,
625 unsigned unit)
626 {
627 /* Did we already schedule to this slot? */
628 if ((*slot) != NULL)
629 return;
630
631 /* Try to schedule something, if not */
632 predicate->unit = unit;
633 *slot = mir_choose_instruction(instructions, worklist, len, predicate);
634
635 /* Store unit upon scheduling */
636 if (*slot && !((*slot)->compact_branch))
637 (*slot)->unit = unit;
638 }
639
640 /* When we are scheduling a branch/csel, we need the consumed condition in the
641 * same block as a pipeline register. There are two options to enable this:
642 *
643 * - Move the conditional into the bundle. Preferred, but only works if the
644 * conditional is used only once and is from this block.
645 * - Copy the conditional.
646 *
647 * We search for the conditional. If it's in this block, single-use, and
648 * without embedded constants, we schedule it immediately. Otherwise, we
649 * schedule a move for it.
650 *
651 * mir_comparison_mobile is a helper to find the moveable condition.
652 */
653
654 static unsigned
655 mir_comparison_mobile(
656 compiler_context *ctx,
657 midgard_instruction **instructions,
658 struct midgard_predicate *predicate,
659 unsigned count,
660 unsigned cond)
661 {
662 if (!mir_single_use(ctx, cond))
663 return ~0;
664
665 unsigned ret = ~0;
666
667 for (unsigned i = 0; i < count; ++i) {
668 if (instructions[i]->dest != cond)
669 continue;
670
671 /* Must fit in an ALU bundle */
672 if (instructions[i]->type != TAG_ALU_4)
673 return ~0;
674
675 /* If it would itself require a condition, that's recursive */
676 if (OP_IS_CSEL(instructions[i]->alu.op))
677 return ~0;
678
679 /* We'll need to rewrite to .w but that doesn't work for vector
680 * ops that don't replicate (ball/bany), so bail there */
681
682 if (GET_CHANNEL_COUNT(alu_opcode_props[instructions[i]->alu.op].props))
683 return ~0;
684
685 /* Ensure it will fit with constants */
686
687 if (!mir_adjust_constants(instructions[i], predicate, false))
688 return ~0;
689
690 /* Ensure it is written only once */
691
692 if (ret != ~0)
693 return ~0;
694 else
695 ret = i;
696 }
697
698 /* Inject constants now that we are sure we want to */
699 if (ret != ~0)
700 mir_adjust_constants(instructions[ret], predicate, true);
701
702 return ret;
703 }
704
705 /* Using the information about the moveable conditional itself, we either pop
706 * that condition off the worklist for use now, or create a move to
707 * artificially schedule instead as a fallback */
708
709 static midgard_instruction *
710 mir_schedule_comparison(
711 compiler_context *ctx,
712 midgard_instruction **instructions,
713 struct midgard_predicate *predicate,
714 BITSET_WORD *worklist, unsigned count,
715 unsigned cond, bool vector, unsigned *swizzle,
716 midgard_instruction *user)
717 {
718 /* TODO: swizzle when scheduling */
719 unsigned comp_i =
720 (!vector && (swizzle[0] == 0)) ?
721 mir_comparison_mobile(ctx, instructions, predicate, count, cond) : ~0;
722
723 /* If we can, schedule the condition immediately */
724 if ((comp_i != ~0) && BITSET_TEST(worklist, comp_i)) {
725 assert(comp_i < count);
726 BITSET_CLEAR(worklist, comp_i);
727 return instructions[comp_i];
728 }
729
730 /* Otherwise, we insert a move */
731
732 midgard_instruction mov = v_mov(cond, cond);
733 mov.mask = vector ? 0xF : 0x1;
734 memcpy(mov.swizzle[1], swizzle, sizeof(mov.swizzle[1]));
735
736 return mir_insert_instruction_before(ctx, user, mov);
737 }
738
739 /* Most generally, we need instructions writing to r31 in the appropriate
740 * components */
741
742 static midgard_instruction *
743 mir_schedule_condition(compiler_context *ctx,
744 struct midgard_predicate *predicate,
745 BITSET_WORD *worklist, unsigned count,
746 midgard_instruction **instructions,
747 midgard_instruction *last)
748 {
749 /* For a branch, the condition is the only argument; for csel, third */
750 bool branch = last->compact_branch;
751 unsigned condition_index = branch ? 0 : 2;
752
753 /* csel_v is vector; otherwise, conditions are scalar */
754 bool vector = !branch && OP_IS_CSEL_V(last->alu.op);
755
756 /* Grab the conditional instruction */
757
758 midgard_instruction *cond = mir_schedule_comparison(
759 ctx, instructions, predicate, worklist, count, last->src[condition_index],
760 vector, last->swizzle[2], last);
761
762 /* We have exclusive reign over this (possibly move) conditional
763 * instruction. We can rewrite into a pipeline conditional register */
764
765 predicate->exclude = cond->dest;
766 cond->dest = SSA_FIXED_REGISTER(31);
767
768 if (!vector) {
769 cond->mask = (1 << COMPONENT_W);
770
771 mir_foreach_src(cond, s) {
772 if (cond->src[s] == ~0)
773 continue;
774
775 for (unsigned q = 0; q < 4; ++q)
776 cond->swizzle[s][q + COMPONENT_W] = cond->swizzle[s][q];
777 }
778 }
779
780 /* Schedule the unit: csel is always in the latter pipeline, so a csel
781 * condition must be in the former pipeline stage (vmul/sadd),
782 * depending on scalar/vector of the instruction itself. A branch must
783 * be written from the latter pipeline stage and a branch condition is
784 * always scalar, so it is always in smul (exception: ball/bany, which
785 * will be vadd) */
786
787 if (branch)
788 cond->unit = UNIT_SMUL;
789 else
790 cond->unit = vector ? UNIT_VMUL : UNIT_SADD;
791
792 return cond;
793 }
794
795 /* Schedules a single bundle of the given type */
796
797 static midgard_bundle
798 mir_schedule_texture(
799 midgard_instruction **instructions,
800 BITSET_WORD *worklist, unsigned len)
801 {
802 struct midgard_predicate predicate = {
803 .tag = TAG_TEXTURE_4,
804 .destructive = true,
805 .exclude = ~0
806 };
807
808 midgard_instruction *ins =
809 mir_choose_instruction(instructions, worklist, len, &predicate);
810
811 mir_update_worklist(worklist, len, instructions, ins);
812
813 struct midgard_bundle out = {
814 .tag = ins->texture.op == TEXTURE_OP_BARRIER ?
815 TAG_TEXTURE_4_BARRIER : TAG_TEXTURE_4,
816 .instruction_count = 1,
817 .instructions = { ins }
818 };
819
820 return out;
821 }
822
823 static midgard_bundle
824 mir_schedule_ldst(
825 midgard_instruction **instructions,
826 BITSET_WORD *worklist, unsigned len)
827 {
828 struct midgard_predicate predicate = {
829 .tag = TAG_LOAD_STORE_4,
830 .destructive = true,
831 .exclude = ~0
832 };
833
834 /* Try to pick two load/store ops. Second not gauranteed to exist */
835
836 midgard_instruction *ins =
837 mir_choose_instruction(instructions, worklist, len, &predicate);
838
839 midgard_instruction *pair =
840 mir_choose_instruction(instructions, worklist, len, &predicate);
841
842 struct midgard_bundle out = {
843 .tag = TAG_LOAD_STORE_4,
844 .instruction_count = pair ? 2 : 1,
845 .instructions = { ins, pair }
846 };
847
848 /* We have to update the worklist atomically, since the two
849 * instructions run concurrently (TODO: verify it's not pipelined) */
850
851 mir_update_worklist(worklist, len, instructions, ins);
852 mir_update_worklist(worklist, len, instructions, pair);
853
854 return out;
855 }
856
857 static midgard_bundle
858 mir_schedule_alu(
859 compiler_context *ctx,
860 midgard_instruction **instructions,
861 BITSET_WORD *worklist, unsigned len)
862 {
863 struct midgard_bundle bundle = {};
864
865 unsigned bytes_emitted = sizeof(bundle.control);
866
867 struct midgard_predicate predicate = {
868 .tag = TAG_ALU_4,
869 .destructive = true,
870 .exclude = ~0,
871 .constants = &bundle.constants
872 };
873
874 midgard_instruction *vmul = NULL;
875 midgard_instruction *vadd = NULL;
876 midgard_instruction *vlut = NULL;
877 midgard_instruction *smul = NULL;
878 midgard_instruction *sadd = NULL;
879 midgard_instruction *branch = NULL;
880
881 mir_choose_alu(&branch, instructions, worklist, len, &predicate, ALU_ENAB_BR_COMPACT);
882 mir_update_worklist(worklist, len, instructions, branch);
883 bool writeout = branch && branch->writeout;
884 bool zs_writeout = writeout && (branch->writeout_depth | branch->writeout_stencil);
885
886 if (branch && branch->branch.conditional) {
887 midgard_instruction *cond = mir_schedule_condition(ctx, &predicate, worklist, len, instructions, branch);
888
889 if (cond->unit == UNIT_VADD)
890 vadd = cond;
891 else if (cond->unit == UNIT_SMUL)
892 smul = cond;
893 else
894 unreachable("Bad condition");
895 }
896
897 /* If we have a render target reference, schedule a move for it. Since
898 * this will be in sadd, we boost this to prevent scheduling csel into
899 * smul */
900
901 if (writeout && (branch->constants.u32[0] || ctx->is_blend)) {
902 sadd = ralloc(ctx, midgard_instruction);
903 *sadd = v_mov(~0, make_compiler_temp(ctx));
904 sadd->unit = UNIT_SADD;
905 sadd->mask = 0x1;
906 sadd->has_inline_constant = true;
907 sadd->inline_constant = branch->constants.u32[0];
908 branch->src[1] = sadd->dest;
909 branch->src_types[1] = sadd->dest_type;
910
911 /* Mask off any conditionals. Could be optimized to just scalar
912 * conditionals TODO */
913 predicate.no_cond = true;
914 }
915
916 mir_choose_alu(&smul, instructions, worklist, len, &predicate, UNIT_SMUL);
917
918 if (!writeout) {
919 mir_choose_alu(&vlut, instructions, worklist, len, &predicate, UNIT_VLUT);
920 } else {
921 /* Propagate up */
922 bundle.last_writeout = branch->last_writeout;
923 }
924
925 if (writeout && !zs_writeout) {
926 vadd = ralloc(ctx, midgard_instruction);
927 *vadd = v_mov(~0, make_compiler_temp(ctx));
928
929 if (!ctx->is_blend) {
930 vadd->alu.op = midgard_alu_op_iadd;
931 vadd->src[0] = SSA_FIXED_REGISTER(31);
932 vadd->src_types[0] = nir_type_uint32;
933
934 for (unsigned c = 0; c < 16; ++c)
935 vadd->swizzle[0][c] = COMPONENT_X;
936
937 vadd->has_inline_constant = true;
938 vadd->inline_constant = 0;
939 } else {
940 vadd->src[1] = SSA_FIXED_REGISTER(1);
941 vadd->src_types[0] = nir_type_uint32;
942
943 for (unsigned c = 0; c < 16; ++c)
944 vadd->swizzle[1][c] = COMPONENT_W;
945 }
946
947 vadd->unit = UNIT_VADD;
948 vadd->mask = 0x1;
949 branch->src[2] = vadd->dest;
950 branch->src_types[2] = vadd->dest_type;
951 }
952
953 mir_choose_alu(&vadd, instructions, worklist, len, &predicate, UNIT_VADD);
954
955 mir_update_worklist(worklist, len, instructions, vlut);
956 mir_update_worklist(worklist, len, instructions, vadd);
957 mir_update_worklist(worklist, len, instructions, smul);
958
959 bool vadd_csel = vadd && OP_IS_CSEL(vadd->alu.op);
960 bool smul_csel = smul && OP_IS_CSEL(smul->alu.op);
961
962 if (vadd_csel || smul_csel) {
963 midgard_instruction *ins = vadd_csel ? vadd : smul;
964 midgard_instruction *cond = mir_schedule_condition(ctx, &predicate, worklist, len, instructions, ins);
965
966 if (cond->unit == UNIT_VMUL)
967 vmul = cond;
968 else if (cond->unit == UNIT_SADD)
969 sadd = cond;
970 else
971 unreachable("Bad condition");
972 }
973
974 /* Stage 2, let's schedule sadd before vmul for writeout */
975 mir_choose_alu(&sadd, instructions, worklist, len, &predicate, UNIT_SADD);
976
977 /* Check if writeout reads its own register */
978
979 if (writeout) {
980 midgard_instruction *stages[] = { sadd, vadd, smul };
981 unsigned src = (branch->src[0] == ~0) ? SSA_FIXED_REGISTER(zs_writeout ? 1 : 0) : branch->src[0];
982 unsigned writeout_mask = 0x0;
983 bool bad_writeout = false;
984
985 for (unsigned i = 0; i < ARRAY_SIZE(stages); ++i) {
986 if (!stages[i])
987 continue;
988
989 if (stages[i]->dest != src)
990 continue;
991
992 writeout_mask |= stages[i]->mask;
993 bad_writeout |= mir_has_arg(stages[i], branch->src[0]);
994 }
995
996 /* It's possible we'll be able to schedule something into vmul
997 * to fill r0/r1. Let's peak into the future, trying to schedule
998 * vmul specially that way. */
999
1000 unsigned full_mask = zs_writeout ?
1001 (1 << (branch->writeout_depth + branch->writeout_stencil)) - 1 :
1002 0xF;
1003
1004 if (!bad_writeout && writeout_mask != full_mask) {
1005 predicate.unit = UNIT_VMUL;
1006 predicate.dest = src;
1007 predicate.mask = writeout_mask ^ full_mask;
1008
1009 struct midgard_instruction *peaked =
1010 mir_choose_instruction(instructions, worklist, len, &predicate);
1011
1012 if (peaked) {
1013 vmul = peaked;
1014 vmul->unit = UNIT_VMUL;
1015 writeout_mask |= predicate.mask;
1016 assert(writeout_mask == full_mask);
1017 }
1018
1019 /* Cleanup */
1020 predicate.dest = predicate.mask = 0;
1021 }
1022
1023 /* Finally, add a move if necessary */
1024 if (bad_writeout || writeout_mask != full_mask) {
1025 unsigned temp = (branch->src[0] == ~0) ? SSA_FIXED_REGISTER(zs_writeout ? 1 : 0) : make_compiler_temp(ctx);
1026
1027 vmul = ralloc(ctx, midgard_instruction);
1028 *vmul = v_mov(src, temp);
1029 vmul->unit = UNIT_VMUL;
1030 vmul->mask = full_mask ^ writeout_mask;
1031
1032 /* Rewrite to use our temp */
1033
1034 for (unsigned i = 0; i < ARRAY_SIZE(stages); ++i) {
1035 if (stages[i])
1036 mir_rewrite_index_dst_single(stages[i], src, temp);
1037 }
1038
1039 mir_rewrite_index_src_single(branch, src, temp);
1040 }
1041 }
1042
1043 mir_choose_alu(&vmul, instructions, worklist, len, &predicate, UNIT_VMUL);
1044
1045 mir_update_worklist(worklist, len, instructions, vmul);
1046 mir_update_worklist(worklist, len, instructions, sadd);
1047
1048 bundle.has_blend_constant = predicate.blend_constant;
1049 bundle.has_embedded_constants = predicate.constant_mask != 0;
1050
1051 unsigned padding = 0;
1052
1053 /* Now that we have finished scheduling, build up the bundle */
1054 midgard_instruction *stages[] = { vmul, sadd, vadd, smul, vlut, branch };
1055
1056 for (unsigned i = 0; i < ARRAY_SIZE(stages); ++i) {
1057 if (stages[i]) {
1058 bundle.control |= stages[i]->unit;
1059 bytes_emitted += bytes_for_instruction(stages[i]);
1060 bundle.instructions[bundle.instruction_count++] = stages[i];
1061
1062 /* If we branch, we can't spill to TLS since the store
1063 * instruction will never get executed. We could try to
1064 * break the bundle but this is probably easier for
1065 * now. */
1066
1067 if (branch)
1068 stages[i]->no_spill |= (1 << REG_CLASS_WORK);
1069 }
1070 }
1071
1072 /* Pad ALU op to nearest word */
1073
1074 if (bytes_emitted & 15) {
1075 padding = 16 - (bytes_emitted & 15);
1076 bytes_emitted += padding;
1077 }
1078
1079 /* Constants must always be quadwords */
1080 if (bundle.has_embedded_constants)
1081 bytes_emitted += 16;
1082
1083 /* Size ALU instruction for tag */
1084 bundle.tag = (TAG_ALU_4) + (bytes_emitted / 16) - 1;
1085
1086 /* MRT capable GPUs use a special writeout procedure */
1087 if (writeout && !(ctx->quirks & MIDGARD_NO_UPPER_ALU))
1088 bundle.tag += 4;
1089
1090 bundle.padding = padding;
1091 bundle.control |= bundle.tag;
1092
1093 return bundle;
1094 }
1095
1096 /* Schedule a single block by iterating its instruction to create bundles.
1097 * While we go, tally about the bundle sizes to compute the block size. */
1098
1099
1100 static void
1101 schedule_block(compiler_context *ctx, midgard_block *block)
1102 {
1103 /* Copy list to dynamic array */
1104 unsigned len = 0;
1105 midgard_instruction **instructions = flatten_mir(block, &len);
1106
1107 if (!len)
1108 return;
1109
1110 /* Calculate dependencies and initial worklist */
1111 unsigned node_count = ctx->temp_count + 1;
1112 mir_create_dependency_graph(instructions, len, node_count);
1113
1114 /* Allocate the worklist */
1115 size_t sz = BITSET_WORDS(len) * sizeof(BITSET_WORD);
1116 BITSET_WORD *worklist = calloc(sz, 1);
1117 mir_initialize_worklist(worklist, instructions, len);
1118
1119 struct util_dynarray bundles;
1120 util_dynarray_init(&bundles, NULL);
1121
1122 block->quadword_count = 0;
1123 unsigned blend_offset = 0;
1124
1125 for (;;) {
1126 unsigned tag = mir_choose_bundle(instructions, worklist, len);
1127 midgard_bundle bundle;
1128
1129 if (tag == TAG_TEXTURE_4)
1130 bundle = mir_schedule_texture(instructions, worklist, len);
1131 else if (tag == TAG_LOAD_STORE_4)
1132 bundle = mir_schedule_ldst(instructions, worklist, len);
1133 else if (tag == TAG_ALU_4)
1134 bundle = mir_schedule_alu(ctx, instructions, worklist, len);
1135 else
1136 break;
1137
1138 util_dynarray_append(&bundles, midgard_bundle, bundle);
1139
1140 if (bundle.has_blend_constant)
1141 blend_offset = block->quadword_count;
1142
1143 block->quadword_count += midgard_tag_props[bundle.tag].size;
1144 }
1145
1146 /* We emitted bundles backwards; copy into the block in reverse-order */
1147
1148 util_dynarray_init(&block->bundles, block);
1149 util_dynarray_foreach_reverse(&bundles, midgard_bundle, bundle) {
1150 util_dynarray_append(&block->bundles, midgard_bundle, *bundle);
1151 }
1152 util_dynarray_fini(&bundles);
1153
1154 /* Blend constant was backwards as well. blend_offset if set is
1155 * strictly positive, as an offset of zero would imply constants before
1156 * any instructions which is invalid in Midgard. TODO: blend constants
1157 * are broken if you spill since then quadword_count becomes invalid
1158 * XXX */
1159
1160 if (blend_offset)
1161 ctx->blend_constant_offset = ((ctx->quadword_count + block->quadword_count) - blend_offset - 1) * 0x10;
1162
1163 block->scheduled = true;
1164 ctx->quadword_count += block->quadword_count;
1165
1166 /* Reorder instructions to match bundled. First remove existing
1167 * instructions and then recreate the list */
1168
1169 mir_foreach_instr_in_block_safe(block, ins) {
1170 list_del(&ins->link);
1171 }
1172
1173 mir_foreach_instr_in_block_scheduled_rev(block, ins) {
1174 list_add(&ins->link, &block->base.instructions);
1175 }
1176
1177 free(instructions); /* Allocated by flatten_mir() */
1178 free(worklist);
1179 }
1180
1181 void
1182 midgard_schedule_program(compiler_context *ctx)
1183 {
1184 midgard_promote_uniforms(ctx);
1185
1186 /* Must be lowered right before scheduling */
1187 mir_squeeze_index(ctx);
1188 mir_lower_special_reads(ctx);
1189 mir_squeeze_index(ctx);
1190
1191 /* Lowering can introduce some dead moves */
1192
1193 mir_foreach_block(ctx, _block) {
1194 midgard_block *block = (midgard_block *) _block;
1195 midgard_opt_dead_move_eliminate(ctx, block);
1196 schedule_block(ctx, block);
1197 }
1198
1199 }