14 #include "nlohmann/json.hpp"
15 #include "rapidjson/document.h"
26 namespace netlist_preprocessing
36 GateScope(
const std::vector<Gate*>& gates) : m_all(gates.empty())
41 if (m_lookup.insert(g).second)
48 bool contains(
const Gate* g)
const
50 return m_all || m_lookup.find(g) != m_lookup.end();
57 std::vector<Gate*> gates(
const Netlist* nl,
const std::function<
bool(
const Gate*)>& type_filter =
nullptr)
const
61 return type_filter ? nl->get_gates(type_filter) : nl->get_gates();
64 std::vector<Gate*> res;
65 for (
auto* g : m_gates)
67 if (!type_filter || type_filter(g))
77 std::vector<Gate*> m_gates;
78 std::unordered_set<const Gate*> m_lookup;
88 if (gnd_gates.empty())
90 return ERR(
"could not remove unused LUT endpoints from netlist with ID " + std::to_string(nl->
get_id()) +
": no GND net available within netlist");
92 Net* gnd_net = gnd_gates.front()->get_fan_out_nets().front();
94 const GateScope scope(gates);
97 for (
const auto& gate : scope.gates(nl, [](
const Gate* g) { return g->get_type()->has_property(GateTypeProperty::c_lut); }))
99 std::vector<Endpoint*> fan_in = gate->get_fan_in_endpoints();
100 std::unordered_map<std::string, BooleanFunction> functions = gate->get_boolean_functions();
103 if (functions.size() != 1)
109 auto active_pins = functions.begin()->second.get_variable_names();
112 if (fan_in.size() > active_pins.size())
114 for (
const auto& ep : fan_in)
116 if (ep->get_net()->is_gnd_net() || ep->get_net()->is_vcc_net())
121 if (std::find(active_pins.begin(), active_pins.end(), ep->get_pin()->get_name()) == active_pins.end())
124 if (!ep->get_net()->remove_destination(gate, pin))
127 "netlist_preprocessing",
"failed to remove unused input from LUT gate '{}' with ID {} from netlist with ID {}.", gate->get_name(), gate->get_id(), nl->
get_id());
133 "failed to reconnect unused input of LUT gate '{}' with ID {} to GND in netlist with ID {}.",
145 log_info(
"netlist_preprocessing",
"removed {} unused LUT endpoints from netlist with ID {}.", num_eps, nl->
get_id());
155 std::queue<Gate*> gates_to_be_deleted;
157 const GateScope scope(gates);
159 for (
const auto& gate : scope.gates(nl))
161 std::vector<Endpoint*> fan_out = gate->get_fan_out_endpoints();
172 if (fan_out.size() != 1)
179 if (functions.size() != 1)
185 Endpoint* out_endpoint = *(fan_out.begin());
191 std::vector<Endpoint*> fan_in = gate->get_fan_in_endpoints();
196 if (substitute_res.is_error())
199 "Cannot replace buffers: failed to substitute pins with constants at gate " + gate->get_name() +
" with ID " + std::to_string(gate->get_id()));
211 for (
Endpoint* in_endpoint : fan_in)
213 Net* in_net = in_endpoint->get_net();
218 if (merge_res.is_error())
220 log_warning(
"netlist_preprocessing",
"{}", merge_res.get_error().get());
230 "failed to remove destination from input net '{}' with ID {} of buffer gate '{}' with ID {} from netlist with ID {}.",
248 gates_to_be_deleted.push(gate);
369 log_debug(
"netlist_preprocessing",
"removing {} buffer gates...", gates_to_be_deleted.size());
371 while (!gates_to_be_deleted.empty())
373 Gate* gate = gates_to_be_deleted.front();
374 gates_to_be_deleted.pop();
377 log_warning(
"netlist_preprocessing",
"failed to remove buffer gate '{}' with ID {} from netlist with ID {}.", gate->
get_name(), gate->
get_id(), nl->
get_id());
383 log_info(
"netlist_preprocessing",
"removed {} buffer gates from netlist with ID {}.", num_gates, nl->
get_id());
384 return OK(num_gates);
389 std::unordered_map<Gate*, std::vector<std::string>> restore_ff_replacements(
const Netlist* nl)
391 std::unordered_map<Gate*, std::vector<std::string>> replacements;
395 if (g->has_data(
"preprocessing_information",
"replaced_gates"))
397 const auto& [_, s] = g->get_data(
"preprocessing_information",
"replaced_gates");
399 replacements.insert({g, replaced_gate_names});
406 void update_ff_replacements(std::unordered_map<Gate*, std::vector<std::string>>& replacements)
408 for (
auto& [g, r] : replacements)
410 const nlohmann::json j = r;
411 const std::string s = j.dump();
413 g->set_data(
"preprocessing_information",
"replaced_gates",
"string", s);
419 void annotate_ff_survivor(std::unordered_map<Gate*, std::vector<std::string>>& replacements, Gate* survivor, Gate* to_be_replaced)
421 auto& it_s = replacements[survivor];
423 if (
const auto& it = replacements.find(to_be_replaced); it != replacements.end())
425 for (
const auto& s : it->second)
429 replacements.erase(it);
432 it_s.push_back(to_be_replaced->get_name());
442 const GateScope scope(gates);
446 #ifdef BITWUZLA_LIBRARY
449 config = config.with_solver(s_type).with_call(s_call);
451 struct GateFingerprint
454 std::map<GatePin*, Net*> ordered_fan_in = {};
455 std::set<Net*> unordered_fan_in = {};
456 u8 truth_table_hw = 0;
457 std::vector<std::string> init_data = {};
459 bool operator<(
const GateFingerprint& other)
const
461 return std::tie(
type, ordered_fan_in, unordered_fan_in, truth_table_hw, init_data)
462 < std::tie(other.type, other.ordered_fan_in, other.unordered_fan_in, other.truth_table_hw, other.init_data);
466 static std::vector<u8> hw_map = {0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4};
471 std::vector<Gate*> target_gates;
487 auto ff_replacements = restore_ff_replacements(nl);
491 std::map<GateFingerprint, std::vector<Gate*>> fingerprinted_gates;
495 for (
auto* gate : target_gates)
497 GateFingerprint fingerprint;
498 fingerprint.type = gate->get_type();
501 const auto& fan_in_nets = gate->get_fan_in_nets();
502 fingerprint.unordered_fan_in.insert(fan_in_nets.cbegin(), fan_in_nets.cend());
505 if (
const auto res = gate->get_init_data(); res.is_ok())
507 const auto& init_str = res.get().front();
508 for (
const auto c : init_str)
510 u8 tmp = std::toupper(c) - 0x30;
515 fingerprint.truth_table_hw += hw_map.at(tmp);
522 for (
const auto& ep : gate->get_fan_in_endpoints())
524 fingerprint.ordered_fan_in[ep->get_pin()] = ep->get_net();
531 if (
const auto res = gate->get_init_data(); res.is_ok())
533 fingerprint.init_data = res.get();
537 fingerprinted_gates[fingerprint].push_back(gate);
540 std::vector<std::vector<Gate*>> duplicate_gates;
541 for (
const auto& [fingerprint, gates] : fingerprinted_gates)
543 if (gates.size() == 1)
549 if (std::none_of(gates.begin(), gates.end(), [&scope](
const Gate* g) { return scope.contains(g); }))
556 std::set<const Gate*> visited;
557 for (
size_t i = 0; i < gates.size(); i++)
559 Gate* master_gate = gates.at(i);
561 if (visited.find(master_gate) != visited.cend())
566 std::vector<Gate*> current_duplicates = {master_gate};
568 for (
size_t j = i + 1; j < gates.size(); j++)
570 Gate* current_gate = gates.at(j);
572 for (
const auto* pin : fingerprint.type->get_output_pins())
574 const auto solver_res =
584 if (solver_res.is_error() || !solver_res.get().is_unsat())
592 current_duplicates.push_back(current_gate);
593 visited.insert(current_gate);
597 if (current_duplicates.size() > 1)
599 duplicate_gates.push_back(current_duplicates);
605 duplicate_gates.push_back(std::move(gates));
609 std::set<Gate*> affected_gates;
610 for (
auto& current_duplicates : duplicate_gates)
612 std::sort(current_duplicates.begin(), current_duplicates.end(), [](
const auto& g1,
const auto& g2) { return g1->get_name().length() < g2->get_name().length(); });
616 std::stable_partition(current_duplicates.begin(), current_duplicates.end(), [&scope](
const Gate* g) { return !scope.contains(g); });
618 auto* survivor_gate = current_duplicates.front();
619 std::map<GatePin*, Net*> out_pins_to_nets;
620 for (
auto* ep : survivor_gate->get_fan_out_endpoints())
622 Net* out_net = ep->get_net();
623 out_pins_to_nets[ep->get_pin()] = out_net;
626 auto* dst_gate = dst->get_gate();
627 auto* dst_type = dst_gate->get_type();
630 affected_gates.insert(dst_gate);
635 for (
u32 k = 1; k < current_duplicates.size(); k++)
637 auto* current_gate = current_duplicates.at(k);
640 if (!scope.contains(current_gate))
645 for (
auto* ep : current_gate->get_fan_out_endpoints())
647 auto* ep_net = ep->get_net();
648 auto* ep_pin = ep->get_pin();
650 if (
auto it = out_pins_to_nets.find(ep_pin); it != out_pins_to_nets.cend())
653 for (
auto* dst : ep_net->get_destinations())
655 auto* dst_gate = dst->get_gate();
656 auto* dst_pin = dst->get_pin();
658 it->second->add_destination(dst_gate, dst_pin);
660 auto* dst_type = dst_gate->get_type();
663 affected_gates.insert(dst_gate);
668 log_warning(
"netlist_preprocessing",
"could not delete net '{}' with ID {} from netlist with ID {}.", ep_net->get_name(), ep_net->get_id(), nl->
get_id());
674 ep_net->add_source(survivor_gate, ep_pin);
675 out_pins_to_nets[ep_pin] = ep_net;
676 for (
auto* dst : ep_net->get_destinations())
678 auto* dst_gate = dst->get_gate();
679 auto* dst_type = dst_gate->get_type();
682 affected_gates.insert(dst_gate);
688 annotate_ff_survivor(ff_replacements, survivor_gate, current_gate);
690 affected_gates.erase(current_gate);
693 log_warning(
"netlist_preprocessing",
"could not delete gate '{}' with ID {} from netlist with ID {}.", current_gate->get_name(), current_gate->get_id(), nl->
get_id());
702 target_gates = std::vector<Gate*>(affected_gates.cbegin(), affected_gates.cend());
705 update_ff_replacements(ff_replacements);
707 log_info(
"netlist_preprocessing",
"removed {} redundant gates from netlist with ID {}.", num_gates, nl->
get_id());
708 return OK(num_gates);
713 struct LoopFingerprint
715 std::map<const GateType*, u32> types;
716 std::set<std::string> external_variable_names;
717 std::set<const Net*> ff_control_nets;
719 bool operator<(
const LoopFingerprint& other)
const
721 return (other.types < types) || (other.types == types && other.external_variable_names < external_variable_names)
722 || (other.types == types && other.external_variable_names == external_variable_names && other.ff_control_nets < ff_control_nets);
728 #ifdef BITWUZLA_LIBRARY
731 config = config.with_solver(s_type).with_call(s_call);
736 auto ff_replacements = restore_ff_replacements(nl);
742 std::unordered_map<Gate*, std::unordered_set<Gate*>> loops_by_start_gate;
743 for (
auto* start_ff : nl->
get_gates([](
const Gate* g) { return g->get_type()->has_property(GateTypeProperty::ff); }))
745 std::vector<Gate*> stack = {start_ff};
746 std::vector<Gate*> previous_gates;
747 std::unordered_set<Gate*> visited_gates;
748 std::unordered_set<Gate*> cache;
750 while (!stack.empty())
752 auto* current_gate = stack.back();
754 if (!previous_gates.empty() && current_gate == previous_gates.back())
757 previous_gates.pop_back();
761 visited_gates.insert(current_gate);
764 for (
const auto* suc_ep : current_gate->get_successors())
766 if (ff_control_pin_types.find(suc_ep->get_pin()->get_type()) != ff_control_pin_types.end())
771 auto* suc_gate = suc_ep->get_gate();
772 if (suc_gate == start_ff || cache.find(suc_gate) != cache.end())
774 loops_by_start_gate[start_ff].insert(current_gate);
775 cache.insert(current_gate);
776 for (
auto it = ++(previous_gates.begin()); it != previous_gates.end(); it++)
779 loops_by_start_gate[start_ff].insert(*it);
784 if (visited_gates.find(suc_gate) == visited_gates.end())
786 stack.push_back(suc_gate);
794 previous_gates.push_back(current_gate);
803 std::map<LoopFingerprint, std::vector<std::pair<std::vector<Gate*>,
BooleanFunction>>> fingerprinted_loops;
804 for (
const auto& [start_ff, comb_gates] : loops_by_start_gate)
806 LoopFingerprint fingerprint;
809 if (comb_gates.size() > 30)
815 std::vector<const Endpoint*> data_in;
816 for (
const auto* ep : start_ff->get_fan_in_endpoints())
818 auto pin_type = ep->get_pin()->get_type();
819 if (ff_control_pin_types.find(pin_type) != ff_control_pin_types.end())
821 fingerprint.ff_control_nets.insert(ep->get_net());
825 data_in.push_back(ep);
829 if (data_in.size() != 1)
835 fingerprint.types[start_ff->get_type()] = 1;
836 for (
const auto* g : comb_gates)
839 if (
const auto type_it = fingerprint.types.find(gt); type_it == fingerprint.types.end())
841 fingerprint.types[gt] = 0;
843 fingerprint.types[gt]++;
846 std::vector<const Gate*> comb_gates_vec(comb_gates.cbegin(), comb_gates.cend());
854 for (
const auto* ep : start_ff->get_fan_out_endpoints())
857 it != fingerprint.external_variable_names.end())
859 function =
function.substitute(*it, ep->get_pin()->get_name());
860 fingerprint.external_variable_names.erase(it);
864 std::vector<Gate*> loop_gates = {start_ff};
865 loop_gates.insert(loop_gates.end(), comb_gates.begin(), comb_gates.end());
866 fingerprinted_loops[fingerprint].push_back(std::make_pair(loop_gates, std::move(
function)));
870 std::vector<std::vector<std::vector<Gate*>>> duplicate_loops;
871 for (
const auto& [_, loops] : fingerprinted_loops)
873 if (loops.size() == 1)
878 std::set<u32> visited;
879 for (
u32 i = 0; i < loops.size(); i++)
881 if (visited.find(i) != visited.cend())
886 const auto& master_loop = loops.at(i);
888 std::vector<std::vector<Gate*>> current_duplicates = {std::get<0>(master_loop)};
890 for (
size_t j = i + 1; j < loops.size(); j++)
892 const auto& current_loop = loops.at(j);
893 const auto solver_res =
894 BooleanFunction::Eq(std::get<1>(master_loop).clone(), std::get<1>(current_loop).clone(), 1)
898 if (solver_res.is_ok() && solver_res.get().is_unsat())
900 current_duplicates.push_back(std::get<0>(current_loop));
905 if (current_duplicates.size() > 1)
907 duplicate_loops.push_back(std::move(current_duplicates));
912 for (
const auto& current_duplicates : duplicate_loops)
915 const auto& survivor_loop = current_duplicates.front();
916 auto* survivor_ff = survivor_loop.front();
918 std::map<GatePin*, Net*> out_pins_to_nets;
919 for (
auto* ep : survivor_ff->get_fan_out_endpoints())
921 Net* out_net = ep->get_net();
922 out_pins_to_nets[ep->get_pin()] = out_net;
925 for (
u32 i = 1; i < current_duplicates.size(); i++)
927 auto* current_ff = current_duplicates.at(i).front();
928 for (
auto* ep : current_ff->get_fan_out_endpoints())
930 auto* ep_net = ep->get_net();
931 auto* ep_pin = ep->get_pin();
933 if (
auto it = out_pins_to_nets.find(ep_pin); it != out_pins_to_nets.cend())
936 for (
auto* dst : ep_net->get_destinations())
938 auto* dst_gate = dst->get_gate();
939 auto* dst_pin = dst->get_pin();
941 it->second->add_destination(dst_gate, dst_pin);
945 log_warning(
"netlist_preprocessing",
"could not delete net '{}' with ID {} from netlist with ID {}.", ep_net->get_name(), ep_net->get_id(), nl->
get_id());
951 ep_net->add_source(survivor_ff, ep_pin);
952 out_pins_to_nets[ep_pin] = ep_net;
956 annotate_ff_survivor(ff_replacements, survivor_ff, current_ff);
960 log_warning(
"netlist_preprocessing",
"could not delete gate '{}' with ID {} from netlist with ID {}.", current_ff->get_name(), current_ff->get_id(), nl->
get_id());
969 update_ff_replacements(ff_replacements);
971 log_info(
"netlist_preprocessing",
"removed {} redundant loops from netlist with ID {}.", num_gates, nl->
get_id());
972 return OK(num_gates);
977 struct TreeFingerprint
979 std::set<const Net*> external_inputs;
982 bool operator<(
const TreeFingerprint& other)
const
984 return (other.external_inputs < external_inputs);
991 std::map<TreeFingerprint, std::set<Net*>> fingerprint_to_nets;
992 for (
const auto& g : all_comb_gates_vec)
994 for (
const auto& out_ep : g->get_fan_out_endpoints())
999 const auto& out_net = out_ep->get_net();
1001 if (inputs_res.is_error())
1004 "Unable to remove redundant logic trees: failed to gather inputs for net " + out_net->get_name() +
" with ID " + std::to_string(out_net->get_id()));
1007 tf.external_inputs = inputs_res.get();
1010 fingerprint_to_nets[tf].insert(out_net);
1015 std::vector<std::vector<Net*>> equality_classes;
1017 for (
const auto& [_fingerprint, nets] : fingerprint_to_nets)
1031 std::vector<Net*> current_candidate_nets = {nets.begin(), nets.end()};
1032 std::vector<Net*> next_candidate_nets;
1034 while (!current_candidate_nets.empty())
1036 const auto n = current_candidate_nets.back();
1037 current_candidate_nets.pop_back();
1039 std::vector<Net*> new_equality_class = {n};
1041 for (
const auto& m : current_candidate_nets)
1044 if (comp_res.is_error())
1047 "Unable to remove redundant logic trees: failed to compare net " + n->get_name() +
" with ID " + std::to_string(n->get_id()) +
" with net "
1048 + m->get_name() +
" with ID " + std::to_string(m->get_id()));
1050 const auto are_equal = comp_res.get();
1054 new_equality_class.push_back(m);
1058 next_candidate_nets.push_back(m);
1062 equality_classes.push_back(new_equality_class);
1063 current_candidate_nets = next_candidate_nets;
1064 next_candidate_nets.clear();
1069 for (
const auto& eq_class : equality_classes)
1078 auto survivor_net = eq_class.front();
1080 for (
u32 i = 1; i < eq_class.size(); i++)
1082 auto victim_net = eq_class.at(i);
1083 for (
const auto& dst : victim_net->get_destinations())
1085 auto dst_gate = dst->get_gate();
1086 auto dst_pin = dst->get_pin();
1088 if (!victim_net->remove_destination(dst))
1090 return ERR(
"Unable to remove redundant logic trees: failed to remove destination of net " + victim_net->get_name() +
" with ID " + std::to_string(victim_net->get_id())
1091 +
" at gate " + dst_gate->get_name() +
" with ID " + std::to_string(dst_gate->get_id()) +
" and pin " + dst_pin->get_name());
1093 if (!survivor_net->add_destination(dst_gate, dst_pin))
1095 return ERR(
"Unable to remove redundant logic trees: failed to add destination to net " + survivor_net->get_name() +
" with ID " + std::to_string(survivor_net->get_id())
1096 +
" at gate " + dst_gate->get_name() +
" with ID " + std::to_string(dst_gate->get_id()) +
" and pin " + dst_pin->get_name());
1105 if (clean_up_res.is_error())
1107 return ERR_APPEND(clean_up_res.get_error(),
"Unable to remove redundant logic trees: failed to clean up dangling trees");
1110 return OK(clean_up_res.get() + counter);
1116 const GateScope scope(gates);
1119 std::vector<Gate*> candidates = scope.gates(nl);
1121 std::vector<Gate*> to_delete;
1126 for (
const auto& g : candidates)
1128 bool is_unconnected =
true;
1129 for (
const auto& on : g->get_fan_out_nets())
1131 if (!on->get_destinations().empty() || on->is_global_output_net())
1133 is_unconnected =
false;
1139 to_delete.push_back(g);
1143 for (
const auto& g : to_delete)
1147 log_warning(
"netlist_preprocessing",
"could not delete gate '{}' with ID {} from netlist with ID {}.", g->get_name(), g->get_id(), nl->
get_id());
1157 if (!to_delete.empty())
1159 const std::unordered_set<Gate*> handled(to_delete.begin(), to_delete.end());
1160 candidates.erase(std::remove_if(candidates.begin(), candidates.end(), [&handled](
Gate* g) { return handled.find(g) != handled.end(); }), candidates.end());
1162 }
while (!to_delete.empty());
1164 log_info(
"netlist_preprocessing",
"removed {} unconnected gates from netlist with ID {}.", num_gates, nl->
get_id());
1165 return OK(num_gates);
1172 std::vector<Net*> to_delete;
1174 for (
const auto& n : nl->
get_nets())
1176 if (!n->is_global_input_net() && n->get_sources().empty() && !n->is_global_output_net() && n->get_destinations().empty())
1178 to_delete.push_back(n);
1182 for (
const auto& n : to_delete)
1186 log_warning(
"netlist_preprocessing",
"could not delete net '{}' with ID {} from netlist with ID {}.", n->get_name(), n->get_id(), nl->
get_id());
1194 log_info(
"netlist_preprocessing",
"removed {} unconnected nets from netlist with ID {}.", num_nets, nl->
get_id());
1195 return OK(num_nets);
1200 u32 total_removed = 0;
1205 if (gate_res.is_error())
1207 return ERR_APPEND(gate_res.get_error(),
"unable to execute clean up loop: failed to remove unconnected gates");
1211 if (net_res.is_error())
1213 return ERR_APPEND(net_res.get_error(),
"unable to execute clean up loop: failed to remove unconnected nets");
1216 const u32 removed = gate_res.get() + net_res.get();
1217 total_removed += removed;
1224 return OK(total_removed);
1236 u32 delete_count = 0;
1237 std::vector<Gate*> delete_gate_q;
1239 for (
const auto& g : muxes)
1249 if (data_pins.size() < 2)
1254 if (out_pins.size() != 1)
1259 bool preceded_by_inv =
true;
1260 for (
const auto& pin : data_pins)
1265 preceded_by_inv =
false;
1270 if (!preceded_by_inv)
1275 bool succeded_by_inv =
true;
1276 for (
const auto& pin : out_pins)
1281 succeded_by_inv =
false;
1286 if (!succeded_by_inv)
1292 for (
const auto& pin : data_pins)
1300 auto in_net = pred->get_gate()->get_fan_in_nets().front();
1301 in_net->add_destination(g, pin);
1304 if (pred->get_gate()->get_successors().empty())
1306 delete_gate_q.push_back(pred->get_gate());
1310 for (
const auto& pin : out_pins)
1318 auto in_net = suc->get_gate()->get_fan_out_nets().front();
1319 in_net->add_source(g, pin);
1322 if (suc->get_gate()->get_predecessors().empty())
1324 delete_gate_q.push_back(suc->get_gate());
1329 for (
auto g : delete_gate_q)
1335 log_info(
"netlist_preprocessing",
"removed {} encasing inverters", delete_count);
1337 return OK(delete_count);
1340 struct MuxFingerprint
1345 bool operator<(
const MuxFingerprint& other)
const
1347 return (other.type <
type) || (other.type ==
type && other.inverters <
inverters);
1351 Result<u32> unify_inverted_select_signals(Netlist* nl, GateLibrary* mux_inv_gl)
1355 return ERR(
"netlist is a nullptr");
1358 if (mux_inv_gl ==
nullptr)
1360 return ERR(
"gate library is a nullptr");
1364 if (base_path_res.is_error())
1366 return ERR_APPEND(base_path_res.get_error(),
"unable to resynthesize boolean functions with yosys: failed to get unique temp directory");
1368 const std::filesystem::path base_path = base_path_res.get();
1369 const std::filesystem::path genlib_path = base_path /
"mux_inv.genlib";
1370 std::filesystem::create_directory(base_path);
1375 return ERR(
"unable to unify muxe select signals: failed to save gate library " + mux_inv_gl->get_name() +
" to location " + genlib_path.string());
1378 const i64 initial_size = nl->get_gates().size();
1383 std::vector<Gate*> muxes = nl->get_gates([](
const Gate* g) {
return (g->get_type()->get_name().find(
"HAL_MUX") != std::string::npos); });
1385 std::map<MuxFingerprint, std::unique_ptr<Netlist>> resynth_cache;
1387 for (
const auto& g : muxes)
1391 mf.type = g->get_type();
1394 std::map<GatePin*, Net*> pin_to_input;
1396 auto select_pins = g->get_type()->get_pins([](
const GatePin* pin) {
return (pin->get_type() ==
PinType::select) && (pin->get_direction() ==
PinDirection::input); });
1398 std::vector<Gate*> preceding_inverters;
1399 for (
const auto& pin : g->get_type()->get_input_pins())
1401 const auto pred = g->get_predecessor(pin);
1402 const auto is_select = (std::find(select_pins.begin(), select_pins.end(), pin) != select_pins.end());
1403 if (!is_select || pred ==
nullptr || pred->get_gate() ==
nullptr || !pred->get_gate()->get_type()->has_property(
GateTypeProperty::c_inverter)
1404 || (pred->get_gate()->get_fan_in_endpoints().size() != 1))
1406 pin_to_input.insert({pin, g->get_fan_in_net(pin)});
1410 auto inv_gate = pred->get_gate();
1411 preceding_inverters.push_back(inv_gate);
1412 pin_to_input.insert({pin, inv_gate->get_fan_in_endpoints().front()->get_net()});
1413 mf.inverters.insert(pin);
1418 if (!preceding_inverters.empty())
1420 const Netlist* resynth_nl;
1422 auto subgraph = preceding_inverters;
1423 subgraph.push_back(g);
1426 if (
const auto it = resynth_cache.find(mf); it == resynth_cache.end())
1428 std::unordered_map<std::string, BooleanFunction> bfs;
1429 for (
const auto& ep : g->get_fan_out_endpoints())
1431 const auto bf_res = SubgraphNetlistDecorator(*nl).get_subgraph_function(subgraph, ep->get_net());
1432 if (bf_res.is_error())
1435 "unable to unify muxes select signals: failed to build boolean function for mux " + g->get_name() +
" with ID " + std::to_string(g->get_id())
1436 +
" at output " + ep->get_pin()->get_name());
1438 auto bf = bf_res.get();
1441 for (
const auto& [pin,
net] : pin_to_input)
1443 auto sub_res = bf.substitute(BooleanFunctionNetDecorator(*net).get_boolean_variable_name(),
BooleanFunction::Var(pin->get_name(), 1));
1444 if (sub_res.is_error())
1446 return ERR_APPEND(sub_res.get_error(),
"unable to unify muxes select signals: failed to substitute net_id variable with generic variable");
1451 bfs.insert({ep->get_pin()->get_name(), std::move(bf)});
1455 if (resynth_res.is_error())
1457 return ERR_APPEND(resynth_res.get_error(),
"unable to unify select signals of muxes: failed to resynthesize mux subgraph to netlist");
1459 auto unique_resynth_nl = resynth_res.get();
1460 resynth_nl = unique_resynth_nl.get();
1461 resynth_cache.insert({mf, std::move(unique_resynth_nl)});
1465 resynth_nl = it->second.get();
1468 std::unordered_map<Net*, std::vector<Net*>> global_io_mapping;
1471 for (
const auto& pin : resynth_nl->get_top_module()->get_input_pins())
1473 auto net_it = pin_to_input.find(g->get_type()->get_pin_by_name(pin->get_name()));
1474 if (net_it == pin_to_input.end())
1476 return ERR(
"unable to unify muxes select signals:: failed to locate net in destination netlist from global input " + pin->get_name() +
" in resynthesized netlist");
1478 global_io_mapping[pin->get_net()].push_back(net_it->second);
1480 for (
const auto& pin : resynth_nl->get_top_module()->get_output_pins())
1482 auto net = g->get_fan_out_net(pin->get_name());
1485 return ERR(
"unable to unify muxes select signals:: failed to locate net in destination netlist from global output " + pin->get_name() +
" in resynthesized netlist");
1487 global_io_mapping[pin->get_net()].push_back(
net);
1491 if (replace_res.is_error())
1493 return ERR(
"unable to unify muxes select signals: failed to replace mux subgraph with resynthesized netlist");
1497 std::vector<Gate*> to_delete;
1498 for (
const auto g : subgraph)
1500 bool has_no_outside_destinations =
true;
1501 bool has_only_outside_destinations =
true;
1502 for (
const auto& suc : g->get_successors())
1504 const auto it = std::find(subgraph.begin(), subgraph.end(), suc->get_gate());
1505 if (it == subgraph.end())
1507 has_no_outside_destinations =
false;
1510 if (it != subgraph.end())
1512 has_only_outside_destinations =
false;
1516 if (has_no_outside_destinations || has_only_outside_destinations)
1518 to_delete.push_back(g);
1522 for (
const auto& g : to_delete)
1524 if (!nl->delete_gate(g))
1526 return ERR(
"unable to unify muxes select signals: failed to delete gate " + g->get_name() +
" with ID " + std::to_string(g->get_id()) +
" in destination netlist");
1533 std::filesystem::remove_all(base_path);
1535 const i64 new_size = nl->get_gates().size();
1536 const i64 difference = std::abs(initial_size - new_size);
1538 return OK(
u32(difference));
1541 Result<u32> unify_select_signals(Netlist* nl)
1545 return ERR(
"netlist is a nullptr");
1548 u32 changed_connections = 0;
1551 std::map<std::pair<GateType*, std::set<Net*>>, std::vector<Gate*>> grouped_muxes;
1552 for (
const auto& g : nl->get_gates([](
const Gate* g) { return g->get_type()->has_property(GateTypeProperty::c_mux); }))
1554 std::set<Net*> select_signals;
1555 const auto select_pins = g->get_type()->get_pins([](
const GatePin* pin) {
return (pin->get_type() ==
PinType::select) && (pin->get_direction() ==
PinDirection::input); });
1556 for (
const auto& sp : select_pins)
1558 select_signals.insert(g->get_fan_in_net(sp));
1561 grouped_muxes[{g->get_type(), select_signals}].push_back(g);
1565 for (
const auto& [finger_print, mux_group] : grouped_muxes)
1567 const auto& [
type, select_signals_set] = finger_print;
1569 const auto output_pins =
type->get_pins([](
const GatePin* pin) {
return pin->get_direction() ==
PinDirection::output; });
1571 if (output_pins.size() != 1)
1574 "Cannot unify select signals for muxes of type {} since the type has {} output signals and we can only handle 1.",
1576 output_pins.size());
1581 std::map<std::map<GatePin*, Net*>, std::vector<Gate*>> select_map_to_muxes;
1582 for (
const auto& g : mux_group)
1584 std::map<GatePin*, Net*> select_map;
1585 for (
const auto& sp : select_pins)
1587 select_map.insert({sp, g->get_fan_in_net(sp)});
1590 select_map_to_muxes[select_map].push_back(g);
1593 if (select_map_to_muxes.size() == 1)
1598 const std::vector<Net*> select_signals = {select_signals_set.begin(), select_signals_set.end()};
1601 std::map<Gate*, std::map<GatePin*, Net*>> new_net_to_pin;
1604 for (
const auto& g : mux_group)
1606 for (
u32 select_index = 0; select_index < select_pins.size(); select_index++)
1608 auto select_pin = select_pins.at(select_index);
1609 auto select_signal = select_signals.at(select_index);
1610 new_net_to_pin[g][select_pin] = select_signal;
1615 auto type_bf =
type->get_boolean_function(output_pins.front());
1616 for (
u32 select_val = 0; select_val < (1 << select_signals.size()); select_val++)
1618 std::map<std::string, BooleanFunction> type_substitution;
1619 for (
u32 select_idx = 0; select_idx < select_pins.size(); select_idx++)
1621 auto select_pin = select_pins.at(select_idx);
1623 auto type_substitution_val = ((select_val >> select_idx) & 0x1) ?
BooleanFunction::Const(1, 1) : BooleanFunction::Const(0, 1);
1624 type_substitution.insert({select_pin->get_name(), type_substitution_val});
1627 auto type_substitution_res = type_bf.substitute(type_substitution);
1628 if (type_substitution_res.is_error())
1630 return ERR_APPEND(type_substitution_res.get_error(),
"cannot unify mux select signals: failed to substitute type Boolean function with select signal value mapping.");
1632 auto input = type_substitution_res.get().simplify_local();
1634 if (!
input.is_variable())
1636 return ERR(
"cannot unify mux select signals: substituted and simplified type Boolean function (" +
input.to_string() +
") is not a variable");
1639 const auto pin_name =
input.get_variable_name().get();
1640 auto pin =
type->get_pins([pin_name](
const auto& p) {
return p->get_name() == pin_name; }).front();
1642 for (
const auto& g : mux_group)
1644 auto gate_bf_res = g->get_resolved_boolean_function(output_pins.front(),
false);
1645 if (gate_bf_res.is_error())
1648 "cannot unify mux select signals: failed to build Boolean function for gate " + g->get_name() +
" with ID " + std::to_string(g->get_id()));
1650 auto gate_bf = gate_bf_res.get();
1652 std::map<std::string, BooleanFunction> gate_substitution;
1654 for (
u32 select_idx = 0; select_idx < select_pins.size(); select_idx++)
1656 auto gate_substitution_val = ((select_val >> select_idx) & 0x1) ?
BooleanFunction::Const(1, 1) : BooleanFunction::Const(0, 1);
1657 gate_substitution.insert({BooleanFunctionNetDecorator(*(select_signals.at(select_idx))).get_boolean_variable_name(), gate_substitution_val});
1660 auto gate_substitution_res = gate_bf.substitute(gate_substitution);
1661 if (gate_substitution_res.is_error())
1663 return ERR_APPEND(gate_substitution_res.get_error(),
"cannot unify mux select signals: failed to substitute gate Boolean function with select signal value mapping.");
1665 auto input_net_var = gate_substitution_res.get().simplify_local();
1668 if (net_res.is_error())
1670 return ERR_APPEND(net_res.get_error(),
"cannot unify mux select signals: failed to extract net from substituted and simplified gate Boolean function");
1673 auto net = net_res.get();
1674 new_net_to_pin[g][pin] =
net;
1679 for (
auto& [g, pin_net] : new_net_to_pin)
1681 for (
const auto& [pin,
net] : pin_net)
1683 auto connected_net = g->get_fan_in_net(pin);
1684 if (
net == connected_net)
1689 connected_net->remove_destination(g, pin);
1690 net->add_destination(g, pin);
1692 changed_connections += 1;
1697 return OK(changed_connections);
1707 return ERR(
"netlist is a nullptr");
1710 if (mux_inv_gl ==
nullptr)
1712 return ERR(
"gate library is a nullptr");
1715 auto remove_res = remove_encasing_inverters(nl);
1716 if (remove_res.is_error())
1718 return ERR_APPEND(remove_res.get_error(),
"unable to apply manual mux optimizations: failed to remove encasing inverters");
1720 res_count += remove_res.get();
1722 auto unify_inverted_res = unify_inverted_select_signals(nl, mux_inv_gl);
1723 if (unify_inverted_res.is_error())
1725 return ERR_APPEND(unify_inverted_res.get_error(),
"unable to apply manual mux optimizations: failed to unify inverted select signals");
1727 res_count += unify_inverted_res.get();
1729 auto unify_res = unify_select_signals(nl);
1730 if (unify_res.is_error())
1732 return ERR_APPEND(unify_res.get_error(),
"unable to apply manual mux optimizations: failed to unify select signals");
1734 res_count += unify_res.get();
1736 return OK(res_count);
1743 return ERR(
"netlist is a nullptr");
1746 const GateScope scope(gates);
1751 u32 total_replaced_dst_count = 0;
1755 u32 replaced_dst_count = 0;
1756 std::vector<Gate*> to_delete;
1759 for (
const auto g : nl->
get_gates([&scope](
const auto g) {
1760 return scope.contains(g) && g->get_type()->has_property(GateTypeProperty::combinational) && !g->get_type()->has_property(GateTypeProperty::ground)
1761 && !g->get_type()->has_property(GateTypeProperty::power);
1764 bool has_global_output =
false;
1765 for (
const auto ep : g->get_fan_out_endpoints())
1767 if (ep->get_net()->is_global_output_net())
1769 has_global_output =
true;
1772 auto bf_res = g->get_resolved_boolean_function(ep->get_pin(),
false);
1773 if (bf_res.is_error())
1776 "unable to propagate constants: failed to generate boolean function at gate " + g->get_name() +
" with ID " + std::to_string(g->get_id()) +
" for pin "
1777 + ep->get_pin()->get_name());
1779 auto bf = bf_res.get();
1781 if (sub_res.is_error())
1784 "unable to propagate constants: failed to substitue power and ground nets in boolean function of gate " + g->get_name() +
" with ID "
1785 + std::to_string(g->get_id()) +
" for pin " + ep->get_pin()->get_name());
1788 bf = bf.simplify_local();
1791 if (bf.is_constant())
1794 if (bf.has_constant_value(0))
1796 new_source = gnd_net;
1798 else if (bf.has_constant_value(1))
1800 new_source = vcc_net;
1807 if (new_source ==
nullptr)
1810 return ERR(
"unable to propagate constants: netlist is missing gnd or vcc net!");
1813 std::vector<std::pair<Gate*, GatePin*>> to_replace;
1814 for (
auto dst : ep->get_net()->get_destinations())
1816 to_replace.push_back({dst->get_gate(), dst->get_pin()});
1819 for (
const auto& [dst_g, dst_p] : to_replace)
1821 ep->get_net()->remove_destination(dst_g, dst_p);
1824 replaced_dst_count++;
1831 if (!has_global_output && g->get_successors().empty())
1833 to_delete.push_back(g);
1837 for (
auto g : to_delete)
1842 if (replaced_dst_count == 0)
1847 log_debug(
"netlist_preprocessing",
"replaced {} destinations this with power/ground nets this iteration", replaced_dst_count);
1848 total_replaced_dst_count += replaced_dst_count;
1851 log_info(
"netlist_preprocessing",
"replaced {} destinations with power/ground nets in total", total_replaced_dst_count);
1852 return OK(total_replaced_dst_count);
1859 return ERR(
"netlist is a nullptr");
1862 const GateScope scope(gates);
1864 std::set<Gate*> gates_to_delete;
1865 for (
auto* inv_gate : scope.gates(nl, [](
const Gate* g) { return g->get_type()->has_property(GateTypeProperty::c_inverter); }))
1867 if (gates_to_delete.find(inv_gate) != gates_to_delete.end())
1872 const auto& connection_endpoints = inv_gate->get_fan_in_endpoints();
1873 if (connection_endpoints.size() != 1)
1875 log_warning(
"netlist_preprocessing",
"could not handle gate '{}' with ID {} due to a fan-in size != 1", inv_gate->get_name(), inv_gate->get_id());
1879 auto* middle_fan_in_ep = connection_endpoints.front();
1880 auto* middle_net = middle_fan_in_ep->get_net();
1881 if (middle_net->get_sources().size() != 1)
1883 log_warning(
"netlist_preprocessing",
"could not handle gate '{}' with ID {} due to a number of predecessors != 1", inv_gate->get_name(), inv_gate->get_id());
1886 auto* pred_gate = middle_net->get_sources().front()->get_gate();
1889 if (!scope.contains(pred_gate))
1896 const auto& fan_in = pred_gate->get_fan_in_endpoints();
1897 if (fan_in.size() != 1)
1899 log_warning(
"netlist_preprocessing",
"could not handle gate '{}' with ID {} due to a fan-in size != 1", pred_gate->get_name(), pred_gate->get_id());
1902 if (pred_gate->get_fan_out_endpoints().size() != 1)
1904 log_warning(
"netlist_preprocessing",
"could not handle gate '{}' with ID {} due to a fan-out size != 1", pred_gate->get_name(), pred_gate->get_id());
1907 auto* in_net = fan_in.front()->get_net();
1909 const auto& fan_out = inv_gate->get_fan_out_endpoints();
1910 if (fan_out.size() != 1)
1912 log_warning(
"netlist_preprocessing",
"could not handle gate '{}' with ID {} due to a fan-out size != 1", inv_gate->get_name(), inv_gate->get_id());
1915 auto* out_net = fan_out.front()->get_net();
1917 for (
auto* dst_ep : out_net->get_destinations())
1919 auto* dst_pin = dst_ep->get_pin();
1920 auto* dst_gate = dst_ep->get_gate();
1922 out_net->remove_destination(dst_ep);
1923 in_net->add_destination(dst_gate, dst_pin);
1926 middle_net->remove_destination(middle_fan_in_ep);
1928 if (middle_net->get_num_of_destinations() == 0)
1931 gates_to_delete.insert(pred_gate);
1934 gates_to_delete.insert(inv_gate);
1938 u32 removed_ctr = 0;
1939 for (
auto* g : gates_to_delete)
1945 return OK(removed_ctr);
1950 std::string generate_hex_truth_table_string(
const std::vector<BooleanFunction::Value>& tt)
1952 std::string tt_str =
"";
1955 for (
u32 i = 0; i < tt.size(); i++)
1958 if (bit == BooleanFunction::Value::ONE)
1960 acc += (1 << (i % 4));
1965 std::stringstream stream;
1966 stream << std::hex << acc;
1968 tt_str = stream.str() + tt_str;
1982 const GateScope scope(gates);
1984 for (
auto g : scope.gates(nl, [](
const auto& g) { return g->get_type()->has_property(GateTypeProperty::c_lut); }))
1986 auto res = g->get_init_data();
1990 "unable to simplify lut init string for gate " + g->get_name() +
" with ID " + std::to_string(g->get_id()) +
": failed to get original INIT string");
1993 const auto original_inits = res.get();
1995 if (original_inits.size() != 1)
1997 return ERR(
"unable to simplify lut init string for gate " + g->get_name() +
" with ID " + std::to_string(g->get_id()) +
": found " + std::to_string(original_inits.size())
1998 +
" init data strings but expected exactly 1.");
2001 const auto original_init = original_inits.front();
2004 if (g->get_type()->get_output_pins().size() != 1)
2010 if (g->get_fan_out_endpoints().empty())
2015 const auto out_ep = g->get_fan_out_endpoints().front();
2018 if (g->get_boolean_functions().size() != 1)
2023 const auto bf_org = g->get_boolean_function(out_ep->get_pin());
2024 const auto org_vars = bf_org.get_variable_names();
2027 if (bf_replaced_res.is_error())
2029 return ERR_APPEND(bf_replaced_res.get_error(),
2030 "cannot simplify LUT inits: failed to replace power and ground pins for gate " + g->get_name() +
" with ID " + std::to_string(g->get_id()));
2032 const auto bf_replaced = bf_replaced_res.get();
2033 const auto bf_simplified = bf_replaced.simplify_local();
2035 const auto new_vars = bf_simplified.get_variable_names();
2037 if (org_vars.size() == new_vars.size())
2042 auto bf_extended = bf_simplified.clone();
2043 for (
const auto& in_pin : g->get_type()->get_input_pin_names())
2045 if (new_vars.find(in_pin) == new_vars.end())
2052 const auto tt = bf_extended.compute_truth_table().get();
2053 const auto new_init_string = generate_hex_truth_table_string(tt.front());
2058 g->set_init_data({new_init_string}).get();
2059 g->set_data(
"preprocessing_information",
"original_init",
"string", original_init);
2072 log_info(
"netlist_preprocessing",
"simplified {} LUT INIT strings inside of netlist with ID {}.", num_inits, nl->
get_id());
2073 return OK(num_inits);
2078 struct indexed_identifier
2080 indexed_identifier(
const std::string& p_identifier,
const u32 p_index,
const std::string& p_origin) :
identifier{p_identifier},
index{p_index},
origin{p_origin}
2090 const std::string hal_instance_index_pattern =
"__\\[(\\d+)\\]__";
2091 const std::string hal_instance_index_pattern_reverse =
"<HAL>(\\d+)<HAL>";
2093 std::string replace_hal_instance_index(
const std::string&
name)
2095 std::regex re(hal_instance_index_pattern);
2100 while (std::regex_search(
input, match, re))
2109 std::string reconstruct_hal_instance_index(
const std::string&
name)
2111 std::regex re(hal_instance_index_pattern_reverse);
2116 while (std::regex_search(input, match, re))
2125 const std::string net_index_pattern =
"\\((\\d+)\\)";
2126 const std::string gate_index_pattern =
"\\[(\\d+)\\]";
2129 std::optional<indexed_identifier> extract_index(
const std::string&
name,
const std::string& index_pattern,
const std::string&
origin)
2131 std::regex re(index_pattern);
2134 std::optional<std::string> last_match;
2135 std::optional<u32> last_index;
2139 while (std::regex_search(input, match, re))
2142 last_index = std::stoi(match[1]);
2143 last_match = match.str();
2144 input = match.suffix().str();
2147 if (!last_index.has_value())
2149 return std::nullopt;
2152 const auto found_match = last_match.value();
2153 auto identifier_name =
name;
2154 identifier_name = identifier_name.replace(
name.rfind(found_match), found_match.size(),
"");
2156 return std::optional<indexed_identifier>{{identifier_name, last_index.value(),
origin}};
2160 bool annotate_indexed_identifiers(Gate* gate,
const std::vector<indexed_identifier>& identifiers)
2162 std::string json_identifier_str =
2163 "[" +
utils::join(
", ", identifiers, [](
const auto& i) {
return std::string(
"[") +
'"' + i.identifier +
'"' +
", " + std::to_string(i.index) +
", " +
'"' + i.origin +
'"' +
"]"; })
2166 return gate->set_data(
"preprocessing_information",
"multi_bit_indexed_identifiers",
"string", json_identifier_str);
2170 std::vector<indexed_identifier> check_net_at_pin(
const PinType pin_type, Gate* gate)
2172 const auto typed_pins = gate->get_type()->get_pins([pin_type](
const auto p) {
return p->get_type() == pin_type; });
2174 std::vector<indexed_identifier> found_identfiers;
2176 for (
const auto& pin : typed_pins)
2178 const auto typed_net = (pin->get_direction() ==
PinDirection::output) ? gate->get_fan_out_net(pin) : gate->get_fan_in_net(pin);
2187 const auto net_name_index = extract_index(typed_net->get_name(), net_index_pattern,
"net_name");
2188 if (net_name_index.has_value())
2190 found_identfiers.push_back(net_name_index.value());
2194 if (!typed_net->has_data(
"parser_annotation",
"merged_nets"))
2199 const auto all_merged_nets_str = std::get<1>(typed_net->get_data(
"parser_annotation",
"merged_nets"));
2201 if (all_merged_nets_str.empty())
2207 rapidjson::Document doc;
2208 doc.Parse(all_merged_nets_str.c_str());
2210 for (
u32 i = 0; i < doc.GetArray().Size(); i++)
2212 const auto list = doc[i].GetArray();
2213 for (
u32 j = 0; j < list.Size(); j++)
2215 const auto merged_wire_name = list[j].GetString();
2217 const auto merged_wire_name_index = extract_index(merged_wire_name, net_index_pattern,
"net_name");
2218 if (merged_wire_name_index.has_value())
2220 found_identfiers.push_back(merged_wire_name_index.value());
2226 return found_identfiers;
2233 for (
auto&
ff : nl->
get_gates([](
const auto g) { return g->get_type()->has_property(GateTypeProperty::ff); }))
2235 std::vector<indexed_identifier> all_identifiers;
2238 const auto cleaned_gate_name = replace_hal_instance_index(
ff->get_name());
2239 const auto gate_name_index = extract_index(cleaned_gate_name, gate_index_pattern,
"gate_name");
2241 if (gate_name_index.has_value())
2243 auto found_identifier = gate_name_index.value();
2244 found_identifier.identifier = reconstruct_hal_instance_index(found_identifier.identifier);
2245 all_identifiers.push_back(found_identifier);
2251 for (
const auto& pt : relevant_pin_types)
2253 const auto found_identifiers = check_net_at_pin(pt,
ff);
2254 all_identifiers.insert(all_identifiers.end(), found_identifiers.begin(), found_identifiers.end());
2257 if (!all_identifiers.empty())
2262 annotate_indexed_identifiers(
ff, all_identifiers);
2270 std::map<std::string, std::map<u32, std::vector<ModulePin*>>> pg_name_to_indexed_pins;
2274 auto reconstruct = extract_index(pin->get_name(), net_index_pattern,
"");
2275 if (!reconstruct.has_value())
2280 auto [pg_name,
index, _] = reconstruct.value();
2282 pg_name_to_indexed_pins[pg_name][
index].push_back(pin);
2285 u32 reconstructed_counter = 0;
2286 for (
const auto& [pg_name, indexed_pins] : pg_name_to_indexed_pins)
2288 std::vector<ModulePin*> ordered_pins;
2290 bool valid_indices =
true;
2292 for (
const auto& [_index,
pins] : indexed_pins)
2294 if (
pins.size() > 1)
2296 valid_indices =
false;
2300 ordered_pins.push_back(
pins.front());
2311 return ERR_APPEND(res.get_error(),
"cannot reconstruct top module pin groups: failed to create pin group " + pg_name);
2314 reconstructed_counter++;
2317 return OK(reconstructed_counter);
2322 struct ComponentData
2330 TokenStream<std::string> tokenize(std::stringstream& ss)
2332 const std::string delimiters =
" ;-";
2333 std::string current_token;
2334 u32 line_number = 0;
2337 bool escaped =
false;
2339 std::vector<Token<std::string>> parsed_tokens;
2340 while (std::getline(ss, line))
2352 else if (escaped && std::isspace(c))
2358 if (((!std::isspace(c) && delimiters.find(c) == std::string::npos) || escaped))
2364 if (!current_token.empty())
2366 parsed_tokens.emplace_back(line_number, current_token);
2367 current_token.clear();
2370 if (!std::isspace(c))
2372 parsed_tokens.emplace_back(line_number, std::string(1, c));
2377 if (!current_token.empty())
2379 parsed_tokens.emplace_back(line_number, current_token);
2380 current_token.clear();
2384 return TokenStream(parsed_tokens, {}, {});
2387 Result<std::unordered_map<std::string, ComponentData>> parse_tokens(TokenStream<std::string>& ts)
2389 ts.consume_until(
"COMPONENTS");
2390 ts.consume(
"COMPONENTS");
2391 const auto component_count_str = ts.consume().string;
2394 u32 component_count;
2397 component_count = res.get();
2401 return ERR_APPEND(res.get_error(),
"could not parse tokens: failed to read component count from token" + component_count_str);
2404 std::cout <<
"Component count: " << component_count << std::endl;
2406 std::unordered_map<std::string, ComponentData> component_data;
2407 for (
u32 c_idx = 0; c_idx < component_count; c_idx++)
2410 ComponentData new_data_entry;
2412 new_data_entry.name = ts.consume().string;
2413 new_data_entry.type = ts.consume().string;
2415 ts.consume(
"SOURCE");
2417 ts.consume(
"TIMING");
2419 ts.consume(
"PLACED");
2420 ts.consume(
"FIXED");
2425 new_data_entry.x = res.get();
2429 return ERR_APPEND(res.get_error(),
"could not parse tokens: failed to read x coordinate from token");
2434 new_data_entry.y = res.get();
2438 return ERR_APPEND(res.get_error(),
"could not parse tokens: failed to read y coordinate from token");
2443 ts.consume_current_line();
2445 component_data.insert({new_data_entry.name, new_data_entry});
2448 return OK(component_data);
2454 std::stringstream ss;
2456 ifs.open(def_file.string(), std::ifstream::in);
2459 return ERR(
"could not parse DEF (Design Exchange Format) file '" + def_file.string() +
"' : unable to open file");
2464 auto ts = tokenize(ss);
2466 std::unordered_map<std::string, ComponentData> component_data;
2470 if (
auto res = parse_tokens(ts); res.is_error())
2472 return ERR_APPEND(res.get_error(),
"could not parse Design Exchange Format file '" + def_file.string() +
"': unable to parse tokens");
2476 component_data = res.get();
2481 if (e.line_number != (
u32)-1)
2483 return ERR(
"could not parse Design Exchange Format file '" + def_file.string() +
"': " + e.message +
" (line " + std::to_string(e.line_number) +
")");
2487 return ERR(
"could not parse Design Exchange Format file '" + def_file.string() +
"': " + e.message);
2491 std::unordered_map<std::string, Gate*> name_to_gate;
2494 name_to_gate.insert({g->get_name(), g});
2498 for (
const auto& [gate_name,
data] : component_data)
2500 if (
const auto& g_it = name_to_gate.find(gate_name); g_it != name_to_gate.end())
2503 g_it->second->set_location_x(
data.x);
2504 g_it->second->set_location_y(
data.y);
2510 log_info(
"netlist_preprocessing",
"reconstructed coordinates for {} / {} ({:.2}) gates", counter, nl->
get_gates().size(), (
double)counter / (
double)nl->
get_gates().size());
2517 std::vector<Module*> all_modules;
2518 for (
const auto& [gt_name, pin_groups] : concatenated_pin_groups)
2523 return ERR(
"unable to create multi bit gate module for gate type " + gt_name +
": failed to find gate type with that name in gate library " + nl->
get_gate_library()->
get_name());
2526 for (
const auto& g : nl->
get_gates([>](
const auto& g) { return g->get_type() == gt; }))
2528 auto m = nl->
create_module(
"module_" + g->get_name(), g->get_module(), {g});
2530 for (
const auto& [module_pg_name, gate_pg_names] : pin_groups)
2532 std::vector<ModulePin*> module_pins;
2533 for (
const auto& gate_pg_name : gate_pg_names)
2535 const auto& gate_pg = g->
get_type()->get_pin_group_by_name(gate_pg_name);
2537 if (gate_pg ==
nullptr)
2539 return ERR(
"unable to create multi-bit gate module for gate type " + gt_name +
" and pin group " + gate_pg_name +
": failed to find pin group with that name");
2542 std::vector<GatePin*> pin_list = gate_pg->get_pins();
2543 if (!gate_pg->is_ascending())
2545 std::reverse(pin_list.begin(), pin_list.end());
2548 for (
const auto& gate_pin : pin_list)
2550 const auto net = (gate_pin->get_direction() ==
PinDirection::output) ? g->get_fan_out_net(gate_pin) : g->get_fan_in_net(gate_pin);
2556 if (
net->is_gnd_net() ||
net->is_vcc_net())
2561 const auto module_pin = m->get_pin_by_net(
net);
2563 module_pins.push_back(module_pin);
2567 m->create_pin_group(module_pg_name, module_pins);
2568 u32 idx_counter = 0;
2569 for (
const auto& mp : module_pins)
2571 m->set_pin_name(mp, module_pg_name +
"_" + std::to_string(idx_counter));
2576 all_modules.push_back(m);
2580 return OK(all_modules);
2585 std::vector<Net*> created_nets;
2587 const GateScope scope(gates);
2589 for (
const auto& g : scope.gates(nl))
2591 for (
const auto& p : g->get_type()->get_output_pins())
2593 if (g->get_fan_out_net(p) ==
nullptr)
2596 new_net->
set_name(
"HAL_UNCONNECTED_" + std::to_string(new_net->get_id()));
2597 new_net->add_source(g, p);
2599 created_nets.push_back(new_net);
2604 return OK(created_nets);
2611 return ERR(
"netlist is a nullptr");
2614 if (inverter_type ==
nullptr)
2617 const auto inv_types =
2619 if (inv_types.empty())
2621 return ERR(
"gate library '" + gl->get_name() +
"' of netlist does not contain an inverter gate");
2623 inverter_type = inv_types.begin()->second;
2629 return ERR(
"inverter gate type '" + inverter_type->
get_name() +
"' of gate library '" + inverter_type->
get_gate_library()->
get_name() +
"' does not belong to gate library '"
2641 +
"' has an invalid number of input pins or output pins");
2650 const std::vector<Gate*>& gates = ffs.empty() ? nl->
get_gates() : ffs;
2652 for (
auto*
ff : gates)
2654 auto* ff_type =
ff->get_type();
2662 GatePin* neg_state_pin =
nullptr;
2664 for (
auto* o_pin : ff_type->get_output_pins())
2672 neg_state_pin = o_pin;
2676 if (neg_state_pin ==
nullptr)
2681 auto* neg_state_ep =
ff->get_fan_out_endpoint(neg_state_pin);
2682 if (neg_state_ep ==
nullptr)
2686 auto* neg_state_net = neg_state_ep->get_net();
2688 auto state_net =
ff->get_fan_out_net(state_pin);
2689 if (state_net ==
nullptr)
2691 state_net = nl->
create_net(
ff->get_name() +
"__STATE_NET__");
2695 auto* inv = nl->
create_gate(inverter_type,
ff->get_name() +
"__NEG_STATE_INVERT__");
2698 if (
auto* mod =
ff->get_module(); !mod->is_top_module())
2700 mod->assign_gate(inv);
2703 state_net->add_destination(inv, inv_in_pin);
2704 neg_state_net->remove_source(neg_state_ep);
2705 neg_state_net->add_source(inv, inv_out_pin);
const std::string & get_name() const
Result< BooleanFunction > substitute_power_ground_nets(const Netlist *nl) const
Result< BooleanFunction > substitute_power_ground_pins(const Gate *g) const
static Result< BooleanFunction > Eq(BooleanFunction &&p0, BooleanFunction &&p1, u16 size)
static BooleanFunction Var(const std::string &name, u16 size=1)
Result< std::string > get_variable_name() const
std::set< std::string > get_variable_names() const
Value
represents the type of the node
BooleanFunction simplify_local() const
static BooleanFunction Const(const BooleanFunction::Value &value)
static Result< BooleanFunction > Not(BooleanFunction &&p0, u16 size)
static Result< BooleanFunction > And(BooleanFunction &&p0, BooleanFunction &&p1, u16 size)
static Result< Net * > get_net_from(const Netlist *netlist, const BooleanFunction &var)
std::string get_boolean_variable_name() const
GatePin * get_pin() const
GateType * get_type() const
Result< BooleanFunction > get_resolved_boolean_function(const GatePin *pin, const bool use_net_variables=false) const
std::vector< Endpoint * > get_successors(const std::function< bool(const GatePin *pin, Endpoint *ep)> &filter=nullptr) const
const std::string & get_name() const
Endpoint * get_predecessor(const std::string &pin_name) const
Endpoint * get_successor(const std::string &pin_name) const
std::unordered_map< std::string, GateType * > get_gate_types(const std::function< bool(const GateType *)> &filter=nullptr) const
GateType * get_gate_type_by_name(const std::string &name) const
std::string get_name() const
std::vector< std::string > get_input_pin_names() const
GateLibrary * get_gate_library() const
std::vector< GatePin * > get_output_pins() const
const std::string & get_name() const
bool has_property(GateTypeProperty property) const
std::vector< GatePin * > get_input_pins() const
const std::unordered_map< std::string, BooleanFunction > & get_boolean_functions() const
std::vector< GatePin * > get_pins(const std::function< bool(GatePin *)> &filter=nullptr) const
std::vector< ModulePin * > get_pins(const std::function< bool(ModulePin *)> &filter=nullptr) const
Result< PinGroup< ModulePin > * > create_pin_group(const u32 id, const std::string &name, const std::vector< ModulePin * > pins={}, PinDirection direction=PinDirection::none, PinType type=PinType::none, bool ascending=false, u32 start_index=0, bool delete_empty_groups=true, bool force_name=false)
std::string get_type() const
Endpoint * add_destination(Gate *gate, const std::string &pin_name)
bool remove_source(Gate *gate, const std::string &pin_name)
void set_name(const std::string &name)
Endpoint * add_source(Gate *gate, const std::string &pin_name)
const std::string & get_name() const
std::vector< Endpoint * > get_destinations(const std::function< bool(Endpoint *ep)> &filter=nullptr) const
bool remove_destination(Gate *gate, const std::string &pin_name)
Module * get_top_module() const
const std::vector< Gate * > & get_gates() const
bool delete_net(Net *net)
Net * create_net(const u32 net_id, const std::string &name)
const std::vector< Gate * > & get_gnd_gates() const
const std::vector< Gate * > & get_vcc_gates() const
bool delete_gate(Gate *gate)
Gate * create_gate(const u32 gate_id, GateType *gate_type, const std::string &name="", i32 x=-1, i32 y=-1)
const std::vector< Net * > & get_nets() const
const GateLibrary * get_gate_library() const
Module * create_module(const u32 module_id, const std::string &name, Module *parent, const std::vector< Gate * > &gates={})
Result< Net * > connect_nets(Net *master_net, Net *slave_net)
Result< std::set< const Net * > > get_subgraph_function_inputs(const std::vector< const Gate * > &subgraph_gates, const Net *subgraph_output) const
Result< BooleanFunction > get_subgraph_function(const std::vector< const Gate * > &subgraph_gates, const Net *subgraph_output, std::map< std::pair< u32, const GatePin * >, BooleanFunction > &cache) const
#define log_debug(channel,...)
#define log_info(channel,...)
#define log_warning(channel,...)
#define ERR_APPEND(prev_error, message)
bool save(std::filesystem::path file_path, GateLibrary *gate_lib, bool overwrite=false)
std::unique_ptr< GateLibrary > parse(std::filesystem::path file_path)
Result< std::monostate > parse_def_file(Netlist *nl, const std::filesystem::path &def_file)
Result< u32 > manual_mux_optimizations(Netlist *nl, GateLibrary *mux_inv_gl)
Result< u32 > propagate_constants(Netlist *nl, const std::vector< Gate * > &gates={})
Result< std::vector< Net * > > create_nets_at_unconnected_pins(Netlist *nl, const std::vector< Gate * > &gates={})
Result< u32 > remove_unconnected_gates(Netlist *nl, const std::vector< Gate * > &gates={})
Result< u32 > remove_redundant_loops(Netlist *nl)
Result< u32 > remove_redundant_logic_trees(Netlist *nl)
Result< u32 > remove_redundant_gates(Netlist *nl, const std::function< bool(const Gate *)> &filter=nullptr, const std::vector< Gate * > &gates={})
Result< u32 > reconstruct_top_module_pin_groups(Netlist *nl)
Result< u32 > simplify_lut_inits(Netlist *nl, const std::vector< Gate * > &gates={})
Result< u32 > remove_buffers(Netlist *nl, const std::vector< Gate * > &gates={})
Result< u32 > remove_unused_lut_inputs(Netlist *nl, const std::vector< Gate * > &gates={})
Result< u32 > remove_unconnected_looped(Netlist *nl)
Result< u32 > remove_unconnected_nets(Netlist *nl)
Result< u32 > reconstruct_indexed_ff_identifiers(Netlist *nl)
Result< u32 > remove_consecutive_inverters(Netlist *nl, const std::vector< Gate * > &gates={})
Result< std::vector< Module * > > create_multi_bit_gate_modules(Netlist *nl, const std::map< std::string, std::map< std::string, std::vector< std::string >>> &concatenated_pin_groups)
Result< u32 > unify_ff_outputs(Netlist *nl, const std::vector< Gate * > &ffs={}, GateType *inverter_type=nullptr)
Result< std::monostate > replace_subgraph_with_netlist(const std::vector< Gate * > &subgraph, const std::unordered_map< Net *, std::vector< Net * >> &global_io_mapping, const Netlist *src_nl, Netlist *dst_nl, const bool delete_subgraph_gates)
Result< std::unique_ptr< Netlist > > generate_resynth_netlist_for_boolean_functions(const std::unordered_map< std::string, BooleanFunction > &bfs, const std::filesystem::path &genlib_path, GateLibrary *target_gl, const bool optimize_area)
T replace(const T &str, const T &search, const T &replace)
Result< u64 > wrapped_stoull(const std::string &s, const u32 base=10)
Result< u32 > wrapped_stoul(const std::string &s, const u32 base=10)
std::string join(const std::string &joiner, const Iterator &begin, const Iterator &end, const Transform &transform)
Result< std::filesystem::path > get_unique_temp_directory(const std::string &prefix="", const u32 max_attempts=5)
Result< bool > compare_nets(const Netlist *netlist_a, const Netlist *netlist_b, const Net *net_a, const Net *net_b, const bool fail_on_unknown=true, const u32 solver_timeout=10)
Compare two nets from two different netlists.
std::vector< PinInformation > pins
std::set< GatePin * > inverters
This file contains functions to decompose or re-synthesize combinational parts of a gate-level netlis...