544 template <
typename Jump>
554 void move_to_phi_nodes(BlockIndex target) {
555 if (analyzer.block_has_phis(target)) {
556 move_to_phi_nodes_impl(target);
560 void move_to_phi_nodes_impl(BlockIndex target);
566 return analyzer.block_has_phis(target);
571 BlockIndex next_block()
const;
573 bool try_force_fixed_assignment(IRValueRef)
const {
return false; }
575 bool hook_post_func_sym_init() {
return true; }
577 void analysis_start() {}
579 void analysis_end() {}
581 void reloc_text(SymRef sym, u32 type, u64 offset, i64 addend = 0) {
582 this->assembler.reloc_sec(
583 text_writer.get_sec_ref(), sym, type, offset, addend);
588 this->text_writer.label_place(label, text_writer.offset());
592 SymRef get_personality_sym();
594 bool compile_func(IRFuncRef func, u32 func_idx);
596 bool compile_block(IRBlockRef block, u32 block_idx);
600#include "GenericValuePart.hpp"
601#include "ScratchReg.hpp"
602#include "ValuePartRef.hpp"
603#include "ValueRef.hpp"
607template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
608template <
typename CBDerived>
611 if (!cca.byval && cca.bank == RegBank{}) {
612 cca.bank = vp.bank();
613 cca.size = vp.part_size();
616 assigner.assign_arg(cca);
617 bool needs_ext = cca.int_ext != 0;
618 bool ext_sign = cca.int_ext >> 7;
619 unsigned ext_bits = cca.int_ext & 0x3f;
622 derived()->add_arg_byval(vp, cca);
624 }
else if (!cca.reg.valid()) {
626 auto ext = std::move(vp).into_extended(&compiler, ext_sign, ext_bits, 64);
627 derived()->add_arg_stack(ext, cca);
628 ext.reset(&compiler);
630 derived()->add_arg_stack(vp, cca);
634 if (vp.is_in_reg(cca.reg)) {
635 if (!vp.can_salvage()) {
636 compiler.evict_reg(cca.reg);
638 vp.salvage(&compiler);
641 compiler.generate_raw_intext(cca.reg, cca.reg, ext_sign, ext_bits, 64);
644 if (compiler.register_file.is_used(cca.reg)) {
645 compiler.evict_reg(cca.reg);
647 if (vp.can_salvage()) {
648 AsmReg vp_reg = vp.salvage(&compiler);
650 compiler.generate_raw_intext(cca.reg, vp_reg, ext_sign, ext_bits, 64);
652 compiler.mov(cca.reg, vp_reg, cca.size);
654 }
else if (needs_ext && vp.is_const()) {
655 u64 val = vp.const_data()[0];
657 ext_sign ? util::sext(val, ext_bits) : util::zext(val, ext_bits);
658 compiler.materialize_constant(&extended, cca.bank, 8, cca.reg);
660 vp.reload_into_specific_fixed(&compiler, cca.reg);
662 compiler.generate_raw_intext(
663 cca.reg, cca.reg, ext_sign, ext_bits, 64);
668 assert(!compiler.register_file.is_used(cca.reg));
669 compiler.register_file.mark_clobbered(cca.reg);
670 compiler.register_file.allocatable &= ~(u64{1} << cca.reg.id());
671 arg_regs |= (1ull << cca.reg.id());
675template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
676template <
typename CBDerived>
679 ValueRef vr = compiler.val_ref(arg.
value);
682 assert(part_count == 1);
686 .align = arg.byval_align,
687 .size = arg.byval_size,
695 for (u32 part_idx = 0; part_idx < part_count; ++part_idx) {
698 assert(arg.
ext_bits != 0 &&
"cannot extend zero-bit integer");
701 u32 remaining = part_count < 256 ? part_count - part_idx - 1 : 255;
702 derived()->add_arg(vr.part(part_idx),
704 .consecutive = u8(allow_split ? 0 : remaining),
705 .sret = arg.flag == CallArg::Flag::sret,
707 .align = u8(part_idx == 0 ? align : 1),
712template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
713template <
typename CBDerived>
715 std::variant<SymRef, ValuePart> target) {
716 assert(!compiler.stack.is_leaf_function &&
"leaf func must not have calls");
717 compiler.stack.generated_call =
true;
718 typename RegisterFile::RegBitSet skip_evict = arg_regs;
719 if (
auto *vp = std::get_if<ValuePart>(&target); vp && vp->can_salvage()) {
721 assert(vp->cur_reg_unlocked().valid() &&
"can_salvage implies register");
722 skip_evict |= (1ull << vp->cur_reg_unlocked().
id());
725 auto clobbered = ~assigner.get_ccinfo().callee_saved_regs;
726 for (
auto reg_id : util::BitSetIterator<>{compiler.register_file.used &
727 clobbered & ~skip_evict}) {
728 compiler.evict_reg(AsmReg{reg_id});
729 compiler.register_file.mark_clobbered(Reg{reg_id});
732 derived()->call_impl(std::move(target));
734 assert((compiler.register_file.allocatable & arg_regs) == 0);
735 compiler.register_file.allocatable |= arg_regs;
738template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
739template <
typename CBDerived>
742 cca.bank = vp.bank();
743 cca.size = vp.part_size();
744 assigner.assign_ret(cca);
745 assert(cca.reg.valid() &&
"return value must be in register");
746 vp.set_value_reg(&compiler, cca.reg);
749template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
750template <
typename CBDerived>
753 assert(vr.has_assignment());
754 u32 part_count = vr.assignment()->part_count;
755 for (u32 part_idx = 0; part_idx < part_count; ++part_idx) {
757 add_ret(vr.part(part_idx), cca);
761template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
762void CompilerBase<Adaptor, Derived, Config>::RetBuilder::add(ValuePart &&vp,
764 cca.bank = vp.bank();
765 u32 size = cca.size = vp.part_size();
766 assigner.assign_ret(cca);
767 assert(cca.reg.valid() &&
"indirect return value must use sret argument");
769 bool needs_ext = cca.int_ext != 0;
770 bool ext_sign = cca.int_ext >> 7;
771 unsigned ext_bits = cca.int_ext & 0x3f;
773 if (vp.is_in_reg(cca.reg)) {
774 if (!vp.can_salvage()) {
775 compiler.evict_reg(cca.reg);
777 vp.salvage(&compiler);
780 compiler.generate_raw_intext(cca.reg, cca.reg, ext_sign, ext_bits, 64);
783 if (compiler.register_file.is_used(cca.reg)) {
784 compiler.evict_reg(cca.reg);
786 if (vp.can_salvage()) {
787 AsmReg vp_reg = vp.salvage(&compiler);
789 compiler.generate_raw_intext(cca.reg, vp_reg, ext_sign, ext_bits, 64);
791 compiler.mov(cca.reg, vp_reg, size);
794 vp.reload_into_specific_fixed(&compiler, cca.reg);
796 compiler.generate_raw_intext(cca.reg, cca.reg, ext_sign, ext_bits, 64);
801 assert(!compiler.register_file.is_used(cca.reg));
802 compiler.register_file.mark_clobbered(cca.reg);
803 compiler.register_file.allocatable &= ~(u64{1} << cca.reg.id());
804 ret_regs |= (1ull << cca.reg.id());
807template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
809 u32 part_count = compiler.val_parts(val).count();
810 ValueRef vr = compiler.val_ref(val);
811 for (u32 part_idx = 0; part_idx < part_count; ++part_idx) {
812 add(vr.part(part_idx), CCAssignment{});
816template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
818 assert((compiler.register_file.allocatable & ret_regs) == 0);
819 compiler.register_file.allocatable |= ret_regs;
821 compiler.gen_func_epilog();
822 compiler.release_regs_after_return();
825template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
828 text_writer.begin_module(assembler);
829 text_writer.switch_section(
830 assembler.get_section(assembler.get_default_section(SectionKind::Text)));
832 assert(func_syms.empty());
833 for (
const IRFuncRef func : adaptor->funcs()) {
835 if (adaptor->func_has_weak_linkage(func)) {
837 }
else if (adaptor->func_only_local(func)) {
840 if (adaptor->func_extern(func)) {
841 func_syms.push_back(
derived()->assembler.sym_add_undef(
842 adaptor->func_link_name(func), binding));
844 func_syms.push_back(
derived()->assembler.sym_predef_func(
845 adaptor->func_link_name(func), binding));
847 derived()->define_func_idx(func, func_syms.size() - 1);
850 if (!
derived()->hook_post_func_sym_init()) {
851 TPDE_LOG_ERR(
"hook_pust_func_sym_init failed");
860 for (
const IRFuncRef func : adaptor->funcs()) {
861 if (adaptor->func_extern(func)) {
862 TPDE_LOG_TRACE(
"Skipping compilation of func {}",
863 adaptor->func_link_name(func));
868 TPDE_LOG_TRACE(
"Compiling func {}", adaptor->func_link_name(func));
869 if (!
derived()->compile_func(func, func_idx)) {
870 TPDE_LOG_ERR(
"Failed to compile function {}",
871 adaptor->func_link_name(func));
878 text_writer.end_module();
879 assembler.finalize();
886template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
890 for (
auto &e : stack.fixed_free_lists) {
893 stack.dynamic_free_lists.clear();
897 block_labels.clear();
898 personality_syms.clear();
901template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
902void CompilerBase<Adaptor, Derived, Config>::init_assignment(
903 IRValueRef value, ValLocalIdx local_idx) {
904 assert(val_assignment(local_idx) ==
nullptr);
905 TPDE_LOG_TRACE(
"Initializing assignment for value {}",
906 static_cast<u32
>(local_idx));
908 const auto parts =
derived()->val_parts(value);
909 const u32 part_count = parts.count();
910 assert(part_count > 0);
911 auto *assignment = assignments.allocator.allocate(part_count);
912 assignments.value_ptrs[
static_cast<u32
>(local_idx)] = assignment;
914 u32 max_part_size = 0;
915 for (u32 part_idx = 0; part_idx < part_count; ++part_idx) {
916 auto ap = AssignmentPartRef{assignment, part_idx};
918 ap.set_bank(parts.reg_bank(part_idx));
919 const u32 size = parts.size_bytes(part_idx);
921 max_part_size = std::max(max_part_size, size);
922 ap.set_part_size(size);
925 const auto &liveness = analyzer.liveness_info(local_idx);
934 if (part_count == 1) {
935 const auto &cur_loop =
936 analyzer.loop_from_idx(analyzer.block_loop_idx(cur_block_idx));
937 auto ap = AssignmentPartRef{assignment, 0};
940 liveness.last > cur_block_idx &&
941 cur_loop.definitions_in_childs +
942 assignments.cur_fixed_assignment_count[ap.bank().id()] <
943 Derived::NUM_FIXED_ASSIGNMENTS[ap.bank().id()];
944 if (
derived()->try_force_fixed_assignment(value)) {
945 try_fixed = assignments.cur_fixed_assignment_count[ap.bank().id()] <
946 Derived::NUM_FIXED_ASSIGNMENTS[ap.bank().id()];
951 AsmReg reg =
derived()->select_fixed_assignment_reg(ap, value);
952 TPDE_LOG_TRACE(
"Trying to assign fixed reg to value {}",
953 static_cast<u32
>(local_idx));
957 if (!reg.invalid() && !register_file.is_used(reg)) {
958 TPDE_LOG_TRACE(
"Assigning fixed assignment to reg {} for value {}",
960 static_cast<u32
>(local_idx));
962 ap.set_register_valid(
true);
963 ap.set_fixed_assignment(
true);
964 register_file.mark_used(reg, local_idx, 0);
965 register_file.inc_lock_count(reg);
966 register_file.mark_clobbered(reg);
967 ++assignments.cur_fixed_assignment_count[ap.bank().id()];
972 const auto last_full = liveness.last_full;
973 const auto ref_count = liveness.ref_count;
975 assert(max_part_size <= 256);
976 assignment->max_part_size = max_part_size;
977 assignment->pending_free =
false;
978 assignment->variable_ref =
false;
979 assignment->stack_variable =
false;
980 assignment->delay_free = last_full;
981 assignment->part_count = part_count;
982 assignment->frame_off = 0;
983 assignment->references_left = ref_count;
986template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
988 ValLocalIdx local_idx, ValueAssignment *assignment) {
989 TPDE_LOG_TRACE(
"Freeing assignment for value {}",
990 static_cast<u32
>(local_idx));
992 assert(assignments.value_ptrs[
static_cast<u32
>(local_idx)] == assignment);
993 assignments.value_ptrs[
static_cast<u32
>(local_idx)] =
nullptr;
994 const auto is_var_ref = assignment->variable_ref;
995 const u32 part_count = assignment->part_count;
998 for (u32 part_idx = 0; part_idx < part_count; ++part_idx) {
999 auto ap = AssignmentPartRef{assignment, part_idx};
1000 if (ap.fixed_assignment()) [[unlikely]] {
1001 const auto reg = ap.get_reg();
1002 assert(register_file.is_fixed(reg));
1003 assert(register_file.reg_local_idx(reg) == local_idx);
1004 assert(register_file.reg_part(reg) == part_idx);
1005 --assignments.cur_fixed_assignment_count[ap.bank().id()];
1006 register_file.dec_lock_count_must_zero(reg);
1007 register_file.unmark_used(reg);
1008 }
else if (ap.register_valid()) {
1009 const auto reg = ap.get_reg();
1010 assert(!register_file.is_fixed(reg));
1011 register_file.unmark_used(reg);
1015 if constexpr (WithAsserts) {
1016 for (
auto reg_id : register_file.used_regs()) {
1017 assert(register_file.reg_local_idx(AsmReg{reg_id}) != local_idx &&
1018 "freeing assignment that is still referenced by a register");
1023 bool has_stack = Config::FRAME_INDEXING_NEGATIVE ? assignment->frame_off < 0
1024 : assignment->frame_off != 0;
1025 if (!is_var_ref && has_stack) {
1029 assignments.allocator.deallocate(assignment);
1032template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
1033[[gnu::noinline]]
void
1035 ValLocalIdx local_idx, ValueAssignment *assignment) {
1036 if (!assignment->delay_free) {
1037 free_assignment(local_idx, assignment);
1042 TPDE_LOG_TRACE(
"Delay freeing assignment for value {}",
1043 static_cast<u32
>(local_idx));
1044 const auto &liveness = analyzer.liveness_info(local_idx);
1045 auto &free_list_head = assignments.delayed_free_lists[u32(liveness.last)];
1046 assignment->next_delayed_free_entry = free_list_head;
1047 assignment->pending_free =
true;
1048 free_list_head = local_idx;
1051template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
1053 ValLocalIdx local_idx, u32 var_ref_data) {
1054 TPDE_LOG_TRACE(
"Initializing variable-ref assignment for value {}",
1055 static_cast<u32
>(local_idx));
1057 assert(val_assignment(local_idx) ==
nullptr);
1058 auto *assignment = assignments.allocator.allocate_slow(1,
true);
1059 assignments.value_ptrs[
static_cast<u32
>(local_idx)] = assignment;
1061 assignment->max_part_size = Config::PLATFORM_POINTER_SIZE;
1062 assignment->variable_ref =
true;
1063 assignment->stack_variable =
false;
1064 assignment->part_count = 1;
1065 assignment->var_ref_custom_idx = var_ref_data;
1066 assignment->next_delayed_free_entry = assignments.variable_ref_list;
1068 assignments.variable_ref_list = local_idx;
1070 AssignmentPartRef ap{assignment, 0};
1072 ap.set_bank(Config::GP_BANK);
1073 ap.set_part_size(Config::PLATFORM_POINTER_SIZE);
1076template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
1078 this->stack.frame_used =
true;
1079 unsigned align_bits = 4;
1082 }
else if (size <= 16) {
1084 u32 free_list_idx = size == 1 ? 0 : 32 - util::cnt_lz<u32>(size - 1);
1085 assert(size <= 1u << free_list_idx);
1086 size = 1 << free_list_idx;
1087 align_bits = free_list_idx;
1089 if (!stack.fixed_free_lists[free_list_idx].empty()) {
1090 auto slot = stack.fixed_free_lists[free_list_idx].back();
1091 stack.fixed_free_lists[free_list_idx].pop_back();
1095 size = util::align_up(size, 16);
1096 auto it = stack.dynamic_free_lists.find(size);
1097 if (it != stack.dynamic_free_lists.end() && !it->second.empty()) {
1098 const auto slot = it->second.back();
1099 it->second.pop_back();
1104 assert(stack.frame_size != ~0u &&
1105 "cannot allocate stack slot before stack frame is initialized");
1108 for (u32 list_idx = util::cnt_tz(stack.frame_size); list_idx < align_bits;
1109 list_idx = util::cnt_tz(stack.frame_size)) {
1110 i32 slot = stack.frame_size;
1111 if constexpr (Config::FRAME_INDEXING_NEGATIVE) {
1112 slot = -(slot + (1ull << list_idx));
1114 stack.fixed_free_lists[list_idx].push_back(slot);
1115 stack.frame_size += 1ull << list_idx;
1118 auto slot = stack.frame_size;
1119 assert(slot != 0 &&
"stack slot 0 is reserved");
1120 stack.frame_size += size;
1122 if constexpr (Config::FRAME_INDEXING_NEGATIVE) {
1123 slot = -(slot + size);
1128template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
1131 if (size == 0) [[unlikely]] {
1132 assert(slot == 0 &&
"unexpected slot for zero-sized stack-slot?");
1134 }
else if (size <= 16) [[likely]] {
1135 u32 free_list_idx = size == 1 ? 0 : 32 - util::cnt_lz<u32>(size - 1);
1136 stack.fixed_free_lists[free_list_idx].push_back(slot);
1138 size = util::align_up(size, 16);
1139 stack.dynamic_free_lists[size].push_back(slot);
1143template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
1145 CCAssigner *cc_assigner,
1150 ValueRef vr =
derived()->result_ref(arg);
1151 if (adaptor->cur_arg_is_byval(arg_idx)) {
1154 .align = u8(adaptor->cur_arg_byval_align(arg_idx)),
1155 .size = adaptor->cur_arg_byval_size(arg_idx),
1157 cc_assigner->assign_arg(cca);
1158 std::optional<i32> byval_frame_off =
1159 derived()->prologue_assign_arg_part(vr.part(0), cca);
1161 if (byval_frame_off) {
1163 ValLocalIdx local_idx = val_idx(arg);
1169 if (ValueAssignment *assignment = val_assignment(local_idx)) {
1170 free_assignment(local_idx, assignment);
1173 ValueAssignment *assignment = this->val_assignment(local_idx);
1174 assignment->stack_variable =
true;
1175 assignment->frame_off = *byval_frame_off;
1180 if (adaptor->cur_arg_is_sret(arg_idx)) {
1181 assert(vr.assignment()->part_count == 1 &&
"sret must be single-part");
1182 ValuePartRef vp = vr.part(0);
1184 .sret =
true, .bank = vp.bank(), .size = Config::PLATFORM_POINTER_SIZE};
1185 cc_assigner->assign_arg(cca);
1186 derived()->prologue_assign_arg_part(std::move(vp), cca);
1190 const u32 part_count = vr.assignment()->part_count;
1191 for (u32 part_idx = 0; part_idx < part_count; ++part_idx) {
1192 ValuePartRef vp = vr.part(part_idx);
1193 u32 remaining = part_count < 256 ? part_count - part_idx - 1 : 255;
1195 .consecutive = u8(allow_split ? 0 : remaining),
1196 .align = u8(part_idx == 0 ? align : 1),
1198 .size = vp.part_size(),
1200 cc_assigner->assign_arg(cca);
1201 derived()->prologue_assign_arg_part(std::move(vp), cca);
1205template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
1206typename CompilerBase<Adaptor, Derived, Config>::ValueRef
1208 if (
auto special =
derived()->val_ref_special(value); special) {
1209 return ValueRef{
this, std::move(*special)};
1212 const ValLocalIdx local_idx = analyzer.adaptor->val_local_idx(value);
1213 assert(val_assignment(local_idx) !=
nullptr &&
"value use before def");
1214 return ValueRef{
this, local_idx};
1217template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
1218std::pair<typename CompilerBase<Adaptor, Derived, Config>::ValueRef,
1219 typename CompilerBase<Adaptor, Derived, Config>::ValuePartRef>
1221 std::pair<ValueRef, ValuePartRef> res{
val_ref(value),
this};
1222 res.second = res.first.part(0);
1226template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
1227typename CompilerBase<Adaptor, Derived, Config>::ValueRef
1229 const ValLocalIdx local_idx = analyzer.adaptor->val_local_idx(value);
1230 if (val_assignment(local_idx) ==
nullptr) {
1231 init_assignment(value, local_idx);
1233 return ValueRef{
this, local_idx};
1236template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
1237std::pair<typename CompilerBase<Adaptor, Derived, Config>::ValueRef,
1238 typename CompilerBase<Adaptor, Derived, Config>::ValuePartRef>
1241 std::pair<ValueRef, ValuePartRef> res{
result_ref(value),
this};
1242 res.second = res.first.part(0);
1246template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
1247typename CompilerBase<Adaptor, Derived, Config>::ValueRef
1250 const ValLocalIdx local_idx = analyzer.adaptor->val_local_idx(dst);
1251 assert(!val_assignment(local_idx) &&
"alias target already defined");
1252 assert(src.has_assignment() &&
"alias src must have an assignment");
1257 assert(src.is_owned() &&
"alias src must be owned");
1259 ValueAssignment *assignment = src.assignment();
1260 u32 part_count = assignment->part_count;
1261 assert(!assignment->pending_free);
1262 assert(!assignment->variable_ref);
1263 assert(!assignment->pending_free);
1264 if constexpr (WithAsserts) {
1265 const auto &src_liveness = analyzer.liveness_info(src.local_idx());
1266 assert(!src_liveness.last_full);
1267 assert(assignment->references_left == 1);
1270 const auto parts =
derived()->val_parts(dst);
1271 assert(parts.count() == part_count);
1272 for (u32 part_idx = 0; part_idx < part_count; ++part_idx) {
1273 AssignmentPartRef ap{assignment, part_idx};
1274 assert(parts.reg_bank(part_idx) == ap.bank());
1275 assert(parts.size_bytes(part_idx) == ap.part_size());
1280 for (u32 part_idx = 0; part_idx < part_count; ++part_idx) {
1281 AssignmentPartRef ap{assignment, part_idx};
1282 if (ap.register_valid()) {
1283 register_file.update_reg_assignment(ap.get_reg(), local_idx, part_idx);
1287 const auto &liveness = analyzer.liveness_info(local_idx);
1288 assignment->delay_free = liveness.last_full;
1289 assignment->references_left = liveness.ref_count;
1290 assignments.value_ptrs[
static_cast<u32
>(src.local_idx())] =
nullptr;
1291 assignments.value_ptrs[
static_cast<u32
>(local_idx)] = assignment;
1295 return ValueRef{
this, local_idx};
1298template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
1299typename CompilerBase<Adaptor, Derived, Config>::ValueRef
1301 IRValueRef dst, AssignmentPartRef base, i32 off) {
1302 const ValLocalIdx local_idx = analyzer.adaptor->val_local_idx(dst);
1303 assert(!val_assignment(local_idx) &&
"new value already defined");
1305 ValueAssignment *assignment = this->val_assignment(local_idx);
1306 assignment->stack_variable =
true;
1307 assignment->frame_off = base.variable_stack_off() + off;
1308 return ValueRef{
this, local_idx};
1311template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
1312void CompilerBase<Adaptor, Derived, Config>::set_value(ValuePartRef &
val_ref,
1313 ScratchReg &scratch) {
1314 val_ref.set_value(std::move(scratch));
1317template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
1318typename CompilerBase<Adaptor, Derived, Config>::AsmReg
1320 if (std::holds_alternative<ScratchReg>(gv.state)) {
1321 return std::get<ScratchReg>(gv.state).cur_reg();
1323 if (std::holds_alternative<ValuePartRef>(gv.state)) {
1324 auto &vpr = std::get<ValuePartRef>(gv.state);
1325 if (vpr.has_reg()) {
1326 return vpr.cur_reg();
1328 return vpr.load_to_reg();
1330 if (
auto *expr = std::get_if<typename GenericValuePart::Expr>(&gv.state)) {
1331 if (expr->has_base() && !expr->has_index() && expr->disp == 0) {
1332 return expr->base_reg();
1334 return derived()->gval_expr_as_reg(gv);
1336 TPDE_UNREACHABLE(
"gval_as_reg on empty GenericValuePart");
1339template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
1340typename CompilerBase<Adaptor, Derived, Config>::AsmReg
1345 if (
auto *scratch = std::get_if<ScratchReg>(&gv.state)) {
1346 dst = std::move(*scratch);
1347 }
else if (
auto *
val_ref = std::get_if<ValuePartRef>(&gv.state)) {
1350 assert(dst.
cur_reg() == reg &&
"salvaging unsuccessful");
1357template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
1358typename CompilerBase<Adaptor, Derived, Config>::AsmReg
1360 GenericValuePart &gv, ValuePart &dst) {
1362 if (!dst.has_reg() &&
1363 (!dst.has_assignment() || !dst.assignment().fixed_assignment())) {
1365 if (
auto *scratch = std::get_if<ScratchReg>(&gv.state)) {
1366 dst.set_value(
this, std::move(*scratch));
1367 if (dst.has_assignment()) {
1370 }
else if (
auto *
val_ref = std::get_if<ValuePartRef>(&gv.state)) {
1372 dst.set_value(
this, std::move(*
val_ref));
1373 if (dst.has_assignment()) {
1382template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
1383Reg CompilerBase<Adaptor, Derived, Config>::select_reg_evict(RegBank bank) {
1384 TPDE_LOG_DBG(
"select_reg_evict for bank {}", bank.id());
1385 auto candidates = register_file.used & register_file.bank_regs(bank);
1387 Reg candidate = Reg::make_invalid();
1389 for (
auto reg_id : util::BitSetIterator<>(candidates)) {
1391 if (register_file.is_fixed(reg)) {
1396 auto local_idx = register_file.reg_local_idx(reg);
1397 u32 part = register_file.reg_part(Reg{reg});
1398 assert(local_idx != INVALID_VAL_LOCAL_IDX);
1399 ValueAssignment *va = val_assignment(local_idx);
1400 AssignmentPartRef ap{va, part};
1413 if (ap.variable_ref()) {
1414 TPDE_LOG_DBG(
" r{} ({}) is variable-ref", reg_id, u32(local_idx));
1420 if (ap.stack_valid()) {
1421 score |= u32{1} << 31;
1424 const auto &liveness = analyzer.liveness_info(local_idx);
1425 u32 last_use_dist = u32(liveness.last) - u32(cur_block_idx);
1426 score |= (last_use_dist < 0x8000 ? 0x8000 - last_use_dist : 0) << 16;
1428 u32 refs_left = va->pending_free ? 0 : va->references_left;
1429 score |= (refs_left < 0xffff ? 0x10000 - refs_left : 1);
1431 TPDE_LOG_DBG(
" r{} ({}:{}) rc={}/{} live={}-{}{} spilled={} score={:#x}",
1437 u32(liveness.first),
1439 &
"*"[!liveness.last_full],
1444 if (score > max_score) {
1449 if (candidate.invalid()) [[unlikely]] {
1450 TPDE_FATAL(
"ran out of registers for scratch registers");
1452 TPDE_LOG_DBG(
" selected r{}", candidate.id());
1457template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
1459 AsmReg dst, AssignmentPartRef ap) {
1460 if (!ap.variable_ref()) {
1461 assert(ap.stack_valid());
1462 derived()->load_from_stack(dst, ap.frame_off(), ap.part_size());
1463 }
else if (ap.is_stack_variable()) {
1464 derived()->load_address_of_stack_var(dst, ap);
1465 }
else if constexpr (!Config::DEFAULT_VAR_REF_HANDLING) {
1466 derived()->load_address_of_var_reference(dst, ap);
1468 TPDE_UNREACHABLE(
"non-stack-variable needs custom var-ref handling");
1472template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
1474 AssignmentPartRef ap) {
1475 assert(!ap.variable_ref() &&
"cannot allocate spill slot for variable ref");
1476 if (ap.assignment()->frame_off == 0) {
1477 assert(!ap.stack_valid() &&
"stack-valid set without spill slot");
1479 assert(ap.assignment()->frame_off != 0);
1483template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
1485 assert(may_change_value_state());
1486 if (!ap.stack_valid() && !ap.variable_ref()) {
1487 assert(ap.register_valid() &&
"cannot spill uninitialized assignment part");
1489 derived()->spill_reg(ap.get_reg(), ap.frame_off(), ap.part_size());
1490 ap.set_stack_valid();
1494template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
1496 assert(may_change_value_state());
1497 assert(ap.register_valid());
1499 ap.set_register_valid(
false);
1500 register_file.unmark_used(ap.get_reg());
1503template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
1505 assert(may_change_value_state());
1506 assert(!register_file.is_fixed(reg));
1507 assert(register_file.reg_local_idx(reg) != INVALID_VAL_LOCAL_IDX);
1509 ValLocalIdx local_idx = register_file.reg_local_idx(reg);
1510 auto part = register_file.reg_part(reg);
1511 AssignmentPartRef evict_part{val_assignment(local_idx), part};
1512 assert(evict_part.register_valid());
1513 assert(evict_part.get_reg() == reg);
1515 evict_part.set_register_valid(
false);
1516 register_file.unmark_used(reg);
1519template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
1521 assert(may_change_value_state());
1522 assert(!register_file.is_fixed(reg));
1523 assert(register_file.reg_local_idx(reg) != INVALID_VAL_LOCAL_IDX);
1525 ValLocalIdx local_idx = register_file.reg_local_idx(reg);
1526 auto part = register_file.reg_part(reg);
1527 AssignmentPartRef ap{val_assignment(local_idx), part};
1528 assert(ap.register_valid());
1529 assert(ap.get_reg() == reg);
1530 assert(!ap.modified() || ap.variable_ref());
1531 ap.set_register_valid(
false);
1532 register_file.unmark_used(reg);
1535template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
1536typename CompilerBase<Adaptor, Derived, Config>::RegisterFile::RegBitSet
1562 using RegBitSet =
typename RegisterFile::RegBitSet;
1564 assert(may_change_value_state());
1566 const IRBlockRef cur_block_ref = analyzer.block_ref(cur_block_idx);
1570 BlockIndex earliest_next_succ = Analyzer<Adaptor>::INVALID_BLOCK_IDX;
1572 bool must_spill = force_spill;
1576 auto next_block_is_succ =
false;
1577 auto next_block_has_multiple_incoming =
false;
1579 for (
const IRBlockRef succ : adaptor->block_succs(cur_block_ref)) {
1581 BlockIndex succ_idx = analyzer.block_idx(succ);
1582 if (u32(succ_idx) == u32(cur_block_idx) + 1) {
1583 next_block_is_succ =
true;
1584 if (analyzer.block_has_multiple_incoming(succ)) {
1585 next_block_has_multiple_incoming =
true;
1587 }
else if (succ_idx > cur_block_idx && succ_idx < earliest_next_succ) {
1588 earliest_next_succ = succ_idx;
1592 must_spill = !next_block_is_succ || next_block_has_multiple_incoming;
1594 if (succ_count == 1 && !must_spill) {
1599 auto release_regs = RegBitSet{};
1601 for (
auto reg : register_file.used_regs()) {
1602 auto local_idx = register_file.reg_local_idx(Reg{reg});
1603 auto part = register_file.reg_part(Reg{reg});
1604 if (local_idx == INVALID_VAL_LOCAL_IDX) {
1608 AssignmentPartRef ap{val_assignment(local_idx), part};
1609 if (ap.fixed_assignment()) {
1617 release_regs |= RegBitSet{1ull} << reg;
1620 if (!ap.modified() || ap.variable_ref()) {
1625 const auto &liveness = analyzer.liveness_info(local_idx);
1626 if (liveness.last <= cur_block_idx) {
1639 if (must_spill || earliest_next_succ <= liveness.last) {
1644 return release_regs;
1647template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
1649 typename RegisterFile::RegBitSet regs) {
1650 assert(may_change_value_state());
1653 for (
auto reg_id : util::BitSetIterator<>{regs & register_file.used}) {
1654 if (!register_file.is_fixed(Reg{reg_id})) {
1660template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
1663 for (
auto reg_id : register_file.used_regs()) {
1664 if (!register_file.is_fixed(Reg{reg_id})) {
1670template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
1671template <
typename Jump>
1673 Jump jmp, IRBlockRef target,
bool needs_split,
bool last_inst) {
1674 BlockIndex target_idx = this->analyzer.block_idx(target);
1675 Label target_label = this->block_labels[u32(target_idx)];
1677 move_to_phi_nodes(target_idx);
1678 if (!last_inst || target_idx != this->next_block()) {
1679 derived()->generate_raw_jump(jmp, target_label);
1682 Label tmp_label = this->text_writer.label_create();
1683 derived()->generate_raw_jump(
derived()->invert_jump(jmp), tmp_label);
1684 move_to_phi_nodes(target_idx);
1685 derived()->generate_raw_jump(Jump::jmp, target_label);
1690template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
1692 IRBlockRef target) {
1702template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
1703template <
typename Jump>
1705 Jump jmp, IRBlockRef true_target, IRBlockRef false_target) {
1706 IRBlockRef next = analyzer.block_ref(next_block());
1714 if (next == true_target || (next != false_target && true_needs_split)) {
1716 derived()->invert_jump(jmp), false_target, false_needs_split,
false);
1718 }
else if (next == false_target) {
1722 assert(!true_needs_split);
1731template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
1735 IRBlockRef default_block,
1736 std::span<
const std::pair<u64, IRBlockRef>> cases) {
1741 assert(width <= 64);
1744 assert(cases.size() < UINT32_MAX &&
"large switches are unsupported");
1746 AsmReg cmp_reg = cond.cur_reg();
1747 bool width_is_32 = width <= 32;
1748 if (u32 dst_width = util::align_up(width, 32); width != dst_width) {
1749 derived()->generate_raw_intext(cmp_reg, cmp_reg,
false, width, dst_width);
1756 AsmReg tmp_reg = tmp_scratch.
alloc_gp();
1761 tpde::util::SmallVector<tpde::Label, 64> case_labels;
1764 tpde::util::SmallVector<std::pair<tpde::Label, IRBlockRef>, 64> case_blocks;
1765 for (
auto i = 0u; i < cases.size(); ++i) {
1769 BlockIndex target = this->analyzer.block_idx(cases[i].second);
1770 if (analyzer.block_has_phis(target)) {
1771 case_labels.push_back(this->text_writer.label_create());
1772 case_blocks.emplace_back(case_labels.back(), cases[i].second);
1774 case_labels.push_back(this->block_labels[u32(target)]);
1778 const auto default_label = this->text_writer.label_create();
1780 const auto build_range = [&,
1781 this](
size_t begin,
size_t end,
const auto &self) {
1782 assert(begin <= end);
1783 const auto num_cases = end - begin;
1784 if (num_cases <= 4) {
1787 for (
auto i = 0u; i < num_cases; ++i) {
1788 derived()->switch_emit_cmpeq(case_labels[begin + i],
1791 cases[begin + i].first,
1795 derived()->generate_raw_jump(Derived::Jump::jmp, default_label);
1801 u64 low_bound = cases[begin].first;
1802 u64 high_bound = cases[end - 1].first;
1803 auto range = high_bound - low_bound + 1;
1806 if (range != 0 && (range / num_cases) < 8) {
1811 auto *jt =
derived()->switch_create_jump_table(
1812 default_label, cmp_reg, tmp_reg, low_bound, high_bound, width_is_32);
1814 if (range == num_cases) {
1815 std::copy(case_labels.begin() + begin,
1816 case_labels.begin() + end,
1817 jt->labels().begin());
1819 std::ranges::fill(jt->labels(), default_label);
1820 for (
auto i = begin; i != end; ++i) {
1821 jt->labels()[cases[i].first - low_bound] = case_labels[i];
1829 const auto half_len = num_cases / 2;
1830 const auto half_value = cases[begin + half_len].first;
1831 const auto gt_label = this->text_writer.label_create();
1836 derived()->switch_emit_binary_step(case_labels[begin + half_len],
1843 self(begin, begin + half_len, self);
1847 self(begin + half_len + 1, end, self);
1850 build_range(0, case_labels.size(), build_range);
1854 derived()->generate_branch_to_block(
1855 Derived::Jump::jmp, default_block,
false,
false);
1857 for (
const auto &[label, target] : case_blocks) {
1860 this->text_writer.align(8);
1862 derived()->generate_branch_to_block(
1863 Derived::Jump::jmp, target,
false,
false);
1870template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
1871void CompilerBase<Adaptor, Derived, Config>::move_to_phi_nodes_impl(
1872 BlockIndex target) {
1881 struct ScratchWrapper {
1883 AsmReg cur_reg = AsmReg::make_invalid();
1884 bool backed_up =
false;
1885 bool was_modified =
false;
1887 ValLocalIdx local_idx = INVALID_VAL_LOCAL_IDX;
1889 ScratchWrapper(Derived *self) : self{self} {}
1891 ~ScratchWrapper() { reset(); }
1894 if (cur_reg.invalid()) {
1898 self->register_file.unmark_fixed(cur_reg);
1899 self->register_file.unmark_used(cur_reg);
1904 auto *assignment = self->val_assignment(local_idx);
1908 auto ap = AssignmentPartRef{assignment, part};
1909 if (!ap.variable_ref()) {
1911 assert(ap.stack_valid());
1912 self->load_from_stack(cur_reg, ap.frame_off(), ap.part_size());
1914 ap.set_reg(cur_reg);
1915 ap.set_register_valid(
true);
1916 ap.set_modified(was_modified);
1917 self->register_file.mark_used(cur_reg, local_idx, part);
1921 cur_reg = AsmReg::make_invalid();
1924 AsmReg alloc_from_bank(RegBank bank) {
1925 if (cur_reg.valid() && self->register_file.reg_bank(cur_reg) == bank) {
1928 if (cur_reg.valid()) {
1934 auto ®_file = self->register_file;
1935 auto reg = reg_file.find_first_free_excluding(bank, 0);
1936 if (reg.invalid()) {
1938 reg = reg_file.find_first_nonfixed_excluding(bank, 0);
1939 if (reg.invalid()) {
1940 TPDE_FATAL(
"ran out of registers for scratch registers");
1944 local_idx = reg_file.reg_local_idx(reg);
1945 part = reg_file.reg_part(reg);
1946 AssignmentPartRef ap{self->val_assignment(local_idx), part};
1947 was_modified = ap.modified();
1951 assert(ap.register_valid() && ap.get_reg() == reg);
1952 if (!ap.stack_valid() && !ap.variable_ref()) {
1953 self->allocate_spill_slot(ap);
1954 self->spill_reg(ap.get_reg(), ap.frame_off(), ap.part_size());
1955 ap.set_stack_valid();
1957 ap.set_register_valid(
false);
1958 reg_file.unmark_used(reg);
1961 reg_file.mark_used(reg, INVALID_VAL_LOCAL_IDX, 0);
1962 reg_file.mark_clobbered(reg);
1963 reg_file.mark_fixed(reg);
1968 ScratchWrapper &operator=(
const ScratchWrapper &) =
delete;
1969 ScratchWrapper &operator=(ScratchWrapper &&) =
delete;
1972 IRBlockRef target_ref = analyzer.block_ref(target);
1973 IRBlockRef cur_ref = analyzer.block_ref(cur_block_idx);
1978 IRValueRef incoming_val;
1979 ValLocalIdx phi_local_idx;
1981 ValLocalIdx incoming_phi_local_idx = INVALID_VAL_LOCAL_IDX;
1985 bool operator<(
const NodeEntry &other)
const {
1986 return phi_local_idx < other.phi_local_idx;
1989 bool operator<(ValLocalIdx other)
const {
return phi_local_idx < other; }
1992 util::SmallVector<NodeEntry, 16> nodes;
1993 for (IRValueRef phi : adaptor->block_phis(target_ref)) {
1994 ValLocalIdx phi_local_idx = adaptor->val_local_idx(phi);
1995 auto incoming = adaptor->val_as_phi(phi).incoming_val_for_block(cur_ref);
1996 nodes.emplace_back(NodeEntry{
1997 .phi = phi, .incoming_val = incoming, .phi_local_idx = phi_local_idx});
2001 assert(!nodes.empty() &&
"block marked has having phi nodes has none");
2003 ScratchWrapper scratch{
derived()};
2004 const auto move_to_phi = [
this, &scratch](IRValueRef phi,
2005 IRValueRef incoming_val) {
2006 auto phi_vr =
derived()->result_ref(phi);
2007 auto val_vr =
derived()->val_ref(incoming_val);
2008 if (phi == incoming_val) {
2012 u32 part_count = phi_vr.assignment()->part_count;
2013 for (u32 i = 0; i < part_count; ++i) {
2014 AssignmentPartRef phi_ap{phi_vr.assignment(), i};
2015 ValuePartRef val_vpr = val_vr.part(i);
2017 if (phi_ap.fixed_assignment()) {
2018 if (AsmReg reg = val_vpr.cur_reg_unlocked(); reg.valid()) {
2019 derived()->mov(phi_ap.get_reg(), reg, phi_ap.part_size());
2021 val_vpr.reload_into_specific_fixed(phi_ap.get_reg());
2024 AsmReg reg = val_vpr.cur_reg_unlocked();
2026 reg = scratch.alloc_from_bank(val_vpr.bank());
2027 val_vpr.reload_into_specific_fixed(reg);
2030 derived()->spill_reg(reg, phi_ap.frame_off(), phi_ap.part_size());
2031 phi_ap.set_stack_valid();
2036 if (nodes.size() == 1) {
2037 move_to_phi(nodes[0].phi, nodes[0].incoming_val);
2042 std::sort(nodes.begin(), nodes.end());
2045 auto all_zero_ref =
true;
2046 for (
auto &node : nodes) {
2049 bool incoming_is_phi = adaptor->val_is_phi(node.incoming_val);
2050 if (!incoming_is_phi || node.incoming_val == node.phi) {
2054 ValLocalIdx inc_local_idx = adaptor->val_local_idx(node.incoming_val);
2055 auto it = std::lower_bound(nodes.begin(), nodes.end(), inc_local_idx);
2056 if (it == nodes.end() || it->phi != node.incoming_val) {
2061 node.incoming_phi_local_idx = inc_local_idx;
2063 all_zero_ref =
false;
2068 for (
auto &node : nodes) {
2069 move_to_phi(node.phi, node.incoming_val);
2075 util::SmallVector<u32, 32> ready_indices;
2076 ready_indices.reserve(nodes.size());
2077 util::SmallBitSet<256> waiting_nodes;
2078 waiting_nodes.resize(nodes.size());
2079 for (u32 i = 0; i < nodes.size(); ++i) {
2080 if (nodes[i].ref_count) {
2081 waiting_nodes.mark_set(i);
2083 ready_indices.push_back(i);
2087 u32 handled_count = 0;
2088 u32 cur_tmp_part_count = 0;
2089 i32 cur_tmp_slot = 0;
2090 u32 cur_tmp_slot_size = 0;
2091 IRValueRef cur_tmp_val = Adaptor::INVALID_VALUE_REF;
2094 const auto move_from_tmp_phi = [&](IRValueRef target_phi) {
2095 auto phi_vr =
val_ref(target_phi);
2096 if (cur_tmp_part_count <= 2) {
2097 AssignmentPartRef ap{phi_vr.assignment(), 0};
2098 assert(!tmp_reg1.cur_reg.invalid());
2099 if (ap.fixed_assignment()) {
2100 derived()->mov(ap.get_reg(), tmp_reg1.cur_reg, ap.part_size());
2102 derived()->spill_reg(tmp_reg1.cur_reg, ap.frame_off(), ap.part_size());
2105 if (cur_tmp_part_count == 2) {
2106 AssignmentPartRef ap_high{phi_vr.assignment(), 1};
2107 assert(!ap_high.fixed_assignment());
2108 assert(!tmp_reg2.cur_reg.invalid());
2110 tmp_reg2.cur_reg, ap_high.frame_off(), ap_high.part_size());
2115 for (u32 i = 0; i < cur_tmp_part_count; ++i) {
2116 AssignmentPartRef phi_ap{phi_vr.assignment(), i};
2117 assert(!phi_ap.fixed_assignment());
2119 auto slot_off = cur_tmp_slot + phi_ap.part_off();
2120 auto reg = tmp_reg1.alloc_from_bank(phi_ap.bank());
2121 derived()->load_from_stack(reg, slot_off, phi_ap.part_size());
2122 derived()->spill_reg(reg, phi_ap.frame_off(), phi_ap.part_size());
2126 while (handled_count != nodes.size()) {
2127 if (ready_indices.empty()) {
2129 auto cur_idx_opt = waiting_nodes.first_set();
2130 assert(cur_idx_opt);
2131 auto cur_idx = *cur_idx_opt;
2132 assert(nodes[cur_idx].ref_count == 1);
2133 assert(cur_tmp_val == Adaptor::INVALID_VALUE_REF);
2135 auto phi_val = nodes[cur_idx].phi;
2136 auto phi_vr = this->
val_ref(phi_val);
2137 auto *assignment = phi_vr.assignment();
2138 cur_tmp_part_count = assignment->part_count;
2139 cur_tmp_val = phi_val;
2141 if (cur_tmp_part_count > 2) {
2143 cur_tmp_slot_size = assignment->size();
2146 for (u32 i = 0; i < cur_tmp_part_count; ++i) {
2147 auto ap = AssignmentPartRef{assignment, i};
2148 assert(!ap.fixed_assignment());
2149 auto slot_off = cur_tmp_slot + ap.part_off();
2151 if (ap.register_valid()) {
2152 auto reg = ap.get_reg();
2153 derived()->spill_reg(reg, slot_off, ap.part_size());
2155 auto reg = tmp_reg1.alloc_from_bank(ap.bank());
2156 assert(ap.stack_valid());
2157 derived()->load_from_stack(reg, ap.frame_off(), ap.part_size());
2158 derived()->spill_reg(reg, slot_off, ap.part_size());
2164 auto phi_vpr = phi_vr.part(0);
2165 auto reg = tmp_reg1.alloc_from_bank(phi_vpr.bank());
2166 phi_vpr.reload_into_specific_fixed(
this, reg);
2168 if (cur_tmp_part_count == 2) {
2170 auto phi_vpr_high = phi_vr.part(1);
2171 auto reg_high = tmp_reg2.alloc_from_bank(phi_vpr_high.bank());
2172 phi_vpr_high.reload_into_specific_fixed(
this, reg_high);
2176 nodes[cur_idx].ref_count = 0;
2177 ready_indices.push_back(cur_idx);
2178 waiting_nodes.mark_unset(cur_idx);
2181 for (u32 i = 0; i < ready_indices.size(); ++i) {
2183 auto cur_idx = ready_indices[i];
2184 auto phi_val = nodes[cur_idx].phi;
2185 IRValueRef incoming_val = nodes[cur_idx].incoming_val;
2186 if (incoming_val == phi_val) {
2193 if (incoming_val == cur_tmp_val) {
2194 move_from_tmp_phi(phi_val);
2196 if (cur_tmp_part_count > 2) {
2198 cur_tmp_slot = 0xFFFF'FFFF;
2199 cur_tmp_slot_size = 0;
2201 cur_tmp_val = Adaptor::INVALID_VALUE_REF;
2208 move_to_phi(phi_val, incoming_val);
2210 if (nodes[cur_idx].incoming_phi_local_idx == INVALID_VAL_LOCAL_IDX) {
2214 auto it = std::lower_bound(
2215 nodes.begin(), nodes.end(), nodes[cur_idx].incoming_phi_local_idx);
2216 assert(it != nodes.end() && it->phi == incoming_val &&
2217 "incoming_phi_local_idx set incorrectly");
2219 assert(it->ref_count > 0);
2220 if (--it->ref_count == 0) {
2221 auto node_idx =
static_cast<u32
>(it - nodes.begin());
2222 ready_indices.push_back(node_idx);
2223 waiting_nodes.mark_unset(node_idx);
2226 ready_indices.clear();
2230template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
2233 return static_cast<BlockIndex
>(
static_cast<u32
>(cur_block_idx) + 1);
2236template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
2238 SymRef personality_sym;
2239 if (this->adaptor->cur_needs_unwind_info()) {
2240 SymRef personality_func =
derived()->cur_personality_func();
2241 if (personality_func.valid()) {
2242 for (
const auto &[fn_sym, ptr_sym] : personality_syms) {
2243 if (fn_sym == personality_func) {
2244 personality_sym = ptr_sym;
2249 if (!personality_sym.valid()) {
2253 static constexpr std::array<u8, 8> zero{};
2256 this->assembler.get_default_section(SectionKind::DataRelRO);
2257 personality_sym = this->assembler.sym_def_data(
2259 this->assembler.reloc_abs(rodata, personality_func, off, 0);
2261 personality_syms.emplace_back(personality_func, personality_sym);
2265 return personality_sym;
2268template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
2270 const u32 func_idx) {
2271 if (!adaptor->switch_func(func)) {
2275 analyzer.switch_func(func);
2278 if constexpr (WithAsserts) {
2279 stack.frame_size = ~0u;
2281 for (
auto &e : stack.fixed_free_lists) {
2284 stack.dynamic_free_lists.clear();
2286 stack.has_dynamic_alloca = this->adaptor->cur_has_dynamic_alloca();
2287 stack.is_leaf_function = !
derived()->cur_func_may_emit_calls();
2288 stack.generated_call =
false;
2289 stack.frame_used =
false;
2291 assignments.cur_fixed_assignment_count = {};
2292 assert(std::ranges::none_of(assignments.value_ptrs, std::identity{}));
2293 if (assignments.value_ptrs.size() < analyzer.liveness.size()) {
2294 assignments.value_ptrs.resize(analyzer.liveness.size());
2297 assignments.allocator.reset();
2298 assignments.variable_ref_list = INVALID_VAL_LOCAL_IDX;
2299 assignments.delayed_free_lists.clear();
2300 assignments.delayed_free_lists.resize(analyzer.block_layout.size(),
2301 INVALID_VAL_LOCAL_IDX);
2304 static_cast<BlockIndex
>(analyzer.block_idx(adaptor->cur_entry_block()));
2306 register_file.reset();
2312 u32 expected_code_size = 0x8 * analyzer.num_insts + 0x40;
2313 this->text_writer.begin_func(16, expected_code_size);
2315 derived()->start_func(func_idx);
2317 block_labels.clear();
2318 block_labels.resize_uninitialized(analyzer.block_layout.size());
2319 for (u32 i = 0; i < analyzer.block_layout.size(); ++i) {
2320 block_labels[i] = text_writer.label_create();
2326 CCAssigner *cc_assigner =
derived()->cur_cc_assigner();
2327 assert(cc_assigner !=
nullptr);
2329 register_file.allocatable = cc_assigner->get_ccinfo().allocatable_regs;
2331 cc_assigner->reset();
2333 const CCInfo &cc_info = cc_assigner->get_ccinfo();
2334 assert((cc_info.allocatable_regs & cc_info.arg_regs) == cc_info.arg_regs &&
2335 "argument registers must also be allocatable");
2336 this->register_file.allocatable &= ~cc_info.arg_regs;
2339 derived()->prologue_begin(cc_assigner);
2341 for (
const IRValueRef arg : this->adaptor->cur_args()) {
2344 derived()->prologue_assign_arg(cc_assigner, arg_idx++, arg);
2347 derived()->prologue_end(cc_assigner);
2349 this->register_file.allocatable |= cc_info.arg_regs;
2352 util::SmallVector<std::tuple<IRValueRef, u32, u32>> dyn_allocas;
2353 for (
const IRValueRef alloca : adaptor->cur_static_allocas()) {
2354 auto size = adaptor->val_alloca_size(alloca);
2355 auto align = adaptor->val_alloca_align(alloca);
2356 if (align > 16 || size > Derived::MaxStaticAllocaSize) {
2357 stack.has_dynamic_alloca =
true;
2358 dyn_allocas.emplace_back(alloca, size, align);
2362 ValLocalIdx local_idx = adaptor->val_local_idx(alloca);
2364 ValueAssignment *assignment = val_assignment(local_idx);
2365 assignment->stack_variable =
true;
2369 if constexpr (!Config::DEFAULT_VAR_REF_HANDLING) {
2370 derived()->setup_var_ref_assignments();
2373 for (
auto &[alloca, size, align] : dyn_allocas) {
2375 derived()->alloca_fixed(size, align, vr);
2378 for (u32 i = 0; i < analyzer.block_layout.size(); ++i) {
2379 const auto block_ref = analyzer.block_layout[i];
2381 "Compiling block {} ({})", i, adaptor->block_fmt_ref(block_ref));
2382 if (!
derived()->compile_block(block_ref, i)) [[unlikely]] {
2383 TPDE_LOG_ERR(
"Failed to compile block {} ({})",
2385 adaptor->block_fmt_ref(block_ref));
2387 assignments.value_ptrs.clear();
2393 ValLocalIdx variable_ref_list = assignments.variable_ref_list;
2394 while (variable_ref_list != INVALID_VAL_LOCAL_IDX) {
2395 u32 idx = u32(variable_ref_list);
2396 ValLocalIdx next = assignments.value_ptrs[idx]->next_delayed_free_entry;
2397 assignments.value_ptrs[idx] =
nullptr;
2398 variable_ref_list = next;
2401 assert(std::ranges::none_of(assignments.value_ptrs, std::identity{}) &&
2402 "found non-freed ValueAssignment, maybe missing ref-count?");
2404 derived()->finish_func(func_idx);
2405 this->text_writer.finish_func();
2410template <IRAdaptor Adaptor,
typename Derived, CompilerConfig Config>
2412 const IRBlockRef block,
const u32 block_idx) {
2414 static_cast<typename Analyzer<Adaptor>::BlockIndex
>(block_idx);
2417 auto &&val_range = adaptor->block_insts(block);
2418 auto end = val_range.end();
2419 for (
auto it = val_range.begin(); it != end; ++it) {
2420 const IRInstRef inst = *it;
2421 if (this->adaptor->inst_fused(inst)) {
2427 if (!
derived()->compile_inst(inst, InstRange{.from = it_cpy, .to = end}))
2429 TPDE_LOG_ERR(
"Failed to compile instruction {}",
2430 this->adaptor->inst_fmt_ref(inst));
2435 if constexpr (WithAsserts) {
2439 for (
auto reg_id : register_file.used_regs()) {
2441 assert(register_file.reg_local_idx(reg) != INVALID_VAL_LOCAL_IDX);
2442 AssignmentPartRef ap{val_assignment(register_file.reg_local_idx(reg)),
2443 register_file.reg_part(reg)};
2444 assert(ap.register_valid());
2445 assert(ap.get_reg() == reg);
2446 assert(!register_file.is_fixed(reg) || ap.fixed_assignment());
2450 if (
static_cast<u32
>(assignments.delayed_free_lists[block_idx]) != ~0u) {
2451 auto list_entry = assignments.delayed_free_lists[block_idx];
2452 while (
static_cast<u32
>(list_entry) != ~0u) {
2453 auto *assignment = assignments.value_ptrs[
static_cast<u32
>(list_entry)];
2454 auto next_entry = assignment->next_delayed_free_entry;
2455 derived()->free_assignment(list_entry, assignment);
2456 list_entry = next_entry;