diff --git a/passes/techmap/abc.cc b/passes/techmap/abc.cc index 42287966288..99d361193ca 100644 --- a/passes/techmap/abc.cc +++ b/passes/techmap/abc.cc @@ -30,7 +30,8 @@ // http://en.wikipedia.org/wiki/Topological_sorting #define ABC_COMMAND_LIB "strash; &get -n; &fraig -x; &put; scorr; dc2; dretime; strash; &get -n; &dch -f; &nf {D}; &put" -#define ABC_COMMAND_CTR "strash; &get -n; &fraig -x; &put; scorr; dc2; dretime; strash; &get -n; &dch -f; &nf {D}; &put; buffer; upsize {D}; dnsize {D}; stime -p" +#define ABC_COMMAND_CTR \ + "strash; &get -n; &fraig -x; &put; scorr; dc2; dretime; strash; &get -n; &dch -f; &nf {D}; &put; buffer; upsize {D}; dnsize {D}; stime -p" #define ABC_COMMAND_LUT "strash; &get -n; &fraig -x; &put; scorr; dc2; dretime; strash; dch -f; if; mfs2" #define ABC_COMMAND_SOP "strash; &get -n; &fraig -x; &put; scorr; dc2; dretime; strash; dch -f; cover {I} {P}" #define ABC_COMMAND_DFL "strash; &get -n; &fraig -x; &put; scorr; dc2; dretime; strash; &get -n; &dch -f; &nf {D}; &put" @@ -41,32 +42,33 @@ #define ABC_FAST_COMMAND_SOP "strash; dretime; cover {I} {P}" #define ABC_FAST_COMMAND_DFL "strash; dretime; map" -#include "kernel/register.h" -#include "kernel/sigtools.h" #include "kernel/celltypes.h" -#include "kernel/ffinit.h" -#include "kernel/ff.h" #include "kernel/cost.h" +#include "kernel/ff.h" +#include "kernel/ffinit.h" #include "kernel/log.h" -#include -#include -#include +#include "kernel/register.h" +#include "kernel/sigtools.h" #include #include -#include #include +#include +#include +#include +#include #include #ifndef _WIN32 -# include -# include +#include +#include #endif #include "frontends/blif/blifparse.h" #ifdef YOSYS_LINK_ABC -namespace abc { - int Abc_RealMain(int argc, char *argv[]); +namespace abc +{ +int Abc_RealMain(int argc, char *argv[]); } #endif @@ -96,10 +98,9 @@ enum class gate_type_t { G_OAI4 }; -#define G(_name) gate_type_t::G_ ## _name +#define G(_name) gate_type_t::G_##_name -struct gate_t -{ +struct gate_t { int id; gate_type_t type; int in1, in2, in3, in4; @@ -257,8 +258,7 @@ void extract_cell(RTLIL::Cell *cell, bool keepff) return; } - if (cell->type.in(ID($_BUF_), ID($_NOT_))) - { + if (cell->type.in(ID($_BUF_), ID($_NOT_))) { RTLIL::SigSpec sig_a = cell->getPort(ID::A); RTLIL::SigSpec sig_y = cell->getPort(ID::Y); @@ -271,8 +271,7 @@ void extract_cell(RTLIL::Cell *cell, bool keepff) return; } - if (cell->type.in(ID($_AND_), ID($_NAND_), ID($_OR_), ID($_NOR_), ID($_XOR_), ID($_XNOR_), ID($_ANDNOT_), ID($_ORNOT_))) - { + if (cell->type.in(ID($_AND_), ID($_NAND_), ID($_OR_), ID($_NOR_), ID($_XOR_), ID($_XNOR_), ID($_ANDNOT_), ID($_ORNOT_))) { RTLIL::SigSpec sig_a = cell->getPort(ID::A); RTLIL::SigSpec sig_b = cell->getPort(ID::B); RTLIL::SigSpec sig_y = cell->getPort(ID::Y); @@ -307,8 +306,7 @@ void extract_cell(RTLIL::Cell *cell, bool keepff) return; } - if (cell->type.in(ID($_MUX_), ID($_NMUX_))) - { + if (cell->type.in(ID($_MUX_), ID($_NMUX_))) { RTLIL::SigSpec sig_a = cell->getPort(ID::A); RTLIL::SigSpec sig_b = cell->getPort(ID::B); RTLIL::SigSpec sig_s = cell->getPort(ID::S); @@ -329,8 +327,7 @@ void extract_cell(RTLIL::Cell *cell, bool keepff) return; } - if (cell->type.in(ID($_AOI3_), ID($_OAI3_))) - { + if (cell->type.in(ID($_AOI3_), ID($_OAI3_))) { RTLIL::SigSpec sig_a = cell->getPort(ID::A); RTLIL::SigSpec sig_b = cell->getPort(ID::B); RTLIL::SigSpec sig_c = cell->getPort(ID::C); @@ -351,8 +348,7 @@ void extract_cell(RTLIL::Cell *cell, bool keepff) return; } - if (cell->type.in(ID($_AOI4_), ID($_OAI4_))) - { + if (cell->type.in(ID($_AOI4_), ID($_OAI4_))) { RTLIL::SigSpec sig_a = cell->getPort(ID::A); RTLIL::SigSpec sig_b = cell->getPort(ID::B); RTLIL::SigSpec sig_c = cell->getPort(ID::C); @@ -381,26 +377,21 @@ std::string remap_name(RTLIL::IdString abc_name, RTLIL::Wire **orig_wire = nullp { std::string abc_sname = abc_name.substr(1); bool isnew = false; - if (abc_sname.compare(0, 4, "new_") == 0) - { + if (abc_sname.compare(0, 4, "new_") == 0) { abc_sname.erase(0, 4); isnew = true; } - if (abc_sname.compare(0, 5, "ys__n") == 0) - { + if (abc_sname.compare(0, 5, "ys__n") == 0) { abc_sname.erase(0, 5); - if (std::isdigit(abc_sname.at(0))) - { + if (std::isdigit(abc_sname.at(0))) { int sid = std::atoi(abc_sname.c_str()); size_t postfix_start = abc_sname.find_first_not_of("0123456789"); std::string postfix = postfix_start != std::string::npos ? abc_sname.substr(postfix_start) : ""; - if (sid < GetSize(signal_list)) - { + if (sid < GetSize(signal_list)) { auto sig = signal_list.at(sid); - if (sig.bit.wire != nullptr) - { - std::string s = stringf("$abc$%d$%s", map_autoidx, sig.bit.wire->name.c_str()+1); + if (sig.bit.wire != nullptr) { + std::string s = stringf("$abc$%d$%s", map_autoidx, sig.bit.wire->name.c_str() + 1); if (sig.bit.wire->width != 1) s += stringf("[%d]", sig.bit.offset); if (isnew) @@ -413,7 +404,7 @@ std::string remap_name(RTLIL::IdString abc_name, RTLIL::Wire **orig_wire = nullp } } } - return stringf("$abc$%d$%s", map_autoidx, abc_name.c_str()+1); + return stringf("$abc$%d$%s", map_autoidx, abc_name.c_str() + 1); } void dump_loop_graph(FILE *f, int &nr, dict> &edges, pool &workpool, std::vector &in_counts) @@ -435,12 +426,12 @@ void dump_loop_graph(FILE *f, int &nr, dict> &edges, pool &w } for (auto n : nodes) - fprintf(f, " ys__n%d [label=\"%s\\nid=%d, count=%d\"%s];\n", n, log_signal(signal_list[n].bit), - n, in_counts[n], workpool.count(n) ? ", shape=box" : ""); + fprintf(f, " ys__n%d [label=\"%s\\nid=%d, count=%d\"%s];\n", n, log_signal(signal_list[n].bit), n, in_counts[n], + workpool.count(n) ? ", shape=box" : ""); for (auto &e : edges) - for (auto n : e.second) - fprintf(f, " ys__n%d -> ys__n%d;\n", e.first, n); + for (auto n : e.second) + fprintf(f, " ys__n%d -> ys__n%d;\n", e.first, n); fprintf(f, "}\n"); } @@ -485,8 +476,7 @@ void handle_loops() dump_loop_graph(dot_f, dot_nr, edges, workpool, in_edges_count); - while (workpool.size() > 0) - { + while (workpool.size() > 0) { int id = *workpool.begin(); workpool.erase(id); @@ -501,8 +491,7 @@ void handle_loops() dump_loop_graph(dot_f, dot_nr, edges, workpool, in_edges_count); - while (workpool.size() == 0) - { + while (workpool.size() == 0) { if (edges.size() == 0) break; @@ -543,10 +532,10 @@ void handle_loops() for (int id2 : edges[id1]) { if (first_line) log("Breaking loop using new signal %s: %s -> %s\n", log_signal(RTLIL::SigSpec(wire)), - log_signal(signal_list[id1].bit), log_signal(signal_list[id2].bit)); + log_signal(signal_list[id1].bit), log_signal(signal_list[id2].bit)); else log(" %*s %s -> %s\n", int(strlen(log_signal(RTLIL::SigSpec(wire)))), "", - log_signal(signal_list[id1].bit), log_signal(signal_list[id2].bit)); + log_signal(signal_list[id1].bit), log_signal(signal_list[id2].bit)); first_line = false; } @@ -584,7 +573,7 @@ std::string add_echos_to_abc_cmd(std::string str) for (size_t i = 0; i < str.size(); i++) { token += str[i]; if (str[i] == ';') { - while (i+1 < str.size() && str[i+1] == ' ') + while (i + 1 < str.size() && str[i + 1] == ' ') i++; new_str += "echo + " + token + " " + token + " "; token.clear(); @@ -631,7 +620,7 @@ std::string replace_tempdir(std::string text, std::string tempdir_name, bool sho text = text.substr(0, pos) + "" + text.substr(pos + GetSize(tempdir_name)); } - std::string selfdir_name = proc_self_dirname(); + std::string selfdir_name = proc_self_dirname(); if (selfdir_name != "/") { while (1) { size_t pos = text.find(selfdir_name); @@ -644,8 +633,7 @@ std::string replace_tempdir(std::string text, std::string tempdir_name, bool sho return text; } -struct abc_output_filter -{ +struct abc_output_filter { bool got_cr; int escape_seq_state; std::string linebuf; @@ -692,9 +680,8 @@ struct abc_output_filter { int pi, po; if (sscanf(line.c_str(), "Start-point = pi%d. End-point = po%d.", &pi, &po) == 2) { - log("ABC: Start-point = pi%d (%s). End-point = po%d (%s).\n", - pi, pi_map.count(pi) ? pi_map.at(pi).c_str() : "???", - po, po_map.count(po) ? po_map.at(po).c_str() : "???"); + log("ABC: Start-point = pi%d (%s). End-point = po%d (%s).\n", pi, pi_map.count(pi) ? pi_map.at(pi).c_str() : "???", po, + po_map.count(po) ? po_map.at(po).c_str() : "???"); return; } @@ -704,10 +691,10 @@ struct abc_output_filter }; void abc_module(RTLIL::Design *design, RTLIL::Module *current_module, std::string script_file, std::string exe_file, - std::vector &liberty_files, std::vector &genlib_files, std::string constr_file, - bool cleanup, vector lut_costs, bool dff_mode, std::string clk_str, bool keepff, std::string delay_target, - std::string sop_inputs, std::string sop_products, std::string lutin_shared, bool fast_mode, - const std::vector &cells, bool show_tempdir, bool sop_mode, bool abc_dress, std::vector &dont_use_cells) + std::vector &liberty_files, std::vector &genlib_files, std::string constr_file, bool cleanup, + vector lut_costs, bool dff_mode, std::string clk_str, bool keepff, std::string delay_target, std::string sop_inputs, + std::string sop_products, std::string lutin_shared, bool fast_mode, const std::vector &cells, bool show_tempdir, + bool sop_mode, bool abc_dress, std::vector &dont_use_cells) { module = current_module; map_autoidx = autoidx++; @@ -717,8 +704,7 @@ void abc_module(RTLIL::Design *design, RTLIL::Module *current_module, std::strin pi_map.clear(); po_map.clear(); - if (clk_str != "$") - { + if (clk_str != "$") { clk_polarity = true; clk_sig = RTLIL::SigSpec(); @@ -732,24 +718,23 @@ void abc_module(RTLIL::Design *design, RTLIL::Module *current_module, std::strin srst_sig = RTLIL::SigSpec(); } - if (!clk_str.empty() && clk_str != "$") - { + if (!clk_str.empty() && clk_str != "$") { std::string en_str; std::string arst_str; std::string srst_str; if (clk_str.find(',') != std::string::npos) { int pos = clk_str.find(','); - en_str = clk_str.substr(pos+1); + en_str = clk_str.substr(pos + 1); clk_str = clk_str.substr(0, pos); } if (en_str.find(',') != std::string::npos) { int pos = en_str.find(','); - arst_str = en_str.substr(pos+1); + arst_str = en_str.substr(pos + 1); arst_str = en_str.substr(0, pos); } if (arst_str.find(',') != std::string::npos) { int pos = arst_str.find(','); - srst_str = arst_str.substr(pos+1); + srst_str = arst_str.substr(pos + 1); srst_str = arst_str.substr(0, pos); } if (clk_str[0] == '!') { @@ -788,14 +773,14 @@ void abc_module(RTLIL::Design *design, RTLIL::Module *current_module, std::strin log_cmd_error("Clock domain %s not found.\n", clk_str.c_str()); std::string tempdir_name; - if (cleanup) + if (cleanup) tempdir_name = get_base_tmpdir() + "/"; else tempdir_name = "_tmp_"; tempdir_name += proc_program_prefix() + "yosys-abc-XXXXXX"; tempdir_name = make_temp_dir(tempdir_name); - log_header(design, "Extracting gate netlist of module `%s' to `%s/input.blif'..\n", - module->name.c_str(), replace_tempdir(tempdir_name, tempdir_name, show_tempdir).c_str()); + log_header(design, "Extracting gate netlist of module `%s' to `%s/input.blif'..\n", module->name.c_str(), + replace_tempdir(tempdir_name, tempdir_name, show_tempdir).c_str()); std::string abc_script = stringf("read_blif \"%s/input.blif\"; ", tempdir_name.c_str()); @@ -811,8 +796,7 @@ void abc_module(RTLIL::Design *design, RTLIL::Module *current_module, std::strin abc_script += stringf("read_library \"%s\"; ", liberty_file.c_str()); if (!constr_file.empty()) abc_script += stringf("read_constr -v \"%s\"; ", constr_file.c_str()); - } else - if (!lut_costs.empty()) + } else if (!lut_costs.empty()) abc_script += stringf("read_lut %s/lutdefs.txt; ", tempdir_name.c_str()); else abc_script += stringf("read_library %s/stdcells.genlib; ", tempdir_name.c_str()); @@ -837,35 +821,36 @@ void abc_module(RTLIL::Design *design, RTLIL::Module *current_module, std::strin if (all_luts_cost_same && !fast_mode) abc_script += "; lutpack {S}"; } else if (!liberty_files.empty() || !genlib_files.empty()) - abc_script += constr_file.empty() ? (fast_mode ? ABC_FAST_COMMAND_LIB : ABC_COMMAND_LIB) : (fast_mode ? ABC_FAST_COMMAND_CTR : ABC_COMMAND_CTR); + abc_script += + constr_file.empty() ? (fast_mode ? ABC_FAST_COMMAND_LIB : ABC_COMMAND_LIB) : (fast_mode ? ABC_FAST_COMMAND_CTR : ABC_COMMAND_CTR); else if (sop_mode) abc_script += fast_mode ? ABC_FAST_COMMAND_SOP : ABC_COMMAND_SOP; else abc_script += fast_mode ? ABC_FAST_COMMAND_DFL : ABC_COMMAND_DFL; if (script_file.empty() && !delay_target.empty()) - for (size_t pos = abc_script.find("dretime;"); pos != std::string::npos; pos = abc_script.find("dretime;", pos+1)) - abc_script = abc_script.substr(0, pos) + "dretime; retime -o {D};" + abc_script.substr(pos+8); + for (size_t pos = abc_script.find("dretime;"); pos != std::string::npos; pos = abc_script.find("dretime;", pos + 1)) + abc_script = abc_script.substr(0, pos) + "dretime; retime -o {D};" + abc_script.substr(pos + 8); for (size_t pos = abc_script.find("{D}"); pos != std::string::npos; pos = abc_script.find("{D}", pos)) - abc_script = abc_script.substr(0, pos) + delay_target + abc_script.substr(pos+3); + abc_script = abc_script.substr(0, pos) + delay_target + abc_script.substr(pos + 3); for (size_t pos = abc_script.find("{I}"); pos != std::string::npos; pos = abc_script.find("{I}", pos)) - abc_script = abc_script.substr(0, pos) + sop_inputs + abc_script.substr(pos+3); + abc_script = abc_script.substr(0, pos) + sop_inputs + abc_script.substr(pos + 3); for (size_t pos = abc_script.find("{P}"); pos != std::string::npos; pos = abc_script.find("{P}", pos)) - abc_script = abc_script.substr(0, pos) + sop_products + abc_script.substr(pos+3); + abc_script = abc_script.substr(0, pos) + sop_products + abc_script.substr(pos + 3); for (size_t pos = abc_script.find("{S}"); pos != std::string::npos; pos = abc_script.find("{S}", pos)) - abc_script = abc_script.substr(0, pos) + lutin_shared + abc_script.substr(pos+3); + abc_script = abc_script.substr(0, pos) + lutin_shared + abc_script.substr(pos + 3); if (abc_dress) abc_script += stringf("; dress \"%s/input.blif\"", tempdir_name.c_str()); abc_script += stringf("; write_blif %s/output.blif", tempdir_name.c_str()); abc_script = add_echos_to_abc_cmd(abc_script); - for (size_t i = 0; i+1 < abc_script.size(); i++) - if (abc_script[i] == ';' && abc_script[i+1] == ' ') - abc_script[i+1] = '\n'; + for (size_t i = 0; i + 1 < abc_script.size(); i++) + if (abc_script[i] == ';' && abc_script[i + 1] == ' ') + abc_script[i + 1] = '\n'; std::string buffer = stringf("%s/abc.script", tempdir_name.c_str()); FILE *f = fopen(buffer.c_str(), "wt"); @@ -874,12 +859,12 @@ void abc_module(RTLIL::Design *design, RTLIL::Module *current_module, std::strin fprintf(f, "%s\n", abc_script.c_str()); fclose(f); - if (dff_mode || !clk_str.empty()) - { + if (dff_mode || !clk_str.empty()) { if (clk_sig.size() == 0) log("No%s clock domain found. Not extracting any FF cells.\n", clk_str.empty() ? "" : " matching"); else { - log("Found%s %s clock domain: %s", clk_str.empty() ? "" : " matching", clk_polarity ? "posedge" : "negedge", log_signal(clk_sig)); + log("Found%s %s clock domain: %s", clk_str.empty() ? "" : " matching", clk_polarity ? "posedge" : "negedge", + log_signal(clk_sig)); if (en_sig.size() != 0) log(", enabled by %s%s", en_polarity ? "" : "!", log_signal(en_sig)); if (arst_sig.size() != 0) @@ -905,8 +890,8 @@ void abc_module(RTLIL::Design *design, RTLIL::Module *current_module, std::strin } for (auto cell : module->cells()) - for (auto &port_it : cell->connections()) - mark_port(port_it.second); + for (auto &port_it : cell->connections()) + mark_port(port_it.second); if (clk_sig.size() != 0) mark_port(clk_sig); @@ -1040,11 +1025,10 @@ void abc_module(RTLIL::Design *design, RTLIL::Module *current_module, std::strin fprintf(f, ".end\n"); fclose(f); - log("Extracted %d gates and %d wires to a netlist network with %d inputs and %d outputs.\n", - count_gates, GetSize(signal_list), count_input, count_output); + log("Extracted %d gates and %d wires to a netlist network with %d inputs and %d outputs.\n", count_gates, GetSize(signal_list), count_input, + count_output); log_push(); - if (count_output > 0) - { + if (count_output > 0) { log_header(design, "Executing ABC.\n"); auto &cell_cost = cmos_cost ? CellCosts::cmos_gate_cost() : CellCosts::default_gate_cost(); @@ -1086,11 +1070,20 @@ void abc_module(RTLIL::Design *design, RTLIL::Module *current_module, std::strin if (enabled_gates.count("NMUX")) fprintf(f, "GATE NMUX %d Y=!((A*B)+(S*B)+(!S*A)); PIN * UNKNOWN 1 999 1 0 1 0\n", cell_cost.at(ID($_NMUX_))); if (map_mux4) - fprintf(f, "GATE MUX4 %d Y=(!S*!T*A)+(S*!T*B)+(!S*T*C)+(S*T*D); PIN * UNKNOWN 1 999 1 0 1 0\n", 2*cell_cost.at(ID($_MUX_))); + fprintf(f, "GATE MUX4 %d Y=(!S*!T*A)+(S*!T*B)+(!S*T*C)+(S*T*D); PIN * UNKNOWN 1 999 1 0 1 0\n", + 2 * cell_cost.at(ID($_MUX_))); if (map_mux8) - fprintf(f, "GATE MUX8 %d Y=(!S*!T*!U*A)+(S*!T*!U*B)+(!S*T*!U*C)+(S*T*!U*D)+(!S*!T*U*E)+(S*!T*U*F)+(!S*T*U*G)+(S*T*U*H); PIN * UNKNOWN 1 999 1 0 1 0\n", 4*cell_cost.at(ID($_MUX_))); + fprintf(f, + "GATE MUX8 %d Y=(!S*!T*!U*A)+(S*!T*!U*B)+(!S*T*!U*C)+(S*T*!U*D)+(!S*!T*U*E)+(S*!T*U*F)+(!S*T*U*G)+(S*T*U*H); PIN * " + "UNKNOWN 1 999 1 0 1 0\n", + 4 * cell_cost.at(ID($_MUX_))); if (map_mux16) - fprintf(f, "GATE MUX16 %d Y=(!S*!T*!U*!V*A)+(S*!T*!U*!V*B)+(!S*T*!U*!V*C)+(S*T*!U*!V*D)+(!S*!T*U*!V*E)+(S*!T*U*!V*F)+(!S*T*U*!V*G)+(S*T*U*!V*H)+(!S*!T*!U*V*I)+(S*!T*!U*V*J)+(!S*T*!U*V*K)+(S*T*!U*V*L)+(!S*!T*U*V*M)+(S*!T*U*V*N)+(!S*T*U*V*O)+(S*T*U*V*P); PIN * UNKNOWN 1 999 1 0 1 0\n", 8*cell_cost.at(ID($_MUX_))); + fprintf(f, + "GATE MUX16 %d " + "Y=(!S*!T*!U*!V*A)+(S*!T*!U*!V*B)+(!S*T*!U*!V*C)+(S*T*!U*!V*D)+(!S*!T*U*!V*E)+(S*!T*U*!V*F)+(!S*T*U*!V*G)+(S*T*U*!V*" + "H)+(!S*!T*!U*V*I)+(S*!T*!U*V*J)+(!S*T*!U*V*K)+(S*T*!U*V*L)+(!S*!T*U*V*M)+(S*!T*U*V*N)+(!S*T*U*V*O)+(S*T*U*V*P); PIN " + "* UNKNOWN 1 999 1 0 1 0\n", + 8 * cell_cost.at(ID($_MUX_))); fclose(f); if (!lut_costs.empty()) { @@ -1099,7 +1092,7 @@ void abc_module(RTLIL::Design *design, RTLIL::Module *current_module, std::strin if (f == nullptr) log_error("Opening %s for writing failed: %s\n", buffer.c_str(), strerror(errno)); for (int i = 0; i < GetSize(lut_costs); i++) - fprintf(f, "%d %d.00 1.00\n", i+1, lut_costs.at(i)); + fprintf(f, "%d %d.00 1.00\n", i + 1, lut_costs.at(i)); fclose(f); } @@ -1149,7 +1142,7 @@ void abc_module(RTLIL::Design *design, RTLIL::Module *current_module, std::strin fclose(old_stderr); std::ifstream temp_stdouterr_r(temp_stdouterr_name); abc_output_filter filt(tempdir_name, show_tempdir); - for (std::string line; std::getline(temp_stdouterr_r, line); ) + for (std::string line; std::getline(temp_stdouterr_r, line);) filt.next_line(line + "\n"); temp_stdouterr_r.close(); #endif @@ -1177,7 +1170,8 @@ void abc_module(RTLIL::Design *design, RTLIL::Module *current_module, std::strin RTLIL::Wire *wire = module->addWire(remap_name(w->name, &orig_wire)); if (orig_wire != nullptr && orig_wire->attributes.count(ID::src)) wire->attributes[ID::src] = orig_wire->attributes[ID::src]; - if (markgroups) wire->attributes[ID::abcgroup] = map_autoidx; + if (markgroups) + wire->attributes[ID::abcgroup] = map_autoidx; design->select(module, wire); } @@ -1185,10 +1179,8 @@ void abc_module(RTLIL::Design *design, RTLIL::Module *current_module, std::strin FfInitVals mapped_initvals(&mapped_sigmap, mapped_mod); dict cell_stats; - for (auto c : mapped_mod->cells()) - { - if (builtin_lib) - { + for (auto c : mapped_mod->cells()) { + if (builtin_lib) { cell_stats[RTLIL::unescape_id(c->type)]++; if (c->type.in(ID(ZERO), ID(ONE))) { RTLIL::SigSig conn; @@ -1209,7 +1201,8 @@ void abc_module(RTLIL::Design *design, RTLIL::Module *current_module, std::strin } if (c->type == ID(NOT)) { RTLIL::Cell *cell = module->addCell(remap_name(c->name), ID($_NOT_)); - if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx; + if (markgroups) + cell->attributes[ID::abcgroup] = map_autoidx; for (auto name : {ID::A, ID::Y}) { RTLIL::IdString remapped_name = remap_name(c->getPort(name).as_wire()->name); cell->setPort(name, module->wire(remapped_name)); @@ -1218,8 +1211,9 @@ void abc_module(RTLIL::Design *design, RTLIL::Module *current_module, std::strin continue; } if (c->type.in(ID(AND), ID(OR), ID(XOR), ID(NAND), ID(NOR), ID(XNOR), ID(ANDNOT), ID(ORNOT))) { - RTLIL::Cell *cell = module->addCell(remap_name(c->name), stringf("$_%s_", c->type.c_str()+1)); - if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx; + RTLIL::Cell *cell = module->addCell(remap_name(c->name), stringf("$_%s_", c->type.c_str() + 1)); + if (markgroups) + cell->attributes[ID::abcgroup] = map_autoidx; for (auto name : {ID::A, ID::B, ID::Y}) { RTLIL::IdString remapped_name = remap_name(c->getPort(name).as_wire()->name); cell->setPort(name, module->wire(remapped_name)); @@ -1228,8 +1222,9 @@ void abc_module(RTLIL::Design *design, RTLIL::Module *current_module, std::strin continue; } if (c->type.in(ID(MUX), ID(NMUX))) { - RTLIL::Cell *cell = module->addCell(remap_name(c->name), stringf("$_%s_", c->type.c_str()+1)); - if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx; + RTLIL::Cell *cell = module->addCell(remap_name(c->name), stringf("$_%s_", c->type.c_str() + 1)); + if (markgroups) + cell->attributes[ID::abcgroup] = map_autoidx; for (auto name : {ID::A, ID::B, ID::S, ID::Y}) { RTLIL::IdString remapped_name = remap_name(c->getPort(name).as_wire()->name); cell->setPort(name, module->wire(remapped_name)); @@ -1239,7 +1234,8 @@ void abc_module(RTLIL::Design *design, RTLIL::Module *current_module, std::strin } if (c->type == ID(MUX4)) { RTLIL::Cell *cell = module->addCell(remap_name(c->name), ID($_MUX4_)); - if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx; + if (markgroups) + cell->attributes[ID::abcgroup] = map_autoidx; for (auto name : {ID::A, ID::B, ID::C, ID::D, ID::S, ID::T, ID::Y}) { RTLIL::IdString remapped_name = remap_name(c->getPort(name).as_wire()->name); cell->setPort(name, module->wire(remapped_name)); @@ -1249,7 +1245,8 @@ void abc_module(RTLIL::Design *design, RTLIL::Module *current_module, std::strin } if (c->type == ID(MUX8)) { RTLIL::Cell *cell = module->addCell(remap_name(c->name), ID($_MUX8_)); - if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx; + if (markgroups) + cell->attributes[ID::abcgroup] = map_autoidx; for (auto name : {ID::A, ID::B, ID::C, ID::D, ID::E, ID::F, ID::G, ID::H, ID::S, ID::T, ID::U, ID::Y}) { RTLIL::IdString remapped_name = remap_name(c->getPort(name).as_wire()->name); cell->setPort(name, module->wire(remapped_name)); @@ -1259,9 +1256,10 @@ void abc_module(RTLIL::Design *design, RTLIL::Module *current_module, std::strin } if (c->type == ID(MUX16)) { RTLIL::Cell *cell = module->addCell(remap_name(c->name), ID($_MUX16_)); - if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx; + if (markgroups) + cell->attributes[ID::abcgroup] = map_autoidx; for (auto name : {ID::A, ID::B, ID::C, ID::D, ID::E, ID::F, ID::G, ID::H, ID::I, ID::J, ID::K, - ID::L, ID::M, ID::N, ID::O, ID::P, ID::S, ID::T, ID::U, ID::V, ID::Y}) { + ID::L, ID::M, ID::N, ID::O, ID::P, ID::S, ID::T, ID::U, ID::V, ID::Y}) { RTLIL::IdString remapped_name = remap_name(c->getPort(name).as_wire()->name); cell->setPort(name, module->wire(remapped_name)); } @@ -1269,8 +1267,9 @@ void abc_module(RTLIL::Design *design, RTLIL::Module *current_module, std::strin continue; } if (c->type.in(ID(AOI3), ID(OAI3))) { - RTLIL::Cell *cell = module->addCell(remap_name(c->name), stringf("$_%s_", c->type.c_str()+1)); - if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx; + RTLIL::Cell *cell = module->addCell(remap_name(c->name), stringf("$_%s_", c->type.c_str() + 1)); + if (markgroups) + cell->attributes[ID::abcgroup] = map_autoidx; for (auto name : {ID::A, ID::B, ID::C, ID::Y}) { RTLIL::IdString remapped_name = remap_name(c->getPort(name).as_wire()->name); cell->setPort(name, module->wire(remapped_name)); @@ -1279,8 +1278,9 @@ void abc_module(RTLIL::Design *design, RTLIL::Module *current_module, std::strin continue; } if (c->type.in(ID(AOI4), ID(OAI4))) { - RTLIL::Cell *cell = module->addCell(remap_name(c->name), stringf("$_%s_", c->type.c_str()+1)); - if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx; + RTLIL::Cell *cell = module->addCell(remap_name(c->name), stringf("$_%s_", c->type.c_str() + 1)); + if (markgroups) + cell->attributes[ID::abcgroup] = map_autoidx; for (auto name : {ID::A, ID::B, ID::C, ID::D, ID::Y}) { RTLIL::IdString remapped_name = remap_name(c->getPort(name).as_wire()->name); cell->setPort(name, module->wire(remapped_name)); @@ -1324,12 +1324,12 @@ void abc_module(RTLIL::Design *design, RTLIL::Module *current_module, std::strin ff.sig_d = module->wire(remap_name(c->getPort(ID::D).as_wire()->name)); ff.sig_q = module->wire(remap_name(c->getPort(ID::Q).as_wire()->name)); RTLIL::Cell *cell = ff.emit(); - if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx; + if (markgroups) + cell->attributes[ID::abcgroup] = map_autoidx; design->select(module, cell); continue; } - } - else + } else cell_stats[RTLIL::unescape_id(c->type)]++; if (c->type.in(ID(_const0_), ID(_const1_))) { @@ -1373,7 +1373,8 @@ void abc_module(RTLIL::Design *design, RTLIL::Module *current_module, std::strin ff.sig_d = module->wire(remap_name(c->getPort(ID::D).as_wire()->name)); ff.sig_q = module->wire(remap_name(c->getPort(ID::Q).as_wire()->name)); RTLIL::Cell *cell = ff.emit(); - if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx; + if (markgroups) + cell->attributes[ID::abcgroup] = map_autoidx; design->select(module, cell); continue; } @@ -1386,7 +1387,8 @@ void abc_module(RTLIL::Design *design, RTLIL::Module *current_module, std::strin } RTLIL::Cell *cell = module->addCell(remap_name(c->name), c->type); - if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx; + if (markgroups) + cell->attributes[ID::abcgroup] = map_autoidx; cell->parameters = c->parameters; for (auto &conn : c->connections()) { RTLIL::SigSpec newsig; @@ -1433,14 +1435,11 @@ void abc_module(RTLIL::Design *design, RTLIL::Module *current_module, std::strin log("ABC RESULTS: output signals: %8d\n", out_wires); delete mapped_design; - } - else - { + } else { log("Don't call ABC as there is nothing to map.\n"); } - if (cleanup) - { + if (cleanup) { log("Removing temp directory.\n"); remove_directory(tempdir_name); } @@ -1449,7 +1448,7 @@ void abc_module(RTLIL::Design *design, RTLIL::Module *current_module, std::strin } struct AbcPass : public Pass { - AbcPass() : Pass("abc", "use ABC for technology mapping") { } + AbcPass() : Pass("abc", "use ABC for technology mapping") {} void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| @@ -1721,7 +1720,7 @@ struct AbcPass : public Pass { #if defined(__wasm) const char *pwd = "."; #else - char pwd [PATH_MAX]; + char pwd[PATH_MAX]; if (!getcwd(pwd, sizeof(pwd))) { log_cmd_error("getcwd failed: %s\n", strerror(errno)); log_abort(); @@ -1729,51 +1728,51 @@ struct AbcPass : public Pass { #endif for (argidx = 1; argidx < args.size(); argidx++) { std::string arg = args[argidx]; - if (arg == "-exe" && argidx+1 < args.size()) { + if (arg == "-exe" && argidx + 1 < args.size()) { exe_file = args[++argidx]; continue; } - if (arg == "-script" && argidx+1 < args.size()) { + if (arg == "-script" && argidx + 1 < args.size()) { script_file = args[++argidx]; continue; } - if (arg == "-liberty" && argidx+1 < args.size()) { + if (arg == "-liberty" && argidx + 1 < args.size()) { liberty_files.push_back(args[++argidx]); continue; } - if (arg == "-dont_use" && argidx+1 < args.size()) { + if (arg == "-dont_use" && argidx + 1 < args.size()) { dont_use_cells.push_back(args[++argidx]); continue; } - if (arg == "-genlib" && argidx+1 < args.size()) { + if (arg == "-genlib" && argidx + 1 < args.size()) { genlib_files.push_back(args[++argidx]); continue; } - if (arg == "-constr" && argidx+1 < args.size()) { + if (arg == "-constr" && argidx + 1 < args.size()) { constr_file = args[++argidx]; continue; } - if (arg == "-D" && argidx+1 < args.size()) { + if (arg == "-D" && argidx + 1 < args.size()) { delay_target = "-D " + args[++argidx]; continue; } - if (arg == "-I" && argidx+1 < args.size()) { + if (arg == "-I" && argidx + 1 < args.size()) { sop_inputs = "-I " + args[++argidx]; continue; } - if (arg == "-P" && argidx+1 < args.size()) { + if (arg == "-P" && argidx + 1 < args.size()) { sop_products = "-P " + args[++argidx]; continue; } - if (arg == "-S" && argidx+1 < args.size()) { + if (arg == "-S" && argidx + 1 < args.size()) { lutin_shared = "-S " + args[++argidx]; continue; } - if (arg == "-lut" && argidx+1 < args.size()) { + if (arg == "-lut" && argidx + 1 < args.size()) { lut_arg = args[++argidx]; continue; } - if (arg == "-luts" && argidx+1 < args.size()) { + if (arg == "-luts" && argidx + 1 < args.size()) { luts_arg = args[++argidx]; continue; } @@ -1797,7 +1796,7 @@ struct AbcPass : public Pass { abc_dress = true; continue; } - if (arg == "-g" && argidx+1 < args.size()) { + if (arg == "-g" && argidx + 1 < args.size()) { if (g_arg_from_cmd) log_cmd_error("Can only use -g once. Please combine."); g_arg = args[++argidx]; @@ -1813,7 +1812,7 @@ struct AbcPass : public Pass { dff_mode = true; continue; } - if (arg == "-clk" && argidx+1 < args.size()) { + if (arg == "-clk" && argidx + 1 < args.size()) { clk_str = args[++argidx]; dff_mode = true; continue; @@ -1864,7 +1863,7 @@ struct AbcPass : public Pass { int lut_mode = 0, lut_mode2 = 0; if (pos != string::npos) { lut_mode = atoi(lut_arg.substr(0, pos).c_str()); - lut_mode2 = atoi(lut_arg.substr(pos+1).c_str()); + lut_mode2 = atoi(lut_arg.substr(pos + 1).c_str()); } else { lut_mode = atoi(lut_arg.c_str()); lut_mode2 = lut_mode; @@ -1875,8 +1874,8 @@ struct AbcPass : public Pass { for (int i = lut_mode; i < lut_mode2; i++) lut_costs.push_back(2 << (i - lut_mode)); } - //handle -luts argument - if (!luts_arg.empty()){ + // handle -luts argument + if (!luts_arg.empty()) { lut_costs.clear(); for (auto &tok : split_tokens(luts_arg, ",")) { auto parts = split_tokens(tok, ":"); @@ -1893,7 +1892,7 @@ struct AbcPass : public Pass { } // handle -g argument - if (!g_arg.empty()){ + if (!g_arg.empty()) { for (auto g : split_tokens(g_arg, ",")) { vector gate_list; bool remove_gates = false; @@ -1901,20 +1900,34 @@ struct AbcPass : public Pass { remove_gates = true; g = g.substr(1); } - if (g == "AND") goto ok_gate; - if (g == "NAND") goto ok_gate; - if (g == "OR") goto ok_gate; - if (g == "NOR") goto ok_gate; - if (g == "XOR") goto ok_gate; - if (g == "XNOR") goto ok_gate; - if (g == "ANDNOT") goto ok_gate; - if (g == "ORNOT") goto ok_gate; - if (g == "MUX") goto ok_gate; - if (g == "NMUX") goto ok_gate; - if (g == "AOI3") goto ok_gate; - if (g == "OAI3") goto ok_gate; - if (g == "AOI4") goto ok_gate; - if (g == "OAI4") goto ok_gate; + if (g == "AND") + goto ok_gate; + if (g == "NAND") + goto ok_gate; + if (g == "OR") + goto ok_gate; + if (g == "NOR") + goto ok_gate; + if (g == "XOR") + goto ok_gate; + if (g == "XNOR") + goto ok_gate; + if (g == "ANDNOT") + goto ok_gate; + if (g == "ORNOT") + goto ok_gate; + if (g == "MUX") + goto ok_gate; + if (g == "NMUX") + goto ok_gate; + if (g == "AOI3") + goto ok_gate; + if (g == "OAI3") + goto ok_gate; + if (g == "AOI4") + goto ok_gate; + if (g == "OAI4") + goto ok_gate; if (g == "simple") { gate_list.push_back("AND"); gate_list.push_back("OR"); @@ -2039,8 +2052,7 @@ struct AbcPass : public Pass { // enabled_gates.insert("NMUX"); } - for (auto mod : design->selected_modules()) - { + for (auto mod : design->selected_modules()) { if (mod->processes.size() > 0) { log("Skipping module %s as it contains processes.\n", log_id(mod)); continue; @@ -2050,47 +2062,47 @@ struct AbcPass : public Pass { initvals.set(&assign_map, mod); if (!dff_mode || !clk_str.empty()) { - abc_module(design, mod, script_file, exe_file, liberty_files, genlib_files, constr_file, cleanup, lut_costs, dff_mode, clk_str, keepff, - delay_target, sop_inputs, sop_products, lutin_shared, fast_mode, mod->selected_cells(), show_tempdir, sop_mode, abc_dress, dont_use_cells); + abc_module(design, mod, script_file, exe_file, liberty_files, genlib_files, constr_file, cleanup, lut_costs, dff_mode, + clk_str, keepff, delay_target, sop_inputs, sop_products, lutin_shared, fast_mode, mod->selected_cells(), + show_tempdir, sop_mode, abc_dress, dont_use_cells); continue; } CellTypes ct(design); - std::vector all_cells = mod->selected_cells(); - pool unassigned_cells(all_cells.begin(), all_cells.end()); + std::vector all_cells = mod->selected_cells(); + pool unassigned_cells(all_cells.begin(), all_cells.end()); - pool expand_queue, next_expand_queue; - pool expand_queue_up, next_expand_queue_up; - pool expand_queue_down, next_expand_queue_down; + pool expand_queue, next_expand_queue; + pool expand_queue_up, next_expand_queue_up; + pool expand_queue_down, next_expand_queue_down; typedef tuple clkdomain_t; - dict> assigned_cells; - dict assigned_cells_reverse; + dict> assigned_cells; + dict assigned_cells_reverse; - dict> cell_to_bit, cell_to_bit_up, cell_to_bit_down; - dict> bit_to_cell, bit_to_cell_up, bit_to_cell_down; + dict> cell_to_bit, cell_to_bit_up, cell_to_bit_down; + dict> bit_to_cell, bit_to_cell_up, bit_to_cell_down; - for (auto cell : all_cells) - { + for (auto cell : all_cells) { clkdomain_t key; for (auto &conn : cell->connections()) - for (auto bit : conn.second) { - bit = assign_map(bit); - if (bit.wire != nullptr) { - cell_to_bit[cell].insert(bit); - bit_to_cell[bit].insert(cell); - if (ct.cell_input(cell->type, conn.first)) { - cell_to_bit_up[cell].insert(bit); - bit_to_cell_down[bit].insert(cell); - } - if (ct.cell_output(cell->type, conn.first)) { - cell_to_bit_down[cell].insert(bit); - bit_to_cell_up[bit].insert(cell); + for (auto bit : conn.second) { + bit = assign_map(bit); + if (bit.wire != nullptr) { + cell_to_bit[cell].insert(bit); + bit_to_cell[bit].insert(cell); + if (ct.cell_input(cell->type, conn.first)) { + cell_to_bit_up[cell].insert(bit); + bit_to_cell_down[bit].insert(cell); + } + if (ct.cell_output(cell->type, conn.first)) { + cell_to_bit_down[cell].insert(bit); + bit_to_cell_up[bit].insert(cell); + } } } - } if (!RTLIL::builtin_ff_cell_types().count(cell->type)) continue; @@ -2106,16 +2118,10 @@ struct AbcPass : public Pass { continue; if (!ff.is_fine) continue; - key = clkdomain_t( - ff.pol_clk, - ff.sig_clk, - ff.has_ce ? ff.pol_ce : true, - ff.has_ce ? assign_map(ff.sig_ce) : RTLIL::SigSpec(), - ff.has_arst ? ff.pol_arst : true, - ff.has_arst ? assign_map(ff.sig_arst) : RTLIL::SigSpec(), - ff.has_srst ? ff.pol_srst : true, - ff.has_srst ? assign_map(ff.sig_srst) : RTLIL::SigSpec() - ); + key = clkdomain_t(ff.pol_clk, ff.sig_clk, ff.has_ce ? ff.pol_ce : true, + ff.has_ce ? assign_map(ff.sig_ce) : RTLIL::SigSpec(), ff.has_arst ? ff.pol_arst : true, + ff.has_arst ? assign_map(ff.sig_arst) : RTLIL::SigSpec(), ff.has_srst ? ff.pol_srst : true, + ff.has_srst ? assign_map(ff.sig_srst) : RTLIL::SigSpec()); unassigned_cells.erase(cell); expand_queue.insert(cell); @@ -2126,40 +2132,37 @@ struct AbcPass : public Pass { assigned_cells_reverse[cell] = key; } - while (!expand_queue_up.empty() || !expand_queue_down.empty()) - { - if (!expand_queue_up.empty()) - { + while (!expand_queue_up.empty() || !expand_queue_down.empty()) { + if (!expand_queue_up.empty()) { RTLIL::Cell *cell = *expand_queue_up.begin(); clkdomain_t key = assigned_cells_reverse.at(cell); expand_queue_up.erase(cell); for (auto bit : cell_to_bit_up[cell]) - for (auto c : bit_to_cell_up[bit]) - if (unassigned_cells.count(c)) { - unassigned_cells.erase(c); - next_expand_queue_up.insert(c); - assigned_cells[key].push_back(c); - assigned_cells_reverse[c] = key; - expand_queue.insert(c); - } + for (auto c : bit_to_cell_up[bit]) + if (unassigned_cells.count(c)) { + unassigned_cells.erase(c); + next_expand_queue_up.insert(c); + assigned_cells[key].push_back(c); + assigned_cells_reverse[c] = key; + expand_queue.insert(c); + } } - if (!expand_queue_down.empty()) - { + if (!expand_queue_down.empty()) { RTLIL::Cell *cell = *expand_queue_down.begin(); clkdomain_t key = assigned_cells_reverse.at(cell); expand_queue_down.erase(cell); for (auto bit : cell_to_bit_down[cell]) - for (auto c : bit_to_cell_down[bit]) - if (unassigned_cells.count(c)) { - unassigned_cells.erase(c); - next_expand_queue_up.insert(c); - assigned_cells[key].push_back(c); - assigned_cells_reverse[c] = key; - expand_queue.insert(c); - } + for (auto c : bit_to_cell_down[bit]) + if (unassigned_cells.count(c)) { + unassigned_cells.erase(c); + next_expand_queue_up.insert(c); + assigned_cells[key].push_back(c); + assigned_cells_reverse[c] = key; + expand_queue.insert(c); + } } if (expand_queue_up.empty() && expand_queue_down.empty()) { @@ -2168,8 +2171,7 @@ struct AbcPass : public Pass { } } - while (!expand_queue.empty()) - { + while (!expand_queue.empty()) { RTLIL::Cell *cell = *expand_queue.begin(); clkdomain_t key = assigned_cells_reverse.at(cell); expand_queue.erase(cell); @@ -2197,11 +2199,10 @@ struct AbcPass : public Pass { log_header(design, "Summary of detected clock domains:\n"); for (auto &it : assigned_cells) - log(" %d cells in clk=%s%s, en=%s%s, arst=%s%s, srst=%s%s\n", GetSize(it.second), - std::get<0>(it.first) ? "" : "!", log_signal(std::get<1>(it.first)), - std::get<2>(it.first) ? "" : "!", log_signal(std::get<3>(it.first)), - std::get<4>(it.first) ? "" : "!", log_signal(std::get<5>(it.first)), - std::get<6>(it.first) ? "" : "!", log_signal(std::get<7>(it.first))); + log(" %d cells in clk=%s%s, en=%s%s, arst=%s%s, srst=%s%s\n", GetSize(it.second), std::get<0>(it.first) ? "" : "!", + log_signal(std::get<1>(it.first)), std::get<2>(it.first) ? "" : "!", log_signal(std::get<3>(it.first)), + std::get<4>(it.first) ? "" : "!", log_signal(std::get<5>(it.first)), std::get<6>(it.first) ? "" : "!", + log_signal(std::get<7>(it.first))); for (auto &it : assigned_cells) { clk_polarity = std::get<0>(it.first); @@ -2212,8 +2213,9 @@ struct AbcPass : public Pass { arst_sig = assign_map(std::get<5>(it.first)); srst_polarity = std::get<6>(it.first); srst_sig = assign_map(std::get<7>(it.first)); - abc_module(design, mod, script_file, exe_file, liberty_files, genlib_files, constr_file, cleanup, lut_costs, !clk_sig.empty(), "$", - keepff, delay_target, sop_inputs, sop_products, lutin_shared, fast_mode, it.second, show_tempdir, sop_mode, abc_dress, dont_use_cells); + abc_module(design, mod, script_file, exe_file, liberty_files, genlib_files, constr_file, cleanup, lut_costs, + !clk_sig.empty(), "$", keepff, delay_target, sop_inputs, sop_products, lutin_shared, fast_mode, it.second, + show_tempdir, sop_mode, abc_dress, dont_use_cells); assign_map.set(mod); } } diff --git a/passes/techmap/abc9.cc b/passes/techmap/abc9.cc index 876917e565e..43e6071fe3f 100644 --- a/passes/techmap/abc9.cc +++ b/passes/techmap/abc9.cc @@ -22,10 +22,10 @@ // Berkeley Logic Synthesis and Verification Group, ABC: A System for Sequential Synthesis and Verification // http://www.eecs.berkeley.edu/~alanmi/abc/ -#include "kernel/register.h" #include "kernel/celltypes.h" -#include "kernel/rtlil.h" #include "kernel/log.h" +#include "kernel/register.h" +#include "kernel/rtlil.h" // abc9_exe.cc std::string fold_abc9_cmd(std::string str); @@ -33,59 +33,47 @@ std::string fold_abc9_cmd(std::string str); USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN -struct Abc9Pass : public ScriptPass -{ - Abc9Pass() : ScriptPass("abc9", "use ABC9 for technology mapping") { } +struct Abc9Pass : public ScriptPass { + Abc9Pass() : ScriptPass("abc9", "use ABC9 for technology mapping") {} void on_register() override { RTLIL::constpad["abc9.script.default"] = "+&scorr; &sweep; &dc2; &dch -f; &ps; &if {C} {W} {D} {R} -v; &mfs"; RTLIL::constpad["abc9.script.default.area"] = "+&scorr; &sweep; &dc2; &dch -f; &ps; &if {C} {W} {D} {R} -a -v; &mfs"; RTLIL::constpad["abc9.script.default.fast"] = "+&if {C} {W} {D} {R} -v"; // Based on ABC's &flow - RTLIL::constpad["abc9.script.flow"] = "+&scorr; &sweep;" \ - "&dch -C 500;" \ - /* Round 1 */ \ - /* Map 1 */ "&unmap; &if {C} {W} {D} {R} -v; &save; &load; &mfs;" \ - "&st; &dsdb;" \ - /* Map 2 */ "&unmap; &if {C} {W} {D} {R} -v; &save; &load; &mfs;" \ - "&st; &syn2 -m -R 10; &dsdb;" \ - "&blut -a -K 6;" \ - /* Map 3 */ "&unmap; &if {C} {W} {D} {R} -v; &save; &load; &mfs;" \ - /* Round 2 */ \ - "&st; &sopb;" \ - /* Map 1 */ "&unmap; &if {C} {W} {D} {R} -v; &save; &load; &mfs;" \ - "&st; &dsdb;" \ - /* Map 2 */ "&unmap; &if {C} {W} {D} {R} -v; &save; &load; &mfs;" \ - "&st; &syn2 -m -R 10; &dsdb;" \ - "&blut -a -K 6;" \ - /* Map 3 */ "&unmap; &if {C} {W} {D} {R} -v; &save; &load; &mfs;" \ - /* Round 3 */ \ - /* Map 1 */ "&unmap; &if {C} {W} {D} {R} -v; &save; &load; &mfs;" \ - "&st; &dsdb;" \ - /* Map 2 */ "&unmap; &if {C} {W} {D} {R} -v; &save; &load; &mfs;" \ - "&st; &syn2 -m -R 10; &dsdb;" \ - "&blut -a -K 6;" \ - /* Map 3 */ "&unmap; &if {C} {W} {D} {R} -v; &save; &load; &mfs;"; + RTLIL::constpad["abc9.script.flow"] = "+&scorr; &sweep;" + "&dch -C 500;" /* Round 1 */ /* Map 1 */ "&unmap; &if {C} {W} {D} {R} -v; &save; &load; &mfs;" + "&st; &dsdb;" /* Map 2 */ "&unmap; &if {C} {W} {D} {R} -v; &save; &load; &mfs;" + "&st; &syn2 -m -R 10; &dsdb;" + "&blut -a -K 6;" /* Map 3 */ "&unmap; &if {C} {W} {D} {R} -v; &save; &load; &mfs;" /* Round 2 */ + "&st; &sopb;" /* Map 1 */ "&unmap; &if {C} {W} {D} {R} -v; &save; &load; &mfs;" + "&st; &dsdb;" /* Map 2 */ "&unmap; &if {C} {W} {D} {R} -v; &save; &load; &mfs;" + "&st; &syn2 -m -R 10; &dsdb;" + "&blut -a -K 6;" /* Map 3 */ "&unmap; &if {C} {W} {D} {R} -v; &save; &load; &mfs;" /* Round 3 */ + /* Map 1 */ "&unmap; &if {C} {W} {D} {R} -v; &save; &load; &mfs;" + "&st; &dsdb;" /* Map 2 */ "&unmap; &if {C} {W} {D} {R} -v; &save; &load; &mfs;" + "&st; &syn2 -m -R 10; &dsdb;" + "&blut -a -K 6;" /* Map 3 */ "&unmap; &if {C} {W} {D} {R} -v; &save; &load; &mfs;"; // Based on ABC's &flow2 - RTLIL::constpad["abc9.script.flow2"] = "+&scorr; &sweep;" \ - /* Comm1 */ "&synch2 -K 6 -C 500; &if -m {C} {W} {D} {R} -v; &mfs "/*"-W 4 -M 500 -C 7000"*/"; &save;"\ - /* Comm2 */ "&dch -C 500; &if -m {C} {W} {D} {R} -v; &mfs "/*"-W 4 -M 500 -C 7000"*/"; &save;"\ - "&load; &st; &sopb -R 10 -C 4; " \ - /* Comm3 */ "&synch2 -K 6 -C 500; &if -m "/*"-E 5"*/" {C} {W} {D} {R} -v; &mfs "/*"-W 4 -M 500 -C 7000"*/"; &save;"\ - /* Comm2 */ "&dch -C 500; &if -m {C} {W} {D} {R} -v; &mfs "/*"-W 4 -M 500 -C 7000"*/"; &save; "\ - "&load"; + RTLIL::constpad["abc9.script.flow2"] = + "+&scorr; &sweep;" /* Comm1 */ "&synch2 -K 6 -C 500; &if -m {C} {W} {D} {R} -v; &mfs " /*"-W 4 -M 500 -C 7000"*/ + "; &save;" /* Comm2 */ "&dch -C 500; &if -m {C} {W} {D} {R} -v; &mfs " /*"-W 4 -M 500 -C 7000"*/ "; &save;" + "&load; &st; &sopb -R 10 -C 4; " /* Comm3 */ "&synch2 -K 6 -C 500; &if -m " /*"-E 5"*/ " {C} {W} {D} {R} -v; &mfs " /*"-W 4 -M 500 + -C 7000"*/ + "; &save;" /* Comm2 */ "&dch -C 500; &if -m {C} {W} {D} {R} -v; &mfs " /*"-W 4 -M 500 -C 7000"*/ "; &save; " + "&load"; // Based on ABC's &flow3 -m - RTLIL::constpad["abc9.script.flow3"] = "+&scorr; &sweep;" \ - "&if {C} {W} {D}; &save; &st; &syn2; &if {C} {W} {D} {R} -v; &save; &load;"\ - "&st; &if {C} -g -K 6; &dch -f; &if {C} {W} {D} {R} -v; &save; &load;"\ - "&st; &if {C} -g -K 6; &synch2; &if {C} {W} {D} {R} -v; &save; &load;"\ - "&mfs"; + RTLIL::constpad["abc9.script.flow3"] = "+&scorr; &sweep;" + "&if {C} {W} {D}; &save; &st; &syn2; &if {C} {W} {D} {R} -v; &save; &load;" + "&st; &if {C} -g -K 6; &dch -f; &if {C} {W} {D} {R} -v; &save; &load;" + "&st; &if {C} -g -K 6; &synch2; &if {C} {W} {D} {R} -v; &save; &load;" + "&mfs"; // As above, but with &mfs calls as in the original &flow3 - RTLIL::constpad["abc9.script.flow3mfs"] = "+&scorr; &sweep;" \ - "&if {C} {W} {D}; &save; &st; &syn2; &if {C} {W} {D} {R} -v; &save; &load;"\ - "&st; &if {C} -g -K 6; &dch -f; &if {C} {W} {D} {R} -v; &mfs; &save; &load;"\ - "&st; &if {C} -g -K 6; &synch2; &if {C} {W} {D} {R} -v; &mfs; &save; &load;"\ - "&mfs"; + RTLIL::constpad["abc9.script.flow3mfs"] = "+&scorr; &sweep;" + "&if {C} {W} {D}; &save; &st; &syn2; &if {C} {W} {D} {R} -v; &save; &load;" + "&st; &if {C} -g -K 6; &dch -f; &if {C} {W} {D} {R} -v; &mfs; &save; &load;" + "&st; &if {C} -g -K 6; &synch2; &if {C} {W} {D} {R} -v; &mfs; &save; &load;" + "&mfs"; } void help() override { @@ -119,22 +107,22 @@ struct Abc9Pass : public ScriptPass log(" replaced with blanks before the string is passed to ABC.\n"); log("\n"); log(" if no -script parameter is given, the following scripts are used:\n"); - log("%s\n", fold_abc9_cmd(RTLIL::constpad.at("abc9.script.default").substr(1,std::string::npos)).c_str()); + log("%s\n", fold_abc9_cmd(RTLIL::constpad.at("abc9.script.default").substr(1, std::string::npos)).c_str()); log("\n"); log(" -fast\n"); log(" use different default scripts that are slightly faster (at the cost\n"); log(" of output quality):\n"); - log("%s\n", fold_abc9_cmd(RTLIL::constpad.at("abc9.script.default.fast").substr(1,std::string::npos)).c_str()); + log("%s\n", fold_abc9_cmd(RTLIL::constpad.at("abc9.script.default.fast").substr(1, std::string::npos)).c_str()); log("\n"); log(" -D \n"); log(" set delay target. the string {D} in the default scripts above is\n"); log(" replaced by this option when used, and an empty string otherwise\n"); log(" (indicating best possible delay).\n"); log("\n"); -// log(" -S \n"); -// log(" maximum number of LUT inputs shared.\n"); -// log(" (replaces {S} in the default scripts above, default: -S 1)\n"); -// log("\n"); + // log(" -S \n"); + // log(" maximum number of LUT inputs shared.\n"); + // log(" (replaces {S} in the default scripts above, default: -S 1)\n"); + // log("\n"); log(" -lut \n"); log(" generate netlist using luts of (max) the specified width.\n"); log("\n"); @@ -219,16 +207,16 @@ struct Abc9Pass : public ScriptPass for (argidx = 1; argidx < args.size(); argidx++) { std::string arg = args[argidx]; if ((arg == "-exe" || arg == "-script" || arg == "-D" || - /*arg == "-S" ||*/ arg == "-lut" || arg == "-luts" || - /*arg == "-box" ||*/ arg == "-W") && - argidx+1 < args.size()) { + /*arg == "-S" ||*/ arg == "-lut" || arg == "-luts" || + /*arg == "-box" ||*/ arg == "-W") && + argidx + 1 < args.size()) { if (arg == "-lut" || arg == "-luts") lut_mode = true; exe_cmd << " " << arg << " " << args[++argidx]; continue; } if (arg == "-fast" || /* arg == "-dff" || */ - /* arg == "-nocleanup" || */ arg == "-showtmp") { + /* arg == "-nocleanup" || */ arg == "-showtmp") { exe_cmd << " " << arg; continue; } @@ -241,20 +229,20 @@ struct Abc9Pass : public ScriptPass cleanup = false; continue; } - if (arg == "-box" && argidx+1 < args.size()) { + if (arg == "-box" && argidx + 1 < args.size()) { box_file = args[++argidx]; continue; } - if (arg == "-maxlut" && argidx+1 < args.size()) { + if (arg == "-maxlut" && argidx + 1 < args.size()) { maxlut = atoi(args[++argidx].c_str()); continue; } - if (arg == "-run" && argidx+1 < args.size()) { - size_t pos = args[argidx+1].find(':'); + if (arg == "-run" && argidx + 1 < args.size()) { + size_t pos = args[argidx + 1].find(':'); if (pos == std::string::npos) break; run_from = args[++argidx].substr(0, pos); - run_to = args[argidx].substr(pos+1); + run_to = args[argidx].substr(pos + 1); continue; } break; @@ -312,21 +300,21 @@ struct Abc9Pass : public ScriptPass if (dff_mode || help_mode) { if (!help_mode) active_design->scratchpad_unset("abc9_ops.prep_dff_submod.did_something"); - run("abc9_ops -prep_dff_submod", " (only if -dff)"); // rewrite specify + run("abc9_ops -prep_dff_submod", + " (only if -dff)"); // rewrite specify bool did_something = help_mode || active_design->scratchpad_get_bool("abc9_ops.prep_dff_submod.did_something"); if (did_something) { - // select all $_DFF_[NP]_ - // then select all its fanins - // then select all fanouts of all that - // lastly remove $_DFF_[NP]_ cells + // select all $_DFF_[NP]_ + // then select all its fanins + // then select all fanouts of all that + // lastly remove $_DFF_[NP]_ cells run("setattr -set submod \"$abc9_flop\" t:$_DFF_?_ %ci* %co* t:$_DFF_?_ %d", " (only if -dff)"); run("submod", " (only if -dff)"); run("setattr -mod -set whitebox 1 -set abc9_flop 1 -set abc9_box 1 *_$abc9_flop", "(only if -dff)"); if (help_mode) { run("foreach module in design"); run(" rename _$abc9_flop _TECHMAP_REPLACE_", " (only if -dff)"); - } - else { + } else { // Rename all submod-s to _TECHMAP_REPLACE_ to inherit name + attrs for (auto module : active_design->selected_modules()) { active_design->selected_active_module = module->name.str(); @@ -336,7 +324,8 @@ struct Abc9Pass : public ScriptPass active_design->selected_active_module.clear(); } run("abc9_ops -prep_dff_unmap", " (only if -dff)"); - run("design -copy-to $abc9 =*_$abc9_flop", " (only if -dff)"); // copy submod out + run("design -copy-to $abc9 =*_$abc9_flop", + " (only if -dff)"); // copy submod out run("delete =*_$abc9_flop", " (only if -dff)"); } } @@ -347,7 +336,8 @@ struct Abc9Pass : public ScriptPass if (help_mode) run("techmap -wb -max_iter 1 -map %$abc9_map -map +/abc9_map.v [-D DFF]", "(option if -dff)"); else - run(stringf("techmap -wb -max_iter 1 -map %%$abc9_map -map +/abc9_map.v %s a:abc9_scc_id %%n", dff_mode ? "-D DFF" : "")); + run(stringf("techmap -wb -max_iter 1 -map %%$abc9_map -map +/abc9_map.v %s a:abc9_scc_id %%n", + dff_mode ? "-D DFF" : "")); run("design -delete $abc9_map"); } @@ -385,10 +375,10 @@ struct Abc9Pass : public ScriptPass run(" abc9_ops -write_box /input.box", "(skip if '-box')"); run(" write_xaiger -map /input.sym [-dff] /input.xaig"); run(" abc9_exe [options] -cwd -lut [/input.lut] -box [/input.box]"); - run(" read_aiger -xaiger -wideports -module_name $abc9 -map /input.sym /output.aig"); + run(" read_aiger -xaiger -wideports -module_name $abc9 -map /input.sym " + "/output.aig"); run(" abc9_ops -reintegrate [-dff]"); - } - else { + } else { auto selected_modules = active_design->selected_modules(); active_design->selection_stack.emplace_back(false); @@ -405,7 +395,7 @@ struct Abc9Pass : public ScriptPass log_error("Can't handle partially selected module %s!\n", log_id(mod)); std::string tempdir_name; - if (cleanup) + if (cleanup) tempdir_name = get_base_tmpdir() + "/"; else tempdir_name = "_tmp_"; @@ -416,16 +406,16 @@ struct Abc9Pass : public ScriptPass run_nocheck(stringf("abc9_ops -write_lut %s/input.lut", tempdir_name.c_str())); if (box_file.empty()) run_nocheck(stringf("abc9_ops -write_box %s/input.box", tempdir_name.c_str())); - run_nocheck(stringf("write_xaiger -map %s/input.sym %s %s/input.xaig", tempdir_name.c_str(), dff_mode ? "-dff" : "", tempdir_name.c_str())); + run_nocheck(stringf("write_xaiger -map %s/input.sym %s %s/input.xaig", tempdir_name.c_str(), + dff_mode ? "-dff" : "", tempdir_name.c_str())); int num_outputs = active_design->scratchpad_get_int("write_xaiger.num_outputs"); - log("Extracted %d AND gates and %d wires from module `%s' to a netlist network with %d inputs and %d outputs.\n", - active_design->scratchpad_get_int("write_xaiger.num_ands"), - active_design->scratchpad_get_int("write_xaiger.num_wires"), - log_id(mod), - active_design->scratchpad_get_int("write_xaiger.num_inputs"), - num_outputs); + log("Extracted %d AND gates and %d wires from module `%s' to a netlist network with %d inputs and %d " + "outputs.\n", + active_design->scratchpad_get_int("write_xaiger.num_ands"), + active_design->scratchpad_get_int("write_xaiger.num_wires"), log_id(mod), + active_design->scratchpad_get_int("write_xaiger.num_inputs"), num_outputs); if (num_outputs) { std::string abc9_exe_cmd; abc9_exe_cmd += stringf("%s -cwd %s", exe_cmd.str().c_str(), tempdir_name.c_str()); @@ -436,10 +426,11 @@ struct Abc9Pass : public ScriptPass else abc9_exe_cmd += stringf(" -box %s", box_file.c_str()); run_nocheck(abc9_exe_cmd); - run_nocheck(stringf("read_aiger -xaiger -wideports -module_name %s$abc9 -map %s/input.sym %s/output.aig", log_id(mod), tempdir_name.c_str(), tempdir_name.c_str())); + run_nocheck( + stringf("read_aiger -xaiger -wideports -module_name %s$abc9 -map %s/input.sym %s/output.aig", + log_id(mod), tempdir_name.c_str(), tempdir_name.c_str())); run_nocheck(stringf("abc9_ops -reintegrate %s", dff_mode ? "-dff" : "")); - } - else + } else log("Don't call ABC as there is nothing to map.\n"); if (cleanup) { @@ -456,8 +447,8 @@ struct Abc9Pass : public ScriptPass } if (check_label("unmap")) { - run("techmap -wb -map %$abc9_unmap -map +/abc9_unmap.v"); // techmap user design from submod back to original cell - // ($_DFF_[NP]_ already shorted by -reintegrate) + run("techmap -wb -map %$abc9_unmap -map +/abc9_unmap.v"); // techmap user design from submod back to original cell + // ($_DFF_[NP]_ already shorted by -reintegrate) run("design -delete $abc9_unmap"); if (saved_designs.count("$abc9_holes") || help_mode) run("design -delete $abc9_holes"); diff --git a/passes/techmap/abc9_exe.cc b/passes/techmap/abc9_exe.cc index 8e02e25a4bf..b01770e614a 100644 --- a/passes/techmap/abc9_exe.cc +++ b/passes/techmap/abc9_exe.cc @@ -22,17 +22,18 @@ // Berkeley Logic Synthesis and Verification Group, ABC: A System for Sequential Synthesis and Verification // http://www.eecs.berkeley.edu/~alanmi/abc/ -#include "kernel/register.h" #include "kernel/log.h" +#include "kernel/register.h" #ifndef _WIN32 -# include -# include +#include +#include #endif #ifdef YOSYS_LINK_ABC -namespace abc { - int Abc_RealMain(int argc, char *argv[]); +namespace abc +{ +int Abc_RealMain(int argc, char *argv[]); } #endif @@ -64,7 +65,7 @@ std::string add_echos_to_abc9_cmd(std::string str) for (size_t i = 0; i < str.size(); i++) { token += str[i]; if (str[i] == ';') { - while (i+1 < str.size() && str[i+1] == ' ') + while (i + 1 < str.size() && str[i + 1] == ' ') i++; new_str += "echo + " + token + " " + token + " "; token.clear(); @@ -92,7 +93,7 @@ std::string replace_tempdir(std::string text, std::string tempdir_name, bool sho text = text.substr(0, pos) + "" + text.substr(pos + GetSize(tempdir_name)); } - std::string selfdir_name = proc_self_dirname(); + std::string selfdir_name = proc_self_dirname(); if (selfdir_name != "/") { while (1) { size_t pos = text.find(selfdir_name); @@ -105,8 +106,7 @@ std::string replace_tempdir(std::string text, std::string tempdir_name, bool sho return text; } -struct abc9_output_filter -{ +struct abc9_output_filter { bool got_cr; int escape_seq_state; std::string linebuf; @@ -151,24 +151,22 @@ struct abc9_output_filter void next_line(const std::string &line) { - //int pi, po; - //if (sscanf(line.c_str(), "Start-point = pi%d. End-point = po%d.", &pi, &po) == 2) { + // int pi, po; + // if (sscanf(line.c_str(), "Start-point = pi%d. End-point = po%d.", &pi, &po) == 2) { // log("ABC: Start-point = pi%d (%s). End-point = po%d (%s).\n", // pi, pi_map.count(pi) ? pi_map.at(pi).c_str() : "???", // po, po_map.count(po) ? po_map.at(po).c_str() : "???"); // return; - //} + // } for (char ch : line) next_char(ch); } }; -void abc9_module(RTLIL::Design *design, std::string script_file, std::string exe_file, - vector lut_costs, bool dff_mode, std::string delay_target, std::string /*lutin_shared*/, bool fast_mode, - bool show_tempdir, std::string box_file, std::string lut_file, - std::string wire_delay, std::string tempdir_name -) +void abc9_module(RTLIL::Design *design, std::string script_file, std::string exe_file, vector lut_costs, bool dff_mode, std::string delay_target, + std::string /*lutin_shared*/, bool fast_mode, bool show_tempdir, std::string box_file, std::string lut_file, std::string wire_delay, + std::string tempdir_name) { std::string abc9_script; @@ -195,31 +193,31 @@ void abc9_module(RTLIL::Design *design, std::string script_file, std::string exe } else abc9_script += stringf("source %s", script_file.c_str()); } else if (!lut_costs.empty() || !lut_file.empty()) { - abc9_script += fast_mode ? RTLIL::constpad.at("abc9.script.default.fast").substr(1,std::string::npos) - : RTLIL::constpad.at("abc9.script.default").substr(1,std::string::npos); + abc9_script += fast_mode ? RTLIL::constpad.at("abc9.script.default.fast").substr(1, std::string::npos) + : RTLIL::constpad.at("abc9.script.default").substr(1, std::string::npos); } else log_abort(); for (size_t pos = abc9_script.find("{D}"); pos != std::string::npos; pos = abc9_script.find("{D}", pos)) - abc9_script = abc9_script.substr(0, pos) + delay_target + abc9_script.substr(pos+3); + abc9_script = abc9_script.substr(0, pos) + delay_target + abc9_script.substr(pos + 3); - //for (size_t pos = abc9_script.find("{S}"); pos != std::string::npos; pos = abc9_script.find("{S}", pos)) + // for (size_t pos = abc9_script.find("{S}"); pos != std::string::npos; pos = abc9_script.find("{S}", pos)) // abc9_script = abc9_script.substr(0, pos) + lutin_shared + abc9_script.substr(pos+3); for (size_t pos = abc9_script.find("{W}"); pos != std::string::npos; pos = abc9_script.find("{W}", pos)) - abc9_script = abc9_script.substr(0, pos) + wire_delay + abc9_script.substr(pos+3); + abc9_script = abc9_script.substr(0, pos) + wire_delay + abc9_script.substr(pos + 3); std::string C; if (design->scratchpad.count("abc9.if.C")) C = "-C " + design->scratchpad_get_string("abc9.if.C"); for (size_t pos = abc9_script.find("{C}"); pos != std::string::npos; pos = abc9_script.find("{C}", pos)) - abc9_script = abc9_script.substr(0, pos) + C + abc9_script.substr(pos+3); + abc9_script = abc9_script.substr(0, pos) + C + abc9_script.substr(pos + 3); std::string R; if (design->scratchpad.count("abc9.if.R")) R = "-R " + design->scratchpad_get_string("abc9.if.R"); for (size_t pos = abc9_script.find("{R}"); pos != std::string::npos; pos = abc9_script.find("{R}", pos)) - abc9_script = abc9_script.substr(0, pos) + R + abc9_script.substr(pos+3); + abc9_script = abc9_script.substr(0, pos) + R + abc9_script.substr(pos + 3); if (design->scratchpad_get_bool("abc9.nomfs")) for (size_t pos = abc9_script.find("&mfs"); pos != std::string::npos; pos = abc9_script.find("&mfs", pos)) @@ -242,9 +240,9 @@ void abc9_module(RTLIL::Design *design, std::string script_file, std::string exe abc9_script += "; time"; abc9_script = add_echos_to_abc9_cmd(abc9_script); - for (size_t i = 0; i+1 < abc9_script.size(); i++) - if (abc9_script[i] == ';' && abc9_script[i+1] == ' ') - abc9_script[i+1] = '\n'; + for (size_t i = 0; i + 1 < abc9_script.size(); i++) + if (abc9_script[i] == ';' && abc9_script[i + 1] == ' ') + abc9_script[i + 1] = '\n'; FILE *f = fopen(stringf("%s/abc.script", tempdir_name.c_str()).c_str(), "wt"); fprintf(f, "%s\n", abc9_script.c_str()); @@ -260,7 +258,7 @@ void abc9_module(RTLIL::Design *design, std::string script_file, std::string exe if (f == NULL) log_error("Opening %s for writing failed: %s\n", buffer.c_str(), strerror(errno)); for (int i = 0; i < GetSize(lut_costs); i++) - fprintf(f, "%d %d.00 1.00\n", i+1, lut_costs.at(i)); + fprintf(f, "%d %d.00 1.00\n", i + 1, lut_costs.at(i)); fclose(f); } @@ -310,7 +308,7 @@ void abc9_module(RTLIL::Design *design, std::string script_file, std::string exe fclose(old_stderr); std::ifstream temp_stdouterr_r(temp_stdouterr_name); abc9_output_filter filt(tempdir_name, show_tempdir); - for (std::string line; std::getline(temp_stdouterr_r, line); ) + for (std::string line; std::getline(temp_stdouterr_r, line);) filt.next_line(line + "\n"); temp_stdouterr_r.close(); #endif @@ -323,7 +321,7 @@ void abc9_module(RTLIL::Design *design, std::string script_file, std::string exe } struct Abc9ExePass : public Pass { - Abc9ExePass() : Pass("abc9_exe", "use ABC9 for technology mapping") { } + Abc9ExePass() : Pass("abc9_exe", "use ABC9 for technology mapping") {} void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| @@ -352,22 +350,22 @@ struct Abc9ExePass : public Pass { log(" replaced with blanks before the string is passed to ABC.\n"); log("\n"); log(" if no -script parameter is given, the following scripts are used:\n"); - log("%s\n", fold_abc9_cmd(RTLIL::constpad.at("abc9.script.default").substr(1,std::string::npos)).c_str()); + log("%s\n", fold_abc9_cmd(RTLIL::constpad.at("abc9.script.default").substr(1, std::string::npos)).c_str()); log("\n"); log(" -fast\n"); log(" use different default scripts that are slightly faster (at the cost\n"); log(" of output quality):\n"); - log("%s\n", fold_abc9_cmd(RTLIL::constpad.at("abc9.script.default.fast").substr(1,std::string::npos)).c_str()); + log("%s\n", fold_abc9_cmd(RTLIL::constpad.at("abc9.script.default.fast").substr(1, std::string::npos)).c_str()); log("\n"); log(" -D \n"); log(" set delay target. the string {D} in the default scripts above is\n"); log(" replaced by this option when used, and an empty string otherwise\n"); log(" (indicating best possible delay).\n"); log("\n"); -// log(" -S \n"); -// log(" maximum number of LUT inputs shared.\n"); -// log(" (replaces {S} in the default scripts above, default: -S 1)\n"); -// log("\n"); + // log(" -S \n"); + // log(" maximum number of LUT inputs shared.\n"); + // log(" (replaces {S} in the default scripts above, default: -S 1)\n"); + // log("\n"); log(" -lut \n"); log(" generate netlist using luts of (max) the specified width.\n"); log("\n"); @@ -443,7 +441,7 @@ struct Abc9ExePass : public Pass { #if defined(__wasm) const char *pwd = "."; #else - char pwd [PATH_MAX]; + char pwd[PATH_MAX]; if (!getcwd(pwd, sizeof(pwd))) { log_cmd_error("getcwd failed: %s\n", strerror(errno)); log_abort(); @@ -451,27 +449,27 @@ struct Abc9ExePass : public Pass { #endif for (argidx = 1; argidx < args.size(); argidx++) { std::string arg = args[argidx]; - if (arg == "-exe" && argidx+1 < args.size()) { + if (arg == "-exe" && argidx + 1 < args.size()) { exe_file = args[++argidx]; continue; } - if (arg == "-script" && argidx+1 < args.size()) { + if (arg == "-script" && argidx + 1 < args.size()) { script_file = args[++argidx]; continue; } - if (arg == "-D" && argidx+1 < args.size()) { + if (arg == "-D" && argidx + 1 < args.size()) { delay_target = "-D " + args[++argidx]; continue; } - //if (arg == "-S" && argidx+1 < args.size()) { + // if (arg == "-S" && argidx+1 < args.size()) { // lutin_shared = "-S " + args[++argidx]; // continue; - //} - if (arg == "-lut" && argidx+1 < args.size()) { + // } + if (arg == "-lut" && argidx + 1 < args.size()) { lut_arg = args[++argidx]; continue; } - if (arg == "-luts" && argidx+1 < args.size()) { + if (arg == "-luts" && argidx + 1 < args.size()) { lut_arg = args[++argidx]; continue; } @@ -487,15 +485,15 @@ struct Abc9ExePass : public Pass { show_tempdir = true; continue; } - if (arg == "-box" && argidx+1 < args.size()) { + if (arg == "-box" && argidx + 1 < args.size()) { box_file = args[++argidx]; continue; } - if (arg == "-W" && argidx+1 < args.size()) { + if (arg == "-W" && argidx + 1 < args.size()) { wire_delay = "-W " + args[++argidx]; continue; } - if (arg == "-cwd" && argidx+1 < args.size()) { + if (arg == "-cwd" && argidx + 1 < args.size()) { tempdir_name = args[++argidx]; continue; } @@ -515,7 +513,7 @@ struct Abc9ExePass : public Pass { int lut_mode = 0, lut_mode2 = 0; if (pos != string::npos) { lut_mode = atoi(arg.substr(0, pos).c_str()); - lut_mode2 = atoi(arg.substr(pos+1).c_str()); + lut_mode2 = atoi(arg.substr(pos + 1).c_str()); } else { lut_mode = atoi(arg.c_str()); lut_mode2 = lut_mode; @@ -525,8 +523,7 @@ struct Abc9ExePass : public Pass { lut_costs.push_back(1); for (int i = lut_mode; i < lut_mode2; i++) lut_costs.push_back(2 << (i - lut_mode)); - } - else { + } else { lut_file = arg; rewrite_filename(lut_file); if (!lut_file.empty() && !is_absolute_path(lut_file) && lut_file[0] != '+') @@ -559,10 +556,8 @@ struct Abc9ExePass : public Pass { if (tempdir_name.empty()) log_cmd_error("abc9_exe '-cwd' option is mandatory.\n"); - - abc9_module(design, script_file, exe_file, lut_costs, dff_mode, - delay_target, lutin_shared, fast_mode, show_tempdir, - box_file, lut_file, wire_delay, tempdir_name); + abc9_module(design, script_file, exe_file, lut_costs, dff_mode, delay_target, lutin_shared, fast_mode, show_tempdir, box_file, + lut_file, wire_delay, tempdir_name); } } Abc9ExePass; diff --git a/passes/techmap/abc9_ops.cc b/passes/techmap/abc9_ops.cc index 4eaed1f75dc..0266df0905f 100644 --- a/passes/techmap/abc9_ops.cc +++ b/passes/techmap/abc9_ops.cc @@ -18,25 +18,22 @@ * */ +#include "kernel/celltypes.h" #include "kernel/register.h" #include "kernel/sigtools.h" -#include "kernel/utils.h" -#include "kernel/celltypes.h" #include "kernel/timinginfo.h" +#include "kernel/utils.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN int map_autoidx; -inline std::string remap_name(RTLIL::IdString abc9_name) -{ - return stringf("$abc$%d$%s", map_autoidx, abc9_name.c_str()+1); -} +inline std::string remap_name(RTLIL::IdString abc9_name) { return stringf("$abc$%d$%s", map_autoidx, abc9_name.c_str() + 1); } void check(RTLIL::Design *design, bool dff_mode) { - dict box_lookup; + dict box_lookup; for (auto m : design->modules()) { auto flop = m->get_bool_attribute(ID::abc9_flop); auto it = m->attributes.find(ID::abc9_box_id); @@ -46,8 +43,7 @@ void check(RTLIL::Design *design, bool dff_mode) auto id = it->second.as_int(); auto r = box_lookup.insert(std::make_pair(stringf("$__boxid%d", id), m->name)); if (!r.second) - log_error("Module '%s' has the same abc9_box_id = %d value as '%s'.\n", - log_id(m), id, log_id(r.first->second)); + log_error("Module '%s' has the same abc9_box_id = %d value as '%s'.\n", log_id(m), id, log_id(r.first->second)); } // Make carry in the last PI, and carry out the last PO @@ -79,7 +75,8 @@ void check(RTLIL::Design *design, bool dff_mode) int num_outputs = 0; for (auto port_name : m->ports) { auto wire = m->wire(port_name); - if (wire->port_output) num_outputs++; + if (wire->port_output) + num_outputs++; } if (num_outputs != 1) log_error("Module '%s' with (* abc9_flop *) has %d outputs (expect 1).\n", log_id(m), num_outputs); @@ -87,15 +84,13 @@ void check(RTLIL::Design *design, bool dff_mode) } if (dff_mode) { - static pool unsupported{ - ID($adff), ID($dlatch), ID($dlatchsr), ID($sr), - ID($_DFF_NN0_), ID($_DFF_NN1_), ID($_DFF_NP0_), ID($_DFF_NP1_), - ID($_DFF_PN0_), ID($_DFF_PN1_), ID($_DFF_PP0_), ID($_DFF_PP1_), - ID($_DLATCH_N_), ID($_DLATCH_P_), - ID($_DLATCHSR_NNN_), ID($_DLATCHSR_NNP_), ID($_DLATCHSR_NPN_), ID($_DLATCHSR_NPP_), - ID($_DLATCHSR_PNN_), ID($_DLATCHSR_PNP_), ID($_DLATCHSR_PPN_), ID($_DLATCHSR_PPP_), - ID($_SR_NN_), ID($_SR_NP_), ID($_SR_PN_), ID($_SR_PP_) - }; + static pool unsupported{ID($adff), ID($dlatch), ID($dlatchsr), ID($sr), + ID($_DFF_NN0_), ID($_DFF_NN1_), ID($_DFF_NP0_), ID($_DFF_NP1_), + ID($_DFF_PN0_), ID($_DFF_PN1_), ID($_DFF_PP0_), ID($_DFF_PP1_), + ID($_DLATCH_N_), ID($_DLATCH_P_), ID($_DLATCHSR_NNN_), ID($_DLATCHSR_NNP_), + ID($_DLATCHSR_NPN_), ID($_DLATCHSR_NPP_), ID($_DLATCHSR_PNN_), ID($_DLATCHSR_PNP_), + ID($_DLATCHSR_PPN_), ID($_DLATCHSR_PPP_), ID($_SR_NN_), ID($_SR_NP_), + ID($_SR_PN_), ID($_SR_PP_)}; pool processed; for (auto module : design->selected_modules()) for (auto cell : module->cells()) { @@ -107,8 +102,7 @@ void check(RTLIL::Design *design, bool dff_mode) if (cell->parameters.empty()) { derived_type = cell->type; derived_module = inst_module; - } - else { + } else { // Check potential (since its value may depend on a parameter, // but not its existence) if (!inst_module->has_attribute(ID::abc9_flop)) @@ -129,20 +123,24 @@ void check(RTLIL::Design *design, bool dff_mode) for (auto derived_cell : derived_module->cells()) { if (derived_cell->type.in(ID($dff), ID($_DFF_N_), ID($_DFF_P_))) { if (found) - log_error("Whitebox '%s' with (* abc9_flop *) contains more than one $_DFF_[NP]_ cell.\n", log_id(derived_module)); + log_error("Whitebox '%s' with (* abc9_flop *) contains more than one $_DFF_[NP]_ cell.\n", + log_id(derived_module)); found = true; SigBit Q = derived_cell->getPort(ID::Q); log_assert(GetSize(Q.wire) == 1); if (!Q.wire->port_output) - log_error("Whitebox '%s' with (* abc9_flop *) contains a %s cell where its 'Q' port does not drive a module output.\n", log_id(derived_module), log_id(derived_cell->type)); + log_error("Whitebox '%s' with (* abc9_flop *) contains a %s cell where its 'Q' port does not " + "drive a module output.\n", + log_id(derived_module), log_id(derived_cell->type)); Const init = Q.wire->attributes.at(ID::init, State::Sx); log_assert(GetSize(init) == 1); - } - else if (unsupported.count(derived_cell->type)) - log_error("Whitebox '%s' with (* abc9_flop *) contains a %s cell, which is not supported for sequential synthesis.\n", log_id(derived_module), log_id(derived_cell->type)); + } else if (unsupported.count(derived_cell->type)) + log_error("Whitebox '%s' with (* abc9_flop *) contains a %s cell, which is not supported for " + "sequential synthesis.\n", + log_id(derived_module), log_id(derived_cell->type)); } } } @@ -168,8 +166,7 @@ void prep_hier(RTLIL::Design *design, bool dff_mode) if (cell->parameters.empty()) { derived_type = cell->type; derived_module = inst_module; - } - else { + } else { derived_type = inst_module->derive(design, cell->parameters); derived_module = design->module(derived_type); unused_derived.insert(derived_type); @@ -178,8 +175,7 @@ void prep_hier(RTLIL::Design *design, bool dff_mode) if (derived_module->get_bool_attribute(ID::abc9_flop)) { if (!dff_mode) continue; - } - else { + } else { bool has_timing = false; for (auto derived_cell : derived_module->cells()) { if (derived_cell->type.in(ID($specify2), ID($specify3), ID($specrule))) { @@ -189,11 +185,13 @@ void prep_hier(RTLIL::Design *design, bool dff_mode) break; } } - if (!derived_module->get_bool_attribute(ID::abc9_box) && !derived_module->get_bool_attribute(ID::abc9_bypass) && !has_timing) { + if (!derived_module->get_bool_attribute(ID::abc9_box) && !derived_module->get_bool_attribute(ID::abc9_bypass) && + !has_timing) { if (unmap_design->module(derived_type)) { - // If derived_type is present in unmap_design, it means that it was processed previously, but found to be incompatible -- e.g. if - // it contained a non-zero initial state. In this case, continue to replace the cell type/parameters so that it has the same properties - // as a compatible type, yet will be safely unmapped later + // If derived_type is present in unmap_design, it means that it was processed previously, but found to + // be incompatible -- e.g. if it contained a non-zero initial state. In this case, continue to replace + // the cell type/parameters so that it has the same properties as a compatible type, yet will be + // safely unmapped later cell->type = derived_type; cell->parameters.clear(); unused_derived.erase(derived_type); @@ -216,13 +214,15 @@ void prep_hier(RTLIL::Design *design, bool dff_mode) // Block sequential synthesis on cells with (* init *) != 1'b0 // because ABC9 doesn't support them if (init != State::S0) { - log_warning("Whitebox '%s' with (* abc9_flop *) contains a %s cell with non-zero initial state -- this is not supported for ABC9 sequential synthesis. Treating as a blackbox.\n", log_id(derived_module), log_id(derived_cell->type)); + log_warning( + "Whitebox '%s' with (* abc9_flop *) contains a %s cell with non-zero initial state " + "-- this is not supported for ABC9 sequential synthesis. Treating as a blackbox.\n", + log_id(derived_module), log_id(derived_cell->type)); derived_module->set_bool_attribute(ID::abc9_flop, false); } break; } - } - else if (derived_module->get_bool_attribute(ID::abc9_box)) { + } else if (derived_module->get_bool_attribute(ID::abc9_box)) { for (auto derived_cell : derived_module->cells()) if (derived_cell->is_mem_cell() || RTLIL::builtin_ff_cell_types().count(derived_cell->type)) { derived_module->set_bool_attribute(ID::abc9_box, false); @@ -288,7 +288,6 @@ void prep_bypass(RTLIL::Design *design) log_assert(!inst_module->get_blackbox_attribute(true /* ignore_wb */)); log_assert(cell->parameters.empty()); - // The idea is to create two techmap designs, one which maps: // // box u0 (.i(i), .o(o)); @@ -317,7 +316,6 @@ void prep_bypass(RTLIL::Design *design) // box u0 (.i(i), .o($abc9_byp$o)); // assign o = $abc9_byp$o; - // Copy inst_module into map_design, with the same interface // and duplicate $abc9$* wires for its output ports auto map_module = map_design->addModule(cell->type); @@ -391,8 +389,7 @@ void prep_bypass(RTLIL::Design *design) } if (DST.empty()) continue; - auto rw = [bypass_module](RTLIL::SigSpec &sig) - { + auto rw = [bypass_module](RTLIL::SigSpec &sig) { SigSpec new_sig; for (auto c : sig.chunks()) { if (c.wire) { @@ -432,7 +429,6 @@ void prep_bypass(RTLIL::Design *design) } } - // Lastly, create a new module in the unmap_design that shorts // out the bypass cell back to leave the replace cell behind // driving the outputs @@ -467,13 +463,13 @@ void prep_dff(RTLIL::Design *design) if (!inst_module->get_bool_attribute(ID::abc9_flop)) continue; log_assert(!inst_module->get_blackbox_attribute(true /* ignore_wb */)); - if (!cell->parameters.empty()) - { - // At this stage of the ABC9 flow, cells instantiating (* abc9_flop *) modules must not contain any parameters -- instead it should - // be instantiating the derived module which will have had any parameters constant-propagated. - // This task is expected to be performed by `abc9_ops -prep_hier`, but it looks like it failed to do so for this design. + if (!cell->parameters.empty()) { + // At this stage of the ABC9 flow, cells instantiating (* abc9_flop *) modules must not contain any parameters -- + // instead it should be instantiating the derived module which will have had any parameters constant-propagated. This + // task is expected to be performed by `abc9_ops -prep_hier`, but it looks like it failed to do so for this design. // Please file a bug report! - log_error("Not expecting parameters on cell '%s' instantiating module '%s' marked (* abc9_flop *)\n", log_id(cell->name), log_id(cell->type)); + log_error("Not expecting parameters on cell '%s' instantiating module '%s' marked (* abc9_flop *)\n", + log_id(cell->name), log_id(cell->type)); } modules_sel.select(inst_module); } @@ -482,9 +478,9 @@ void prep_dff(RTLIL::Design *design) void prep_dff_submod(RTLIL::Design *design) { for (auto module : design->modules()) { - vector specify_cells; + vector specify_cells; SigBit Q; - Cell* dff_cell = nullptr; + Cell *dff_cell = nullptr; if (!module->get_bool_attribute(ID::abc9_flop)) continue; @@ -495,8 +491,7 @@ void prep_dff_submod(RTLIL::Design *design) dff_cell = cell; Q = cell->getPort(ID::Q); log_assert(GetSize(Q.wire) == 1); - } - else if (cell->type.in(ID($specify3), ID($specrule))) + } else if (cell->type.in(ID($specify3), ID($specrule))) specify_cells.emplace_back(cell); log_assert(dff_cell); @@ -568,7 +563,7 @@ void break_scc(RTLIL::Module *module) // Do not break SCCs which have a cell instantiating an abc9_bypass-able // module (but which wouldn't have been bypassed) auto design = module->design; - pool scc_cells; + pool scc_cells; pool ids_seen; for (auto cell : module->cells()) { auto it = cell->attributes.find(ID::abc9_scc_id); @@ -590,7 +585,8 @@ void break_scc(RTLIL::Module *module) if (!r.second) continue; for (auto &c : cell->connections_) { - if (c.second.is_fully_const()) continue; + if (c.second.is_fully_const()) + continue; if (cell->output(c.first)) { Wire *w = module->addWire(NEW_ID, GetSize(c.second)); I.append(w); @@ -600,8 +596,7 @@ void break_scc(RTLIL::Module *module) } } - if (!I.empty()) - { + if (!I.empty()) { auto cell = module->addCell(NEW_ID, ID($__ABC9_SCC_BREAKER)); log_assert(GetSize(I) == GetSize(O)); cell->setParam(ID::WIDTH, GetSize(I)); @@ -616,7 +611,7 @@ void prep_delays(RTLIL::Design *design, bool dff_mode) // Derive all Yosys blackbox modules that are not combinatorial abc9 boxes // (e.g. DSPs, RAMs, etc.) nor abc9 flops and collect all such instantiations - std::vector cells; + std::vector cells; for (auto module : design->selected_modules()) { if (module->processes.size() > 0) { log("Skipping module %s as it contains processes.\n", log_id(module)); @@ -628,7 +623,7 @@ void prep_delays(RTLIL::Design *design, bool dff_mode) continue; log_assert(!cell->type.begins_with("$paramod$__ABC9_DELAY\\DELAY=")); - RTLIL::Module* inst_module = design->module(cell->type); + RTLIL::Module *inst_module = design->module(cell->type); if (!inst_module) continue; if (!inst_module->get_blackbox_attribute()) @@ -642,8 +637,8 @@ void prep_delays(RTLIL::Design *design, bool dff_mode) continue; if (dff_mode && inst_module->get_bool_attribute(ID::abc9_flop)) { - continue; // do not add $__ABC9_DELAY boxes to flops - // as delays will be captured in the flop box + continue; // do not add $__ABC9_DELAY boxes to flops + // as delays will be captured in the flop box } if (!timing.count(cell->type)) @@ -666,8 +661,8 @@ void prep_delays(RTLIL::Design *design, bool dff_mode) for (auto &i : timing.at(cell->type).required) { auto port_wire = inst_module->wire(i.first.name); if (!port_wire) - log_error("Port %s in cell %s (type %s) from module %s does not actually exist", - log_id(i.first.name), log_id(cell), log_id(cell->type), log_id(module)); + log_error("Port %s in cell %s (type %s) from module %s does not actually exist", log_id(i.first.name), log_id(cell), + log_id(cell->type), log_id(module)); log_assert(port_wire->port_input); auto d = i.second.first; @@ -684,9 +679,9 @@ void prep_delays(RTLIL::Design *design, bool dff_mode) #ifndef NDEBUG if (ys_debug(1)) { - static pool> seen; - if (seen.emplace(cell->type, i.first).second) log("%s.%s[%d] abc9_required = %d\n", - log_id(cell->type), log_id(i.first.name), offset, d); + static pool> seen; + if (seen.emplace(cell->type, i.first).second) + log("%s.%s[%d] abc9_required = %d\n", log_id(cell->type), log_id(i.first.name), offset, d); } #endif auto r = box_cache.insert(d); @@ -740,8 +735,7 @@ void prep_xaiger(RTLIL::Module *module, bool dff) carry_in = port_name; else if (w->port_output) carry_out = port_name; - } - else + } else r.first->second.push_back(port_name); } if (carry_in != IdString()) { @@ -749,8 +743,7 @@ void prep_xaiger(RTLIL::Module *module, bool dff) r.first->second.push_back(carry_out); } } - } - else if (!yosys_celltypes.cell_known(cell->type)) + } else if (!yosys_celltypes.cell_known(cell->type)) continue; // TODO: Speed up toposort -- we care about box ordering only @@ -802,7 +795,7 @@ void prep_xaiger(RTLIL::Module *module, bool dff) RTLIL::Module *holes_module = holes_design->addModule(module->name); log_assert(holes_module); - dict cell_cache; + dict cell_cache; TimingInfo timing; int port_id = 1, box_count = 0; @@ -810,18 +803,17 @@ void prep_xaiger(RTLIL::Module *module, bool dff) RTLIL::Cell *cell = module->cell(cell_name); log_assert(cell); - RTLIL::Module* box_module = design->module(cell->type); + RTLIL::Module *box_module = design->module(cell->type); if (!box_module) continue; if (!box_module->get_bool_attribute(ID::abc9_box)) continue; - if (!cell->parameters.empty()) - { - // At this stage of the ABC9 flow, cells instantiating (* abc9_box *) modules must not contain any parameters -- instead it should - // be instantiating the derived module which will have had any parameters constant-propagated. - // This task is expected to be performed by `abc9_ops -prep_hier`, but it looks like it failed to do so for this design. - // Please file a bug report! - log_error("Not expecting parameters on cell '%s' instantiating module '%s' marked (* abc9_box *)\n", log_id(cell_name), log_id(cell->type)); + if (!cell->parameters.empty()) { + // At this stage of the ABC9 flow, cells instantiating (* abc9_box *) modules must not contain any parameters -- instead it + // should be instantiating the derived module which will have had any parameters constant-propagated. This task is expected to + // be performed by `abc9_ops -prep_hier`, but it looks like it failed to do so for this design. Please file a bug report! + log_error("Not expecting parameters on cell '%s' instantiating module '%s' marked (* abc9_box *)\n", log_id(cell_name), + log_id(cell->type)); } log_assert(box_module->get_blackbox_attribute()); @@ -854,12 +846,10 @@ void prep_xaiger(RTLIL::Module *module, bool dff) } conn.append(holes_wire); } - } - else if (w->port_output) + } else if (w->port_output) conn = holes_module->addWire(stringf("%s.%s", cell->type.c_str(), log_id(port_name)), GetSize(w)); } - } - else // box_module is a blackbox + } else // box_module is a blackbox log_assert(holes_cell == nullptr); } @@ -889,7 +879,7 @@ void prep_lut(RTLIL::Design *design, int maxlut) int area; std::vector delays; }; - std::map table; + std::map table; for (auto module : design->modules()) { auto it = module->attributes.find(ID::abc9_lut); if (it == module->attributes.end()) @@ -920,7 +910,8 @@ void prep_lut(RTLIL::Design *design, int maxlut) auto r = table.emplace(K, entry); if (!r.second) { if (r.first->second.area != entry.area) - log_error("Modules '%s' and '%s' have conflicting (* abc9_lut *) values.\n", log_id(module), log_id(r.first->second.name)); + log_error("Modules '%s' and '%s' have conflicting (* abc9_lut *) values.\n", log_id(module), + log_id(r.first->second.name)); if (r.first->second.delays != entry.delays) log_error("Modules '%s' and '%s' have conflicting specify entries.\n", log_id(module), log_id(r.first->second.name)); } @@ -950,7 +941,8 @@ void prep_lut(RTLIL::Design *design, int maxlut) design->scratchpad_set_string("abc9_ops.lut_library", ss.str()); } -void write_lut(RTLIL::Module *module, const std::string &dst) { +void write_lut(RTLIL::Module *module, const std::string &dst) +{ std::ofstream ofs(dst); log_assert(ofs.is_open()); ofs << module->design->scratchpad_get_string("abc9_ops.lut_library"); @@ -963,7 +955,7 @@ void prep_box(RTLIL::Design *design) int abc9_box_id = 1; std::stringstream ss; - dict> box_ports; + dict> box_ports; for (auto module : design->modules()) { auto it = module->attributes.find(ID::abc9_box); if (it == module->attributes.end()) @@ -983,14 +975,17 @@ void prep_box(RTLIL::Design *design) for (auto port_name : module->ports) { auto wire = module->wire(port_name); log_assert(GetSize(wire) == 1); - if (wire->port_input) num_inputs++; - if (wire->port_output) num_outputs++; + if (wire->port_input) + num_inputs++; + if (wire->port_output) + num_outputs++; } log_assert(num_outputs == 1); ss << log_id(module) << " " << r.first->second.as_int(); log_assert(module->get_bool_attribute(ID::whitebox)); - ss << " " << "1"; + ss << " " + << "1"; ss << " " << num_inputs << " " << num_outputs << std::endl; ss << "#"; @@ -1009,7 +1004,8 @@ void prep_box(RTLIL::Design *design) auto &t = timing.setup_module(module).required; if (t.empty()) - log_error("Module '%s' with (* abc9_flop *) has no clk-to-q timing (and thus no connectivity) information.\n", log_id(module)); + log_error("Module '%s' with (* abc9_flop *) has no clk-to-q timing (and thus no connectivity) information.\n", + log_id(module)); first = true; for (auto port_name : module->ports) { @@ -1021,7 +1017,7 @@ void prep_box(RTLIL::Design *design) else ss << " "; log_assert(GetSize(wire) == 1); - auto it = t.find(TimingInfo::NameBit(port_name,0)); + auto it = t.find(TimingInfo::NameBit(port_name, 0)); if (it == t.end()) // Assume that no setup time means zero ss << 0; @@ -1030,17 +1026,16 @@ void prep_box(RTLIL::Design *design) #ifndef NDEBUG if (ys_debug(1)) { - static std::set> seen; - if (seen.emplace(module->name, port_name).second) log("%s.%s abc9_required = %d\n", log_id(module), - log_id(port_name), it->second.first); + static std::set> seen; + if (seen.emplace(module->name, port_name).second) + log("%s.%s abc9_required = %d\n", log_id(module), log_id(port_name), it->second.first); } #endif } } ss << " # $_DFF_[NP]_.D" << std::endl; ss << std::endl; - } - else { + } else { auto r2 = box_ports.insert(module->name); if (r2.second) { // Make carry in the last PI, and carry out the last PO @@ -1055,8 +1050,7 @@ void prep_box(RTLIL::Design *design) carry_in = port_name; else if (w->port_output) carry_out = port_name; - } - else + } else r2.first->second.push_back(port_name); } @@ -1106,7 +1100,7 @@ void prep_box(RTLIL::Design *design) first = false; else ss << " "; - auto jt = t.comb.find(TimingInfo::BitBit(i,o)); + auto jt = t.comb.find(TimingInfo::BitBit(i, o)); if (jt == t.comb.end()) ss << "-"; else @@ -1130,7 +1124,8 @@ void prep_box(RTLIL::Design *design) design->scratchpad_set_string("abc9_ops.box_library", ss.str()); } -void write_box(RTLIL::Module *module, const std::string &dst) { +void write_box(RTLIL::Module *module, const std::string &dst) +{ std::ofstream ofs(dst); log_assert(ofs.is_open()); ofs << module->design->scratchpad_get_string("abc9_ops.box_library"); @@ -1155,7 +1150,7 @@ void reintegrate(RTLIL::Module *module, bool dff_mode) w->attributes.erase(ID::init); } - dict> box_ports; + dict> box_ports; for (auto m : design->modules()) { if (!m->attributes.count(ID::abc9_box_id)) @@ -1177,8 +1172,7 @@ void reintegrate(RTLIL::Module *module, bool dff_mode) carry_in = port_name; else if (w->port_output) carry_out = port_name; - } - else + } else r.first->second.push_back(port_name); } @@ -1202,7 +1196,7 @@ void reintegrate(RTLIL::Module *module, bool dff_mode) } } - std::vector boxes; + std::vector boxes; for (auto cell : module->cells().to_vector()) { if (cell->has_keep_attr()) continue; @@ -1218,8 +1212,7 @@ void reintegrate(RTLIL::Module *module, bool dff_mode) auto it = Qi.wire->attributes.find(ID::init); if (it != Qi.wire->attributes.end()) it->second[Qi.offset] = State::Sx; - } - else if (cell->type.in(ID($_AND_), ID($_NOT_))) + } else if (cell->type.in(ID($_AND_), ID($_NOT_))) module->remove(cell); else if (cell->attributes.erase(ID::abc9_box_seq)) boxes.emplace_back(cell); @@ -1227,12 +1220,11 @@ void reintegrate(RTLIL::Module *module, bool dff_mode) dict> bit_drivers, bit_users; TopoSort toposort; - dict not2drivers; - dict> bit2sinks; + dict not2drivers; + dict> bit2sinks; std::map cell_stats; - for (auto mapped_cell : mapped_mod->cells()) - { + for (auto mapped_cell : mapped_mod->cells()) { // Short out $_FF_ cells since the flop box already has // all the information we need to reconstruct cell if (dff_mode && mapped_cell->type == ID($_FF_)) { @@ -1261,9 +1253,8 @@ void reintegrate(RTLIL::Module *module, bool dff_mode) RTLIL::Wire *wire = module->wire(remap_name(y_bit.wire->name)); log_assert(wire); module->connect(RTLIL::SigBit(wire, y_bit.offset), State::S1); - } - else { - RTLIL::Cell* driver_lut = nullptr; + } else { + RTLIL::Cell *driver_lut = nullptr; // ABC can return NOT gates that drive POs if (!a_bit.wire->port_input) { // If it's not a NOT gate that that comes from a PI directly, @@ -1281,14 +1272,14 @@ void reintegrate(RTLIL::Module *module, bool dff_mode) if (!driver_lut) { // If a driver couldn't be found (could be from PI or box CI) // then implement using a LUT - RTLIL::Cell *cell = module->addLut(remap_name(stringf("$lut%s", mapped_cell->name.c_str())), - RTLIL::SigBit(module->wires_.at(remap_name(a_bit.wire->name)), a_bit.offset), - RTLIL::SigBit(module->wires_.at(remap_name(y_bit.wire->name)), y_bit.offset), - RTLIL::Const::from_string("01")); + RTLIL::Cell *cell = + module->addLut(remap_name(stringf("$lut%s", mapped_cell->name.c_str())), + RTLIL::SigBit(module->wires_.at(remap_name(a_bit.wire->name)), a_bit.offset), + RTLIL::SigBit(module->wires_.at(remap_name(y_bit.wire->name)), y_bit.offset), + RTLIL::Const::from_string("01")); bit2sinks[cell->getPort(ID::A)].push_back(cell); cell_stats[ID($lut)]++; - } - else + } else not2drivers[mapped_cell] = driver_lut; } continue; @@ -1304,7 +1295,7 @@ void reintegrate(RTLIL::Module *module, bool dff_mode) for (auto c : mapped_conn.second.chunks()) { if (c.width == 0) continue; - //log_assert(c.width == 1); + // log_assert(c.width == 1); if (c.wire) c.wire = module->wires_.at(remap_name(c.wire->name)); newsig.append(c); @@ -1323,8 +1314,7 @@ void reintegrate(RTLIL::Module *module, bool dff_mode) if (i.wire && !(i.wire->port_input && i.wire->port_output)) bit_drivers[i].insert(mapped_cell->name); } - } - else { + } else { RTLIL::Cell *existing_cell = module->cell(mapped_cell->name); if (!existing_cell) log_error("Cannot find existing box cell with name '%s' in original design.\n", log_id(mapped_cell)); @@ -1340,7 +1330,7 @@ void reintegrate(RTLIL::Module *module, bool dff_mode) continue; } - RTLIL::Module* box_module = design->module(existing_cell->type); + RTLIL::Module *box_module = design->module(existing_cell->type); log_assert(existing_cell->parameters.empty()); log_assert(mapped_cell->type == stringf("$__boxid%d", box_module->attributes.at(ID::abc9_box_id).as_int())); mapped_cell->type = existing_cell->type; @@ -1376,9 +1366,8 @@ void reintegrate(RTLIL::Module *module, bool dff_mode) } auto new_q = outputs[0]; new_q.wire = module->wires_.at(remap_name(new_q.wire->name)); - module->connect(old_q, new_q); - } - else { + module->connect(old_q, new_q); + } else { for (const auto &i : inputs) bit_users[i].insert(mapped_cell->name); for (const auto &i : outputs) @@ -1406,7 +1395,7 @@ void reintegrate(RTLIL::Module *module, bool dff_mode) for (auto c : sig.chunks()) { if (c.width == 0) continue; - //log_assert(c.width == 1); + // log_assert(c.width == 1); if (c.wire) c.wire = module->wires_.at(remap_name(c.wire->name)); newsig.append(c); @@ -1455,7 +1444,7 @@ void reintegrate(RTLIL::Module *module, bool dff_mode) log_assert(wire); RTLIL::Wire *remap_wire = module->wire(remap_name(port)); - RTLIL::SigSpec signal(wire, remap_wire->start_offset-wire->start_offset, GetSize(remap_wire)); + RTLIL::SigSpec signal(wire, remap_wire->start_offset - wire->start_offset, GetSize(remap_wire)); log_assert(GetSize(signal) >= GetSize(remap_wire)); RTLIL::SigSig conn; @@ -1464,8 +1453,7 @@ void reintegrate(RTLIL::Module *module, bool dff_mode) conn.second = remap_wire; out_wires++; module->connect(conn); - } - else if (mapped_wire->port_input) { + } else if (mapped_wire->port_input) { conn.first = remap_wire; conn.second = signal; in_wires++; @@ -1487,8 +1475,8 @@ void reintegrate(RTLIL::Module *module, bool dff_mode) for (auto &it : bit_users) if (bit_drivers.count(it.first)) for (auto driver_cell : bit_drivers.at(it.first)) - for (auto user_cell : it.second) - toposort.edge(driver_cell, user_cell); + for (auto user_cell : it.second) + toposort.edge(driver_cell, user_cell); bool no_loops = toposort.sort(); log_assert(no_loops); @@ -1528,8 +1516,8 @@ void reintegrate(RTLIL::Module *module, bool dff_mode) int i = 0; while (i < GetSize(mask)) { for (int j = 0; j < (1 << index); j++) - std::swap(mask[i+j], mask[i+j+(1 << index)]); - i += 1 << (index+1); + std::swap(mask[i + j], mask[i + j + (1 << index)]); + i += 1 << (index + 1); } A[index] = y_bit; sink_cell->setPort(ID::A, A); @@ -1541,23 +1529,22 @@ void reintegrate(RTLIL::Module *module, bool dff_mode) // go ahead and clone the LUT with the expectation // that the original driving LUT will become dangling // and get cleaned away -clone_lut: + clone_lut: driver_mask = driver_lut->getParam(ID::LUT); for (auto &b : driver_mask.bits) { - if (b == RTLIL::State::S0) b = RTLIL::State::S1; - else if (b == RTLIL::State::S1) b = RTLIL::State::S0; + if (b == RTLIL::State::S0) + b = RTLIL::State::S1; + else if (b == RTLIL::State::S1) + b = RTLIL::State::S0; } - auto cell = module->addLut(NEW_ID, - driver_lut->getPort(ID::A), - y_bit, - driver_mask); + auto cell = module->addLut(NEW_ID, driver_lut->getPort(ID::A), y_bit, driver_mask); for (auto &bit : cell->connections_.at(ID::A)) { bit.wire = module->wires_.at(remap_name(bit.wire->name)); bit2sinks[bit].push_back(cell); } } - //log("ABC RESULTS: internal signals: %8d\n", int(signal_list.size()) - in_wires - out_wires); + // log("ABC RESULTS: internal signals: %8d\n", int(signal_list.size()) - in_wires - out_wires); log("ABC RESULTS: input signals: %8d\n", in_wires); log("ABC RESULTS: output signals: %8d\n", out_wires); @@ -1565,7 +1552,7 @@ void reintegrate(RTLIL::Module *module, bool dff_mode) } struct Abc9OpsPass : public Pass { - Abc9OpsPass() : Pass("abc9_ops", "helper functions for ABC9") { } + Abc9OpsPass() : Pass("abc9_ops", "helper functions for ABC9") {} void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| @@ -1720,13 +1707,13 @@ struct Abc9OpsPass : public Pass { valid = true; continue; } - if (arg == "-prep_lut" && argidx+1 < args.size()) { + if (arg == "-prep_lut" && argidx + 1 < args.size()) { prep_lut_mode = true; maxlut = atoi(args[++argidx].c_str()); valid = true; continue; } - if (arg == "-write_lut" && argidx+1 < args.size()) { + if (arg == "-write_lut" && argidx + 1 < args.size()) { write_lut_dst = args[++argidx]; rewrite_filename(write_lut_dst); valid = true; @@ -1737,7 +1724,7 @@ struct Abc9OpsPass : public Pass { valid = true; continue; } - if (arg == "-write_box" && argidx+1 < args.size()) { + if (arg == "-write_box" && argidx + 1 < args.size()) { write_box_dst = args[++argidx]; rewrite_filename(write_box_dst); valid = true; @@ -1757,7 +1744,8 @@ struct Abc9OpsPass : public Pass { extra_args(args, argidx, design); if (!valid) - log_cmd_error("At least one of -check, -break_scc, -prep_{delays,xaiger,dff[123],lut,box}, -write_{lut,box}, -reintegrate must be specified.\n"); + log_cmd_error("At least one of -check, -break_scc, -prep_{delays,xaiger,dff[123],lut,box}, -write_{lut,box}, -reintegrate " + "must be specified.\n"); if (dff_mode && !check_mode && !prep_hier_mode && !prep_delays_mode && !prep_xaiger_mode && !reintegrate_mode) log_cmd_error("'-dff' option is only relevant for -prep_{hier,delay,xaiger} or -reintegrate.\n"); diff --git a/passes/techmap/aigmap.cc b/passes/techmap/aigmap.cc index 4836ebe3484..dc6ef0941bd 100644 --- a/passes/techmap/aigmap.cc +++ b/passes/techmap/aigmap.cc @@ -17,14 +17,14 @@ * */ -#include "kernel/yosys.h" #include "kernel/cellaigs.h" +#include "kernel/yosys.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct AigmapPass : public Pass { - AigmapPass() : Pass("aigmap", "map logic to and-inverter-graph circuit") { } + AigmapPass() : Pass("aigmap", "map logic to and-inverter-graph circuit") {} void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| @@ -50,8 +50,7 @@ struct AigmapPass : public Pass { log_header(design, "Executing AIGMAP pass (map logic to AIG).\n"); size_t argidx; - for (argidx = 1; argidx < args.size(); argidx++) - { + for (argidx = 1; argidx < args.size(); argidx++) { if (args[argidx] == "-nand") { nand_mode = true; continue; @@ -64,17 +63,15 @@ struct AigmapPass : public Pass { } extra_args(args, argidx, design); - for (auto module : design->selected_modules()) - { - vector replaced_cells; + for (auto module : design->selected_modules()) { + vector replaced_cells; int not_replaced_count = 0; dict stat_replaced; dict stat_not_replaced; int orig_num_cells = GetSize(module->cells()); pool new_sel; - for (auto cell : module->selected_cells()) - { + for (auto cell : module->selected_cells()) { Aig aig(cell); if (cell->type.in(ID($_AND_), ID($_NOT_))) @@ -94,8 +91,7 @@ struct AigmapPass : public Pass { vector sigs; dict, SigBit> and_cache; - for (int node_idx = 0; node_idx < GetSize(aig.nodes); node_idx++) - { + for (int node_idx = 0; node_idx < GetSize(aig.nodes); node_idx++) { SigBit bit; auto &node = aig.nodes[node_idx]; @@ -133,7 +129,6 @@ struct AigmapPass : public Pass { bit = new_bit; if (select_mode) new_sel.insert(gate->name); - } skip_inverter: @@ -150,8 +145,8 @@ struct AigmapPass : public Pass { if (not_replaced_count == 0 && replaced_cells.empty()) continue; - log("Module %s: replaced %d cells with %d new cells, skipped %d cells.\n", log_id(module), - GetSize(replaced_cells), GetSize(module->cells()) - orig_num_cells, not_replaced_count); + log("Module %s: replaced %d cells with %d new cells, skipped %d cells.\n", log_id(module), GetSize(replaced_cells), + GetSize(module->cells()) - orig_num_cells, not_replaced_count); if (!stat_replaced.empty()) { stat_replaced.sort(); @@ -172,10 +167,9 @@ struct AigmapPass : public Pass { if (select_mode) { log_assert(!design->selection_stack.empty()); - RTLIL::Selection& sel = design->selection_stack.back(); + RTLIL::Selection &sel = design->selection_stack.back(); sel.selected_members[module->name] = std::move(new_sel); } - } } } AigmapPass; diff --git a/passes/techmap/alumacc.cc b/passes/techmap/alumacc.cc index e4e70004c0f..0ae2c5c9276 100644 --- a/passes/techmap/alumacc.cc +++ b/passes/techmap/alumacc.cc @@ -17,15 +17,14 @@ * */ -#include "kernel/yosys.h" -#include "kernel/sigtools.h" #include "kernel/macc.h" +#include "kernel/sigtools.h" +#include "kernel/yosys.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN -struct AlumaccWorker -{ +struct AlumaccWorker { RTLIL::Module *module; SigMap sigmap; @@ -36,9 +35,8 @@ struct AlumaccWorker int users; }; - struct alunode_t - { - std::vector cells; + struct alunode_t { + std::vector cells; RTLIL::SigSpec a, b, c, y; std::vector> cmp; bool is_signed, invert_b; @@ -47,20 +45,21 @@ struct AlumaccWorker RTLIL::SigSpec cached_lt, cached_gt, cached_eq, cached_ne; RTLIL::SigSpec cached_cf, cached_of, cached_sf; - RTLIL::SigSpec get_lt() { + RTLIL::SigSpec get_lt() + { if (GetSize(cached_lt) == 0) { if (is_signed) { get_of(); get_sf(); cached_lt = alu_cell->module->Xor(NEW_ID, cached_of, cached_sf); - } - else + } else cached_lt = get_cf(); } return cached_lt; } - RTLIL::SigSpec get_gt() { + RTLIL::SigSpec get_gt() + { if (GetSize(cached_gt) == 0) { get_lt(); get_eq(); @@ -70,48 +69,53 @@ struct AlumaccWorker return cached_gt; } - RTLIL::SigSpec get_eq() { + RTLIL::SigSpec get_eq() + { if (GetSize(cached_eq) == 0) cached_eq = alu_cell->module->ReduceAnd(NEW_ID, alu_cell->getPort(ID::X), false, alu_cell->get_src_attribute()); return cached_eq; } - RTLIL::SigSpec get_ne() { + RTLIL::SigSpec get_ne() + { if (GetSize(cached_ne) == 0) cached_ne = alu_cell->module->Not(NEW_ID, get_eq(), false, alu_cell->get_src_attribute()); return cached_ne; } - RTLIL::SigSpec get_cf() { + RTLIL::SigSpec get_cf() + { if (GetSize(cached_cf) == 0) { cached_cf = alu_cell->getPort(ID::CO); log_assert(GetSize(cached_cf) >= 1); - cached_cf = alu_cell->module->Not(NEW_ID, cached_cf[GetSize(cached_cf)-1], false, alu_cell->get_src_attribute()); + cached_cf = alu_cell->module->Not(NEW_ID, cached_cf[GetSize(cached_cf) - 1], false, alu_cell->get_src_attribute()); } return cached_cf; } - RTLIL::SigSpec get_of() { + RTLIL::SigSpec get_of() + { if (GetSize(cached_of) == 0) { cached_of = {alu_cell->getPort(ID::CO), alu_cell->getPort(ID::CI)}; log_assert(GetSize(cached_of) >= 2); - cached_of = alu_cell->module->Xor(NEW_ID, cached_of[GetSize(cached_of)-1], cached_of[GetSize(cached_of)-2]); + cached_of = alu_cell->module->Xor(NEW_ID, cached_of[GetSize(cached_of) - 1], cached_of[GetSize(cached_of) - 2]); } return cached_of; } - RTLIL::SigSpec get_sf() { + RTLIL::SigSpec get_sf() + { if (GetSize(cached_sf) == 0) { cached_sf = alu_cell->getPort(ID::Y); - cached_sf = cached_sf[GetSize(cached_sf)-1]; + cached_sf = cached_sf[GetSize(cached_sf) - 1]; } return cached_sf; } }; dict bit_users; - dict sig_macc; - dict> sig_alu; + dict sig_macc; + dict> sig_alu; int macc_counter, alu_counter; AlumaccWorker(RTLIL::Module *module) : module(module), sigmap(module) @@ -127,15 +131,14 @@ struct AlumaccWorker bit_users[bit]++; for (auto cell : module->cells()) - for (auto &conn : cell->connections()) - for (auto bit : sigmap(conn.second)) - bit_users[bit]++; + for (auto &conn : cell->connections()) + for (auto bit : sigmap(conn.second)) + bit_users[bit]++; } void extract_macc() { - for (auto cell : module->selected_cells()) - { + for (auto cell : module->selected_cells()) { if (!cell->type.in(ID($pos), ID($neg), ID($add), ID($sub), ID($mul))) continue; @@ -151,16 +154,14 @@ struct AlumaccWorker for (auto bit : n->y) n->users = max(n->users, bit_users.at(bit) - 1); - if (cell->type.in(ID($pos), ID($neg))) - { + if (cell->type.in(ID($pos), ID($neg))) { new_port.in_a = sigmap(cell->getPort(ID::A)); new_port.is_signed = cell->getParam(ID::A_SIGNED).as_bool(); new_port.do_subtract = cell->type == ID($neg); n->macc.ports.push_back(new_port); } - if (cell->type.in(ID($add), ID($sub))) - { + if (cell->type.in(ID($add), ID($sub))) { new_port.in_a = sigmap(cell->getPort(ID::A)); new_port.is_signed = cell->getParam(ID::A_SIGNED).as_bool(); new_port.do_subtract = false; @@ -172,8 +173,7 @@ struct AlumaccWorker n->macc.ports.push_back(new_port); } - if (cell->type.in(ID($mul))) - { + if (cell->type.in(ID($mul))) { new_port.in_a = sigmap(cell->getPort(ID::A)); new_port.in_b = sigmap(cell->getPort(ID::B)); new_port.is_signed = cell->getParam(ID::A_SIGNED).as_bool(); @@ -224,19 +224,16 @@ struct AlumaccWorker void merge_macc() { - while (1) - { - pool delete_nodes; + while (1) { + pool delete_nodes; - for (auto &it : sig_macc) - { + for (auto &it : sig_macc) { auto n = it.second; if (delete_nodes.count(n)) continue; - for (int i = 0; i < GetSize(n->macc.ports); i++) - { + for (int i = 0; i < GetSize(n->macc.ports); i++) { auto &port = n->macc.ports[i]; if (GetSize(port.in_b) > 0 || sig_macc.count(port.in_a) == 0) @@ -247,7 +244,8 @@ struct AlumaccWorker if (other_n->users > 1) continue; - if (GetSize(other_n->y) != GetSize(n->y) && macc_may_overflow(other_n->macc, GetSize(other_n->y), port.is_signed)) + if (GetSize(other_n->y) != GetSize(n->y) && + macc_may_overflow(other_n->macc, GetSize(other_n->y), port.is_signed)) continue; log(" merging $macc model for %s into %s.\n", log_id(other_n->cell), log_id(n->cell)); @@ -278,10 +276,9 @@ struct AlumaccWorker void macc_to_alu() { - pool delete_nodes; + pool delete_nodes; - for (auto &it : sig_macc) - { + for (auto &it : sig_macc) { auto n = it.second; RTLIL::SigSpec A, B, C = n->macc.bit_ports; bool a_signed = false, b_signed = false; @@ -359,8 +356,7 @@ struct AlumaccWorker void replace_macc() { - for (auto &it : sig_macc) - { + for (auto &it : sig_macc) { auto n = it.second; auto cell = module->addCell(NEW_ID, ID($macc)); @@ -383,18 +379,16 @@ struct AlumaccWorker void extract_cmp_alu() { - std::vector lge_cells, eq_cells; + std::vector lge_cells, eq_cells; - for (auto cell : module->selected_cells()) - { + for (auto cell : module->selected_cells()) { if (cell->type.in(ID($lt), ID($le), ID($ge), ID($gt))) lge_cells.push_back(cell); if (cell->type.in(ID($eq), ID($eqx), ID($ne), ID($nex))) eq_cells.push_back(cell); } - for (auto cell : lge_cells) - { + for (auto cell : lge_cells) { log(" creating $alu model for %s (%s):", log_id(cell), log_id(cell->type)); bool cmp_less = cell->type.in(ID($lt), ID($le)); @@ -436,8 +430,7 @@ struct AlumaccWorker n->cmp.push_back(std::make_tuple(cmp_less, !cmp_less, cmp_equal, false, Y)); } - for (auto cell : eq_cells) - { + for (auto cell : eq_cells) { bool cmp_equal = cell->type.in(ID($eq), ID($eqx)); bool is_signed = cell->getParam(ID::A_SIGNED).as_bool(); @@ -457,7 +450,8 @@ struct AlumaccWorker } if (n != nullptr) { - log(" creating $alu model for %s (%s): merged with %s.\n", log_id(cell), log_id(cell->type), log_id(n->cells.front())); + log(" creating $alu model for %s (%s): merged with %s.\n", log_id(cell), log_id(cell->type), + log_id(n->cells.front())); n->cells.push_back(cell); n->cmp.push_back(std::make_tuple(false, false, cmp_equal, !cmp_equal, Y)); } @@ -468,67 +462,68 @@ struct AlumaccWorker { std::string src(""); for (auto &it1 : sig_alu) - for (auto n : it1.second) - { - if (GetSize(n->b) == 0 && GetSize(n->c) == 0 && GetSize(n->cmp) == 0) - { - n->alu_cell = module->addPos(NEW_ID, n->a, n->y, n->is_signed); + for (auto n : it1.second) { + if (GetSize(n->b) == 0 && GetSize(n->c) == 0 && GetSize(n->cmp) == 0) { + n->alu_cell = module->addPos(NEW_ID, n->a, n->y, n->is_signed); + + log(" creating $pos cell for "); + for (int i = 0; i < GetSize(n->cells); i++) + log("%s%s", i ? ", " : "", log_id(n->cells[i])); + log(": %s\n", log_id(n->alu_cell)); + + goto delete_node; + } + + n->alu_cell = module->addCell(NEW_ID, ID($alu)); + alu_counter++; - log(" creating $pos cell for "); + log(" creating $alu cell for "); for (int i = 0; i < GetSize(n->cells); i++) - log("%s%s", i ? ", ": "", log_id(n->cells[i])); + log("%s%s", i ? ", " : "", log_id(n->cells[i])); log(": %s\n", log_id(n->alu_cell)); - goto delete_node; - } + if (n->cells.size() > 0) + n->alu_cell->set_src_attribute(n->cells[0]->get_src_attribute()); + + n->alu_cell->setPort(ID::A, n->a); + n->alu_cell->setPort(ID::B, n->b); + n->alu_cell->setPort(ID::CI, GetSize(n->c) ? n->c : State::S0); + n->alu_cell->setPort(ID::BI, n->invert_b ? State::S1 : State::S0); + n->alu_cell->setPort(ID::Y, n->y); + n->alu_cell->setPort(ID::X, module->addWire(NEW_ID, GetSize(n->y))); + n->alu_cell->setPort(ID::CO, module->addWire(NEW_ID, GetSize(n->y))); + n->alu_cell->fixup_parameters(n->is_signed, n->is_signed); + + for (auto &it : n->cmp) { + bool cmp_lt = std::get<0>(it); + bool cmp_gt = std::get<1>(it); + bool cmp_eq = std::get<2>(it); + bool cmp_ne = std::get<3>(it); + RTLIL::SigSpec cmp_y = std::get<4>(it); + + RTLIL::SigSpec sig; + if (cmp_lt) + sig.append(n->get_lt()); + if (cmp_gt) + sig.append(n->get_gt()); + if (cmp_eq) + sig.append(n->get_eq()); + if (cmp_ne) + sig.append(n->get_ne()); + + if (GetSize(sig) > 1) + sig = module->ReduceOr(NEW_ID, sig); + + sig.extend_u0(GetSize(cmp_y)); + module->connect(cmp_y, sig); + } - n->alu_cell = module->addCell(NEW_ID, ID($alu)); - alu_counter++; - - log(" creating $alu cell for "); - for (int i = 0; i < GetSize(n->cells); i++) - log("%s%s", i ? ", ": "", log_id(n->cells[i])); - log(": %s\n", log_id(n->alu_cell)); - - if (n->cells.size() > 0) - n->alu_cell->set_src_attribute(n->cells[0]->get_src_attribute()); - - n->alu_cell->setPort(ID::A, n->a); - n->alu_cell->setPort(ID::B, n->b); - n->alu_cell->setPort(ID::CI, GetSize(n->c) ? n->c : State::S0); - n->alu_cell->setPort(ID::BI, n->invert_b ? State::S1 : State::S0); - n->alu_cell->setPort(ID::Y, n->y); - n->alu_cell->setPort(ID::X, module->addWire(NEW_ID, GetSize(n->y))); - n->alu_cell->setPort(ID::CO, module->addWire(NEW_ID, GetSize(n->y))); - n->alu_cell->fixup_parameters(n->is_signed, n->is_signed); - - for (auto &it : n->cmp) - { - bool cmp_lt = std::get<0>(it); - bool cmp_gt = std::get<1>(it); - bool cmp_eq = std::get<2>(it); - bool cmp_ne = std::get<3>(it); - RTLIL::SigSpec cmp_y = std::get<4>(it); - - RTLIL::SigSpec sig; - if (cmp_lt) sig.append(n->get_lt()); - if (cmp_gt) sig.append(n->get_gt()); - if (cmp_eq) sig.append(n->get_eq()); - if (cmp_ne) sig.append(n->get_ne()); - - if (GetSize(sig) > 1) - sig = module->ReduceOr(NEW_ID, sig); - - sig.extend_u0(GetSize(cmp_y)); - module->connect(cmp_y, sig); + delete_node: + for (auto c : n->cells) + module->remove(c); + delete n; } - delete_node: - for (auto c : n->cells) - module->remove(c); - delete n; - } - sig_alu.clear(); } @@ -549,7 +544,7 @@ struct AlumaccWorker }; struct AlumaccPass : public Pass { - AlumaccPass() : Pass("alumacc", "extract ALU and MACC cells") { } + AlumaccPass() : Pass("alumacc", "extract ALU and MACC cells") {} void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| diff --git a/passes/techmap/attrmap.cc b/passes/techmap/attrmap.cc index 96e65ff2e9a..a66eb3f9946 100644 --- a/passes/techmap/attrmap.cc +++ b/passes/techmap/attrmap.cc @@ -17,8 +17,8 @@ * */ -#include "kernel/yosys.h" #include "kernel/sigtools.h" +#include "kernel/yosys.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN @@ -26,7 +26,7 @@ PRIVATE_NAMESPACE_BEGIN Const make_value(string &value) { if (GetSize(value) >= 2 && value.front() == '"' && value.back() == '"') - return Const(value.substr(1, GetSize(value)-2)); + return Const(value.substr(1, GetSize(value) - 2)); SigSpec sig; SigSpec::parse(sig, nullptr, value); @@ -38,8 +38,7 @@ bool string_compare_nocase(const string &str1, const string &str2) if (str1.size() != str2.size()) return false; - for (size_t i = 0; i < str1.size(); i++) - { + for (size_t i = 0; i < str1.size(); i++) { char ch1 = str1[i], ch2 = str2[i]; if ('a' <= ch1 && ch1 <= 'z') ch1 -= 'a' - 'A'; @@ -52,7 +51,7 @@ bool string_compare_nocase(const string &str1, const string &str2) return true; } -bool match_name(string &name, IdString &id, bool ignore_case=false) +bool match_name(string &name, IdString &id, bool ignore_case = false) { string str1 = RTLIL::escape_id(name); string str2 = id.str(); @@ -63,10 +62,10 @@ bool match_name(string &name, IdString &id, bool ignore_case=false) return str1 == str2; } -bool match_value(string &value, Const &val, bool ignore_case=false) +bool match_value(string &value, Const &val, bool ignore_case = false) { if (ignore_case && ((val.flags & RTLIL::CONST_FLAG_STRING) != 0) && GetSize(value) && value.front() == '"' && value.back() == '"') { - string str1 = value.substr(1, GetSize(value)-2); + string str1 = value.substr(1, GetSize(value) - 2); string str2 = val.decode_string(); return string_compare_nocase(str1, str2); } @@ -75,13 +74,14 @@ bool match_value(string &value, Const &val, bool ignore_case=false) } struct AttrmapAction { - virtual ~AttrmapAction() { } + virtual ~AttrmapAction() {} virtual bool apply(IdString &id, Const &val) = 0; }; struct AttrmapTocase : AttrmapAction { string name; - bool apply(IdString &id, Const&) override { + bool apply(IdString &id, Const &) override + { if (match_name(name, id, true)) id = RTLIL::escape_id(name); return true; @@ -90,7 +90,8 @@ struct AttrmapTocase : AttrmapAction { struct AttrmapRename : AttrmapAction { string old_name, new_name; - bool apply(IdString &id, Const&) override { + bool apply(IdString &id, Const &) override + { if (match_name(old_name, id)) id = RTLIL::escape_id(new_name); return true; @@ -101,7 +102,8 @@ struct AttrmapMap : AttrmapAction { bool imap; string old_name, new_name; string old_value, new_value; - bool apply(IdString &id, Const &val) override { + bool apply(IdString &id, Const &val) override + { if (match_name(old_name, id) && match_value(old_value, val, true)) { id = RTLIL::escape_id(new_name); val = make_value(new_value); @@ -113,30 +115,27 @@ struct AttrmapMap : AttrmapAction { struct AttrmapRemove : AttrmapAction { bool has_value; string name, value; - bool apply(IdString &id, Const &val) override { - return !(match_name(name, id) && (!has_value || match_value(value, val))); - } + bool apply(IdString &id, Const &val) override { return !(match_name(name, id) && (!has_value || match_value(value, val))); } }; void attrmap_apply(string objname, vector> &actions, dict &attributes) { dict new_attributes; - for (auto attr : attributes) - { + for (auto attr : attributes) { auto new_attr = attr; for (auto &action : actions) if (!action->apply(new_attr.first, new_attr.second)) goto delete_this_attr; if (new_attr != attr) - log("Changed attribute on %s: %s=%s -> %s=%s\n", objname.c_str(), - log_id(attr.first), log_const(attr.second), log_id(new_attr.first), log_const(new_attr.second)); + log("Changed attribute on %s: %s=%s -> %s=%s\n", objname.c_str(), log_id(attr.first), log_const(attr.second), + log_id(new_attr.first), log_const(new_attr.second)); new_attributes[new_attr.first] = new_attr.second; if (0) - delete_this_attr: + delete_this_attr: log("Removed attribute on %s: %s=%s\n", objname.c_str(), log_id(attr.first), log_const(attr.second)); } @@ -166,31 +165,31 @@ void log_attrmap_paramap_options() bool parse_attrmap_paramap_options(size_t &argidx, std::vector &args, vector> &actions) { std::string arg = args[argidx]; - if (arg == "-tocase" && argidx+1 < args.size()) { + if (arg == "-tocase" && argidx + 1 < args.size()) { auto action = new AttrmapTocase; action->name = args[++argidx]; actions.push_back(std::unique_ptr(action)); return true; } - if (arg == "-rename" && argidx+2 < args.size()) { + if (arg == "-rename" && argidx + 2 < args.size()) { auto action = new AttrmapRename; action->old_name = args[++argidx]; action->new_name = args[++argidx]; actions.push_back(std::unique_ptr(action)); return true; } - if ((arg == "-map" || arg == "-imap") && argidx+2 < args.size()) { + if ((arg == "-map" || arg == "-imap") && argidx + 2 < args.size()) { string arg1 = args[++argidx]; string arg2 = args[++argidx]; string val1, val2; size_t p = arg1.find("="); if (p != string::npos) { - val1 = arg1.substr(p+1); + val1 = arg1.substr(p + 1); arg1 = arg1.substr(0, p); } p = arg2.find("="); if (p != string::npos) { - val2 = arg2.substr(p+1); + val2 = arg2.substr(p + 1); arg2 = arg2.substr(0, p); } auto action = new AttrmapMap; @@ -202,11 +201,11 @@ bool parse_attrmap_paramap_options(size_t &argidx, std::vector &arg actions.push_back(std::unique_ptr(action)); return true; } - if (arg == "-remove" && argidx+1 < args.size()) { + if (arg == "-remove" && argidx + 1 < args.size()) { string arg1 = args[++argidx], val1; size_t p = arg1.find("="); if (p != string::npos) { - val1 = arg1.substr(p+1); + val1 = arg1.substr(p + 1); arg1 = arg1.substr(0, p); } auto action = new AttrmapRemove; @@ -220,7 +219,7 @@ bool parse_attrmap_paramap_options(size_t &argidx, std::vector &arg } struct AttrmapPass : public Pass { - AttrmapPass() : Pass("attrmap", "renaming attributes") { } + AttrmapPass() : Pass("attrmap", "renaming attributes") {} void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| @@ -249,8 +248,7 @@ struct AttrmapPass : public Pass { vector> actions; size_t argidx; - for (argidx = 1; argidx < args.size(); argidx++) - { + for (argidx = 1; argidx < args.size(); argidx++) { if (parse_attrmap_paramap_options(argidx, args, actions)) continue; if (args[argidx] == "-modattr") { @@ -261,35 +259,31 @@ struct AttrmapPass : public Pass { } extra_args(args, argidx, design); - if (modattr_mode) - { + if (modattr_mode) { for (auto module : design->selected_whole_modules()) attrmap_apply(stringf("%s", log_id(module)), actions, module->attributes); - } - else - { - for (auto module : design->selected_modules()) - { + } else { + for (auto module : design->selected_modules()) { for (auto wire : module->selected_wires()) attrmap_apply(stringf("%s.%s", log_id(module), log_id(wire)), actions, wire->attributes); for (auto cell : module->selected_cells()) attrmap_apply(stringf("%s.%s", log_id(module), log_id(cell)), actions, cell->attributes); - for (auto proc : module->processes) - { + for (auto proc : module->processes) { if (!design->selected(module, proc.second)) continue; attrmap_apply(stringf("%s.%s", log_id(module), log_id(proc.first)), actions, proc.second->attributes); - std::vector all_cases = {&proc.second->root_case}; + std::vector all_cases = {&proc.second->root_case}; while (!all_cases.empty()) { RTLIL::CaseRule *cs = all_cases.back(); all_cases.pop_back(); attrmap_apply(stringf("%s.%s (case)", log_id(module), log_id(proc.first)), actions, cs->attributes); for (auto &sw : cs->switches) { - attrmap_apply(stringf("%s.%s (switch)", log_id(module), log_id(proc.first)), actions, sw->attributes); + attrmap_apply(stringf("%s.%s (switch)", log_id(module), log_id(proc.first)), actions, + sw->attributes); all_cases.insert(all_cases.end(), sw->cases.begin(), sw->cases.end()); } } @@ -300,7 +294,7 @@ struct AttrmapPass : public Pass { } AttrmapPass; struct ParamapPass : public Pass { - ParamapPass() : Pass("paramap", "renaming cell parameters") { } + ParamapPass() : Pass("paramap", "renaming cell parameters") {} void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| @@ -324,8 +318,7 @@ struct ParamapPass : public Pass { vector> actions; size_t argidx; - for (argidx = 1; argidx < args.size(); argidx++) - { + for (argidx = 1; argidx < args.size(); argidx++) { if (parse_attrmap_paramap_options(argidx, args, actions)) continue; break; @@ -333,8 +326,8 @@ struct ParamapPass : public Pass { extra_args(args, argidx, design); for (auto module : design->selected_modules()) - for (auto cell : module->selected_cells()) - attrmap_apply(stringf("%s.%s", log_id(module), log_id(cell)), actions, cell->parameters); + for (auto cell : module->selected_cells()) + attrmap_apply(stringf("%s.%s", log_id(module), log_id(cell)), actions, cell->parameters); } } ParamapPass; diff --git a/passes/techmap/attrmvcp.cc b/passes/techmap/attrmvcp.cc index 65b63daf1df..e7d5a0de9a1 100644 --- a/passes/techmap/attrmvcp.cc +++ b/passes/techmap/attrmvcp.cc @@ -17,14 +17,14 @@ * */ -#include "kernel/yosys.h" #include "kernel/sigtools.h" +#include "kernel/yosys.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct AttrmvcpPass : public Pass { - AttrmvcpPass() : Pass("attrmvcp", "move or copy attributes from wires to driving cells") { } + AttrmvcpPass() : Pass("attrmvcp", "move or copy attributes from wires to driving cells") {} void help() override { log("\n"); @@ -63,8 +63,7 @@ struct AttrmvcpPass : public Pass { pool attrnames; size_t argidx; - for (argidx = 1; argidx < args.size(); argidx++) - { + for (argidx = 1; argidx < args.size(); argidx++) { std::string arg = args[argidx]; if (arg == "-copy") { copy_mode = true; @@ -78,7 +77,7 @@ struct AttrmvcpPass : public Pass { purge_mode = true; continue; } - if (arg == "-attr" && argidx+1 < args.size()) { + if (arg == "-attr" && argidx + 1 < args.size()) { attrnames.insert(RTLIL::escape_id(args[++argidx])); continue; } @@ -86,31 +85,27 @@ struct AttrmvcpPass : public Pass { } extra_args(args, argidx, design); - for (auto module : design->selected_modules()) - { - dict> net2cells; + for (auto module : design->selected_modules()) { + dict> net2cells; SigMap sigmap(module); for (auto cell : module->selected_cells()) - for (auto &conn : cell->connections()) - { - if (driven_mode) { - if (cell->input(conn.first)) - for (auto bit : sigmap(conn.second)) - net2cells[bit].insert(cell); - } else { - if (cell->output(conn.first)) - for (auto bit : sigmap(conn.second)) - net2cells[bit].insert(cell); + for (auto &conn : cell->connections()) { + if (driven_mode) { + if (cell->input(conn.first)) + for (auto bit : sigmap(conn.second)) + net2cells[bit].insert(cell); + } else { + if (cell->output(conn.first)) + for (auto bit : sigmap(conn.second)) + net2cells[bit].insert(cell); + } } - } - for (auto wire : module->selected_wires()) - { + for (auto wire : module->selected_wires()) { dict new_attributes; - for (auto attr : wire->attributes) - { + for (auto attr : wire->attributes) { bool did_something = false; if (!attrnames.count(attr.first)) { @@ -121,8 +116,9 @@ struct AttrmvcpPass : public Pass { for (auto bit : sigmap(wire)) if (net2cells.count(bit)) for (auto cell : net2cells.at(bit)) { - log("Moving attribute %s=%s from %s.%s to %s.%s.\n", log_id(attr.first), log_const(attr.second), - log_id(module), log_id(wire), log_id(module), log_id(cell)); + log("Moving attribute %s=%s from %s.%s to %s.%s.\n", log_id(attr.first), + log_const(attr.second), log_id(module), log_id(wire), log_id(module), + log_id(cell)); cell->attributes[attr.first] = attr.second; did_something = true; } diff --git a/passes/techmap/bmuxmap.cc b/passes/techmap/bmuxmap.cc index 7aa67d3c071..6fd9a7dc424 100644 --- a/passes/techmap/bmuxmap.cc +++ b/passes/techmap/bmuxmap.cc @@ -17,14 +17,14 @@ * */ -#include "kernel/yosys.h" #include "kernel/sigtools.h" +#include "kernel/yosys.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct BmuxmapPass : public Pass { - BmuxmapPass() : Pass("bmuxmap", "transform $bmux cells to trees of $mux cells") { } + BmuxmapPass() : Pass("bmuxmap", "transform $bmux cells to trees of $mux cells") {} void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| @@ -54,49 +54,42 @@ struct BmuxmapPass : public Pass { extra_args(args, argidx, design); for (auto module : design->selected_modules()) - for (auto cell : module->selected_cells()) - { - if (cell->type != ID($bmux)) - continue; + for (auto cell : module->selected_cells()) { + if (cell->type != ID($bmux)) + continue; - SigSpec sel = cell->getPort(ID::S); - SigSpec data = cell->getPort(ID::A); - int width = GetSize(cell->getPort(ID::Y)); - int s_width = GetSize(cell->getPort(ID::S)); + SigSpec sel = cell->getPort(ID::S); + SigSpec data = cell->getPort(ID::A); + int width = GetSize(cell->getPort(ID::Y)); + int s_width = GetSize(cell->getPort(ID::S)); - if(pmux_mode) - { - int num_cases = 1 << s_width; - SigSpec new_a = SigSpec(State::Sx, width); - SigSpec new_s = module->addWire(NEW_ID, num_cases); - SigSpec new_data = module->addWire(NEW_ID, width); - for (int val = 0; val < num_cases; val++) - { - module->addEq(NEW_ID, sel, SigSpec(val, GetSize(sel)), new_s[val]); - } - RTLIL::Cell *pmux = module->addPmux(NEW_ID, new_a, data, new_s, new_data); - pmux->add_strpool_attribute(ID::src, cell->get_strpool_attribute(ID::src)); - data = new_data; - } - else - { - for (int idx = 0; idx < GetSize(sel); idx++) { - SigSpec new_data = module->addWire(NEW_ID, GetSize(data)/2); - for (int i = 0; i < GetSize(new_data); i += width) { - RTLIL::Cell *mux = module->addMux(NEW_ID, - data.extract(i*2, width), - data.extract(i*2+width, width), - sel[idx], - new_data.extract(i, width)); - mux->add_strpool_attribute(ID::src, cell->get_strpool_attribute(ID::src)); + if (pmux_mode) { + int num_cases = 1 << s_width; + SigSpec new_a = SigSpec(State::Sx, width); + SigSpec new_s = module->addWire(NEW_ID, num_cases); + SigSpec new_data = module->addWire(NEW_ID, width); + for (int val = 0; val < num_cases; val++) { + module->addEq(NEW_ID, sel, SigSpec(val, GetSize(sel)), new_s[val]); } + RTLIL::Cell *pmux = module->addPmux(NEW_ID, new_a, data, new_s, new_data); + pmux->add_strpool_attribute(ID::src, cell->get_strpool_attribute(ID::src)); data = new_data; + } else { + for (int idx = 0; idx < GetSize(sel); idx++) { + SigSpec new_data = module->addWire(NEW_ID, GetSize(data) / 2); + for (int i = 0; i < GetSize(new_data); i += width) { + RTLIL::Cell *mux = + module->addMux(NEW_ID, data.extract(i * 2, width), data.extract(i * 2 + width, width), + sel[idx], new_data.extract(i, width)); + mux->add_strpool_attribute(ID::src, cell->get_strpool_attribute(ID::src)); + } + data = new_data; + } } - } - module->connect(cell->getPort(ID::Y), data); - module->remove(cell); - } + module->connect(cell->getPort(ID::Y), data); + module->remove(cell); + } } } BmuxmapPass; diff --git a/passes/techmap/bwmuxmap.cc b/passes/techmap/bwmuxmap.cc index 7fe1cded777..e772727b5d8 100644 --- a/passes/techmap/bwmuxmap.cc +++ b/passes/techmap/bwmuxmap.cc @@ -48,22 +48,21 @@ struct BwmuxmapPass : public Pass { extra_args(args, argidx, design); for (auto module : design->selected_modules()) - for (auto cell : module->selected_cells()) - { - if (cell->type != ID($bwmux)) - continue; - auto &sig_y = cell->getPort(ID::Y); - auto &sig_a = cell->getPort(ID::A); - auto &sig_b = cell->getPort(ID::B); - auto &sig_s = cell->getPort(ID::S); + for (auto cell : module->selected_cells()) { + if (cell->type != ID($bwmux)) + continue; + auto &sig_y = cell->getPort(ID::Y); + auto &sig_a = cell->getPort(ID::A); + auto &sig_b = cell->getPort(ID::B); + auto &sig_s = cell->getPort(ID::S); - auto not_s = module->Not(NEW_ID, sig_s); - auto masked_b = module->And(NEW_ID, sig_s, sig_b); - auto masked_a = module->And(NEW_ID, not_s, sig_a); - module->addOr(NEW_ID, masked_a, masked_b, sig_y); + auto not_s = module->Not(NEW_ID, sig_s); + auto masked_b = module->And(NEW_ID, sig_s, sig_b); + auto masked_a = module->And(NEW_ID, not_s, sig_a); + module->addOr(NEW_ID, masked_a, masked_b, sig_y); - module->remove(cell); - } + module->remove(cell); + } } } BwmuxmapPass; diff --git a/passes/techmap/clkbufmap.cc b/passes/techmap/clkbufmap.cc index a7b96a9c6e9..9a28912597b 100644 --- a/passes/techmap/clkbufmap.cc +++ b/passes/techmap/clkbufmap.cc @@ -18,8 +18,8 @@ * */ -#include "kernel/yosys.h" #include "kernel/sigtools.h" +#include "kernel/yosys.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN @@ -28,13 +28,13 @@ void split_portname_pair(std::string &port1, std::string &port2) { size_t pos = port1.find_first_of(':'); if (pos != std::string::npos) { - port2 = port1.substr(pos+1); + port2 = port1.substr(pos + 1); port1 = port1.substr(0, pos); } } struct ClkbufmapPass : public Pass { - ClkbufmapPass() : Pass("clkbufmap", "insert clock buffers on clock networks") { } + ClkbufmapPass() : Pass("clkbufmap", "insert clock buffers on clock networks") {} void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| @@ -64,7 +64,8 @@ struct ClkbufmapPass : public Pass { log("At least one of -buf or -inpad should be specified.\n"); } - void module_queue(Design *design, Module *module, std::vector &modules_sorted, pool &modules_processed) { + void module_queue(Design *design, Module *module, std::vector &modules_sorted, pool &modules_processed) + { if (modules_processed.count(module)) return; for (auto cell : module->cells()) { @@ -85,16 +86,15 @@ struct ClkbufmapPass : public Pass { std::string inpad_celltype, inpad_portname, inpad_portname2; size_t argidx; - for (argidx = 1; argidx < args.size(); argidx++) - { + for (argidx = 1; argidx < args.size(); argidx++) { std::string arg = args[argidx]; - if (arg == "-buf" && argidx+2 < args.size()) { + if (arg == "-buf" && argidx + 2 < args.size()) { buf_celltype = args[++argidx]; buf_portname = args[++argidx]; split_portname_pair(buf_portname, buf_portname2); continue; } - if (arg == "-inpad" && argidx+2 < args.size()) { + if (arg == "-inpad" && argidx + 2 < args.size()) { inpad_celltype = args[++argidx]; inpad_portname = args[++argidx]; split_portname_pair(inpad_portname, inpad_portname2); @@ -135,8 +135,7 @@ struct ClkbufmapPass : public Pass { for (auto module : design->selected_modules()) module_queue(design, module, modules_sorted, modules_processed); - for (auto module : modules_sorted) - { + for (auto module : modules_sorted) { if (module->get_blackbox_attribute()) { for (auto port : module->ports) { auto wire = module->wire(port); @@ -166,62 +165,60 @@ struct ClkbufmapPass : public Pass { // First, collect nets that could use a clock buffer. for (auto cell : module->cells()) - for (auto port : cell->connections()) - for (int i = 0; i < port.second.size(); i++) - if (sink_ports.count(make_pair(cell->type, make_pair(port.first, i)))) - sink_wire_bits.insert(sigmap(port.second[i])); + for (auto port : cell->connections()) + for (int i = 0; i < port.second.size(); i++) + if (sink_ports.count(make_pair(cell->type, make_pair(port.first, i)))) + sink_wire_bits.insert(sigmap(port.second[i])); // Second, collect ones that already have a clock buffer. for (auto cell : module->cells()) - for (auto port : cell->connections()) - for (int i = 0; i < port.second.size(); i++) - if (buf_ports.count(make_pair(cell->type, make_pair(port.first, i)))) - buf_wire_bits.insert(sigmap(port.second[i])); + for (auto port : cell->connections()) + for (int i = 0; i < port.second.size(); i++) + if (buf_ports.count(make_pair(cell->type, make_pair(port.first, i)))) + buf_wire_bits.insert(sigmap(port.second[i])); // Third, propagate tags through inverters. bool retry = true; while (retry) { retry = false; for (auto cell : module->cells()) - for (auto port : cell->connections()) - for (int i = 0; i < port.second.size(); i++) { - auto it = inv_ports_out.find(make_pair(cell->type, make_pair(port.first, i))); - auto bit = sigmap(port.second[i]); - // If output of an inverter is connected to a sink, mark it as buffered, - // and request a buffer on the inverter's input instead. - if (it != inv_ports_out.end() && !buf_wire_bits.count(bit) && sink_wire_bits.count(bit)) { - buf_wire_bits.insert(bit); - auto other_bit = sigmap(cell->getPort(it->second.first)[it->second.second]); - sink_wire_bits.insert(other_bit); - retry = true; - } - // If input of an inverter is marked as already-buffered, - // mark its output already-buffered as well. - auto it2 = inv_ports_in.find(make_pair(cell->type, make_pair(port.first, i))); - if (it2 != inv_ports_in.end() && buf_wire_bits.count(bit)) { - auto other_bit = sigmap(cell->getPort(it2->second.first)[it2->second.second]); - if (!buf_wire_bits.count(other_bit)) { - buf_wire_bits.insert(other_bit); - retry = true; + for (auto port : cell->connections()) + for (int i = 0; i < port.second.size(); i++) { + auto it = inv_ports_out.find(make_pair(cell->type, make_pair(port.first, i))); + auto bit = sigmap(port.second[i]); + // If output of an inverter is connected to a sink, mark it as buffered, + // and request a buffer on the inverter's input instead. + if (it != inv_ports_out.end() && !buf_wire_bits.count(bit) && sink_wire_bits.count(bit)) { + buf_wire_bits.insert(bit); + auto other_bit = sigmap(cell->getPort(it->second.first)[it->second.second]); + sink_wire_bits.insert(other_bit); + retry = true; + } + // If input of an inverter is marked as already-buffered, + // mark its output already-buffered as well. + auto it2 = inv_ports_in.find(make_pair(cell->type, make_pair(port.first, i))); + if (it2 != inv_ports_in.end() && buf_wire_bits.count(bit)) { + auto other_bit = sigmap(cell->getPort(it2->second.first)[it2->second.second]); + if (!buf_wire_bits.count(other_bit)) { + buf_wire_bits.insert(other_bit); + retry = true; + } + } } - } - - } }; // Collect all driven bits. for (auto cell : module->cells()) - for (auto port : cell->connections()) - if (cell->output(port.first)) - for (int i = 0; i < port.second.size(); i++) - driven_wire_bits.insert(port.second[i]); + for (auto port : cell->connections()) + if (cell->output(port.first)) + for (int i = 0; i < port.second.size(); i++) + driven_wire_bits.insert(port.second[i]); // Insert buffers. std::vector> input_queue; // Copy current wire list, as we will be adding new ones during iteration. std::vector wires(module->wires()); - for (auto wire : wires) - { + for (auto wire : wires) { // Should not happen. if (wire->port_input && wire->port_output) continue; @@ -239,8 +236,7 @@ struct ClkbufmapPass : public Pass { pool input_bits; - for (int i = 0; i < GetSize(wire); i++) - { + for (int i = 0; i < GetSize(wire); i++) { SigBit wire_bit(wire, i); SigBit mapped_wire_bit = sigmap(wire_bit); if (buf_wire_bits.count(mapped_wire_bit)) { @@ -312,8 +308,7 @@ struct ClkbufmapPass : public Pass { for (auto wire : module->selected_wires()) { if (wire->port_input || !wire->port_output) continue; - for (int i = 0; i < GetSize(wire); i++) - { + for (int i = 0; i < GetSize(wire); i++) { SigBit wire_bit(wire, i); SigBit mapped_wire_bit = sigmap(wire_bit); if (buffered_bits.count(mapped_wire_bit)) @@ -323,24 +318,24 @@ struct ClkbufmapPass : public Pass { // Reconnect the drivers to buffer inputs. for (auto cell : module->cells()) - for (auto port : cell->connections()) { - if (!cell->output(port.first)) - continue; - SigSpec sig = port.second; - bool newsig = false; - for (auto &bit : sig) { - const auto it = buffered_bits.find(sigmap(bit)); - if (it == buffered_bits.end()) - continue; - // Avoid substituting buffer's own output pin. - if (cell == it->second.first) + for (auto port : cell->connections()) { + if (!cell->output(port.first)) continue; - bit = it->second.second; - newsig = true; + SigSpec sig = port.second; + bool newsig = false; + for (auto &bit : sig) { + const auto it = buffered_bits.find(sigmap(bit)); + if (it == buffered_bits.end()) + continue; + // Avoid substituting buffer's own output pin. + if (cell == it->second.first) + continue; + bit = it->second.second; + newsig = true; + } + if (newsig) + cell->setPort(port.first, sig); } - if (newsig) - cell->setPort(port.first, sig); - } // This has to be done last, to avoid upsetting sigmap before the port reconnections. for (auto &it : input_queue) { diff --git a/passes/techmap/deminout.cc b/passes/techmap/deminout.cc index 5245331f8af..3c54cc283d2 100644 --- a/passes/techmap/deminout.cc +++ b/passes/techmap/deminout.cc @@ -17,14 +17,14 @@ * */ -#include "kernel/yosys.h" #include "kernel/sigtools.h" +#include "kernel/yosys.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct DeminoutPass : public Pass { - DeminoutPass() : Pass("deminout", "demote inout ports to input or output") { } + DeminoutPass() : Pass("deminout", "demote inout ports to input or output") {} void help() override { log("\n"); @@ -38,8 +38,7 @@ struct DeminoutPass : public Pass { log_header(design, "Executing DEMINOUT pass (demote inout ports to input or output).\n"); size_t argidx; - for (argidx = 1; argidx < args.size(); argidx++) - { + for (argidx = 1; argidx < args.size(); argidx++) { // if (args[argidx] == "-bits") { // flag_bits = true; // continue; @@ -50,12 +49,10 @@ struct DeminoutPass : public Pass { bool keep_running = true; - while (keep_running) - { + while (keep_running) { keep_running = false; - for (auto module : design->selected_modules()) - { + for (auto module : design->selected_modules()) { SigMap sigmap(module); pool bits_written, bits_used, bits_inout, bits_tribuf; dict bits_numports; @@ -66,51 +63,47 @@ struct DeminoutPass : public Pass { bits_numports[bit]++; for (auto cell : module->cells()) - for (auto &conn : cell->connections()) - { - bool cellport_out = cell->output(conn.first) || !cell->known(); - bool cellport_in = cell->input(conn.first) || !cell->known(); - - if (cellport_out && cellport_in) - for (auto bit : sigmap(conn.second)) - bits_inout.insert(bit); - - if (cellport_out) - for (auto bit : sigmap(conn.second)) - bits_written.insert(bit); - - if (cellport_in) - for (auto bit : sigmap(conn.second)) - bits_used.insert(bit); - - if (conn.first == ID::Y && cell->type.in(ID($mux), ID($pmux), ID($_MUX_), ID($_TBUF_), ID($tribuf))) - { - bool tribuf = cell->type.in(ID($_TBUF_), ID($tribuf)); - - if (!tribuf) { - for (auto &c : cell->connections()) { - if (!c.first.in(ID::A, ID::B)) - continue; - for (auto b : sigmap(c.second)) - if (b == State::Sz) - tribuf = true; - } - } + for (auto &conn : cell->connections()) { + bool cellport_out = cell->output(conn.first) || !cell->known(); + bool cellport_in = cell->input(conn.first) || !cell->known(); + + if (cellport_out && cellport_in) + for (auto bit : sigmap(conn.second)) + bits_inout.insert(bit); - if (tribuf) + if (cellport_out) for (auto bit : sigmap(conn.second)) - bits_tribuf.insert(bit); + bits_written.insert(bit); + + if (cellport_in) + for (auto bit : sigmap(conn.second)) + bits_used.insert(bit); + + if (conn.first == ID::Y && cell->type.in(ID($mux), ID($pmux), ID($_MUX_), ID($_TBUF_), ID($tribuf))) { + bool tribuf = cell->type.in(ID($_TBUF_), ID($tribuf)); + + if (!tribuf) { + for (auto &c : cell->connections()) { + if (!c.first.in(ID::A, ID::B)) + continue; + for (auto b : sigmap(c.second)) + if (b == State::Sz) + tribuf = true; + } + } + + if (tribuf) + for (auto bit : sigmap(conn.second)) + bits_tribuf.insert(bit); + } } - } for (auto wire : module->selected_wires()) - if (wire->port_input && wire->port_output) - { + if (wire->port_input && wire->port_output) { bool new_input = false; bool new_output = false; - for (auto bit : sigmap(wire)) - { + for (auto bit : sigmap(wire)) { if (bits_numports[bit] > 1 || bits_inout.count(bit)) new_input = true, new_output = true; if (!bit.wire) @@ -120,13 +113,14 @@ struct DeminoutPass : public Pass { if (bits_tribuf.count(bit)) goto tribuf_bit; } else { - tribuf_bit: + tribuf_bit: new_input = true; } } if (new_input != new_output) { - log("Demoting inout port %s.%s to %s.\n", log_id(module), log_id(wire), new_input ? "input" : "output"); + log("Demoting inout port %s.%s to %s.\n", log_id(module), log_id(wire), + new_input ? "input" : "output"); wire->port_input = new_input; wire->port_output = new_output; keep_running = true; diff --git a/passes/techmap/demuxmap.cc b/passes/techmap/demuxmap.cc index 292b18badf0..2026cdad3a3 100644 --- a/passes/techmap/demuxmap.cc +++ b/passes/techmap/demuxmap.cc @@ -17,14 +17,14 @@ * */ -#include "kernel/yosys.h" #include "kernel/sigtools.h" +#include "kernel/yosys.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct DemuxmapPass : public Pass { - DemuxmapPass() : Pass("demuxmap", "transform $demux cells to $eq + $mux cells") { } + DemuxmapPass() : Pass("demuxmap", "transform $demux cells to $eq + $mux cells") {} void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| @@ -45,35 +45,31 @@ struct DemuxmapPass : public Pass { extra_args(args, argidx, design); for (auto module : design->selected_modules()) - for (auto cell : module->selected_cells()) - { - if (cell->type != ID($demux)) - continue; + for (auto cell : module->selected_cells()) { + if (cell->type != ID($demux)) + continue; - SigSpec sel = cell->getPort(ID::S); - SigSpec data = cell->getPort(ID::A); - SigSpec out = cell->getPort(ID::Y); - int width = GetSize(cell->getPort(ID::A)); + SigSpec sel = cell->getPort(ID::S); + SigSpec data = cell->getPort(ID::A); + SigSpec out = cell->getPort(ID::Y); + int width = GetSize(cell->getPort(ID::A)); - for (int i = 0; i < 1 << GetSize(sel); i++) { - if (width == 1 && data == State::S1) { - RTLIL::Cell *eq_cell = module->addEq(NEW_ID, sel, Const(i, GetSize(sel)), out[i]); - eq_cell->add_strpool_attribute(ID::src, cell->get_strpool_attribute(ID::src)); - } else { - Wire *eq = module->addWire(NEW_ID); - RTLIL::Cell *eq_cell = module->addEq(NEW_ID, sel, Const(i, GetSize(sel)), eq); - eq_cell->add_strpool_attribute(ID::src, cell->get_strpool_attribute(ID::src)); - RTLIL::Cell *mux = module->addMux(NEW_ID, - Const(State::S0, width), - data, - eq, - out.extract(i*width, width)); - mux->add_strpool_attribute(ID::src, cell->get_strpool_attribute(ID::src)); + for (int i = 0; i < 1 << GetSize(sel); i++) { + if (width == 1 && data == State::S1) { + RTLIL::Cell *eq_cell = module->addEq(NEW_ID, sel, Const(i, GetSize(sel)), out[i]); + eq_cell->add_strpool_attribute(ID::src, cell->get_strpool_attribute(ID::src)); + } else { + Wire *eq = module->addWire(NEW_ID); + RTLIL::Cell *eq_cell = module->addEq(NEW_ID, sel, Const(i, GetSize(sel)), eq); + eq_cell->add_strpool_attribute(ID::src, cell->get_strpool_attribute(ID::src)); + RTLIL::Cell *mux = + module->addMux(NEW_ID, Const(State::S0, width), data, eq, out.extract(i * width, width)); + mux->add_strpool_attribute(ID::src, cell->get_strpool_attribute(ID::src)); + } } - } - module->remove(cell); - } + module->remove(cell); + } } } DemuxmapPass; diff --git a/passes/techmap/dffinit.cc b/passes/techmap/dffinit.cc index 9cfe55947ba..1d31e46eefc 100644 --- a/passes/techmap/dffinit.cc +++ b/passes/techmap/dffinit.cc @@ -17,15 +17,15 @@ * */ -#include "kernel/yosys.h" -#include "kernel/sigtools.h" #include "kernel/ffinit.h" +#include "kernel/sigtools.h" +#include "kernel/yosys.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct DffinitPass : public Pass { - DffinitPass() : Pass("dffinit", "set INIT param on FF cells") { } + DffinitPass() : Pass("dffinit", "set INIT param on FF cells") {} void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| @@ -71,13 +71,13 @@ struct DffinitPass : public Pass { low_string = "low"; continue; } - if (args[argidx] == "-strinit" && argidx+2 < args.size()) { + if (args[argidx] == "-strinit" && argidx + 2 < args.size()) { highlow_mode = true; high_string = args[++argidx]; low_string = args[++argidx]; continue; } - if (args[argidx] == "-ff" && argidx+3 < args.size()) { + if (args[argidx] == "-ff" && argidx + 3 < args.size()) { IdString cell_name = RTLIL::escape_id(args[++argidx]); IdString output_port = RTLIL::escape_id(args[++argidx]); IdString init_param = RTLIL::escape_id(args[++argidx]); @@ -92,18 +92,15 @@ struct DffinitPass : public Pass { } extra_args(args, argidx, design); - for (auto module : design->selected_modules()) - { + for (auto module : design->selected_modules()) { SigMap sigmap(module); FfInitVals initvals(&sigmap, module); - for (auto cell : module->selected_cells()) - { + for (auto cell : module->selected_cells()) { if (ff_types.count(cell->type) == 0) continue; - for (auto &it : ff_types[cell->type]) - { + for (auto &it : ff_types[cell->type]) { if (!cell->hasPort(it.first)) continue; @@ -122,15 +119,15 @@ struct DffinitPass : public Pass { value.bits.push_back(State::S0); if (noreinit && value.bits[i] != State::Sx && value.bits[i] != initval[i]) log_error("Trying to assign a different init value for %s.%s.%s which technically " - "have a conflicted init value.\n", - log_id(module), log_id(cell), log_id(it.second)); + "have a conflicted init value.\n", + log_id(module), log_id(cell), log_id(it.second)); value.bits[i] = initval[i]; } if (highlow_mode && GetSize(value) != 0) { if (GetSize(value) != 1) log_error("Multi-bit init value for %s.%s.%s is incompatible with -highlow mode.\n", - log_id(module), log_id(cell), log_id(it.second)); + log_id(module), log_id(cell), log_id(it.second)); if (value[0] == State::S1) value = Const(high_string); else @@ -139,7 +136,7 @@ struct DffinitPass : public Pass { if (value.size() != 0) { log("Setting %s.%s.%s (port=%s, net=%s) to %s.\n", log_id(module), log_id(cell), log_id(it.second), - log_id(it.first), log_signal(sig), log_signal(value)); + log_id(it.first), log_signal(sig), log_signal(value)); cell->setParam(it.second, value); } } diff --git a/passes/techmap/dfflegalize.cc b/passes/techmap/dfflegalize.cc index 64f07b708c6..9c3b7f9865a 100644 --- a/passes/techmap/dfflegalize.cc +++ b/passes/techmap/dfflegalize.cc @@ -17,10 +17,10 @@ * */ -#include "kernel/yosys.h" -#include "kernel/sigtools.h" -#include "kernel/ffinit.h" #include "kernel/ff.h" +#include "kernel/ffinit.h" +#include "kernel/sigtools.h" +#include "kernel/yosys.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN @@ -67,7 +67,7 @@ enum FfInit { }; struct DffLegalizePass : public Pass { - DffLegalizePass() : Pass("dfflegalize", "convert FFs to types supported by the target") { } + DffLegalizePass() : Pass("dfflegalize", "convert FFs to types supported by the target") {} void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| @@ -139,7 +139,7 @@ struct DffLegalizePass : public Pass { } // Table of all supported cell types. - // First index in the array is one of the FF_* values, second + // First index in the array is one of the FF_* values, second // index is the set of negative-polarity inputs (OR of NEG_* // values), and the value is the set of supported init values // (OR of INIT_* values). @@ -182,7 +182,8 @@ struct DffLegalizePass : public Pass { SigMap sigmap; FfInitVals initvals; - int flip_initmask(int mask) { + int flip_initmask(int mask) + { int res = mask & INIT_X; if (mask & INIT_0) res |= INIT_1; @@ -203,7 +204,8 @@ struct DffLegalizePass : public Pass { return res; } - int get_ff_type(const FfData &ff) { + int get_ff_type(const FfData &ff) + { if (ff.has_clk) { if (ff.has_sr) { return ff.has_ce ? FF_DFFSRE : FF_DFFSR; @@ -240,7 +242,8 @@ struct DffLegalizePass : public Pass { } } - int get_initmask(FfData &ff) { + int get_initmask(FfData &ff) + { int res = 0; if (ff.val_init[0] == State::S0) res = INIT_0; @@ -262,11 +265,14 @@ struct DffLegalizePass : public Pass { return res; } - void fail_ff(const FfData &ff, const char *reason) { - log_error("FF %s.%s (type %s) cannot be legalized: %s\n", log_id(ff.module->name), log_id(ff.cell->name), log_id(ff.cell->type), reason); + void fail_ff(const FfData &ff, const char *reason) + { + log_error("FF %s.%s (type %s) cannot be legalized: %s\n", log_id(ff.module->name), log_id(ff.cell->name), log_id(ff.cell->type), + reason); } - bool try_flip(FfData &ff, int supported_mask) { + bool try_flip(FfData &ff, int supported_mask) + { int initmask = get_initmask(ff); if (supported_mask & initmask) return true; @@ -277,7 +283,8 @@ struct DffLegalizePass : public Pass { return false; } - void emulate_split_init_arst(FfData &ff) { + void emulate_split_init_arst(FfData &ff) + { ff.remove(); FfData ff_dff(ff.module, &initvals, NEW_ID); @@ -338,7 +345,8 @@ struct DffLegalizePass : public Pass { legalize_ff(ff_sel); } - void emulate_split_set_clr(FfData &ff) { + void emulate_split_set_clr(FfData &ff) + { // No native DFFSR. However, if we can conjure // a SR latch and ADFF, it can still be emulated. int initmask = get_initmask(ff); @@ -449,7 +457,8 @@ struct DffLegalizePass : public Pass { legalize_ff(ff_sel); } - void legalize_dff(FfData &ff) { + void legalize_dff(FfData &ff) + { if (!try_flip(ff, supported_dff)) { if (!supported_dff) fail_ff(ff, "D flip-flops are not supported"); @@ -529,7 +538,8 @@ struct DffLegalizePass : public Pass { log_assert(0); } - void legalize_sdffce(FfData &ff) { + void legalize_sdffce(FfData &ff) + { if (!try_flip(ff, supported_cells[FF_SDFFCE] | supported_cells[FF_SDFFE])) { ff.unmap_srst(); legalize_dff(ff); @@ -547,7 +557,8 @@ struct DffLegalizePass : public Pass { legalize_finish(ff); } - void legalize_sdff(FfData &ff) { + void legalize_sdff(FfData &ff) + { if (!try_flip(ff, supported_sdff)) { ff.unmap_srst(); legalize_dff(ff); @@ -581,7 +592,8 @@ struct DffLegalizePass : public Pass { legalize_finish(ff); } - void legalize_adff(FfData &ff) { + void legalize_adff(FfData &ff) + { if (!try_flip(ff, supported_adff)) { if (!supported_adff) fail_ff(ff, "dffs with async set or reset are not supported"); @@ -600,7 +612,8 @@ struct DffLegalizePass : public Pass { ff.unmap_ce(); if (ff.cell) - log_warning("Emulating mismatched async reset and init with several FFs and a mux for %s.%s\n", log_id(ff.module->name), log_id(ff.cell->name)); + log_warning("Emulating mismatched async reset and init with several FFs and a mux for %s.%s\n", + log_id(ff.module->name), log_id(ff.cell->name)); emulate_split_init_arst(ff); return; } @@ -648,7 +661,8 @@ struct DffLegalizePass : public Pass { log_assert(0); } - void legalize_aldff(FfData &ff) { + void legalize_aldff(FfData &ff) + { if (!try_flip(ff, supported_aldff)) { ff.aload_to_sr(); emulate_split_set_clr(ff); @@ -684,7 +698,8 @@ struct DffLegalizePass : public Pass { log_assert(0); } - void legalize_dffsr(FfData &ff) { + void legalize_dffsr(FfData &ff) + { if (!try_flip(ff, supported_dffsr)) { emulate_split_set_clr(ff); return; @@ -707,7 +722,8 @@ struct DffLegalizePass : public Pass { legalize_finish(ff); } - void legalize_dlatch(FfData &ff) { + void legalize_dlatch(FfData &ff) + { if (!try_flip(ff, supported_dlatch)) { if (!supported_dlatch) fail_ff(ff, "D latches are not supported"); @@ -740,7 +756,8 @@ struct DffLegalizePass : public Pass { } } - void legalize_adlatch(FfData &ff) { + void legalize_adlatch(FfData &ff) + { if (!try_flip(ff, supported_adlatch)) { if (!supported_adlatch) fail_ff(ff, "D latches with async set or reset are not supported"); @@ -752,7 +769,8 @@ struct DffLegalizePass : public Pass { // The only hope left is breaking down to adlatch + dlatch + dlatch + mux. if (ff.cell) - log_warning("Emulating mismatched async reset and init with several latches and a mux for %s.%s\n", log_id(ff.module->name), log_id(ff.cell->name)); + log_warning("Emulating mismatched async reset and init with several latches and a mux for %s.%s\n", + log_id(ff.module->name), log_id(ff.cell->name)); ff.remove(); emulate_split_init_arst(ff); @@ -769,7 +787,8 @@ struct DffLegalizePass : public Pass { legalize_finish(ff); } - void legalize_dlatchsr(FfData &ff) { + void legalize_dlatchsr(FfData &ff) + { if (!try_flip(ff, supported_cells[FF_DLATCHSR])) { emulate_split_set_clr(ff); return; @@ -777,7 +796,8 @@ struct DffLegalizePass : public Pass { legalize_finish(ff); } - void legalize_rlatch(FfData &ff) { + void legalize_rlatch(FfData &ff) + { if (!try_flip(ff, supported_rlatch)) { if (!supported_dlatch) fail_ff(ff, "D latches are not supported"); @@ -800,7 +820,8 @@ struct DffLegalizePass : public Pass { } } - void legalize_sr(FfData &ff) { + void legalize_sr(FfData &ff) + { if (!try_flip(ff, supported_sr)) { if (!supported_sr) fail_ff(ff, "sr latches are not supported"); @@ -857,7 +878,8 @@ struct DffLegalizePass : public Pass { legalize_finish(ff); } - void fixup_reset_x(FfData &ff, int supported) { + void fixup_reset_x(FfData &ff, int supported) + { for (int i = 0; i < ff.width; i++) { int mask; if (ff.val_init[i] == State::S0) @@ -885,7 +907,8 @@ struct DffLegalizePass : public Pass { } } - void legalize_ff(FfData &ff) { + void legalize_ff(FfData &ff) + { if (ff.has_gclk) return; @@ -932,7 +955,8 @@ struct DffLegalizePass : public Pass { } } - void flip_pol(FfData &ff, SigSpec &sig, bool &pol) { + void flip_pol(FfData &ff, SigSpec &sig, bool &pol) + { if (sig == State::S0) { sig = State::S1; } else if (sig == State::S1) { @@ -945,7 +969,8 @@ struct DffLegalizePass : public Pass { pol = !pol; } - void legalize_finish(FfData &ff) { + void legalize_finish(FfData &ff) + { int ff_type = get_ff_type(ff); int initmask = get_initmask(ff); log_assert(supported_cells[ff_type] & initmask); @@ -1025,8 +1050,7 @@ struct DffLegalizePass : public Pass { minsrst = design->scratchpad_get_int("dfflegalize.minsrst", 0); size_t argidx; - for (argidx = 1; argidx < args.size(); argidx++) - { + for (argidx = 1; argidx < args.size(); argidx++) { if (args[argidx] == "-cell" && argidx + 2 < args.size()) { std::string celltype = args[++argidx]; std::string inittype = args[++argidx]; @@ -1110,18 +1134,18 @@ struct DffLegalizePass : public Pass { pol_s = celltype[12]; pol_r = celltype[13]; } else { -unrecognized: + unrecognized: log_error("unrecognized cell type %s.\n", celltype.c_str()); } int mask = 0; int match = 0; for (auto pair : { - std::make_pair(pol_c, NEG_C), - std::make_pair(pol_l, NEG_L), - std::make_pair(pol_s, NEG_S), - std::make_pair(pol_r, NEG_R), - std::make_pair(pol_ce, NEG_CE), - }) { + std::make_pair(pol_c, NEG_C), + std::make_pair(pol_l, NEG_L), + std::make_pair(pol_s, NEG_S), + std::make_pair(pol_r, NEG_R), + std::make_pair(pol_ce, NEG_CE), + }) { if (pair.first == 'N') { mask |= pair.second; match |= pair.second; @@ -1176,18 +1200,19 @@ struct DffLegalizePass : public Pass { supported_adffe = supported_cells[FF_ADFFE] | supported_cells[FF_ALDFFE] | supported_cells[FF_DFFSRE]; supported_sdff = supported_cells[FF_SDFF] | supported_cells[FF_SDFFE] | supported_cells[FF_SDFFCE]; supported_dff = supported_cells[FF_DFF] | supported_cells[FF_DFFE] | supported_adff | supported_sdff; - supported_dffe = supported_cells[FF_DFFE] | supported_cells[FF_DFFSRE] | supported_cells[FF_ALDFFE] | supported_cells[FF_ADFFE] | supported_cells[FF_SDFFE] | supported_cells[FF_SDFFCE]; + supported_dffe = supported_cells[FF_DFFE] | supported_cells[FF_DFFSRE] | supported_cells[FF_ALDFFE] | supported_cells[FF_ADFFE] | + supported_cells[FF_SDFFE] | supported_cells[FF_SDFFCE]; supported_sr_plain = supported_dffsr | supported_cells[FF_DLATCHSR] | supported_cells[FF_SR]; supported_sr = supported_sr_plain; supported_sr |= (supported_cells[FF_ADLATCH] >> 4 & 7) * 0x111; supported_sr |= (flip_initmask(supported_cells[FF_ADLATCH]) >> 4 & 7) * 0x111; - supported_dlatch_plain = supported_cells[FF_DLATCH] | supported_cells[FF_ADLATCH] | supported_cells[FF_DLATCHSR] | supported_cells[FF_ALDFF] | supported_cells[FF_ALDFFE]; + supported_dlatch_plain = supported_cells[FF_DLATCH] | supported_cells[FF_ADLATCH] | supported_cells[FF_DLATCHSR] | + supported_cells[FF_ALDFF] | supported_cells[FF_ALDFFE]; supported_dlatch = supported_dlatch_plain | supported_sr_plain; supported_rlatch = supported_adff | (supported_dlatch & 7) * 0x111; supported_adlatch = supported_cells[FF_ADLATCH] | supported_cells[FF_DLATCHSR]; - for (auto module : design->selected_modules()) - { + for (auto module : design->selected_modules()) { sigmap.set(module); initvals.set(&sigmap, module); @@ -1206,8 +1231,7 @@ struct DffLegalizePass : public Pass { srst_used[ff.sig_srst[0]] += ff.width; } } - for (auto cell : module->selected_cells()) - { + for (auto cell : module->selected_cells()) { if (!RTLIL::builtin_ff_cell_types().count(cell->type)) continue; FfData ff(&initvals, cell); diff --git a/passes/techmap/dfflibmap.cc b/passes/techmap/dfflibmap.cc index 12c3a95de89..1ee89219c4b 100644 --- a/passes/techmap/dfflibmap.cc +++ b/passes/techmap/dfflibmap.cc @@ -17,11 +17,11 @@ * */ -#include "kernel/yosys.h" #include "kernel/sigtools.h" +#include "kernel/yosys.h" #include "libparse.h" -#include #include +#include USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN @@ -40,7 +40,7 @@ static void logmap(IdString dff) log(" %s %s (", cell_mappings[dff].cell_name.c_str(), dff.substr(1).c_str()); bool first = true; for (auto &port : cell_mappings[dff].ports) { - char arg[3] = { port.second, 0, 0 }; + char arg[3] = {port.second, 0, 0}; if ('a' <= arg[0] && arg[0] <= 'z') arg[1] = arg[0] - ('a' - 'A'), arg[0] = '~'; else @@ -86,11 +86,11 @@ static bool parse_pin(LibertyAst *cell, LibertyAst *attr, std::string &pin_name, for (size_t pos = value.find_first_of("\" \t()"); pos != std::string::npos; pos = value.find_first_of("\" \t()")) value.erase(pos, 1); - if (value[value.size()-1] == '\'') { - pin_name = value.substr(0, value.size()-1); + if (value[value.size() - 1] == '\'') { + pin_name = value.substr(0, value.size() - 1); pin_pol = false; } else if (value[0] == '!') { - pin_name = value.substr(1, value.size()-1); + pin_name = value.substr(1, value.size() - 1); pin_pol = false; } else { pin_name = value; @@ -107,8 +107,7 @@ static bool parse_pin(LibertyAst *cell, LibertyAst *attr, std::string &pin_name, */ if (pin_name.find_first_of("^*|&") == std::string::npos) { log_warning("Malformed liberty file - cannot find pin '%s' in cell '%s' - skipping.\n", pin_name.c_str(), cell->args[0].c_str()); - } - else { + } else { log_warning("Found unsupported expression '%s' in pin attribute of cell '%s' - skipping.\n", pin_name.c_str(), cell->args[0].c_str()); } @@ -126,8 +125,7 @@ static void find_cell(LibertyAst *ast, IdString cell_type, bool clkpol, bool has if (ast->id != "library") log_error("Format error in liberty file.\n"); - for (auto cell : ast->children) - { + for (auto cell : ast->children) { if (cell->id != "cell" || cell->args.size() != 1) continue; @@ -169,8 +167,7 @@ static void find_cell(LibertyAst *ast, IdString cell_type, bool clkpol, bool has int num_pins = 0; bool found_output = false; bool found_noninv_output = false; - for (auto pin : cell->children) - { + for (auto pin : cell->children) { if (pin->id != "pin" || pin->args.size() != 1) continue; @@ -192,8 +189,7 @@ static void find_cell(LibertyAst *ast, IdString cell_type, bool clkpol, bool has if (cell_next_pol) found_noninv_output = true; found_output = true; - } else - if (value == ff->args[1]) { + } else if (value == ff->args[1]) { this_cell_ports[pin->args[0]] = cell_next_pol ? 'q' : 'Q'; if (!cell_next_pol) found_noninv_output = true; @@ -220,8 +216,8 @@ static void find_cell(LibertyAst *ast, IdString cell_type, bool clkpol, bool has } if (best_cell != nullptr) { - log(" cell %s (%sinv, pins=%d, area=%.2f) is a direct match for cell type %s.\n", - best_cell->args[0].c_str(), best_cell_noninv ? "non" : "", best_cell_pins, best_cell_area, cell_type.c_str()); + log(" cell %s (%sinv, pins=%d, area=%.2f) is a direct match for cell type %s.\n", best_cell->args[0].c_str(), + best_cell_noninv ? "non" : "", best_cell_pins, best_cell_area, cell_type.c_str()); cell_mappings[cell_type].cell_name = RTLIL::escape_id(best_cell->args[0]); cell_mappings[cell_type].ports = best_cell_ports; } @@ -238,8 +234,7 @@ static void find_cell_sr(LibertyAst *ast, IdString cell_type, bool clkpol, bool if (ast->id != "library") log_error("Format error in liberty file.\n"); - for (auto cell : ast->children) - { + for (auto cell : ast->children) { if (cell->id != "cell" || cell->args.size() != 1) continue; @@ -277,8 +272,7 @@ static void find_cell_sr(LibertyAst *ast, IdString cell_type, bool clkpol, bool int num_pins = 0; bool found_output = false; bool found_noninv_output = false; - for (auto pin : cell->children) - { + for (auto pin : cell->children) { if (pin->id != "pin" || pin->args.size() != 1) continue; @@ -300,8 +294,7 @@ static void find_cell_sr(LibertyAst *ast, IdString cell_type, bool clkpol, bool if (cell_next_pol) found_noninv_output = true; found_output = true; - } else - if (value == ff->args[1]) { + } else if (value == ff->args[1]) { this_cell_ports[pin->args[0]] = cell_next_pol ? 'q' : 'Q'; if (!cell_next_pol) found_noninv_output = true; @@ -328,8 +321,8 @@ static void find_cell_sr(LibertyAst *ast, IdString cell_type, bool clkpol, bool } if (best_cell != nullptr) { - log(" cell %s (%sinv, pins=%d, area=%.2f) is a direct match for cell type %s.\n", - best_cell->args[0].c_str(), best_cell_noninv ? "non" : "", best_cell_pins, best_cell_area, cell_type.c_str()); + log(" cell %s (%sinv, pins=%d, area=%.2f) is a direct match for cell type %s.\n", best_cell->args[0].c_str(), + best_cell_noninv ? "non" : "", best_cell_pins, best_cell_area, cell_type.c_str()); cell_mappings[cell_type].cell_name = RTLIL::escape_id(best_cell->args[0]); cell_mappings[cell_type].ports = best_cell_ports; } @@ -339,10 +332,10 @@ static void dfflibmap(RTLIL::Design *design, RTLIL::Module *module) { log("Mapping DFF cells in module `%s':\n", module->name.c_str()); - dict> notmap; + dict> notmap; SigMap sigmap(module); - std::vector cell_list; + std::vector cell_list; for (auto cell : module->cells()) { if (design->selected(module, cell) && cell_mappings.count(cell->type) > 0) cell_list.push_back(cell); @@ -351,8 +344,7 @@ static void dfflibmap(RTLIL::Design *design, RTLIL::Module *module) } std::map stats; - for (auto cell : cell_list) - { + for (auto cell : cell_list) { auto cell_type = cell->type; auto cell_name = cell->name; auto cell_connections = cell->connections(); @@ -367,16 +359,17 @@ static void dfflibmap(RTLIL::Design *design, RTLIL::Module *module) bool has_q = false, has_qn = false; for (auto &port : cm.ports) { - if (port.second == 'Q') has_q = true; - if (port.second == 'q') has_qn = true; + if (port.second == 'Q') + has_q = true; + if (port.second == 'q') + has_qn = true; } for (auto &port : cm.ports) { RTLIL::SigSpec sig; if ('A' <= port.second && port.second <= 'Z') { sig = cell_connections[std::string("\\") + port.second]; - } else - if (port.second == 'q') { + } else if (port.second == 'q') { RTLIL::SigSpec old_sig = cell_connections[std::string("\\") + char(port.second - ('a' - 'A'))]; sig = module->addWire(NEW_ID, GetSize(old_sig)); if (has_q && has_qn) { @@ -387,15 +380,12 @@ static void dfflibmap(RTLIL::Design *design, RTLIL::Module *module) } else { module->addNotGate(NEW_ID, sig, old_sig); } - } else - if ('a' <= port.second && port.second <= 'z') { + } else if ('a' <= port.second && port.second <= 'z') { sig = cell_connections[std::string("\\") + char(port.second - ('a' - 'A'))]; sig = module->NotGate(NEW_ID, sig); - } else - if (port.second == '0' || port.second == '1') { + } else if (port.second == '0' || port.second == '1') { sig = RTLIL::SigSpec(port.second == '0' ? 0 : 1, 1); - } else - if (port.second == 0) { + } else if (port.second == 0) { sig = module->addWire(NEW_ID); } else log_abort(); @@ -405,12 +395,12 @@ static void dfflibmap(RTLIL::Design *design, RTLIL::Module *module) stats[stringf(" mapped %%d %s cells to %s cells.\n", cell_type.c_str(), new_cell->type.c_str())]++; } - for (auto &stat: stats) + for (auto &stat : stats) log(stat.first.c_str(), stat.second); } struct DfflibmapPass : public Pass { - DfflibmapPass() : Pass("dfflibmap", "technology mapping of flip-flops") { } + DfflibmapPass() : Pass("dfflibmap", "technology mapping of flip-flops") {} void help() override { log("\n"); @@ -447,10 +437,9 @@ struct DfflibmapPass : public Pass { bool info_mode = false; size_t argidx; - for (argidx = 1; argidx < args.size(); argidx++) - { + for (argidx = 1; argidx < args.size(); argidx++) { std::string arg = args[argidx]; - if (arg == "-liberty" && argidx+1 < args.size()) { + if (arg == "-liberty" && argidx + 1 < args.size()) { liberty_file = args[++argidx]; rewrite_filename(liberty_file); continue; diff --git a/passes/techmap/dffunmap.cc b/passes/techmap/dffunmap.cc index 8703bf1a037..488545dd810 100644 --- a/passes/techmap/dffunmap.cc +++ b/passes/techmap/dffunmap.cc @@ -17,15 +17,15 @@ * */ -#include "kernel/yosys.h" -#include "kernel/sigtools.h" #include "kernel/ff.h" +#include "kernel/sigtools.h" +#include "kernel/yosys.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct DffunmapPass : public Pass { - DffunmapPass() : Pass("dffunmap", "unmap clock enable and synchronous reset from FFs") { } + DffunmapPass() : Pass("dffunmap", "unmap clock enable and synchronous reset from FFs") {} void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| @@ -67,13 +67,11 @@ struct DffunmapPass : public Pass { if (ce_only && srst_only) log_cmd_error("Options -ce-only and -srst-only are mutually exclusive!\n"); - for (auto mod : design->selected_modules()) - { + for (auto mod : design->selected_modules()) { SigMap sigmap(mod); FfInitVals initvals(&sigmap, mod); - for (auto cell : mod->selected_cells()) - { + for (auto cell : mod->selected_cells()) { if (!RTLIL::builtin_ff_cell_types().count(cell->type)) continue; diff --git a/passes/techmap/extract.cc b/passes/techmap/extract.cc index 137d2217064..1ce8ec89967 100644 --- a/passes/techmap/extract.cc +++ b/passes/techmap/extract.cc @@ -17,13 +17,13 @@ * */ +#include "kernel/log.h" #include "kernel/register.h" #include "kernel/sigtools.h" -#include "kernel/log.h" #include "libs/subcircuit/subcircuit.h" #include -#include #include +#include #include USING_YOSYS_NAMESPACE @@ -31,16 +31,15 @@ PRIVATE_NAMESPACE_BEGIN class SubCircuitSolver : public SubCircuit::Solver { -public: + public: bool ignore_parameters; std::set> ignored_parameters; std::set cell_attr, wire_attr; - SubCircuitSolver() : ignore_parameters(false) - { - } + SubCircuitSolver() : ignore_parameters(false) {} - bool compareAttributes(const std::set &attr, const dict &needleAttr, const dict &haystackAttr) + bool compareAttributes(const std::set &attr, const dict &needleAttr, + const dict &haystackAttr) { for (auto &it : attr) { size_t nc = needleAttr.count(it), hc = haystackAttr.count(it); @@ -55,7 +54,9 @@ class SubCircuitSolver : public SubCircuit::Solver if (!cell_type.begins_with("$") || cell_type.begins_with("$_")) return value; - #define param_bool(_n) if (param == _n) return value.as_bool(); +#define param_bool(_n) \ + if (param == _n) \ + return value.as_bool(); param_bool(ID::ARST_POLARITY); param_bool(ID::A_SIGNED); param_bool(ID::B_SIGNED); @@ -65,38 +66,25 @@ class SubCircuitSolver : public SubCircuit::Solver param_bool(ID::EN_POLARITY); param_bool(ID::SET_POLARITY); param_bool(ID::TRANSPARENT); - #undef param_bool - - #define param_int(_n) if (param == _n) return value.as_int(); - param_int(ID::ABITS) - param_int(ID::A_WIDTH) - param_int(ID::B_WIDTH) - param_int(ID::CTRL_IN_WIDTH) - param_int(ID::CTRL_OUT_WIDTH) - param_int(ID::OFFSET) - param_int(ID::PORTID) - param_int(ID::PRIORITY) - param_int(ID::RD_PORTS) - param_int(ID::SIZE) - param_int(ID::STATE_BITS) - param_int(ID::STATE_NUM) - param_int(ID::STATE_NUM_LOG2) - param_int(ID::STATE_RST) - param_int(ID::S_WIDTH) - param_int(ID::TRANS_NUM) - param_int(ID::WIDTH) - param_int(ID::WR_PORTS) - param_int(ID::Y_WIDTH) - #undef param_int - - return value; +#undef param_bool + +#define param_int(_n) \ + if (param == _n) \ + return value.as_int(); + param_int(ID::ABITS) param_int(ID::A_WIDTH) param_int(ID::B_WIDTH) param_int(ID::CTRL_IN_WIDTH) param_int(ID::CTRL_OUT_WIDTH) + param_int(ID::OFFSET) param_int(ID::PORTID) param_int(ID::PRIORITY) param_int(ID::RD_PORTS) param_int(ID::SIZE) + param_int(ID::STATE_BITS) param_int(ID::STATE_NUM) param_int(ID::STATE_NUM_LOG2) param_int(ID::STATE_RST) param_int(ID::S_WIDTH) + param_int(ID::TRANS_NUM) param_int(ID::WIDTH) param_int(ID::WR_PORTS) param_int(ID::Y_WIDTH) +#undef param_int + + return value; } - virtual bool userCompareNodes(const std::string &, const std::string &, void *needleUserData, - const std::string &, const std::string &, void *haystackUserData, const std::map &portMapping) + virtual bool userCompareNodes(const std::string &, const std::string &, void *needleUserData, const std::string &, const std::string &, + void *haystackUserData, const std::map &portMapping) { - RTLIL::Cell *needleCell = (RTLIL::Cell*) needleUserData; - RTLIL::Cell *haystackCell = (RTLIL::Cell*) haystackUserData; + RTLIL::Cell *needleCell = (RTLIL::Cell *)needleUserData; + RTLIL::Cell *haystackCell = (RTLIL::Cell *)haystackUserData; if (!needleCell || !haystackCell) { log_assert(!needleCell && !haystackCell); @@ -118,21 +106,20 @@ class SubCircuitSolver : public SubCircuit::Solver if (cell_attr.size() > 0 && !compareAttributes(cell_attr, needleCell->attributes, haystackCell->attributes)) return false; - if (wire_attr.size() > 0) - { + if (wire_attr.size() > 0) { RTLIL::Wire *lastNeedleWire = nullptr; RTLIL::Wire *lastHaystackWire = nullptr; dict emptyAttr; - for (auto &conn : needleCell->connections()) - { + for (auto &conn : needleCell->connections()) { RTLIL::SigSpec needleSig = conn.second; RTLIL::SigSpec haystackSig = haystackCell->getPort(portMapping.at(conn.first.str())); for (int i = 0; i < min(needleSig.size(), haystackSig.size()); i++) { RTLIL::Wire *needleWire = needleSig[i].wire, *haystackWire = haystackSig[i].wire; if (needleWire != lastNeedleWire || haystackWire != lastHaystackWire) - if (!compareAttributes(wire_attr, needleWire ? needleWire->attributes : emptyAttr, haystackWire ? haystackWire->attributes : emptyAttr)) + if (!compareAttributes(wire_attr, needleWire ? needleWire->attributes : emptyAttr, + haystackWire ? haystackWire->attributes : emptyAttr)) return false; lastNeedleWire = needleWire, lastHaystackWire = haystackWire; } @@ -148,8 +135,8 @@ struct bit_ref_t { int bit; }; -bool module2graph(SubCircuit::Graph &graph, RTLIL::Module *mod, bool constports, RTLIL::Design *sel = nullptr, - int max_fanout = -1, std::set> *split = nullptr) +bool module2graph(SubCircuit::Graph &graph, RTLIL::Module *mod, bool constports, RTLIL::Design *sel = nullptr, int max_fanout = -1, + std::set> *split = nullptr) { SigMap sigmap(mod); std::map sig_bit_ref; @@ -179,33 +166,30 @@ bool module2graph(SubCircuit::Graph &graph, RTLIL::Module *mod, bool constports, graph.markExtern("$const$z", "\\Y", 0); } - std::map, int> sig_use_count; + std::map, int> sig_use_count; if (max_fanout > 0) - for (auto cell : mod->cells()) - { + for (auto cell : mod->cells()) { if (!sel || sel->selected(mod, cell)) for (auto &conn : cell->connections()) { RTLIL::SigSpec conn_sig = conn.second; sigmap.apply(conn_sig); for (auto &bit : conn_sig) if (bit.wire != nullptr) - sig_use_count[std::pair(bit.wire, bit.offset)]++; + sig_use_count[std::pair(bit.wire, bit.offset)]++; } } // create graph nodes from cells - for (auto cell : mod->cells()) - { + for (auto cell : mod->cells()) { if (sel && !sel->selected(mod, cell)) continue; std::string type = cell->type.str(); if (sel == nullptr && type.compare(0, 2, "\\$") == 0) type = type.substr(1); - graph.createNode(cell->name.str(), type, (void*)cell); + graph.createNode(cell->name.str(), type, (void *)cell); - for (auto &conn : cell->connections()) - { + for (auto &conn : cell->connections()) { graph.createPort(cell->name.str(), conn.first.str(), conn.second.size()); if (split && split->count(std::pair(cell->type, conn.first)) > 0) @@ -214,23 +198,25 @@ bool module2graph(SubCircuit::Graph &graph, RTLIL::Module *mod, bool constports, RTLIL::SigSpec conn_sig = conn.second; sigmap.apply(conn_sig); - for (int i = 0; i < conn_sig.size(); i++) - { + for (int i = 0; i < conn_sig.size(); i++) { auto &bit = conn_sig[i]; if (bit.wire == nullptr) { if (constports) { std::string node = "$const$x"; - if (bit == RTLIL::State::S0) node = "$const$0"; - if (bit == RTLIL::State::S1) node = "$const$1"; - if (bit == RTLIL::State::Sz) node = "$const$z"; + if (bit == RTLIL::State::S0) + node = "$const$0"; + if (bit == RTLIL::State::S1) + node = "$const$1"; + if (bit == RTLIL::State::Sz) + node = "$const$z"; graph.createConnection(cell->name.str(), conn.first.str(), i, node, "\\Y", 0); } else graph.createConstant(cell->name.str(), conn.first.str(), i, int(bit.data)); continue; } - if (max_fanout > 0 && sig_use_count[std::pair(bit.wire, bit.offset)] > max_fanout) + if (max_fanout > 0 && sig_use_count[std::pair(bit.wire, bit.offset)] > max_fanout) continue; if (sel && !sel->selected(mod, bit.wire)) @@ -250,11 +236,9 @@ bool module2graph(SubCircuit::Graph &graph, RTLIL::Module *mod, bool constports, } // mark external signals (used in non-selected cells) - for (auto cell : mod->cells()) - { + for (auto cell : mod->cells()) { if (sel && !sel->selected(mod, cell)) - for (auto &conn : cell->connections()) - { + for (auto &conn : cell->connections()) { RTLIL::SigSpec conn_sig = conn.second; sigmap.apply(conn_sig); @@ -267,10 +251,8 @@ bool module2graph(SubCircuit::Graph &graph, RTLIL::Module *mod, bool constports, } // mark external signals (used in module ports) - for (auto wire : mod->wires()) - { - if (wire->port_id > 0) - { + for (auto wire : mod->wires()) { + if (wire->port_id > 0) { RTLIL::SigSpec conn_sig(wire); sigmap.apply(conn_sig); @@ -304,11 +286,10 @@ RTLIL::Cell *replace(RTLIL::Module *needle, RTLIL::Module *haystack, SubCircuit: } // delete replaced cells and connect new ports - for (auto &it : match.mappings) - { + for (auto &it : match.mappings) { auto &mapping = it.second; - RTLIL::Cell *needle_cell = (RTLIL::Cell*)mapping.needleUserData; - RTLIL::Cell *haystack_cell = (RTLIL::Cell*)mapping.haystackUserData; + RTLIL::Cell *needle_cell = (RTLIL::Cell *)mapping.needleUserData; + RTLIL::Cell *haystack_cell = (RTLIL::Cell *)mapping.haystackUserData; if (needle_cell == nullptr) continue; @@ -317,12 +298,12 @@ RTLIL::Cell *replace(RTLIL::Module *needle, RTLIL::Module *haystack, SubCircuit: RTLIL::SigSpec sig = sigmap(conn.second); if (mapping.portMapping.count(conn.first.str()) > 0 && sig2port.has(sigmap(sig))) { for (int i = 0; i < sig.size(); i++) - for (auto &port : sig2port.find(sig[i])) { - RTLIL::SigSpec bitsig = haystack_cell->getPort(mapping.portMapping[conn.first.str()]).extract(i, 1); - RTLIL::SigSpec new_sig = cell->getPort(port.first); - new_sig.replace(port.second, bitsig); - cell->setPort(port.first, new_sig); - } + for (auto &port : sig2port.find(sig[i])) { + RTLIL::SigSpec bitsig = haystack_cell->getPort(mapping.portMapping[conn.first.str()]).extract(i, 1); + RTLIL::SigSpec new_sig = cell->getPort(port.first); + new_sig.replace(port.second, bitsig); + cell->setPort(port.first, new_sig); + } } } @@ -345,7 +326,7 @@ bool compareSortNeedleList(RTLIL::Module *left, RTLIL::Module *right) } struct ExtractPass : public Pass { - ExtractPass() : Pass("extract", "find subcircuits and replace them with cells") { } + ExtractPass() : Pass("extract", "find subcircuits and replace them with cells") {} void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| @@ -456,38 +437,39 @@ struct ExtractPass : public Pass { size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { - if (args[argidx] == "-map" && argidx+1 < args.size()) { + if (args[argidx] == "-map" && argidx + 1 < args.size()) { if (mine_mode) log_cmd_error("You cannot mix -map and -mine.\n"); map_filenames.push_back(args[++argidx]); continue; } - if (args[argidx] == "-mine" && argidx+1 < args.size()) { + if (args[argidx] == "-mine" && argidx + 1 < args.size()) { if (!map_filenames.empty()) log_cmd_error("You cannot mix -map and -mine.\n"); mine_outfile = args[++argidx]; mine_mode = true; continue; } - if (args[argidx] == "-mine_cells_span" && argidx+2 < args.size()) { + if (args[argidx] == "-mine_cells_span" && argidx + 2 < args.size()) { mine_cells_min = atoi(args[++argidx].c_str()); mine_cells_max = atoi(args[++argidx].c_str()); continue; } - if (args[argidx] == "-mine_min_freq" && argidx+1 < args.size()) { + if (args[argidx] == "-mine_min_freq" && argidx + 1 < args.size()) { mine_min_freq = atoi(args[++argidx].c_str()); continue; } - if (args[argidx] == "-mine_limit_matches_per_module" && argidx+1 < args.size()) { + if (args[argidx] == "-mine_limit_matches_per_module" && argidx + 1 < args.size()) { mine_limit_mod = atoi(args[++argidx].c_str()); continue; } - if (args[argidx] == "-mine_split" && argidx+2 < args.size()) { - mine_split.insert(std::pair(RTLIL::escape_id(args[argidx+1]), RTLIL::escape_id(args[argidx+2]))); + if (args[argidx] == "-mine_split" && argidx + 2 < args.size()) { + mine_split.insert(std::pair(RTLIL::escape_id(args[argidx + 1]), + RTLIL::escape_id(args[argidx + 2]))); argidx += 2; continue; } - if (args[argidx] == "-mine_max_fanout" && argidx+1 < args.size()) { + if (args[argidx] == "-mine_max_fanout" && argidx + 1 < args.size()) { mine_max_fanout = atoi(args[++argidx].c_str()); continue; } @@ -503,13 +485,13 @@ struct ExtractPass : public Pass { nodefaultswaps = true; continue; } - if (args[argidx] == "-compat" && argidx+2 < args.size()) { + if (args[argidx] == "-compat" && argidx + 2 < args.size()) { std::string needle_type = RTLIL::escape_id(args[++argidx]); std::string haystack_type = RTLIL::escape_id(args[++argidx]); solver.addCompatibleTypes(needle_type, haystack_type); continue; } - if (args[argidx] == "-swap" && argidx+2 < args.size()) { + if (args[argidx] == "-swap" && argidx + 2 < args.size()) { std::string type = RTLIL::escape_id(args[++argidx]); std::set ports; std::string ports_str = args[++argidx], p; @@ -518,7 +500,7 @@ struct ExtractPass : public Pass { solver.addSwappablePorts(type, ports); continue; } - if (args[argidx] == "-perm" && argidx+3 < args.size()) { + if (args[argidx] == "-perm" && argidx + 3 < args.size()) { std::string type = RTLIL::escape_id(args[++argidx]); std::vector map_left, map_right; std::string left_str = args[++argidx]; @@ -539,11 +521,11 @@ struct ExtractPass : public Pass { solver.addSwappablePortsPermutation(type, map); continue; } - if (args[argidx] == "-cell_attr" && argidx+1 < args.size()) { + if (args[argidx] == "-cell_attr" && argidx + 1 < args.size()) { solver.cell_attr.insert(RTLIL::escape_id(args[++argidx])); continue; } - if (args[argidx] == "-wire_attr" && argidx+1 < args.size()) { + if (args[argidx] == "-wire_attr" && argidx + 1 < args.size()) { solver.wire_attr.insert(RTLIL::escape_id(args[++argidx])); continue; } @@ -551,8 +533,9 @@ struct ExtractPass : public Pass { solver.ignore_parameters = true; continue; } - if (args[argidx] == "-ignore_param" && argidx+2 < args.size()) { - solver.ignored_parameters.insert(std::pair(RTLIL::escape_id(args[argidx+1]), RTLIL::escape_id(args[argidx+2]))); + if (args[argidx] == "-ignore_param" && argidx + 2 < args.size()) { + solver.ignored_parameters.insert(std::pair(RTLIL::escape_id(args[argidx + 1]), + RTLIL::escape_id(args[argidx + 2]))); argidx += 2; continue; } @@ -561,21 +544,21 @@ struct ExtractPass : public Pass { extra_args(args, argidx, design); if (!nodefaultswaps) { - solver.addSwappablePorts("$and", "\\A", "\\B"); - solver.addSwappablePorts("$or", "\\A", "\\B"); - solver.addSwappablePorts("$xor", "\\A", "\\B"); - solver.addSwappablePorts("$xnor", "\\A", "\\B"); - solver.addSwappablePorts("$eq", "\\A", "\\B"); - solver.addSwappablePorts("$ne", "\\A", "\\B"); - solver.addSwappablePorts("$eqx", "\\A", "\\B"); - solver.addSwappablePorts("$nex", "\\A", "\\B"); - solver.addSwappablePorts("$add", "\\A", "\\B"); - solver.addSwappablePorts("$mul", "\\A", "\\B"); + solver.addSwappablePorts("$and", "\\A", "\\B"); + solver.addSwappablePorts("$or", "\\A", "\\B"); + solver.addSwappablePorts("$xor", "\\A", "\\B"); + solver.addSwappablePorts("$xnor", "\\A", "\\B"); + solver.addSwappablePorts("$eq", "\\A", "\\B"); + solver.addSwappablePorts("$ne", "\\A", "\\B"); + solver.addSwappablePorts("$eqx", "\\A", "\\B"); + solver.addSwappablePorts("$nex", "\\A", "\\B"); + solver.addSwappablePorts("$add", "\\A", "\\B"); + solver.addSwappablePorts("$mul", "\\A", "\\B"); solver.addSwappablePorts("$logic_and", "\\A", "\\B"); - solver.addSwappablePorts("$logic_or", "\\A", "\\B"); - solver.addSwappablePorts("$_AND_", "\\A", "\\B"); - solver.addSwappablePorts("$_OR_", "\\A", "\\B"); - solver.addSwappablePorts("$_XOR_", "\\A", "\\B"); + solver.addSwappablePorts("$logic_or", "\\A", "\\B"); + solver.addSwappablePorts("$_AND_", "\\A", "\\B"); + solver.addSwappablePorts("$_OR_", "\\A", "\\B"); + solver.addSwappablePorts("$_XOR_", "\\A", "\\B"); } if (map_filenames.empty() && mine_outfile.empty()) @@ -583,23 +566,18 @@ struct ExtractPass : public Pass { RTLIL::Design *map = nullptr; - if (!mine_mode) - { + if (!mine_mode) { map = new RTLIL::Design; - for (auto &filename : map_filenames) - { - if (filename.compare(0, 1, "%") == 0) - { + for (auto &filename : map_filenames) { + if (filename.compare(0, 1, "%") == 0) { if (!saved_designs.count(filename.substr(1))) { delete map; - log_cmd_error("Can't saved design `%s'.\n", filename.c_str()+1); + log_cmd_error("Can't saved design `%s'.\n", filename.c_str() + 1); } for (auto mod : saved_designs.at(filename.substr(1))->modules()) if (!map->has(mod->name)) map->add(mod->clone()); - } - else - { + } else { std::ifstream f; rewrite_filename(filename); f.open(filename.c_str()); @@ -607,10 +585,13 @@ struct ExtractPass : public Pass { delete map; log_cmd_error("Can't open map file `%s'.\n", filename.c_str()); } - Frontend::frontend_call(map, &f, filename, (filename.size() > 3 && filename.compare(filename.size()-3, std::string::npos, ".il") == 0 ? "rtlil" : "verilog")); + Frontend::frontend_call( + map, &f, filename, + (filename.size() > 3 && filename.compare(filename.size() - 3, std::string::npos, ".il") == 0 ? "rtlil" + : "verilog")); f.close(); - if (filename.size() <= 3 || filename.compare(filename.size()-3, std::string::npos, ".il") != 0) { + if (filename.size() <= 3 || filename.compare(filename.size() - 3, std::string::npos, ".il") != 0) { Pass::call(map, "proc"); Pass::call(map, "opt_clean"); } @@ -618,8 +599,8 @@ struct ExtractPass : public Pass { } } - std::map needle_map, haystack_map; - std::vector needle_list; + std::map needle_map, haystack_map; + std::vector needle_list; log_header(design, "Creating graphs for SubCircuit library.\n"); @@ -639,28 +620,28 @@ struct ExtractPass : public Pass { SubCircuit::Graph mod_graph; std::string graph_name = "haystack_" + RTLIL::unescape_id(module->name); log("Creating haystack graph %s.\n", graph_name.c_str()); - if (module2graph(mod_graph, module, constports, design, mine_mode ? mine_max_fanout : -1, mine_mode ? &mine_split : nullptr)) { + if (module2graph(mod_graph, module, constports, design, mine_mode ? mine_max_fanout : -1, + mine_mode ? &mine_split : nullptr)) { solver.addGraph(graph_name, mod_graph); haystack_map[graph_name] = module; } } - if (!mine_mode) - { + if (!mine_mode) { std::vector results; log_header(design, "Running solver from SubCircuit library.\n"); std::sort(needle_list.begin(), needle_list.end(), compareSortNeedleList); for (auto needle : needle_list) - for (auto &haystack_it : haystack_map) { - log("Solving for %s in %s.\n", ("needle_" + RTLIL::unescape_id(needle->name)).c_str(), haystack_it.first.c_str()); - solver.solve(results, "needle_" + RTLIL::unescape_id(needle->name), haystack_it.first, false); - } + for (auto &haystack_it : haystack_map) { + log("Solving for %s in %s.\n", ("needle_" + RTLIL::unescape_id(needle->name)).c_str(), + haystack_it.first.c_str()); + solver.solve(results, "needle_" + RTLIL::unescape_id(needle->name), haystack_it.first, false); + } log("Found %d matches.\n", GetSize(results)); - if (results.size() > 0) - { + if (results.size() > 0) { log_header(design, "Substitute SubCircuits with cells.\n"); for (int i = 0; i < int(results.size()); i++) { @@ -668,18 +649,17 @@ struct ExtractPass : public Pass { log("\nMatch #%d: (%s in %s)\n", i, result.needleGraphId.c_str(), result.haystackGraphId.c_str()); for (const auto &it : result.mappings) { log(" %s -> %s", it.first.c_str(), it.second.haystackNodeId.c_str()); - for (const auto & it2 : it.second.portMapping) + for (const auto &it2 : it.second.portMapping) log(" %s:%s", it2.first.c_str(), it2.second.c_str()); log("\n"); } - RTLIL::Cell *new_cell = replace(needle_map.at(result.needleGraphId), haystack_map.at(result.haystackGraphId), result); + RTLIL::Cell *new_cell = + replace(needle_map.at(result.needleGraphId), haystack_map.at(result.haystackGraphId), result); design->select(haystack_map.at(result.haystackGraphId), new_cell); log(" new cell: %s\n", log_id(new_cell->name)); } } - } - else - { + } else { std::vector results; log_header(design, "Running miner from SubCircuit library.\n"); @@ -688,9 +668,9 @@ struct ExtractPass : public Pass { map = new RTLIL::Design; int needleCounter = 0; - for (auto &result: results) - { - log("\nFrequent SubCircuit with %d nodes and %d matches:\n", int(result.nodes.size()), result.totalMatchesAfterLimits); + for (auto &result : results) { + log("\nFrequent SubCircuit with %d nodes and %d matches:\n", int(result.nodes.size()), + result.totalMatchesAfterLimits); log(" primary match in %s:", log_id(haystack_map.at(result.graphId)->name)); for (auto &node : result.nodes) log(" %s", RTLIL::unescape_id(node.nodeId).c_str()); @@ -699,24 +679,25 @@ struct ExtractPass : public Pass { log(" matches in %s: %d\n", log_id(haystack_map.at(it.first)->name), it.second); RTLIL::Module *mod = haystack_map.at(result.graphId); - std::set cells; - std::set wires; + std::set cells; + std::set wires; SigMap sigmap(mod); for (auto &node : result.nodes) - cells.insert((RTLIL::Cell*)node.userData); + cells.insert((RTLIL::Cell *)node.userData); for (auto cell : cells) - for (auto &conn : cell->connections()) { - RTLIL::SigSpec sig = sigmap(conn.second); - for (auto &chunk : sig.chunks()) - if (chunk.wire != nullptr) - wires.insert(chunk.wire); - } + for (auto &conn : cell->connections()) { + RTLIL::SigSpec sig = sigmap(conn.second); + for (auto &chunk : sig.chunks()) + if (chunk.wire != nullptr) + wires.insert(chunk.wire); + } RTLIL::Module *newMod = new RTLIL::Module; - newMod->name = stringf("\\needle%05d_%s_%dx", needleCounter++, log_id(haystack_map.at(result.graphId)->name), result.totalMatchesAfterLimits); + newMod->name = stringf("\\needle%05d_%s_%dx", needleCounter++, log_id(haystack_map.at(result.graphId)->name), + result.totalMatchesAfterLimits); map->add(newMod); for (auto wire : wires) { diff --git a/passes/techmap/extract_counter.cc b/passes/techmap/extract_counter.cc index b780f7df06c..6ab75f447bd 100644 --- a/passes/techmap/extract_counter.cc +++ b/passes/techmap/extract_counter.cc @@ -17,23 +17,21 @@ * */ -#include "kernel/yosys.h" -#include "kernel/sigtools.h" #include "kernel/modtools.h" +#include "kernel/sigtools.h" +#include "kernel/yosys.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN -//get the list of cells hooked up to at least one bit of a given net -pool get_other_cells(const RTLIL::SigSpec& port, ModIndex& index, Cell* src) +// get the list of cells hooked up to at least one bit of a given net +pool get_other_cells(const RTLIL::SigSpec &port, ModIndex &index, Cell *src) { - pool rval; - for(auto b : port) - { + pool rval; + for (auto b : port) { pool ports = index.query_ports(b); - for(auto x : ports) - { - if(x.cell == src) + for (auto x : ports) { + if (x.cell == src) continue; rval.insert(x.cell); } @@ -41,196 +39,161 @@ pool get_other_cells(const RTLIL::SigSpec& port, ModIndex& index, Cell* s return rval; } -//return true if there is a full-width bus connection from cell a port ap to cell b port bp -//if other_conns_allowed is false, then we require a strict point to point connection (no other links) -bool is_full_bus( - const RTLIL::SigSpec& sig, - ModIndex& index, - Cell* a, - RTLIL::IdString ap, - Cell* b, - RTLIL::IdString bp, - bool other_conns_allowed = false) +// return true if there is a full-width bus connection from cell a port ap to cell b port bp +// if other_conns_allowed is false, then we require a strict point to point connection (no other links) +bool is_full_bus(const RTLIL::SigSpec &sig, ModIndex &index, Cell *a, RTLIL::IdString ap, Cell *b, RTLIL::IdString bp, + bool other_conns_allowed = false) { - for(auto s : sig) - { + for (auto s : sig) { pool ports = index.query_ports(s); bool found_a = false; bool found_b = false; - for(auto x : ports) - { - if( (x.cell == a) && (x.port == ap) ) + for (auto x : ports) { + if ((x.cell == a) && (x.port == ap)) found_a = true; - else if( (x.cell == b) && (x.port == bp) ) + else if ((x.cell == b) && (x.port == bp)) found_b = true; - else if(!other_conns_allowed) + else if (!other_conns_allowed) return false; } - if( (!found_a) || (!found_b) ) + if ((!found_a) || (!found_b)) return false; } return true; } -//return true if the signal connects to one port only (nothing on the other end) -bool is_unconnected(const RTLIL::SigSpec& port, ModIndex& index) +// return true if the signal connects to one port only (nothing on the other end) +bool is_unconnected(const RTLIL::SigSpec &port, ModIndex &index) { - for(auto b : port) - { + for (auto b : port) { pool ports = index.query_ports(b); - if(ports.size() > 1) + if (ports.size() > 1) return false; } return true; } -struct CounterExtraction -{ - int width; //counter width - bool count_is_up; //count up (else down) - RTLIL::Wire* rwire; //the register output - bool has_reset; //true if we have a reset - bool has_ce; //true if we have a clock enable - bool ce_inverted; //true if clock enable is active low - RTLIL::SigSpec rst; //reset pin - bool rst_inverted; //true if reset is active low - bool rst_to_max; //true if we reset to max instead of 0 - int count_value; //value we count from - RTLIL::SigSpec ce; //clock signal - RTLIL::SigSpec clk; //clock enable, if any - RTLIL::SigSpec outsig; //counter overflow output signal - RTLIL::SigSpec poutsig; //counter parallel output signal - bool has_pout; //whether parallel output is used - RTLIL::Cell* count_mux; //counter mux - RTLIL::Cell* count_reg; //counter register - RTLIL::Cell* overflow_cell; //cell for counter overflow (either inverter reduction or $eq) - pool pouts; //Ports that take a parallel output from us +struct CounterExtraction { + int width; // counter width + bool count_is_up; // count up (else down) + RTLIL::Wire *rwire; // the register output + bool has_reset; // true if we have a reset + bool has_ce; // true if we have a clock enable + bool ce_inverted; // true if clock enable is active low + RTLIL::SigSpec rst; // reset pin + bool rst_inverted; // true if reset is active low + bool rst_to_max; // true if we reset to max instead of 0 + int count_value; // value we count from + RTLIL::SigSpec ce; // clock signal + RTLIL::SigSpec clk; // clock enable, if any + RTLIL::SigSpec outsig; // counter overflow output signal + RTLIL::SigSpec poutsig; // counter parallel output signal + bool has_pout; // whether parallel output is used + RTLIL::Cell *count_mux; // counter mux + RTLIL::Cell *count_reg; // counter register + RTLIL::Cell *overflow_cell; // cell for counter overflow (either inverter reduction or $eq) + pool pouts; // Ports that take a parallel output from us }; -struct CounterExtractionSettings -{ - pool& parallel_cells; +struct CounterExtractionSettings { + pool ¶llel_cells; int maxwidth; int minwidth; bool allow_arst; - int allowed_dirs; //0 = down, 1 = up, 2 = both + int allowed_dirs; // 0 = down, 1 = up, 2 = both }; -//attempt to extract a counter centered on the given adder cell -int counter_tryextract( - ModIndex& index, - Cell *cell, - CounterExtraction& extract, - CounterExtractionSettings settings) +// attempt to extract a counter centered on the given adder cell +int counter_tryextract(ModIndex &index, Cell *cell, CounterExtraction &extract, CounterExtractionSettings settings) { - SigMap& sigmap = index.sigmap; + SigMap &sigmap = index.sigmap; - //Both inputs must be unsigned, so don't extract anything with a signed input + // Both inputs must be unsigned, so don't extract anything with a signed input bool a_sign = cell->getParam(ID::A_SIGNED).as_bool(); bool b_sign = cell->getParam(ID::B_SIGNED).as_bool(); - if(a_sign || b_sign) + if (a_sign || b_sign) return 3; - //CO and X must be unconnected (exactly one connection to each port) - if(!is_unconnected(sigmap(cell->getPort(ID::CO)), index)) + // CO and X must be unconnected (exactly one connection to each port) + if (!is_unconnected(sigmap(cell->getPort(ID::CO)), index)) return 7; - if(!is_unconnected(sigmap(cell->getPort(ID::X)), index)) + if (!is_unconnected(sigmap(cell->getPort(ID::X)), index)) return 8; - //true if $alu is performing A - B, else A + B + // true if $alu is performing A - B, else A + B bool alu_is_subtract; - //BI and CI must be both constant 0 or both constant 1 as well + // BI and CI must be both constant 0 or both constant 1 as well const RTLIL::SigSpec bi_port = sigmap(cell->getPort(ID::BI)); const RTLIL::SigSpec ci_port = sigmap(cell->getPort(ID::CI)); - if(bi_port.is_fully_const() && bi_port.as_int() == 1 && - ci_port.is_fully_const() && ci_port.as_int() == 1) - { + if (bi_port.is_fully_const() && bi_port.as_int() == 1 && ci_port.is_fully_const() && ci_port.as_int() == 1) { alu_is_subtract = true; - } - else if(bi_port.is_fully_const() && bi_port.as_int() == 0 && - ci_port.is_fully_const() && ci_port.as_int() == 0) - { + } else if (bi_port.is_fully_const() && bi_port.as_int() == 0 && ci_port.is_fully_const() && ci_port.as_int() == 0) { alu_is_subtract = false; - } - else - { + } else { return 5; } - //false -> port B connects to value - //true -> port A connects to value + // false -> port B connects to value + // true -> port A connects to value bool alu_port_use_a = false; - if(alu_is_subtract) - { + if (alu_is_subtract) { const int a_width = cell->getParam(ID::A_WIDTH).as_int(); const int b_width = cell->getParam(ID::B_WIDTH).as_int(); const RTLIL::SigSpec b_port = sigmap(cell->getPort(ID::B)); // down, cnt <= cnt - 1 - if (b_width == 1 && b_port.is_fully_const() && b_port.as_int() == 1) - { + if (b_width == 1 && b_port.is_fully_const() && b_port.as_int() == 1) { // OK alu_port_use_a = true; extract.count_is_up = false; } // up, cnt <= cnt - -1 - else if (b_width == a_width && b_port.is_fully_const() && b_port.is_fully_ones()) - { + else if (b_width == a_width && b_port.is_fully_const() && b_port.is_fully_ones()) { // OK alu_port_use_a = true; extract.count_is_up = true; } // ??? - else - { + else { return 2; } - } - else - { + } else { const int a_width = cell->getParam(ID::A_WIDTH).as_int(); const int b_width = cell->getParam(ID::B_WIDTH).as_int(); const RTLIL::SigSpec a_port = sigmap(cell->getPort(ID::A)); const RTLIL::SigSpec b_port = sigmap(cell->getPort(ID::B)); // down, cnt <= cnt + -1 - if (b_width == a_width && b_port.is_fully_const() && b_port.is_fully_ones()) - { + if (b_width == a_width && b_port.is_fully_const() && b_port.is_fully_ones()) { // OK alu_port_use_a = true; extract.count_is_up = false; - } - else if (a_width == b_width && a_port.is_fully_const() && a_port.is_fully_ones()) - { + } else if (a_width == b_width && a_port.is_fully_const() && a_port.is_fully_ones()) { // OK alu_port_use_a = false; extract.count_is_up = false; } // up, cnt <= cnt + 1 - else if (b_width == 1 && b_port.is_fully_const() && b_port.as_int() == 1) - { + else if (b_width == 1 && b_port.is_fully_const() && b_port.as_int() == 1) { // OK alu_port_use_a = true; extract.count_is_up = true; - } - else if (a_width == 1 && a_port.is_fully_const() && a_port.as_int() == 1) - { + } else if (a_width == 1 && a_port.is_fully_const() && a_port.as_int() == 1) { // OK alu_port_use_a = false; extract.count_is_up = true; } // ??? - else - { + else { return 2; } } @@ -240,197 +203,176 @@ int counter_tryextract( if (!extract.count_is_up && settings.allowed_dirs == 1) return 26; - //Check if counter is an appropriate size + // Check if counter is an appropriate size int count_width; if (alu_port_use_a) count_width = cell->getParam(ID::A_WIDTH).as_int(); else count_width = cell->getParam(ID::B_WIDTH).as_int(); extract.width = count_width; - if( (count_width < settings.minwidth) || (count_width > settings.maxwidth) ) + if ((count_width < settings.minwidth) || (count_width > settings.maxwidth)) return 1; - //Y must have exactly one connection, and it has to be a $mux cell. - //We must have a direct bus connection from our Y to their A. + // Y must have exactly one connection, and it has to be a $mux cell. + // We must have a direct bus connection from our Y to their A. const RTLIL::SigSpec aluy = sigmap(cell->getPort(ID::Y)); - pool y_loads = get_other_cells(aluy, index, cell); - if(y_loads.size() != 1) + pool y_loads = get_other_cells(aluy, index, cell); + if (y_loads.size() != 1) return 9; - Cell* count_mux = *y_loads.begin(); + Cell *count_mux = *y_loads.begin(); extract.count_mux = count_mux; - if(count_mux->type != ID($mux)) + if (count_mux->type != ID($mux)) return 10; - if(!is_full_bus(aluy, index, cell, ID::Y, count_mux, ID::A)) + if (!is_full_bus(aluy, index, cell, ID::Y, count_mux, ID::A)) return 11; - if (extract.count_is_up) - { - //B connection of the mux must be 0 + if (extract.count_is_up) { + // B connection of the mux must be 0 const RTLIL::SigSpec underflow = sigmap(count_mux->getPort(ID::B)); - if(!(underflow.is_fully_const() && underflow.is_fully_zero())) + if (!(underflow.is_fully_const() && underflow.is_fully_zero())) return 12; - } - else - { - //B connection of the mux is our underflow value + } else { + // B connection of the mux is our underflow value const RTLIL::SigSpec underflow = sigmap(count_mux->getPort(ID::B)); - if(!underflow.is_fully_const()) + if (!underflow.is_fully_const()) return 12; extract.count_value = underflow.as_int(); } - //S connection of the mux must come from an inverter if down, eq if up + // S connection of the mux must come from an inverter if down, eq if up //(need not be the only load) const RTLIL::SigSpec muxsel = sigmap(count_mux->getPort(ID::S)); extract.outsig = muxsel; - pool muxsel_conns = get_other_cells(muxsel, index, count_mux); - Cell* overflow_cell = NULL; - for(auto c : muxsel_conns) - { - if(extract.count_is_up && c->type != ID($eq)) + pool muxsel_conns = get_other_cells(muxsel, index, count_mux); + Cell *overflow_cell = NULL; + for (auto c : muxsel_conns) { + if (extract.count_is_up && c->type != ID($eq)) continue; - if(!extract.count_is_up && c->type != ID($logic_not)) + if (!extract.count_is_up && c->type != ID($logic_not)) continue; - if(!is_full_bus(muxsel, index, c, ID::Y, count_mux, ID::S, true)) + if (!is_full_bus(muxsel, index, c, ID::Y, count_mux, ID::S, true)) continue; overflow_cell = c; break; } - if(overflow_cell == NULL) + if (overflow_cell == NULL) return 13; extract.overflow_cell = overflow_cell; - //Y connection of the mux must have exactly one load, the counter's internal register, if there's no clock enable - //If we have a clock enable, Y drives the B input of a mux. A of that mux must come from our register + // Y connection of the mux must have exactly one load, the counter's internal register, if there's no clock enable + // If we have a clock enable, Y drives the B input of a mux. A of that mux must come from our register const RTLIL::SigSpec muxy = sigmap(count_mux->getPort(ID::Y)); - pool muxy_loads = get_other_cells(muxy, index, count_mux); - if(muxy_loads.size() != 1) + pool muxy_loads = get_other_cells(muxy, index, count_mux); + if (muxy_loads.size() != 1) return 14; - Cell* muxload = *muxy_loads.begin(); - Cell* count_reg = muxload; - Cell* cemux = NULL; + Cell *muxload = *muxy_loads.begin(); + Cell *count_reg = muxload; + Cell *cemux = NULL; RTLIL::SigSpec cey; - if(muxload->type == ID($mux)) - { - //This mux is probably a clock enable mux. - //Find our count register (should be our only load) + if (muxload->type == ID($mux)) { + // This mux is probably a clock enable mux. + // Find our count register (should be our only load) cemux = muxload; cey = sigmap(cemux->getPort(ID::Y)); - pool cey_loads = get_other_cells(cey, index, cemux); - if(cey_loads.size() != 1) + pool cey_loads = get_other_cells(cey, index, cemux); + if (cey_loads.size() != 1) return 24; count_reg = *cey_loads.begin(); - if(sigmap(cemux->getPort(ID::Y)) != sigmap(count_reg->getPort(ID::D))) + if (sigmap(cemux->getPort(ID::Y)) != sigmap(count_reg->getPort(ID::D))) return 24; - //Mux should have A driven by count Q, and B by muxy - //if A and B are swapped, CE polarity is inverted - if(sigmap(cemux->getPort(ID::B)) == muxy && - sigmap(cemux->getPort(ID::A)) == sigmap(count_reg->getPort(ID::Q))) - { + // Mux should have A driven by count Q, and B by muxy + // if A and B are swapped, CE polarity is inverted + if (sigmap(cemux->getPort(ID::B)) == muxy && sigmap(cemux->getPort(ID::A)) == sigmap(count_reg->getPort(ID::Q))) { extract.ce_inverted = false; - } - else if(sigmap(cemux->getPort(ID::A)) == muxy && - sigmap(cemux->getPort(ID::B)) == sigmap(count_reg->getPort(ID::Q))) - { + } else if (sigmap(cemux->getPort(ID::A)) == muxy && sigmap(cemux->getPort(ID::B)) == sigmap(count_reg->getPort(ID::Q))) { extract.ce_inverted = true; - } - else - { + } else { return 24; } - //Select of the mux is our clock enable + // Select of the mux is our clock enable extract.has_ce = true; extract.ce = sigmap(cemux->getPort(ID::S)); - } - else + } else extract.has_ce = false; extract.count_reg = count_reg; - if(count_reg->type == ID($dff)) + if (count_reg->type == ID($dff)) extract.has_reset = false; - else if(count_reg->type == ID($adff)) - { + else if (count_reg->type == ID($adff)) { if (!settings.allow_arst) return 25; extract.has_reset = true; - //Check polarity of reset - we may have to add an inverter later on! + // Check polarity of reset - we may have to add an inverter later on! extract.rst_inverted = (count_reg->getParam(ID::ARST_POLARITY).as_int() != 1); - //Verify ARST_VALUE is zero or full scale + // Verify ARST_VALUE is zero or full scale int rst_value = count_reg->getParam(ID::ARST_VALUE).as_int(); - if(rst_value == 0) + if (rst_value == 0) extract.rst_to_max = false; - else if(rst_value == extract.count_value) + else if (rst_value == extract.count_value) extract.rst_to_max = true; else return 23; - //Save the reset + // Save the reset extract.rst = sigmap(count_reg->getPort(ID::ARST)); } - //TODO: support synchronous reset + // TODO: support synchronous reset else return 15; - //Sanity check that we use the ALU output properly - if(extract.has_ce) - { - if(!extract.ce_inverted && !is_full_bus(muxy, index, count_mux, ID::Y, cemux, ID::B)) + // Sanity check that we use the ALU output properly + if (extract.has_ce) { + if (!extract.ce_inverted && !is_full_bus(muxy, index, count_mux, ID::Y, cemux, ID::B)) return 16; - if(extract.ce_inverted && !is_full_bus(muxy, index, count_mux, ID::Y, cemux, ID::A)) + if (extract.ce_inverted && !is_full_bus(muxy, index, count_mux, ID::Y, cemux, ID::A)) return 16; - if(!is_full_bus(cey, index, cemux, ID::Y, count_reg, ID::D)) + if (!is_full_bus(cey, index, cemux, ID::Y, count_reg, ID::D)) return 16; - } - else if(!is_full_bus(muxy, index, count_mux, ID::Y, count_reg, ID::D)) + } else if (!is_full_bus(muxy, index, count_mux, ID::Y, count_reg, ID::D)) return 16; - //TODO: Verify count_reg CLK_POLARITY is 1 + // TODO: Verify count_reg CLK_POLARITY is 1 - //Register output must have exactly two loads, the inverter and ALU + // Register output must have exactly two loads, the inverter and ALU //(unless we have a parallel output!) - //If we have a clock enable, 3 is OK + // If we have a clock enable, 3 is OK const RTLIL::SigSpec qport = count_reg->getPort(ID::Q); extract.poutsig = qport; extract.has_pout = false; const RTLIL::SigSpec cnout = sigmap(qport); - pool cnout_loads = get_other_cells(cnout, index, count_reg); + pool cnout_loads = get_other_cells(cnout, index, count_reg); unsigned int max_loads = 2; - if(extract.has_ce) + if (extract.has_ce) max_loads = 3; - if(cnout_loads.size() > max_loads) - { - for(auto c : cnout_loads) - { - if(c == overflow_cell) + if (cnout_loads.size() > max_loads) { + for (auto c : cnout_loads) { + if (c == overflow_cell) continue; - if(c == cell) + if (c == cell) continue; - if(c == muxload) + if (c == muxload) continue; - //If we specified a limited set of cells for parallel output, check that we only drive them - if(!settings.parallel_cells.empty()) - { - //Make sure we're in the whitelist - if( settings.parallel_cells.find(c->type) == settings.parallel_cells.end()) + // If we specified a limited set of cells for parallel output, check that we only drive them + if (!settings.parallel_cells.empty()) { + // Make sure we're in the whitelist + if (settings.parallel_cells.find(c->type) == settings.parallel_cells.end()) return 17; } - //Figure out what port(s) are driven by it - //TODO: this can probably be done more efficiently w/o multiple iterations over our whole net? - //TODO: For what purpose do we actually need extract.pouts? - for(auto b : qport) - { + // Figure out what port(s) are driven by it + // TODO: this can probably be done more efficiently w/o multiple iterations over our whole net? + // TODO: For what purpose do we actually need extract.pouts? + for (auto b : qport) { pool ports = index.query_ports(b); - for(auto x : ports) - { - if(x.cell != c) + for (auto x : ports) { + if (x.cell != c) continue; extract.pouts.insert(ModIndex::PortInfo(c, x.port, 0)); extract.has_pout = true; @@ -438,182 +380,152 @@ int counter_tryextract( } } } - for (auto b : qport) - { - if(index.query_is_output(b)) - { + for (auto b : qport) { + if (index.query_is_output(b)) { // Parallel out goes out of module extract.has_pout = true; } } - if(!extract.count_is_up) - { - if(!is_full_bus(cnout, index, count_reg, ID::Q, overflow_cell, ID::A, true)) + if (!extract.count_is_up) { + if (!is_full_bus(cnout, index, count_reg, ID::Q, overflow_cell, ID::A, true)) return 18; - } - else - { - if(is_full_bus(cnout, index, count_reg, ID::Q, overflow_cell, ID::A, true)) - { + } else { + if (is_full_bus(cnout, index, count_reg, ID::Q, overflow_cell, ID::A, true)) { // B must be the overflow value const RTLIL::SigSpec overflow = sigmap(overflow_cell->getPort(ID::B)); - if(!overflow.is_fully_const()) + if (!overflow.is_fully_const()) return 12; extract.count_value = overflow.as_int(); - } - else if(is_full_bus(cnout, index, count_reg, ID::Q, overflow_cell, ID::B, true)) - { + } else if (is_full_bus(cnout, index, count_reg, ID::Q, overflow_cell, ID::B, true)) { // A must be the overflow value const RTLIL::SigSpec overflow = sigmap(overflow_cell->getPort(ID::A)); - if(!overflow.is_fully_const()) + if (!overflow.is_fully_const()) return 12; extract.count_value = overflow.as_int(); - } - else - { + } else { return 18; } } - if(alu_port_use_a && !is_full_bus(cnout, index, count_reg, ID::Q, cell, ID::A, true)) + if (alu_port_use_a && !is_full_bus(cnout, index, count_reg, ID::Q, cell, ID::A, true)) return 19; - if(!alu_port_use_a && !is_full_bus(cnout, index, count_reg, ID::Q, cell, ID::B, true)) + if (!alu_port_use_a && !is_full_bus(cnout, index, count_reg, ID::Q, cell, ID::B, true)) return 19; - //Look up the clock from the register + // Look up the clock from the register extract.clk = sigmap(count_reg->getPort(ID::CLK)); - if(!extract.count_is_up) - { - //Register output net must have an INIT attribute equal to the count value + if (!extract.count_is_up) { + // Register output net must have an INIT attribute equal to the count value extract.rwire = cnout.as_wire(); - if(extract.rwire->attributes.find(ID::init) == extract.rwire->attributes.end()) + if (extract.rwire->attributes.find(ID::init) == extract.rwire->attributes.end()) return 20; int rinit = extract.rwire->attributes[ID::init].as_int(); - if(rinit != extract.count_value) + if (rinit != extract.count_value) return 21; - } - else - { - //Register output net must not have an INIT attribute or it must be zero + } else { + // Register output net must not have an INIT attribute or it must be zero extract.rwire = cnout.as_wire(); - if(extract.rwire->attributes.find(ID::init) == extract.rwire->attributes.end()) + if (extract.rwire->attributes.find(ID::init) == extract.rwire->attributes.end()) return 0; int rinit = extract.rwire->attributes[ID::init].as_int(); - if(rinit != 0) + if (rinit != 0) return 21; } return 0; } -void counter_worker( - ModIndex& index, - Cell *cell, - unsigned int& total_counters, - pool& cells_to_remove, - pool>& cells_to_rename, - CounterExtractionSettings settings) +void counter_worker(ModIndex &index, Cell *cell, unsigned int &total_counters, pool &cells_to_remove, + pool> &cells_to_rename, CounterExtractionSettings settings) { - SigMap& sigmap = index.sigmap; + SigMap &sigmap = index.sigmap; - //Core of the counter must be an ALU + // Core of the counter must be an ALU if (cell->type != ID($alu)) return; - //A input is the count value. Check if it has COUNT_EXTRACT set. - //If it's not a wire, don't even try + // A input is the count value. Check if it has COUNT_EXTRACT set. + // If it's not a wire, don't even try auto port = sigmap(cell->getPort(ID::A)); - if(!port.is_wire()) - { + if (!port.is_wire()) { port = sigmap(cell->getPort(ID::B)); - if(!port.is_wire()) + if (!port.is_wire()) return; } - RTLIL::Wire* port_wire = port.as_wire(); + RTLIL::Wire *port_wire = port.as_wire(); bool force_extract = false; bool never_extract = false; string count_reg_src = port_wire->attributes[ID::src].decode_string().c_str(); - if(port_wire->attributes.find(ID(COUNT_EXTRACT)) != port_wire->attributes.end()) - { + if (port_wire->attributes.find(ID(COUNT_EXTRACT)) != port_wire->attributes.end()) { pool sa = port_wire->get_strpool_attribute(ID(COUNT_EXTRACT)); string extract_value; - if(sa.size() >= 1) - { + if (sa.size() >= 1) { extract_value = *sa.begin(); - log(" Signal %s declared at %s has COUNT_EXTRACT = %s\n", - log_id(port_wire), - count_reg_src.c_str(), - extract_value.c_str()); + log(" Signal %s declared at %s has COUNT_EXTRACT = %s\n", log_id(port_wire), count_reg_src.c_str(), extract_value.c_str()); - if(extract_value == "FORCE") + if (extract_value == "FORCE") force_extract = true; - else if(extract_value == "NO") + else if (extract_value == "NO") never_extract = true; - else if(extract_value == "AUTO") - {} //default + else if (extract_value == "AUTO") { + } // default else - log_error(" Illegal COUNT_EXTRACT value %s (must be one of FORCE, NO, AUTO)\n", - extract_value.c_str()); + log_error(" Illegal COUNT_EXTRACT value %s (must be one of FORCE, NO, AUTO)\n", extract_value.c_str()); } } - //If we're explicitly told not to extract, don't infer a counter - if(never_extract) + // If we're explicitly told not to extract, don't infer a counter + if (never_extract) return; - //Attempt to extract a counter + // Attempt to extract a counter CounterExtraction extract; int reason = counter_tryextract(index, cell, extract, settings); - //Nonzero code - we could not find a matchable counter. - //Do nothing, unless extraction was forced in which case give an error - if(reason != 0) - { - static const char* reasons[]= - { - "no problem", //0 - "counter is too large/small", //1 - "counter does not count by one", //2 - "counter uses signed math", //3 - "RESERVED, not implemented", //4 - "ALU is not an adder/subtractor", //5 - "RESERVED, not implemented", //6 - "ALU ports used outside counter", //7 - "ALU ports used outside counter", //8 - "ALU output used outside counter", //9 - "ALU output is not a mux", //10 - "ALU output is not full bus", //11 - "Underflow value is not constant", //12 - "No underflow detector found", //13 - "Mux output is used outside counter", //14 - "Counter reg is not DFF/ADFF", //15 - "Counter input is not full bus", //16 - "Count register is used outside counter, but not by an allowed cell", //17 - "Register output is not full bus", //18 - "Register output is not full bus", //19 - "No init value found", //20 - "Underflow value is not equal to init value", //21 - "RESERVED, not implemented", //22, kept for compatibility but not used anymore - "Reset is not to zero or COUNT_TO", //23 - "Clock enable configuration is unsupported", //24 - "Async reset used but not permitted", //25 - "Count direction is not allowed" //26 + // Nonzero code - we could not find a matchable counter. + // Do nothing, unless extraction was forced in which case give an error + if (reason != 0) { + static const char *reasons[] = { + "no problem", // 0 + "counter is too large/small", // 1 + "counter does not count by one", // 2 + "counter uses signed math", // 3 + "RESERVED, not implemented", // 4 + "ALU is not an adder/subtractor", // 5 + "RESERVED, not implemented", // 6 + "ALU ports used outside counter", // 7 + "ALU ports used outside counter", // 8 + "ALU output used outside counter", // 9 + "ALU output is not a mux", // 10 + "ALU output is not full bus", // 11 + "Underflow value is not constant", // 12 + "No underflow detector found", // 13 + "Mux output is used outside counter", // 14 + "Counter reg is not DFF/ADFF", // 15 + "Counter input is not full bus", // 16 + "Count register is used outside counter, but not by an allowed cell", // 17 + "Register output is not full bus", // 18 + "Register output is not full bus", // 19 + "No init value found", // 20 + "Underflow value is not equal to init value", // 21 + "RESERVED, not implemented", // 22, kept for compatibility but not used anymore + "Reset is not to zero or COUNT_TO", // 23 + "Clock enable configuration is unsupported", // 24 + "Async reset used but not permitted", // 25 + "Count direction is not allowed" // 26 }; - if(force_extract) - { - log_error( - "Counter extraction is set to FORCE on register %s, but a counter could not be inferred (%s)\n", - log_id(port_wire), - reasons[reason]); + if (force_extract) { + log_error("Counter extraction is set to FORCE on register %s, but a counter could not be inferred (%s)\n", log_id(port_wire), + reasons[reason]); } return; } - //Get new cell name + // Get new cell name string countname = string("$COUNTx$") + log_id(extract.rwire->name.str()); - //Wipe all of the old connections to the ALU + // Wipe all of the old connections to the ALU cell->unsetPort(ID::A); cell->unsetPort(ID::B); cell->unsetPort(ID::BI); @@ -627,137 +539,111 @@ void counter_worker( cell->unsetParam(ID::B_WIDTH); cell->unsetParam(ID::Y_WIDTH); - //Change the cell type + // Change the cell type cell->type = ID($__COUNT_); - //Hook up resets - if(extract.has_reset) - { - //TODO: support other kinds of reset + // Hook up resets + if (extract.has_reset) { + // TODO: support other kinds of reset cell->setParam(ID(RESET_MODE), RTLIL::Const("LEVEL")); - //If the reset is active low, infer an inverter ($__COUNT_ cells always have active high reset) - if(extract.rst_inverted) - { + // If the reset is active low, infer an inverter ($__COUNT_ cells always have active high reset) + if (extract.rst_inverted) { auto realreset = cell->module->addWire(NEW_ID); cell->module->addNot(NEW_ID, extract.rst, RTLIL::SigSpec(realreset)); cell->setPort(ID(RST), realreset); - } - else + } else cell->setPort(ID(RST), extract.rst); - } - else - { + } else { cell->setParam(ID(RESET_MODE), RTLIL::Const("RISING")); cell->setPort(ID(RST), RTLIL::SigSpec(false)); } - //Hook up other stuff - //cell->setParam(ID(CLKIN_DIVIDE), RTLIL::Const(1)); + // Hook up other stuff + // cell->setParam(ID(CLKIN_DIVIDE), RTLIL::Const(1)); cell->setParam(ID(COUNT_TO), RTLIL::Const(extract.count_value)); cell->setParam(ID::WIDTH, RTLIL::Const(extract.width)); cell->setPort(ID::CLK, extract.clk); cell->setPort(ID(OUT), extract.outsig); - //Hook up clock enable - if(extract.has_ce) - { + // Hook up clock enable + if (extract.has_ce) { cell->setParam(ID(HAS_CE), RTLIL::Const(1)); - if(extract.ce_inverted) - { + if (extract.ce_inverted) { auto realce = cell->module->addWire(NEW_ID); cell->module->addNot(NEW_ID, extract.ce, RTLIL::SigSpec(realce)); cell->setPort(ID(CE), realce); - } - else + } else cell->setPort(ID(CE), extract.ce); - } - else - { + } else { cell->setParam(ID(HAS_CE), RTLIL::Const(0)); cell->setPort(ID(CE), RTLIL::Const(1)); } - if(extract.count_is_up) - { + if (extract.count_is_up) { cell->setParam(ID(DIRECTION), RTLIL::Const("UP")); - //XXX: What is this supposed to do? + // XXX: What is this supposed to do? cell->setPort(ID(UP), RTLIL::Const(1)); - } - else - { + } else { cell->setParam(ID(DIRECTION), RTLIL::Const("DOWN")); cell->setPort(ID(UP), RTLIL::Const(0)); } - //Hook up hard-wired ports, default to no parallel output + // Hook up hard-wired ports, default to no parallel output cell->setParam(ID(HAS_POUT), RTLIL::Const(0)); cell->setParam(ID(RESET_TO_MAX), RTLIL::Const(0)); - //Hook up any parallel outputs - for(auto load : extract.pouts) - { + // Hook up any parallel outputs + for (auto load : extract.pouts) { log(" Counter has parallel output to cell %s port %s\n", log_id(load.cell->name), log_id(load.port)); } - if(extract.has_pout) - { - //Connect it to our parallel output + if (extract.has_pout) { + // Connect it to our parallel output cell->setPort(ID(POUT), extract.poutsig); cell->setParam(ID(HAS_POUT), RTLIL::Const(1)); } - //Delete the cells we've replaced (let opt_clean handle deleting the now-redundant wires) + // Delete the cells we've replaced (let opt_clean handle deleting the now-redundant wires) cells_to_remove.insert(extract.count_mux); cells_to_remove.insert(extract.count_reg); cells_to_remove.insert(extract.overflow_cell); - //Log it - total_counters ++; + // Log it + total_counters++; string reset_type = "non-resettable"; - if(extract.has_reset) - { - if(extract.rst_inverted) + if (extract.has_reset) { + if (extract.rst_inverted) reset_type = "negative"; else reset_type = "positive"; - //TODO: support other kind of reset + // TODO: support other kind of reset reset_type += " async resettable"; } - log(" Found %d-bit (%s) %s counter %s (counting %s %d) for register %s, declared at %s\n", - extract.width, - reset_type.c_str(), - extract.count_is_up ? "up" : "down", - countname.c_str(), - extract.count_is_up ? "to" : "from", - extract.count_value, - log_id(extract.rwire->name), - count_reg_src.c_str()); - - //Optimize the counter - //If we have no parallel output, and we have redundant bits, shrink us - if(!extract.has_pout) - { - //TODO: Need to update this when we add support for counters with nonzero reset values - //to make sure the reset value fits in our bit space too + log(" Found %d-bit (%s) %s counter %s (counting %s %d) for register %s, declared at %s\n", extract.width, reset_type.c_str(), + extract.count_is_up ? "up" : "down", countname.c_str(), extract.count_is_up ? "to" : "from", extract.count_value, + log_id(extract.rwire->name), count_reg_src.c_str()); + + // Optimize the counter + // If we have no parallel output, and we have redundant bits, shrink us + if (!extract.has_pout) { + // TODO: Need to update this when we add support for counters with nonzero reset values + // to make sure the reset value fits in our bit space too - //Optimize it + // Optimize it int newbits = ceil(log2(extract.count_value)); - if(extract.width != newbits) - { + if (extract.width != newbits) { cell->setParam(ID::WIDTH, RTLIL::Const(newbits)); - log(" Optimizing out %d unused high-order bits (new width is %d)\n", - extract.width - newbits, - newbits); + log(" Optimizing out %d unused high-order bits (new width is %d)\n", extract.width - newbits, newbits); } } - //Finally, rename the cell - cells_to_rename.insert(pair(cell, countname)); + // Finally, rename the cell + cells_to_rename.insert(pair(cell, countname)); } struct ExtractCounterPass : public Pass { - ExtractCounterPass() : Pass("extract_counter", "Extract GreenPak4 counter cells") { } + ExtractCounterPass() : Pass("extract_counter", "Extract GreenPak4 counter cells") {} void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| @@ -791,56 +677,46 @@ struct ExtractCounterPass : public Pass { log_header(design, "Executing EXTRACT_COUNTER pass (find counters in netlist).\n"); pool _parallel_cells; - CounterExtractionSettings settings - { - _parallel_cells, // parallel_cells - 64, // maxwidth - 2, // minwidth - true, // allow_arst - 0, // allowed_dirs + CounterExtractionSettings settings{ + _parallel_cells, // parallel_cells + 64, // maxwidth + 2, // minwidth + true, // allow_arst + 0, // allowed_dirs }; size_t argidx; - for (argidx = 1; argidx < args.size(); argidx++) - { - if (args[argidx] == "-pout") - { - if(argidx + 1 >= args.size()) - { + for (argidx = 1; argidx < args.size(); argidx++) { + if (args[argidx] == "-pout") { + if (argidx + 1 >= args.size()) { log_error("extract_counter -pout requires an argument\n"); return; } std::string pouts = args[++argidx]; std::string tmp; - for(size_t i=0; iselected_modules()) - { - pool cells_to_remove; - pool> cells_to_rename; + for (auto module : design->selected_modules()) { + pool cells_to_remove; + pool> cells_to_rename; ModIndex index(module); for (auto cell : module->selected_cells()) counter_worker(index, cell, total_counters, cells_to_remove, cells_to_rename, settings); - for(auto cell : cells_to_remove) - { - //log("Removing cell %s\n", log_id(cell->name)); + for (auto cell : cells_to_remove) { + // log("Removing cell %s\n", log_id(cell->name)); module->remove(cell); } - for(auto cpair : cells_to_rename) - { - //log("Renaming cell %s to %s\n", log_id(cpair.first->name), cpair.second.c_str()); + for (auto cpair : cells_to_rename) { + // log("Renaming cell %s to %s\n", log_id(cpair.first->name), cpair.second.c_str()); module->rename(cpair.first, cpair.second); } } - if(total_counters) + if (total_counters) log("Extracted %u counters\n", total_counters); } } ExtractCounterPass; diff --git a/passes/techmap/extract_fa.cc b/passes/techmap/extract_fa.cc index 117fdd54cf6..c90ca4a09d2 100644 --- a/passes/techmap/extract_fa.cc +++ b/passes/techmap/extract_fa.cc @@ -17,15 +17,14 @@ * */ -#include "kernel/yosys.h" -#include "kernel/sigtools.h" #include "kernel/consteval.h" +#include "kernel/sigtools.h" +#include "kernel/yosys.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN -struct ExtractFaConfig -{ +struct ExtractFaConfig { bool enable_fa = false; bool enable_ha = false; bool verbose = false; @@ -47,14 +46,13 @@ int bindec(unsigned char v) return r; } -struct ExtractFaWorker -{ +struct ExtractFaWorker { const ExtractFaConfig &config; Module *module; ConstEval ce; SigMap &sigmap; - dict driver; + dict driver; pool handled_bits; const int xor2_func = 0x6, xnor2_func = 0x9; @@ -80,15 +78,11 @@ struct ExtractFaWorker dict func2_and_info; dict func3_maj_info; - ExtractFaWorker(const ExtractFaConfig &config, Module *module) : - config(config), module(module), ce(module), sigmap(ce.assign_map) + ExtractFaWorker(const ExtractFaConfig &config, Module *module) : config(config), module(module), ce(module), sigmap(ce.assign_map) { - for (auto cell : module->selected_cells()) - { - if (cell->type.in( ID($_BUF_), ID($_NOT_), ID($_AND_), ID($_NAND_), ID($_OR_), ID($_NOR_), - ID($_XOR_), ID($_XNOR_), ID($_ANDNOT_), ID($_ORNOT_), ID($_MUX_), ID($_NMUX_), - ID($_AOI3_), ID($_OAI3_), ID($_AOI4_), ID($_OAI4_))) - { + for (auto cell : module->selected_cells()) { + if (cell->type.in(ID($_BUF_), ID($_NOT_), ID($_AND_), ID($_NAND_), ID($_OR_), ID($_NOR_), ID($_XOR_), ID($_XNOR_), + ID($_ANDNOT_), ID($_ORNOT_), ID($_MUX_), ID($_NMUX_), ID($_AOI3_), ID($_OAI3_), ID($_AOI4_), ID($_OAI4_))) { SigBit y = sigmap(SigBit(cell->getPort(ID::Y))); log_assert(driver.count(y) == 0); driver[y] = cell; @@ -96,75 +90,71 @@ struct ExtractFaWorker } for (int ia = 0; ia < 2; ia++) - for (int ib = 0; ib < 2; ib++) - { - func2_and_info_t f2i; - - f2i.inv_a = ia; - f2i.inv_b = ib; - f2i.inv_y = false; - - int func = 0; - for (int i = 0; i < 4; i++) - { - bool a = (i & 1) ? !f2i.inv_a : f2i.inv_a; - bool b = (i & 2) ? !f2i.inv_b : f2i.inv_b; - if (a && b) func |= 1 << i; - } - - log_assert(func2_and_info.count(func) == 0); - func2_and_info[func] = f2i; - - f2i.inv_y = true; - func ^= 15; - - log_assert(func2_and_info.count(func) == 0); - func2_and_info[func] = f2i; - } + for (int ib = 0; ib < 2; ib++) { + func2_and_info_t f2i; + + f2i.inv_a = ia; + f2i.inv_b = ib; + f2i.inv_y = false; + + int func = 0; + for (int i = 0; i < 4; i++) { + bool a = (i & 1) ? !f2i.inv_a : f2i.inv_a; + bool b = (i & 2) ? !f2i.inv_b : f2i.inv_b; + if (a && b) + func |= 1 << i; + } - for (int ia = 0; ia < 2; ia++) - for (int ib = 0; ib < 2; ib++) - for (int ic = 0; ic < 2; ic++) - { - func3_maj_info_t f3i; + log_assert(func2_and_info.count(func) == 0); + func2_and_info[func] = f2i; - f3i.inv_a = ia; - f3i.inv_b = ib; - f3i.inv_c = ic; - f3i.inv_y = false; + f2i.inv_y = true; + func ^= 15; - int func = 0; - for (int i = 0; i < 8; i++) - { - bool a = (i & 1) ? !f3i.inv_a : f3i.inv_a; - bool b = (i & 2) ? !f3i.inv_b : f3i.inv_b; - bool c = (i & 4) ? !f3i.inv_c : f3i.inv_c; - if ((a && b) || (a && c) || (b &&c)) func |= 1 << i; + log_assert(func2_and_info.count(func) == 0); + func2_and_info[func] = f2i; } - log_assert(func3_maj_info.count(func) == 0); - func3_maj_info[func] = f3i; - - // f3i.inv_y = true; - // func ^= 255; - - // log_assert(func3_maj_info.count(func) == 0); - // func3_maj_info[func] = f3i; - } + for (int ia = 0; ia < 2; ia++) + for (int ib = 0; ib < 2; ib++) + for (int ic = 0; ic < 2; ic++) { + func3_maj_info_t f3i; + + f3i.inv_a = ia; + f3i.inv_b = ib; + f3i.inv_c = ic; + f3i.inv_y = false; + + int func = 0; + for (int i = 0; i < 8; i++) { + bool a = (i & 1) ? !f3i.inv_a : f3i.inv_a; + bool b = (i & 2) ? !f3i.inv_b : f3i.inv_b; + bool c = (i & 4) ? !f3i.inv_c : f3i.inv_c; + if ((a && b) || (a && c) || (b && c)) + func |= 1 << i; + } + + log_assert(func3_maj_info.count(func) == 0); + func3_maj_info[func] = f3i; + + // f3i.inv_y = true; + // func ^= 255; + + // log_assert(func3_maj_info.count(func) == 0); + // func3_maj_info[func] = f3i; + } } void check_partition(SigBit root, pool &leaves) { - if (config.enable_ha && GetSize(leaves) == 2) - { + if (config.enable_ha && GetSize(leaves) == 2) { leaves.sort(); SigBit A = SigSpec(leaves)[0]; SigBit B = SigSpec(leaves)[1]; int func = 0; - for (int i = 0; i < 4; i++) - { + for (int i = 0; i < 4; i++) { bool a_value = (i & 1) != 0; bool b_value = (i & 2) != 0; @@ -194,8 +184,7 @@ struct ExtractFaWorker func2[tuple(A, B)][func].insert(root); } - if (config.enable_fa && GetSize(leaves) == 3) - { + if (config.enable_fa && GetSize(leaves) == 3) { leaves.sort(); SigBit A = SigSpec(leaves)[0]; @@ -203,8 +192,7 @@ struct ExtractFaWorker SigBit C = SigSpec(leaves)[2]; int func = 0; - for (int i = 0; i < 8; i++) - { + for (int i = 0; i < 8; i++) { bool a_value = (i & 1) != 0; bool b_value = (i & 2) != 0; bool c_value = (i & 4) != 0; @@ -253,8 +241,7 @@ struct ExtractFaWorker if (maxdepth == 0) return; - for (SigBit bit : leaves) - { + for (SigBit bit : leaves) { if (driver.count(bit) == 0) continue; @@ -274,7 +261,7 @@ struct ExtractFaWorker if (GetSize(new_leaves) > maxbreadth) continue; - find_partitions(root, new_leaves, cache, maxdepth-1, maxbreadth); + find_partitions(root, new_leaves, cache, maxdepth - 1, maxbreadth); } } @@ -291,13 +278,12 @@ struct ExtractFaWorker { log("Extracting full/half adders from %s:\n", log_id(module)); - for (auto it : driver) - { + for (auto it : driver) { if (it.second->type.in(ID($_BUF_), ID($_NOT_))) continue; SigBit root = it.first; - pool leaves = { root }; + pool leaves = {root}; pool> cache; if (config.verbose) @@ -315,16 +301,14 @@ struct ExtractFaWorker log(" extracted %d three-input functions\n", count_func3); } - for (auto &key : xorxnor3) - { + for (auto &key : xorxnor3) { SigBit A = get<0>(key); SigBit B = get<1>(key); SigBit C = get<2>(key); log(" 3-Input XOR/XNOR %s %s %s:\n", log_signal(A), log_signal(B), log_signal(C)); - for (auto &it : func3.at(key)) - { + for (auto &it : func3.at(key)) { if (it.first != xor3_func && it.first != xnor3_func) continue; @@ -334,10 +318,9 @@ struct ExtractFaWorker log("\n"); } - dict> facache; + dict> facache; - for (auto &it : func3_maj_info) - { + for (auto &it : func3_maj_info) { int func = it.first; auto f3i = it.second; @@ -355,10 +338,14 @@ struct ExtractFaWorker log(" Majority without inversions:\n"); } else { log(" Majority with inverted"); - if (f3i.inv_a) log(" A"); - if (f3i.inv_b) log(" B"); - if (f3i.inv_c) log(" C"); - if (f3i.inv_y) log(" Y"); + if (f3i.inv_a) + log(" A"); + if (f3i.inv_b) + log(" B"); + if (f3i.inv_c) + log(" C"); + if (f3i.inv_y) + log(" Y"); log(":\n"); } @@ -368,32 +355,29 @@ struct ExtractFaWorker log("\n"); int fakey = 0; - if (f3i.inv_a) fakey |= 1; - if (f3i.inv_b) fakey |= 2; - if (f3i.inv_c) fakey |= 4; + if (f3i.inv_a) + fakey |= 1; + if (f3i.inv_b) + fakey |= 2; + if (f3i.inv_c) + fakey |= 4; int fakey_inv = fakey ^ 7; bool invert_xy = false; SigBit X, Y; - if (facache.count(fakey)) - { + if (facache.count(fakey)) { auto &fa = facache.at(fakey); X = get<0>(fa); Y = get<1>(fa); log(" Reusing $fa cell %s.\n", log_id(get<2>(fa))); - } - else - if (facache.count(fakey_inv)) - { + } else if (facache.count(fakey_inv)) { auto &fa = facache.at(fakey_inv); invert_xy = true; X = get<0>(fa); Y = get<1>(fa); log(" Reusing $fa cell %s.\n", log_id(get<2>(fa))); - } - else - { + } else { Cell *cell = module->addCell(NEW_ID, ID($fa)); cell->setParam(ID::WIDTH, 1); @@ -431,15 +415,13 @@ struct ExtractFaWorker } } - for (auto &key : xorxnor2) - { + for (auto &key : xorxnor2) { SigBit A = get<0>(key); SigBit B = get<1>(key); log(" 2-Input XOR/XNOR %s %s:\n", log_signal(A), log_signal(B)); - for (auto &it : func2.at(key)) - { + for (auto &it : func2.at(key)) { if (it.first != xor2_func && it.first != xnor2_func) continue; @@ -449,10 +431,9 @@ struct ExtractFaWorker log("\n"); } - dict> facache; + dict> facache; - for (auto &it : func2_and_info) - { + for (auto &it : func2_and_info) { int func = it.first; auto &f2i = it.second; @@ -463,9 +444,12 @@ struct ExtractFaWorker log(" AND without inversions:\n"); } else { log(" AND with inverted"); - if (f2i.inv_a) log(" A"); - if (f2i.inv_b) log(" B"); - if (f2i.inv_y) log(" Y"); + if (f2i.inv_a) + log(" A"); + if (f2i.inv_b) + log(" B"); + if (f2i.inv_y) + log(" Y"); log(":\n"); } @@ -475,31 +459,27 @@ struct ExtractFaWorker log("\n"); int fakey = 0; - if (f2i.inv_a) fakey |= 1; - if (f2i.inv_b) fakey |= 2; + if (f2i.inv_a) + fakey |= 1; + if (f2i.inv_b) + fakey |= 2; int fakey_inv = fakey ^ 3; bool invert_xy = false; SigBit X, Y; - if (facache.count(fakey)) - { + if (facache.count(fakey)) { auto &fa = facache.at(fakey); X = get<0>(fa); Y = get<1>(fa); log(" Reusing $fa cell %s.\n", log_id(get<2>(fa))); - } - else - if (facache.count(fakey_inv)) - { + } else if (facache.count(fakey_inv)) { auto &fa = facache.at(fakey_inv); invert_xy = true; X = get<0>(fa); Y = get<1>(fa); log(" Reusing $fa cell %s.\n", log_id(get<2>(fa))); - } - else - { + } else { Cell *cell = module->addCell(NEW_ID, ID($fa)); cell->setParam(ID::WIDTH, 1); @@ -517,13 +497,15 @@ struct ExtractFaWorker } if (func2.at(key).count(xor2_func)) { - SigBit YY = invert_xy || (f2i.inv_a && !f2i.inv_b) || (!f2i.inv_a && f2i.inv_b) ? module->NotGate(NEW_ID, Y) : Y; + SigBit YY = + invert_xy || (f2i.inv_a && !f2i.inv_b) || (!f2i.inv_a && f2i.inv_b) ? module->NotGate(NEW_ID, Y) : Y; for (auto bit : func2.at(key).at(xor2_func)) assign_new_driver(bit, YY); } if (func2.at(key).count(xnor2_func)) { - SigBit YY = invert_xy || (f2i.inv_a && !f2i.inv_b) || (!f2i.inv_a && f2i.inv_b) ? Y : module->NotGate(NEW_ID, Y); + SigBit YY = + invert_xy || (f2i.inv_a && !f2i.inv_b) || (!f2i.inv_a && f2i.inv_b) ? Y : module->NotGate(NEW_ID, Y); for (auto bit : func2.at(key).at(xnor2_func)) assign_new_driver(bit, YY); } @@ -538,7 +520,7 @@ struct ExtractFaWorker }; struct ExtractFaPass : public Pass { - ExtractFaPass() : Pass("extract_fa", "find and extract full/half adders") { } + ExtractFaPass() : Pass("extract_fa", "find and extract full/half adders") {} void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| @@ -569,8 +551,7 @@ struct ExtractFaPass : public Pass { log_push(); size_t argidx; - for (argidx = 1; argidx < args.size(); argidx++) - { + for (argidx = 1; argidx < args.size(); argidx++) { if (args[argidx] == "-fa") { config.enable_fa = true; continue; @@ -583,11 +564,11 @@ struct ExtractFaPass : public Pass { config.verbose = true; continue; } - if (args[argidx] == "-d" && argidx+2 < args.size()) { + if (args[argidx] == "-d" && argidx + 2 < args.size()) { config.maxdepth = atoi(args[++argidx].c_str()); continue; } - if (args[argidx] == "-b" && argidx+2 < args.size()) { + if (args[argidx] == "-b" && argidx + 2 < args.size()) { config.maxbreadth = atoi(args[++argidx].c_str()); continue; } @@ -600,8 +581,7 @@ struct ExtractFaPass : public Pass { config.enable_ha = true; } - for (auto module : design->selected_modules()) - { + for (auto module : design->selected_modules()) { ExtractFaWorker worker(config, module); worker.run(); } diff --git a/passes/techmap/extract_reduce.cc b/passes/techmap/extract_reduce.cc index 892e9a3644b..bc2d31d8f4c 100644 --- a/passes/techmap/extract_reduce.cc +++ b/passes/techmap/extract_reduce.cc @@ -17,22 +17,17 @@ * */ -#include "kernel/yosys.h" #include "kernel/sigtools.h" +#include "kernel/yosys.h" #include USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN -struct ExtractReducePass : public Pass -{ - enum GateType { - And, - Or, - Xor - }; +struct ExtractReducePass : public Pass { + enum GateType { And, Or, Xor }; - ExtractReducePass() : Pass("extract_reduce", "converts gate chains into $reduce_* cells") { } + ExtractReducePass() : Pass("extract_reduce", "converts gate chains into $reduce_* cells") {} void help() override { @@ -56,11 +51,10 @@ struct ExtractReducePass : public Pass log("\n"); } - inline bool IsRightType(Cell* cell, GateType gt) + inline bool IsRightType(Cell *cell, GateType gt) { - return (cell->type == ID($_AND_) && gt == GateType::And) || - (cell->type == ID($_OR_) && gt == GateType::Or) || - (cell->type == ID($_XOR_) && gt == GateType::Xor); + return (cell->type == ID($_AND_) && gt == GateType::And) || (cell->type == ID($_OR_) && gt == GateType::Or) || + (cell->type == ID($_XOR_) && gt == GateType::Xor); } void execute(std::vector args, RTLIL::Design *design) override @@ -70,10 +64,8 @@ struct ExtractReducePass : public Pass size_t argidx; bool allow_off_chain = false; - for (argidx = 1; argidx < args.size(); argidx++) - { - if (args[argidx] == "-allow-off-chain") - { + for (argidx = 1; argidx < args.size(); argidx++) { + if (args[argidx] == "-allow-off-chain") { allow_off_chain = true; continue; } @@ -81,27 +73,22 @@ struct ExtractReducePass : public Pass } extra_args(args, argidx, design); - for (auto module : design->selected_modules()) - { + for (auto module : design->selected_modules()) { SigMap sigmap(module); // Index all of the nets in the module - dict sig_to_driver; - dict> sig_to_sink; - for (auto cell : module->selected_cells()) - { - for (auto &conn : cell->connections()) - { + dict sig_to_driver; + dict> sig_to_sink; + for (auto cell : module->selected_cells()) { + for (auto &conn : cell->connections()) { if (cell->output(conn.first)) for (auto bit : sigmap(conn.second)) sig_to_driver[bit] = cell; - if (cell->input(conn.first)) - { - for (auto bit : sigmap(conn.second)) - { + if (cell->input(conn.first)) { + for (auto bit : sigmap(conn.second)) { if (sig_to_sink.count(bit) == 0) - sig_to_sink[bit] = pool(); + sig_to_sink[bit] = pool(); sig_to_sink[bit].insert(cell); } } @@ -116,9 +103,8 @@ struct ExtractReducePass : public Pass port_sigs.insert(bit); // Actual logic starts here - pool consumed_cells; - for (auto cell : module->selected_cells()) - { + pool consumed_cells; + for (auto cell : module->selected_cells()) { if (consumed_cells.count(cell)) continue; @@ -136,14 +122,12 @@ struct ExtractReducePass : public Pass log("Working on cell %s...\n", cell->name.c_str()); // If looking for a single chain, follow linearly to the sink - pool sinks; - if(!allow_off_chain) - { - Cell* head_cell = cell; - Cell* x = cell; - while (true) - { - if(!IsRightType(x, gt)) + pool sinks; + if (!allow_off_chain) { + Cell *head_cell = cell; + Cell *x = cell; + while (true) { + if (!IsRightType(x, gt)) break; head_cell = x; @@ -161,49 +145,43 @@ struct ExtractReducePass : public Pass sinks.insert(head_cell); } - //If off-chain loads are allowed, we have to do a wider traversal to see what the longest chain is - else - { - //BFS, following all chains until they hit a cell of a different type - //Pick the longest one + // If off-chain loads are allowed, we have to do a wider traversal to see what the longest chain is + else { + // BFS, following all chains until they hit a cell of a different type + // Pick the longest one auto y = sigmap(cell->getPort(ID::Y)); - pool current_loads = sig_to_sink[y]; - pool next_loads; - - while(!current_loads.empty()) - { - //Find each sink and see what they are - for(auto x : current_loads) - { - //Not one of our gates? Don't follow any further + pool current_loads = sig_to_sink[y]; + pool next_loads; + + while (!current_loads.empty()) { + // Find each sink and see what they are + for (auto x : current_loads) { + // Not one of our gates? Don't follow any further //(but add the originating cell to the list of sinks) - if(!IsRightType(x, gt)) - { + if (!IsRightType(x, gt)) { sinks.insert(cell); continue; } auto xy = sigmap(x->getPort(ID::Y)); - //If this signal drives a port, add it to the sinks + // If this signal drives a port, add it to the sinks //(even though it may not be the end of a chain) - if(port_sigs.count(xy) && !consumed_cells.count(x)) + if (port_sigs.count(xy) && !consumed_cells.count(x)) sinks.insert(x); - //It's a match, search everything out from it - auto& next = sig_to_sink[xy]; - for(auto z : next) + // It's a match, search everything out from it + auto &next = sig_to_sink[xy]; + for (auto z : next) next_loads.insert(z); } - //If we couldn't find any downstream loads, stop. - //Create a reduction for each of the max-length chains we found - if(next_loads.empty()) - { - for(auto s : current_loads) - { - //Not one of our gates? Don't follow any further - if(!IsRightType(s, gt)) + // If we couldn't find any downstream loads, stop. + // Create a reduction for each of the max-length chains we found + if (next_loads.empty()) { + for (auto s : current_loads) { + // Not one of our gates? Don't follow any further + if (!IsRightType(s, gt)) continue; sinks.insert(s); @@ -211,35 +189,33 @@ struct ExtractReducePass : public Pass break; } - //Otherwise, continue down the chain + // Otherwise, continue down the chain current_loads = next_loads; next_loads.clear(); } } - //We have our list, go act on it - for(auto head_cell : sinks) - { + // We have our list, go act on it + for (auto head_cell : sinks) { log(" Head cell is %s\n", head_cell->name.c_str()); - //Avoid duplication if we already were covered - if(consumed_cells.count(head_cell)) + // Avoid duplication if we already were covered + if (consumed_cells.count(head_cell)) continue; dict sources; int inner_cells = 0; - std::deque bfs_queue = {head_cell}; - while (bfs_queue.size()) - { - Cell* x = bfs_queue.front(); + std::deque bfs_queue = {head_cell}; + while (bfs_queue.size()) { + Cell *x = bfs_queue.front(); bfs_queue.pop_front(); - for (auto port: {ID::A, ID::B}) { + for (auto port : {ID::A, ID::B}) { auto bit = sigmap(x->getPort(port)[0]); bool sink_single = sig_to_sink[bit].size() == 1 && !port_sigs.count(bit); - Cell* drv = sig_to_driver[bit]; + Cell *drv = sig_to_driver[bit]; bool drv_ok = drv && drv->type == head_cell->type; if (drv_ok && (allow_off_chain || sink_single)) { @@ -251,8 +227,7 @@ struct ExtractReducePass : public Pass } } - if (inner_cells) - { + if (inner_cells) { // Worth it to create reduce cell log(" Creating $reduce_* cell!\n"); diff --git a/passes/techmap/extractinv.cc b/passes/techmap/extractinv.cc index 48d9600fa72..07556ca659d 100644 --- a/passes/techmap/extractinv.cc +++ b/passes/techmap/extractinv.cc @@ -18,8 +18,8 @@ * */ -#include "kernel/yosys.h" #include "kernel/sigtools.h" +#include "kernel/yosys.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN @@ -28,13 +28,13 @@ void split_portname_pair(std::string &port1, std::string &port2) { size_t pos = port1.find_first_of(':'); if (pos != std::string::npos) { - port2 = port1.substr(pos+1); + port2 = port1.substr(pos + 1); port1 = port1.substr(0, pos); } } struct ExtractinvPass : public Pass { - ExtractinvPass() : Pass("extractinv", "extract explicit inverter cells for invertible cell pins") { } + ExtractinvPass() : Pass("extractinv", "extract explicit inverter cells for invertible cell pins") {} void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| @@ -64,10 +64,9 @@ struct ExtractinvPass : public Pass { std::string inv_celltype, inv_portname, inv_portname2; size_t argidx; - for (argidx = 1; argidx < args.size(); argidx++) - { + for (argidx = 1; argidx < args.size(); argidx++) { std::string arg = args[argidx]; - if (arg == "-inv" && argidx+2 < args.size()) { + if (arg == "-inv" && argidx + 2 < args.size()) { inv_celltype = args[++argidx]; inv_portname = args[++argidx]; split_portname_pair(inv_portname, inv_portname2); @@ -80,42 +79,44 @@ struct ExtractinvPass : public Pass { if (inv_celltype.empty()) log_error("The -inv option is required.\n"); - for (auto module : design->selected_modules()) - { + for (auto module : design->selected_modules()) { for (auto cell : module->selected_cells()) - for (auto port : cell->connections()) { - auto cell_module = design->module(cell->type); - if (!cell_module) - continue; - auto cell_wire = cell_module->wire(port.first); - if (!cell_wire) - continue; - auto it = cell_wire->attributes.find(ID::invertible_pin); - if (it == cell_wire->attributes.end()) - continue; - IdString param_name = RTLIL::escape_id(it->second.decode_string()); - auto it2 = cell->parameters.find(param_name); - // Inversion not used -- skip. - if (it2 == cell->parameters.end()) - continue; - SigSpec sig = port.second; - if (it2->second.size() != sig.size()) - log_error("The inversion parameter needs to be the same width as the port (%s.%s port %s parameter %s)", log_id(module->name), log_id(cell->type), log_id(port.first), log_id(param_name)); - RTLIL::Const invmask = it2->second; - cell->parameters.erase(param_name); - if (invmask.is_fully_zero()) - continue; - Wire *iwire = module->addWire(NEW_ID, sig.size()); - for (int i = 0; i < sig.size(); i++) - if (invmask[i] == State::S1) { - RTLIL::Cell *icell = module->addCell(NEW_ID, RTLIL::escape_id(inv_celltype)); - icell->setPort(RTLIL::escape_id(inv_portname), SigSpec(iwire, i)); - icell->setPort(RTLIL::escape_id(inv_portname2), sig[i]); - log("Inserting %s on %s.%s.%s[%d].\n", inv_celltype.c_str(), log_id(module), log_id(cell->type), log_id(port.first), i); - sig[i] = SigBit(iwire, i); - } - cell->setPort(port.first, sig); - } + for (auto port : cell->connections()) { + auto cell_module = design->module(cell->type); + if (!cell_module) + continue; + auto cell_wire = cell_module->wire(port.first); + if (!cell_wire) + continue; + auto it = cell_wire->attributes.find(ID::invertible_pin); + if (it == cell_wire->attributes.end()) + continue; + IdString param_name = RTLIL::escape_id(it->second.decode_string()); + auto it2 = cell->parameters.find(param_name); + // Inversion not used -- skip. + if (it2 == cell->parameters.end()) + continue; + SigSpec sig = port.second; + if (it2->second.size() != sig.size()) + log_error( + "The inversion parameter needs to be the same width as the port (%s.%s port %s parameter %s)", + log_id(module->name), log_id(cell->type), log_id(port.first), log_id(param_name)); + RTLIL::Const invmask = it2->second; + cell->parameters.erase(param_name); + if (invmask.is_fully_zero()) + continue; + Wire *iwire = module->addWire(NEW_ID, sig.size()); + for (int i = 0; i < sig.size(); i++) + if (invmask[i] == State::S1) { + RTLIL::Cell *icell = module->addCell(NEW_ID, RTLIL::escape_id(inv_celltype)); + icell->setPort(RTLIL::escape_id(inv_portname), SigSpec(iwire, i)); + icell->setPort(RTLIL::escape_id(inv_portname2), sig[i]); + log("Inserting %s on %s.%s.%s[%d].\n", inv_celltype.c_str(), log_id(module), + log_id(cell->type), log_id(port.first), i); + sig[i] = SigBit(iwire, i); + } + cell->setPort(port.first, sig); + } } } } ExtractinvPass; diff --git a/passes/techmap/filterlib.cc b/passes/techmap/filterlib.cc index 05cfa6d24b6..f553527d3b4 100644 --- a/passes/techmap/filterlib.cc +++ b/passes/techmap/filterlib.cc @@ -1,4 +1,3 @@ #define FILTERLIB #include "libparse.cc" - diff --git a/passes/techmap/flatten.cc b/passes/techmap/flatten.cc index 7e6df5d2c1f..e9532a39b36 100644 --- a/passes/techmap/flatten.cc +++ b/passes/techmap/flatten.cc @@ -17,12 +17,12 @@ * */ -#include "kernel/yosys.h" -#include "kernel/utils.h" #include "kernel/sigtools.h" +#include "kernel/utils.h" +#include "kernel/yosys.h" -#include #include +#include #include USING_YOSYS_NAMESPACE @@ -40,14 +40,9 @@ IdString concat_name(RTLIL::Cell *cell, IdString object_name) } } -template -IdString map_name(RTLIL::Cell *cell, T *object) -{ - return cell->module->uniquify(concat_name(cell, object->name)); -} +template IdString map_name(RTLIL::Cell *cell, T *object) { return cell->module->uniquify(concat_name(cell, object->name)); } -template -void map_attributes(RTLIL::Cell *cell, T *object, IdString orig_object_name) +template void map_attributes(RTLIL::Cell *cell, T *object, IdString orig_object_name) { if (object->has_attribute(ID::src)) object->add_strpool_attribute(ID::src, cell->get_strpool_attribute(ID::src)); @@ -64,7 +59,7 @@ void map_attributes(RTLIL::Cell *cell, T *object, IdString orig_object_name) } } -void map_sigspec(const dict &map, RTLIL::SigSpec &sig, RTLIL::Module *into = nullptr) +void map_sigspec(const dict &map, RTLIL::SigSpec &sig, RTLIL::Module *into = nullptr) { vector chunks = sig; for (auto &chunk : chunks) @@ -73,11 +68,11 @@ void map_sigspec(const dict &map, RTLIL::SigSpec &si sig = chunks; } -struct FlattenWorker -{ +struct FlattenWorker { bool ignore_wb = false; - void flatten_cell(RTLIL::Design *design, RTLIL::Module *module, RTLIL::Cell *cell, RTLIL::Module *tpl, SigMap &sigmap, std::vector &new_cells) + void flatten_cell(RTLIL::Design *design, RTLIL::Module *module, RTLIL::Cell *cell, RTLIL::Module *tpl, SigMap &sigmap, + std::vector &new_cells) { // Copy the contents of the flattened cell @@ -89,7 +84,7 @@ struct FlattenWorker design->select(module, new_memory); } - dict wire_map; + dict wire_map; dict positional_ports; for (auto tpl_wire : tpl->wires()) { if (tpl_wire->port_id > 0) @@ -101,8 +96,8 @@ struct FlattenWorker if (hier_wire != nullptr && hier_wire->get_bool_attribute(ID::hierconn)) { hier_wire->attributes.erase(ID::hierconn); if (GetSize(hier_wire) < GetSize(tpl_wire)) { - log_warning("Widening signal %s.%s to match size of %s.%s (via %s.%s).\n", - log_id(module), log_id(hier_wire), log_id(tpl), log_id(tpl_wire), log_id(module), log_id(cell)); + log_warning("Widening signal %s.%s to match size of %s.%s (via %s.%s).\n", log_id(module), + log_id(hier_wire), log_id(tpl), log_id(tpl_wire), log_id(module), log_id(cell)); hier_wire->width = GetSize(tpl_wire); } new_wire = hier_wire; @@ -165,15 +160,14 @@ struct FlattenWorker for (auto bit : tpl_conn.first) tpl_driven.insert(bit); - for (auto &port_it : cell->connections()) - { + for (auto &port_it : cell->connections()) { IdString port_name = port_it.first; if (positional_ports.count(port_name) > 0) port_name = positional_ports.at(port_name); if (tpl->wire(port_name) == nullptr || tpl->wire(port_name)->port_id == 0) { if (port_name.begins_with("$")) - log_error("Can't map port `%s' of cell `%s' to template `%s'!\n", - port_name.c_str(), cell->name.c_str(), tpl->name.c_str()); + log_error("Can't map port `%s' of cell `%s' to template `%s'!\n", port_name.c_str(), cell->name.c_str(), + tpl->name.c_str()); continue; } @@ -213,8 +207,8 @@ struct FlattenWorker log_assert(new_conn.first.size() == new_conn.second.size()); if (sigmap(new_conn.first).has_const()) - log_error("Cell port %s.%s.%s is driving constant bits: %s <= %s\n", - log_id(module), log_id(cell), log_id(port_it.first), log_signal(new_conn.first), log_signal(new_conn.second)); + log_error("Cell port %s.%s.%s is driving constant bits: %s <= %s\n", log_id(module), log_id(cell), + log_id(port_it.first), log_signal(new_conn.first), log_signal(new_conn.second)); module->connect(new_conn); sigmap.add(new_conn.first, new_conn.second); @@ -223,15 +217,14 @@ struct FlattenWorker module->remove(cell); } - void flatten_module(RTLIL::Design *design, RTLIL::Module *module, pool &used_modules) + void flatten_module(RTLIL::Design *design, RTLIL::Module *module, pool &used_modules) { if (!design->selected(module) || module->get_blackbox_attribute(ignore_wb)) return; SigMap sigmap(module); - std::vector worklist = module->selected_cells(); - while (!worklist.empty()) - { + std::vector worklist = module->selected_cells(); + while (!worklist.empty()) { RTLIL::Cell *cell = worklist.back(); worklist.pop_back(); @@ -258,7 +251,7 @@ struct FlattenWorker }; struct FlattenPass : public Pass { - FlattenPass() : Pass("flatten", "flatten design") { } + FlattenPass() : Pass("flatten", "flatten design") {} void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| @@ -299,14 +292,14 @@ struct FlattenPass : public Pass { if (module->get_bool_attribute(ID::top)) top = module; - pool used_modules; + pool used_modules; if (top == nullptr) used_modules = design->modules(); else used_modules.insert(top); - TopoSort> topo_modules; - pool worklist = used_modules; + TopoSort> topo_modules; + pool worklist = used_modules; while (!worklist.empty()) { RTLIL::Module *module = worklist.pop(); for (auto cell : module->selected_cells()) { diff --git a/passes/techmap/flowmap.cc b/passes/techmap/flowmap.cc index 579503a0b75..13b60cf281e 100644 --- a/passes/techmap/flowmap.cc +++ b/passes/techmap/flowmap.cc @@ -95,29 +95,26 @@ // // We call this IR "LUT IR". -#include "kernel/yosys.h" -#include "kernel/sigtools.h" -#include "kernel/modtools.h" #include "kernel/consteval.h" +#include "kernel/modtools.h" +#include "kernel/sigtools.h" +#include "kernel/yosys.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN -struct GraphStyle -{ +struct GraphStyle { string label; string color, fillcolor; - GraphStyle(string label = "", string color = "black", string fillcolor = "") : - label(label), color(color), fillcolor(fillcolor) {} + GraphStyle(string label = "", string color = "black", string fillcolor = "") : label(label), color(color), fillcolor(fillcolor) {} }; static string dot_escape(string value) { std::string escaped; for (char c : value) { - if (c == '\n') - { + if (c == '\n') { escaped += "\\n"; continue; } @@ -128,22 +125,17 @@ static string dot_escape(string value) return escaped; } -static void dump_dot_graph(string filename, - pool nodes, dict> edges, - pool inputs, pool outputs, - std::function node_style = - [](RTLIL::SigBit) { return GraphStyle{}; }, - std::function edge_style = - [](RTLIL::SigBit, RTLIL::SigBit) { return GraphStyle{}; }, - string name = "") +static void dump_dot_graph( + string filename, pool nodes, dict> edges, pool inputs, pool outputs, + std::function node_style = [](RTLIL::SigBit) { return GraphStyle{}; }, + std::function edge_style = [](RTLIL::SigBit, RTLIL::SigBit) { return GraphStyle{}; }, string name = "") { FILE *f = fopen(filename.c_str(), "w"); fprintf(f, "digraph \"%s\" {\n", name.c_str()); fprintf(f, " rankdir=\"TB\";\n"); dict ids; - for (auto node : nodes) - { + for (auto node : nodes) { ids[node] = ids.size(); string shape = "ellipse"; @@ -155,8 +147,8 @@ static void dump_dot_graph(string filename, string style = ""; if (!prop.fillcolor.empty()) style = "filled"; - fprintf(f, " n%d [ shape=%s, fontname=\"Monospace\", label=\"%s\", color=\"%s\", fillcolor=\"%s\", style=\"%s\" ];\n", - ids[node], shape.c_str(), dot_escape(prop.label.c_str()).c_str(), prop.color.c_str(), prop.fillcolor.c_str(), style.c_str()); + fprintf(f, " n%d [ shape=%s, fontname=\"Monospace\", label=\"%s\", color=\"%s\", fillcolor=\"%s\", style=\"%s\" ];\n", ids[node], + shape.c_str(), dot_escape(prop.label.c_str()).c_str(), prop.color.c_str(), prop.fillcolor.c_str(), style.c_str()); } fprintf(f, " { rank=\"source\"; "); @@ -171,15 +163,13 @@ static void dump_dot_graph(string filename, fprintf(f, "n%d; ", ids[output]); fprintf(f, "}\n"); - for (auto edge : edges) - { + for (auto edge : edges) { auto source = edge.first; for (auto sink : edge.second) { - if (nodes[source] && nodes[sink]) - { + if (nodes[source] && nodes[sink]) { auto prop = edge_style(source, sink); - fprintf(f, " n%d -> n%d [ label=\"%s\", color=\"%s\", fillcolor=\"%s\" ];\n", - ids[source], ids[sink], dot_escape(prop.label.c_str()).c_str(), prop.color.c_str(), prop.fillcolor.c_str()); + fprintf(f, " n%d -> n%d [ label=\"%s\", color=\"%s\", fillcolor=\"%s\" ];\n", ids[source], ids[sink], + dot_escape(prop.label.c_str()).c_str(), prop.color.c_str(), prop.fillcolor.c_str()); } } } @@ -188,8 +178,7 @@ static void dump_dot_graph(string filename, fclose(f); } -struct FlowGraph -{ +struct FlowGraph { const RTLIL::SigBit source; RTLIL::SigBit sink; pool nodes = {source}; @@ -234,36 +223,19 @@ struct FlowGraph // in the sense that nodes v't and v'b are overlaid on top of the original node v, and only exist // in paths and worklists. - struct NodePrime - { + struct NodePrime { RTLIL::SigBit node; bool is_bottom; - NodePrime(RTLIL::SigBit node, bool is_bottom) : - node(node), is_bottom(is_bottom) {} + NodePrime(RTLIL::SigBit node, bool is_bottom) : node(node), is_bottom(is_bottom) {} - bool operator==(const NodePrime &other) const - { - return node == other.node && is_bottom == other.is_bottom; - } - bool operator!=(const NodePrime &other) const - { - return !(*this == other); - } - unsigned int hash() const - { - return hash_ops>::hash({node, is_bottom}); - } + bool operator==(const NodePrime &other) const { return node == other.node && is_bottom == other.is_bottom; } + bool operator!=(const NodePrime &other) const { return !(*this == other); } + unsigned int hash() const { return hash_ops>::hash({node, is_bottom}); } - static NodePrime top(RTLIL::SigBit node) - { - return NodePrime(node, /*is_bottom=*/false); - } + static NodePrime top(RTLIL::SigBit node) { return NodePrime(node, /*is_bottom=*/false); } - static NodePrime bottom(RTLIL::SigBit node) - { - return NodePrime(node, /*is_bottom=*/true); - } + static NodePrime bottom(RTLIL::SigBit node) { return NodePrime(node, /*is_bottom=*/true); } NodePrime as_top() const { @@ -293,37 +265,26 @@ struct FlowGraph if (!node_prime.is_bottom) // vt { - if (!visited[node_prime.as_bottom()] && node_flow[node_prime.node] < MAX_NODE_FLOW) - { + if (!visited[node_prime.as_bottom()] && node_flow[node_prime.node] < MAX_NODE_FLOW) { path.push_back(node_prime.as_bottom()); found = true; - } - else - { - for (auto node_pred : edges_bw[node_prime.node]) - { - if (!visited[NodePrime::bottom(node_pred)] && edge_flow[{node_pred, node_prime.node}] > 0) - { + } else { + for (auto node_pred : edges_bw[node_prime.node]) { + if (!visited[NodePrime::bottom(node_pred)] && edge_flow[{node_pred, node_prime.node}] > 0) { path.push_back(NodePrime::bottom(node_pred)); found = true; break; } } } - } - else // vb + } else // vb { - if (!visited[node_prime.as_top()] && node_flow[node_prime.node] > 0) - { + if (!visited[node_prime.as_top()] && node_flow[node_prime.node] > 0) { path.push_back(node_prime.as_top()); found = true; - } - else - { - for (auto node_succ : edges_fw[node_prime.node]) - { - if (!visited[NodePrime::top(node_succ)] /* && edge_flow[...] < ∞ */) - { + } else { + for (auto node_succ : edges_fw[node_prime.node]) { + if (!visited[NodePrime::top(node_succ)] /* && edge_flow[...] < ∞ */) { path.push_back(NodePrime::top(node_succ)); found = true; break; @@ -332,45 +293,33 @@ struct FlowGraph } } - if (!found && path.size() > 1) - { + if (!found && path.size() > 1) { path.pop_back(); found = true; } - } while(path.back() != sink_prime && found); + } while (path.back() != sink_prime && found); - if (commit && path.back() == sink_prime) - { + if (commit && path.back() == sink_prime) { auto prev_prime = path.front(); - for (auto node_prime : path) - { + for (auto node_prime : path) { if (node_prime == source_prime) continue; log_assert(prev_prime.is_bottom ^ node_prime.is_bottom); - if (prev_prime.node == node_prime.node) - { + if (prev_prime.node == node_prime.node) { auto node = node_prime.node; - if (!prev_prime.is_bottom && node_prime.is_bottom) - { + if (!prev_prime.is_bottom && node_prime.is_bottom) { log_assert(node_flow[node] == 0); node_flow[node]++; - } - else - { + } else { log_assert(node_flow[node] != 0); node_flow[node]--; } - } - else - { - if (prev_prime.is_bottom && !node_prime.is_bottom) - { + } else { + if (prev_prime.is_bottom && !node_prime.is_bottom) { log_assert(true /* edge_flow[...] < ∞ */); edge_flow[{prev_prime.node, node_prime.node}]++; - } - else - { + } else { log_assert((edge_flow[{node_prime.node, prev_prime.node}] > 0)); edge_flow[{node_prime.node, prev_prime.node}]--; } @@ -399,8 +348,7 @@ struct FlowGraph NodePrime source_prime = {source, true}; pool visited; vector worklist = {source_prime}; - while (!worklist.empty()) - { + while (!worklist.empty()) { auto node_prime = worklist.back(); worklist.pop_back(); if (visited[node_prime]) @@ -419,8 +367,7 @@ struct FlowGraph for (auto node_pred : edges_bw[node_prime.node]) if (edge_flow[{node_pred, node_prime.node}] > 0) worklist.push_back(NodePrime::bottom(node_pred)); - } - else // bottom + } else // bottom { if (node_flow[node_prime.node] > 0) worklist.push_back(node_prime.as_top()); @@ -443,8 +390,7 @@ struct FlowGraph } }; -struct FlowmapWorker -{ +struct FlowmapWorker { int order; int r_alpha, r_beta, r_gamma; bool debug, debug_relax; @@ -475,10 +421,9 @@ struct FlowmapWorker Slack, }; - void dump_dot_graph(string filename, GraphMode mode, - pool subgraph_nodes = {}, dict> subgraph_edges = {}, - dict> collapsed = {}, - pair, pool> cut = {}) + void dump_dot_graph(string filename, GraphMode mode, pool subgraph_nodes = {}, + dict> subgraph_edges = {}, dict> collapsed = {}, + pair, pool> cut = {}) { if (subgraph_nodes.empty()) subgraph_nodes = nodes; @@ -490,37 +435,31 @@ struct FlowmapWorker for (auto collapsed_node : collapsed[node]) if (collapsed_node != node) label += stringf(" %s", log_signal(collapsed_node)); - switch (mode) - { - case GraphMode::Label: - if (labels[node] == -1) - { - label += "\nl=?"; - return GraphStyle{label}; - } - else - { - label += stringf("\nl=%d", labels[node]); - string fillcolor = stringf("/set311/%d", 1 + labels[node] % 11); - return GraphStyle{label, "", fillcolor}; - } - - case GraphMode::Cut: - if (cut.first[node]) - return GraphStyle{label, "blue"}; - if (cut.second[node]) - return GraphStyle{label, "red"}; + switch (mode) { + case GraphMode::Label: + if (labels[node] == -1) { + label += "\nl=?"; return GraphStyle{label}; + } else { + label += stringf("\nl=%d", labels[node]); + string fillcolor = stringf("/set311/%d", 1 + labels[node] % 11); + return GraphStyle{label, "", fillcolor}; + } - case GraphMode::Slack: - label += stringf("\nd=%d a=%d\ns=%d", lut_depths[node], lut_altitudes[node], lut_slacks[node]); - return GraphStyle{label, lut_slacks[node] == 0 ? "red" : "black"}; + case GraphMode::Cut: + if (cut.first[node]) + return GraphStyle{label, "blue"}; + if (cut.second[node]) + return GraphStyle{label, "red"}; + return GraphStyle{label}; + + case GraphMode::Slack: + label += stringf("\nd=%d a=%d\ns=%d", lut_depths[node], lut_altitudes[node], lut_slacks[node]); + return GraphStyle{label, lut_slacks[node] == 0 ? "red" : "black"}; } return GraphStyle{label}; }; - auto edge_style = [&](RTLIL::SigBit, RTLIL::SigBit) { - return GraphStyle{}; - }; + auto edge_style = [&](RTLIL::SigBit, RTLIL::SigBit) { return GraphStyle{}; }; ::dump_dot_graph(filename, subgraph_nodes, subgraph_edges, inputs, outputs, node_style, edge_style, module->name.str()); } @@ -536,12 +475,10 @@ struct FlowmapWorker { pool subgraph; pool worklist = {sink}; - while (!worklist.empty()) - { + while (!worklist.empty()) { auto node = worklist.pop(); subgraph.insert(node); - for (auto source : edges_bw[node]) - { + for (auto source : edges_bw[node]) { if (!subgraph[source]) worklist.insert(source); } @@ -555,8 +492,7 @@ struct FlowmapWorker flow_graph.sink = sink; pool worklist = {sink}, visited; - while (!worklist.empty()) - { + while (!worklist.empty()) { auto node = worklist.pop(); visited.insert(node); @@ -565,18 +501,15 @@ struct FlowmapWorker flow_graph.collapsed[collapsed_node].insert(node); flow_graph.nodes.insert(collapsed_node); - for (auto node_pred : edges_bw[node]) - { + for (auto node_pred : edges_bw[node]) { auto collapsed_node_pred = labels[node_pred] == p ? sink : node_pred; if (node_pred != collapsed_node_pred) flow_graph.collapsed[collapsed_node_pred].insert(node_pred); - if (collapsed_node != collapsed_node_pred) - { + if (collapsed_node != collapsed_node_pred) { flow_graph.edges_bw[collapsed_node].insert(collapsed_node_pred); flow_graph.edges_fw[collapsed_node_pred].insert(collapsed_node); } - if (inputs[node_pred]) - { + if (inputs[node_pred]) { flow_graph.edges_bw[collapsed_node_pred].insert(flow_graph.source); flow_graph.edges_fw[flow_graph.source].insert(collapsed_node_pred); } @@ -590,8 +523,7 @@ struct FlowmapWorker void discover_nodes(pool cell_types) { - for (auto cell : module->selected_cells()) - { + for (auto cell : module->selected_cells()) { if (!cell_types[cell->type]) continue; @@ -599,14 +531,14 @@ struct FlowmapWorker log_error("Cell %s (%s.%s) is unknown.\n", cell->type.c_str(), log_id(module), log_id(cell)); pool fanout; - for (auto conn : cell->connections()) - { - if (!cell->output(conn.first)) continue; + for (auto conn : cell->connections()) { + if (!cell->output(conn.first)) + continue; int offset = -1; - for (auto bit : conn.second) - { + for (auto bit : conn.second) { offset++; - if (!bit.wire) continue; + if (!bit.wire) + continue; auto mapped_bit = sigmap(bit); if (nodes[mapped_bit]) log_error("Multiple drivers found for wire %s.\n", log_signal(mapped_bit)); @@ -617,14 +549,13 @@ struct FlowmapWorker } int fanin = 0; - for (auto conn : cell->connections()) - { - if (!cell->input(conn.first)) continue; - for (auto bit : sigmap(conn.second)) - { - if (!bit.wire) continue; - for (auto fanout_bit : fanout) - { + for (auto conn : cell->connections()) { + if (!cell->input(conn.first)) + continue; + for (auto bit : sigmap(conn.second)) { + if (!bit.wire) + continue; + for (auto fanout_bit : fanout) { edges_fw[bit].insert(fanout_bit); edges_bw[fanout_bit].insert(bit); } @@ -633,24 +564,21 @@ struct FlowmapWorker } if (fanin > order) - log_error("Cell %s (%s.%s) with fan-in %d cannot be mapped to a %d-LUT.\n", - cell->type.c_str(), log_id(module), log_id(cell), fanin, order); + log_error("Cell %s (%s.%s) with fan-in %d cannot be mapped to a %d-LUT.\n", cell->type.c_str(), log_id(module), + log_id(cell), fanin, order); gate_count++; gate_area += 1 << fanin; } - for (auto edge : edges_fw) - { - if (!nodes[edge.first]) - { + for (auto edge : edges_fw) { + if (!nodes[edge.first]) { inputs.insert(edge.first); nodes.insert(edge.first); } } - for (auto node : nodes) - { + for (auto node : nodes) { auto node_info = index.query(node); if (node_info->is_output && !inputs[node]) outputs.insert(node); @@ -659,8 +587,7 @@ struct FlowmapWorker outputs.insert(node); } - if (debug) - { + if (debug) { dump_dot_graph("flowmap-initial.dot", GraphMode::Label); log("Dumped initial graph to `flowmap-initial.dot`.\n"); } @@ -670,8 +597,7 @@ struct FlowmapWorker { for (auto node : nodes) labels[node] = -1; - for (auto input : inputs) - { + for (auto input : inputs) { if (input.wire->attributes.count(ID($flowmap_level))) labels[input] = input.wire->attributes[ID($flowmap_level)].as_int(); else @@ -680,17 +606,14 @@ struct FlowmapWorker pool worklist = nodes; int debug_num = 0; - while (!worklist.empty()) - { + while (!worklist.empty()) { auto sink = worklist.pop(); if (labels[sink] != -1) continue; bool inputs_have_labels = true; - for (auto sink_input : edges_bw[sink]) - { - if (labels[sink_input] == -1) - { + for (auto sink_input : edges_bw[sink]) { + if (labels[sink_input] == -1) { inputs_have_labels = false; break; } @@ -698,8 +621,7 @@ struct FlowmapWorker if (!inputs_have_labels) continue; - if (debug) - { + if (debug) { debug_num++; log("Examining subgraph %d rooted in %s.\n", debug_num, log_signal(sink)); } @@ -713,15 +635,12 @@ struct FlowmapWorker FlowGraph flow_graph = build_flow_graph(sink, p); int flow = flow_graph.maximum_flow(order); pool x, xi; - if (flow <= order) - { + if (flow <= order) { labels[sink] = p; auto cut = flow_graph.edge_cut(); x = cut.first; xi = cut.second; - } - else - { + } else { labels[sink] = p + 1; x = subgraph; x.erase(sink); @@ -730,8 +649,7 @@ struct FlowmapWorker lut_gates[sink] = xi; pool k; - for (auto xi_node : xi) - { + for (auto xi_node : xi) { for (auto xi_node_pred : edges_bw[xi_node]) if (x[xi_node_pred]) k.insert(xi_node_pred); @@ -741,8 +659,7 @@ struct FlowmapWorker for (auto k_node : k) lut_edges_fw[k_node].insert(sink); - if (debug) - { + if (debug) { log(" Maximum flow: %d. Assigned label %d.\n", flow, labels[sink]); dump_dot_graph(stringf("flowmap-%d-sub.dot", debug_num), GraphMode::Cut, subgraph, {}, {}, {x, xi}); log(" Dumped subgraph to `flowmap-%d-sub.dot`.\n", debug_num); @@ -762,8 +679,7 @@ struct FlowmapWorker worklist.insert(sink_succ); } - if (debug) - { + if (debug) { dump_dot_graph("flowmap-labeled.dot", GraphMode::Label); log("Dumped labeled graph to `flowmap-labeled.dot`.\n"); } @@ -772,8 +688,7 @@ struct FlowmapWorker int map_luts() { pool worklist = outputs; - while (!worklist.empty()) - { + while (!worklist.empty()) { auto lut_node = worklist.pop(); lut_nodes.insert(lut_node); for (auto input_node : lut_edges_bw[lut_node]) @@ -786,8 +701,7 @@ struct FlowmapWorker depth = max(depth, label.second); log("Mapped to %d LUTs with maximum depth %d.\n", GetSize(lut_nodes), depth); - if (debug) - { + if (debug) { dump_dot_lut_graph("flowmap-mapped.dot", GraphMode::Label); log("Dumped mapped graph to `flowmap-mapped.dot`.\n"); } @@ -798,8 +712,7 @@ struct FlowmapWorker void realize_derealize_lut(RTLIL::SigBit lut, pool *changed = nullptr) { pool worklist = {lut}; - while (!worklist.empty()) - { + while (!worklist.empty()) { auto lut = worklist.pop(); if (inputs[lut]) continue; @@ -833,8 +746,7 @@ struct FlowmapWorker lut_edges_bw[succ].insert(pred); realize_derealize_lut(pred, changed); - if (changed) - { + if (changed) { changed->insert(pred); changed->insert(succ); } @@ -848,8 +760,7 @@ struct FlowmapWorker lut_edges_bw[succ].erase(pred); realize_derealize_lut(pred, changed); - if (changed) - { + if (changed) { if (lut_nodes[pred]) changed->insert(pred); changed->insert(succ); @@ -861,17 +772,14 @@ struct FlowmapWorker pool gate_inputs = lut_edges_bw[lut]; pool other_inputs; pool worklist = {lut}; - while (!worklist.empty()) - { + while (!worklist.empty()) { auto node = worklist.pop(); - for (auto node_pred : edges_bw[node]) - { + for (auto node_pred : edges_bw[node]) { if (node_pred == lut_gate) continue; if (lut_gates[lut][node_pred]) worklist.insert(node_pred); - else - { + else { gate_inputs.erase(node_pred); other_inputs.insert(node_pred); } @@ -880,8 +788,8 @@ struct FlowmapWorker return {gate_inputs, other_inputs}; } - void compute_lut_distances(dict &lut_distances, bool forward, - pool initial = {}, pool *changed = nullptr) + void compute_lut_distances(dict &lut_distances, bool forward, pool initial = {}, + pool *changed = nullptr) { pool terminals = forward ? inputs : outputs; auto &lut_edges_next = forward ? lut_edges_fw : lut_edges_bw; @@ -893,8 +801,7 @@ struct FlowmapWorker lut_distances.erase(node); pool worklist = initial; - while (!worklist.empty()) - { + while (!worklist.empty()) { auto lut = worklist.pop(); int lut_distance = 0; if (forward && inputs[lut]) @@ -902,8 +809,7 @@ struct FlowmapWorker for (auto lut_prev : lut_edges_prev[lut]) if ((lut_nodes[lut_prev] || inputs[lut_prev]) && lut_distances.count(lut_prev)) lut_distance = max(lut_distance, lut_distances[lut_prev] + 1); - if (!lut_distances.count(lut) || lut_distances[lut] != lut_distance) - { + if (!lut_distances.count(lut) || lut_distances[lut] != lut_distance) { lut_distances[lut] = lut_distance; if (changed != nullptr && !inputs[lut]) changed->insert(lut); @@ -937,38 +843,31 @@ struct FlowmapWorker // LUT critical output set is the set of outputs whose depth will increase (equivalently, slack will decrease) if the depth of // the LUT increases. (This is referred to as RPOv for LUTv in the paper.) - void compute_lut_critical_outputs(dict> &lut_critical_outputs, - pool worklist = {}) + void compute_lut_critical_outputs(dict> &lut_critical_outputs, pool worklist = {}) { if (worklist.empty()) worklist = lut_nodes; - while (!worklist.empty()) - { + while (!worklist.empty()) { bool updated_some = false; - for (auto lut : worklist) - { + for (auto lut : worklist) { if (outputs[lut]) lut_critical_outputs[lut] = {lut}; - else - { + else { bool all_succ_computed = true; lut_critical_outputs[lut] = {}; - for (auto lut_succ : lut_edges_fw[lut]) - { - if (lut_nodes[lut_succ] && lut_depths[lut_succ] == lut_depths[lut] + 1) - { + for (auto lut_succ : lut_edges_fw[lut]) { + if (lut_nodes[lut_succ] && lut_depths[lut_succ] == lut_depths[lut] + 1) { if (lut_critical_outputs.count(lut_succ)) - lut_critical_outputs[lut].insert(lut_critical_outputs[lut_succ].begin(), lut_critical_outputs[lut_succ].end()); - else - { + lut_critical_outputs[lut].insert(lut_critical_outputs[lut_succ].begin(), + lut_critical_outputs[lut_succ].end()); + else { all_succ_computed = false; break; } } } - if (!all_succ_computed) - { + if (!all_succ_computed) { lut_critical_outputs.erase(lut); continue; } @@ -984,18 +883,15 @@ struct FlowmapWorker // path to the output. Conservatively, if we increase depth of some LUT, every LUT in its input cone needs to have its critical output // set invalidated, too. pool invalidate_lut_critical_outputs(dict> &lut_critical_outputs, - pool worklist) + pool worklist) { pool changed; - while (!worklist.empty()) - { + while (!worklist.empty()) { auto lut = worklist.pop(); changed.insert(lut); lut_critical_outputs.erase(lut); - for (auto lut_pred : lut_edges_bw[lut]) - { - if (lut_nodes[lut_pred] && !changed[lut_pred]) - { + for (auto lut_pred : lut_edges_bw[lut]) { + if (lut_nodes[lut_pred] && !changed[lut_pred]) { changed.insert(lut_pred); worklist.insert(lut_pred); } @@ -1013,24 +909,20 @@ struct FlowmapWorker log_assert(lut_critical_output.second == gold_lut_critical_outputs[lut_critical_output.first]); } - void update_lut_critical_outputs(dict> &lut_critical_outputs, - pool worklist = {}) + void update_lut_critical_outputs(dict> &lut_critical_outputs, pool worklist = {}) { - if (!worklist.empty()) - { + if (!worklist.empty()) { pool invalidated = invalidate_lut_critical_outputs(lut_critical_outputs, worklist); compute_lut_critical_outputs(lut_critical_outputs, invalidated); check_lut_critical_outputs(lut_critical_outputs); - } - else + } else compute_lut_critical_outputs(lut_critical_outputs); } void update_breaking_node_potentials(dict> &potentials, - const dict> &lut_critical_outputs) + const dict> &lut_critical_outputs) { - for (auto lut : lut_nodes) - { + for (auto lut : lut_nodes) { if (potentials.count(lut)) continue; if (lut_gates[lut].size() == 1 || lut_slacks[lut] == 0) @@ -1039,8 +931,7 @@ struct FlowmapWorker if (debug_relax) log(" Computing potentials for LUT %s.\n", log_signal(lut)); - for (auto lut_gate : lut_gates[lut]) - { + for (auto lut_gate : lut_gates[lut]) { if (lut == lut_gate) continue; @@ -1051,35 +942,29 @@ struct FlowmapWorker auto cut_inputs = cut_lut_at_gate(lut, lut_gate); pool gate_inputs = cut_inputs.first, other_inputs = cut_inputs.second; - if (gate_inputs.empty() && (int)other_inputs.size() >= order) - { + if (gate_inputs.empty() && (int)other_inputs.size() >= order) { if (debug_relax) log(" Breaking would result in a (k+1)-LUT.\n"); continue; } pool elim_fanin_luts; - for (auto gate_input : gate_inputs) - { - if (lut_edges_fw[gate_input].size() == 1) - { + for (auto gate_input : gate_inputs) { + if (lut_edges_fw[gate_input].size() == 1) { log_assert(lut_edges_fw[gate_input][lut]); elim_fanin_luts.insert(gate_input); } } - if (debug_relax) - { + if (debug_relax) { if (!lut_nodes[lut_gate]) log(" Breaking requires a new LUT.\n"); - if (!gate_inputs.empty()) - { + if (!gate_inputs.empty()) { log(" Breaking eliminates LUT inputs"); for (auto gate_input : gate_inputs) log(" %s", log_signal(gate_input)); log(".\n"); } - if (!elim_fanin_luts.empty()) - { + if (!elim_fanin_luts.empty()) { log(" Breaking eliminates fan-in LUTs"); for (auto elim_fanin_lut : elim_fanin_luts) log(" %s", log_signal(elim_fanin_lut)); @@ -1093,10 +978,8 @@ struct FlowmapWorker // Try to merge LUTv with one of its successors. RTLIL::SigBit last_lut_succ; int fanout = 0; - for (auto lut_succ : lut_edges_fw[lut]) - { - if (lut_nodes[lut_succ]) - { + for (auto lut_succ : lut_edges_fw[lut]) { + if (lut_nodes[lut_succ]) { fanout++; last_lut_succ = lut_succ; } @@ -1105,8 +988,7 @@ struct FlowmapWorker maybe_mergeable_luts.insert({lut, last_lut_succ}); // Try to merge LUTv with one of its predecessors. - for (auto lut_pred : other_inputs) - { + for (auto lut_pred : other_inputs) { int fanout = 0; for (auto lut_pred_succ : lut_edges_fw[lut_pred]) if (lut_nodes[lut_pred_succ] || lut_pred_succ == lut_gate) @@ -1116,8 +998,7 @@ struct FlowmapWorker } // Try to merge LUTw with one of its predecessors. - for (auto lut_gate_pred : lut_edges_bw[lut_gate]) - { + for (auto lut_gate_pred : lut_edges_bw[lut_gate]) { int fanout = 0; for (auto lut_gate_pred_succ : lut_edges_fw[lut_gate_pred]) if (lut_nodes[lut_gate_pred_succ] || lut_gate_pred_succ == lut_gate) @@ -1127,8 +1008,7 @@ struct FlowmapWorker } r_im = 0; - for (auto maybe_mergeable_pair : maybe_mergeable_luts) - { + for (auto maybe_mergeable_pair : maybe_mergeable_luts) { log_assert(lut_edges_fw[maybe_mergeable_pair.first][maybe_mergeable_pair.second]); pool unique_inputs; for (auto fst_lut_pred : lut_edges_bw[maybe_mergeable_pair.first]) @@ -1138,11 +1018,10 @@ struct FlowmapWorker if (lut_nodes[snd_lut_pred]) unique_inputs.insert(snd_lut_pred); unique_inputs.erase(maybe_mergeable_pair.first); - if ((int)unique_inputs.size() <= order) - { + if ((int)unique_inputs.size() <= order) { if (debug_relax) - log(" Breaking may allow merging %s and %s.\n", - log_signal(maybe_mergeable_pair.first), log_signal(maybe_mergeable_pair.second)); + log(" Breaking may allow merging %s and %s.\n", log_signal(maybe_mergeable_pair.first), + log_signal(maybe_mergeable_pair.second)); r_im++; } } @@ -1150,32 +1029,27 @@ struct FlowmapWorker int lut_gate_depth; if (lut_nodes[lut_gate]) lut_gate_depth = lut_depths[lut_gate]; - else - { + else { lut_gate_depth = 0; for (auto lut_gate_pred : lut_edges_bw[lut_gate]) lut_gate_depth = max(lut_gate_depth, lut_depths[lut_gate_pred] + 1); } if (lut_depths[lut] >= lut_gate_depth + 1) r_slk = 0; - else - { + else { int depth_delta = lut_gate_depth + 1 - lut_depths[lut]; - if (depth_delta > lut_slacks[lut]) - { + if (depth_delta > lut_slacks[lut]) { if (debug_relax) - log(" Breaking would increase depth by %d, which is more than available slack.\n", depth_delta); + log(" Breaking would increase depth by %d, which is more than available slack.\n", + depth_delta); continue; } - if (debug_relax) - { + if (debug_relax) { log(" Breaking increases depth of LUT by %d.\n", depth_delta); - if (lut_critical_outputs.at(lut).size()) - { + if (lut_critical_outputs.at(lut).size()) { log(" Breaking decreases slack of outputs"); - for (auto lut_critical_output : lut_critical_outputs.at(lut)) - { + for (auto lut_critical_output : lut_critical_outputs.at(lut)) { log(" %s", log_signal(lut_critical_output)); log_assert(lut_slacks[lut_critical_output] > 0); } @@ -1187,8 +1061,8 @@ struct FlowmapWorker int p = 100 * (r_alpha * r_ex + r_beta * r_im + r_gamma) / (r_slk + 1); if (debug_relax) - log(" Potential for breaking node %s: %d (Rex=%d, Rim=%d, Rslk=%d).\n", - log_signal(lut_gate), p, r_ex, r_im, r_slk); + log(" Potential for breaking node %s: %d (Rex=%d, Rim=%d, Rslk=%d).\n", log_signal(lut_gate), p, r_ex, + r_im, r_slk); potentials[lut][lut_gate] = p; } } @@ -1198,32 +1072,25 @@ struct FlowmapWorker { int initial_count = GetSize(lut_nodes); - for (auto node : lut_nodes) - { + for (auto node : lut_nodes) { lut_slacks[node] = depth_bound - (lut_depths[node] + lut_altitudes[node]); log_assert(lut_slacks[node] >= 0); } - if (debug) - { + if (debug) { dump_dot_lut_graph(stringf("flowmap-relax-%d-initial.dot", depth_bound), GraphMode::Slack); log(" Dumped initial slack graph to `flowmap-relax-%d-initial.dot`.\n", depth_bound); } dict> potentials; - for (int break_num = 1; ; break_num++) - { + for (int break_num = 1;; break_num++) { update_breaking_node_potentials(potentials, lut_critical_outputs); - if (potentials.empty()) - { + if (potentials.empty()) { log(" Relaxed to %d (+%d) LUTs.\n", GetSize(lut_nodes), GetSize(lut_nodes) - initial_count); - if (!first && break_num == 1) - { + if (!first && break_num == 1) { log(" Design fully relaxed.\n"); return true; - } - else - { + } else { log(" Slack exhausted.\n"); break; } @@ -1231,20 +1098,17 @@ struct FlowmapWorker RTLIL::SigBit breaking_lut, breaking_gate; int best_potential = INT_MIN; - for (auto lut_gate_potentials : potentials) - { - for (auto gate_potential : lut_gate_potentials.second) - { - if (gate_potential.second > best_potential) - { + for (auto lut_gate_potentials : potentials) { + for (auto gate_potential : lut_gate_potentials.second) { + if (gate_potential.second > best_potential) { breaking_lut = lut_gate_potentials.first; breaking_gate = gate_potential.first; best_potential = gate_potential.second; } } } - log(" Breaking LUT %s to %s LUT %s (potential %d).\n", - log_signal(breaking_lut), lut_nodes[breaking_gate] ? "reuse" : "extract", log_signal(breaking_gate), best_potential); + log(" Breaking LUT %s to %s LUT %s (potential %d).\n", log_signal(breaking_lut), + lut_nodes[breaking_gate] ? "reuse" : "extract", log_signal(breaking_gate), best_potential); if (debug_relax) log(" Removing breaking gate %s from LUT.\n", log_signal(breaking_gate)); @@ -1255,15 +1119,13 @@ struct FlowmapWorker pool worklist = lut_gates[breaking_lut]; pool elim_gates = gate_inputs; - while (!worklist.empty()) - { + while (!worklist.empty()) { auto lut_gate = worklist.pop(); bool all_gate_preds_elim = true; for (auto lut_gate_pred : edges_bw[lut_gate]) if (!elim_gates[lut_gate_pred]) all_gate_preds_elim = false; - if (all_gate_preds_elim) - { + if (all_gate_preds_elim) { if (debug_relax) log(" Removing gate %s from LUT.\n", log_signal(lut_gate)); lut_gates[breaking_lut].erase(lut_gate); @@ -1274,8 +1136,7 @@ struct FlowmapWorker log_assert(!lut_gates[breaking_lut].empty()); pool directly_affected_nodes = {breaking_lut}; - for (auto gate_input : gate_inputs) - { + for (auto gate_input : gate_inputs) { if (debug_relax) log(" Removing LUT edge %s -> %s.\n", log_signal(gate_input), log_signal(breaking_lut)); remove_lut_edge(gate_input, breaking_lut, &directly_affected_nodes); @@ -1290,8 +1151,7 @@ struct FlowmapWorker pool indirectly_affected_nodes = {}; update_lut_depths_altitudes(directly_affected_nodes, &indirectly_affected_nodes); update_lut_critical_outputs(lut_critical_outputs, indirectly_affected_nodes); - for (auto node : indirectly_affected_nodes) - { + for (auto node : indirectly_affected_nodes) { lut_slacks[node] = depth_bound - (lut_depths[node] + lut_altitudes[node]); log_assert(lut_slacks[node] >= 0); if (debug_relax) @@ -1300,24 +1160,22 @@ struct FlowmapWorker worklist = indirectly_affected_nodes; pool visited; - while (!worklist.empty()) - { + while (!worklist.empty()) { auto node = worklist.pop(); visited.insert(node); potentials.erase(node); - // We are invalidating the entire output cone of the gate IR node, not just of the LUT IR node. This is done to also invalidate - // all LUTs that could contain one of the indirectly affected nodes as a *part* of them, as they may not be in the output cone - // of any of the LUT IR nodes, e.g. if we have a LUT IR node A and node B as predecessors of node C, where node B includes all - // gates from node A. + // We are invalidating the entire output cone of the gate IR node, not just of the LUT IR node. This is done to also + // invalidate all LUTs that could contain one of the indirectly affected nodes as a *part* of them, as they may not be + // in the output cone of any of the LUT IR nodes, e.g. if we have a LUT IR node A and node B as predecessors of node + // C, where node B includes all gates from node A. for (auto node_succ : edges_fw[node]) if (!visited[node_succ]) worklist.insert(node_succ); } - if (debug) - { + if (debug) { dump_dot_lut_graph(stringf("flowmap-relax-%d-break-%d.dot", depth_bound, break_num), GraphMode::Slack); - log(" Dumped slack graph after break %d to `flowmap-relax-%d-break-%d.dot`.\n", break_num, depth_bound, break_num); + log(" Dumped slack graph after break %d to `flowmap-relax-%d-break-%d.dot`.\n", break_num, depth_bound, break_num); } } @@ -1330,8 +1188,7 @@ struct FlowmapWorker update_lut_depths_altitudes(); update_lut_critical_outputs(lut_critical_outputs); - for (int depth_bound = depth; depth_bound <= depth + optarea; depth_bound++) - { + for (int depth_bound = depth; depth_bound <= depth + optarea; depth_bound++) { log("Relaxing with depth bound %d.\n", depth_bound); bool fully_relaxed = relax_depth_for_bound(depth_bound == depth, depth_bound, lut_critical_outputs); @@ -1347,25 +1204,19 @@ struct FlowmapWorker ce.stop(input_node); pool mapped_nodes; - for (auto node : lut_nodes) - { - if (node_origins.count(node)) - { + for (auto node : lut_nodes) { + if (node_origins.count(node)) { auto origin = node_origins[node]; if (origin.cell->getPort(origin.port).size() == 1) - log("Packing %s.%s.%s (%s).\n", - log_id(module), log_id(origin.cell), origin.port.c_str(), log_signal(node)); + log("Packing %s.%s.%s (%s).\n", log_id(module), log_id(origin.cell), origin.port.c_str(), log_signal(node)); else - log("Packing %s.%s.%s [%d] (%s).\n", - log_id(module), log_id(origin.cell), origin.port.c_str(), origin.offset, log_signal(node)); - } - else - { + log("Packing %s.%s.%s [%d] (%s).\n", log_id(module), log_id(origin.cell), origin.port.c_str(), origin.offset, + log_signal(node)); + } else { log("Packing %s.%s.\n", log_id(module), log_signal(node)); } - for (auto gate_node : lut_gates[node]) - { + for (auto gate_node : lut_gates[node]) { log_assert(node_origins.count(gate_node)); if (gate_node == node) @@ -1373,30 +1224,28 @@ struct FlowmapWorker auto gate_origin = node_origins[gate_node]; if (gate_origin.cell->getPort(gate_origin.port).size() == 1) - log(" Packing %s.%s.%s (%s).\n", - log_id(module), log_id(gate_origin.cell), gate_origin.port.c_str(), log_signal(gate_node)); + log(" Packing %s.%s.%s (%s).\n", log_id(module), log_id(gate_origin.cell), gate_origin.port.c_str(), + log_signal(gate_node)); else - log(" Packing %s.%s.%s [%d] (%s).\n", - log_id(module), log_id(gate_origin.cell), gate_origin.port.c_str(), gate_origin.offset, log_signal(gate_node)); + log(" Packing %s.%s.%s [%d] (%s).\n", log_id(module), log_id(gate_origin.cell), gate_origin.port.c_str(), + gate_origin.offset, log_signal(gate_node)); } vector input_nodes(lut_edges_bw[node].begin(), lut_edges_bw[node].end()); RTLIL::Const lut_table(State::Sx, max(1 << input_nodes.size(), 1 << minlut)); unsigned const mask = 1 << input_nodes.size(); - for (unsigned i = 0; i < mask; i++) - { + for (unsigned i = 0; i < mask; i++) { ce.push(); for (size_t n = 0; n < input_nodes.size(); n++) ce.set(input_nodes[n], ((i >> n) & 1) ? State::S1 : State::S0); RTLIL::SigSpec value = node, undef; - if (!ce.eval(value, undef)) - { + if (!ce.eval(value, undef)) { string env; for (auto input_node : input_nodes) env += stringf(" %s = %s\n", log_signal(input_node), log_signal(ce.values_map(input_node))); - log_error("Cannot evaluate %s because %s is not defined.\nEvaluation environment:\n%s", - log_signal(node), log_signal(undef), env.c_str()); + log_error("Cannot evaluate %s because %s is not defined.\nEvaluation environment:\n%s", log_signal(node), + log_signal(undef), env.c_str()); } lut_table[i] = value.as_bool() ? State::S1 : State::S0; @@ -1411,8 +1260,7 @@ struct FlowmapWorker RTLIL::Cell *lut = module->addLut(NEW_ID, lut_a, lut_y, lut_table); mapped_nodes.insert(node); - for (auto gate_node : lut_gates[node]) - { + for (auto gate_node : lut_gates[node]) { auto gate_origin = node_origins[gate_node]; lut->add_strpool_attribute(ID::src, gate_origin.cell->get_strpool_attribute(ID::src)); packed_count++; @@ -1423,11 +1271,11 @@ struct FlowmapWorker if ((int)input_nodes.size() >= minlut) log(" Packed into a %d-LUT %s.%s.\n", GetSize(input_nodes), log_id(module), log_id(lut)); else - log(" Packed into a %d-LUT %s.%s (implemented as %d-LUT).\n", GetSize(input_nodes), log_id(module), log_id(lut), minlut); + log(" Packed into a %d-LUT %s.%s (implemented as %d-LUT).\n", GetSize(input_nodes), log_id(module), log_id(lut), + minlut); } - for (auto node : mapped_nodes) - { + for (auto node : mapped_nodes) { auto origin = node_origins[node]; RTLIL::SigSpec driver = origin.cell->getPort(origin.port); driver[origin.offset] = module->addWire(NEW_ID); @@ -1435,19 +1283,17 @@ struct FlowmapWorker } } - FlowmapWorker(int order, int minlut, pool cell_types, int r_alpha, int r_beta, int r_gamma, - bool relax, int optarea, bool debug, bool debug_relax, - RTLIL::Module *module) : - order(order), r_alpha(r_alpha), r_beta(r_beta), r_gamma(r_gamma), debug(debug), debug_relax(debug_relax), - module(module), sigmap(module), index(module) + FlowmapWorker(int order, int minlut, pool cell_types, int r_alpha, int r_beta, int r_gamma, bool relax, int optarea, bool debug, + bool debug_relax, RTLIL::Module *module) + : order(order), r_alpha(r_alpha), r_beta(r_beta), r_gamma(r_gamma), debug(debug), debug_relax(debug_relax), module(module), + sigmap(module), index(module) { log("Labeling cells.\n"); discover_nodes(cell_types); label_nodes(); int depth = map_luts(); - if (relax) - { + if (relax) { log("\n"); log("Optimizing area.\n"); optimize_area(depth, optarea); @@ -1470,7 +1316,7 @@ static void split(std::vector &tokens, const std::string &text, cha } struct FlowmapPass : public Pass { - FlowmapPass() : Pass("flowmap", "pack LUTs with FlowMap") { } + FlowmapPass() : Pass("flowmap", "pack LUTs with FlowMap") {} void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| @@ -1523,56 +1369,45 @@ struct FlowmapPass : public Pass { bool debug = false, debug_relax = false; size_t argidx; - for (argidx = 1; argidx < args.size(); argidx++) - { - if (args[argidx] == "-maxlut" && argidx + 1 < args.size()) - { + for (argidx = 1; argidx < args.size(); argidx++) { + if (args[argidx] == "-maxlut" && argidx + 1 < args.size()) { order = atoi(args[++argidx].c_str()); continue; } - if (args[argidx] == "-minlut" && argidx + 1 < args.size()) - { + if (args[argidx] == "-minlut" && argidx + 1 < args.size()) { minlut = atoi(args[++argidx].c_str()); continue; } - if (args[argidx] == "-cells" && argidx + 1 < args.size()) - { + if (args[argidx] == "-cells" && argidx + 1 < args.size()) { split(cells, args[++argidx], ','); continue; } - if (args[argidx] == "-relax") - { + if (args[argidx] == "-relax") { relax = true; continue; } - if (args[argidx] == "-r-alpha" && argidx + 1 < args.size()) - { + if (args[argidx] == "-r-alpha" && argidx + 1 < args.size()) { r_alpha = atoi(args[++argidx].c_str()); continue; } - if (args[argidx] == "-r-beta" && argidx + 1 < args.size()) - { + if (args[argidx] == "-r-beta" && argidx + 1 < args.size()) { r_beta = atoi(args[++argidx].c_str()); continue; } - if (args[argidx] == "-r-gamma" && argidx + 1 < args.size()) - { + if (args[argidx] == "-r-gamma" && argidx + 1 < args.size()) { r_gamma = atoi(args[++argidx].c_str()); continue; } - if (args[argidx] == "-optarea" && argidx + 1 < args.size()) - { + if (args[argidx] == "-optarea" && argidx + 1 < args.size()) { relax = true; optarea = atoi(args[++argidx].c_str()); continue; } - if (args[argidx] == "-debug") - { + if (args[argidx] == "-debug") { debug = true; continue; } - if (args[argidx] == "-debug-relax") - { + if (args[argidx] == "-debug-relax") { debug = debug_relax = true; continue; } @@ -1581,13 +1416,10 @@ struct FlowmapPass : public Pass { extra_args(args, argidx, design); pool cell_types; - if (!cells.empty()) - { + if (!cells.empty()) { for (auto &cell : cells) cell_types.insert(cell); - } - else - { + } else { cell_types = {ID($_NOT_), ID($_AND_), ID($_OR_), ID($_XOR_), ID($_MUX_)}; } @@ -1596,8 +1428,7 @@ struct FlowmapPass : public Pass { int gate_count = 0, lut_count = 0, packed_count = 0; int gate_area = 0, lut_area = 0; - for (auto module : design->selected_modules()) - { + for (auto module : design->selected_modules()) { FlowmapWorker worker(order, minlut, cell_types, r_alpha, r_beta, r_gamma, relax, optarea, debug, debug_relax, module); gate_count += worker.gate_count; lut_count += worker.lut_count; diff --git a/passes/techmap/hilomap.cc b/passes/techmap/hilomap.cc index c1b94722159..80918cb3431 100644 --- a/passes/techmap/hilomap.cc +++ b/passes/techmap/hilomap.cc @@ -17,9 +17,9 @@ * */ +#include "kernel/log.h" #include "kernel/register.h" #include "kernel/rtlil.h" -#include "kernel/log.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN @@ -54,7 +54,7 @@ void hilomap_worker(RTLIL::SigSpec &sig) } struct HilomapPass : public Pass { - HilomapPass() : Pass("hilomap", "technology mapping of constant hi- and/or lo-drivers") { } + HilomapPass() : Pass("hilomap", "technology mapping of constant hi- and/or lo-drivers") {} void help() override { log("\n"); @@ -85,14 +85,13 @@ struct HilomapPass : public Pass { singleton_mode = false; size_t argidx; - for (argidx = 1; argidx < args.size(); argidx++) - { - if (args[argidx] == "-hicell" && argidx+2 < args.size()) { + for (argidx = 1; argidx < args.size(); argidx++) { + if (args[argidx] == "-hicell" && argidx + 2 < args.size()) { hicell_celltype = args[++argidx]; hicell_portname = args[++argidx]; continue; } - if (args[argidx] == "-locell" && argidx+2 < args.size()) { + if (args[argidx] == "-locell" && argidx + 2 < args.size()) { locell_celltype = args[++argidx]; locell_portname = args[++argidx]; continue; @@ -105,8 +104,7 @@ struct HilomapPass : public Pass { } extra_args(args, argidx, design); - for (auto mod : design->selected_modules()) - { + for (auto mod : design->selected_modules()) { module = mod; last_hi = RTLIL::State::Sm; last_lo = RTLIL::State::Sm; diff --git a/passes/techmap/insbuf.cc b/passes/techmap/insbuf.cc index f288987a116..6cda7c8fa55 100644 --- a/passes/techmap/insbuf.cc +++ b/passes/techmap/insbuf.cc @@ -17,14 +17,14 @@ * */ -#include "kernel/yosys.h" #include "kernel/sigtools.h" +#include "kernel/yosys.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct InsbufPass : public Pass { - InsbufPass() : Pass("insbuf", "insert buffer cells for connected wires") { } + InsbufPass() : Pass("insbuf", "insert buffer cells for connected wires") {} void help() override { log("\n"); @@ -48,10 +48,9 @@ struct InsbufPass : public Pass { bool chain_mode = false; size_t argidx; - for (argidx = 1; argidx < args.size(); argidx++) - { + for (argidx = 1; argidx < args.size(); argidx++) { std::string arg = args[argidx]; - if (arg == "-buf" && argidx+3 < args.size()) { + if (arg == "-buf" && argidx + 3 < args.size()) { celltype = RTLIL::escape_id(args[++argidx]); in_portname = RTLIL::escape_id(args[++argidx]); out_portname = RTLIL::escape_id(args[++argidx]); @@ -65,18 +64,15 @@ struct InsbufPass : public Pass { } extra_args(args, argidx, design); - for (auto module : design->selected_modules()) - { + for (auto module : design->selected_modules()) { std::vector new_connections; - pool bufcells; + pool bufcells; SigMap sigmap; - for (auto &conn : module->connections()) - { + for (auto &conn : module->connections()) { RTLIL::SigSig new_conn; - for (int i = 0; i < GetSize(conn.first); i++) - { + for (int i = 0; i < GetSize(conn.first); i++) { SigBit lhs = conn.first[i]; SigBit rhs = conn.second[i]; @@ -115,8 +111,8 @@ struct InsbufPass : public Pass { auto s = sigmap(port.second); if (s == port.second) continue; - log("Rewrite %s/%s/%s: %s -> %s\n", log_id(module), log_id(cell), - log_id(port.first), log_signal(port.second), log_signal(s)); + log("Rewrite %s/%s/%s: %s -> %s\n", log_id(module), log_id(cell), log_id(port.first), + log_signal(port.second), log_signal(s)); cell->setPort(port.first, s); } } diff --git a/passes/techmap/iopadmap.cc b/passes/techmap/iopadmap.cc index 322eb7779ac..14176a4d7c5 100644 --- a/passes/techmap/iopadmap.cc +++ b/passes/techmap/iopadmap.cc @@ -17,8 +17,8 @@ * */ -#include "kernel/yosys.h" #include "kernel/sigtools.h" +#include "kernel/yosys.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN @@ -27,13 +27,13 @@ void split_portname_pair(std::string &port1, std::string &port2) { size_t pos = port1.find_first_of(':'); if (pos != std::string::npos) { - port2 = port1.substr(pos+1); + port2 = port1.substr(pos + 1); port1 = port1.substr(0, pos); } } struct IopadmapPass : public Pass { - IopadmapPass() : Pass("iopadmap", "technology mapping of i/o pads (or buffers)") { } + IopadmapPass() : Pass("iopadmap", "technology mapping of i/o pads (or buffers)") {} void help() override { log("\n"); @@ -86,7 +86,8 @@ struct IopadmapPass : public Pass { log("\n"); } - void module_queue(Design *design, Module *module, std::vector &modules_sorted, pool &modules_processed) { + void module_queue(Design *design, Module *module, std::vector &modules_sorted, pool &modules_processed) + { if (modules_processed.count(module)) return; for (auto cell : module->cells()) { @@ -114,28 +115,27 @@ struct IopadmapPass : public Pass { bool flag_bits = false; size_t argidx; - for (argidx = 1; argidx < args.size(); argidx++) - { + for (argidx = 1; argidx < args.size(); argidx++) { std::string arg = args[argidx]; - if (arg == "-inpad" && argidx+2 < args.size()) { + if (arg == "-inpad" && argidx + 2 < args.size()) { inpad_celltype = args[++argidx]; inpad_portname_o = args[++argidx]; split_portname_pair(inpad_portname_o, inpad_portname_pad); continue; } - if (arg == "-outpad" && argidx+2 < args.size()) { + if (arg == "-outpad" && argidx + 2 < args.size()) { outpad_celltype = args[++argidx]; outpad_portname_i = args[++argidx]; split_portname_pair(outpad_portname_i, outpad_portname_pad); continue; } - if (arg == "-inoutpad" && argidx+2 < args.size()) { + if (arg == "-inoutpad" && argidx + 2 < args.size()) { inoutpad_celltype = args[++argidx]; inoutpad_portname_io = args[++argidx]; split_portname_pair(inoutpad_portname_io, inoutpad_portname_pad); continue; } - if (arg == "-toutpad" && argidx+2 < args.size()) { + if (arg == "-toutpad" && argidx + 2 < args.size()) { toutpad_celltype = args[++argidx]; toutpad_portname_oe = args[++argidx]; split_portname_pair(toutpad_portname_oe, toutpad_portname_i); @@ -146,7 +146,7 @@ struct IopadmapPass : public Pass { } continue; } - if (arg == "-tinoutpad" && argidx+2 < args.size()) { + if (arg == "-tinoutpad" && argidx + 2 < args.size()) { tinoutpad_celltype = args[++argidx]; tinoutpad_portname_oe = args[++argidx]; split_portname_pair(tinoutpad_portname_oe, tinoutpad_portname_o); @@ -158,7 +158,7 @@ struct IopadmapPass : public Pass { } continue; } - if (arg == "-ignore" && argidx+2 < args.size()) { + if (arg == "-ignore" && argidx + 2 < args.size()) { std::string ignore_celltype = args[++argidx]; std::string ignore_portname = args[++argidx]; std::string ignore_portname2; @@ -170,11 +170,11 @@ struct IopadmapPass : public Pass { } continue; } - if (arg == "-widthparam" && argidx+1 < args.size()) { + if (arg == "-widthparam" && argidx + 1 < args.size()) { widthparam = args[++argidx]; continue; } - if (arg == "-nameparam" && argidx+1 < args.size()) { + if (arg == "-nameparam" && argidx + 1 < args.size()) { nameparam = args[++argidx]; continue; } @@ -207,8 +207,7 @@ struct IopadmapPass : public Pass { for (auto module : design->selected_modules()) module_queue(design, module, modules_sorted, modules_processed); - for (auto module : modules_sorted) - { + for (auto module : modules_sorted) { pool buf_bits; SigMap sigmap(module); @@ -220,10 +219,10 @@ struct IopadmapPass : public Pass { // Collect SigBits connected to already-buffered ports. for (auto cell : module->cells()) - for (auto port : cell->connections()) - for (int i = 0; i < port.second.size(); i++) - if (buf_ports.count(make_pair(cell->type, make_pair(port.first, i)))) - buf_bits.insert(sigmap(port.second[i])); + for (auto port : cell->connections()) + for (int i = 0; i < port.second.size(); i++) + if (buf_ports.count(make_pair(cell->type, make_pair(port.first, i)))) + buf_bits.insert(sigmap(port.second[i])); // Now fill buf_ports. for (auto wire : module->wires()) @@ -237,13 +236,11 @@ struct IopadmapPass : public Pass { // Now do the actual buffer insertion. - for (auto module : design->selected_modules()) - { + for (auto module : design->selected_modules()) { dict>> rewrite_bits; dict> remove_conns; - if (!toutpad_celltype.empty() || !tinoutpad_celltype.empty()) - { + if (!toutpad_celltype.empty() || !tinoutpad_celltype.empty()) { dict tbuf_bits; pool driven_bits; dict> z_conns; @@ -272,8 +269,7 @@ struct IopadmapPass : public Pass { driven_bits.insert(dstbit); } - for (auto wire : module->selected_wires()) - { + for (auto wire : module->selected_wires()) { if (!wire->port_output) continue; @@ -285,8 +281,7 @@ struct IopadmapPass : public Pass { if (!wire->port_input && toutpad_celltype.empty()) continue; - for (int i = 0; i < GetSize(wire); i++) - { + for (int i = 0; i < GetSize(wire); i++) { SigBit wire_bit(wire, i); Cell *tbuf_cell = nullptr; @@ -322,13 +317,13 @@ struct IopadmapPass : public Pass { remove_conns[it->second.first].insert(it->second.second); } - if (wire->port_input) - { - log("Mapping port %s.%s[%d] using %s.\n", log_id(module), log_id(wire), i, tinoutpad_celltype.c_str()); + if (wire->port_input) { + log("Mapping port %s.%s[%d] using %s.\n", log_id(module), log_id(wire), i, + tinoutpad_celltype.c_str()); Cell *cell = module->addCell( - module->uniquify(stringf("$iopadmap$%s.%s[%d]", log_id(module), log_id(wire), i)), - RTLIL::escape_id(tinoutpad_celltype)); + module->uniquify(stringf("$iopadmap$%s.%s[%d]", log_id(module), log_id(wire), i)), + RTLIL::escape_id(tinoutpad_celltype)); if (tinoutpad_neg_oe) en_sig = module->NotGate(NEW_ID, en_sig); @@ -348,11 +343,12 @@ struct IopadmapPass : public Pass { if (!tinoutpad_portname_pad.empty()) rewrite_bits[wire][i] = make_pair(cell, RTLIL::escape_id(tinoutpad_portname_pad)); } else { - log("Mapping port %s.%s[%d] using %s.\n", log_id(module), log_id(wire), i, toutpad_celltype.c_str()); + log("Mapping port %s.%s[%d] using %s.\n", log_id(module), log_id(wire), i, + toutpad_celltype.c_str()); Cell *cell = module->addCell( - module->uniquify(stringf("$iopadmap$%s.%s[%d]", log_id(module), log_id(wire), i)), - RTLIL::escape_id(toutpad_celltype)); + module->uniquify(stringf("$iopadmap$%s.%s[%d]", log_id(module), log_id(wire), i)), + RTLIL::escape_id(toutpad_celltype)); if (toutpad_neg_oe) en_sig = module->NotGate(NEW_ID, en_sig); @@ -372,8 +368,7 @@ struct IopadmapPass : public Pass { } } - for (auto wire : module->selected_wires()) - { + for (auto wire : module->selected_wires()) { if (!wire->port_id) continue; @@ -389,25 +384,26 @@ struct IopadmapPass : public Pass { if (wire->port_input && !wire->port_output) { if (inpad_celltype.empty()) { - log("Don't map input port %s.%s: Missing option -inpad.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(wire->name)); + log("Don't map input port %s.%s: Missing option -inpad.\n", RTLIL::id2cstr(module->name), + RTLIL::id2cstr(wire->name)); continue; } celltype = inpad_celltype; portname_int = inpad_portname_o; portname_pad = inpad_portname_pad; - } else - if (!wire->port_input && wire->port_output) { + } else if (!wire->port_input && wire->port_output) { if (outpad_celltype.empty()) { - log("Don't map output port %s.%s: Missing option -outpad.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(wire->name)); + log("Don't map output port %s.%s: Missing option -outpad.\n", RTLIL::id2cstr(module->name), + RTLIL::id2cstr(wire->name)); continue; } celltype = outpad_celltype; portname_int = outpad_portname_i; portname_pad = outpad_portname_pad; - } else - if (wire->port_input && wire->port_output) { + } else if (wire->port_input && wire->port_output) { if (inoutpad_celltype.empty()) { - log("Don't map inout port %s.%s: Missing option -inoutpad.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(wire->name)); + log("Don't map inout port %s.%s: Missing option -inoutpad.\n", RTLIL::id2cstr(module->name), + RTLIL::id2cstr(wire->name)); continue; } celltype = inoutpad_celltype; @@ -417,24 +413,23 @@ struct IopadmapPass : public Pass { log_abort(); if (!flag_bits && wire->width != 1 && widthparam.empty()) { - log("Don't map multi-bit port %s.%s: Missing option -widthparam or -bits.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(wire->name)); + log("Don't map multi-bit port %s.%s: Missing option -widthparam or -bits.\n", RTLIL::id2cstr(module->name), + RTLIL::id2cstr(wire->name)); continue; } log("Mapping port %s.%s using %s.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(wire->name), celltype.c_str()); - if (flag_bits) - { - for (int i = 0; i < wire->width; i++) - { + if (flag_bits) { + for (int i = 0; i < wire->width; i++) { if (skip_bit_indices.count(i)) continue; SigBit wire_bit(wire, i); RTLIL::Cell *cell = module->addCell( - module->uniquify(stringf("$iopadmap$%s.%s", log_id(module->name), log_id(wire->name))), - RTLIL::escape_id(celltype)); + module->uniquify(stringf("$iopadmap$%s.%s", log_id(module->name), log_id(wire->name))), + RTLIL::escape_id(celltype)); cell->setPort(RTLIL::escape_id(portname_int), wire_bit); if (!portname_pad.empty()) @@ -442,22 +437,19 @@ struct IopadmapPass : public Pass { if (!widthparam.empty()) cell->parameters[RTLIL::escape_id(widthparam)] = RTLIL::Const(1); if (!nameparam.empty()) - cell->parameters[RTLIL::escape_id(nameparam)] = RTLIL::Const(stringf("%s[%d]", RTLIL::id2cstr(wire->name), i)); + cell->parameters[RTLIL::escape_id(nameparam)] = + RTLIL::Const(stringf("%s[%d]", RTLIL::id2cstr(wire->name), i)); cell->attributes[ID::keep] = RTLIL::Const(1); } - } - else - { - RTLIL::Cell *cell = module->addCell( - module->uniquify(stringf("$iopadmap$%s.%s", log_id(module->name), log_id(wire->name))), - RTLIL::escape_id(celltype)); + } else { + RTLIL::Cell *cell = + module->addCell(module->uniquify(stringf("$iopadmap$%s.%s", log_id(module->name), log_id(wire->name))), + RTLIL::escape_id(celltype)); cell->setPort(RTLIL::escape_id(portname_int), RTLIL::SigSpec(wire)); if (!portname_pad.empty()) { RTLIL::Wire *new_wire = NULL; - new_wire = module->addWire( - module->uniquify(stringf("$iopadmap$%s", log_id(wire))), - wire); + new_wire = module->addWire(module->uniquify(stringf("$iopadmap$%s", log_id(wire))), wire); module->swap_names(new_wire, wire); wire->attributes.clear(); cell->setPort(RTLIL::escape_id(portname_pad), RTLIL::SigSpec(new_wire)); @@ -491,7 +483,6 @@ struct IopadmapPass : public Pass { } } new_conns.push_back(SigSig(lhs, rhs)); - } } module->new_connections(new_conns); @@ -499,13 +490,10 @@ struct IopadmapPass : public Pass { for (auto &it : rewrite_bits) { RTLIL::Wire *wire = it.first; - RTLIL::Wire *new_wire = module->addWire( - module->uniquify(stringf("$iopadmap$%s", log_id(wire))), - wire); + RTLIL::Wire *new_wire = module->addWire(module->uniquify(stringf("$iopadmap$%s", log_id(wire))), wire); module->swap_names(new_wire, wire); wire->attributes.clear(); - for (int i = 0; i < wire->width; i++) - { + for (int i = 0; i < wire->width; i++) { SigBit wire_bit(wire, i); if (!it.second.count(i)) { if (wire->port_output) diff --git a/passes/techmap/libparse.cc b/passes/techmap/libparse.cc index efe00c105e4..d78a8157ca4 100644 --- a/passes/techmap/libparse.cc +++ b/passes/techmap/libparse.cc @@ -21,9 +21,9 @@ #include #include -#include #include #include +#include #include #ifndef FILTERLIB @@ -97,7 +97,8 @@ int LibertyParser::lexer(std::string &str) str = static_cast(c); while (1) { c = f.get(); - if (('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9') || c == '_' || c == '-' || c == '+' || c == '.') + if (('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9') || c == '_' || c == '-' || c == '+' || + c == '.') str += c; else break; @@ -107,8 +108,7 @@ int LibertyParser::lexer(std::string &str) /* Single operator is not an identifier */ // fprintf(stderr, "LEX: char >>%s<<\n", str.c_str()); return str[0]; - } - else { + } else { // fprintf(stderr, "LEX: identifier >>%s<<\n", str.c_str()); return 'v'; } @@ -133,7 +133,7 @@ int LibertyParser::lexer(std::string &str) // if it wasn't a string, perhaps it's a comment or a forward slash? if (c == '/') { c = f.get(); - if (c == '*') { // start of '/*' block comment + if (c == '*') { // start of '/*' block comment int last_c = 0; while (c > 0 && (last_c != '*' || c != '/')) { last_c = c; @@ -142,7 +142,7 @@ int LibertyParser::lexer(std::string &str) line++; } return lexer(str); - } else if (c == '/') { // start of '//' line comment + } else if (c == '/') { // start of '//' line comment while (c > 0 && c != '\n') c = f.get(); line++; @@ -150,12 +150,12 @@ int LibertyParser::lexer(std::string &str) } f.unget(); // fprintf(stderr, "LEX: char >>/<<\n"); - return '/'; // a single '/' charater. + return '/'; // a single '/' charater. } // check for a backslash if (c == '\\') { - c = f.get(); + c = f.get(); if (c == '\r') c = f.get(); if (c == '\n') { @@ -201,8 +201,7 @@ LibertyAst *LibertyParser::parse() if (tok != 'v') { std::string eReport; - switch(tok) - { + switch (tok) { case 'n': error("Unexpected newline."); break; @@ -225,11 +224,10 @@ LibertyAst *LibertyParser::parse() LibertyAst *ast = new LibertyAst; ast->id = str; - while (1) - { + while (1) { tok = lexer(str); - // allow both ';' and new lines to + // allow both ';' and new lines to // terminate a statement. if ((tok == ';') || (tok == 'n')) break; @@ -237,7 +235,7 @@ LibertyAst *LibertyParser::parse() if (tok == ':' && ast->value.empty()) { tok = lexer(ast->value); if (tok == 'v') { - tok = lexer(str); + tok = lexer(str); } while (tok == '+' || tok == '-' || tok == '*' || tok == '/' || tok == '!') { ast->value += tok; @@ -247,7 +245,7 @@ LibertyAst *LibertyParser::parse() ast->value += str; tok = lexer(str); } - + // In a liberty file, all key : value pairs should end in ';' // However, there are some liberty files in the wild that // just have a newline. We'll be kind and accept a newline @@ -267,54 +265,44 @@ LibertyAst *LibertyParser::parse() continue; if (tok == ')') break; - + // FIXME: the AST needs to be extended to store // these vector ranges. - if (tok == '[') - { + if (tok == '[') { // parse vector range [A] or [A:B] std::string arg; tok = lexer(arg); - if (tok != 'v') - { + if (tok != 'v') { // expected a vector array index error("Expected a number."); - } - else - { + } else { // fixme: check for number A } tok = lexer(arg); // optionally check for : in case of [A:B] // if it isn't we just expect ']' // as we have [A] - if (tok == ':') - { + if (tok == ':') { tok = lexer(arg); - if (tok != 'v') - { + if (tok != 'v') { // expected a vector array index error("Expected a number."); - } - else - { + } else { // fixme: check for number B - tok = lexer(arg); + tok = lexer(arg); } } // expect a closing bracket of array range - if (tok != ']') - { + if (tok != ']') { error("Expected ']' on array range."); } - continue; + continue; } if (tok != 'v') { std::string eReport; - switch(tok) - { + switch (tok) { case 'n': - continue; + continue; case '[': case ']': case '}': @@ -353,10 +341,7 @@ LibertyAst *LibertyParser::parse() #ifndef FILTERLIB -void LibertyParser::error() -{ - log_error("Syntax error in liberty file on line %d.\n", line); -} +void LibertyParser::error() { log_error("Syntax error in liberty file on line %d.\n", line); } void LibertyParser::error(const std::string &str) { @@ -385,24 +370,22 @@ void LibertyParser::error(const std::string &str) /**** BEGIN: http://svn.clairexen.net/tools/trunk/examples/check.h ****/ -#define CHECK_NV(result, check) \ - do { \ - auto _R = (result); \ - if (!(_R check)) { \ - fprintf(stderr, "Error from '%s' (%ld %s) in %s:%d.\n", \ - #result, (long int)_R, #check, __FILE__, __LINE__); \ - abort(); \ - } \ - } while(0) - -#define CHECK_COND(result) \ - do { \ - if (!(result)) { \ - fprintf(stderr, "Error from '%s' in %s:%d.\n", \ - #result, __FILE__, __LINE__); \ - abort(); \ - } \ - } while(0) +#define CHECK_NV(result, check) \ + do { \ + auto _R = (result); \ + if (!(_R check)) { \ + fprintf(stderr, "Error from '%s' (%ld %s) in %s:%d.\n", #result, (long int)_R, #check, __FILE__, __LINE__); \ + abort(); \ + } \ + } while (0) + +#define CHECK_COND(result) \ + do { \ + if (!(result)) { \ + fprintf(stderr, "Error from '%s' in %s:%d.\n", #result, __FILE__, __LINE__); \ + abort(); \ + } \ + } while (0) /**** END: http://svn.clairexen.net/tools/trunk/examples/check.h ****/ @@ -417,8 +400,8 @@ LibertyAst *find_non_null(LibertyAst *node, const char *name) std::string func2vl(std::string str) { for (size_t pos = str.find_first_of("\" \t"); pos != std::string::npos; pos = str.find_first_of("\" \t")) { - char c_left = pos > 0 ? str[pos-1] : ' '; - char c_right = pos+1 < str.size() ? str[pos+1] : ' '; + char c_left = pos > 0 ? str[pos - 1] : ' '; + char c_right = pos + 1 < str.size() ? str[pos + 1] : ' '; if (std::string("\" \t*+").find(c_left) != std::string::npos) str.erase(pos, 1); else if (std::string("\" \t*+").find(c_right) != std::string::npos) @@ -432,19 +415,19 @@ std::string func2vl(std::string str) if (str[pos] == '(') group_start.push_back(pos); if (str[pos] == ')' && group_start.size() > 0) { - if (pos+1 < str.size() && str[pos+1] == '\'') { - std::string group = str.substr(group_start.back(), pos-group_start.back()+1); + if (pos + 1 < str.size() && str[pos + 1] == '\'') { + std::string group = str.substr(group_start.back(), pos - group_start.back() + 1); str[group_start.back()] = '~'; - str.replace(group_start.back()+1, group.size(), group); + str.replace(group_start.back() + 1, group.size(), group); pos++; } group_start.pop_back(); } if (str[pos] == '\'' && pos > 0) { - size_t start = str.find_last_of("()'*+^&| ", pos-1)+1; - std::string group = str.substr(start, pos-start); + size_t start = str.find_last_of("()'*+^&| ", pos - 1) + 1; + std::string group = str.substr(start, pos - start); str[start] = '~'; - str.replace(start+1, group.size(), group); + str.replace(start + 1, group.size(), group); } if (str[pos] == '*') str[pos] = '&'; @@ -529,8 +512,7 @@ void gen_verilogsim_cell(LibertyAst *ast) printf(" assign %s = %s; // %s\n", child->args[0].c_str(), func2vl(func->value).c_str(), func->value.c_str()); } - for (auto child : ast->children) - { + for (auto child : ast->children) { if (child->id != "ff" || child->args.size() != 2) continue; @@ -593,8 +575,7 @@ void gen_verilogsim_cell(LibertyAst *ast) printf(" end\n"); } - for (auto child : ast->children) - { + for (auto child : ast->children) { if (child->id != "latch" || child->args.size() != 2) continue; @@ -672,12 +653,10 @@ int main(int argc, char **argv) if (argc > 3) usage(); - if (argc > 1) - { + if (argc > 1) { if (!strcmp(argv[1], "-verilogsim")) flag_verilogsim = true; - if (!strcmp(argv[1], "-") || !strcmp(argv[1], "-verilogsim")) - { + if (!strcmp(argv[1], "-") || !strcmp(argv[1], "-verilogsim")) { LibertyAst::whitelist.insert("/library"); LibertyAst::whitelist.insert("/library/cell"); LibertyAst::whitelist.insert("/library/cell/area"); @@ -698,9 +677,7 @@ int main(int argc, char **argv) LibertyAst::whitelist.insert("/library/cell/pin/three_state"); LibertyAst::whitelist.insert("/library/cell/statetable"); LibertyAst::whitelist.insert("/library/cell/statetable/*"); - } - else - { + } else { FILE *f = fopen(argv[1], "r"); if (f == NULL) { fprintf(stderr, "Can't open rules file `%s'.\n", argv[1]); @@ -708,12 +685,10 @@ int main(int argc, char **argv) } char buffer[1024]; - while (fgets(buffer, 1024, f) != NULL) - { + while (fgets(buffer, 1024, f) != NULL) { char mode = 0; std::string id; - for (char *p = buffer; *p; p++) - { + for (char *p = buffer; *p; p++) { if (*p == '-' || *p == '+') { if (mode != 0) goto syntax_error; @@ -724,8 +699,7 @@ int main(int argc, char **argv) if (!id.empty()) { if (mode == '-') LibertyAst::blacklist.insert(id); - else - if (mode == '+') + else if (mode == '+') LibertyAst::whitelist.insert(id); else goto syntax_error; @@ -774,4 +748,3 @@ int main(int argc, char **argv) } #endif - diff --git a/passes/techmap/libparse.h b/passes/techmap/libparse.h index 77e305f0b87..f6725ffb609 100644 --- a/passes/techmap/libparse.h +++ b/passes/techmap/libparse.h @@ -20,45 +20,46 @@ #ifndef LIBPARSE_H #define LIBPARSE_H +#include #include #include #include -#include namespace Yosys { - struct LibertyAst - { - std::string id, value; - std::vector args; - std::vector children; - ~LibertyAst(); - LibertyAst *find(std::string name); - void dump(FILE *f, std::string indent = "", std::string path = "", bool path_ok = false); - static std::set blacklist; - static std::set whitelist; - }; +struct LibertyAst { + std::string id, value; + std::vector args; + std::vector children; + ~LibertyAst(); + LibertyAst *find(std::string name); + void dump(FILE *f, std::string indent = "", std::string path = "", bool path_ok = false); + static std::set blacklist; + static std::set whitelist; +}; - struct LibertyParser +struct LibertyParser { + std::istream &f; + int line; + LibertyAst *ast; + LibertyParser(std::istream &f) : f(f), line(1), ast(parse()) {} + ~LibertyParser() { - std::istream &f; - int line; - LibertyAst *ast; - LibertyParser(std::istream &f) : f(f), line(1), ast(parse()) {} - ~LibertyParser() { if (ast) delete ast; } - - /* lexer return values: - 'v': identifier, string, array range [...] -> str holds the token string - 'n': newline - anything else is a single character. - */ - int lexer(std::string &str); - - LibertyAst *parse(); - void error(); - void error(const std::string &str); - }; -} + if (ast) + delete ast; + } -#endif + /* lexer return values: + 'v': identifier, string, array range [...] -> str holds the token string + 'n': newline + anything else is a single character. + */ + int lexer(std::string &str); + + LibertyAst *parse(); + void error(); + void error(const std::string &str); +}; +} // namespace Yosys +#endif diff --git a/passes/techmap/lut2mux.cc b/passes/techmap/lut2mux.cc index ef76e0deb5d..a17b032b676 100644 --- a/passes/techmap/lut2mux.cc +++ b/passes/techmap/lut2mux.cc @@ -17,8 +17,8 @@ * */ -#include "kernel/yosys.h" #include "kernel/sigtools.h" +#include "kernel/yosys.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN @@ -30,19 +30,16 @@ int lut2mux(Cell *cell) Const lut = cell->getParam(ID::LUT); int count = 1; - if (GetSize(sig_a) == 1) - { + if (GetSize(sig_a) == 1) { cell->module->addMuxGate(NEW_ID, lut.extract(0)[0], lut.extract(1)[0], sig_a, sig_y); - } - else - { - SigSpec sig_a_hi = sig_a[GetSize(sig_a)-1]; - SigSpec sig_a_lo = sig_a.extract(0, GetSize(sig_a)-1); + } else { + SigSpec sig_a_hi = sig_a[GetSize(sig_a) - 1]; + SigSpec sig_a_lo = sig_a.extract(0, GetSize(sig_a) - 1); SigSpec sig_y1 = cell->module->addWire(NEW_ID); SigSpec sig_y2 = cell->module->addWire(NEW_ID); - Const lut1 = lut.extract(0, GetSize(lut)/2); - Const lut2 = lut.extract(GetSize(lut)/2, GetSize(lut)/2); + Const lut1 = lut.extract(0, GetSize(lut) / 2); + Const lut2 = lut.extract(GetSize(lut) / 2, GetSize(lut) / 2); count += lut2mux(cell->module->addLut(NEW_ID, sig_a_lo, sig_y1, lut1)); count += lut2mux(cell->module->addLut(NEW_ID, sig_a_lo, sig_y2, lut2)); @@ -55,7 +52,7 @@ int lut2mux(Cell *cell) } struct Lut2muxPass : public Pass { - Lut2muxPass() : Pass("lut2mux", "convert $lut to $_MUX_") { } + Lut2muxPass() : Pass("lut2mux", "convert $lut to $_MUX_") {} void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| @@ -70,8 +67,7 @@ struct Lut2muxPass : public Pass { log_header(design, "Executing LUT2MUX pass (convert $lut to $_MUX_).\n"); size_t argidx; - for (argidx = 1; argidx < args.size(); argidx++) - { + for (argidx = 1; argidx < args.size(); argidx++) { // if (args[argidx] == "-v") { // continue; // } @@ -80,13 +76,13 @@ struct Lut2muxPass : public Pass { extra_args(args, argidx, design); for (auto module : design->selected_modules()) - for (auto cell : module->selected_cells()) { - if (cell->type == ID($lut)) { - IdString cell_name = cell->name; - int count = lut2mux(cell); - log("Converted %s.%s to %d MUX cells.\n", log_id(module), log_id(cell_name), count); + for (auto cell : module->selected_cells()) { + if (cell->type == ID($lut)) { + IdString cell_name = cell->name; + int count = lut2mux(cell); + log("Converted %s.%s to %d MUX cells.\n", log_id(module), log_id(cell_name), count); + } } - } } } Lut2muxPass; diff --git a/passes/techmap/maccmap.cc b/passes/techmap/maccmap.cc index 2235bdef9fa..1a8ad72b017 100644 --- a/passes/techmap/maccmap.cc +++ b/passes/techmap/maccmap.cc @@ -17,22 +17,18 @@ * */ -#include "kernel/yosys.h" #include "kernel/macc.h" +#include "kernel/yosys.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN -struct MaccmapWorker -{ +struct MaccmapWorker { std::vector> bits; RTLIL::Module *module; int width; - MaccmapWorker(RTLIL::Module *module, int width) : module(module), width(width) - { - bits.resize(width); - } + MaccmapWorker(RTLIL::Module *module, int width) : module(module), width(width) { bits.resize(width); } void add(RTLIL::SigBit bit, int position) { @@ -41,7 +37,7 @@ struct MaccmapWorker if (bits.at(position).count(bit)) { bits.at(position).erase(bit); - add(bit, position+1); + add(bit, position + 1); } else { bits.at(position).insert(bit); } @@ -71,16 +67,13 @@ struct MaccmapWorker b.extend_u0(width, is_signed); for (int i = 0; i < GetSize(b); i++) - if (is_signed && i+1 == GetSize(b)) - { - a = {module->Not(NEW_ID, a.extract(i, width-i)), RTLIL::SigSpec(0, i)}; + if (is_signed && i + 1 == GetSize(b)) { + a = {module->Not(NEW_ID, a.extract(i, width - i)), RTLIL::SigSpec(0, i)}; add(module->And(NEW_ID, a, RTLIL::SigSpec(b[i], width)), false, do_subtract); add({b[i], RTLIL::SigSpec(0, i)}, false, do_subtract); - } - else - { + } else { add(module->And(NEW_ID, a, RTLIL::SigSpec(b[i], width)), false, do_subtract); - a = {a.extract(0, width-1), State::S0}; + a = {a.extract(0, width - 1), State::S0}; } } @@ -91,21 +84,19 @@ struct MaccmapWorker while (start_index < stop_index && in1[start_index] == State::S0 && in2[start_index] == RTLIL::S0 && in3[start_index] == RTLIL::S0) start_index++; - while (start_index < stop_index && in1[stop_index-1] == State::S0 && in2[stop_index-1] == RTLIL::S0 && in3[stop_index-1] == RTLIL::S0) + while (start_index < stop_index && in1[stop_index - 1] == State::S0 && in2[stop_index - 1] == RTLIL::S0 && + in3[stop_index - 1] == RTLIL::S0) stop_index--; - if (start_index == stop_index) - { + if (start_index == stop_index) { out1 = RTLIL::SigSpec(0, GetSize(in1)); out2 = RTLIL::SigSpec(0, GetSize(in1)); - } - else - { - RTLIL::SigSpec out_zeros_lsb(0, start_index), out_zeros_msb(0, GetSize(in1)-stop_index); + } else { + RTLIL::SigSpec out_zeros_lsb(0, start_index), out_zeros_msb(0, GetSize(in1) - stop_index); - in1 = in1.extract(start_index, stop_index-start_index); - in2 = in2.extract(start_index, stop_index-start_index); - in3 = in3.extract(start_index, stop_index-start_index); + in1 = in1.extract(start_index, stop_index - start_index); + in2 = in2.extract(start_index, stop_index - start_index); + in3 = in3.extract(start_index, stop_index - start_index); int width = GetSize(in1); RTLIL::Wire *w1 = module->addWire(NEW_ID, width); @@ -126,16 +117,16 @@ struct MaccmapWorker int tree_bit_slots(int n) { - #if 0 +#if 0 int retval = 1; while (n > 2) { retval += n / 3; n = 2*(n / 3) + (n % 3); } return retval; - #else +#else return max(n - 1, 0); - #endif +#endif } RTLIL::SigSpec synth() @@ -145,8 +136,7 @@ struct MaccmapWorker int unique_tree_bits = 0; int count_tree_words = 0; - while (1) - { + while (1) { RTLIL::SigSpec summand(0, width); bool got_data_bits = false; @@ -163,8 +153,7 @@ struct MaccmapWorker summands.push_back(summand); - while (1) - { + while (1) { int free_bit_slots = tree_bit_slots(GetSize(summands)) - GetSize(tree_sum_bits); int max_depth = 0, max_position = 0; @@ -212,14 +201,13 @@ struct MaccmapWorker return summands.front(); } - while (GetSize(summands) > 2) - { + while (GetSize(summands) > 2) { std::vector new_summands; for (int i = 0; i < GetSize(summands); i += 3) - if (i+2 < GetSize(summands)) { + if (i + 2 < GetSize(summands)) { RTLIL::SigSpec in1 = summands[i]; - RTLIL::SigSpec in2 = summands[i+1]; - RTLIL::SigSpec in3 = summands[i+2]; + RTLIL::SigSpec in2 = summands[i + 1]; + RTLIL::SigSpec in3 = summands[i + 2]; RTLIL::SigSpec out1, out2; fulladd(in1, in2, in3, out1, out2); RTLIL::SigBit extra_bit = State::S0; @@ -228,7 +216,7 @@ struct MaccmapWorker tree_sum_bits.pop_back(); } new_summands.push_back(out1); - new_summands.push_back({out2.extract(0, width-1), extra_bit}); + new_summands.push_back({out2.extract(0, width - 1), extra_bit}); } else { new_summands.push_back(summands[i]); i -= 2; @@ -236,7 +224,6 @@ struct MaccmapWorker summands.swap(new_summands); } - RTLIL::Cell *c = module->addCell(NEW_ID, ID($alu)); c->setPort(ID::A, summands.front()); c->setPort(ID::B, summands.back()); @@ -280,17 +267,16 @@ void maccmap(RTLIL::Module *module, RTLIL::Cell *cell, bool unmap) for (auto &port : macc.ports) if (GetSize(port.in_b) == 0) - log(" %s %s (%d bits, %s)\n", port.do_subtract ? "sub" : "add", log_signal(port.in_a), - GetSize(port.in_a), port.is_signed ? "signed" : "unsigned"); + log(" %s %s (%d bits, %s)\n", port.do_subtract ? "sub" : "add", log_signal(port.in_a), GetSize(port.in_a), + port.is_signed ? "signed" : "unsigned"); else log(" %s %s * %s (%dx%d bits, %s)\n", port.do_subtract ? "sub" : "add", log_signal(port.in_a), log_signal(port.in_b), - GetSize(port.in_a), GetSize(port.in_b), port.is_signed ? "signed" : "unsigned"); + GetSize(port.in_a), GetSize(port.in_b), port.is_signed ? "signed" : "unsigned"); if (GetSize(macc.bit_ports) != 0) log(" add bits %s (%d bits)\n", log_signal(macc.bit_ports), GetSize(macc.bit_ports)); - if (unmap) - { + if (unmap) { typedef std::pair summand_t; std::vector summands; @@ -315,20 +301,19 @@ void maccmap(RTLIL::Module *module, RTLIL::Cell *cell, bool unmap) if (GetSize(summands) == 0) summands.push_back(summand_t(RTLIL::SigSpec(0, width), false)); - while (GetSize(summands) > 1) - { + while (GetSize(summands) > 1) { std::vector new_summands; for (int i = 0; i < GetSize(summands); i += 2) { - if (i+1 < GetSize(summands)) { + if (i + 1 < GetSize(summands)) { summand_t this_summand; this_summand.first = module->addWire(NEW_ID, width); - this_summand.second = summands[i].second && summands[i+1].second; - if (summands[i].second == summands[i+1].second) - module->addAdd(NEW_ID, summands[i].first, summands[i+1].first, this_summand.first); + this_summand.second = summands[i].second && summands[i + 1].second; + if (summands[i].second == summands[i + 1].second) + module->addAdd(NEW_ID, summands[i].first, summands[i + 1].first, this_summand.first); else if (summands[i].second) - module->addSub(NEW_ID, summands[i+1].first, summands[i].first, this_summand.first); - else if (summands[i+1].second) - module->addSub(NEW_ID, summands[i].first, summands[i+1].first, this_summand.first); + module->addSub(NEW_ID, summands[i + 1].first, summands[i].first, this_summand.first); + else if (summands[i + 1].second) + module->addSub(NEW_ID, summands[i].first, summands[i + 1].first, this_summand.first); else log_abort(); new_summands.push_back(this_summand); @@ -342,9 +327,7 @@ void maccmap(RTLIL::Module *module, RTLIL::Cell *cell, bool unmap) module->addNeg(NEW_ID, summands.front().first, cell->getPort(ID::Y)); else module->connect(cell->getPort(ID::Y), summands.front().first); - } - else - { + } else { MaccmapWorker worker(module, width); for (auto &port : macc.ports) @@ -364,7 +347,7 @@ YOSYS_NAMESPACE_END PRIVATE_NAMESPACE_BEGIN struct MaccmapPass : public Pass { - MaccmapPass() : Pass("maccmap", "mapping macc cells") { } + MaccmapPass() : Pass("maccmap", "mapping macc cells") {} void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| @@ -392,12 +375,12 @@ struct MaccmapPass : public Pass { extra_args(args, argidx, design); for (auto mod : design->selected_modules()) - for (auto cell : mod->selected_cells()) - if (cell->type == ID($macc)) { - log("Mapping %s.%s (%s).\n", log_id(mod), log_id(cell), log_id(cell->type)); - maccmap(mod, cell, unmap_mode); - mod->remove(cell); - } + for (auto cell : mod->selected_cells()) + if (cell->type == ID($macc)) { + log("Mapping %s.%s (%s).\n", log_id(mod), log_id(cell), log_id(cell->type)); + maccmap(mod, cell, unmap_mode); + mod->remove(cell); + } } } MaccmapPass; diff --git a/passes/techmap/muxcover.cc b/passes/techmap/muxcover.cc index 2656f30ce56..e852a9d702a 100644 --- a/passes/techmap/muxcover.cc +++ b/passes/techmap/muxcover.cc @@ -17,34 +17,31 @@ * */ -#include "kernel/yosys.h" #include "kernel/sigtools.h" +#include "kernel/yosys.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN -#define COST_DMUX 90 -#define COST_MUX2 100 -#define COST_MUX4 220 -#define COST_MUX8 460 +#define COST_DMUX 90 +#define COST_MUX2 100 +#define COST_MUX4 220 +#define COST_MUX8 460 #define COST_MUX16 940 -struct MuxcoverWorker -{ +struct MuxcoverWorker { Module *module; SigMap sigmap; - struct newmux_t - { + struct newmux_t { int cost; vector inputs, selects; newmux_t() : cost(0) {} }; - struct tree_t - { + struct tree_t { SigBit root; - dict muxes; + dict muxes; dict newmuxes; }; @@ -102,7 +99,7 @@ struct MuxcoverWorker { pool roots; pool used_once; - dict sig_to_mux; + dict sig_to_mux; for (auto wire : module->wires()) { if (!wire->port_output) @@ -128,8 +125,7 @@ struct MuxcoverWorker log(" Treeifying %d MUXes:\n", GetSize(sig_to_mux)); roots.sort(); - for (auto rootsig : roots) - { + for (auto rootsig : roots) { tree_t tree; tree.root = rootsig; @@ -170,7 +166,7 @@ struct MuxcoverWorker return true; } char port_name[3] = {'\\', *path, 0}; - return follow_muxtree(ret_bit, tree, sigmap(tree.muxes.at(bit)->getPort(port_name)), path+1, false); + return follow_muxtree(ret_bit, tree, sigmap(tree.muxes.at(bit)->getPort(port_name)), path + 1, false); } else { ret_bit = bit; return true; @@ -264,8 +260,7 @@ struct MuxcoverWorker ok = ok && follow_muxtree(S1, tree, bit, "S"); - if (ok) - { + if (ok) { newmux_t mux; mux.inputs.push_back(A); @@ -285,8 +280,7 @@ struct MuxcoverWorker // 4-Input MUX - if (use_mux4) - { + if (use_mux4) { ok = ok && follow_muxtree(A, tree, bit, "AA"); ok = ok && follow_muxtree(B, tree, bit, "AB"); ok = ok && follow_muxtree(C, tree, bit, "BA"); @@ -300,8 +294,7 @@ struct MuxcoverWorker ok = ok && follow_muxtree(T1, tree, bit, "S"); - if (ok) - { + if (ok) { newmux_t mux; mux.inputs.push_back(A); @@ -329,8 +322,7 @@ struct MuxcoverWorker // 8-Input MUX - if (use_mux8) - { + if (use_mux8) { ok = ok && follow_muxtree(A, tree, bit, "AAA"); ok = ok && follow_muxtree(B, tree, bit, "AAB"); ok = ok && follow_muxtree(C, tree, bit, "ABA"); @@ -356,8 +348,7 @@ struct MuxcoverWorker ok = ok && follow_muxtree(U1, tree, bit, "S"); - if (ok) - { + if (ok) { newmux_t mux; mux.inputs.push_back(A); @@ -394,8 +385,7 @@ struct MuxcoverWorker // 16-Input MUX - if (use_mux16) - { + if (use_mux16) { ok = ok && follow_muxtree(A, tree, bit, "AAAA"); ok = ok && follow_muxtree(B, tree, bit, "AAAB"); ok = ok && follow_muxtree(C, tree, bit, "AABA"); @@ -441,8 +431,7 @@ struct MuxcoverWorker ok = ok && follow_muxtree(V1, tree, bit, "S"); - if (ok) - { + if (ok) { newmux_t mux; mux.inputs.push_back(A); @@ -588,8 +577,8 @@ struct MuxcoverWorker log_debug(" Searching for best cover for tree at %s.\n", log_signal(tree.root)); find_best_cover(tree, tree.root); implement_best_cover(tree, tree.root, count_muxes_by_type); - log(" Replaced tree at %s: %d MUX2, %d MUX4, %d MUX8, %d MUX16\n", log_signal(tree.root), - count_muxes_by_type[0], count_muxes_by_type[1], count_muxes_by_type[2], count_muxes_by_type[3]); + log(" Replaced tree at %s: %d MUX2, %d MUX4, %d MUX8, %d MUX16\n", log_signal(tree.root), count_muxes_by_type[0], + count_muxes_by_type[1], count_muxes_by_type[2], count_muxes_by_type[3]); for (auto &it : tree.muxes) module->remove(it.second); } @@ -619,7 +608,7 @@ struct MuxcoverWorker }; struct MuxcoverPass : public Pass { - MuxcoverPass() : Pass("muxcover", "cover trees of MUX cells with wider MUXes") { } + MuxcoverPass() : Pass("muxcover", "cover trees of MUX cells with wider MUXes") {} void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| @@ -669,38 +658,40 @@ struct MuxcoverPass : public Pass { int cost_mux16 = COST_MUX16; size_t argidx; - for (argidx = 1; argidx < args.size(); argidx++) - { + for (argidx = 1; argidx < args.size(); argidx++) { const auto &arg = args[argidx]; - if (arg.size() >= 6 && arg.compare(0,6,"-mux2=") == 0) { + if (arg.size() >= 6 && arg.compare(0, 6, "-mux2=") == 0) { cost_mux2 = atoi(arg.substr(6).c_str()); continue; } - if (arg.size() >= 5 && arg.compare(0,5,"-mux4") == 0) { + if (arg.size() >= 5 && arg.compare(0, 5, "-mux4") == 0) { use_mux4 = true; if (arg.size() > 5) { - if (arg[5] != '=') break; + if (arg[5] != '=') + break; cost_mux4 = atoi(arg.substr(6).c_str()); } continue; } - if (arg.size() >= 5 && arg.compare(0,5,"-mux8") == 0) { + if (arg.size() >= 5 && arg.compare(0, 5, "-mux8") == 0) { use_mux8 = true; if (arg.size() > 5) { - if (arg[5] != '=') break; + if (arg[5] != '=') + break; cost_mux8 = atoi(arg.substr(6).c_str()); } continue; } - if (arg.size() >= 6 && arg.compare(0,6,"-mux16") == 0) { + if (arg.size() >= 6 && arg.compare(0, 6, "-mux16") == 0) { use_mux16 = true; if (arg.size() > 6) { - if (arg[6] != '=') break; + if (arg[6] != '=') + break; cost_mux16 = atoi(arg.substr(7).c_str()); } continue; } - if (arg.size() >= 6 && arg.compare(0,6,"-dmux=") == 0) { + if (arg.size() >= 6 && arg.compare(0, 6, "-dmux=") == 0) { cost_dmux = atoi(arg.substr(6).c_str()); continue; } @@ -722,8 +713,7 @@ struct MuxcoverPass : public Pass { use_mux16 = true; } - for (auto module : design->selected_modules()) - { + for (auto module : design->selected_modules()) { MuxcoverWorker worker(module); worker.use_mux4 = use_mux4; worker.use_mux8 = use_mux8; diff --git a/passes/techmap/nlutmap.cc b/passes/techmap/nlutmap.cc index 0167891571f..514b24a7326 100644 --- a/passes/techmap/nlutmap.cc +++ b/passes/techmap/nlutmap.cc @@ -17,28 +17,23 @@ * */ -#include "kernel/yosys.h" #include "kernel/sigtools.h" +#include "kernel/yosys.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN -struct NlutmapConfig -{ +struct NlutmapConfig { vector luts; bool assert_mode = false; }; -struct NlutmapWorker -{ +struct NlutmapWorker { const NlutmapConfig &config; - pool mapped_cells; + pool mapped_cells; Module *module; - NlutmapWorker(const NlutmapConfig &config, Module *module) : - config(config), module(module) - { - } + NlutmapWorker(const NlutmapConfig &config, Module *module) : config(config), module(module) {} RTLIL::Selection get_selection() { @@ -65,8 +60,7 @@ struct NlutmapWorker { vector available_luts = config.luts; - while (GetSize(available_luts) > 1) - { + while (GetSize(available_luts) > 1) { int n_luts = available_luts.back(); int lut_size = GetSize(available_luts); available_luts.pop_back(); @@ -77,11 +71,10 @@ struct NlutmapWorker run_abc(lut_size); SigMap sigmap(module); - dict candidate_ratings; + dict candidate_ratings; dict bit_lut_count; - for (auto cell : module->cells()) - { + for (auto cell : module->cells()) { if (cell->type != ID($lut) || mapped_cells.count(cell)) continue; @@ -93,8 +86,7 @@ struct NlutmapWorker bit_lut_count[bit]++; } - for (auto &cand : candidate_ratings) - { + for (auto &cand : candidate_ratings) { for (auto &conn : cand.first->connections()) for (auto bit : sigmap(conn.second)) cand.second -= bit_lut_count[bit]; @@ -128,7 +120,7 @@ struct NlutmapWorker }; struct NlutmapPass : public Pass { - NlutmapPass() : Pass("nlutmap", "map to LUTs of different sizes") { } + NlutmapPass() : Pass("nlutmap", "map to LUTs of different sizes") {} void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| @@ -157,9 +149,8 @@ struct NlutmapPass : public Pass { log_push(); size_t argidx; - for (argidx = 1; argidx < args.size(); argidx++) - { - if (args[argidx] == "-luts" && argidx+1 < args.size()) { + for (argidx = 1; argidx < args.size(); argidx++) { + if (args[argidx] == "-luts" && argidx + 1 < args.size()) { vector tokens = split_tokens(args[++argidx], ","); config.luts.clear(); for (auto &token : tokens) @@ -174,8 +165,7 @@ struct NlutmapPass : public Pass { } extra_args(args, argidx, design); - for (auto module : design->selected_whole_modules_warn()) - { + for (auto module : design->selected_whole_modules_warn()) { NlutmapWorker worker(config, module); worker.run(); } diff --git a/passes/techmap/pmuxtree.cc b/passes/techmap/pmuxtree.cc index ff6bb549bdf..a8933daa52e 100644 --- a/passes/techmap/pmuxtree.cc +++ b/passes/techmap/pmuxtree.cc @@ -17,16 +17,15 @@ * */ -#include "kernel/yosys.h" #include "kernel/sigtools.h" +#include "kernel/yosys.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN static SigSpec or_generator(Module *module, const SigSpec &sig) { - switch (GetSize(sig)) - { + switch (GetSize(sig)) { case 0: return State::S0; case 1: @@ -49,8 +48,8 @@ static SigSpec recursive_mux_generator(Module *module, const SigSpec &sig_data, int right_size = GetSize(sig_sel) - left_size; int stride = GetSize(sig_data) / GetSize(sig_sel); - SigSpec left_data = sig_data.extract(0, stride*left_size); - SigSpec right_data = sig_data.extract(stride*left_size, stride*right_size); + SigSpec left_data = sig_data.extract(0, stride * left_size); + SigSpec right_data = sig_data.extract(stride * left_size, stride * right_size); SigSpec left_sel = sig_sel.extract(0, left_size); SigSpec right_sel = sig_sel.extract(left_size, right_size); @@ -66,7 +65,7 @@ static SigSpec recursive_mux_generator(Module *module, const SigSpec &sig_data, } struct PmuxtreePass : public Pass { - PmuxtreePass() : Pass("pmuxtree", "transform $pmux cells to trees of $mux cells") { } + PmuxtreePass() : Pass("pmuxtree", "transform $pmux cells to trees of $mux cells") {} void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| @@ -87,25 +86,24 @@ struct PmuxtreePass : public Pass { extra_args(args, argidx, design); for (auto module : design->selected_modules()) - for (auto cell : module->selected_cells()) - { - if (cell->type != ID($pmux)) - continue; - - SigSpec sig_data = cell->getPort(ID::B); - SigSpec sig_sel = cell->getPort(ID::S); - - if (!cell->getPort(ID::A).is_fully_undef()) { - sig_data.append(cell->getPort(ID::A)); - SigSpec sig_sel_or = module->ReduceOr(NEW_ID, sig_sel); - sig_sel.append(module->Not(NEW_ID, sig_sel_or)); + for (auto cell : module->selected_cells()) { + if (cell->type != ID($pmux)) + continue; + + SigSpec sig_data = cell->getPort(ID::B); + SigSpec sig_sel = cell->getPort(ID::S); + + if (!cell->getPort(ID::A).is_fully_undef()) { + sig_data.append(cell->getPort(ID::A)); + SigSpec sig_sel_or = module->ReduceOr(NEW_ID, sig_sel); + sig_sel.append(module->Not(NEW_ID, sig_sel_or)); + } + + SigSpec result, result_or; + result = recursive_mux_generator(module, sig_data, sig_sel, result_or); + module->connect(cell->getPort(ID::Y), result); + module->remove(cell); } - - SigSpec result, result_or; - result = recursive_mux_generator(module, sig_data, sig_sel, result_or); - module->connect(cell->getPort(ID::Y), result); - module->remove(cell); - } } } PmuxtreePass; diff --git a/passes/techmap/shregmap.cc b/passes/techmap/shregmap.cc index 9281829700f..820fcd2b13d 100644 --- a/passes/techmap/shregmap.cc +++ b/passes/techmap/shregmap.cc @@ -17,22 +17,20 @@ * */ -#include "kernel/yosys.h" -#include "kernel/sigtools.h" #include "kernel/ffinit.h" +#include "kernel/sigtools.h" +#include "kernel/yosys.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN -struct ShregmapTech -{ - virtual ~ShregmapTech() { } +struct ShregmapTech { + virtual ~ShregmapTech() {} virtual bool analyze(vector &taps) = 0; virtual bool fixup(Cell *cell, dict &taps) = 0; }; -struct ShregmapOptions -{ +struct ShregmapOptions { int minlen, maxlen; int keep_before, keep_after; bool zinit, init, params, ffe; @@ -53,8 +51,7 @@ struct ShregmapOptions } }; -struct ShregmapTechGreenpak4 : ShregmapTech -{ +struct ShregmapTechGreenpak4 : ShregmapTech { bool analyze(vector &taps) { if (GetSize(taps) > 2 && taps[0] == 0 && taps[2] < 17) { @@ -65,7 +62,8 @@ struct ShregmapTechGreenpak4 : ShregmapTech if (GetSize(taps) > 2) return false; - if (taps.back() > 16) return false; + if (taps.back() > 16) + return false; return true; } @@ -92,36 +90,32 @@ struct ShregmapTechGreenpak4 : ShregmapTech } }; -struct ShregmapWorker -{ +struct ShregmapWorker { Module *module; SigMap sigmap; const ShregmapOptions &opts; int dff_count, shreg_count; - pool remove_cells; + pool remove_cells; FfInitVals initvals; - dict sigbit_chain_next; - dict sigbit_chain_prev; + dict sigbit_chain_next; + dict sigbit_chain_prev; pool sigbit_with_non_chain_users; - pool chain_start_cells; + pool chain_start_cells; void make_sigbit_chain_next_prev() { - for (auto wire : module->wires()) - { + for (auto wire : module->wires()) { if (wire->port_output || wire->get_bool_attribute(ID::keep)) { for (auto bit : sigmap(wire)) sigbit_with_non_chain_users.insert(bit); } } - for (auto cell : module->cells()) - { - if (opts.ffcells.count(cell->type) && !cell->get_bool_attribute(ID::keep)) - { + for (auto cell : module->cells()) { + if (opts.ffcells.count(cell->type) && !cell->get_bool_attribute(ID::keep)) { IdString d_port = opts.ffcells.at(cell->type).first; IdString q_port = opts.ffcells.at(cell->type).second; @@ -129,8 +123,7 @@ struct ShregmapWorker SigBit q_bit = sigmap(cell->getPort(q_port).as_bit()); State initval = initvals(q_bit); - if (opts.init || initval == State::Sx || (opts.zinit && initval == State::S0)) - { + if (opts.init || initval == State::Sx || (opts.zinit && initval == State::S0)) { auto r = sigbit_chain_next.insert(std::make_pair(d_bit, cell)); if (!r.second) { // Insertion not successful means that d_bit is already @@ -162,13 +155,11 @@ struct ShregmapWorker void find_chain_start_cells() { - for (auto it : sigbit_chain_next) - { + for (auto it : sigbit_chain_next) { if (opts.tech == nullptr && sigbit_with_non_chain_users.count(it.first)) goto start_cell; - if (sigbit_chain_prev.count(it.first) != 0) - { + if (sigbit_chain_prev.count(it.first) != 0) { Cell *c1 = sigbit_chain_prev.at(it.first); Cell *c2 = it.second; @@ -201,13 +192,12 @@ struct ShregmapWorker } } - vector create_chain(Cell *start_cell) + vector create_chain(Cell *start_cell) { - vector chain; + vector chain; Cell *c = start_cell; - while (c != nullptr) - { + while (c != nullptr) { chain.push_back(c); IdString q_port = opts.ffcells.at(c->type).second; @@ -224,14 +214,13 @@ struct ShregmapWorker return chain; } - void process_chain(vector &chain) + void process_chain(vector &chain) { if (GetSize(chain) < opts.keep_before + opts.minlen + opts.keep_after) return; int cursor = opts.keep_before; - while (cursor < GetSize(chain) - opts.keep_after) - { + while (cursor < GetSize(chain) - opts.keep_after) { int depth = GetSize(chain) - opts.keep_after - cursor; if (opts.maxlen > 0) @@ -241,14 +230,12 @@ struct ShregmapWorker IdString q_port = opts.ffcells.at(first_cell->type).second; dict taps_dict; - if (opts.tech) - { + if (opts.tech) { vector qbits; vector taps; - for (int i = 0; i < depth; i++) - { - Cell *cell = chain[cursor+i]; + for (int i = 0; i < depth; i++) { + Cell *cell = chain[cursor + i]; auto qbit = sigmap(cell->getPort(q_port)); qbits.push_back(qbit); @@ -256,10 +243,9 @@ struct ShregmapWorker taps.push_back(i); } - while (depth > 0) - { - if (taps.empty() || taps.back() < depth-1) - taps.push_back(depth-1); + while (depth > 0) { + if (taps.empty() || taps.back() < depth - 1) + taps.push_back(depth - 1); if (opts.tech->analyze(taps)) break; @@ -271,8 +257,8 @@ struct ShregmapWorker depth = 0; for (auto tap : taps) { taps_dict[tap] = qbits.at(tap); - log_assert(depth < tap+1); - depth = tap+1; + log_assert(depth < tap + 1); + depth = tap + 1; } } @@ -281,10 +267,10 @@ struct ShregmapWorker continue; } - Cell *last_cell = chain[cursor+depth-1]; + Cell *last_cell = chain[cursor + depth - 1]; - log("Converting %s.%s ... %s.%s to a shift register with depth %d.\n", - log_id(module), log_id(first_cell), log_id(module), log_id(last_cell), depth); + log("Converting %s.%s ... %s.%s to a shift register with depth %d.\n", log_id(module), log_id(first_cell), log_id(module), + log_id(last_cell), depth); dff_count += depth; shreg_count += 1; @@ -300,8 +286,8 @@ struct ShregmapWorker if (opts.init) { vector initval; - for (int i = depth-1; i >= 0; i--) { - SigBit bit = chain[cursor+i]->getPort(q_port).as_bit(); + for (int i = depth - 1; i >= 0; i--) { + SigBit bit = chain[cursor + i]->getPort(q_port).as_bit(); initval.push_back(initvals(bit)); initvals.remove_init(bit); } @@ -309,27 +295,33 @@ struct ShregmapWorker } if (opts.zinit) - for (int i = depth-1; i >= 0; i--) { - SigBit bit = chain[cursor+i]->getPort(q_port).as_bit(); + for (int i = depth - 1; i >= 0; i--) { + SigBit bit = chain[cursor + i]->getPort(q_port).as_bit(); initvals.remove_init(bit); } - if (opts.params) - { + if (opts.params) { int param_clkpol = -1; int param_enpol = 2; - if (first_cell->type == ID($_DFF_N_)) param_clkpol = 0; - if (first_cell->type == ID($_DFF_P_)) param_clkpol = 1; + if (first_cell->type == ID($_DFF_N_)) + param_clkpol = 0; + if (first_cell->type == ID($_DFF_P_)) + param_clkpol = 1; - if (first_cell->type == ID($_DFFE_NN_)) param_clkpol = 0, param_enpol = 0; - if (first_cell->type == ID($_DFFE_NP_)) param_clkpol = 0, param_enpol = 1; - if (first_cell->type == ID($_DFFE_PN_)) param_clkpol = 1, param_enpol = 0; - if (first_cell->type == ID($_DFFE_PP_)) param_clkpol = 1, param_enpol = 1; + if (first_cell->type == ID($_DFFE_NN_)) + param_clkpol = 0, param_enpol = 0; + if (first_cell->type == ID($_DFFE_NP_)) + param_clkpol = 0, param_enpol = 1; + if (first_cell->type == ID($_DFFE_PN_)) + param_clkpol = 1, param_enpol = 0; + if (first_cell->type == ID($_DFFE_PP_)) + param_clkpol = 1, param_enpol = 1; log_assert(param_clkpol >= 0); first_cell->setParam(ID(CLKPOL), param_clkpol); - if (opts.ffe) first_cell->setParam(ID(ENPOL), param_enpol); + if (opts.ffe) + first_cell->setParam(ID(ENPOL), param_enpol); } first_cell->type = shreg_cell_type_str; @@ -340,7 +332,7 @@ struct ShregmapWorker remove_cells.insert(first_cell); for (int i = 1; i < depth; i++) - remove_cells.insert(chain[cursor+i]); + remove_cells.insert(chain[cursor + i]); cursor += depth; } } @@ -356,15 +348,14 @@ struct ShregmapWorker chain_start_cells.clear(); } - ShregmapWorker(Module *module, const ShregmapOptions &opts) : - module(module), sigmap(module), opts(opts), dff_count(0), shreg_count(0) + ShregmapWorker(Module *module, const ShregmapOptions &opts) : module(module), sigmap(module), opts(opts), dff_count(0), shreg_count(0) { initvals.set(&sigmap, module); make_sigbit_chain_next_prev(); find_chain_start_cells(); for (auto c : chain_start_cells) { - vector chain = create_chain(c); + vector chain = create_chain(c); process_chain(chain); } @@ -373,7 +364,7 @@ struct ShregmapWorker }; struct ShregmapPass : public Pass { - ShregmapPass() : Pass("shregmap", "map shift registers") { } + ShregmapPass() : Pass("shregmap", "map shift registers") {} void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| @@ -440,17 +431,16 @@ struct ShregmapPass : public Pass { log_header(design, "Executing SHREGMAP pass (map shift registers).\n"); size_t argidx; - for (argidx = 1; argidx < args.size(); argidx++) - { - if (args[argidx] == "-clkpol" && argidx+1 < args.size()) { + for (argidx = 1; argidx < args.size(); argidx++) { + if (args[argidx] == "-clkpol" && argidx + 1 < args.size()) { clkpol = args[++argidx]; continue; } - if (args[argidx] == "-enpol" && argidx+1 < args.size()) { + if (args[argidx] == "-enpol" && argidx + 1 < args.size()) { enpol = args[++argidx]; continue; } - if (args[argidx] == "-match" && argidx+1 < args.size()) { + if (args[argidx] == "-match" && argidx + 1 < args.size()) { vector match_args = split_tokens(args[++argidx], ":"); if (GetSize(match_args) < 2) match_args.push_back("D"); @@ -462,23 +452,23 @@ struct ShregmapPass : public Pass { opts.ffcells[id_cell_type] = make_pair(id_d_port_name, id_q_port_name); continue; } - if (args[argidx] == "-minlen" && argidx+1 < args.size()) { + if (args[argidx] == "-minlen" && argidx + 1 < args.size()) { opts.minlen = atoi(args[++argidx].c_str()); continue; } - if (args[argidx] == "-maxlen" && argidx+1 < args.size()) { + if (args[argidx] == "-maxlen" && argidx + 1 < args.size()) { opts.maxlen = atoi(args[++argidx].c_str()); continue; } - if (args[argidx] == "-keep_before" && argidx+1 < args.size()) { + if (args[argidx] == "-keep_before" && argidx + 1 < args.size()) { opts.keep_before = atoi(args[++argidx].c_str()); continue; } - if (args[argidx] == "-keep_after" && argidx+1 < args.size()) { + if (args[argidx] == "-keep_after" && argidx + 1 < args.size()) { opts.keep_after = atoi(args[++argidx].c_str()); continue; } - if (args[argidx] == "-tech" && argidx+1 < args.size() && opts.tech == nullptr) { + if (args[argidx] == "-tech" && argidx + 1 < args.size() && opts.tech == nullptr) { string tech = args[++argidx]; if (tech == "greenpak4") { clkpol = "pos"; @@ -509,8 +499,7 @@ struct ShregmapPass : public Pass { if (opts.zinit && opts.init) log_cmd_error("Options -zinit and -init are exclusive!\n"); - if (opts.ffcells.empty()) - { + if (opts.ffcells.empty()) { bool clk_pos = clkpol == "" || clkpol == "pos" || clkpol == "any"; bool clk_neg = clkpol == "" || clkpol == "neg" || clkpol == "any"; @@ -535,9 +524,7 @@ struct ShregmapPass : public Pass { if (en_pos || en_neg) opts.ffe = true; - } - else - { + } else { if (!clkpol.empty()) log_cmd_error("Options -clkpol and -match are exclusive!\n"); if (!enpol.empty()) diff --git a/passes/techmap/simplemap.cc b/passes/techmap/simplemap.cc index 11692b715ea..1686b4dc0f2 100644 --- a/passes/techmap/simplemap.cc +++ b/passes/techmap/simplemap.cc @@ -18,10 +18,10 @@ */ #include "simplemap.h" -#include "kernel/sigtools.h" #include "kernel/ff.h" -#include +#include "kernel/sigtools.h" #include +#include #include USING_YOSYS_NAMESPACE @@ -64,11 +64,16 @@ void simplemap_bitop(RTLIL::Module *module, RTLIL::Cell *cell) } IdString gate_type; - if (cell->type == ID($and)) gate_type = ID($_AND_); - if (cell->type == ID($or)) gate_type = ID($_OR_); - if (cell->type == ID($xor)) gate_type = ID($_XOR_); - if (cell->type == ID($xnor)) gate_type = ID($_XNOR_); - if (cell->type == ID($bweqx)) gate_type = ID($_XNOR_); + if (cell->type == ID($and)) + gate_type = ID($_AND_); + if (cell->type == ID($or)) + gate_type = ID($_OR_); + if (cell->type == ID($xor)) + gate_type = ID($_XOR_); + if (cell->type == ID($xnor)) + gate_type = ID($_XNOR_); + if (cell->type == ID($bweqx)) + gate_type = ID($_XNOR_); log_assert(!gate_type.empty()); for (int i = 0; i < GetSize(sig_y); i++) { @@ -89,36 +94,44 @@ void simplemap_reduce(RTLIL::Module *module, RTLIL::Cell *cell) return; if (sig_a.size() == 0) { - if (cell->type == ID($reduce_and)) module->connect(RTLIL::SigSig(sig_y, RTLIL::SigSpec(1, sig_y.size()))); - if (cell->type == ID($reduce_or)) module->connect(RTLIL::SigSig(sig_y, RTLIL::SigSpec(0, sig_y.size()))); - if (cell->type == ID($reduce_xor)) module->connect(RTLIL::SigSig(sig_y, RTLIL::SigSpec(0, sig_y.size()))); - if (cell->type == ID($reduce_xnor)) module->connect(RTLIL::SigSig(sig_y, RTLIL::SigSpec(1, sig_y.size()))); - if (cell->type == ID($reduce_bool)) module->connect(RTLIL::SigSig(sig_y, RTLIL::SigSpec(0, sig_y.size()))); + if (cell->type == ID($reduce_and)) + module->connect(RTLIL::SigSig(sig_y, RTLIL::SigSpec(1, sig_y.size()))); + if (cell->type == ID($reduce_or)) + module->connect(RTLIL::SigSig(sig_y, RTLIL::SigSpec(0, sig_y.size()))); + if (cell->type == ID($reduce_xor)) + module->connect(RTLIL::SigSig(sig_y, RTLIL::SigSpec(0, sig_y.size()))); + if (cell->type == ID($reduce_xnor)) + module->connect(RTLIL::SigSig(sig_y, RTLIL::SigSpec(1, sig_y.size()))); + if (cell->type == ID($reduce_bool)) + module->connect(RTLIL::SigSig(sig_y, RTLIL::SigSpec(0, sig_y.size()))); return; } if (sig_y.size() > 1) { - module->connect(RTLIL::SigSig(sig_y.extract(1, sig_y.size()-1), RTLIL::SigSpec(0, sig_y.size()-1))); + module->connect(RTLIL::SigSig(sig_y.extract(1, sig_y.size() - 1), RTLIL::SigSpec(0, sig_y.size() - 1))); sig_y = sig_y.extract(0, 1); } IdString gate_type; - if (cell->type == ID($reduce_and)) gate_type = ID($_AND_); - if (cell->type == ID($reduce_or)) gate_type = ID($_OR_); - if (cell->type == ID($reduce_xor)) gate_type = ID($_XOR_); - if (cell->type == ID($reduce_xnor)) gate_type = ID($_XOR_); - if (cell->type == ID($reduce_bool)) gate_type = ID($_OR_); + if (cell->type == ID($reduce_and)) + gate_type = ID($_AND_); + if (cell->type == ID($reduce_or)) + gate_type = ID($_OR_); + if (cell->type == ID($reduce_xor)) + gate_type = ID($_XOR_); + if (cell->type == ID($reduce_xnor)) + gate_type = ID($_XOR_); + if (cell->type == ID($reduce_bool)) + gate_type = ID($_OR_); log_assert(!gate_type.empty()); RTLIL::Cell *last_output_cell = NULL; - while (sig_a.size() > 1) - { + while (sig_a.size() > 1) { RTLIL::SigSpec sig_t = module->addWire(NEW_ID, sig_a.size() / 2); - for (int i = 0; i < sig_a.size(); i += 2) - { - if (i+1 == sig_a.size()) { + for (int i = 0; i < sig_a.size(); i += 2) { + if (i + 1 == sig_a.size()) { sig_t.append(sig_a[i]); continue; } @@ -126,8 +139,8 @@ void simplemap_reduce(RTLIL::Module *module, RTLIL::Cell *cell) RTLIL::Cell *gate = module->addCell(NEW_ID, gate_type); gate->add_strpool_attribute(ID::src, cell->get_strpool_attribute(ID::src)); gate->setPort(ID::A, sig_a[i]); - gate->setPort(ID::B, sig_a[i+1]); - gate->setPort(ID::Y, sig_t[i/2]); + gate->setPort(ID::B, sig_a[i + 1]); + gate->setPort(ID::Y, sig_t[i / 2]); last_output_cell = gate; } @@ -153,13 +166,11 @@ void simplemap_reduce(RTLIL::Module *module, RTLIL::Cell *cell) static void logic_reduce(RTLIL::Module *module, RTLIL::SigSpec &sig, RTLIL::Cell *cell) { - while (sig.size() > 1) - { + while (sig.size() > 1) { RTLIL::SigSpec sig_t = module->addWire(NEW_ID, sig.size() / 2); - for (int i = 0; i < sig.size(); i += 2) - { - if (i+1 == sig.size()) { + for (int i = 0; i < sig.size(); i += 2) { + if (i + 1 == sig.size()) { sig_t.append(sig[i]); continue; } @@ -167,8 +178,8 @@ static void logic_reduce(RTLIL::Module *module, RTLIL::SigSpec &sig, RTLIL::Cell RTLIL::Cell *gate = module->addCell(NEW_ID, ID($_OR_)); gate->add_strpool_attribute(ID::src, cell->get_strpool_attribute(ID::src)); gate->setPort(ID::A, sig[i]); - gate->setPort(ID::B, sig[i+1]); - gate->setPort(ID::Y, sig_t[i/2]); + gate->setPort(ID::B, sig[i + 1]); + gate->setPort(ID::Y, sig_t[i / 2]); } sig = sig_t; @@ -189,7 +200,7 @@ void simplemap_lognot(RTLIL::Module *module, RTLIL::Cell *cell) return; if (sig_y.size() > 1) { - module->connect(RTLIL::SigSig(sig_y.extract(1, sig_y.size()-1), RTLIL::SigSpec(0, sig_y.size()-1))); + module->connect(RTLIL::SigSig(sig_y.extract(1, sig_y.size() - 1), RTLIL::SigSpec(0, sig_y.size() - 1))); sig_y = sig_y.extract(0, 1); } @@ -213,13 +224,15 @@ void simplemap_logbin(RTLIL::Module *module, RTLIL::Cell *cell) return; if (sig_y.size() > 1) { - module->connect(RTLIL::SigSig(sig_y.extract(1, sig_y.size()-1), RTLIL::SigSpec(0, sig_y.size()-1))); + module->connect(RTLIL::SigSig(sig_y.extract(1, sig_y.size() - 1), RTLIL::SigSpec(0, sig_y.size() - 1))); sig_y = sig_y.extract(0, 1); } IdString gate_type; - if (cell->type == ID($logic_and)) gate_type = ID($_AND_); - if (cell->type == ID($logic_or)) gate_type = ID($_OR_); + if (cell->type == ID($logic_and)) + gate_type = ID($_AND_); + if (cell->type == ID($logic_or)) + gate_type = ID($_OR_); log_assert(!gate_type.empty()); RTLIL::Cell *gate = module->addCell(NEW_ID, gate_type); @@ -312,15 +325,15 @@ void simplemap_bmux(RTLIL::Module *module, RTLIL::Cell *cell) int width = GetSize(cell->getPort(ID::Y)); for (int idx = 0; idx < GetSize(sel); idx++) { - SigSpec new_data = module->addWire(NEW_ID, GetSize(data)/2); + SigSpec new_data = module->addWire(NEW_ID, GetSize(data) / 2); for (int i = 0; i < GetSize(new_data); i += width) { for (int k = 0; k < width; k++) { RTLIL::Cell *gate = module->addCell(NEW_ID, ID($_MUX_)); gate->add_strpool_attribute(ID::src, cell->get_strpool_attribute(ID::src)); - gate->setPort(ID::A, data[i*2+k]); - gate->setPort(ID::B, data[i*2+width+k]); + gate->setPort(ID::A, data[i * 2 + k]); + gate->setPort(ID::B, data[i * 2 + width + k]); gate->setPort(ID::S, sel[idx]); - gate->setPort(ID::Y, new_data[i+k]); + gate->setPort(ID::Y, new_data[i + k]); } } data = new_data; @@ -336,14 +349,14 @@ void simplemap_lut(RTLIL::Module *module, RTLIL::Cell *cell) lut_data.extend_u0(1 << cell->getParam(ID::WIDTH).as_int()); for (int idx = 0; GetSize(lut_data) > 1; idx++) { - SigSpec new_lut_data = module->addWire(NEW_ID, GetSize(lut_data)/2); + SigSpec new_lut_data = module->addWire(NEW_ID, GetSize(lut_data) / 2); for (int i = 0; i < GetSize(lut_data); i += 2) { RTLIL::Cell *gate = module->addCell(NEW_ID, ID($_MUX_)); gate->add_strpool_attribute(ID::src, cell->get_strpool_attribute(ID::src)); gate->setPort(ID::A, lut_data[i]); - gate->setPort(ID::B, lut_data[i+1]); + gate->setPort(ID::B, lut_data[i + 1]); gate->setPort(ID::S, lut_ctrl[idx]); - gate->setPort(ID::Y, new_lut_data[i/2]); + gate->setPort(ID::Y, new_lut_data[i / 2]); } lut_data = new_lut_data; } @@ -365,11 +378,11 @@ void simplemap_sop(RTLIL::Module *module, RTLIL::Cell *cell) for (int i = 0; i < depth; i++) { SigSpec in, pat; for (int j = 0; j < width; j++) { - if (table[2*i*width + 2*j + 0] == State::S1) { + if (table[2 * i * width + 2 * j + 0] == State::S1) { in.append(ctrl[j]); pat.append(State::S0); } - if (table[2*i*width + 2*j + 1] == State::S1) { + if (table[2 * i * width + 2 * j + 1] == State::S1) { in.append(ctrl[j]); pat.append(State::S1); } @@ -407,56 +420,56 @@ void simplemap_ff(RTLIL::Module *, RTLIL::Cell *cell) } } -void simplemap_get_mappers(dict &mappers) +void simplemap_get_mappers(dict &mappers) { - mappers[ID($not)] = simplemap_not; - mappers[ID($pos)] = simplemap_pos; - mappers[ID($and)] = simplemap_bitop; - mappers[ID($or)] = simplemap_bitop; - mappers[ID($xor)] = simplemap_bitop; - mappers[ID($xnor)] = simplemap_bitop; - mappers[ID($bweqx)] = simplemap_bitop; - mappers[ID($reduce_and)] = simplemap_reduce; - mappers[ID($reduce_or)] = simplemap_reduce; - mappers[ID($reduce_xor)] = simplemap_reduce; + mappers[ID($not)] = simplemap_not; + mappers[ID($pos)] = simplemap_pos; + mappers[ID($and)] = simplemap_bitop; + mappers[ID($or)] = simplemap_bitop; + mappers[ID($xor)] = simplemap_bitop; + mappers[ID($xnor)] = simplemap_bitop; + mappers[ID($bweqx)] = simplemap_bitop; + mappers[ID($reduce_and)] = simplemap_reduce; + mappers[ID($reduce_or)] = simplemap_reduce; + mappers[ID($reduce_xor)] = simplemap_reduce; mappers[ID($reduce_xnor)] = simplemap_reduce; mappers[ID($reduce_bool)] = simplemap_reduce; - mappers[ID($logic_not)] = simplemap_lognot; - mappers[ID($logic_and)] = simplemap_logbin; - mappers[ID($logic_or)] = simplemap_logbin; - mappers[ID($eq)] = simplemap_eqne; - mappers[ID($eqx)] = simplemap_eqne; - mappers[ID($ne)] = simplemap_eqne; - mappers[ID($nex)] = simplemap_eqne; - mappers[ID($mux)] = simplemap_mux; - mappers[ID($bwmux)] = simplemap_bwmux; - mappers[ID($tribuf)] = simplemap_tribuf; - mappers[ID($bmux)] = simplemap_bmux; - mappers[ID($lut)] = simplemap_lut; - mappers[ID($sop)] = simplemap_sop; - mappers[ID($slice)] = simplemap_slice; - mappers[ID($concat)] = simplemap_concat; - mappers[ID($sr)] = simplemap_ff; - mappers[ID($ff)] = simplemap_ff; - mappers[ID($dff)] = simplemap_ff; - mappers[ID($dffe)] = simplemap_ff; - mappers[ID($dffsr)] = simplemap_ff; - mappers[ID($dffsre)] = simplemap_ff; - mappers[ID($adff)] = simplemap_ff; - mappers[ID($sdff)] = simplemap_ff; - mappers[ID($adffe)] = simplemap_ff; - mappers[ID($sdffe)] = simplemap_ff; - mappers[ID($sdffce)] = simplemap_ff; - mappers[ID($aldff)] = simplemap_ff; - mappers[ID($aldffe)] = simplemap_ff; - mappers[ID($dlatch)] = simplemap_ff; - mappers[ID($adlatch)] = simplemap_ff; - mappers[ID($dlatchsr)] = simplemap_ff; + mappers[ID($logic_not)] = simplemap_lognot; + mappers[ID($logic_and)] = simplemap_logbin; + mappers[ID($logic_or)] = simplemap_logbin; + mappers[ID($eq)] = simplemap_eqne; + mappers[ID($eqx)] = simplemap_eqne; + mappers[ID($ne)] = simplemap_eqne; + mappers[ID($nex)] = simplemap_eqne; + mappers[ID($mux)] = simplemap_mux; + mappers[ID($bwmux)] = simplemap_bwmux; + mappers[ID($tribuf)] = simplemap_tribuf; + mappers[ID($bmux)] = simplemap_bmux; + mappers[ID($lut)] = simplemap_lut; + mappers[ID($sop)] = simplemap_sop; + mappers[ID($slice)] = simplemap_slice; + mappers[ID($concat)] = simplemap_concat; + mappers[ID($sr)] = simplemap_ff; + mappers[ID($ff)] = simplemap_ff; + mappers[ID($dff)] = simplemap_ff; + mappers[ID($dffe)] = simplemap_ff; + mappers[ID($dffsr)] = simplemap_ff; + mappers[ID($dffsre)] = simplemap_ff; + mappers[ID($adff)] = simplemap_ff; + mappers[ID($sdff)] = simplemap_ff; + mappers[ID($adffe)] = simplemap_ff; + mappers[ID($sdffe)] = simplemap_ff; + mappers[ID($sdffce)] = simplemap_ff; + mappers[ID($aldff)] = simplemap_ff; + mappers[ID($aldffe)] = simplemap_ff; + mappers[ID($dlatch)] = simplemap_ff; + mappers[ID($adlatch)] = simplemap_ff; + mappers[ID($dlatchsr)] = simplemap_ff; } void simplemap(RTLIL::Module *module, RTLIL::Cell *cell) { - static dict mappers; + static dict mappers; static bool initialized_mappers = false; if (!initialized_mappers) { @@ -471,7 +484,7 @@ YOSYS_NAMESPACE_END PRIVATE_NAMESPACE_BEGIN struct SimplemapPass : public Pass { - SimplemapPass() : Pass("simplemap", "mapping simple coarse-grain cells") { } + SimplemapPass() : Pass("simplemap", "mapping simple coarse-grain cells") {} void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| @@ -493,13 +506,13 @@ struct SimplemapPass : public Pass { log_header(design, "Executing SIMPLEMAP pass (map simple cells to gate primitives).\n"); extra_args(args, 1, design); - dict mappers; + dict mappers; simplemap_get_mappers(mappers); for (auto mod : design->modules()) { if (!design->selected(mod) || mod->get_blackbox_attribute()) continue; - std::vector cells = mod->cells(); + std::vector cells = mod->cells(); for (auto cell : cells) { if (mappers.count(cell->type) == 0) continue; diff --git a/passes/techmap/simplemap.h b/passes/techmap/simplemap.h index 30cc1ccfe5a..dac16e7eb1b 100644 --- a/passes/techmap/simplemap.h +++ b/passes/techmap/simplemap.h @@ -38,7 +38,7 @@ extern void simplemap_concat(RTLIL::Module *module, RTLIL::Cell *cell); extern void simplemap_ff(RTLIL::Module *module, RTLIL::Cell *cell); extern void simplemap(RTLIL::Module *module, RTLIL::Cell *cell); -extern void simplemap_get_mappers(dict &mappers); +extern void simplemap_get_mappers(dict &mappers); YOSYS_NAMESPACE_END diff --git a/passes/techmap/techmap.cc b/passes/techmap/techmap.cc index 144f596c88c..423af07dfab 100644 --- a/passes/techmap/techmap.cc +++ b/passes/techmap/techmap.cc @@ -17,14 +17,14 @@ * */ -#include "kernel/yosys.h" -#include "kernel/utils.h" -#include "kernel/sigtools.h" #include "kernel/ffinit.h" +#include "kernel/sigtools.h" +#include "kernel/utils.h" +#include "kernel/yosys.h" #include "libs/sha1/sha1.h" -#include #include +#include #include #include "simplemap.h" @@ -42,7 +42,7 @@ PRIVATE_NAMESPACE_BEGIN void apply_prefix(IdString prefix, IdString &id) { if (id[0] == '\\') - id = stringf("%s.%s", prefix.c_str(), id.c_str()+1); + id = stringf("%s.%s", prefix.c_str(), id.c_str() + 1); else id = stringf("$techmap%s.%s", prefix.c_str(), id.c_str()); } @@ -60,13 +60,12 @@ void apply_prefix(IdString prefix, RTLIL::SigSpec &sig, RTLIL::Module *module) sig = chunks; } -struct TechmapWorker -{ - dict simplemap_mappers; - dict>, RTLIL::Module*> techmap_cache; - dict techmap_do_cache; - pool module_queue; - dict sigmaps; +struct TechmapWorker { + dict simplemap_mappers; + dict>, RTLIL::Module *> techmap_cache; + dict techmap_do_cache; + pool module_queue; + dict sigmaps; pool log_msg_cache; @@ -98,9 +97,9 @@ struct TechmapWorker } else if (connbits_map.count(bit)) { if (verbose) log(" Bit %d of port %s and bit %d of port %s are connected.\n", i, log_id(conn.first), - connbits_map.at(bit).second, log_id(connbits_map.at(bit).first)); - constmap_info += stringf("|%s %d %s %d", log_id(conn.first), i, - log_id(connbits_map.at(bit).first), connbits_map.at(bit).second); + connbits_map.at(bit).second, log_id(connbits_map.at(bit).first)); + constmap_info += stringf("|%s %d %s %d", log_id(conn.first), i, log_id(connbits_map.at(bit).first), + connbits_map.at(bit).second); } else { connbits_map.emplace(bit, std::make_pair(conn.first, i)); constmap_info += stringf("|%s %d", log_id(conn.first), i); @@ -134,8 +133,8 @@ struct TechmapWorker if (!result.empty()) { SigMap sigmap(module); for (auto &it1 : result) - for (auto &it2 : it1.second) - sigmap.apply(it2.value); + for (auto &it2 : it1.second) + sigmap.apply(it2.value); } return result; @@ -146,7 +145,7 @@ struct TechmapWorker if (tpl->processes.size() != 0) { log("Technology map yielded processes:"); for (auto &it : tpl->processes) - log(" %s",log_id(it.first)); + log(" %s", log_id(it.first)); log("\n"); if (autoproc_mode) { Pass::call_on_module(tpl->design, tpl, "proc"); @@ -178,20 +177,17 @@ struct TechmapWorker } dict positional_ports; - dict temp_renamed_wires; + dict temp_renamed_wires; pool autopurge_tpl_bits; - for (auto tpl_w : tpl->wires()) - { - if (tpl_w->port_id > 0) - { + for (auto tpl_w : tpl->wires()) { + if (tpl_w->port_id > 0) { IdString posportname = stringf("$%d", tpl_w->port_id); positional_ports.emplace(posportname, tpl_w->name); if (tpl_w->get_bool_attribute(ID::techmap_autopurge) && - (!cell->hasPort(tpl_w->name) || !GetSize(cell->getPort(tpl_w->name))) && - (!cell->hasPort(posportname) || !GetSize(cell->getPort(posportname)))) - { + (!cell->hasPort(tpl_w->name) || !GetSize(cell->getPort(tpl_w->name))) && + (!cell->hasPort(posportname) || !GetSize(cell->getPort(posportname)))) { if (sigmaps.count(tpl) == 0) sigmaps[tpl].set(tpl); @@ -230,24 +226,24 @@ struct TechmapWorker pool tpl_written_bits; for (auto tpl_cell : tpl->cells()) - for (auto &conn : tpl_cell->connections()) - if (tpl_cell->output(conn.first)) - for (auto bit : conn.second) - tpl_written_bits.insert(bit); + for (auto &conn : tpl_cell->connections()) + if (tpl_cell->output(conn.first)) + for (auto bit : conn.second) + tpl_written_bits.insert(bit); for (auto &conn : tpl->connections()) for (auto bit : conn.first) tpl_written_bits.insert(bit); SigMap port_signal_map; - for (auto &it : cell->connections()) - { + for (auto &it : cell->connections()) { IdString portname = it.first; if (positional_ports.count(portname) > 0) portname = positional_ports.at(portname); if (tpl->wire(portname) == nullptr || tpl->wire(portname)->port_id == 0) { if (portname.begins_with("$")) - log_error("Can't map port `%s' of cell `%s' to template `%s'!\n", portname.c_str(), cell->name.c_str(), tpl->name.c_str()); + log_error("Can't map port `%s' of cell `%s' to template `%s'!\n", portname.c_str(), cell->name.c_str(), + tpl->name.c_str()); continue; } @@ -297,8 +293,7 @@ struct TechmapWorker if (w->port_output && !w->port_input) { port_signal_map.add(c.second, c.first); - } else - if (!w->port_output && w->port_input) { + } else if (!w->port_output && w->port_input) { port_signal_map.add(c.first, c.second); } else { module->connect(c); @@ -311,16 +306,15 @@ struct TechmapWorker auto lhs = GetSize(extra_connect.first); auto rhs = GetSize(extra_connect.second); if (lhs > rhs) - extra_connect.first.remove(rhs, lhs-rhs); + extra_connect.first.remove(rhs, lhs - rhs); else if (rhs > lhs) - extra_connect.second.remove(lhs, rhs-lhs); + extra_connect.second.remove(lhs, rhs - lhs); module->connect(extra_connect); break; } } - for (auto tpl_cell : tpl->cells()) - { + for (auto tpl_cell : tpl->cells()) { IdString c_name = tpl_cell->name; bool techmap_replace_cell = c_name.ends_with("_TECHMAP_REPLACE_"); @@ -339,8 +333,7 @@ struct TechmapWorker vector autopurge_ports; - for (auto &conn : c->connections()) - { + for (auto &conn : c->connections()) { bool autopurge = false; if (!autopurge_tpl_bits.empty()) { autopurge = GetSize(conn.second) != 0; @@ -396,8 +389,7 @@ struct TechmapWorker module->remove(cell); - for (auto &it : temp_renamed_wires) - { + for (auto &it : temp_renamed_wires) { Wire *w = it.first; IdString name = it.second; IdString altname = module->uniquify(name); @@ -407,8 +399,8 @@ struct TechmapWorker } } - bool techmap_module(RTLIL::Design *design, RTLIL::Module *module, RTLIL::Design *map, pool &handled_cells, - const dict> &celltypeMap, bool in_recursion) + bool techmap_module(RTLIL::Design *design, RTLIL::Module *module, RTLIL::Design *map, pool &handled_cells, + const dict> &celltypeMap, bool in_recursion) { std::string mapmsg_prefix = in_recursion ? "Recursively mapping" : "Mapping"; @@ -422,12 +414,11 @@ struct TechmapWorker SigMap sigmap(module); FfInitVals initvals(&sigmap, module); - TopoSort> cells; - dict> cell_to_inbit; - dict> outbit_to_cell; + TopoSort> cells; + dict> cell_to_inbit; + dict> outbit_to_cell; - for (auto cell : module->selected_cells()) - { + for (auto cell : module->selected_cells()) { if (handled_cells.count(cell) > 0) continue; @@ -441,8 +432,7 @@ struct TechmapWorker continue; } - for (auto &conn : cell->connections()) - { + for (auto &conn : cell->connections()) { RTLIL::SigSpec sig = sigmap(conn.second); sig.remove_const(); @@ -464,14 +454,13 @@ struct TechmapWorker } for (auto &it_right : cell_to_inbit) - for (auto &it_sigbit : it_right.second) - for (auto &it_left : outbit_to_cell[it_sigbit]) - cells.edge(it_left, it_right.first); + for (auto &it_sigbit : it_right.second) + for (auto &it_left : outbit_to_cell[it_sigbit]) + cells.edge(it_left, it_right.first); cells.sort(); - for (auto cell : cells.sorted) - { + for (auto cell : cells.sorted) { log_assert(handled_cells.count(cell) == 0); log_assert(cell == module->cell(cell->name)); bool mapped_cell = false; @@ -481,8 +470,7 @@ struct TechmapWorker if (in_recursion && cell->type.begins_with("\\$")) cell_type = cell_type.substr(1); - for (auto &tpl_name : celltypeMap.at(cell_type)) - { + for (auto &tpl_name : celltypeMap.at(cell_type)) { IdString derived_name = tpl_name; RTLIL::Module *tpl = map->module(tpl_name); dict parameters(cell->parameters); @@ -501,12 +489,10 @@ struct TechmapWorker if (tpl->attributes.count(ID::techmap_wrap)) extmapper_name = "wrap"; - if (!extmapper_name.empty()) - { + if (!extmapper_name.empty()) { cell->type = cell_type; - if ((extern_mode && !in_recursion) || extmapper_name == "wrap") - { + if ((extern_mode && !in_recursion) || extmapper_name == "wrap") { std::string m_name = stringf("$extern:%s:%s", extmapper_name.c_str(), log_id(cell->type)); for (auto &c : cell->parameters) @@ -518,8 +504,7 @@ struct TechmapWorker RTLIL::Design *extmapper_design = extern_mode && !in_recursion ? design : tpl->design; RTLIL::Module *extmapper_module = extmapper_design->module(m_name); - if (extmapper_module == nullptr) - { + if (extmapper_module == nullptr) { extmapper_module = extmapper_design->addModule(m_name); RTLIL::Cell *extmapper_cell = extmapper_module->addCell(cell->type, cell); @@ -542,7 +527,8 @@ struct TechmapWorker if (extmapper_name == "simplemap") { log("Creating %s with simplemap.\n", log_id(extmapper_module)); if (simplemap_mappers.count(extmapper_cell->type) == 0) - log_error("No simplemap mapper for cell type %s found!\n", log_id(extmapper_cell->type)); + log_error("No simplemap mapper for cell type %s found!\n", + log_id(extmapper_cell->type)); simplemap_mappers.at(extmapper_cell->type)(extmapper_module, extmapper_cell); extmapper_module->remove(extmapper_cell); } @@ -550,7 +536,8 @@ struct TechmapWorker if (extmapper_name == "maccmap") { log("Creating %s with maccmap.\n", log_id(extmapper_module)); if (extmapper_cell->type != ID($macc)) - log_error("The maccmap mapper can only map $macc (not %s) cells!\n", log_id(extmapper_cell->type)); + log_error("The maccmap mapper can only map $macc (not %s) cells!\n", + log_id(extmapper_cell->type)); maccmap(extmapper_module, extmapper_cell); extmapper_module->remove(extmapper_cell); } @@ -572,21 +559,23 @@ struct TechmapWorker goto use_wrapper_tpl; } - auto msg = stringf("Using extmapper %s for cells of type %s.", log_id(extmapper_module), log_id(cell->type)); + auto msg = + stringf("Using extmapper %s for cells of type %s.", log_id(extmapper_module), log_id(cell->type)); if (!log_msg_cache.count(msg)) { log_msg_cache.insert(msg); log("%s\n", msg.c_str()); } - log_debug("%s %s.%s (%s) to %s.\n", mapmsg_prefix.c_str(), log_id(module), log_id(cell), log_id(cell->type), log_id(extmapper_module)); - } - else - { - auto msg = stringf("Using extmapper %s for cells of type %s.", extmapper_name.c_str(), log_id(cell->type)); + log_debug("%s %s.%s (%s) to %s.\n", mapmsg_prefix.c_str(), log_id(module), log_id(cell), + log_id(cell->type), log_id(extmapper_module)); + } else { + auto msg = + stringf("Using extmapper %s for cells of type %s.", extmapper_name.c_str(), log_id(cell->type)); if (!log_msg_cache.count(msg)) { log_msg_cache.insert(msg); log("%s\n", msg.c_str()); } - log_debug("%s %s.%s (%s) with %s.\n", mapmsg_prefix.c_str(), log_id(module), log_id(cell), log_id(cell->type), extmapper_name.c_str()); + log_debug("%s %s.%s (%s) with %s.\n", mapmsg_prefix.c_str(), log_id(module), log_id(cell), + log_id(cell->type), extmapper_name.c_str()); if (extmapper_name == "simplemap") { if (simplemap_mappers.count(cell->type) == 0) @@ -596,7 +585,8 @@ struct TechmapWorker if (extmapper_name == "maccmap") { if (cell->type != ID($macc)) - log_error("The maccmap mapper can only map $macc (not %s) cells!\n", log_id(cell->type)); + log_error("The maccmap mapper can only map $macc (not %s) cells!\n", + log_id(cell->type)); maccmap(module, cell); } @@ -614,13 +604,14 @@ struct TechmapWorker continue; if (tpl->wire(conn.first) != nullptr && tpl->wire(conn.first)->port_id > 0) continue; - if (!conn.second.is_fully_const() || parameters.count(conn.first) > 0 || tpl->avail_parameters.count(conn.first) == 0) + if (!conn.second.is_fully_const() || parameters.count(conn.first) > 0 || + tpl->avail_parameters.count(conn.first) == 0) goto next_tpl; parameters[conn.first] = conn.second.as_const(); } if (0) { - next_tpl: + next_tpl: continue; } @@ -634,14 +625,16 @@ struct TechmapWorker std::vector v = sigmap(conn.second).to_sigbit_vector(); for (auto &bit : v) bit = RTLIL::SigBit(bit.wire == nullptr ? RTLIL::State::S1 : RTLIL::State::S0); - parameters.emplace(stringf("\\_TECHMAP_CONSTMSK_%s_", log_id(conn.first)), RTLIL::SigSpec(v).as_const()); + parameters.emplace(stringf("\\_TECHMAP_CONSTMSK_%s_", log_id(conn.first)), + RTLIL::SigSpec(v).as_const()); } if (tpl->avail_parameters.count(stringf("\\_TECHMAP_CONSTVAL_%s_", log_id(conn.first))) != 0) { std::vector v = sigmap(conn.second).to_sigbit_vector(); for (auto &bit : v) if (bit.wire != nullptr) bit = RTLIL::SigBit(RTLIL::State::Sx); - parameters.emplace(stringf("\\_TECHMAP_CONSTVAL_%s_", log_id(conn.first)), RTLIL::SigSpec(v).as_const()); + parameters.emplace(stringf("\\_TECHMAP_CONSTVAL_%s_", log_id(conn.first)), + RTLIL::SigSpec(v).as_const()); } if (tpl->avail_parameters.count(stringf("\\_TECHMAP_WIREINIT_%s_", log_id(conn.first))) != 0) { parameters.emplace(stringf("\\_TECHMAP_WIREINIT_%s_", log_id(conn.first)), initvals(conn.second)); @@ -666,7 +659,7 @@ struct TechmapWorker // Find highest bit set int bits = 0; for (int i = 0; i < 32; i++) - if (((unique_bit_id_counter-1) & (1 << i)) != 0) + if (((unique_bit_id_counter - 1) & (1 << i)) != 0) bits = i; // Increment index by one to get number of bits bits++; @@ -688,7 +681,7 @@ struct TechmapWorker } if (0) { - use_wrapper_tpl:; + use_wrapper_tpl:; // do not register techmap_wrap modules with techmap_cache } else { std::pair> key(tpl_name, parameters); @@ -710,15 +703,13 @@ struct TechmapWorker if (constmapped_tpl != nullptr) tpl = constmapped_tpl; - if (techmap_do_cache.count(tpl) == 0) - { + if (techmap_do_cache.count(tpl) == 0) { bool keep_running = true; techmap_do_cache[tpl] = true; pool techmap_wire_names; - while (keep_running) - { + while (keep_running) { TechmapWires twd = techmap_find_special_wires(tpl); keep_running = false; @@ -731,8 +722,9 @@ struct TechmapWorker for (const TechmapWireData &elem : it.second) { RTLIL::SigSpec value = elem.value; if (value.is_fully_const() && value.as_bool()) { - log("Not using module `%s' from techmap as it contains a %s marker wire with non-zero value %s.\n", - derived_name.c_str(), log_id(elem.wire->name), log_signal(value)); + log("Not using module `%s' from techmap as it contains a %s marker wire with " + "non-zero value %s.\n", + derived_name.c_str(), log_id(elem.wire->name), log_signal(value)); techmap_do_cache[tpl] = false; } } @@ -741,27 +733,26 @@ struct TechmapWorker if (!techmap_do_cache[tpl]) break; - for (auto &it : twd) - { + for (auto &it : twd) { if (!it.first.contains("_TECHMAP_DO_") || it.second.empty()) continue; auto &data = it.second.front(); if (!data.value.is_fully_const()) - log_error("Techmap yielded config wire %s with non-const value %s.\n", log_id(data.wire->name), log_signal(data.value)); + log_error("Techmap yielded config wire %s with non-const value %s.\n", + log_id(data.wire->name), log_signal(data.value)); techmap_wire_names.erase(it.first); const char *p = data.wire->name.c_str(); - const char *q = strrchr(p+1, '.'); - q = q ? q+1 : p+1; + const char *q = strrchr(p + 1, '.'); + q = q ? q + 1 : p + 1; std::string cmd_string = data.value.as_const().decode_string(); restart_eval_cmd_string: - if (cmd_string.rfind("CONSTMAP; ", 0) == 0) - { + if (cmd_string.rfind("CONSTMAP; ", 0) == 0) { cmd_string = cmd_string.substr(strlen("CONSTMAP; ")); log("Analyzing pattern of constant bits for this cell:\n"); @@ -780,8 +771,7 @@ struct TechmapWorker dict port_connmap; dict cellbits_to_tplbits; - for (auto wire : tpl->wires().to_vector()) - { + for (auto wire : tpl->wires().to_vector()) { if (!wire->port_input || wire->port_output) continue; @@ -793,14 +783,15 @@ struct TechmapWorker wire->port_id = 0; for (int i = 0; i < wire->width; i++) { - port_new2old_map.emplace(RTLIL::SigBit(new_wire, i), RTLIL::SigBit(wire, i)); - port_connmap.emplace(RTLIL::SigBit(wire, i), RTLIL::SigBit(new_wire, i)); + port_new2old_map.emplace(RTLIL::SigBit(new_wire, i), + RTLIL::SigBit(wire, i)); + port_connmap.emplace(RTLIL::SigBit(wire, i), + RTLIL::SigBit(new_wire, i)); } } // Handle outputs first, as these cannot be remapped. - for (auto &conn : cell->connections()) - { + for (auto &conn : cell->connections()) { Wire *twire = tpl->wire(conn.first); if (!twire->port_output) continue; @@ -813,28 +804,22 @@ struct TechmapWorker } // Now handle inputs, remapping as necessary. - for (auto &conn : cell->connections()) - { + for (auto &conn : cell->connections()) { Wire *twire = tpl->wire(conn.first); if (twire->port_output) continue; - for (int i = 0; i < GetSize(conn.second); i++) - { + for (int i = 0; i < GetSize(conn.second); i++) { RTLIL::SigBit bit = sigmap(conn.second[i]); RTLIL::SigBit tplbit(twire, i); - if (bit.wire == nullptr) - { + if (bit.wire == nullptr) { RTLIL::SigBit oldbit = port_new2old_map.at(tplbit); port_connmap.at(oldbit) = bit; - } - else if (cellbits_to_tplbits.count(bit)) - { + } else if (cellbits_to_tplbits.count(bit)) { RTLIL::SigBit oldbit = port_new2old_map.at(tplbit); port_connmap.at(oldbit) = cellbits_to_tplbits[bit]; - } - else + } else cellbits_to_tplbits[bit] = tplbit; } } @@ -850,17 +835,18 @@ struct TechmapWorker goto restart_eval_cmd_string; } - if (cmd_string.rfind("RECURSION; ", 0) == 0) - { + if (cmd_string.rfind("RECURSION; ", 0) == 0) { cmd_string = cmd_string.substr(strlen("RECURSION; ")); - while (techmap_module(map, tpl, map, handled_cells, celltypeMap, true)) { } + while (techmap_module(map, tpl, map, handled_cells, celltypeMap, true)) { + } goto restart_eval_cmd_string; } Pass::call_on_module(map, tpl, cmd_string); log_assert(!strncmp(q, "_TECHMAP_DO_", 12)); - std::string new_name = data.wire->name.substr(0, q-p) + "_TECHMAP_DONE_" + data.wire->name.substr(q-p+12); + std::string new_name = + data.wire->name.substr(0, q - p) + "_TECHMAP_DONE_" + data.wire->name.substr(q - p + 12); while (tpl->wire(new_name) != nullptr) new_name += "_"; tpl->rename(data.wire->name, new_name); @@ -872,12 +858,15 @@ struct TechmapWorker TechmapWires twd = techmap_find_special_wires(tpl); for (auto &it : twd) { - if (!it.first.ends_with("_TECHMAP_FAIL_") && (!it.first.begins_with("\\_TECHMAP_REMOVEINIT_") || !it.first.ends_with("_")) && !it.first.contains("_TECHMAP_DO_") && !it.first.contains("_TECHMAP_DONE_")) + if (!it.first.ends_with("_TECHMAP_FAIL_") && + (!it.first.begins_with("\\_TECHMAP_REMOVEINIT_") || !it.first.ends_with("_")) && + !it.first.contains("_TECHMAP_DO_") && !it.first.contains("_TECHMAP_DONE_")) log_error("Techmap yielded unknown config wire %s.\n", log_id(it.first)); if (techmap_do_cache[tpl]) for (auto &it2 : it.second) if (!it2.value.is_fully_const()) - log_error("Techmap yielded config wire %s with non-const value %s.\n", log_id(it2.wire->name), log_signal(it2.value)); + log_error("Techmap yielded config wire %s with non-const value %s.\n", + log_id(it2.wire->name), log_signal(it2.value)); techmap_wire_names.erase(it.first); } @@ -890,7 +879,8 @@ struct TechmapWorker log_continue = false; mkdebug.off(); } - while (techmap_module(map, tpl, map, handled_cells, celltypeMap, true)) { } + while (techmap_module(map, tpl, map, handled_cells, celltypeMap, true)) { + } } } @@ -920,12 +910,10 @@ struct TechmapWorker } } - if (extern_mode && !in_recursion) - { + if (extern_mode && !in_recursion) { std::string m_name = stringf("$extern:%s", log_id(tpl)); - if (!design->module(m_name)) - { + if (!design->module(m_name)) { RTLIL::Module *m = design->addModule(m_name); tpl->cloneInto(m); @@ -940,15 +928,14 @@ struct TechmapWorker log_debug("%s %s.%s to imported %s.\n", mapmsg_prefix.c_str(), log_id(module), log_id(cell), log_id(m_name)); cell->type = m_name; cell->parameters.clear(); - } - else - { + } else { auto msg = stringf("Using template %s for cells of type %s.", log_id(tpl), log_id(cell->type)); if (!log_msg_cache.count(msg)) { log_msg_cache.insert(msg); log("%s\n", msg.c_str()); } - log_debug("%s %s.%s (%s) using %s.\n", mapmsg_prefix.c_str(), log_id(module), log_id(cell), log_id(cell->type), log_id(tpl)); + log_debug("%s %s.%s (%s) using %s.\n", mapmsg_prefix.c_str(), log_id(module), log_id(cell), + log_id(cell->type), log_id(tpl)); techmap_module_worker(design, module, cell, tpl); cell = nullptr; } @@ -974,7 +961,7 @@ struct TechmapWorker }; struct TechmapPass : public Pass { - TechmapPass() : Pass("techmap", "generic technology mapper") { } + TechmapPass() : Pass("techmap", "generic technology mapper") {} void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| @@ -1155,19 +1142,19 @@ struct TechmapPass : public Pass { size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { - if (args[argidx] == "-map" && argidx+1 < args.size()) { + if (args[argidx] == "-map" && argidx + 1 < args.size()) { map_files.push_back(args[++argidx]); continue; } - if (args[argidx] == "-max_iter" && argidx+1 < args.size()) { + if (args[argidx] == "-max_iter" && argidx + 1 < args.size()) { max_iter = atoi(args[++argidx].c_str()); continue; } - if (args[argidx] == "-D" && argidx+1 < args.size()) { + if (args[argidx] == "-D" && argidx + 1 < args.size()) { verilog_frontend += " -D " + args[++argidx]; continue; } - if (args[argidx] == "-I" && argidx+1 < args.size()) { + if (args[argidx] == "-I" && argidx + 1 < args.size()) { verilog_frontend += " -I " + args[++argidx]; continue; } @@ -1203,13 +1190,15 @@ struct TechmapPass : public Pass { if (fn.compare(0, 1, "%") == 0) { if (!saved_designs.count(fn.substr(1))) { delete map; - log_cmd_error("Can't open saved design `%s'.\n", fn.c_str()+1); + log_cmd_error("Can't open saved design `%s'.\n", fn.c_str() + 1); } for (auto mod : saved_designs.at(fn.substr(1))->modules()) if (!map->module(mod->name)) map->add(mod->clone()); } else { - Frontend::frontend_call(map, nullptr, fn, (fn.size() > 3 && fn.compare(fn.size()-3, std::string::npos, ".il") == 0 ? "rtlil" : verilog_frontend)); + Frontend::frontend_call( + map, nullptr, fn, + (fn.size() > 3 && fn.compare(fn.size() - 3, std::string::npos, ".il") == 0 ? "rtlil" : verilog_frontend)); } } @@ -1235,15 +1224,15 @@ struct TechmapPass : public Pass { if (epos == std::string::npos) log_error("Malformed techmap_celltype pattern %s\n", q); for (size_t i = pos + 1; i < epos; i++) { - queue.push_back(name.substr(0, pos) + name[i] + name.substr(epos + 1, std::string::npos)); + queue.push_back(name.substr(0, pos) + name[i] + + name.substr(epos + 1, std::string::npos)); } } } } free(p); } else { - IdString module_name = module->name.begins_with("\\$") ? - module->name.substr(1) : module->name.str(); + IdString module_name = module->name.begins_with("\\$") ? module->name.substr(1) : module->name.str(); celltypeMap[module_name].insert(module->name); } } @@ -1260,14 +1249,13 @@ struct TechmapPass : public Pass { for (auto module : design->modules()) worker.module_queue.insert(module); - while (!worker.module_queue.empty()) - { + while (!worker.module_queue.empty()) { RTLIL::Module *module = *worker.module_queue.begin(); worker.module_queue.erase(module); int module_max_iter = max_iter; bool did_something = true; - pool handled_cells; + pool handled_cells; while (did_something) { did_something = false; if (worker.techmap_module(design, module, map, handled_cells, celltypeMap, false)) diff --git a/passes/techmap/tribuf.cc b/passes/techmap/tribuf.cc index b45cd268a00..c1a2ea64d3a 100644 --- a/passes/techmap/tribuf.cc +++ b/passes/techmap/tribuf.cc @@ -17,8 +17,8 @@ * */ -#include "kernel/yosys.h" #include "kernel/sigtools.h" +#include "kernel/yosys.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN @@ -28,7 +28,8 @@ struct TribufConfig { bool logic_mode; bool formal_mode; - TribufConfig() { + TribufConfig() + { merge_mode = false; logic_mode = false; formal_mode = false; @@ -40,9 +41,7 @@ struct TribufWorker { SigMap sigmap; const TribufConfig &config; - TribufWorker(Module *module, const TribufConfig &config) : module(module), sigmap(module), config(config) - { - } + TribufWorker(Module *module, const TribufConfig &config) : module(module), sigmap(module), config(config) {} static bool is_all_z(SigSpec sig) { @@ -54,7 +53,7 @@ struct TribufWorker { void run() { - dict> tribuf_cells; + dict> tribuf_cells; pool output_bits; if (config.logic_mode || config.formal_mode) @@ -63,16 +62,14 @@ struct TribufWorker { for (auto bit : sigmap(wire)) output_bits.insert(bit); - for (auto cell : module->selected_cells()) - { + for (auto cell : module->selected_cells()) { if (cell->type == ID($tribuf)) tribuf_cells[sigmap(cell->getPort(ID::Y))].push_back(cell); if (cell->type == ID($_TBUF_)) tribuf_cells[sigmap(cell->getPort(ID::Y))].push_back(cell); - if (cell->type.in(ID($mux), ID($_MUX_))) - { + if (cell->type.in(ID($mux), ID($_MUX_))) { IdString en_port = cell->type == ID($mux) ? ID::EN : ID::E; IdString tri_type = cell->type == ID($mux) ? ID($tribuf) : ID($_TBUF_); @@ -104,10 +101,8 @@ struct TribufWorker { } } - if (config.merge_mode || config.logic_mode || config.formal_mode) - { - for (auto &it : tribuf_cells) - { + if (config.merge_mode || config.logic_mode || config.formal_mode) { + for (auto &it : tribuf_cells) { bool no_tribuf = false; if (config.logic_mode && !config.formal_mode) { @@ -162,7 +157,8 @@ struct TribufWorker { module->remove(cell); } - SigSpec muxout = GetSize(pmux_s) > 1 ? module->Pmux(NEW_ID, SigSpec(State::Sx, GetSize(it.first)), pmux_b, pmux_s) : pmux_b; + SigSpec muxout = + GetSize(pmux_s) > 1 ? module->Pmux(NEW_ID, SigSpec(State::Sx, GetSize(it.first)), pmux_b, pmux_s) : pmux_b; if (no_tribuf) module->connect(it.first, muxout); @@ -176,7 +172,7 @@ struct TribufWorker { }; struct TribufPass : public Pass { - TribufPass() : Pass("tribuf", "infer tri-state buffers") { } + TribufPass() : Pass("tribuf", "infer tri-state buffers") {} void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| diff --git a/passes/techmap/zinit.cc b/passes/techmap/zinit.cc index cc208c5169c..79147cd6ae2 100644 --- a/passes/techmap/zinit.cc +++ b/passes/techmap/zinit.cc @@ -17,16 +17,16 @@ * */ -#include "kernel/yosys.h" -#include "kernel/sigtools.h" -#include "kernel/ffinit.h" #include "kernel/ff.h" +#include "kernel/ffinit.h" +#include "kernel/sigtools.h" +#include "kernel/yosys.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct ZinitPass : public Pass { - ZinitPass() : Pass("zinit", "add inverters so all FF are zero-initialized") { } + ZinitPass() : Pass("zinit", "add inverters so all FF are zero-initialized") {} void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| @@ -46,8 +46,7 @@ struct ZinitPass : public Pass { log_header(design, "Executing ZINIT pass (make all FFs zero-initialized).\n"); size_t argidx; - for (argidx = 1; argidx < args.size(); argidx++) - { + for (argidx = 1; argidx < args.size(); argidx++) { if (args[argidx] == "-all") { all_mode = true; continue; @@ -56,20 +55,18 @@ struct ZinitPass : public Pass { } extra_args(args, argidx, design); - for (auto module : design->selected_modules()) - { + for (auto module : design->selected_modules()) { SigMap sigmap(module); FfInitVals initvals(&sigmap, module); - for (auto cell : module->selected_cells()) - { + for (auto cell : module->selected_cells()) { if (!RTLIL::builtin_ff_cell_types().count(cell->type)) continue; FfData ff(&initvals, cell); - log("FF init value for cell %s (%s): %s = %s\n", log_id(cell), log_id(cell->type), - log_signal(ff.sig_q), log_signal(ff.val_init)); + log("FF init value for cell %s (%s): %s = %s\n", log_id(cell), log_id(cell->type), log_signal(ff.sig_q), + log_signal(ff.val_init)); pool bits; for (int i = 0; i < ff.width; i++) {