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;
394 std::vector<std::string> init_data = {};
396 bool operator<(
const GateFingerprint& other)
const
398 return std::tie(
type, ordered_fan_in, unordered_fan_in, truth_table_hw, init_data)
399 < std::tie(other.type, other.ordered_fan_in, other.unordered_fan_in, other.truth_table_hw, other.init_data);
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();
468 if (
const auto res = gate->get_init_data(); res.is_ok())
470 fingerprint.init_data = res.get();
474 fingerprinted_gates[fingerprint].push_back(gate);
477 std::vector<std::vector<Gate*>> duplicate_gates;
478 for (
const auto& [fingerprint, gates] : fingerprinted_gates)
480 if (gates.size() == 1)
487 std::set<const Gate*> visited;
488 for (
size_t i = 0; i < gates.size(); i++)
490 Gate* master_gate = gates.at(i);
492 if (visited.find(master_gate) != visited.cend())
497 std::vector<Gate*> current_duplicates = {master_gate};
499 for (
size_t j = i + 1; j < gates.size(); j++)
501 Gate* current_gate = gates.at(j);
503 for (
const auto* pin : fingerprint.type->get_output_pins())
505 const auto solver_res =
515 if (solver_res.is_error() || !solver_res.get().is_unsat())
523 current_duplicates.push_back(current_gate);
524 visited.insert(current_gate);
528 if (current_duplicates.size() > 1)
530 duplicate_gates.push_back(current_duplicates);
536 duplicate_gates.push_back(std::move(gates));
540 std::set<Gate*> affected_gates;
541 for (
auto& current_duplicates : duplicate_gates)
543 std::sort(current_duplicates.begin(), current_duplicates.end(), [](
const auto& g1,
const auto& g2) { return g1->get_name().length() < g2->get_name().length(); });
545 auto* survivor_gate = current_duplicates.front();
546 std::map<GatePin*, Net*> out_pins_to_nets;
547 for (
auto* ep : survivor_gate->get_fan_out_endpoints())
549 Net* out_net = ep->get_net();
550 out_pins_to_nets[ep->get_pin()] = out_net;
553 auto* dst_gate = dst->get_gate();
554 auto* dst_type = dst_gate->get_type();
557 affected_gates.insert(dst_gate);
562 for (
u32 k = 1; k < current_duplicates.size(); k++)
564 auto* current_gate = current_duplicates.at(k);
565 for (
auto* ep : current_gate->get_fan_out_endpoints())
567 auto* ep_net = ep->get_net();
568 auto* ep_pin = ep->get_pin();
570 if (
auto it = out_pins_to_nets.find(ep_pin); it != out_pins_to_nets.cend())
573 for (
auto* dst : ep_net->get_destinations())
575 auto* dst_gate = dst->get_gate();
576 auto* dst_pin = dst->get_pin();
578 it->second->add_destination(dst_gate, dst_pin);
580 auto* dst_type = dst_gate->get_type();
583 affected_gates.insert(dst_gate);
588 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());
594 ep_net->add_source(survivor_gate, ep_pin);
595 out_pins_to_nets[ep_pin] = ep_net;
596 for (
auto* dst : ep_net->get_destinations())
598 auto* dst_gate = dst->get_gate();
599 auto* dst_type = dst_gate->get_type();
602 affected_gates.insert(dst_gate);
608 annotate_ff_survivor(ff_replacements, survivor_gate, current_gate);
610 affected_gates.erase(current_gate);
613 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());
622 target_gates = std::vector<Gate*>(affected_gates.cbegin(), affected_gates.cend());
625 update_ff_replacements(ff_replacements);
627 log_info(
"netlist_preprocessing",
"removed {} redundant gates from netlist with ID {}.", num_gates, nl->
get_id());
628 return OK(num_gates);
633 struct LoopFingerprint
635 std::map<const GateType*, u32> types;
636 std::set<std::string> external_variable_names;
637 std::set<const Net*> ff_control_nets;
639 bool operator<(
const LoopFingerprint& other)
const
641 return (other.types < types) || (other.types == types && other.external_variable_names < external_variable_names)
642 || (other.types == types && other.external_variable_names == external_variable_names && other.ff_control_nets < ff_control_nets);
648 #ifdef BITWUZLA_LIBRARY
651 config = config.with_solver(s_type).with_call(s_call);
656 auto ff_replacements = restore_ff_replacements(nl);
662 std::unordered_map<Gate*, std::unordered_set<Gate*>> loops_by_start_gate;
663 for (
auto* start_ff : nl->
get_gates([](
const Gate* g) { return g->get_type()->has_property(GateTypeProperty::ff); }))
665 std::vector<Gate*> stack = {start_ff};
666 std::vector<Gate*> previous_gates;
667 std::unordered_set<Gate*> visited_gates;
668 std::unordered_set<Gate*> cache;
670 while (!stack.empty())
672 auto* current_gate = stack.back();
674 if (!previous_gates.empty() && current_gate == previous_gates.back())
677 previous_gates.pop_back();
681 visited_gates.insert(current_gate);
684 for (
const auto* suc_ep : current_gate->get_successors())
686 if (ff_control_pin_types.find(suc_ep->get_pin()->get_type()) != ff_control_pin_types.end())
691 auto* suc_gate = suc_ep->get_gate();
692 if (suc_gate == start_ff || cache.find(suc_gate) != cache.end())
694 loops_by_start_gate[start_ff].insert(current_gate);
695 cache.insert(current_gate);
696 for (
auto it = ++(previous_gates.begin()); it != previous_gates.end(); it++)
699 loops_by_start_gate[start_ff].insert(*it);
704 if (visited_gates.find(suc_gate) == visited_gates.end())
706 stack.push_back(suc_gate);
714 previous_gates.push_back(current_gate);
723 std::map<LoopFingerprint, std::vector<std::pair<std::vector<Gate*>,
BooleanFunction>>> fingerprinted_loops;
724 for (
const auto& [start_ff, comb_gates] : loops_by_start_gate)
726 LoopFingerprint fingerprint;
729 if (comb_gates.size() > 30)
735 std::vector<const Endpoint*> data_in;
736 for (
const auto* ep : start_ff->get_fan_in_endpoints())
738 auto pin_type = ep->get_pin()->get_type();
739 if (ff_control_pin_types.find(pin_type) != ff_control_pin_types.end())
741 fingerprint.ff_control_nets.insert(ep->get_net());
745 data_in.push_back(ep);
749 if (data_in.size() != 1)
755 fingerprint.types[start_ff->get_type()] = 1;
756 for (
const auto* g : comb_gates)
759 if (
const auto type_it = fingerprint.types.find(gt); type_it == fingerprint.types.end())
761 fingerprint.types[gt] = 0;
763 fingerprint.types[gt]++;
766 std::vector<const Gate*> comb_gates_vec(comb_gates.cbegin(), comb_gates.cend());
774 for (
const auto* ep : start_ff->get_fan_out_endpoints())
777 it != fingerprint.external_variable_names.end())
779 function =
function.substitute(*it, ep->get_pin()->get_name());
780 fingerprint.external_variable_names.erase(it);
784 std::vector<Gate*> loop_gates = {start_ff};
785 loop_gates.insert(loop_gates.end(), comb_gates.begin(), comb_gates.end());
786 fingerprinted_loops[fingerprint].push_back(std::make_pair(loop_gates, std::move(
function)));
790 std::vector<std::vector<std::vector<Gate*>>> duplicate_loops;
791 for (
const auto& [_, loops] : fingerprinted_loops)
793 if (loops.size() == 1)
798 std::set<u32> visited;
799 for (
u32 i = 0; i < loops.size(); i++)
801 if (visited.find(i) != visited.cend())
806 const auto& master_loop = loops.at(i);
808 std::vector<std::vector<Gate*>> current_duplicates = {std::get<0>(master_loop)};
810 for (
size_t j = i + 1; j < loops.size(); j++)
812 const auto& current_loop = loops.at(j);
813 const auto solver_res =
814 BooleanFunction::Eq(std::get<1>(master_loop).clone(), std::get<1>(current_loop).clone(), 1)
818 if (solver_res.is_ok() && solver_res.get().is_unsat())
820 current_duplicates.push_back(std::get<0>(current_loop));
825 if (current_duplicates.size() > 1)
827 duplicate_loops.push_back(std::move(current_duplicates));
832 for (
const auto& current_duplicates : duplicate_loops)
835 const auto& survivor_loop = current_duplicates.front();
836 auto* survivor_ff = survivor_loop.front();
838 std::map<GatePin*, Net*> out_pins_to_nets;
839 for (
auto* ep : survivor_ff->get_fan_out_endpoints())
841 Net* out_net = ep->get_net();
842 out_pins_to_nets[ep->get_pin()] = out_net;
845 for (
u32 i = 1; i < current_duplicates.size(); i++)
847 auto* current_ff = current_duplicates.at(i).front();
848 for (
auto* ep : current_ff->get_fan_out_endpoints())
850 auto* ep_net = ep->get_net();
851 auto* ep_pin = ep->get_pin();
853 if (
auto it = out_pins_to_nets.find(ep_pin); it != out_pins_to_nets.cend())
856 for (
auto* dst : ep_net->get_destinations())
858 auto* dst_gate = dst->get_gate();
859 auto* dst_pin = dst->get_pin();
861 it->second->add_destination(dst_gate, dst_pin);
865 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());
871 ep_net->add_source(survivor_ff, ep_pin);
872 out_pins_to_nets[ep_pin] = ep_net;
876 annotate_ff_survivor(ff_replacements, survivor_ff, current_ff);
880 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());
889 update_ff_replacements(ff_replacements);
891 log_info(
"netlist_preprocessing",
"removed {} redundant loops from netlist with ID {}.", num_gates, nl->
get_id());
892 return OK(num_gates);
897 struct TreeFingerprint
899 std::set<const Net*> external_inputs;
902 bool operator<(
const TreeFingerprint& other)
const
904 return (other.external_inputs < external_inputs);
911 std::map<TreeFingerprint, std::set<Net*>> fingerprint_to_nets;
912 for (
const auto& g : all_comb_gates_vec)
914 for (
const auto& out_ep : g->get_fan_out_endpoints())
919 const auto& out_net = out_ep->get_net();
921 if (inputs_res.is_error())
924 "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()));
927 tf.external_inputs = inputs_res.get();
930 fingerprint_to_nets[tf].insert(out_net);
935 std::vector<std::vector<Net*>> equality_classes;
937 for (
const auto& [_fingerprint, nets] : fingerprint_to_nets)
951 std::vector<Net*> current_candidate_nets = {nets.begin(), nets.end()};
952 std::vector<Net*> next_candidate_nets;
954 while (!current_candidate_nets.empty())
956 const auto n = current_candidate_nets.back();
957 current_candidate_nets.pop_back();
959 std::vector<Net*> new_equality_class = {n};
961 for (
const auto& m : current_candidate_nets)
964 if (comp_res.is_error())
967 "Unable to remove redundant logic trees: failed to compare net " + n->get_name() +
" with ID " + std::to_string(n->get_id()) +
" with net "
968 + m->get_name() +
" with ID " + std::to_string(m->get_id()));
970 const auto are_equal = comp_res.get();
974 new_equality_class.push_back(m);
978 next_candidate_nets.push_back(m);
982 equality_classes.push_back(new_equality_class);
983 current_candidate_nets = next_candidate_nets;
984 next_candidate_nets.clear();
989 for (
const auto& eq_class : equality_classes)
998 auto survivor_net = eq_class.front();
1000 for (
u32 i = 1; i < eq_class.size(); i++)
1002 auto victim_net = eq_class.at(i);
1003 for (
const auto& dst : victim_net->get_destinations())
1005 auto dst_gate = dst->get_gate();
1006 auto dst_pin = dst->get_pin();
1008 if (!victim_net->remove_destination(dst))
1010 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())
1011 +
" at gate " + dst_gate->get_name() +
" with ID " + std::to_string(dst_gate->get_id()) +
" and pin " + dst_pin->get_name());
1013 if (!survivor_net->add_destination(dst_gate, dst_pin))
1015 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())
1016 +
" at gate " + dst_gate->get_name() +
" with ID " + std::to_string(dst_gate->get_id()) +
" and pin " + dst_pin->get_name());
1025 if (clean_up_res.is_error())
1027 return ERR_APPEND(clean_up_res.get_error(),
"Unable to remove redundant logic trees: failed to clean up dangling trees");
1030 return OK(clean_up_res.get() + counter);
1036 std::vector<Gate*> to_delete;
1043 bool is_unconnected =
true;
1044 for (
const auto& on : g->get_fan_out_nets())
1046 if (!on->get_destinations().empty() || on->is_global_output_net())
1048 is_unconnected =
false;
1054 to_delete.push_back(g);
1058 for (
const auto& g : to_delete)
1062 log_warning(
"netlist_preprocessing",
"could not delete gate '{}' with ID {} from netlist with ID {}.", g->get_name(), g->get_id(), nl->
get_id());
1069 }
while (!to_delete.empty());
1071 log_info(
"netlist_preprocessing",
"removed {} unconnected gates from netlist with ID {}.", num_gates, nl->
get_id());
1072 return OK(num_gates);
1079 std::vector<Net*> to_delete;
1081 for (
const auto& n : nl->
get_nets())
1083 if (!n->is_global_input_net() && n->get_sources().empty() && !n->is_global_output_net() && n->get_destinations().empty())
1085 to_delete.push_back(n);
1089 for (
const auto& n : to_delete)
1093 log_warning(
"netlist_preprocessing",
"could not delete net '{}' with ID {} from netlist with ID {}.", n->get_name(), n->get_id(), nl->
get_id());
1101 log_info(
"netlist_preprocessing",
"removed {} unconnected nets from netlist with ID {}.", num_nets, nl->
get_id());
1102 return OK(num_nets);
1107 u32 total_removed = 0;
1112 if (gate_res.is_error())
1114 return ERR_APPEND(gate_res.get_error(),
"unable to execute clean up loop: failed to remove unconnected gates");
1118 if (net_res.is_error())
1120 return ERR_APPEND(net_res.get_error(),
"unable to execute clean up loop: failed to remove unconnected nets");
1123 const u32 removed = gate_res.get() + net_res.get();
1124 total_removed += removed;
1131 return OK(total_removed);
1143 u32 delete_count = 0;
1144 std::vector<Gate*> delete_gate_q;
1146 for (
const auto& g : muxes)
1156 if (data_pins.size() < 2)
1161 if (out_pins.size() != 1)
1166 bool preceded_by_inv =
true;
1167 for (
const auto& pin : data_pins)
1172 preceded_by_inv =
false;
1177 if (!preceded_by_inv)
1182 bool succeded_by_inv =
true;
1183 for (
const auto& pin : out_pins)
1188 succeded_by_inv =
false;
1193 if (!succeded_by_inv)
1199 for (
const auto& pin : data_pins)
1207 auto in_net = pred->get_gate()->get_fan_in_nets().front();
1208 in_net->add_destination(g, pin);
1211 if (pred->get_gate()->get_successors().empty())
1213 delete_gate_q.push_back(pred->get_gate());
1217 for (
const auto& pin : out_pins)
1225 auto in_net = suc->get_gate()->get_fan_out_nets().front();
1226 in_net->add_source(g, pin);
1229 if (suc->get_gate()->get_predecessors().empty())
1231 delete_gate_q.push_back(suc->get_gate());
1236 for (
auto g : delete_gate_q)
1242 log_info(
"netlist_preprocessing",
"removed {} encasing inverters", delete_count);
1244 return OK(delete_count);
1247 struct MuxFingerprint
1252 bool operator<(
const MuxFingerprint& other)
const
1254 return (other.type <
type) || (other.type ==
type && other.inverters <
inverters);
1258 Result<u32> unify_inverted_select_signals(Netlist* nl, GateLibrary* mux_inv_gl)
1262 return ERR(
"netlist is a nullptr");
1265 if (mux_inv_gl ==
nullptr)
1267 return ERR(
"gate library is a nullptr");
1271 if (base_path_res.is_error())
1273 return ERR_APPEND(base_path_res.get_error(),
"unable to resynthesize boolean functions with yosys: failed to get unique temp directory");
1275 const std::filesystem::path base_path = base_path_res.get();
1276 const std::filesystem::path genlib_path = base_path /
"mux_inv.genlib";
1277 std::filesystem::create_directory(base_path);
1282 return ERR(
"unable to unify muxe select signals: failed to save gate library " + mux_inv_gl->get_name() +
" to location " + genlib_path.string());
1285 const i64 initial_size = nl->get_gates().size();
1290 std::vector<Gate*> muxes = nl->get_gates([](
const Gate* g) {
return (g->get_type()->get_name().find(
"HAL_MUX") != std::string::npos); });
1292 std::map<MuxFingerprint, std::unique_ptr<Netlist>> resynth_cache;
1294 for (
const auto& g : muxes)
1298 mf.type = g->get_type();
1301 std::map<GatePin*, Net*> pin_to_input;
1303 auto select_pins = g->get_type()->get_pins([](
const GatePin* pin) {
return (pin->get_type() ==
PinType::select) && (pin->get_direction() ==
PinDirection::input); });
1305 std::vector<Gate*> preceding_inverters;
1306 for (
const auto& pin : g->get_type()->get_input_pins())
1308 const auto pred = g->get_predecessor(pin);
1309 const auto is_select = (std::find(select_pins.begin(), select_pins.end(), pin) != select_pins.end());
1310 if (!is_select || pred ==
nullptr || pred->get_gate() ==
nullptr || !pred->get_gate()->get_type()->has_property(
GateTypeProperty::c_inverter)
1311 || (pred->get_gate()->get_fan_in_endpoints().size() != 1))
1313 pin_to_input.insert({pin, g->get_fan_in_net(pin)});
1317 auto inv_gate = pred->get_gate();
1318 preceding_inverters.push_back(inv_gate);
1319 pin_to_input.insert({pin, inv_gate->get_fan_in_endpoints().front()->get_net()});
1320 mf.inverters.insert(pin);
1325 if (!preceding_inverters.empty())
1327 const Netlist* resynth_nl;
1329 auto subgraph = preceding_inverters;
1330 subgraph.push_back(g);
1333 if (
const auto it = resynth_cache.find(mf); it == resynth_cache.end())
1335 std::unordered_map<std::string, BooleanFunction> bfs;
1336 for (
const auto& ep : g->get_fan_out_endpoints())
1338 const auto bf_res = SubgraphNetlistDecorator(*nl).get_subgraph_function(subgraph, ep->get_net());
1339 if (bf_res.is_error())
1342 "unable to unify muxes select signals: failed to build boolean function for mux " + g->get_name() +
" with ID " + std::to_string(g->get_id())
1343 +
" at output " + ep->get_pin()->get_name());
1345 auto bf = bf_res.get();
1348 for (
const auto& [pin,
net] : pin_to_input)
1350 auto sub_res = bf.substitute(BooleanFunctionNetDecorator(*net).get_boolean_variable_name(),
BooleanFunction::Var(pin->get_name(), 1));
1351 if (sub_res.is_error())
1353 return ERR_APPEND(sub_res.get_error(),
"unable to unify muxes select signals: failed to substitute net_id variable with generic variable");
1358 bfs.insert({ep->get_pin()->get_name(), std::move(bf)});
1362 if (resynth_res.is_error())
1364 return ERR_APPEND(resynth_res.get_error(),
"unable to unify select signals of muxes: failed to resynthesize mux subgraph to netlist");
1366 auto unique_resynth_nl = resynth_res.get();
1367 resynth_nl = unique_resynth_nl.get();
1368 resynth_cache.insert({mf, std::move(unique_resynth_nl)});
1372 resynth_nl = it->second.get();
1375 std::unordered_map<Net*, std::vector<Net*>> global_io_mapping;
1378 for (
const auto& pin : resynth_nl->get_top_module()->get_input_pins())
1380 auto net_it = pin_to_input.find(g->get_type()->get_pin_by_name(pin->get_name()));
1381 if (net_it == pin_to_input.end())
1383 return ERR(
"unable to unify muxes select signals:: failed to locate net in destination netlist from global input " + pin->get_name() +
" in resynthesized netlist");
1385 global_io_mapping[pin->get_net()].push_back(net_it->second);
1387 for (
const auto& pin : resynth_nl->get_top_module()->get_output_pins())
1389 auto net = g->get_fan_out_net(pin->get_name());
1392 return ERR(
"unable to unify muxes select signals:: failed to locate net in destination netlist from global output " + pin->get_name() +
" in resynthesized netlist");
1394 global_io_mapping[pin->get_net()].push_back(
net);
1398 if (replace_res.is_error())
1400 return ERR(
"unable to unify muxes select signals: failed to replace mux subgraph with resynthesized netlist");
1404 std::vector<Gate*> to_delete;
1405 for (
const auto g : subgraph)
1407 bool has_no_outside_destinations =
true;
1408 bool has_only_outside_destinations =
true;
1409 for (
const auto& suc : g->get_successors())
1411 const auto it = std::find(subgraph.begin(), subgraph.end(), suc->get_gate());
1412 if (it == subgraph.end())
1414 has_no_outside_destinations =
false;
1417 if (it != subgraph.end())
1419 has_only_outside_destinations =
false;
1423 if (has_no_outside_destinations || has_only_outside_destinations)
1425 to_delete.push_back(g);
1429 for (
const auto& g : to_delete)
1431 if (!nl->delete_gate(g))
1433 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");
1440 std::filesystem::remove_all(base_path);
1442 const i64 new_size = nl->get_gates().size();
1443 const i64 difference = std::abs(initial_size - new_size);
1445 return OK(
u32(difference));
1448 Result<u32> unify_select_signals(Netlist* nl)
1452 return ERR(
"netlist is a nullptr");
1455 u32 changed_connections = 0;
1458 std::map<std::pair<GateType*, std::set<Net*>>, std::vector<Gate*>> grouped_muxes;
1459 for (
const auto& g : nl->get_gates([](
const Gate* g) { return g->get_type()->has_property(GateTypeProperty::c_mux); }))
1461 std::set<Net*> select_signals;
1462 const auto select_pins = g->get_type()->get_pins([](
const GatePin* pin) {
return (pin->get_type() ==
PinType::select) && (pin->get_direction() ==
PinDirection::input); });
1463 for (
const auto& sp : select_pins)
1465 select_signals.insert(g->get_fan_in_net(sp));
1468 grouped_muxes[{g->get_type(), select_signals}].push_back(g);
1472 for (
const auto& [finger_print, mux_group] : grouped_muxes)
1474 const auto& [
type, select_signals_set] = finger_print;
1476 const auto output_pins =
type->get_pins([](
const GatePin* pin) {
return pin->get_direction() ==
PinDirection::output; });
1478 if (output_pins.size() != 1)
1481 "Cannot unify select signals for muxes of type {} since the type has {} output signals and we can only handle 1.",
1483 output_pins.size());
1488 std::map<std::map<GatePin*, Net*>, std::vector<Gate*>> select_map_to_muxes;
1489 for (
const auto& g : mux_group)
1491 std::map<GatePin*, Net*> select_map;
1492 for (
const auto& sp : select_pins)
1494 select_map.insert({sp, g->get_fan_in_net(sp)});
1497 select_map_to_muxes[select_map].push_back(g);
1500 if (select_map_to_muxes.size() == 1)
1505 const std::vector<Net*> select_signals = {select_signals_set.begin(), select_signals_set.end()};
1508 std::map<Gate*, std::map<GatePin*, Net*>> new_net_to_pin;
1511 for (
const auto& g : mux_group)
1513 for (
u32 select_index = 0; select_index < select_pins.size(); select_index++)
1515 auto select_pin = select_pins.at(select_index);
1516 auto select_signal = select_signals.at(select_index);
1517 new_net_to_pin[g][select_pin] = select_signal;
1522 auto type_bf =
type->get_boolean_function(output_pins.front());
1523 for (
u32 select_val = 0; select_val < (1 << select_signals.size()); select_val++)
1525 std::map<std::string, BooleanFunction> type_substitution;
1526 for (
u32 select_idx = 0; select_idx < select_pins.size(); select_idx++)
1528 auto select_pin = select_pins.at(select_idx);
1530 auto type_substitution_val = ((select_val >> select_idx) & 0x1) ?
BooleanFunction::Const(1, 1) : BooleanFunction::Const(0, 1);
1531 type_substitution.insert({select_pin->get_name(), type_substitution_val});
1534 auto type_substitution_res = type_bf.substitute(type_substitution);
1535 if (type_substitution_res.is_error())
1537 return ERR_APPEND(type_substitution_res.get_error(),
"cannot unify mux select signals: failed to substitute type Boolean function with select signal value mapping.");
1539 auto input = type_substitution_res.get().simplify_local();
1541 if (!
input.is_variable())
1543 return ERR(
"cannot unify mux select signals: substituted and simplified type Boolean function (" +
input.to_string() +
") is not a variable");
1546 const auto pin_name =
input.get_variable_name().get();
1547 auto pin =
type->get_pins([pin_name](
const auto& p) {
return p->get_name() == pin_name; }).front();
1549 for (
const auto& g : mux_group)
1551 auto gate_bf_res = g->get_resolved_boolean_function(output_pins.front(),
false);
1552 if (gate_bf_res.is_error())
1555 "cannot unify mux select signals: failed to build Boolean function for gate " + g->get_name() +
" with ID " + std::to_string(g->get_id()));
1557 auto gate_bf = gate_bf_res.get();
1559 std::map<std::string, BooleanFunction> gate_substitution;
1561 for (
u32 select_idx = 0; select_idx < select_pins.size(); select_idx++)
1563 auto gate_substitution_val = ((select_val >> select_idx) & 0x1) ?
BooleanFunction::Const(1, 1) : BooleanFunction::Const(0, 1);
1564 gate_substitution.insert({BooleanFunctionNetDecorator(*(select_signals.at(select_idx))).get_boolean_variable_name(), gate_substitution_val});
1567 auto gate_substitution_res = gate_bf.substitute(gate_substitution);
1568 if (gate_substitution_res.is_error())
1570 return ERR_APPEND(gate_substitution_res.get_error(),
"cannot unify mux select signals: failed to substitute gate Boolean function with select signal value mapping.");
1572 auto input_net_var = gate_substitution_res.get().simplify_local();
1575 if (net_res.is_error())
1577 return ERR_APPEND(net_res.get_error(),
"cannot unify mux select signals: failed to extract net from substituted and simplified gate Boolean function");
1580 auto net = net_res.get();
1581 new_net_to_pin[g][pin] =
net;
1586 for (
auto& [g, pin_net] : new_net_to_pin)
1588 for (
const auto& [pin,
net] : pin_net)
1590 auto connected_net = g->get_fan_in_net(pin);
1591 if (
net == connected_net)
1596 connected_net->remove_destination(g, pin);
1597 net->add_destination(g, pin);
1599 changed_connections += 1;
1604 return OK(changed_connections);
1614 return ERR(
"netlist is a nullptr");
1617 if (mux_inv_gl ==
nullptr)
1619 return ERR(
"gate library is a nullptr");
1622 auto remove_res = remove_encasing_inverters(nl);
1623 if (remove_res.is_error())
1625 return ERR_APPEND(remove_res.get_error(),
"unable to apply manual mux optimizations: failed to remove encasing inverters");
1627 res_count += remove_res.get();
1629 auto unify_inverted_res = unify_inverted_select_signals(nl, mux_inv_gl);
1630 if (unify_inverted_res.is_error())
1632 return ERR_APPEND(unify_inverted_res.get_error(),
"unable to apply manual mux optimizations: failed to unify inverted select signals");
1634 res_count += unify_inverted_res.get();
1636 auto unify_res = unify_select_signals(nl);
1637 if (unify_res.is_error())
1639 return ERR_APPEND(unify_res.get_error(),
"unable to apply manual mux optimizations: failed to unify select signals");
1641 res_count += unify_res.get();
1643 return OK(res_count);
1650 return ERR(
"netlist is a nullptr");
1656 u32 total_replaced_dst_count = 0;
1660 u32 replaced_dst_count = 0;
1661 std::vector<Gate*> to_delete;
1662 for (
const auto g : nl->
get_gates([](
const auto g) {
1663 return g->get_type()->has_property(GateTypeProperty::combinational) && !g->get_type()->has_property(GateTypeProperty::ground)
1664 && !g->get_type()->has_property(GateTypeProperty::power);
1667 bool has_global_output =
false;
1668 for (
const auto ep : g->get_fan_out_endpoints())
1670 if (ep->get_net()->is_global_output_net())
1672 has_global_output =
true;
1675 auto bf_res = g->get_resolved_boolean_function(ep->get_pin(),
false);
1676 if (bf_res.is_error())
1679 "unable to propagate constants: failed to generate boolean function at gate " + g->get_name() +
" with ID " + std::to_string(g->get_id()) +
" for pin "
1680 + ep->get_pin()->get_name());
1682 auto bf = bf_res.get();
1684 if (sub_res.is_error())
1687 "unable to propagate constants: failed to substitue power and ground nets in boolean function of gate " + g->get_name() +
" with ID "
1688 + std::to_string(g->get_id()) +
" for pin " + ep->get_pin()->get_name());
1691 bf = bf.simplify_local();
1694 if (bf.is_constant())
1697 if (bf.has_constant_value(0))
1699 new_source = gnd_net;
1701 else if (bf.has_constant_value(1))
1703 new_source = vcc_net;
1710 if (new_source ==
nullptr)
1713 return ERR(
"unable to propagate constants: netlist is missing gnd or vcc net!");
1716 std::vector<std::pair<Gate*, GatePin*>> to_replace;
1717 for (
auto dst : ep->get_net()->get_destinations())
1719 to_replace.push_back({dst->get_gate(), dst->get_pin()});
1722 for (
const auto& [dst_g, dst_p] : to_replace)
1724 ep->get_net()->remove_destination(dst_g, dst_p);
1727 replaced_dst_count++;
1734 if (!has_global_output && g->get_successors().empty())
1736 to_delete.push_back(g);
1740 for (
auto g : to_delete)
1745 if (replaced_dst_count == 0)
1750 log_debug(
"netlist_preprocessing",
"replaced {} destinations this with power/ground nets this iteration", replaced_dst_count);
1751 total_replaced_dst_count += replaced_dst_count;
1754 log_info(
"netlist_preprocessing",
"replaced {} destinations with power/ground nets in total", total_replaced_dst_count);
1755 return OK(total_replaced_dst_count);
1762 return ERR(
"netlist is a nullptr");
1765 std::set<Gate*> gates_to_delete;
1766 for (
auto* inv_gate : nl->
get_gates([](
const Gate* g) { return g->get_type()->has_property(GateTypeProperty::c_inverter); }))
1768 if (gates_to_delete.find(inv_gate) != gates_to_delete.end())
1773 const auto& connection_endpoints = inv_gate->get_fan_in_endpoints();
1774 if (connection_endpoints.size() != 1)
1776 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());
1780 auto* middle_fan_in_ep = connection_endpoints.front();
1781 auto* middle_net = middle_fan_in_ep->get_net();
1782 if (middle_net->get_sources().size() != 1)
1784 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());
1787 auto* pred_gate = middle_net->get_sources().front()->get_gate();
1791 const auto& fan_in = pred_gate->get_fan_in_endpoints();
1792 if (fan_in.size() != 1)
1794 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());
1797 if (pred_gate->get_fan_out_endpoints().size() != 1)
1799 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());
1802 auto* in_net = fan_in.front()->get_net();
1804 const auto& fan_out = inv_gate->get_fan_out_endpoints();
1805 if (fan_out.size() != 1)
1807 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());
1810 auto* out_net = fan_out.front()->get_net();
1812 for (
auto* dst_ep : out_net->get_destinations())
1814 auto* dst_pin = dst_ep->get_pin();
1815 auto* dst_gate = dst_ep->get_gate();
1817 out_net->remove_destination(dst_ep);
1818 in_net->add_destination(dst_gate, dst_pin);
1821 middle_net->remove_destination(middle_fan_in_ep);
1823 if (middle_net->get_num_of_destinations() == 0)
1826 gates_to_delete.insert(pred_gate);
1829 gates_to_delete.insert(inv_gate);
1833 u32 removed_ctr = 0;
1834 for (
auto* g : gates_to_delete)
1840 return OK(removed_ctr);
1845 std::string generate_hex_truth_table_string(
const std::vector<BooleanFunction::Value>& tt)
1847 std::string tt_str =
"";
1850 for (
u32 i = 0; i < tt.size(); i++)
1853 if (bit == BooleanFunction::Value::ONE)
1855 acc += (1 << (i % 4));
1860 std::stringstream stream;
1861 stream << std::hex << acc;
1863 tt_str = stream.str() + tt_str;
1877 for (
auto g : nl->
get_gates([](
const auto& g) { return g->get_type()->has_property(GateTypeProperty::c_lut); }))
1879 auto res = g->get_init_data();
1883 "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");
1886 const auto original_inits = res.get();
1888 if (original_inits.size() != 1)
1890 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())
1891 +
" init data strings but expected exactly 1.");
1894 const auto original_init = original_inits.front();
1897 if (g->get_type()->get_output_pins().size() != 1)
1902 const auto out_ep = g->get_fan_out_endpoints().front();
1905 if (g->get_boolean_functions().size() != 1)
1910 const auto bf_org = g->get_boolean_function(out_ep->get_pin());
1911 const auto org_vars = bf_org.get_variable_names();
1914 if (bf_replaced_res.is_error())
1916 return ERR_APPEND(bf_replaced_res.get_error(),
1917 "cannot simplify LUT inits: failed to replace power and ground pins for gate " + g->get_name() +
" with ID " + std::to_string(g->get_id()));
1919 const auto bf_replaced = bf_replaced_res.get();
1920 const auto bf_simplified = bf_replaced.simplify_local();
1922 const auto new_vars = bf_simplified.get_variable_names();
1924 if (org_vars.size() == new_vars.size())
1929 auto bf_extended = bf_simplified.clone();
1930 for (
const auto& in_pin : g->get_type()->get_input_pin_names())
1932 if (new_vars.find(in_pin) == new_vars.end())
1939 const auto tt = bf_extended.compute_truth_table().get();
1940 const auto new_init_string = generate_hex_truth_table_string(tt.front());
1945 g->set_init_data({new_init_string}).get();
1946 g->set_data(
"preprocessing_information",
"original_init",
"string", original_init);
1959 log_info(
"netlist_preprocessing",
"simplified {} LUT INIT strings inside of netlist with ID {}.", num_inits, nl->
get_id());
1960 return OK(num_inits);
1965 struct indexed_identifier
1967 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}
1977 const std::string hal_instance_index_pattern =
"__\\[(\\d+)\\]__";
1978 const std::string hal_instance_index_pattern_reverse =
"<HAL>(\\d+)<HAL>";
1980 std::string replace_hal_instance_index(
const std::string&
name)
1982 std::regex re(hal_instance_index_pattern);
1987 while (std::regex_search(
input, match, re))
1996 std::string reconstruct_hal_instance_index(
const std::string&
name)
1998 std::regex re(hal_instance_index_pattern_reverse);
2003 while (std::regex_search(input, match, re))
2012 const std::string net_index_pattern =
"\\((\\d+)\\)";
2013 const std::string gate_index_pattern =
"\\[(\\d+)\\]";
2016 std::optional<indexed_identifier> extract_index(
const std::string&
name,
const std::string& index_pattern,
const std::string&
origin)
2018 std::regex re(index_pattern);
2021 std::optional<std::string> last_match;
2022 std::optional<u32> last_index;
2026 while (std::regex_search(input, match, re))
2029 last_index = std::stoi(match[1]);
2030 last_match = match.str();
2031 input = match.suffix().str();
2034 if (!last_index.has_value())
2036 return std::nullopt;
2039 const auto found_match = last_match.value();
2040 auto identifier_name =
name;
2041 identifier_name = identifier_name.replace(
name.rfind(found_match), found_match.size(),
"");
2043 return std::optional<indexed_identifier>{{identifier_name, last_index.value(),
origin}};
2047 bool annotate_indexed_identifiers(Gate* gate,
const std::vector<indexed_identifier>& identifiers)
2049 std::string json_identifier_str =
2050 "[" +
utils::join(
", ", identifiers, [](
const auto& i) {
return std::string(
"[") +
'"' + i.identifier +
'"' +
", " + std::to_string(i.index) +
", " +
'"' + i.origin +
'"' +
"]"; })
2053 return gate->set_data(
"preprocessing_information",
"multi_bit_indexed_identifiers",
"string", json_identifier_str);
2057 std::vector<indexed_identifier> check_net_at_pin(
const PinType pin_type, Gate* gate)
2059 const auto typed_pins = gate->get_type()->get_pins([pin_type](
const auto p) {
return p->get_type() == pin_type; });
2061 std::vector<indexed_identifier> found_identfiers;
2063 for (
const auto& pin : typed_pins)
2065 const auto typed_net = (pin->get_direction() ==
PinDirection::output) ? gate->get_fan_out_net(pin) : gate->get_fan_in_net(pin);
2074 const auto net_name_index = extract_index(typed_net->get_name(), net_index_pattern,
"net_name");
2075 if (net_name_index.has_value())
2077 found_identfiers.push_back(net_name_index.value());
2081 if (!typed_net->has_data(
"parser_annotation",
"merged_nets"))
2086 const auto all_merged_nets_str = std::get<1>(typed_net->get_data(
"parser_annotation",
"merged_nets"));
2088 if (all_merged_nets_str.empty())
2094 rapidjson::Document doc;
2095 doc.Parse(all_merged_nets_str.c_str());
2097 for (
u32 i = 0; i < doc.GetArray().Size(); i++)
2099 const auto list = doc[i].GetArray();
2100 for (
u32 j = 0; j < list.Size(); j++)
2102 const auto merged_wire_name = list[j].GetString();
2104 const auto merged_wire_name_index = extract_index(merged_wire_name, net_index_pattern,
"net_name");
2105 if (merged_wire_name_index.has_value())
2107 found_identfiers.push_back(merged_wire_name_index.value());
2113 return found_identfiers;
2120 for (
auto&
ff : nl->
get_gates([](
const auto g) { return g->get_type()->has_property(GateTypeProperty::ff); }))
2122 std::vector<indexed_identifier> all_identifiers;
2125 const auto cleaned_gate_name = replace_hal_instance_index(
ff->get_name());
2126 const auto gate_name_index = extract_index(cleaned_gate_name, gate_index_pattern,
"gate_name");
2128 if (gate_name_index.has_value())
2130 auto found_identifier = gate_name_index.value();
2131 found_identifier.identifier = reconstruct_hal_instance_index(found_identifier.identifier);
2132 all_identifiers.push_back(found_identifier);
2138 for (
const auto& pt : relevant_pin_types)
2140 const auto found_identifiers = check_net_at_pin(pt,
ff);
2141 all_identifiers.insert(all_identifiers.end(), found_identifiers.begin(), found_identifiers.end());
2144 if (!all_identifiers.empty())
2149 annotate_indexed_identifiers(
ff, all_identifiers);
2157 std::map<std::string, std::map<u32, std::vector<ModulePin*>>> pg_name_to_indexed_pins;
2161 auto reconstruct = extract_index(pin->get_name(), net_index_pattern,
"");
2162 if (!reconstruct.has_value())
2167 auto [pg_name,
index, _] = reconstruct.value();
2169 pg_name_to_indexed_pins[pg_name][
index].push_back(pin);
2172 u32 reconstructed_counter = 0;
2173 for (
const auto& [pg_name, indexed_pins] : pg_name_to_indexed_pins)
2175 std::vector<ModulePin*> ordered_pins;
2177 bool valid_indices =
true;
2179 for (
const auto& [_index,
pins] : indexed_pins)
2181 if (
pins.size() > 1)
2183 valid_indices =
false;
2187 ordered_pins.push_back(
pins.front());
2198 return ERR_APPEND(res.get_error(),
"cannot reconstruct top module pin groups: failed to create pin group " + pg_name);
2201 reconstructed_counter++;
2204 return OK(reconstructed_counter);
2209 struct ComponentData
2217 TokenStream<std::string> tokenize(std::stringstream& ss)
2219 const std::string delimiters =
" ;-";
2220 std::string current_token;
2221 u32 line_number = 0;
2224 bool escaped =
false;
2226 std::vector<Token<std::string>> parsed_tokens;
2227 while (std::getline(ss, line))
2239 else if (escaped && std::isspace(c))
2245 if (((!std::isspace(c) && delimiters.find(c) == std::string::npos) || escaped))
2251 if (!current_token.empty())
2253 parsed_tokens.emplace_back(line_number, current_token);
2254 current_token.clear();
2257 if (!std::isspace(c))
2259 parsed_tokens.emplace_back(line_number, std::string(1, c));
2264 if (!current_token.empty())
2266 parsed_tokens.emplace_back(line_number, current_token);
2267 current_token.clear();
2271 return TokenStream(parsed_tokens, {}, {});
2274 Result<std::unordered_map<std::string, ComponentData>> parse_tokens(TokenStream<std::string>& ts)
2276 ts.consume_until(
"COMPONENTS");
2277 ts.consume(
"COMPONENTS");
2278 const auto component_count_str = ts.consume().string;
2281 u32 component_count;
2284 component_count = res.get();
2288 return ERR_APPEND(res.get_error(),
"could not parse tokens: failed to read component count from token" + component_count_str);
2291 std::cout <<
"Component count: " << component_count << std::endl;
2293 std::unordered_map<std::string, ComponentData> component_data;
2294 for (
u32 c_idx = 0; c_idx < component_count; c_idx++)
2297 ComponentData new_data_entry;
2299 new_data_entry.name = ts.consume().string;
2300 new_data_entry.type = ts.consume().string;
2302 ts.consume(
"SOURCE");
2304 ts.consume(
"TIMING");
2306 ts.consume(
"PLACED");
2307 ts.consume(
"FIXED");
2312 new_data_entry.x = res.get();
2316 return ERR_APPEND(res.get_error(),
"could not parse tokens: failed to read x coordinate from token");
2321 new_data_entry.y = res.get();
2325 return ERR_APPEND(res.get_error(),
"could not parse tokens: failed to read y coordinate from token");
2330 ts.consume_current_line();
2332 component_data.insert({new_data_entry.name, new_data_entry});
2335 return OK(component_data);
2341 std::stringstream ss;
2343 ifs.open(def_file.string(), std::ifstream::in);
2346 return ERR(
"could not parse DEF (Design Exchange Format) file '" + def_file.string() +
"' : unable to open file");
2351 auto ts = tokenize(ss);
2353 std::unordered_map<std::string, ComponentData> component_data;
2357 if (
auto res = parse_tokens(ts); res.is_error())
2359 return ERR_APPEND(res.get_error(),
"could not parse Design Exchange Format file '" + def_file.string() +
"': unable to parse tokens");
2363 component_data = res.get();
2368 if (e.line_number != (
u32)-1)
2370 return ERR(
"could not parse Design Exchange Format file '" + def_file.string() +
"': " + e.message +
" (line " + std::to_string(e.line_number) +
")");
2374 return ERR(
"could not parse Design Exchange Format file '" + def_file.string() +
"': " + e.message);
2378 std::unordered_map<std::string, Gate*> name_to_gate;
2381 name_to_gate.insert({g->get_name(), g});
2385 for (
const auto& [gate_name,
data] : component_data)
2387 if (
const auto& g_it = name_to_gate.find(gate_name); g_it != name_to_gate.end())
2390 g_it->second->set_location_x(
data.x);
2391 g_it->second->set_location_y(
data.y);
2397 log_info(
"netlist_preprocessing",
"reconstructed coordinates for {} / {} ({:.2}) gates", counter, nl->
get_gates().size(), (
double)counter / (
double)nl->
get_gates().size());
2404 std::vector<Module*> all_modules;
2405 for (
const auto& [gt_name, pin_groups] : concatenated_pin_groups)
2410 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());
2413 for (
const auto& g : nl->
get_gates([>](
const auto& g) { return g->get_type() == gt; }))
2415 auto m = nl->
create_module(
"module_" + g->get_name(), g->get_module(), {g});
2417 for (
const auto& [module_pg_name, gate_pg_names] : pin_groups)
2419 std::vector<ModulePin*> module_pins;
2420 for (
const auto& gate_pg_name : gate_pg_names)
2422 const auto& gate_pg = g->
get_type()->get_pin_group_by_name(gate_pg_name);
2424 if (gate_pg ==
nullptr)
2426 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");
2429 std::vector<GatePin*> pin_list = gate_pg->get_pins();
2430 if (!gate_pg->is_ascending())
2432 std::reverse(pin_list.begin(), pin_list.end());
2435 for (
const auto& gate_pin : pin_list)
2437 const auto net = (gate_pin->get_direction() ==
PinDirection::output) ? g->get_fan_out_net(gate_pin) : g->get_fan_in_net(gate_pin);
2443 if (
net->is_gnd_net() ||
net->is_vcc_net())
2448 const auto module_pin = m->get_pin_by_net(
net);
2450 module_pins.push_back(module_pin);
2454 m->create_pin_group(module_pg_name, module_pins);
2455 u32 idx_counter = 0;
2456 for (
const auto& mp : module_pins)
2458 m->set_pin_name(mp, module_pg_name +
"_" + std::to_string(idx_counter));
2463 all_modules.push_back(m);
2467 return OK(all_modules);
2472 std::vector<Net*> created_nets;
2476 for (
const auto& p : g->get_type()->get_output_pins())
2478 if (g->get_fan_out_net(p) ==
nullptr)
2481 new_net->
set_name(
"HAL_UNCONNECTED_" + std::to_string(new_net->get_id()));
2482 new_net->add_source(g, p);
2484 created_nets.push_back(new_net);
2489 return OK(created_nets);
2496 return ERR(
"netlist is a nullptr");
2499 if (inverter_type ==
nullptr)
2502 const auto inv_types =
2504 if (inv_types.empty())
2506 return ERR(
"gate library '" + gl->get_name() +
"' of netlist does not contain an inverter gate");
2508 inverter_type = inv_types.begin()->second;
2514 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 '"
2526 +
"' has an invalid number of input pins or output pins");
2535 const std::vector<Gate*>& gates = ffs.empty() ? nl->
get_gates() : ffs;
2537 for (
auto*
ff : gates)
2539 auto* ff_type =
ff->get_type();
2547 GatePin* neg_state_pin =
nullptr;
2549 for (
auto* o_pin : ff_type->get_output_pins())
2557 neg_state_pin = o_pin;
2561 if (neg_state_pin ==
nullptr)
2566 auto* neg_state_ep =
ff->get_fan_out_endpoint(neg_state_pin);
2567 if (neg_state_ep ==
nullptr)
2571 auto* neg_state_net = neg_state_ep->get_net();
2573 auto state_net =
ff->get_fan_out_net(state_pin);
2574 if (state_net ==
nullptr)
2576 state_net = nl->
create_net(
ff->get_name() +
"__STATE_NET__");
2580 auto* inv = nl->
create_gate(inverter_type,
ff->get_name() +
"__NEG_STATE_INVERT__");
2581 state_net->add_destination(inv, inv_in_pin);
2582 neg_state_net->remove_source(neg_state_ep);
2583 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...