14 #include "nlohmann/json.hpp"
15 #include "rapidjson/document.h"
25 namespace netlist_preprocessing
33 if (gnd_gates.empty())
35 return ERR(
"could not remove unused LUT endpoints from netlist with ID " + std::to_string(nl->
get_id()) +
": no GND net available within netlist");
37 Net* gnd_net = gnd_gates.front()->get_fan_out_nets().front();
40 for (
const auto& gate : nl->
get_gates([](
const Gate* g) { return g->get_type()->has_property(GateTypeProperty::c_lut); }))
42 std::vector<Endpoint*> fan_in = gate->get_fan_in_endpoints();
43 std::unordered_map<std::string, BooleanFunction> functions = gate->get_boolean_functions();
46 if (functions.size() != 1)
52 auto active_pins = functions.begin()->second.get_variable_names();
55 if (fan_in.size() > active_pins.size())
57 for (
const auto& ep : fan_in)
59 if (ep->get_net()->is_gnd_net() || ep->get_net()->is_vcc_net())
64 if (std::find(active_pins.begin(), active_pins.end(), ep->get_pin()->get_name()) == active_pins.end())
67 if (!ep->get_net()->remove_destination(gate, pin))
70 "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());
76 "failed to reconnect unused input of LUT gate '{}' with ID {} to GND in netlist with ID {}.",
88 log_info(
"netlist_preprocessing",
"removed {} unused LUT endpoints from netlist with ID {}.", num_eps, nl->
get_id());
98 std::queue<Gate*> gates_to_be_deleted;
102 std::vector<Endpoint*> fan_out = gate->get_fan_out_endpoints();
113 if (fan_out.size() != 1)
120 if (functions.size() != 1)
126 Endpoint* out_endpoint = *(fan_out.begin());
132 std::vector<Endpoint*> fan_in = gate->get_fan_in_endpoints();
137 if (substitute_res.is_error())
140 "Cannot replace buffers: failed to substitute pins with constants at gate " + gate->get_name() +
" with ID " + std::to_string(gate->get_id()));
152 for (
Endpoint* in_endpoint : fan_in)
154 Net* in_net = in_endpoint->get_net();
159 if (merge_res.is_error())
161 log_warning(
"netlist_preprocessing",
"{}", merge_res.get_error().get());
171 "failed to remove destination from input net '{}' with ID {} of buffer gate '{}' with ID {} from netlist with ID {}.",
189 gates_to_be_deleted.push(gate);
310 log_debug(
"netlist_preprocessing",
"removing {} buffer gates...", gates_to_be_deleted.size());
312 while (!gates_to_be_deleted.empty())
314 Gate* gate = gates_to_be_deleted.front();
315 gates_to_be_deleted.pop();
318 log_warning(
"netlist_preprocessing",
"failed to remove buffer gate '{}' with ID {} from netlist with ID {}.", gate->
get_name(), gate->
get_id(), nl->
get_id());
324 log_info(
"netlist_preprocessing",
"removed {} buffer gates from netlist with ID {}.", num_gates, nl->
get_id());
325 return OK(num_gates);
330 std::unordered_map<Gate*, std::vector<std::string>> restore_ff_replacements(
const Netlist* nl)
332 std::unordered_map<Gate*, std::vector<std::string>> replacements;
336 if (g->has_data(
"preprocessing_information",
"replaced_gates"))
338 const auto& [_, s] = g->get_data(
"preprocessing_information",
"replaced_gates");
340 replacements.insert({g, replaced_gate_names});
347 void update_ff_replacements(std::unordered_map<Gate*, std::vector<std::string>>& replacements)
349 for (
auto& [g, r] : replacements)
351 const nlohmann::json j = r;
352 const std::string s = j.dump();
354 g->set_data(
"preprocessing_information",
"replaced_gates",
"string", s);
360 void annotate_ff_survivor(std::unordered_map<Gate*, std::vector<std::string>>& replacements, Gate* survivor, Gate* to_be_replaced)
362 auto& it_s = replacements[survivor];
364 if (
const auto& it = replacements.find(to_be_replaced); it != replacements.end())
366 for (
const auto& s : it->second)
370 replacements.erase(it);
373 it_s.push_back(to_be_replaced->get_name());
383 #ifdef BITWUZLA_LIBRARY
386 config = config.with_solver(s_type).with_call(s_call);
388 struct GateFingerprint
391 std::map<GatePin*, Net*> ordered_fan_in = {};
392 std::set<Net*> unordered_fan_in = {};
393 u8 truth_table_hw = 0;
395 bool operator<(
const GateFingerprint& other)
const
397 return (other.type <
type) || (other.type ==
type && other.ordered_fan_in < ordered_fan_in)
398 || (other.type ==
type && other.ordered_fan_in == ordered_fan_in && other.unordered_fan_in < unordered_fan_in)
399 || (other.type ==
type && other.ordered_fan_in == ordered_fan_in && other.unordered_fan_in == unordered_fan_in && other.truth_table_hw < truth_table_hw);
403 static std::vector<u8> hw_map = {0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4};
408 std::vector<Gate*> target_gates;
424 auto ff_replacements = restore_ff_replacements(nl);
428 std::map<GateFingerprint, std::vector<Gate*>> fingerprinted_gates;
432 for (
auto* gate : target_gates)
434 GateFingerprint fingerprint;
435 fingerprint.type = gate->get_type();
438 const auto& fan_in_nets = gate->get_fan_in_nets();
439 fingerprint.unordered_fan_in.insert(fan_in_nets.cbegin(), fan_in_nets.cend());
442 if (
const auto res = gate->get_init_data(); res.is_ok())
444 const auto& init_str = res.get().front();
445 for (
const auto c : init_str)
447 u8 tmp = std::toupper(c) - 0x30;
452 fingerprint.truth_table_hw += hw_map.at(tmp);
459 for (
const auto& ep : gate->get_fan_in_endpoints())
461 fingerprint.ordered_fan_in[ep->get_pin()] = ep->get_net();
465 fingerprinted_gates[fingerprint].push_back(gate);
468 std::vector<std::vector<Gate*>> duplicate_gates;
469 for (
const auto& [fingerprint, gates] : fingerprinted_gates)
471 if (gates.size() == 1)
478 std::set<const Gate*> visited;
479 for (
size_t i = 0; i < gates.size(); i++)
481 Gate* master_gate = gates.at(i);
483 if (visited.find(master_gate) != visited.cend())
488 std::vector<Gate*> current_duplicates = {master_gate};
490 for (
size_t j = i + 1; j < gates.size(); j++)
492 Gate* current_gate = gates.at(j);
494 for (
const auto* pin : fingerprint.type->get_output_pins())
496 const auto solver_res =
506 if (solver_res.is_error() || !solver_res.get().is_unsat())
514 current_duplicates.push_back(current_gate);
515 visited.insert(current_gate);
519 if (current_duplicates.size() > 1)
521 duplicate_gates.push_back(current_duplicates);
527 duplicate_gates.push_back(std::move(gates));
531 std::set<Gate*> affected_gates;
532 for (
auto& current_duplicates : duplicate_gates)
534 std::sort(current_duplicates.begin(), current_duplicates.end(), [](
const auto& g1,
const auto& g2) { return g1->get_name().length() < g2->get_name().length(); });
536 auto* survivor_gate = current_duplicates.front();
537 std::map<GatePin*, Net*> out_pins_to_nets;
538 for (
auto* ep : survivor_gate->get_fan_out_endpoints())
540 Net* out_net = ep->get_net();
541 out_pins_to_nets[ep->get_pin()] = out_net;
544 auto* dst_gate = dst->get_gate();
545 auto* dst_type = dst_gate->get_type();
548 affected_gates.insert(dst_gate);
553 for (
u32 k = 1; k < current_duplicates.size(); k++)
555 auto* current_gate = current_duplicates.at(k);
556 for (
auto* ep : current_gate->get_fan_out_endpoints())
558 auto* ep_net = ep->get_net();
559 auto* ep_pin = ep->get_pin();
561 if (
auto it = out_pins_to_nets.find(ep_pin); it != out_pins_to_nets.cend())
564 for (
auto* dst : ep_net->get_destinations())
566 auto* dst_gate = dst->get_gate();
567 auto* dst_pin = dst->get_pin();
569 it->second->add_destination(dst_gate, dst_pin);
571 auto* dst_type = dst_gate->get_type();
574 affected_gates.insert(dst_gate);
579 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());
585 ep_net->add_source(survivor_gate, ep_pin);
586 out_pins_to_nets[ep_pin] = ep_net;
587 for (
auto* dst : ep_net->get_destinations())
589 auto* dst_gate = dst->get_gate();
590 auto* dst_type = dst_gate->get_type();
593 affected_gates.insert(dst_gate);
599 annotate_ff_survivor(ff_replacements, survivor_gate, current_gate);
601 affected_gates.erase(current_gate);
604 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());
613 target_gates = std::vector<Gate*>(affected_gates.cbegin(), affected_gates.cend());
616 update_ff_replacements(ff_replacements);
618 log_info(
"netlist_preprocessing",
"removed {} redundant gates from netlist with ID {}.", num_gates, nl->
get_id());
619 return OK(num_gates);
624 struct LoopFingerprint
626 std::map<const GateType*, u32> types;
627 std::set<std::string> external_variable_names;
628 std::set<const Net*> ff_control_nets;
630 bool operator<(
const LoopFingerprint& other)
const
632 return (other.types < types) || (other.types == types && other.external_variable_names < external_variable_names)
633 || (other.types == types && other.external_variable_names == external_variable_names && other.ff_control_nets < ff_control_nets);
639 #ifdef BITWUZLA_LIBRARY
642 config = config.with_solver(s_type).with_call(s_call);
647 auto ff_replacements = restore_ff_replacements(nl);
653 std::unordered_map<Gate*, std::unordered_set<Gate*>> loops_by_start_gate;
654 for (
auto* start_ff : nl->
get_gates([](
const Gate* g) { return g->get_type()->has_property(GateTypeProperty::ff); }))
656 std::vector<Gate*> stack = {start_ff};
657 std::vector<Gate*> previous_gates;
658 std::unordered_set<Gate*> visited_gates;
659 std::unordered_set<Gate*> cache;
661 while (!stack.empty())
663 auto* current_gate = stack.back();
665 if (!previous_gates.empty() && current_gate == previous_gates.back())
668 previous_gates.pop_back();
672 visited_gates.insert(current_gate);
675 for (
const auto* suc_ep : current_gate->get_successors())
677 if (ff_control_pin_types.find(suc_ep->get_pin()->get_type()) != ff_control_pin_types.end())
682 auto* suc_gate = suc_ep->get_gate();
683 if (suc_gate == start_ff || cache.find(suc_gate) != cache.end())
685 loops_by_start_gate[start_ff].insert(current_gate);
686 cache.insert(current_gate);
687 for (
auto it = ++(previous_gates.begin()); it != previous_gates.end(); it++)
690 loops_by_start_gate[start_ff].insert(*it);
695 if (visited_gates.find(suc_gate) == visited_gates.end())
697 stack.push_back(suc_gate);
705 previous_gates.push_back(current_gate);
714 std::map<LoopFingerprint, std::vector<std::pair<std::vector<Gate*>,
BooleanFunction>>> fingerprinted_loops;
715 for (
const auto& [start_ff, comb_gates] : loops_by_start_gate)
717 LoopFingerprint fingerprint;
720 if (comb_gates.size() > 30)
726 std::vector<const Endpoint*> data_in;
727 for (
const auto* ep : start_ff->get_fan_in_endpoints())
729 auto pin_type = ep->get_pin()->get_type();
730 if (ff_control_pin_types.find(pin_type) != ff_control_pin_types.end())
732 fingerprint.ff_control_nets.insert(ep->get_net());
736 data_in.push_back(ep);
740 if (data_in.size() != 1)
746 fingerprint.types[start_ff->get_type()] = 1;
747 for (
const auto* g : comb_gates)
750 if (
const auto type_it = fingerprint.types.find(gt); type_it == fingerprint.types.end())
752 fingerprint.types[gt] = 0;
754 fingerprint.types[gt]++;
757 std::vector<const Gate*> comb_gates_vec(comb_gates.cbegin(), comb_gates.cend());
765 for (
const auto* ep : start_ff->get_fan_out_endpoints())
768 it != fingerprint.external_variable_names.end())
770 function =
function.substitute(*it, ep->get_pin()->get_name());
771 fingerprint.external_variable_names.erase(it);
775 std::vector<Gate*> loop_gates = {start_ff};
776 loop_gates.insert(loop_gates.end(), comb_gates.begin(), comb_gates.end());
777 fingerprinted_loops[fingerprint].push_back(std::make_pair(loop_gates, std::move(
function)));
781 std::vector<std::vector<std::vector<Gate*>>> duplicate_loops;
782 for (
const auto& [_, loops] : fingerprinted_loops)
784 if (loops.size() == 1)
789 std::set<u32> visited;
790 for (
u32 i = 0; i < loops.size(); i++)
792 if (visited.find(i) != visited.cend())
797 const auto& master_loop = loops.at(i);
799 std::vector<std::vector<Gate*>> current_duplicates = {std::get<0>(master_loop)};
801 for (
size_t j = i + 1; j < loops.size(); j++)
803 const auto& current_loop = loops.at(j);
804 const auto solver_res =
805 BooleanFunction::Eq(std::get<1>(master_loop).clone(), std::get<1>(current_loop).clone(), 1)
809 if (solver_res.is_ok() && solver_res.get().is_unsat())
811 current_duplicates.push_back(std::get<0>(current_loop));
816 if (current_duplicates.size() > 1)
818 duplicate_loops.push_back(std::move(current_duplicates));
823 for (
const auto& current_duplicates : duplicate_loops)
826 const auto& survivor_loop = current_duplicates.front();
827 auto* survivor_ff = survivor_loop.front();
829 std::map<GatePin*, Net*> out_pins_to_nets;
830 for (
auto* ep : survivor_ff->get_fan_out_endpoints())
832 Net* out_net = ep->get_net();
833 out_pins_to_nets[ep->get_pin()] = out_net;
836 for (
u32 i = 1; i < current_duplicates.size(); i++)
838 auto* current_ff = current_duplicates.at(i).front();
839 for (
auto* ep : current_ff->get_fan_out_endpoints())
841 auto* ep_net = ep->get_net();
842 auto* ep_pin = ep->get_pin();
844 if (
auto it = out_pins_to_nets.find(ep_pin); it != out_pins_to_nets.cend())
847 for (
auto* dst : ep_net->get_destinations())
849 auto* dst_gate = dst->get_gate();
850 auto* dst_pin = dst->get_pin();
852 it->second->add_destination(dst_gate, dst_pin);
856 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());
862 ep_net->add_source(survivor_ff, ep_pin);
863 out_pins_to_nets[ep_pin] = ep_net;
867 annotate_ff_survivor(ff_replacements, survivor_ff, current_ff);
871 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());
880 update_ff_replacements(ff_replacements);
882 log_info(
"netlist_preprocessing",
"removed {} redundant loops from netlist with ID {}.", num_gates, nl->
get_id());
883 return OK(num_gates);
888 struct TreeFingerprint
890 std::set<const Net*> external_inputs;
893 bool operator<(
const TreeFingerprint& other)
const
895 return (other.external_inputs < external_inputs);
902 std::map<TreeFingerprint, std::set<Net*>> fingerprint_to_nets;
903 for (
const auto& g : all_comb_gates_vec)
905 for (
const auto& out_ep : g->get_fan_out_endpoints())
910 const auto& out_net = out_ep->get_net();
912 if (inputs_res.is_error())
915 "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()));
918 tf.external_inputs = inputs_res.get();
921 fingerprint_to_nets[tf].insert(out_net);
926 std::vector<std::vector<Net*>> equality_classes;
928 for (
const auto& [_fingerprint, nets] : fingerprint_to_nets)
942 std::vector<Net*> current_candidate_nets = {nets.begin(), nets.end()};
943 std::vector<Net*> next_candidate_nets;
945 while (!current_candidate_nets.empty())
947 const auto n = current_candidate_nets.back();
948 current_candidate_nets.pop_back();
950 std::vector<Net*> new_equality_class = {n};
952 for (
const auto& m : current_candidate_nets)
955 if (comp_res.is_error())
958 "Unable to remove redundant logic trees: failed to compare net " + n->get_name() +
" with ID " + std::to_string(n->get_id()) +
" with net "
959 + m->get_name() +
" with ID " + std::to_string(m->get_id()));
961 const auto are_equal = comp_res.get();
965 new_equality_class.push_back(m);
969 next_candidate_nets.push_back(m);
973 equality_classes.push_back(new_equality_class);
974 current_candidate_nets = next_candidate_nets;
975 next_candidate_nets.clear();
980 for (
const auto& eq_class : equality_classes)
989 auto survivor_net = eq_class.front();
991 for (
u32 i = 1; i < eq_class.size(); i++)
993 auto victim_net = eq_class.at(i);
994 for (
const auto& dst : victim_net->get_destinations())
996 auto dst_gate = dst->get_gate();
997 auto dst_pin = dst->get_pin();
999 if (!victim_net->remove_destination(dst))
1001 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())
1002 +
" at gate " + dst_gate->get_name() +
" with ID " + std::to_string(dst_gate->get_id()) +
" and pin " + dst_pin->get_name());
1004 if (!survivor_net->add_destination(dst_gate, dst_pin))
1006 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())
1007 +
" at gate " + dst_gate->get_name() +
" with ID " + std::to_string(dst_gate->get_id()) +
" and pin " + dst_pin->get_name());
1016 if (clean_up_res.is_error())
1018 return ERR_APPEND(clean_up_res.get_error(),
"Unable to remove redundant logic trees: failed to clean up dangling trees");
1021 return OK(clean_up_res.get() + counter);
1027 std::vector<Gate*> to_delete;
1034 bool is_unconnected =
true;
1035 for (
const auto& on : g->get_fan_out_nets())
1037 if (!on->get_destinations().empty() || on->is_global_output_net())
1039 is_unconnected =
false;
1045 to_delete.push_back(g);
1049 for (
const auto& g : to_delete)
1053 log_warning(
"netlist_preprocessing",
"could not delete gate '{}' with ID {} from netlist with ID {}.", g->get_name(), g->get_id(), nl->
get_id());
1060 }
while (!to_delete.empty());
1062 log_info(
"netlist_preprocessing",
"removed {} unconnected gates from netlist with ID {}.", num_gates, nl->
get_id());
1063 return OK(num_gates);
1070 std::vector<Net*> to_delete;
1072 for (
const auto& n : nl->
get_nets())
1074 if (!n->is_global_input_net() && n->get_sources().empty() && !n->is_global_output_net() && n->get_destinations().empty())
1076 to_delete.push_back(n);
1080 for (
const auto& n : to_delete)
1084 log_warning(
"netlist_preprocessing",
"could not delete net '{}' with ID {} from netlist with ID {}.", n->get_name(), n->get_id(), nl->
get_id());
1092 log_info(
"netlist_preprocessing",
"removed {} unconnected nets from netlist with ID {}.", num_nets, nl->
get_id());
1093 return OK(num_nets);
1098 u32 total_removed = 0;
1103 if (gate_res.is_error())
1105 return ERR_APPEND(gate_res.get_error(),
"unable to execute clean up loop: failed to remove unconnected gates");
1109 if (net_res.is_error())
1111 return ERR_APPEND(net_res.get_error(),
"unable to execute clean up loop: failed to remove unconnected nets");
1114 const u32 removed = gate_res.get() + net_res.get();
1115 total_removed += removed;
1122 return OK(total_removed);
1134 u32 delete_count = 0;
1135 std::vector<Gate*> delete_gate_q;
1137 for (
const auto& g : muxes)
1147 if (data_pins.size() < 2)
1152 if (out_pins.size() != 1)
1157 bool preceded_by_inv =
true;
1158 for (
const auto& pin : data_pins)
1163 preceded_by_inv =
false;
1168 if (!preceded_by_inv)
1173 bool succeded_by_inv =
true;
1174 for (
const auto& pin : out_pins)
1179 succeded_by_inv =
false;
1184 if (!succeded_by_inv)
1190 for (
const auto& pin : data_pins)
1198 auto in_net = pred->get_gate()->get_fan_in_nets().front();
1199 in_net->add_destination(g, pin);
1202 if (pred->get_gate()->get_successors().empty())
1204 delete_gate_q.push_back(pred->get_gate());
1208 for (
const auto& pin : out_pins)
1216 auto in_net = suc->get_gate()->get_fan_out_nets().front();
1217 in_net->add_source(g, pin);
1220 if (suc->get_gate()->get_predecessors().empty())
1222 delete_gate_q.push_back(suc->get_gate());
1227 for (
auto g : delete_gate_q)
1233 log_info(
"netlist_preprocessing",
"removed {} encasing inverters", delete_count);
1235 return OK(delete_count);
1238 struct MuxFingerprint
1243 bool operator<(
const MuxFingerprint& other)
const
1245 return (other.type <
type) || (other.type ==
type && other.inverters <
inverters);
1249 Result<u32> unify_inverted_select_signals(Netlist* nl, GateLibrary* mux_inv_gl)
1253 return ERR(
"netlist is a nullptr");
1256 if (mux_inv_gl ==
nullptr)
1258 return ERR(
"gate library is a nullptr");
1262 if (base_path_res.is_error())
1264 return ERR_APPEND(base_path_res.get_error(),
"unable to resynthesize boolean functions with yosys: failed to get unique temp directory");
1266 const std::filesystem::path base_path = base_path_res.get();
1267 const std::filesystem::path genlib_path = base_path /
"mux_inv.genlib";
1268 std::filesystem::create_directory(base_path);
1273 return ERR(
"unable to unify muxe select signals: failed to save gate library " + mux_inv_gl->get_name() +
" to location " + genlib_path.string());
1276 const i64 initial_size = nl->get_gates().size();
1281 std::vector<Gate*> muxes = nl->get_gates([](
const Gate* g) {
return (g->get_type()->get_name().find(
"HAL_MUX") != std::string::npos); });
1283 std::map<MuxFingerprint, std::unique_ptr<Netlist>> resynth_cache;
1285 for (
const auto& g : muxes)
1289 mf.type = g->get_type();
1292 std::map<GatePin*, Net*> pin_to_input;
1294 auto select_pins = g->get_type()->get_pins([](
const GatePin* pin) {
return (pin->get_type() ==
PinType::select) && (pin->get_direction() ==
PinDirection::input); });
1296 std::vector<Gate*> preceding_inverters;
1297 for (
const auto& pin : g->get_type()->get_input_pins())
1299 const auto pred = g->get_predecessor(pin);
1300 const auto is_select = (std::find(select_pins.begin(), select_pins.end(), pin) != select_pins.end());
1301 if (!is_select || pred ==
nullptr || pred->get_gate() ==
nullptr || !pred->get_gate()->get_type()->has_property(
GateTypeProperty::c_inverter)
1302 || (pred->get_gate()->get_fan_in_endpoints().size() != 1))
1304 pin_to_input.insert({pin, g->get_fan_in_net(pin)});
1308 auto inv_gate = pred->get_gate();
1309 preceding_inverters.push_back(inv_gate);
1310 pin_to_input.insert({pin, inv_gate->get_fan_in_endpoints().front()->get_net()});
1311 mf.inverters.insert(pin);
1316 if (!preceding_inverters.empty())
1318 const Netlist* resynth_nl;
1320 auto subgraph = preceding_inverters;
1321 subgraph.push_back(g);
1324 if (
const auto it = resynth_cache.find(mf); it == resynth_cache.end())
1326 std::unordered_map<std::string, BooleanFunction> bfs;
1327 for (
const auto& ep : g->get_fan_out_endpoints())
1329 const auto bf_res = SubgraphNetlistDecorator(*nl).get_subgraph_function(subgraph, ep->get_net());
1330 if (bf_res.is_error())
1333 "unable to unify muxes select signals: failed to build boolean function for mux " + g->get_name() +
" with ID " + std::to_string(g->get_id())
1334 +
" at output " + ep->get_pin()->get_name());
1336 auto bf = bf_res.get();
1339 for (
const auto& [pin,
net] : pin_to_input)
1341 auto sub_res = bf.substitute(BooleanFunctionNetDecorator(*net).get_boolean_variable_name(),
BooleanFunction::Var(pin->get_name(), 1));
1342 if (sub_res.is_error())
1344 return ERR_APPEND(sub_res.get_error(),
"unable to unify muxes select signals: failed to substitute net_id variable with generic variable");
1349 bfs.insert({ep->get_pin()->get_name(), std::move(bf)});
1353 if (resynth_res.is_error())
1355 return ERR_APPEND(resynth_res.get_error(),
"unable to unify select signals of muxes: failed to resynthesize mux subgraph to netlist");
1357 auto unique_resynth_nl = resynth_res.get();
1358 resynth_nl = unique_resynth_nl.get();
1359 resynth_cache.insert({mf, std::move(unique_resynth_nl)});
1363 resynth_nl = it->second.get();
1366 std::unordered_map<Net*, std::vector<Net*>> global_io_mapping;
1369 for (
const auto& pin : resynth_nl->get_top_module()->get_input_pins())
1371 auto net_it = pin_to_input.find(g->get_type()->get_pin_by_name(pin->get_name()));
1372 if (net_it == pin_to_input.end())
1374 return ERR(
"unable to unify muxes select signals:: failed to locate net in destination netlist from global input " + pin->get_name() +
" in resynthesized netlist");
1376 global_io_mapping[pin->get_net()].push_back(net_it->second);
1378 for (
const auto& pin : resynth_nl->get_top_module()->get_output_pins())
1380 auto net = g->get_fan_out_net(pin->get_name());
1383 return ERR(
"unable to unify muxes select signals:: failed to locate net in destination netlist from global output " + pin->get_name() +
" in resynthesized netlist");
1385 global_io_mapping[pin->get_net()].push_back(
net);
1389 if (replace_res.is_error())
1391 return ERR(
"unable to unify muxes select signals: failed to replace mux subgraph with resynthesized netlist");
1395 std::vector<Gate*> to_delete;
1396 for (
const auto g : subgraph)
1398 bool has_no_outside_destinations =
true;
1399 bool has_only_outside_destinations =
true;
1400 for (
const auto& suc : g->get_successors())
1402 const auto it = std::find(subgraph.begin(), subgraph.end(), suc->get_gate());
1403 if (it == subgraph.end())
1405 has_no_outside_destinations =
false;
1408 if (it != subgraph.end())
1410 has_only_outside_destinations =
false;
1414 if (has_no_outside_destinations || has_only_outside_destinations)
1416 to_delete.push_back(g);
1420 for (
const auto& g : to_delete)
1422 if (!nl->delete_gate(g))
1424 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");
1431 std::filesystem::remove_all(base_path);
1433 const i64 new_size = nl->get_gates().size();
1434 const i64 difference = std::abs(initial_size - new_size);
1436 return OK(
u32(difference));
1439 Result<u32> unify_select_signals(Netlist* nl)
1443 return ERR(
"netlist is a nullptr");
1446 u32 changed_connections = 0;
1449 std::map<std::pair<GateType*, std::set<Net*>>, std::vector<Gate*>> grouped_muxes;
1450 for (
const auto& g : nl->get_gates([](
const Gate* g) { return g->get_type()->has_property(GateTypeProperty::c_mux); }))
1452 std::set<Net*> select_signals;
1453 const auto select_pins = g->get_type()->get_pins([](
const GatePin* pin) {
return (pin->get_type() ==
PinType::select) && (pin->get_direction() ==
PinDirection::input); });
1454 for (
const auto& sp : select_pins)
1456 select_signals.insert(g->get_fan_in_net(sp));
1459 grouped_muxes[{g->get_type(), select_signals}].push_back(g);
1463 for (
const auto& [finger_print, mux_group] : grouped_muxes)
1465 const auto& [
type, select_signals_set] = finger_print;
1467 const auto output_pins =
type->get_pins([](
const GatePin* pin) {
return pin->get_direction() ==
PinDirection::output; });
1469 if (output_pins.size() != 1)
1472 "Cannot unify select signals for muxes of type {} since the type has {} output signals and we can only handle 1.",
1474 output_pins.size());
1479 std::map<std::map<GatePin*, Net*>, std::vector<Gate*>> select_map_to_muxes;
1480 for (
const auto& g : mux_group)
1482 std::map<GatePin*, Net*> select_map;
1483 for (
const auto& sp : select_pins)
1485 select_map.insert({sp, g->get_fan_in_net(sp)});
1488 select_map_to_muxes[select_map].push_back(g);
1491 if (select_map_to_muxes.size() == 1)
1496 const std::vector<Net*> select_signals = {select_signals_set.begin(), select_signals_set.end()};
1499 std::map<Gate*, std::map<GatePin*, Net*>> new_net_to_pin;
1502 for (
const auto& g : mux_group)
1504 for (
u32 select_index = 0; select_index < select_pins.size(); select_index++)
1506 auto select_pin = select_pins.at(select_index);
1507 auto select_signal = select_signals.at(select_index);
1508 new_net_to_pin[g][select_pin] = select_signal;
1513 auto type_bf =
type->get_boolean_function(output_pins.front());
1514 for (
u32 select_val = 0; select_val < (1 << select_signals.size()); select_val++)
1516 std::map<std::string, BooleanFunction> type_substitution;
1517 for (
u32 select_idx = 0; select_idx < select_pins.size(); select_idx++)
1519 auto select_pin = select_pins.at(select_idx);
1521 auto type_substitution_val = ((select_val >> select_idx) & 0x1) ?
BooleanFunction::Const(1, 1) : BooleanFunction::Const(0, 1);
1522 type_substitution.insert({select_pin->get_name(), type_substitution_val});
1525 auto type_substitution_res = type_bf.substitute(type_substitution);
1526 if (type_substitution_res.is_error())
1528 return ERR_APPEND(type_substitution_res.get_error(),
"cannot unify mux select signals: failed to substitute type Boolean function with select signal value mapping.");
1530 auto input = type_substitution_res.get().simplify_local();
1532 if (!
input.is_variable())
1534 return ERR(
"cannot unify mux select signals: substituted and simplified type Boolean function (" +
input.to_string() +
") is not a variable");
1537 const auto pin_name =
input.get_variable_name().get();
1538 auto pin =
type->get_pins([pin_name](
const auto& p) {
return p->get_name() == pin_name; }).front();
1540 for (
const auto& g : mux_group)
1542 auto gate_bf_res = g->get_resolved_boolean_function(output_pins.front(),
false);
1543 if (gate_bf_res.is_error())
1546 "cannot unify mux select signals: failed to build Boolean function for gate " + g->get_name() +
" with ID " + std::to_string(g->get_id()));
1548 auto gate_bf = gate_bf_res.get();
1550 std::map<std::string, BooleanFunction> gate_substitution;
1552 for (
u32 select_idx = 0; select_idx < select_pins.size(); select_idx++)
1554 auto gate_substitution_val = ((select_val >> select_idx) & 0x1) ?
BooleanFunction::Const(1, 1) : BooleanFunction::Const(0, 1);
1555 gate_substitution.insert({BooleanFunctionNetDecorator(*(select_signals.at(select_idx))).get_boolean_variable_name(), gate_substitution_val});
1558 auto gate_substitution_res = gate_bf.substitute(gate_substitution);
1559 if (gate_substitution_res.is_error())
1561 return ERR_APPEND(gate_substitution_res.get_error(),
"cannot unify mux select signals: failed to substitute gate Boolean function with select signal value mapping.");
1563 auto input_net_var = gate_substitution_res.get().simplify_local();
1566 if (net_res.is_error())
1568 return ERR_APPEND(net_res.get_error(),
"cannot unify mux select signals: failed to extract net from substituted and simplified gate Boolean function");
1571 auto net = net_res.get();
1572 new_net_to_pin[g][pin] =
net;
1577 for (
auto& [g, pin_net] : new_net_to_pin)
1579 for (
const auto& [pin,
net] : pin_net)
1581 auto connected_net = g->get_fan_in_net(pin);
1582 if (
net == connected_net)
1587 connected_net->remove_destination(g, pin);
1588 net->add_destination(g, pin);
1590 changed_connections += 1;
1595 return OK(changed_connections);
1605 return ERR(
"netlist is a nullptr");
1608 if (mux_inv_gl ==
nullptr)
1610 return ERR(
"gate library is a nullptr");
1613 auto remove_res = remove_encasing_inverters(nl);
1614 if (remove_res.is_error())
1616 return ERR_APPEND(remove_res.get_error(),
"unable to apply manual mux optimizations: failed to remove encasing inverters");
1618 res_count += remove_res.get();
1620 auto unify_inverted_res = unify_inverted_select_signals(nl, mux_inv_gl);
1621 if (unify_inverted_res.is_error())
1623 return ERR_APPEND(unify_inverted_res.get_error(),
"unable to apply manual mux optimizations: failed to unify inverted select signals");
1625 res_count += unify_inverted_res.get();
1627 auto unify_res = unify_select_signals(nl);
1628 if (unify_res.is_error())
1630 return ERR_APPEND(unify_res.get_error(),
"unable to apply manual mux optimizations: failed to unify select signals");
1632 res_count += unify_res.get();
1634 return OK(res_count);
1641 return ERR(
"netlist is a nullptr");
1647 u32 total_replaced_dst_count = 0;
1651 u32 replaced_dst_count = 0;
1652 std::vector<Gate*> to_delete;
1653 for (
const auto g : nl->
get_gates([](
const auto g) {
1654 return g->get_type()->has_property(GateTypeProperty::combinational) && !g->get_type()->has_property(GateTypeProperty::ground)
1655 && !g->get_type()->has_property(GateTypeProperty::power);
1658 bool has_global_output =
false;
1659 for (
const auto ep : g->get_fan_out_endpoints())
1661 if (ep->get_net()->is_global_output_net())
1663 has_global_output =
true;
1666 auto bf_res = g->get_resolved_boolean_function(ep->get_pin(),
false);
1667 if (bf_res.is_error())
1670 "unable to propagate constants: failed to generate boolean function at gate " + g->get_name() +
" with ID " + std::to_string(g->get_id()) +
" for pin "
1671 + ep->get_pin()->get_name());
1673 auto bf = bf_res.get();
1675 if (sub_res.is_error())
1678 "unable to propagate constants: failed to substitue power and ground nets in boolean function of gate " + g->get_name() +
" with ID "
1679 + std::to_string(g->get_id()) +
" for pin " + ep->get_pin()->get_name());
1682 bf = bf.simplify_local();
1685 if (bf.is_constant())
1688 if (bf.has_constant_value(0))
1690 new_source = gnd_net;
1692 else if (bf.has_constant_value(1))
1694 new_source = vcc_net;
1701 if (new_source ==
nullptr)
1704 return ERR(
"unable to propagate constants: netlist is missing gnd or vcc net!");
1707 std::vector<std::pair<Gate*, GatePin*>> to_replace;
1708 for (
auto dst : ep->get_net()->get_destinations())
1710 to_replace.push_back({dst->get_gate(), dst->get_pin()});
1713 for (
const auto& [dst_g, dst_p] : to_replace)
1715 ep->get_net()->remove_destination(dst_g, dst_p);
1718 replaced_dst_count++;
1725 if (!has_global_output && g->get_successors().empty())
1727 to_delete.push_back(g);
1731 for (
auto g : to_delete)
1736 if (replaced_dst_count == 0)
1741 log_debug(
"netlist_preprocessing",
"replaced {} destinations this with power/ground nets this iteration", replaced_dst_count);
1742 total_replaced_dst_count += replaced_dst_count;
1745 log_info(
"netlist_preprocessing",
"replaced {} destinations with power/ground nets in total", total_replaced_dst_count);
1746 return OK(total_replaced_dst_count);
1753 return ERR(
"netlist is a nullptr");
1756 std::set<Gate*> gates_to_delete;
1757 for (
auto* inv_gate : nl->
get_gates([](
const Gate* g) { return g->get_type()->has_property(GateTypeProperty::c_inverter); }))
1759 if (gates_to_delete.find(inv_gate) != gates_to_delete.end())
1764 const auto& connection_endpoints = inv_gate->get_fan_in_endpoints();
1765 if (connection_endpoints.size() != 1)
1767 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());
1771 auto* middle_fan_in_ep = connection_endpoints.front();
1772 auto* middle_net = middle_fan_in_ep->get_net();
1773 if (middle_net->get_sources().size() != 1)
1775 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());
1778 auto* pred_gate = middle_net->get_sources().front()->get_gate();
1782 const auto& fan_in = pred_gate->get_fan_in_endpoints();
1783 if (fan_in.size() != 1)
1785 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());
1788 if (pred_gate->get_fan_out_endpoints().size() != 1)
1790 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());
1793 auto* in_net = fan_in.front()->get_net();
1795 const auto& fan_out = inv_gate->get_fan_out_endpoints();
1796 if (fan_out.size() != 1)
1798 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());
1801 auto* out_net = fan_out.front()->get_net();
1803 for (
auto* dst_ep : out_net->get_destinations())
1805 auto* dst_pin = dst_ep->get_pin();
1806 auto* dst_gate = dst_ep->get_gate();
1808 out_net->remove_destination(dst_ep);
1809 in_net->add_destination(dst_gate, dst_pin);
1812 middle_net->remove_destination(middle_fan_in_ep);
1814 if (middle_net->get_num_of_destinations() == 0)
1817 gates_to_delete.insert(pred_gate);
1820 gates_to_delete.insert(inv_gate);
1824 u32 removed_ctr = 0;
1825 for (
auto* g : gates_to_delete)
1831 return OK(removed_ctr);
1836 std::string generate_hex_truth_table_string(
const std::vector<BooleanFunction::Value>& tt)
1838 std::string tt_str =
"";
1841 for (
u32 i = 0; i < tt.size(); i++)
1844 if (bit == BooleanFunction::Value::ONE)
1846 acc += (1 << (i % 4));
1851 std::stringstream stream;
1852 stream << std::hex << acc;
1854 tt_str = stream.str() + tt_str;
1868 for (
auto g : nl->
get_gates([](
const auto& g) { return g->get_type()->has_property(GateTypeProperty::c_lut); }))
1870 auto res = g->get_init_data();
1874 "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");
1877 const auto original_inits = res.get();
1879 if (original_inits.size() != 1)
1881 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())
1882 +
" init data strings but expected exactly 1.");
1885 const auto original_init = original_inits.front();
1888 if (g->get_type()->get_output_pins().size() != 1)
1893 const auto out_ep = g->get_fan_out_endpoints().front();
1896 if (g->get_boolean_functions().size() != 1)
1901 const auto bf_org = g->get_boolean_function(out_ep->get_pin());
1902 const auto org_vars = bf_org.get_variable_names();
1905 if (bf_replaced_res.is_error())
1907 return ERR_APPEND(bf_replaced_res.get_error(),
1908 "cannot simplify LUT inits: failed to replace power and ground pins for gate " + g->get_name() +
" with ID " + std::to_string(g->get_id()));
1910 const auto bf_replaced = bf_replaced_res.get();
1911 const auto bf_simplified = bf_replaced.simplify_local();
1913 const auto new_vars = bf_simplified.get_variable_names();
1915 if (org_vars.size() == new_vars.size())
1920 auto bf_extended = bf_simplified.clone();
1921 for (
const auto& in_pin : g->get_type()->get_input_pin_names())
1923 if (new_vars.find(in_pin) == new_vars.end())
1930 const auto tt = bf_extended.compute_truth_table().get();
1931 const auto new_init_string = generate_hex_truth_table_string(tt.front());
1936 g->set_init_data({new_init_string}).get();
1937 g->set_data(
"preprocessing_information",
"original_init",
"string", original_init);
1950 log_info(
"netlist_preprocessing",
"simplified {} LUT INIT strings inside of netlist with ID {}.", num_inits, nl->
get_id());
1951 return OK(num_inits);
1956 struct indexed_identifier
1958 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}
1968 const std::string hal_instance_index_pattern =
"__\\[(\\d+)\\]__";
1969 const std::string hal_instance_index_pattern_reverse =
"<HAL>(\\d+)<HAL>";
1971 std::string replace_hal_instance_index(
const std::string&
name)
1973 std::regex re(hal_instance_index_pattern);
1978 while (std::regex_search(
input, match, re))
1987 std::string reconstruct_hal_instance_index(
const std::string&
name)
1989 std::regex re(hal_instance_index_pattern_reverse);
1994 while (std::regex_search(input, match, re))
2003 const std::string net_index_pattern =
"\\((\\d+)\\)";
2004 const std::string gate_index_pattern =
"\\[(\\d+)\\]";
2007 std::optional<indexed_identifier> extract_index(
const std::string&
name,
const std::string& index_pattern,
const std::string&
origin)
2009 std::regex re(index_pattern);
2012 std::optional<std::string> last_match;
2013 std::optional<u32> last_index;
2017 while (std::regex_search(input, match, re))
2020 last_index = std::stoi(match[1]);
2021 last_match = match.str();
2022 input = match.suffix().str();
2025 if (!last_index.has_value())
2027 return std::nullopt;
2030 const auto found_match = last_match.value();
2031 auto identifier_name =
name;
2032 identifier_name = identifier_name.replace(
name.rfind(found_match), found_match.size(),
"");
2034 return std::optional<indexed_identifier>{{identifier_name, last_index.value(),
origin}};
2038 bool annotate_indexed_identifiers(Gate* gate,
const std::vector<indexed_identifier>& identifiers)
2040 std::string json_identifier_str =
2041 "[" +
utils::join(
", ", identifiers, [](
const auto& i) {
return std::string(
"[") +
'"' + i.identifier +
'"' +
", " + std::to_string(i.index) +
", " +
'"' + i.origin +
'"' +
"]"; })
2044 return gate->set_data(
"preprocessing_information",
"multi_bit_indexed_identifiers",
"string", json_identifier_str);
2048 std::vector<indexed_identifier> check_net_at_pin(
const PinType pin_type, Gate* gate)
2050 const auto typed_pins = gate->get_type()->get_pins([pin_type](
const auto p) {
return p->get_type() == pin_type; });
2052 std::vector<indexed_identifier> found_identfiers;
2054 for (
const auto& pin : typed_pins)
2056 const auto typed_net = (pin->get_direction() ==
PinDirection::output) ? gate->get_fan_out_net(pin) : gate->get_fan_in_net(pin);
2065 const auto net_name_index = extract_index(typed_net->get_name(), net_index_pattern,
"net_name");
2066 if (net_name_index.has_value())
2068 found_identfiers.push_back(net_name_index.value());
2072 if (!typed_net->has_data(
"parser_annotation",
"merged_nets"))
2077 const auto all_merged_nets_str = std::get<1>(typed_net->get_data(
"parser_annotation",
"merged_nets"));
2079 if (all_merged_nets_str.empty())
2085 rapidjson::Document doc;
2086 doc.Parse(all_merged_nets_str.c_str());
2088 for (
u32 i = 0; i < doc.GetArray().Size(); i++)
2090 const auto list = doc[i].GetArray();
2091 for (
u32 j = 0; j < list.Size(); j++)
2093 const auto merged_wire_name = list[j].GetString();
2095 const auto merged_wire_name_index = extract_index(merged_wire_name, net_index_pattern,
"net_name");
2096 if (merged_wire_name_index.has_value())
2098 found_identfiers.push_back(merged_wire_name_index.value());
2104 return found_identfiers;
2111 for (
auto&
ff : nl->
get_gates([](
const auto g) { return g->get_type()->has_property(GateTypeProperty::ff); }))
2113 std::vector<indexed_identifier> all_identifiers;
2116 const auto cleaned_gate_name = replace_hal_instance_index(
ff->get_name());
2117 const auto gate_name_index = extract_index(cleaned_gate_name, gate_index_pattern,
"gate_name");
2119 if (gate_name_index.has_value())
2121 auto found_identifier = gate_name_index.value();
2122 found_identifier.identifier = reconstruct_hal_instance_index(found_identifier.identifier);
2123 all_identifiers.push_back(found_identifier);
2129 for (
const auto& pt : relevant_pin_types)
2131 const auto found_identifiers = check_net_at_pin(pt,
ff);
2132 all_identifiers.insert(all_identifiers.end(), found_identifiers.begin(), found_identifiers.end());
2135 if (!all_identifiers.empty())
2140 annotate_indexed_identifiers(
ff, all_identifiers);
2148 std::map<std::string, std::map<u32, std::vector<ModulePin*>>> pg_name_to_indexed_pins;
2152 auto reconstruct = extract_index(pin->get_name(), net_index_pattern,
"");
2153 if (!reconstruct.has_value())
2158 auto [pg_name,
index, _] = reconstruct.value();
2160 pg_name_to_indexed_pins[pg_name][
index].push_back(pin);
2163 u32 reconstructed_counter = 0;
2164 for (
const auto& [pg_name, indexed_pins] : pg_name_to_indexed_pins)
2166 std::vector<ModulePin*> ordered_pins;
2168 bool valid_indices =
true;
2170 for (
const auto& [_index,
pins] : indexed_pins)
2172 if (
pins.size() > 1)
2174 valid_indices =
false;
2178 ordered_pins.push_back(
pins.front());
2189 return ERR_APPEND(res.get_error(),
"cannot reconstruct top module pin groups: failed to create pin group " + pg_name);
2192 reconstructed_counter++;
2195 return OK(reconstructed_counter);
2200 struct ComponentData
2208 TokenStream<std::string> tokenize(std::stringstream& ss)
2210 const std::string delimiters =
" ;-";
2211 std::string current_token;
2212 u32 line_number = 0;
2215 bool escaped =
false;
2217 std::vector<Token<std::string>> parsed_tokens;
2218 while (std::getline(ss, line))
2230 else if (escaped && std::isspace(c))
2236 if (((!std::isspace(c) && delimiters.find(c) == std::string::npos) || escaped))
2242 if (!current_token.empty())
2244 parsed_tokens.emplace_back(line_number, current_token);
2245 current_token.clear();
2248 if (!std::isspace(c))
2250 parsed_tokens.emplace_back(line_number, std::string(1, c));
2255 if (!current_token.empty())
2257 parsed_tokens.emplace_back(line_number, current_token);
2258 current_token.clear();
2262 return TokenStream(parsed_tokens, {}, {});
2265 Result<std::unordered_map<std::string, ComponentData>> parse_tokens(TokenStream<std::string>& ts)
2267 ts.consume_until(
"COMPONENTS");
2268 ts.consume(
"COMPONENTS");
2269 const auto component_count_str = ts.consume().string;
2272 u32 component_count;
2275 component_count = res.get();
2279 return ERR_APPEND(res.get_error(),
"could not parse tokens: failed to read component count from token" + component_count_str);
2282 std::cout <<
"Component count: " << component_count << std::endl;
2284 std::unordered_map<std::string, ComponentData> component_data;
2285 for (
u32 c_idx = 0; c_idx < component_count; c_idx++)
2288 ComponentData new_data_entry;
2290 new_data_entry.name = ts.consume().string;
2291 new_data_entry.type = ts.consume().string;
2293 ts.consume(
"SOURCE");
2295 ts.consume(
"TIMING");
2297 ts.consume(
"PLACED");
2298 ts.consume(
"FIXED");
2303 new_data_entry.x = res.get();
2307 return ERR_APPEND(res.get_error(),
"could not parse tokens: failed to read x coordinate from token");
2312 new_data_entry.y = res.get();
2316 return ERR_APPEND(res.get_error(),
"could not parse tokens: failed to read y coordinate from token");
2321 ts.consume_current_line();
2323 component_data.insert({new_data_entry.name, new_data_entry});
2326 return OK(component_data);
2332 std::stringstream ss;
2334 ifs.open(def_file.string(), std::ifstream::in);
2337 return ERR(
"could not parse DEF (Design Exchange Format) file '" + def_file.string() +
"' : unable to open file");
2342 auto ts = tokenize(ss);
2344 std::unordered_map<std::string, ComponentData> component_data;
2348 if (
auto res = parse_tokens(ts); res.is_error())
2350 return ERR_APPEND(res.get_error(),
"could not parse Design Exchange Format file '" + def_file.string() +
"': unable to parse tokens");
2354 component_data = res.get();
2359 if (e.line_number != (
u32)-1)
2361 return ERR(
"could not parse Design Exchange Format file '" + def_file.string() +
"': " + e.message +
" (line " + std::to_string(e.line_number) +
")");
2365 return ERR(
"could not parse Design Exchange Format file '" + def_file.string() +
"': " + e.message);
2369 std::unordered_map<std::string, Gate*> name_to_gate;
2372 name_to_gate.insert({g->get_name(), g});
2376 for (
const auto& [gate_name,
data] : component_data)
2378 if (
const auto& g_it = name_to_gate.find(gate_name); g_it != name_to_gate.end())
2381 g_it->second->set_location_x(
data.x);
2382 g_it->second->set_location_y(
data.y);
2388 log_info(
"netlist_preprocessing",
"reconstructed coordinates for {} / {} ({:.2}) gates", counter, nl->
get_gates().size(), (
double)counter / (
double)nl->
get_gates().size());
2395 std::vector<Module*> all_modules;
2396 for (
const auto& [gt_name, pin_groups] : concatenated_pin_groups)
2401 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());
2404 for (
const auto& g : nl->
get_gates([>](
const auto& g) { return g->get_type() == gt; }))
2406 auto m = nl->
create_module(
"module_" + g->get_name(), g->get_module(), {g});
2408 for (
const auto& [module_pg_name, gate_pg_names] : pin_groups)
2410 std::vector<ModulePin*> module_pins;
2411 for (
const auto& gate_pg_name : gate_pg_names)
2413 const auto& gate_pg = g->
get_type()->get_pin_group_by_name(gate_pg_name);
2415 if (gate_pg ==
nullptr)
2417 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");
2420 std::vector<GatePin*> pin_list = gate_pg->get_pins();
2421 if (!gate_pg->is_ascending())
2423 std::reverse(pin_list.begin(), pin_list.end());
2426 for (
const auto& gate_pin : pin_list)
2428 const auto net = (gate_pin->get_direction() ==
PinDirection::output) ? g->get_fan_out_net(gate_pin) : g->get_fan_in_net(gate_pin);
2434 if (
net->is_gnd_net() ||
net->is_vcc_net())
2439 const auto module_pin = m->get_pin_by_net(
net);
2441 module_pins.push_back(module_pin);
2445 m->create_pin_group(module_pg_name, module_pins);
2446 u32 idx_counter = 0;
2447 for (
const auto& mp : module_pins)
2449 m->set_pin_name(mp, module_pg_name +
"_" + std::to_string(idx_counter));
2454 all_modules.push_back(m);
2458 return OK(all_modules);
2463 std::vector<Net*> created_nets;
2467 for (
const auto& p : g->get_type()->get_output_pins())
2469 if (g->get_fan_out_net(p) ==
nullptr)
2472 new_net->
set_name(
"HAL_UNCONNECTED_" + std::to_string(new_net->get_id()));
2473 new_net->add_source(g, p);
2475 created_nets.push_back(new_net);
2480 return OK(created_nets);
2487 return ERR(
"netlist is a nullptr");
2490 if (inverter_type ==
nullptr)
2493 const auto inv_types =
2495 if (inv_types.empty())
2497 return ERR(
"gate library '" + gl->get_name() +
"' of netlist does not contain an inverter gate");
2499 inverter_type = inv_types.begin()->second;
2505 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 '"
2517 +
"' has an invalid number of input pins or output pins");
2526 const std::vector<Gate*>& gates = ffs.empty() ? nl->
get_gates() : ffs;
2528 for (
auto*
ff : gates)
2530 auto* ff_type =
ff->get_type();
2538 GatePin* neg_state_pin =
nullptr;
2540 for (
auto* o_pin : ff_type->get_output_pins())
2548 neg_state_pin = o_pin;
2552 if (neg_state_pin ==
nullptr)
2557 auto* neg_state_ep =
ff->get_fan_out_endpoint(neg_state_pin);
2558 if (neg_state_ep ==
nullptr)
2562 auto* neg_state_net = neg_state_ep->get_net();
2564 auto state_net =
ff->get_fan_out_net(state_pin);
2565 if (state_net ==
nullptr)
2567 state_net = nl->
create_net(
ff->get_name() +
"__STATE_NET__");
2571 auto* inv = nl->
create_gate(inverter_type,
ff->get_name() +
"__NEG_STATE_INVERT__");
2572 state_net->add_destination(inv, inv_in_pin);
2573 neg_state_net->remove_source(neg_state_ep);
2574 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=true, 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< u32 > remove_unconnected_gates(Netlist *nl)
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 > simplify_lut_inits(Netlist *nl)
Result< std::vector< Net * > > create_nets_at_unconnected_pins(Netlist *nl)
Result< u32 > remove_redundant_loops(Netlist *nl)
Result< u32 > remove_redundant_logic_trees(Netlist *nl)
Result< u32 > reconstruct_top_module_pin_groups(Netlist *nl)
Result< u32 > remove_redundant_gates(Netlist *nl, const std::function< bool(const Gate *)> &filter=nullptr)
Result< u32 > remove_buffers(Netlist *nl)
Result< u32 > propagate_constants(Netlist *nl)
Result< u32 > remove_unused_lut_inputs(Netlist *nl)
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)
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...