2 * Copyright (C) 2018-2019 Alyssa Rosenzweig <alyssa@rosenzweig.io>
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:
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
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
25 #include "midgard_ops.h"
26 #include "util/u_memory.h"
28 /* Scheduling for Midgard is complicated, to say the least. ALU instructions
29 * must be grouped into VLIW bundles according to following model:
32 * [VADD] [SMUL] [VLUT]
34 * A given instruction can execute on some subset of the units (or a few can
35 * execute on all). Instructions can be either vector or scalar; only scalar
36 * instructions can execute on SADD/SMUL units. Units on a given line execute
37 * in parallel. Subsequent lines execute separately and can pass results
38 * directly via pipeline registers r24/r25, bypassing the register file.
40 * A bundle can optionally have 128-bits of embedded constants, shared across
41 * all of the instructions within a bundle.
43 * Instructions consuming conditionals (branches and conditional selects)
44 * require their condition to be written into the conditional register (r31)
45 * within the same bundle they are consumed.
47 * Fragment writeout requires its argument to be written in full within the
48 * same bundle as the branch, with no hanging dependencies.
50 * Load/store instructions are also in bundles of simply two instructions, and
51 * texture instructions have no bundling.
53 * -------------------------------------------------------------------------
57 /* We create the dependency graph with per-byte granularity */
62 add_dependency(struct util_dynarray
*table
, unsigned index
, uint16_t mask
, midgard_instruction
**instructions
, unsigned child
)
64 for (unsigned i
= 0; i
< BYTE_COUNT
; ++i
) {
65 if (!(mask
& (1 << i
)))
68 struct util_dynarray
*parents
= &table
[(BYTE_COUNT
* index
) + i
];
70 util_dynarray_foreach(parents
, unsigned, parent
) {
71 BITSET_WORD
*dependents
= instructions
[*parent
]->dependents
;
73 /* Already have the dependency */
74 if (BITSET_TEST(dependents
, child
))
77 BITSET_SET(dependents
, child
);
78 instructions
[child
]->nr_dependencies
++;
84 mark_access(struct util_dynarray
*table
, unsigned index
, uint16_t mask
, unsigned parent
)
86 for (unsigned i
= 0; i
< BYTE_COUNT
; ++i
) {
87 if (!(mask
& (1 << i
)))
90 util_dynarray_append(&table
[(BYTE_COUNT
* index
) + i
], unsigned, parent
);
95 mir_create_dependency_graph(midgard_instruction
**instructions
, unsigned count
, unsigned node_count
)
97 size_t sz
= node_count
* BYTE_COUNT
;
99 struct util_dynarray
*last_read
= calloc(sizeof(struct util_dynarray
), sz
);
100 struct util_dynarray
*last_write
= calloc(sizeof(struct util_dynarray
), sz
);
102 for (unsigned i
= 0; i
< sz
; ++i
) {
103 util_dynarray_init(&last_read
[i
], NULL
);
104 util_dynarray_init(&last_write
[i
], NULL
);
107 /* Initialize dependency graph */
108 for (unsigned i
= 0; i
< count
; ++i
) {
109 instructions
[i
]->dependents
=
110 calloc(BITSET_WORDS(count
), sizeof(BITSET_WORD
));
112 instructions
[i
]->nr_dependencies
= 0;
115 /* Populate dependency graph */
116 for (signed i
= count
- 1; i
>= 0; --i
) {
117 if (instructions
[i
]->compact_branch
)
120 unsigned dest
= instructions
[i
]->dest
;
121 unsigned mask
= mir_bytemask(instructions
[i
]);
123 mir_foreach_src((*instructions
), s
) {
124 unsigned src
= instructions
[i
]->src
[s
];
126 if (src
< node_count
) {
127 unsigned readmask
= mir_bytemask_of_read_components(instructions
[i
], src
);
128 add_dependency(last_write
, src
, readmask
, instructions
, i
);
132 if (dest
< node_count
) {
133 add_dependency(last_read
, dest
, mask
, instructions
, i
);
134 add_dependency(last_write
, dest
, mask
, instructions
, i
);
135 mark_access(last_write
, dest
, mask
, i
);
138 mir_foreach_src((*instructions
), s
) {
139 unsigned src
= instructions
[i
]->src
[s
];
141 if (src
< node_count
) {
142 unsigned readmask
= mir_bytemask_of_read_components(instructions
[i
], src
);
143 mark_access(last_read
, src
, readmask
, i
);
148 /* If there is a branch, all instructions depend on it, as interblock
149 * execution must be purely in-order */
151 if (instructions
[count
- 1]->compact_branch
) {
152 BITSET_WORD
*dependents
= instructions
[count
- 1]->dependents
;
154 for (signed i
= count
- 2; i
>= 0; --i
) {
155 if (BITSET_TEST(dependents
, i
))
158 BITSET_SET(dependents
, i
);
159 instructions
[i
]->nr_dependencies
++;
163 /* Free the intermediate structures */
164 for (unsigned i
= 0; i
< sz
; ++i
) {
165 util_dynarray_fini(&last_read
[i
]);
166 util_dynarray_fini(&last_write
[i
]);
170 /* Does the mask cover more than a scalar? */
173 is_single_component_mask(unsigned mask
)
177 for (int c
= 0; c
< 8; ++c
) {
182 return components
== 1;
185 /* Helpers for scheudling */
188 mir_is_scalar(midgard_instruction
*ains
)
190 /* Do we try to use it as a vector op? */
191 if (!is_single_component_mask(ains
->mask
))
194 /* Otherwise, check mode hazards */
195 bool could_scalar
= true;
197 /* Only 16/32-bit can run on a scalar unit */
198 could_scalar
&= ains
->alu
.reg_mode
!= midgard_reg_mode_8
;
199 could_scalar
&= ains
->alu
.reg_mode
!= midgard_reg_mode_64
;
200 could_scalar
&= ains
->alu
.dest_override
== midgard_dest_override_none
;
202 if (ains
->alu
.reg_mode
== midgard_reg_mode_16
) {
203 /* If we're running in 16-bit mode, we
204 * can't have any 8-bit sources on the
205 * scalar unit (since the scalar unit
206 * doesn't understand 8-bit) */
208 midgard_vector_alu_src s1
=
209 vector_alu_from_unsigned(ains
->alu
.src1
);
211 could_scalar
&= !s1
.half
;
213 midgard_vector_alu_src s2
=
214 vector_alu_from_unsigned(ains
->alu
.src2
);
216 could_scalar
&= !s2
.half
;
222 /* How many bytes does this ALU instruction add to the bundle? */
225 bytes_for_instruction(midgard_instruction
*ains
)
227 if (ains
->unit
& UNITS_ANY_VECTOR
)
228 return sizeof(midgard_reg_info
) + sizeof(midgard_vector_alu
);
229 else if (ains
->unit
== ALU_ENAB_BRANCH
)
230 return sizeof(midgard_branch_extended
);
231 else if (ains
->compact_branch
)
232 return sizeof(ains
->br_compact
);
234 return sizeof(midgard_reg_info
) + sizeof(midgard_scalar_alu
);
237 /* We would like to flatten the linked list of midgard_instructions in a bundle
238 * to an array of pointers on the heap for easy indexing */
240 static midgard_instruction
**
241 flatten_mir(midgard_block
*block
, unsigned *len
)
243 *len
= list_length(&block
->instructions
);
248 midgard_instruction
**instructions
=
249 calloc(sizeof(midgard_instruction
*), *len
);
253 mir_foreach_instr_in_block(block
, ins
)
254 instructions
[i
++] = ins
;
259 /* The worklist is the set of instructions that can be scheduled now; that is,
260 * the set of instructions with no remaining dependencies */
263 mir_initialize_worklist(BITSET_WORD
*worklist
, midgard_instruction
**instructions
, unsigned count
)
265 for (unsigned i
= 0; i
< count
; ++i
) {
266 if (instructions
[i
]->nr_dependencies
== 0)
267 BITSET_SET(worklist
, i
);
271 /* Update the worklist after an instruction terminates. Remove its edges from
272 * the graph and if that causes any node to have no dependencies, add it to the
277 BITSET_WORD
*worklist
, unsigned count
,
278 midgard_instruction
**instructions
, midgard_instruction
*done
)
280 /* Sanity check: if no instruction terminated, there is nothing to do.
281 * If the instruction that terminated had dependencies, that makes no
282 * sense and means we messed up the worklist. Finally, as the purpose
283 * of this routine is to update dependents, we abort early if there are
284 * no dependents defined. */
289 assert(done
->nr_dependencies
== 0);
291 if (!done
->dependents
)
294 /* We have an instruction with dependents. Iterate each dependent to
295 * remove one dependency (`done`), adding dependents to the worklist
300 BITSET_FOREACH_SET(i
, tmp
, done
->dependents
, count
) {
301 assert(instructions
[i
]->nr_dependencies
);
303 if (!(--instructions
[i
]->nr_dependencies
))
304 BITSET_SET(worklist
, i
);
307 free(done
->dependents
);
310 /* While scheduling, we need to choose instructions satisfying certain
311 * criteria. As we schedule backwards, we choose the *last* instruction in the
312 * worklist to simulate in-order scheduling. Chosen instructions must satisfy a
313 * given predicate. */
315 struct midgard_predicate
{
316 /* TAG or ~0 for dont-care */
319 /* True if we want to pop off the chosen instruction */
322 /* For ALU, choose only this unit */
325 /* State for bundle constants. constants is the actual constants
326 * for the bundle. constant_count is the number of bytes (up to
327 * 16) currently in use for constants. When picking in destructive
328 * mode, the constants array will be updated, and the instruction
329 * will be adjusted to index into the constants array */
332 unsigned constant_count
;
335 /* Exclude this destination (if not ~0) */
338 /* Don't schedule instructions consuming conditionals (since we already
339 * scheduled one). Excludes conditional branches and csel */
342 /* Require a minimal mask and (if nonzero) given destination. Used for
343 * writeout optimizations */
349 /* For an instruction that can fit, adjust it to fit and update the constants
350 * array, in destructive mode. Returns whether the fitting was successful. */
353 mir_adjust_constants(midgard_instruction
*ins
,
354 struct midgard_predicate
*pred
,
357 /* Blend constants dominate */
358 if (ins
->has_blend_constant
) {
359 if (pred
->constant_count
)
361 else if (destructive
) {
362 pred
->blend_constant
= true;
363 pred
->constant_count
= 16;
368 /* No constant, nothing to adjust */
369 if (!ins
->has_constants
)
372 if (ins
->alu
.reg_mode
!= midgard_reg_mode_32
) {
373 /* TODO: 16-bit constant combining */
374 if (pred
->constant_count
)
377 uint16_t *bundles
= (uint16_t *) pred
->constants
;
378 uint32_t *constants
= (uint32_t *) ins
->constants
;
380 /* Copy them wholesale */
381 for (unsigned i
= 0; i
< 4; ++i
)
382 bundles
[i
] = constants
[i
];
384 pred
->constant_count
= 16;
386 /* Pack 32-bit constants */
387 uint32_t *bundles
= (uint32_t *) pred
->constants
;
388 uint32_t *constants
= (uint32_t *) ins
->constants
;
389 unsigned r_constant
= SSA_FIXED_REGISTER(REGISTER_CONSTANT
);
390 unsigned mask
= mir_from_bytemask(mir_bytemask_of_read_components(ins
, r_constant
), midgard_reg_mode_32
);
392 /* First, check if it fits */
393 unsigned count
= DIV_ROUND_UP(pred
->constant_count
, sizeof(uint32_t));
394 unsigned existing_count
= count
;
396 for (unsigned i
= 0; i
< 4; ++i
) {
397 if (!(mask
& (1 << i
)))
402 /* Look for existing constant */
403 for (unsigned j
= 0; j
< existing_count
; ++j
) {
404 if (bundles
[j
] == constants
[i
]) {
413 /* If the constant is new, check ourselves */
414 for (unsigned j
= 0; j
< i
; ++j
) {
415 if (constants
[j
] == constants
[i
]) {
424 /* Otherwise, this is a new constant */
428 /* Check if we have space */
432 /* If non-destructive, we're done */
436 /* If destructive, let's copy in the new constants and adjust
437 * swizzles to pack it in. */
439 unsigned indices
[16] = { 0 };
442 count
= existing_count
;
444 for (unsigned i
= 0; i
< 4; ++i
) {
445 if (!(mask
& (1 << i
)))
448 uint32_t cons
= constants
[i
];
449 bool constant_found
= false;
451 /* Search for the constant */
452 for (unsigned j
= 0; j
< count
; ++j
) {
453 if (bundles
[j
] != cons
)
456 /* We found it, reuse */
458 constant_found
= true;
465 /* We didn't find it, so allocate it */
466 unsigned idx
= count
++;
468 /* We have space, copy it in! */
473 pred
->constant_count
= count
* sizeof(uint32_t);
475 /* Use indices as a swizzle */
477 mir_foreach_src(ins
, s
) {
478 if (ins
->src
[s
] == r_constant
)
479 mir_compose_swizzle(ins
->swizzle
[s
], indices
, ins
->swizzle
[s
]);
486 static midgard_instruction
*
487 mir_choose_instruction(
488 midgard_instruction
**instructions
,
489 BITSET_WORD
*worklist
, unsigned count
,
490 struct midgard_predicate
*predicate
)
492 /* Parse the predicate */
493 unsigned tag
= predicate
->tag
;
494 bool alu
= tag
== TAG_ALU_4
;
495 unsigned unit
= predicate
->unit
;
496 bool branch
= alu
&& (unit
== ALU_ENAB_BR_COMPACT
);
497 bool scalar
= (unit
!= ~0) && (unit
& UNITS_SCALAR
);
498 bool no_cond
= predicate
->no_cond
;
500 unsigned mask
= predicate
->mask
;
501 unsigned dest
= predicate
->dest
;
502 bool needs_dest
= mask
& 0xF;
504 /* Iterate to find the best instruction satisfying the predicate */
508 signed best_index
= -1;
509 bool best_conditional
= false;
511 /* Enforce a simple metric limiting distance to keep down register
512 * pressure. TOOD: replace with liveness tracking for much better
515 unsigned max_active
= 0;
516 unsigned max_distance
= 6;
518 BITSET_FOREACH_SET(i
, tmp
, worklist
, count
) {
519 max_active
= MAX2(max_active
, i
);
522 BITSET_FOREACH_SET(i
, tmp
, worklist
, count
) {
523 if ((max_active
- i
) >= max_distance
)
526 if (tag
!= ~0 && instructions
[i
]->type
!= tag
)
529 if (predicate
->exclude
!= ~0 && instructions
[i
]->dest
== predicate
->exclude
)
532 if (alu
&& !branch
&& !(alu_opcode_props
[instructions
[i
]->alu
.op
].props
& unit
))
535 if (branch
&& !instructions
[i
]->compact_branch
)
538 if (alu
&& scalar
&& !mir_is_scalar(instructions
[i
]))
541 if (alu
&& !mir_adjust_constants(instructions
[i
], predicate
, false))
544 if (needs_dest
&& instructions
[i
]->dest
!= dest
)
547 if (mask
&& ((~instructions
[i
]->mask
) & mask
))
550 bool conditional
= alu
&& !branch
&& OP_IS_CSEL(instructions
[i
]->alu
.op
);
551 conditional
|= (branch
&& !instructions
[i
]->prepacked_branch
&& instructions
[i
]->branch
.conditional
);
553 if (conditional
&& no_cond
)
556 /* Simulate in-order scheduling */
557 if ((signed) i
< best_index
)
561 best_conditional
= conditional
;
565 /* Did we find anything? */
570 /* If we found something, remove it from the worklist */
571 assert(best_index
< count
);
573 if (predicate
->destructive
) {
574 BITSET_CLEAR(worklist
, best_index
);
577 mir_adjust_constants(instructions
[best_index
], predicate
, true);
579 /* Once we schedule a conditional, we can't again */
580 predicate
->no_cond
|= best_conditional
;
583 return instructions
[best_index
];
586 /* Still, we don't choose instructions in a vacuum. We need a way to choose the
587 * best bundle type (ALU, load/store, texture). Nondestructive. */
591 midgard_instruction
**instructions
,
592 BITSET_WORD
*worklist
, unsigned count
)
594 /* At the moment, our algorithm is very simple - use the bundle of the
595 * best instruction, regardless of what else could be scheduled
596 * alongside it. This is not optimal but it works okay for in-order */
598 struct midgard_predicate predicate
= {
600 .destructive
= false,
604 midgard_instruction
*chosen
= mir_choose_instruction(instructions
, worklist
, count
, &predicate
);
612 /* We want to choose an ALU instruction filling a given unit */
614 mir_choose_alu(midgard_instruction
**slot
,
615 midgard_instruction
**instructions
,
616 BITSET_WORD
*worklist
, unsigned len
,
617 struct midgard_predicate
*predicate
,
620 /* Did we already schedule to this slot? */
624 /* Try to schedule something, if not */
625 predicate
->unit
= unit
;
626 *slot
= mir_choose_instruction(instructions
, worklist
, len
, predicate
);
628 /* Store unit upon scheduling */
629 if (*slot
&& !((*slot
)->compact_branch
))
630 (*slot
)->unit
= unit
;
633 /* When we are scheduling a branch/csel, we need the consumed condition in the
634 * same block as a pipeline register. There are two options to enable this:
636 * - Move the conditional into the bundle. Preferred, but only works if the
637 * conditional is used only once and is from this block.
638 * - Copy the conditional.
640 * We search for the conditional. If it's in this block, single-use, and
641 * without embedded constants, we schedule it immediately. Otherwise, we
642 * schedule a move for it.
644 * mir_comparison_mobile is a helper to find the moveable condition.
648 mir_comparison_mobile(
649 compiler_context
*ctx
,
650 midgard_instruction
**instructions
,
651 struct midgard_predicate
*predicate
,
655 if (!mir_single_use(ctx
, cond
))
660 for (unsigned i
= 0; i
< count
; ++i
) {
661 if (instructions
[i
]->dest
!= cond
)
664 /* Must fit in an ALU bundle */
665 if (instructions
[i
]->type
!= TAG_ALU_4
)
668 /* We'll need to rewrite to .w but that doesn't work for vector
669 * ops that don't replicate (ball/bany), so bail there */
671 if (GET_CHANNEL_COUNT(alu_opcode_props
[instructions
[i
]->alu
.op
].props
))
674 /* Ensure it will fit with constants */
676 if (!mir_adjust_constants(instructions
[i
], predicate
, false))
679 /* Ensure it is written only once */
687 /* Inject constants now that we are sure we want to */
689 mir_adjust_constants(instructions
[ret
], predicate
, true);
694 /* Using the information about the moveable conditional itself, we either pop
695 * that condition off the worklist for use now, or create a move to
696 * artificially schedule instead as a fallback */
698 static midgard_instruction
*
699 mir_schedule_comparison(
700 compiler_context
*ctx
,
701 midgard_instruction
**instructions
,
702 struct midgard_predicate
*predicate
,
703 BITSET_WORD
*worklist
, unsigned count
,
704 unsigned cond
, bool vector
, unsigned *swizzle
,
705 midgard_instruction
*user
)
707 /* TODO: swizzle when scheduling */
709 (!vector
&& (swizzle
[0] == 0)) ?
710 mir_comparison_mobile(ctx
, instructions
, predicate
, count
, cond
) : ~0;
712 /* If we can, schedule the condition immediately */
713 if ((comp_i
!= ~0) && BITSET_TEST(worklist
, comp_i
)) {
714 assert(comp_i
< count
);
715 BITSET_CLEAR(worklist
, comp_i
);
716 return instructions
[comp_i
];
719 /* Otherwise, we insert a move */
721 midgard_instruction mov
= v_mov(cond
, cond
);
722 mov
.mask
= vector
? 0xF : 0x1;
723 memcpy(mov
.swizzle
[1], swizzle
, sizeof(mov
.swizzle
[1]));
725 return mir_insert_instruction_before(ctx
, user
, mov
);
728 /* Most generally, we need instructions writing to r31 in the appropriate
731 static midgard_instruction
*
732 mir_schedule_condition(compiler_context
*ctx
,
733 struct midgard_predicate
*predicate
,
734 BITSET_WORD
*worklist
, unsigned count
,
735 midgard_instruction
**instructions
,
736 midgard_instruction
*last
)
738 /* For a branch, the condition is the only argument; for csel, third */
739 bool branch
= last
->compact_branch
;
740 unsigned condition_index
= branch
? 0 : 2;
742 /* csel_v is vector; otherwise, conditions are scalar */
743 bool vector
= !branch
&& OP_IS_CSEL_V(last
->alu
.op
);
745 /* Grab the conditional instruction */
747 midgard_instruction
*cond
= mir_schedule_comparison(
748 ctx
, instructions
, predicate
, worklist
, count
, last
->src
[condition_index
],
749 vector
, last
->swizzle
[2], last
);
751 /* We have exclusive reign over this (possibly move) conditional
752 * instruction. We can rewrite into a pipeline conditional register */
754 predicate
->exclude
= cond
->dest
;
755 cond
->dest
= SSA_FIXED_REGISTER(31);
758 cond
->mask
= (1 << COMPONENT_W
);
760 mir_foreach_src(cond
, s
) {
761 if (cond
->src
[s
] == ~0)
764 for (unsigned q
= 0; q
< 4; ++q
)
765 cond
->swizzle
[s
][q
+ COMPONENT_W
] = cond
->swizzle
[s
][q
];
769 /* Schedule the unit: csel is always in the latter pipeline, so a csel
770 * condition must be in the former pipeline stage (vmul/sadd),
771 * depending on scalar/vector of the instruction itself. A branch must
772 * be written from the latter pipeline stage and a branch condition is
773 * always scalar, so it is always in smul (exception: ball/bany, which
777 cond
->unit
= UNIT_SMUL
;
779 cond
->unit
= vector
? UNIT_VMUL
: UNIT_SADD
;
784 /* Schedules a single bundle of the given type */
786 static midgard_bundle
787 mir_schedule_texture(
788 midgard_instruction
**instructions
,
789 BITSET_WORD
*worklist
, unsigned len
)
791 struct midgard_predicate predicate
= {
792 .tag
= TAG_TEXTURE_4
,
797 midgard_instruction
*ins
=
798 mir_choose_instruction(instructions
, worklist
, len
, &predicate
);
800 mir_update_worklist(worklist
, len
, instructions
, ins
);
802 struct midgard_bundle out
= {
803 .tag
= TAG_TEXTURE_4
,
804 .instruction_count
= 1,
805 .instructions
= { ins
}
811 static midgard_bundle
813 midgard_instruction
**instructions
,
814 BITSET_WORD
*worklist
, unsigned len
)
816 struct midgard_predicate predicate
= {
817 .tag
= TAG_LOAD_STORE_4
,
822 /* Try to pick two load/store ops. Second not gauranteed to exist */
824 midgard_instruction
*ins
=
825 mir_choose_instruction(instructions
, worklist
, len
, &predicate
);
827 midgard_instruction
*pair
=
828 mir_choose_instruction(instructions
, worklist
, len
, &predicate
);
830 struct midgard_bundle out
= {
831 .tag
= TAG_LOAD_STORE_4
,
832 .instruction_count
= pair
? 2 : 1,
833 .instructions
= { ins
, pair
}
836 /* We have to update the worklist atomically, since the two
837 * instructions run concurrently (TODO: verify it's not pipelined) */
839 mir_update_worklist(worklist
, len
, instructions
, ins
);
840 mir_update_worklist(worklist
, len
, instructions
, pair
);
845 static midgard_bundle
847 compiler_context
*ctx
,
848 midgard_instruction
**instructions
,
849 BITSET_WORD
*worklist
, unsigned len
)
851 struct midgard_bundle bundle
= {};
853 unsigned bytes_emitted
= sizeof(bundle
.control
);
855 struct midgard_predicate predicate
= {
859 .constants
= (uint8_t *) bundle
.constants
862 midgard_instruction
*vmul
= NULL
;
863 midgard_instruction
*vadd
= NULL
;
864 midgard_instruction
*vlut
= NULL
;
865 midgard_instruction
*smul
= NULL
;
866 midgard_instruction
*sadd
= NULL
;
867 midgard_instruction
*branch
= NULL
;
869 mir_choose_alu(&branch
, instructions
, worklist
, len
, &predicate
, ALU_ENAB_BR_COMPACT
);
870 mir_update_worklist(worklist
, len
, instructions
, branch
);
871 bool writeout
= branch
&& branch
->writeout
;
873 if (branch
&& !branch
->prepacked_branch
&& branch
->branch
.conditional
) {
874 midgard_instruction
*cond
= mir_schedule_condition(ctx
, &predicate
, worklist
, len
, instructions
, branch
);
876 if (cond
->unit
== UNIT_VADD
)
878 else if (cond
->unit
== UNIT_SMUL
)
881 unreachable("Bad condition");
884 mir_choose_alu(&smul
, instructions
, worklist
, len
, &predicate
, UNIT_SMUL
);
887 mir_choose_alu(&vlut
, instructions
, worklist
, len
, &predicate
, UNIT_VLUT
);
889 mir_choose_alu(&vadd
, instructions
, worklist
, len
, &predicate
, UNIT_VADD
);
891 mir_update_worklist(worklist
, len
, instructions
, vlut
);
892 mir_update_worklist(worklist
, len
, instructions
, vadd
);
893 mir_update_worklist(worklist
, len
, instructions
, smul
);
895 bool vadd_csel
= vadd
&& OP_IS_CSEL(vadd
->alu
.op
);
896 bool smul_csel
= smul
&& OP_IS_CSEL(smul
->alu
.op
);
898 if (vadd_csel
|| smul_csel
) {
899 midgard_instruction
*ins
= vadd_csel
? vadd
: smul
;
900 midgard_instruction
*cond
= mir_schedule_condition(ctx
, &predicate
, worklist
, len
, instructions
, ins
);
902 if (cond
->unit
== UNIT_VMUL
)
904 else if (cond
->unit
== UNIT_SADD
)
907 unreachable("Bad condition");
910 /* Stage 2, let's schedule sadd before vmul for writeout */
911 mir_choose_alu(&sadd
, instructions
, worklist
, len
, &predicate
, UNIT_SADD
);
913 /* Check if writeout reads its own register */
914 bool bad_writeout
= false;
916 if (branch
&& branch
->writeout
) {
917 midgard_instruction
*stages
[] = { sadd
, vadd
, smul
};
918 unsigned src
= (branch
->src
[0] == ~0) ? SSA_FIXED_REGISTER(0) : branch
->src
[0];
919 unsigned writeout_mask
= 0x0;
921 for (unsigned i
= 0; i
< ARRAY_SIZE(stages
); ++i
) {
925 if (stages
[i
]->dest
!= src
)
928 writeout_mask
|= stages
[i
]->mask
;
929 bad_writeout
|= mir_has_arg(stages
[i
], branch
->src
[0]);
932 /* It's possible we'll be able to schedule something into vmul
933 * to fill r0. Let's peak into the future, trying to schedule
934 * vmul specially that way. */
936 if (!bad_writeout
&& writeout_mask
!= 0xF) {
937 predicate
.unit
= UNIT_VMUL
;
938 predicate
.dest
= src
;
939 predicate
.mask
= writeout_mask
^ 0xF;
941 struct midgard_instruction
*peaked
=
942 mir_choose_instruction(instructions
, worklist
, len
, &predicate
);
946 vmul
->unit
= UNIT_VMUL
;
947 writeout_mask
|= predicate
.mask
;
948 assert(writeout_mask
== 0xF);
952 predicate
.dest
= predicate
.mask
= 0;
955 /* Finally, add a move if necessary */
956 if (bad_writeout
|| writeout_mask
!= 0xF) {
957 unsigned temp
= (branch
->src
[0] == ~0) ? SSA_FIXED_REGISTER(0) : make_compiler_temp(ctx
);
958 midgard_instruction mov
= v_mov(src
, temp
);
959 vmul
= mem_dup(&mov
, sizeof(midgard_instruction
));
960 vmul
->unit
= UNIT_VMUL
;
961 vmul
->mask
= 0xF ^ writeout_mask
;
962 /* TODO: Don't leak */
964 /* Rewrite to use our temp */
966 for (unsigned i
= 0; i
< ARRAY_SIZE(stages
); ++i
) {
968 mir_rewrite_index_dst_single(stages
[i
], src
, temp
);
971 mir_rewrite_index_src_single(branch
, src
, temp
);
975 mir_choose_alu(&vmul
, instructions
, worklist
, len
, &predicate
, UNIT_VMUL
);
977 mir_update_worklist(worklist
, len
, instructions
, vmul
);
978 mir_update_worklist(worklist
, len
, instructions
, sadd
);
980 bundle
.has_blend_constant
= predicate
.blend_constant
;
981 bundle
.has_embedded_constants
= predicate
.constant_count
> 0;
983 unsigned padding
= 0;
985 /* Now that we have finished scheduling, build up the bundle */
986 midgard_instruction
*stages
[] = { vmul
, sadd
, vadd
, smul
, vlut
, branch
};
988 for (unsigned i
= 0; i
< ARRAY_SIZE(stages
); ++i
) {
990 bundle
.control
|= stages
[i
]->unit
;
991 bytes_emitted
+= bytes_for_instruction(stages
[i
]);
992 bundle
.instructions
[bundle
.instruction_count
++] = stages
[i
];
996 /* Pad ALU op to nearest word */
998 if (bytes_emitted
& 15) {
999 padding
= 16 - (bytes_emitted
& 15);
1000 bytes_emitted
+= padding
;
1003 /* Constants must always be quadwords */
1004 if (bundle
.has_embedded_constants
)
1005 bytes_emitted
+= 16;
1007 /* Size ALU instruction for tag */
1008 bundle
.tag
= (TAG_ALU_4
) + (bytes_emitted
/ 16) - 1;
1009 bundle
.padding
= padding
;
1010 bundle
.control
|= bundle
.tag
;
1015 /* Schedule a single block by iterating its instruction to create bundles.
1016 * While we go, tally about the bundle sizes to compute the block size. */
1020 schedule_block(compiler_context
*ctx
, midgard_block
*block
)
1022 /* Copy list to dynamic array */
1024 midgard_instruction
**instructions
= flatten_mir(block
, &len
);
1029 /* Calculate dependencies and initial worklist */
1030 unsigned node_count
= ctx
->temp_count
+ 1;
1031 mir_create_dependency_graph(instructions
, len
, node_count
);
1033 /* Allocate the worklist */
1034 size_t sz
= BITSET_WORDS(len
) * sizeof(BITSET_WORD
);
1035 BITSET_WORD
*worklist
= calloc(sz
, 1);
1036 mir_initialize_worklist(worklist
, instructions
, len
);
1038 struct util_dynarray bundles
;
1039 util_dynarray_init(&bundles
, NULL
);
1041 block
->quadword_count
= 0;
1042 unsigned blend_offset
= 0;
1045 unsigned tag
= mir_choose_bundle(instructions
, worklist
, len
);
1046 midgard_bundle bundle
;
1048 if (tag
== TAG_TEXTURE_4
)
1049 bundle
= mir_schedule_texture(instructions
, worklist
, len
);
1050 else if (tag
== TAG_LOAD_STORE_4
)
1051 bundle
= mir_schedule_ldst(instructions
, worklist
, len
);
1052 else if (tag
== TAG_ALU_4
)
1053 bundle
= mir_schedule_alu(ctx
, instructions
, worklist
, len
);
1057 util_dynarray_append(&bundles
, midgard_bundle
, bundle
);
1059 if (bundle
.has_blend_constant
)
1060 blend_offset
= block
->quadword_count
;
1062 block
->quadword_count
+= quadword_size(bundle
.tag
);
1065 /* We emitted bundles backwards; copy into the block in reverse-order */
1067 util_dynarray_init(&block
->bundles
, NULL
);
1068 util_dynarray_foreach_reverse(&bundles
, midgard_bundle
, bundle
) {
1069 util_dynarray_append(&block
->bundles
, midgard_bundle
, *bundle
);
1072 /* Blend constant was backwards as well. blend_offset if set is
1073 * strictly positive, as an offset of zero would imply constants before
1074 * any instructions which is invalid in Midgard. TODO: blend constants
1075 * are broken if you spill since then quadword_count becomes invalid
1079 ctx
->blend_constant_offset
= ((ctx
->quadword_count
+ block
->quadword_count
) - blend_offset
- 1) * 0x10;
1081 block
->is_scheduled
= true;
1082 ctx
->quadword_count
+= block
->quadword_count
;
1084 /* Reorder instructions to match bundled. First remove existing
1085 * instructions and then recreate the list */
1087 mir_foreach_instr_in_block_safe(block
, ins
) {
1088 list_del(&ins
->link
);
1091 mir_foreach_instr_in_block_scheduled_rev(block
, ins
) {
1092 list_add(&ins
->link
, &block
->instructions
);
1096 /* When we're 'squeezing down' the values in the IR, we maintain a hash
1100 find_or_allocate_temp(compiler_context
*ctx
, unsigned hash
)
1102 if (hash
>= SSA_FIXED_MINIMUM
)
1105 unsigned temp
= (uintptr_t) _mesa_hash_table_u64_search(
1106 ctx
->hash_to_temp
, hash
+ 1);
1111 /* If no temp is find, allocate one */
1112 temp
= ctx
->temp_count
++;
1113 ctx
->max_hash
= MAX2(ctx
->max_hash
, hash
);
1115 _mesa_hash_table_u64_insert(ctx
->hash_to_temp
,
1116 hash
+ 1, (void *) ((uintptr_t) temp
+ 1));
1121 /* Reassigns numbering to get rid of gaps in the indices and to prioritize
1122 * smaller register classes */
1125 mir_squeeze_index(compiler_context
*ctx
)
1128 ctx
->temp_count
= 0;
1129 /* TODO don't leak old hash_to_temp */
1130 ctx
->hash_to_temp
= _mesa_hash_table_u64_create(NULL
);
1132 /* We need to prioritize texture registers on older GPUs so we don't
1133 * fail RA trying to assign to work registers r0/r1 when a work
1134 * register is already there */
1136 mir_foreach_instr_global(ctx
, ins
) {
1137 if (ins
->type
== TAG_TEXTURE_4
)
1138 ins
->dest
= find_or_allocate_temp(ctx
, ins
->dest
);
1141 mir_foreach_instr_global(ctx
, ins
) {
1142 if (ins
->type
!= TAG_TEXTURE_4
)
1143 ins
->dest
= find_or_allocate_temp(ctx
, ins
->dest
);
1145 for (unsigned i
= 0; i
< ARRAY_SIZE(ins
->src
); ++i
)
1146 ins
->src
[i
] = find_or_allocate_temp(ctx
, ins
->src
[i
]);
1150 static midgard_instruction
1151 v_load_store_scratch(
1157 /* We index by 32-bit vec4s */
1158 unsigned byte
= (index
* 4 * 4);
1160 midgard_instruction ins
= {
1161 .type
= TAG_LOAD_STORE_4
,
1164 .src
= { ~0, ~0, ~0 },
1165 .swizzle
= SWIZZLE_IDENTITY_4
,
1167 .op
= is_store
? midgard_op_st_int4
: midgard_op_ld_int4
,
1169 /* For register spilling - to thread local storage */
1174 /* If we spill an unspill, RA goes into an infinite loop */
1178 ins
.constants
[0] = byte
;
1181 /* r0 = r26, r1 = r27 */
1182 assert(srcdest
== SSA_FIXED_REGISTER(26) || srcdest
== SSA_FIXED_REGISTER(27));
1183 ins
.src
[0] = srcdest
;
1191 /* If register allocation fails, find the best spill node and spill it to fix
1192 * whatever the issue was. This spill node could be a work register (spilling
1193 * to thread local storage), but it could also simply be a special register
1194 * that needs to spill to become a work register. */
1196 static void mir_spill_register(
1197 compiler_context
*ctx
,
1198 struct lcra_state
*l
,
1199 unsigned *spill_count
)
1201 unsigned spill_index
= ctx
->temp_count
;
1203 /* Our first step is to calculate spill cost to figure out the best
1204 * spill node. All nodes are equal in spill cost, but we can't spill
1205 * nodes written to from an unspill */
1207 unsigned *cost
= calloc(ctx
->temp_count
, sizeof(cost
[0]));
1209 mir_foreach_instr_global(ctx
, ins
) {
1210 if (ins
->dest
< ctx
->temp_count
)
1213 mir_foreach_src(ins
, s
) {
1214 if (ins
->src
[s
] < ctx
->temp_count
)
1215 cost
[ins
->src
[s
]]++;
1219 for (unsigned i
= 0; i
< ctx
->temp_count
; ++i
)
1220 lcra_set_node_spill_cost(l
, i
, cost
[i
]);
1222 /* We can't spill any bundles that contain unspills. This could be
1223 * optimized to allow use of r27 to spill twice per bundle, but if
1224 * you're at the point of optimizing spilling, it's too late.
1226 * We also can't double-spill. */
1228 mir_foreach_block(ctx
, block
) {
1229 mir_foreach_bundle_in_block(block
, bun
) {
1230 bool no_spill
= false;
1232 for (unsigned i
= 0; i
< bun
->instruction_count
; ++i
) {
1233 no_spill
|= bun
->instructions
[i
]->no_spill
;
1235 if (bun
->instructions
[i
]->no_spill
) {
1236 mir_foreach_src(bun
->instructions
[i
], s
) {
1237 unsigned src
= bun
->instructions
[i
]->src
[s
];
1239 if (src
< ctx
->temp_count
)
1240 lcra_set_node_spill_cost(l
, src
, -1);
1248 for (unsigned i
= 0; i
< bun
->instruction_count
; ++i
) {
1249 unsigned dest
= bun
->instructions
[i
]->dest
;
1250 if (dest
< ctx
->temp_count
)
1251 lcra_set_node_spill_cost(l
, dest
, -1);
1256 int spill_node
= lcra_get_best_spill_node(l
);
1258 if (spill_node
< 0) {
1259 mir_print_shader(ctx
);
1263 /* We have a spill node, so check the class. Work registers
1264 * legitimately spill to TLS, but special registers just spill to work
1267 bool is_special
= l
->class[spill_node
] != REG_CLASS_WORK
;
1268 bool is_special_w
= l
->class[spill_node
] == REG_CLASS_TEXW
;
1270 /* Allocate TLS slot (maybe) */
1271 unsigned spill_slot
= !is_special
? (*spill_count
)++ : 0;
1273 /* For TLS, replace all stores to the spilled node. For
1274 * special reads, just keep as-is; the class will be demoted
1275 * implicitly. For special writes, spill to a work register */
1277 if (!is_special
|| is_special_w
) {
1279 spill_slot
= spill_index
++;
1281 mir_foreach_block(ctx
, block
) {
1282 mir_foreach_instr_in_block_safe(block
, ins
) {
1283 if (ins
->dest
!= spill_node
) continue;
1285 midgard_instruction st
;
1288 st
= v_mov(spill_node
, spill_slot
);
1291 ins
->dest
= SSA_FIXED_REGISTER(26);
1292 ins
->no_spill
= true;
1293 st
= v_load_store_scratch(ins
->dest
, spill_slot
, true, ins
->mask
);
1296 /* Hint: don't rewrite this node */
1299 mir_insert_instruction_after_scheduled(ctx
, block
, ins
, st
);
1307 /* For special reads, figure out how many bytes we need */
1308 unsigned read_bytemask
= 0;
1310 mir_foreach_instr_global_safe(ctx
, ins
) {
1311 read_bytemask
|= mir_bytemask_of_read_components(ins
, spill_node
);
1314 /* Insert a load from TLS before the first consecutive
1315 * use of the node, rewriting to use spilled indices to
1316 * break up the live range. Or, for special, insert a
1317 * move. Ironically the latter *increases* register
1318 * pressure, but the two uses of the spilling mechanism
1319 * are somewhat orthogonal. (special spilling is to use
1320 * work registers to back special registers; TLS
1321 * spilling is to use memory to back work registers) */
1323 mir_foreach_block(ctx
, block
) {
1324 bool consecutive_skip
= false;
1325 unsigned consecutive_index
= 0;
1327 mir_foreach_instr_in_block(block
, ins
) {
1328 /* We can't rewrite the moves used to spill in the
1329 * first place. These moves are hinted. */
1330 if (ins
->hint
) continue;
1332 if (!mir_has_arg(ins
, spill_node
)) {
1333 consecutive_skip
= false;
1337 if (consecutive_skip
) {
1339 mir_rewrite_index_src_single(ins
, spill_node
, consecutive_index
);
1343 if (!is_special_w
) {
1344 consecutive_index
= ++spill_index
;
1346 midgard_instruction
*before
= ins
;
1348 /* TODO: Remove me I'm a fossil */
1349 if (ins
->type
== TAG_ALU_4
&& OP_IS_CSEL(ins
->alu
.op
))
1350 before
= mir_prev_op(before
);
1352 midgard_instruction st
;
1356 st
= v_mov(spill_node
, consecutive_index
);
1360 st
= v_load_store_scratch(consecutive_index
, spill_slot
, false, 0xF);
1363 /* Mask the load based on the component count
1364 * actually needed to prevent RA loops */
1366 st
.mask
= mir_from_bytemask(read_bytemask
, midgard_reg_mode_32
);
1368 mir_insert_instruction_before_scheduled(ctx
, block
, before
, st
);
1369 // consecutive_skip = true;
1371 /* Special writes already have their move spilled in */
1372 consecutive_index
= spill_slot
;
1376 /* Rewrite to use */
1377 mir_rewrite_index_src_single(ins
, spill_node
, consecutive_index
);
1386 mir_foreach_instr_global(ctx
, ins
) {
1392 schedule_program(compiler_context
*ctx
)
1394 struct lcra_state
*l
= NULL
;
1395 bool spilled
= false;
1396 int iter_count
= 1000; /* max iterations */
1398 /* Number of 128-bit slots in memory we've spilled into */
1399 unsigned spill_count
= 0;
1401 midgard_promote_uniforms(ctx
, 16);
1403 /* Must be lowered right before RA */
1404 mir_squeeze_index(ctx
);
1405 mir_lower_special_reads(ctx
);
1406 mir_squeeze_index(ctx
);
1408 /* Lowering can introduce some dead moves */
1410 mir_foreach_block(ctx
, block
) {
1411 midgard_opt_dead_move_eliminate(ctx
, block
);
1412 schedule_block(ctx
, block
);
1415 mir_create_pipeline_registers(ctx
);
1419 mir_spill_register(ctx
, l
, &spill_count
);
1421 mir_squeeze_index(ctx
);
1422 mir_invalidate_liveness(ctx
);
1425 l
= allocate_registers(ctx
, &spilled
);
1426 } while(spilled
&& ((iter_count
--) > 0));
1428 if (iter_count
<= 0) {
1429 fprintf(stderr
, "panfrost: Gave up allocating registers, rendering will be incomplete\n");
1433 /* Report spilling information. spill_count is in 128-bit slots (vec4 x
1434 * fp32), but tls_size is in bytes, so multiply by 16 */
1436 ctx
->tls_size
= spill_count
* 16;
1438 install_registers(ctx
, l
);