diff --git a/chips/yosys/passes/CMakeLists.txt b/chips/yosys/passes/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..8e0c4a14d512518c80cf9dc5d10895b942f9c5b9 --- /dev/null +++ b/chips/yosys/passes/CMakeLists.txt @@ -0,0 +1,11 @@ +add_subdirectory(cmds) +add_subdirectory(equiv) +add_subdirectory(fsm) +add_subdirectory(hierarchy) +add_subdirectory(memory) +add_subdirectory(opt) +add_subdirectory(pmgen) +add_subdirectory(proc) +add_subdirectory(sat) +add_subdirectory(techmap) +add_subdirectory(tests) diff --git a/chips/yosys/passes/cmds/CMakeLists.txt b/chips/yosys/passes/cmds/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..60306da054bc33ba4f375e566c4d29ed1690df6b --- /dev/null +++ b/chips/yosys/passes/cmds/CMakeLists.txt @@ -0,0 +1,224 @@ +add_subdirectory(sdc) + +yosys_pass(exec + exec.cc + ENABLE_IF + YOSYS_ENABLE_SPAWN +) +yosys_pass(add + add.cc +) +yosys_pass(delete + delete.cc +) +yosys_pass(design + design.cc + ESSENTIAL +) +yosys_pass(design_equal + design_equal.cc +) +yosys_pass(select + select.cc + PROVIDES + cd + ls + ESSENTIAL +) +yosys_pass(show + show.cc + LIBRARIES + $<${YOSYS_ENABLE_READLINE}:PkgConfig::readline> + $<${YOSYS_ENABLE_EDITLINE}:PkgConfig::editline> + REQUIRES + read_rtlil + read_verilog +) +yosys_pass(viz + viz.cc +) +yosys_pass(rename + rename.cc + REQUIRES + write_verilog +) +yosys_pass(autoname + autoname.cc +) +yosys_pass(connect + connect.cc +) +yosys_pass(optbarriers + optbarriers.cc +) +yosys_pass(scatter + scatter.cc +) +yosys_pass(setundef + setundef.cc +) +yosys_pass(splitnets + splitnets.cc +) +yosys_pass(splitcells + splitcells.cc +) +yosys_pass(stat + stat.cc + REQUIRES + libparse +) +yosys_pass(internal_stats + internal_stats.cc + REQUIRES + libparse +) +yosys_pass(setattr + setattr.cc + PROVIDES + wbflip + setparam + chparam +) +yosys_pass(copy + copy.cc +) +yosys_pass(splice + splice.cc +) +yosys_pass(shuffle + shuffle.cc +) +yosys_pass(scc + scc.cc +) +yosys_pass(glift + glift.cc +) +yosys_pass(torder + torder.cc +) +yosys_pass(logcmd + logcmd.cc +) +yosys_pass(tee + tee.cc +) +yosys_pass(write_file + write_file.cc +) +yosys_pass(connwrappers + connwrappers.cc +) +yosys_pass(trace + trace.cc + PROVIDES + debug +) +yosys_pass(plugin + plugin.cc + INCLUDE_DIRS + ${pybind11_INCLUDE_DIR} + LIBRARIES + $<${YOSYS_ENABLE_PLUGINS}:${Dlfcn_LIBRARIES}> + $<${YOSYS_ENABLE_PYTHON}:Python3::Module> + ESSENTIAL +) +yosys_pass(check + check.cc +) +yosys_pass(edgetypes + edgetypes.cc +) +yosys_pass(portlist + portlist.cc +) +yosys_pass(chformal + chformal.cc +) +yosys_pass(chtype + chtype.cc +) +yosys_pass(blackbox + blackbox.cc +) +yosys_pass(ltp + ltp.cc +) +yosys_pass(linux_perf + linux_perf.cc +) +yosys_pass(bugpoint + bugpoint.cc + REQUIRES + proc_clean + opt_clean + design + ENABLE_IF + YOSYS_ENABLE_SPAWN +) +yosys_pass(scratchpad + scratchpad.cc +) +yosys_pass(logger + logger.cc +) +yosys_pass(printattrs + printattrs.cc +) +yosys_pass(sta + sta.cc +) +yosys_pass(clean_zerowidth + clean_zerowidth.cc +) +yosys_pass(xprop + xprop.cc + REQUIRES + bmuxmap + demuxmap +) +yosys_pass(dft_tag + dft_tag.cc +) +yosys_pass(future + future.cc +) +yosys_pass(box_derive + box_derive.cc +) +yosys_pass(example_dt + example_dt.cc +) +yosys_pass(portarcs + portarcs.cc +) +yosys_pass(wrapcell + wrapcell.cc +) +yosys_pass(setenv + setenv.cc +) +yosys_pass(abstract + abstract.cc +) +yosys_pass(test_select + test_select.cc +) +yosys_pass(timeest + timeest.cc +) +yosys_pass(linecoverage + linecoverage.cc +) +yosys_pass(sort + sort.cc +) +yosys_pass(icell_liberty + icell_liberty.cc +) +yosys_pass(symfpu + symfpu.cc + LIBRARIES + symfpu +) diff --git a/chips/yosys/passes/cmds/abstract.cc b/chips/yosys/passes/cmds/abstract.cc new file mode 100644 index 0000000000000000000000000000000000000000..23d3442138fca166e1b4542add83ec9828040fa1 --- /dev/null +++ b/chips/yosys/passes/cmds/abstract.cc @@ -0,0 +1,535 @@ +#include "kernel/yosys.h" +#include "kernel/celltypes.h" +#include "kernel/ff.h" +#include "kernel/ffinit.h" +#include +#include + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct EnableLogic { + SigBit bit; + bool pol; +}; + +enum SliceIndices { + RtlilSlice, + HdlSlice, +}; + +struct Slice { + SliceIndices indices; + int first; + int last; + + Slice(SliceIndices indices, const std::string &slice) : + indices(indices) + { + if (slice.empty()) + syntax_error(slice); + auto sep = slice.find(':'); + const char *first_begin, *first_end, *last_begin, *last_end; + if (sep == std::string::npos) { + first_begin = last_begin = slice.c_str(); + first_end = last_end = slice.c_str() + slice.length(); + } else { + first_begin = slice.c_str(); + first_end = first_begin + sep; + + last_begin = first_end + 1; + last_end = slice.c_str() + slice.length(); + } + first = parse_index(first_begin, first_end, slice); + last = parse_index(last_begin, last_end, slice); + } + + static int parse_index(const char *begin, const char *end, const std::string &slice) { + int value = 0; + auto result = std::from_chars(begin, end, value, 10); + if (result.ptr != end || result.ptr == begin) + syntax_error(slice); + return value; + } + + static void syntax_error(const std::string &slice) { + log_cmd_error("Invalid slice '%s', expected ':' or ''\n", slice); + } + + std::string to_string() const { + const char *option = indices == RtlilSlice ? "-rtlilslice" : "-slice"; + if (first == last) + return stringf("%s %d", option, first); + else + return stringf("%s %d:%d", option, first, last); + } + + int wire_offset(RTLIL::Wire *wire, int index) const { + int rtl_offset = indices == RtlilSlice ? index : wire->from_hdl_index(index); + if (rtl_offset < 0 || rtl_offset >= wire->width) { + log_error("Slice %s is out of bounds for wire %s in module %s\n", to_string(), wire, wire->module); + } + return rtl_offset; + } + + std::pair wire_range(RTLIL::Wire *wire) const { + int rtl_first = wire_offset(wire, first); + int rtl_last = wire_offset(wire, last); + if (rtl_first > rtl_last) + std::swap(rtl_first, rtl_last); + return {rtl_first, rtl_last + 1}; + } +}; + +void emit_mux_anyseq(Module* mod, const SigSpec& mux_input, const SigSpec& mux_output, EnableLogic enable) { + auto anyseq = mod->Anyseq(NEW_ID, mux_input.size()); + if (enable.bit == (enable.pol ? State::S1 : State::S0)) { + mod->connect(mux_output, anyseq); + } + SigSpec mux_a, mux_b; + if (enable.pol) { + mux_a = mux_input; + mux_b = anyseq; + } else { + mux_a = anyseq; + mux_b = mux_input; + } + (void)mod->addMux(NEW_ID, + mux_a, + mux_b, + enable.bit, + mux_output); +} + +bool abstract_state_port(FfData& ff, SigSpec& port_sig, std::set offsets, EnableLogic enable) { + Wire* abstracted = ff.module->addWire(NEW_ID, offsets.size()); + SigSpec mux_input; + int abstracted_idx = 0; + for (int d_idx = 0; d_idx < ff.width; d_idx++) { + if (offsets.count(d_idx)) { + mux_input.append(port_sig[d_idx]); + port_sig[d_idx].wire = abstracted; + port_sig[d_idx].offset = abstracted_idx; + log_assert(abstracted_idx < abstracted->width); + abstracted_idx++; + } + } + emit_mux_anyseq(ff.module, mux_input, abstracted, enable); + (void)ff.emit(); + return true; +} + +using SelReason=std::variant; + +dict> gather_selected_reps(Module* mod, const std::vector &slices, SigMap& sigmap) { + dict> selected_reps; + + if (slices.empty()) { + // Collect reps for all wire bits of selected wires + for (auto wire : mod->selected_wires()) + for (auto bit : sigmap(wire)) + selected_reps.insert(bit).first->second.push_back(wire); + + // Collect reps for all output wire bits of selected cells + for (auto cell : mod->selected_cells()) + for (auto conn : cell->connections()) + if (cell->output(conn.first)) + for (auto bit : conn.second.bits()) + selected_reps.insert(sigmap(bit)).first->second.push_back(cell); + } else { + if (mod->selected_wires().size() != 1 || !mod->selected_cells().empty()) + log_error("Slices are only supported for single-wire selections\n"); + + auto wire = mod->selected_wires()[0]; + + for (auto slice : slices) { + auto [begin, end] = slice.wire_range(wire); + for (int i = begin; i < end; i++) { + selected_reps.insert(sigmap(SigBit(wire, i))).first->second.push_back(wire); + } + } + + } + return selected_reps; +} + +void explain_selections(const std::vector& reasons) { + for (std::variant reason : reasons) { + if (Cell** cell_reason = std::get_if(&reason)) + log_debug("\tcell %s\n", (*cell_reason)->name); + else if (Wire** wire_reason = std::get_if(&reason)) + log_debug("\twire %s\n", (*wire_reason)->name); + else + log_assert(false && "insane reason variant\n"); + } +} + +unsigned int abstract_state(Module* mod, EnableLogic enable, const std::vector &slices) { + CellTypes ct; + ct.setup_internals_ff(); + SigMap sigmap(mod); + dict> selected_reps = gather_selected_reps(mod, slices, sigmap); + + unsigned int changed = 0; + std::vector ffs; + // Abstract flop inputs if they're driving a selected output rep + for (auto cell : mod->cells()) { + if (!ct.cell_types.count(cell->type)) + continue; + FfData ff(nullptr, cell); + if (ff.has_sr) + log_cmd_error("SR not supported\n"); + ffs.push_back(ff); + } + for (auto ff : ffs) { + // A bit inefficient + std::set offsets_to_abstract; + for (int i = 0; i < GetSize(ff.sig_q); i++) { + SigBit bit = ff.sig_q[i]; + if (selected_reps.count(sigmap(bit))) { + log_debug("Abstracting state for %s.Q[%i] in module %s due to selections:\n", ff.cell, i, mod); + explain_selections(selected_reps.at(sigmap(bit))); + offsets_to_abstract.insert(i); + } + } + + if (offsets_to_abstract.empty()) + continue; + + // Normalize to simpler FF + ff.unmap_ce(); + ff.unmap_srst(); + if (ff.has_arst) + ff.arst_to_aload(); + + bool cell_changed = false; + + if (ff.has_aload) + cell_changed = abstract_state_port(ff, ff.sig_ad, offsets_to_abstract, enable); + cell_changed |= abstract_state_port(ff, ff.sig_d, offsets_to_abstract, enable); + changed += cell_changed; + } + return changed; +} + +bool abstract_value_cell_port(Module* mod, Cell* cell, std::set offsets, IdString port_name, EnableLogic enable) { + Wire* to_abstract = mod->addWire(NEW_ID, offsets.size()); + SigSpec mux_input; + SigSpec mux_output; + const SigSpec& old_port = cell->getPort(port_name); + SigSpec new_port = old_port; + int to_abstract_idx = 0; + for (int port_idx = 0; port_idx < old_port.size(); port_idx++) { + if (offsets.count(port_idx)) { + mux_output.append(old_port[port_idx]); + SigBit in_bit {to_abstract, to_abstract_idx}; + new_port.replace(port_idx, in_bit); + mux_input.append(in_bit); + log_assert(to_abstract_idx < to_abstract->width); + to_abstract_idx++; + } + } + cell->setPort(port_name, new_port); + emit_mux_anyseq(mod, mux_input, mux_output, enable); + return true; +} + +bool abstract_value_mod_port(Module* mod, Wire* wire, std::set offsets, EnableLogic enable) { + Wire* to_abstract = mod->addWire(NEW_ID, wire); + to_abstract->port_input = true; + to_abstract->port_id = wire->port_id; + wire->port_input = false; + wire->port_id = 0; + mod->swap_names(wire, to_abstract); + SigSpec mux_input; + SigSpec mux_output; + SigSpec direct_lhs; + SigSpec direct_rhs; + for (int port_idx = 0; port_idx < wire->width; port_idx++) { + if (offsets.count(port_idx)) { + mux_output.append(SigBit(wire, port_idx)); + mux_input.append(SigBit(to_abstract, port_idx)); + } else { + direct_lhs.append(SigBit(wire, port_idx)); + direct_rhs.append(SigBit(to_abstract, port_idx)); + } + } + mod->connections_.push_back(SigSig(direct_lhs, direct_rhs)); + emit_mux_anyseq(mod, mux_input, mux_output, enable); + return true; +} + +unsigned int abstract_value(Module* mod, EnableLogic enable, const std::vector &slices) { + SigMap sigmap(mod); + dict> selected_reps = gather_selected_reps(mod, slices, sigmap); + unsigned int changed = 0; + std::vector cells_snapshot = mod->cells(); + for (auto cell : cells_snapshot) { + for (auto conn : cell->connections()) + if (cell->output(conn.first)) { + std::set offsets_to_abstract; + for (int i = 0; i < conn.second.size(); i++) { + if (selected_reps.count(sigmap(conn.second[i]))) { + log_debug("Abstracting value for %s.%s[%i] in module %s due to selections:\n", + cell, PooledName(cell->module, conn.first).unescape(), i, mod); + explain_selections(selected_reps.at(sigmap(conn.second[i]))); + offsets_to_abstract.insert(i); + } + } + if (offsets_to_abstract.empty()) + continue; + + changed += abstract_value_cell_port(mod, cell, offsets_to_abstract, conn.first, enable); + } + } + std::vector wires_snapshot = mod->wires(); + for (auto wire : wires_snapshot) + if (wire->port_input) { + std::set offsets_to_abstract; + for (auto bit : SigSpec(wire)) + if (selected_reps.count(sigmap(bit))) { + log_debug("Abstracting value for module input port bit %s in module %s due to selections:\n", + log_signal(bit), mod); + explain_selections(selected_reps.at(sigmap(bit))); + offsets_to_abstract.insert(bit.offset); + } + if (offsets_to_abstract.empty()) + continue; + + changed += abstract_value_mod_port(mod, wire, offsets_to_abstract, enable); + } + return changed; +} + +unsigned int abstract_init(Module* mod, const std::vector &slices) { + unsigned int changed = 0; + FfInitVals initvals; + SigMap sigmap(mod); + dict> selected_reps = gather_selected_reps(mod, slices, sigmap); + initvals.set(&sigmap, mod); + for (auto bit : selected_reps) { + log_debug("Removing init bit on %s due to selections:\n", log_signal(bit.first)); + explain_selections(bit.second); + initvals.remove_init(bit.first); + changed++; + } + return changed; +} + +struct AbstractPass : public Pass { + AbstractPass() : Pass("abstract", "replace signals with abstract values during formal verification") { } + void help() override { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" abstract [mode] [options] [selection]\n"); + log("\n"); + log("Perform abstraction of signals within the design. Abstraction replaces a signal\n"); + log("with an unconstrained abstract value that can take an arbitrary concrete value\n"); + log("during formal verification. The mode and options control when a signal should\n"); + log("be abstracted and how it should affect FFs present in the design.\n"); + log("\n"); + log("Modes:\n"); + log("\n"); + log(" -state\n"); + log(" The selected FFs will be modified to load a new abstract value on every\n"); + log(" active clock edge, async reset or async load. This is independent of any\n"); + log(" clock enable that may be present on the FF cell. Conditional abstraction\n"); + log(" is supported with the -enable/-enabeln options. If present, the condition\n"); + log(" is sampled at the same time as the FF would smaple the correspnding data\n"); + log(" or async-data input whose value will be replaced with an abstract value.\n"); + log("\n"); + log(" The selection can be used to specify which state bits to abstract. For\n"); + log(" each selected wire, any state bits that the wire is driven by will be\n"); + log(" abstracted. For a selected FF cell, all of its state is abstracted.\n"); + log(" Individual bits of a single wire can be abtracted using the -slice and\n"); + log(" -rtlilslice options.\n"); + log("\n"); + log(" -init\n"); + log(" The selected FFs will be modified to have an abstract initial value.\n"); + log(" The -enable/-enablen options are not supported in this mode.\n"); + log(" \n"); + log(" The selection is used in the same way as it is for the -state mode.\n"); + log("\n"); + log(" -value\n"); + log(" The drivers of the selected signals will be replaced with an abstract\n"); + log(" value. In this mode, the abstract value can change at any time and is\n"); + log(" not synchronized to any clock or other signal. Conditional abstraction\n"); + log(" is supported with the -enable/-enablen options. The condition will\n"); + log(" combinationally select between the original driver and the abstract\n"); + log(" value.\n"); + log("\n"); + log(" The selection can be used to specify which output bits of which drivers\n"); + log(" to abtract. For a selected cell, all its output bits will be abstracted.\n"); + log(" For a selected wire, every output bit that is driving the wire will be\n"); + log(" abstracted. Individual bits of a single wire can be abstracted using the\n"); + log(" -slice and -rtlilslice options.\n"); + log("\n"); + log(" -enable \n"); + log(" -enablen \n"); + log(" Perform conditional abstraction with a named single bit wire as\n"); + log(" condition. For -enable the wire is used as an active-high condition and\n"); + log(" for -enablen as an active-low condition. See the description of the\n"); + log(" -state and -value modes for details on how the condition affects the\n"); + log(" abstractions performed by either mode. This option is not supported in\n"); + log(" the -init mode.\n"); + log("\n"); + log(" -initstates \n"); + log(" Perform conditional abstraction for the first time steps. See the\n"); + log(" description of the -state and -value modes for details on how the\n"); + log(" condition affects the abstractions performed by either mode. This option\n"); + log(" is not supported in the -init mode.\n"); + log("\n"); + log(" -slice :\n"); + log(" -slice \n"); + log(" -rtlilslice :\n"); + log(" -rtlilslice \n"); + log(" Limit the abstraction to a slice of a single selected wire. The targeted\n"); + log(" bits of the wire can be given as an inclusive range of indices or as a\n"); + log(" single index. When using the -slice option, the indices are interpreted\n"); + log(" following the source level declaration of the wire. This means the\n"); + log(" -slice option will respect declarations with a non-zero-based index range\n"); + log(" or with reversed bitorder. The -rtlilslice options will always use\n"); + log(" zero-based indexing where index 0 corresponds to the least significant\n"); + log(" bit of the wire.\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override { + log_header(design, "Executing ABSTRACT pass.\n"); + + size_t argidx; + enum Mode { + None, + State, + Initial, + Value, + }; + Mode mode = Mode::None; + enum Enable { + Always = -1, + ActiveLow = false, // ensuring we can use bool(enable) + ActiveHigh = true, + Initstates = 2, + }; + Enable enable = Enable::Always; + int initstates = 0; + std::string enable_name; + std::vector slices; + for (argidx = 1; argidx < args.size(); argidx++) + { + std::string arg = args[argidx]; + if (arg == "-state") { + mode = State; + continue; + } + if (arg == "-init") { + mode = Initial; + continue; + } + if (arg == "-value") { + mode = Value; + continue; + } + if (arg == "-enable" && argidx + 1 < args.size()) { + if (enable != Enable::Always) + log_cmd_error("Multiple enable condition are not supported\n"); + enable_name = args[++argidx]; + enable = Enable::ActiveHigh; + continue; + } + if (arg == "-enablen" && argidx + 1 < args.size()) { + if (enable != Enable::Always) + log_cmd_error("Multiple enable condition are not supported\n"); + enable_name = args[++argidx]; + enable = Enable::ActiveLow; + continue; + } + if (arg == "-initstates" && argidx + 1 < args.size()) { + if (enable != Enable::Always) + log_cmd_error("Multiple enable condition are not supported\n"); + initstates = atoi(args[++argidx].c_str()); + enable = Enable::Initstates; + continue; + } + if (arg == "-slice" && argidx + 1 < args.size()) { + slices.emplace_back(SliceIndices::HdlSlice, args[++argidx]); + continue; + } + if (arg == "-rtlilslice" && argidx + 1 < args.size()) { + slices.emplace_back(SliceIndices::RtlilSlice, args[++argidx]); + continue; + } + break; + } + extra_args(args, argidx, design); + + if (enable != Enable::Always) { + if (mode == Mode::Initial) + log_cmd_error("Conditional initial value abstraction is not supported\n"); + + switch (enable) { + case Enable::Always: + log_assert(false); + YS_FALLTHROUGH + case Enable::ActiveLow: + case Enable::ActiveHigh: { + if (enable_name.empty()) + log_cmd_error("Unspecified enable wire\n"); + } break; + case Enable::Initstates: { + if (initstates <= 0) + log_cmd_error("Number of initial time steps must be positive\n"); + } break; + } + } + + unsigned int changed = 0; + if ((mode == State) || (mode == Value)) { + for (auto mod : design->selected_modules()) { + EnableLogic enable_logic; + + switch (enable) { + case Enable::Always: { + enable_logic = { State::S1, true }; + } break; + case Enable::ActiveLow: + case Enable::ActiveHigh: { + Wire *enable_wire = mod->wire("\\" + enable_name); + if (!enable_wire) + log_cmd_error("Enable wire %s not found in module %s\n", enable_name, mod->name); + if (GetSize(enable_wire) != 1) + log_cmd_error("Enable wire %s must have width 1 but has width %d in module %s\n", + enable_name, GetSize(enable_wire), mod->name); + enable_logic = { enable_wire, enable == Enable::ActiveHigh }; + } break; + case Enable::Initstates: { + SigBit in_init_states = mod->Initstate(NEW_ID); + for (int i = 1; i < initstates; i++) { + Wire *in_init_states_q = mod->addWire(NEW_ID); + mod->addFf(NEW_ID, in_init_states, in_init_states_q); + in_init_states_q->attributes[ID::init] = State::S1; + in_init_states = in_init_states_q; + } + enable_logic = { in_init_states, true }; + } break; + } + if (mode == State) + changed += abstract_state(mod, enable_logic, slices); + else + changed += abstract_value(mod, enable_logic, slices); + } + if (mode == State) + log("Abstracted %d stateful cells.\n", changed); + else + log("Abstracted %d driver ports.\n", changed); + } else if (mode == Initial) { + for (auto mod : design->selected_modules()) { + changed += abstract_init(mod, slices); + } + log("Abstracted %d init bits.\n", changed); + } else { + log_cmd_error("No mode selected, see help message\n"); + } + } +} AbstractPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/add.cc b/chips/yosys/passes/cmds/add.cc new file mode 100644 index 0000000000000000000000000000000000000000..63c786e44061522abd790a5b3dc8fded575d269d --- /dev/null +++ b/chips/yosys/passes/cmds/add.cc @@ -0,0 +1,232 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +static bool is_formal_celltype(const std::string &celltype) +{ + if(celltype == "assert" || celltype == "assume" || celltype == "live" || celltype == "fair" || celltype == "cover") + return true; + else + return false; +} + +static void add_formal(RTLIL::Module *module, const std::string &celltype, const std::string &name, const std::string &enable_name) +{ + std::string escaped_name = RTLIL::escape_id(name); + std::string escaped_enable_name = (enable_name != "") ? RTLIL::escape_id(enable_name) : ""; + RTLIL::Wire *wire = module->wire(escaped_name); + log_assert(is_formal_celltype(celltype)); + + if (wire == nullptr) { + log_error("Could not find wire with name \"%s\".\n", name); + } + else { + RTLIL::Cell *formal_cell = module->addCell(NEW_ID, "$" + celltype); + formal_cell->setPort(ID::A, wire); + if(enable_name == "") { + formal_cell->setPort(ID::EN, State::S1); + log("Added $%s cell for wire \"%s.%s\"\n", celltype, module->name.str(), name); + } + else { + RTLIL::Wire *enable_wire = module->wire(escaped_enable_name); + if(enable_wire == nullptr) + log_error("Could not find enable wire with name \"%s\".\n", enable_name); + + formal_cell->setPort(ID::EN, enable_wire); + log("Added $%s cell for wire \"%s.%s\" enabled by wire \"%s.%s\".\n", celltype, module->name.str(), name, module->name.str(), enable_name); + } + } +} + +static void add_wire(RTLIL::Design *design, RTLIL::Module *module, std::string name, int width, bool flag_input, bool flag_output, bool flag_global) +{ + RTLIL::Wire *wire = nullptr; + name = RTLIL::escape_id(name); + IdString name_ref = design->twines().find(name); + + if (module->count_id(name_ref) != 0) + { + wire = module->wire(name_ref); + + if (wire != nullptr && wire->width != width) + wire = nullptr; + + if (wire != nullptr && wire->port_input != flag_input) + wire = nullptr; + + if (wire != nullptr && wire->port_output != flag_output) + wire = nullptr; + + if (wire == nullptr) + log_cmd_error("Found incompatible object with same name in module %s!\n", module->name); + + log("Module %s already has such an object.\n", module->name); + } + else + { + wire = module->addWire(name, width); + wire->port_input = flag_input; + wire->port_output = flag_output; + + if (flag_input || flag_output) { + module->fixup_ports(); + } + + log("Added wire %s to module %s.\n", name, module->name); + } + + if (!flag_global) + return; + + IdString port_id = design->twines().add(name); + + for (auto cell : module->cells()) + { + RTLIL::Module *mod = design->module(cell->type); + if (mod == nullptr) + continue; + if (!mod->is_selected_whole()) + continue; + if (mod->get_blackbox_attribute()) + continue; + if (cell->hasPort(port_id)) + continue; + + cell->setPort(port_id, wire); + log("Added connection %s to cell %s.%s (%s).\n", name, module->name, cell->name, cell->type); + } +} + +struct AddPass : public Pass { + AddPass() : Pass("add", "add objects to the design") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" add [selection]\n"); + log("\n"); + log("This command adds objects to the design. It operates on all fully selected\n"); + log("modules. So e.g. 'add -wire foo' will add a wire foo to all selected modules.\n"); + log("\n"); + log("\n"); + log(" add {-wire|-input|-inout|-output} [selection]\n"); + log("\n"); + log("Add a wire (input, inout, output port) with the given name and width. The\n"); + log("command will fail if the object exists already and has different properties\n"); + log("than the object to be created.\n"); + log("\n"); + log("\n"); + log(" add -global_input [selection]\n"); + log("\n"); + log("Like 'add -input', but also connect the signal between instances of the\n"); + log("selected modules.\n"); + log("\n"); + log("\n"); + log(" add {-assert|-assume|-live|-fair|-cover} [-if ]\n"); + log("\n"); + log("Add an $assert, $assume, etc. cell connected to a wire named name1, with its\n"); + log("enable signal optionally connected to a wire named name2 (default: 1'b1).\n"); + log("\n"); + log("\n"); + log(" add -mod \n"); + log("\n"); + log("Add module[s] with the specified name[s].\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + std::string command; + std::string arg_name; + std::string enable_name = ""; + bool arg_flag_input = false; + bool arg_flag_output = false; + bool arg_flag_global = false; + bool mod_mode = false; + int arg_width = 0; + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) + { + std::string arg = args[argidx]; + if (arg == "-wire" || arg == "-input" || arg == "-inout" || arg == "-output" || arg == "-global_input") { + if (argidx+2 >= args.size()) + break; + command = "wire"; + if (arg == "-input" || arg == "-inout" || arg == "-global_input") + arg_flag_input = true; + if (arg == "-output" || arg == "-inout") + arg_flag_output = true; + if (arg == "-global_input") + arg_flag_global = true; + arg_name = args[++argidx]; + arg_width = atoi(args[++argidx].c_str()); + continue; + } + if (arg == "-mod") { + mod_mode = true; + argidx++; + break; + } + if (arg.length() > 0 && arg[0] == '-' && is_formal_celltype(arg.substr(1))) { + if (argidx + 1 >= args.size()) + break; + command = arg.substr(1); + arg_name = args[++argidx]; + if (argidx + 2 < args.size() && args[argidx + 1] == "-if") { + enable_name = args[argidx + 2]; + argidx += 2; + } + continue; + } + break; + } + + if (mod_mode) { + for (; argidx < args.size(); argidx++) + design->addModule(RTLIL::escape_id(args[argidx])); + return; + } + + extra_args(args, argidx, design); + + bool selected_anything = false; + for (auto module : design->modules()) + { + log_assert(module != nullptr); + if (!design->selected_whole_module(module->name)) + continue; + if (module->get_bool_attribute(ID::blackbox)) + continue; + + selected_anything = true; + if (is_formal_celltype(command)) + add_formal(module, command, arg_name, enable_name); + else if (command == "wire") + add_wire(design, module, arg_name, arg_width, arg_flag_input, arg_flag_output, arg_flag_global); + } + if (!selected_anything) + log_warning("No modules selected, or only blackboxes. Nothing was added.\n"); + } +} AddPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/autoname.cc b/chips/yosys/passes/cmds/autoname.cc new file mode 100644 index 0000000000000000000000000000000000000000..9dc65f1e5154912a39601d1b6b474fe36e10019a --- /dev/null +++ b/chips/yosys/passes/cmds/autoname.cc @@ -0,0 +1,295 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + + +#include "kernel/yosys.h" +#include +#include +#include + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +// An "object" is a cell or a wire. +// An object is "private" if its name starts with a '$'. +// +// The "autoname" pass renames private objects based on public object names, +// with suffixes added to show the relationship to the public objects. +// The pass chooses the "best" names based on minimizing their "cost". + +// The cost of a new name for a private object is the cost along a path +// to a publicly named object. +struct cost { + // score is a property of one "edge", not of the entire path. + // 0 if the neighbour drives the object, and the wire's fanout otherwise + unsigned int score = UINT_MAX; + // New name length + size_t length = SIZE_MAX; + // Earlier discovered connection wins + int edge_pos = 0; + + auto operator<=>(const cost &) const = default; +}; + +// Endpoints of an "edge" are always a cell index and a wire index. Goofy, I know. +// SigSig connections (module->connections()) don't count +// as neighbors. This means that the equivalent of `assign $w1 = \w2;` won't lead +// to $w1 being renamed. +struct Edge { + // Cell port name at which the wire connects to the cell + IdString port; + int cell; + int wire; + bool cell_is_output; + unsigned int score; + // Edge's position in the edge list + int pos_in_cell; + int pos_in_wire; +}; + +// decide() finds shortest names for every object reachable from a public name, +// cheapest-first. It doesn't apply the renames to the objects yet. +// +// commit() then renames in decide() order, which is topological, so a source +// neighbour always already carries its final uniquify()d name. + +// A selected cell or wire +struct node { + // Exactly one of cell/wire is set + Cell *cell = nullptr; + Wire *wire = nullptr; + vector edges; + // Ignores module->connections() just as the rest of the code + unsigned int fanout = 0; + bool is_public = false; + bool renameable = false; + bool selected = false; + + size_t name_length = 0; + // Node index from which we want to construct the rename + int from_node = -1; + // Cost for the edge from that node + cost c; + // Suffix to append to the name of that node + string suffix; + // Is this name final? + bool decided = false; + + IdString name() const { return cell ? IdString(cell->name) : IdString(wire->name); } +}; + +// Decides the order of exploring neighbors +struct queue_item { + unsigned int score; + size_t length; + int index; + + auto operator<=>(const queue_item &) const = default; +}; + +struct ModuleAutonamer +{ + Module *module; + + // Cells in module order, then wires in the order that they're seen from cells. + // The index doubles as the tie-break between equally good + // proposals for different nodes + vector nodes; + vector decided; + std::priority_queue, std::greater<>> queue; + int renamed = 0; + + ModuleAutonamer(Module *module) : module(module) { build_adjacency(); } + + void build_adjacency() + { + vector cells(module->cells().begin(), module->cells().end()); + // Arbitrary. Kinda just for passing tests without modifying them + for (auto cell : cells | std::views::reverse) + nodes.emplace_back().cell = cell; + int ncells = GetSize(nodes); + + idict wire_ids; + + for (int ci = 0; ci < ncells; ci++) { + Cell *cell = nodes[ci].cell; + for (auto &conn : cell->connections()) { + bool cell_is_output = cell->output(conn.first); + pool seen_in_this_port; + for (auto bit : conn.second) { + if (bit.wire == nullptr) + continue; + int wi = ncells + wire_ids(bit.wire); + if (wi == GetSize(nodes)) + nodes.emplace_back().wire = bit.wire; + nodes[wi].fanout++; + if (!seen_in_this_port.insert(bit.wire).second) + continue; + Edge edge{ + .port = conn.first, + .cell = ci, + .wire = wi, + .cell_is_output = cell_is_output, + .score = 0, // no fanouts are final yet + .pos_in_cell = GetSize(nodes[ci].edges), + .pos_in_wire = GetSize(nodes[wi].edges), + }; + nodes[ci].edges.push_back(edge); + nodes[wi].edges.push_back(edge); + } + } + } + + // Resolve selection before renaming + for (auto &nd : nodes) { + nd.selected = nd.cell ? module->selected(nd.cell) : module->selected(nd.wire); + nd.is_public = nd.name().isPublic(); + nd.renameable = !nd.is_public && (nd.cell || nd.wire->port_id == 0); + if (nd.is_public) + nd.name_length = module->twines().str(nd.name()).size(); + } + + // Only possible once every fanout is known + for (auto &nd : nodes) + for (auto &edge : nd.edges) + edge.score = edge.cell_is_output ? 0 : nodes[edge.wire].fanout; + } + + void offer(int from, int to, const Edge &edge, int edge_pos) + { + node &nd = nodes[to]; + if (!nd.renameable || nd.decided) + return; + std::string port = module->twines().unescaped_str(edge.port); + string suffix = nd.cell + ? stringf("_%s_%s", nd.cell->type.unescape(), port) + : stringf("_%s", port); + cost c{edge.score, nodes[from].name_length + suffix.length(), edge_pos}; + if (c >= nd.c) + return; + nd.c = c; + nd.from_node = from; + nd.name_length = c.length; + nd.suffix = std::move(suffix); + queue.push(queue_item{c.score, c.length, to}); + } + + // Expand a public (or newly decided) node. The name it lends + // is already settled and the neighbour can keep what offer() built + void expand(int n) + { + const node &nd = nodes[n]; + for (auto &edge : nd.edges) + if (nd.cell) + offer(n, edge.wire, edge, edge.pos_in_wire); + else + offer(n, edge.cell, edge, edge.pos_in_cell); + } + + void decide() + { + for (int n = 0; n < GetSize(nodes); n++) + if (nodes[n].is_public) + expand(n); + + while (!queue.empty()) { + int n = queue.top().index; + queue.pop(); + if (nodes[n].decided) + continue; + nodes[n].decided = true; + decided.push_back(n); + expand(n); + } + } + + void append_name(int n, string &out) + { + const node &nd = nodes[n]; + if (nd.is_public || nd.selected) { + out += module->twines().str(nd.name()); + return; + } + append_name(nd.from_node, out); + out += nd.suffix; + } + + void commit(int n) + { + node &nd = nodes[n]; + if (!nd.selected) + return; + string full; + full.reserve(nd.name_length); + append_name(nd.from_node, full); + full += nd.suffix; + IdString name = module->uniquify(full); + if (nd.cell) { + log_debug("Rename cell %s in %s to %s.\n", nd.cell, module, PooledName(module, name).unescape()); + module->rename(nd.cell, name); + } else { + log_debug("Rename wire %s in %s to %s.\n", nd.wire, module, PooledName(module, name).unescape()); + module->rename(nd.wire, name); + } + renamed++; + } + + void run() + { + decide(); + for (int n : decided) + commit(n); + if (renamed > 0) + log("Renamed %d objects in module %s.\n", renamed, module); + } +}; + +struct AutonamePass : public Pass { + AutonamePass() : Pass("autoname", "automatically assign names to objects") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" autoname [selection]\n"); + log("\n"); + log("Assign auto-generated public names to objects with private names (the ones\n"); + log("with $-prefix).\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) + { + // if (args[argidx] == "-foo") { + // foo = true; + // continue; + // } + break; + } + extra_args(args, argidx, design); + + log_header(design, "Executing AUTONAME pass.\n"); + + for (auto module : design->selected_modules()) + ModuleAutonamer(module).run(); + } +} AutonamePass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/blackbox.cc b/chips/yosys/passes/cmds/blackbox.cc new file mode 100644 index 0000000000000000000000000000000000000000..43670efaf24bb8f7b5a852b291df37c3b1deb36b --- /dev/null +++ b/chips/yosys/passes/cmds/blackbox.cc @@ -0,0 +1,58 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct BlackboxPass : public Pass { + BlackboxPass() : Pass("blackbox", "convert modules into blackbox modules") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" blackbox [options] [selection]\n"); + log("\n"); + log("Convert modules into blackbox modules (remove contents and set the blackbox\n"); + log("module attribute).\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) + { + // if (args[argidx] == "-???") { + // continue; + // } + break; + } + extra_args(args, argidx, design); + + for (auto module : design->selected_whole_modules_warn(true)) + { + module->makeblackbox(); + module->set_bool_attribute(ID::blackbox); + module->set_bool_attribute(ID::whitebox, false); + } + } +} BlackboxPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/box_derive.cc b/chips/yosys/passes/cmds/box_derive.cc new file mode 100644 index 0000000000000000000000000000000000000000..d2aeb529ec1d04cba2fee05c5a58a56344726888 --- /dev/null +++ b/chips/yosys/passes/cmds/box_derive.cc @@ -0,0 +1,130 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2024 Martin Povišer + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ +#include "kernel/yosys.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct BoxDerivePass : Pass { + BoxDerivePass() : Pass("box_derive", "derive box modules") {} + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" box_derive [-base ] [-naming_attr ] [selection]\n"); + log("\n"); + log("As part of the assembly of the design hierarchy done by the 'hierarchy' command,\n"); + log("specializations of parametric modules are derived on demand: for each choice of\n"); + log("parameter values appearing in the design, a copy of the parametric module is\n"); + log("derived which is specialized to that choice.\n"); + log("\n"); + log("This derivation process ignores blackboxes and whiteboxes (boxes). To supplement,\n"); + log("this 'box_derive' command can be used to request the derivation of modules based\n"); + log("on box instances appearing in the design, which is desirable in certain use\n"); + log("cases. Only the selected cells are considered as the instances that steer the\n"); + log("derivation process.\n"); + log("\n"); + log(" -base \n"); + log(" instead of deriving the module that directly corresponds to each box\n"); + log(" instance, derive a specialization of (this option applies\n"); + log(" to all selected box cells)\n"); + log("\n"); + log(" -naming_attr \n"); + log(" once a specialization is derived, use the value of the module attribute\n"); + log(" for a name which should be used for the derived module (this\n"); + log(" replaces the internal Yosys naming scheme in which the names of derived\n"); + log(" modules start with '$paramod$')\n"); + log("\n"); + log(" -apply_derived_type\n"); + log(" use the derived modules\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *d) override + { + log_header(d, "Executing BOX_DERIVE pass. (derive modules for boxes)\n"); + + size_t argidx; + std::string naming_attr; + std::string base_name; + bool apply_mode = false; + for (argidx = 1; argidx < args.size(); argidx++) { + if (args[argidx] == "-naming_attr" && argidx + 1 < args.size()) + naming_attr = RTLIL::escape_id(args[++argidx]); + else if (args[argidx] == "-base" && argidx + 1 < args.size()) + base_name = RTLIL::escape_id(args[++argidx]); + else if (args[argidx] == "-apply_derived_type") + apply_mode = true; + else + break; + } + extra_args(args, argidx, d); + + IdString naming_attr_ref = naming_attr.empty() ? IdString::Null : d->twines().find(naming_attr); + + Module *base_override = nullptr; + if (!base_name.empty()) { + IdString base_ref = d->twines().find(base_name); + base_override = base_ref == IdString::Null ? nullptr : d->module(base_ref); + if (!base_override) + log_cmd_error("Base module %s not found.\n", RTLIL::unescape_id(base_name)); + } + + dict>, Module*> done; + + for (auto module : d->selected_modules()) { + for (auto cell : module->selected_cells()) { + Module *inst_module = d->module(cell->type); + if (!inst_module || !inst_module->get_blackbox_attribute()) + continue; + + Module *base = inst_module; + if (base_override) + base = base_override; + + auto index = std::make_pair(IdString(base->name), cell->parameters); + + if (cell->parameters.empty()) + continue; + + if (!done.count(index)) { + IdString derived_type = base->derive(d, cell->parameters); + Module *derived = d->module(derived_type); + log_assert(derived && "Failed to derive module\n"); + log("derived %s\n", d->twines().str(derived_type)); + + if (naming_attr_ref != IdString::Null && derived->has_attribute(naming_attr_ref)) { + std::string new_name = RTLIL::escape_id(derived->get_string_attribute(naming_attr_ref)); + if (new_name.empty() || new_name[0] != '\\') + log_error("Derived module %s cannot be renamed to private name %s.\n", + derived, RTLIL::unescape_id(new_name)); + derived->attributes.erase(naming_attr_ref); + d->rename(derived, std::move(new_name)); + } + + done[index] = derived; + } + + if (apply_mode) + cell->type = cell->twines().copy_from(done[index]->twines(), done[index]->name); + } + } + } +} BoxDerivePass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/bugpoint.cc b/chips/yosys/passes/cmds/bugpoint.cc new file mode 100644 index 0000000000000000000000000000000000000000..576cdafcec7a8ab298812699837229fdc3fb8e86 --- /dev/null +++ b/chips/yosys/passes/cmds/bugpoint.cc @@ -0,0 +1,681 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2018 whitequark + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "backends/rtlil/rtlil_backend.h" + +#if defined(_WIN32) +# include +# define WIFEXITED(x) 1 +# define WIFSIGNALED(x) 0 +# define WIFSTOPPED(x) 0 +# define WEXITSTATUS(x) ((x) & 0xff) +# define WTERMSIG(x) SIGTERM +# define WSTOPSIG(x) 0 +#else +#include +#endif + +USING_YOSYS_NAMESPACE +using namespace RTLIL_BACKEND; +PRIVATE_NAMESPACE_BEGIN + +struct BugpointPass : public Pass { + BugpointPass() : Pass("bugpoint", "minimize testcases") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" bugpoint [options] [-script | -command \"\"]\n"); + log("\n"); + log("This command minimizes the current design that is known to crash Yosys with the\n"); + log("given script into a smaller testcase. It does this by removing an arbitrary part\n"); + log("of the design and recursively invokes a new Yosys process with this modified\n"); + log("design and the same script, repeating these steps while it can find a smaller\n"); + log("design that still causes a crash. Once this command finishes, it replaces the\n"); + log("current design with the smallest testcase it was able to produce.\n"); + log("In order to save the reduced testcase you must write this out to a file with\n"); + log("another command after `bugpoint` like `write_rtlil` or `write_verilog`.\n"); + log("\n"); + log(" -script | -command \"\"\n"); + log(" use this script file or command to crash Yosys. required.\n"); + log("\n"); + log(" -yosys \n"); + log(" use this Yosys binary. if not specified, `yosys` is used.\n"); + log("\n"); + log(" -grep \"\"\n"); + log(" only consider crashes that place this string in the log file.\n"); + log("\n"); + log(" -expect-return \n"); + log(" only consider crashes that return the specified value. e.g. SEGFAULT\n"); + log(" returns a value of 139.\n"); + log("\n"); + log(" -fast\n"); + log(" run `proc_clean; clean -purge` after each minimization step. converges\n"); + log(" faster, but produces larger testcases, and may fail to produce any\n"); + log(" testcase at all if the crash is related to dangling wires.\n"); + log("\n"); + log(" -clean\n"); + log(" run `proc_clean; clean -purge` before checking testcase and after\n"); + log(" finishing. produces smaller and more useful testcases, but may fail to\n"); + log(" produce any testcase at all if the crash is related to dangling wires.\n"); + log("\n"); + log(" -runner \"\"\n"); + log(" child process wrapping command, e.g., \"timeout 30\", or valgrind.\n"); + log("\n"); + log(" -err-grep \"\"\n"); + log(" only consider crashes that print this string on stderr. useful for\n"); + log(" errors outside of yosys.\n"); + log("\n"); + log(" -suffix \"\"\n"); + log(" add suffix to generated file names. useful when running more than one\n"); + log(" instance of bugpoint in the same directory. limited to 8 characters.\n"); + log("\n"); + log("It is possible to constrain which parts of the design will be considered for\n"); + log("removal. Unless one or more of the following options are specified, all parts\n"); + log("will be considered.\n"); + log("\n"); + log(" -modules\n"); + log(" try to remove modules. modules with a (* bugpoint_keep *) attribute\n"); + log(" will be skipped.\n"); + log("\n"); + log(" -ports\n"); + log(" try to remove module ports. ports with a (* bugpoint_keep *) attribute\n"); + log(" will be skipped (useful for clocks, resets, etc.)\n"); + log("\n"); + log(" -cells\n"); + log(" try to remove cells. cells with a (* bugpoint_keep *) attribute will\n"); + log(" be skipped.\n"); + log("\n"); + log(" -connections\n"); + log(" try to reconnect ports to 'x.\n"); + log("\n"); + log(" -processes\n"); + log(" try to remove processes. processes with a (* bugpoint_keep *) attribute\n"); + log(" will be skipped.\n"); + log("\n"); + log(" -assigns\n"); + log(" try to remove process assigns from cases.\n"); + log("\n"); + log(" -updates\n"); + log(" try to remove process updates from syncs.\n"); + log("\n"); + log(" -wires\n"); + log(" try to remove wires. wires with a (* bugpoint_keep *) attribute will be\n"); + log(" skipped.\n"); + log("\n"); + } + + int run_yosys(RTLIL::Design *design, string runner, string yosys_cmd, string yosys_arg, string suffix, bool catch_err) + { + string bugpoint_file = "bugpoint-case"; + if (suffix.size()) + bugpoint_file += stringf(".%.8s", suffix); + + std::ofstream f(bugpoint_file + ".il"); + RTLIL_BACKEND::dump_design(f, design, /*only_selected=*/false, /*flag_m=*/true, /*flag_n=*/false); + f.close(); + + string yosys_cmdline = stringf("%s %s -qq -L %s.log %s %s.il", runner, yosys_cmd, bugpoint_file, yosys_arg, bugpoint_file); + if (catch_err) yosys_cmdline += stringf(" 2>%s.err", bugpoint_file); + auto status = run_command(yosys_cmdline); + // we're not processing lines, which means we're getting raw system() returns + if(WIFEXITED(status)) + return WEXITSTATUS(status); + else if(WIFSIGNALED(status)) + return WTERMSIG(status); + else if(WIFSTOPPED(status)) + return WSTOPSIG(status); + else + return 0; + } + + bool check_logfile(string grep, string suffix, bool err=false) + { + if (grep.empty()) + return true; + + if (grep.size() > 2 && grep.front() == '"' && grep.back() == '"') + grep = grep.substr(1, grep.size() - 2); + + string bugpoint_file = "bugpoint-case"; + if (suffix.size()) + bugpoint_file += stringf(".%.8s", suffix); + bugpoint_file += err ? ".err" : ".log"; + + std::ifstream f(bugpoint_file); + + while (!f.eof()) + { + string line; + getline(f, line); + if (line.find(grep) != std::string::npos) + return true; + } + return false; + } + + bool check_logfiles(string grep, string err_grep, string suffix) + { + return check_logfile(grep, suffix) && check_logfile(err_grep, suffix, true); + } + + std::unique_ptr clean_design(RTLIL::Design *design) + { + auto design_copy = std::make_unique(); + for (auto module : design->modules()) + module->clone(design_copy.get()); + Pass::call(design_copy.get(), "proc_clean -quiet"); + Pass::call(design_copy.get(), "clean -purge"); + return design_copy; + } + + std::unique_ptr simplify_something(RTLIL::Design *design, int &seed, bool stage2, bool modules, bool ports, bool cells, bool connections, bool processes, bool assigns, bool updates, bool wires) + { + auto design_copy = std::make_unique(); + for (auto module : design->modules()) + module->clone(design_copy.get()); + + int index = 0; + if (modules) + { + Module *removed_module = nullptr; + for (auto module : design_copy->modules()) + { + if (module->get_blackbox_attribute()) + continue; + + if (module->get_bool_attribute(ID::bugpoint_keep)) + continue; + + if (index++ == seed) + { + log_header(design, "Trying to remove module %s.\n", module); + removed_module = module; + break; + } + } + if (removed_module) { + design_copy->remove(removed_module); + return design_copy; + } + } + if (ports) + { + for (auto mod : design_copy->modules()) + { + if (mod->get_blackbox_attribute()) + continue; + + for (auto wire : mod->wires()) + { + if (!wire->port_id) + continue; + + if (!stage2 && wire->get_bool_attribute(ID($bugpoint))) + continue; + + if (wire->get_bool_attribute(ID::bugpoint_keep)) + continue; + + if (index++ == seed) + { + log_header(design, "Trying to remove module port %s.\n", wire); + wire->port_input = wire->port_output = false; + mod->fixup_ports(); + return design_copy; + } + } + } + } + if (cells) + { + for (auto mod : design_copy->modules()) + { + if (mod->get_blackbox_attribute()) + continue; + + Cell *removed_cell = nullptr; + for (auto cell : mod->cells()) + { + if (cell->get_bool_attribute(ID::bugpoint_keep)) + continue; + + if (index++ == seed) + { + log_header(design, "Trying to remove cell %s.%s.\n", mod, cell); + removed_cell = cell; + break; + } + } + if (removed_cell) { + mod->remove(removed_cell); + return design_copy; + } + } + } + if (connections) + { + for (auto mod : design_copy->modules()) + { + if (mod->get_blackbox_attribute()) + continue; + + for (auto cell : mod->cells()) + { + for (auto it : cell->connections_) + { + RTLIL::SigSpec port = cell->getPort(it.first); + bool is_undef = port.is_fully_undef(); + bool is_port = port.is_wire() && (port.as_wire()->port_input || port.as_wire()->port_output); + + if(is_undef || (!stage2 && is_port)) + continue; + + if (index++ == seed) + { + log_header(design, "Trying to remove cell port %s.%s.%s.\n", mod, cell, PooledName(design_copy.get(), it.first).unescape()); + RTLIL::SigSpec port_x(State::Sx, port.size()); + cell->unsetPort(it.first); + cell->setPort(it.first, port_x); + return design_copy; + } + + if (!stage2 && (cell->input(it.first) || cell->output(it.first)) && index++ == seed) + { + log_header(design, "Trying to expose cell port %s.%s.%s as module port.\n", mod, cell, PooledName(design_copy.get(), it.first).unescape()); + RTLIL::Wire *wire = mod->addWire(NEW_ID, port.size()); + wire->set_bool_attribute(ID($bugpoint)); + wire->port_input = cell->input(it.first); + wire->port_output = cell->output(it.first); + cell->unsetPort(it.first); + cell->setPort(it.first, wire); + mod->fixup_ports(); + return design_copy; + } + } + } + } + } + if (processes) + { + for (auto mod : design_copy->modules()) + { + if (mod->get_blackbox_attribute()) + continue; + + RTLIL::Process *removed_process = nullptr; + for (auto process : mod->processes) + { + if (process.second->get_bool_attribute(ID::bugpoint_keep)) + continue; + + if (index++ == seed) + { + log_header(design, "Trying to remove process %s.%s.\n", mod, PooledName(design_copy.get(), process.first).unescape()); + removed_process = process.second; + break; + } + } + if (removed_process) { + mod->remove(removed_process); + return design_copy; + } + } + } + if (assigns) + { + for (auto mod : design_copy->modules()) + { + if (mod->get_blackbox_attribute()) + continue; + + for (auto &pr : mod->processes) + { + vector cases = {&pr.second->root_case}; + while (!cases.empty()) + { + RTLIL::CaseRule *cs = cases[0]; + cases.erase(cases.begin()); + for (auto it = cs->actions.begin(); it != cs->actions.end(); ++it) + { + if (index++ == seed) + { + log_header(design, "Trying to remove assign %s %s in %s.%s.\n", log_signal(it->first), log_signal(it->second), mod, PooledName(design_copy.get(), pr.first).unescape()); + cs->actions.erase(it); + return design_copy; + } + } + for (auto &sw : cs->switches) + cases.insert(cases.end(), sw->cases.begin(), sw->cases.end()); + } + } + } + } + if (updates) + { + for (auto mod : design_copy->modules()) + { + if (mod->get_blackbox_attribute()) + continue; + + for (auto &pr : mod->processes) + { + for (auto &sy : pr.second->syncs) + { + for (auto it = sy->actions.begin(); it != sy->actions.end(); ++it) + { + if (index++ == seed) + { + log_header(design, "Trying to remove sync %s update %s %s in %s.%s.\n", log_signal(sy->signal), log_signal(it->first), log_signal(it->second), mod, PooledName(design_copy.get(), pr.first).unescape()); + sy->actions.erase(it); + return design_copy; + } + } + int i = 0; + for (auto it = sy->mem_write_actions.begin(); it != sy->mem_write_actions.end(); ++it, ++i) + { + if (index++ == seed) + { + log_header(design, "Trying to remove sync %s memwr %s %s %s %s in %s.%s.\n", log_signal(sy->signal), PooledName(design_copy.get(), it->memid).unescape(), log_signal(it->address), log_signal(it->data), log_signal(it->enable), mod, PooledName(design_copy.get(), pr.first).unescape()); + sy->mem_write_actions.erase(it); + // Remove the bit for removed action from other actions' priority masks. + for (auto it2 = sy->mem_write_actions.begin(); it2 != sy->mem_write_actions.end(); ++it2) { + auto &mask = it2->priority_mask; + if (GetSize(mask) > i) { + RTLIL::Const::Builder new_mask_builder(GetSize(mask) - 1); + for (int k = 0; k < GetSize(mask); k++) + if (k != i) + new_mask_builder.push_back(mask[k]); + mask = new_mask_builder.build(); + } + } + return design_copy; + } + } + } + } + } + } + if (wires) + { + for (auto mod : design_copy->modules()) + { + if (mod->get_blackbox_attribute()) + continue; + + Wire *removed_wire = nullptr; + for (auto wire : mod->wires()) + { + if (wire->get_bool_attribute(ID::bugpoint_keep)) + continue; + + if (wire->name.begins_with("$delete_wire") || wire->name.begins_with("$auto$bugpoint")) + continue; + + if (index++ == seed) + { + log_header(design, "Trying to remove wire %s.%s.\n", mod, wire); + removed_wire = wire; + break; + } + } + if (removed_wire) { + mod->remove({removed_wire}); + return design_copy; + } + } + } + return nullptr; + } + + void execute(std::vector args, RTLIL::Design *design) override + { + string yosys_cmd = "yosys", yosys_arg, grep, err_grep, runner, suffix; + bool flag_expect_return = false, has_check = false, check_err = false; + int expect_return_value = 0; + bool fast = false, clean = false; + bool modules = false, ports = false, cells = false, connections = false, processes = false, assigns = false, updates = false, wires = false, has_part = false; + + log_header(design, "Executing BUGPOINT pass (minimize testcases).\n"); + log_push(); + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) + { + if (args[argidx] == "-yosys" && argidx + 1 < args.size()) { + yosys_cmd = args[++argidx]; + continue; + } + if (args[argidx] == "-script" && argidx + 1 < args.size()) { + if (!yosys_arg.empty()) + log_cmd_error("A -script or -command option can be only provided once!\n"); + yosys_arg = stringf("-s %s", args[++argidx]); + continue; + } + if (args[argidx] == "-command" && argidx + 1 < args.size()) { + if (!yosys_arg.empty()) + log_cmd_error("A -script or -command option can be only provided once!\n"); + yosys_arg = stringf("-p %s", args[++argidx]); + continue; + } + if (args[argidx] == "-grep" && argidx + 1 < args.size()) { + has_check = true; + grep = args[++argidx]; + continue; + } + if (args[argidx] == "-err-grep" && argidx + 1 < args.size()) { + has_check = true; + check_err = true; + err_grep = args[++argidx]; + continue; + } + if (args[argidx] == "-expect-return") { + flag_expect_return = true; + ++argidx; + if (argidx >= args.size()) + log_cmd_error("No expected return value specified.\n"); + + expect_return_value = atoi(args[argidx].c_str()); + continue; + } + if (args[argidx] == "-fast") { + fast = true; + continue; + } + if (args[argidx] == "-clean") { + clean = true; + continue; + } + if (args[argidx] == "-modules") { + modules = true; + has_part = true; + continue; + } + if (args[argidx] == "-ports") { + ports = true; + has_part = true; + continue; + } + if (args[argidx] == "-cells") { + cells = true; + has_part = true; + continue; + } + if (args[argidx] == "-connections") { + connections = true; + has_part = true; + continue; + } + if (args[argidx] == "-processes") { + processes = true; + has_part = true; + continue; + } + if (args[argidx] == "-assigns") { + assigns = true; + has_part = true; + continue; + } + if (args[argidx] == "-updates") { + updates = true; + has_part = true; + continue; + } + if (args[argidx] == "-wires") { + wires = true; + has_part = true; + continue; + } + if (args[argidx] == "-runner" && argidx + 1 < args.size()) { + runner = args[++argidx]; + if (runner.size() && runner.at(0) == '"') { + log_assert(runner.back() == '"'); + runner = runner.substr(1, runner.size() - 2); + } + continue; + } + if (args[argidx] == "-suffix" && argidx + 1 < args.size()) { + suffix = args[++argidx]; + if (suffix.size() && suffix.at(0) == '"') { + log_assert(suffix.back() == '"'); + suffix = suffix.substr(1, suffix.size() - 2); + } + continue; + } + break; + } + extra_args(args, argidx, design); + + if (yosys_arg.empty()) + log_cmd_error("Missing -script or -command option.\n"); + + if (flag_expect_return && expect_return_value == 0 && !has_check) + log_cmd_error("Nothing to match on for -expect-return 0; change value or use -grep.\n"); + + if (!has_part) + { + modules = true; + ports = true; + cells = true; + connections = true; + processes = true; + assigns = true; + updates = true; + wires = true; + } + + if (!design->full_selection()) + log_cmd_error("This command only operates on fully selected designs!\n"); + + std::unique_ptr crashing_design; + if (clean) + crashing_design = clean_design(design); + int retval = run_yosys(crashing_design ? crashing_design.get() : design, runner, yosys_cmd, yosys_arg, suffix, check_err); + if (flag_expect_return && retval != expect_return_value) + log_cmd_error("The provided script file or command and Yosys binary returned value %d instead of expected %d on this design!\n", retval, expect_return_value); + if (!flag_expect_return && retval == 0) + log_cmd_error("The provided script file or command and Yosys binary do not crash on this design!\n"); + if (!check_logfile(grep, suffix)) + log_cmd_error("The provided grep string is not found in the log file!\n"); + if (!check_logfile(err_grep, suffix, true)) + log_cmd_error("The provided grep string is not found in stderr log!\n"); + + int seed = 0; + bool found_something = false, stage2 = false; + while (true) + { + if (auto simplified = simplify_something(crashing_design ? crashing_design.get() : design, seed, stage2, modules, ports, cells, connections, processes, assigns, updates, wires)) + { + if (fast) + simplified = clean_design(simplified.get()); + + if (clean) + { + auto testcase = clean_design(simplified.get()); + retval = run_yosys(testcase.get(), runner, yosys_cmd, yosys_arg, suffix, check_err); + } + else + { + retval = run_yosys(simplified.get(), runner, yosys_cmd, yosys_arg, suffix, check_err); + } + + bool crashes = false; + if (flag_expect_return && retval == expect_return_value && check_logfiles(grep, err_grep, suffix)) + { + log("Testcase matches expected crash.\n"); + crashes = true; + } + else if (!flag_expect_return && retval == 0) + log("Testcase does not crash.\n"); + else if (!flag_expect_return && check_logfiles(grep, err_grep, suffix)) + { + log("Testcase crashes.\n"); + crashes = true; + } + else + // flag_expect_return && !(retval == expect_return_value && check_logfiles(grep, err_grep, suffix)) + // !flag_expect_return && !(retval == 0 && check_logfiles(grep, err_grep, suffix)) + log("Testcase does not match expected crash.\n"); + + if (crashes) + { + crashing_design = std::move(simplified); + found_something = true; + } + else + { + seed++; + } + } + else + { + seed = 0; + if (found_something) + found_something = false; + else + { + if (!stage2) + { + log("Demoting introduced module ports.\n"); + stage2 = true; + } + else + { + log("Simplifications exhausted.\n"); + break; + } + } + } + } + + if (crashing_design) + { + Pass::call(design, "design -reset"); + if (clean) + crashing_design = clean_design(crashing_design.get()); + for (auto module : crashing_design->modules()) + module->clone(design); + } + + log_pop(); + } +} BugpointPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/check.cc b/chips/yosys/passes/cmds/check.cc new file mode 100644 index 0000000000000000000000000000000000000000..2ffda51023b592538d02aad4ca418b619c8d227b --- /dev/null +++ b/chips/yosys/passes/cmds/check.cc @@ -0,0 +1,605 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "kernel/sigtools.h" +#include "kernel/celledges.h" +#include "kernel/newcelltypes.h" +#include "kernel/utils.h" +#include "kernel/log_help.h" +#include "kernel/mem.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct CheckPass : public Pass { + CheckPass() : Pass("check", "check for obvious problems in the design") { } + bool formatted_help() override { + auto *help = PrettyHelp::get_current(); + help->set_group("passes/status"); + return false; + } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" check [options] [selection]\n"); + log("\n"); + log("This pass identifies the following problems in the current design:\n"); + log("\n"); + log(" - combinatorial loops\n"); + log(" - two or more conflicting drivers for one wire\n"); + log(" - used wires that do not have a driver\n"); + log(" - cells of an internal ($-prefixed) type that is neither a known cell type\n"); + log(" nor a module in the design\n"); + log("\n"); + log("Options:\n"); + log("\n"); + log(" -noinit\n"); + log(" also check for wires which have the 'init' attribute set\n"); + log("\n"); + log(" -initdrv\n"); + log(" also check for wires that have the 'init' attribute set and are not\n"); + log(" driven by an FF cell type\n"); + log("\n"); + log(" -mapped\n"); + log(" also check for internal cells that have not been mapped to cells of the\n"); + log(" target architecture\n"); + log("\n"); + log(" -nolatches\n"); + log(" also check for latch cells ($dlatch, $adlatch, $dlatchsr and their\n"); + log(" $_DLATCH_*/$_DLATCHSR_* mappings) remaining in the design. Use this\n"); + log(" before techmapping in flows that must not emit latches. Cells marked\n"); + log(" with the 'always_latch' attribute are not reported.\n"); + log("\n"); + log(" -latchonly\n"); + log(" check only for latch cells (as listed under -nolatches), skipping all\n"); + log(" other checks.\n"); + log("\n"); + log(" -allow-tbuf\n"); + log(" modify the -mapped behavior to still allow $_TBUF_ cells\n"); + log("\n"); + log(" -assert\n"); + log(" produce a runtime error if any problems are found in the current design\n"); + log("\n"); + log(" -force-detailed-loop-check\n"); + log(" for the detection of combinatorial loops, use a detailed connectivity\n"); + log(" model for all internal cells for which it is available. This disables\n"); + log(" falling back to a simpler overapproximating model for those cells for\n"); + log(" which the detailed model is expected costly.\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + int counter = 0; + bool noinit = false; + bool initdrv = false; + bool mapped = false; + bool nolatches = false; + bool latchonly = false; + bool allow_tbuf = false; + bool assert_mode = false; + bool force_detailed_loop_check = false; + bool suggest_detail = false; + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + if (args[argidx] == "-noinit") { + noinit = true; + continue; + } + if (args[argidx] == "-initdrv") { + initdrv = true; + continue; + } + if (args[argidx] == "-mapped") { + mapped = true; + continue; + } + if (args[argidx] == "-nolatches") { + nolatches = true; + continue; + } + if (args[argidx] == "-latchonly") { + latchonly = true; + continue; + } + if (args[argidx] == "-allow-tbuf") { + allow_tbuf = true; + continue; + } + if (args[argidx] == "-assert") { + assert_mode = true; + continue; + } + if (args[argidx] == "-force-detailed-loop-check") { + force_detailed_loop_check = true; + continue; + } + break; + } + extra_args(args, argidx, design); + + log_header(design, "Executing CHECK pass (checking for obvious problems).\n"); + + for (auto module : design->selected_whole_modules_warn()) + { + log("Checking module %s...\n", module); + + // latch-only mode only flags latches, skipping the (potentially false-positive mid-flow) undriven/driver/loop checks below + if (latchonly) { + for (auto cell : module->cells()) + if (!cell->get_bool_attribute(ID::always_latch) && ( + cell->type.in(ID($dlatch), ID($adlatch), ID($dlatchsr)) || + cell->type.begins_with("$_DLATCH_") || cell->type.begins_with("$_DLATCHSR_"))) { + log_warning("Cell %s.%s is a latch of type %s.\n", module, cell, cell->type.unescape()); + counter++; + } + continue; + } + + SigMap sigmap(module); + dict> wire_drivers; + dict driver_cells; + dict wire_drivers_count; + pool used_wires; + TopoSort> topo; + for (auto &proc_it : module->processes) + { + pool proc_driven_bits; + std::vector all_cases = {&proc_it.second->root_case}; + for (size_t i = 0; i < all_cases.size(); i++) { + for (auto action : all_cases[i]->actions) { + for (auto bit : sigmap(action.first)) { + wire_drivers[bit].push_back( + stringf("action %s <= %s (case rule) in process %s", + log_signal(action.first), log_signal(action.second), module->twines().unescaped_str(proc_it.first))); + if (bit.wire) + proc_driven_bits.insert(bit); + } + + for (auto bit : sigmap(action.second)) + if (bit.wire) used_wires.insert(bit); + } + for (auto switch_ : all_cases[i]->switches) { + for (auto case_ : switch_->cases) { + all_cases.push_back(case_); + for (auto compare : case_->compare) + for (auto bit : sigmap(compare)) + if (bit.wire) used_wires.insert(bit); + } + } + } + for (auto &sync : proc_it.second->syncs) { + for (auto bit : sigmap(sync->signal)) + if (bit.wire) used_wires.insert(bit); + for (auto action : sync->actions) { + for (auto bit : sigmap(action.first)) { + wire_drivers[bit].push_back( + stringf("action %s <= %s (sync rule) in process %s", + log_signal(action.first), log_signal(action.second), module->twines().unescaped_str(proc_it.first))); + if (bit.wire && sync->type != RTLIL::SyncType::STi) + proc_driven_bits.insert(bit); + } + for (auto bit : sigmap(action.second)) + if (bit.wire) used_wires.insert(bit); + } + for (auto memwr : sync->mem_write_actions) { + for (auto bit : sigmap(memwr.address)) + if (bit.wire) used_wires.insert(bit); + for (auto bit : sigmap(memwr.data)) + if (bit.wire) used_wires.insert(bit); + for (auto bit : sigmap(memwr.enable)) + if (bit.wire) used_wires.insert(bit); + } + } + for (auto bit : proc_driven_bits) + wire_drivers_count[bit]++; + } + + struct CircuitEdgesDatabase : AbstractCellEdgesDatabase { + TopoSort> &topo; + SigMap sigmap; + bool force_detail; + + CircuitEdgesDatabase(TopoSort> &topo, SigMap &sigmap, bool force_detail) + : topo(topo), sigmap(sigmap), force_detail(force_detail) {} + + void add_edge(RTLIL::Cell *cell, RTLIL::IdString from_port, int from_bit, + RTLIL::IdString to_port, int to_bit, int) override { + SigSpec from_portsig = cell->getPort(from_port); + SigSpec to_portsig = cell->getPort(to_port); + log_assert(from_bit >= 0 && from_bit < from_portsig.size()); + log_assert(to_bit >= 0 && to_bit < to_portsig.size()); + SigBit from = sigmap(from_portsig[from_bit]); + SigBit to = sigmap(to_portsig[to_bit]); + + if (from.wire && to.wire) + topo.edge(std::make_pair(IdString(from.wire->name), from.offset), std::make_pair(IdString(to.wire->name), to.offset)); + } + + bool detail_costly(Cell *cell) { + // Only those cell types for which the edge data can expode quadratically + // in port widths are those for us to check. + if (!cell->type.in( + ID($add), ID($sub), + ID($shl), ID($shr), ID($sshl), ID($sshr), ID($shift), ID($shiftx), + ID($pmux), ID($bmux))) + return false; + + int in_widths = 0, out_widths = 0; + + if (cell->type.in(ID($pmux), ID($bmux))) { + // We're skipping inputs A and B, since each of their bits contributes only one edge + in_widths = GetSize(cell->getPort(ID::S)); + out_widths = GetSize(cell->getPort(ID::Y)); + } else { + for (auto &conn : cell->connections()) { + if (cell->input(conn.first)) + in_widths += conn.second.size(); + if (cell->output(conn.first)) + out_widths += conn.second.size(); + } + } + + const int threshold = 1024; + + // if the multiplication may overflow we will catch it here + if (in_widths + out_widths >= threshold) + return true; + + if (in_widths * out_widths >= threshold) + return true; + + return false; + } + + bool add_edges_from_cell(Cell *cell) { + if (force_detail || !detail_costly(cell)) { + if (AbstractCellEdgesDatabase::add_edges_from_cell(cell)) + return true; + } + + // We don't have accurate cell edges, do the fallback of all input-output pairs + for (auto &conn : cell->connections()) { + if (cell->input(conn.first)) + for (auto bit : sigmap(conn.second)) + if (bit.wire) + topo.edge(std::make_pair(IdString(bit.wire->name), bit.offset), + std::make_pair(IdString(cell->name), -1)); + + if (cell->output(conn.first)) + for (auto bit : sigmap(conn.second)) + if (bit.wire) + topo.edge(std::make_pair(IdString(cell->name), -1), + std::make_pair(IdString(bit.wire->name), bit.offset)); + } + + // Return false to signify the fallback + return false; + } + }; + + CircuitEdgesDatabase edges_db(topo, sigmap, force_detailed_loop_check); + + pool coarsened_cells; + for (auto cell : module->cells()) + { + if (cell->type.begins_with("$") && !yosys_celltypes.cell_known(cell->type) && design->module(cell->type) == nullptr) { + log_warning("Cell %s.%s has unknown internal type %s.\n", module, cell, cell->type.unescape()); + counter++; + } + + if (mapped && cell->type.begins_with("$") && design->module(cell->type) == nullptr) { + if (allow_tbuf && cell->type == ID($_TBUF_)) goto cell_allowed; + log_warning("Cell %s.%s is an unmapped internal cell of type %s.\n", module, cell, cell->type.unescape()); + counter++; + cell_allowed:; + } + + if ( + nolatches && !cell->get_bool_attribute(ID::always_latch) && ( + cell->type.in(ID($dlatch), ID($adlatch), ID($dlatchsr)) || + cell->type.begins_with("$_DLATCH_") || cell->type.begins_with("$_DLATCHSR_")) + ) { + log_warning("Cell %s.%s is a latch of type %s.\n", module, cell, cell->type.unescape()); + counter++; + } + + for (auto &conn : cell->connections()) { + bool input = cell->input(conn.first); + bool output = cell->output(conn.first); + + SigSpec sig = sigmap(conn.second); + for (int i = 0; i < sig.size(); i++) { + SigBit bit = sig[i]; + + if (input && bit.wire) + used_wires.insert(bit); + if (output && !input && bit.wire) + wire_drivers_count[bit]++; + if (output && (bit.wire || !input)) + wire_drivers[bit].push_back(stringf("port %s[%d] of cell %s (%s)", cell->twines().unescaped_str(conn.first), i, + cell, cell->type.unescape())); + if (output) + driver_cells[bit] = cell; + } + } + + if (yosys_celltypes.cell_evaluable(cell->type) || cell->type.in(ID($mem_v2), ID($memrd), ID($memrd_v2), ID($barrier)) \ + || cell->is_builtin_ff()) { + if (!edges_db.add_edges_from_cell(cell)) + coarsened_cells.insert(cell); + } + } + + pool init_bits; + + for (auto wire : module->wires()) { + if (wire->port_input) { + SigSpec sig = sigmap(wire); + for (int i = 0; i < GetSize(sig); i++) + if (sig[i].wire || !wire->port_output) + wire_drivers[sig[i]].push_back(stringf("module input %s[%d]", wire, i)); + } + if (wire->port_output) + for (auto bit : sigmap(wire)) + if (bit.wire) used_wires.insert(bit); + if (wire->port_input && !wire->port_output) + for (auto bit : sigmap(wire)) + if (bit.wire) wire_drivers_count[bit]++; + if (wire->attributes.count(ID::init)) { + Const initval = wire->attributes.at(ID::init); + for (int i = 0; i < GetSize(initval) && i < GetSize(wire); i++) + if (initval[i] == State::S0 || initval[i] == State::S1) + init_bits.insert(sigmap(SigBit(wire, i))); + if (noinit) { + log_warning("Wire %s.%s has an unprocessed 'init' attribute.\n", module, wire); + counter++; + } + } + } + + for (auto state : {State::S0, State::S1, State::Sx}) + if (wire_drivers.count(state)) { + string message = stringf("Drivers conflicting with a constant %s driver:\n", log_signal(state)); + for (auto str : wire_drivers[state]) + message += stringf(" %s\n", str); + log_warning("%s", message); + counter++; + } + + for (auto it : wire_drivers) + if (wire_drivers_count[it.first] > 1) { + string message = stringf("multiple conflicting drivers for %s.%s:\n", module, log_signal(it.first)); + for (auto str : it.second) + message += stringf(" %s\n", str); + log_warning("%s", message); + counter++; + } + + for (auto bit : used_wires) + if (!wire_drivers.count(bit)) { + log_warning("Wire %s.%s is used but has no driver.\n", module, log_signal(bit)); + counter++; + } + + topo.sort(); + for (auto &loop : topo.loops) { + string message = stringf("found logic loop in module %s:\n", module); + + // `loop` only contains wire bits, or an occasional special helper node for cells for + // which we have done the edges fallback. The cell and its ports that led to an edge are + // a piece of information we need to recover now. For that we need to have the previous + // wire bit of the loop at hand. + SigBit prev; + for (auto it = loop.rbegin(); it != loop.rend(); it++) + if (it->second != -1) { // skip the fallback helper nodes + prev = SigBit(module->wire(it->first), it->second); + break; + } + log_assert(prev != SigBit()); + + for (auto &pair : loop) { + if (pair.second == -1) + continue; // helper node for edges fallback, we can ignore it + + struct MatchingEdgePrinter : AbstractCellEdgesDatabase { + std::string &message; + SigMap &sigmap; + SigBit from, to; + int nhits; + const int HITS_LIMIT = 3; + + MatchingEdgePrinter(std::string &message, SigMap &sigmap, SigBit from, SigBit to) + : message(message), sigmap(sigmap), from(from), to(to), nhits(0) {} + + void add_edge(RTLIL::Cell *cell, RTLIL::IdString from_port, int from_bit, + RTLIL::IdString to_port, int to_bit, int) override { + SigBit edge_from = sigmap(cell->getPort(from_port))[from_bit]; + SigBit edge_to = sigmap(cell->getPort(to_port))[to_bit]; + + if (edge_from == from && edge_to == to && nhits++ < HITS_LIMIT) + message += stringf(" %s[%d] --> %s[%d]\n", cell->twines().unescaped_str(from_port), from_bit, + cell->twines().unescaped_str(to_port), to_bit); + if (nhits == HITS_LIMIT) + message += " ...\n"; + } + }; + + Wire *wire = module->wire(pair.first); + log_assert(wire); + SigBit bit(wire, pair.second); + log_assert(driver_cells.count(bit)); + Cell *driver = driver_cells.at(bit); + + std::string driver_src; + if (driver->has_attribute(ID::src)) { + std::string src_attr = driver->get_src_attribute(); + driver_src = stringf(" source: %s", src_attr); + } + + message += stringf(" cell %s (%s)%s\n", driver, driver->type.unescape(), driver_src); + + if (!coarsened_cells.count(driver)) { + MatchingEdgePrinter printer(message, sigmap, prev, bit); + printer.add_edges_from_cell(driver); + } else { + message += " (cell's internal connectivity overapproximated; loop may be a false positive)\n"; + suggest_detail = true; + } + + if (wire->name.isPublic()) { + std::string wire_src; + if (wire->has_attribute(ID::src)) { + std::string src_attr = wire->get_src_attribute(); + wire_src = stringf(" source: %s", src_attr); + } + message += stringf(" wire %s%s\n", log_signal(SigBit(wire, pair.second)), wire_src); + } + + prev = bit; + } + log_warning("%s", message); + counter++; + } + + if (initdrv) + { + for (auto cell : module->cells()) + { + if (cell->is_builtin_ff() == 0) + continue; + + for (auto bit : sigmap(cell->getPort(ID::Q))) + init_bits.erase(bit); + } + + SigSpec init_sig(init_bits); + init_sig.sort_and_unify(); + + for (auto chunk : init_sig.chunks()) { + log_warning("Wire %s.%s has 'init' attribute and is not driven by an FF cell.\n", module, log_signal(chunk)); + counter++; + } + } + } + + log("Found and reported %d problems.\n", counter); + + if (suggest_detail) + log("Consider re-running with '-force-detailed-loop-check' to rule out false positives.\n"); + + if (assert_mode && counter > 0) + log_error("Found %d problems in 'check -assert'.\n", counter); + } +} CheckPass; + +struct CheckMemPass : public Pass { + CheckMemPass() : Pass("check_mem", "check for obvious memory problems in the design") { } + bool formatted_help() override { + auto *help = PrettyHelp::get_current(); + help->set_group("passes/status"); + + auto content_root = help->get_root(); + + content_root->usage("check_mem [selection]"); + content_root->paragraph( + "This pass identifies the following problems in the current design: " + "addressing invalid memory." + ); + + content_root->option("-non-const", "also check non-const address signals (may produce false-positives)"); + content_root->option("-assert", "produce a runtime error if any problems are found in the current design"); + + return true; + } + void execute(std::vector args, RTLIL::Design *design) override + { + int counter = 0; + bool assert_mode = false; + bool nonconst_mode = false; + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + if (args[argidx] == "-assert") { + assert_mode = true; + continue; + } + if (args[argidx] == "-non-const") { + nonconst_mode = true; + continue; + } + break; + } + + extra_args(args, argidx, design); + + log_header(design, "Executing CHECK_MEM pass.\n"); + + for (auto *module : design->selected_unboxed_modules_warn()) { + for (auto mem : Mem::get_selected_memories(module)) { + int min_addr = mem.mem->start_offset; + int max_addr = mem.mem->size + min_addr - 1; + for (auto &init : mem.inits) { + int start = init.addr.as_int(); + if (start < min_addr) { + log_warning("Mem %s.%s starts at %d but initializes address %d.\n", module, mem.mem, min_addr, start); + counter++; + } + int end = start + (GetSize(init.data) / mem.width) - 1; + if (end > max_addr) { + log_warning("Mem %s.%s ends at %d but initializes address %d.\n", module, mem.mem, max_addr, end); + counter++; + } + } + + auto check_addr = [min_addr, max_addr, &counter, module, &mem, &nonconst_mode](SigSpec &addr_sig, const char* access) { + if (addr_sig.is_fully_const()) { + auto addr = addr_sig.as_int(); + if (addr < min_addr || addr > max_addr) { + log_warning("Mem %s.%s contains entries for addresses %d..%d but %s address %d.\n", module, mem.mem, min_addr, max_addr, access, addr); + counter++; + } + } else if (nonconst_mode) { + // TODO check addr_sig.has_const() for constant MSb/LSb that may change effective min/max + // TODO consider sat solver for variable addresses + int addr_sig_min = 0; + int addr_sig_max = (1 << addr_sig.size()) - 1; + if (min_addr > addr_sig_min || max_addr < addr_sig_max) { + log_warning("Mem %s.%s contains entries for addresses %d..%d but has a potentially dangerous non-const input %s\n", module, mem.mem, min_addr, max_addr, log_signal(addr_sig)); + counter++; + } + } + }; + + // TODO test ABITS and WIDTH? + // TODO can we limit ports via selection? + for (auto &rd_port : mem.rd_ports) + check_addr(rd_port.addr, "reads"); + for (auto &wr_port : mem.wr_ports) + check_addr(wr_port.addr, "writes"); + } + } + + if (assert_mode && counter > 0) + log_error("Found %d problems in 'check_mem -assert'.\n", counter); + } +} CheckMemPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/chformal.cc b/chips/yosys/passes/cmds/chformal.cc new file mode 100644 index 0000000000000000000000000000000000000000..fca943d8656992e7e3645c3825ee13b300ef68cb --- /dev/null +++ b/chips/yosys/passes/cmds/chformal.cc @@ -0,0 +1,448 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "kernel/sigtools.h" +#include "kernel/log_help.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +static RTLIL::IdString formal_flavor(RTLIL::Cell *cell) +{ + if (cell->type != ID($check)) + return cell->type; + + std::string flavor_param = cell->getParam(ID(FLAVOR)).decode_string(); + if (flavor_param == "assert") + return ID($assert); + else if (flavor_param == "assume") + return ID($assume); + else if (flavor_param == "cover") + return ID($cover); + else if (flavor_param == "live") + return ID($live); + else if (flavor_param == "fair") + return ID($fair); + else + log_abort(); +} + +static void set_formal_flavor(RTLIL::Cell *cell, RTLIL::IdString flavor) +{ + if (cell->type != ID($check)) { + cell->type = flavor; + return; + } + + if (flavor == ID($assert)) + cell->setParam(ID(FLAVOR), std::string("assert")); + else if (flavor == ID($assume)) + cell->setParam(ID(FLAVOR), std::string("assume")); + else if (flavor == ID($cover)) + cell->setParam(ID(FLAVOR), std::string("cover")); + else if (flavor == ID($live)) + cell->setParam(ID(FLAVOR), std::string("live")); + else if (flavor == ID($fair)) + cell->setParam(ID(FLAVOR), std::string("fair")); + else + log_abort(); +} + +static bool is_triggered_check_cell(RTLIL::Cell * cell) +{ + return cell->type == ID($check) && cell->getParam(ID(TRG_ENABLE)).as_bool(); +} + +struct ChformalPass : public Pass { + ChformalPass() : Pass("chformal", "change formal constraints of the design") {} + + bool formatted_help() override { + auto *help = PrettyHelp::get_current(); + help->set_group("formal"); + + auto content_root = help->get_root(); + + content_root->usage("chformal [types] [mode] [options] [selection]"); + content_root->paragraph( + "Make changes to the formal constraints of the design. The [types] options " + "the type of constraint to operate on. If none of the following options are " + "given, the command will operate on all constraint types:" + ); + + content_root->option("-assert", "`$assert` cells, representing ``assert(...)`` constraints"); + content_root->option("-assume", "`$assume` cells, representing ``assume(...)`` constraints"); + content_root->option("-live", "`$live` cells, representing ``assert(s_eventually ...)``"); + content_root->option("-fair", "`$fair` cells, representing ``assume(s_eventually ...)``"); + content_root->option("-cover", "`$cover` cells, representing ``cover()`` statements"); + content_root->paragraph( + "Additionally chformal will operate on `$check` cells corresponding to the " + "selected constraint types." + ); + + content_root->paragraph("Exactly one of the following modes must be specified:"); + + content_root->option("-remove", "remove the cells and thus constraints from the design"); + content_root->option("-early", + "bypass FFs that only delay the activation of a constraint. When inputs " + "of the bypassed FFs do not remain stable between clock edges, this may " + "result in unexpected behavior." + ); + content_root->option("-delay ", "delay activation of the constraint by clock cycles"); + content_root->option("-skip ", "ignore activation of the constraint in the first clock cycles"); + auto cover_option = content_root->open_option("-coverenable"); + cover_option->paragraph( + "add cover statements for the enable signals of the constraints" + ); +#ifdef YOSYS_ENABLE_VERIFIC + cover_option->paragraph( + "Note: For the Verific frontend it is currently not guaranteed that a " + "reachable SVA statement corresponds to an active enable signal." + ); +#endif + content_root->option("-assert2assume"); + content_root->option("-assert2cover"); + content_root->option("-assume2assert"); + content_root->option("-live2fair"); + content_root->option("-fair2live", "change the roles of cells as indicated. these options can be combined"); + content_root->option("-lower", + "convert each $check cell into an $assert, $assume, $live, $fair or " + "$cover cell. If the $check cell contains a message, also produce a " + "$print cell." + ); + return true; + } + void execute(std::vector args, RTLIL::Design *design) override + { + bool assert2assume = false; + bool assert2cover = false; + bool assume2assert = false; + bool live2fair = false; + bool fair2live = false; + + pool constr_types; + char mode = 0; + int mode_arg = 0; + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) + { + if (args[argidx] == "-assert") { + constr_types.insert(ID($assert)); + continue; + } + if (args[argidx] == "-assume") { + constr_types.insert(ID($assume)); + continue; + } + if (args[argidx] == "-live") { + constr_types.insert(ID($live)); + continue; + } + if (args[argidx] == "-fair") { + constr_types.insert(ID($fair)); + continue; + } + if (args[argidx] == "-cover") { + constr_types.insert(ID($cover)); + continue; + } + if (mode == 0 && args[argidx] == "-remove") { + mode = 'r'; + continue; + } + if (mode == 0 && args[argidx] == "-early") { + mode = 'e'; + continue; + } + if (mode == 0 && args[argidx] == "-delay" && argidx+1 < args.size()) { + mode = 'd'; + mode_arg = atoi(args[++argidx].c_str()); + continue; + } + if (mode == 0 && args[argidx] == "-skip" && argidx+1 < args.size()) { + mode = 's'; + mode_arg = atoi(args[++argidx].c_str()); + continue; + } + if (mode == 0 && args[argidx] == "-coverenable") { + mode = 'p'; + continue; + } + if ((mode == 0 || mode == 'c') && args[argidx] == "-assert2assume") { + assert2assume = true; + mode = 'c'; + continue; + } + if ((mode == 0 || mode == 'c') && args[argidx] == "-assert2cover") { + assert2cover = true; + mode = 'c'; + continue; + } + if ((mode == 0 || mode == 'c') && args[argidx] == "-assume2assert") { + assume2assert = true; + mode = 'c'; + continue; + } + if ((mode == 0 || mode == 'c') && args[argidx] == "-live2fair") { + live2fair = true; + mode = 'c'; + continue; + } + if ((mode == 0 || mode == 'c') && args[argidx] == "-fair2live") { + fair2live = true; + mode = 'c'; + continue; + } + if (mode == 0 && args[argidx] == "-lower") { + mode = 'l'; + continue; + } + break; + } + extra_args(args, argidx, design); + + if (constr_types.empty()) { + constr_types.insert(ID($assert)); + constr_types.insert(ID($assume)); + constr_types.insert(ID($live)); + constr_types.insert(ID($fair)); + constr_types.insert(ID($cover)); + } + + if (assert2assume && assert2cover) { + log_cmd_error("Cannot use both -assert2assume and -assert2cover.\n"); + } + + if (mode == 0) + log_cmd_error("Mode option is missing.\n"); + + for (auto module : design->selected_modules()) + { + vector constr_cells; + + for (auto cell : module->selected_cells()) + if (constr_types.count(formal_flavor(cell))) + constr_cells.push_back(cell); + + if (mode == 'r') + { + for (auto cell : constr_cells) + module->remove(cell); + } + else + if (mode == 'e') + { + SigMap sigmap(module); + dict>> ffmap; + pool init_zero, init_one; + + for (auto wire : module->wires()) + { + if (wire->attributes.count(ID::init) == 0) + continue; + + SigSpec initsig = sigmap(wire); + Const initval = wire->attributes.at(ID::init); + + for (int i = 0; i < GetSize(initsig) && i < GetSize(initval); i++) { + if (initval[i] == State::S0) + init_zero.insert(initsig[i]); + if (initval[i] == State::S1) + init_one.insert(initsig[i]); + } + } + + for (auto cell : module->selected_cells()) + { + if (cell->type == ID($ff)) { + SigSpec D = sigmap(cell->getPort(ID::D)); + SigSpec Q = sigmap(cell->getPort(ID::Q)); + for (int i = 0; i < GetSize(D); i++) + ffmap[Q[i]] = make_pair(D[i], make_pair(State::Sm, false)); + } + if (cell->type == ID($dff)) { + SigSpec D = sigmap(cell->getPort(ID::D)); + SigSpec Q = sigmap(cell->getPort(ID::Q)); + SigSpec C = sigmap(cell->getPort(ID::CLK)); + bool clockpol = cell->getParam(ID::CLK_POLARITY).as_bool(); + for (int i = 0; i < GetSize(D); i++) + ffmap[Q[i]] = make_pair(D[i], make_pair(C, clockpol)); + } + } + + for (auto cell : constr_cells) + { + if (is_triggered_check_cell(cell)) { + if (cell->getParam(ID::TRG_WIDTH).as_int() != 1) + continue; + cell->setPort(ID::TRG, SigSpec()); + cell->setParam(ID::TRG_ENABLE, false); + cell->setParam(ID::TRG_WIDTH, 0); + cell->setParam(ID::TRG_POLARITY, false); + } + + IdString flavor = formal_flavor(cell); + + while (true) + { + SigSpec A = sigmap(cell->getPort(ID::A)); + SigSpec EN = sigmap(cell->getPort(ID::EN)); + + if (ffmap.count(A) == 0 || ffmap.count(EN) == 0) + break; + + if (!init_zero.count(EN)) { + if (flavor == ID($cover)) break; + if (flavor.in(ID($assert), ID($assume)) && !init_one.count(A)) break; + } + + const auto &A_map = ffmap.at(A); + const auto &EN_map = ffmap.at(EN); + + if (A_map.second != EN_map.second) + break; + + cell->setPort(ID::A, A_map.first); + cell->setPort(ID::EN, EN_map.first); + } + } + } + else + if (mode == 'd') + { + for (auto cell : constr_cells) + { + if (is_triggered_check_cell(cell)) + log_error("Cannot delay edge triggered $check cell %s, run async2sync or clk2fflogic first.\n", cell); + + for (int i = 0; i < mode_arg; i++) + { + SigSpec orig_a = cell->getPort(ID::A); + SigSpec orig_en = cell->getPort(ID::EN); + + Wire *new_a = module->addWire(NEW_ID); + Wire *new_en = module->addWire(NEW_ID); + new_en->attributes[ID::init] = State::S0; + + module->addFf(NEW_ID, orig_a, new_a); + module->addFf(NEW_ID, orig_en, new_en); + + cell->setPort(ID::A, new_a); + cell->setPort(ID::EN, new_en); + } + } + } + else + if (mode == 's') + { + SigSpec en = State::S1; + + for (int i = 0; i < mode_arg; i++) { + Wire *w = module->addWire(NEW_ID); + w->attributes[ID::init] = State::S0; + module->addFf(NEW_ID, en, w); + en = w; + } + + for (auto cell : constr_cells) + cell->setPort(ID::EN, module->LogicAnd(NEW_ID, en, cell->getPort(ID::EN))); + } + else + if (mode =='p') + { + for (auto cell : constr_cells) + { + if (cell->type == ID($check)) { + Cell *cover = module->addCell(NEW_ID_SUFFIX("coverenable"), ID($check)); + cover->attributes = cell->attributes; + cover->parameters = cell->parameters; + cover->setParam(ID(FLAVOR), Const("cover")); + + for (auto const &conn : cell->connections()) + if (!conn.first.in(ID::A, ID::EN)) + cover->setPort(conn.first, conn.second); + cover->setPort(ID::A, cell->getPort(ID::EN)); + cover->setPort(ID::EN, State::S1); + } else { + module->addCover(NEW_ID_SUFFIX("coverenable"), + cell->getPort(ID::EN), State::S1, cell->get_src_attribute()); + } + } + } + else + if (mode == 'c') + { + for (auto cell : constr_cells) { + IdString flavor = formal_flavor(cell); + if (assert2assume && flavor == ID($assert)) + set_formal_flavor(cell, ID($assume)); + if (assert2cover && flavor == ID($assert)) + set_formal_flavor(cell, ID($cover)); + else if (assume2assert && flavor == ID($assume)) + set_formal_flavor(cell, ID($assert)); + else if (live2fair && flavor == ID($live)) + set_formal_flavor(cell, ID($fair)); + else if (fair2live && flavor == ID($fair)) + set_formal_flavor(cell, ID($live)); + } + } + else + if (mode == 'l') + { + for (auto cell : constr_cells) { + if (cell->type != ID($check)) + continue; + + if (is_triggered_check_cell(cell)) + log_error("Cannot lower edge triggered $check cell %s, run async2sync or clk2fflogic first.\n", cell); + + + Cell *plain_cell = module->addCell(NEW_ID, formal_flavor(cell)); + + plain_cell->attributes = cell->attributes; + + SigBit sig_a = cell->getPort(ID::A); + SigBit sig_en = cell->getPort(ID::EN); + + plain_cell->setPort(ID::A, sig_a); + plain_cell->setPort(ID::EN, sig_en); + + if (plain_cell->type.in(ID($assert), ID($assume))) + sig_a = module->Not(NEW_ID, sig_a); + + SigBit combined_en = module->And(NEW_ID, sig_a, sig_en); + + module->swap_names(cell, plain_cell); + + if (cell->getPort(ID::ARGS).empty()) { + module->remove(cell); + } else { + cell->type = ID($print); + cell->setPort(ID::EN, combined_en); + cell->unsetPort(ID::A); + cell->unsetParam(ID(FLAVOR)); + } + } + } + } + } +} ChformalPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/chtype.cc b/chips/yosys/passes/cmds/chtype.cc new file mode 100644 index 0000000000000000000000000000000000000000..c8399a7e2fa1e806e25bb58eaa812176aa957be5 --- /dev/null +++ b/chips/yosys/passes/cmds/chtype.cc @@ -0,0 +1,117 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +static IdString publish(TwinePool &twines, IdString id) { + std::string name = twines.str(id); + if (!name.starts_with("$")) + return id; + log_debug("publishing %s\n", name); + IdString published = twines.add("\\" + name); + log_debug("published %s\n", twines.str(published)); + return published; +} + +static void publish_design(RTLIL::Design* design) { + auto saved_modules = design->modules_; + design->modules_.clear(); + for (auto& [_, mod] : saved_modules) { + IdString new_name = publish(design->twines(), mod->name); + mod->name = new_name; + design->modules_[new_name] = mod; + for (auto* cell : mod->cells()) + cell->type = publish(design->twines(), cell->type); + } +} + + +struct ChtypePass : public Pass { + ChtypePass() : Pass("chtype", "change type of cells in the design") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" chtype [options] [selection]\n"); + log("\n"); + log("Change the types of cells in the design.\n"); + log("\n"); + log(" -set \n"); + log(" set the cell type to the given type\n"); + log("\n"); + log(" -map \n"); + log(" change cells types that match to \n"); + log("\n"); + log(" -publish_icells\n"); + log(" change internal cells types to public types\n"); + log("\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + IdString set_type; + dict map_types; + bool publish_mode = false; + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) + { + if (set_type == IdString() && args[argidx] == "-set" && argidx+1 < args.size()) { + set_type = design->twines().add(RTLIL::escape_id(args[++argidx])); + continue; + } + if (args[argidx] == "-map" && argidx+2 < args.size()) { + IdString old_type = design->twines().add(RTLIL::escape_id(args[++argidx])); + IdString new_type = design->twines().add(RTLIL::escape_id(args[++argidx])); + map_types[old_type] = new_type; + continue; + } + if (args[argidx] == "-publish_icells") { + publish_mode = true; + continue; + } + break; + } + extra_args(args, argidx, design); + + if (publish_mode) + publish_design(design); + + for (auto module : design->selected_modules()) + { + for (auto cell : module->selected_cells()) + { + if (map_types.count(cell->type)) { + cell->type = map_types.at(cell->type); + continue; + } + + if (set_type != IdString()) { + cell->type = set_type; + continue; + } + } + } + } +} ChtypePass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/clean_zerowidth.cc b/chips/yosys/passes/cmds/clean_zerowidth.cc new file mode 100644 index 0000000000000000000000000000000000000000..d48d3a9587da629691e883ceae6e92e8c0803270 --- /dev/null +++ b/chips/yosys/passes/cmds/clean_zerowidth.cc @@ -0,0 +1,210 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2021 Marcelina Kościelnicka + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "kernel/celltypes.h" +#include "kernel/mem.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct CleanZeroWidthPass : public Pass { + CleanZeroWidthPass() : Pass("clean_zerowidth", "clean zero-width connections from the design") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" clean_zerowidth [selection]\n"); + log("\n"); + log("Fixes the selected cells and processes to contain no zero-width connections.\n"); + log("Depending on the cell type, this may be implemented by removing the connection,\n"); + log("widening it to 1-bit, or removing the cell altogether.\n"); + log("\n"); + } + + void clean_case(RTLIL::CaseRule *cs) + { + std::vector new_actions; + for (auto &action : cs->actions) + if (GetSize(action.first) != 0) + new_actions.push_back(action); + std::swap(new_actions, cs->actions); + for (auto sw : cs->switches) + for (auto scs : sw->cases) + clean_case(scs); + } + + void execute(std::vector args, RTLIL::Design *design) override + { + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) + { + break; + } + extra_args(args, argidx, design); + + CellTypes ct; + ct.setup(); + + for (auto module : design->selected_modules()) + { + for (auto cell : module->selected_cells()) + { + if (!ct.cell_known(cell->type)) { + // User-defined cell: just prune zero-width connections. + for (auto it: cell->connections()) { + if (GetSize(it.second) == 0) { + cell->unsetPort(it.first); + } + } + } else if (cell->is_builtin_ff()) { + // Coarse FF cells: remove if WIDTH == 0 (no outputs). + // This will also trigger on fine cells, so use the Q port + // width instead of actual WIDTH parameter. + if (GetSize(cell->getPort(ID::Q)) == 0) { + module->remove(cell); + } + } else if (cell->type.in(ID($pmux), ID($bmux), ID($demux))) { + // Remove altogether if WIDTH is 0, replace with + // a connection if S_WIDTH is 0. + if (cell->getParam(ID::WIDTH).as_int() == 0) { + module->remove(cell); + } + if (cell->getParam(ID::S_WIDTH).as_int() == 0) { + module->connect(cell->getPort(ID::Y), cell->getPort(ID::A)); + module->remove(cell); + } + } else if (cell->type == ID($concat)) { + // If a concat has a zero-width input: replace with direct + // connection to the other input. + if (cell->getParam(ID::A_WIDTH).as_int() == 0) { + module->connect(cell->getPort(ID::Y), cell->getPort(ID::B)); + module->remove(cell); + } else if (cell->getParam(ID::B_WIDTH).as_int() == 0) { + module->connect(cell->getPort(ID::Y), cell->getPort(ID::A)); + module->remove(cell); + } + } else if (cell->type == ID($fsm)) { + // TODO: not supported + } else if (cell->is_mem_cell()) { + // Skip — will be handled below. + } else if (cell->type == ID($lut)) { + // Zero-width LUT is just a const driver. + if (cell->getParam(ID::WIDTH).as_int() == 0) { + module->connect(cell->getPort(ID::Y), cell->getParam(ID::LUT)[0]); + module->remove(cell); + } + } else if (cell->type == ID($sop)) { + // Zero-width SOP is just a const driver. + if (cell->getParam(ID::WIDTH).as_int() == 0) { + // The value is 1 iff DEPTH is non-0. + bool val = cell->getParam(ID::DEPTH).as_int() != 0; + module->connect(cell->getPort(ID::Y), val); + module->remove(cell); + } + } else if (cell->hasParam(ID::WIDTH)) { + // For cells with WIDTH parameter: remove if zero. + if (cell->getParam(ID::WIDTH).as_int() == 0) { + module->remove(cell); + } + } else if (cell->hasParam(ID::Y_WIDTH)) { + // For most operators: remove if Y width is 0, expand + // A and B to 1-bit if their width is 0. + if (cell->getParam(ID::Y_WIDTH).as_int() == 0) { + module->remove(cell); + } else if (cell->type.in(ID($macc), ID($macc_v2))) { + // TODO: fixing zero-width A and B not supported. + } else { + if (cell->getParam(ID::A_WIDTH).as_int() == 0) { + cell->setPort(ID::A, State::S0); + cell->setParam(ID::A_WIDTH, 1); + } + if (cell->hasParam(ID::B_WIDTH) && cell->getParam(ID::B_WIDTH).as_int() == 0) { + cell->setPort(ID::B, State::S0); + cell->setParam(ID::B_WIDTH, 1); + } + } + } + } + + // NOTE: Zero-width switch signals are left alone for processes, as there + // is no simple way of cleaning them up. + for (auto &it: module->processes) { + if (!design->selected(module, it.second)) + continue; + clean_case(&it.second->root_case); + for (auto sync : it.second->syncs) { + std::vector swizzle; + std::vector new_memwr_actions; + for (int i = 0; i < GetSize(sync->mem_write_actions); i++) { + auto &memwr = sync->mem_write_actions[i]; + if (GetSize(memwr.data) == 0) + continue; + if (GetSize(memwr.address) == 0) + memwr.address = State::S0; + RTLIL::Const::Builder new_mask_bits(swizzle.size()); + for (auto x : swizzle) { + new_mask_bits.push_back(memwr.priority_mask[x]); + } + memwr.priority_mask = new_mask_bits.build(); + swizzle.push_back(i); + new_memwr_actions.push_back(memwr); + } + std::swap(new_memwr_actions, sync->mem_write_actions); + std::vector new_actions; + for (auto &action : sync->actions) + if (GetSize(action.first) != 0) + new_actions.push_back(action); + std::swap(new_actions, sync->actions); + } + } + + for (auto &mem : Mem::get_selected_memories(module)) { + if (mem.width == 0) { + mem.remove(); + continue; + } + for (auto &init : mem.inits) { + if (GetSize(init.addr) == 0) { + init.addr = State::S0; + } + } + for (auto &port : mem.rd_ports) { + if (GetSize(port.addr) == 0) { + port.addr = State::S0; + } + } + for (auto &port : mem.wr_ports) { + if (GetSize(port.addr) == 0) { + port.addr = State::S0; + } + } + mem.emit(); + } + + std::vector new_conns; + for (auto &conn : module->connections()) + if (GetSize(conn.first) != 0) + new_conns.push_back(conn); + module->new_connections(new_conns); + } + } +} CleanZeroWidthPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/connect.cc b/chips/yosys/passes/cmds/connect.cc new file mode 100644 index 0000000000000000000000000000000000000000..6dada3ba1ba6f5b5649e903a53ed14af158a3cf5 --- /dev/null +++ b/chips/yosys/passes/cmds/connect.cc @@ -0,0 +1,210 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/register.h" +#include "kernel/rtlil.h" +#include "kernel/sigtools.h" +#include "kernel/celltypes.h" +#include "kernel/log.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +static void unset_drivers(RTLIL::Design *design, RTLIL::Module *module, SigMap &sigmap, RTLIL::SigSpec &sig) +{ + CellTypes ct(design); + + RTLIL::Wire *dummy_wire = module->addWire(NEW_ID, sig.size()); + + for (auto cell : module->cells()) + for (auto &port : cell->connections_) + if (ct.cell_output(cell->type, port.first)) + sigmap(port.second).replace(sig, dummy_wire, &port.second); + + for (auto &conn : module->connections_) + sigmap(conn.first).replace(sig, dummy_wire, &conn.first); +} + +struct ConnectPass : public Pass { + ConnectPass() : Pass("connect", "create or remove connections") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" connect [-nomap] [-nounset] -set [selection]\n"); + log("\n"); + log("Create a connection. This is equivalent to adding the statement 'assign\n"); + log(" = ;' to the Verilog input. Per default, all existing\n"); + log("drivers for are unconnected. This can be overwritten by using\n"); + log("the -nounset option.\n"); + log("\n"); + log("\n"); + log(" connect [-nomap] -unset [selection]\n"); + log("\n"); + log("Unconnect all existing drivers for the specified expression.\n"); + log("\n"); + log("\n"); + log(" connect [-nomap] [-assert] -port [selection]\n"); + log("\n"); + log("Connect the specified cell port to the specified cell port.\n"); + log("\n"); + log("\n"); + log("Per default signal alias names are resolved and all signal names are mapped\n"); + log("the the signal name of the primary driver. Using the -nomap option deactivates\n"); + log("this behavior.\n"); + log("\n"); + log("The connect command operates in one module only. Either only one module must\n"); + log("be selected or an active module must be set using the 'cd' command.\n"); + log("\n"); + log("The -assert option verifies that the connection already exists, instead of\n"); + log("making it.\n"); + log("\n"); + log("This command does not operate on module with processes.\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + bool flag_nounset = false, flag_nomap = false, flag_assert = false; + std::string set_lhs, set_rhs, unset_expr; + std::string port_cell, port_port, port_expr; + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) + { + std::string arg = args[argidx]; + if (arg == "-nounset") { + flag_nounset = true; + continue; + } + if (arg == "-nomap") { + flag_nomap = true; + continue; + } + if (arg == "-assert") { + flag_assert = true; + continue; + } + if (arg == "-set" && argidx+2 < args.size()) { + set_lhs = args[++argidx]; + set_rhs = args[++argidx]; + continue; + } + if (arg == "-unset" && argidx+1 < args.size()) { + unset_expr = args[++argidx]; + continue; + } + if (arg == "-port" && argidx+3 < args.size()) { + port_cell = args[++argidx]; + port_port = args[++argidx]; + port_expr = args[++argidx]; + continue; + } + break; + } + extra_args(args, argidx, design); + + RTLIL::Module *module = nullptr; + for (auto mod : design->selected_modules()) { + if (module != nullptr) + log_cmd_error("Multiple modules selected: %s, %s\n", module, mod); + module = mod; + } + if (module == nullptr) + log_cmd_error("No modules selected.\n"); + if (!module->processes.empty()) + log_cmd_error("Found processes in selected module.\n"); + + SigMap sigmap; + if (!flag_nomap) + for (auto &it : module->connections()) { + std::vector lhs = it.first.to_sigbit_vector(); + std::vector rhs = it.second.to_sigbit_vector(); + for (size_t i = 0; i < lhs.size(); i++) + if (rhs[i].wire != nullptr) + sigmap.add(lhs[i], rhs[i]); + } + + if (!set_lhs.empty()) + { + if (!unset_expr.empty() || !port_cell.empty()) + log_cmd_error("Can't use -set together with -unset and/or -port.\n"); + + if (flag_assert) + log_cmd_error("The -assert option is only supported with -port.\n"); + + RTLIL::SigSpec sig_lhs, sig_rhs; + if (!RTLIL::SigSpec::parse_sel(sig_lhs, design, module, set_lhs)) + log_cmd_error("Failed to parse set lhs expression `%s'.\n", set_lhs); + if (!RTLIL::SigSpec::parse_rhs(sig_lhs, sig_rhs, module, set_rhs)) + log_cmd_error("Failed to parse set rhs expression `%s'.\n", set_rhs); + + sigmap.apply(sig_lhs); + sigmap.apply(sig_rhs); + + if (!flag_nounset) + unset_drivers(design, module, sigmap, sig_lhs); + + module->connect(RTLIL::SigSig(sig_lhs, sig_rhs)); + } + else + if (!unset_expr.empty()) + { + if (!port_cell.empty() || flag_nounset) + log_cmd_error("Can't use -unset together with -port and/or -nounset.\n"); + + if (flag_assert) + log_cmd_error("The -assert option is only supported with -port.\n"); + + RTLIL::SigSpec sig; + if (!RTLIL::SigSpec::parse_sel(sig, design, module, unset_expr)) + log_cmd_error("Failed to parse unset expression `%s'.\n", unset_expr); + + sigmap.apply(sig); + unset_drivers(design, module, sigmap, sig); + } + else + if (!port_cell.empty()) + { + if (flag_nounset) + log_cmd_error("Can't use -port together with -nounset.\n"); + + RTLIL::Cell *port_cell_obj = module->cell(RTLIL::escape_id(port_cell)); + if (port_cell_obj == nullptr) + log_cmd_error("Can't find cell %s.\n", port_cell); + + RTLIL::SigSpec sig; + if (!RTLIL::SigSpec::parse_sel(sig, design, module, port_expr)) + log_cmd_error("Failed to parse port expression `%s'.\n", port_expr); + + IdString port_port_ref = module->twines().add(RTLIL::escape_id(port_port)); + if (!flag_assert) { + port_cell_obj->setPort(port_port_ref, sigmap(sig)); + } else { + SigSpec cur = port_cell_obj->getPort(port_port_ref); + if (sigmap(sig) != sigmap(cur)) { + log_cmd_error("Expected connection not present: expected %s, found %s.\n", log_signal(sig), log_signal(cur)); + } + } + } + else + log_cmd_error("Expected -set, -unset, or -port.\n"); + } +} ConnectPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/connwrappers.cc b/chips/yosys/passes/cmds/connwrappers.cc new file mode 100644 index 0000000000000000000000000000000000000000..40a087482764645dcf71bfe0baee7baf7e3e5e24 --- /dev/null +++ b/chips/yosys/passes/cmds/connwrappers.cc @@ -0,0 +1,203 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/register.h" +#include "kernel/sigtools.h" +#include "kernel/rtlil.h" +#include "kernel/log.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct ConnwrappersWorker +{ + struct portdecl_t { + // key: celltype, portname; + std::string widthparam, signparam; + bool is_signed; + }; + + std::set decl_celltypes; + std::map, portdecl_t> decls; + + void add_port(std::string celltype, std::string portname, std::string widthparam, std::string signparam) + { + std::pair key(RTLIL::escape_id(celltype), RTLIL::escape_id(portname)); + decl_celltypes.insert(key.first); + + if (decls.count(key)) + log_cmd_error("Duplicate port decl: %s %s\n", celltype, portname); + + portdecl_t decl; + decl.widthparam = RTLIL::escape_id(widthparam); + decl.signparam = RTLIL::escape_id(signparam); + decl.is_signed = false; + decls[key] = decl; + } + + void add_port(std::string celltype, std::string portname, std::string widthparam, bool is_signed) + { + std::pair key(RTLIL::escape_id(celltype), RTLIL::escape_id(portname)); + decl_celltypes.insert(key.first); + + if (decls.count(key)) + log_cmd_error("Duplicate port decl: %s %s\n", celltype, portname); + + portdecl_t decl; + decl.widthparam = RTLIL::escape_id(widthparam); + decl.is_signed = is_signed; + decls[key] = decl; + } + + void work(RTLIL::Module *module) + { + std::map> extend_map; + SigMap sigmap(module); + + for (auto cell : module->cells()) + { + if (!decl_celltypes.count(cell->type)) + continue; + + for (auto &conn : cell->connections()) + { + std::pair key(cell->type, module->twines().str(conn.first)); + + if (!decls.count(key)) + continue; + + portdecl_t &decl = decls.at(key); + + IdString widthparam = module->twines().find(decl.widthparam); + if (widthparam == IdString::Null || !cell->parameters.count(widthparam)) + continue; + + IdString signparam = decl.signparam.empty() ? IdString::Null : module->twines().find(decl.signparam); + if (!decl.signparam.empty() && (signparam == IdString::Null || !cell->parameters.count(signparam))) + continue; + + int inner_width = cell->parameters.at(widthparam).as_int(); + int outer_width = conn.second.size(); + bool is_signed = decl.signparam.empty() ? decl.is_signed : cell->parameters.at(signparam).as_bool(); + + if (inner_width >= outer_width) + continue; + + RTLIL::SigSpec sig = sigmap(conn.second); + extend_map[sig.extract(inner_width - 1, 1)] = std::pair(is_signed, + sig.extract(inner_width, outer_width - inner_width)); + } + } + + for (auto cell : module->selected_cells()) + { + for (auto &conn : cell->connections_) + { + std::vector sigbits = sigmap(conn.second).to_sigbit_vector(); + RTLIL::SigSpec old_sig; + + for (size_t i = 0; i < sigbits.size(); i++) + { + if (!extend_map.count(sigbits[i])) + continue; + + bool is_signed = extend_map.at(sigbits[i]).first; + RTLIL::SigSpec extend_sig = extend_map.at(sigbits[i]).second; + + int extend_width = 0; + RTLIL::SigBit extend_bit = is_signed ? sigbits[i] : RTLIL::SigBit(RTLIL::State::S0); + while (extend_width < extend_sig.size() && i + extend_width + 1 < sigbits.size() && + sigbits[i + extend_width + 1] == extend_bit) extend_width++; + + if (extend_width == 0) + continue; + + if (old_sig.size() == 0) + old_sig = conn.second; + + conn.second.replace(i+1, extend_sig.extract(0, extend_width)); + i += extend_width; + } + + if (old_sig.size()) + log("Connected extended bits of %s.%s:%s: %s -> %s\n", module, cell, + PooledName(module, conn.first).unescape(), log_signal(old_sig), log_signal(conn.second)); + } + } + } +}; + +struct ConnwrappersPass : public Pass { + ConnwrappersPass() : Pass("connwrappers", "match width of input-output port pairs") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" connwrappers [options] [selection]\n"); + log("\n"); + log("Wrappers are used in coarse-grain synthesis to wrap cells with smaller ports\n"); + log("in wrapper cells with a (larger) constant port size. I.e. the upper bits\n"); + log("of the wrapper output are signed/unsigned bit extended. This command uses this\n"); + log("knowledge to rewire the inputs of the driven cells to match the output of\n"); + log("the driving cell.\n"); + log("\n"); + log(" -signed \n"); + log(" -unsigned \n"); + log(" consider the specified signed/unsigned wrapper output\n"); + log("\n"); + log(" -port \n"); + log(" use the specified parameter to decide if signed or unsigned\n"); + log("\n"); + log("The options -signed, -unsigned, and -port can be specified multiple times.\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + ConnwrappersWorker worker; + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) + { + if (args[argidx] == "-signed" && argidx+3 < args.size()) { + worker.add_port(args[argidx+1], args[argidx+2], args[argidx+3], true); + argidx += 3; + continue; + } + if (args[argidx] == "-unsigned" && argidx+3 < args.size()) { + worker.add_port(args[argidx+1], args[argidx+2], args[argidx+3], false); + argidx += 3; + continue; + } + if (args[argidx] == "-port" && argidx+4 < args.size()) { + worker.add_port(args[argidx+1], args[argidx+2], args[argidx+3], args[argidx+4]); + argidx += 4; + continue; + } + break; + } + extra_args(args, argidx, design); + + log_header(design, "Executing CONNWRAPPERS pass (connect extended ports of wrapper cells).\n"); + + for (auto module : design->selected_modules()) + worker.work(module); + } +} ConnwrappersPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/copy.cc b/chips/yosys/passes/cmds/copy.cc new file mode 100644 index 0000000000000000000000000000000000000000..f9f3c0246dddd0ca01b8787ff055908dfd7f6de9 --- /dev/null +++ b/chips/yosys/passes/cmds/copy.cc @@ -0,0 +1,58 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/register.h" +#include "kernel/rtlil.h" +#include "kernel/log.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct CopyPass : public Pass { + CopyPass() : Pass("copy", "copy modules in the design") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" copy old_name new_name\n"); + log("\n"); + log("Copy the specified module. Note that selection patterns are not supported\n"); + log("by this command.\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + if (args.size() != 3) + log_cmd_error("Invalid number of arguments!\n"); + + std::string src_name = RTLIL::escape_id(args[1]); + std::string trg_name = RTLIL::escape_id(args[2]); + + IdString src_ref = design->twines().find(src_name); + if (design->module(src_ref) == nullptr) + log_cmd_error("Can't find source module %s.\n", src_name); + + if (design->module(trg_name) != nullptr) + log_cmd_error("Target module name %s already exists.\n", trg_name); + + design->module(src_ref)->clone(design, design->twines().add(trg_name)); + } +} CopyPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/delete.cc b/chips/yosys/passes/cmds/delete.cc new file mode 100644 index 0000000000000000000000000000000000000000..6dba6bab5a549571b650d99abcc20a2af400c733 --- /dev/null +++ b/chips/yosys/passes/cmds/delete.cc @@ -0,0 +1,137 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct DeletePass : public Pass { + DeletePass() : Pass("delete", "delete objects in the design") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" delete [selection]\n"); + log("\n"); + log("Deletes the selected objects. This will also remove entire modules, if the\n"); + log("whole module is selected.\n"); + log("\n"); + log("\n"); + log(" delete {-input|-output|-port} [selection]\n"); + log("\n"); + log("Does not delete any object but removes the input and/or output flag on the\n"); + log("selected wires, thus 'deleting' module ports.\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + bool flag_input = false; + bool flag_output = false; + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) + { + if (args[argidx] == "-input") { + flag_input = true; + continue; + } + if (args[argidx] == "-output") { + flag_output = true; + continue; + } + if (args[argidx] == "-port") { + flag_input = true; + flag_output = true; + continue; + } + break; + } + extra_args(args, argidx, design); + + std::vector delete_mods; + for (auto module : design->modules()) + { + if (design->selected_whole_module(module->name) && !flag_input && !flag_output) { + delete_mods.push_back(module); + continue; + } + + if (!design->selected_module(module->name)) + continue; + + if (flag_input || flag_output) { + for (auto wire : module->wires()) + if (design->selected(module, wire)) { + if (flag_input) + wire->port_input = false; + if (flag_output) + wire->port_output = false; + } + module->fixup_ports(); + continue; + } + + pool delete_wires; + pool delete_cells; + pool delete_procs; + dict delete_mems; + + for (auto wire : module->selected_wires()) + delete_wires.insert(wire); + + for (auto &it : module->memories) + if (design->selected(module, it.second)) + delete_mems[design->twines().str(it.first)] = it.first; + + for (auto cell : module->cells()) { + if (design->selected(module, cell)) + delete_cells.insert(cell); + if (cell->has_memid() && + delete_mems.count(cell->parameters.at(ID::MEMID).decode_string()) != 0) + delete_cells.insert(cell); + } + + for (auto &it : module->processes) + if (design->selected(module, it.second)) + delete_procs.insert(it.second); + + for (auto &it : delete_mems) { + delete module->memories.at(it.second); + module->memories.erase(it.second); + } + + for (auto &it : delete_cells) + module->remove(it); + + for (auto &it : delete_procs) + module->remove(it); + + module->remove(delete_wires); + + module->fixup_ports(); + } + + for (auto mod : delete_mods) { + design->remove(mod); + } + } +} DeletePass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/design.cc b/chips/yosys/passes/cmds/design.cc new file mode 100644 index 0000000000000000000000000000000000000000..d80a2b2abbd5c84a3d69f102d4b190343639f8a6 --- /dev/null +++ b/chips/yosys/passes/cmds/design.cc @@ -0,0 +1,339 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "frontends/verilog/preproc.h" +#include "frontends/ast/ast.h" + +YOSYS_NAMESPACE_BEGIN + +std::map> saved_designs; +std::vector> pushed_designs; + +static std::shared_ptr snapshot(RTLIL::Design *design) +{ + auto copy = std::make_shared(); + design->clone_into(copy.get()); + return copy; +} + +static void copy_modules(RTLIL::Design *dst, const std::vector &modules, const std::string &as_name) +{ + if (!as_name.empty() && modules.size() > 1) + log_cmd_error("Only one module can be selected in combination with -as.\n"); + + for (auto mod : modules) + { + std::string trg_name = as_name.empty() ? mod->name.str() : RTLIL::escape_id(as_name); + IdString trg_ref = dst->twines().add(trg_name); + + if (dst->module(trg_ref) != nullptr) + dst->remove(dst->module(trg_ref)); + + mod->clone(dst, trg_ref); + } +} + +static void import_design(RTLIL::Design *src, RTLIL::Design *dst, std::vector modules, + const std::string &as_name) +{ + std::vector candidates; + for (auto module : modules) + { + if (module->get_bool_attribute(ID::top)) { + candidates.clear(); + candidates.push_back(module); + break; + } + if (!module->get_blackbox_attribute()) + candidates.push_back(module); + } + + if (GetSize(candidates) == 1) + modules = std::move(candidates); + + std::string prefix = RTLIL::escape_id(as_name); + IdString as_name_ref = dst->twines().add(prefix); + + pool queue; + dict done; + + if (dst->module(as_name_ref) != nullptr) + dst->remove(dst->module(as_name_ref)); + + if (GetSize(modules) != 1) + log_cmd_error("No top module found in source design.\n"); + + for (auto mod : modules) + { + log("Importing %s as %s.\n", mod, PooledName(dst, as_name_ref).unescape()); + + RTLIL::Module *t = mod->clone(dst, as_name_ref); + t->attributes.erase(ID::top); + + queue.insert(t); + done[mod->name] = as_name_ref; + } + + while (!queue.empty()) + { + pool old_queue; + old_queue.swap(queue); + + for (auto mod : old_queue) + for (auto cell : mod->cells()) + { + Module *fmod = src->module(src->twines().find(dst->twines().str(cell->type))); + + if (fmod == nullptr) + continue; + + if (done.count(cell->type) == 0) + { + IdString trg_ref = dst->twines().add( + TwineSpec::Suffix{as_name_ref, "." + cell->type.unescape()}); + + log("Importing %s as %s.\n", fmod, PooledName(dst, trg_ref).unescape()); + + if (dst->module(trg_ref) != nullptr) + dst->remove(dst->module(trg_ref)); + + RTLIL::Module *t = fmod->clone(dst, trg_ref); + t->attributes.erase(ID::top); + + queue.insert(t); + done[cell->type] = trg_ref; + } + + cell->type = done.at(cell->type); + } + } +} + +struct DesignPass : public Pass { + DesignPass() : Pass("design", "save, restore and reset current design") { } + void on_shutdown() override { + saved_designs.clear(); + pushed_designs.clear(); + } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" design -reset\n"); + log("\n"); + log("Clear the current design. This also restarts the numbering of generated\n"); + log("names.\n"); + log("\n"); + log("\n"); + log(" design -save \n"); + log("\n"); + log("Save the current design under the given name.\n"); + log("\n"); + log("\n"); + log(" design -stash \n"); + log("\n"); + log("Save the current design under the given name and then clear the current design.\n"); + log("\n"); + log("\n"); + log(" design -push\n"); + log("\n"); + log("Push the current design to the stack and then clear the current design.\n"); + log("\n"); + log("\n"); + log(" design -push-copy\n"); + log("\n"); + log("Push the current design to the stack without clearing the current design.\n"); + log("\n"); + log("\n"); + log(" design -pop\n"); + log("\n"); + log("Reset the current design and pop the last design from the stack.\n"); + log("\n"); + log("\n"); + log(" design -load \n"); + log("\n"); + log("Reset the current design and load the design previously saved under the given\n"); + log("name.\n"); + log("\n"); + log("\n"); + log(" design -copy-from [-as ] \n"); + log("\n"); + log("Copy modules from the specified design into the current one. The selection is\n"); + log("evaluated in the other design.\n"); + log("\n"); + log("\n"); + log(" design -copy-to [-as ] [selection]\n"); + log("\n"); + log("Copy modules from the current design into the specified one.\n"); + log("\n"); + log("\n"); + log(" design -import [-as ] [selection]\n"); + log("\n"); + log("Import the specified design into the current design. The source design must\n"); + log("either have a selected top module or the selection must contain exactly one\n"); + log("module that is then used as top module for this command.\n"); + log("\n"); + log("\n"); + log(" design -reset-vlog\n"); + log("\n"); + log("The Verilog front-end remembers defined macros and top-level declarations\n"); + log("between calls to 'read_verilog'. This command resets this memory.\n"); + log("\n"); + log(" design -delete \n"); + log("\n"); + log("Delete the design previously saved under the given name.\n"); + log("\n"); + + } + enum class Mode { None, Reset, ResetVlog, Push, PushCopy, Pop, Save, Stash, Load, CopyFrom, CopyTo, Import, Delete }; + + void execute(std::vector args, RTLIL::Design *design) override + { + static const std::map flag_modes = { + {"-reset", Mode::Reset}, {"-reset-vlog", Mode::ResetVlog}, + {"-push", Mode::Push}, {"-push-copy", Mode::PushCopy}, {"-pop", Mode::Pop}, + }; + static const std::map named_modes = { + {"-save", Mode::Save}, {"-stash", Mode::Stash}, {"-load", Mode::Load}, + {"-copy-from", Mode::CopyFrom}, {"-copy-to", Mode::CopyTo}, + {"-import", Mode::Import}, {"-delete", Mode::Delete}, + }; + + Mode mode = Mode::None; + std::string name, as_name; + + if (!design) + log_cmd_error("No default design.\n"); + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) + { + const std::string &arg = args[argidx]; + bool has_value = argidx+1 < args.size(); + if (mode == Mode::None && flag_modes.count(arg)) { + mode = flag_modes.at(arg); + continue; + } + if (mode == Mode::None && named_modes.count(arg) && has_value) { + mode = named_modes.at(arg); + name = args[++argidx]; + continue; + } + bool copying = mode == Mode::CopyFrom || mode == Mode::CopyTo || mode == Mode::Import; + if (copying && arg == "-as" && has_value) { + as_name = args[++argidx]; + continue; + } + break; + } + + bool reads_saved = mode == Mode::Load || mode == Mode::CopyFrom || mode == Mode::Import || mode == Mode::Delete; + if (reads_saved && saved_designs.count(name) == 0) + log_cmd_error("No saved design '%s' found!\n", name); + + RTLIL::Design *copy_from_design = nullptr, *copy_to_design = nullptr; + if (mode == Mode::CopyFrom || mode == Mode::Import) { + copy_from_design = saved_designs.at(name).get(); + copy_to_design = design; + } + if (mode == Mode::CopyTo) { + auto &saved = saved_designs[name]; + if (!saved) + saved = std::make_shared(); + copy_from_design = design; + copy_to_design = saved.get(); + } + if (mode == Mode::Import && as_name.empty()) + as_name = name; + + std::vector copy_src_modules; + if (copy_from_design != nullptr) + { + if (copy_from_design != design && argidx == args.size() && mode != Mode::Import) + cmd_error(args, argidx, "Missing selection."); + + if (argidx != args.size()) { + handle_extra_select_args(this, args, argidx, args.size(), copy_from_design); + argidx = args.size(); + } else { + copy_from_design->push_complete_selection(); + } + + for (auto mod : copy_from_design->selected_modules(RTLIL::SELECT_WHOLE_CMDERR, RTLIL::SB_ALL)) + copy_src_modules.push_back(mod); + + copy_from_design->pop_selection(); + } + + extra_args(args, argidx, design, false); + + if (mode == Mode::None) + cmd_error(args, argidx, "Missing mode argument."); + + if (mode == Mode::Pop && pushed_designs.empty()) + log_cmd_error("No pushed designs.\n"); + + switch (mode) { + case Mode::Reset: + design->reset(); + break; + case Mode::ResetVlog: + design->reset_verilog_state(); + break; + case Mode::Push: + pushed_designs.push_back(snapshot(design)); + design->reset(); + break; + case Mode::PushCopy: + pushed_designs.push_back(snapshot(design)); + break; + case Mode::Pop: + design->reset(); + pushed_designs.back()->clone_into(design); + pushed_designs.pop_back(); + break; + case Mode::Save: + saved_designs[name] = snapshot(design); + break; + case Mode::Stash: + saved_designs[name] = snapshot(design); + design->reset(); + break; + case Mode::Load: + design->reset(); + saved_designs.at(name)->clone_into(design); + break; + case Mode::CopyFrom: + case Mode::CopyTo: + copy_modules(copy_to_design, copy_src_modules, as_name); + break; + case Mode::Import: + import_design(copy_from_design, copy_to_design, copy_src_modules, as_name); + break; + case Mode::Delete: + saved_designs.erase(name); + break; + case Mode::None: + log_abort(); + } + } +} DesignPass; + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/design_equal.cc b/chips/yosys/passes/cmds/design_equal.cc new file mode 100644 index 0000000000000000000000000000000000000000..2b8dd9b0cc86baff5a18a5025e4a2ab4baa09056 --- /dev/null +++ b/chips/yosys/passes/cmds/design_equal.cc @@ -0,0 +1,396 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "kernel/rtlil.h" + +YOSYS_NAMESPACE_BEGIN + +class PoolBridge +{ + const TwinePool *pool_a; + const TwinePool *pool_b; + +public: + PoolBridge(RTLIL::Design *design_a, RTLIL::Design *design_b) : + pool_a(&design_a->twines()), pool_b(&design_b->twines()) {} + + IdString a_to_b(IdString ref) const { return pool_b->find_from(*pool_a, ref); } + IdString b_to_a(IdString ref) const { return pool_a->find_from(*pool_b, ref); } + + bool same(IdString a, IdString b) const { return pool_a->str(a) == pool_b->str(b); } +}; + +class ModuleComparator +{ + RTLIL::Module *mod_a; + RTLIL::Module *mod_b; + const PoolBridge &bridge; + +public: + ModuleComparator(RTLIL::Module *mod_a, RTLIL::Module *mod_b, const PoolBridge &bridge) : + mod_a(mod_a), mod_b(mod_b), bridge(bridge) {} + + template + [[noreturn]] void error(FmtString...> fmt, const Args &... args) + { + formatted_error(fmt.format(args...)); + } + [[noreturn]] + void formatted_error(std::string err) + { + log("Module A: %s\n", mod_a); + log_module(mod_a, " "); + log("Module B: %s\n", mod_b); + log_module(mod_b, " "); + log_cmd_error("Designs are different: %s\n", err); + } + + bool compare_sigbit(const RTLIL::SigBit &a, const RTLIL::SigBit &b) + { + if (a.wire == nullptr && b.wire == nullptr) + return a.data == b.data; + if (a.wire != nullptr && b.wire != nullptr) + return bridge.same(a.wire->name, b.wire->name) && a.offset == b.offset; + return false; + } + + bool compare_sigspec(const RTLIL::SigSpec &a, const RTLIL::SigSpec &b) + { + if (a.size() != b.size()) return false; + auto it_a = a.begin(), it_b = b.begin(); + for (; it_a != a.end(); ++it_a, ++it_b) { + if (!compare_sigbit(*it_a, *it_b)) return false; + } + return true; + } + + std::string compare_attributes(const RTLIL::AttrObject *a, const RTLIL::AttrObject *b) + { + for (const auto &it : a->attributes) { + IdString in_b = bridge.a_to_b(it.first); + if (b->attributes.count(in_b) == 0) + return "missing attribute " + std::string(mod_a->twines().unescaped_str(it.first)) + " in second design"; + if (it.second != b->attributes.at(in_b)) + return "attribute " + std::string(mod_a->twines().unescaped_str(it.first)) + " mismatch: " + log_const(it.second) + " != " + log_const(b->attributes.at(in_b)); + } + for (const auto &it : b->attributes) + if (a->attributes.count(bridge.b_to_a(it.first)) == 0) + return "missing attribute " + std::string(mod_b->twines().unescaped_str(it.first)) + " in first design"; + return ""; + } + + std::string compare_wires(const RTLIL::Wire *a, const RTLIL::Wire *b) + { + if (!bridge.same(a->name, b->name)) + return "name mismatch: " + std::string(a->name.unescape()) + " != " + b->name.unescape(); + if (a->width != b->width) + return "width mismatch: " + std::to_string(a->width) + " != " + std::to_string(b->width); + if (a->start_offset != b->start_offset) + return "start_offset mismatch: " + std::to_string(a->start_offset) + " != " + std::to_string(b->start_offset); + if (a->port_id != b->port_id) + return "port_id mismatch: " + std::to_string(a->port_id) + " != " + std::to_string(b->port_id); + if (a->port_input != b->port_input) + return "port_input mismatch: " + std::to_string(a->port_input) + " != " + std::to_string(b->port_input); + if (a->port_output != b->port_output) + return "port_output mismatch: " + std::to_string(a->port_output) + " != " + std::to_string(b->port_output); + if (a->upto != b->upto) + return "upto mismatch: " + std::to_string(a->upto) + " != " + std::to_string(b->upto); + if (a->is_signed != b->is_signed) + return "is_signed mismatch: " + std::to_string(a->is_signed) + " != " + std::to_string(b->is_signed); + if (std::string mismatch = compare_attributes(a, b); !mismatch.empty()) + return mismatch; + return ""; + } + + void check_wires() + { + for (const auto &it : mod_a->wires_) { + RTLIL::Wire *wb = mod_b->wire(bridge.a_to_b(it.first)); + if (!wb) + error("Module %s missing wire %s in second design.\n", mod_a, it.second); + else if (std::string mismatch = compare_wires(it.second, wb); !mismatch.empty()) + error("Module %s wire %s %s.\n", mod_a, it.second, mismatch); + } + for (const auto &it : mod_b->wires_) { + if (!mod_a->wire(bridge.b_to_a(it.first))) + error("Module %s missing wire %s in first design.\n", mod_b, it.second); + } + } + + std::string compare_memories(const RTLIL::Memory *a, const RTLIL::Memory *b) + { + if (!bridge.same(a->name, b->name)) + return "name mismatch: " + std::string(a->name.unescape()) + " != " + b->name.unescape(); + if (a->width != b->width) + return "width mismatch: " + std::to_string(a->width) + " != " + std::to_string(b->width); + if (a->start_offset != b->start_offset) + return "start_offset mismatch: " + std::to_string(a->start_offset) + " != " + std::to_string(b->start_offset); + if (a->size != b->size) + return "size mismatch: " + std::to_string(a->size) + " != " + std::to_string(b->size); + if (std::string mismatch = compare_attributes(a, b); !mismatch.empty()) + return mismatch; + return ""; + } + + std::string compare_cells(const RTLIL::Cell *a, const RTLIL::Cell *b) + { + if (!bridge.same(a->name, b->name)) + return "name mismatch: " + std::string(a->name.unescape()) + " != " + b->name.unescape(); + if (!bridge.same(a->type, b->type)) + return "type mismatch: " + std::string(a->type.unescape()) + " != " + b->type.unescape(); + if (std::string mismatch = compare_attributes(a, b); !mismatch.empty()) + return mismatch; + + for (const auto &it : a->parameters) { + IdString in_b = bridge.a_to_b(it.first); + if (b->parameters.count(in_b) == 0) + return "parameter mismatch: missing parameter " + std::string(mod_a->twines().unescaped_str(it.first)) + " in second design"; + if (it.second != b->parameters.at(in_b)) + return "parameter mismatch: " + std::string(mod_a->twines().unescaped_str(it.first)) + " mismatch: " + log_const(it.second) + " != " + log_const(b->parameters.at(in_b)); + } + for (const auto &it : b->parameters) + if (a->parameters.count(bridge.b_to_a(it.first)) == 0) + return "parameter mismatch: missing parameter " + std::string(mod_b->twines().unescaped_str(it.first)) + " in first design"; + + for (const auto &it : a->connections()) { + IdString in_b = bridge.a_to_b(it.first); + if (b->connections().count(in_b) == 0) + return "connection mismatch: missing connection " + a->twines().unescaped_str(it.first) + " in second design"; + if (!compare_sigspec(it.second, b->connections().at(in_b))) + return "connection " + a->twines().unescaped_str(it.first) + " mismatch: " + log_signal(it.second) + " != " + log_signal(b->connections().at(in_b)); + } + for (const auto &it : b->connections()) + if (a->connections().count(bridge.b_to_a(it.first)) == 0) + return "connection mismatch: missing connection " + a->twines().unescaped_str(it.first) + " in first design"; + + return ""; + } + + void check_cells() + { + for (const auto &it : mod_a->cells_) { + RTLIL::Cell *cb = mod_b->cell(bridge.a_to_b(it.first)); + if (!cb) + error("Module %s missing cell %s in second design.\n", mod_a, it.second); + else if (std::string mismatch = compare_cells(it.second, cb); !mismatch.empty()) + error("Module %s cell %s %s.\n", mod_a, it.second, mismatch); + } + for (const auto &it : mod_b->cells_) { + if (!mod_a->cell(bridge.b_to_a(it.first))) + error("Module %s missing cell %s in first design.\n", mod_b, it.second); + } + } + + void check_memories() + { + for (const auto &it : mod_a->memories) { + IdString in_b = bridge.a_to_b(it.first); + if (mod_b->memories.count(in_b) == 0) + error("Module %s missing memory %s in second design.\n", mod_a, it.second); + if (std::string mismatch = compare_memories(it.second, mod_b->memories.at(in_b)); !mismatch.empty()) + error("Module %s memory %s %s.\n", mod_a, it.second, mismatch); + } + for (const auto &it : mod_b->memories) + if (mod_a->memories.count(bridge.b_to_a(it.first)) == 0) + error("Module %s missing memory %s in first design.\n", mod_b, it.second); + } + + std::string compare_case_rules(const RTLIL::CaseRule *a, const RTLIL::CaseRule *b) + { + if (std::string mismatch = compare_attributes(a, b); !mismatch.empty()) return mismatch; + + if (a->compare.size() != b->compare.size()) + return "compare size mismatch: " + std::to_string(a->compare.size()) + " != " + std::to_string(b->compare.size()); + for (size_t i = 0; i < a->compare.size(); i++) + if (!compare_sigspec(a->compare[i], b->compare[i])) + return "compare " + std::to_string(i) + " mismatch: " + log_signal(a->compare[i]) + " != " + log_signal(b->compare[i]); + + if (a->actions.size() != b->actions.size()) + return "actions size mismatch: " + std::to_string(a->actions.size()) + " != " + std::to_string(b->actions.size()); + for (size_t i = 0; i < a->actions.size(); i++) { + if (!compare_sigspec(a->actions[i].first, b->actions[i].first)) + return "action " + std::to_string(i) + " lhs mismatch: " + log_signal(a->actions[i].first) + " != " + log_signal(b->actions[i].first); + if (!compare_sigspec(a->actions[i].second, b->actions[i].second)) + return "action " + std::to_string(i) + " rhs mismatch: " + log_signal(a->actions[i].second) + " != " + log_signal(b->actions[i].second); + } + + if (a->switches.size() != b->switches.size()) + return "switches size mismatch: " + std::to_string(a->switches.size()) + " != " + std::to_string(b->switches.size()); + for (size_t i = 0; i < a->switches.size(); i++) + if (std::string mismatch = compare_switch_rules(a->switches[i], b->switches[i]); !mismatch.empty()) + return "switch " + std::to_string(i) + " " + mismatch; + + return ""; + } + + std::string compare_switch_rules(const RTLIL::SwitchRule *a, const RTLIL::SwitchRule *b) + { + if (std::string mismatch = compare_attributes(a, b); !mismatch.empty()) + return mismatch; + if (!compare_sigspec(a->signal, b->signal)) + return "signal mismatch: " + log_signal(a->signal) + " != " + log_signal(b->signal); + + if (a->cases.size() != b->cases.size()) + return "cases size mismatch: " + std::to_string(a->cases.size()) + " != " + std::to_string(b->cases.size()); + for (size_t i = 0; i < a->cases.size(); i++) + if (std::string mismatch = compare_case_rules(a->cases[i], b->cases[i]); !mismatch.empty()) + return "case " + std::to_string(i) + " " + mismatch; + + return ""; + } + + std::string compare_sync_rules(const RTLIL::SyncRule *a, const RTLIL::SyncRule *b) + { + if (a->type != b->type) + return "type mismatch: " + std::to_string(a->type) + " != " + std::to_string(b->type); + if (!compare_sigspec(a->signal, b->signal)) + return "signal mismatch: " + log_signal(a->signal) + " != " + log_signal(b->signal); + if (a->actions.size() != b->actions.size()) + return "actions size mismatch: " + std::to_string(a->actions.size()) + " != " + std::to_string(b->actions.size()); + for (size_t i = 0; i < a->actions.size(); i++) { + if (!compare_sigspec(a->actions[i].first, b->actions[i].first)) + return "action " + std::to_string(i) + " lhs mismatch: " + log_signal(a->actions[i].first) + " != " + log_signal(b->actions[i].first); + if (!compare_sigspec(a->actions[i].second, b->actions[i].second)) + return "action " + std::to_string(i) + " rhs mismatch: " + log_signal(a->actions[i].second) + " != " + log_signal(b->actions[i].second); + } + if (a->mem_write_actions.size() != b->mem_write_actions.size()) + return "mem_write_actions size mismatch: " + std::to_string(a->mem_write_actions.size()) + " != " + std::to_string(b->mem_write_actions.size()); + for (size_t i = 0; i < a->mem_write_actions.size(); i++) { + const auto &ma = a->mem_write_actions[i]; + const auto &mb = b->mem_write_actions[i]; + if (!bridge.same(ma.memid, mb.memid)) + return "mem_write_actions " + std::to_string(i) + " memid mismatch: " + mod_a->twines().unescaped_str(ma.memid) + " != " + mod_b->twines().unescaped_str(mb.memid); + if (!compare_sigspec(ma.address, mb.address)) + return "mem_write_actions " + std::to_string(i) + " address mismatch: " + log_signal(ma.address) + " != " + log_signal(mb.address); + if (!compare_sigspec(ma.data, mb.data)) + return "mem_write_actions " + std::to_string(i) + " data mismatch: " + log_signal(ma.data) + " != " + log_signal(mb.data); + if (!compare_sigspec(ma.enable, mb.enable)) + return "mem_write_actions " + std::to_string(i) + " enable mismatch: " + log_signal(ma.enable) + " != " + log_signal(mb.enable); + if (ma.priority_mask != mb.priority_mask) + return "mem_write_actions " + std::to_string(i) + " priority_mask mismatch: " + log_const(ma.priority_mask) + " != " + log_const(mb.priority_mask); + if (std::string mismatch = compare_attributes(&ma, &mb); !mismatch.empty()) + return "mem_write_actions " + std::to_string(i) + " " + mismatch; + } + return ""; + } + + std::string compare_processes(const RTLIL::Process *a, const RTLIL::Process *b) + { + if (!bridge.same(a->name, b->name)) return "name mismatch: " + std::string(a->name.unescape()) + " != " + b->name.unescape(); + if (std::string mismatch = compare_attributes(a, b); !mismatch.empty()) + return mismatch; + if (std::string mismatch = compare_case_rules(&a->root_case, &b->root_case); !mismatch.empty()) + return "case rule " + mismatch; + if (a->syncs.size() != b->syncs.size()) + return "sync count mismatch: " + std::to_string(a->syncs.size()) + " != " + std::to_string(b->syncs.size()); + for (size_t i = 0; i < a->syncs.size(); i++) + if (std::string mismatch = compare_sync_rules(a->syncs[i], b->syncs[i]); !mismatch.empty()) + return "sync " + std::to_string(i) + " " + mismatch; + return ""; + } + + void check_processes() + { + for (auto &it : mod_a->processes) { + IdString in_b = bridge.a_to_b(it.first); + if (mod_b->processes.count(in_b) == 0) + error("Module %s missing process %s in second design.\n", mod_a, it.second); + if (std::string mismatch = compare_processes(it.second, mod_b->processes.at(in_b)); !mismatch.empty()) + error("Module %s process %s %s.\n", mod_a, it.second, mismatch.c_str()); + } + for (auto &it : mod_b->processes) + if (mod_a->processes.count(bridge.b_to_a(it.first)) == 0) + error("Module %s missing process %s in first design.\n", mod_b, it.second); + } + + void check_connections() + { + const auto &conns_a = mod_a->connections(); + const auto &conns_b = mod_b->connections(); + if (conns_a.size() != conns_b.size()) { + error("Module %s connection count differs: %zu != %zu\n", mod_a, conns_a.size(), conns_b.size()); + } else { + for (size_t i = 0; i < conns_a.size(); i++) { + if (!compare_sigspec(conns_a[i].first, conns_b[i].first)) + error("Module %s connection %zu LHS %s != %s.\n", mod_a, i, log_signal(conns_a[i].first), log_signal(conns_b[i].first)); + if (!compare_sigspec(conns_a[i].second, conns_b[i].second)) + error("Module %s connection %zu RHS %s != %s.\n", mod_a, i, log_signal(conns_a[i].second), log_signal(conns_b[i].second)); + } + } + } + + void check() + { + if (!bridge.same(mod_a->name, mod_b->name)) + error("Modules have different names: %s != %s\n", mod_a, mod_b); + if (std::string mismatch = compare_attributes(mod_a, mod_b); !mismatch.empty()) + error("Module %s %s.\n", mod_a, mismatch); + check_wires(); + check_cells(); + check_memories(); + check_connections(); + check_processes(); + } +}; + +struct DesignEqualPass : public Pass { + DesignEqualPass() : Pass("design_equal", "check if two designs are the same") { } + void help() override + { + log("\n"); + log(" design_equal \n"); + log("\n"); + log("Compare the current design with the design previously saved under the given\n"); + log("name. Abort with an error if the designs are different.\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + if (args.size() != 2) + log_cmd_error("Missing argument.\n"); + + std::string check_name = args[1]; + if (saved_designs.count(check_name) == 0) + log_cmd_error("No saved design '%s' found!\n", check_name); + + RTLIL::Design *other = saved_designs.at(check_name).get(); + + PoolBridge bridge(design, other); + + for (auto &it : design->modules_) { + RTLIL::Module *mod = it.second; + RTLIL::Module *other_mod = other->module(bridge.a_to_b(it.first)); + if (!other_mod) + log_error("Second design missing module %s.\n", mod); + + ModuleComparator cmp(mod, other_mod, bridge); + cmp.check(); + } + for (auto &it : other->modules_) { + RTLIL::Module *mod = it.second; + if (!design->has(bridge.b_to_a(it.first))) + log_error("First design missing module %s.\n", mod); + } + + log("Designs are identical.\n"); + } +} DesignEqualPass; + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/dft_tag.cc b/chips/yosys/passes/cmds/dft_tag.cc new file mode 100644 index 0000000000000000000000000000000000000000..77da141269e501081ca77ade1e2abe7c302f457f --- /dev/null +++ b/chips/yosys/passes/cmds/dft_tag.cc @@ -0,0 +1,1031 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2022 Jannis Harder + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/celltypes.h" +#include "kernel/ff.h" +#include "kernel/modtools.h" +#include "kernel/sigtools.h" +#include "kernel/yosys.h" +#include "kernel/log_help.h" +#include + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct DftTagOptions { + bool tag_public = false; + bool overwrite_only = false; +}; + +struct DftTagWorker { + Module *module; + DftTagOptions options; + ModWalker modwalker; + SigMap &sigmap; + FfInitVals initvals; + + struct tag_set { + int index = 0; + + tag_set(int index = 0) : index(index) {} + + bool operator<(const tag_set &other) const { return index < other.index; } + bool operator==(const tag_set &other) const { return index == other.index; } + + [[nodiscard]] Hasher hash_into(Hasher h) const { h.eat(index); return h; } + + bool empty() const { return index == 0; } + }; + + idict> tag_sets; + + pool tmp_tag_set; + dict, tag_set> tag_set_union_cache; + + dict tagged_signals; + + dict> tag_groups; + dict group_of_tag; + pool all_tags; + + pool pending_cells; + std::deque pending_cell_queue; + + dict, SigBit> tag_signals; + + // Uses SigSpec instead of SigBit so we can use coarse grained cells to combine the individual tags + dict, SigSpec> tag_group_signals; + + pool warned_cells; + + DftTagWorker(Module *module, DftTagOptions options) : + module(module), options(options), modwalker(module->design), sigmap(modwalker.sigmap) + { + modwalker.setup(module); + initvals.set(&modwalker.sigmap, module); + tag_sets(tmp_tag_set); + } + + void resolve_overwrites() + { + std::vector overwrite_cells; + std::vector original_cells; + + bool design_changed = false; + + for (auto cell : module->cells()) { + if (cell->type == ID($overwrite_tag)) + overwrite_cells.push_back(cell); + + if (cell->type == ID($original_tag)) + original_cells.push_back(cell); + } + + for (auto cell : overwrite_cells) { + log_debug("Applying $overwrite_tag %s for signal %s\n", cell, log_signal(cell->getPort(ID::A))); + SigSpec orig_signal = cell->getPort(ID::A); + SigSpec interposed_signal = divert_users(orig_signal); + auto *set_tag_cell = module->addSetTag(NEW_ID, cell->getParam(ID::TAG).decode_string(), orig_signal, cell->getPort(ID::SET), cell->getPort(ID::CLR), interposed_signal); + modwalker.add_cell(set_tag_cell); // Make sure the next $overwrite_tag sees the new connections + design_changed = true; + } + + for (auto cell : overwrite_cells) { + module->remove(cell); + } + for (auto cell : original_cells) { + cell->type = ID($get_tag); + } + + if (design_changed) + modwalker.setup(module); + } + + SigSpec divert_users(SigSpec signal) + { + SigSpec signal_mapped = sigmap(signal); + signal_mapped.sort_and_unify(); + if (GetSize(signal_mapped) < GetSize(signal)) + log_warning("Detected $overwrite_tag on signal %s which contains repeated bits, this can result in unexpected behavior.\n", log_signal(signal)); + SigSpec new_wire = module->addWire(NEW_ID, GetSize(signal)); + for (int i = 0; i < GetSize(new_wire); ++i) + divert_users(signal[i], new_wire[i]); + return new_wire; + } + + void divert_users(SigBit driver_bit, SigBit interposed_bit) + { + dict, SigSpec> updated_ports; + // TODO also check module outputs + auto found = modwalker.signal_consumers.find(driver_bit); + if (found == modwalker.signal_consumers.end()) + return; + for (auto &consumer : found->second) { + if (consumer.cell->type.in(ID($original_tag))) + continue; + if (sigmap(consumer.cell->getPort(consumer.port)[consumer.offset]) != driver_bit) + continue; + std::pair key = {consumer.cell, consumer.port}; + auto found_port = updated_ports.find(key); + if (found_port == updated_ports.end()) { + updated_ports.emplace(key, consumer.cell->getPort(consumer.port)); + } + updated_ports[key][consumer.offset] = interposed_bit; + } + for (auto &update : updated_ports) { + update.first.first->setPort(update.first.second, update.second); + modwalker.add_cell(update.first.first); // Make sure the next $overwrite_tag sees the new connections + } + } + + const pool &tag_pool(tag_set set) { return tag_sets[set.index]; } + + tag_set singleton(IdString tag) + { + tmp_tag_set.clear(); + tmp_tag_set.emplace(tag); + return tag_sets(tmp_tag_set); + } + + tag_set merge(tag_set a, tag_set b) + { + if (b < a) + std::swap(a, b); + if (a.empty() || a == b) + return b; + auto found = tag_set_union_cache.find(std::make_pair(a, b)); + if (found == tag_set_union_cache.end()) { + tmp_tag_set.clear(); + auto &a_tags = tag_pool(a); + auto &b_tags = tag_pool(b); + tmp_tag_set.insert(a_tags.begin(), a_tags.end()); + tmp_tag_set.insert(b_tags.begin(), b_tags.end()); + tag_set result = tag_sets(tmp_tag_set); + tag_set_union_cache.emplace(std::make_pair(a, b), result); + return result; + } + return found->second; + } + + tag_set tags(SigBit bit) + { + sigmap.apply(bit); + auto found = tagged_signals.find(bit); + if (found != tagged_signals.end()) + return found->second; + return tag_set(); + } + + tag_set tags(SigSpec sig) + { + tag_set result; + for (auto bit : sig) + result = merge(result, tags(bit)); + return result; + } + + tag_set tags(Cell *cell) + { + tag_set result; + for (auto &conn : cell->connections()) { + if (cell->input(conn.first)) + result = merge(result, tags(conn.second)); + } + return result; + } + + void add_tags(SigBit bit, tag_set new_tags) + { + sigmap.apply(bit); + auto &tags = tagged_signals[bit]; + tag_set merged_tags = merge(tags, new_tags); + if (merged_tags == tags) + return; + tags = merged_tags; + auto it = modwalker.signal_consumers.find(bit); + if (it == modwalker.signal_consumers.end()) + return; + for (auto &consumer : it->second) + if (pending_cells.insert(consumer.cell).second) + pending_cell_queue.push_back(consumer.cell); + } + + void add_tags(SigSpec sig, tag_set new_tags) + { + for (auto bit : sigmap(sig)) + add_tags(bit, new_tags); + } + + void add_tags(Cell *cell, tag_set new_tags) + { + for (auto &conn : cell->connections()) + if (cell->output(conn.first)) + add_tags(conn.second, new_tags); + } + + void forward_tags(SigSpec dst, SigSpec src) + { + log_assert(GetSize(dst) == GetSize(src)); + for (int i = 0; i < GetSize(dst); i++) + add_tags(dst[i], tags(src[i])); + } + + void propagate_tags() + { + for (auto cell : module->cells()) { + if (cell->type == ID($set_tag)) { + pending_cells.insert(cell); + pending_cell_queue.push_back(cell); + } + } + + while (!pending_cell_queue.empty()) { + Cell *cell = pending_cell_queue.front(); + pending_cell_queue.pop_front(); + pending_cells.erase(cell); + + propagate_tags(cell); + } + } + + SigBit tag_signal(IdString tag, SigBit bit) + { + sigmap.apply(bit); + if (!bit.is_wire()) + return State::S0; // Constant value - no tags + + auto found = tag_signals.find(std::make_pair(tag, bit)); + if (found != tag_signals.end()) + return found->second; + + if (!tag_pool(tags(bit)).count(tag)) + return State::S0; // Statically known to not have this tag + + // TODO handle module inputs + auto drivers = modwalker.signal_drivers.find(bit); + if (drivers == modwalker.signal_drivers.end() || drivers->second.empty()) + return State::S0; // No driver - no tags + + log_assert(drivers->second.size() == 1); + auto driver = *drivers->second.begin(); + + emit_tag_signals(tag, driver.cell); + + found = tag_signals.find(std::make_pair(tag, bit)); + log_assert(found != tag_signals.end()); + return found->second; + } + + SigSpec tag_signal(IdString tag, SigSpec sig) + { + SigSpec result; + for (auto bit : sig) + result.append(tag_signal(tag, bit)); + return result; + } + + SigSpec tag_group_signal(IdString tag_group, SigSpec sig) + { + sigmap.apply(sig); + if (sig.is_fully_const() || tag_groups.count(tag_group) == 0) + return Const(0, GetSize(sig)); + + auto found = tag_group_signals.find(std::make_pair(tag_group, sig)); + if (found != tag_group_signals.end()) + return found->second; + + SigSpec combined; + + for (auto &tag : tag_groups[tag_group]) { + auto tag_sig = tag_signal(tag, sig); + + if (!GetSize(combined)) + combined = tag_sig; + else + combined = autoOr(NEW_ID, combined, tag_sig); + } + + if (!GetSize(combined)) + combined = Const(0, GetSize(sig)); + + tag_group_signals.emplace(std::make_pair(tag_group, sig), combined); + return combined; + } + + void emit_tag_signal(IdString tag, SigBit bit, SigBit tag_bit) + { + sigmap.apply(bit); + sigmap.apply(tag_bit); + + if (!tag_pool(tags(bit)).count(tag)) + return; + + auto key = std::make_pair(tag, bit); + auto found = tag_signals.find(key); + if (found != tag_signals.end()) { + module->connect(found->second, tag_bit); + return; + } + tag_signals.emplace(key, tag_bit); + } + + void emit_tag_signal(IdString tag, SigSpec sig, SigSpec tag_sig) + { + log_assert(GetSize(sig) == GetSize(tag_sig)); + for (int i = 0; i < GetSize(sig); i++) + emit_tag_signal(tag, sig[i], tag_sig[i]); + } + + void emit_tag_signals(IdString tag, Cell *cell) + { + if (!pending_cells.insert(cell).second) { + // We have a cycle, emit placeholder wires which will be connected + // when the outer call for this tag/cell returns + for (auto &conn : cell->connections()) + if (cell->output(conn.first)) + emit_tag_signal(tag, conn.second, module->addWire(NEW_ID, GetSize(conn.second))); + + return; + } + + process_cell(tag, cell); + + pending_cells.erase(cell); + } + + IdString tag_id(const Cell *cell) + { + return module->twines().add(RTLIL::escape_id(cell->getParam(ID::TAG).decode_string())); + } + + void propagate_tags(Cell *cell) + { + if (cell->type == ID($set_tag)) { + IdString tag = tag_id(cell); + if (all_tags.insert(tag).second) { + std::string tag_str = module->twines().str(tag); + auto group_sep = tag_str.find(':'); + IdString tag_group = group_sep != std::string::npos + ? module->twines().add(tag_str.substr(0, group_sep)) : tag; + tag_groups[tag_group].insert(tag); + group_of_tag[tag] = tag_group; + } + + auto &sig_y = cell->getPort(ID::Y); + auto &sig_a = cell->getPort(ID::A); + // TODO handle constant set/clr masks + add_tags(sig_y, singleton(tag)); + forward_tags(sig_y, sig_a); + return; + } + + if (cell->type == ID($get_tag)) { + return; + } + + if (cell->type.in(ID($not), ID($pos))) { + auto &sig_y = cell->getPort(ID::Y); + auto sig_a = cell->getPort(ID::A); + if (cell->type.in(ID($not), ID($or))) { + sig_a.extend_u0(GetSize(sig_y), cell->getParam(ID::A_SIGNED).as_bool()); + } + forward_tags(sig_y, sig_a); + return; + } + + if (cell->type.in(ID($and), ID($or), ID($xor), ID($xnor), ID($bweqx))) { + auto &sig_y = cell->getPort(ID::Y); + auto sig_a = cell->getPort(ID::A); + auto sig_b = cell->getPort(ID::B); + if (cell->type.in(ID($and), ID($or), ID($xor), ID($xnor))) { + sig_a.extend_u0(GetSize(sig_y), cell->getParam(ID::A_SIGNED).as_bool()); + sig_b.extend_u0(GetSize(sig_y), cell->getParam(ID::B_SIGNED).as_bool()); + } + forward_tags(sig_y, sig_a); + forward_tags(sig_y, sig_b); + return; + } + + if (cell->type.in(ID($mux), ID($bwmux))) { + 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); + + if (cell->type == ID($mux)) + sig_s = SigSpec(sig_s[0], GetSize(sig_y)); + + forward_tags(sig_y, sig_a); + forward_tags(sig_y, sig_b); + forward_tags(sig_y, sig_s); + return; + } + + if (cell->is_builtin_ff() || cell->type == ID($anyinit)) { + FfData ff(&initvals, cell); + + if (ff.has_clk || ff.has_gclk) + forward_tags(ff.sig_q, ff.sig_d); + return; + } + + // Single output but, sensitive to all inputs + if (cell->type.in( + ID($le), ID($lt), ID($ge), ID($gt), + ID($reduce_and), ID($reduce_or), ID($reduce_xor), ID($reduce_xnor), + ID($reduce_bool), ID($logic_not), ID($logic_or), ID($logic_and), + ID($eq), ID($ne) + )) { + auto &sig_y = cell->getPort(ID::Y); + + add_tags(sig_y[0], tags(cell)); + return; + } + + + // Fallback, propagate tags from all inputs to all outputs + add_tags(cell, tags(cell)); + + if (cell->type.in( + ID($_AND_), ID($_OR_), ID($_NAND_), ID($_NOR_), ID($_ANDNOT_), ID($_ORNOT_), + ID($_XOR_), ID($_XNOR_), ID($_NOT_), ID($_BUF_), ID($_MUX_), + + ID($assert), ID($assume) + )) { + return; + } + + // This isn't a correctness concern (unless cell is a module generating + // tags), but we may end up generating a lot of extra logic when + // reaching this + if (!warned_cells.insert(cell).second) + return; + if (cell->type.isPublic()) + log_warning("Unhandled cell %s (%s) during tag propagation\n", cell, cell->type.unescape()); + else + log_debug("Unhandled cell %s (%s) during tag propagation\n", cell, cell->type.unescape()); + } + + void process_cell(IdString tag, Cell *cell) + { + if (cell->type == ID($set_tag)) { + IdString cell_tag = tag_id(cell); + + auto tag_sig_a = tag_signal(tag, cell->getPort(ID::A)); + auto &sig_y = cell->getPort(ID::Y); + + if (cell_tag == tag) { + auto &sig_set = cell->getPort(ID::SET); + auto &sig_clr = cell->getPort(ID::CLR); + tag_sig_a = autoAnd(NEW_ID, tag_sig_a, autoNot(NEW_ID, sig_clr)); + tag_sig_a = autoOr(NEW_ID, tag_sig_a, sig_set); + } + + emit_tag_signal(tag, sig_y, tag_sig_a); + return; + } + + if (cell->type == ID($get_tag)) { + log_assert(false); + } + + if (cell->type.in(ID($not), ID($pos), ID($_NOT_), ID($_BUF_))) { + auto &sig_y = cell->getPort(ID::Y); + auto sig_a = cell->getPort(ID::A); + if (cell->type.in(ID($not), ID($or))) { + sig_a.extend_u0(GetSize(sig_y), cell->getParam(ID::A_SIGNED).as_bool()); + } + emit_tag_signal(tag, sig_y, tag_signal(tag, sig_a)); + return; + } + + if (cell->type.in( + ID($and), ID($or), + ID($_AND_), ID($_OR_), ID($_NAND_), ID($_NOR_), ID($_ANDNOT_), ID($_ORNOT_) + )) { + auto &sig_y = cell->getPort(ID::Y); + auto sig_a = cell->getPort(ID::A); + auto sig_b = cell->getPort(ID::B); + if (cell->type.in(ID($and), ID($or))) { + sig_a.extend_u0(GetSize(sig_y), cell->getParam(ID::A_SIGNED).as_bool()); + sig_b.extend_u0(GetSize(sig_y), cell->getParam(ID::B_SIGNED).as_bool()); + } + + bool inv_a = false; + bool inv_b = false; + + if (cell->type.in(ID($or), ID($_OR_), ID($_NOR_), ID($_ORNOT_))) + inv_a ^= true, inv_b ^= true; + if (cell->type.in(ID($_ANDNOT_), ID($_ORNOT_))) + inv_b ^= true; + + if (inv_a) + sig_a = autoNot(NEW_ID, sig_a); + if (inv_b) + sig_b = autoNot(NEW_ID, sig_b); + + auto group_sig_a = tag_group_signal(tag, sig_a); + auto group_sig_b = tag_group_signal(tag, sig_b); + + auto tag_sig_a = tag_signal(tag, sig_a); + auto tag_sig_b = tag_signal(tag, sig_b); + + + // Does this input allow propagating (doesn't fix output or same tag group) + sig_a = autoOr(NEW_ID, sig_a, group_sig_a); + sig_b = autoOr(NEW_ID, sig_b, group_sig_b); + + // Mask input tags by whether the other side allows propagation + tag_sig_a = autoAnd(NEW_ID, tag_sig_a, sig_b); + tag_sig_b = autoAnd(NEW_ID, tag_sig_b, sig_a); + + + auto tag_sig = autoOr(NEW_ID, tag_sig_a, tag_sig_b); + emit_tag_signal(tag, sig_y, tag_sig); + return; + } + + if (cell->type.in(ID($xor), ID($xnor), ID($bweqx), ID($_XOR_), ID($_XNOR_))) { + auto &sig_y = cell->getPort(ID::Y); + auto sig_a = cell->getPort(ID::A); + auto sig_b = cell->getPort(ID::B); + if (cell->type.in(ID($xor), ID($xnor))) { + sig_a.extend_u0(GetSize(sig_y), cell->getParam(ID::A_SIGNED).as_bool()); + sig_b.extend_u0(GetSize(sig_y), cell->getParam(ID::B_SIGNED).as_bool()); + } + + auto tag_sig_a = tag_signal(tag, sig_a); + auto tag_sig_b = tag_signal(tag, sig_b); + + auto tag_sig = autoOr(NEW_ID, tag_sig_a, tag_sig_b); + emit_tag_signal(tag, sig_y, tag_sig); + return; + } + + + if (cell->type.in(ID($_MUX_), ID($mux), ID($bwmux))) { + 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); + + if (cell->type == ID($mux)) + sig_s = SigSpec(sig_s[0], GetSize(sig_y)); + + auto group_sig_a = tag_group_signal(tag, sig_a); + auto group_sig_b = tag_group_signal(tag, sig_b); + auto group_sig_s = tag_group_signal(tag, sig_s); + + auto prop_s = autoOr(NEW_ID, + autoXor(NEW_ID, sig_a, sig_b), + autoOr(NEW_ID, group_sig_a, group_sig_b)); + + auto prop_a = autoOr(NEW_ID, autoNot(NEW_ID, sig_s), group_sig_s); + auto prop_b = autoOr(NEW_ID, sig_s, group_sig_s); + + auto tag_sig_a = tag_signal(tag, sig_a); + auto tag_sig_b = tag_signal(tag, sig_b); + auto tag_sig_s = tag_signal(tag, sig_s); + + tag_sig_a = autoAnd(NEW_ID, tag_sig_a, prop_a); + tag_sig_b = autoAnd(NEW_ID, tag_sig_b, prop_b); + tag_sig_s = autoAnd(NEW_ID, tag_sig_s, prop_s); + + auto tag_sig = autoOr(NEW_ID, tag_sig_s, + autoOr(NEW_ID, tag_sig_a, tag_sig_b)); + emit_tag_signal(tag, sig_y, tag_sig); + return; + } + + if (cell->type.in(ID($eq), ID($ne), ID($eqx), ID($nex))) { + auto &sig_y = cell->getPort(ID::Y); + auto sig_a = cell->getPort(ID::A); + auto sig_b = cell->getPort(ID::B); + int width = std::max(GetSize(sig_a), GetSize(sig_b)); + sig_a.extend_u0(width, cell->getParam(ID::A_SIGNED).as_bool()); + sig_b.extend_u0(width, cell->getParam(ID::B_SIGNED).as_bool()); + + auto group_sig_a = tag_group_signal(tag, sig_a); + auto group_sig_b = tag_group_signal(tag, sig_b); + + auto tag_sig_a = tag_signal(tag, sig_a); + auto tag_sig_b = tag_signal(tag, sig_b); + + auto group_sig = autoOr(NEW_ID, group_sig_a, group_sig_b); + // The output can only be affected by the tagged inputs if all group-untagged bits are equal + + auto masked_a = autoOr(NEW_ID, sig_a, group_sig); + auto masked_b = autoOr(NEW_ID, sig_b, group_sig); + + auto prop = autoEq(NEW_ID, masked_a, masked_b); + + auto tag_sig = autoAnd(NEW_ID, prop, autoReduceOr(NEW_ID, SigSpec{tag_sig_a, tag_sig_b})); + tag_sig.extend_u0(GetSize(sig_y), false); + emit_tag_signal(tag, sig_y, tag_sig); + return; + } + + + if (cell->type.in(ID($lt), ID($gt), ID($le), ID($ge))) { + auto &sig_y = cell->getPort(ID::Y); + auto sig_a = cell->getPort(ID::A); + auto sig_b = cell->getPort(ID::B); + int width = std::max(GetSize(sig_a), GetSize(sig_b)); + sig_a.extend_u0(width, cell->getParam(ID::A_SIGNED).as_bool()); + sig_b.extend_u0(width, cell->getParam(ID::B_SIGNED).as_bool()); + + if (cell->type.in(ID($gt), ID($le))) + std::swap(sig_a, sig_b); + + auto group_sig_a = tag_group_signal(tag, sig_a); + auto group_sig_b = tag_group_signal(tag, sig_b); + + auto tag_sig_a = tag_signal(tag, sig_a); + auto tag_sig_b = tag_signal(tag, sig_b); + + auto group_sig = autoOr(NEW_ID, group_sig_a, group_sig_b); + // The output can only be affected by the tagged inputs if the greatest possible sig_a is + // greater or equal to the least possible sig_b + auto masked_a = autoOr(NEW_ID, sig_a, group_sig); + auto masked_b = autoAnd(NEW_ID, sig_b, autoNot(NEW_ID, group_sig)); + + auto prop = autoGe(NEW_ID, masked_a, masked_b); + + auto tag_sig = autoAnd(NEW_ID, prop, autoReduceOr(NEW_ID, SigSpec{tag_sig_a, tag_sig_b})); + tag_sig.extend_u0(GetSize(sig_y), false); + emit_tag_signal(tag, sig_y, tag_sig); + return; + } + + if (cell->type.in(ID($reduce_and), ID($reduce_or), ID($reduce_bool), ID($logic_not))) { + auto &sig_y = cell->getPort(ID::Y); + auto sig_a = cell->getPort(ID::A); + + auto group_sig_a = tag_group_signal(tag, sig_a); + auto tag_sig_a = tag_signal(tag, sig_a); + + if (cell->type.in(ID($reduce_or), ID($reduce_bool), ID($logic_not))) + sig_a = autoNot(NEW_ID, sig_a); + + auto filled = autoOr(NEW_ID, sig_a, group_sig_a); + + auto prop = autoReduceAnd(NEW_ID, filled); + auto tagged = autoReduceOr(NEW_ID, tag_sig_a); + auto tag_sig = autoAnd(NEW_ID, prop, tagged); + tag_sig.extend_u0(GetSize(sig_y), false); + emit_tag_signal(tag, sig_y, tag_sig); + return; + } + + if (cell->is_builtin_ff() || cell->type == ID($anyinit)) { + FfData ff(&initvals, cell); + // TODO handle some more variants + if ((ff.has_clk || ff.has_gclk) && !ff.has_ce && !ff.has_aload && !ff.has_srst && !ff.has_arst && !ff.has_sr) { + if (ff.has_clk && !tags(ff.sig_clk).empty()) + log_warning("Tags on CLK input ignored for %s (%s)\n", cell, cell->type.unescape()); + + int width = ff.width; + + auto sig_q = ff.sig_q; + auto sig_d = ff.sig_d; + + ff.name = module->twines().add(NEW_ID); + ff.cell = nullptr; + ff.sig_d = tag_signal(tag, ff.sig_d); + ff.sig_q = module->addWire(NEW_ID, width); + ff.is_anyinit = false; + ff.val_init = Const(0, width); + ff.emit(); + + emit_tag_signal(tag, sig_q, ff.sig_q); + return; + } else { + log_warning("Unhandled FF-cell %s (%s), consider running clk2fflogic, async2sync and/or dffunmap\n", cell, cell->type.unescape()); + + // For unhandled FFs, the default propagation would cause combinational loops + emit_tag_signal(tag, ff.sig_q, Const(0, ff.width)); + return; + } + } + + // Fallback + SigSpec tag_input; + + for (auto &conn : cell->connections()) { + if (cell->input(conn.first)) { + auto tag_sig = tag_signal(tag, conn.second); + tag_input.append(tag_sig); + } + } + + SigBit any_tagged = autoReduceOr(NEW_ID, tag_input); + + for (auto &conn : cell->connections()) { + if (cell->output(conn.first)) { + emit_tag_signal(tag, conn.second, SigSpec(any_tagged, GetSize(conn.second))); + } + } + + // As fallback we propagate all tags from all inputs to all outputs, + // which is an over-approximation (unless the cell is a module that + // generates tags itself in which case it could be arbitrary). + if (warned_cells.insert(cell).second) + log_warning("Unhandled cell %s (%s) while emitting tag signals\n", cell, cell->type.unescape()); + } + + void emit_tags() + { + warned_cells.clear(); + std::vector get_tag_cells; + for (auto cell : module->selected_cells()) + if (cell->type == ID($get_tag)) + get_tag_cells.push_back(cell); + + for (auto cell : get_tag_cells) { + auto &sig_a = cell->getPort(ID::A); + IdString tag = tag_id(cell); + + tag_signal(tag, sig_a); + } + + if (options.tag_public) + { + std::vector public_wires; + + for (auto wire : module->selected_wires()) + if (wire->name.isPublic()) + public_wires.push_back(wire); + + for (auto wire : public_wires) { + for (auto tag : tag_pool(tags(SigSpec(wire)))) { + auto tag_sig = tag_signal(tag, SigSpec(wire)); + if (tag_sig.is_fully_zero()) + continue; + + int index = 0; + std::string tag_str = module->twines().unescaped_str(tag); + auto name = module->uniquify(stringf("%s:%s", wire->name, tag_str), index); + auto hdlname = wire->get_hdlname_attribute(); + + if (!hdlname.empty()) + hdlname.back() += index ? + stringf(":%s_%d", tag_str, index) : + stringf(":%s", tag_str); + + auto tag_wire = module->addWire(name, wire->width); + + tag_wire->set_bool_attribute(ID::keep); + tag_wire->set_bool_attribute(ID(dft_tag)); + if (!hdlname.empty()) + tag_wire->set_hdlname_attribute(hdlname); + + module->connect(tag_wire, tag_sig); + } + } + } + } + + void replace_dft_cells() + { + std::vector get_tag_cells; + std::vector set_tag_cells; + for (auto cell : module->cells()) { + if (cell->type == ID($get_tag)) + get_tag_cells.push_back(cell); + + if (cell->type == ID($set_tag)) + set_tag_cells.push_back(cell); + + log_assert(!cell->type.in(ID($overwrite_tag), ID($original_tag))); + } + + for (auto cell : set_tag_cells) { + auto &sig_a = cell->getPort(ID::A); + auto &sig_y = cell->getPort(ID::Y); + module->connect(sig_y, sig_a); + module->remove(cell); + } + + for (auto cell : get_tag_cells) { + auto &sig_a = cell->getPort(ID::A); + auto &sig_y = cell->getPort(ID::Y); + IdString tag = tag_id(cell); + + auto tag_sig = tag_signal(tag, sig_a); + module->connect(sig_y, tag_sig); + module->remove(cell); + } + } + + + SigSpec autoAnd(TwineSpec &&name, const SigSpec &sig_a, const SigSpec &sig_b) + { + log_assert(GetSize(sig_a) == GetSize(sig_b)); + if (sig_a.is_fully_zero() || sig_b.is_fully_ones() || sig_a == sig_b) + return sig_a; + if (sig_a.is_fully_ones() || sig_b.is_fully_zero()) + return sig_b; + + return module->And(std::move(name), sig_a, sig_b); + } + + SigSpec autoOr(TwineSpec &&name, const SigSpec &sig_a, const SigSpec &sig_b) + { + log_assert(GetSize(sig_a) == GetSize(sig_b)); + if (sig_a.is_fully_ones() || sig_b.is_fully_zero() || sig_a == sig_b) + return sig_a; + if (sig_a.is_fully_zero() || sig_b.is_fully_ones()) + return sig_b; + + return module->Or(std::move(name), sig_a, sig_b); + } + + SigSpec autoXor(TwineSpec &&name, const SigSpec &sig_a, const SigSpec &sig_b) + { + log_assert(GetSize(sig_a) == GetSize(sig_b)); + if (sig_a == sig_b) + return Const(State::S0, GetSize(sig_a)); + if (sig_a.is_fully_zero()) + return sig_b; + if (sig_b.is_fully_zero()) + return sig_a; + if (sig_a.is_fully_ones()) + return autoNot(std::move(name), sig_b); + if (sig_b.is_fully_ones()) + return autoNot(std::move(name), sig_a); + return module->Xor(std::move(name), sig_a, sig_b); + } + + SigSpec autoXnor(TwineSpec &&name, const SigSpec &sig_a, const SigSpec &sig_b) + { + log_assert(GetSize(sig_a) == GetSize(sig_b)); + if (sig_a == sig_b) + return Const(State::S1, GetSize(sig_a)); + if (sig_a.is_fully_ones()) + return sig_b; + if (sig_b.is_fully_ones()) + return sig_a; + if (sig_a.is_fully_zero()) + return autoNot(std::move(name), sig_b); + if (sig_b.is_fully_zero()) + return autoNot(std::move(name), sig_a); + return module->Xnor(std::move(name), sig_a, sig_b); + } + + SigSpec autoNot(TwineSpec &&name, const SigSpec &sig_a) + { + if (sig_a.is_fully_const()) { + auto const_val = sig_a.as_const(); + for (auto bit : const_val) { + State b = bit; + bit = b == State::S0 ? State::S1 : b == State::S1 ? State::S0 : b; + } + return const_val; + } + return module->Not(std::move(name), sig_a); + } + + SigSpec autoEq(TwineSpec &&name, const SigSpec &sig_a, const SigSpec &sig_b) + { + log_assert(GetSize(sig_a) == GetSize(sig_b)); + if (sig_a == sig_b) + return State::S1; + for (int i = 0; i < GetSize(sig_a); i++) { + auto bit_a = sig_a[i]; + auto bit_b = sig_b[i]; + if (bit_a.is_wire() || bit_b.is_wire()) + continue; + if ((bit_a.data == State::S0 && bit_b.data == State::S1) || + (bit_a.data == State::S1 && bit_b.data == State::S0)) + return State::S0; + } + + return module->Eq(std::move(name), sig_a, sig_b); + } + + SigSpec autoGe(TwineSpec &&name, const SigSpec &sig_a, const SigSpec &sig_b) + { + log_assert(GetSize(sig_a) == GetSize(sig_b)); + if (sig_a == sig_b || sig_a.is_fully_ones()) + return State::S1; + if (sig_b.is_fully_zero()) + return State::S1; + + return module->Ge(std::move(name), sig_a, sig_b); + } + + SigSpec autoReduceAnd(TwineSpec &&name, const SigSpec &sig_a) + { + if (GetSize(sig_a) == 0) + return State::S1; + + if (GetSize(sig_a) == 1 || sig_a == SigSpec(sig_a[0], GetSize(sig_a))) + return sig_a[0]; + for (auto bit : sig_a) + if (!bit.is_wire() && bit.data == State::S0) + return State::S0; + if (sig_a.is_fully_ones()) + return State::S1; + return module->ReduceAnd(std::move(name), sig_a); + } + + SigSpec autoReduceOr(TwineSpec &&name, const SigSpec &sig_a) + { + if (GetSize(sig_a) == 0) + return State::S0; + + if (GetSize(sig_a) == 1 || sig_a == SigSpec(sig_a[0], GetSize(sig_a))) + return sig_a[0]; + for (auto bit : sig_a) + if (!bit.is_wire() && bit.data == State::S1) + return State::S1; + if (sig_a.is_fully_zero()) + return State::S0; + return module->ReduceOr(std::move(name), sig_a); + } +}; + +struct DftTagPass : public Pass { + DftTagPass() : Pass("dft_tag", "create tagging logic for data flow tracking") {} + bool formatted_help() override { + auto *help = PrettyHelp::get_current(); + help->set_group("formal"); + return false; + } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" dft_tag [options] [selection]\n"); + log("\n"); + log("This pass... TODO\n"); + log("\n"); + log(" -overwrite-only\n"); + log(" Only process $overwrite_tag and $original_tag cells.\n"); + log(" -tag-public\n"); + log(" For each public wire that may carry tagged data, create a new public\n"); + log(" wire (named :) that carries the tag bits. Note\n"); + log(" that without this, tagging logic will only be emitted as required\n"); + log(" for uses of $get_tag.\n"); + log("\n"); + } + + void execute(std::vector args, RTLIL::Design *design) override + { + DftTagOptions options; + + log_header(design, "Executing DFT_TAG pass.\n"); + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + if (args[argidx] == "-tag-public") { + options.tag_public = true; + continue; + } + if (args[argidx] == "-overwrite-only") { + options.overwrite_only = true; + continue; + } + break; + } + + extra_args(args, argidx, design); + + for (auto module : design->selected_modules()) { + DftTagWorker worker(module, options); + + log_debug("Resolve overwrite_tag and original_tag.\n"); + worker.resolve_overwrites(); + + if (options.overwrite_only) + continue; + + log_debug("Propagate tagged signals.\n"); + worker.propagate_tags(); + + log_debug("Emit tag signals and logic.\n"); + worker.emit_tags(); + + log_debug("Replace dft cells.\n"); + worker.replace_dft_cells(); + } + } +} DftTagPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/edgetypes.cc b/chips/yosys/passes/cmds/edgetypes.cc new file mode 100644 index 0000000000000000000000000000000000000000..51022bc4abe85c273fe67e903727e16fb46be32c --- /dev/null +++ b/chips/yosys/passes/cmds/edgetypes.cc @@ -0,0 +1,112 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "kernel/sigtools.h" +#include "kernel/log_help.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct EdgetypePass : public Pass { + EdgetypePass() : Pass("edgetypes", "list all types of edges in selection") { } + bool formatted_help() override { + auto *help = PrettyHelp::get_current(); + help->set_group("passes/status"); + return false; + } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" edgetypes [options] [selection]\n"); + log("\n"); + log("This command lists all unique types of 'edges' found in the selection. An 'edge'\n"); + log("is a 4-tuple of source and sink cell type and port name.\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + // if (args[argidx] == "-ltr") { + // config.ltr = true; + // continue; + // } + break; + } + extra_args(args, argidx, design); + + pool edge_cache; + + for (auto module : design->selected_modules()) + { + SigMap sigmap(module); + dict>> bit_sources, bit_sinks; + pool> multibit_ports; + + for (auto cell : module->selected_cells()) + for (auto conn : cell->connections()) + { + IdString cell_type = cell->type; + IdString port_name = conn.first; + SigSpec sig = sigmap(conn.second); + + if (GetSize(sig) > 1) + multibit_ports.insert(std::pair(cell_type, port_name)); + + for (int i = 0; i < GetSize(sig); i++) { + if (cell->output(port_name)) + bit_sources[sig[i]].insert(tuple(cell_type, port_name, i)); + if (cell->input(port_name)) + bit_sinks[sig[i]].insert(tuple(cell_type, port_name, i)); + } + } + + for (auto &it : bit_sources) + for (auto &source : it.second) + for (auto &sink : bit_sinks[it.first]) + { + auto source_cell_type = std::get<0>(source); + auto source_port_name = std::get<1>(source); + auto source_bit_index = std::get<2>(source); + + auto sink_cell_type = std::get<0>(sink); + auto sink_port_name = std::get<1>(sink); + auto sink_bit_index = std::get<2>(sink); + + string source_str = multibit_ports.count(std::pair(source_cell_type, source_port_name)) ? + stringf("%s.%s[%d]", PooledName(module, source_cell_type).unescape(), PooledName(module, source_port_name).unescape(), source_bit_index) : + stringf("%s.%s", PooledName(module, source_cell_type).unescape(), PooledName(module, source_port_name).unescape()); + + string sink_str = multibit_ports.count(std::pair(sink_cell_type, sink_port_name)) ? + stringf("%s.%s[%d]", PooledName(module, sink_cell_type).unescape(), PooledName(module, sink_port_name).unescape(), sink_bit_index) : + stringf("%s.%s", PooledName(module, sink_cell_type).unescape(), PooledName(module, sink_port_name).unescape()); + + edge_cache.insert(source_str + " " + sink_str); + } + } + + edge_cache.sort(); + for (auto &str : edge_cache) + log("%s\n", str); + } +} EdgetypePass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/example_dt.cc b/chips/yosys/passes/cmds/example_dt.cc new file mode 100644 index 0000000000000000000000000000000000000000..43ef6d6e0c4bcf62e666b64239c9ab02e83eccb5 --- /dev/null +++ b/chips/yosys/passes/cmds/example_dt.cc @@ -0,0 +1,271 @@ +#include "kernel/yosys.h" +#include "kernel/drivertools.h" +#include "kernel/topo_scc.h" +#include "kernel/compute_graph.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + + + + +struct ExampleWorker +{ + DriverMap dm; + Module *module; + + ExampleWorker(Module *module) : module(module) { + dm.celltypes.setup(); + } +}; + +struct ExampleDtPass : public Pass +{ + ExampleDtPass() : Pass("example_dt", "drivertools example") { + internal(); + } + + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log("TODO: add help message\n"); + log("\n"); + } + + + void execute(std::vector args, RTLIL::Design *design) override + { + size_t argidx = 1; + extra_args(args, argidx, design); + + for (auto module : design->selected_modules()) { + ExampleWorker worker(module); + DriverMap dm; + + TwinePool &twines = design->twines(); + const IdString fn_concat = twines.add("$$concat"); + const IdString fn_input = twines.add("$$input"); + const IdString fn_buf = twines.add("$$buf"); + const IdString fn_slice = twines.add("$$slice"); + const IdString fn_state = twines.add("$$state"); + const IdString fn_cell_output = twines.add("$$cell_output"); + const IdString fn_const = twines.add("$$const"); + const IdString fn_multi = twines.add("$$multi"); + const IdString fn_undriven = twines.add("$$undriven"); + + struct ExampleFn { + IdString name; + dict parameters; + + ExampleFn(IdString name) : name(name) {} + ExampleFn(IdString name, dict parameters) : name(name), parameters(parameters) {} + + bool operator==(ExampleFn const &other) const { + return name == other.name && parameters == other.parameters; + } + + [[nodiscard]] Hasher hash_into(Hasher h) const { + h.eat(name); + h.eat(parameters); + return h; + } + }; + + typedef ComputeGraph ExampleGraph; + + ExampleGraph compute_graph; + + + dm.add(module); + + idict queue; + idict cells; + + IntGraph edges; + std::vector graph_nodes; + + auto enqueue = [&](DriveSpec const &spec) { + int index = queue(spec); + if (index == GetSize(graph_nodes)) + graph_nodes.emplace_back(compute_graph.add(ID($pending), index).index()); + //if (index >= GetSize(graph_nodes)) + return compute_graph[graph_nodes[index]]; + }; + + for (auto cell : module->cells()) { + if (cell->type.in(ID($assert), ID($assume), ID($cover), ID($check))) + enqueue(DriveBitMarker(cells(cell), 0)); + } + + for (auto wire : module->wires()) { + if (!wire->port_output) + continue; + enqueue(DriveChunk(DriveChunkWire(wire, 0, wire->width))).assign_key(wire->name); + } + + for (int i = 0; i != GetSize(queue); ++i) + { + DriveSpec spec = queue[i]; + ExampleGraph::Ref node = compute_graph[i]; + + if (spec.chunks().size() > 1) { + node.set_function(fn_concat); + + for (auto const &chunk : spec.chunks()) { + node.append_arg(enqueue(chunk)); + } + } else if (spec.chunks().size() == 1) { + DriveChunk chunk = spec.chunks()[0]; + if (chunk.is_wire()) { + DriveChunkWire wire_chunk = chunk.wire(); + if (wire_chunk.is_whole()) { + node.sparse_attr() = wire_chunk.wire->name; + if (wire_chunk.wire->port_input) { + node.set_function(ExampleFn(fn_input, {{wire_chunk.wire->name, {}}})); + } else { + DriveSpec driver = dm(DriveSpec(wire_chunk)); + node.set_function(fn_buf); + + node.append_arg(enqueue(driver)); + } + } else { + DriveChunkWire whole_wire(wire_chunk.wire, 0, wire_chunk.wire->width); + node.set_function(ExampleFn(fn_slice, {{ID::offset, wire_chunk.offset}, {ID::width, wire_chunk.width}})); + node.append_arg(enqueue(whole_wire)); + } + } else if (chunk.is_port()) { + DriveChunkPort port_chunk = chunk.port(); + if (port_chunk.is_whole()) { + if (dm.celltypes.cell_output(port_chunk.cell->type, port_chunk.port)) { + if (port_chunk.cell->type.in(ID($dff), ID($ff))) + { + Cell *cell = port_chunk.cell; + node.set_function(ExampleFn(fn_state, {{cell->name, {}}})); + for (auto const &conn : cell->connections()) { + if (!dm.celltypes.cell_input(cell->type, conn.first)) + continue; + enqueue(DriveChunkPort(cell, conn)).assign_key(cell->name); + } + } + else + { + node.set_function(ExampleFn(fn_cell_output, {{port_chunk.port, {}}})); + node.append_arg(enqueue(DriveBitMarker(cells(port_chunk.cell), 0))); + } + } else { + node.set_function(fn_buf); + + DriveSpec driver = dm(DriveSpec(port_chunk)); + node.append_arg(enqueue(driver)); + } + + } else { + DriveChunkPort whole_port(port_chunk.cell, port_chunk.port, 0, GetSize(port_chunk.cell->connections().at(port_chunk.port))); + node.set_function(ExampleFn(fn_slice, {{ID::offset, port_chunk.offset}})); + node.append_arg(enqueue(whole_port)); + } + } else if (chunk.is_constant()) { + node.set_function(ExampleFn(fn_const, {{ID::value, chunk.constant()}})); + + } else if (chunk.is_multiple()) { + node.set_function(fn_multi); + for (auto const &driver : chunk.multiple().multiple()) + node.append_arg(enqueue(driver)); + } else if (chunk.is_marker()) { + Cell *cell = cells[chunk.marker().marker]; + + node.set_function(ExampleFn(cell->type, dict(cell->parameters.begin(), cell->parameters.end()))); + for (auto const &conn : cell->connections()) { + if (!dm.celltypes.cell_input(cell->type, conn.first)) + continue; + + node.append_arg(enqueue(DriveChunkPort(cell, conn))); + } + } else if (chunk.is_none()) { + node.set_function(fn_undriven); + + } else { + log_error("unhandled drivespec: %s\n", log_signal(chunk)); + log_abort(); + } + } else { + log_abort(); + } + } + + + // Perform topo sort and detect SCCs + ExampleGraph::SccAdaptor compute_graph_scc(compute_graph); + + + std::vector perm; + TopoSortedSccs(compute_graph_scc, [&](int *begin, int *end) { + perm.insert(perm.end(), begin, end); + if (end > begin + 1) + { + std::string message = "SCC:"; + for (int *i = begin; i != end; ++i) + message += stringf(" %d", *i); + log_warning("%s\n", message); + } + }).process_sources().process_all(); + compute_graph.permute(perm); + + + // Forward $$buf unless we have a name in the sparse attribute + std::vector alias; + perm.clear(); + + for (int i = 0; i < compute_graph.size(); ++i) + { + if (compute_graph[i].function().name == fn_buf && !compute_graph[i].has_sparse_attr() && compute_graph[i].arg(0).index() < i) + { + + alias.push_back(alias[compute_graph[i].arg(0).index()]); + } + else + { + alias.push_back(GetSize(perm)); + perm.push_back(i); + } + } + compute_graph.permute(perm, alias); + + // Dump the compute graph + for (int i = 0; i < compute_graph.size(); ++i) + { + auto ref = compute_graph[i]; + std::string message = stringf("n%d ", i); + message += PooledName(design, ref.function().name).unescape(); + for (auto const ¶m : ref.function().parameters) + { + if (param.second.empty()) + message += stringf("[%s]", PooledName(design, param.first).unescape()); + else + message += stringf("[%s=%s]", PooledName(design, param.first).unescape(), log_const(param.second)); + } + message += "("; + + for (int i = 0, end = ref.size(); i != end; ++i) + { + if (i > 0) + message += ", "; + message += stringf("n%d", ref.arg(i).index()); + } + log("%s)\n", message); + if (ref.has_sparse_attr()) + log("// wire %s\n", PooledName(design, ref.sparse_attr()).unescape()); + log("// was #%d %s\n", ref.attr(), log_signal(queue[ref.attr()])); + } + + for (auto const &key : compute_graph.keys()) + { + log("return %d as %s \n", key.second, PooledName(design, key.first).unescape()); + } + } + log("Plugin test passed!\n"); + } +} ExampleDtPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/exec.cc b/chips/yosys/passes/cmds/exec.cc new file mode 100644 index 0000000000000000000000000000000000000000..8d117affee90a2deae9e5d130deeb76e9d6f3846 --- /dev/null +++ b/chips/yosys/passes/cmds/exec.cc @@ -0,0 +1,209 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 - 2020 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "kernel/log_help.h" +#include +#include + +#if defined(_WIN32) +# include +# define WIFEXITED(x) 1 +# define WIFSIGNALED(x) 0 +# define WIFSTOPPED(x) 0 +# define WEXITSTATUS(x) ((x) & 0xff) +# define WTERMSIG(x) SIGTERM +# define WSTOPSIG(x) 0 +#else +# include +#endif + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct ExecPass : public Pass { + ExecPass() : Pass("exec", "execute commands in the operating system shell") { } + bool formatted_help() override { + auto *help = PrettyHelp::get_current(); + help->set_group("passes/status"); + return false; + } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" exec [options] -- [command]\n"); + log("\n"); + log("Execute a command in the operating system shell. All supplied arguments are\n"); + log("concatenated and passed as a command to popen(3). Whitespace is not guaranteed\n"); + log("to be preserved, even if quoted. stdin and stderr are not connected, while\n"); + log("stdout is logged unless the \"-q\" option is specified.\n"); + log("\n"); + log("\n"); + log(" -q\n"); + log(" Suppress stdout and stderr from subprocess\n"); + log("\n"); + log(" -expect-return \n"); + log(" Generate an error if popen() does not return specified value.\n"); + log(" May only be specified once; the final specified value is controlling\n"); + log(" if specified multiple times.\n"); + log("\n"); + log(" -expect-stdout \n"); + log(" Generate an error if the specified regex does not match any line\n"); + log(" in subprocess's stdout. May be specified multiple times.\n"); + log("\n"); + log(" -not-expect-stdout \n"); + log(" Generate an error if the specified regex matches any line\n"); + log(" in subprocess's stdout. May be specified multiple times.\n"); + log("\n"); + log("\n"); + log(" Example: exec -q -expect-return 0 -- echo \"bananapie\" | grep \"nana\"\n"); + log("\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + std::string cmd = ""; + char buf[1024] = {}; + std::string linebuf = ""; + bool flag_cmd = false; + bool flag_quiet = false; + bool flag_expect_return = false; + int expect_return_value = 0; + bool flag_expect_stdout = false; + struct expect_stdout_elem { + bool matched; + bool polarity; //true: this regex must match at least one line + //false: this regex must not match any line + std::string str; + std::regex re; + + expect_stdout_elem() : matched(false), polarity(true), str(), re(){}; + }; + std::vector expect_stdout; + + if(args.size() == 0) + log_cmd_error("No command provided.\n"); + + for(size_t argidx = 1; argidx < args.size(); ++argidx) { + if (flag_cmd) { + cmd += args[argidx] + (argidx != (args.size() - 1)? " " : ""); + } else { + if (args[argidx] == "--") + flag_cmd = true; + else if (args[argidx] == "-q") + flag_quiet = true; + else if (args[argidx] == "-expect-return") { + flag_expect_return = true; + ++argidx; + if (argidx >= args.size()) + log_cmd_error("No expected return value specified.\n"); + + expect_return_value = atoi(args[argidx].c_str()); + } else if (args[argidx] == "-expect-stdout") { + flag_expect_stdout = true; + ++argidx; + if (argidx >= args.size()) + log_cmd_error("No expected regular expression specified.\n"); + + try{ + expect_stdout_elem x; + x.str = args[argidx]; + x.re = YS_REGEX_COMPILE(args[argidx]); + expect_stdout.push_back(x); + } catch (const std::regex_error& e) { + log_cmd_error("Error in regex expression '%s' !\n", args[argidx]); + } + } else if (args[argidx] == "-not-expect-stdout") { + flag_expect_stdout = true; + ++argidx; + if (argidx >= args.size()) + log_cmd_error("No expected regular expression specified.\n"); + + try{ + expect_stdout_elem x; + x.str = args[argidx]; + x.re = YS_REGEX_COMPILE(args[argidx]); + x.polarity = false; + expect_stdout.push_back(x); + } catch (const std::regex_error& e) { + log_cmd_error("Error in regex expression '%s' !\n", args[argidx]); + } + + } else + log_cmd_error("Unknown option \"%s\" or \"--\" doesn\'t precede command.\n", args[argidx]); + } + } + + log_header(design, "Executing command \"%s\".\n", cmd); + log_push(); + + fflush(stdout); + bool keep_reading = true; + int status = 0; + int retval = 0; + + FILE *f = popen(cmd.c_str(), "r"); + if (f == nullptr) + log_cmd_error("errno %d after popen() returned NULL.\n", errno); + while (keep_reading) { + keep_reading = (fgets(buf, sizeof(buf), f) != nullptr); + linebuf += buf; + memset(buf, 0, sizeof(buf)); + + auto pos = linebuf.find('\n'); + while (pos != std::string::npos) { + std::string line = linebuf.substr(0, pos); + linebuf.erase(0, pos + 1); + if (!flag_quiet) + log("%s\n", line); + + if (flag_expect_stdout) + for(auto &x : expect_stdout) + if (std::regex_search(line, x.re)) + x.matched = true; + + pos = linebuf.find('\n'); + } + } + status = pclose(f); + + if(WIFEXITED(status)) { + retval = WEXITSTATUS(status); + } + else if(WIFSIGNALED(status)) { + retval = WTERMSIG(status); + } + else if(WIFSTOPPED(status)) { + retval = WSTOPSIG(status); + } + + if (flag_expect_return && retval != expect_return_value) + log_cmd_error("Return value %d did not match expected return value %d.\n", retval, expect_return_value); + + if (flag_expect_stdout) + for (auto &x : expect_stdout) + if (x.polarity ^ x.matched) + log_cmd_error("Command stdout did%s have a line matching given regex \"%s\".\n", (x.polarity? " not" : ""), x.str); + + log_pop(); + } +} ExecPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/future.cc b/chips/yosys/passes/cmds/future.cc new file mode 100644 index 0000000000000000000000000000000000000000..15f4b8bd1dfe6ed2e61fcd8a5aaf12fb7bc739d0 --- /dev/null +++ b/chips/yosys/passes/cmds/future.cc @@ -0,0 +1,146 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2023 Jannis Harder + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/celltypes.h" +#include "kernel/ff.h" +#include "kernel/ffinit.h" +#include "kernel/modtools.h" +#include "kernel/sigtools.h" +#include "kernel/utils.h" +#include "kernel/yosys.h" +#include "kernel/log_help.h" +#include + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct FutureOptions { +}; + +struct FutureWorker { + Module *module; + FutureOptions options; + ModWalker modwalker; + SigMap &sigmap; + FfInitVals initvals; + + dict future_ff_signals; + + FutureWorker(Module *module, FutureOptions options) : + module(module), options(options), modwalker(module->design), sigmap(modwalker.sigmap) + { + modwalker.setup(module); + initvals.set(&modwalker.sigmap, module); + + std::vector replaced_cells; + for (auto cell : module->selected_cells()) { + if (cell->type != ID($future_ff)) + continue; + + module->connect(cell->getPort(ID::Y), future_ff(cell->getPort(ID::A))); + replaced_cells.push_back(cell); + } + + for (auto cell : replaced_cells) { + module->remove(cell); + } + } + + SigSpec future_ff(SigSpec sig) + { + for (auto &bit : sig) { + bit = future_ff(bit); + } + return sig; + } + + SigBit future_ff(SigBit bit) + { + if (!bit.is_wire()) + return bit; + + auto found = future_ff_signals.find(bit); + if (found != future_ff_signals.end()) + return found->second; + + auto found_driver = modwalker.signal_drivers.find(bit); + if (found_driver == modwalker.signal_drivers.end() || found_driver->second.size() < 1) + log_error("No driver for future_ff target signal %s found\n", log_signal(bit)); + if (found_driver->second.size() > 1) + log_error("Found multiple drivers for future_ff target signal %s\n", log_signal(bit)); + auto driver = *found_driver->second.begin(); + if (!driver.cell->is_builtin_ff() && driver.cell->type != ID($anyinit)) + log_error("Driver for future_ff target signal %s has non-FF cell type %s\n", log_signal(bit), driver.cell->type.unescape()); + + FfData ff(&initvals, driver.cell); + + if (!ff.has_clk && !ff.has_gclk) + log_error("Driver for future_ff target signal %s has cell type %s, which is not clocked\n", log_signal(bit), + driver.cell->type.unescape()); + + ff.unmap_ce_srst(); + + // We insert all bits into the mapping, because unmap_ce_srst might + // have removed the cell which is still present in the modwalker data. + // By inserting all bits driven by th FF we ensure that we'll never use + // that stale modwalker data again. + + for (int i = 0; i < ff.width; ++i) { + future_ff_signals.emplace(ff.sig_q[i], ff.sig_d[i]); + } + + return future_ff_signals.at(bit); + } +}; + +struct FuturePass : public Pass { + FuturePass() : Pass("future", "resolve future sampled value functions") {} + bool formatted_help() override { + auto *help = PrettyHelp::get_current(); + help->set_group("formal"); + return false; + } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" future [options] [selection]\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + FutureOptions options; + + log_header(design, "Executing FUTURE pass.\n"); + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + + break; + } + + extra_args(args, argidx, design); + + for (auto module : design->selected_modules()) { + FutureWorker worker(module, options); + } + } +} FuturePass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/glift.cc b/chips/yosys/passes/cmds/glift.cc new file mode 100644 index 0000000000000000000000000000000000000000..6fc88f4b3ca020702e9381b84737df05a91fe3e4 --- /dev/null +++ b/chips/yosys/passes/cmds/glift.cc @@ -0,0 +1,609 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2020 Alberto Gonzalez + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/utils.h" +#include "kernel/yosys.h" +#include "kernel/log_help.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct GliftWorker { +private: + bool is_top_module = false; + bool opt_create_precise_model = false, opt_create_imprecise_model = false, opt_create_instrumented_model = false; + bool opt_taintconstants = false, opt_keepoutputs = false, opt_simplecostmodel = false, opt_nocostmodel = false; + bool opt_instrumentmore = false; + std::vector new_taint_outputs; + std::vector> meta_mux_selects; + RTLIL::Module *module = nullptr; + + const IdString cost_model_wire_name = ID::__glift_weight; + const IdString glift_attribute_name = ID::glift; + + + RTLIL::SigSpec get_corresponding_taint_signal(RTLIL::SigSpec sig) { + RTLIL::SigSpec ret; + + //Get the connected wire for the cell port: + log_assert(sig.is_wire() || sig.is_fully_const()); + log_assert(sig.is_wire() || sig.is_fully_const()); + + //Get a SigSpec for the corresponding taint signal for the cell port, creating one if necessary: + if (sig.is_wire()) { + IdString taint_name_ref = module->twines().add(sig.as_wire()->name.str() + "_t"); + RTLIL::Wire *w = module->wire(taint_name_ref); + if (w == nullptr) w = module->addWire(sig.as_wire()->name.str() + "_t", 1); + ret = w; + } + else if (sig.is_fully_const() && opt_taintconstants) + ret = RTLIL::State::S1; + else if (sig.is_fully_const()) + ret = RTLIL::State::S0; + else + log_cmd_error("Cell port SigSpec has unexpected type.\n"); + + //Finally, if the cell port was a module input or output, make sure the corresponding taint signal is marked, too: + if(sig.is_wire() && sig.as_wire()->port_input) + ret.as_wire()->port_input = true; + if(sig.is_wire() && sig.as_wire()->port_output) + new_taint_outputs.push_back(ret.as_wire()); + + return ret; + } + + void add_precise_GLIFT_logic(const RTLIL::Cell *cell, RTLIL::SigSpec &port_a, RTLIL::SigSpec &port_a_taint, RTLIL::SigSpec &port_b, RTLIL::SigSpec &port_b_taint, RTLIL::SigSpec &port_y_taint) { + //AKA AN2_SH2 or OR2_SH2 + bool is_and = cell->type.in(ID($_AND_), ID($_NAND_)); + RTLIL::SigSpec n_port_a = module->LogicNot(cell->name.str() + "_t_1_1", port_a, false, cell->get_src_attribute()); + RTLIL::SigSpec n_port_b = module->LogicNot(cell->name.str() + "_t_1_2", port_b, false, cell->get_src_attribute()); + auto subexpr1 = module->And(cell->name.str() + "_t_1_3", is_and? port_a : n_port_a, port_b_taint, false, cell->get_src_attribute()); + auto subexpr2 = module->And(cell->name.str() + "_t_1_4", is_and? port_b : n_port_b, port_a_taint, false, cell->get_src_attribute()); + auto subexpr3 = module->And(cell->name.str() + "_t_1_5", port_a_taint, port_b_taint, false, cell->get_src_attribute()); + auto subexpr4 = module->Or(cell->name.str() + "_t_1_6", subexpr1, subexpr2, false, cell->get_src_attribute()); + module->addOr(cell->name.str() + "_t_1_7", subexpr4, subexpr3, port_y_taint, false, cell->get_src_attribute()); + } + + void add_imprecise_GLIFT_logic_1(const RTLIL::Cell *cell, RTLIL::SigSpec &port_a, RTLIL::SigSpec &port_a_taint, RTLIL::SigSpec &port_b, RTLIL::SigSpec &port_b_taint, RTLIL::SigSpec &port_y_taint) { + //AKA AN2_SH3 or OR2_SH3 + bool is_and = cell->type.in(ID($_AND_), ID($_NAND_)); + RTLIL::SigSpec n_port_a = module->LogicNot(cell->name.str() + "_t_2_1", port_a, false, cell->get_src_attribute()); + auto subexpr1 = module->And(cell->name.str() + "_t_2_2", is_and? port_b : n_port_a, is_and? port_a_taint : port_b_taint, false, cell->get_src_attribute()); + module->addOr(cell->name.str() + "_t_2_3", is_and? port_b_taint : port_a_taint, subexpr1, port_y_taint, false, cell->get_src_attribute()); + } + + void add_imprecise_GLIFT_logic_2(const RTLIL::Cell *cell, RTLIL::SigSpec &port_a, RTLIL::SigSpec &port_a_taint, RTLIL::SigSpec &port_b, RTLIL::SigSpec &port_b_taint, RTLIL::SigSpec &port_y_taint) { + //AKA AN2_SH4 or OR2_SH4 + bool is_and = cell->type.in(ID($_AND_), ID($_NAND_)); + RTLIL::SigSpec n_port_b = module->LogicNot(cell->name.str() + "_t_3_1", port_b, false, cell->get_src_attribute()); + auto subexpr1 = module->And(cell->name.str() + "_t_3_2", is_and? port_a : n_port_b, is_and? port_b_taint : port_a_taint, false, cell->get_src_attribute()); + module->addOr(cell->name.str() + "_t_3_3", is_and? port_a_taint : port_b_taint, subexpr1, port_y_taint, false, cell->get_src_attribute()); + } + + void add_imprecise_GLIFT_logic_3(const RTLIL::Cell *cell, RTLIL::SigSpec &port_a_taint, RTLIL::SigSpec &port_b_taint, RTLIL::SigSpec &port_y_taint) { + //AKA AN2_SH5 or OR2_SH5 or XR2_SH2 + module->addOr(cell->name.str() + "_t_4_1", port_a_taint, port_b_taint, port_y_taint, false, cell->get_src_attribute()); + } + + void add_imprecise_GLIFT_logic_4(RTLIL::SigSpec &port_a_taint, RTLIL::SigSpec &port_y_taint) { + module->connect(port_y_taint, port_a_taint); + } + + void add_imprecise_GLIFT_logic_5(RTLIL::SigSpec &port_b_taint, RTLIL::SigSpec &port_y_taint) { + module->connect(port_y_taint, port_b_taint); + } + + void add_imprecise_GLIFT_logic_6(RTLIL::SigSpec &port_y_taint) { + module->connect(port_y_taint, RTLIL::Const(1, 1)); + } + + void add_imprecise_GLIFT_logic_7(RTLIL::SigSpec &port_y_taint) { + module->connect(port_y_taint, RTLIL::Const(0, 1)); + } + + void add_precise_GLIFT_mux(const RTLIL::Cell *cell, RTLIL::SigSpec &port_a, RTLIL::SigSpec &port_a_taint, RTLIL::SigSpec &port_b, RTLIL::SigSpec &port_b_taint, RTLIL::SigSpec &port_s, RTLIL::SigSpec &port_s_taint, RTLIL::SigSpec &port_y_taint) { + //S&At | ~S&Bt | ~A&B&St | A&~B&St | At&St | Bt&St + RTLIL::SigSpec n_port_a = module->LogicNot(cell->name.str() + "_t_4_1", port_a, false, cell->get_src_attribute()); + RTLIL::SigSpec n_port_b = module->LogicNot(cell->name.str() + "_t_4_2", port_b, false, cell->get_src_attribute()); + RTLIL::SigSpec n_port_s = module->LogicNot(cell->name.str() + "_t_4_3", port_s, false, cell->get_src_attribute()); + auto subexpr1 = module->And(cell->name.str() + "_t_4_4", port_s, port_a_taint, false, cell->get_src_attribute()); + auto subexpr2 = module->And(cell->name.str() + "_t_4_5", n_port_s, port_b_taint, false, cell->get_src_attribute()); + auto subexpr3 = module->And(cell->name.str() + "_t_4_6", n_port_a, port_b, false, cell->get_src_attribute()); + auto subexpr4 = module->And(cell->name.str() + "_t_4_7", subexpr3, port_s_taint, false, cell->get_src_attribute()); + auto subexpr5 = module->And(cell->name.str() + "_t_4_8", port_a, n_port_b, false, cell->get_src_attribute()); + auto subexpr6 = module->And(cell->name.str() + "_t_4_9", subexpr5, port_s_taint, false, cell->get_src_attribute()); + auto subexpr7 = module->And(cell->name.str() + "_t_4_10", port_a_taint, port_s_taint, false, cell->get_src_attribute()); + auto subexpr8 = module->And(cell->name.str() + "_t_4_11", port_b_taint, port_s_taint, false, cell->get_src_attribute()); + auto subexpr9 = module->Or(cell->name.str() + "_t_4_12", subexpr1, subexpr2, false, cell->get_src_attribute()); + auto subexpr10 = module->Or(cell->name.str() + "_t_4_13", subexpr4, subexpr6, false, cell->get_src_attribute()); + auto subexpr11 = module->Or(cell->name.str() + "_t_4_14", subexpr7, subexpr8, false, cell->get_src_attribute()); + auto subexpr12 = module->Or(cell->name.str() + "_t_4_15", subexpr9, subexpr10, false, cell->get_src_attribute()); + module->addOr(cell->name.str() + "_t_4_16", subexpr11, subexpr12, port_y_taint, false, cell->get_src_attribute()); + } + + RTLIL::SigSpec score_metamux_select(const RTLIL::SigSpec &metamux_select, const RTLIL::IdString celltype) { + log_assert(metamux_select.is_wire()); + + if (opt_simplecostmodel) { + //The complex model is an area model, so a lower score should mean smaller. + //In this case, a nonzero hole metamux select value means less logic. + //Thus we should invert the ReduceOr over the metamux_select signal. + RTLIL::SigSpec pmux_select = module->ReduceOr(metamux_select.as_wire()->name.str() + "_nonzero", metamux_select); + return module->Pmux(NEW_ID, RTLIL::Const(1), RTLIL::Const(0), pmux_select, metamux_select.as_wire()->get_src_attribute()); + } else { + auto select_width = metamux_select.as_wire()->width; + + std::vector costs; + if (celltype == ID($_AND_) || celltype == ID($_OR_)) { + costs = {5, 2, 2, 1, 0, 0, 0, 0}; + log_assert(select_width == 2 || select_width == 3); + log_assert(opt_instrumentmore || select_width == 2); + log_assert(!opt_instrumentmore || select_width == 3); + } + else if (celltype == ID($_XOR_) || celltype == ID($_XNOR_)) { + costs = {1, 0, 0, 0}; + log_assert(select_width == 2); + } + + std::vector next_pmux_y_ports, pmux_y_ports(costs.begin(), costs.begin() + exp2(select_width)); + for (auto i = 0; pmux_y_ports.size() > 1; ++i) { + for (auto j = 0; j+1 < GetSize(pmux_y_ports); j += 2) { + next_pmux_y_ports.emplace_back(module->Pmux(stringf("%s_mux_%d_%d", metamux_select.as_wire()->name, i, j), pmux_y_ports[j], pmux_y_ports[j+1], metamux_select[GetSize(metamux_select) - 1 - i], metamux_select.as_wire()->get_src_attribute())); + } + if (GetSize(pmux_y_ports) % 2 == 1) + next_pmux_y_ports.push_back(pmux_y_ports[GetSize(pmux_y_ports) - 1]); + pmux_y_ports.swap(next_pmux_y_ports); + next_pmux_y_ports.clear(); + } + + log_assert(pmux_y_ports.size() == 1); + return pmux_y_ports[0]; + } + } + + void create_glift_logic() { + if (module->get_bool_attribute(glift_attribute_name)) + return; + + std::vector connections(module->connections()); + + for(auto &cell : module->cells().to_vector()) { + if (!cell->type.in(ID($_AND_), ID($_NAND_), ID($_OR_), ID($_NOR_), ID($_XOR_), ID($_XNOR_), ID($_MUX_), ID($_NMUX_), ID($_NOT_), ID($anyconst), ID($allconst), ID($assume), ID($assert)) && module->design->module(cell->type) == nullptr) { + log_cmd_error("Unsupported cell type \"%s\" found. Run `techmap` first.\n", cell->type); + } + if (cell->type.in(ID($_AND_), ID($_NAND_), ID($_OR_), ID($_NOR_))) { + const unsigned int A = 0, B = 1, Y = 2; + const unsigned int NUM_PORTS = 3; + RTLIL::SigSpec ports[NUM_PORTS] = {cell->getPort(ID::A), cell->getPort(ID::B), cell->getPort(ID::Y)}; + RTLIL::SigSpec port_taints[NUM_PORTS]; + + if (ports[A].size() != 1 || ports[B].size() != 1 || ports[Y].size() != 1) + log_cmd_error("Multi-bit signal found. Run `splitnets` first.\n"); + for (unsigned int i = 0; i < NUM_PORTS; ++i) + port_taints[i] = get_corresponding_taint_signal(ports[i]); + + if (opt_create_precise_model) + add_precise_GLIFT_logic(cell, ports[A], port_taints[A], ports[B], port_taints[B], port_taints[Y]); + else if (opt_create_imprecise_model) + add_imprecise_GLIFT_logic_3(cell, port_taints[A], port_taints[B], port_taints[Y]); + else if (opt_create_instrumented_model) { + std::vector taint_version; + int num_versions = opt_instrumentmore? 8 : 4; + + for (auto i = 1; i <= num_versions; ++i) + taint_version.emplace_back(RTLIL::SigSpec(module->addWire(stringf("%s_y%d", cell->name, i), 1))); + + for (auto i = 0; i < num_versions; ++i) { + switch(i) { + case 0: add_precise_GLIFT_logic(cell, ports[A], port_taints[A], ports[B], port_taints[B], taint_version[i]); + break; + case 1: add_imprecise_GLIFT_logic_1(cell, ports[A], port_taints[A], ports[B], port_taints[B], taint_version[i]); + break; + case 2: add_imprecise_GLIFT_logic_2(cell, ports[A], port_taints[A], ports[B], port_taints[B], taint_version[i]); + break; + case 3: add_imprecise_GLIFT_logic_3(cell, port_taints[A], port_taints[B], taint_version[i]); + break; + case 4: add_imprecise_GLIFT_logic_4(port_taints[A], taint_version[i]); + break; + case 5: add_imprecise_GLIFT_logic_5(port_taints[B], taint_version[i]); + break; + case 6: add_imprecise_GLIFT_logic_6(taint_version[i]); + break; + case 7: add_imprecise_GLIFT_logic_7(taint_version[i]); + break; + default: log_assert(false); + } + } + + auto select_width = log2(num_versions); + log_assert(exp2(select_width) == num_versions); + RTLIL::SigSpec meta_mux_select(module->addWire(cell->name.str() + "_sel", select_width)); + meta_mux_selects.push_back(make_pair(meta_mux_select, cell->type)); + module->connect(meta_mux_select, module->Anyconst(cell->name.str() + "_hole", select_width, cell->get_src_attribute())); + + std::vector next_meta_mux_y_ports, meta_mux_y_ports(taint_version); + for (auto i = 0; meta_mux_y_ports.size() > 1; ++i) { + for (auto j = 0; j+1 < GetSize(meta_mux_y_ports); j += 2) { + next_meta_mux_y_ports.emplace_back(module->Mux(stringf("%s_mux_%d_%d", cell->name, i, j), meta_mux_y_ports[j], meta_mux_y_ports[j+1], meta_mux_select[GetSize(meta_mux_select) - 1 - i])); + } + if (GetSize(meta_mux_y_ports) % 2 == 1) + next_meta_mux_y_ports.push_back(meta_mux_y_ports[GetSize(meta_mux_y_ports) - 1]); + meta_mux_y_ports.swap(next_meta_mux_y_ports); + next_meta_mux_y_ports.clear(); + } + log_assert(meta_mux_y_ports.size() == 1); + module->connect(port_taints[Y], meta_mux_y_ports[0]); + } + else log_cmd_error("This is a bug (1).\n"); + } + else if (cell->type.in(ID($_XOR_), ID($_XNOR_))) { + const unsigned int A = 0, B = 1, Y = 2; + const unsigned int NUM_PORTS = 3; + RTLIL::SigSpec ports[NUM_PORTS] = {cell->getPort(ID::A), cell->getPort(ID::B), cell->getPort(ID::Y)}; + RTLIL::SigSpec port_taints[NUM_PORTS]; + + if (ports[A].size() != 1 || ports[B].size() != 1 || ports[Y].size() != 1) + log_cmd_error("Multi-bit signal found. Run `splitnets` first.\n"); + for (unsigned int i = 0; i < NUM_PORTS; ++i) + port_taints[i] = get_corresponding_taint_signal(ports[i]); + + if (opt_create_precise_model || opt_create_imprecise_model) + add_imprecise_GLIFT_logic_3(cell, port_taints[A], port_taints[B], port_taints[Y]); + else if (opt_create_instrumented_model) { + std::vector taint_version; + int num_versions = 4; + auto select_width = log2(num_versions); + log_assert(exp2(select_width) == num_versions); + + for (auto i = 1; i <= num_versions; ++i) + taint_version.emplace_back(RTLIL::SigSpec(module->addWire(stringf("%s_y%d", cell->name, i), 1))); + + for (auto i = 0; i < num_versions; ++i) { + switch(i) { + case 0: add_imprecise_GLIFT_logic_3(cell, port_taints[A], port_taints[B], taint_version[i]); + break; + case 1: add_imprecise_GLIFT_logic_4(port_taints[A], taint_version[i]); + break; + case 2: add_imprecise_GLIFT_logic_5(port_taints[B], taint_version[i]); + break; + case 3: add_imprecise_GLIFT_logic_6(taint_version[i]); + break; + default: log_assert(false); + } + } + + RTLIL::SigSpec meta_mux_select(module->addWire(cell->name.str() + "_sel", select_width)); + meta_mux_selects.push_back(make_pair(meta_mux_select, cell->type)); + module->connect(meta_mux_select, module->Anyconst(cell->name.str() + "_hole", select_width, cell->get_src_attribute())); + + std::vector next_meta_mux_y_ports, meta_mux_y_ports(taint_version); + for (auto i = 0; meta_mux_y_ports.size() > 1; ++i) { + for (auto j = 0; j+1 < GetSize(meta_mux_y_ports); j += 2) { + next_meta_mux_y_ports.emplace_back(module->Mux(stringf("%s_mux_%d_%d", cell->name, i, j), meta_mux_y_ports[j], meta_mux_y_ports[j+1], meta_mux_select[GetSize(meta_mux_select) - 1 - i])); + } + if (GetSize(meta_mux_y_ports) % 2 == 1) + next_meta_mux_y_ports.push_back(meta_mux_y_ports[GetSize(meta_mux_y_ports) - 1]); + meta_mux_y_ports.swap(next_meta_mux_y_ports); + next_meta_mux_y_ports.clear(); + } + log_assert(meta_mux_y_ports.size() == 1); + module->connect(port_taints[Y], meta_mux_y_ports[0]); + } + else log_cmd_error("This is a bug (2).\n"); + + } + else if (cell->type.in(ID($_MUX_), ID($_NMUX_))) { + const unsigned int A = 0, B = 1, S = 2, Y = 3; + const unsigned int NUM_PORTS = 4; + RTLIL::SigSpec ports[NUM_PORTS] = {cell->getPort(ID::A), cell->getPort(ID::B), cell->getPort(ID::S), cell->getPort(ID::Y)}; + RTLIL::SigSpec port_taints[NUM_PORTS]; + + if (ports[A].size() != 1 || ports[B].size() != 1 || ports[S].size() != 1 || ports[Y].size() != 1) + log_cmd_error("Multi-bit signal found. Run `splitnets` first.\n"); + for (unsigned int i = 0; i < NUM_PORTS; ++i) + port_taints[i] = get_corresponding_taint_signal(ports[i]); + + add_precise_GLIFT_mux(cell, ports[A], port_taints[A], ports[B], port_taints[B], ports[S], port_taints[S], port_taints[Y]); + } + else if (cell->type.in(ID($_NOT_))) { + const unsigned int A = 0, Y = 1; + const unsigned int NUM_PORTS = 2; + RTLIL::SigSpec ports[NUM_PORTS] = {cell->getPort(ID::A), cell->getPort(ID::Y)}; + RTLIL::SigSpec port_taints[NUM_PORTS]; + + if (ports[A].size() != 1 || ports[Y].size() != 1) + log_cmd_error("Multi-bit signal found. Run `splitnets` first.\n"); + for (unsigned int i = 0; i < NUM_PORTS; ++i) + port_taints[i] = get_corresponding_taint_signal(ports[i]); + + if (cell->type == ID($_NOT_)) { + module->connect(port_taints[Y], port_taints[A]); + } + else log_cmd_error("This is a bug (3).\n"); + } + else if (module->design->module(cell->type) != nullptr) { + //User cell type + //This function is called on modules according to topological order, so we do not need to + //recurse to GLIFT model the child module. However, we need to augment the ports list + //with taint signals and connect the new ports to the corresponding taint signals. + RTLIL::Module *cell_module_def = module->design->module(cell->type); + dict orig_ports = cell->connections(); + log("Adding cell %s\n", cell_module_def->name); + for (auto &it : orig_ports) { + RTLIL::SigSpec port = it.second; + RTLIL::SigSpec port_taint = get_corresponding_taint_signal(port); + + log_assert(port_taint.is_wire()); + log_assert(std::find(cell_module_def->ports.begin(), cell_module_def->ports.end(), port_taint.as_wire()->name) != cell_module_def->ports.end()); + cell->setPort(port_taint.as_wire()->name, port_taint); + } + } + else log_cmd_error("This is a bug (4).\n"); + } //end foreach cell in cells + + for (auto &conn : connections) { + RTLIL::SigSpec first = get_corresponding_taint_signal(conn.first); + RTLIL::SigSpec second = get_corresponding_taint_signal(conn.second); + + module->connect(first, second); + + if(conn.second.is_wire() && conn.second.as_wire()->port_input) + second.as_wire()->port_input = true; + if(conn.first.is_wire() && conn.first.as_wire()->port_output) + new_taint_outputs.push_back(first.as_wire()); + } //end foreach conn in connections + + //Create a rough model of area by summing the (potentially simplified) "weight" score of each meta-mux select: + if (!opt_nocostmodel) { + std::vector meta_mux_select_sums; + std::vector meta_mux_select_sums_buf; + for (auto &it : meta_mux_selects) { + meta_mux_select_sums.emplace_back(score_metamux_select(it.first, it.second)); + } + for (unsigned int i = 0; meta_mux_select_sums.size() > 1; ) { + meta_mux_select_sums_buf.clear(); + for (i = 0; i + 1 < meta_mux_select_sums.size(); i += 2) { + meta_mux_select_sums_buf.push_back(module->Add(meta_mux_select_sums[i].as_wire()->name.str() + "_add", meta_mux_select_sums[i], meta_mux_select_sums[i+1], false)); + } + if (meta_mux_select_sums.size() % 2 == 1) + meta_mux_select_sums_buf.push_back(meta_mux_select_sums[meta_mux_select_sums.size()-1]); + meta_mux_select_sums.swap(meta_mux_select_sums_buf); + } + if (meta_mux_select_sums.size() > 0) { + meta_mux_select_sums[0].as_wire()->set_bool_attribute(ID::minimize); + meta_mux_select_sums[0].as_wire()->set_bool_attribute(ID::keep); + module->rename(meta_mux_select_sums[0].as_wire(), cost_model_wire_name); + } + } + + //Mark new module outputs: + for (auto &port_name : module->ports) { + RTLIL::Wire *port = module->wire(port_name); + log_assert(port != nullptr); + if (is_top_module && port->port_output && !opt_keepoutputs) + port->port_output = false; + } + for (auto &output : new_taint_outputs) + output->port_output = true; + module->fixup_ports(); //we have some new taint signals in the module interface + module->set_bool_attribute(glift_attribute_name, true); + } + +public: + GliftWorker(RTLIL::Module *_module, bool _is_top_module, bool _opt_create_precise_model, bool _opt_create_imprecise_model, bool _opt_create_instrumented_model, bool _opt_taintconstants, bool _opt_keepoutputs, bool _opt_simplecostmodel, bool _opt_nocostmodel, bool _opt_instrumentmore) { + module = _module; + is_top_module = _is_top_module; + opt_create_precise_model = _opt_create_precise_model; + opt_create_imprecise_model = _opt_create_imprecise_model; + opt_create_instrumented_model = _opt_create_instrumented_model; + opt_taintconstants = _opt_taintconstants; + opt_keepoutputs = _opt_keepoutputs; + opt_simplecostmodel = _opt_simplecostmodel; + opt_nocostmodel = _opt_nocostmodel; + opt_instrumentmore = _opt_instrumentmore; + + create_glift_logic(); + } +}; + +struct GliftPass : public Pass { + GliftPass() : Pass("glift", "create GLIFT models and optimization problems") {} + + bool formatted_help() override { + auto *help = PrettyHelp::get_current(); + help->set_group("formal"); + return false; + } + + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" glift [options] [selection]\n"); + log("\n"); + log("Augments the current or specified module with gate-level information flow \n"); + log("tracking (GLIFT) logic using the \"constructive mapping\" approach. Also can set\n"); + log("up QBF-SAT optimization problems in order to optimize GLIFT models or trade off\n"); + log("precision and complexity.\n"); + log("\n"); + log("\n"); + log("Commands:\n"); + log("\n"); + log(" -create-precise-model\n"); + log(" Replaces the current or specified module with one that has corresponding\n"); + log(" \"taint\" inputs, outputs, and internal nets along with precise taint\n"); + log(" tracking logic. For example, precise taint tracking logic for an AND gate\n"); + log(" is:\n"); + log("\n"); + log(" y_t = a & b_t | b & a_t | a_t & b_t\n"); + log("\n"); + log("\n"); + log(" -create-imprecise-model\n"); + log(" Replaces the current or specified module with one that has corresponding\n"); + log(" \"taint\" inputs, outputs, and internal nets along with imprecise \"All OR\"\n"); + log(" taint tracking logic:\n"); + log("\n"); + log(" y_t = a_t | b_t\n"); + log("\n"); + log("\n"); + log(" -create-instrumented-model\n"); + log(" Replaces the current or specified module with one that has corresponding\n"); + log(" \"taint\" inputs, outputs, and internal nets along with 4 varying-precision\n"); + log(" versions of taint tracking logic. Which version of taint tracking logic is\n"); + log(" used for a given gate is determined by a MUX selected by an $anyconst cell.\n"); + log(" By default, unless the `-no-cost-model` option is provided, an additional\n"); + log(" wire named `__glift_weight` with the `keep` and `minimize` attributes is\n"); + log(" added to the module along with pmuxes and adders to calculate a rough\n"); + log(" estimate of the number of logic gates in the GLIFT model given an assignment\n"); + log(" for the $anyconst cells. The four versions of taint tracking logic for an\n"); + log(" AND gate are:\n"); + log(" y_t = a & b_t | b & a_t | a_t & b_t (like `-create-precise-model`)\n"); + log(" y_t = a_t | a & b_t\n"); + log(" y_t = b_t | b & a_t\n"); + log(" y_t = a_t | b_t (like `-create-imprecise-model`)\n"); + log("\n"); + log("\n"); + log("Options:\n"); + log("\n"); + log(" -taint-constants\n"); + log(" Constant values in the design are labeled as tainted.\n"); + log(" (default: label constants as un-tainted)\n"); + log("\n"); + log(" -keep-outputs\n"); + log(" Do not remove module outputs. Taint tracking outputs will appear in the\n"); + log(" module ports alongside the orignal outputs.\n"); + log(" (default: original module outputs are removed)\n"); + log("\n"); + log(" -simple-cost-model\n"); + log(" Do not model logic area. Instead model the number of non-zero assignments to\n"); + log(" $anyconsts. Taint tracking logic versions vary in their size, but all\n"); + log(" reduced-precision versions are significantly smaller than the fully-precise\n"); + log(" version. A non-zero $anyconst assignment means that reduced-precision taint\n"); + log(" tracking logic was chosen for some gate. Only applicable in combination with\n"); + log(" `-create-instrumented-model`. (default: use a complex model and give that\n"); + log(" wire the \"keep\" and \"minimize\" attributes)\n"); + log("\n"); + log(" -no-cost-model\n"); + log(" Do not model taint tracking logic area and do not create a `__glift_weight`\n"); + log(" wire. Only applicable in combination with `-create-instrumented-model`.\n"); + log(" (default: model area and give that wire the \"keep\" and \"minimize\"\n"); + log(" attributes)\n"); + log("\n"); + log(" -instrument-more\n"); + log(" Allow choice from more versions of (even simpler) taint tracking logic. A\n"); + log(" total of 8 versions of taint tracking logic will be added per gate,\n"); + log(" including the 4 versions from `-create-instrumented-model` and these\n"); + log(" additional versions:\n"); + log("\n"); + log(" y_t = a_t\n"); + log(" y_t = b_t\n"); + log(" y_t = 1\n"); + log(" y_t = 0\n"); + log("\n"); + log(" Only applicable in combination with `-create-instrumented-model`.\n"); + log(" (default: do not add more versions of taint tracking logic.\n"); + log("\n"); + } + + void execute(std::vector args, RTLIL::Design *design) override + { + bool opt_create_precise_model = false, opt_create_imprecise_model = false, opt_create_instrumented_model = false; + bool opt_taintconstants = false, opt_keepoutputs = false, opt_simplecostmodel = false, opt_nocostmodel = false; + bool opt_instrumentmore = false; + log_header(design, "Executing GLIFT pass (creating and manipulating GLIFT models).\n"); + std::vector::size_type argidx; + + for (argidx = 1; argidx < args.size(); argidx++) { + if (args[argidx] == "-create-precise-model") { + opt_create_precise_model = true; + continue; + } + if (args[argidx] == "-create-imprecise-model") { + opt_create_imprecise_model = true; + continue; + } + if (args[argidx] == "-create-instrumented-model") { + opt_create_instrumented_model = true; + continue; + } + if (args[argidx] == "-taint-constants") { + opt_taintconstants = true; + continue; + } + if (args[argidx] == "-keep-outputs") { + opt_keepoutputs = true; + continue; + } + if (args[argidx] == "-simple-cost-model") { + opt_simplecostmodel = true; + continue; + } + if (args[argidx] == "-no-cost-model") { + opt_nocostmodel = true; + continue; + } + if (args[argidx] == "-instrument-more") { + opt_instrumentmore = true; + continue; + } + break; + } + if(!opt_create_precise_model && !opt_create_imprecise_model && !opt_create_instrumented_model) + log_cmd_error("No command provided. See help for usage.\n"); + if(static_cast(opt_create_precise_model) + static_cast(opt_create_imprecise_model) + static_cast(opt_create_instrumented_model) != 1) + log_cmd_error("Only one command may be specified. See help for usage.\n"); + if(opt_simplecostmodel && opt_nocostmodel) + log_cmd_error("Only one of `-simple-cost-model` and `-no-cost-model` may be specified. See help for usage.\n"); + if((opt_simplecostmodel || opt_nocostmodel) && !opt_create_instrumented_model) + log_cmd_error("Options `-simple-cost-model` and `-no-cost-model` may only be used with `-create-instrumented-model`. See help for usage.\n"); + extra_args(args, argidx, design); + + if (GetSize(design->selected_modules()) == 0) + log_cmd_error("Can't operate on an empty selection!\n"); + + TopoSort> topo_modules; //cribbed from passes/techmap/flatten.cc + auto worklist = design->selected_modules(); + pool non_top_modules; + while (!worklist.empty()) { + RTLIL::Module *module = *(worklist.begin()); + worklist.erase(worklist.begin()); + topo_modules.node(module); + + for (auto cell : module->selected_cells()) { + RTLIL::Module *tpl = design->module(cell->type); + if (tpl != nullptr) { + if (!topo_modules.has_node(tpl)) + worklist.push_back(tpl); + topo_modules.edge(tpl, module); + non_top_modules.insert(cell->type); + } + } + } + + if (!topo_modules.sort()) + log_cmd_error("Cannot handle recursive module instantiations.\n"); + + for (auto i = 0; i < GetSize(topo_modules.sorted); ++i) { + RTLIL::Module *module = topo_modules.sorted[i]; + GliftWorker(module, !non_top_modules.count(module->name), opt_create_precise_model, opt_create_imprecise_model, opt_create_instrumented_model, opt_taintconstants, opt_keepoutputs, opt_simplecostmodel, opt_nocostmodel, opt_instrumentmore); + } + } +} GliftPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/icell_liberty.cc b/chips/yosys/passes/cmds/icell_liberty.cc new file mode 100644 index 0000000000000000000000000000000000000000..33093a13bfae03dfe63fd26db79852e6fbd16963 --- /dev/null +++ b/chips/yosys/passes/cmds/icell_liberty.cc @@ -0,0 +1,209 @@ +#include "kernel/yosys.h" +#include "kernel/celltypes.h" +#include "kernel/newcelltypes.h" +#include "kernel/ff.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct LibertyStubber { + CellTypes ct; + LibertyStubber() { + ct.setup(); + ct.setup_internals_ff(); + } + void liberty_prefix(std::ostream& f) + { + f << "/*\n"; + f << stringf("\tModels interfaces of select Yosys internal cell.\n"); + f << stringf("\tLikely contains INCORRECT POLARITIES.\n"); + f << stringf("\tImpractical for any simulation, synthesis, or timing.\n"); + f << stringf("\tIntended purely for SDC expansion.\n"); + f << stringf("\tDo not microwave or tumble dry.\n"); + f << stringf("\tGenerated by %s\n", yosys_maybe_version()); + f << "*/\n"; + f << "library (yosys) {\n"; + f << "\tinput_threshold_pct_fall : 50;\n"; + f << "\tinput_threshold_pct_rise : 50;\n"; + f << "\toutput_threshold_pct_fall : 50;\n"; + f << "\toutput_threshold_pct_rise : 50;\n"; + f << "\tslew_lower_threshold_pct_fall : 1;\n"; + f << "\tslew_lower_threshold_pct_rise : 1;\n"; + f << "\tslew_upper_threshold_pct_fall : 99;\n"; + f << "\tslew_upper_threshold_pct_rise : 99;\n"; + } + void liberty_suffix(std::ostream& f) + { + f << "}\n"; + } + struct LibertyItemizer { + std::ostream& f; + int indent; + LibertyItemizer(std::ostream& f) : f(f), indent(0) {}; + void item(std::string key, std::string val) + { + f << std::string(indent, '\t') << key << " : \"" << val << "\";\n"; + } + }; + void liberty_flop(Module* base, Module* derived, std::ostream& f) + { + auto base_name = base->name.str().substr(1); + auto derived_name = derived->name.str().substr(1); + + FfTypeData ffType(base->name); + LibertyItemizer i(f); + + if (ffType.has_gclk) { + log_warning("Formal flip flop %s can't be modeled\n", base_name); + return; + } + if (ffType.has_ce) { + log_warning("DFFE %s can't be modeled\n", base_name); + return; + } + + f << "\tcell (\"" << derived_name << "\") {\n"; + auto& base_type = ct.cell_types[base->name]; + i.indent = 3; + auto sorted_ports = derived->ports; + // Hack for CLK and C coming before Q does + auto cmp = [derived](IdString l, IdString r) { return derived->twines().str(l) < derived->twines().str(r); }; + std::sort(sorted_ports.begin(), sorted_ports.end(), cmp); + std::string clock_pin_name = ""; + for (auto x : sorted_ports) { + std::string port_name = derived->twines().unescaped_str(x); + bool is_input = base_type.inputs.count(x); + bool is_output = base_type.outputs.count(x); + f << "\t\tpin (" << port_name << ") {\n"; + if (is_input && !is_output) { + i.item("direction", "input"); + } else if (!is_input && is_output) { + i.item("direction", "output"); + } else { + i.item("direction", "inout"); + } + if (port_name == "CLK" || port_name == "C") { + i.item("clock", "true"); + clock_pin_name = port_name; + } + if (port_name == "Q") { + i.item("function", "IQ"); + f << "\t\t\ttiming () {\n"; + i.indent++; + log_assert(clock_pin_name.size()); + i.item("related_pin", clock_pin_name); + i.indent--; + f << "\t\t\t}\n"; + } + f << "\t\t}\n"; + } + + f << "\t\tff (\"IQ\",\"IQ_N\") {\n"; + i.indent = 3; + // TODO polarities? + if (ffType.has_clk) { + auto pin = ffType.is_fine ? "C" : "CLK"; + i.item("clocked_on", pin); + } + if (ffType.has_arst) { + auto meaning = (ffType.val_arst == State::S1) ? "preset" : "clear"; + auto pin = ffType.is_fine ? "R" : "ARST"; + i.item(meaning, pin); + } + auto next_state = ffType.has_ce ? "D & EN" : "D"; + i.item("next_state", next_state); + f << "\t\t}\n"; + f << "\t}\n"; + } + void liberty_cell(Module* base, Module* derived, std::ostream& f) + { + auto base_name = base->name.str().substr(1); + auto derived_name = derived->name.str().substr(1); + if (!ct.cell_types.count(base->name)) { + log_debug("skip skeleton for %s\n", base_name); + return; + } + + if (StaticCellTypes::categories.is_ff(base->name)) + return liberty_flop(base, derived, f); + + auto& base_type = ct.cell_types[base->name]; + f << "\tcell (\"" << derived_name << "\") {\n"; + for (auto x : derived->ports) { + std::string port_name = derived->twines().unescaped_str(x); + bool is_input = base_type.inputs.count(x); + bool is_output = base_type.outputs.count(x); + f << "\t\tpin (" << port_name << ") {\n"; + if (is_input && !is_output) { + f << "\t\t\tdirection : input;\n"; + } else if (!is_input && is_output) { + f << "\t\t\tdirection : output;\n"; + } else { + f << "\t\t\tdirection : inout;\n"; + } + f << "\t\t}\n"; + } + f << "\t}\n"; + } +}; + +struct IcellLiberty : Pass { + IcellLiberty() : Pass("icell_liberty", "write Liberty interfaces for used internal cells") {} + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" icell_liberty \n"); + log("\n"); + log("Write Liberty files modeling the interfaces of used internal cells.\n"); + log("\n"); + log("Models are not guaranteed to be logically sound.\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *d) override + { + log_header(d, "Executing ICELL_LIBERTY pass.\n"); + + size_t argidx; + std::string liberty_filename; + auto liberty_file = std::make_unique(); + + for (argidx = 1; argidx < args.size(); argidx++) { + break; + } + if (argidx < args.size()) + liberty_filename = args[argidx++]; + else + log_cmd_error("no Liberty filename specified\n"); + + if (liberty_filename.size()) { + liberty_file->open(liberty_filename.c_str()); + if (liberty_file->fail()) { + log_cmd_error("Can't open file `%s' for writing: %s\n", liberty_filename, strerror(errno)); + } + } + + pool done; + LibertyStubber stubber = {}; + + stubber.liberty_prefix(*liberty_file); + + for (auto module : d->selected_modules()) { + for (auto cell : module->selected_cells()) { + Module *inst_module = d->module(cell->type); + if (!inst_module || !inst_module->get_blackbox_attribute()) + continue; + Module *base = inst_module; + IdString base_name_id = base->name; + if (!done.count(base_name_id)) { + stubber.liberty_cell(base, base, *liberty_file); + done.insert(base_name_id); + } + } + } + + stubber.liberty_suffix(*liberty_file); + } +} IcellLiberty; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/internal_stats.cc b/chips/yosys/passes/cmds/internal_stats.cc new file mode 100644 index 0000000000000000000000000000000000000000..65e74cc044b33814ffe120690c4b004c6e10fead --- /dev/null +++ b/chips/yosys/passes/cmds/internal_stats.cc @@ -0,0 +1,124 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include + +#include "kernel/yosys.h" +#include "kernel/celltypes.h" +#include "passes/techmap/libparse.h" +#include "kernel/cost.h" +#include "frontends/ast/ast.h" +#include "libs/json11/json11.hpp" + +#if defined(__APPLE__) && defined(__MACH__) +#include +#include +#endif + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +std::optional current_mem_bytes() { + +#if defined(__APPLE__) + task_basic_info_64_data_t basicInfo; + mach_msg_type_number_t count = TASK_BASIC_INFO_64_COUNT; + kern_return_t error = task_info(mach_task_self(), TASK_BASIC_INFO_64, (task_info_t)&basicInfo, &count); + if (error != KERN_SUCCESS) { + return {}; // Error getting task information + } + return basicInfo.resident_size; // Return RSS in KB + +#elif defined(__linux__) + // Not all linux distributions have to have this file + std::ifstream statusFile("/proc/self/status"); + std::string line; + while (std::getline(statusFile, line)) { + if (line.find("VmRSS:") == 0) { + std::istringstream iss(line); + std::string token; + // Skip prefix + iss >> token; + uint64_t rss; + iss >> rss; + return rss * 1024; + } + } + // Error reading /proc/self/status + return {}; + +#else + return {}; +#endif +} + +struct InternalStatsPass : public Pass { + InternalStatsPass() : Pass("internal_stats", "print internal statistics") { + experimental(); + internal(); + } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("Print internal statistics for developers (experimental)\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + bool json_mode = false; + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) + { + if (args[argidx] == "-json") { + json_mode = true; + continue; + } + break; + } + extra_args(args, argidx, design); + + if(!json_mode) + log_header(design, "Printing internal statistics.\n"); + + log_experimental("internal_stats"); + + if (json_mode) { + log("{\n"); + log(" \"creator\": %s,\n", json11::Json(yosys_maybe_version()).dump()); + std::stringstream invocation; + std::copy(args.begin(), args.end(), std::ostream_iterator(invocation, " ")); + log(" \"invocation\": %s,\n", json11::Json(invocation.str()).dump()); + if (auto mem = current_mem_bytes()) { + log(" \"memory_now\": %s,\n", std::to_string(*mem)); + } + auto ast_bytes = AST::astnode_count() * (unsigned long long) sizeof(AST::AstNode); + log(" \"memory_ast\": %s,\n", std::to_string(ast_bytes)); + } + + // stats go here + + if (json_mode) { + log("\n"); + log("}\n"); + } + + } +} InternalStatsPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/linecoverage.cc b/chips/yosys/passes/cmds/linecoverage.cc new file mode 100644 index 0000000000000000000000000000000000000000..ce588fd6cb75b268fc94882b5e0352a95ca4d22c --- /dev/null +++ b/chips/yosys/passes/cmds/linecoverage.cc @@ -0,0 +1,152 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "kernel/sigtools.h" + +#include + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + + +static const std::regex src_re("(.*):(\\d+)\\.(\\d+)-(\\d+)\\.(\\d+)"); + +struct CoveragePass : public Pass { + CoveragePass() : Pass("linecoverage", "report coverage information") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" linecoverage [options] [selection]\n"); + log("\n"); + log("This command prints coverage information on the design based on the current\n"); + log("selection, where items in the selection are considered covered and items not in\n"); + log("the selection are considered uncovered. If the same source location is found\n"); + log("both on items inside and out of the selection, it is considered uncovered.\n"); + log("\n"); + log(" -lcov \n"); + log(" write coverage information in lcov format to this file\n"); + log("\n"); + } + + std::string extract_src_filename(std::string src) const + { + std::smatch m; + if (std::regex_match(src, m, src_re)) { + return m[1].str(); + }; + return ""; + } + + std::pair extract_src_lines(std::string src) const + { + std::smatch m; + if (std::regex_match(src, m, src_re)) { + return std::make_pair(stoi(m[2].str()), stoi(m[4].str())); + }; + return std::make_pair(0,0); + } + + void execute(std::vector args, RTLIL::Design *design) override + { + std::string ofile; + + log_header(design, "Executing linecoverage pass.\n"); + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) + { + if (args[argidx] == "-lcov" && argidx+1 < args.size()) { + ofile = args[++argidx]; + continue; + } + break; + } + extra_args(args, argidx, design); + + std::ofstream fout; + if (!ofile.empty()) { + fout.open(ofile, std::ios::out | std::ios::trunc); + if (!fout.is_open()) + log_error("Could not open file \"%s\" with write access.\n", ofile); + } + + std::map> uncovered_lines; + std::map> all_lines; + + for (auto module : design->modules()) + { + log_debug("Module %s:\n", module); + for (auto wire: module->wires()) { + log_debug("%s\t%s\t%s\n", module->selected(wire) ? "*" : " ", wire->get_src_attribute(), wire); + for (auto src: wire->get_strpool_attribute(ID::src)) { + auto filename = extract_src_filename(src); + if (filename.empty()) continue; + auto [begin, end] = extract_src_lines(src); + for (int l = begin; l <=end; l++) { + if (l == 0) continue; + all_lines[filename].insert(l); + if (!module->selected(wire)) + uncovered_lines[filename].insert(l); + } + } + } + for (auto cell: module->cells()) { + log_debug("%s\t%s\t%s\n", module->selected(cell) ? "*" : " ", cell->get_src_attribute(), cell); + for (auto src: cell->get_strpool_attribute(ID::src)) { + auto filename = extract_src_filename(src); + if (filename.empty()) continue; + auto [begin, end] = extract_src_lines(src); + for (int l = begin; l <=end; l++) { + if (l == 0) continue; + all_lines[filename].insert(l); + if (!module->selected(cell)) + uncovered_lines[filename].insert(l); + } + } + } + log_debug("\n"); + } + + for (const auto& file_entry : all_lines) { + int lines_found = file_entry.second.size(); + int lines_hit = file_entry.second.size() - (uncovered_lines.count(file_entry.first) ? uncovered_lines[file_entry.first].size() : 0); + log("File %s: %d/%d lines covered\n", file_entry.first, lines_hit, lines_found); + + if(!ofile.empty()) { + fout << "SF:" << file_entry.first << "\n"; + for (int l : file_entry.second) { + fout << "DA:" << l << ","; + if (uncovered_lines.count(file_entry.first) && uncovered_lines[file_entry.first].count(l)) + fout << "0"; + else + fout << "1"; + fout << "\n"; + } + fout << "LF:" << lines_found << "\n"; + fout << "LH:" << lines_hit << "\n"; + fout << "end_of_record\n"; + } + } + + } +} CoveragePass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/linux_perf.cc b/chips/yosys/passes/cmds/linux_perf.cc new file mode 100644 index 0000000000000000000000000000000000000000..79047883490996dc6353ffe3074aba3f83e25489 --- /dev/null +++ b/chips/yosys/passes/cmds/linux_perf.cc @@ -0,0 +1,102 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2014 Claire Xenia Wolf + * Copyright (C) 2014 Johann Glaser + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "kernel/log_help.h" + +#include +#include + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +#ifdef __linux__ +#include +struct LinuxPerf : public Pass { + LinuxPerf() : Pass("linux_perf", "turn linux perf recording off or on") { + internal(); + } + bool formatted_help() override + { + auto *help = PrettyHelp::get_current(); + + auto content_root = help->get_root(); + + content_root->usage("linux_perf [on|off]"); + + content_root->paragraph( + "This pass turns Linux 'perf' profiling on or off, when it has been configured to use control FIFOs." + "YOSYS_PERF_CTL and YOSYS_PERF_ACK must point to Linux perf control FIFOs." + ); + content_root->paragraph("Example shell command line:"); + content_root->codeblock( + "mkfifo /tmp/perf.fifo /tmp/perf-ack.fifo\n" + "YOSYS_PERF_CTL=/tmp/perf.fifo YOSYS_PERF_ACK=/tmp/perf-ack.fifo \\\n" + " perf record --latency --delay=-1 \\\n" + " --control=fifo:/tmp/perf.fifo,/tmp/perf-ack.fifo --call-graph=dwarf ./yosys \\\n" + " -dt -p \"read_rtlil design.rtlil; linux_perf on; opt_clean; linux_perf off\"\n" + ); + + return true; + } + void execute(std::vector args, RTLIL::Design *) override + { + if (args.size() > 2) + cmd_error(args, 2, "Unexpected argument."); + + std::string_view ctl_msg; + if (args.size() == 2) { + if (args[1] == "on") + ctl_msg = "enable\n"; + else if (args[1] == "off") + ctl_msg = "disable\n"; + else + cmd_error(args, 1, "Unexpected argument."); + } + + const char *ctl_fifo = std::getenv("YOSYS_PERF_CTL"); + if (!ctl_fifo) + log_error("YOSYS_PERF_CTL environment variable not set.\n"); + const char *ack_fifo = std::getenv("YOSYS_PERF_ACK"); + if (!ack_fifo) + log_error("YOSYS_PERF_ACK environment variable not set.\n"); + + int ctl_fd = open(ctl_fifo, O_WRONLY); + if (ctl_fd < 0) + log_error("Failed to open YOSYS_PERF_CTL.\n"); + int ack_fd = open(ack_fifo, O_RDONLY); + if (ack_fd < 0) + log_error("Failed to open YOSYS_PERF_ACK.\n"); + int result = write(ctl_fd, ctl_msg.data(), ctl_msg.size()); + if (result != static_cast(ctl_msg.size())) + log_error("Failed to write to YOSYS_PERF_CTL.\n"); + char buffer[64]; + result = read(ack_fd, buffer, sizeof(buffer)); + close(ctl_fd); + close(ack_fd); + if (result <= 0) + log_error("Failed to read from YOSYS_PERF_ACK.\n"); + if (strcmp(buffer, "ack\n") != 0) + log_error("YOSYS_PERF_ACK did not return 'ack'.\n"); + } +} LinuxPerf; +#endif + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/logcmd.cc b/chips/yosys/passes/cmds/logcmd.cc new file mode 100644 index 0000000000000000000000000000000000000000..dd2d708d85d9bba37ac251ad8a9df988bde2b13c --- /dev/null +++ b/chips/yosys/passes/cmds/logcmd.cc @@ -0,0 +1,115 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * Copyright (C) 2014 Johann Glaser + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "kernel/log_help.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct LogPass : public Pass { + LogPass() : Pass("log", "print text and log files") { } + bool formatted_help() override { + auto *help = PrettyHelp::get_current(); + help->set_group("passes/status"); + return false; + } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" log [options] string\n"); + log(" log [ -push | -pop ]\n"); + log("\n"); + log("Print the given string to the screen and/or the log file. This is useful for TCL\n"); + log("scripts, because the TCL command \"puts\" only goes to stdout but not to\n"); + log("logfiles.\n"); + log("\n"); + log(" -stdout\n"); + log(" Print the output to stdout too. This is useful when all Yosys is\n"); + log(" executed with a script and the -q (quiet operation) argument to notify\n"); + log(" the user.\n"); + log("\n"); + log(" -stderr\n"); + log(" Print the output to stderr too.\n"); + log("\n"); + log(" -nolog\n"); + log(" Don't use the internal log() command. Use either -stdout or -stderr,\n"); + log(" otherwise no output will be generated at all.\n"); + log("\n"); + log(" -n\n"); + log(" do not append a newline\n"); + log("\n"); + log(" -header\n"); + log(" log a pass header\n"); + log("\n"); + log(" -push\n"); + log(" push a new level on the pass counter\n"); + log("\n"); + log(" -pop\n"); + log(" pop from the pass counter\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design* design) override + { + size_t argidx; + bool to_stdout = false; + bool to_stderr = false; + bool to_log = true; + bool newline = true; + bool header = false; + bool push = false; + bool pop = false; + std::string text; + + for (argidx = 1; argidx < args.size(); argidx++) + { + if (args[argidx] == "-stdout") to_stdout = true; + else if (args[argidx] == "-stderr") to_stderr = true; + else if (args[argidx] == "-nolog") to_log = false; + else if (args[argidx] == "-n") newline = false; + else if (args[argidx] == "-header") header = true; + else if (args[argidx] == "-push") push = true; + else if (args[argidx] == "-pop") pop = true; + else break; + } + + if ((push || pop) && args.size() != 2) + log_cmd_error("Bad usage: 'log -push' or 'log -pop' must be used without other arguments.\n"); + + if (push) { log_push(); return; } + if (pop) { log_pop(); return; } + + for (; argidx < args.size(); argidx++) + text += args[argidx] + ' '; + if (!text.empty()) text.resize(text.size()-1); + + const char *line_end = newline ? "\n" : ""; + + if (to_stdout) fprintf(stdout, "%s%s", text.c_str(), line_end); + if (to_stderr) fprintf(stderr, "%s%s", text.c_str(), line_end); + if (to_log) { + if (!header) log("%s%s", text, line_end); + else log_header(design, "%s%s", text, line_end); + } + } +} LogPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/logger.cc b/chips/yosys/passes/cmds/logger.cc new file mode 100644 index 0000000000000000000000000000000000000000..2c08cd458b1804c54c05513526ba39ad8e0270cd --- /dev/null +++ b/chips/yosys/passes/cmds/logger.cc @@ -0,0 +1,185 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2020 Miodrag Milanovic + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "kernel/log_help.h" +#include + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct LoggerPass : public Pass { + LoggerPass() : Pass("logger", "set logger properties") { } + bool formatted_help() override { + auto *help = PrettyHelp::get_current(); + help->set_group("passes/status"); + return false; + } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" logger [options]\n"); + log("\n"); + log("This command sets global logger properties, also available using command line\n"); + log("options.\n"); + log("\n"); + log(" -[no]time\n"); + log(" enable/disable display of timestamp in log output.\n"); + log("\n"); + log(" -warn regex\n"); + log(" print a warning for all log messages matching the regex.\n"); + log("\n"); + log(" -nowarn regex\n"); + log(" if a warning message matches the regex, it is printed as regular\n"); + log(" message instead.\n"); + log("\n"); + log(" -werror regex\n"); + log(" if a warning message matches the regex, it is printed as error\n"); + log(" message instead and the tool terminates with a nonzero return code.\n"); + log("\n"); + log(" -[no]debug\n"); + log(" globally enable/disable debug log messages.\n"); + log("\n"); + log(" -experimental \n"); + log(" do not print warnings for the specified experimental feature\n"); + log("\n"); + log(" -expect \n"); + log(" expect log, warning or error to appear. matched errors will terminate\n"); + log(" with exit code 0.\n"); + log(" Types prefix-log, prefix-warning and prefix-error match the entire\n"); + log(" logged string, including filename if present.\n"); + log("\n"); + log(" -expect-no-warnings\n"); + log(" gives error in case there is at least one warning that is not expected.\n"); + log("\n"); + log(" -check-expected\n"); + log(" verifies that the patterns previously set up by -expect have actually\n"); + log(" been met, then clears the expected log list. If this is not called\n"); + log(" manually, the check will happen at yosys exit time instead.\n"); + log("\n"); + } + + void execute(std::vector args, RTLIL::Design * design) override + { + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) + { + + if (args[argidx] == "-time") { + logger().set_log_time(true); + log("Enabled timestamp in logs.\n"); + continue; + } + if (args[argidx] == "-notime") { + logger().set_log_time(false); + log("Disabled timestamp in logs.\n"); + continue; + } + if (args[argidx] == "-warn" && argidx+1 < args.size()) { + std::string pattern = args[++argidx]; + if (pattern.front() == '\"' && pattern.back() == '\"') pattern = pattern.substr(1, pattern.size() - 2); + try { + log("Added regex '%s' for warnings to warn list.\n", pattern); + logger().add_warn(pattern); + } + catch (const std::regex_error& e) { + log_cmd_error("Error in regex expression '%s' !\n", pattern); + } + continue; + } + if (args[argidx] == "-nowarn" && argidx+1 < args.size()) { + std::string pattern = args[++argidx]; + if (pattern.front() == '\"' && pattern.back() == '\"') pattern = pattern.substr(1, pattern.size() - 2); + try { + log("Added regex '%s' for warnings to nowarn list.\n", pattern); + logger().add_nowarn(pattern); + } + catch (const std::regex_error& e) { + log_cmd_error("Error in regex expression '%s' !\n", pattern); + } + continue; + } + if (args[argidx] == "-werror" && argidx+1 < args.size()) { + std::string pattern = args[++argidx]; + if (pattern.front() == '\"' && pattern.back() == '\"') pattern = pattern.substr(1, pattern.size() - 2); + try { + log("Added regex '%s' for warnings to werror list.\n", pattern); + logger().add_werror(pattern); + } + catch (const std::regex_error& e) { + log_cmd_error("Error in regex expression '%s' !\n", pattern); + } + continue; + } + if (args[argidx] == "-debug") { + logger().set_force_debug(true); + log("Enabled debug log messages.\n"); + continue; + } + if (args[argidx] == "-nodebug") { + logger().set_force_debug(false); + log("Disabled debug log messages.\n"); + continue; + } + if (args[argidx] == "-experimental" && argidx+1 < args.size()) { + std::string value = args[++argidx]; + log("Added '%s' experimental ignore list.\n", value); + logger().add_experimental_ignore(value); + continue; + } + if (args[argidx] == "-expect" && argidx+3 < args.size()) { + std::string type = args[++argidx]; + if (type!="error" && type!="warning" && type!="log" + && type!="prefix-error" && type!="prefix-warning" && type!="prefix-log") + log_cmd_error("Expect command require type to be 'log', 'warning' or 'error' !\n"); + if ((type=="error" || type=="prefix-error") && logger().expects_error()) + log_cmd_error("Only single error message can be expected !\n"); + std::string pattern = args[++argidx]; + if (pattern.front() == '\"' && pattern.back() == '\"') pattern = pattern.substr(1, pattern.size() - 2); + int count = atoi(args[++argidx].c_str()); + if (count<=0) + log_cmd_error("Number of expected messages must be higher then 0 !\n"); + if ((type=="error" || type=="prefix-error") && count!=1) + log_cmd_error("Expected error message occurrences must be 1 !\n"); + log("Added regex '%s' to expected %s messages list.\n", + pattern, type); + try { + logger().add_expect(type, pattern, count); + } + catch (const std::regex_error& e) { + log_cmd_error("Error in regex expression '%s' !\n", pattern); + } + continue; + } + if (args[argidx] == "-expect-no-warnings") { + logger().set_expect_no_warnings(true); + continue; + } + if (args[argidx] == "-check-expected") { + logger().check_expected(); + continue; + } + break; + } + extra_args(args, argidx, design, false); + } +} LoggerPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/ltp.cc b/chips/yosys/passes/cmds/ltp.cc new file mode 100644 index 0000000000000000000000000000000000000000..862768858b6fdbf3a6dee9024a54488f61d7ba5f --- /dev/null +++ b/chips/yosys/passes/cmds/ltp.cc @@ -0,0 +1,235 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "kernel/celltypes.h" +#include "kernel/sigtools.h" +#include "kernel/log_help.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct LtpWorker +{ + RTLIL::Design *design; + RTLIL::Module *module; + SigMap sigmap; + + dict> bits; + dict> bit2bits; + dict> bit2ff; + + int maxlvl; + SigBit maxbit; + pool busy; + + LtpWorker(RTLIL::Module *module, bool noff) : design(module->design), module(module), sigmap(module) + { + CellTypes ff_celltypes; + + if (noff) { + ff_celltypes.setup_internals_mem(); + ff_celltypes.setup_stdcells_mem(); + } + + for (auto wire : module->selected_wires()) + for (auto bit : sigmap(wire)) + bits[bit] = tuple(-1, State::Sx, nullptr); + + for (auto cell : module->selected_cells()) + { + pool src_bits, dst_bits; + + for (auto &conn : cell->connections()) + for (auto bit : sigmap(conn.second)) { + if (cell->input(conn.first)) + src_bits.insert(bit); + if (cell->output(conn.first)) + dst_bits.insert(bit); + } + + if (noff && ff_celltypes.cell_known(cell->type)) { + for (auto s : src_bits) + for (auto d : dst_bits) { + bit2ff[s] = tuple(d, cell); + break; + } + continue; + } + + for (auto s : src_bits) + for (auto d : dst_bits) + bit2bits[s][d] = cell; + } + + maxlvl = -1; + maxbit = State::Sx; + } + + void runner(SigBit bit, int level, SigBit from, Cell *via) + { + auto &bitinfo = bits.at(bit); + + if (get<0>(bitinfo) >= level) + return; + + if (busy.count(bit) > 0) { + log_warning("Detected loop at %s in %s\n", log_signal(bit), module); + return; + } + + busy.insert(bit); + get<0>(bitinfo) = level; + get<1>(bitinfo) = from; + get<2>(bitinfo) = via; + + if (level > maxlvl) { + maxlvl = level; + maxbit = bit; + } + + if (bit2bits.count(bit)) { + for (auto &it : bit2bits.at(bit)) + runner(it.first, level+1, bit, it.second); + } + + busy.erase(bit); + } + + void printpath(SigBit bit) + { + auto &bitinfo = bits.at(bit); + if (get<2>(bitinfo)) { + printpath(get<1>(bitinfo)); + log("%5d: %s (via %s)\n", get<0>(bitinfo), log_signal(bit), get<2>(bitinfo)); + } else { + log("%5d: %s\n", get<0>(bitinfo), log_signal(bit)); + } + } + + void selectpath(RTLIL::Selection &sel) + { + if (maxlvl < 0) + return; + + SigBit bit = maxbit; + while (true) { + if (!bit.wire) + break; + + sel.select(module, bit.wire); + + auto &bitinfo = bits.at(bit); + Cell *via = get<2>(bitinfo); + if(!via) + break; + sel.select(module, via); + + bit = get<1>(bitinfo); + } + } + + void run(bool selectMode, RTLIL::Selection &sel) + { + for (auto &it : bits) + if (get<0>(it.second) < 0) + runner(it.first, 0, State::Sx, nullptr); + + if (selectMode) { + log("\n"); + log("Longest topological path in %s is length %d.\n", module, maxlvl); + selectpath(sel); + } else { + log("\n"); + log("Longest topological path in %s (length=%d):\n", module, maxlvl); + + if (maxlvl >= 0) + printpath(maxbit); + + if (bit2ff.count(maxbit)) + log("%5s: %s (via %s)\n", "ff", log_signal(get<0>(bit2ff.at(maxbit))), get<1>(bit2ff.at(maxbit))); + } + } +}; + +struct LtpPass : public Pass { + LtpPass() : Pass("ltp", "print longest topological path") { } + bool formatted_help() override { + auto *help = PrettyHelp::get_current(); + help->set_group("passes/status"); + return false; + } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" ltp [options] [selection]\n"); + log("\n"); + log("This command prints the longest topological path in the design. (Only considers\n"); + log("paths within a single module, so the design must be flattened.)\n"); + log("\n"); + log(" -noff\n"); + log(" automatically exclude FF cell types\n"); + log("\n"); + log(" -select\n"); + log(" select the path elements instead of printing\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + bool noff = false; + bool selectMode = false; + + log_header(design, "Executing LTP pass (find longest path).\n"); + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + if (args[argidx] == "-noff") { + noff = true; + continue; + } + if (args[argidx] == "-select") { + selectMode = true; + continue; + } + break; + } + int origSelectPos = design->selection_stack.size() - 1; + extra_args(args, argidx, design); + + auto newSelection = RTLIL::Selection::EmptySelection(design); + + for (Module *module : design->selected_modules()) + { + if (module->has_processes_warn()) + continue; + + LtpWorker worker(module, noff); + worker.run(selectMode, newSelection); + } + + if (selectMode) { + log_assert(origSelectPos >= 0); + design->selection_stack[origSelectPos] = newSelection; + design->selection_stack[origSelectPos].optimize(design); + } + } +} LtpPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/optbarriers.cc b/chips/yosys/passes/cmds/optbarriers.cc new file mode 100644 index 0000000000000000000000000000000000000000..0ff1c11abea2077de8cf61a27532a5cd2cb67ada --- /dev/null +++ b/chips/yosys/passes/cmds/optbarriers.cc @@ -0,0 +1,549 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2024 George Rennie + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "kernel/sigtools.h" +#include "kernel/ffinit.h" +#include "kernel/topo_scc.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +// Standard visitor helper +template +struct overloaded : Ts... { using Ts::operator()...; }; +template +overloaded(Ts...) -> overloaded; + +// This computes a graph of assignment dependencies in a process, which is used +// to preserve SCCs in the process which are useful for DFF inference +struct ProcessDependencyWorker { + ProcessDependencyWorker(const RTLIL::Process& proc) { + add_process(proc); + find_sccs(); + } + + ProcessDependencyWorker(const std::vector& connections) { + for (const auto& sigsig : connections) + add_sigsig(sigsig); + find_sccs(); + } + + void add_process(const RTLIL::Process& proc) { + add_caserule(proc.root_case); + + for (const auto* sync : proc.syncs) + add_syncrule(*sync); + } + + void add_syncrule(const RTLIL::SyncRule& sync) { + for (const auto& sigsig : sync.actions) + add_sigsig(sigsig); + } + + void add_caserule(const RTLIL::CaseRule& caserule) { + for (const auto& sigsig : caserule.actions) + add_sigsig(sigsig); + + for (const auto* rule : caserule.switches) + add_switchrule(*rule); + } + + void add_switchrule(const RTLIL::SwitchRule& switchrule) { + for (const auto* rule : switchrule.cases) + add_caserule(*rule); + } + + void add_sigsig(const RTLIL::SigSig& sigsig) { + for (int i = 0; i < GetSize(sigsig.first); i++) { + const auto lhs = sigsig.first[i], rhs = sigsig.second[i]; + // Every driven bit is a node, also one only assigned constants + auto& rhs_bits = dependencies[lhs]; + if (rhs.is_wire()) + rhs_bits.emplace(rhs); + } + } + + // Returns the set of nodes that are on a cycle through this bit - its SCC, + // or nothing when the bit is on no cycle + const pool& scc_nodes(const SigBit bit) const { + const auto it = scc_of.find(bit); + return it == scc_of.end() ? no_nodes : sccs[it->second]; + } + + dict> dependencies; +private: + // A lone bit is on a cycle only with a self-loop + void find_sccs() { + idict ids; + IntGraph graph; + for (const auto& [lhs, rhs_bits] : dependencies) + for (const auto& rhs : rhs_bits) + if (dependencies.count(rhs)) + graph.add_edge(ids(lhs), ids(rhs)); + + TopoSortedSccs(graph, [&](int* begin, int* end) { + pool scc; + for (int* it = begin; it != end; it++) + scc.insert(ids[*it]); + const SigBit bit = *scc.begin(); + if (GetSize(scc) == 1 && !dependencies.at(bit).count(bit)) + return; + for (const auto& member : scc) + scc_of[member] = GetSize(sccs); + sccs.push_back(std::move(scc)); + }).process_all(); + } + + dict scc_of; + std::vector> sccs; + pool no_nodes; +}; + +struct ResetPathWorker { + ResetPathWorker(RTLIL::Module* module) { + std::vector>> edge_procs; + for (const auto& [_, proc] : module->processes) { + pool edges; + for (const auto* sync : proc->syncs) + if (sync->type == RTLIL::STp || sync->type == RTLIL::STn || sync->type == RTLIL::STe) + for (const auto& bit : sync->signal) + edges.insert(bit); + if (!edges.empty()) + edge_procs.emplace_back(proc, std::move(edges)); + } + + // Without edge triggered processes there are no reset paths + if (edge_procs.empty()) + return; + + for (auto* cell : module->cells()) + if (cell->type.in(ID($reduce_or), ID($reduce_bool), ID($logic_not), ID($not), ID($eq), ID($eqx), ID($ne), ID($nex))) + if (GetSize(cell->getPort(ID::Y)) == 1) + drivers[cell->getPort(ID::Y)[0]] = cell; + + for (const auto& [proc, edges] : edge_procs) + visit(proc->root_case, edges); + } + + void visit(const RTLIL::CaseRule& caserule, const pool& edges) { + if (GetSize(caserule.switches) != 1) + return; + const auto* sw = caserule.switches[0]; + std::vector trace; + if (reaches_edge(sw->signal, edges, trace)) + path.insert(trace.begin(), trace.end()); + for (const auto* rule : sw->cases) + visit(*rule, edges); + } + + bool reaches_edge(RTLIL::SigSpec signal, const pool& edges, std::vector& trace) { + while (GetSize(signal) == 1) { + const SigBit bit = signal[0]; + if (edges.count(bit)) + return true; + const auto it = drivers.find(bit); + if (it == drivers.end() || GetSize(trace) > GetSize(drivers)) + return false; + trace.push_back(bit); + signal = next_signal(it->second); + } + return false; + } + + static RTLIL::SigSpec next_signal(RTLIL::Cell* cell) { + if (!cell->type.in(ID($eq), ID($eqx), ID($ne), ID($nex))) + return cell->getPort(ID::A); + if (cell->getPort(ID::A).is_fully_const()) + return cell->getPort(ID::B); + if (cell->getPort(ID::B).is_fully_const()) + return cell->getPort(ID::A); + return RTLIL::SigSpec(); + } + + dict drivers; + pool path; +}; + +struct OptBarriersPass : public Pass { + OptBarriersPass() : Pass("optbarriers", "(experimental) insert optimization barriers") + { + experimental(); + } + + void help() override { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" optbarriers [options] [selection]\n"); + log("\n"); + log("Insert optimization barriers to drivers of selected public wires.\n"); + log("\n"); + log("\n"); + log(" -nocells\n"); + log(" don't add optimization barriers to the outputs of cells\n"); + log("\n"); + log(" -noprocs\n"); + log(" don't add optimization barriers to the outputs of processes\n"); + log("\n"); + log(" -noconns\n"); + log(" don't add optimization barriers to the left hand sides of connections\n"); + log("\n"); + log(" -private\n"); + log(" also add optimization barriers to private wires driven by cells and\n"); + log(" connections, excluding private wires driven by processes\n"); + log("\n"); + log(" -remove\n"); + log(" replace selected optimization barriers with connections\n"); + log("\n"); + } + + void execute(std::vector args, RTLIL::Design *design) override { + log_header(design, "Executing OPTBARRIERS pass (insert optimization barriers).\n"); + + bool nocells_mode = false; + bool noprocs_mode = false; + bool noconns_mode = false; + bool private_mode = false; + bool remove_mode = false; + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + std::string arg = args[argidx]; + if (arg == "-nocells") { + nocells_mode = true; + continue; + } + if (arg == "-noprocs") { + noprocs_mode = true; + continue; + } + if (arg == "-noconns") { + noconns_mode = true; + continue; + } + if (arg == "-private") { + private_mode = true; + continue; + } + if (arg == "-remove") { + remove_mode = true; + continue; + } + break; + } + extra_args(args, argidx, design); + + if (remove_mode) { + log("Replacing optimization barriers with connections.\n"); + remove_barriers(design); + return; + } + + for (auto* module : design->selected_modules()) { + // We can't just sigmap and iterate through wires for rewriting as + // we want to maintain the structure in connections, and sigmap + // will just return a canonical wire which does not have to be one + // that is directly driving the wire. Therefore for each type of + // object that could be driving the wires (cells, processes, + // connections) we rewrite the sigspecs. + + // Keep track of which wires we have allocated new wires for + dict new_wires; + // Keep track of bit pairs we need to construct barriers for from + // Y to A + dict new_barriers; + + // Nets that already drive a barrier input which must not get a second barrier. + // Only private wires check this, so only needed in private mode + SigMap sigmap; + pool barrier_inputs; + if (private_mode) { + sigmap.set(module); + for (auto* cell : module->cells()) + if (cell->type == ID($barrier)) + for (const auto& bit : sigmap(cell->getPort(ID::A))) + barrier_inputs.insert(bit); + } + const ResetPathWorker reset_path(module); + + // Skip constants, unselected wires, private wires when not in + // private mode, input and inout ports, and private pre-barrier bits. + const auto skip = [&](const SigBit& bit) { + if (!bit.is_wire()) + return true; + + if (!design->selected(module, bit.wire)) + return true; + + if (bit.wire->port_input) + return true; + + if (reset_path.path.count(bit)) + return true; + + if (!bit.wire->name.isPublic() && (!private_mode || barrier_inputs.count(sigmap(bit)))) + return true; + + return false; + }; + + const auto rewrite_sigspec = [&](const SigSpec& sig) { + RTLIL::SigSpec new_output; + for (const auto& bit : sig) { + if (skip(bit)) { + new_output.append(bit); + continue; + } + + // Add a wire to drive if one does not already exist + auto* new_wire = new_wires.at(bit.wire, nullptr); + if (!new_wire) { + new_wire = module->addWire(NEW_ID_SUFFIX(bit.wire->name.str()), GetSize(bit.wire)); + new_wires.emplace(bit.wire, new_wire); + } + + // Rewrite output to drive new wire, and schedule adding + // a barrier bit from new wire to original + const SigBit new_bit(new_wire, bit.offset); + new_output.append(new_bit); + new_barriers.emplace(bit, new_bit); + } + + return new_output; + }; + + // Rewrite processes. It is not as simple as changing all LHS + // expressions to drive barriers if required, as this prevents + // proc passes from optimizing self feedback which is important to + // prevent false comb paths when generating FFs. We only care about + // the assignments/connections within processes, and want to maintain + // the property that if a bit that is to be rewritten to use a + // barrier can be assigned transitively to itself, the value that is + // assigned should be the value before the barrier. + // + // To do this we first enumerate the assignment dependency graph + // for the process - marking which bits drive any other bit. We + // then look for strongly connected components containing barrier + // bits. These correspond to potential paths where the bit can be + // driven by itself and so should see the pre-barrier value. For + // each of the bits on this path we want to construct a parallel + // version that appears in all the same process assignments but is + // driven originally by the pre-barrier value. + // + // For example, consider the following set of assignments appear + // somewhere in the process and we want to add a barrier to b: + // a <- b + // b <- a + // There is a path from b to itself through a, so we add wire b\b to + // represent the pre-barrier version of b and a\b to represent + // the version of a that sees a pre-barrier version of b. We then + // correspondingly add these paths to the assignments and a barrier: + // {a\b, a} <- {b\b, b} + // b\b <- a\b + // b\b -$barrier> b + // + // This has retained that b\b is transitively driven by itself, but + // a is still driven by b, the post-barrier version of b + if (!noprocs_mode) + for (const auto& proc : module->processes) { + // A map from each bit driven by the original process to the + // set of variants required for it. If a bit doesn't appear in + // variants it is only needed in the original form it appears + // in the process. + // + // To get bit a\b from the above example you would index + // variants[a][b] + dict> variants; + + { + // We want to minimize the number of wires we have to create + // for each bit in variants, so for variants[a][b] we create + // a unique wire with size GetSize(a.wire) for each tuple + // of a.wire, b.wire, a.offset - b.offset rather than for + // every pair (a, b). + using IdxTuple = std::tuple; + dict variant_wires; + + // Collect all assignment dependencies in the process + ProcessDependencyWorker dep_worker(*proc.second); + + // Enumerate driven bits that need barriers added + for (const auto& [variant_bit, _] : dep_worker.dependencies) { + // Private bits driven by processes are frontend temporaries + if (skip(variant_bit) || !variant_bit.wire->name.isPublic()) + continue; + + // Collect the bits that are in an SCC with this bit and + // thus need to have variants constructed that see the + // pre-barrier value + for (const auto& lhs_bit : dep_worker.scc_nodes(variant_bit)) { + // Don't add a new wire for the variant_bit itself as this + // should be driven by a wire generated by rewrite_sigspec below + if (lhs_bit == variant_bit) + continue; + + const int offset = lhs_bit.offset - variant_bit.offset; + const IdxTuple idx{lhs_bit.wire, variant_bit.wire, offset}; + auto it = variant_wires.find(idx); + + // Create a new wire to represent this offset combination + // if needed + if (it == variant_wires.end()) { + const auto name = NEW_ID_SUFFIX(lhs_bit.wire->name.str()); + auto* new_wire = module->addWire(name, GetSize(lhs_bit.wire)); + it = variant_wires.emplace(idx, new_wire).first; + } + + variants[lhs_bit].emplace(variant_bit, SigBit(it->second, lhs_bit.offset)); + } + + // Even if a bit doesn't appear in any SCCs we want to rewrite it if it + // isn't skipped + variants[variant_bit].emplace(variant_bit, rewrite_sigspec(variant_bit)); + } + } + + const auto variant = [&](const SigBit a, const SigBit b) { + const auto it1 = variants.find(a); + // There are no variants of a required, so a definitely isn't + // transitively driven by b + if (it1 == variants.end()) + return a; + + const auto it2 = it1->second.find(b); + // a isn't be transitively driven by b + if (it2 == it1->second.end()) + return a; + + // a can be transitively driven by b so return the variant + // of a that sees pre-barrier b + return it2->second; + }; + + const auto proc_rewriter = overloaded{ + // Don't do anything for input sigspecs, these are not connections + [&](const SigSpec&) {}, + // Rewrite connections to drive barrier and see pre-barrier + // values if needed + [&](SigSpec& lhs, SigSpec& rhs) { + for (int i = 0; i < GetSize(lhs); i++) { + const auto lhs_bit = lhs[i], rhs_bit = rhs[i]; + + for (const auto& [variant_bit, variant_lhs_bit] : variants[lhs_bit]) { + // For the existing connections, update the lhs to be pre-barrier + // variant_lhs_bit and rhs to be the variant of itself that sees + // the pre-barrier version of variant_bit + if (variant_bit == lhs_bit) { + lhs[i] = variant_lhs_bit; + rhs[i] = variant(rhs_bit, variant_bit); + continue; + } + + // For new variants of lhs_bit that we need to exist, set the + // rhs bit to the variant of rhs_bit that sees the pre_barrier + // version of variant_bit + lhs.append(variant_lhs_bit); + rhs.append(variant(rhs_bit, variant_bit)); + } + } + } + }; + + proc.second->rewrite_sigspecs2(proc_rewriter); + } + + // Rewrite cell outputs + if (!nocells_mode) + for (auto* cell : module->cells()) + if (cell->type != ID($barrier)) + for (const auto& [name, sig] : cell->connections()) + if (cell->output(name) && !cell->input(name)) + cell->setPort(name, rewrite_sigspec(sig)); + + // Add all the scheduled barriers. To minimize the number of cells, + // first construct a sigspec of all bits, then sort and unify before + // creating barriers + SigSpec barrier_y; + for (const auto&[y_bit, _] : new_barriers) + barrier_y.append(y_bit); + barrier_y.sort_and_unify(); + + bool added_barriers = !barrier_y.empty(); + for (const auto& sig_y : barrier_y.chunks()) { + log_assert(sig_y.is_wire()); + SigSpec sig_a; + for (int i = 0; i < GetSize(sig_y); i++) + sig_a.append(new_barriers[sig_y[i]]); + module->addBarrier(NEW_ID, sig_a, sig_y); + } + + // Rewrite connections + if (!noconns_mode) { + // A connection on a cycle of connections would become a barrier loop + const ProcessDependencyWorker conn_deps(module->connections()); + std::vector new_connections; + for (const auto& conn : module->connections()) { + RTLIL::SigSig skip_conn, barrier_conn; + + for (int i = 0; i < GetSize(conn.first); i++) { + bool keep_conn = skip(conn.first[i]) || !conn_deps.scc_nodes(conn.first[i]).empty(); + auto& sigsig = keep_conn ? skip_conn : barrier_conn; + sigsig.first.append(conn.first[i]); + sigsig.second.append(conn.second[i]); + } + + if (!skip_conn.first.empty()) + new_connections.emplace_back(std::move(skip_conn)); + + if (!barrier_conn.first.empty()) { + module->addBarrier(NEW_ID, barrier_conn.second, barrier_conn.first); + added_barriers = true; + } + } + module->new_connections(new_connections); + } + + // Init values belong to the driver side of the barriers + if (added_barriers) { + SigMap init_sigmap(module); + FfInitVals initvals(&init_sigmap, module); + initvals.move_barrier_inits(module); + } + } + } + + void remove_barriers(RTLIL::Design* design) { + for (auto* module : design->selected_modules()) { + std::vector barriers; + + for (auto* cell : module->selected_cells()) + if (cell->type == ID($barrier)) + barriers.emplace_back(cell); + + for (auto* cell : barriers) { + const auto lhs = cell->getPort(ID::Y), rhs = cell->getPort(ID::A); + module->connect(lhs, rhs); + module->remove(cell); + } + } + } + +} OptBarriersPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/plugin.cc b/chips/yosys/passes/cmds/plugin.cc new file mode 100644 index 0000000000000000000000000000000000000000..dec53cf37d6800717136c54462ef2faa7e2493bc --- /dev/null +++ b/chips/yosys/passes/cmds/plugin.cc @@ -0,0 +1,233 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2014 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "kernel/log_help.h" + +#ifdef YOSYS_ENABLE_PLUGINS +# include +# include +namespace fs = std::filesystem; +#endif + +#ifdef YOSYS_ENABLE_PYTHON +# include +# include +namespace py = pybind11; +#endif + +YOSYS_NAMESPACE_BEGIN + +std::map loaded_plugins; +#ifdef YOSYS_ENABLE_PYTHON +std::map loaded_python_plugins; +#endif +std::map loaded_plugin_aliases; + +#ifdef YOSYS_ENABLE_PLUGINS + +static constexpr const char *path_delimiters = fs::path::preferred_separator == '\\' ? ";" : ":" ; + +inline const std::vector get_plugin_search_paths() { + std::vector result; + const char *yosys_plugin_path = std::getenv("YOSYS_PLUGIN_PATH"); + if (yosys_plugin_path != nullptr && strlen(yosys_plugin_path)) { + // make mutable. std::string also manages allocation as a bonus + // guaranteed contiguous in c++>=11 + std::string copy{yosys_plugin_path}; + char *token = nullptr; + char *rest = ©[0]; + while ((token = strtok_r(rest, path_delimiters, &rest))) { + result.push_back(fs::path(token)); + } + } + result.push_back(fs::path(proc_share_dirname()) / "plugins"); // lowest priority + return result; +} + +void load_plugin(std::string filename, std::vector aliases) +{ + std::string orig_filename = filename; + rewrite_filename(filename); + + // Would something like this better be put in `rewrite_filename`? + if (filename.find("/") == std::string::npos) + filename = "./" + filename; + + + #ifdef YOSYS_ENABLE_PYTHON + const bool is_loaded = loaded_plugins.count(orig_filename) && loaded_python_plugins.count(orig_filename); + #else + const bool is_loaded = loaded_plugins.count(orig_filename); + #endif + + fs::path full_path = fs::absolute(filename); + + if (!is_loaded) { + // Check if we're loading a python script + if (full_path.extension() == ".py") { + #ifdef YOSYS_ENABLE_PYTHON + fs::path plugin_python_path = full_path.parent_path(); + fs::path basename = full_path.stem(); + + py::object sys = py::module_::import("sys"); + sys.attr("path").attr("insert")(0, py::str(plugin_python_path.c_str())); + + try { + auto module_container = py::module_::import(basename.c_str()); + loaded_python_plugins[orig_filename] = module_container.ptr(); + } catch (py::error_already_set &e) { + log_cmd_error("Can't load python module `%s': %s\n", basename, e.what()); + return; + } + Pass::init_register(); + #else + log_error( + "\n This version of Yosys cannot load python plugins.\n" + " Ensure Yosys is built with Python support to do so.\n" + ); + #endif + } else { + // Otherwise we assume it's a native plugin + void *hdl = dlopen(filename.c_str(), RTLD_LAZY|RTLD_LOCAL); + + // We were unable to open the file, try to do so from plugin search + // paths + if (hdl == nullptr && orig_filename.find('/') == std::string::npos) { + const std::vector search_paths = get_plugin_search_paths(); + for (const auto &search_path: search_paths) { + fs::path potential_path = search_path / orig_filename; + if (potential_path.extension() != ".so") { + potential_path = search_path / (orig_filename + ".so"); + } + hdl = dlopen(potential_path.string().c_str(), RTLD_LAZY | RTLD_LOCAL); + if (hdl != nullptr) { + break; + } + } + } + + if (hdl == nullptr) + log_cmd_error("Can't load module `%s': %s\n", filename, dlerror()); + + loaded_plugins[orig_filename] = hdl; + Pass::init_register(); + } + } + + for (auto &alias : aliases) + loaded_plugin_aliases[alias] = orig_filename; +} +#else +void load_plugin(std::string, std::vector) +{ + log_error( + "\n This version of Yosys cannot load plugins at runtime.\n" + " Some plugins may have been included at build time.\n" + " Use `yosys -H' to see the available built-in and plugin commands.\n" + ); +} +#endif + +struct PluginPass : public Pass { + PluginPass() : Pass("plugin", "load and list loaded plugins") { } + bool formatted_help() override { + auto *help = PrettyHelp::get_current(); + help->set_group("passes/status"); + return false; + } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" plugin [options]\n"); + log("\n"); + log("Load and list loaded plugins.\n"); + log("\n"); + log(" -i \n"); + log(" Load (install) the specified plugin.\n"); + log("\n"); + log(" -a \n"); + log(" Register the specified alias name for the loaded plugin\n"); + log("\n"); + log(" -l\n"); + log(" List loaded plugins\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + std::string plugin_filename; + std::vector plugin_aliases; + bool list_mode = false; + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) + { + if ((args[argidx] == "-i") && argidx+1 < args.size() && plugin_filename.empty()) { + plugin_filename = args[++argidx]; + continue; + } + if ((args[argidx] == "-a") && argidx+1 < args.size()) { + plugin_aliases.push_back(args[++argidx]); + continue; + } + if (args[argidx] == "-l") { + list_mode = true; + continue; + } + break; + } + extra_args(args, argidx, design, false); + + if (!plugin_filename.empty()) + load_plugin(plugin_filename, plugin_aliases); + + if (list_mode) + { + log("\n"); +#ifdef YOSYS_ENABLE_PYTHON + if (loaded_plugins.empty() and loaded_python_plugins.empty()) +#else + if (loaded_plugins.empty()) +#endif + log("No plugins loaded.\n"); + else + log("Loaded plugins:\n"); + + for (auto &it : loaded_plugins) + log(" %s\n", it.first); + +#ifdef YOSYS_ENABLE_PYTHON + for (auto &it : loaded_python_plugins) + log(" %s\n", it.first); +#endif + + if (!loaded_plugin_aliases.empty()) { + log("\n"); + int max_alias_len = 1; + for (auto &it : loaded_plugin_aliases) + max_alias_len = max(max_alias_len, GetSize(it.first)); + for (auto &it : loaded_plugin_aliases) + log("Alias: %-*s %s\n", max_alias_len, it.first, it.second); + } + } + } +} PluginPass; + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/portarcs.cc b/chips/yosys/passes/cmds/portarcs.cc new file mode 100644 index 0000000000000000000000000000000000000000..06c4412a74ef8695642a634fada6a16fb9120e80 --- /dev/null +++ b/chips/yosys/passes/cmds/portarcs.cc @@ -0,0 +1,322 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2024 Martin Povišer + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + + +#include "kernel/timinginfo.h" +#include "kernel/rtlil.h" +#include "kernel/utils.h" +#include "kernel/celltypes.h" +#include "kernel/log_help.h" + +PRIVATE_NAMESPACE_BEGIN +USING_YOSYS_NAMESPACE + +static RTLIL::SigBit canonical_bit(RTLIL::SigBit bit) +{ + RTLIL::Wire *w; + while ((w = bit.wire) != NULL && !w->port_input && + w->driverCell()->type.in(ID($buf), ID($_BUF_))) { + bit = w->driverCell()->getPort(ID::A)[bit.offset]; + } + return bit; +} + +struct PortarcsPass : Pass { + PortarcsPass() : Pass("portarcs", "derive port arcs for propagation delay") {} + bool formatted_help() override { + auto *help = PrettyHelp::get_current(); + help->set_group("passes/status"); + return false; + } + + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" portarcs [options] [selection]\n"); + log("\n"); + log("This command characterizes the combinational content of selected modules and\n"); + log("derives timing arcs going from module inputs to module outputs representing the\n"); + log("propagation delay of the module.\n"); + log("\n"); + log(" -draw\n"); + log(" plot the computed delay table to the terminal\n"); + log("\n"); + log(" -icells\n"); + log(" assign unit delay to gates from the internal Yosys cell library\n"); + log("\n"); + log(" -write\n"); + log(" write the computed arcs back into the module as $specify2 instances\n"); + log("\n"); + } + + void execute(std::vector args, RTLIL::Design *d) override + { + log_header(d, "Executing PORTARCS pass. (derive propagation arcs)\n"); + + size_t argidx; + bool icells_mode = false, write_mode = false, draw_mode = false; + for (argidx = 1; argidx < args.size(); argidx++) { + if (args[argidx] == "-icells") + icells_mode = true; + else if (args[argidx] == "-write") + write_mode = true; + else if (args[argidx] == "-draw") + draw_mode = true; + else + break; + } + extra_args(args, argidx, d); + + d->bufNormalize(true); + TimingInfo tinfo(d); + + if (icells_mode) { + CellTypes ct; + ct.setup_stdcells_eval(); + for (auto [id, type] : ct.cell_types) { + auto &tdata = tinfo.data[id]; + tdata.has_inputs = true; + for (auto inp : type.inputs) + for (auto out : type.outputs) + tdata.comb[TimingInfo::BitBit({inp, 0}, {out, 0})] = 1000; + } + } + + for (auto m : d->selected_whole_modules_warn()) { + bool ambiguous_ports = false; + SigSpec inputs, outputs; + for (auto port : m->ports) { + Wire *w = m->wire(port); + log_assert(w->port_input || w->port_output); + if (w->port_input && w->port_output) { + log_warning("Module '%s' with ambiguous direction on port %s ignored.\n", + m, w); + ambiguous_ports = true; + break; + } + if (w->port_input) + inputs.append(w); + else + outputs.append(w); + } + if (ambiguous_ports) + continue; + + SigSpec ordering; + { + TopoSort sort; + + for (auto cell : m->cells()) + // Ignore all bufnorm helper cells + if (!cell->type.in(ID($buf), ID($input_port), ID($connect), ID($tribuf))) { + auto tdata = tinfo.find(cell->type); + if (tdata == tinfo.end()) + log_cmd_error("Missing timing data for module '%s'.\n", cell->type.unescape()); + for (auto [edge, delay] : tdata->second.comb) { + auto from = edge.first.get_connection(cell); + auto to = edge.second.get_connection(cell); + if (from && to) { + auto from_c = canonical_bit(from.value()); + if (from_c.wire) + sort.edge(from_c, to.value()); + } + } + } + + if (!sort.sort()) + log_error("Failed to sort instances in module %s.\n", m); + + ordering = sort.sorted; + } + + dict annotations; + std::vector> allocated; + std::vector recycling; + + auto alloc_for_bit = [&](SigBit bit) { + if (!recycling.empty()) { + annotations[bit] = recycling.back(); + recycling.pop_back(); + } else { + int *p = new int[std::max(1, inputs.size())]; + allocated.emplace_back(p); + annotations[bit] = p; + } + }; + + for (auto bit : outputs) { + SigBit bit_c = canonical_bit(bit); + alloc_for_bit(bit_c); + + // consistency check + annotations.at(bit_c)[0] = (intptr_t) bit_c.wire; + } + + for (int i = ordering.size() - 1; i >= 0; i--) { + SigBit bit = ordering[i]; + + if (!bit.wire->port_input) { + auto cell = bit.wire->driverCell(); + auto tdata = tinfo.find(cell->type); + log_assert(tdata != tinfo.end()); + for (auto [edge, delay] : tdata->second.comb) { + auto from = edge.first.get_connection(cell); + auto to = edge.second.get_connection(cell); + if (from && to && to.value() == bit) { + auto from_c = canonical_bit(from.value()); + if (from_c.wire) { + if (!annotations.count(from_c)) { + alloc_for_bit(from_c); + + // consistency check + annotations.at(from_c)[0] = (intptr_t) from_c.wire; + } else { + // consistency check + log_assert(annotations.at(from_c)[0] == ((int) (intptr_t) from_c.wire)); + } + } + } + } + } + + if (annotations.count(bit)) { + // consistency check + log_assert(annotations.at(bit)[0] == ((int) (intptr_t) bit.wire)); + } else { + alloc_for_bit(bit); + } + + recycling.push_back(annotations.at(ordering[i])); + } + log_debug("Allocated %lux%d\n", allocated.size(), inputs.size()); + + for (auto bit : outputs) { + int *p = annotations.at(canonical_bit(bit)); + for (int i = 0; i < inputs.size(); i++) + p[i] = -1; + } + + for (int i = 0; i < ordering.size(); i++) { + SigBit bit = ordering[i]; + int *p = annotations.at(bit); + if (bit.wire->port_input) { + for (int j = 0; j < inputs.size(); j++) + p[j] = (j == i) ? 0 : -1; + } else { + for (int j = 0; j < inputs.size(); j++) + p[j] = -1; + + auto cell = ordering[i].wire->driverCell(); + auto tdata = tinfo.find(cell->type); + log_assert(tdata != tinfo.end()); + for (auto [edge, delay] : tdata->second.comb) { + auto from = edge.first.get_connection(cell); + auto to = edge.second.get_connection(cell); + if (from && to && to.value() == ordering[i]) { + auto from_c = canonical_bit(from.value()); + if (from_c.wire) { + int *q = annotations.at(from_c); + for (int j = 0; j < inputs.size(); j++) + if (q[j] >= 0) + p[j] = std::max(p[j], q[j] + delay); + } + } + } + } + } + + if (draw_mode) { + auto bit_str = [](SigBit bit) { + return stringf("%s%d", bit.wire, bit.offset); + }; + + std::vector headings; + int top_length = 0; + for (auto bit : inputs) { + headings.push_back(bit_str(bit)); + top_length = std::max(top_length, (int) headings.back().size()); + } + + int max_delay = 0; + for (auto bit : outputs) { + int *p = annotations.at(canonical_bit(bit)); + for (auto i = 0; i < inputs.size(); i++) + if (p[i] > max_delay) + max_delay = p[i]; + } + + if (max_delay == 0) + max_delay = 1; + + log("Delay legend:\n"); + log("\n"); + std::string message = " "; + for (int i = 0; i < 24; i++) + message += stringf("\033[48;5;%dm ", 232+i); + log("%s\033[0m\n", message); + log(" |%22s|\n", ""); + log(" 0%22s%d\n", "", max_delay); + for (int k = top_length - 1; k >= 0; k--) { + message = stringf(" %10s ", ""); + for (auto &h : headings) + message += (k < (int) h.size()) ? h[k] : ' '; + log("%s\n", message); + } + log("\n"); + + for (auto bit : outputs) { + message = stringf(" %10s ", bit_str(bit)); + int *p = annotations.at(canonical_bit(bit)); + for (auto i = 0; i < inputs.size(); i++) + message += stringf("\033[48;5;%dm ", 232 + ((std::max(p[i], 0) * 24) - 1) / max_delay); + log("%s\033[0m\n", message); + } + } + + if (write_mode) { + for (auto bit : outputs) { + int *p = annotations.at(canonical_bit(bit)); + for (auto i = 0; i < inputs.size(); i++) { + if (p[i] >= 0) { + Cell *spec = m->addCell(NEW_ID, ID($specify2)); + spec->setParam(ID::SRC_WIDTH, 1); + spec->setParam(ID::DST_WIDTH, 1); + spec->setParam(ID::T_FALL_MAX, p[i]); + spec->setParam(ID::T_FALL_TYP, p[i]); + spec->setParam(ID::T_FALL_MIN, p[i]); + spec->setParam(ID::T_RISE_MAX, p[i]); + spec->setParam(ID::T_RISE_TYP, p[i]); + spec->setParam(ID::T_RISE_MIN, p[i]); + spec->setParam(ID::SRC_DST_POL, false); + spec->setParam(ID::SRC_DST_PEN, false); + spec->setParam(ID::FULL, false); + spec->setPort(ID::EN, Const(1, 1)); + spec->setPort(ID::SRC, inputs[i]); + spec->setPort(ID::DST, bit); + } + } + } + } + } + d->bufNormalize(false); + } +} PortarcsPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/portlist.cc b/chips/yosys/passes/cmds/portlist.cc new file mode 100644 index 0000000000000000000000000000000000000000..f9413a8087b497bd36ab9480485f0263165435c4 --- /dev/null +++ b/chips/yosys/passes/cmds/portlist.cc @@ -0,0 +1,101 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "kernel/sigtools.h" +#include "kernel/log_help.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct PortlistPass : public Pass { + PortlistPass() : Pass("portlist", "list (top-level) ports") { } + bool formatted_help() override { + auto *help = PrettyHelp::get_current(); + help->set_group("passes/status"); + return false; + } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" portlist [options] [selection]\n"); + log("\n"); + log("This command lists all module ports found in the selected modules.\n"); + log("\n"); + log("If no selection is provided then it lists the ports on the top module.\n"); + log("\n"); + log(" -m\n"); + log(" print verilog blackbox module definitions instead of port lists\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + bool m_mode = false; + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + if (args[argidx] == "-m") { + m_mode = true; + continue; + } + break; + } + + bool first_module = true; + + auto handle_module = [&](RTLIL::Module *module) { + vector ports; + if (first_module) + first_module = false; + else + log("\n"); + for (auto port : module->ports) { + auto *w = module->wire(port); + ports.push_back(stringf("%s [%d:%d] %s", w->port_input ? w->port_output ? "inout" : "input" : "output", + w->upto ? w->start_offset : w->start_offset + w->width - 1, + w->upto ? w->start_offset + w->width - 1 : w->start_offset, + w)); + } + log("module %s%s\n", module, m_mode ? " (" : ""); + for (int i = 0; i < GetSize(ports); i++) + log("%s%s\n", ports[i], m_mode && i+1 < GetSize(ports) ? "," : ""); + if (m_mode) { + log(");\n"); + log("endmodule\n"); + } + }; + + if (argidx == args.size()) + { + auto *top = design->top_module(); + if (top == nullptr) + log_cmd_error("Can't find top module in current design!\n"); + handle_module(top); + } + else + { + extra_args(args, argidx, design); + for (auto module : design->selected_modules()) + handle_module(module); + } + } +} PortlistPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/printattrs.cc b/chips/yosys/passes/cmds/printattrs.cc new file mode 100644 index 0000000000000000000000000000000000000000..445f2c9a5c26df3747b253c864b9148e271da5d4 --- /dev/null +++ b/chips/yosys/passes/cmds/printattrs.cc @@ -0,0 +1,96 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2020 Alberto Gonzalez + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "kernel/log_help.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct PrintAttrsPass : public Pass { + PrintAttrsPass() : Pass("printattrs", "print attributes of selected objects") { } + bool formatted_help() override { + auto *help = PrettyHelp::get_current(); + help->set_group("passes/status"); + return false; + } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" printattrs [selection]\n"); + log("\n"); + log("Print all attributes of the selected objects.\n"); + log("\n"); + log("\n"); + } + + static std::string get_indent_str(const unsigned int indent) { + return stringf("%*s", indent, ""); + } + + static void log_const(PooledName s, const RTLIL::Const &x, const unsigned int indent) { + if (x.flags & RTLIL::CONST_FLAG_STRING) + log("%s(* %s=\"%s\" *)\n", get_indent_str(indent), s.unescape(), x.decode_string()); + else if (x.flags == RTLIL::CONST_FLAG_NONE || x.flags == RTLIL::CONST_FLAG_SIGNED) + log("%s(* %s=%s *)\n", get_indent_str(indent), s.unescape(), x.as_string()); + else + log_assert(x.flags & RTLIL::CONST_FLAG_STRING || x.flags == RTLIL::CONST_FLAG_NONE); //intended to fail + } + + void execute(std::vector args, RTLIL::Design *design) override + { + size_t argidx = 1; + extra_args(args, argidx, design); + + unsigned int indent = 0; + for (auto mod : design->selected_modules()) + { + if (design->selected_whole_module(mod)) { + log("%s%s\n", get_indent_str(indent), mod); + indent += 2; + for (auto &it : mod->attributes) + log_const(PooledName(design, it.first), it.second, indent); + } + + for (auto cell : mod->selected_cells()) { + log("%s%s\n", get_indent_str(indent), cell); + indent += 2; + for (auto &it : cell->attributes) + log_const(PooledName(design, it.first), it.second, indent); + indent -= 2; + } + + for (auto wire : mod->selected_wires()) { + log("%s%s\n", get_indent_str(indent), wire); + indent += 2; + for (auto &it : wire->attributes) + log_const(PooledName(design, it.first), it.second, indent); + indent -= 2; + } + + if (design->selected_whole_module(mod)) + indent -= 2; + } + + log("\n"); + } +} PrintAttrsPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/rename.cc b/chips/yosys/passes/cmds/rename.cc new file mode 100644 index 0000000000000000000000000000000000000000..cff2a7a57ddf364abe6c672399a49ce7bb0c9290 --- /dev/null +++ b/chips/yosys/passes/cmds/rename.cc @@ -0,0 +1,647 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/register.h" +#include "kernel/rtlil.h" +#include "kernel/log.h" +#include "backends/verilog/verilog_backend.h" +#include "kernel/twine.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +static void rename_in_module(RTLIL::Module *module, std::string from_name, std::string to_name, bool flag_output) +{ + from_name = RTLIL::escape_id(from_name); + to_name = RTLIL::escape_id(to_name); + + IdString to_ref = module->twines().find(to_name); + if (module->count_id(to_ref)) + log_cmd_error("There is already an object `%s' in module `%s'.\n", RTLIL::unescape_id(to_name), module); + + IdString from_ref = module->twines().find(from_name); + RTLIL::Wire *wire_to_rename = module->wire(from_ref); + RTLIL::Cell *cell_to_rename = module->cell(from_ref); + + if (wire_to_rename != nullptr) { + log("Renaming wire %s to %s in module %s.\n", wire_to_rename, RTLIL::unescape_id(to_name), module); + module->rename(wire_to_rename, to_name); + if (wire_to_rename->port_id || flag_output) { + if (flag_output) + wire_to_rename->port_output = true; + module->fixup_ports(); + } + return; + } + + if (cell_to_rename != nullptr) { + if (flag_output) + log_cmd_error("Called with -output but the specified object is a cell.\n"); + log("Renaming cell %s to %s in module %s.\n", cell_to_rename, RTLIL::unescape_id(to_name), module); + module->rename(cell_to_rename, to_name); + return; + } + + log_cmd_error("Object `%s' not found!\n", RTLIL::unescape_id(from_name)); +} + +static IdString derive_name_from_src(RTLIL::Module *module, const std::string &src, int counter) +{ + std::string src_base = src.substr(0, src.find('|')); + if (src_base.empty()) + return module->twines().add(stringf("$%d", counter)); + IdString base = module->twines().add("\\" + src_base); + return module->twines().add(base, stringf("$%d", counter)); +} + +static IdString derive_name_from_cell_output_wire(const RTLIL::Cell *cell, string suffix, bool move_to_cell) +{ + // Find output + const SigSpec *output = nullptr; + int num_outputs = 0; + for (auto &connection : cell->connections()) { + if (cell->output(connection.first)) { + output = &connection.second; + num_outputs++; + } + } + + if (num_outputs != 1) // Skip cells thad drive multiple outputs + return cell->name; + + std::string name = ""; + for (auto &chunk : output->chunks()) { + // Skip cells that drive privately named wires + if (!chunk.wire || chunk.wire->name.str()[0] == '$') + return cell->name; + + if (name != "") + name += "$"; + + name += chunk.wire->name.str(); + if (chunk.wire->width != chunk.width) { + int lhs = chunk.wire->to_hdl_index(chunk.offset + chunk.width - 1); + int rhs = chunk.wire->to_hdl_index(chunk.offset); + + if (lhs != rhs) + name += stringf("[%d:%d]", lhs, rhs); + else + name += stringf("[%d]", lhs); + } + } + + RTLIL::Wire *wire; + + if (move_to_cell) { + IdString name_ref = cell->twines().find(name); + if (!(wire = cell->module->wire(name_ref)) || !(wire->port_input || wire->port_output)) + return cell->twines().add(std::move(name)); + } + + if (suffix.empty()) { + suffix = cell->type.str(); + } + return cell->twines().add(name + suffix); +} + +static bool rename_witness(RTLIL::Design *design, dict &cache, RTLIL::Module *module) +{ + auto cached = cache.find(module); + if (cached != cache.end()) { + if (cached->second == -1) + log_error("Cannot rename witness signals in a design containing recursive instantiations.\n"); + return cached->second; + } + cache.emplace(module, -1); + + std::vector> renames; + + bool has_witness_signals = false; + for (auto cell : module->cells()) + { + RTLIL::Module *impl = design->module(cell->type); + if (impl != nullptr) { + bool witness_in_cell = rename_witness(design, cache, impl); + has_witness_signals |= witness_in_cell; + if (witness_in_cell && !cell->name.isPublic()) { + std::string name = cell->name.str().substr(1); + for (auto &c : name) + if ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && (c < '0' || c > '9') && c != '_') + c = '_'; + auto new_id = module->uniquify("\\_witness_." + name); + cell->set_hdlname_attribute({ "_witness_", strstr(module->twines().str(new_id).c_str(), ".") + 1 }); + renames.emplace_back(cell, new_id); + } + } + + if (cell->type.in(ID($anyconst), ID($anyseq), ID($anyinit), ID($allconst), ID($allseq))) { + has_witness_signals = true; + IdString QY; + bool clk2fflogic = false; + if (cell->type == ID($anyinit)) + QY = (clk2fflogic = cell->get_bool_attribute(ID(clk2fflogic))) ? ID::D : ID::Q; + else + QY = ID::Y; + auto sig_out = cell->getPort(QY); + + for (auto chunk : sig_out.chunks()) { + if (chunk.is_wire() && !chunk.wire->name.isPublic()) { + std::string name = stringf("%s_%s", cell->type.str().substr(1), cell->name.str().substr(1)); + for (auto &c : name) + if ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && (c < '0' || c > '9') && c != '_') + c = '_'; + auto new_id = module->uniquify("\\_witness_." + name); + auto new_wire = module->addWire(new_id, GetSize(sig_out)); + new_wire->set_hdlname_attribute({ "_witness_", strstr(module->twines().str(new_id).c_str(), ".") + 1 }); + if (clk2fflogic) + module->connect({new_wire, sig_out}); + else + module->connect({sig_out, new_wire}); + cell->setPort(QY, new_wire); + break; + } + } + } + + + if (cell->type.in(ID($assert), ID($assume), ID($cover), ID($live), ID($fair), ID($check))) { + has_witness_signals = true; + if (cell->name.isPublic()) + continue; + std::string name = stringf("%s_%s", cell->type.str().substr(1), cell->name.str().substr(1)); + for (auto &c : name) + if ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && (c < '0' || c > '9') && c != '_') + c = '_'; + auto new_id = module->uniquify("\\_witness_." + name); + renames.emplace_back(cell, new_id); + cell->set_hdlname_attribute({ "_witness_", strstr(module->twines().str(new_id).c_str(), ".") + 1 }); + } + } + for (auto rename : renames) { + module->rename(rename.first, rename.second); + } + + cache[module] = has_witness_signals; + return has_witness_signals; +} + +static std::string renamed_unescaped(const std::string& str) +{ + std::string new_str = ""; + + if ('0' <= str[0] && str[0] <= '9') + new_str = '_' + new_str; + + for (char c : str) { + if (VERILOG_BACKEND::char_is_verilog_escaped(c)) + new_str += '_'; + else + new_str += c; + } + + if (VERILOG_BACKEND::verilog_keywords().count(str)) + new_str += "_"; + + return new_str; +} + +struct RenamePass : public Pass { + RenamePass() : Pass("rename", "rename object in the design") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" rename old_name new_name\n"); + log("\n"); + log("Rename the specified object. Note that selection patterns are not supported\n"); + log("by this command.\n"); + log("\n"); + log("\n"); + log("\n"); + log(" rename -output old_name new_name\n"); + log("\n"); + log("Like above, but also make the wire an output. This will fail if the object is\n"); + log("not a wire.\n"); + log("\n"); + log("\n"); + log(" rename -src [selection]\n"); + log("\n"); + log("Assign names auto-generated from the src attribute to all selected wires and\n"); + log("cells with private names.\n"); + log("\n"); + log("\n"); + log(" rename -wire [selection] [-move-to-cell] [-suffix ]\n"); + log("\n"); + log("Assign auto-generated names based on the wires they drive to all selected\n"); + log("cells with private names. Ignores cells driving privatly named wires.\n"); + log("By default, the cell is named after the wire with the cell type as suffix.\n"); + log("The -suffix option can be used to set the suffix to the given string instead.\n"); + log("\n"); + log("The -move-to-cell option can be used to name the cell after the wire without\n"); + log("any suffix. If this would lead to conflicts, the suffix is added to the wire\n"); + log("instead. For cells driving ports, the -move-to-cell option is ignored.\n"); + log("\n"); + log("\n"); + log(" rename -enumerate [-pattern ] [selection]\n"); + log("\n"); + log("Assigns auto-generated names to objects used in formal verification\n"); + log("that do not have a public name. This applies to all formal property\n"); + log("cells, $any*/$all* output wires, and their containing cells.\n"); + log("\n"); + log("\n"); + log(" rename -witness\n"); + log("\n"); + log("Assigns auto-generated names to objects used in formal verification\n"); + log("that do not have a public name. This applies to all formal property\n"); + log("cells ($assert, $assume, $cover, $live, $fair, $check), $any*/$all*\n"); + log("output wires, and their containing cells.\n"); + log("\n"); + log("\n"); + log(" rename -hide [selection]\n"); + log("\n"); + log("Assign private names (the ones with $-prefix) to all selected wires and cells\n"); + log("with public names. This ignores all selected ports.\n"); + log("\n"); + log("\n"); + log(" rename -top new_name\n"); + log("\n"); + log("Rename top module.\n"); + log("\n"); + log("\n"); + log(" rename -scramble-name [-seed ] [selection]\n"); + log("\n"); + log("Assign randomly-generated names to all selected wires and cells. The seed option\n"); + log("can be used to change the random number generator seed from the default, but it\n"); + log("must be non-zero.\n"); + log("\n"); + log("\n"); + log(" rename -unescape [selection]\n"); + log("\n"); + log("Rename all selected public wires and cells that have to be escaped in Verilog.\n"); + log("Replaces characters with underscores or adds additional underscores and numbers.\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + std::string pattern_prefix = "_", pattern_suffix = "_"; + std::string cell_suffix = ""; + bool flag_src = false; + bool flag_wire = false; + bool flag_move_to_cell = false; + bool flag_enumerate = false; + bool flag_witness = false; + bool flag_hide = false; + bool flag_top = false; + bool flag_output = false; + bool flag_scramble_name = false; + bool flag_unescape = false; + bool got_mode = false; + unsigned int seed = 1; + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) + { + std::string arg = args[argidx]; + if (arg == "-src" && !got_mode) { + flag_src = true; + got_mode = true; + continue; + } + if (arg == "-output" && !got_mode) { + flag_output = true; + got_mode = true; + continue; + } + if (arg == "-wire" && !got_mode) { + flag_wire = true; + got_mode = true; + continue; + } + if (arg == "-enumerate" && !got_mode) { + flag_enumerate = true; + got_mode = true; + continue; + } + if (arg == "-witness" && !got_mode) { + flag_witness = true; + got_mode = true; + continue; + } + if (arg == "-hide" && !got_mode) { + flag_hide = true; + got_mode = true; + continue; + } + if (arg == "-top" && !got_mode) { + flag_top = true; + got_mode = true; + continue; + } + if (arg == "-scramble-name" && !got_mode) { + flag_scramble_name = true; + got_mode = true; + continue; + } + if (arg == "-unescape" && !got_mode) { + flag_unescape = true; + got_mode = true; + continue; + } + if (arg == "-move-to-cell" && flag_wire && !flag_move_to_cell) { + flag_move_to_cell = true; + continue; + } + if (arg == "-pattern" && argidx+1 < args.size() && args[argidx+1].find('%') != std::string::npos) { + int pos = args[++argidx].find('%'); + pattern_prefix = args[argidx].substr(0, pos); + pattern_suffix = args[argidx].substr(pos+1); + continue; + } + if (arg == "-suffix" && argidx + 1 < args.size()) { + cell_suffix = args[++argidx]; + continue; + } + if (arg == "-seed" && argidx+1 < args.size()) { + seed = std::stoi(args[++argidx]); + continue; + } + break; + } + + if (flag_src) + { + extra_args(args, argidx, design); + + for (auto module : design->selected_modules()) + { + int counter = 0; + dict new_wire_names; + dict new_cell_names; + + for (auto wire : module->selected_wires()) + if (!wire->name.isPublic()) + new_wire_names.emplace(wire, module->uniquify(derive_name_from_src(module, wire->get_src_attribute(), counter++))); + + for (auto cell : module->selected_cells()) + if (!cell->name.isPublic()) + new_cell_names.emplace(cell, module->uniquify(derive_name_from_src(module, cell->get_src_attribute(), counter++))); + + for (auto &it : new_wire_names) + module->rename(it.first, it.second); + + for (auto &it : new_cell_names) + module->rename(it.first, it.second); + } + } + else + if (flag_wire) + { + extra_args(args, argidx, design); + + for (auto module : design->selected_modules()) { + dict new_cell_names; + for (auto cell : module->selected_cells()) + if (!cell->name.isPublic()) + new_cell_names[cell] = derive_name_from_cell_output_wire(cell, cell_suffix, flag_move_to_cell); + for (auto &[cell, new_name] : new_cell_names) { + if (flag_move_to_cell) { + RTLIL::Wire *found_wire = module->wire(new_name); + if (found_wire) { + std::string wire_suffix = cell_suffix; + if (wire_suffix.empty()) { + for (auto const &[port, _] : cell->connections()) { + if (cell->output(port)) { + wire_suffix += stringf("%s.%s", cell->type, module->twines().str(port).substr(1)); + break; + } + } + } + module->rename(found_wire, found_wire->name.str() + wire_suffix); + } + } + module->rename(cell, new_name); + } + } + } + else + if (flag_enumerate) + { + extra_args(args, argidx, design); + + for (auto module : design->selected_modules()) + { + int counter = 0; + dict new_wire_names; + dict new_cell_names; + + for (auto wire : module->selected_wires()) + if (!wire->name.isPublic()) { + std::string buf; + do buf = stringf("\\%s%d%s", pattern_prefix, counter++, pattern_suffix); + while (module->wire(buf) != nullptr); + new_wire_names[wire] = design->twines().add(std::move(buf)); + } + + for (auto cell : module->selected_cells()) + if (!cell->name.isPublic()) { + std::string buf; + do buf = stringf("\\%s%d%s", pattern_prefix, counter++, pattern_suffix); + while (module->cell(buf) != nullptr); + new_cell_names[cell] = design->twines().add(std::move(buf)); + } + + for (auto &it : new_wire_names) + module->rename(it.first, it.second); + + for (auto &it : new_cell_names) + module->rename(it.first, it.second); + } + } + else + if (flag_witness) + { + extra_args(args, argidx, design, false); + + RTLIL::Module *module = design->top_module(); + + if (module == nullptr) + log_cmd_error("No top module found!\n"); + + dict cache; + rename_witness(design, cache, module); + } + else + if (flag_hide) + { + extra_args(args, argidx, design); + + for (auto module : design->selected_modules()) + { + dict new_wire_names; + dict new_cell_names; + + for (auto wire : module->selected_wires()) + if (wire->name.isPublic() && wire->port_id == 0) + new_wire_names[wire] = module->twines().add(NEW_ID); + + for (auto cell : module->selected_cells()) + if (cell->name.isPublic()) + new_cell_names[cell] = module->twines().add(NEW_ID); + + for (auto &it : new_wire_names) + module->rename(it.first, it.second); + + for (auto &it : new_cell_names) + module->rename(it.first, it.second); + } + } + else + if (flag_top) + { + if (argidx+1 != args.size()) + log_cmd_error("Invalid number of arguments!\n"); + + IdString new_name = design->twines().add(RTLIL::escape_id(args[argidx])); + RTLIL::Module *module = design->top_module(); + + if (module == nullptr) + log_cmd_error("No top module found!\n"); + + log("Renaming module %s to %s.\n", module, PooledName(design, new_name).unescape()); + design->rename(module, new_name); + } + else + if (flag_scramble_name) + { + extra_args(args, argidx, design); + + if (seed == 0) + log_error("Seed for -scramble-name cannot be zero.\n"); + + for (auto module : design->selected_modules()) + { + if (module->memories.size() != 0 || module->processes.size() != 0) { + log_warning("Skipping module %s with unprocessed memories or processes\n", module); + continue; + } + + dict new_wire_names; + dict new_cell_names; + + for (auto wire : module->selected_wires()) + if (wire->port_id == 0) { + seed = mkhash_xorshift(seed); + new_wire_names[wire] = module->twines().add(stringf("$_%u_", seed)); + } + + for (auto cell : module->selected_cells()) { + seed = mkhash_xorshift(seed); + new_cell_names[cell] = module->twines().add(stringf("$_%u_", seed)); + } + + for (auto &it : new_wire_names) + module->rename(it.first, it.second); + + for (auto &it : new_cell_names) + module->rename(it.first, it.second); + } + } + else if (flag_unescape) + { + extra_args(args, argidx, design); + + for (auto module : design->selected_modules()) + { + dict new_wire_names; + dict new_cell_names; + + for (auto wire : module->selected_wires()) { + auto name = wire->name.str(); + if (name[0] != '\\') + continue; + name = name.substr(1); + if (!VERILOG_BACKEND::id_is_verilog_escaped(name)) + continue; + new_wire_names[wire] = module->uniquify("\\" + renamed_unescaped(name)); + auto new_name = module->twines().str(new_wire_names[wire]).substr(1); + if (VERILOG_BACKEND::id_is_verilog_escaped(new_name)) + log_error("Failed to rename wire %s -> %s\n", name, new_name); + } + + for (auto cell : module->selected_cells()) { + auto name = cell->name.str(); + if (name[0] != '\\') + continue; + name = name.substr(1); + if (!VERILOG_BACKEND::id_is_verilog_escaped(name)) + continue; + new_cell_names[cell] = module->uniquify("\\" + renamed_unescaped(name)); + auto new_name = module->twines().str(new_cell_names[cell]).substr(1); + if (VERILOG_BACKEND::id_is_verilog_escaped(new_name)) + log_error("Failed to rename cell %s -> %s\n", name, new_name); + } + + for (auto &it : new_wire_names) + module->rename(it.first, it.second); + + for (auto &it : new_cell_names) + module->rename(it.first, it.second); + + module->fixup_ports(); + } + } + else + { + if (argidx+2 != args.size()) + log_cmd_error("Invalid number of arguments!\n"); + + std::string from_name = args[argidx++]; + std::string to_name = args[argidx++]; + + if (!design->selected_active_module.empty()) + { + if (design->module(design->selected_active_module) != nullptr) + rename_in_module(design->module(design->selected_active_module), from_name, to_name, flag_output); + } + else + { + if (flag_output) + log_cmd_error("Mode -output requires that there is an active module selected.\n"); + + RTLIL::Module *module_to_rename = nullptr; + for (auto module : design->modules()) { + std::string module_name_str = module->name.str(); + if (module_name_str == from_name || RTLIL::unescape_id(module_name_str) == from_name) { + module_to_rename = module; + break; + } + } + + if (module_to_rename != nullptr) { + to_name = RTLIL::escape_id(to_name); + log("Renaming module %s to %s.\n", module_to_rename->name, to_name); + design->rename(module_to_rename, to_name); + } else + log_cmd_error("Object `%s' not found!\n", from_name); + } + } + } +} RenamePass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/scatter.cc b/chips/yosys/passes/cmds/scatter.cc new file mode 100644 index 0000000000000000000000000000000000000000..017600a46f7d6e92716ebf3ebe3d07a666f62e78 --- /dev/null +++ b/chips/yosys/passes/cmds/scatter.cc @@ -0,0 +1,67 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/register.h" +#include "kernel/celltypes.h" +#include "kernel/rtlil.h" +#include "kernel/log.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct ScatterPass : public Pass { + ScatterPass() : Pass("scatter", "add additional intermediate nets") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" scatter [selection]\n"); + log("\n"); + log("This command adds additional intermediate nets on all cell ports. This is used\n"); + log("for testing the correct use of the SigMap helper in passes. If you don't know\n"); + log("what this means: don't worry -- you only need this pass when testing your own\n"); + log("extensions to Yosys.\n"); + log("\n"); + log("Use the opt_clean command to get rid of the additional nets.\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + CellTypes ct(design); + extra_args(args, 1, design); + + for (auto module : design->selected_modules()) + { + for (auto cell : module->cells()) { + dict new_connections; + for (auto conn : cell->connections()) + new_connections.emplace(conn.first, RTLIL::SigSig(conn.second, module->addWire(NEW_ID, GetSize(conn.second)))); + for (auto &it : new_connections) { + if (ct.cell_output(cell->type, it.first)) + module->connect(RTLIL::SigSig(it.second.first, it.second.second)); + else + module->connect(RTLIL::SigSig(it.second.second, it.second.first)); + cell->setPort(it.first, it.second.second); + } + } + } + } +} ScatterPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/scc.cc b/chips/yosys/passes/cmds/scc.cc new file mode 100644 index 0000000000000000000000000000000000000000..677234e9785414af313a0d88718eef389c8df4b3 --- /dev/null +++ b/chips/yosys/passes/cmds/scc.cc @@ -0,0 +1,400 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +// [[CITE]] Tarjan's strongly connected components algorithm +// Tarjan, R. E. (1972), "Depth-first search and linear graph algorithms", SIAM Journal on Computing 1 (2): 146-160, doi:10.1137/0201010 +// http://en.wikipedia.org/wiki/Tarjan's_strongly_connected_components_algorithm + +#include "kernel/yosys.h" +#include "kernel/celltypes.h" +#include "kernel/sigtools.h" +#include "kernel/log_help.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct SccWorker +{ + RTLIL::Design *design; + RTLIL::Module *module; + SigMap sigmap; + CellTypes ct, specifyCells; + + pool workQueue; + dict> cellToNextCell; + dict cellToPrevSig, cellToNextSig; + + dict> cellLabels; + dict cellDepth; + pool cellsOnStack; + std::vector cellStack; + int labelCounter; + + dict cell2scc; + std::vector> sccList; + + void run(RTLIL::Cell *cell, int depth, int maxDepth) + { + log_assert(workQueue.count(cell) > 0); + + workQueue.erase(cell); + cellLabels[cell] = std::pair(labelCounter, labelCounter); + labelCounter++; + + cellsOnStack.insert(cell); + cellStack.push_back(cell); + + if (maxDepth >= 0) + cellDepth[cell] = depth; + + for (auto nextCell : cellToNextCell[cell]) + if (cellLabels.count(nextCell) == 0) { + run(nextCell, depth+1, maxDepth); + cellLabels[cell].second = min(cellLabels[cell].second, cellLabels[nextCell].second); + } else + if (cellsOnStack.count(nextCell) > 0 && (maxDepth < 0 || cellDepth[nextCell] + maxDepth > depth)) { + cellLabels[cell].second = min(cellLabels[cell].second, cellLabels[nextCell].second); + } + + if (cellLabels[cell].first == cellLabels[cell].second) + { + if (cellStack.back() == cell) + { + cellStack.pop_back(); + cellsOnStack.erase(cell); + } + else + { + std::string message = "Found an SCC:"; + pool scc; + while (cellsOnStack.count(cell) > 0) { + RTLIL::Cell *c = cellStack.back(); + cellStack.pop_back(); + cellsOnStack.erase(c); + message += stringf(" %s", c); + cell2scc[c] = sccList.size(); + scc.insert(c); + } + sccList.push_back(scc); + log("%s\n", message); + } + } + } + + SccWorker(RTLIL::Design *design, RTLIL::Module *module, bool nofeedbackMode, bool allCellTypes, bool specifyMode, int maxDepth) : + design(design), module(module), sigmap(module) + { + if (module->processes.size() > 0) { + log("Skipping module %s as it contains processes (run 'proc' pass first).\n", module->name); + return; + } + + if (allCellTypes) { + ct.setup(design); + } else { + ct.setup_internals(); + ct.setup_stdcells(); + } + + // Discover boxes with specify rules in them, for special handling. + if (specifyMode) { + for (auto mod : design->modules()) + if (mod->get_blackbox_attribute(false)) + for (auto cell : mod->cells()) + if (cell->type == ID($specify2)) + { + specifyCells.setup_module(mod); + break; + } + } + + SigPool selectedSignals; + SigSet sigToNextCells; + + for (auto &it : module->wires_) + if (design->selected(module, it.second)) + selectedSignals.add(sigmap(RTLIL::SigSpec(it.second))); + + for (auto &it : module->cells_) + { + RTLIL::Cell *cell = it.second; + + if (!design->selected(module, cell)) + continue; + + if (!allCellTypes && !ct.cell_known(cell->type) && !specifyCells.cell_known(cell->type)) + continue; + + workQueue.insert(cell); + + RTLIL::SigSpec inputSignals, outputSignals; + + if (specifyCells.cell_known(cell->type)) { + // Use specify rules of the type `(X => Y) = NN` to look for asynchronous paths in boxes. + for (auto subcell : design->module(cell->type)->cells()) + { + if (subcell->type != ID($specify2)) + continue; + + for (auto bit : subcell->getPort(ID::SRC)) + { + if (!bit.wire || !cell->hasPort(bit.wire->name)) + continue; + inputSignals.append(sigmap(cell->getPort(bit.wire->name))); + } + + for (auto bit : subcell->getPort(ID::DST)) + { + if (!bit.wire || !cell->hasPort(bit.wire->name)) + continue; + outputSignals.append(sigmap(cell->getPort(bit.wire->name))); + } + } + } else { + for (auto &conn : cell->connections()) + { + bool isInput = true, isOutput = true; + + if (ct.cell_known(cell->type)) { + isInput = ct.cell_input(cell->type, conn.first); + isOutput = ct.cell_output(cell->type, conn.first); + } + + RTLIL::SigSpec sig = selectedSignals.extract(sigmap(conn.second)); + sig.sort_and_unify(); + + if (isInput) + inputSignals.append(sig); + if (isOutput) + outputSignals.append(sig); + } + } + + inputSignals.sort_and_unify(); + outputSignals.sort_and_unify(); + + cellToPrevSig[cell] = inputSignals; + cellToNextSig[cell] = outputSignals; + sigToNextCells.insert(inputSignals, cell); + } + + for (auto cell : workQueue) + { + sigToNextCells.find(cellToNextSig[cell], cellToNextCell[cell]); + + if (!nofeedbackMode && cellToNextCell[cell].count(cell)) { + std::string message = "Found an SCC:"; + pool scc; + message += stringf(" %s", cell); + cell2scc[cell] = sccList.size(); + scc.insert(cell); + sccList.push_back(scc); + log("%s\n", message); + } + } + + labelCounter = 0; + cellLabels.clear(); + + while (!workQueue.empty()) + { + RTLIL::Cell *cell = *workQueue.begin(); + log_assert(cellStack.size() == 0); + cellDepth.clear(); + + run(cell, 0, maxDepth); + } + + log("Found %d SCCs in module %s.\n", int(sccList.size()), module); + } + + void select(RTLIL::Selection &sel) + { + for (int i = 0; i < int(sccList.size()); i++) + { + pool &cells = sccList[i]; + RTLIL::SigSpec prevsig, nextsig, sig; + + for (auto cell : cells) { + sel.selected_members[module->name].insert(cell->name); + prevsig.append(cellToPrevSig[cell]); + nextsig.append(cellToNextSig[cell]); + } + + prevsig.sort_and_unify(); + nextsig.sort_and_unify(); + sig = prevsig.extract(nextsig); + + for (auto &chunk : sig.chunks()) + if (chunk.wire != NULL) + sel.selected_members[module->name].insert(chunk.wire->name); + } + } +}; + +struct SccPass : public Pass { + SccPass() : Pass("scc", "detect strongly connected components (logic loops)") { } + bool formatted_help() override { + auto *help = PrettyHelp::get_current(); + help->set_group("passes/status"); + return false; + } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" scc [options] [selection]\n"); + log("\n"); + log("This command identifies strongly connected components (aka logic loops) in the\n"); + log("design.\n"); + log("\n"); + log(" -expect \n"); + log(" expect to find exactly SCCs. A different number of SCCs will\n"); + log(" produce an error.\n"); + log("\n"); + log(" -max_depth \n"); + log(" limit to loops not longer than the specified number of cells. This\n"); + log(" can e.g. be useful in identifying small local loops in a module that\n"); + log(" implements one large SCC.\n"); + log("\n"); + log(" -nofeedback\n"); + log(" do not count cells that have their output fed back into one of their\n"); + log(" inputs as single-cell scc.\n"); + log("\n"); + log(" -all_cell_types\n"); + log(" Usually this command only considers internal non-memory cells. With\n"); + log(" this option set, all cells are considered. For unknown cells all ports\n"); + log(" are assumed to be bidirectional 'inout' ports.\n"); + log("\n"); + log(" -set_attr \n"); + log(" set the specified attribute on all cells that are part of a logic\n"); + log(" loop. the special token {} in the value is replaced with a unique\n"); + log(" identifier for the logic loop.\n"); + log("\n"); + log(" -select\n"); + log(" replace the current selection with a selection of all cells and wires\n"); + log(" that are part of a found logic loop\n"); + log("\n"); + log(" -specify\n"); + log(" examine specify rules to detect logic loops in whitebox/blackbox cells\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + dict setAttr; + bool allCellTypes = false; + bool selectMode = false; + bool nofeedbackMode = false; + bool specifyMode = false; + int maxDepth = -1; + int expect = -1; + + log_header(design, "Executing SCC pass (detecting logic loops).\n"); + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + if (args[argidx] == "-max_depth" && argidx+1 < args.size()) { + maxDepth = atoi(args[++argidx].c_str()); + continue; + } + if (args[argidx] == "-expect" && argidx+1 < args.size()) { + expect = atoi(args[++argidx].c_str()); + continue; + } + if (args[argidx] == "-nofeedback") { + nofeedbackMode = true; + continue; + } + if (args[argidx] == "-all_cell_types") { + allCellTypes = true; + continue; + } + if (args[argidx] == "-set_attr" && argidx+2 < args.size()) { + setAttr[args[argidx+1]] = args[argidx+2]; + argidx += 2; + continue; + } + if (args[argidx] == "-select") { + selectMode = true; + continue; + } + if (args[argidx] == "-specify") { + specifyMode = true; + continue; + } + break; + } + int origSelectPos = design->selection_stack.size() - 1; + extra_args(args, argidx, design); + + auto newSelection = RTLIL::Selection::EmptySelection(design); + int scc_counter = 0; + + for (auto mod : design->selected_modules()) + { + SccWorker worker(design, mod, nofeedbackMode, allCellTypes, specifyMode, maxDepth); + + if (!setAttr.empty()) + { + for (const auto &cells : worker.sccList) + { + for (auto attr : setAttr) + { + IdString attr_name = design->twines().add(RTLIL::escape_id(attr.first)); + string attr_valstr = attr.second; + string index = stringf("%d", scc_counter); + + for (size_t pos = 0; (pos = attr_valstr.find("{}", pos)) != string::npos; pos += index.size()) + attr_valstr.replace(pos, 2, index); + + Const attr_value(attr_valstr); + + for (auto cell : cells) + cell->attributes[attr_name] = attr_value; + } + + scc_counter++; + } + } + else + { + scc_counter += GetSize(worker.sccList); + } + + if (selectMode) + worker.select(newSelection); + } + + if (expect >= 0) { + if (scc_counter == expect) + log("Found and expected %d SCCs.\n", scc_counter); + else + log_error("Found %d SCCs but expected %d.\n", scc_counter, expect); + } else + log("Found %d SCCs.\n", scc_counter); + + if (selectMode) { + log_assert(origSelectPos >= 0); + design->selection_stack[origSelectPos] = newSelection; + design->selection_stack[origSelectPos].optimize(design); + } + } +} SccPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/scratchpad.cc b/chips/yosys/passes/cmds/scratchpad.cc new file mode 100644 index 0000000000000000000000000000000000000000..a4f16ce55503dd5043d1f5f5b2eda9db8ae53004 --- /dev/null +++ b/chips/yosys/passes/cmds/scratchpad.cc @@ -0,0 +1,146 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * 2019 N. Engelhardt + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "kernel/log_help.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct ScratchpadPass : public Pass { + ScratchpadPass() : Pass("scratchpad", "get/set values in the scratchpad") { } + bool formatted_help() override { + auto *help = PrettyHelp::get_current(); + help->set_group("passes/status"); + return false; + } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" scratchpad [options]\n"); + log("\n"); + log("This pass allows reading and modifying values from the scratchpad of the current\n"); + log("design. Options:\n"); + log("\n"); + log(" -get \n"); + log(" print the value saved in the scratchpad under the given identifier.\n"); + log("\n"); + log(" -set \n"); + log(" save the given value in the scratchpad under the given identifier.\n"); + log("\n"); + log(" -unset \n"); + log(" remove the entry for the given identifier from the scratchpad.\n"); + log("\n"); + log(" -copy \n"); + log(" copy the value of the first identifier to the second identifier.\n"); + log("\n"); + log(" -assert \n"); + log(" assert that the entry for the given identifier is set to the given\n"); + log(" value.\n"); + log("\n"); + log(" -assert-set \n"); + log(" assert that the entry for the given identifier exists.\n"); + log("\n"); + log(" -assert-unset \n"); + log(" assert that the entry for the given identifier does not exist.\n"); + log("\n"); + log("The identifier may not contain whitespace. By convention, it is usually prefixed\n"); + log("by the name of the pass that uses it, e.g. 'opt.did_something'. If the value\n"); + log("contains whitespace, it must be enclosed in double quotes.\n"); + log("\n"); + } + + void execute(std::vector args, RTLIL::Design *design) override + { + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) + { + if (args[argidx] == "-get" && argidx+1 < args.size()) { + string identifier = args[++argidx]; + if (design->scratchpad.count(identifier)) { + log("%s\n", design->scratchpad_get_string(identifier)); + } else if (RTLIL::constpad.count(identifier)) { + log("%s\n", RTLIL::constpad.at(identifier)); + } else { + log("\"%s\" not set\n", identifier); + } + continue; + } + if (args[argidx] == "-set" && argidx+2 < args.size()) { + string identifier = args[++argidx]; + if (RTLIL::constpad.count(identifier)) + log_error("scratchpad entry \"%s\" is a global constant\n", identifier); + string value = args[++argidx]; + if (value.front() == '\"' && value.back() == '\"') value = value.substr(1, value.size() - 2); + design->scratchpad_set_string(identifier, value); + continue; + } + if (args[argidx] == "-unset" && argidx+1 < args.size()) { + string identifier = args[++argidx]; + design->scratchpad_unset(identifier); + continue; + } + if (args[argidx] == "-copy" && argidx+2 < args.size()) { + string identifier_from = args[++argidx]; + string identifier_to = args[++argidx]; + string value; + if (design->scratchpad.count(identifier_from)) + value = design->scratchpad_get_string(identifier_from); + else if (RTLIL::constpad.count(identifier_from)) + value = RTLIL::constpad.at(identifier_from); + else + log_error("\"%s\" not set\n", identifier_from); + if (RTLIL::constpad.count(identifier_to)) + log_error("scratchpad entry \"%s\" is a global constant\n", identifier_to); + design->scratchpad_set_string(identifier_to, value); + continue; + } + if (args[argidx] == "-assert" && argidx+2 < args.size()) { + string identifier = args[++argidx]; + string expected = args[++argidx]; + if (expected.front() == '\"' && expected.back() == '\"') expected = expected.substr(1, expected.size() - 2); + if (design->scratchpad.count(identifier) == 0) + log_error("scratchpad entry '%s' is not defined\n", identifier); + string value = design->scratchpad_get_string(identifier); + if (value != expected) { + log_error("scratchpad entry '%s' is set to '%s' instead of the asserted '%s'\n", + identifier, value, expected); + } + continue; + } + if (args[argidx] == "-assert-set" && argidx+1 < args.size()) { + string identifier = args[++argidx]; + if (design->scratchpad.count(identifier) == 0) + log_error("scratchpad entry '%s' is not defined\n", identifier); + continue; + } + if (args[argidx] == "-assert-unset" && argidx+1 < args.size()) { + string identifier = args[++argidx]; + if (design->scratchpad.count(identifier) > 0) + log_error("scratchpad entry '%s' is defined\n", identifier); + continue; + } + break; + } + extra_args(args, argidx, design, false); + } +} ScratchpadPass; +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/sdc/CMakeLists.txt b/chips/yosys/passes/cmds/sdc/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..a42525d67f25758b8ff90a9366228490cf800576 --- /dev/null +++ b/chips/yosys/passes/cmds/sdc/CMakeLists.txt @@ -0,0 +1,9 @@ +yosys_pass(sdc + sdc.cc + LIBRARIES + $<${YOSYS_ENABLE_TCL}:PkgConfig::tcl> + DATA_DIR + sdc + DATA_FILES + graph-stubs.sdc +) diff --git a/chips/yosys/passes/cmds/sdc/graph-stubs.sdc b/chips/yosys/passes/cmds/sdc/graph-stubs.sdc new file mode 100644 index 0000000000000000000000000000000000000000..a6601f7f83e80e9feaff6e2c97316171d3703958 --- /dev/null +++ b/chips/yosys/passes/cmds/sdc/graph-stubs.sdc @@ -0,0 +1,42 @@ +proc unknown {args} { + # Check if it's a getter + if {[llength $args] > 0} { + set first_arg [lindex $args 0] + if {[string match "get_*" $first_arg]} { + # It's a getter, has it been redirected from specialized C++ code? + if {[llength $args] > 1} { + set second_arg [lindex $args 1] + if {$second_arg ne "-getter-validated"} { + error "Unknown getter: $first_arg" + } + } else { + error "Unknown getter: $first_arg" + } + } + } + # TODO this safety feature could be optional via a global + + global sdc_call_index + global sdc_calls + if {![info exists sdc_call_index]} { + set sdc_call_index 0 + } + if {![info exists sdc_calls]} { + set sdc_calls {} + } + set ret "YOSYS_SDC_MAGIC_NODE_$sdc_call_index" + incr sdc_call_index + lappend sdc_calls $args + # puts "unknown $args, returning YOSYS_SDC_MAGIC_NODE_$sdc_call_index" + return $ret +} +proc list {args} { + return [unknown "list" {*}$args] +} +proc get_clocks {args} { + # get_clocks isn't a design object getter + # because clocks aren't design objects, just aliases + # so the referred to clock pin already are being tracked + # as arguments of uninterpreted create_clock command or similar + return [unknown "get_clocks" "-getter-validated" {*}$args] +} diff --git a/chips/yosys/passes/cmds/sdc/sdc.cc b/chips/yosys/passes/cmds/sdc/sdc.cc new file mode 100644 index 0000000000000000000000000000000000000000..b1e466099f8b85463afbe79cb7bed55ab5fe2c78 --- /dev/null +++ b/chips/yosys/passes/cmds/sdc/sdc.cc @@ -0,0 +1,796 @@ +#include "kernel/yosys_config.h" +#ifdef YOSYS_ENABLE_TCL + +#include "kernel/register.h" +#include "kernel/rtlil.h" +#include "kernel/log.h" +#include +#include +#include +#include + +#if TCL_MAJOR_VERSION < 9 +typedef int YS_Tcl_Size; +#else +typedef Tcl_Size YS_Tcl_Size; +#endif + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct TclCall { + Tcl_Interp *interp; + int objc; + Tcl_Obj* const* objv; +}; + +static int redirect_unknown(TclCall call); +static size_t get_node_count(Tcl_Interp* interp); + +struct BitSelection { + bool all = false; + std::vector bits = {}; + void set_all() { + bits.clear(); + all = true; + } + void clear() { + bits.clear(); + all = false; + } + void set(size_t idx) { + if (all) + return; + if (idx >= bits.size()) + bits.resize(idx + 1); + bits[idx] = true; + } + void merge(const BitSelection& other) { + if (all) + return; + if (other.all) { + set_all(); + return; + } + if (other.bits.size() > bits.size()) + bits.resize(other.bits.size()); + for (size_t other_idx = 0; other_idx < other.bits.size(); other_idx++) { + bool other_bit = other.bits[other_idx]; + if (other_bit) + set(other_idx); + } + } + void dump() { + if (!all) { + for (size_t i = 0; i < bits.size(); i++) + if (bits[i]) + log("\t\t [%zu]\n", i); + } else { + log("\t\t FULL\n"); + } + } + bool is_set(size_t idx) const { + if (all) + return true; + if (idx >= bits.size()) + return false; + return bits[idx]; + } + // TODO actually use this + void compress(size_t size) { + if (bits.size() < size) + return; + for (size_t i = 0; i < size; i++) + if (!bits[i]) + return; + bits.clear(); + bits.shrink_to_fit(); + all = true; + } +}; + +struct SdcObjects { + enum CollectMode { + // getter-side object tracking with minimal features + SimpleGetter, + // getter-side object tracking with everything + FullGetter, + // constraint-side tracking + FullConstraint, + } collect_mode; + using CellPin = std::pair; + Design* design; + std::vector> design_ports; + std::vector> design_cells; + std::vector> design_pins; + std::vector> design_nets; + + using PortPattern = std::tuple; + using PinPattern = std::tuple; + std::vector> resolved_port_pattern_sets; + std::vector> resolved_pin_pattern_sets; + // TODO + + dict, BitSelection> constrained_ports; + pool> constrained_cells; + dict, BitSelection> constrained_pins; + dict, BitSelection> constrained_nets; + + void sniff_module(std::list& hierarchy, Module* mod) { + std::string prefix; + for (auto mod_name : hierarchy) { + if (prefix.length()) + prefix += "/"; // TODO seperator? + prefix += mod_name; + } + + for (auto* wire : mod->wires()) { + std::string name = wire->name.str(); + log_assert(name.length()); + // TODO: really skip internal wires? + if (name[0] == '$') + continue; + name = name.substr(1); + std::string path = prefix; + if (path.length()) + path += "/"; + path += name; + design_nets.push_back(std::make_pair(path, wire)); + } + + for (auto* cell : mod->cells()) { + std::string name = cell->name.str(); + // TODO: really skip internal cells? + if (name[0] == '$') + continue; + name = name.substr(1); + std::string path = prefix; + if (path.length()) + path += "/"; + path += name; + design_cells.push_back(std::make_pair(path, cell)); + for (auto& pin : cell->connections()) { + IdString pin_name = pin.first; + std::string pin_name_sdc = path + "/" + design->twines().str(pin.first); + design_pins.push_back(std::make_pair(pin_name_sdc, std::make_pair(cell, pin_name))); + } + if (auto sub_mod = mod->design->module(cell->type)) { + hierarchy.push_back(name); + sniff_module(hierarchy, sub_mod); + hierarchy.pop_back(); + } + } + } + SdcObjects(Design* design) : design(design) { + Module* top = design->top_module(); + if (!top) + log_error("Top module couldn't be determined. Check 'top' attribute usage\n"); + for (auto port : top->ports) { + RTLIL::Wire *wire = top->wire(port); + if (!wire) { + // This should not be possible. See https://github.com/YosysHQ/yosys/pull/5594#issue-3791198573 + log_error("Port %s doesn't exist\n", PooledName(design, port).unescape()); + } + design_ports.push_back(std::make_pair(design->twines().str(port), wire)); + } + std::list hierarchy{}; + sniff_module(hierarchy, top); + } + ~SdcObjects() = default; + + template + void build_normal_result(Tcl_Interp* interp, std::vector>&& resolved, U& tgt, std::function width, Tcl_Obj*& result) { + if (!result) + result = Tcl_NewListObj(resolved.size(), nullptr); + for (auto [name, obj, matching_bits] : resolved) { + for (size_t i = 0; i < width(obj); i++) + if (matching_bits.is_set(i)) { + Tcl_ListObjAppendElement(interp, result, Tcl_NewStringObj(name.c_str(), name.size())); + break; + } + + } + size_t node_count = get_node_count(interp); + tgt.emplace_back(std::move(resolved)); + log("%zu %zu\n", node_count, tgt.size()); + log_assert(node_count == tgt.size()); + } + template + void merge_as_constrained(std::vector>&& resolved) { + for (auto [name, obj, matching_bits] : resolved) { + merge_or_init(std::make_pair(name, obj), constrained_pins, matching_bits); + } + } + void dump() { + std::sort(design_ports.begin(), design_ports.end()); + std::sort(design_cells.begin(), design_cells.end()); + std::sort(design_pins.begin(), design_pins.end()); + std::sort(design_nets.begin(), design_nets.end()); + constrained_ports.sort(); + constrained_cells.sort(); + constrained_pins.sort(); + constrained_nets.sort(); + // log("Design ports:\n"); + // for (auto name : design_ports) { + // log("\t%s\n", name); + // } + // log("Design cells:\n"); + // for (auto [name, cell] : design_cells) { + // (void)cell; + // log("\t%s\n", name); + // } + // log("Design pins:\n"); + // for (auto [name, pin] : design_pins) { + // (void)pin; + // log("\t%s\n", name); + // } + // log("Design nets:\n"); + // for (auto [name, net] : design_nets) { + // (void)net; + // log("\t%s\n", name); + // } + // log("\n"); + log("Constrained ports:\n"); + for (auto [ref, bits] : constrained_ports) { + auto [name, port] = ref; + (void)port; + log("\t%s\n", name); + bits.dump(); + } + log("Constrained cells:\n"); + for (auto& [name, cell] : constrained_cells) { + (void)cell; + log("\t%s\n", name); + } + log("Constrained pins:\n"); + for (auto& [ref, bits] : constrained_pins) { + auto [name, pin] = ref; + (void)pin; + log("\t%s\n", name); + bits.dump(); + } + log("Constrained nets:\n"); + for (auto& [ref, bits] : constrained_nets) { + auto [name, net] = ref; + (void)net; + log("\t%s\n", name); + bits.dump(); + } + log("\n"); + } + + class KeepHierarchyWorker { + std::unordered_set tracked_modules = {}; + Design* design = nullptr; + bool mark(Module* mod) { + for (auto* cell : mod->cells()) { + if (auto* submod = design->module(cell->type)) + if (mark(submod)) { + mod->set_bool_attribute(ID::keep_hierarchy); + return true; + } + } + + if (tracked_modules.count(mod)) { + mod->set_bool_attribute(ID::keep_hierarchy); + return true; + } + + return false; + } + public: + KeepHierarchyWorker(SdcObjects* objects, Design* d) : design(d) { + for (auto [ref, _] : objects->constrained_ports) { + tracked_modules.insert(ref.second->module); + } + for (auto& [_, cell] : objects->constrained_cells) { + tracked_modules.insert(cell->module); + } + for (auto& [ref, _] : objects->constrained_pins) { + tracked_modules.insert(ref.second.first->module); + } + for (auto& [ref, _] : objects->constrained_nets) { + tracked_modules.insert(ref.second->module); + } + log_debug("keep_hierarchy tracked modules:\n"); + for (auto* mod : tracked_modules) + log_debug("\t%s\n", mod->name); + } + bool mark() { + return mark(design->top_module()); + } + }; + void keep_hierarchy() { + (void)KeepHierarchyWorker(this, design).mark(); + } +}; + +// TODO vectors +// TODO cell arrays? +struct MatchConfig { + enum MatchMode { + WILDCARD, + REGEX, + } match; + bool match_case; + enum HierMode { + FLAT, + TREE, + } hier; + MatchConfig(bool regexp_flag, bool nocase_flag, bool hierarchical_flag) : + match(regexp_flag ? REGEX : WILDCARD), + match_case(!nocase_flag), + hier(hierarchical_flag ? FLAT : TREE) { } +}; + +static std::pair matches(std::string name, const std::string& pat, const MatchConfig& config) { + (void)config; + bool got_bit_index = false;; + int bit_idx; + std::string pat_base = pat; + size_t pos = pat.rfind('['); + if (pos != std::string::npos) { + got_bit_index = true; + pat_base = pat.substr(0, pos); + std::string bit_selector = pat.substr(pos + 1, pat.rfind(']') - pos - 1); + for (auto c : bit_selector) + if (!std::isdigit(c)) + log_error("Unsupported bit selector %s in SDC pattern %s\n", + bit_selector, pat); + bit_idx = std::stoi(bit_selector); + + } + BitSelection bits = {}; + if (name == pat_base) { + if (got_bit_index) { + bits.set(bit_idx); + return std::make_pair(true, bits); + } else { + bits.set_all(); + return std::make_pair(true, bits); + + } + } else { + return std::make_pair(false, bits); + } +} + +static int getter_graph_node(TclCall call) { + // Insert -getter-validated as first argument for passing to unknown + // to distinguish resolved and unknown getters. + // For example, if call is ["get_foo", "-bar"] + // then newCall is ["get_foo", "-getter-validated", "-bar"] + Tcl_Obj* validity_tag = Tcl_NewStringObj("-getter-validated", -1); + Tcl_IncrRefCount(validity_tag); + std::vector newObjv(call.objc + 1); + log_assert(call.objc > 0); + newObjv[0] = call.objv[0]; + newObjv[1] = validity_tag; + for (int i = 1; i < call.objc; ++i) { + newObjv[i + 1] = call.objv[i]; + } + // Send the vector to the Tcl land + Tcl_Obj** allocatedObjv = (Tcl_Obj**)Tcl_Alloc((call.objc + 1) * sizeof(Tcl_Obj*)); + for (int i = 0; i < call.objc + 1; ++i) { + allocatedObjv[i] = newObjv[i]; + } + TclCall newCall { + .interp = call.interp, + .objc = call.objc + 1, + .objv = allocatedObjv + }; + // Finally, redirect to unknown handler + return redirect_unknown(newCall); +} + +static int redirect_unknown(TclCall call) { + // TODO redirect to different command + Tcl_Obj *newCmd = Tcl_NewStringObj("unknown", -1); + auto newObjc = call.objc + 1; + Tcl_Obj** newObjv = (Tcl_Obj**)Tcl_Alloc(newObjc * sizeof(Tcl_Obj*)); + newObjv[0] = newCmd; + for (int i = 1; i < newObjc; i++) { + newObjv[i] = call.objv[i - 1]; + } + int result = Tcl_EvalObjv(call.interp, newObjc, newObjv, 0); + Tcl_DecrRefCount(newCmd); + Tcl_Free((char*) newObjv); + return result; +} + + +struct SdcGraphNode { + using Child = std::variant; + std::vector children; + SdcGraphNode() = default; + void addChild(SdcGraphNode* child) { + children.push_back(child); + } + void addChild(std::string tcl_string) { + children.push_back(tcl_string); + } + void dump(std::ostream& os) const { + bool first = true; + for (auto child : children) { + if (first) { + first = false; + } else { + os << " "; + } + if (auto* s = std::get_if(&child)) + os << *s; + else if (SdcGraphNode*& c = *std::get_if(&child)) { + os << "["; + c->dump(os); + os << "]"; + } else { + log_assert(false); + } + } + } +}; + +static size_t get_node_count(Tcl_Interp* interp) { + const char* idx_raw = Tcl_GetVar(interp, "sdc_call_index", TCL_GLOBAL_ONLY); + log_assert(idx_raw); + std::string idx(idx_raw); + for (auto c : idx) + if (!std::isdigit(c)) + log_error("sdc_call_index non-numeric value %s\n", idx); + return std::stoi(idx); +} + +std::vector> gather_nested_calls(Tcl_Interp* interp) { + + Tcl_Obj* listObj = Tcl_GetVar2Ex(interp, "sdc_calls", nullptr, TCL_GLOBAL_ONLY); + YS_Tcl_Size listLength; + + std::vector> sdc_calls; + if (Tcl_ListObjLength(interp, listObj, &listLength) == TCL_OK) { + for (int i = 0; i < listLength; i++) { + Tcl_Obj* subListObj; + std::vector subList; + if (Tcl_ListObjIndex(interp, listObj, i, &subListObj) != TCL_OK) { + log_error("broken list of lists\n"); + } + YS_Tcl_Size subListLength; + if (Tcl_ListObjLength(interp, subListObj, &subListLength) == TCL_OK) { + // Valid list - extract elements + for (int j = 0; j < subListLength; j++) { + Tcl_Obj* elementObj; + if (Tcl_ListObjIndex(interp, subListObj, j, &elementObj) == TCL_OK) { + const char* elementStr = Tcl_GetString(elementObj); + subList.push_back(std::string(elementStr)); + } + } + } else { + // Single element, not a list + const char* elementStr = Tcl_GetString(subListObj); + subList.push_back(std::string(elementStr)); + } + sdc_calls.push_back(subList); + } + } + log_assert(sdc_calls.size() == get_node_count(interp)); + return sdc_calls; +} + +std::vector build_graph(const std::vector>& sdc_calls) { + size_t node_count = sdc_calls.size(); + std::vector graph(node_count); + for (size_t i = 0; i < node_count; i++) { + auto& new_node = graph[i]; + for (size_t j = 0; j < sdc_calls[i].size(); j++) { + auto arg = sdc_calls[i][j]; + const std::string prefix = "YOSYS_SDC_MAGIC_NODE_"; + auto pos = arg.find(prefix); + if (pos != std::string::npos) { + std::string rest = arg.substr(pos + prefix.length()); + for (auto c : rest) + if (!std::isdigit(c)) + log_error("weird thing %s in %s\n", rest, arg); + size_t arg_node_idx = std::stoi(rest); + log_assert(arg_node_idx < graph.size()); + new_node.addChild(&graph[arg_node_idx]); + } else { + new_node.addChild(arg); + } + + } + } + return graph; +} + +std::vector node_ownership(const std::vector& graph) { + std::vector has_parent(graph.size()); + for (auto node : graph) { + for (auto child : node.children) { + if (SdcGraphNode** pp = std::get_if(&child)) { + size_t idx = std::distance(&graph.front(), (const SdcGraphNode*)*pp); + log_assert(idx < has_parent.size()); + has_parent[idx] = true; + } + } + } + return has_parent; +} + +void dump_sdc_graph(const std::vector& graph, const std::vector& has_parent) { + for (size_t i = 0; i < graph.size(); i++) { + if (!has_parent[i]) { + graph[i].dump(std::cout); + std::cout << "\n"; + } + } +} + +void inspect_globals(Tcl_Interp* interp, bool dump_mode) { + std::vector> sdc_calls = gather_nested_calls(interp); + std::vector graph = build_graph(sdc_calls); + if (dump_mode) + dump_sdc_graph(graph, node_ownership(graph)); +} + +// patterns -> (pattern-object-bit)s +template +std::vector> +find_matching(U objects, const MatchConfig& config, const std::vector &patterns, const char* obj_type) +{ + std::vector> resolved; + for (auto pat : patterns) { + bool found = false; + for (auto [name, obj] : objects) { + auto [does_match, matching_bits] = matches(name, pat, config); + if (does_match) { + found = true; + resolved.push_back(std::make_tuple(name, obj, matching_bits)); + // TODO add a continue statement, conditional on config + } + } + if (!found) + log_warning("No matches in design for %s %s\n", obj_type, pat); + } + return resolved; +} + +struct TclOpts { + const char* name; + std::initializer_list legals; + TclOpts(const char* name, std::initializer_list legals) : name(name), legals(legals) {} + bool parse_opt(Tcl_Obj* obj, const char* opt_name) { + char* arg = Tcl_GetString(obj); + std::string expected = std::string("-") + opt_name; + if (expected == arg) { + if (!std::find_if(legals.begin(), legals.end(), + [&opt_name](const char* str) { return opt_name == str; })) + log_cmd_error("Illegal argument %s for %s.\n", expected, name); + return true; + } + return false; + } +}; + +struct GetterOpts : TclOpts { + bool hierarchical_flag = false; + bool regexp_flag = false; + bool nocase_flag = false; + std::string separator = "/"; + Tcl_Obj* of_objects = nullptr; + std::vector patterns = {}; + GetterOpts(const char* name, std::initializer_list legals) : TclOpts(name, legals) {} + template + bool parse_flag(Tcl_Obj* obj, const char* flag_name, T& flag_var) { + bool ret = parse_opt(obj, flag_name); + if (ret) + flag_var = true; + return ret; + } + void parse(int objc, Tcl_Obj* const objv[]) { + int i = 1; + for (; i < objc; i++) { + if (parse_flag(objv[i], "hierarchical", hierarchical_flag)) continue; + if (parse_flag(objv[i], "hier", hierarchical_flag)) continue; + if (parse_flag(objv[i], "regexp", regexp_flag)) continue; + if (parse_flag(objv[i], "nocase", nocase_flag)) continue; + if (parse_opt(objv[i], "hsc")) { + log_assert(i + 1 < objc); + separator = Tcl_GetString(objv[++i]); + continue; + } + if (parse_opt(objv[i], "of_objects")) { + log_assert(i + 1 < objc); + of_objects = objv[++i]; + continue; + } + break; + } + for (; i < objc; i++) { + patterns.push_back(Tcl_GetString(objv[i])); + } + }; + void check_simple() { + if (regexp_flag || hierarchical_flag || nocase_flag || separator != "/" || of_objects) { + log_error("%s got unexpected flags in simple mode\n", name); + } + if (patterns.size() != 1) + log_error("%s got unexpected number of patterns in simple mode: %zu\n", name, patterns.size()); + } + void check_simple_sep() { + if (separator != "/") + log_error("Only '/' accepted as separator\n"); + } +}; + +template +void merge_or_init(const T& key, dict& dst, const BitSelection& src) { + if (dst.count(key) == 0) { + dst[key] = src; + } else { + dst[key].merge(src); + } +} + +static int sdc_get_pins_cmd(ClientData data, Tcl_Interp *interp, int objc, Tcl_Obj* const objv[]) +{ + auto* objects = (SdcObjects*)data; + GetterOpts opts("get_pins", {"hierarchical", "hier", "regexp", "nocase", "hsc", "of_objects"}); + opts.parse(objc, objv); + if (objects->collect_mode == SdcObjects::CollectMode::SimpleGetter) + opts.check_simple(); + opts.check_simple_sep(); + + MatchConfig config(opts.regexp_flag, opts.nocase_flag, opts.hierarchical_flag); + std::vector> resolved; + const auto& pins = objects->design_pins; + resolved = find_matching(pins, config, opts.patterns, "pin"); + + return getter_graph_node(TclCall{interp, objc, objv}); +} + +static int sdc_get_ports_cmd(ClientData data, Tcl_Interp *interp, int objc, Tcl_Obj* const objv[]) +{ + auto* objects = (SdcObjects*)data; + GetterOpts opts("get_ports", {"regexp", "nocase"}); + opts.parse(objc, objv); + if (objects->collect_mode == SdcObjects::CollectMode::SimpleGetter) + opts.check_simple(); + + MatchConfig config(opts.regexp_flag, opts.nocase_flag, false); + std::vector> resolved; + const auto& ports = objects->design_ports; + resolved = find_matching(ports, config, opts.patterns, "port"); + + for (auto [name, wire, matching_bits] : resolved) { + if (objects->collect_mode != SdcObjects::CollectMode::FullConstraint) + merge_or_init(std::make_pair(name, wire), objects->constrained_ports, matching_bits); + } + + return getter_graph_node(TclCall{interp, objc, objv}); +} + +static int sdc_get_nets_cmd(ClientData data, Tcl_Interp *interp, int objc, Tcl_Obj* const objv[]) +{ + auto* objects = (SdcObjects*)data; + GetterOpts opts("get_nets", {"hierarchical", "hier", "regexp", "nocase", "hsc", "of_objects"}); + opts.parse(objc, objv); + if (objects->collect_mode == SdcObjects::CollectMode::SimpleGetter) + opts.check_simple(); + + MatchConfig config(opts.regexp_flag, opts.nocase_flag, false); + std::vector> resolved; + const auto& ports = objects->design_nets; + resolved = find_matching(ports, config, opts.patterns, "net"); + + for (auto [name, wire, matching_bits] : resolved) { + if (objects->collect_mode != SdcObjects::CollectMode::FullConstraint) + merge_or_init(std::make_pair(name, wire), objects->constrained_nets, matching_bits); + } + + return getter_graph_node(TclCall{interp, objc, objv}); +} + +class SDCInterpreter +{ +private: + Tcl_Interp* interp = nullptr; +public: + std::unique_ptr objects; + ~SDCInterpreter() { + if (interp) + Tcl_DeleteInterp(interp); + } + static SDCInterpreter& get() { + static SDCInterpreter instance; + return instance; + } + Tcl_Interp* fresh_interp(Design* design) { + if (interp) + Tcl_DeleteInterp(interp); + + interp = Tcl_CreateInterp(); + if (Tcl_Init(interp)!=TCL_OK) + log_error("Tcl_Init() call failed - %s\n",Tcl_ErrnoMsg(Tcl_GetErrno())); + + objects = std::make_unique(design); + objects->collect_mode = SdcObjects::CollectMode::SimpleGetter; + Tcl_CreateObjCommand(interp, "get_pins", sdc_get_pins_cmd, (ClientData) objects.get(), NULL); + Tcl_CreateObjCommand(interp, "get_nets", sdc_get_nets_cmd, (ClientData) objects.get(), NULL); + Tcl_CreateObjCommand(interp, "get_ports", sdc_get_ports_cmd, (ClientData) objects.get(), NULL); + return interp; + } +}; + +// Also see TclPass +struct SdcPass : public Pass { + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" sdc [options] file\n"); + log("\n"); + log("Read the SDC file for the current design.\n"); + log("\n"); + log(" -dump\n"); + log(" Dump the referenced design objects.\n"); + log("\n"); + log(" -dump-graph\n"); + log(" Dump the uninterpreted call graph.\n"); + log("\n"); + log(" -keep_hierarchy\n"); + log(" Add keep_hierarchy attributes while retaining SDC validity.\n"); + log("\n"); + } + SdcPass() : Pass("sdc", "Read an SDC file") { } + void execute(std::vector args, RTLIL::Design *design) override { + log_header(design, "Executing SDC pass.\n"); + log_experimental("sdc"); + size_t argidx; + bool dump_mode = false; + bool dump_graph_mode = false; + bool keep_hierarchy_mode = false; + std::vector stubs_paths; + for (argidx = 1; argidx < args.size(); argidx++) { + if (args[argidx] == "-dump") { + dump_mode = true; + continue; + } else if (args[argidx] == "-dump-graph") { + dump_graph_mode = true; + continue; + } else if (args[argidx] == "-keep_hierarchy") { + keep_hierarchy_mode = true; + continue; + } else if (args[argidx] == "-stubs" && argidx+1 < args.size()) { + stubs_paths.push_back(args[++argidx]); + continue; + } + break; + } + if (argidx >= args.size()) + log_cmd_error("Missing SDC file.\n"); + + std::string sdc_path = args[argidx++]; + if (argidx < args.size()) + log_cmd_error("Unexpected extra positional argument %s after SDC file %s.\n", args[argidx], sdc_path); + SDCInterpreter& sdc = SDCInterpreter::get(); + Tcl_Interp *interp = sdc.fresh_interp(design); + Tcl_Preserve(interp); + std::string stub_path = "+/sdc/graph-stubs.sdc"; + rewrite_filename(stub_path); + if (Tcl_EvalFile(interp, stub_path.c_str()) != TCL_OK) + log_cmd_error("SDC interpreter returned an error in stub preamble file: %s\n", Tcl_GetStringResult(interp)); + for (auto path : stubs_paths) + if (Tcl_EvalFile(interp, path.c_str()) != TCL_OK) + log_cmd_error("SDC interpreter returned an error in OpenSTA stub file %s: %s\n", path, Tcl_GetStringResult(interp)); + if (Tcl_EvalFile(interp, sdc_path.c_str()) != TCL_OK) + log_cmd_error("SDC interpreter returned an error: %s\n", Tcl_GetStringResult(interp)); + if (dump_mode) + sdc.objects->dump(); + if (keep_hierarchy_mode) + sdc.objects->keep_hierarchy(); + inspect_globals(interp, dump_graph_mode); + Tcl_Release(interp); + } +} SdcPass; + +YOSYS_NAMESPACE_END +#endif diff --git a/chips/yosys/passes/cmds/select.cc b/chips/yosys/passes/cmds/select.cc new file mode 100644 index 0000000000000000000000000000000000000000..07043590b24380c231d65de98e1401ececd06be6 --- /dev/null +++ b/chips/yosys/passes/cmds/select.cc @@ -0,0 +1,1851 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/rtlil.h" +#include "kernel/twine.h" +#include "kernel/yosys.h" +#include "kernel/newcelltypes.h" +#include "kernel/sigtools.h" +#include "kernel/log_help.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + + +static bool match_ids(const std::string &id, const std::string &pattern) +{ + if (id == pattern) + return true; + + const char *id_c = id.c_str(); + const char *pat_c = pattern.c_str(); + size_t id_size = id.size(); + size_t pat_size = pattern.size(); + + if (*id_c == '\\' && id_size == 1 + pat_size && memcmp(id_c + 1, pat_c, pat_size) == 0) + return true; + if (patmatch(pat_c, id_c)) + return true; + if (*id_c == '\\' && patmatch(pat_c, id_c + 1)) + return true; + if (*id_c == '$' && *pat_c == '$') { + const char *q = strrchr(id_c, '$'); + if (pattern == q) + return true; + } + return false; +} + +static bool match_attr_val(const RTLIL::Const &value, const std::string &pattern, char match_op) +{ + if (match_op == 0) + return true; + + if ((value.flags & RTLIL::CONST_FLAG_STRING) == 0) + { + RTLIL::SigSpec sig_value; + + if (!RTLIL::SigSpec::parse(sig_value, nullptr, pattern)) + return false; + + RTLIL::Const pattern_value = sig_value.as_const(); + + if (match_op == '=') + return value == pattern_value; + if (match_op == '!') + return value != pattern_value; + if (match_op == '<') + return value.as_int() < pattern_value.as_int(); + if (match_op == '>') + return value.as_int() > pattern_value.as_int(); + if (match_op == '[') + return value.as_int() <= pattern_value.as_int(); + if (match_op == ']') + return value.as_int() >= pattern_value.as_int(); + } + else + { + std::string value_str = value.decode_string(); + + if (match_op == '=') + if (patmatch(pattern.c_str(), value.decode_string().c_str())) + return true; + + if (match_op == '=') + return value_str == pattern; + if (match_op == '!') + return value_str != pattern; + if (match_op == '<') + return value_str < pattern; + if (match_op == '>') + return value_str > pattern; + if (match_op == '[') + return value_str <= pattern; + if (match_op == ']') + return value_str >= pattern; + } + + log_abort(); +} + +static bool match_attr(const TwinePool &pool, const dict &attributes, const std::string &name_pat, const std::string &value_pat, char match_op) +{ + if (name_pat.find('*') != std::string::npos || name_pat.find('?') != std::string::npos || name_pat.find('[') != std::string::npos) { + for (auto &it : attributes) { + std::string name = pool.str(it.first); + if (patmatch(name_pat.c_str(), name.c_str()) && match_attr_val(it.second, value_pat, match_op)) + return true; + if (name.size() > 0 && name[0] == '\\' && patmatch(name_pat.c_str(), name.c_str() + 1) && match_attr_val(it.second, value_pat, match_op)) + return true; + } + } else { + if (name_pat.size() > 0 && (name_pat[0] == '\\' || name_pat[0] == '$')) { + IdString key = pool.find(name_pat); + if (key != IdString::Null && attributes.count(key) && match_attr_val(attributes.at(key), value_pat, match_op)) + return true; + } + IdString key = pool.find("\\" + name_pat); + if (key != IdString::Null && attributes.count(key) && match_attr_val(attributes.at(key), value_pat, match_op)) + return true; + } + return false; +} + +static bool match_attr(const TwinePool &pool, const dict &attributes, const std::string &match_expr) +{ + size_t pos = match_expr.find_first_of(""); + + if (pos != std::string::npos) { + if (match_expr.compare(pos, 2, "!=") == 0) + return match_attr(pool, attributes, match_expr.substr(0, pos), match_expr.substr(pos+2), '!'); + if (match_expr.compare(pos, 2, "<=") == 0) + return match_attr(pool, attributes, match_expr.substr(0, pos), match_expr.substr(pos+2), '['); + if (match_expr.compare(pos, 2, ">=") == 0) + return match_attr(pool, attributes, match_expr.substr(0, pos), match_expr.substr(pos+2), ']'); + return match_attr(pool, attributes, match_expr.substr(0, pos), match_expr.substr(pos+1), match_expr[pos]); + } + + return match_attr(pool, attributes, match_expr, std::string(), 0); +} + +static void select_all(RTLIL::Design *design, RTLIL::Selection &lhs) +{ + if (!lhs.selects_all()) + return; + lhs.current_design = design; + lhs.selected_modules.clear(); + for (auto mod : design->modules()) { + if (!lhs.selects_boxes && mod->get_blackbox_attribute()) + continue; + lhs.selected_modules.insert(mod->name); + } + lhs.full_selection = false; + lhs.complete_selection = false; +} + +static void select_op_neg(RTLIL::Design *design, RTLIL::Selection &lhs) +{ + if (lhs.selects_all()) { + lhs.clear(); + return; + } + + if (lhs.selected_modules.size() == 0 && lhs.selected_members.size() == 0) { + if (lhs.selects_boxes) + lhs.complete_selection = true; + else + lhs.full_selection = true; + return; + } + + auto new_sel = RTLIL::Selection::EmptySelection(); + + for (auto mod : design->modules()) + { + if (!lhs.selects_boxes && mod->get_blackbox_attribute()) + continue; + if (lhs.selected_whole_module(mod->name)) + continue; + if (!lhs.selected_module(mod->name)) { + new_sel.selected_modules.insert(mod->name); + continue; + } + + for (auto wire : mod->wires()) + if (!lhs.selected_member(mod->name, wire->name)) + new_sel.selected_members[mod->name].insert(wire->name); + for (auto &it : mod->memories) + if (!lhs.selected_member(mod->name, it.first)) + new_sel.selected_members[mod->name].insert(it.first); + for (auto cell : mod->cells()) + if (!lhs.selected_member(mod->name, cell->name)) + new_sel.selected_members[mod->name].insert(cell->name); + for (auto &it : mod->processes) + if (!lhs.selected_member(mod->name, it.first)) + new_sel.selected_members[mod->name].insert(it.first); + } + + lhs.selected_modules.swap(new_sel.selected_modules); + lhs.selected_members.swap(new_sel.selected_members); +} + +static int my_xorshift32_rng() { + static uint32_t x32 = 314159265; + x32 ^= x32 << 13; + x32 ^= x32 >> 17; + x32 ^= x32 << 5; + return x32 & 0x0fffffff; +} + +static void select_op_random(RTLIL::Design *design, RTLIL::Selection &lhs, int count) +{ + vector> objects; + + for (auto mod : design->modules()) + { + if (!lhs.selected_module(mod->name)) + continue; + + for (auto cell : mod->cells()) { + if (lhs.selected_member(mod->name, cell->name)) + objects.push_back(make_pair(mod->name, cell->name)); + } + + for (auto wire : mod->wires()) { + if (lhs.selected_member(mod->name, wire->name)) + objects.push_back(make_pair(mod->name, wire->name)); + } + } + + lhs = RTLIL::Selection(false, lhs.selects_boxes, design); + + while (!objects.empty() && count-- > 0) + { + int idx = my_xorshift32_rng() % GetSize(objects); + lhs.selected_members[objects[idx].first].insert(objects[idx].second); + objects[idx] = objects.back(); + objects.pop_back(); + } + + lhs.optimize(design); +} + +static void select_op_submod(RTLIL::Design *design, RTLIL::Selection &lhs) +{ + for (auto mod : design->modules()) + { + if (lhs.selected_whole_module(mod->name)) + { + for (auto cell : mod->cells()) + { + if (design->module(cell->type) == nullptr) + continue; + lhs.selected_modules.insert(cell->type); + } + } + } +} + +static void select_op_cells_to_modules(RTLIL::Design *design, RTLIL::Selection &lhs) +{ + RTLIL::Selection new_sel(false, lhs.selects_boxes, design); + for (auto mod : design->modules()) + if (lhs.selected_module(mod->name)) + for (auto cell : mod->cells()) + if (lhs.selected_member(mod->name, cell->name) && (design->module(cell->type) != nullptr)) + new_sel.selected_modules.insert(cell->type); + lhs = new_sel; +} + +static void select_op_module_to_cells(RTLIL::Design *design, RTLIL::Selection &lhs) +{ + RTLIL::Selection new_sel(false, lhs.selects_boxes, design); + for (auto mod : design->modules()) + for (auto cell : mod->cells()) + if ((design->module(cell->type) != nullptr) && lhs.selected_whole_module(cell->type)) + new_sel.selected_members[mod->name].insert(cell->name); + lhs = new_sel; +} + +static void select_op_fullmod(RTLIL::Design *design, RTLIL::Selection &lhs) +{ + lhs.optimize(design); + for (auto &it : lhs.selected_members) + lhs.selected_modules.insert(it.first); + lhs.selected_members.clear(); +} + +static void select_op_alias(RTLIL::Design *design, RTLIL::Selection &lhs) +{ + for (auto mod : design->modules()) + { + if (!lhs.selects_boxes && mod->get_blackbox_attribute()) + continue; + if (lhs.selected_whole_module(mod->name)) + continue; + if (!lhs.selected_module(mod->name)) + continue; + + SigMap sigmap(mod); + SigPool selected_bits; + + for (auto wire : mod->wires()) + if (lhs.selected_member(mod->name, wire->name)) + selected_bits.add(sigmap(wire)); + + for (auto wire : mod->wires()) + if (!lhs.selected_member(mod->name, wire->name) && selected_bits.check_any(sigmap(wire))) + lhs.selected_members[mod->name].insert(wire->name); + } +} + +static void select_op_union(RTLIL::Design* design, RTLIL::Selection &lhs, const RTLIL::Selection &rhs) +{ + if (lhs.complete_selection) + return; + else if (rhs.complete_selection) { + lhs.complete_selection = true; + lhs.optimize(design); + return; + } + + if (rhs.selects_boxes) { + if (lhs.full_selection) { + select_all(design, lhs); + } + lhs.selects_boxes = true; + } + else if (lhs.full_selection) + return; + + if (rhs.full_selection) { + if (lhs.selects_boxes) { + auto new_rhs = RTLIL::Selection(rhs); + select_all(design, new_rhs); + for (auto mod : new_rhs.selected_modules) + lhs.selected_modules.insert(mod); + } else { + lhs.clear(); + lhs.full_selection = true; + } + return; + } + + for (auto &it : rhs.selected_members) + for (auto &it2 : it.second) + lhs.selected_members[it.first].insert(it2); + + for (auto &it : rhs.selected_modules) { + lhs.selected_modules.insert(it); + lhs.selected_members.erase(it); + } +} + +static void select_op_union_all(RTLIL::Design *design, std::vector &work_stack) +{ + while (work_stack.size() > 1) { + select_op_union(design, work_stack.front(), work_stack.back()); + work_stack.pop_back(); + } +} + +static void select_op_diff(RTLIL::Design *design, RTLIL::Selection &lhs, const RTLIL::Selection &rhs) +{ + if (rhs.complete_selection) { + lhs.clear(); + return; + } + + if (rhs.full_selection) { + if (lhs.selects_boxes) { + auto new_rhs = RTLIL::Selection(rhs); + select_all(design, new_rhs); + select_all(design, lhs); + for (auto mod : new_rhs.selected_modules) { + lhs.selected_modules.erase(mod); + lhs.selected_members.erase(mod); + } + } else { + lhs.clear(); + } + return; + } + + if (rhs.empty() || lhs.empty()) + return; + + select_all(design, lhs); + + for (auto &it : rhs.selected_modules) { + lhs.selected_modules.erase(it); + lhs.selected_members.erase(it); + } + + for (auto &it : rhs.selected_members) + { + if (design->module(it.first) == nullptr) + continue; + + RTLIL::Module *mod = design->module(it.first); + + if (lhs.selected_modules.count(mod->name) > 0) + { + for (auto wire : mod->wires()) + lhs.selected_members[mod->name].insert(wire->name); + for (auto &it : mod->memories) + lhs.selected_members[mod->name].insert(it.first); + for (auto cell : mod->cells()) + lhs.selected_members[mod->name].insert(cell->name); + for (auto &it : mod->processes) + lhs.selected_members[mod->name].insert(it.first); + lhs.selected_modules.erase(mod->name); + } + + if (lhs.selected_members.count(mod->name) == 0) + continue; + + for (auto &it2 : it.second) + lhs.selected_members[mod->name].erase(it2); + } +} + +static void select_op_intersect(RTLIL::Design *design, RTLIL::Selection &lhs, const RTLIL::Selection &rhs) +{ + if (rhs.complete_selection) + return; + + if (rhs.full_selection && !lhs.selects_boxes) + return; + + if (lhs.empty()) + return; + + if (rhs.empty()) { + lhs.clear(); + return; + } + + select_all(design, lhs); + + std::vector del_list; + + for (auto mod_name : lhs.selected_modules) { + if (rhs.selected_whole_module(mod_name)) + continue; + if (rhs.selected_module(mod_name)) + for (auto memb_name : rhs.selected_members.at(mod_name)) + lhs.selected_members[mod_name].insert(memb_name); + del_list.push_back(mod_name); + } + for (auto &it : del_list) + lhs.selected_modules.erase(it); + + del_list.clear(); + for (auto &it : lhs.selected_members) { + if (rhs.selected_whole_module(it.first)) + continue; + if (!rhs.selected_module(it.first)) { + del_list.push_back(it.first); + continue; + } + std::vector del_list2; + for (auto &it2 : it.second) + if (!rhs.selected_member(it.first, it2)) + del_list2.push_back(it2); + for (auto &it2 : del_list2) + it.second.erase(it2); + if (it.second.size() == 0) + del_list.push_back(it.first); + } + for (auto &it : del_list) + lhs.selected_members.erase(it); +} + +namespace { + struct expand_rule_t { + char mode; + std::set cell_types, port_names; + }; +} + +static int parse_comma_list(std::set &tokens, const std::string &str, size_t pos, std::string stopchar) +{ + stopchar += ','; + while (1) { + size_t endpos = str.find_first_of(stopchar, pos); + if (endpos == std::string::npos) + endpos = str.size(); + if (endpos != pos) + tokens.insert(RTLIL::escape_id(str.substr(pos, endpos-pos))); + pos = endpos; + if (pos == str.size() || str[pos] != ',') + return pos; + pos++; + } +} + +static int select_op_expand(RTLIL::Design *design, RTLIL::Selection &lhs, std::vector &rules, std::set &limits, int max_objects, char mode, NewCellTypes &ct, bool eval_only) +{ + int sel_objects = 0; + bool is_input, is_output; + for (auto mod : design->modules()) + { + if (lhs.selected_whole_module(mod->name) || !lhs.selected_module(mod->name)) + continue; + + std::set selected_wires; + auto selected_members = lhs.selected_members[mod->name]; + + for (auto wire : mod->wires()) + if (lhs.selected_member(mod->name, wire->name) && limits.count(wire->name) == 0) + selected_wires.insert(wire); + + for (auto &conn : mod->connections()) + { + std::vector conn_lhs = conn.first.to_sigbit_vector(); + std::vector conn_rhs = conn.second.to_sigbit_vector(); + + for (size_t i = 0; i < conn_lhs.size(); i++) { + if (conn_lhs[i].wire == nullptr || conn_rhs[i].wire == nullptr) + continue; + if (mode != 'i' && selected_wires.count(conn_rhs[i].wire) && selected_members.count(conn_lhs[i].wire->name) == 0) + lhs.selected_members[mod->name].insert(conn_lhs[i].wire->name), sel_objects++, max_objects--; + if (mode != 'o' && selected_wires.count(conn_lhs[i].wire) && selected_members.count(conn_rhs[i].wire->name) == 0) + lhs.selected_members[mod->name].insert(conn_rhs[i].wire->name), sel_objects++, max_objects--; + } + } + + auto &twines = design->twines(); + for (auto cell : mod->cells()) + for (auto &conn : cell->connections()) + { + char last_mode = '-'; + if (eval_only && !yosys_celltypes.cell_evaluable(cell->type)) + goto exclude_match; + for (auto &rule : rules) { + last_mode = rule.mode; + if (rule.cell_types.size() > 0 && rule.cell_types.count(cell->type) == 0) + continue; + if (rule.port_names.size() > 0 && rule.port_names.count(twines.str(conn.first)) == 0) + continue; + if (rule.mode == '+') + goto include_match; + else + goto exclude_match; + } + if (last_mode == '+') + goto exclude_match; + include_match: + is_input = mode == 'x' || ct.cell_input(cell->type, conn.first); + is_output = mode == 'x' || ct.cell_output(cell->type, conn.first); + for (auto &chunk : conn.second.chunks()) + if (chunk.wire != nullptr) { + if (max_objects != 0 && selected_wires.count(chunk.wire) > 0 && selected_members.count(cell->name) == 0) + if (mode == 'x' || (mode == 'i' && is_output) || (mode == 'o' && is_input)) + lhs.selected_members[mod->name].insert(cell->name), sel_objects++, max_objects--; + if (max_objects != 0 && selected_members.count(cell->name) > 0 && limits.count(cell->name) == 0 && selected_members.count(chunk.wire->name) == 0) + if (mode == 'x' || (mode == 'i' && is_input) || (mode == 'o' && is_output)) + lhs.selected_members[mod->name].insert(chunk.wire->name), sel_objects++, max_objects--; + } + exclude_match:; + } + } + + return sel_objects; +} + +static void select_op_expand(RTLIL::Design *design, std::vector &work_stack, const std::string &arg, char mode, bool eval_only) +{ + int pos = (mode == 'x' ? 2 : 3) + (eval_only ? 1 : 0); + int levels = 1, rem_objects = -1; + std::vector rules; + std::set limits; + + NewCellTypes ct; + + if (mode != 'x') + ct.setup(design); + + if (pos < int(arg.size()) && arg[pos] == '*') { + levels = 1'000'000; + pos++; + } else + if (pos < int(arg.size()) && '0' <= arg[pos] && arg[pos] <= '9') { + size_t endpos = arg.find_first_not_of("0123456789", pos); + if (endpos == std::string::npos) + endpos = arg.size(); + levels = atoi(arg.substr(pos, endpos-pos).c_str()); + pos = endpos; + } + + if (pos < int(arg.size()) && arg[pos] == '.') { + size_t endpos = arg.find_first_not_of("0123456789", ++pos); + if (endpos == std::string::npos) + endpos = arg.size(); + if (int(endpos) > pos) + rem_objects = atoi(arg.substr(pos, endpos-pos).c_str()); + pos = endpos; + } + + while (pos < int(arg.size())) { + if (arg[pos] != ':' || pos+1 == int(arg.size())) + log_cmd_error("Syntax error in expand operator '%s'.\n", arg); + pos++; + if (arg[pos] == '+' || arg[pos] == '-') { + expand_rule_t rule; + rule.mode = arg[pos++]; + pos = parse_comma_list(rule.cell_types, arg, pos, "[:"); + if (pos < int(arg.size()) && arg[pos] == '[') { + pos = parse_comma_list(rule.port_names, arg, pos+1, "]:"); + if (pos < int(arg.size()) && arg[pos] == ']') + pos++; + } + rules.push_back(rule); + } else { + size_t endpos = arg.find(':', pos); + if (endpos == std::string::npos) + endpos = arg.size(); + if (int(endpos) > pos) { + std::string str = arg.substr(pos, endpos-pos); + if (str[0] == '@') { + str = RTLIL::escape_id(str.substr(1)); + IdString sel_name = design->twines().find(str); + if (sel_name != IdString::Null && design->selection_vars.count(sel_name) > 0) { + for (auto i1 : design->selection_vars.at(sel_name).selected_members) + for (auto i2 : i1.second) + limits.insert(i2); + } else + log_cmd_error("Selection %s is not defined!\n", RTLIL::unescape_id(str)); + } else + limits.insert(design->twines().add(RTLIL::escape_id(str))); + } + pos = endpos; + } + } + +#if 0 + log("expand by %d levels (max. %d objects):\n", levels, rem_objects); + for (auto &rule : rules) { + log(" rule (%c):\n", rule.mode); + if (rule.cell_types.size() > 0) { + std::string message = " cell types:"; + for (auto &it : rule.cell_types) + message += stringf(" %s", it); + log("%s\n", message); + } + if (rule.port_names.size() > 0) { + std::string message = " port names:"; + for (auto &it : rule.port_names) + message += stringf(" %s", it); + log("%s\n", message); + } + } + if (limits.size() > 0) { + std::string message = " limits:"; + for (auto &it : limits) + message += stringf(" %s", it); + log("%s\n", message); + } +#endif + + while (levels-- > 0 && rem_objects != 0) { + int num_objects = select_op_expand(design, work_stack.back(), rules, limits, rem_objects, mode, ct, eval_only); + if (num_objects == 0) + break; + rem_objects -= num_objects; + } + + if (rem_objects == 0) + log_warning("reached configured limit at `%s'.\n", arg); +} + +static void select_filter_active_mod(RTLIL::Design *design, RTLIL::Selection &sel) +{ + if (design->selected_active_module.empty()) + return; + + if (sel.full_selection) { + sel.clear(); + sel.selected_modules.insert(design->selected_active_module); + return; + } + + std::vector del_list; + for (auto mod_name : sel.selected_modules) + if (mod_name != design->selected_active_module) + del_list.push_back(mod_name); + for (auto &it : sel.selected_members) + if (it.first != design->selected_active_module) + del_list.push_back(it.first); + for (auto mod_name : del_list) { + sel.selected_modules.erase(mod_name); + sel.selected_members.erase(mod_name); + } +} + +static void select_stmt(RTLIL::Design *design, std::vector &work_stack, std::string arg, bool disable_empty_warning = false) +{ + std::string arg_mod, arg_memb; + std::unordered_map arg_mod_found; + std::unordered_map arg_memb_found; + + auto isprefixed = [](const string &s) { + return GetSize(s) >= 2 && ((s[0] >= 'a' && s[0] <= 'z') || (s[0] >= 'A' && s[0] <= 'Z')) && s[1] == ':'; + }; + + if (arg.size() == 0) + return; + + if (arg[0] == '%') { + if (arg == "%") { + work_stack.push_back(design->selection()); + } else + if (arg == "%%") { + select_op_union_all(design, work_stack); + } else + if (arg == "%n") { + if (work_stack.size() < 1) + log_cmd_error("Must have at least one element on the stack for operator %%n.\n"); + select_op_neg(design, work_stack[work_stack.size()-1]); + } else + if (arg == "%u") { + if (work_stack.size() < 2) + log_cmd_error("Must have at least two elements on the stack for operator %%u.\n"); + select_op_union(design, work_stack[work_stack.size()-2], work_stack[work_stack.size()-1]); + work_stack.pop_back(); + } else + if (arg == "%d") { + if (work_stack.size() < 2) + log_cmd_error("Must have at least two elements on the stack for operator %%d.\n"); + select_op_diff(design, work_stack[work_stack.size()-2], work_stack[work_stack.size()-1]); + work_stack.pop_back(); + } else + if (arg == "%D") { + if (work_stack.size() < 2) + log_cmd_error("Must have at least two elements on the stack for operator %%D.\n"); + select_op_diff(design, work_stack[work_stack.size()-1], work_stack[work_stack.size()-2]); + work_stack[work_stack.size()-2] = work_stack[work_stack.size()-1]; + work_stack.pop_back(); + } else + if (arg == "%i") { + if (work_stack.size() < 2) + log_cmd_error("Must have at least two elements on the stack for operator %%i.\n"); + select_op_intersect(design, work_stack[work_stack.size()-2], work_stack[work_stack.size()-1]); + work_stack.pop_back(); + } else + if (arg.size() >= 2 && arg[0] == '%' && arg[1] == 'R') { + if (work_stack.size() < 1) + log_cmd_error("Must have at least one element on the stack for operator %%R.\n"); + int count = arg.size() > 2 ? atoi(arg.c_str() + 2) : 1; + select_op_random(design, work_stack[work_stack.size()-1], count); + } else + if (arg == "%s") { + if (work_stack.size() < 1) + log_cmd_error("Must have at least one element on the stack for operator %%s.\n"); + select_op_submod(design, work_stack[work_stack.size()-1]); + } else + if (arg == "%M") { + if (work_stack.size() < 1) + log_cmd_error("Must have at least one element on the stack for operator %%M.\n"); + select_op_cells_to_modules(design, work_stack[work_stack.size()-1]); + } else + if (arg == "%C") { + if (work_stack.size() < 1) + log_cmd_error("Must have at least one element on the stack for operator %%C.\n"); + select_op_module_to_cells(design, work_stack[work_stack.size()-1]); + } else + if (arg == "%c") { + if (work_stack.size() < 1) + log_cmd_error("Must have at least one element on the stack for operator %%c.\n"); + work_stack.push_back(work_stack.back()); + } else + if (arg == "%m") { + if (work_stack.size() < 1) + log_cmd_error("Must have at least one element on the stack for operator %%m.\n"); + select_op_fullmod(design, work_stack[work_stack.size()-1]); + } else + if (arg == "%a") { + if (work_stack.size() < 1) + log_cmd_error("Must have at least one element on the stack for operator %%a.\n"); + select_op_alias(design, work_stack[work_stack.size()-1]); + } else + if (arg == "%x" || (arg.size() > 2 && arg.compare(0, 2, "%x") == 0 && (arg[2] == ':' || arg[2] == '*' || arg[2] == '.' || ('0' <= arg[2] && arg[2] <= '9')))) { + if (work_stack.size() < 1) + log_cmd_error("Must have at least one element on the stack for operator %%x.\n"); + select_op_expand(design, work_stack, arg, 'x', false); + } else + if (arg == "%ci" || (arg.size() > 3 && arg.compare(0, 3, "%ci") == 0 && (arg[3] == ':' || arg[3] == '*' || arg[3] == '.' || ('0' <= arg[3] && arg[3] <= '9')))) { + if (work_stack.size() < 1) + log_cmd_error("Must have at least one element on the stack for operator %%ci.\n"); + select_op_expand(design, work_stack, arg, 'i', false); + } else + if (arg == "%co" || (arg.size() > 3 && arg.compare(0, 3, "%co") == 0 && (arg[3] == ':' || arg[3] == '*' || arg[3] == '.' || ('0' <= arg[3] && arg[3] <= '9')))) { + if (work_stack.size() < 1) + log_cmd_error("Must have at least one element on the stack for operator %%co.\n"); + select_op_expand(design, work_stack, arg, 'o', false); + } else + if (arg == "%xe" || (arg.size() > 3 && arg.compare(0, 3, "%xe") == 0 && (arg[3] == ':' || arg[3] == '*' || arg[3] == '.' || ('0' <= arg[3] && arg[3] <= '9')))) { + if (work_stack.size() < 1) + log_cmd_error("Must have at least one element on the stack for operator %%xe.\n"); + select_op_expand(design, work_stack, arg, 'x', true); + } else + if (arg == "%cie" || (arg.size() > 4 && arg.compare(0, 4, "%cie") == 0 && (arg[4] == ':' || arg[4] == '*' || arg[4] == '.' || ('0' <= arg[4] && arg[4] <= '9')))) { + if (work_stack.size() < 1) + log_cmd_error("Must have at least one element on the stack for operator %%cie.\n"); + select_op_expand(design, work_stack, arg, 'i', true); + } else + if (arg == "%coe" || (arg.size() > 4 && arg.compare(0, 4, "%coe") == 0 && (arg[4] == ':' || arg[4] == '*' || arg[4] == '.' || ('0' <= arg[4] && arg[4] <= '9')))) { + if (work_stack.size() < 1) + log_cmd_error("Must have at least one element on the stack for operator %%coe.\n"); + select_op_expand(design, work_stack, arg, 'o', true); + } else + log_cmd_error("Unknown selection operator '%s'.\n", arg); + if (work_stack.size() >= 1) + select_filter_active_mod(design, work_stack.back()); + return; + } + + if (arg[0] == '@') { + std::string set_name = RTLIL::escape_id(arg.substr(1)); + IdString set_twine = design->twines().find(set_name); + if (set_twine != IdString::Null && design->selection_vars.count(set_twine) > 0) + work_stack.push_back(design->selection_vars[set_twine]); + else + log_cmd_error("Selection @%s is not defined!\n", RTLIL::unescape_id(set_name)); + select_filter_active_mod(design, work_stack.back()); + return; + } + + bool select_blackboxes = false; + if (arg.substr(0, 1) == "=") { + arg = arg.substr(1); + select_blackboxes = true; + } + + if (!design->selected_active_module.empty()) { + arg_mod = design->twines().str(design->selected_active_module); + arg_memb = arg; + if (!isprefixed(arg_memb)) + arg_memb_found[arg_memb] = false; + } else + if (isprefixed(arg) && arg[0] >= 'a' && arg[0] <= 'z') { + arg_mod = "*", arg_memb = arg; + } else { + size_t pos = arg.find('/'); + if (pos == std::string::npos) { + arg_mod = arg; + if (!isprefixed(arg_mod)) + arg_mod_found[arg_mod] = false; + } else { + arg_mod = arg.substr(0, pos); + if (!isprefixed(arg_mod)) + arg_mod_found[arg_mod] = false; + arg_memb = arg.substr(pos+1); + if (!isprefixed(arg_memb)) + arg_memb_found[arg_memb] = false; + } + } + + bool full_selection = (arg == "*" && arg_mod == "*"); + work_stack.push_back(RTLIL::Selection(full_selection, select_blackboxes, design)); + RTLIL::Selection &sel = work_stack.back(); + + if (sel.full_selection) { + if (sel.selects_boxes) sel.optimize(design); + select_filter_active_mod(design, work_stack.back()); + return; + } + + for (auto mod : design->modules()) + { + if (!select_blackboxes && mod->get_blackbox_attribute()) + continue; + + if (arg_mod.compare(0, 2, "A:") == 0) { + if (!match_attr(design->twines(), mod->attributes, arg_mod.substr(2))) + continue; + } else + if (arg_mod.compare(0, 2, "N:") == 0) { + if (!match_ids(mod->name, arg_mod.substr(2))) + continue; + } else + if (!match_ids(mod->name, arg_mod)) + continue; + else + arg_mod_found[arg_mod] = true; + + if (arg_memb == "") { + sel.selected_modules.insert(mod->name); + continue; + } + + if (arg_memb.compare(0, 2, "w:") == 0) { + for (auto wire : mod->wires()) + if (match_ids(wire->name, arg_memb.substr(2))) + sel.selected_members[mod->name].insert(wire->name); + } else + if (arg_memb.compare(0, 2, "i:") == 0) { + for (auto wire : mod->wires()) + if (wire->port_input && match_ids(wire->name, arg_memb.substr(2))) + sel.selected_members[mod->name].insert(wire->name); + } else + if (arg_memb.compare(0, 2, "o:") == 0) { + for (auto wire : mod->wires()) + if (wire->port_output && match_ids(wire->name, arg_memb.substr(2))) + sel.selected_members[mod->name].insert(wire->name); + } else + if (arg_memb.compare(0, 2, "x:") == 0) { + for (auto wire : mod->wires()) + if ((wire->port_input || wire->port_output) && match_ids(wire->name, arg_memb.substr(2))) + sel.selected_members[mod->name].insert(wire->name); + } else + if (arg_memb.compare(0, 2, "s:") == 0) { + size_t delim = arg_memb.substr(2).find(':'); + if (delim == std::string::npos) { + int width = atoi(arg_memb.substr(2).c_str()); + for (auto wire : mod->wires()) + if (wire->width == width) + sel.selected_members[mod->name].insert(wire->name); + } else { + std::string min_str = arg_memb.substr(2, delim); + std::string max_str = arg_memb.substr(2+delim+1); + int min_width = min_str.empty() ? 0 : atoi(min_str.c_str()); + int max_width = max_str.empty() ? -1 : atoi(max_str.c_str()); + for (auto wire : mod->wires()) + if (min_width <= wire->width && (wire->width <= max_width || max_width == -1)) + sel.selected_members[mod->name].insert(wire->name); + } + } else + if (arg_memb.compare(0, 2, "m:") == 0) { + for (auto &it : mod->memories) + if (match_ids(design->twines().str(it.first), arg_memb.substr(2))) + sel.selected_members[mod->name].insert(it.first); + } else + if (arg_memb.compare(0, 2, "c:") == 0) { + for (auto cell : mod->cells()) + if (match_ids(cell->name, arg_memb.substr(2))) + sel.selected_members[mod->name].insert(cell->name); + } else + if (arg_memb.compare(0, 2, "t:") == 0) { + if (arg_memb.compare(2, 1, "@") == 0) { + std::string set_name = RTLIL::escape_id(arg_memb.substr(3)); + IdString set_twine = design->twines().find(set_name); + if (set_twine == IdString::Null || !design->selection_vars.count(set_twine)) + log_cmd_error("Selection @%s is not defined!\n", RTLIL::unescape_id(set_name)); + + auto &muster = design->selection_vars[set_twine]; + for (auto cell : mod->cells()) + if (muster.selected_modules.count(cell->type)) + sel.selected_members[mod->name].insert(cell->name); + } else { + for (auto cell : mod->cells()) + if (match_ids(cell->type, arg_memb.substr(2))) + sel.selected_members[mod->name].insert(cell->name); + } + } else + if (arg_memb.compare(0, 2, "p:") == 0) { + for (auto &it : mod->processes) + if (match_ids(design->twines().str(it.first), arg_memb.substr(2))) + sel.selected_members[mod->name].insert(it.first); + } else + if (arg_memb.compare(0, 2, "a:") == 0) { + for (auto wire : mod->wires()) + if (match_attr(design->twines(), wire->attributes, arg_memb.substr(2))) + sel.selected_members[mod->name].insert(wire->name); + for (auto &it : mod->memories) + if (match_attr(design->twines(), it.second->attributes, arg_memb.substr(2))) + sel.selected_members[mod->name].insert(it.first); + for (auto cell : mod->cells()) + if (match_attr(design->twines(), cell->attributes, arg_memb.substr(2))) + sel.selected_members[mod->name].insert(cell->name); + for (auto &it : mod->processes) + if (match_attr(design->twines(), it.second->attributes, arg_memb.substr(2))) + sel.selected_members[mod->name].insert(it.first); + } else + if (arg_memb.compare(0, 2, "r:") == 0) { + for (auto cell : mod->cells()) + if (match_attr(design->twines(), cell->parameters, arg_memb.substr(2))) + sel.selected_members[mod->name].insert(cell->name); + } else { + std::string orig_arg_memb = arg_memb; + if (arg_memb.compare(0, 2, "n:") == 0) + arg_memb = arg_memb.substr(2); + for (auto wire : mod->wires()) + if (match_ids(wire->name, arg_memb)) { + sel.selected_members[mod->name].insert(wire->name); + arg_memb_found[orig_arg_memb] = true; + } + for (auto &it : mod->memories) + if (match_ids(design->twines().str(it.first), arg_memb)) { + sel.selected_members[mod->name].insert(it.first); + arg_memb_found[orig_arg_memb] = true; + } + for (auto cell : mod->cells()) + if (match_ids(cell->name, arg_memb)) { + sel.selected_members[mod->name].insert(cell->name); + arg_memb_found[orig_arg_memb] = true; + } + for (auto &it : mod->processes) + if (match_ids(design->twines().str(it.first), arg_memb)) { + sel.selected_members[mod->name].insert(it.first); + arg_memb_found[orig_arg_memb] = true; + } + } + } + + select_filter_active_mod(design, work_stack.back()); + + for (auto &it : arg_mod_found) { + if (it.second == false && !disable_empty_warning) { + std::string selection_str = select_blackboxes ? "=" : ""; + selection_str += it.first; + log_warning("Selection \"%s\" did not match any module.\n", selection_str); + } + } + for (auto &it : arg_memb_found) { + if (it.second == false && !disable_empty_warning) { + std::string selection_str = select_blackboxes ? "=" : ""; + selection_str += it.first; + log_warning("Selection \"%s\" did not match any object.\n", selection_str); + } + } +} + +static std::string describe_selection_for_assert(RTLIL::Design *design, RTLIL::Selection *sel, bool whole_modules = false) +{ + bool push_selection = &design->selection() != sel; + if (push_selection) design->push_selection(*sel); + std::string desc = "Selection contains:\n"; + for (auto mod : design->all_selected_modules()) + { + if (whole_modules && sel->selected_whole_module(mod->name)) + desc += stringf("%s\n", mod); + for (auto it : mod->selected_members()) + desc += stringf("%s/%s\n", mod, it.name.str()); + } + if (push_selection) design->pop_selection(); + return desc; +} + +PRIVATE_NAMESPACE_END +YOSYS_NAMESPACE_BEGIN + +// used in kernel/register.cc and maybe other locations, extern decl. in register.h +void handle_extra_select_args(Pass *pass, const vector &args, size_t argidx, size_t args_size, RTLIL::Design *design) +{ + std::vector work_stack; + for (; argidx < args_size; argidx++) { + if (args[argidx].compare(0, 1, "-") == 0) { + if (pass != nullptr) + pass->cmd_error(args, argidx, "Unexpected option in selection arguments."); + else + log_cmd_error("Unexpected option in selection arguments.\n"); + } + select_stmt(design, work_stack, args[argidx]); + } + select_op_union_all(design, work_stack); + if (work_stack.empty()) + design->push_empty_selection(); + else + design->push_selection(work_stack.back()); +} + +// extern decl. in register.h +RTLIL::Selection eval_select_args(const vector &args, RTLIL::Design *design) +{ + std::vector work_stack; + for (auto &arg : args) + select_stmt(design, work_stack, arg); + select_op_union_all(design, work_stack); + if (work_stack.empty()) + return RTLIL::Selection::EmptySelection(design); + return work_stack.back(); +} + +// extern decl. in register.h +void eval_select_op(vector &work, const string &op, RTLIL::Design *design) +{ + select_stmt(design, work, op); +} + +YOSYS_NAMESPACE_END +PRIVATE_NAMESPACE_BEGIN + +struct SelectPass : public Pass { + SelectPass() : Pass("select", "modify and view the list of selected objects") { } + bool formatted_help() override { + auto *help = PrettyHelp::get_current(); + help->set_group("passes/status"); + return false; + } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" select [ -add | -del | -set ] {-read | }\n"); + log(" select [ -unset ]\n"); + log(" select [ ] {-read | }\n"); + log(" select [ -list | -list-mod | -write | -count | -clear ]\n"); + log(" select -module \n"); + log("\n"); + log("Most commands use the list of currently selected objects to determine which part\n"); + log("of the design to operate on. This command can be used to modify and view this\n"); + log("list of selected objects.\n"); + log("\n"); + log("Note that many commands support an optional [selection] argument that can be\n"); + log("used to override the global selection for the command. The syntax of this\n"); + log("optional argument is identical to the syntax of the argument\n"); + log("described here.\n"); + log("\n"); + log(" -add, -del\n"); + log(" add or remove the given objects to the current selection.\n"); + log(" without this options the current selection is replaced.\n"); + log("\n"); + log(" -set \n"); + log(" do not modify the current selection. instead save the new selection\n"); + log(" under the given name (see @ below). to save the current selection,\n"); + log(" use \"select -set %%\"\n"); + log("\n"); + log(" -unset \n"); + log(" do not modify the current selection. instead remove a previously saved\n"); + log(" selection under the given name (see @ below).\n"); + log("\n"); + log(" -assert-none\n"); + log(" do not modify the current selection. instead assert that the given\n"); + log(" selection is empty. i.e. produce an error if any object or module\n"); + log(" matching the selection is found.\n"); + log("\n"); + log(" -assert-any\n"); + log(" do not modify the current selection. instead assert that the given\n"); + log(" selection is non-empty. i.e. produce an error if no object or module\n"); + log(" matching the selection is found.\n"); + log("\n"); + log(" -assert-mod-count N\n"); + log(" do not modify the current selection. instead assert that the given\n"); + log(" selection contains exactly N modules (partially or fully selected).\n"); + log("\n"); + log(" -assert-count N\n"); + log(" do not modify the current selection. instead assert that the given\n"); + log(" selection contains exactly N objects.\n"); + log("\n"); + log(" -assert-max N\n"); + log(" do not modify the current selection. instead assert that the given\n"); + log(" selection contains less than or exactly N objects.\n"); + log("\n"); + log(" -assert-min N\n"); + log(" do not modify the current selection. instead assert that the given\n"); + log(" selection contains at least N objects.\n"); + log("\n"); + log(" -list\n"); + log(" list all objects in the current selection\n"); + log("\n"); + log(" -write \n"); + log(" like -list but write the output to the specified file\n"); + log("\n"); + log(" -read \n"); + log(" read the specified file (written by -write)\n"); + log("\n"); + log(" -count\n"); + log(" count all objects in the current selection\n"); + log("\n"); + log(" -clear\n"); + log(" clear the current selection. this effectively selects the whole\n"); + log(" design. it also resets the selected module (see -module). use the\n"); + log(" command 'select *' to select everything but stay in the current module.\n"); + log("\n"); + log(" -none\n"); + log(" create an empty selection. the current module is unchanged.\n"); + log("\n"); + log(" -module \n"); + log(" limit the current scope to the specified module.\n"); + log(" the difference between this and simply selecting the module\n"); + log(" is that all object names are interpreted relative to this\n"); + log(" module after this command until the selection is cleared again.\n"); + log("\n"); + log("When this command is called without an argument, the current selection\n"); + log("is displayed in a compact form (i.e. only the module name when a whole module\n"); + log("is selected).\n"); + log("\n"); + log("The argument itself is a series of commands for a simple stack\n"); + log("machine. Each element on the stack represents a set of selected objects.\n"); + log("After this commands have been executed, the union of all remaining sets\n"); + log("on the stack is computed and used as selection for the command.\n"); + log("\n"); + log("Pushing (selecting) object when not in -module mode:\n"); + log("\n"); + log(" \n"); + log(" select the specified module(s)\n"); + log("\n"); + log(" /\n"); + log(" select the specified object(s) from the module(s)\n"); + log("\n"); + log("Pushing (selecting) object when in -module mode:\n"); + log("\n"); + log(" \n"); + log(" select the specified object(s) from the current module\n"); + log("\n"); + log("By default, patterns will not match black/white-box modules or their\n"); + log("contents. To include such objects, prefix the pattern with '='.\n"); + log("\n"); + log("A can be a module name, wildcard expression (*, ?, [..])\n"); + log("matching module names, or one of the following:\n"); + log("\n"); + log(" A:, A:=\n"); + log(" all modules with an attribute matching the given pattern\n"); + log(" in addition to = also <, <=, >=, and > are supported\n"); + log("\n"); + log(" N:\n"); + log(" all modules with a name matching the given pattern\n"); + log(" (i.e. 'N:' is optional as it is the default matching rule)\n"); + log("\n"); + log("An can be an object name, wildcard expression, or one of\n"); + log("the following:\n"); + log("\n"); + log(" w:\n"); + log(" all wires with a name matching the given wildcard pattern\n"); + log("\n"); + log(" i:, o:, x:\n"); + log(" all inputs (i:), outputs (o:) or any ports (x:) with matching names\n"); + log("\n"); + log(" s:, s::\n"); + log(" all wires with a matching width\n"); + log("\n"); + log(" m:\n"); + log(" all memories with a name matching the given pattern\n"); + log("\n"); + log(" c:\n"); + log(" all cells with a name matching the given pattern\n"); + log("\n"); + log(" t:\n"); + log(" all cells with a type matching the given pattern\n"); + log("\n"); + log(" t:@\n"); + log(" all cells with a type matching a module in the saved selection \n"); + log("\n"); + log(" p:\n"); + log(" all processes with a name matching the given pattern\n"); + log("\n"); + log(" a:\n"); + log(" all objects with an attribute name matching the given pattern\n"); + log("\n"); + log(" a:=\n"); + log(" all objects with a matching attribute name-value-pair.\n"); + log(" in addition to = also <, <=, >=, and > are supported\n"); + log("\n"); + log(" r:, r:=\n"); + log(" cells with matching parameters. also with <, <=, >= and >.\n"); + log("\n"); + log(" n:\n"); + log(" all objects with a name matching the given pattern\n"); + log(" (i.e. 'n:' is optional as it is the default matching rule)\n"); + log("\n"); + log(" @\n"); + log(" push the selection saved prior with 'select -set ...'\n"); + log("\n"); + log("The following actions can be performed on the top sets on the stack:\n"); + log("\n"); + log(" %%\n"); + log(" push a copy of the current selection to the stack\n"); + log("\n"); + log(" %%%%\n"); + log(" replace the stack with a union of all elements on it\n"); + log("\n"); + log(" %%n\n"); + log(" replace top set with its invert\n"); + log("\n"); + log(" %%u\n"); + log(" replace the two top sets on the stack with their union\n"); + log("\n"); + log(" %%i\n"); + log(" replace the two top sets on the stack with their intersection\n"); + log("\n"); + log(" %%d\n"); + log(" pop the top set from the stack and subtract it from the new top\n"); + log("\n"); + log(" %%D\n"); + log(" like %%d but swap the roles of two top sets on the stack\n"); + log("\n"); + log(" %%c\n"); + log(" create a copy of the top set from the stack and push it\n"); + log("\n"); + log(" %%x[|*][.][:[:..]]\n"); + log(" expand top set num times according to the specified rules.\n"); + log(" (i.e. select all cells connected to selected wires and select all\n"); + log(" wires connected to selected cells) The rules specify which cell\n"); + log(" ports to use for this. the syntax for a rule is a '-' for exclusion\n"); + log(" and a '+' for inclusion, followed by an optional comma separated\n"); + log(" list of cell types followed by an optional comma separated list of\n"); + log(" cell ports in square brackets. a rule can also be just a cell or wire\n"); + log(" name that limits the expansion (is included but does not go beyond).\n"); + log(" select at most objects. a warning message is printed when this\n"); + log(" limit is reached. When '*' is used instead of then the process\n"); + log(" is repeated until no further object are selected.\n"); + log("\n"); + log(" %%ci[|*][.][:[:..]]\n"); + log(" %%co[|*][.][:[:..]]\n"); + log(" similar to %%x, but only select input (%%ci) or output cones (%%co)\n"); + log("\n"); + log(" %%xe[...] %%cie[...] %%coe\n"); + log(" like %%x, %%ci, and %%co but only consider combinatorial cells\n"); + log("\n"); + log(" %%a\n"); + log(" expand top set by selecting all wires that are (at least in part)\n"); + log(" aliases for selected wires.\n"); + log("\n"); + log(" %%s\n"); + log(" expand top set by adding all modules that implement cells in selected\n"); + log(" modules\n"); + log("\n"); + log(" %%m\n"); + log(" expand top set by selecting all modules that contain selected objects\n"); + log("\n"); + log(" %%M\n"); + log(" select modules that implement selected cells\n"); + log("\n"); + log(" %%C\n"); + log(" select cells that implement selected modules\n"); + log("\n"); + log(" %%R[]\n"); + log(" select random objects from top selection (default 1)\n"); + log("\n"); + log("Example: the following command selects all wires that are connected to a\n"); + log("'GATE' input of a 'SWITCH' cell:\n"); + log("\n"); + log(" select */t:SWITCH %%x:+[GATE] */t:SWITCH %%d\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + bool add_mode = false; + bool del_mode = false; + bool clear_mode = false; + bool none_mode = false; + bool list_mode = false; + bool list_mod_mode = false; + bool count_mode = false; + bool got_module = false; + bool assert_none = false; + bool assert_any = false; + int assert_modcount = -1; + int assert_count = -1; + int assert_max = -1; + int assert_min = -1; + std::string write_file, read_file; + std::string set_name, unset_name, sel_str; + + std::vector work_stack; + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) + { + std::string arg = args[argidx]; + if (arg == "-add") { + add_mode = true; + continue; + } + if (arg == "-del") { + del_mode = true; + continue; + } + if (arg == "-assert-none") { + assert_none = true; + continue; + } + if (arg == "-assert-any") { + assert_any = true; + continue; + } + if (arg == "-assert-mod-count" && argidx+1 < args.size()) { + assert_modcount = atoi(args[++argidx].c_str()); + continue; + } + if (arg == "-assert-count" && argidx+1 < args.size()) { + assert_count = atoi(args[++argidx].c_str()); + continue; + } + if (arg == "-assert-max" && argidx+1 < args.size()) { + assert_max = atoi(args[++argidx].c_str()); + continue; + } + if (arg == "-assert-min" && argidx+1 < args.size()) { + assert_min = atoi(args[++argidx].c_str()); + continue; + } + if (arg == "-clear") { + clear_mode = true; + continue; + } + if (arg == "-none") { + none_mode = true; + continue; + } + if (arg == "-list") { + list_mode = true; + continue; + } + if (arg == "-list-mod") { + list_mode = true; + list_mod_mode = true; + continue; + } + if (arg == "-write" && argidx+1 < args.size()) { + write_file = args[++argidx]; + continue; + } + if (arg == "-read" && argidx+1 < args.size()) { + read_file = args[++argidx]; + continue; + } + if (arg == "-count") { + count_mode = true; + continue; + } + if (arg == "-module" && argidx+1 < args.size()) { + std::string mod_name = RTLIL::escape_id(args[++argidx]); + IdString t = design->twines().find(mod_name); + if (t == IdString::Null || design->module(t) == nullptr) + log_cmd_error("No such module: %s\n", RTLIL::unescape_id(mod_name)); + design->selected_active_module = t; + got_module = true; + continue; + } + if (arg == "-set" && argidx+1 < args.size()) { + set_name = RTLIL::escape_id(args[++argidx]); + continue; + } + if (arg == "-unset" && argidx+1 < args.size()) { + unset_name = RTLIL::escape_id(args[++argidx]); + continue; + } + if (arg.size() > 0 && arg[0] == '-') + log_cmd_error("Unknown option %s.\n", arg); + bool disable_empty_warning = count_mode || assert_none || assert_any || (assert_modcount != -1) || + (assert_count != -1) || (assert_max != -1) || (assert_min != -1); + select_stmt(design, work_stack, arg, disable_empty_warning); + sel_str += " " + arg; + } + + if (!read_file.empty()) + { + if (!sel_str.empty()) + log_cmd_error("Option -read can not be combined with a selection expression.\n"); + + std::ifstream f(read_file); + yosys_input_files.insert(read_file); + if (f.fail()) + log_error("Can't open '%s' for reading: %s\n", read_file, strerror(errno)); + + auto sel = RTLIL::Selection::EmptySelection(design); + string line; + + while (std::getline(f, line)) { + size_t slash_pos = line.find('/'); + if (slash_pos == string::npos) { + log_warning("Ignoring line without slash in 'select -read': %s\n", line); + continue; + } + std::string mod_name = RTLIL::escape_id(line.substr(0, slash_pos)); + std::string obj_name = RTLIL::escape_id(line.substr(slash_pos+1)); + IdString mod_ref = design->twines().find(mod_name); + IdString obj_ref = design->twines().find(obj_name); + if (mod_ref == IdString::Null || obj_ref == IdString::Null) + continue; + sel.selected_members[mod_ref].insert(obj_ref); + } + + select_filter_active_mod(design, sel); + sel.optimize(design); + work_stack.push_back(sel); + } + + if (clear_mode && args.size() != 2) + log_cmd_error("Option -clear can not be combined with any other options.\n"); + + if (none_mode && args.size() != 2) + log_cmd_error("Option -none can not be combined with any other options.\n"); + + int common_flagset_tally = add_mode + del_mode + assert_none + assert_any + (assert_modcount >= 0) + (assert_count >= 0) + (assert_max >= 0) + (assert_min >= 0); + const char *common_flagset = "-add, -del, -assert-none, -assert-any, -assert-mod-count, -assert-count, -assert-max, or -assert-min"; + + if (common_flagset_tally > 1) + log_cmd_error("Options %s can not be combined.\n", common_flagset); + + if ((list_mode || !write_file.empty() || count_mode) && common_flagset_tally) + log_cmd_error("Options -list, -list-mod, -write and -count can not be combined with %s.\n", common_flagset); + + if (!set_name.empty() && (list_mode || !write_file.empty() || count_mode || !unset_name.empty() || common_flagset_tally)) + log_cmd_error("Option -set can not be combined with -list, -write, -count, -unset, %s.\n", common_flagset); + + if (!unset_name.empty() && (list_mode || !write_file.empty() || count_mode || !set_name.empty() || common_flagset_tally)) + log_cmd_error("Option -unset can not be combined with -list, -write, -count, -set, %s.\n", common_flagset); + + if (work_stack.size() == 0 && got_module) { + auto sel = RTLIL::Selection::FullSelection(design); + select_filter_active_mod(design, sel); + work_stack.push_back(sel); + } + + select_op_union_all(design, work_stack); + + log_assert(!design->selection_stack.empty()); + + if (clear_mode) { + design->selection() = RTLIL::Selection::FullSelection(design); + design->selected_active_module.clear(); + return; + } + + if (none_mode) { + design->selection() = RTLIL::Selection::EmptySelection(design); + return; + } + + if (list_mode || count_mode || !write_file.empty()) + { + #define LOG_OBJECT(...) { if (list_mode) log(__VA_ARGS__); if (f != nullptr) fprintf(f, __VA_ARGS__); total_count++; } + int total_count = 0; + FILE *f = nullptr; + if (!write_file.empty()) { + f = fopen(write_file.c_str(), "w"); + yosys_output_files.insert(write_file); + if (f == nullptr) + log_error("Can't open '%s' for writing: %s\n", write_file, strerror(errno)); + } + if (work_stack.size() > 0) + design->push_selection(work_stack.back()); + RTLIL::Selection *sel = &design->selection(); + sel->optimize(design); + for (auto mod : design->all_selected_modules()) + { + if (sel->selected_whole_module(mod->name) && list_mode) + log("%s\n", mod); + if (!list_mod_mode) + for (auto it : mod->selected_members()) + LOG_OBJECT("%s/%s\n", mod->name.unescape().c_str(), it.name.unescape().c_str()) + } + if (count_mode) + { + design->scratchpad_set_int("select.count", total_count); + log("%d objects.\n", total_count); + } + if (f != nullptr) + fclose(f); + if (work_stack.size() > 0) + design->pop_selection(); + #undef LOG_OBJECT + return; + } + + if (add_mode) + { + if (work_stack.size() == 0) + log_cmd_error("Nothing to add to selection.\n"); + select_op_union(design, design->selection(), work_stack.back()); + design->selection().optimize(design); + return; + } + + if (del_mode) + { + if (work_stack.size() == 0) + log_cmd_error("Nothing to delete from selection.\n"); + select_op_diff(design, design->selection(), work_stack.back()); + design->selection().optimize(design); + return; + } + + if (assert_none) + { + if (work_stack.size() == 0) + log_cmd_error("No selection to check.\n"); + work_stack.back().optimize(design); + if (!work_stack.back().empty()) + { + RTLIL::Selection *sel = &work_stack.back(); + sel->optimize(design); + std::string desc = describe_selection_for_assert(design, sel, true); + log_error("Assertion failed: selection is not empty:%s\n%s", sel_str, desc); + } + return; + } + + if (assert_any) + { + if (work_stack.size() == 0) + log_cmd_error("No selection to check.\n"); + work_stack.back().optimize(design); + if (work_stack.back().empty()) + { + RTLIL::Selection *sel = &work_stack.back(); + sel->optimize(design); + std::string desc = describe_selection_for_assert(design, sel, true); + log_error("Assertion failed: selection is empty:%s\n%s", sel_str, desc); + } + return; + } + + if (assert_modcount >= 0 || assert_count >= 0 || assert_max >= 0 || assert_min >= 0) + { + int module_count = 0, total_count = 0; + if (work_stack.size() == 0) + log_cmd_error("No selection to check.\n"); + RTLIL::Selection *sel = &work_stack.back(); + design->push_selection(*sel); + sel->optimize(design); + for (auto mod : design->all_selected_modules()) { + module_count++; + for ([[maybe_unused]] auto member_name : mod->selected_members()) + total_count++; + } + if (assert_modcount >= 0 && assert_modcount != module_count) + { + log_error("Assertion failed: selection contains %d modules instead of the asserted %d:%s\n", + module_count, assert_modcount, sel_str); + } + if (assert_count >= 0 && assert_count != total_count) + { + std::string desc = describe_selection_for_assert(design, sel); + log_error("Assertion failed: selection contains %d elements instead of the asserted %d:%s\n%s", + total_count, assert_count, sel_str, desc); + } + if (assert_max >= 0 && assert_max < total_count) + { + std::string desc = describe_selection_for_assert(design, sel); + log_error("Assertion failed: selection contains %d elements, more than the maximum number %d:%s\n%s", + total_count, assert_max, sel_str, desc); + } + if (assert_min >= 0 && assert_min > total_count) + { + std::string desc = describe_selection_for_assert(design, sel); + log_error("Assertion failed: selection contains %d elements, less than the minimum number %d:%s\n%s", + total_count, assert_min, sel_str, desc); + } + design->pop_selection(); + return; + } + + if (!set_name.empty()) + { + IdString set_twine = design->twines().add(set_name); + if (work_stack.size() == 0) + design->selection_vars[set_twine] = RTLIL::Selection::EmptySelection(design); + else + design->selection_vars[set_twine] = work_stack.back(); + return; + } + + if (!unset_name.empty()) + { + IdString unset_twine = design->twines().find(unset_name); + if (unset_twine == IdString::Null || !design->selection_vars.erase(unset_twine)) + log_error("Selection '%s' does not exist!\n", unset_name); + return; + } + + if (work_stack.size() == 0) { + RTLIL::Selection &sel = design->selection(); + if (sel.full_selection) + log("*\n"); + for (auto &it : sel.selected_modules) + log("%s\n", PooledName(design, it).unescape()); + for (auto &it : sel.selected_members) + for (auto &it2 : it.second) + log("%s/%s\n", PooledName(design, it.first).unescape(), PooledName(design, it2).unescape()); + return; + } + + design->selection() = work_stack.back(); + design->selection().optimize(design); + } +} SelectPass; + +struct CdPass : public Pass { + CdPass() : Pass("cd", "a shortcut for 'select -module '") { } + bool formatted_help() override { + auto *help = PrettyHelp::get_current(); + help->set_group("passes/status"); + return false; + } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" cd \n"); + log("\n"); + log("This is just a shortcut for 'select -module '.\n"); + log("\n"); + log("\n"); + log(" cd \n"); + log("\n"); + log("When no module with the specified name is found, but there is a cell\n"); + log("with the specified name in the current module, then this is equivalent\n"); + log("to 'cd '.\n"); + log("\n"); + log("\n"); + log(" cd ..\n"); + log("\n"); + log("Remove trailing substrings that start with '.' in current module name until\n"); + log("the name of a module in the current design is generated, then switch to that\n"); + log("module. Otherwise clear the current selection.\n"); + log("\n"); + log("\n"); + log(" cd\n"); + log("\n"); + log("This is just a shortcut for 'select -clear'.\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + if (args.size() != 1 && args.size() != 2) + log_cmd_error("Invalid number of arguments.\n"); + + if (args.size() == 1 || args[1] == "/") { + design->pop_selection(); + design->push_full_selection(); + design->selected_active_module.clear(); + return; + } + + if (args[1] == "..") + { + string modname = design->twines().str(design->selected_active_module); + + design->pop_selection(); + design->push_full_selection(); + design->selected_active_module.clear(); + + while (1) + { + size_t pos = modname.rfind('.'); + + if (pos == string::npos) + break; + + modname = modname.substr(0, pos); + IdString mod_ref = design->twines().find(modname); + Module *mod = design->module(mod_ref); + + if (mod == nullptr) + continue; + + design->selected_active_module = mod_ref; + design->pop_selection(); + design->push_full_selection(); + select_filter_active_mod(design, design->selection()); + design->selection().optimize(design); + return; + } + + return; + } + + IdString modname = design->twines().find(RTLIL::escape_id(args[1])); + + if (design->module(modname) == nullptr && !design->selected_active_module.empty()) { + RTLIL::Module *module = design->module(design->selected_active_module); + IdString cell_ref = modname; + if (module != nullptr && cell_ref != IdString::Null && module->cell(cell_ref) != nullptr) + modname = module->cell(cell_ref)->type; + } + + if (design->module(modname) != nullptr) { + design->selected_active_module = modname; + design->pop_selection(); + design->push_full_selection(); + select_filter_active_mod(design, design->selection()); + design->selection().optimize(design); + return; + } + + log_cmd_error("No such module `%s' found!\n", PooledName(design, modname).unescape()); + } +} CdPass; + +template +static void log_matches(const char *title, Module *module, const T &list) +{ + std::vector matches; + + for (auto &it : list) + if (module->selected(it.second)) + matches.push_back(it.first); + + if (!matches.empty()) { + log("\n"); + log("%d %s:\n", int(matches.size()), title); + auto &twines = module->twines(); + std::sort(matches.begin(), matches.end(), [&](IdString a, IdString b) { + return twines.str(a) < twines.str(b); + }); + for (auto ref : matches) + log(" %s\n", twines.unescaped_str(ref)); + } +} + +struct LsPass : public Pass { + LsPass() : Pass("ls", "list modules or objects in modules") { } + bool formatted_help() override { + auto *help = PrettyHelp::get_current(); + help->set_group("passes/status"); + return false; + } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" ls [selection]\n"); + log("\n"); + log("When no active module is selected, this prints a list of modules.\n"); + log("\n"); + log("When an active module is selected, this prints a list of objects in the module.\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + size_t argidx = 1; + extra_args(args, argidx, design); + + if (design->selected_active_module.empty()) + { + std::vector matches; + + for (auto mod : design->all_selected_modules()) + matches.push_back(mod->name); + + if (!matches.empty()) { + log("\n"); + log("%d %s:\n", int(matches.size()), "modules"); + std::sort(matches.begin(), matches.end(), RTLIL::sort_by_id_str(design->twines())); + for (auto id : matches) + log(" %s%s\n", PooledName(design, id).unescape(), design->selected_whole_module(design->module(id)) ? "" : "*"); + } + } + else + if (design->module(design->selected_active_module) != nullptr) + { + RTLIL::Module *module = design->module(design->selected_active_module); + log_matches("wires", module, module->wires_); + log_matches("memories", module, module->memories); + log_matches("cells", module, module->cells_); + log_matches("processes", module, module->processes); + } + } +} LsPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/setattr.cc b/chips/yosys/passes/cmds/setattr.cc new file mode 100644 index 0000000000000000000000000000000000000000..2f0dc1b5635cf9949503387cb316c0583874fd11 --- /dev/null +++ b/chips/yosys/passes/cmds/setattr.cc @@ -0,0 +1,281 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/register.h" +#include "kernel/rtlil.h" +#include "kernel/log.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct setunset_t +{ + std::string name; + RTLIL::Const value; + bool unset; + + setunset_t(std::string unset_name) : name(RTLIL::escape_id(unset_name)), value(), unset(true) { } + + setunset_t(std::string set_name, std::string set_value) : name(RTLIL::escape_id(set_name)), value(), unset(false) + { + if (set_value.compare(0, 1, "\"") == 0 && set_value.compare(GetSize(set_value)-1, std::string::npos, "\"") == 0) { + value = RTLIL::Const(set_value.substr(1, GetSize(set_value)-2)); + } else { + RTLIL::SigSpec sig_value; + if (!RTLIL::SigSpec::parse(sig_value, nullptr, set_value)) + log_cmd_error("Can't decode value '%s'!\n", set_value); + value = sig_value.as_const(); + value.tag_bare_integer_const(set_value); + } + } +}; + +static void do_setunset(RTLIL::Design *design, dict &attrs, const std::vector &list) +{ + for (auto &item : list) + if (item.unset) { + IdString name = design->twines().find(item.name); + if (name != IdString::Null) + attrs.erase(name); + } else + attrs[design->twines().add(item.name)] = item.value; +} + +struct SetattrPass : public Pass { + SetattrPass() : Pass("setattr", "set/unset attributes on objects") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" setattr [ -mod ] [ -set name value | -unset name ]... [selection]\n"); + log("\n"); + log("Set/unset the given attributes on the selected objects. String values must be\n"); + log("passed in double quotes (\").\n"); + log("\n"); + log("When called with -mod, this command will set and unset attributes on modules\n"); + log("instead of objects within modules.\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + std::vector setunset_list; + bool flag_mod = false; + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) + { + std::string arg = args[argidx]; + if (arg == "-set" && argidx+2 < args.size()) { + string set_key = args[++argidx]; + string set_val = args[++argidx]; + setunset_list.push_back(setunset_t(set_key, set_val)); + continue; + } + if (arg == "-unset" && argidx+1 < args.size()) { + setunset_list.push_back(setunset_t(args[++argidx])); + continue; + } + if (arg == "-mod") { + flag_mod = true; + continue; + } + break; + } + extra_args(args, argidx, design); + + for (auto module : design->all_selected_modules()) + { + if (flag_mod) { + if (module->is_selected_whole()) + do_setunset(design, module->attributes, setunset_list); + continue; + } + + for (auto memb : module->selected_members()) + do_setunset(design, memb.obj->attributes, setunset_list); + } + } +} SetattrPass; + +struct WbflipPass : public Pass { + WbflipPass() : Pass("wbflip", "flip the whitebox attribute") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" wbflip [selection]\n"); + log("\n"); + log("Flip the whitebox attribute on selected cells. I.e. if it's set, unset it, and\n"); + log("vice-versa. Blackbox cells are not effected by this command.\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) + { + std::string arg = args[argidx]; + // if (arg == "-mod") { + // flag_mod = true; + // continue; + // } + break; + } + extra_args(args, argidx, design); + + for (auto *module : design->selected_modules(RTLIL::SELECT_ALL, RTLIL::SB_EXCL_BB_ONLY)) + module->set_bool_attribute(ID::whitebox, !module->get_bool_attribute(ID::whitebox)); + } +} WbflipPass; + +struct SetparamPass : public Pass { + SetparamPass() : Pass("setparam", "set/unset parameters on objects") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" setparam [ -type cell_type ] [ -set name value | -unset name ]... [selection]\n"); + log("\n"); + log("Set/unset the given parameters on the selected cells. String values must be\n"); + log("passed in double quotes (\").\n"); + log("\n"); + log("The -type option can be used to change the cell type of the selected cells.\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + vector setunset_list; + string new_cell_type; + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) + { + std::string arg = args[argidx]; + if (arg == "-set" && argidx+2 < args.size()) { + string set_key = args[++argidx]; + string set_val = args[++argidx]; + setunset_list.push_back(setunset_t(set_key, set_val)); + continue; + } + if (arg == "-unset" && argidx+1 < args.size()) { + setunset_list.push_back(setunset_t(args[++argidx])); + continue; + } + if (arg == "-type" && argidx+1 < args.size()) { + new_cell_type = RTLIL::escape_id(args[++argidx]); + continue; + } + break; + } + extra_args(args, argidx, design); + + for (auto module : design->selected_modules()) + { + for (auto cell : module->selected_cells()) { + if (!new_cell_type.empty()) + cell->type = cell->twines().add(new_cell_type); + do_setunset(design, cell->parameters, setunset_list); + } + } + } +} SetparamPass; + +struct ChparamPass : public Pass { + ChparamPass() : Pass("chparam", "re-evaluate modules with new parameters") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" chparam [ -set name value ]... [selection]\n"); + log("\n"); + log("Re-evaluate the selected modules with new parameters. String values must be\n"); + log("passed in double quotes (\").\n"); + log("\n"); + log("\n"); + log(" chparam -list [selection]\n"); + log("\n"); + log("List the available parameters of the selected modules.\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + std::vector setunset_list; + dict new_parameters; + bool list_mode = false; + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) + { + std::string arg = args[argidx]; + if (arg == "-set" && argidx+2 < args.size()) { + string set_key = args[++argidx]; + string set_val = args[++argidx]; + setunset_list.push_back(setunset_t(set_key, set_val)); + continue; + } + if (arg == "-list") { + list_mode = true; + continue; + } + break; + } + + for (int i = argidx; i < GetSize(args); i++) + if (design->module("$abstract\\" + args[i]) != nullptr && + design->module(RTLIL::escape_id(args[i])) == nullptr) + args[i] = "$abstract\\" + args[i]; + + extra_args(args, argidx, design); + + do_setunset(design, new_parameters, setunset_list); + + if (list_mode) { + if (!new_parameters.empty()) + log_cmd_error("The options -set and -list cannot be used together.\n"); + for (auto module : design->selected_modules()) { + log("%s:\n", module); + for (auto param : module->avail_parameters) + log(" %s\n", PooledName(design, param).unescape()); + } + return; + } + + pool modnames, old_modnames; + for (auto module : design->selected_whole_modules_warn()) { + modnames.insert(module->name); + old_modnames.insert(module->name); + } + modnames.sort(); + + for (auto modname : modnames) { + Module *module = design->module(modname); + Module *new_module = design->module(module->derive(design, new_parameters)); + if (module != new_module) { + Module *m = new_module->clone(); + m->name = module->name; + design->remove(module); + design->add(m); + } + if (old_modnames.count(new_module->name) == 0) + design->remove(new_module); + } + } +} ChparamPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/setenv.cc b/chips/yosys/passes/cmds/setenv.cc new file mode 100644 index 0000000000000000000000000000000000000000..bb071b2710ab0a9dae99f5a338e9a03bb2d8304f --- /dev/null +++ b/chips/yosys/passes/cmds/setenv.cc @@ -0,0 +1,61 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2024 N. Engelhardt + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "kernel/log_help.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN +struct SetenvPass : public Pass { + SetenvPass() : Pass("setenv", "set an environment variable") { } + bool formatted_help() override { + auto *help = PrettyHelp::get_current(); + help->set_group("passes/status"); + return false; + } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" setenv name value\n"); + log("\n"); + log("Set the given environment variable on the current process. Values containing\n"); + log("whitespace must be passed in double quotes (\").\n"); + log("\n"); + } + void execute(std::vector args, [[maybe_unused]] RTLIL::Design *design) override + { + if(args.size() != 3) + log_cmd_error("Wrong number of arguments given.\n"); + + std::string name = args[1]; + std::string value = args[2]; + if (value.front() == '\"' && value.back() == '\"') value = value.substr(1, value.size() - 2); + +#if defined(_WIN32) + _putenv_s(name.c_str(), value.c_str()); +#else + if (setenv(name.c_str(), value.c_str(), 1)) + log_cmd_error("Invalid name \"%s\".\n", name); +#endif + + } +} SetenvPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/setundef.cc b/chips/yosys/passes/cmds/setundef.cc new file mode 100644 index 0000000000000000000000000000000000000000..e72bcca382e82f24a99616785cba76ee42e399a0 --- /dev/null +++ b/chips/yosys/passes/cmds/setundef.cc @@ -0,0 +1,566 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/register.h" +#include "kernel/celltypes.h" +#include "kernel/sigtools.h" +#include "kernel/mem.h" +#include "kernel/rtlil.h" +#include "kernel/log.h" + +#define MODE_ZERO 0 +#define MODE_ONE 1 +#define MODE_UNDEF 2 +#define MODE_RANDOM 3 +#define MODE_ANYSEQ 4 +#define MODE_ANYCONST 5 + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +static RTLIL::Wire * add_wire(RTLIL::Module *module, std::string name, int width, bool flag_input, bool flag_output) +{ + RTLIL::Wire *wire = NULL; + name = RTLIL::escape_id(name); + + IdString t = module->twines().add(name); + + if (module->count_id(t) != 0) + { + log("Module %s already has such an object %s.\n", module->name, name); + name += "$"; + return add_wire(module, name, width, flag_input, flag_output); + } + else + { + wire = module->addWire(name, width); + wire->port_input = flag_input; + wire->port_output = flag_output; + + if (flag_input || flag_output) { + wire->port_id = module->wires_.size(); + module->fixup_ports(); + } + + log("Added wire %s to module %s.\n", name, module->name); + } + + return wire; +} + +struct SetundefWorker +{ + int next_bit_mode; + uint32_t next_bit_state; + vector siglist; + + RTLIL::State next_bit() + { + if (next_bit_mode == MODE_ZERO) + return RTLIL::State::S0; + + if (next_bit_mode == MODE_ONE) + return RTLIL::State::S1; + + if (next_bit_mode == MODE_UNDEF) + return RTLIL::State::Sx; + + if (next_bit_mode == MODE_RANDOM) + { + // xorshift32 + next_bit_state ^= next_bit_state << 13; + next_bit_state ^= next_bit_state >> 17; + next_bit_state ^= next_bit_state << 5; + log_assert(next_bit_state != 0); + + return ((next_bit_state >> (next_bit_state & 15)) & 16) ? RTLIL::State::S0 : RTLIL::State::S1; + } + + log_abort(); + } + + void operator()(RTLIL::SigSpec &sig) + { + if (next_bit_mode == MODE_ANYSEQ || next_bit_mode == MODE_ANYCONST) { + siglist.push_back(&sig); + return; + } + + for (auto &bit : sig) + if (bit.wire == NULL && bit.data > RTLIL::State::S1) + bit = next_bit(); + } +}; + +struct SetundefPass : public Pass { + SetundefPass() : Pass("setundef", "replace undef values with defined constants") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" setundef [options] [selection]\n"); + log("\n"); + log("This command replaces undef (x) constants with defined (0/1) constants.\n"); + log("\n"); + log(" -undriven\n"); + log(" also set undriven nets to constant values\n"); + log("\n"); + log(" -expose\n"); + log(" also expose undriven nets as inputs (use with -undriven)\n"); + log("\n"); + log(" -zero\n"); + log(" replace with bits cleared (0)\n"); + log("\n"); + log(" -one\n"); + log(" replace with bits set (1)\n"); + log("\n"); + log(" -undef\n"); + log(" replace with undef (x) bits, may be used with -undriven\n"); + log("\n"); + log(" -anyseq\n"); + log(" replace with $anyseq drivers (for formal)\n"); + log("\n"); + log(" -anyconst\n"); + log(" replace with $anyconst drivers (for formal)\n"); + log("\n"); + log(" -random \n"); + log(" replace with random bits using the specified integer as seed\n"); + log(" value for the random number generator.\n"); + log("\n"); + log(" -init\n"); + log(" also create/update init values for flip-flops\n"); + log("\n"); + log(" -params\n"); + log(" replace undef in cell parameters\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + int got_value = 0; + bool undriven_mode = false; + bool expose_mode = false; + bool init_mode = false; + bool params_mode = false; + SetundefWorker worker; + + log_header(design, "Executing SETUNDEF pass (replace undef values with defined constants).\n"); + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) + { + if (args[argidx] == "-undriven") { + undriven_mode = true; + continue; + } + if (args[argidx] == "-expose") { + expose_mode = true; + continue; + } + if (args[argidx] == "-zero") { + got_value++; + worker.next_bit_mode = MODE_ZERO; + worker.next_bit_state = 0; + continue; + } + if (args[argidx] == "-one") { + got_value++; + worker.next_bit_mode = MODE_ONE; + worker.next_bit_state = 0; + continue; + } + if (args[argidx] == "-anyseq") { + got_value++; + worker.next_bit_mode = MODE_ANYSEQ; + worker.next_bit_state = 0; + continue; + } + if (args[argidx] == "-anyconst") { + got_value++; + worker.next_bit_mode = MODE_ANYCONST; + worker.next_bit_state = 0; + continue; + } + if (args[argidx] == "-undef") { + got_value++; + worker.next_bit_mode = MODE_UNDEF; + worker.next_bit_state = 0; + continue; + } + if (args[argidx] == "-init") { + init_mode = true; + continue; + } + if (args[argidx] == "-params") { + params_mode = true; + continue; + } + if (args[argidx] == "-random" && argidx+1 < args.size()) { + got_value++; + worker.next_bit_mode = MODE_RANDOM; + worker.next_bit_state = atoi(args[++argidx].c_str()) + 1; + for (int i = 0; i < 10; i++) + worker.next_bit(); + continue; + } + break; + } + extra_args(args, argidx, design); + + if (!got_value && expose_mode) { + log("Using default as -undef with -expose.\n"); + got_value++; + worker.next_bit_mode = MODE_UNDEF; + worker.next_bit_state = 0; + } + + if (expose_mode && !undriven_mode) + log_cmd_error("Option -expose must be used with option -undriven.\n"); + if (!got_value) + log_cmd_error("One of the options -zero, -one, -anyseq, -anyconst, -random , or -expose must be specified.\n"); + else if (got_value > 1) + log_cmd_error("Only one of the options -zero, -one, -anyseq, -anyconst, or -random can be specified.\n"); + + if (init_mode && (worker.next_bit_mode == MODE_ANYSEQ || worker.next_bit_mode == MODE_ANYCONST)) + log_cmd_error("The options -init and -anyseq / -anyconst are exclusive.\n"); + + for (auto module : design->selected_modules()) + { + if (params_mode) + { + for (auto *cell : module->selected_cells()) { + for (auto ¶meter : cell->parameters) { + for (auto bit : parameter.second) { + if (bit > RTLIL::State::S1) + bit = worker.next_bit(); + } + } + } + } + + if (undriven_mode) + { + if (!module->processes.empty()) + log_error("The 'setundef' command can't operate in -undriven mode on modules with processes. Run 'proc' first.\n"); + + if (expose_mode) + { + SigMap sigmap(module); + dict wire_drivers; + pool used_wires; + SigPool undriven_signals; + + for (auto cell : module->cells()) + for (auto &conn : cell->connections()) { + SigSpec sig = sigmap(conn.second); + if (cell->input(conn.first)) + for (auto bit : sig) + if (bit.wire) + used_wires.insert(bit); + if (cell->output(conn.first)) + for (int i = 0; i < GetSize(sig); i++) + if (sig[i].wire) + wire_drivers[sig[i]] = true; + } + + for (auto wire : module->wires()) { + if (wire->port_input) { + SigSpec sig = sigmap(wire); + for (int i = 0; i < GetSize(sig); i++) + wire_drivers[sig[i]] = true; + } + if (wire->port_output) { + SigSpec sig = sigmap(wire); + for (auto bit : sig) + if (bit.wire) + used_wires.insert(bit); + } + } + + pool undriven_wires; + for (auto bit : used_wires) + if (!wire_drivers.count(bit)) + undriven_wires.insert(bit.wire); + + for (auto &it : undriven_wires) + undriven_signals.add(sigmap(it)); + + for (auto &it : undriven_wires) + if (it->port_input) + undriven_signals.del(sigmap(it)); + + CellTypes ct(design); + for (auto &it : module->cells_) + for (auto &conn : it.second->connections()) + if (!ct.cell_known(it.second->type) || ct.cell_output(it.second->type, conn.first)) + undriven_signals.del(sigmap(conn.second)); + + RTLIL::SigSpec sig = undriven_signals.export_all(); + for (auto &c : sig.chunks()) { + if (!design->selected(module, c.wire)) + continue; + RTLIL::Wire * wire; + if (c.wire->width == c.width) { + wire = c.wire; + wire->port_input = true; + } else { + string name = c.wire->name.str() + "$[" + std::to_string(c.width + c.offset) + ":" + std::to_string(c.offset) + "]"; + wire = add_wire(module, name, c.width, true, false); + module->connect(RTLIL::SigSig(c, wire)); + } + log("Exposing undriven wire %s as input.\n", wire->name); + } + module->fixup_ports(); + } + else + { + SigMap sigmap(module); + SigPool undriven_signals; + + for (auto wire : module->selected_wires()) + undriven_signals.add(sigmap(wire)); + + for (auto wire : module->selected_wires()) + if (wire->port_input) + undriven_signals.del(sigmap(wire)); + + CellTypes ct(design); + for (auto &it : module->cells_) + for (auto &conn : it.second->connections()) + if (!ct.cell_known(it.second->type) || ct.cell_output(it.second->type, conn.first)) + undriven_signals.del(sigmap(conn.second)); + + RTLIL::SigSpec sig = undriven_signals.export_all(); + for (auto &c : sig.chunks()) { + RTLIL::SigSpec bits; + if (worker.next_bit_mode == MODE_ANYSEQ) + bits = module->Anyseq(NEW_ID, c.width); + else if (worker.next_bit_mode == MODE_ANYCONST) + bits = module->Anyconst(NEW_ID, c.width); + else + for (int i = 0; i < c.width; i++) + bits.append(worker.next_bit()); + module->connect(RTLIL::SigSig(c, bits)); + } + } + } + + if (init_mode) + { + SigMap sigmap(module); + pool ffbits; + pool initwires; + + for (auto cell : module->cells()) + { + if (!cell->is_builtin_ff()) + continue; + + bool cell_selected = design->selected(module, cell); + bool wire_selected = false; + for (auto bit : sigmap(cell->getPort(ID::Q))) + if (bit.wire && design->selected(module, bit.wire)) + wire_selected = true; + if (!cell_selected && !wire_selected) + continue; + + for (auto bit : sigmap(cell->getPort(ID::Q))) + ffbits.insert(bit); + } + + auto process_initwires = [&]() + { + dict wire_weights; + + for (auto wire : initwires) + { + int weight = 0; + + for (auto bit : sigmap(wire)) + weight += ffbits.count(bit) ? +1 : -1; + + wire_weights[wire] = weight; + } + + initwires.sort([&](Wire *a, Wire *b) { return wire_weights.at(a) > wire_weights.at(b); }); + + for (auto wire : initwires) + { + Const &initval = wire->attributes[ID::init]; + initval.resize(GetSize(wire), State::Sx); + + for (int i = 0; i < GetSize(wire); i++) { + SigBit bit = sigmap(SigBit(wire, i)); + if (initval[i] == State::Sx && ffbits.count(bit)) { + initval.set(i, worker.next_bit()); + ffbits.erase(bit); + } + } + + if (initval.is_fully_undef()) + wire->attributes.erase(ID::init); + } + + initwires.clear(); + }; + + for (int wire_types = 0; wire_types < 2; wire_types++) + { + // prioritize wires that already have an init attribute + if (!ffbits.empty()) + { + for (auto wire : module->wires()) + { + if (wire->name.isPublic() == wire_types) + continue; + + if (!wire->attributes.count(ID::init)) + continue; + + Const &initval = wire->attributes[ID::init]; + initval.resize(GetSize(wire), State::Sx); + + if (initval.is_fully_undef()) { + wire->attributes.erase(ID::init); + continue; + } + + for (int i = 0; i < GetSize(wire); i++) + if (initval[i] != State::Sx) + ffbits.erase(sigmap(SigBit(wire, i))); + + initwires.insert(wire); + } + + process_initwires(); + } + + // next consider wires that completely contain bits to be initialized + if (!ffbits.empty()) + { + for (auto wire : module->wires()) + { + if (wire->name.isPublic() == wire_types) + continue; + + for (auto bit : sigmap(wire)) + if (!ffbits.count(bit)) + goto next_wire; + + initwires.insert(wire); + + next_wire: + continue; + } + + process_initwires(); + } + + // finally use whatever wire we can find. + if (!ffbits.empty()) + { + for (auto wire : module->wires()) + { + if (wire->name.isPublic() == wire_types) + continue; + + for (auto bit : sigmap(wire)) + if (ffbits.count(bit)) + initwires.insert(wire); + } + + process_initwires(); + } + } + + log_assert(ffbits.empty()); + } + + if (worker.next_bit_mode == MODE_ANYSEQ || worker.next_bit_mode == MODE_ANYCONST) + { + // Do not add anyseq / anyconst to unused memory port clocks + std::vector memories = Mem::get_selected_memories(module); + for (auto &mem : memories) { + bool changed = false; + for (auto &rd_port : mem.rd_ports) { + if (!rd_port.clk_enable && rd_port.clk.is_fully_undef()) { + changed = true; + rd_port.clk = State::S0; + } + } + for (auto &wr_port : mem.rd_ports) { + if (!wr_port.clk_enable && wr_port.clk.is_fully_undef()) { + changed = true; + wr_port.clk = State::S0; + } + } + if (changed) + mem.emit(); + } + } + + for (auto cell : module->selected_cells()) + if (!cell->get_bool_attribute(ID::xprop_decoder)) + cell->rewrite_sigspecs(worker); + for (auto proc : module->selected_processes()) + proc->rewrite_sigspecs(worker); + for (auto &it : module->connections_) { + SigSpec lhs = it.first; + bool selected = false; + for (auto &chunk : lhs.chunks()) + if (chunk.wire && module->design->selected(module, chunk.wire)) + selected = true; + if (selected) { + worker(it.first); + worker(it.second); + } + } + + if (worker.next_bit_mode == MODE_ANYSEQ || worker.next_bit_mode == MODE_ANYCONST) + { + vector siglist; + siglist.swap(worker.siglist); + + for (auto sigptr : siglist) + { + SigSpec &sig = *sigptr; + int cursor = 0; + + while (cursor < GetSize(sig)) + { + int width = 0; + while (cursor+width < GetSize(sig) && sig[cursor+width] == State::Sx) + width++; + + if (width > 0) { + if (worker.next_bit_mode == MODE_ANYSEQ) + sig.replace(cursor, module->Anyseq(NEW_ID, width)); + else + sig.replace(cursor, module->Anyconst(NEW_ID, width)); + cursor += width; + } else { + cursor++; + } + } + } + } + } + } +} SetundefPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/show.cc b/chips/yosys/passes/cmds/show.cc new file mode 100644 index 0000000000000000000000000000000000000000..1e22b3fec84ba0eaa9301d401e8768d230696f77 --- /dev/null +++ b/chips/yosys/passes/cmds/show.cc @@ -0,0 +1,1008 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/rtlil.h" +#include "kernel/yosys.h" +#include "kernel/celltypes.h" +#include "kernel/log_help.h" + +#ifndef _WIN32 +# include +#endif + +#ifdef __APPLE__ +# include +#endif + +#ifdef YOSYS_ENABLE_READLINE +# include +#endif + +#ifdef YOSYS_ENABLE_EDITLINE +# include +#endif + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +#undef CLUSTER_CELLS_AND_PORTBOXES + +struct ShowWorker +{ + CellTypes ct; + + vector dot_escape_store; + std::map dot_id2num_store; + std::map autonames; + int single_idx_count; + + struct net_conn { std::set> in, out; std::string color; }; + std::map net_conn_map; + + FILE *f; + RTLIL::Design *design; + RTLIL::Module *module; + uint32_t currentColor; + bool genWidthLabels; + std::string wireshape; + bool genSignedLabels; + bool stretchIO; + bool enumerateIds; + bool abbreviateIds; + bool notitle; + bool href; + int page_counter; + + const std::vector> &color_selections; + const std::vector> &label_selections; + + std::map colorattr_cache; + RTLIL::IdString colorattr; + + + static uint32_t xorshift32(uint32_t x) { + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + return x; + } + + std::string nextColor() + { + if (currentColor == 0) + return "color=\"black\", fontcolor=\"black\""; + return stringf("colorscheme=\"dark28\", color=\"%d\", fontcolor=\"%d\"", currentColor%8+1, currentColor%8+1); + } + + std::string nextColor(std::string presetColor) + { + if (presetColor.empty()) + return nextColor(); + return presetColor; + } + + std::string nextColor(RTLIL::SigSpec sig, std::string defaultColor) + { + std::string color = findColor(sig); + if (!color.empty()) return color; + return defaultColor; + } + + std::string nextColor(const RTLIL::SigSig &conn, std::string defaultColor) + { + std::string color = findColor(conn); + if (!color.empty()) return color; + return defaultColor; + } + + std::string nextColor(const RTLIL::SigSpec &sig) + { + return nextColor(sig, nextColor()); + } + + std::string nextColor(const RTLIL::SigSig &conn) + { + return nextColor(conn, nextColor()); + } + + std::string widthLabel(int bits) + { + if (bits <= 1) + return "label=\"\""; + if (!genWidthLabels) + return "style=\"setlinewidth(3)\", label=\"\""; + return stringf("style=\"setlinewidth(3)\", label=\"<%d>\"", bits); + } + + std::string findColor(RTLIL::SigSpec sig) + { + sig.sort_and_unify(); + for (auto &c : sig.chunks()) { + if (c.wire != nullptr) + return findColor(c.wire->name); + } + return ""; + } + + std::string findColor(const RTLIL::SigSig &conn) + { + std::string firstColor = findColor(conn.first); + if (findColor(conn.second) == firstColor) return firstColor; + return ""; + } + + std::string findColor(IdString member_ref) + { + for (auto &s : color_selections) + if (member_ref != IdString::Null && s.second.selected_member(module->name, member_ref)) { + return stringf("color=\"%s\", fontcolor=\"%s\"", s.first, s.first); + } + + RTLIL::Const colorattr_value; + RTLIL::Cell *cell = member_ref != IdString::Null ? module->cell(member_ref) : nullptr; + RTLIL::Wire *wire = member_ref != IdString::Null ? module->wire(member_ref) : nullptr; + + if (cell && cell->attributes.count(colorattr)) + colorattr_value = cell->attributes.at(colorattr); + else if (wire && wire->attributes.count(colorattr)) + colorattr_value = wire->attributes.at(colorattr); + else + return ""; + + if (colorattr_cache.count(colorattr_value) == 0) { + int next_id = GetSize(colorattr_cache); + colorattr_cache[colorattr_value] = (next_id % 8) + 1; + } + + return stringf("colorscheme=\"dark28\", color=\"%d\", fontcolor=\"%d\"", colorattr_cache.at(colorattr_value), colorattr_cache.at(colorattr_value)); + } + + const char *findLabel(std::string member_name) + { + bool is_id = (member_name.starts_with('$') || member_name.starts_with('\\')) && + std::none_of(member_name.begin(), member_name.end(), [](char ch) { return (unsigned char)ch <= ' '; }); + IdString member_ref = is_id ? design->twines().find(member_name) : IdString::Null; + for (auto &s : label_selections) + if (member_ref != IdString::Null && s.second.selected_member(module->name, member_ref)) + return escape(s.first); + return escape(member_name, true); + } + + const char *escape(std::string id, bool is_name = false) + { + if (id.size() == 0) + return ""; + + if (id[0] == '$' && is_name) { + if (enumerateIds) { + if (autonames.count(id) == 0) { + autonames[id] = autonames.size() + 1; + log("Generated short name for internal identifier: _%d_ -> %s\n", autonames[id], id); + } + id = stringf("_%d_", autonames[id]); + } else if (abbreviateIds) { + const char *p = id.c_str(); + const char *q = strrchr(p, '$'); + id = std::string(q); + } + } + + if (id[0] == '\\') + id = id.substr(1); + + // TODO: optionally include autoname + print correspondence in case of ambiguity + size_t max_label_len = abbreviateIds ? 256 : 16384; + if (id.size() > max_label_len) { + id = id.substr(0,max_label_len-3) + "..."; + } + + std::string str; + for (char ch : id) { + if (ch == '\\') { + // new graphviz have bug with escaping '\' + str += "╲"; + continue; + } + if (ch == '"' || ch == '<' || ch == '>') + str += "\\"; + str += ch; + } + + dot_escape_store.push_back(str); + return dot_escape_store.back().c_str(); + } + + int id2num(RTLIL::IdString id) + { + if (dot_id2num_store.count(id) > 0) + return dot_id2num_store[id]; + return dot_id2num_store[id] = dot_id2num_store.size() + 1; + } + + std::string gen_signode_simple(RTLIL::SigSpec sig, bool range_check = true) + { + if (GetSize(sig) == 0) { + fprintf(f, "v%d [ label=\"\" ];\n", single_idx_count); + return stringf("v%d", single_idx_count++); + } + + if (sig.is_chunk()) { + const RTLIL::SigChunk &c = sig.as_chunk(); + if (c.wire != nullptr && design->selected_member(module->name, c.wire->name)) { + if (!range_check || c.wire->width == c.width) + return stringf("n%d", id2num(c.wire->name)); + } else { + fprintf(f, "v%d [ label=\"%s\" ];\n", single_idx_count, findLabel(log_signal(c))); + return stringf("v%d", single_idx_count++); + } + } + + return std::string(); + } + + // Return the pieces of a label joined by a '|' separator + std::string join_label_pieces(std::vector pieces) + { + std::string ret = ""; + bool first_piece = true; + + for (auto &piece : pieces) { + if (!first_piece) + ret += "|"; + ret += piece; + first_piece = false; + } + + return ret; + } + + std::string gen_portbox(std::string port, RTLIL::SigSpec sig, bool driver, std::string *node = nullptr) + { + std::string code; + std::string net = gen_signode_simple(sig); + if (net.empty()) + { + int dot_idx = single_idx_count++; + std::vector label_pieces; + int bitpos = sig.size()-1; + + RTLIL::SigSpec::Chunks sig_chunks = sig.chunks(); + for (int rep, chunk_idx = ((int) sig_chunks.size()) - 1; chunk_idx >= 0; chunk_idx -= rep) { + const RTLIL::SigChunk &c = sig_chunks.at(chunk_idx); + + // Find the number of times this chunk is repeating + for (rep = 1; chunk_idx - rep >= 0 && c == sig_chunks.at(chunk_idx - rep); rep++); + + int cl, cr; + cl = c.offset + c.width - 1; + cr = c.offset; + + if (c.is_wire()) { + if (c.wire->upto) { + cr = (c.wire->width - 1) - c.offset; + cl = cr - (c.width - 1); + } + + cl += c.wire->start_offset; + cr += c.wire->start_offset; + } + + // Is this chunk a constant filled with one kind of bit state? + bool no_signode = !driver && !c.is_wire() \ + && std::equal(c.data.begin() + 1, c.data.end(), c.data.begin()); + + if (!no_signode) { + net = gen_signode_simple(c, false); + log_assert(!net.empty()); + } + + std::string repinfo = rep > 1 ? stringf("%dx ", rep) : ""; + std::string portside = stringf("%d:%d", bitpos, bitpos - rep*c.width + 1); + std::string remoteside = stringf("%s%d:%d", repinfo, cl, cr); + + if (driver) { + log_assert(!net.empty()); + label_pieces.push_back(stringf(" %s - %s ", chunk_idx, portside, remoteside)); + net_conn_map[net].in.insert({stringf("x%d:s%d", dot_idx, chunk_idx), rep*c.width}); + net_conn_map[net].color = nextColor(c, net_conn_map[net].color); + } else { + if (no_signode) { + log_assert(rep == 1); + label_pieces.push_back(stringf("%c -> %d:%d ", + c.data.front() == State::S0 ? '0' : + c.data.front() == State::S1 ? '1' : + c.data.front() == State::Sx ? 'X' : + c.data.front() == State::Sz ? 'Z' : '?', + bitpos, bitpos-rep*c.width+1)); + } else { + label_pieces.push_back(stringf(" %s - %s ", chunk_idx, remoteside, portside)); + net_conn_map[net].out.insert({stringf("x%d:s%d", dot_idx, chunk_idx), rep*c.width}); + net_conn_map[net].color = nextColor(c, net_conn_map[net].color); + } + } + + bitpos -= rep * c.width; + } + + code += stringf("x%d [ shape=record, style=rounded, label=\"", dot_idx) \ + + join_label_pieces(label_pieces) + stringf("\", %s ];\n", nextColor(sig)); + + if (!port.empty()) { + currentColor = xorshift32(currentColor); + if (driver) + code += stringf("%s:e -> x%d:w [arrowhead=odiamond, arrowtail=odiamond, dir=both, %s, %s];\n", port, dot_idx, nextColor(sig), widthLabel(sig.size())); + else + code += stringf("x%d:e -> %s:w [arrowhead=odiamond, arrowtail=odiamond, dir=both, %s, %s];\n", dot_idx, port, nextColor(sig), widthLabel(sig.size())); + } + if (node != nullptr) + *node = stringf("x%d", dot_idx); + } + else + { + if (!port.empty()) { + if (driver) + net_conn_map[net].in.insert({port, GetSize(sig)}); + else + net_conn_map[net].out.insert({port, GetSize(sig)}); + net_conn_map[net].color = nextColor(sig, net_conn_map[net].color); + } + if (node != nullptr) + *node = net; + } + return code; + } + + void collect_proc_signals(std::vector &obj, std::set &signals) + { + for (auto &it : obj) + if (!it.is_fully_const()) + signals.insert(it); + } + + void collect_proc_signals(std::vector &obj, std::set &input_signals, std::set &output_signals) + { + for (auto &it : obj) { + output_signals.insert(it.first); + if (!it.second.is_fully_const()) + input_signals.insert(it.second); + } + } + + void collect_proc_signals(RTLIL::CaseRule *obj, std::set &input_signals, std::set &output_signals) + { + collect_proc_signals(obj->compare, input_signals); + collect_proc_signals(obj->actions, input_signals, output_signals); + for (auto it : obj->switches) + collect_proc_signals(it, input_signals, output_signals); + } + + void collect_proc_signals(RTLIL::SwitchRule *obj, std::set &input_signals, std::set &output_signals) + { + input_signals.insert(obj->signal); + for (auto it : obj->cases) + collect_proc_signals(it, input_signals, output_signals); + } + + void collect_proc_signals(RTLIL::SyncRule *obj, std::set &input_signals, std::set &output_signals) + { + input_signals.insert(obj->signal); + collect_proc_signals(obj->actions, input_signals, output_signals); + for (auto it : obj->mem_write_actions) { + input_signals.insert(it.address); + input_signals.insert(it.data); + input_signals.insert(it.enable); + } + } + + void collect_proc_signals(RTLIL::Process *obj, std::set &input_signals, std::set &output_signals) + { + collect_proc_signals(&obj->root_case, input_signals, output_signals); + for (auto it : obj->syncs) + collect_proc_signals(it, input_signals, output_signals); + } + + void handle_module() + { + single_idx_count = 0; + dot_escape_store.clear(); + dot_id2num_store.clear(); + net_conn_map.clear(); + + fprintf(f, "digraph \"%s\" {\n", escape(module->name.str())); + if (!notitle) + fprintf(f, "label=\"%s\";\n", escape(module->name.str())); + fprintf(f, "rankdir=\"LR\";\n"); + fprintf(f, "remincross=true;\n"); + + std::set all_sources, all_sinks; + + std::map wires_on_demand; + for (auto wire : module->selected_wires()) { + std::string shape = wireshape; + if (wire->port_input || wire->port_output) + shape = "octagon"; + const bool is_borderless = (shape == "plaintext") || (shape == "plain") || (shape == "none"); + if (wire->name.isPublic()) { + std::string src_href; + if (href && wire->attributes.count(ID::src) > 0) + src_href = stringf(", href=\"%s\" ", escape(wire->attributes.at(ID::src).decode_string())); + fprintf(f, "n%d [ shape=%s,%s label=\"%s\", %s%s];\n", + id2num(wire->name), shape.c_str(), is_borderless? " margin=0, width=0" : "", findLabel(wire->name.str()), + is_borderless + ? "color=\"none\", fontcolor=\"black\"" + : nextColor(RTLIL::SigSpec(wire), "color=\"black\", fontcolor=\"black\"").c_str(), + src_href.c_str()); + if (wire->port_input) + all_sources.insert(stringf("n%d", id2num(wire->name))); + else if (wire->port_output) + all_sinks.insert(stringf("n%d", id2num(wire->name))); + } else { + wires_on_demand[stringf("n%d", id2num(wire->name))] = wire->name.str(); + } + } + + if (stretchIO) + { + fprintf(f, "{ rank=\"source\";"); + for (auto n : all_sources) + fprintf(f, " %s;", n.c_str()); + fprintf(f, "}\n"); + + fprintf(f, "{ rank=\"sink\";"); + for (auto n : all_sinks) + fprintf(f, " %s;", n.c_str()); + fprintf(f, "}\n"); + } + + for (auto cell : module->selected_cells()) + { + std::vector in_ports, out_ports; + std::vector in_label_pieces, out_label_pieces; + + for (auto &conn : cell->connections()) { + if (!ct.cell_output(cell->type, conn.first)) + in_ports.push_back(conn.first); + else + out_ports.push_back(conn.first); + } + + std::sort(in_ports.begin(), in_ports.end(), RTLIL::sort_by_id_str(design->twines())); + std::sort(out_ports.begin(), out_ports.end(), RTLIL::sort_by_id_str(design->twines())); + + for (auto &p : in_ports) { + std::string p_str = design->twines().str(p); + IdString signed_param = design->twines().find(p_str + "_SIGNED"); + bool signed_suffix = genSignedLabels && signed_param != IdString::Null + && cell->hasParam(signed_param) + && cell->getParam(signed_param).as_bool(); + + in_label_pieces.push_back(stringf(" %s%s", id2num(p), escape(p_str), + signed_suffix ? "*" : "")); + } + + for (auto &p : out_ports) + out_label_pieces.push_back(stringf(" %s", id2num(p), escape(design->twines().str(p)))); + + std::string in_label = join_label_pieces(in_label_pieces); + std::string out_label = join_label_pieces(out_label_pieces); + + std::string label_string = stringf("{{%s}|%s\\n%s|{%s}}", in_label, + findLabel(cell->name.str()), escape(cell->type.str()), + out_label); + + std::string code; + for (auto &conn : cell->connections()) { + code += gen_portbox(stringf("c%d:p%d", id2num(cell->name), id2num(conn.first)), + conn.second, ct.cell_output(cell->type, conn.first)); + } + + std::string src_href; + if (href && cell->attributes.count(ID::src) > 0) { + src_href = stringf("%shref=\"%s\" ", (findColor(cell->name).empty() ? "" :" , "), escape(cell->attributes.at(ID::src).decode_string())); + } +#ifdef CLUSTER_CELLS_AND_PORTBOXES + if (!code.empty()) + fprintf(f, "subgraph cluster_c%d {\nc%d [ shape=record, label=\"%s\"%s%s ];\n%s}\n", + id2num(cell->name), id2num(cell->name), label_string.c_str(), color.c_str(), src_href.c_str(), code.c_str()); + else +#endif + fprintf(f, "c%d [ shape=record, label=\"%s\", %s%s ];\n%s", + id2num(cell->name), label_string.c_str(), findColor(cell->name).c_str(), src_href.c_str(), code.c_str()); + } + + for (auto &it : module->processes) + { + RTLIL::Process *proc = it.second; + + if (!design->selected_member(module->name, it.first)) + continue; + + std::set input_signals, output_signals; + collect_proc_signals(proc, input_signals, output_signals); + + int pidx = single_idx_count++; + input_signals.erase(RTLIL::SigSpec()); + output_signals.erase(RTLIL::SigSpec()); + + for (auto &sig : input_signals) { + std::string code, node; + code += gen_portbox("", sig, false, &node); + fprintf(f, "%s", code.c_str()); + net_conn_map[node].out.insert({stringf("p%d", pidx), GetSize(sig)}); + net_conn_map[node].color = nextColor(sig, net_conn_map[node].color); + } + + for (auto &sig : output_signals) { + std::string code, node; + code += gen_portbox("", sig, true, &node); + fprintf(f, "%s", code.c_str()); + net_conn_map[node].in.insert({stringf("p%d", pidx), GetSize(sig)}); + net_conn_map[node].color = nextColor(sig, net_conn_map[node].color); + } + + std::string proc_src = proc->name.unescape(); + if (proc->attributes.count(ID::src) > 0) + proc_src = proc->attributes.at(ID::src).decode_string(); + fprintf(f, "p%d [shape=box, style=rounded, label=\"PROC %s\\n%s\", %s];\n", pidx, findLabel(proc->name.str()), proc_src.c_str(), findColor(proc->name).c_str()); + } + + for (auto &conn : module->connections()) + { + bool found_lhs_wire = false; + for (auto &c : conn.first.chunks()) { + if (c.wire == nullptr || design->selected_member(module->name, c.wire->name)) + found_lhs_wire = true; + } + bool found_rhs_wire = false; + for (auto &c : conn.second.chunks()) { + if (c.wire == nullptr || design->selected_member(module->name, c.wire->name)) + found_rhs_wire = true; + } + if (!found_lhs_wire || !found_rhs_wire) + continue; + + std::string code, left_node, right_node; + code += gen_portbox("", conn.second, false, &left_node); + code += gen_portbox("", conn.first, true, &right_node); + fprintf(f, "%s", code.c_str()); + + if (left_node[0] == 'x' && right_node[0] == 'x') { + currentColor = xorshift32(currentColor); + fprintf(f, "%s:e -> %s:w [arrowhead=odiamond, arrowtail=odiamond, dir=both, %s, %s];\n", left_node.c_str(), right_node.c_str(), nextColor(conn).c_str(), widthLabel(conn.first.size()).c_str()); + } else { + net_conn_map[right_node].color = nextColor(conn, net_conn_map[right_node].color); + net_conn_map[left_node].color = nextColor(conn, net_conn_map[left_node].color); + if (left_node[0] == 'x') { + net_conn_map[right_node].in.insert({left_node, GetSize(conn.first)}); + } else if (right_node[0] == 'x') { + net_conn_map[left_node].out.insert({right_node, GetSize(conn.first)}); + } else { + net_conn_map[right_node].in.insert({stringf("x%d", single_idx_count), GetSize(conn.first)}); + net_conn_map[left_node].out.insert({stringf("x%d", single_idx_count), GetSize(conn.first)}); + fprintf(f, "x%d [shape=point, %s];\n", single_idx_count++, findColor(conn).c_str()); + } + } + } + + for (auto &it : net_conn_map) + { + currentColor = xorshift32(currentColor); + if (wires_on_demand.count(it.first) > 0) { + if (it.second.in.size() == 1 && it.second.out.size() > 1 && it.second.in.begin()->first.compare(0, 1, "p") == 0) + it.second.out.erase(*it.second.in.begin()); + if (it.second.in.size() == 1 && it.second.out.size() == 1) { + std::string from = it.second.in.begin()->first, to = it.second.out.begin()->first; + int bits = it.second.in.begin()->second; + if (from != to || from.compare(0, 1, "p") != 0) + fprintf(f, "%s:e -> %s:w [%s, %s];\n", from.c_str(), to.c_str(), nextColor(it.second.color).c_str(), widthLabel(bits).c_str()); + continue; + } + if (it.second.in.size() == 0 || it.second.out.size() == 0) + fprintf(f, "%s [ shape=diamond, label=\"%s\" ];\n", it.first.c_str(), findLabel(wires_on_demand[it.first])); + else + fprintf(f, "%s [ shape=point ];\n", it.first.c_str()); + } + for (auto &it2 : it.second.in) + fprintf(f, "%s:e -> %s:w [%s, %s];\n", it2.first.c_str(), it.first.c_str(), nextColor(it.second.color).c_str(), widthLabel(it2.second).c_str()); + for (auto &it2 : it.second.out) + fprintf(f, "%s:e -> %s:w [%s, %s];\n", it.first.c_str(), it2.first.c_str(), nextColor(it.second.color).c_str(), widthLabel(it2.second).c_str()); + } + + fprintf(f, "}\n"); + } + + ShowWorker(FILE *f, RTLIL::Design *design, std::vector> &libs, uint32_t colorSeed, bool genWidthLabels, + const std::string wireshape, bool genSignedLabels, bool stretchIO, bool enumerateIds, bool abbreviateIds, bool notitle, bool href, + const std::vector> &color_selections, + const std::vector> &label_selections, RTLIL::IdString colorattr) : + f(f), design(design), currentColor(colorSeed), genWidthLabels(genWidthLabels), wireshape(wireshape), + genSignedLabels(genSignedLabels), stretchIO(stretchIO), enumerateIds(enumerateIds), abbreviateIds(abbreviateIds), + notitle(notitle), href(href), color_selections(color_selections), label_selections(label_selections), colorattr(colorattr) + { + ct.setup_internals(); + ct.setup_internals_mem(); + ct.setup_internals_anyinit(); + ct.setup_stdcells(); + ct.setup_stdcells_mem(); + ct.setup_design(design); + + for (auto &lib : libs) + ct.setup_design(lib.get()); + + design->optimize(); + page_counter = 0; + for (auto mod : design->selected_modules()) + { + module = mod; + if (design->selected_whole_module(module->name)) { + if (module->get_blackbox_attribute()) { + //log("Skipping blackbox module %s.\n", module->name.unescape()); + continue; + } else + if (module->cells().size() == 0 && module->connections().empty() && module->processes.empty()) { + log("Skipping empty module %s.\n", module); + continue; + } else + log("Dumping module %s to page %d.\n", module, ++page_counter); + } else + log("Dumping selected parts of module %s to page %d.\n", module, ++page_counter); + handle_module(); + } + } +}; + +struct ShowPass : public Pass { + ShowPass() : Pass("show", "generate schematics using graphviz") { } + bool formatted_help() override { + auto *help = PrettyHelp::get_current(); + help->set_group("passes/status"); + return false; + } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" show [options] [selection]\n"); + log("\n"); + log("Create a graphviz DOT file for the selected part of the design and compile it\n"); + log("to a graphics file (usually SVG or PostScript).\n"); + log("\n"); + log(" -viewer \n"); + log(" Run the specified command with the graphics file as parameter.\n"); + log(" On Windows, this pauses yosys until the viewer exits.\n"); + log(" Use \"-viewer none\" to not run any command.\n"); + log("\n"); + log(" -format \n"); + log(" Generate a graphics file in the specified format. Use 'dot' to just\n"); + log(" generate a .dot file, or other strings such as 'svg' or 'ps'\n"); + log(" to generate files in other formats (this calls the 'dot' command).\n"); + log("\n"); + log(" -lib \n"); + log(" Use the specified library file for determining whether cell ports are\n"); + log(" inputs or outputs. This option can be used multiple times to specify\n"); + log(" more than one library.\n"); + log("\n"); + log(" note: in most cases it is better to load the library before calling\n"); + log(" show with 'read_verilog -lib '. it is also possible to\n"); + log(" load liberty files with 'read_liberty -lib '.\n"); + log("\n"); + log(" -prefix \n"); + log(" generate .* instead of ~/.yosys_show.*\n"); + log("\n"); + log(" -color \n"); + log(" assign the specified color to the specified object. The object can be\n"); + log(" a single selection wildcard expressions or a saved set of objects in\n"); + log(" the @ syntax (see \"help select\" for details).\n"); + log("\n"); + log(" -label \n"); + log(" assign the specified label text to the specified object. The object can\n"); + log(" be a single selection wildcard expressions or a saved set of objects in\n"); + log(" the @ syntax (see \"help select\" for details).\n"); + log("\n"); + log(" -colors \n"); + log(" Randomly assign colors to the wires. The integer argument is the seed\n"); + log(" for the random number generator. Change the seed value if the colored\n"); + log(" graph still is ambiguous. A seed of zero deactivates the coloring.\n"); + log("\n"); + log(" -colorattr \n"); + log(" Use the specified attribute to assign colors. A unique color is\n"); + log(" assigned to each unique value of this attribute.\n"); + log("\n"); + log(" -wireshape \n"); + log(" Use the specified shape for wire nodes. E.g. plaintext.\n"); + log("\n"); + log(" -width\n"); + log(" annotate buses with a label indicating the width of the bus.\n"); + log("\n"); + log(" -signed\n"); + log(" mark ports (A, B) that are declared as signed (using the [AB]_SIGNED\n"); + log(" cell parameter) with an asterisk next to the port name.\n"); + log("\n"); + log(" -stretch\n"); + log(" stretch the graph so all inputs are on the left side and all outputs\n"); + log(" (including inout ports) are on the right side.\n"); + log("\n"); + log(" -pause\n"); + log(" wait for the user to press enter to before returning\n"); + log("\n"); + log(" -enum\n"); + log(" enumerate objects with internal ($-prefixed) names\n"); + log("\n"); + log(" -long\n"); + log(" do not abbreviate objects with internal ($-prefixed) names\n"); + log("\n"); + log(" -notitle\n"); + log(" do not add the module name as graph title to the dot file\n"); + log("\n"); + log(" -nobg\n"); + log(" don't run viewer in the background, IE wait for the viewer tool to\n"); + log(" exit before returning\n"); + log("\n"); + log(" -href\n"); + log(" adds href attribute to all items representing cells and wires, using\n"); + log(" src attribute of origin\n"); + log("\n"); + log("When no is specified, 'dot' is used. When no and is\n"); + log("specified, 'xdot' is used to display the schematic (POSIX systems only).\n"); + log("\n"); + log("The generated output files are '~/.yosys_show.dot' and '~/.yosys_show.',\n"); + log("unless another prefix is specified using -prefix .\n"); + log("\n"); + log("Yosys on Windows and YosysJS use different defaults: The output is written\n"); + log("to 'show.dot' in the current directory and new viewer is launched each time\n"); + log("the 'show' command is executed.\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + log_header(design, "Generating Graphviz representation of design.\n"); + log_push(); + + std::vector> color_selections; + std::vector> label_selections; + +#if defined(_WIN32) || !defined(YOSYS_ENABLE_SPAWN) + std::string format = "dot"; + std::string prefix = "show"; +#else + std::string format; + std::string prefix = stringf("%s/.yosys_show", getenv("HOME") ? getenv("HOME") : "."); +#endif + std::string viewer_exe; + std::string flag_wireshape = "diamond"; + std::vector libfiles; + std::vector> libs; + uint32_t colorSeed = 0; + bool flag_width = false; + bool flag_signed = false; + bool flag_stretch = false; + bool flag_pause = false; + bool flag_enum = false; + bool flag_abbreviate = true; + bool flag_notitle = false; + bool flag_href = false; + bool custom_prefix = false; + std::string background = "&"; + RTLIL::IdString colorattr; + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) + { + std::string arg = args[argidx]; + if (arg == "-viewer" && argidx+1 < args.size()) { + viewer_exe = args[++argidx]; + continue; + } + if (arg == "-lib" && argidx+1 < args.size()) { + libfiles.push_back(args[++argidx]); + continue; + } + if (arg == "-prefix" && argidx+1 < args.size()) { + prefix = args[++argidx]; + custom_prefix = true; + continue; + } + if (arg == "-color" && argidx+2 < args.size()) { + std::pair data; + data.first = args[++argidx], argidx++; + handle_extra_select_args(this, args, argidx, argidx+1, design); + data.second = design->selection(); + design->pop_selection(); + color_selections.push_back(data); + continue; + } + if (arg == "-label" && argidx+2 < args.size()) { + std::pair data; + data.first = args[++argidx], argidx++; + handle_extra_select_args(this, args, argidx, argidx+1, design); + data.second = design->selection(); + design->pop_selection(); + label_selections.push_back(data); + continue; + } + if (arg == "-colors" && argidx+1 < args.size()) { + colorSeed = atoi(args[++argidx].c_str()); + for (int i = 0; i < 100; i++) + colorSeed = ShowWorker::xorshift32(colorSeed); + continue; + } + if (arg == "-colorattr" && argidx+1 < args.size()) { + colorattr = design->twines().add(RTLIL::escape_id(args[++argidx])); + continue; + } + if (arg == "-format" && argidx+1 < args.size()) { + format = args[++argidx]; + continue; + } + if (arg == "-wireshape" && argidx+1 < args.size()) { + flag_wireshape = args[++argidx]; + continue; + } + if (arg == "-width") { + flag_width= true; + continue; + } + if (arg == "-signed") { + flag_signed= true; + continue; + } + if (arg == "-stretch") { + flag_stretch= true; + continue; + } + if (arg == "-pause") { + flag_pause= true; + continue; + } + if (arg == "-enum") { + flag_enum = true; + flag_abbreviate = false; + continue; + } + if (arg == "-long") { + flag_enum = false; + flag_abbreviate = false; + continue; + } + if (arg == "-notitle") { + flag_notitle = true; + continue; + } + if (arg == "-nobg") { + background= ""; + continue; + } + if (arg == "-href") { + flag_href = true; + continue; + } + break; + } + extra_args(args, argidx, design); + + if (format != "ps" && format != "dot") { + int modcount = 0; + for (auto module : design->selected_modules()) { + if (module->get_blackbox_attribute()) + continue; + if (module->cells().size() == 0 && module->connections().empty()) + continue; + modcount++; + } + if (modcount > 1) + log_cmd_error("For formats different than 'ps' or 'dot' only one module must be selected.\n"); + } + + for (auto filename : libfiles) { + std::ifstream f; + rewrite_filename(filename); + f.open(filename.c_str()); + yosys_input_files.insert(filename); + if (f.fail()) + log_error("Can't open lib file `%s'.\n", filename); + auto &lib = libs.emplace_back(std::make_unique()); + Frontend::frontend_call(lib.get(), &f, filename, (filename.size() > 3 && filename.compare(filename.size()-3, std::string::npos, ".il") == 0 ? "rtlil" : "verilog")); + } + + if (libs.size() > 0) + log_header(design, "Continuing show pass.\n"); + + std::string dot_file = stringf("%s.dot", prefix); + std::string out_file = stringf("%s.%s", prefix, format.empty() ? "svg" : format); + + log("Writing dot description to `%s'.\n", dot_file); + FILE *f = fopen(dot_file.c_str(), "w"); + if (custom_prefix) + yosys_output_files.insert(dot_file); + if (f == nullptr) + log_cmd_error("Can't open dot file `%s' for writing.\n", dot_file); + ShowWorker worker(f, design, libs, colorSeed, flag_width, flag_wireshape, flag_signed, flag_stretch, flag_enum, flag_abbreviate, flag_notitle, flag_href, color_selections, label_selections, colorattr); + fclose(f); + + if (worker.page_counter == 0) + log_cmd_error("Nothing there to show.\n"); + + if (format != "dot" && !format.empty()) { + #ifdef _WIN32 + // system()/cmd.exe does not understand single quotes on Windows. + #define DOT_CMD "dot -T%s \"%s\" > \"%s.new\" && move \"%s.new\" \"%s\"" + #else + #define DOT_CMD "dot -T%s '%s' > '%s.new' && mv '%s.new' '%s'" + #endif + std::string cmd = stringf(DOT_CMD, format, dot_file, out_file, out_file, out_file); + #undef DOT_CMD + log("Exec: %s\n", cmd); + #if defined(YOSYS_ENABLE_SPAWN) + if (run_command(cmd) != 0) + log_cmd_error("Shell command failed!\n"); + #endif + } + + #if !defined(YOSYS_ENABLE_SPAWN) + log_assert(viewer_exe.empty() && !format.empty()); + #else + if (viewer_exe != "none") { + if (!viewer_exe.empty()) { + #ifdef _WIN32 + // system()/cmd.exe does not understand single quotes nor + // background tasks on Windows. So we have to pause yosys + // until the viewer exits. + std::string cmd = stringf("%s \"%s\"", viewer_exe, out_file); + #else + std::string cmd = stringf("%s '%s' %s", viewer_exe, out_file, background); + #endif + log("Exec: %s\n", cmd); + if (run_command(cmd) != 0) + log_cmd_error("Shell command failed!\n"); + } else + if (format.empty()) { + #ifdef __APPLE__ + std::string cmd = stringf("ps -fu %d | grep -q '[ ]%s' || xdot '%s' %s", getuid(), dot_file, dot_file, background); + #else + std::string cmd = stringf("{ test -f '%s.pid' && fuser -s '%s.pid' 2> /dev/null; } || ( echo $$ >&3; exec xdot '%s'; ) 3> '%s.pid' %s", dot_file, dot_file, dot_file, dot_file, background); + #endif + log("Exec: %s\n", cmd); + if (run_command(cmd) != 0) + log_cmd_error("Shell command failed!\n"); + } + } + #endif + + if (flag_pause) { + #ifdef YOSYS_ENABLE_READLINE + char *input = nullptr; + while ((input = readline("Press ENTER to continue (or type 'shell' to open a shell)> ")) != nullptr) { + if (input[strspn(input, " \t\r\n")] == 0) + break; + char *p = input + strspn(input, " \t\r\n"); + if (!strcmp(p, "shell")) { + Pass::call(design, "shell"); + break; + } + } + #else + log_cmd_error("This version of yosys is built without readline support => 'show -pause' is not available.\n"); + #endif + } + + log_pop(); + } +} ShowPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/shuffle.cc b/chips/yosys/passes/cmds/shuffle.cc new file mode 100644 index 0000000000000000000000000000000000000000..fa480f170a3307d383de500eebeed9bbc60e25f2 --- /dev/null +++ b/chips/yosys/passes/cmds/shuffle.cc @@ -0,0 +1,72 @@ +#include "kernel/yosys.h" +#include + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +// Fisher–Yates shuffle +// https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle +template +static void shuffle_vector(std::vector &vec, std::mt19937 &rng) +{ + for (size_t i = vec.size(); i > 1; i--) + std::swap(vec[i-1], vec[rng() % i]); +} + +template +static void shuffle_dict(dict &d, std::mt19937 &rng) +{ + std::vector> entries(d.begin(), d.end()); + shuffle_vector(entries, rng); + dict shuffled; + for (auto &entry : entries) + shuffled.insert(std::move(entry)); + d.swap(shuffled); +} + +struct ShufflePass : public Pass { + ShufflePass() : Pass("shuffle", "deterministically reorder design objects") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" shuffle [-seed ] [selection]\n"); + log("\n"); + log("Deterministically reorder design objects.\n"); + log("\n"); + log(" -seed \n"); + log(" use the given random number generator seed (default: 1)\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + unsigned int seed = 1; + + log_header(design, "Executing SHUFFLE pass (deterministically reorder design objects).\n"); + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) + { + if (args[argidx] == "-seed" && argidx+1 < args.size()) { + seed = std::stoul(args[++argidx]); + continue; + } + break; + } + extra_args(args, argidx, design); + + std::mt19937 rng(seed); + + for (auto module : design->selected_whole_modules_warn()) + { + log("Shuffling module %s.\n", module); + shuffle_dict(module->wires_, rng); + shuffle_dict(module->cells_, rng); + shuffle_vector(module->connections_, rng); + shuffle_dict(module->memories, rng); + shuffle_dict(module->processes, rng); + } + } +} ShufflePass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/sort.cc b/chips/yosys/passes/cmds/sort.cc new file mode 100644 index 0000000000000000000000000000000000000000..ab058880ee5fd8e7f879e1fd85d669d1a121476e --- /dev/null +++ b/chips/yosys/passes/cmds/sort.cc @@ -0,0 +1,26 @@ +#include "kernel/yosys.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct SortPass : Pass { + SortPass() : Pass("sort", "sort the design objects") {} + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" sort\n"); + log("\n"); + log("Sorts the design objects.\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *d) override + { + log_header(d, "Executing SORT pass.\n"); + if (args.size() != 1) + log_cmd_error("This pass takes no arguments.\n"); + d->sort(); + } +} SortPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/splice.cc b/chips/yosys/passes/cmds/splice.cc new file mode 100644 index 0000000000000000000000000000000000000000..416294be82570b78613c13e076aa908f7d25f75b --- /dev/null +++ b/chips/yosys/passes/cmds/splice.cc @@ -0,0 +1,365 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/register.h" +#include "kernel/celltypes.h" +#include "kernel/sigtools.h" +#include "kernel/rtlil.h" +#include "kernel/log.h" +#include + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct SpliceWorker +{ + RTLIL::Design *design; + RTLIL::Module *module; + + bool sel_by_cell; + bool sel_by_wire; + bool sel_any_bit; + bool no_outputs; + bool do_wires; + + std::set ports; + std::set no_ports; + + CellTypes ct; + SigMap sigmap; + + std::vector driven_bits; + std::map driven_bits_map; + + std::set driven_chunks; + std::map spliced_signals_cache; + std::map sliced_signals_cache; + + SpliceWorker(RTLIL::Design *design, RTLIL::Module *module) : design(design), module(module), ct(design), sigmap(module) + { + } + + RTLIL::SigSpec get_sliced_signal(RTLIL::SigSpec sig) + { + if (sig.size() == 0 || sig.is_fully_const()) + return sig; + + if (sliced_signals_cache.count(sig)) + return sliced_signals_cache.at(sig); + + int offset = 0; + int p = driven_bits_map.at(sig.extract(0, 1).as_bit()) - 1; + while (driven_bits.at(p) != RTLIL::State::Sm) + p--, offset++; + + RTLIL::SigSpec sig_a; + for (p++; driven_bits.at(p) != RTLIL::State::Sm; p++) + sig_a.append(driven_bits.at(p)); + + RTLIL::SigSpec new_sig = sig; + + if (sig_a.size() != sig.size()) { + RTLIL::Cell *cell = module->addCell(NEW_ID, ID($slice)); + cell->parameters[ID::OFFSET] = offset; + cell->parameters[ID::A_WIDTH] = sig_a.size(); + cell->parameters[ID::Y_WIDTH] = sig.size(); + cell->setPort(ID::A, sig_a); + cell->setPort(ID::Y, module->addWire(NEW_ID, sig.size())); + new_sig = cell->getPort(ID::Y); + } + + sliced_signals_cache[sig] = new_sig; + + return new_sig; + } + + RTLIL::SigSpec get_spliced_signal(RTLIL::SigSpec sig) + { + if (sig.size() == 0 || sig.is_fully_const()) + return sig; + + if (spliced_signals_cache.count(sig)) + return spliced_signals_cache.at(sig); + + int last_bit = -1; + std::vector chunks; + + for (auto &bit : sig.to_sigbit_vector()) + { + if (bit.wire == nullptr) + { + if (last_bit == 0) + chunks.back().append(bit); + else + chunks.push_back(bit); + last_bit = 0; + continue; + } + + if (driven_bits_map.count(bit)) + { + int this_bit = driven_bits_map.at(bit); + if (last_bit+1 == this_bit) + chunks.back().append(bit); + else + chunks.push_back(bit); + last_bit = this_bit; + continue; + } + + log(" Failed to generate spliced signal %s.\n", log_signal(sig)); + spliced_signals_cache[sig] = sig; + return sig; + } + + + RTLIL::SigSpec new_sig = get_sliced_signal(chunks.front()); + for (size_t i = 1; i < chunks.size(); i++) { + RTLIL::SigSpec sig2 = get_sliced_signal(chunks[i]); + RTLIL::Cell *cell = module->addCell(NEW_ID, ID($concat)); + cell->parameters[ID::A_WIDTH] = new_sig.size(); + cell->parameters[ID::B_WIDTH] = sig2.size(); + cell->setPort(ID::A, new_sig); + cell->setPort(ID::B, sig2); + cell->setPort(ID::Y, module->addWire(NEW_ID, new_sig.size() + sig2.size())); + new_sig = cell->getPort(ID::Y); + } + + spliced_signals_cache[sig] = new_sig; + + log(" Created spliced signal: %s -> %s\n", log_signal(sig), log_signal(new_sig)); + return new_sig; + } + + void run() + { + log("Splicing signals in module %s:\n", module); + + driven_bits.push_back(RTLIL::State::Sm); + driven_bits.push_back(RTLIL::State::Sm); + + for (auto wire : module->wires()) + if (wire->port_input) { + RTLIL::SigSpec sig = sigmap(wire); + driven_chunks.insert(sig); + for (auto &bit : sig.to_sigbit_vector()) + driven_bits.push_back(bit); + driven_bits.push_back(RTLIL::State::Sm); + } + + for (auto cell : module->cells()) + for (auto &conn : cell->connections()) + if (!ct.cell_known(cell->type) || ct.cell_output(cell->type, conn.first)) { + RTLIL::SigSpec sig = sigmap(conn.second); + driven_chunks.insert(sig); + for (auto &bit : sig.to_sigbit_vector()) + driven_bits.push_back(bit); + driven_bits.push_back(RTLIL::State::Sm); + } + + driven_bits.push_back(RTLIL::State::Sm); + + for (size_t i = 0; i < driven_bits.size(); i++) + driven_bits_map[driven_bits[i]] = i; + + SigPool selected_bits; + if (!sel_by_cell) + for (auto wire : module->selected_wires()) + selected_bits.add(sigmap(wire)); + + std::vector mod_cells = module->cells(); + + for (auto cell : mod_cells) { + if (!sel_by_wire && !design->selected(module, cell)) + continue; + for (auto &conn : cell->connections_) + if (ct.cell_input(cell->type, conn.first)) { + if (ports.size() > 0 && !ports.count(conn.first)) + continue; + if (no_ports.size() > 0 && no_ports.count(conn.first)) + continue; + RTLIL::SigSpec sig = sigmap(conn.second); + if (!sel_by_cell) { + if (!sel_any_bit && !selected_bits.check_all(sig)) + continue; + if (sel_any_bit && !selected_bits.check_any(sig)) + continue; + } + if (driven_chunks.count(sig) > 0) + continue; + conn.second = get_spliced_signal(sig); + } + } + + std::vector> rework_wires; + std::vector mod_wires = module->wires(); + + for (auto wire : mod_wires) + if ((!no_outputs && wire->port_output) || (do_wires && wire->name.isPublic())) { + if (!design->selected(module, wire)) + continue; + RTLIL::SigSpec sig = sigmap(wire); + if (driven_chunks.count(sig) > 0) + continue; + RTLIL::SigSpec new_sig = get_spliced_signal(sig); + if (new_sig != sig) + rework_wires.push_back(std::pair(wire, new_sig)); + } else + if (!wire->port_input) { + RTLIL::SigSpec sig = sigmap(wire); + if (spliced_signals_cache.count(sig) && spliced_signals_cache.at(sig) != sig) + rework_wires.push_back(std::pair(wire, spliced_signals_cache.at(sig))); + else if (sliced_signals_cache.count(sig) && sliced_signals_cache.at(sig) != sig) + rework_wires.push_back(std::pair(wire, sliced_signals_cache.at(sig))); + } + + for (auto &it : rework_wires) + { + RTLIL::IdString orig_name = it.first->name; + module->rename(it.first, NEW_ID); + + RTLIL::Wire *new_port = module->addWire(orig_name, it.first); + it.first->port_id = 0; + it.first->port_input = false; + it.first->port_output = false; + + module->connect(RTLIL::SigSig(new_port, it.second)); + } + } +}; + +struct SplicePass : public Pass { + SplicePass() : Pass("splice", "create explicit splicing cells") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" splice [options] [selection]\n"); + log("\n"); + log("This command adds $slice and $concat cells to the design to make the splicing\n"); + log("of multi-bit signals explicit. This for example is useful for coarse grain\n"); + log("synthesis, where dedicated hardware is needed to splice signals.\n"); + log("\n"); + log(" -sel_by_cell\n"); + log(" only select the cell ports to rewire by the cell. if the selection\n"); + log(" contains a cell, than all cell inputs are rewired, if necessary.\n"); + log("\n"); + log(" -sel_by_wire\n"); + log(" only select the cell ports to rewire by the wire. if the selection\n"); + log(" contains a wire, than all cell ports driven by this wire are wired,\n"); + log(" if necessary.\n"); + log("\n"); + log(" -sel_any_bit\n"); + log(" it is sufficient if the driver of any bit of a cell port is selected.\n"); + log(" by default all bits must be selected.\n"); + log("\n"); + log(" -wires\n"); + log(" also add $slice and $concat cells to drive otherwise unused wires.\n"); + log("\n"); + log(" -no_outputs\n"); + log(" do not rewire selected module outputs.\n"); + log("\n"); + log(" -port \n"); + log(" only rewire cell ports with the specified name. can be used multiple\n"); + log(" times. implies -no_output.\n"); + log("\n"); + log(" -no_port \n"); + log(" do not rewire cell ports with the specified name. can be used multiple\n"); + log(" times. can not be combined with -port .\n"); + log("\n"); + log("By default selected output wires and all cell ports of selected cells driven\n"); + log("by selected wires are rewired.\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + bool sel_by_cell = false; + bool sel_by_wire = false; + bool sel_any_bit = false; + bool no_outputs = false; + bool do_wires = false; + std::set ports, no_ports; + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + if (args[argidx] == "-sel_by_cell") { + sel_by_cell = true; + continue; + } + if (args[argidx] == "-sel_by_wire") { + sel_by_wire = true; + continue; + } + if (args[argidx] == "-sel_any_bit") { + sel_any_bit = true; + continue; + } + if (args[argidx] == "-wires") { + do_wires = true; + continue; + } + if (args[argidx] == "-no_outputs") { + no_outputs = true; + continue; + } + if (args[argidx] == "-port" && argidx+1 < args.size()) { + ports.insert(design->twines().add(RTLIL::escape_id(args[++argidx]))); + no_outputs = true; + continue; + } + if (args[argidx] == "-no_port" && argidx+1 < args.size()) { + no_ports.insert(design->twines().add(RTLIL::escape_id(args[++argidx]))); + continue; + } + break; + } + extra_args(args, argidx, design); + + if (sel_by_cell && sel_by_wire) + log_cmd_error("The options -sel_by_cell and -sel_by_wire are exclusive!\n"); + + if (sel_by_cell && sel_any_bit) + log_cmd_error("The options -sel_by_cell and -sel_any_bit are exclusive!\n"); + + if (!ports.empty() && !no_ports.empty()) + log_cmd_error("The options -port and -no_port are exclusive!\n"); + + log_header(design, "Executing SPLICE pass (creating cells for signal splicing).\n"); + + for (auto module : design->selected_modules()) + { + if (module->processes.size()) { + log("Skipping module %s as it contains processes.\n", module->name); + continue; + } + + SpliceWorker worker(design, module); + worker.sel_by_cell = sel_by_cell; + worker.sel_by_wire = sel_by_wire; + worker.sel_any_bit = sel_any_bit; + worker.no_outputs = no_outputs; + worker.do_wires = do_wires; + worker.ports = ports; + worker.no_ports = no_ports; + worker.run(); + } + } +} SplicePass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/splitcells.cc b/chips/yosys/passes/cmds/splitcells.cc new file mode 100644 index 0000000000000000000000000000000000000000..dfe5c51768f8f26c23173c121c6db79ba35ec0f9 --- /dev/null +++ b/chips/yosys/passes/cmds/splitcells.cc @@ -0,0 +1,269 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "kernel/sigtools.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct SplitcellsWorker +{ + Module *module; + SigMap sigmap; + dict> bit_drivers_db; + dict>> bit_users_db; + + SplitcellsWorker(Module *module) : module(module), sigmap(module) + { + for (auto cell : module->cells()) { + for (auto conn : cell->connections()) { + if (!cell->output(conn.first)) continue; + for (int i = 0; i < GetSize(conn.second); i++) { + SigBit bit(sigmap(conn.second[i])); + bit_drivers_db[bit] = tuple(cell->name, conn.first, i); + } + } + } + + for (auto cell : module->cells()) { + for (auto conn : cell->connections()) { + if (!cell->input(conn.first)) continue; + for (int i = 0; i < GetSize(conn.second); i++) { + SigBit bit(sigmap(conn.second[i])); + if (!bit_drivers_db.count(bit)) continue; + bit_users_db[bit].insert(tuple(cell->name, + conn.first, i-std::get<2>(bit_drivers_db[bit]))); + } + } + } + + for (auto wire : module->wires()) { + if (!wire->name.isPublic()) continue; + SigSpec sig(sigmap(wire)); + for (int i = 0; i < GetSize(sig); i++) { + SigBit bit(sig[i]); + if (!bit_drivers_db.count(bit)) continue; + bit_users_db[bit].insert(tuple(wire->name, + IdString::Null, i-std::get<2>(bit_drivers_db[bit]))); + } + } + } + + int split(Cell *cell, const std::string &format) + { + if (cell->type.in(ID($and), ID($mux), ID($not), ID($or), ID($pmux), ID($xnor), ID($xor))) + { + SigSpec outsig = sigmap(cell->getPort(ID::Y)); + if (GetSize(outsig) <= 1) return 0; + + std::vector slices; + slices.push_back(0); + + int width = GetSize(outsig); + width = std::min(width, GetSize(cell->getPort(ID::A))); + if (cell->hasPort(ID::B)) + width = std::min(width, GetSize(cell->getPort(ID::B))); + + for (int i = 1; i < width; i++) { + auto &last_users = bit_users_db[outsig[slices.back()]]; + auto &this_users = bit_users_db[outsig[i]]; + if (last_users != this_users) slices.push_back(i); + } + if (GetSize(slices) <= 1) return 0; + slices.push_back(GetSize(outsig)); + + log("Splitting %s cell %s/%s into %d slices:\n", cell->type.unescape(), module, cell, GetSize(slices)-1); + for (int i = 1; i < GetSize(slices); i++) + { + int slice_msb = slices[i]-1; + int slice_lsb = slices[i-1]; + + std::string s = cell->name.str() + (slice_msb == slice_lsb ? + stringf("%c%d%c", format[0], slice_lsb, format[1]) : + stringf("%c%d%c%d%c", format[0], slice_msb, format[2], slice_lsb, format[1])); + IdString slice_name = module->uniquify(std::move(s)); + + Cell *slice = module->addCell(slice_name, cell); + + auto slice_signal = [&](SigSpec old_sig) -> SigSpec { + SigSpec new_sig; + for (int offset = slice_lsb; offset < GetSize(old_sig); offset += GetSize(outsig)) { + int length = std::min(GetSize(old_sig)-offset, slice_msb-slice_lsb+1); + new_sig.append(old_sig.extract(offset, length)); + } + return new_sig; + }; + + slice->setPort(ID::A, slice_signal(slice->getPort(ID::A))); + if (slice->hasParam(ID::A_WIDTH)) + slice->setParam(ID::A_WIDTH, GetSize(slice->getPort(ID::A))); + + if (slice->hasPort(ID::B)) { + slice->setPort(ID::B, slice_signal(slice->getPort(ID::B))); + if (slice->hasParam(ID::B_WIDTH)) + slice->setParam(ID::B_WIDTH, GetSize(slice->getPort(ID::B))); + } + + slice->setPort(ID::Y, slice_signal(slice->getPort(ID::Y))); + if (slice->hasParam(ID::Y_WIDTH)) + slice->setParam(ID::Y_WIDTH, GetSize(slice->getPort(ID::Y))); + if (slice->hasParam(ID::WIDTH)) + slice->setParam(ID::WIDTH, GetSize(slice->getPort(ID::Y))); + + log(" slice %d: %s => %s\n", i, module->twines().str(slice_name), log_signal(slice->getPort(ID::Y))); + } + + module->remove(cell); + return GetSize(slices)-1; + } + + if (cell->type.in(ID($ff), ID($dff), ID($dffe), ID($dffsr), ID($dffsre), ID($adff), ID($adffe), ID($aldff), ID($aldffe), + ID($sdff), ID($sdffce), ID($sdffe), ID($dlatch), ID($dlatchsr), ID($adlatch))) + { + auto splitports = {ID::D, ID::Q, ID::AD, ID::SET, ID::CLR}; + auto splitparams = {ID::ARST_VALUE, ID::SRST_VALUE}; + + SigSpec outsig = sigmap(cell->getPort(ID::Q)); + if (GetSize(outsig) <= 1) return 0; + int width = GetSize(outsig); + + std::vector slices; + slices.push_back(0); + + for (int i = 1; i < width; i++) { + auto &last_users = bit_users_db[outsig[slices.back()]]; + auto &this_users = bit_users_db[outsig[i]]; + if (last_users != this_users) slices.push_back(i); + } + + if (GetSize(slices) <= 1) return 0; + slices.push_back(GetSize(outsig)); + + log("Splitting %s cell %s/%s into %d slices:\n", cell->type.unescape(), module, cell, GetSize(slices)-1); + for (int i = 1; i < GetSize(slices); i++) + { + int slice_msb = slices[i]-1; + int slice_lsb = slices[i-1]; + + TwinePool &twines = module->twines(); + std::string s = cell->name.str() + (slice_msb == slice_lsb ? + stringf("%c%d%c", format[0], slice_lsb, format[1]) : + stringf("%c%d%c%d%c", format[0], slice_msb, format[2], slice_lsb, format[1])); + IdString slice_name = module->uniquify(std::move(s)); + + Cell *slice = module->addCell(slice_name, cell); + + for (IdString portname : splitports) { + if (slice->hasPort(portname)) { + SigSpec sig = slice->getPort(portname); + sig = sig.extract(slice_lsb, slice_msb-slice_lsb+1); + slice->setPort(portname, sig); + } + } + + for (IdString paramname : splitparams) { + if (slice->hasParam(paramname)) { + Const val = slice->getParam(paramname); + val = val.extract(slice_lsb, slice_msb-slice_lsb+1); + slice->setParam(paramname, val); + } + } + + slice->setParam(ID::WIDTH, GetSize(slice->getPort(ID::Q))); + + log(" slice %d: %s => %s\n", i, twines.unescaped_str(slice_name), log_signal(slice->getPort(ID::Q))); + } + + module->remove(cell); + return GetSize(slices)-1; + } + + return 0; + } +}; + +struct SplitcellsPass : public Pass { + SplitcellsPass() : Pass("splitcells", "split up multi-bit cells") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" splitcells [options] [selection]\n"); + log("\n"); + log("This command splits multi-bit cells into smaller chunks, based on usage of the\n"); + log("cell output bits.\n"); + log("\n"); + log("This command operates only in cells such as $or, $and, and $mux, that are easily\n"); + log("cut into bit-slices.\n"); + log("\n"); + log(" -format char1[char2[char3]]\n"); + log(" the first char is inserted between the cell name and the bit index, the\n"); + log(" second char is appended to the cell name. e.g. -format () creates cell\n"); + log(" names like 'mycell(42)'. the 3rd character is the range separation\n"); + log(" character when creating multi-bit cells. the default is '[]:'.\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + std::string format; + + log_header(design, "Executing SPLITCELLS pass (splitting up multi-bit cells).\n"); + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) + { + if (args[argidx] == "-format" && argidx+1 < args.size()) { + format = args[++argidx]; + continue; + } + break; + } + extra_args(args, argidx, design); + + if (GetSize(format) < 1) format += "["; + if (GetSize(format) < 2) format += "]"; + if (GetSize(format) < 3) format += ":"; + + for (auto module : design->selected_modules()) + { + int count_split_pre = 0; + int count_split_post = 0; + + while (1) { + SplitcellsWorker worker(module); + bool did_something = false; + for (auto cell : module->selected_cells()) { + int n = worker.split(cell, format); + did_something |= (n != 0); + count_split_pre += (n != 0); + count_split_post += n; + } + if (!did_something) + break; + } + + if (count_split_pre) + log("Split %d cells in module %s into %d cell slices.\n", + count_split_pre, module, count_split_post); + } + } +} SplitnetsPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/splitnets.cc b/chips/yosys/passes/cmds/splitnets.cc new file mode 100644 index 0000000000000000000000000000000000000000..d61a99ec049e6463308f2f32f2733ed2529d833e --- /dev/null +++ b/chips/yosys/passes/cmds/splitnets.cc @@ -0,0 +1,291 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/register.h" +#include "kernel/celltypes.h" +#include "kernel/rtlil.h" +#include "kernel/log.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct SplitnetsWorker +{ + std::map> splitmap; + + void append_wire(RTLIL::Module *module, RTLIL::Wire *wire, int offset, int width, std::string format) + { + std::string new_wire_name = wire->name.str(); + + if (format.size() > 0) + new_wire_name += format.substr(0, 1); + + if (width > 1) { + if (wire->upto) + new_wire_name += stringf("%d", wire->start_offset+wire->width-(offset+width)-1); + else + new_wire_name += stringf("%d", wire->start_offset+offset+width-1); + if (format.size() > 2) + new_wire_name += format.substr(2, 1); + else + new_wire_name += ":"; + } + + if (wire->upto) + new_wire_name += stringf("%d", wire->start_offset+wire->width-offset-1); + else + new_wire_name += stringf("%d", wire->start_offset+offset); + + if (format.size() > 1) + new_wire_name += format.substr(1, 1); + + RTLIL::Wire *new_wire = module->addWire(module->uniquify(new_wire_name), width); + new_wire->port_id = wire->port_id ? wire->port_id + offset : 0; + new_wire->port_input = wire->port_input; + new_wire->port_output = wire->port_output; + new_wire->start_offset = wire->start_offset + offset; + + auto it = wire->attributes.find(ID::src); + if (it != wire->attributes.end()) + new_wire->attributes.emplace(ID::src, it->second); + + it = wire->attributes.find(ID::hdlname); + if (it != wire->attributes.end()) + new_wire->attributes.emplace(ID::hdlname, it->second); + + it = wire->attributes.find(ID::keep); + if (it != wire->attributes.end()) + new_wire->attributes.emplace(ID::keep, it->second); + + it = wire->attributes.find(ID::init); + if (it != wire->attributes.end()) { + Const old_init = it->second; + RTLIL::Const::Builder new_init_bits_builder(width); + for (int i = offset; i < offset+width; i++) + new_init_bits_builder.push_back(i < GetSize(old_init) ? old_init.at(i) : State::Sx); + new_wire->attributes.emplace(ID::init, new_init_bits_builder.build()); + } + + std::vector sigvec = RTLIL::SigSpec(new_wire).to_sigbit_vector(); + splitmap[wire].insert(splitmap[wire].end(), sigvec.begin(), sigvec.end()); + } + + void operator()(RTLIL::SigSpec &sig) + { + for (auto &bit : sig) + if (splitmap.count(bit.wire) > 0) + bit = splitmap.at(bit.wire).at(bit.offset); + } +}; + +struct SplitnetsPass : public Pass { + SplitnetsPass() : Pass("splitnets", "split up multi-bit nets") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" splitnets [options] [selection]\n"); + log("\n"); + log("This command splits multi-bit nets into single-bit nets.\n"); + log("\n"); + log(" -format char1[char2[char3]]\n"); + log(" the first char is inserted between the net name and the bit index, the\n"); + log(" second char is appended to the netname. e.g. -format () creates net\n"); + log(" names like 'mysignal(42)'. the 3rd character is the range separation\n"); + log(" character when creating multi-bit wires. the default is '[]:'.\n"); + log("\n"); + log(" -ports\n"); + log(" also split module ports. per default only internal signals are split.\n"); + log("\n"); + log(" -driver\n"); + log(" don't blindly split nets in individual bits. instead look at the driver\n"); + log(" and split nets so that no driver drives only part of a net.\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + bool flag_ports = false; + bool flag_driver = false; + std::string format = "[]:"; + + log_header(design, "Executing SPLITNETS pass (splitting up multi-bit signals).\n"); + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) + { + if (args[argidx] == "-format" && argidx+1 < args.size()) { + format = args[++argidx]; + continue; + } + if (args[argidx] == "-ports") { + flag_ports = true; + continue; + } + if (args[argidx] == "-driver") { + flag_driver = true; + continue; + } + break; + } + extra_args(args, argidx, design); + + // module_ports_db[module_name][old_port_name] = new_port_name_list + dict>> module_ports_db; + + for (auto module : design->selected_modules()) + { + if (module->has_processes_warn()) + continue; + + SplitnetsWorker worker; + + if (flag_ports) + { + int normalized_port_factor = 0; + + for (auto wire : module->wires()) + if (wire->port_id != 0) { + normalized_port_factor = max(normalized_port_factor, wire->port_id+1); + normalized_port_factor = max(normalized_port_factor, GetSize(wire)+1); + } + + for (auto wire : module->wires()) + wire->port_id *= normalized_port_factor; + } + + if (flag_driver) + { + CellTypes ct(design); + + std::map> split_wires_at; + + for (auto c : module->cells()) + for (auto &p : c->connections()) + { + if (!ct.cell_known(c->type)) + continue; + if (!ct.cell_output(c->type, p.first)) + continue; + + RTLIL::SigSpec sig = p.second; + for (auto &chunk : sig.chunks()) { + if (chunk.wire == NULL) + continue; + if (chunk.wire->port_id == 0 || flag_ports) { + if (chunk.offset != 0) + split_wires_at[chunk.wire].insert(chunk.offset); + if (chunk.offset + chunk.width < chunk.wire->width) + split_wires_at[chunk.wire].insert(chunk.offset + chunk.width); + } + } + } + + for (auto &it : split_wires_at) { + int cursor = 0; + for (int next_cursor : it.second) { + worker.append_wire(module, it.first, cursor, next_cursor - cursor, format); + cursor = next_cursor; + } + worker.append_wire(module, it.first, cursor, it.first->width - cursor, format); + } + } + else + { + for (auto wire : module->wires()) { + if (((wire->width > 1) || (wire->has_attribute(ID::single_bit_vector))) + && (wire->port_id == 0 || flag_ports) + && design->selected(module, wire)) { + wire->attributes.erase(ID::single_bit_vector); + worker.splitmap[wire] = std::vector(); + } + } + + for (auto &it : worker.splitmap) + for (int i = 0; i < it.first->width; i++) + worker.append_wire(module, it.first, i, 1, format); + } + + module->rewrite_sigspecs(worker); + + if (flag_ports) + { + for (auto wire : module->wires()) + { + if (wire->port_id == 0) + continue; + + SigSpec sig(wire); + worker(sig); + + if (sig == wire) + continue; + + vector &new_ports = module_ports_db[module->name][wire->name]; + + for (SigSpec c : sig.chunks()) + new_ports.push_back(c.as_wire()->name); + } + } + + pool delete_wires; + for (auto &it : worker.splitmap) + delete_wires.insert(it.first); + module->remove(delete_wires); + + if (flag_ports) + module->fixup_ports(); + } + + if (!module_ports_db.empty()) + { + for (auto module : design->modules()) + for (auto cell : module->cells()) + { + if (module_ports_db.count(cell->type) == 0) + continue; + + for (auto &it : module_ports_db.at(cell->type)) + { + IdString port_id = it.first; + const auto &new_port_ids = it.second; + + if (!cell->hasPort(port_id)) + continue; + + int offset = 0; + SigSpec sig = cell->getPort(port_id); + + for (auto nid : new_port_ids) + { + int nlen = GetSize(design->module(cell->type)->wire(nid)); + if (offset + nlen > GetSize(sig)) + nlen = GetSize(sig) - offset; + if (nlen > 0) + cell->setPort(nid, sig.extract(offset, nlen)); + offset += nlen; + } + + cell->unsetPort(port_id); + } + } + } + } +} SplitnetsPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/sta.cc b/chips/yosys/passes/cmds/sta.cc new file mode 100644 index 0000000000000000000000000000000000000000..a227fa45a2c6061e60f78b927951434d9ce55910 --- /dev/null +++ b/chips/yosys/passes/cmds/sta.cc @@ -0,0 +1,321 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Clifford Wolf + * (C) 2019 Eddie Hung + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "kernel/sigtools.h" +#include "kernel/timinginfo.h" +#include "kernel/log_help.h" +#include + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct StaWorker +{ + Design *design; + Module *module; + SigMap sigmap; + + struct t_data { + Cell* driver; + IdString dst_port, src_port; + vector> fanouts; + SigBit backtrack; + t_data() : driver(nullptr) {} + }; + dict data; + std::deque queue; + struct t_endpoint { + Cell *sink; + IdString port; + int required; + t_endpoint() : sink(nullptr), required(0) {} + }; + dict endpoints; + + int maxarrival; + SigBit maxbit; + + pool driven; + + StaWorker(RTLIL::Module *module) : design(module->design), module(module), sigmap(module), maxarrival(0) + { + TimingInfo timing; + + pool unrecognised_cells; + + for (auto cell : module->cells()) + { + Module *inst_module = design->module(cell->type); + if (!inst_module) { + if (unrecognised_cells.insert(cell->type).second) + log_warning("Cell type '%s' not recognised! Ignoring.\n", cell->type.unescape()); + continue; + } + + if (!inst_module->get_blackbox_attribute()) { + log_warning("Cell type '%s' is not a black- nor white-box! Ignoring.\n", cell->type.unescape()); + continue; + } + + IdString derived_type = inst_module->derive(design, cell->parameters); + inst_module = design->module(derived_type); + log_assert(inst_module); + + if (!timing.count(derived_type)) { + auto &t = timing.setup_module(inst_module); + if (t.has_inputs && t.comb.empty() && t.arrival.empty() && t.required.empty()) + log_warning("Module '%s' has no timing arcs!\n", cell->type.unescape()); + } + + auto &t = timing.at(derived_type); + if (t.comb.empty() && t.arrival.empty() && t.required.empty()) + continue; + + pool> src_bits, dst_bits; + + for (auto &conn : cell->connections()) { + auto rhs = sigmap(conn.second); + for (auto i = 0; i < GetSize(rhs); i++) { + const auto &bit = rhs[i]; + if (!bit.wire) + continue; + TimingInfo::NameBit namebit(conn.first,i); + if (cell->input(conn.first)) { + src_bits.insert(std::make_pair(bit,namebit)); + + auto it = t.required.find(namebit); + if (it == t.required.end()) + continue; + auto r = endpoints.insert(bit); + if (r.second || r.first->second.required < it->second.first) { + r.first->second.sink = cell; + r.first->second.port = conn.first; + r.first->second.required = it->second.first; + } + } + if (cell->output(conn.first)) { + dst_bits.insert(std::make_pair(bit,namebit)); + auto &d = data[bit]; + d.driver = cell; + d.dst_port = conn.first; + driven.insert(bit); + + auto it = t.arrival.find(namebit); + if (it == t.arrival.end()) + continue; + const auto &s = it->second.second; + if (cell->hasPort(s.name)) { + auto s_bit = sigmap(cell->getPort(s.name)[s.offset]); + if (s_bit.wire) + data[s_bit].fanouts.emplace_back(bit,it->second.first,s.name); + } + } + } + } + + for (const auto &s : src_bits) + for (const auto &d : dst_bits) { + auto it = t.comb.find(TimingInfo::BitBit(s.second,d.second)); + if (it == t.comb.end()) + continue; + data[s.first].fanouts.emplace_back(d.first,it->second,s.second.name); + } + } + + for (auto port_name : module->ports) { + auto wire = module->wire(port_name); + if (wire->port_input) { + for (const auto &b : sigmap(wire)) { + queue.emplace_back(b); + driven.insert(b); + } + // All primary inputs to arrive at time zero + wire->set_intvec_attribute(ID::sta_arrival, std::vector(GetSize(wire), 0)); + } + if (wire->port_output) + for (const auto &b : sigmap(wire)) + if (b.wire) + endpoints.insert(b); + } + } + + void run() + { + while (!queue.empty()) { + auto b = queue.front(); + queue.pop_front(); + auto it = data.find(b); + if (it == data.end()) + continue; + const auto& src_arrivals = b.wire->get_intvec_attribute(ID::sta_arrival); + log_assert(GetSize(src_arrivals) == GetSize(b.wire)); + auto src_arrival = src_arrivals[b.offset]; + for (const auto &d : it->second.fanouts) { + const auto &dst_bit = std::get<0>(d); + auto dst_arrivals = dst_bit.wire->get_intvec_attribute(ID::sta_arrival); + if (dst_arrivals.empty()) + dst_arrivals = std::vector(GetSize(dst_bit.wire), -1); + else + log_assert(GetSize(dst_arrivals) == GetSize(dst_bit.wire)); + auto &dst_arrival = dst_arrivals[dst_bit.offset]; + auto new_arrival = src_arrival + std::get<1>(d); + if (dst_arrival < new_arrival) { + auto dst_wire = dst_bit.wire; + dst_arrival = std::max(dst_arrival, new_arrival); + dst_wire->set_intvec_attribute(ID::sta_arrival, dst_arrivals); + queue.emplace_back(dst_bit); + + data[dst_bit].backtrack = b; + data[dst_bit].src_port = std::get<2>(d); + + auto it = endpoints.find(dst_bit); + if (it != endpoints.end()) + new_arrival += it->second.required; + if (new_arrival > maxarrival && driven.count(b)) { + maxarrival = new_arrival; + maxbit = dst_bit; + } + } + } + } + + auto b = maxbit; + if (b == SigBit()) { + log("No timing paths found.\n"); + return; + } + + log("Latest arrival time in '%s' is %d:\n", module, maxarrival); + auto it = endpoints.find(maxbit); + if (it != endpoints.end() && it->second.sink) + log(" %6d %s (%s.%s)\n", maxarrival, it->second.sink, it->second.sink->type.unescape(), PooledName(it->second.sink->module, it->second.port).unescape()); + else { + log(" %6d (%s)\n", maxarrival, b.wire->port_output ? "" : ""); + if (!b.wire->port_output) + log_warning("Critical-path does not terminate in a recognised endpoint.\n"); + } + auto jt = data.find(b); + while (jt != data.end()) { + int arrival = b.wire->get_intvec_attribute(ID::sta_arrival)[b.offset]; + if (jt->second.driver) { + log(" %s\n", log_signal(b)); + log(" %6d %s (%s.%s->%s)\n", arrival, jt->second.driver, jt->second.driver->type.unescape(), PooledName(jt->second.driver->module, jt->second.src_port).unescape(), PooledName(jt->second.driver->module, jt->second.dst_port).unescape()); + } + else if (b.wire->port_input) + log(" %6d %s (%s)\n", arrival, log_signal(b), ""); + else + log_abort(); + b = jt->second.backtrack; + jt = data.find(b); + } + + std::map arrival_histogram; + for (const auto &i : endpoints) { + const auto &b = i.first; + if (!driven.count(b)) + continue; + + if (!b.wire->attributes.count(ID::sta_arrival)) { + log_warning("Endpoint %s.%s has no (* sta_arrival *) value.\n", module, log_signal(b)); + continue; + } + + auto arrival = b.wire->get_intvec_attribute(ID::sta_arrival)[b.offset]; + if (arrival < 0) { + log_warning("Endpoint %s.%s has no (* sta_arrival *) value.\n", module, log_signal(b)); + continue; + } + arrival += i.second.required; + arrival_histogram[arrival]++; + } + // Adapted from https://github.com/YosysHQ/nextpnr/blob/affb12cc27ebf409eade062c4c59bb98569d8147/common/timing.cc#L946-L969 + if (arrival_histogram.size() > 0) { + unsigned num_bins = 20; + unsigned bar_width = 60; + auto min_arrival = arrival_histogram.begin()->first; + auto max_arrival = arrival_histogram.rbegin()->first; + auto bin_size = std::max(1, ceil((max_arrival - min_arrival + 1) / float(num_bins))); + std::vector bins(num_bins); + unsigned max_freq = 0; + for (const auto &i : arrival_histogram) { + auto &bin = bins[(i.first - min_arrival) / bin_size]; + bin += i.second; + max_freq = std::max(max_freq, bin); + } + bar_width = std::min(bar_width, max_freq); + + log("\n"); + log("Arrival histogram:\n"); + log(" legend: * represents %d endpoint(s)\n", max_freq / bar_width); + log(" + represents [1,%d) endpoint(s)\n", max_freq / bar_width); + for (int i = num_bins-1; i >= 0; --i) + log("(%6d, %6d] |%s%c\n", min_arrival + bin_size * (i + 1), min_arrival + bin_size * i, + std::string(bins[i] * bar_width / max_freq, '*'), + (bins[i] * bar_width) % max_freq > 0 ? '+' : ' '); + } + } +}; + +struct StaPass : public Pass { + StaPass() : Pass("sta", "perform static timing analysis") { } + bool formatted_help() override { + auto *help = PrettyHelp::get_current(); + help->set_group("passes/status"); + return false; + } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" sta [options] [selection]\n"); + log("\n"); + log("This command performs static timing analysis on the design. (Only considers\n"); + log("paths within a single module, so the design must be flattened.)\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + log_header(design, "Executing STA pass (static timing analysis).\n"); + + /* + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + if (args[argidx] == "-TODO") { + continue; + } + break; + } + */ + + extra_args(args, 1, design); + + for (Module *module : design->selected_modules()) + { + if (module->has_processes_warn()) + continue; + + StaWorker worker(module); + worker.run(); + } + } +} StaPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/stat.cc b/chips/yosys/passes/cmds/stat.cc new file mode 100644 index 0000000000000000000000000000000000000000..31382840d98ee8655328a83e25d3a891ed9255ff --- /dev/null +++ b/chips/yosys/passes/cmds/stat.cc @@ -0,0 +1,1080 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include + +#include "kernel/celltypes.h" +#include "kernel/cost.h" +#include "kernel/gzip.h" +#include "kernel/log_help.h" +#include "kernel/rtlil.h" +#include "kernel/yosys.h" +#include "libs/json11/json11.hpp" +#include "passes/techmap/libparse.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct cell_area_t { + double area; + bool is_sequential; + vector single_parameter_area; + vector> double_parameter_area; + vector parameter_names; +}; + +struct statdata_t { +#define STAT_INT_MEMBERS \ + X(num_wires) \ + X(num_wire_bits) \ + X(num_pub_wires) X(num_pub_wire_bits) X(num_ports) X(num_port_bits) X(num_memories) X(num_memory_bits) X(num_cells) X(num_processes) + +#define STAT_NUMERIC_MEMBERS STAT_INT_MEMBERS X(area) X(sequential_area) + +#define X(_name) unsigned int _name; + STAT_INT_MEMBERS +#undef X +#define X(_name) unsigned int local_##_name; + STAT_INT_MEMBERS +#undef X + double area = 0; + double sequential_area = 0; + double local_area = 0; + double local_sequential_area = 0; + double submodule_area = 0; + int num_submodules = 0; + std::map num_submodules_by_type; + std::map submodules_area_by_type; + + std::map local_num_cells_by_type; + std::map local_area_cells_by_type; + std::map local_seq_area_cells_by_type; + string tech; + + std::map num_cells_by_type_raw; + std::map num_cells_by_type; + std::map area_cells_by_type; + std::map seq_area_cells_by_type; + std::set unknown_cell_area; + + statdata_t operator+(const statdata_t &other) const + { + statdata_t sum = other; +#define X(_name) sum._name += _name; + STAT_NUMERIC_MEMBERS +#undef X + for (auto &it : num_cells_by_type) + sum.num_cells_by_type[it.first] += it.second; + for (auto &it : num_cells_by_type_raw) + sum.num_cells_by_type_raw[it.first] += it.second; + return sum; + } + statdata_t operator*(unsigned int other) const + { + statdata_t sum = *this; +#define X(_name) sum._name *= other; + STAT_NUMERIC_MEMBERS +#undef X + for (auto &it : sum.num_cells_by_type_raw) + it.second *= other; + for (auto &it : sum.num_cells_by_type) + it.second *= other; + return sum; + } + statdata_t add(const statdata_t &other) + { +#define X(_name) _name += other._name; + STAT_NUMERIC_MEMBERS +#undef X + for (auto &it : other.num_cells_by_type) { + if (num_cells_by_type.count(it.first)) + num_cells_by_type[it.first] += it.second; + else + num_cells_by_type[it.first] = it.second; + } + for (auto &it : other.num_cells_by_type_raw) { + if (num_cells_by_type_raw.count(it.first)) + num_cells_by_type_raw[it.first] += it.second; + else + num_cells_by_type_raw[it.first] = it.second; + } + for (auto &it : other.submodules_area_by_type) { + if (submodules_area_by_type.count(it.first)) + submodules_area_by_type[it.first] += it.second; + else + submodules_area_by_type[it.first] = it.second; + } + for (auto &it : other.area_cells_by_type) { + if (area_cells_by_type.count(it.first)) + area_cells_by_type[it.first] += it.second; + else + area_cells_by_type[it.first] = it.second; + } + for (auto &it : other.seq_area_cells_by_type) { + if (seq_area_cells_by_type.count(it.first)) + seq_area_cells_by_type[it.first] += it.second; + else + seq_area_cells_by_type[it.first] = it.second; + } + unknown_cell_area.insert(other.unknown_cell_area.begin(), other.unknown_cell_area.end()); + return *this; + } + + statdata_t() + { +#define X(_name) _name = 0; + STAT_NUMERIC_MEMBERS +#undef X + } + + statdata_t(cell_area_t &cell_data, string techname) + { + tech = techname; + area = cell_data.area; + if (cell_data.is_sequential) { + sequential_area = cell_data.area; + } + } + + statdata_t(RTLIL::Design *design, const RTLIL::Module *mod, bool width_mode, dict &cell_area, string techname) + { + tech = techname; + +#define X(_name) _name = 0; + STAT_NUMERIC_MEMBERS +#undef X +#define X(_name) local_##_name = 0; + STAT_NUMERIC_MEMBERS +#undef X + // additional_cell_area + + for (auto wire : mod->selected_wires()) { + if (wire->port_input || wire->port_output) { + num_ports++; + local_num_ports++; + num_port_bits += wire->width; + local_num_port_bits += wire->width; + } + + if (wire->name.isPublic()) { + num_pub_wires++; + local_num_pub_wires++; + num_pub_wire_bits += wire->width; + local_num_pub_wire_bits += wire->width; + } + + num_wires++; + local_num_wires++; + num_wire_bits += wire->width; + local_num_wire_bits += wire->width; + } + + for (auto &it : mod->memories) { + if (!design->selected(mod, it.second)) + continue; + num_memories++; + local_num_memories++; + num_memory_bits += it.second->width * it.second->size; + local_num_memory_bits += it.second->width * it.second->size; + } + for (auto cell : mod->selected_cells()) { + std::string cell_type = cell->type.str(); + if (width_mode) { + if (cell->type.in(ID($not), ID($pos), ID($neg), ID($logic_not), ID($logic_and), ID($logic_or), ID($reduce_and), + ID($reduce_or), ID($reduce_xor), ID($reduce_xnor), ID($reduce_bool), ID($lut), ID($and), ID($or), + ID($xor), ID($xnor), ID($shl), ID($shr), ID($sshl), ID($sshr), ID($shift), ID($shiftx), ID($lt), + ID($le), ID($eq), ID($ne), ID($eqx), ID($nex), ID($ge), ID($gt), ID($add), ID($sub), ID($mul), + ID($div), ID($mod), ID($divfloor), ID($modfloor), ID($pow), ID($alu))) { + int width_a = cell->hasPort(ID::A) ? GetSize(cell->getPort(ID::A)) : 0; + int width_b = cell->hasPort(ID::B) ? GetSize(cell->getPort(ID::B)) : 0; + int width_y = cell->hasPort(ID::Y) ? GetSize(cell->getPort(ID::Y)) : 0; + cell_type = stringf("%s_%d", cell_type, max({width_a, width_b, width_y})); + } else if (cell->type.in(ID($mux))) + cell_type = stringf("%s_%d", cell_type, GetSize(cell->getPort(ID::Y))); + else if (cell->type.in(ID($bmux), ID($pmux))) + cell_type = + stringf("%s_%d_%d", cell_type, GetSize(cell->getPort(ID::Y)), GetSize(cell->getPort(ID::S))); + else if (cell->type == ID($demux)) + cell_type = + stringf("%s_%d_%d", cell_type, GetSize(cell->getPort(ID::A)), GetSize(cell->getPort(ID::S))); + else if (cell->type.in(ID($sr), ID($ff), ID($dff), ID($dffe), ID($dffsr), ID($dffsre), ID($adff), ID($adffe), + ID($sdff), ID($sdffe), ID($sdffce), ID($aldff), ID($aldffe), ID($dlatch), ID($adlatch), + ID($dlatchsr))) + cell_type = stringf("%s_%d", cell_type, GetSize(cell->getPort(ID::Q))); + } + + if (!cell_area.empty()) { + // check if cell_area provides a area calculator + if (cell_area.count(cell->type)) { + cell_area_t cell_data = cell_area.at(cell->type); + if (cell_data.single_parameter_area.size() > 0) { + // assume that we just take the max of the A,B,Y ports + + int width_a = cell->hasPort(ID::A) ? GetSize(cell->getPort(ID::A)) : 0; + int width_b = cell->hasPort(ID::B) ? GetSize(cell->getPort(ID::B)) : 0; + int width_y = cell->hasPort(ID::Y) ? GetSize(cell->getPort(ID::Y)) : 0; + int width_q = cell->hasPort(ID::Q) ? GetSize(cell->getPort(ID::Q)) : 0; + int max_width = max({width_a, width_b, width_y, width_q}); + if (!cell_area.count(cell_type)) { + cell_area[cell_type] = cell_data; + } + if (cell_data.single_parameter_area.size() > max_width - 1u) { + cell_area.at(cell_type).area = cell_data.single_parameter_area.at(max_width - 1); + cell_area.at(cell_type).is_sequential = cell_data.is_sequential; + + } else { + log_warning("too small single_parameter_area %s width: %d size: %d\n", cell_type, max_width, + (int)cell_data.single_parameter_area.size()); + cell_area.at(cell_type).area = cell_data.single_parameter_area.back(); + cell_area.at(cell_type).is_sequential = cell_data.is_sequential; + } + } + vector widths; + if (cell_data.parameter_names.size() > 0) { + for (auto &it : cell_data.parameter_names) { + RTLIL::IdString port_name; + if (it == "A") { + port_name = ID::A; + } else if (it == "B") { + port_name = ID::B; + } else if (it == "Y") { + port_name = ID::Y; + } else if (it == "Q") { + port_name = ID::Q; + } else if (it == "S") { + port_name = ID::S; + } else { + port_name = design->twines().add(it); + } + if (cell->hasPort(port_name)) { + int width = GetSize(cell->getPort(port_name)); + widths.push_back(width); + } else { + widths.push_back(0); + } + } + } + + if (cell_data.double_parameter_area.size() > 0) { + if (!cell_area.count(cell_type)) { + cell_area[cell_type] = cell_data; + } + if (widths.size() == 2) { + unsigned int width_a = widths.at(0); + unsigned int width_b = widths.at(1); + if (width_a > 0 && width_b > 0) { + if (cell_data.double_parameter_area.size() > width_a - 1 && + cell_data.double_parameter_area.at(width_a - 1).size() > width_b - 1) { + cell_area.at(cell_type).area = + cell_data.double_parameter_area.at(width_a - 1).at(width_b - 1); + cell_area.at(cell_type).is_sequential = cell_data.is_sequential; + } else { + log_warning("too small double_parameter_area %s, width_a: %d, width_b: %d, size_a: %d, size_b: %d\n", cell_type, + width_a, width_b, (int)cell_data.double_parameter_area.size(), + (int)cell_data.double_parameter_area.at(width_a - 1).size()); + cell_area.at(cell_type).area = cell_data.double_parameter_area.back().back(); + cell_area.at(cell_type).is_sequential = cell_data.is_sequential; + } + } else { + cell_area.at(cell_type).area = cell_data.area; + cell_area.at(cell_type).is_sequential = cell_data.is_sequential; + } + } else { + log_error("double_parameter_area for %s has %d parameters, but only 2 are expected.\n", cell_type, + (int)cell_data.double_parameter_area.size()); + } + } + } + + if (cell_area.count(cell_type)) { + cell_area_t cell_data = cell_area.at(cell_type); + if (cell_data.is_sequential) { + sequential_area += cell_data.area; + local_sequential_area += cell_data.area; + } + area += cell_data.area; + num_cells++; + num_cells_by_type[cell_type]++; + area_cells_by_type[cell_type] += cell_data.area; + seq_area_cells_by_type[cell_type] += cell_data.is_sequential ? cell_data.area : 0; + local_area_cells_by_type[cell_type] += cell_data.area; + local_seq_area_cells_by_type[cell_type] += cell_data.is_sequential ? cell_data.area : 0; + local_area += cell_data.area; + local_num_cells++; + local_num_cells_by_type[cell_type]++; + + } else { + unknown_cell_area.insert(cell_type); + num_cells++; + num_cells_by_type_raw[cell->type]++; + num_cells_by_type[cell_type]++; + local_num_cells++; + local_num_cells_by_type[cell_type]++; + area_cells_by_type[cell_type] = 0; + seq_area_cells_by_type[cell_type] = 0; + local_area_cells_by_type[cell_type] = 0; + local_seq_area_cells_by_type[cell_type] = 0; + } + } else { + num_cells++; + num_cells_by_type_raw[cell->type]++; + num_cells_by_type[cell_type]++; + area_cells_by_type[cell_type] = 0; + seq_area_cells_by_type[cell_type] = 0; + local_num_cells++; + local_num_cells_by_type[cell_type]++; + local_area_cells_by_type[cell_type] = 0; + local_seq_area_cells_by_type[cell_type] = 0; + } + } + + for (auto &it : mod->processes) { + if (!design->selected(mod, it.second)) + continue; + num_processes++; + local_num_processes++; + } + } + + unsigned int estimate_xilinx_lc() + { + unsigned int lut6_cnt = num_cells_by_type[ID::str(ID::LUT6)]; + unsigned int lut5_cnt = num_cells_by_type[ID::str(ID::LUT5)]; + unsigned int lut4_cnt = num_cells_by_type[ID::str(ID::LUT4)]; + unsigned int lut3_cnt = num_cells_by_type[ID::str(ID::LUT3)]; + unsigned int lut2_cnt = num_cells_by_type[ID::str(ID::LUT2)]; + unsigned int lut1_cnt = num_cells_by_type[ID::str(ID::LUT1)]; + unsigned int lc_cnt = 0; + + lc_cnt += lut6_cnt; + + lc_cnt += lut5_cnt; + if (lut1_cnt) { + int cnt = std::min(lut5_cnt, lut1_cnt); + lut5_cnt -= cnt; + lut1_cnt -= cnt; + } + + lc_cnt += lut4_cnt; + if (lut1_cnt) { + int cnt = std::min(lut4_cnt, lut1_cnt); + lut4_cnt -= cnt; + lut1_cnt -= cnt; + } + if (lut2_cnt) { + int cnt = std::min(lut4_cnt, lut2_cnt); + lut4_cnt -= cnt; + lut2_cnt -= cnt; + } + + lc_cnt += lut3_cnt; + if (lut1_cnt) { + int cnt = std::min(lut3_cnt, lut1_cnt); + lut3_cnt -= cnt; + lut1_cnt -= cnt; + } + if (lut2_cnt) { + int cnt = std::min(lut3_cnt, lut2_cnt); + lut3_cnt -= cnt; + lut2_cnt -= cnt; + } + if (lut3_cnt) { + int cnt = (lut3_cnt + 1) / 2; + lut3_cnt -= cnt; + } + + lc_cnt += (lut2_cnt + lut1_cnt + 1) / 2; + + return lc_cnt; + } + + unsigned int cmos_transistor_count(bool *tran_cnt_exact) + { + unsigned int tran_cnt = 0; + auto &gate_costs = CellCosts::cmos_gate_cost(); + + for (auto it : num_cells_by_type_raw) { + auto ctype = it.first; + auto cnum = it.second; + + if (gate_costs.count(ctype)) + tran_cnt += cnum * gate_costs.at(ctype); + else + *tran_cnt_exact = false; + } + + return tran_cnt; + } + + /* + format a floating point value to a of 8 characters, with at most 7 digits or scientific notation + uses - to mark zero or very small values + */ + std::string f_val(double value) + { + if (std::abs(value) < 1e-12) + return " -"; + + char buf[16]; + + int len = snprintf(buf, sizeof(buf), "%.3f", value); + + while (len > 0 && buf[len - 1] == '0') + --len; + if (len > 0 && buf[len - 1] == '.') + --len; + buf[len] = '\0'; + + if (len <= 7) { + return std::string(8 - len, ' ') + std::string(buf); + } + + // use scientific notation, this should always fit in 8 characters + snprintf(buf, sizeof(buf), "%8.3G", value); + + return std::string(buf); + } + + void print_log_line(const std::string &name, unsigned int count_local, double area_local, unsigned int count_global, double area_global, + int spacer = 0, bool print_area = true, bool print_hierarchical = true, bool print_global_only = false) + { + const std::string indent(2 * spacer, ' '); + + std::string count_local_str = f_val(static_cast(count_local)); + std::string count_global_str = f_val(static_cast(count_global)); + std::string area_local_str = f_val(area_local); + std::string area_global_str = f_val(area_global); + + if (print_area) { + if (print_hierarchical) { + log(" %s %s %s %s %s%s\n", count_global_str, area_global_str, count_local_str, + area_local_str, indent, name); + } else if (print_global_only) { + log(" %s %s %s%s\n", count_global_str, area_global_str, indent, name); + } else { + if (count_local > 0) + log(" %s %s %s%s\n", count_local_str, area_local_str, indent, name); + } + } else { + if (print_hierarchical) { + log(" %s %s %s%s\n", count_global_str, count_local_str, indent, name); + } else if (print_global_only) { + log(" %s %s%s\n", count_global_str, indent, name); + } else { + if (count_local > 0) + log(" %s %s%s\n", count_local_str, indent, name); + } + } + } + + void print_log_header(bool print_area = true, bool print_hierarchical = true, bool print_global_only = false) + { + if (print_area) { + if (print_hierarchical) { + log(" %8s-%8s-%8s-%8s-%s\n", "+", "--------", "--------", "--------", "Count including submodules."); + log(" %8s %8s-%8s-%8s-%s\n", "|", "+", "--------", "--------", "Area including submodules."); + log(" %8s %8s %8s-%8s-%s\n", "|", "|", "+", "--------", "Local count, excluding submodules."); + log(" %8s %8s %8s %8s-%s\n", "|", "|", "|", "+", "Local area, excluding submodules."); + log(" %8s %8s %8s %8s \n", "|", "|", "|", "|"); + } else if (print_global_only) { + log(" %8s-%8s-%s\n", "+", "--------", "Count including submodules."); + log(" %8s %8s-%s\n", "|", "+", "Area including submodules."); + log(" %8s %8s \n", "|", "|"); + } else { + log(" %8s-%8s-%s\n", "+", "--------", "Local Count, excluding submodules."); + log(" %8s %8s-%s\n", "|", "+", "Local Area, excluding submodules."); + log(" %8s %8s \n", "|", "|"); + } + } else { + if (print_hierarchical) { + log(" %8s-%8s-%8s-%s\n", "+", "--------", "--------", "Count including submodules."); + log(" %8s %8s-%8s-%s\n", "|", "+", "--------", "Local count, excluding submodules."); + log(" %8s %8s \n", "|", "|"); + } else if (print_global_only) { + log(" %8s-%8s-%s\n", "+", "--------", "Count including submodules."); + log(" %8s \n", "|"); + } else { + log(" %8s-%8s-%s\n", "+", "--------", "Local Count, excluding submodules."); + log(" %8s \n", "|"); + } + } + } + + void log_data(const std::string &mod_name, bool top_mod, bool print_area = true, bool print_hierarchical = true, bool print_global_only = false) + { + + print_log_header(print_area, print_hierarchical, print_global_only); + + print_log_line("wires", local_num_wires, 0, num_wires, 0, 0, print_area, print_hierarchical, print_global_only); + print_log_line("wire bits", local_num_wire_bits, 0, num_wire_bits, 0, 0, print_area, print_hierarchical, print_global_only); + print_log_line("public wires", local_num_pub_wires, 0, num_pub_wires, 0, 0, print_area, print_hierarchical, print_global_only); + print_log_line("public wire bits", local_num_pub_wire_bits, 0, num_pub_wire_bits, 0, 0, print_area, print_hierarchical, + print_global_only); + print_log_line("ports", local_num_ports, 0, num_ports, 0, 0, print_area, print_hierarchical, print_global_only); + print_log_line("port bits", local_num_port_bits, 0, num_port_bits, 0, 0, print_area, print_hierarchical, print_global_only); + print_log_line("memories", local_num_memories, 0, num_memories, 0, 0, print_area, print_hierarchical, print_global_only); + print_log_line("memory bits", local_num_memory_bits, 0, num_memory_bits, 0, 0, print_area, print_hierarchical, print_global_only); + print_log_line("processes", local_num_processes, 0, num_processes, 0, 0, print_area, print_hierarchical, print_global_only); + print_log_line("cells", local_num_cells, local_area, num_cells, area, 0, print_area, print_hierarchical, print_global_only); + for (auto &it : num_cells_by_type) + if (it.second) { + auto name = RTLIL::unescape_id(it.first); + print_log_line(name, local_num_cells_by_type.count(it.first) ? local_num_cells_by_type.at(it.first) : 0, + local_area_cells_by_type.count(it.first) ? local_area_cells_by_type.at(it.first) : 0, it.second, + area_cells_by_type.at(it.first), 1, print_area, print_hierarchical, print_global_only); + } + if (num_submodules > 0) { + print_log_line("submodules", num_submodules, 0, num_submodules, submodule_area, 0, print_area, print_hierarchical, + print_global_only); + for (auto &it : num_submodules_by_type) + if (it.second) + print_log_line(RTLIL::unescape_id(it.first), it.second, 0, it.second, + submodules_area_by_type.count(it.first) ? submodules_area_by_type.at(it.first) : 0, 1, + print_area, print_hierarchical, print_global_only); + } + if (!unknown_cell_area.empty()) { + log("\n"); + for (auto cell_type : unknown_cell_area) + log(" Area for cell type %s is unknown!\n", cell_type); + } + + if (area != 0) { + log("\n"); + if (print_hierarchical || print_global_only) { + log(" Chip area for %smodule '%s': %f\n", (top_mod) ? "top " : "", mod_name, area); + log(" of which used for sequential elements: %f (%.2f%%)\n", sequential_area, 100.0 * sequential_area / area); + } else { + double local_area = 0; + for (auto &it : local_area_cells_by_type) + local_area += it.second; + double local_sequential_area = 0; + for (auto &it : local_seq_area_cells_by_type) + local_sequential_area += it.second; + log(" Chip area for %smodule '%s': %f\n", (top_mod) ? "top " : "", mod_name, local_area); + log(" of which used for sequential elements: %f (%.2f%%)\n", local_sequential_area, + 100.0 * local_sequential_area / local_area); + } + } + + if (tech == "xilinx" || tech == "analogdevices") { + log("\n"); + log(" Estimated number of LCs: %10u\n", estimate_xilinx_lc()); + } + + if (tech == "cmos") { + bool tran_cnt_exact = true; + unsigned int tran_cnt = cmos_transistor_count(&tran_cnt_exact); + + log("\n"); + log(" Estimated number of transistors: %10u%s\n", tran_cnt, tran_cnt_exact ? "" : "+"); + } + } + + string json_line(unsigned int count_local, double area_local, unsigned int count_global, double area_global) + { + + return stringf("{ \"count\": \"%u\", \"area\": \"%f\", \"local_count\": \"%u\", \"local_area\": \"%f\" }", count_global, area_global, + count_local, area_local); + } + + void append_json(std::string &json, const char *mod_name, bool first_module, bool hierarchical = false, bool global_only = false) + { + if (!first_module) + json += ",\n"; + if (hierarchical) { + json += stringf(" %s: {\n", json11::Json(mod_name).dump()); + json += stringf(" \"num_wires\": %s,\n", json_line(local_num_wires, 0, num_wires, 0)); + json += stringf(" \"num_wire_bits\": %s,\n", json_line(local_num_wire_bits, 0, num_wire_bits, 0)); + json += stringf(" \"num_pub_wires\": %s,\n", json_line(local_num_pub_wires, 0, num_pub_wires, 0)); + json += stringf(" \"num_pub_wire_bits\": %s,\n", json_line(local_num_pub_wire_bits, 0, num_pub_wire_bits, 0)); + json += stringf(" \"num_ports\": %s,\n", json_line(local_num_ports, 0, num_ports, 0)); + json += stringf(" \"num_port_bits\": %s,\n", json_line(local_num_port_bits, 0, num_port_bits, 0)); + json += stringf(" \"num_memories\": %s,\n", json_line(local_num_memories, 0, num_memories, 0)); + json += stringf(" \"num_memory_bits\": %s,\n", json_line(local_num_memory_bits, 0, num_memory_bits, 0)); + json += stringf(" \"num_processes\": %s,\n", json_line(local_num_processes, 0, num_processes, 0)); + json += stringf(" \"num_cells\": %s,\n", json_line(local_num_cells, local_area, num_cells, area)); + json += stringf(" \"num_submodules\": %s,\n", json_line(0, 0, num_submodules, submodule_area)); + json += stringf(" \"sequential_area\": %s,\n", json_line(0, local_sequential_area, 0, sequential_area)); + + json += " \"num_cells_by_type\": {\n"; + bool first_line = true; + for (auto &it : num_cells_by_type) + if (it.second) { + if (!first_line) + json += ",\n"; + json += stringf(" %s: %s", json11::Json(RTLIL::unescape_id(it.first)).dump(), + json_line(local_num_cells_by_type.count(it.first) ? local_num_cells_by_type.at(it.first) : 0, + local_area_cells_by_type.count(it.first) ? local_area_cells_by_type.at(it.first) : 0, it.second, + area_cells_by_type.at(it.first)) + ); + first_line = false; + } + json += "\n"; + json += " },\n"; + json += " \"num_submodules_by_type\": {\n"; + first_line = true; + for (auto &it : num_submodules_by_type) + if (it.second) { + if (!first_line) + json += ",\n"; + json += stringf(" %s: %s", json11::Json(RTLIL::unescape_id(it.first)).dump(), + json_line(0, 0, it.second, + submodules_area_by_type.count(it.first) ? submodules_area_by_type.at(it.first) : 0) + ); + first_line = false; + } + json += "\n"; + json += " }\n"; + if (tech == "xilinx" || tech == "analogdevices") { + json += stringf(" \"estimated_num_lc\": %u,\n", estimate_xilinx_lc()); + } + if (tech == "cmos") { + bool tran_cnt_exact = true; + unsigned int tran_cnt = cmos_transistor_count(&tran_cnt_exact); + json += stringf(" \"estimated_num_transistors\": \"%u%s\"\n", tran_cnt, tran_cnt_exact ? "" : "+"); + } + json += " }"; + + } else { + if (global_only) { + json += stringf(" %s: {\n", json11::Json(mod_name).dump()); + json += stringf(" \"num_wires\": %u,\n", num_wires); + json += stringf(" \"num_wire_bits\": %u,\n", num_wire_bits); + json += stringf(" \"num_pub_wires\": %u,\n", num_pub_wires); + json += stringf(" \"num_pub_wire_bits\": %u,\n", num_pub_wire_bits); + json += stringf(" \"num_ports\": %u,\n", num_ports); + json += stringf(" \"num_port_bits\": %u,\n", num_port_bits); + json += stringf(" \"num_memories\": %u,\n", num_memories); + json += stringf(" \"num_memory_bits\": %u,\n", num_memory_bits); + json += stringf(" \"num_processes\": %u,\n", num_processes); + json += stringf(" \"num_cells\": %u,\n", num_cells); + json += stringf(" \"num_submodules\": %u,\n", num_submodules); + if (area != 0) { + json += stringf(" \"area\": %f,\n", area); + json += stringf(" \"sequential_area\": %f,\n", sequential_area); + } + json += " \"num_cells_by_type\": {\n"; + bool first_line = true; + for (auto &it : num_cells_by_type) + if (it.second) { + if (!first_line) + json += ",\n"; + json += stringf(" %s: %u", json11::Json(RTLIL::unescape_id(it.first)).dump(), it.second); + first_line = false; + } + for (auto &it : num_submodules_by_type) + if (it.second) { + if (!first_line) + json += ",\n"; + json += stringf(" %s: %u", json11::Json(RTLIL::unescape_id(it.first)).dump(), it.second); + first_line = false; + } + json += "\n"; + json += " }"; + } else { + json += stringf(" %s: {\n", json11::Json(mod_name).dump()); + json += stringf(" \"num_wires\": %u,\n", local_num_wires); + json += stringf(" \"num_wire_bits\": %u,\n", local_num_wire_bits); + json += stringf(" \"num_pub_wires\": %u,\n", local_num_pub_wires); + json += stringf(" \"num_pub_wire_bits\": %u,\n", local_num_pub_wire_bits); + json += stringf(" \"num_ports\": %u,\n", local_num_ports); + json += stringf(" \"num_port_bits\": %u,\n", local_num_port_bits); + json += stringf(" \"num_memories\": %u,\n", local_num_memories); + json += stringf(" \"num_memory_bits\": %u,\n", local_num_memory_bits); + json += stringf(" \"num_processes\": %u,\n", local_num_processes); + json += stringf(" \"num_cells\": %u,\n", local_num_cells); + json += stringf(" \"num_submodules\": %u,\n", num_submodules); + if (area != 0) { + json += stringf(" \"area\": %f,\n", area); + json += stringf(" \"sequential_area\": %f,\n", sequential_area); + } + json += " \"num_cells_by_type\": {\n"; + bool first_line = true; + for (auto &it : local_num_cells_by_type) + if (it.second) { + if (!first_line) + json += ",\n"; + json += stringf(" %s: %u", json11::Json(RTLIL::unescape_id(it.first)).dump(), it.second); + first_line = false; + } + for (auto &it : num_submodules_by_type) + if (it.second) { + if (!first_line) + json += ",\n"; + json += stringf(" %s: %u", json11::Json(RTLIL::unescape_id(it.first)).dump(), it.second); + first_line = false; + } + json += "\n"; + json += " }"; + } + if (tech == "xilinx" || tech == "analogdevices") { + json += ",\n"; + json += stringf(" \"estimated_num_lc\": %u", estimate_xilinx_lc()); + } + if (tech == "cmos") { + bool tran_cnt_exact = true; + unsigned int tran_cnt = cmos_transistor_count(&tran_cnt_exact); + json += ",\n"; + json += stringf(" \"estimated_num_transistors\": \"%u%s\"", tran_cnt, tran_cnt_exact ? "" : "+"); + } + json += "\n"; + json += " }"; + } + } +}; + +statdata_t hierarchy_worker(const TwinePool &twines, std::map &mod_stat, IdString mod, int level, bool quiet = false, bool has_area = true, + bool hierarchy_mode = true) +{ + statdata_t mod_data = mod_stat.at(mod); + + for (auto &it : mod_data.num_submodules_by_type) { + IdString sub = twines.find(it.first); + if (sub != IdString::Null && mod_stat.count(sub) > 0) { + if (!quiet) + mod_data.print_log_line(RTLIL::unescape_id(it.first), mod_stat.at(sub).local_num_cells, + mod_stat.at(sub).local_area, mod_stat.at(sub).num_cells, mod_stat.at(sub).area, + level, has_area, hierarchy_mode); + hierarchy_worker(twines, mod_stat, sub, level + 1, quiet, has_area, hierarchy_mode) * it.second; + } + } + + return mod_data; +} + +statdata_t hierarchy_builder(RTLIL::Design *design, const RTLIL::Module *top_mod, std::map &mod_stat, + bool width_mode, dict &cell_area, string techname) +{ + if (top_mod == nullptr) + top_mod = design->top_module(); + statdata_t mod_data(design, top_mod, width_mode, cell_area, techname); + for (auto cell : top_mod->selected_cells()) { + if (cell_area.count(cell->type) == 0) { + if (design->has(cell->type)) { + if (!(design->module(cell->type)->attributes.count(ID::blackbox))) { + // deal with modules + mod_data.add( + hierarchy_builder(design, design->module(cell->type), mod_stat, width_mode, cell_area, techname)); + mod_data.num_submodules_by_type[cell->type]++; + mod_data.submodules_area_by_type[cell->type] += mod_stat.at(cell->type).area; + mod_data.submodule_area += mod_stat.at(cell->type).area; + mod_data.num_submodules++; + mod_data.unknown_cell_area.erase(cell->type); + mod_data.num_cells -= + (mod_data.num_cells_by_type.count(cell->type) != 0) ? mod_data.num_cells_by_type.at(cell->type) : 0; + mod_data.num_cells_by_type.erase(cell->type); + mod_data.local_num_cells -= (mod_data.local_num_cells_by_type.count(cell->type) != 0) + ? mod_data.local_num_cells_by_type.at(cell->type) + : 0; + mod_data.local_num_cells_by_type.erase(cell->type); + mod_data.local_area_cells_by_type.erase(cell->type); + } else { + // deal with blackbox cells + if (design->module(cell->type)->attributes.count(ID::area) && + design->module(cell->type)->attributes.at(ID::area).size() == 0) { + mod_data.num_submodules_by_type[cell->type]++; + mod_data.num_submodules++; + mod_data.submodules_area_by_type[cell->type] += + double(design->module(cell->type)->attributes.at(ID::area).as_int()); + mod_data.area += double(design->module(cell->type)->attributes.at(ID::area).as_int()); + mod_data.unknown_cell_area.erase(cell->type); + mod_data.num_cells -= + (mod_data.num_cells_by_type.count(cell->type) != 0) ? mod_data.num_cells_by_type.at(cell->type) : 0; + mod_data.num_cells_by_type.erase(cell->type); + mod_data.local_num_cells -= (mod_data.local_num_cells_by_type.count(cell->type) != 0) + ? mod_data.local_num_cells_by_type.at(cell->type) + : 0; + mod_data.local_num_cells_by_type.erase(cell->type); + mod_data.local_area_cells_by_type.erase(cell->type); + } + } + } + } + } + mod_stat[top_mod->name] = mod_data; + return mod_data; +} + +void read_liberty_cellarea(dict &cell_area, string liberty_file) +{ + std::istream *f = uncompressed(liberty_file.c_str()); + yosys_input_files.insert(liberty_file); + LibertyParser libparser(*f, liberty_file, liberty_synth_filter); + delete f; + + for (auto cell : libparser.ast->children) { + if (cell->id != "cell" || cell->args.size() != 1) + continue; + + const LibertyAst *ar = cell->find("area"); + bool is_flip_flop = cell->find("ff") != nullptr; + vector single_parameter_area; + vector> double_parameter_area; + vector port_names; + const LibertyAst *sar = cell->find("single_area_parameterised"); + if (sar != nullptr) { + for (const auto &s : sar->args) { + if (s.empty()) { + //catches trailing commas + continue; + } + try { + double value = std::stod(s); + single_parameter_area.push_back(value); + } catch (const std::exception &e) { + log_error("Failed to parse single parameter area value '%s': %s\n", s, e.what()); + } + } + if (single_parameter_area.size() == 0) + log_error("single parameter area has size 0: %s\n", sar->args[single_parameter_area.size() - 1]); + // check if it is a double parameterised area + } + const LibertyAst *dar = cell->find("double_area_parameterised"); + if (dar != nullptr) { + for (const auto &s : dar->args) { + + + vector sub_array; + std::string::size_type start = 0; + std::string::size_type end = s.find_first_of(",", start); + while (end != std::string::npos) { + sub_array.push_back(s.substr(start, end - start)); + start = end + 1; + end = s.find_first_of(",", start); + } + sub_array.push_back(s.substr(start, end)); + + vector cast_sub_array; + for (const auto &s : sub_array) { + double value = 0; + if (s.empty()) { + //catches trailing commas + continue; + } + try { + value = std::stod(s); + cast_sub_array.push_back(value); + } catch (const std::exception &e) { + log_error("Failed to parse double parameter area value for '%s': %s\n", s, e.what()); + } + } + double_parameter_area.push_back(cast_sub_array); + if (cast_sub_array.size() == 0) + log_error("double paramter array has size 0: %s\n", s); + } + } + const LibertyAst *par = cell->find("port_names"); + if (par != nullptr) { + for (const auto &s : par->args) { + port_names.push_back(s); + } + } + + if (ar != nullptr && !ar->value.empty()) { + string prefix = cell->args[0].substr(0, 1) == "$" ? "" : "\\"; + cell_area[prefix + cell->args[0]] = {atof(ar->value.c_str()), is_flip_flop, single_parameter_area, double_parameter_area, + port_names}; + } + } +} + +struct StatPass : public Pass { + StatPass() : Pass("stat", "print some statistics") {} + bool formatted_help() override + { + auto *help = PrettyHelp::get_current(); + help->set_group("passes/status"); + return false; + } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" stat [options] [selection]\n"); + log("\n"); + log("Print some statistics (number of objects) on the selected portion of the\n"); + log("design.\n"); + log("Extracts the area of cells from a liberty file, if provided.\n"); + log("\n"); + log(" -top \n"); + log(" print design hierarchy with this module as top. if the design is fully\n"); + log(" selected and a module has the 'top' attribute set, this module is used\n"); + log(" default value for this option.\n"); + log("\n"); + log(" -liberty \n"); + log(" use cell area information from the provided liberty file\n"); + log("\n"); + log(" -tech \n"); + log(" print area estimate for the specified technology. Currently supported\n"); + log(" values for : xilinx, analogdevices, cmos\n"); + log("\n"); + log(" -width\n"); + log(" annotate internal cell types with their word width.\n"); + log(" e.g. $add_8 for an 8 bit wide $add cell.\n"); + log("\n"); + log(" -json\n"); + log(" output the statistics in a machine-readable JSON format.\n"); + log(" this is output to the console; use \"tee\" to output to a file.\n"); + log("\n"); + log(" -hierarchy\n"); + log(" print hierarchical statistics, i.e. The area and number of cells include submodules.\n"); + log(" this changes the format of the json output.\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + bool width_mode = false, json_mode = false, hierarchy_mode = false; + RTLIL::Module *top_mod = nullptr; + std::map mod_stat; + dict cell_area; + string techname; + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + if (args[argidx] == "-width") { + width_mode = true; + continue; + } + if (args[argidx] == "-liberty" && argidx + 1 < args.size()) { + string liberty_file = args[++argidx]; + rewrite_filename(liberty_file); + read_liberty_cellarea(cell_area, liberty_file); + continue; + } + if (args[argidx] == "-tech" && argidx + 1 < args.size()) { + techname = args[++argidx]; + continue; + } + if (args[argidx] == "-top" && argidx + 1 < args.size()) { + IdString top_ref = design->twines().find(RTLIL::escape_id(args[argidx + 1])); + if (design->module(top_ref) == nullptr) + log_cmd_error("Can't find module %s.\n", args[argidx + 1]); + top_mod = design->module(top_ref); + argidx++; + continue; + } + if (args[argidx] == "-json") { + json_mode = true; + continue; + } + if (args[argidx] == "-hierarchy") { + hierarchy_mode = true; + continue; + } + break; + } + extra_args(args, argidx, design); + + if (!json_mode) + log_header(design, "Printing statistics.\n"); + + if (techname != "" && techname != "xilinx" && techname != "analogdevices" && techname != "cmos" && !json_mode) + log_cmd_error("Unsupported technology: '%s'\n", techname); + + std::string json; + if (json_mode) { + json += "{\n"; + json += stringf(" \"creator\": %s,\n", json11::Json(yosys_maybe_version()).dump()); + std::stringstream invocation; + std::copy(args.begin(), args.end(), std::ostream_iterator(invocation, " ")); + json += stringf(" \"invocation\": %s,\n", json11::Json(invocation.str()).dump()); + json += " \"modules\": {\n"; + } + + if (top_mod != nullptr) { + hierarchy_builder(design, top_mod, mod_stat, width_mode, cell_area, techname); + } else { + for (auto mod : design->selected_modules()) { + if (mod_stat.count(mod->name) == 0) { + hierarchy_builder(design, mod, mod_stat, width_mode, cell_area, techname); + } + } + } + + bool first_module = true; + // determine if anything has a area. + bool has_area = false; + for (auto &it : mod_stat) { + if (it.second.area > 0 || it.second.sequential_area > 0) { + has_area = true; + break; + } + } + for (auto mod : design->selected_modules()) { + if (!top_mod && design->full_selection()) + if (mod->get_bool_attribute(ID::top)) + top_mod = mod; + statdata_t data = mod_stat.at(mod->name); + if (json_mode) { + data.append_json(json, mod->name.str().c_str(), first_module, hierarchy_mode); + first_module = false; + } else { + log("\n"); + log("=== %s%s ===\n", mod, mod->is_selected_whole() ? "" : " (partially selected)"); + log("\n"); + data.log_data(mod->name, false, has_area, hierarchy_mode); + } + } + + if (json_mode) + json += top_mod == nullptr ? "\n }\n" : "\n },\n"; + + if (top_mod != nullptr) { + if (!json_mode && GetSize(mod_stat) > 1) { + log("\n"); + log("=== design hierarchy ===\n"); + log("\n"); + mod_stat[top_mod->name].print_log_header(has_area, hierarchy_mode, true); + mod_stat[top_mod->name].print_log_line(top_mod->name.unescape(), mod_stat[top_mod->name].local_num_cells, + mod_stat[top_mod->name].local_area, mod_stat[top_mod->name].num_cells, + mod_stat[top_mod->name].area, 0, has_area, hierarchy_mode, true); + } + + statdata_t data = hierarchy_worker(design->twines(), mod_stat, top_mod->name, 0, /*quiet=*/json_mode, has_area, hierarchy_mode); + + if (json_mode) + data.append_json(json, "design", true, hierarchy_mode, true); + else if (GetSize(mod_stat) > 1) { + log("\n"); + data.log_data(top_mod->name, true, has_area, hierarchy_mode, true); + } + + design->scratchpad_set_int("stat.num_wires", data.num_wires); + design->scratchpad_set_int("stat.num_wire_bits", data.num_wire_bits); + design->scratchpad_set_int("stat.num_pub_wires", data.num_pub_wires); + design->scratchpad_set_int("stat.num_pub_wire_bits", data.num_pub_wire_bits); + design->scratchpad_set_int("stat.num_ports", data.num_ports); + design->scratchpad_set_int("stat.num_port_bits", data.num_port_bits); + design->scratchpad_set_int("stat.num_memories", data.num_memories); + design->scratchpad_set_int("stat.num_memory_bits", data.num_memory_bits); + design->scratchpad_set_int("stat.num_processes", data.num_processes); + design->scratchpad_set_int("stat.num_cells", data.num_cells); + design->scratchpad_set_int("stat.area", data.area); + } + + if (json_mode) { + json += "\n}\n"; + log_lines(json); + } + + log("\n"); + } +} StatPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/symfpu.cc b/chips/yosys/passes/cmds/symfpu.cc new file mode 100644 index 0000000000000000000000000000000000000000..c227266a6fef7562875af51617e5e28dff5dff3b --- /dev/null +++ b/chips/yosys/passes/cmds/symfpu.cc @@ -0,0 +1,799 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2025 Jannis Harder + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/log_help.h" +#include "kernel/yosys.h" + +#include "symfpu/baseTypes/shared.h" +#include "symfpu/core/add.h" +#include "symfpu/core/divide.h" +#include "symfpu/core/fma.h" +#include "symfpu/core/ite.h" +#include "symfpu/core/multiply.h" +#include "symfpu/core/packing.h" +#include "symfpu/core/sqrt.h" +#include "symfpu/core/unpackedFloat.h" +#include "symfpu/core/classify.h" +#include "symfpu/core/compare.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct prop; + +template struct bv; + +struct rm { + enum class mode { RNE, RNA, RTP, RTN, RTZ }; + mode mode; + + prop operator==(rm op) const; +}; + +thread_local Module *symfpu_mod = nullptr; + +struct rtlil_traits { + using bwt = uint64_t; + using rm = struct rm; + using fpt = symfpu::shared::floatingPointTypeInfo; + using prop = struct prop; + using sbv = bv; + using ubv = bv; + + // Return an instance of each rounding mode. + static rm RNE(void) { return {rm::mode::RNE}; }; + static rm RNA(void) { return {rm::mode::RNA}; }; + static rm RTP(void) { return {rm::mode::RTP}; }; + static rm RTN(void) { return {rm::mode::RTN}; }; + static rm RTZ(void) { return {rm::mode::RTZ}; }; + + // Handle various invariants. + // These can be empty to start with. + static void precondition(const bool b) { assert(b); } + static void postcondition(const bool b) { assert(b); } + static void invariant(const bool b) { assert(b); } + static void precondition(const prop &p); + static void postcondition(const prop &p); + static void invariant(const prop &p); + static void setflag(const string &name, const prop &p); +}; + +rm parse_rounding(std::string rounding) { + if (rounding.compare("RNE") == 0) + return rtlil_traits::RNE(); + else if (rounding.compare("RNA") == 0) + return rtlil_traits::RNA(); + else if (rounding.compare("RTP") == 0) + return rtlil_traits::RTP(); + else if (rounding.compare("RTN") == 0) + return rtlil_traits::RTN(); + else if (rounding.compare("RTZ") == 0) + return rtlil_traits::RTZ(); + else if (rounding.compare("DYN") == 0) + return {}; + else + log_cmd_error("Unknown rounding mode '%s'. Call help sympfpu for available rounding modes.\n", rounding); +} + +using bwt = rtlil_traits::bwt; +using fpt = rtlil_traits::fpt; +using ubv = rtlil_traits::ubv; +using sbv = rtlil_traits::sbv; +using symfpu::ite; +using uf = symfpu::unpackedFloat; +using uf_flagged = symfpu::floatWithStatusFlags; +using uf_flagged_ite = symfpu::ite; +using ubv_flagged = symfpu::bvWithStatusFlags; +using sbv_flagged = symfpu::bvWithStatusFlags; + +PRIVATE_NAMESPACE_END + +namespace symfpu +{ +template <> struct ite { + static prop iteOp(const prop &cond, const prop &t, const prop &e); +}; +template struct ite> { + static bv iteOp(const prop &cond, const bv &t, const bv &e); +}; +template <> struct ite { + static prop iteOp(bool cond, const prop &t, const prop &e); +}; +template struct ite> { + static bv iteOp(bool cond, const bv &t, const bv &e); +}; +} // namespace symfpu + +PRIVATE_NAMESPACE_BEGIN + +struct prop { + SigBit bit; + + explicit prop(SigBit bit) : bit(bit) {} + prop(bool v) : bit(v) {} + + prop operator&&(const prop &op) const { return prop{symfpu_mod->And(NEW_ID, bit, op.bit)}; } + prop operator||(const prop &op) const { return prop{symfpu_mod->Or(NEW_ID, bit, op.bit)}; } + prop operator^(const prop &op) const { return prop{symfpu_mod->Xor(NEW_ID, bit, op.bit)}; } + prop operator!() const { return prop{symfpu_mod->Not(NEW_ID, bit)}; } + + prop operator==(const prop &op) const { return prop{symfpu_mod->Eq(NEW_ID, bit, op.bit)}; } + + const prop &named(std::string_view s) const + { + symfpu_mod->connect(symfpu_mod->addWire(symfpu_mod->uniquify(stringf("\\%s", s))), bit); + return *this; + } +}; + +template struct bv { + SigSpec bits; + + const bv &named(std::string_view s) const + { + symfpu_mod->connect(symfpu_mod->addWire(symfpu_mod->uniquify(stringf("\\%s", s)), bits.size()), bits); + return *this; + } + + friend ite>; + + explicit bv(SigSpec bits) : bits(bits) {} + explicit bv(prop prop) : bits(prop.bit) {} + explicit bv(bwt w, unsigned v) { bits = Const((long long)v, w); } + bv(bv const &other) : bits(other.bits) {} + + bwt getWidth() const { return bits.size(); } + + static bv one(bwt w) { return bv{SigSpec(1, w)}; } + static bv zero(bwt w) { return bv{SigSpec(0, w)}; } + static bv allOnes(bwt w) { return bv{SigSpec(State::S1, w)}; } + + static bv maxValue(bwt w) + { + if (!is_signed) + return allOnes(w); + log_assert(w > 0); + Const value = Const(State::S1, w); + value.set(w - 1, State::S0); + return bv{SigSpec(value)}; + } + static bv minValue(bwt w) + { + + if (!is_signed) + return zero(w); + log_assert(w > 0); + Const value = Const(State::S0, w); + value.set(w - 1, State::S1); + return bv{SigSpec(value)}; + } + + bv toSigned(void) const { return bv(*this); } + bv toUnsigned(void) const { return bv(*this); } + + bv extract(bwt upper, bwt lower) const + { + return bv{bits.extract(lower, upper + 1 - lower)}; + } + + bv extend(bwt extension) const + { + auto extended_bits = bits; + extended_bits.extend_u0(bits.size() + extension, is_signed); + return bv{extended_bits}; + } + + inline bv matchWidth(const bv &op) const + { + log_assert(this->getWidth() <= op.getWidth()); + return this->extend(op.getWidth() - this->getWidth()); + } + + inline bv resize(bwt newSize) const + { + bwt width = this->getWidth(); + + if (newSize > width) { + return this->extend(newSize - width); + } else if (newSize < width) { + return this->extract(newSize - 1, 0); + } else { + return *this; + } + } + + inline bv contract(bwt reduction) const + { + log_assert(getWidth() > reduction); + return resize(getWidth() - reduction); + } + + bv append(const bv &op) const { return bv{SigSpec({bits, op.bits})}; } + + prop isAllOnes() const { return prop{symfpu_mod->ReduceAnd(NEW_ID, bits)}; } + prop isAllZeros() const { return prop{symfpu_mod->ReduceAnd(NEW_ID, symfpu_mod->Not(NEW_ID, bits))}; } + + bv operator-() const { return bv{symfpu_mod->Neg(NEW_ID, bits, is_signed)}; } + bv operator~() const { return bv{symfpu_mod->Not(NEW_ID, bits, is_signed)}; } + + bv operator+(const bv &op) const + { + log_assert(getWidth() == op.getWidth()); + return bv{symfpu_mod->Add(NEW_ID, bits, op.bits, is_signed)}; + } + bv operator-(const bv &op) const + { + log_assert(getWidth() == op.getWidth()); + return bv{symfpu_mod->Sub(NEW_ID, bits, op.bits, is_signed)}; + } + bv operator*(const bv &op) const + { + log_assert(getWidth() == op.getWidth()); + log_assert(!is_signed); + return bv{symfpu_mod->Mul(NEW_ID, bits, op.bits, is_signed)}; + } + bv operator%(const bv &op) const + { + log_assert(getWidth() == op.getWidth()); + log_assert(!is_signed); + return bv{symfpu_mod->Mod(NEW_ID, bits, op.bits, is_signed)}; + } + bv operator/(const bv &op) const + { + log_assert(getWidth() == op.getWidth()); + log_assert(!is_signed); + return bv{symfpu_mod->Div(NEW_ID, bits, op.bits, is_signed)}; + } + + bv operator|(const bv &op) const + { + log_assert(getWidth() == op.getWidth()); + return bv{symfpu_mod->Or(NEW_ID, bits, op.bits, is_signed)}; + } + bv operator&(const bv &op) const + { + log_assert(getWidth() == op.getWidth()); + return bv{symfpu_mod->And(NEW_ID, bits, op.bits, is_signed)}; + } + bv operator<<(const bv &op) const + { + log_assert(getWidth() == op.getWidth()); + return bv{symfpu_mod->Shl(NEW_ID, bits, op.bits, is_signed)}; + } + bv operator>>(const bv &op) const + { + log_assert(getWidth() == op.getWidth()); + if (is_signed) + return bv{symfpu_mod->Sshr(NEW_ID, bits, op.bits, is_signed)}; + else + return bv{symfpu_mod->Shr(NEW_ID, bits, op.bits, is_signed)}; + } + + prop operator!=(const bv &op) const + { + log_assert(getWidth() == op.getWidth()); + return prop{symfpu_mod->Ne(NEW_ID, bits, op.bits, is_signed)}; + } + + prop operator==(const bv &op) const + { + log_assert(getWidth() == op.getWidth()); + return prop{symfpu_mod->Eq(NEW_ID, bits, op.bits, is_signed)}; + } + + prop operator<=(const bv &op) const + { + log_assert(getWidth() == op.getWidth()); + return prop{symfpu_mod->Le(NEW_ID, bits, op.bits, is_signed)}; + } + prop operator>=(const bv &op) const + { + log_assert(getWidth() == op.getWidth()); + return prop{symfpu_mod->Ge(NEW_ID, bits, op.bits, is_signed)}; + } + + prop operator<(const bv &op) const + { + log_assert(getWidth() == op.getWidth()); + return prop{symfpu_mod->Lt(NEW_ID, bits, op.bits, is_signed)}; + } + prop operator>(const bv &op) const + { + log_assert(getWidth() == op.getWidth()); + return prop{symfpu_mod->Gt(NEW_ID, bits, op.bits, is_signed)}; + } + + inline bv increment() const { return *this + one(getWidth()); } + inline bv decrement() const { return *this - one(getWidth()); } + + inline bv modularLeftShift(const bv &op) const { return *this << op; } + + inline bv modularRightShift(const bv &op) const { return *this >> op; } + + inline bv modularIncrement() const { return this->increment(); } + + inline bv modularDecrement() const { return this->decrement(); } + + inline bv modularAdd(const bv &op) const { return *this + op; } + inline bv modularSubtract(const bv &op) const { return *this - op; } + + inline bv modularNegate() const { return -(*this); } + + inline bv signExtendRightShift(const bv &op) const { return bv{sbv(sbv(*this) >> sbv(op))}; } +}; + +PRIVATE_NAMESPACE_END + +prop symfpu::ite::iteOp(const prop &cond, const prop &t, const prop &e) { return prop{symfpu_mod->Mux(NEW_ID, e.bit, t.bit, cond.bit)}; } + +template bv symfpu::ite>::iteOp(const prop &cond, const bv &t, const bv &e) +{ + log_assert(t.getWidth() == e.getWidth()); + return bv{symfpu_mod->Mux(NEW_ID, e.bits, t.bits, cond.bit)}; +} + +[[maybe_unused]] prop symfpu::ite::iteOp(bool cond, const prop &t, const prop &e) { return cond ? t : e; } + +template bv symfpu::ite>::iteOp(bool cond, const bv &t, const bv &e) +{ + log_assert(t.getWidth() == e.getWidth()); + return cond ? t : e; +} + +PRIVATE_NAMESPACE_BEGIN + +prop rm::operator==(rm op) const { return mode == op.mode; } + +void rtlil_traits::precondition(const prop &cond) +{ + Cell *cell = symfpu_mod->addAssert(NEW_ID, cond.bit, State::S1); + cell->set_bool_attribute(ID(symfpu_pre)); +} +void rtlil_traits::postcondition(const prop &cond) +{ + Cell *cell = symfpu_mod->addAssert(NEW_ID, cond.bit, State::S1); + cell->set_bool_attribute(ID(symfpu_post)); +} +void rtlil_traits::invariant(const prop &cond) +{ + Cell *cell = symfpu_mod->addAssert(NEW_ID, cond.bit, State::S1); + cell->set_bool_attribute(ID(symfpu_inv)); +} + +ubv input_ubv(IdString name, int width) +{ + auto input = symfpu_mod->addWire(name, width); + input->port_input = true; + return ubv(SigSpec(input)); +} + +prop input_prop(IdString name) +{ + auto input = symfpu_mod->addWire(name); + input->port_input = true; + return prop(SigBit(input)); +} + +void output_ubv(IdString name, const ubv &value) +{ + auto output = symfpu_mod->addWire(name, value.getWidth()); + symfpu_mod->connect(output, value.bits); + output->port_output = true; +} + +void output_prop(IdString name, const prop &value) +{ + auto output = symfpu_mod->addWire(name); + symfpu_mod->connect(output, value.bit); + output->port_output = true; +} + +// unpacked floats don't track NaN signalling, so we need to check the +// raw bitvector +template prop is_sNaN(bv bitvector, int sb) { + return bitvector.extract(sb-2, sb-2).isAllZeros(); +} + +struct SymFpuPass : public Pass { + SymFpuPass() : Pass("symfpu", "SymFPU based floating point netlist generator") {} + bool formatted_help() override + { + auto *help = PrettyHelp::get_current(); + help->set_group("formal"); + + auto content_root = help->get_root(); + + content_root->usage("symfpu [size] [-op ] [-rm ]"); + content_root->paragraph( + "Generates netlist for given floating point operation with floating point inputs " + "a, b, c, floating point output o, 5-bit input rm (rounding mode), and " + "5 single-bit outputs NV (invalid operation), DZ (divide by zero), OF (overflow), " + "UF (underflow), and NX (inexact)." + ); + + content_root->paragraph( + "Operations use single precision float unless [size] options are provided:" + ); + content_root->option("-eb ", "use bits for exponent; default=8"); + content_root->option("-sb ", "use bits for significand, including hidden bit; default=24"); + + // conversions could be useful, but for targeting Sail we don't need them + auto op_option = content_root->open_option("-op "); + op_option->paragraph("floating point operation to generate, must be one of the below; default=mul"); + op_option->codeblock( + " | description | equation\n" + "-------+--------------------------------+------------\n" + "sqrt | one input square root | o = sqrt(a)\n" + "add | two input addition | o = a+b\n" + "sub | two input subtraction | o = a-b\n" + "mul | two input multiplication | o = a*b\n" + "div | two input divison | o = a/b\n" + "min | two input minimum | o = min(a,b)\n" + "max | two input maximum | o = max(a,b)\n" + "muladd | three input fused multiple-add | o = (a*b)+c\n" + ); + + auto rm_option = content_root->open_option("-rm "); + rm_option->paragraph("rounding mode to generate, must be one of the below; default=DYN"); + rm_option->codeblock( + " | rm | description\n" + "-----+--------+----------------------\n" + "RNE | 00001 | round ties to even\n" + "RNA | 00010 | round ties to away\n" + "RTP | 00100 | round toward positive\n" + "RTN | 01000 | round toward negative\n" + "RTZ | 10000 | round toward zero\n" + "DYN | xxxxx | round based on 'rm' input signal\n" + ); + rm_option->paragraph("Note: when not using DYN mode, the 'rm' input is ignored."); + + content_root->usage("symfpu -classify [size]"); + content_root->paragraph( + "Generates netlist for floating point classification of input a. Outputs " + "8 single-bit signals, isNormal, isSubnormal, isZero, isInfinite, isNaN, " + "isPositive, isNegative, and isFinite." + ); + + content_root->usage("symfpu -compare [size]"); + content_root->paragraph( + "Generates netlist for floating point comparison of inputs a and b. Outputs " + "6 single-bit signals, smtlibEqual, ieee754Equal, lessThan, lessThanOrEqual, " + "sNV (invalid signaling comparison), and qNV (invalid quiet comparison)." + ); + + return true; + } + void execute(std::vector args, RTLIL::Design *design) override + { + //TODO: fix multiple calls to symfpu in single Yosys instance + int eb = 8, sb = 24; + string op = "mul", rounding = "DYN"; + int inputs = 2; + bool classify = false, compare = false; + log_header(design, "Executing SYMFPU pass.\n"); + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + if (args[argidx] == "-eb" && argidx+1 < args.size()) { + eb = atoi(args[++argidx].c_str()); + continue; + } + if (args[argidx] == "-sb" && argidx+1 < args.size()) { + sb = atoi(args[++argidx].c_str()); + continue; + } + if (args[argidx] == "-op" && argidx+1 < args.size()) { + op = args[++argidx]; + if (op.compare("sqrt") == 0 + || op.compare("altsqrt") == 0) // currently undocumented + inputs = 1; + else if (op.compare("add") == 0 + || op.compare("sub") == 0 + || op.compare("mul") == 0 + || op.compare("altdiv") == 0 // currently undocumented + || op.compare("alt2div") == 0 // currently undocumented + || op.compare("min") == 0 + || op.compare("max") == 0 + || op.compare("div") == 0) + inputs = 2; + else if (op.compare("muladd") == 0) + inputs = 3; + else + log_cmd_error("Unknown operation '%s'. Call help symfpu for available operations.\n", op); + log("Generating '%s'\n", op); + continue; + } + if (args[argidx] == "-rm" && argidx+1 < args.size()) { + rounding = args[++argidx]; + continue; + } + if (args[argidx] == "-classify") { + classify = true; + continue; + } + if (args[argidx] == "-compare") { + compare = true; + continue; + } + break; + } + + extra_args(args, argidx, design); + + if (compare && classify) + log_cmd_error("-classify and -compare flags are incompatible.\n"); + + if (rounding.compare("DYN") != 0) { + if (compare) + log_cmd_error("symfpu -compare does not support rounding modes.\n"); + if (classify) + log_cmd_error("symfpu -classify does not support rounding modes.\n"); + if (op.compare("min") == 0 || op.compare("max") == 0) + log_cmd_error("min/max operations do not support rounding modes.\n"); + } + + if (op.compare("mul") != 0) { + if (compare) + log_cmd_error("symfpu -compare does not support operator selection.\n"); + if (classify) + log_cmd_error("symfpu -classify does not support operator selection.\n"); + } + + rm rounding_mode = parse_rounding(rounding); + fpt format(eb, sb); + + auto mod = design->addModule(ID(symfpu)); + + symfpu_mod = mod; + + auto a_bv = input_ubv(ID(a), eb+sb); + uf a = symfpu::unpack(format, a_bv); + + if (classify) { + output_prop(ID(isNormal), symfpu::isNormal(format, a)); + output_prop(ID(isSubnormal), symfpu::isSubnormal(format, a)); + output_prop(ID(isZero), symfpu::isZero(format, a)); + output_prop(ID(isInfinite), symfpu::isInfinite(format, a)); + output_prop(ID(isNaN), symfpu::isNaN(format, a)); + output_prop(ID(isPositive), symfpu::isPositive(format, a)); + output_prop(ID(isNegative), symfpu::isNegative(format, a)); + output_prop(ID(isFinite), symfpu::isFinite(format, a)); + } else if (compare) { + auto b_bv = input_ubv(ID(b), eb+sb); + uf b = symfpu::unpack(format, b_bv); + output_prop(ID(smtlibEqual), symfpu::smtlibEqual(format, a, b)); + output_prop(ID(ieee754Equal), symfpu::ieee754Equal(format, a, b)); + output_prop(ID(lessThan), symfpu::lessThan(format, a, b)); + output_prop(ID(lessThanOrEqual), symfpu::lessThanOrEqual(format, a, b)); + output_prop(ID(sNV), a.getNaN() || b.getNaN()); + output_prop(ID(qNV), (a.getNaN() && is_sNaN(a_bv, sb)) || (b.getNaN() && is_sNaN(b_bv, sb))); + } else { + auto b_bv = input_ubv(ID(b), eb+sb); + auto c_bv = input_ubv(ID(c), eb+sb); + uf b = symfpu::unpack(format, b_bv); + uf c = symfpu::unpack(format, c_bv); + + auto rm_wire = symfpu_mod->addWire(ID(rm), 5); + rm_wire->port_input = true; + SigSpec rm_sig(rm_wire); + prop rm_RNE(rm_sig[0]); + prop rm_RNA(rm_sig[1]); + prop rm_RTP(rm_sig[2]); + prop rm_RTN(rm_sig[3]); + prop rm_RTZ(rm_sig[4]); + + // signaling NaN inputs raise NV + prop signals_invalid((a.getNaN() && is_sNaN(a_bv, sb)) + || (b.getNaN() && is_sNaN(b_bv, sb) && inputs >= 2) + || (c.getNaN() && is_sNaN(c_bv, sb) && inputs >= 3) + ); + + auto make_op = [&op, &format, &a, &b, &c](rm rounding_mode) { + if (op.compare("add") == 0) + return symfpu::add_flagged(format, rounding_mode, a, b, prop(true)); + else if (op.compare("sub") == 0) + return symfpu::add_flagged(format, rounding_mode, a, b, prop(false)); + else if (op.compare("mul") == 0) + return symfpu::multiply_flagged(format, rounding_mode, a, b); + else if (op.compare("div") == 0) + return symfpu::divide_flagged(format, rounding_mode, a, b); + else if (op.compare("sqrt") == 0) + return symfpu::sqrt_flagged(format, rounding_mode, a); + else if (op.compare("muladd") == 0) + return symfpu::fma_flagged(format, rounding_mode, a, b, c); + else if (op.compare("altdiv") == 0) + return symfpu::falseDivide_flagged(format, rounding_mode, a, b, prop(true)); + else if (op.compare("alt2div") == 0) + return symfpu::falseDivide_flagged(format, rounding_mode, a, b, prop(false)); + else if (op.compare("altsqrt") == 0) + return symfpu::falseSqrt_flagged(format, rounding_mode, a); + else if (op.compare("min") == 0) + // setting zeroCase=a.getSign() makes +0 > -0, as per IEEE 754-2019 + return uf_flagged(symfpu::min(format, a, b, a.getSign())); + else if (op.compare("max") == 0) + return uf_flagged(symfpu::max(format, a, b, a.getSign())); + else + log_abort(); + }; + + // calling this more than once will fail + auto output_fpu = [&signals_invalid, &format](const uf_flagged &o_flagged) { + output_prop(ID(NV), o_flagged.nv || signals_invalid); + output_prop(ID(DZ), o_flagged.dz); + output_prop(ID(OF), o_flagged.of); + output_prop(ID(UF), o_flagged.uf); + output_prop(ID(NX), o_flagged.nx); + + output_ubv(ID(o), symfpu::pack(format, o_flagged.val)); + }; + + if (rounding.compare("DYN") != 0) + output_fpu(make_op(rounding_mode)); + else { + auto out_RNE = make_op(rtlil_traits::RNE()); + auto out_RNA = make_op(rtlil_traits::RNA()); + auto out_RTP = make_op(rtlil_traits::RTP()); + auto out_RTN = make_op(rtlil_traits::RTN()); + auto out_RTZ = make_op(rtlil_traits::RTZ()); + output_fpu( + uf_flagged_ite::iteOp(rm_RNE, out_RNE, + uf_flagged_ite::iteOp(rm_RNA, out_RNA, + uf_flagged_ite::iteOp(rm_RTP, out_RTP, + uf_flagged_ite::iteOp(rm_RTN, out_RTN, + uf_flagged_ite::iteOp(rm_RTZ, out_RTZ, + uf_flagged::makeNaN(format, prop(true))))))) + ); + } + } + + symfpu_mod->fixup_ports(); + } +} SymFpuPass; + + +struct SymFpuConvertPass : public Pass { + SymFpuConvertPass() : Pass("symfpu_convert", "SymFPU based floating point conversion netlist generator") {} + bool formatted_help() override + { + auto *help = PrettyHelp::get_current(); + help->set_group("formal"); + + auto content_root = help->get_root(); + + content_root->usage("symfpu_convert [-rm ]"); + content_root->paragraph( + "Generates netlist for converting given input size to given output size. " + "Generated module has one input `i`, and three outputs, `o_if`, `o_fi`, and `o_ff`, " + "performing int -> float, float -> int, and float -> float conversions respectively. " + ); + + content_root->option("-isize ", "input port is bits wide; default=32"); + content_root->option("-osize ", "output ports are bits wide; default=32"); + content_root->option("-iexp ", "input port uses bits for exponent; default=8"); + content_root->option("-oexp ", "output ports use bits for exponent; default=8"); + + content_root->paragraph( + " bits of exponent implies bits of significand (including hidden bit), " + "e.g. the default is single precision float with N=32 and M=8 (and 24 bits of significand). " + ); + + auto rm_option = content_root->open_option("-rm "); + rm_option->paragraph("rounding mode to generate, must be one of the below; default=DYN"); + rm_option->codeblock( + " | rm | description\n" + "-----+--------+----------------------\n" + "RNE | 00001 | round ties to even\n" + "RNA | 00010 | round ties to away\n" + "RTP | 00100 | round toward positive\n" + "RTN | 01000 | round toward negative\n" + "RTZ | 10000 | round toward zero\n" + "DYN | xxxxx | round based on 'rm' input signal\n" + ); + rm_option->paragraph("Note: when not using DYN mode, the 'rm' input is ignored."); + + return true; + } + void execute(std::vector args, RTLIL::Design *design) override + { + //TODO: fix multiple calls to symfpu in single Yosys instance + //TODO: signed integers + int i_size = 32, o_size = 32, i_exp = 8, o_exp = 8; + string rounding = "DYN"; + log_header(design, "Executing SYMFPU_CONVERT pass.\n"); + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + // all args take a value + if (argidx+1 >= args.size()) + break; + if (args[argidx] == "-isize") { + i_size = atoi(args[++argidx].c_str()); + continue; + } + if (args[argidx] == "-osize") { + o_size = atoi(args[++argidx].c_str()); + continue; + } + if (args[argidx] == "-iexp") { + i_exp = atoi(args[++argidx].c_str()); + continue; + } + if (args[argidx] == "-oexp") { + o_exp = atoi(args[++argidx].c_str()); + continue; + } + if (args[argidx] == "-rm") { + rounding = args[++argidx]; + continue; + } + break; + } + + extra_args(args, argidx, design); + + if (o_exp >= o_size || o_exp <= 0) + log_cmd_error("-oexp value (%d) must be in range: 0 < oM < oN (oN=%d)!\n", o_exp, o_size); + if (i_exp >= i_size || i_exp <= 0) + log_cmd_error("-iexp value (%d) must be in range: 0 < iM < iN (iN=%d)!\n", i_exp, i_size); + + if (rounding.compare("DYN") == 0) + log_cmd_error("rm must be set to a single rounding mode!\n"); + rm rounding_mode = parse_rounding(rounding); + + auto mod = design->addModule(ID(symfpu)); + symfpu_mod = mod; + + fpt i_format(i_exp, i_size-i_exp); + fpt o_format(o_exp, o_size-o_exp); + + auto i_bv = input_ubv(ID(i), i_size); + uf i_f = symfpu::unpack(i_format, i_bv); + prop i_sNaN(i_f.getNaN() && is_sNaN(i_bv, i_size-i_exp)); + + auto output_flags = [](IdString name, const prop &nv, const prop &nx, const prop &of = prop(false), const prop &uf = prop(false), const prop &dz = prop(false)) { + output_ubv(name, ubv{SigSpec({nv.bit, dz.bit, of.bit, uf.bit, nx.bit})}); + }; + + uf_flagged o_ff = symfpu::convertFloatToFloat_flagged(i_format, o_format, rounding_mode, i_f); + output_ubv(ID(o_ff), symfpu::pack(o_format, o_ff.val)); + output_flags(ID(flags_ff), o_ff.nv || i_sNaN, o_ff.nx, o_ff.of, o_ff.uf); + + auto is_signed = input_prop(ID(is_signed)); + + // use riscv behavior for invalid inputs + ubv o_signed_default = symfpu::ITE(i_f.getSign(), ubv::one(1).append(ubv::zero(o_size-1)), ubv::zero(1).append(ubv::allOnes(o_size-1))); + ubv o_unsigned_default = symfpu::ITE(i_f.getSign(), ubv::zero(o_size), ubv::allOnes(o_size)); + auto o_fi_signed = symfpu::convertFloatToSBV_flagged(i_format, rounding_mode, i_f, o_size, o_signed_default); + auto o_fi_unsigned = symfpu::convertFloatToUBV_flagged(i_format, rounding_mode, i_f, o_size, o_unsigned_default); + output_ubv(ID(o_fi), symfpu::ITE(is_signed, o_fi_signed.val.toUnsigned(), o_fi_unsigned.val)); + output_flags(ID(flags_fi), + symfpu::ITE(is_signed, o_fi_signed.nv, o_fi_unsigned.nv), + symfpu::ITE(is_signed, o_fi_signed.nx, o_fi_unsigned.nx)); + + uf_flagged o_if(uf_flagged_ite::iteOp(is_signed, + symfpu::convertSBVToFloat_flagged(o_format, rounding_mode, i_bv), + symfpu::convertUBVToFloat_flagged(o_format, rounding_mode, i_bv))); + output_ubv(ID(o_if), symfpu::pack(o_format, o_if.val)); + output_flags(ID(flags_if), o_if.nv, o_if.nx, o_if.of); + + symfpu_mod->fixup_ports(); + } +} SymFpuConvertPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/tee.cc b/chips/yosys/passes/cmds/tee.cc new file mode 100644 index 0000000000000000000000000000000000000000..456bc221c1df2a7b4a304a8bee4f0a78cd56e553 --- /dev/null +++ b/chips/yosys/passes/cmds/tee.cc @@ -0,0 +1,99 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2014 Claire Xenia Wolf + * Copyright (C) 2014 Johann Glaser + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "kernel/log_help.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct TeePass : public Pass { + TeePass() : Pass("tee", "redirect command output to file") { } + bool formatted_help() override { + auto *help = PrettyHelp::get_current(); + help->set_group("passes/status"); + return false; + } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" tee [-q] [-o logfile|-a logfile] cmd\n"); + log("\n"); + log("Execute the specified command, optionally writing the commands output to the\n"); + log("specified logfile(s).\n"); + log("\n"); + log(" -q\n"); + log(" Do not print output to the normal destination (console and/or log file).\n"); + log("\n"); + log(" -o logfile\n"); + log(" Write output to this file, truncate if exists.\n"); + log("\n"); + log(" -a logfile\n"); + log(" Write output to this file, append if exists.\n"); + log("\n"); + log(" -s scratchpad\n"); + log(" Write output to this scratchpad value, truncate if it exists.\n"); + log("\n"); + log(" +INT, -INT\n"); + log(" Add/subtract INT from the -v setting for this command.\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + auto log_scope = logger().sink_scope(); + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) + { + if (args[argidx] == "-q") { + logger().clear_original(); + continue; + } + if ((args[argidx] == "-o" || args[argidx] == "-a") && argidx+1 < args.size()) { + bool is_append = args[argidx] == "-a"; + auto path = args[++argidx]; + rewrite_filename(path); + try { + logger().add_sink(path.c_str(), false, is_append); + } catch (const std::runtime_error &) { + log_cmd_error("Can't create file %s.\n", args[argidx]); + } + continue; + } + if (args[argidx] == "-s" && argidx+1 < args.size()) { + auto name = args[++argidx]; + design->scratchpad[name] = ""; + logger().add_sink(name); + continue; + } + if (GetSize(args[argidx]) >= 2 && (args[argidx][0] == '-' || args[argidx][0] == '+') && args[argidx][1] >= '0' && args[argidx][1] <= '9') { + logger().add_verbose_level(atoi(args[argidx].c_str())); + continue; + } + break; + } + + std::vector new_args(args.begin() + argidx, args.end()); + Pass::call(design, new_args); + } +} TeePass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/test_select.cc b/chips/yosys/passes/cmds/test_select.cc new file mode 100644 index 0000000000000000000000000000000000000000..237d0e0a708b3aed2f192527e91f9e67590c67a6 --- /dev/null +++ b/chips/yosys/passes/cmds/test_select.cc @@ -0,0 +1,173 @@ +#include "kernel/rtlil.h" +#include "kernel/yosys.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct TestSelectPass : public Pass { + TestSelectPass() : Pass("test_select", "call internal selection methods on design for testing purposes") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" test_select [options]\n"); + log("\n"); + log("Test semantics of internal 'RTLIL::Design::selected_modules()' by modifying the\n"); + log("current selection to only include the results of the call.\n"); + log("\n"); + log("Includes partially selected modules by default, use one of the following options\n"); + log("to remove them instead:\n"); + log("\n"); + log(" -whole_only\n"); + log("\n"); + log(" -whole_warn\n"); + log(" -whole_err\n"); + log(" -whole_cmderr\n"); + log(" remove partially selected modules, raising warning, error, or cmd error\n"); + log("\n"); + log(" test_select -unboxed_only [options]\n"); + log("\n"); + log("Remove boxed modules from selection.\n"); + log("\n"); + log(" -include_wb\n"); + log(" don't remove white boxes from selection\n"); + log("\n"); + log(" -warn_boxes\n"); + log(" -err_boxes\n"); + log(" -cmderr_boxes\n"); + log(" raise warning, error, or cmd error if a box is removed\n"); + log("\n"); + } + void execute(vector args, RTLIL::Design *design) override + { + log_header(design, "Executing TEST_SELECTION pass.\n"); + bool whole_only = false; + bool whole_warn = false; + bool whole_err = false; + bool whole_cmderr = false; + int whole_opts = 0; + + bool warn_boxes = false; + bool err_boxes = false; + bool cmderr_boxes = false; + int box_level = 0; + + bool unboxed_only = false; + bool include_wb = false; + + int argidx; + for (argidx = 1; argidx < GetSize(args); argidx++) + { + if (args[argidx] == "-whole_only") { + whole_only = true; + whole_opts++; + continue; + } + if (args[argidx] == "-whole_warn") { + whole_warn = true; + whole_opts++; + continue; + } + if (args[argidx] == "-whole_err") { + whole_err = true; + whole_opts++; + continue; + } + if (args[argidx] == "-whole_cmderr") { + whole_cmderr = true; + whole_opts++; + continue; + } + if (args[argidx] == "-warn_boxes") { + warn_boxes = true; + box_level++; + continue; + } + if (args[argidx] == "-err_boxes") { + err_boxes = true; + box_level++; + continue; + } + if (args[argidx] == "-cmderr_boxes") { + cmderr_boxes = true; + box_level++; + continue; + } + if (args[argidx] == "-unboxed_only") { + unboxed_only = true; + continue; + } + if (args[argidx] == "-include_wb") { + include_wb = true; + continue; + } + break; + } + + if (whole_opts > 1) + log_cmd_error("Only one of -whole_only, -whole_warn, -whole_err, or -whole_cmderr may be selected.\n"); + + if (include_wb && !unboxed_only) + log_cmd_error("-include_wb option requires -unboxed_only.\n"); + + if (box_level > 0 && !unboxed_only) + log_cmd_error("-*_boxes options require -unboxed_only.\n"); + + if (box_level > 1) + log_cmd_error("Only one of -warn_boxes, -err_boxes, or -cmderr_boxes may be selected.\n"); + + extra_args(args, argidx, design, false); + + // construct enums + RTLIL::SelectPartials partials; + if (whole_only) + partials = RTLIL::SELECT_WHOLE_ONLY; + else if (whole_warn) + partials = RTLIL::SELECT_WHOLE_WARN; + else if (whole_err) + partials = RTLIL::SELECT_WHOLE_ERR; + else if (whole_cmderr) + partials = RTLIL::SELECT_WHOLE_CMDERR; + else + partials = RTLIL::SELECT_ALL; + + char boxes = RTLIL::SB_ALL; + if (warn_boxes) boxes |= RTLIL::SB_WARN; + if (err_boxes) boxes |= RTLIL::SB_ERR; + if (cmderr_boxes) boxes |= RTLIL::SB_CMDERR; + if (unboxed_only) boxes |= RTLIL::SB_UNBOXED_ONLY; + if (include_wb) boxes |= RTLIL::SB_INCL_WB; + + // get sub selection and store the results + auto sub_sel = design->selected_modules(partials, (RTLIL::SelectBoxes)boxes); + pool selected_modules; + dict> selected_members; + + for (auto *mod : sub_sel) { + if (mod->is_selected_whole()) { + log_debug(" Adding %s.\n", mod); + selected_modules.insert(mod->name); + } else for (auto memb : mod->selected_members()) { + log_debug(" Adding %s.%s.\n", mod, memb.name.str()); + selected_members[mod->name].insert(memb.name.ref()); + } + } + + // fully reset current selection + design->selection() = RTLIL::Selection::EmptySelection(design); + + // add back sub selection + for (auto modname : selected_modules) + design->selection().select(design->module(modname)); + for (auto &it : selected_members) { + auto mod = design->module(it.first); + for (auto memb : it.second) + design->selection().select(mod, memb); + } + + // optimize + design->selection().optimize(design); + } +} TestSelectPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/timeest.cc b/chips/yosys/passes/cmds/timeest.cc new file mode 100644 index 0000000000000000000000000000000000000000..dedce78c5c1714114c49fea7bb43237296734cbb --- /dev/null +++ b/chips/yosys/passes/cmds/timeest.cc @@ -0,0 +1,446 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2024 Martin Povišer + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/sigtools.h" +#include "kernel/register.h" +#include "kernel/cellaigs.h" +#include "kernel/utils.h" +#include "kernel/ff.h" +#include "kernel/mem.h" + +#include +#include + +USING_YOSYS_NAMESPACE +template<> struct Yosys::hashlib::hash_ops : Yosys::hashlib::hash_ptr_ops {}; + +PRIVATE_NAMESPACE_BEGIN + +typedef long int arrivalint; +const arrivalint INF_PAST = std::numeric_limits::min(); + +// each clock domain must have its own EstimateSta structure +struct EstimateSta { + SigMap sigmap; + Module *m; + std::optional clk; + bool top_port_endpoints = false; + + dict>, Aig> aigs; + dict cell_aigs; + + std::vector> launchers; + std::vector> samplers; + bool all_paths = false; + bool select = false; + + void add_seq(Cell *cell, SigSpec launch, SigSpec sample) + { + sigmap.apply(launch); + sigmap.apply(sample); + launch.sort_and_unify(); + sample.sort_and_unify(); + for (auto bit : launch) + launchers.push_back(std::make_pair(cell, bit)); + for (auto bit : sample) + samplers.push_back(std::make_pair(cell, bit)); + } + + // we include a discount factor for cells that can be implemented using carry chain logic + // and to account for the AIG model not being balanced + int cell_type_factor(IdString type) + { + if (type.in(ID($gt), ID($ge), ID($lt), ID($le), ID($add), ID($sub), + ID($logic_not), ID($reduce_and), ID($reduce_or), ID($eq))) + return 1; + else + return 2; + } + + // TODO: ignores clock polarity + EstimateSta(Module *m, std::optional clk, bool top_port_endpoints) + : sigmap(m), m(m), clk(clk), top_port_endpoints(top_port_endpoints) + { + if (clk.has_value()) + sigmap.apply(*clk); + } + + void run() + { + log("\n"); + log("Module %s\n", m); + if (clk.has_value()) + log("Domain %s\n", log_signal(*clk)); + + // first, we collect launch and sample points and convert the combinational logic to AIG + std::vector combinational; + + for (auto cell : m->cells()) { + SigSpec launch, sample; + if (cell->is_builtin_ff()) { + // collect launch and sample points for FF cell + FfData ff(nullptr, cell); + if (!ff.has_clk) { + log_warning("Ignoring unsupported storage element '%s' (%s)\n", + cell, cell->type.unescape()); + continue; + } + if (!clk || ff.sig_clk.as_bit() != *clk) + continue; + launch.append(ff.sig_q); + sample.append(ff.sig_d); + if (ff.has_ce) + sample.append(ff.sig_ce); + if (ff.has_srst) + sample.append(ff.sig_srst); + add_seq(cell, launch, sample); + } else if (cell->is_mem_cell()) { + // memories handled separately + continue; + } else if (cell->type == ID($scopeinfo)) { + continue; + } else { + // find or build AIG model of combinational cell + auto fingerprint = std::make_pair(IdString(cell->type), cell->parameters); + if (!aigs.count(fingerprint)) { + aigs.emplace(fingerprint, Aig(cell)); + if (aigs.at(fingerprint).name.empty()) { + log_error("Unsupported cell '%s' in module '%s'\n", + cell->type.unescape(), m); + } + } + + combinational.push_back(cell); + continue; + } + } + + // since we're now taking reference into `aigs`, we can no longer modify it + // and thus have to fill `cell_aigs` in a separate loop + for (auto cell : combinational) { + auto fingerprint = std::make_pair(IdString(cell->type), cell->parameters); + cell_aigs.emplace(cell, &aigs.at(fingerprint)); + } + + // collect launch and sample points for memory cells + for (auto &mem : Mem::get_all_memories(m)) { + for (auto &rd : mem.rd_ports) { + if (!rd.clk_enable) { + log_error("Unsupported async memory port '%s'\n", rd.cell); + continue; + } + if (!clk || sigmap(rd.clk).as_bit() != *clk) + continue; + add_seq(rd.cell, rd.data, {rd.addr, rd.srst, rd.en}); + } + for (auto &wr : mem.wr_ports) { + if (!clk || sigmap(wr.clk).as_bit() != *clk) + continue; + add_seq(wr.cell, {}, {wr.en, wr.addr, wr.data}); + } + } + + // add top module port launching/sampling, if requested + if (top_port_endpoints) { + SigSpec all_inputs, all_outputs; + for (auto port_id : m->ports) { + Wire *port = m->wire(port_id); + if (port->port_input && !port->port_output) { + all_inputs.append(port); + } else if (port->port_output && !port->port_input) { + all_outputs.append(port); + } else if (port->port_output && port->port_input) { + log_warning("Ignoring bi-directional port %s\n", port); + } + } + add_seq(nullptr, all_inputs, all_outputs); + } + + // now we toposort the combinational logic + + // each toposort node is either a SigBit or a pair of Cell * / AigNode * + TopoSort> topo; + + auto desc_aig = [&](Cell *cell, AigNode &node) { + return std::make_tuple(RTLIL::S0, cell, &node); + }; + auto desc_sig = [&](SigBit bit) { + return std::make_tuple(sigmap(bit), (Cell *) NULL, (AigNode *) NULL); + }; + + // collect edges of the AIG graph + for (auto cell : combinational) { + assert(cell_aigs.count(cell)); + Aig &aig = *cell_aigs.at(cell); + for (auto &node : aig.nodes) { + if (node.portname != IdString{}) { + topo.edge( + desc_sig(cell->getPort(node.portname)[node.portbit]), + desc_aig(cell, node) + ); + } else if (node.left_parent < 0 && node.right_parent < 0) { + // constant, nothing to do + } else { + topo.edge( + desc_aig(cell, aig.nodes[node.left_parent]), + desc_aig(cell, node) + ); + topo.edge( + desc_aig(cell, aig.nodes[node.right_parent]), + desc_aig(cell, node) + ); + } + + for (auto &oport : node.outports) { + topo.edge( + desc_aig(cell, node), + desc_sig(cell->getPort(oport.first)[oport.second]) + ); + } + } + } + + if (!topo.sort()) + log_error("Module '%s' contains combinational loops\n", m); + + // now we determine how long it takes for signals to stabilize + + // `levels` records the time after a clock edge after which a signal is stable + dict, arrivalint> levels; + + for (auto node : topo.sorted) + levels[node] = INF_PAST; + + // launch points are at 0 by definition + for (auto pair : launchers) + levels[desc_sig(pair.second)] = 0; + + for (auto node : topo.sorted) { + AigNode *aig_node = std::get<2>(node); + if (aig_node) { + Cell *cell = std::get<1>(node); + Aig &aig = *cell_aigs.at(cell); + if (aig_node->portname != IdString{}) { + // for a cell port, copy `levels` value from port bit + SigBit bit = cell->getPort(aig_node->portname)[aig_node->portbit]; + levels[node] = levels[desc_sig(bit)]; + } else if (aig_node->left_parent < 0 && aig_node->right_parent < 0) { + // constant, nothing to do + } else { + // for each AIG node, find maximum of parents and add a cell-specific delay + int left = levels[desc_aig(cell, aig.nodes[aig_node->left_parent])]; + int right = levels[desc_aig(cell, aig.nodes[aig_node->right_parent])]; + levels[node] = (std::max(left, right) + cell_type_factor(cell->type)); + } + + // copy `levels` value to any output ports + for (auto &oport : aig_node->outports) { + levels[desc_sig(cell->getPort(oport.first)[oport.second])] = levels[node]; + } + } + } + + // now find the length of the critical path (slowest path in the design) + arrivalint crit = INF_PAST; + for (auto pair : samplers) + if (levels[desc_sig(pair.second)] > crit) + crit = levels[desc_sig(pair.second)]; + + if (crit < 0) { + log("No paths found\n"); + return; + } + + log("Critical path is %ld nodes long:\n", crit); + log("\n"); + + // we use dict instead of pool because dict gives us + // some compile-time errors related to hashing + dict, bool> critical; + + // actually find one critical path, or all such paths if requested + for (auto pair : samplers) { + if (levels[desc_sig(pair.second)] == crit) { + critical[desc_sig(pair.second)] = true; + if (!all_paths) + break; + } + } + + // walk backwards through toposorted nodes and set critical flag on nodes in critical path + for (auto it = topo.sorted.rbegin(); it != topo.sorted.rend(); it++) { + auto node = *it; + AigNode *aig_node = std::get<2>(node); + if (aig_node) { + Cell *cell = std::get<1>(node); + Aig &aig = *cell_aigs.at(cell); + + for (auto &oport : aig_node->outports) { + if (critical.count(desc_sig(cell->getPort(oport.first)[oport.second]))) + critical[node] = true; + } + + if (aig_node->portname != IdString{}) { + SigBit bit = cell->getPort(aig_node->portname)[aig_node->portbit]; + if (critical.count(node)) + critical[desc_sig(bit)] = true; + } else if (aig_node->left_parent < 0 && aig_node->right_parent < 0) { + // constant, nothing to do + } else { + // figure out which parent is on the critical path + auto left = desc_aig(cell, aig.nodes[aig_node->left_parent]); + auto right = desc_aig(cell, aig.nodes[aig_node->right_parent]); + int crit_input_lvl = levels[node] - cell_type_factor(cell->type); + if (critical.count(node)) { + bool left_critical = (levels[left] == crit_input_lvl); + bool right_critical = (levels[right] == crit_input_lvl); + if (all_paths) { + if (left_critical) + critical[left] = true; + if (right_critical) + critical[right] = true; + } else { + if (left_critical) + critical[left] = true; + else if (right_critical) + critical[right] = true; + } + } + } + } + } + + // finally print the path we found + SigPool bits_to_select; + pool to_select; + + pool printed; + for (auto node : topo.sorted) { + if (!critical.count(node)) + continue; + AigNode *aig_node = std::get<2>(node); + if (aig_node) { + Cell *cell = std::get<1>(node); + if (!printed.count(cell)) { + to_select.insert(cell->name); + std::string cell_src; + if (cell->has_attribute(ID::src)) { + std::string src_attr = cell->get_src_attribute(); + cell_src = stringf(" source: %s", src_attr); + } + log(" cell %s (%s)%s\n", cell, cell->type.unescape(), cell_src); + printed.insert(cell); + } + } else { + SigBit bit = std::get<0>(node); + bits_to_select.add(bit); + std::string wire_src; + if (bit.wire && bit.wire->has_attribute(ID::src)) { + std::string src_attr = bit.wire->get_src_attribute(); + wire_src = stringf(" source: %s", src_attr); + } + log(" wire %s%s (level %ld)\n", log_signal(bit), wire_src, levels[node]); + } + } + + for (auto wire : m->wires()) { + if (bits_to_select.check_any(sigmap(wire))) + { IdString wn = wire->name; to_select.insert(wn); } + } + + if (select) { + RTLIL::Selection sel(false); + for (auto member : to_select) + sel.selected_members[m->name].insert(member); + m->design->selection_stack.back() = sel; + m->design->selection_stack.back().optimize(m->design); + } + } +}; + +struct TimeestPass : Pass { + TimeestPass() : Pass("timeest", "estimate timing") {} + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" timeest [-clk ] [options] [selection]\n"); + log("\n"); + log("Estimate the critical path by counting AIG nodes.\n"); + log("\n"); + log(" -all_paths\n"); + log(" Print or select nodes from all critical paths instead of focusing on\n"); + log(" a single illustratory path.\n"); + log("\n"); + log(" -select\n"); + log(" Select the nodes of a critical path\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *d) override + { + log_header(d, "Executing TIMEEST pass. (estimate timing)\n"); + + std::string clk_name; + bool clk_domain_specified = false; + bool all_paths = false; + bool select = false; + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + if (args[argidx] == "-all_paths") { + all_paths = true; + continue; + } + if (args[argidx] == "-select") { + select = true; + continue; + } + if (args[argidx] == "-clk" && argidx + 1 < args.size()) { + clk_domain_specified = true; + clk_name = args[++argidx]; + continue; + } + break; + } + extra_args(args, argidx, d); + + if (select && d->selected_modules().size() > 1) + log_cmd_error("The -select option operates on a single selected module\n"); + + for (auto m : d->selected_modules()) { + std::optional clk; + + if (clk_domain_specified) { + IdString clk_ref = d->twines().find(RTLIL::escape_id(clk_name)); + if (!m->wire(clk_ref)) { + log_warning("No domain '%s' in module %s\n", clk_name, m); + continue; + } + + clk = SigBit(m->wire(clk_ref), 0); + } + + EstimateSta sta(m, clk, /*top_port_endpoints=*/ !clk_domain_specified); + sta.all_paths = all_paths; + sta.select = select; + sta.run(); + } + } +} TimeestPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/torder.cc b/chips/yosys/passes/cmds/torder.cc new file mode 100644 index 0000000000000000000000000000000000000000..d9f27510752833e7ce052c784706af48eb66b581 --- /dev/null +++ b/chips/yosys/passes/cmds/torder.cc @@ -0,0 +1,129 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "kernel/newcelltypes.h" +#include "kernel/sigtools.h" +#include "kernel/utils.h" +#include "kernel/log_help.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct TorderPass : public Pass { + TorderPass() : Pass("torder", "print cells in topological order") { } + bool formatted_help() override { + auto *help = PrettyHelp::get_current(); + help->set_group("passes/status"); + return false; + } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" torder [options] [selection]\n"); + log("\n"); + log("This command prints the selected cells in topological order.\n"); + log("\n"); + log(" -stop \n"); + log(" do not use the specified cell port in topological sorting\n"); + log("\n"); + log(" -noautostop\n"); + log(" by default Q outputs of internal FF cells and memory read port outputs\n"); + log(" are not used in topological sorting. this option deactivates that.\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + bool noautostop = false; + dict> stop_db; + + log_header(design, "Executing TORDER pass (print cells in topological order).\n"); + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + if (args[argidx] == "-stop" && argidx+2 < args.size()) { + IdString cell_type = design->twines().add(RTLIL::escape_id(args[++argidx])); + IdString cell_port = design->twines().add(RTLIL::escape_id(args[++argidx])); + stop_db[cell_type].insert(cell_port); + continue; + } + if (args[argidx] == "-noautostop") { + noautostop = true; + continue; + } + break; + } + extra_args(args, argidx, design); + + for (auto module : design->selected_modules()) + { + log("module %s\n", module); + + SigMap sigmap(module); + dict> bit_drivers, bit_users; + TopoSort toposort(RTLIL::sort_by_id_str(module->twines())); + + for (auto cell : module->selected_cells()) + for (auto conn : cell->connections()) + { + if (stop_db.count(IdString(cell->type)) && stop_db.at(IdString(cell->type)).count(conn.first)) + continue; + + if (!noautostop && yosys_celltypes.cell_known(cell->type)) { + if (conn.first.in(ID::Q, ID::CTRL_OUT, ID::RD_DATA)) + continue; + if (cell->type.in(ID($memrd), ID($memrd_v2)) && conn.first == ID::DATA) + continue; + } + + if (cell->input(conn.first)) + for (auto bit : sigmap(conn.second)) + bit_users[bit].insert(cell->name); + + if (cell->output(conn.first)) + for (auto bit : sigmap(conn.second)) + bit_drivers[bit].insert(cell->name); + + toposort.node(cell->name); + } + + 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); + + toposort.analyze_loops = true; + toposort.sort(); + + for (auto &it : toposort.loops) { + std::string message = " loop"; + for (auto cell : it) + message += stringf(" %s", design->twines().str(cell)); + log("%s\n", message); + } + + for (auto cell : toposort.sorted) + log(" cell %s\n", design->twines().str(cell)); + } + } +} TorderPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/trace.cc b/chips/yosys/passes/cmds/trace.cc new file mode 100644 index 0000000000000000000000000000000000000000..331019d40deff61834a6c4aa61c7ab13cf4d142d --- /dev/null +++ b/chips/yosys/passes/cmds/trace.cc @@ -0,0 +1,163 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2014 Claire Xenia Wolf + * Copyright (C) 2014 Johann Glaser + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "kernel/log_help.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct TraceMonitor : public RTLIL::Monitor +{ + void notify_module_add(RTLIL::Module *module) override + { + log("#TRACE# Module add: %s\n", module); + } + + void notify_module_del(RTLIL::Module *module) override + { + log("#TRACE# Module delete: %s\n", module); + } + + void notify_connect(RTLIL::Cell *cell, RTLIL::IdString port, const RTLIL::SigSpec &old_sig, const RTLIL::SigSpec &sig) override + { + log("#TRACE# Cell connect: %s.%s.%s = %s (was: %s)\n", cell->module, cell, PooledName(cell->module, port).unescape(), log_signal(sig), log_signal(old_sig)); + } + + void notify_connect(RTLIL::Module *module, const RTLIL::SigSig &sigsig) override + { + log("#TRACE# Connection in module %s: %s = %s\n", module, log_signal(sigsig.first), log_signal(sigsig.second)); + } + + void notify_connect(RTLIL::Module *module, const std::vector &sigsig_vec) override + { + log("#TRACE# New connections in module %s:\n", module); + for (auto &sigsig : sigsig_vec) + log("## %s = %s\n", log_signal(sigsig.first), log_signal(sigsig.second)); + } + + void notify_blackout(RTLIL::Module *module) override + { + log("#TRACE# Blackout in module %s:\n", module); + } +}; + +struct TracePass : public Pass { + TracePass() : Pass("trace", "redirect command output to file") { } + bool formatted_help() override { + auto *help = PrettyHelp::get_current(); + help->set_group("passes/status"); + return false; + } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" trace cmd\n"); + log("\n"); + log("Execute the specified command, logging all changes the command performs on\n"); + log("the design in real time.\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) + { + // .. parse options .. + break; + } + + TraceMonitor monitor; + design->monitors.insert(&monitor); + + try { + std::vector new_args(args.begin() + argidx, args.end()); + Pass::call(design, new_args); + } catch (...) { + design->monitors.erase(&monitor); + throw; + } + + design->monitors.erase(&monitor); + } +} TracePass; + +struct DebugPass : public Pass { + DebugPass() : Pass("debug", "run command with debug log messages enabled") { } + bool formatted_help() override { + auto *help = PrettyHelp::get_current(); + help->set_group("passes/status"); + return false; + } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" debug cmd\n"); + log("\n"); + log("Execute the specified command with debug log messages enabled\n"); + log("\n"); + log(" debug -on\n"); + log(" debug -off\n"); + log("\n"); + log("Enable or disable debug log messages globally\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + size_t argidx; + bool mode_on = false; + bool mode_off = false; + + for (argidx = 1; argidx < args.size(); argidx++) + { + if (args[argidx] == "-on") { + mode_on = true; + continue; + } + if (args[argidx] == "-off") { + mode_off = true; + continue; + } + break; + } + + if (mode_on && mode_off) + log_cmd_error("Cannot specify both -on and -off\n"); + + if (mode_on) { + logger().force_debug_on(); + return; + } + + if (mode_off) { + logger().force_debug_off(); + return; + } + + auto force_debug = logger().force_debug_scope(true); + + std::vector new_args(args.begin() + argidx, args.end()); + Pass::call(design, new_args); + } +} DebugPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/viz.cc b/chips/yosys/passes/cmds/viz.cc new file mode 100644 index 0000000000000000000000000000000000000000..69ac6064a18d7b8755b1c175d36b7009311a3574 --- /dev/null +++ b/chips/yosys/passes/cmds/viz.cc @@ -0,0 +1,1087 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "kernel/sigtools.h" +#include "kernel/log_help.h" + +#ifndef _WIN32 +# include +#endif + +#ifdef __APPLE__ +# include +#endif + +#ifdef YOSYS_ENABLE_READLINE +# include +#endif + +#ifdef YOSYS_ENABLE_EDITLINE +# include +#endif + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct VizConfig { + enum group_type_t { + TYPE_G, + TYPE_U, + TYPE_X, + TYPE_S + }; + + int effort = 9; + int similar_thresh = 30; + int small_group_thresh = 10; + int large_group_count = 10; + std::vector> groups; +}; + +struct GraphNode { + int index = -1; + bool nomerge = false; + bool terminal = false; + bool excluded = false; + bool special = false; + GraphNode *replaced = nullptr; + + GraphNode *get() { + if (replaced == nullptr) + return this; + return replaced = replaced->get(); + } + + pool names_; + dict tags_; + pool upstream_; + pool downstream_; + + pool &names() { return get()->names_; } + dict &tags() { return get()->tags_; } + pool &upstream() { return get()->upstream_; } + pool &downstream() { return get()->downstream_; } + + uint8_t tag(int index) { + return tags().at(index, 0); + } + + bool tag(int index, uint8_t mask) { + if (!mask) return false; + uint8_t &v = tags()[index]; + if (v == (v|mask)) return false; + v |= mask; + return true; + } +}; + +struct Graph { + bool dirty = true; + int phase_counter = 0; + + vector nodes; + vector term_nodes; + vector nonterm_nodes; + vector replaced_nodes; + + Module *module; + const VizConfig &config; + + // statistics and indices, updated by update() + std::vector max_group_sizes; + double mean_group_size; + double rms_group_size; + int edge_count, tag_count; + + ~Graph() + { + for (auto n : nodes) delete n; + for (auto n : replaced_nodes) delete n; + } + + GraphNode *node(int index) + { + if (index) + return nodes[index-1]->get(); + return nullptr; + } + + void update_nodes() + { + // Filter-out replaced nodes + + term_nodes.clear(); + nonterm_nodes.clear(); + + for (auto n : nodes) { + if (n->replaced) + replaced_nodes.push_back(n); + else if (n->terminal) + term_nodes.push_back(n); + else + nonterm_nodes.push_back(n); + } + + // Re-index the remaining nodes + + nodes.clear(); + + max_group_sizes.clear(); + max_group_sizes.resize(config.large_group_count); + + mean_group_size = 0; + rms_group_size = 0; + edge_count = 0; + + auto update_node = [&](GraphNode *n) + { + nodes.push_back(n); + n->index = GetSize(nodes); + + pool new_upstream; + pool new_downstream; + + for (auto g : n->upstream()) { + if (n != (g = g->get())) + new_upstream.insert(g); + } + for (auto g : n->downstream()) { + if (n != (g = g->get())) + new_downstream.insert(g), edge_count++; + } + + new_upstream.sort(); + new_downstream.sort(); + + std::swap(n->upstream(), new_upstream); + std::swap(n->downstream(), new_downstream); + + if (!n->terminal) { + int t = GetSize(n->names()); + mean_group_size += t; + rms_group_size += t*t; + for (int i = 0; i < config.large_group_count; i++) + if (t >= max_group_sizes[i]) + std::swap(t, max_group_sizes[i]); + } + }; + + for (auto n : term_nodes) + update_node(n); + + for (auto n : nonterm_nodes) + update_node(n); + + mean_group_size /= GetSize(nonterm_nodes); + rms_group_size = sqrt(rms_group_size / GetSize(nonterm_nodes)); + } + + void update_tags() + { + std::function up_down_prop_tag = + [&](GraphNode *g, int index, bool down) + { + for (auto n : (down ? g->downstream_ : g->upstream_)) { + if (n->tag(index, down ? 2 : 1)) { + if (!n->terminal) + up_down_prop_tag(n, index, down); + tag_count++; + } + } + }; + + tag_count = 0; + for (auto g : nodes) + g->tags().clear(); + + for (auto g : term_nodes) { + up_down_prop_tag(g, g->index, false); + up_down_prop_tag(g, g->index, true); + } + + for (auto g : nodes) + g->tags().sort(); + } + + bool update() + { + if (!dirty) { + std::string message = " Largest non-term group sizes: "; + for (int i = 0; i < config.large_group_count; i++) + message += stringf("%d%s", max_group_sizes[i], i+1 == config.large_group_count ? "." : " "); + log("%s\n", message); + // log(" Mean and Root-Mean-Square group sizes: %.1f and %.1f\n", mean_group_size, rms_group_size); + + return false; + } + + dirty = false; + update_nodes(); + update_tags(); + + log(" Status: %d nodes (%d term and %d non-term), %d edges, and %d tags\n", + GetSize(nodes), GetSize(term_nodes), GetSize(nonterm_nodes), edge_count, tag_count); + return true; + } + + void merge(GraphNode *g, GraphNode *n) + { + g = g->get(); + n = n->get(); + + log_assert(!g->nomerge); + log_assert(!n->nomerge); + log_assert(g->terminal == n->terminal); + + if (g == n) return; + + for (auto v : n->names_) + g->names_.insert(v); + + for (auto v : n->tags_) + g->tags_[v.first] |= v.second; + + for (auto v : n->upstream_) { + if (g != (v = v->get())) + g->upstream_.insert(v); + } + + for (auto v : n->downstream_) { + if (g != (v = v->get())) + g->downstream_.insert(v); + } + + n->names_.clear(); + n->tags_.clear(); + n->upstream_.clear(); + n->downstream_.clear(); + + dirty = true; + n->replaced = g; + } + + Graph(Module *module, const VizConfig &config) : module(module), config(config) + { + log("Running 'viz -%d' for module %s:\n", config.effort, module); + log(" Phase %d: Construct initial graph\n", phase_counter++); + + SigMap sigmap(module); + dict wire_nodes; + + for (auto wire : module->selected_wires()) + { + if (!wire->name.isPublic()) continue; + auto g = new GraphNode; + g->terminal = true; + g->names().insert(wire->name); + nodes.push_back(g); + + for (auto bit : sigmap(wire)) { + if (!bit.wire) continue; + auto it = wire_nodes.find(bit); + if (it == wire_nodes.end()) + wire_nodes[bit] = g; + else + merge(g, it->second); + } + } + + pool excluded; + + for (auto grp : config.groups) + { + GraphNode *g = nullptr; + + if (!grp.second.selected_module(module->name)) + continue; + + for (auto wire : module->wires()) { + if (!wire->name.isPublic()) continue; + if (!grp.second.selected_member(module->name, wire->name)) continue; + for (auto bit : sigmap(wire)) { + auto it = wire_nodes.find(bit); + if (it == wire_nodes.end()) + continue; + auto n = it->second->get(); + if (n->nomerge) + continue; + if (grp.first == VizConfig::TYPE_G || grp.first == VizConfig::TYPE_S) { + if (g) { + if (!n->nomerge) + merge(g, n); + } else + g = n; + } else if (grp.first == VizConfig::TYPE_U) { + n->nomerge = true; + } else if (grp.first == VizConfig::TYPE_X) { + n->nomerge = true; + excluded.insert(n); + } else + log_abort(); + } + } + + if (g) { + if (grp.first == VizConfig::TYPE_S) + g->special = true; + g->nomerge = true; + } + } + + for (auto g : excluded) + excluded.insert(g->get()); + + dict cell_nodes; + dict> sig_users; + + for (auto cell : module->selected_cells()) { + auto g = new GraphNode; + cell_nodes[cell] = g; + g->names().insert(cell->name); + nodes.push_back(g); + + for (auto &conn : cell->connections()) { + if (cell->input(conn.first)) + for (auto bit : sigmap(conn.second)) { + if (!bit.wire) continue; + auto it = wire_nodes.find(bit); + if (it != wire_nodes.end()) { + auto n = it->second->get(); + if (!excluded.count(n)) { + g->upstream().insert(n); + n->downstream().insert(g); + } + } else { + sig_users[bit].insert(g); + } + } + if (cell->output(conn.first)) + for (auto bit : sigmap(conn.second)) { + if (!bit.wire) continue; + auto it = wire_nodes.find(bit); + if (it != wire_nodes.end()) { + auto n = it->second->get(); + if (!excluded.count(n)) { + g->downstream().insert(n); + n->upstream().insert(g); + } + } + } + } + } + + for (auto cell : module->selected_cells()) { + auto g = cell_nodes.at(cell); + + for (auto &conn : cell->connections()) { + if (!cell->output(conn.first)) continue; + for (auto bit : sigmap(conn.second)) { + if (!bit.wire) continue; + for (auto u : sig_users[bit]) { + g->downstream().insert(u); + u->upstream().insert(g); + } + } + } + } + + update(); + } + + int compare_tags(GraphNode *g, GraphNode *n, bool strict_mode) + { + if (GetSize(g->tags()) > GetSize(n->tags())) + return compare_tags(n, g, strict_mode); + + if (g->tags().empty()) + return 100; + + bool gn_specials = true; + bool g_nonspecials = false; + bool n_nonspecials = false; + + int score = 0; + for (auto it : g->tags()) { + auto g_tag = it.second; + auto n_tag = n->tag(it.first); + log_assert(g_tag != 0); + if (node(it.first)->special) { + gn_specials = true; + if (g_tag != n_tag) return 0; + } else + g_nonspecials = true; + if (n_tag == 0) continue; + if (g_tag == n_tag) + score += 2; + else if (!strict_mode && (g_tag + n_tag == 4)) + score += 1; + else + return 0; + } + for (auto it : n->tags()) { + auto n_tag = it.second; + log_assert(n_tag != 0); + if (node(it.first)->special) { + gn_specials = true; + auto g_tag = g->tag(it.first); + if (g_tag != n_tag) return 0; + } else + n_nonspecials = true; + } + + if (gn_specials && (g_nonspecials != n_nonspecials)) + return 0; + + return (100*score) / GetSize(g->tags()); + } + + int phase(bool term, int effort) + { + log(" Phase %d: Merge %sterminal nodes with effort level %d\n", phase_counter++, term ? "" : "non-", effort); + int start_replaced_nodes = GetSize(replaced_nodes); + + do { + dict>> candidates; + auto queue = [&](GraphNode *g, GraphNode *n) -> bool { + if (g->terminal != n->terminal) + return false; + if (g->nomerge || n->nomerge) + return false; + int sz = GetSize(g->names()) + GetSize(n->names()); + if (g->index < n->index) + candidates[sz].insert(pair(g->index, n->index)); + else if (g->index != n->index) + candidates[sz].insert(pair(n->index, g->index)); + return true; + }; + + int last_candidates_size = 0; + const char *last_section_header = nullptr; + auto header = [&](const char *p = nullptr) { + if (GetSize(candidates) != last_candidates_size && last_section_header) + log(" Found %d cadidates of type '%s'.\n", + GetSize(candidates) - last_candidates_size, last_section_header); + last_candidates_size = GetSize(candidates); + last_section_header = p; + }; + + { + header("Any nodes with identical connections"); + typedef pair, pool> node_conn_t; + dict> nodes_by_conn; + for (auto g : term ? term_nodes : nonterm_nodes) { + auto &entry = nodes_by_conn[node_conn_t(g->upstream(), g->downstream())]; + for (auto n : entry) + queue(g, n); + entry.insert(g); + } + } + + if (!candidates.empty() || effort < 1) goto execute; + + if (!term) { + header("Source-Sink with identical tags"); + for (auto g : nonterm_nodes) { + for (auto n : g->downstream()) { + if (n->terminal) continue; + if (g->tags() == n->tags()) queue(g, n); + } + } + + header("Sibblings with identical tags"); + for (auto g : nonterm_nodes) { + auto process_conns = [&](const pool &stream) { + dict, pool> nodes_by_tags; + for (auto n : stream) { + if (n->terminal) continue; + std::vector key; + for (auto kv : n->tags()) + key.push_back(kv.first), key.push_back(kv.second); + auto &entry = nodes_by_tags[key]; + for (auto m : entry) queue(n, m); + entry.insert(n); + } + }; + process_conns(g->upstream()); + process_conns(g->downstream()); + } + } + + if (!candidates.empty() || effort < 2) goto execute; + + if (!term) { + header("Nodes with single fan-out and compatible tags"); + for (auto g : nonterm_nodes) { + if (GetSize(g->downstream()) != 1) continue; + auto n = *g->downstream().begin(); + if (!n->terminal && compare_tags(g, n, true)) queue(g, n); + } + + header("Nodes with single fan-in and compatible tags"); + for (auto g : nonterm_nodes) { + if (GetSize(g->upstream()) != 1) continue; + auto n = *g->upstream().begin(); + if (!n->terminal && compare_tags(g, n, true)) queue(g, n); + } + } + + if (!candidates.empty() || effort < 3) goto execute; + + if (!term) { + header("Connected nodes with similar tags (strict)"); + for (auto g : nonterm_nodes) { + for (auto n : g->downstream()) + if (!n->terminal && compare_tags(g, n, true) > config.similar_thresh) queue(g, n); + } + } + + if (!candidates.empty() || effort < 4) goto execute; + + if (!term) { + header("Sibblings with similar tags (strict)"); + for (auto g : nonterm_nodes) { + auto process_conns = [&](const pool &stream) { + std::vector nodes; + for (auto n : stream) + if (!n->terminal) nodes.push_back(n); + for (int i = 0; i < GetSize(nodes); i++) + for (int j = 0; j < i; j++) + if (compare_tags(nodes[i], nodes[j], true) > config.similar_thresh) + queue(nodes[i], nodes[j]); + }; + process_conns(g->upstream()); + process_conns(g->downstream()); + } + } + + if (!candidates.empty() || effort < 5) goto execute; + + if (!term) { + header("Connected nodes with similar tags (non-strict)"); + for (auto g : nonterm_nodes) { + for (auto n : g->downstream()) + if (!n->terminal && compare_tags(g, n, false) > config.similar_thresh) queue(g, n); + } + } + + if (!candidates.empty() || effort < 6) goto execute; + + if (!term) { + header("Sibblings with similar tags (non-strict)"); + for (auto g : nonterm_nodes) { + auto process_conns = [&](const pool &stream) { + std::vector nodes; + for (auto n : stream) + if (!n->terminal) nodes.push_back(n); + for (int i = 0; i < GetSize(nodes); i++) + for (int j = 0; j < i; j++) + if (compare_tags(nodes[i], nodes[j], false) > config.similar_thresh) + queue(nodes[i], nodes[j]); + }; + process_conns(g->upstream()); + process_conns(g->downstream()); + } + } + + if (!candidates.empty() || effort < 7) goto execute; + + { + header("Any nodes with identical fan-in or fan-out"); + dict, pool> nodes_by_conn[2]; + for (auto g : term ? term_nodes : nonterm_nodes) { + auto &up_entry = nodes_by_conn[0][g->upstream()]; + auto &down_entry = nodes_by_conn[1][g->downstream()]; + for (auto n : up_entry) queue(g, n); + for (auto n : down_entry) queue(g, n); + up_entry.insert(g); + down_entry.insert(g); + } + } + + if (!candidates.empty() || effort < 8) goto execute; + + if (!term) { + header("Connected nodes with similar tags (lax)"); + for (auto g : nonterm_nodes) { + for (auto n : g->downstream()) + if (!n->terminal && compare_tags(g, n, false)) queue(g, n); + } + } + + if (!candidates.empty() || effort < 9) goto execute; + + if (!term) { + header("Sibblings with similar tags (lax)"); + for (auto g : nonterm_nodes) { + auto process_conns = [&](const pool &stream) { + std::vector nodes; + for (auto n : stream) + if (!n->terminal) nodes.push_back(n); + for (int i = 0; i < GetSize(nodes); i++) + for (int j = 0; j < i; j++) + if (compare_tags(nodes[i], nodes[j], false)) + queue(nodes[i], nodes[j]); + }; + process_conns(g->upstream()); + process_conns(g->downstream()); + } + } + + execute: + header(); + candidates.sort(); + bool small_mode = false; + bool medium_mode = false; + for (auto &candidate_group : candidates) { + for (auto &candidate : candidate_group.second) { + auto g = node(candidate.first); + auto n = node(candidate.second); + if (!term) { + int sz = GetSize(g->names()) + GetSize(n->names()); + if (sz <= config.small_group_thresh) + small_mode = true; + else if (small_mode && sz >= max_group_sizes.back()) + continue; + if (sz <= max_group_sizes.front()) + medium_mode = true; + else if (medium_mode && sz > max_group_sizes.front()) + continue; + } + merge(g, n); + } + } + if (small_mode) + log(" Using 'small-mode' to prevent big groups.\n"); + else if (medium_mode) + log(" Using 'medium-mode' to prevent big groups.\n"); + } while (update()); + + int merged_nodes = GetSize(replaced_nodes) - start_replaced_nodes; + log(" Merged a total of %d nodes.\n", merged_nodes); + return merged_nodes; + } +}; + +struct VizWorker +{ + VizConfig config; + Module *module; + Graph graph; + + VizWorker(Module *module, const VizConfig &cfg) : config(cfg), module(module), graph(module, config) + { + for (int effort = 0; effort <= config.effort; effort++) { + bool first = true; + while (1) { + if (!graph.phase(false, effort) && !first) break; + if (!graph.phase(true, effort)) break; + first = false; + } + log(" %s: %d nodes (%d term and %d non-term), %d edges, and %d tags\n", + effort == config.effort ? "Final" : "Status", GetSize(graph.nodes), + GetSize(graph.term_nodes), GetSize(graph.nonterm_nodes), + graph.edge_count, graph.tag_count); + } + } + + void update_attrs() + { + IdString vg_id = module->twines().add("\\vg"); + for (auto c : module->cells()) + c->attributes.erase(vg_id); + for (auto g : graph.nodes) { + for (auto ref : g->names()) { + auto w = module->wire(ref); + auto c = module->cell(ref); + if (w) w->attributes[vg_id] = g->index; + if (c) c->attributes[vg_id] = g->index; + } + } + } + + void write_dot(FILE *f) + { + fprintf(f, "digraph \"%s\" {\n", module->name.unescape().c_str()); + fprintf(f, " rankdir = LR;\n"); + + dict>> extra_lines; + dict bypass_nodes; + pool bypass_candidates; + + auto bypass = [&](GraphNode *g, GraphNode *n) { + log_assert(g->terminal); + log_assert(!n->terminal); + bypass_nodes[g] = n; + + auto &buffer = extra_lines[n]; + buffer.emplace_back(); + + for (auto name : g->names()) + buffer.back().push_back(module->twines().unescaped_str(name)); + + std::sort(buffer.back().begin(), buffer.back().end()); + std::sort(buffer.begin(), buffer.end()); + }; + + for (auto g : graph.nonterm_nodes) { + for (auto n : g->downstream()) + if (!n->terminal) goto not_a_candidate; + bypass_candidates.insert(g); + not_a_candidate:; + } + + for (auto g : graph.term_nodes) + { + if (g->special || bypass_nodes.count(g)) continue; + if (GetSize(g->upstream()) != 1) continue; + if (!g->downstream().empty() && g->downstream() != g->upstream()) continue; + + auto n = *(g->upstream().begin()); + if (n->terminal || !bypass_candidates.count(n)) continue; + + bypass(g, n); + } + + for (auto g : graph.term_nodes) + { + if (g->special || bypass_nodes.count(g)) continue; + if (GetSize(g->upstream()) != 1) continue; + + auto n = *(g->upstream().begin()); + if (n->terminal || !bypass_candidates.count(n)) continue; + + if (GetSize(n->downstream()) != 1) continue; + if (extra_lines.count(n)) continue; + + bypass(g, n); + } + + for (auto g : graph.nodes) { + if (g->downstream().empty() && g->upstream().empty()) + continue; + if (bypass_nodes.count(g)) + continue; + if (g->terminal) { + g->names().sort(); + std::string label; // = stringf("vg=%d\\n", g->index); + for (auto n : g->names()) + label = label + (label.empty() ? "" : "\\n") + PooledName(module, n).unescape(); + fprintf(f, "\tn%d [shape=rectangle,label=\"%s\"];\n", g->index, label.c_str()); + } else { + std::string label = stringf("vg=%d | %d cells", g->index, GetSize(g->names())); + std::string shape = "oval"; + if (extra_lines.count(g)) { + for (auto &block : extra_lines.at(g)) { + label += label.empty() ? "" : "\\n"; + for (auto &line : block) + label = label + (label.empty() ? "" : "\\n") + line; + shape = "octagon"; + } + } + fprintf(f, "\tn%d [shape=%s,label=\"%s\"];\n", g->index, shape.c_str(), label.c_str()); + } + } + + pool edges; + for (auto g : graph.nodes) { + auto p = bypass_nodes.at(g, g); + for (auto n : g->downstream()) { + auto q = bypass_nodes.at(n, n); + if (p == q) continue; + edges.insert(stringf("n%d -> n%d", p->index, q->index)); + } + } + edges.sort(); + for (auto e : edges) + fprintf(f, "\t%s;\n", e.c_str()); + + fprintf(f, "}\n"); + } +}; + +struct VizPass : public Pass { + VizPass() : Pass("viz", "visualize data flow graph") { } + bool formatted_help() override { + auto *help = PrettyHelp::get_current(); + help->set_group("passes/status"); + return false; + } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" viz [options] [selection]\n"); + log("\n"); + log("Create a graphviz DOT file for the selected part of the design, showing the\n"); + log("relationships between the selected wires, and compile it to a graphics\n"); + log("file (usually SVG or PostScript).\n"); + log("\n"); + log(" -viewer \n"); + log(" Run the specified command with the graphics file as parameter.\n"); + log(" On Windows, this pauses yosys until the viewer exits.\n"); + log("\n"); + log(" -format \n"); + log(" Generate a graphics file in the specified format. Use 'dot' to just\n"); + log(" generate a .dot file, or other strings such as 'svg' or 'ps'\n"); + log(" to generate files in other formats (this calls the 'dot' command).\n"); + log("\n"); + log(" -prefix \n"); + log(" generate .* instead of ~/.yosys_viz.*\n"); + log("\n"); + log(" -pause\n"); + log(" wait for the user to press enter to before returning\n"); + log("\n"); + log(" -nobg\n"); + log(" don't run viewer in the background, IE wait for the viewer tool to\n"); + log(" exit before returning\n"); + log("\n"); + log(" -set-vg-attr\n"); + log(" set their group index as 'vg' attribute on cells and wires\n"); + log("\n"); + log(" -g \n"); + log(" manually define a group of terminal signals. this group is not being\n"); + log(" merged with other terminal groups.\n"); + log("\n"); + log(" -u \n"); + log(" manually define a unique group for each wire in the selection.\n"); + log("\n"); + log(" -x \n"); + log(" manually exclude wires from being considered. (usually this is\n"); + log(" used for global signals, such as reset.)\n"); + log("\n"); + log(" -s \n"); + log(" like -g, but mark group as 'special', changing the algorithm to\n"); + log(" preserve as much info about this groups connectivity as possible.\n"); + log("\n"); + log(" -G .\n"); + log(" -U .\n"); + log(" -X .\n"); + log(" -S .\n"); + log(" like -u, -g, -x, and -s, but parse all arguments up to a terminating .\n"); + log(" as a single select expression. (see 'help select' for details)\n"); + log("\n"); + log(" -0, -1, -2, -3, -4, -5, -6, -7, -8, -9\n"); + log(" select effort level. each level corresponds to an incresingly more\n"); + log(" aggressive sequence of strategies for merging nodes of the data flow\n"); + log(" graph. (default: %d)\n", VizConfig().effort); + log("\n"); + log("When no is specified, 'dot' is used. When no and is\n"); + log("specified, 'xdot' is used to display the schematic (POSIX systems only).\n"); + log("\n"); + log("The generated output files are '~/.yosys_viz.dot' and '~/.yosys_viz.',\n"); + log("unless another prefix is specified using -prefix .\n"); + log("\n"); + log("Yosys on Windows and YosysJS use different defaults: The output is written\n"); + log("to 'show.dot' in the current directory and new viewer is launched each time\n"); + log("the 'show' command is executed.\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + log_header(design, "Generating Graphviz representation of design.\n"); + log_push(); + +#if defined(_WIN32) || !defined(YOSYS_ENABLE_SPAWN) + std::string format = "dot"; + std::string prefix = "show"; +#else + std::string format; + std::string prefix = stringf("%s/.yosys_viz", getenv("HOME") ? getenv("HOME") : "."); +#endif + std::string viewer_exe; + bool flag_pause = false; + bool flag_attr = false; + bool custom_prefix = false; + std::string background = "&"; + + VizConfig config; + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) + { + std::string arg = args[argidx]; + if (arg == "-viewer" && argidx+1 < args.size()) { + viewer_exe = args[++argidx]; + continue; + } + if (arg == "-prefix" && argidx+1 < args.size()) { + prefix = args[++argidx]; + custom_prefix = true; + continue; + } + if (arg == "-format" && argidx+1 < args.size()) { + format = args[++argidx]; + continue; + } + if (arg == "-pause") { + flag_pause= true; + continue; + } + if (arg == "-set-vg-attr") { + flag_attr= true; + continue; + } + if (arg == "-nobg") { + background= ""; + continue; + } + if ((arg == "-g" || arg == "-u" || arg == "-x" || arg == "-s" || + arg == "-G" || arg == "-U" || arg == "-X" || arg == "-S") && argidx+1 < args.size()) { + int numargs = 1; + int first_arg = ++argidx; + if (arg == "-G" || arg == "-U" || arg == "-X" || arg == "-S") { + while (argidx+1 < args.size()) { + if (args[++argidx] == ".") break; + numargs++; + } + } + handle_extra_select_args(this, args, first_arg, first_arg+numargs, design); + auto type = arg == "-g" || arg == "-G" ? VizConfig::TYPE_G : + arg == "-u" || arg == "-U" ? VizConfig::TYPE_U : + arg == "-x" || arg == "-X" ? VizConfig::TYPE_X : VizConfig::TYPE_S; + config.groups.push_back({type, design->selection()}); + design->pop_selection(); + continue; + } + if (arg == "-0" || arg == "-1" || arg == "-2" || arg == "-3" || arg == "-4" || + arg == "-5" || arg == "-6" || arg == "-7" || arg == "-8" || arg == "-9") { + config.effort = arg[1] - '0'; + continue; + } + break; + } + extra_args(args, argidx, design); + + std::vector modlist; + for (auto module : design->selected_modules()) { + if (module->get_blackbox_attribute()) + continue; + if (module->cells().size() == 0 && module->connections().empty()) + continue; + modlist.push_back(module); + } + if (format != "ps" && format != "dot" && GetSize(modlist) > 1) + log_cmd_error("For formats different than 'ps' or 'dot' only one module must be selected.\n"); + if (modlist.empty()) + log_cmd_error("Nothing there to show.\n"); + + std::string dot_file = stringf("%s.dot", prefix); + std::string out_file = stringf("%s.%s", prefix, format.empty() ? "svg" : format); + + if (custom_prefix) + yosys_output_files.insert(dot_file); + + log("Writing dot description to `%s'.\n", dot_file); + FILE *f = nullptr; + auto open_dot_file = [&]() { + if (f != nullptr) return; + f = fopen(dot_file.c_str(), "w"); + if (f == nullptr) + log_cmd_error("Can't open dot file `%s' for writing.\n", dot_file); + }; + for (auto module : modlist) { + VizWorker worker(module, config); + + if (flag_attr) + worker.update_attrs(); + + if (format != "dot" && GetSize(worker.graph.nodes) > 200) { + if (format.empty()) { + log_warning("Suppressing module in output as graph size exceeds 200 nodes.\n"); + continue; + } else { + log_warning("Changing format to 'dot' as graph size exceeds 200 nodes.\n"); + format = "dot"; + } + } + + // delay opening of output file until we have something to write, to avoid race with xdot + open_dot_file(); + worker.write_dot(f); + } + open_dot_file(); + fclose(f); + + if (format != "dot" && !format.empty()) { + #ifdef _WIN32 + // system()/cmd.exe does not understand single quotes on Windows. + #define DOT_CMD "dot -T%s \"%s\" > \"%s.new\" && move \"%s.new\" \"%s\"" + #else + #define DOT_CMD "dot -T%s '%s' > '%s.new' && mv '%s.new' '%s'" + #endif + std::string cmd = stringf(DOT_CMD, format, dot_file, out_file, out_file, out_file); + #undef DOT_CMD + log("Exec: %s\n", cmd); + #if defined(YOSYS_ENABLE_SPAWN) + if (run_command(cmd) != 0) + log_cmd_error("Shell command failed!\n"); + #endif + } + + #if !defined(YOSYS_ENABLE_SPAWN) + log_assert(viewer_exe.empty() && !format.empty()); + #else + if (!viewer_exe.empty()) { + #ifdef _WIN32 + // system()/cmd.exe does not understand single quotes nor + // background tasks on Windows. So we have to pause yosys + // until the viewer exits. + std::string cmd = stringf("%s \"%s\"", viewer_exe, out_file); + #else + std::string cmd = stringf("%s '%s' %s", viewer_exe, out_file, background); + #endif + log("Exec: %s\n", cmd); + if (run_command(cmd) != 0) + log_cmd_error("Shell command failed!\n"); + } else + if (format.empty()) { + #ifdef __APPLE__ + std::string cmd = stringf("ps -fu %d | grep -q '[ ]%s' || xdot '%s' %s", getuid(), dot_file, dot_file, background); + #else + std::string cmd = stringf("{ test -f '%s.pid' && fuser -s '%s.pid' 2> /dev/null; } || ( echo $$ >&3; exec xdot '%s'; ) 3> '%s.pid' %s", dot_file, dot_file, dot_file, dot_file, background); + #endif + log("Exec: %s\n", cmd); + if (run_command(cmd) != 0) + log_cmd_error("Shell command failed!\n"); + } + #endif + + if (flag_pause) { + #ifdef YOSYS_ENABLE_READLINE + char *input = nullptr; + while ((input = readline("Press ENTER to continue (or type 'shell' to open a shell)> ")) != nullptr) { + if (input[strspn(input, " \t\r\n")] == 0) + break; + char *p = input + strspn(input, " \t\r\n"); + if (!strcmp(p, "shell")) { + Pass::call(design, "shell"); + break; + } + } + #else + log_cmd_error("This version of yosys is built without readline support => 'show -pause' is not available.\n"); + #endif + } + + log_pop(); + } +} VizPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/wrapcell.cc b/chips/yosys/passes/cmds/wrapcell.cc new file mode 100644 index 0000000000000000000000000000000000000000..fb6670744146013079f37f65140041ec606def4a --- /dev/null +++ b/chips/yosys/passes/cmds/wrapcell.cc @@ -0,0 +1,298 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2024 Martin Povišer + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ +#include "kernel/yosys.h" +#include "kernel/celltypes.h" +#include "kernel/sigtools.h" +#include "kernel/unused_bits.h" +#include "backends/rtlil/rtlil_backend.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +bool has_fmt_field(std::string fmt, std::string field_name) +{ + auto it = fmt.begin(); + while (it != fmt.end()) { + if (*it == '{') { + it++; + auto beg = it; + while (it != fmt.end() && *it != '}') it++; + if (it == fmt.end()) + return false; + + if (std::string(beg, it) == field_name) + return true; + } + it++; + } + return false; +} + +struct ContextData { + std::string unused_outputs; +}; + +std::optional format_with_params(const TwinePool &twines, std::string fmt, const dict ¶meters, + const ContextData &context) +{ + std::stringstream result; + + auto it = fmt.begin(); + while (it != fmt.end()) { + if (*it == '{') { + it++; + auto beg = it; + while (it != fmt.end() && *it != '}') it++; + if (it == fmt.end()) { + log("Unclosed curly brackets in format string '%s'\n", fmt); + return {}; + } + + std::string param_name = {beg, it}; + + if (param_name == "%unused") { + result << context.unused_outputs; + } else { + auto name = RTLIL::escape_id(std::string(beg, it)); + IdString id = twines.find(name); + if (id == IdString::Null || !parameters.count(id)) { + log("Parameter %s referenced in format string '%s' not found\n", name, fmt); + return {}; + } + + RTLIL_BACKEND::dump_const(result, parameters.at(id)); + } + } else { + result << *it; + } + it++; + } + + return {result.str()}; +} + +struct Chunk { + IdString port; + int base, len; + + Chunk(IdString id, int base, int len) + : port(id), base(base), len(len) {} + + IdString format(Cell *cell) + { + if (len == cell->getPort(port).size()) + return port; + auto &pool = cell->twines(); + if (len == 1) + return pool.add(stringf("%s[%d]", pool.str(port), base)); + return pool.add(stringf("%s[%d:%d]", pool.str(port), base + len - 1, base)); + } + + SigSpec sample(Cell *cell) + { + return cell->getPort(port).extract(base, len); + } +}; + +// Joins contiguous runs of bits into a 'Chunk' +std::vector collect_chunks(std::vector> bits) +{ + std::vector ret; + std::sort(bits.begin(), bits.end(), [](const auto &a, const auto &b) { + return a.first.raw() < b.first.raw() || (a.first.raw() == b.first.raw() && a.second < b.second); + }); + for (auto it = bits.begin(); it != bits.end();) { + auto sep = it + 1; + for (; sep != bits.end() && + sep->first == it->first && + sep->second == (sep - 1)->second + 1; sep++); + ret.emplace_back(it->first, it->second, sep - it); + it = sep; + } + return ret; +} + +struct WrapcellPass : Pass { + WrapcellPass() : Pass("wrapcell", "wrap individual cells into new modules") {} + + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" wrapcell -name [selection]\n"); + log("\n"); + log("This command wraps the selected cells individually into modules. The name for\n"); + log("each wrapper module is derived from the template by substituting\n"); + log("parameter values as specified in curly brackets. If the named module already\n"); + log("exists, it is reused.\n"); + log("\n"); + log("If the template contains the special string '{%%unused}', the command tracks\n"); + log("unused output ports -- specialized wrapper modules will be generated per every\n"); + log("distinct set of unused port bits as appearing on any selected cell.\n"); + log("\n"); + log(" -setattr \n"); + log(" set the given boolean attribute on each created wrapper module\n"); + log("\n"); + log(" -formatattr \n"); + log(" set a string attribute on the created wrapper module by substituting\n"); + log(" parameter values into \n"); + log("\n"); + log("Currently this command only supports wrapping internal cell types.\n"); + log("\n"); + } + + void execute(std::vector args, Design *d) override + { + log_header(d, "Executing WRAPCELL pass. (wrap selected cells)\n"); + + struct AttrRule { + IdString name; + std::string value_fmt; + + AttrRule(IdString name, std::string value_fmt) + : name(name), value_fmt(value_fmt) {} + }; + std::vector attributes; + std::string name_fmt; + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + if (args[argidx] == "-setattr" && argidx+1 < args.size()) { + attributes.emplace_back(d->twines().add(RTLIL::escape_id(args[++argidx])), ""); + } else if (args[argidx] == "-formatattr" && argidx+2 < args.size()) { + IdString id = d->twines().add(RTLIL::escape_id(args[++argidx])); + attributes.emplace_back(id, args[++argidx]); + } else if (args[argidx] == "-name" && argidx+1 < args.size()) { + name_fmt = args[++argidx]; + } else { + break; + } + } + extra_args(args, argidx, d); + + if (name_fmt.empty()) + log_cmd_error("Argument -name required\n"); + + CellTypes ct; + ct.setup(); + + bool tracking_unused = has_fmt_field(name_fmt, "%unused"); + + NewCellTypes ct_all(d); + + for (auto module : d->selected_modules()) { + UnusedBits unused(module, ct_all); + + for (auto cell : module->selected_cells()) { + Module *subm; + Cell *subcell; + IdString name_ref; + + if (!ct.cell_known(cell->type)) + log_error("Non-internal cell type '%s' on cell '%s' in module '%s' unsupported\n", + cell->type.unescape(), cell, module); + + std::vector> unused_outputs, used_outputs; + for (auto conn : cell->connections()) { + if (ct.cell_output(cell->type, conn.first)) + for (int i = 0; i < conn.second.size(); i++) { + if (tracking_unused && unused.check(conn.second[i])) + unused_outputs.emplace_back(conn.first, i); + else + used_outputs.emplace_back(conn.first, i); + } + } + + ContextData context; + if (!unused_outputs.empty()) { + context.unused_outputs += "_unused"; + for (auto chunk : collect_chunks(unused_outputs)) + context.unused_outputs += "_" + module->twines().unescaped_str(chunk.format(cell)); + } + + std::optional unescaped_name = format_with_params(d->twines(), name_fmt, cell->parameters, context); + if (!unescaped_name) + log_error("Formatting error when processing cell '%s' in module '%s'\n", + cell, module); + + name_ref = d->twines().add(RTLIL::escape_id(unescaped_name.value())); + if (d->module(name_ref)) + goto replace_cell; + + subm = d->addModule(name_ref); + subcell = subm->addCell("$1", IdString(cell->type)); + for (auto conn : cell->connections()) { + if (ct.cell_output(cell->type, conn.first)) { + // Insert marker bits as placehodlers which need to be replaced + subcell->setPort(conn.first, SigSpec(RTLIL::Sm, conn.second.size())); + } else { + Wire *w = subm->addWire(conn.first, conn.second.size()); + w->port_input = true; + subcell->setPort(conn.first, w); + } + } + + for (auto chunk : collect_chunks(used_outputs)) { + Wire *w = subm->addWire(chunk.format(cell), chunk.len); + w->port_output = true; + subcell->connections_[chunk.port].replace(chunk.base, w); + } + + for (auto chunk : collect_chunks(unused_outputs)) { + Wire *w = subm->addWire(chunk.format(cell), chunk.len); + subcell->connections_[chunk.port].replace(chunk.base, w); + } + + subcell->parameters = cell->parameters; + subm->fixup_ports(); + + for (auto rule : attributes) { + if (rule.value_fmt.empty()) { + subm->set_bool_attribute(rule.name); + } else { + std::optional value = format_with_params(d->twines(), rule.value_fmt, cell->parameters, context); + + if (!value) + log_error("Formatting error when processing cell '%s' in module '%s'\n", + cell, module); + + subm->set_string_attribute(rule.name, value.value()); + } + } + + replace_cell: + cell->parameters.clear(); + + dict new_connections; + + for (auto conn : cell->connections()) + if (!ct.cell_output(cell->type, conn.first)) + new_connections[conn.first] = conn.second; + + for (auto chunk : collect_chunks(used_outputs)) + new_connections[chunk.format(cell)] = chunk.sample(cell); + + cell->type = name_ref; + cell->connections_ = new_connections; + } + } + } +} WrapcellPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/write_file.cc b/chips/yosys/passes/cmds/write_file.cc new file mode 100644 index 0000000000000000000000000000000000000000..a22fdaf2ad0b48731ee767f5bb80e60648cabe27 --- /dev/null +++ b/chips/yosys/passes/cmds/write_file.cc @@ -0,0 +1,87 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2014 Claire Xenia Wolf + * Copyright (C) 2014 Johann Glaser + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "kernel/log_help.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct WriteFileFrontend : public Frontend { + WriteFileFrontend() : Frontend("=write_file", "write a text to a file") { } + bool formatted_help() override { + auto *help = PrettyHelp::get_current(); + help->set_group("passes/status"); + return false; + } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" write_file [options] output_file [input_file]\n"); + log("\n"); + log("Write the text from the input file to the output file.\n"); + log("\n"); + log(" -a\n"); + log(" Append to output file (instead of overwriting)\n"); + log("\n"); + log("\n"); + log("Inside a script the input file can also can a here-document:\n"); + log("\n"); + log(" write_file hello.txt < args, RTLIL::Design*) override + { + bool append_mode = false; + std::string output_filename; + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) + { + if (args[argidx] == "-a") { + append_mode = true; + continue; + } + break; + } + + if (argidx < args.size() && args[argidx].rfind("-", 0) != 0) + output_filename = args[argidx++]; + else + log_cmd_error("Missing output filename.\n"); + + extra_args(f, filename, args, argidx); + + FILE *of = fopen(output_filename.c_str(), append_mode ? "a" : "w"); + yosys_output_files.insert(output_filename); + char buffer[64 * 1024]; + int bytes; + + while (0 < (bytes = readsome(*f, buffer, sizeof(buffer)))) + fwrite(buffer, bytes, 1, of); + + fclose(of); + } +} WriteFileFrontend; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/cmds/xprop.cc b/chips/yosys/passes/cmds/xprop.cc new file mode 100644 index 0000000000000000000000000000000000000000..8d4dd393840a5e9eb7da75306d25f019c285777d --- /dev/null +++ b/chips/yosys/passes/cmds/xprop.cc @@ -0,0 +1,1259 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2022 Jannis Harder + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/celltypes.h" +#include "kernel/ffinit.h" +#include "kernel/ff.h" +#include "kernel/modtools.h" +#include "kernel/sigtools.h" +#include "kernel/utils.h" +#include "kernel/yosys.h" +#include "kernel/log_help.h" +#include + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct XpropOptions +{ + bool split_inputs = false; + bool split_outputs = false; + bool split_public = false; + bool assume_encoding = false; + bool assert_encoding = false; + bool assume_def_inputs = false; + bool required = false; + bool formal = false; + bool debug_asserts = false; +}; + +struct XpropWorker +{ + struct EncodedBit { + SigBit is_0, is_1, is_x; + bool driven; + }; + + struct EncodedSig { + SigSpec is_0, is_1, is_x; + Module *module; + + void invert() { std::swap(is_0, is_1); } + void auto_0() { connect_0(module->Not(NEW_ID, module->Or(NEW_ID, is_1, is_x))); } + void auto_1() { connect_1(module->Not(NEW_ID, module->Or(NEW_ID, is_0, is_x))); } + void auto_x() { connect_x(module->Not(NEW_ID, module->Or(NEW_ID, is_0, is_1))); } + + void connect_0(SigSpec sig) { module->connect(is_0, sig); } + void connect_1(SigSpec sig) { module->connect(is_1, sig); } + void connect_x(SigSpec sig) { module->connect(is_x, sig); } + + void connect_1_under_x(SigSpec sig) { connect_1(module->And(NEW_ID, sig, module->Not(NEW_ID, is_x))); } + void connect_0_under_x(SigSpec sig) { connect_0(module->And(NEW_ID, sig, module->Not(NEW_ID, is_x))); } + + void connect_x_under_0(SigSpec sig) { connect_x(module->And(NEW_ID, sig, module->Not(NEW_ID, is_0))); } + + void connect_as_bool() { + int width = GetSize(is_0); + if (width <= 1) + return; + module->connect(is_0.extract(1, width - 1), Const(State::S1, width - 1)); + module->connect(is_1.extract(1, width - 1), Const(State::S0, width - 1)); + module->connect(is_x.extract(1, width - 1), Const(State::S0, width - 1)); + is_0 = is_0[0]; + is_1 = is_1[0]; + is_x = is_x[0]; + } + + int size() const { return is_0.size(); } + }; + + Module *module; + XpropOptions options; + ModWalker modwalker; + SigMap &sigmap; + FfInitVals initvals; + + pool maybe_x_bits; + dict encoded_bits; + + pool pending_cells; + std::deque pending_cell_queue; + + XpropWorker(Module *module, XpropOptions options) : + module(module), options(options), + modwalker(module->design), sigmap(modwalker.sigmap) + { + modwalker.setup(module); + initvals.set(&modwalker.sigmap, module); + + maybe_x_bits.insert(State::Sx); + + for (auto cell : module->cells()) { + pending_cells.insert(cell); + pending_cell_queue.push_back(cell); + } + + if (!options.assume_def_inputs) { + for (auto port : module->ports) { + auto wire = module->wire(port); + if (wire->port_input) + mark_maybe_x(SigSpec(wire)); + } + } + } + + bool maybe_x(SigBit bit) + { + return maybe_x_bits.count(sigmap(bit)); + } + + bool maybe_x(const SigSpec &sig) + { + for (auto bit : sig) + if (maybe_x(bit)) return true; + return false; + } + + bool ports_maybe_x(Cell *cell) + { + for (auto &conn : cell->connections()) + if (maybe_x(conn.second)) + return true; + return false; + } + + bool inputs_maybe_x(Cell *cell) + { + for (auto &conn : cell->connections()) + if (cell->input(conn.first) && maybe_x(conn.second)) + return true; + return false; + } + + void mark_maybe_x(SigBit bit) + { + sigmap.apply(bit); + if (!maybe_x_bits.insert(bit).second) + return; + auto it = modwalker.signal_consumers.find(bit); + if (it == modwalker.signal_consumers.end()) + return; + for (auto &consumer : it->second) + if (pending_cells.insert(consumer.cell).second) + pending_cell_queue.push_back(consumer.cell); + } + + void mark_maybe_x(const SigSpec &sig) + { + for (auto bit : sig) + mark_maybe_x(bit); + } + + void mark_outputs_maybe_x(Cell *cell) + { + for (auto &conn : cell->connections()) + if (cell->output(conn.first)) + mark_maybe_x(conn.second); + } + + EncodedSig encoded(SigSpec sig, bool driving = false) + { + EncodedSig result; + SigSpec invert; + + if (driving) + result.module = module; + + int new_bits = 0; + + sigmap.apply(sig); + + for (auto bit : sig) { + if (!bit.is_wire()) + continue; + else if (!maybe_x(bit) && !driving) + invert.append(bit); + else if (!encoded_bits.count(bit)) { + new_bits += 1; + encoded_bits.emplace(bit, { + State::Sm, State::Sm, State::Sm, false + }); + } + } + + if (!invert.empty() && !driving) + invert = module->Not(NEW_ID, invert); + + EncodedSig new_sigs; + if (new_bits > 0) { + new_sigs.is_0 = module->addWire(NEW_ID, new_bits); + new_sigs.is_1 = module->addWire(NEW_ID, new_bits); + new_sigs.is_x = module->addWire(NEW_ID, new_bits); + } + + int invert_pos = 0; + int new_pos = 0; + + SigSpec driven_orig; + EncodedSig driven_enc; + SigSig driven_never_x; + + for (auto bit : sig) + { + if (!bit.is_wire()) { + result.is_0.append(bit == State::S0 ? State::S1 : State::S0); + result.is_1.append(bit == State::S1 ? State::S1 : State::S0); + result.is_x.append(bit == State::Sx ? State::S1 : State::S0); + continue; + } else if (!maybe_x(bit) && !driving) { + result.is_0.append(invert[invert_pos++]); + result.is_1.append(bit); + result.is_x.append(State::S0); + continue; + } + auto &enc = encoded_bits.at(bit); + if (enc.is_0 == State::Sm) { + enc.is_0 = new_sigs.is_0[new_pos]; + enc.is_1 = new_sigs.is_1[new_pos]; + enc.is_x = new_sigs.is_x[new_pos]; + new_pos++; + } + if (driving) { + log_assert(!enc.driven); + enc.driven = true; + if (maybe_x(bit)) { + driven_orig.append(bit); + driven_enc.is_0.append(enc.is_0); + driven_enc.is_1.append(enc.is_1); + driven_enc.is_x.append(enc.is_x); + } else { + driven_never_x.first.append(bit); + driven_never_x.second.append(enc.is_1); + } + } + result.is_0.append(enc.is_0); + result.is_1.append(enc.is_1); + result.is_x.append(enc.is_x); + } + + if (!driven_orig.empty()) { + auto decoder = module->addBwmux(NEW_ID, driven_enc.is_1, Const(State::Sx, GetSize(driven_orig)), driven_enc.is_x, driven_orig); + decoder->set_bool_attribute(ID::xprop_decoder); + } + if (!driven_never_x.first.empty()) { + module->connect(driven_never_x); + } + + if (driving && (options.assert_encoding || options.assume_encoding)) { + auto not_0 = module->Not(NEW_ID, result.is_0); + auto not_1 = module->Not(NEW_ID, result.is_1); + auto not_x = module->Not(NEW_ID, result.is_x); + auto valid = module->ReduceAnd(NEW_ID, SigSpec{ + module->Eq(NEW_ID, result.is_0, module->And(NEW_ID, not_1, not_x)), + module->Eq(NEW_ID, result.is_1, module->And(NEW_ID, not_0, not_x)), + module->Eq(NEW_ID, result.is_x, module->And(NEW_ID, not_0, not_1)), + }); + if (options.assert_encoding) + module->addAssert(NEW_ID_SUFFIX("xprop_enc"), valid, State::S1); + else + module->addAssume(NEW_ID_SUFFIX("xprop_enc"), valid, State::S1); + if (options.debug_asserts) { + auto bad_bits = module->Bweqx(NEW_ID, SigSpec{result.is_0, result.is_1, result.is_x}, Const(State::Sx, GetSize(result) * 3)); + module->addAssert(NEW_ID_SUFFIX("xprop_debug"), module->LogicNot(NEW_ID, bad_bits), State::S1); + } + } + + return result; + } + + void mark_all_maybe_x() + { + while (!pending_cell_queue.empty()) { + Cell *cell = pending_cell_queue.front(); + pending_cell_queue.pop_front(); + pending_cells.erase(cell); + + mark_maybe_x(cell); + } + } + + void mark_maybe_x(Cell *cell) { + if (cell->type.in(ID($bweqx), ID($eqx), ID($nex), ID($initstate), ID($assert), ID($assume), ID($cover), ID($anyseq), ID($anyconst))) + return; + + if (cell->type.in(ID($pmux))) { + mark_outputs_maybe_x(cell); + return; + } + + if (cell->is_builtin_ff() || cell->type == ID($anyinit)) { + FfData ff(&initvals, cell); + + if (cell->type != ID($anyinit)) + for (int i = 0; i < ff.width; i++) + if (ff.val_init[i] == State::Sx) + mark_maybe_x(ff.sig_q[i]); + + for (int i = 0; i < ff.width; i++) + if (maybe_x(ff.sig_d[i])) + mark_maybe_x(ff.sig_q[i]); + + if ((ff.has_clk || ff.has_gclk) && !ff.has_ce && !ff.has_aload && !ff.has_srst && !ff.has_arst && !ff.has_sr) + return; + } + + if (cell->type == ID($not)) { + auto &sig_y = cell->getPort(ID::Y); + auto sig_a = cell->getPort(ID::A); sig_a.extend_u0(GetSize(sig_y), cell->getParam(ID::A_SIGNED).as_bool()); + for (int i = 0; i < GetSize(sig_y); i++) + if (maybe_x(sig_a[i])) + mark_maybe_x(sig_y[i]); + return; + } + + if (cell->type.in(ID($and), ID($or), ID($xor), ID($xnor))) { + auto &sig_y = cell->getPort(ID::Y); + auto sig_a = cell->getPort(ID::A); sig_a.extend_u0(GetSize(sig_y), cell->getParam(ID::A_SIGNED).as_bool()); + auto sig_b = cell->getPort(ID::B); sig_b.extend_u0(GetSize(sig_y), cell->getParam(ID::B_SIGNED).as_bool()); + for (int i = 0; i < GetSize(sig_y); i++) + if (maybe_x(sig_a[i]) || maybe_x(sig_b[i])) + mark_maybe_x(sig_y[i]); + return; + } + + if (cell->type.in(ID($bwmux))) { + 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 (int i = 0; i < GetSize(sig_y); i++) + if (maybe_x(sig_a[i]) || maybe_x(sig_b[i]) || maybe_x(sig_s[i])) + mark_maybe_x(sig_y[i]); + return; + } + + if (cell->type.in(ID($_MUX_), ID($mux), ID($bmux))) { + 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); + if (maybe_x(sig_s)) { + mark_maybe_x(sig_y); + return; + } + for (int i = 0; i < GetSize(sig_y); i++) { + if (maybe_x(sig_a[i])) { + mark_maybe_x(sig_y[i]); + continue; + } + for (int j = i; j < GetSize(sig_b); j += GetSize(sig_y)) { + if (maybe_x(sig_b[j])) { + mark_maybe_x(sig_y[i]); + break; + } + } + } + return; + } + + if (cell->type.in(ID($demux))) { + auto &sig_y = cell->getPort(ID::Y); + auto &sig_a = cell->getPort(ID::A); + auto &sig_s = cell->getPort(ID::S); + if (maybe_x(sig_s)) { + mark_maybe_x(sig_y); + return; + } + for (int i = 0; i < GetSize(sig_a); i++) + if (maybe_x(sig_a[i])) + for (int j = i; j < GetSize(sig_y); j += GetSize(sig_a)) + mark_maybe_x(sig_y[j]); + return; + } + + if (cell->type.in(ID($shl), ID($shr), ID($sshl), ID($sshr), ID($shift))) { + auto &sig_b = cell->getPort(ID::B); + auto &sig_y = cell->getPort(ID::Y); + + if (maybe_x(sig_b)) { + mark_maybe_x(sig_y); + return; + } + + auto &sig_a = cell->getPort(ID::A); + + if (maybe_x(sig_a)) { + // We could be more precise for shifts, but that's not required + // for correctness, so let's keep it simple + mark_maybe_x(sig_y); + return; + } + return; + } + + if (cell->type.in(ID($shiftx))) { + auto &sig_b = cell->getPort(ID::B); + auto &sig_y = cell->getPort(ID::Y); + + if (cell->getParam(ID::B_SIGNED).as_bool() || GetSize(sig_b) >= 30) { + mark_maybe_x(sig_y); + } else { + int max_shift = (1 << GetSize(sig_b)) - 1; + + auto &sig_a = cell->getPort(ID::A); + + for (int i = 0; i < GetSize(sig_y); i++) + if (i + max_shift >= GetSize(sig_a)) + mark_maybe_x(sig_y[i]); + } + + if (maybe_x(sig_b)) { + mark_maybe_x(sig_y); + return; + } + + auto &sig_a = cell->getPort(ID::A); + if (maybe_x(sig_a)) { + // We could be more precise for shifts, but that's not required + // for correctness, so let's keep it simple + mark_maybe_x(sig_y); + return; + } + return; + } + + if (cell->type.in(ID($add), ID($sub), ID($mul), ID($neg))) { + if (inputs_maybe_x(cell)) + mark_outputs_maybe_x(cell); + return; + } + + if (cell->type.in(ID($div), ID($mod), ID($divfloor), ID($modfloor))) { + mark_outputs_maybe_x(cell); + return; + } + + if (cell->type.in( + ID($le), ID($lt), ID($ge), ID($gt), + ID($reduce_and), ID($reduce_or), ID($reduce_xor), ID($reduce_xnor), + ID($reduce_bool), ID($logic_not), ID($logic_or), ID($logic_and), + ID($eq), ID($ne), + + ID($_NOT_), ID($_AND_), ID($_NAND_), ID($_ANDNOT_), ID($_OR_), ID($_NOR_), ID($_ORNOT_), ID($_XOR_), ID($_XNOR_) + )) { + auto &sig_y = cell->getPort(ID::Y); + if (inputs_maybe_x(cell)) + mark_maybe_x(sig_y[0]); + return; + } + + if (cell->type.in(ID($scopeinfo))) { + return; + } + + log_warning("Unhandled cell %s (%s) during maybe-x marking\n", cell, cell->type.unescape()); + mark_outputs_maybe_x(cell); + } + + void process_cells() + { + for (auto cell : module->selected_cells()) + process_cell(cell); + } + + void process_cell(Cell *cell) + { + if (!ports_maybe_x(cell)) { + + if (cell->type == ID($bweq)) { + auto sig_y = cell->getPort(ID::Y); + auto sig_a = cell->getPort(ID::A); + auto sig_b = cell->getPort(ID::B); + + std::string name_str = cell->name.str(); + module->remove(cell); + module->addXnor(name_str, sig_a, sig_b, sig_y); + return; + } + + if (cell->type.in(ID($nex), ID($eqx))) { + auto sig_y = cell->getPort(ID::Y); + auto sig_a = cell->getPort(ID::A); + auto sig_b = cell->getPort(ID::B); + + std::string name_str = cell->name.str(); + IdString type = cell->type; + module->remove(cell); + if (type == ID($eqx)) + module->addEq(name_str, sig_a, sig_b, sig_y); + else + module->addNe(name_str, sig_a, sig_b, sig_y); + return; + } + + return; + } + + if (cell->type.in(ID($not), ID($_NOT_))) { + auto &sig_y = cell->getPort(ID::Y); + auto sig_a = cell->getPort(ID::A); + if (cell->type == ID($not)) + sig_a.extend_u0(GetSize(sig_y), cell->getParam(ID::A_SIGNED).as_bool()); + + auto enc_a = encoded(sig_a); + auto enc_y = encoded(sig_y, true); + + enc_y.connect_x(enc_a.is_x); + enc_y.connect_0(enc_a.is_1); + enc_y.connect_1(enc_a.is_0); + + module->remove(cell); + return; + } + + if (cell->type.in(ID($and), ID($or), ID($_AND_), ID($_OR_), ID($_NAND_), ID($_NOR_), ID($_ANDNOT_), ID($_ORNOT_))) { + auto &sig_y = cell->getPort(ID::Y); + auto sig_a = cell->getPort(ID::A); + auto sig_b = cell->getPort(ID::B); + if (cell->type.in(ID($and), ID($or))) { + sig_a.extend_u0(GetSize(sig_y), cell->getParam(ID::A_SIGNED).as_bool()); + sig_b.extend_u0(GetSize(sig_y), cell->getParam(ID::B_SIGNED).as_bool()); + } + + auto enc_a = encoded(sig_a); + auto enc_b = encoded(sig_b); + auto enc_y = encoded(sig_y, true); + + if (cell->type.in(ID($or), ID($_OR_), ID($_NOR_), ID($_ORNOT_))) + enc_a.invert(), enc_b.invert(), enc_y.invert(); + if (cell->type.in(ID($_NAND_), ID($_NOR_))) + enc_y.invert(); + if (cell->type.in(ID($_ANDNOT_), ID($_ORNOT_))) + enc_b.invert(); + + enc_y.connect_0(module->Or(NEW_ID, enc_a.is_0, enc_b.is_0)); + enc_y.connect_1(module->And(NEW_ID, enc_a.is_1, enc_b.is_1)); + enc_y.auto_x(); + module->remove(cell); + return; + } + + if (cell->type.in(ID($reduce_and), ID($reduce_or), ID($reduce_bool), ID($logic_not))) { + auto &sig_y = cell->getPort(ID::Y); + auto &sig_a = cell->getPort(ID::A); + + auto enc_a = encoded(sig_a); + auto enc_y = encoded(sig_y, true); + + enc_y.connect_as_bool(); + + if (cell->type.in(ID($reduce_or), ID($reduce_bool))) + enc_a.invert(), enc_y.invert(); + if (cell->type == ID($logic_not)) + enc_a.invert(); + + enc_y.connect_0(module->ReduceOr(NEW_ID, enc_a.is_0)); + enc_y.connect_1(module->ReduceAnd(NEW_ID, enc_a.is_1)); + enc_y.auto_x(); + module->remove(cell); + + return; + } + + if (cell->type.in(ID($reduce_xor), ID($reduce_xnor))) { + auto &sig_y = cell->getPort(ID::Y); + auto &sig_a = cell->getPort(ID::A); + + auto enc_a = encoded(sig_a); + auto enc_y = encoded(sig_y, true); + + enc_y.connect_as_bool(); + if (cell->type == ID($reduce_xnor)) + enc_y.invert(); + + + enc_y.connect_x(module->ReduceOr(NEW_ID, enc_a.is_x)); + enc_y.connect_1_under_x(module->ReduceXor(NEW_ID, enc_a.is_1)); + enc_y.auto_0(); + module->remove(cell); + + return; + } + + if (cell->type.in(ID($logic_and), ID($logic_or))) { + auto &sig_y = cell->getPort(ID::Y); + auto &sig_a = cell->getPort(ID::A); + auto &sig_b = cell->getPort(ID::B); + + auto enc_a = encoded(sig_a); + auto enc_b = encoded(sig_b); + auto enc_y = encoded(sig_y, true); + + enc_y.connect_as_bool(); + + auto a_is_1 = module->ReduceOr(NEW_ID, enc_a.is_1); + auto a_is_0 = module->ReduceAnd(NEW_ID, enc_a.is_0); + auto b_is_1 = module->ReduceOr(NEW_ID, enc_b.is_1); + auto b_is_0 = module->ReduceAnd(NEW_ID, enc_b.is_0); + + if (cell->type == ID($logic_or)) + enc_y.invert(), std::swap(a_is_0, a_is_1), std::swap(b_is_0, b_is_1); + + enc_y.connect_0(module->Or(NEW_ID, a_is_0, b_is_0)); + enc_y.connect_1(module->And(NEW_ID, a_is_1, b_is_1)); + enc_y.auto_x(); + module->remove(cell); + return; + } + + if (cell->type.in(ID($xor), ID($xnor), ID($_XOR_), ID($_XNOR_))) { + auto &sig_y = cell->getPort(ID::Y); + auto sig_a = cell->getPort(ID::A); + auto sig_b = cell->getPort(ID::B); + if (cell->type.in(ID($xor), ID($xnor))) { + sig_a.extend_u0(GetSize(sig_y), cell->getParam(ID::A_SIGNED).as_bool()); + sig_b.extend_u0(GetSize(sig_y), cell->getParam(ID::B_SIGNED).as_bool()); + } + + auto enc_a = encoded(sig_a); + auto enc_b = encoded(sig_b); + auto enc_y = encoded(sig_y, true); + + if (cell->type.in(ID($xnor), ID($_XNOR_))) + enc_y.invert(); + + enc_y.connect_x(module->Or(NEW_ID, enc_a.is_x, enc_b.is_x)); + enc_y.connect_1_under_x(module->Xor(NEW_ID, enc_a.is_1, enc_b.is_1)); + enc_y.auto_0(); + module->remove(cell); + return; + } + + if (cell->type.in(ID($eq), ID($ne))) { + auto &sig_y = cell->getPort(ID::Y); + auto sig_a = cell->getPort(ID::A); + auto sig_b = cell->getPort(ID::B); + int width = std::max(GetSize(sig_a), GetSize(sig_b)); + sig_a.extend_u0(width, cell->getParam(ID::A_SIGNED).as_bool()); + sig_b.extend_u0(width, cell->getParam(ID::B_SIGNED).as_bool()); + + auto enc_a = encoded(sig_a); + auto enc_b = encoded(sig_b); + auto enc_y = encoded(sig_y, true); + enc_y.connect_as_bool(); + + if (cell->type == ID($ne)) + enc_y.invert(); + + auto delta = module->Xor(NEW_ID, enc_a.is_1, enc_b.is_1); + auto xpos = module->Or(NEW_ID, enc_a.is_x, enc_b.is_x); + + enc_y.connect_0(module->ReduceOr(NEW_ID, module->And(NEW_ID, delta, module->Not(NEW_ID, xpos)))); + enc_y.connect_x_under_0(module->ReduceOr(NEW_ID, xpos)); + enc_y.auto_1(); + module->remove(cell); + return; + } + + if (cell->type.in(ID($eqx), ID($nex))) { + auto &sig_y = cell->getPort(ID::Y); + auto sig_a = cell->getPort(ID::A); + auto sig_b = cell->getPort(ID::B); + int width = std::max(GetSize(sig_a), GetSize(sig_b)); + sig_a.extend_u0(width, cell->getParam(ID::A_SIGNED).as_bool()); + sig_b.extend_u0(width, cell->getParam(ID::B_SIGNED).as_bool()); + + auto enc_a = encoded(sig_a); + auto enc_b = encoded(sig_b); + + auto delta_0 = module->Xnor(NEW_ID, enc_a.is_0, enc_b.is_0); + auto delta_1 = module->Xnor(NEW_ID, enc_a.is_1, enc_b.is_1); + + auto eq = module->ReduceAnd(NEW_ID, SigSpec{delta_0, delta_1}); + + auto res = cell->type == ID($nex) ? module->Not(NEW_ID, eq) : eq; + + module->connect(sig_y[0], res); + if (GetSize(sig_y) > 1) + module->connect(sig_y.extract(1, GetSize(sig_y) - 1), Const(State::S0, GetSize(sig_y) - 1)); + module->remove(cell); + return; + } + + if (cell->type.in(ID($bweqx))) { + auto &sig_y = cell->getPort(ID::Y); + auto &sig_a = cell->getPort(ID::A); + auto &sig_b = cell->getPort(ID::B); + + auto enc_a = encoded(sig_a); + auto enc_b = encoded(sig_b); + + auto delta_0 = module->Xnor(NEW_ID, enc_a.is_0, enc_b.is_0); + auto delta_1 = module->Xnor(NEW_ID, enc_a.is_1, enc_b.is_1); + module->addAnd(NEW_ID, delta_0, delta_1, sig_y); + module->remove(cell); + return; + } + + if (cell->type.in(ID($_MUX_), ID($mux), ID($bwmux))) { + 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); + + if (cell->type == ID($mux)) + sig_s = SigSpec(sig_s[0], GetSize(sig_y)); + + auto enc_a = encoded(sig_a); + auto enc_b = encoded(sig_b); + auto enc_s = encoded(sig_s); + auto enc_y = encoded(sig_y, true); + + enc_y.connect_1(module->And(NEW_ID, + module->Or(NEW_ID, enc_a.is_1, enc_s.is_1), + module->Or(NEW_ID, enc_b.is_1, enc_s.is_0))); + enc_y.connect_0(module->And(NEW_ID, + module->Or(NEW_ID, enc_a.is_0, enc_s.is_1), + module->Or(NEW_ID, enc_b.is_0, enc_s.is_0))); + enc_y.auto_x(); + module->remove(cell); + return; + } + + if (cell->type.in(ID($pmux))) { + 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 enc_a = encoded(sig_a); + auto enc_b = encoded(sig_b); + auto enc_s = encoded(sig_s); + auto enc_y = encoded(sig_y, true); + + int width = GetSize(enc_y); + + auto all_x = module->ReduceOr(NEW_ID, SigSpec{ + enc_s.is_x, + module->And(NEW_ID, enc_s.is_1, module->Sub(NEW_ID, enc_s.is_1, Const(1, width))) + }); + + auto selected = enc_a; + + for (int i = 0; i < GetSize(enc_s); i++) { + auto sel_bit = enc_s.is_1[i]; + selected.is_0 = module->Mux(NEW_ID, selected.is_0, enc_b.is_0.extract(i * width, width), sel_bit); + selected.is_1 = module->Mux(NEW_ID, selected.is_1, enc_b.is_1.extract(i * width, width), sel_bit); + selected.is_x = module->Mux(NEW_ID, selected.is_x, enc_b.is_x.extract(i * width, width), sel_bit); + } + + enc_y.connect_0(module->Mux(NEW_ID, selected.is_0, Const(State::S0, width), all_x)); + enc_y.connect_1(module->Mux(NEW_ID, selected.is_1, Const(State::S0, width), all_x)); + enc_y.connect_x(module->Mux(NEW_ID, selected.is_x, Const(State::S1, width), all_x)); + + module->remove(cell); + return; + } + + if (cell->type.in(ID($shl), ID($shr), ID($sshl), ID($sshr), ID($shift), ID($shiftx))) { + auto &sig_y = cell->getPort(ID::Y); + auto &sig_a = cell->getPort(ID::A); + auto &sig_b = cell->getPort(ID::B); + + auto enc_a = encoded(sig_a); + auto enc_b = encoded(sig_b); + auto enc_y = encoded(sig_y, true); + + auto all_x = module->ReduceOr(NEW_ID, enc_b.is_x)[0]; + auto not_all_x = module->Not(NEW_ID, all_x)[0]; + + SigSpec y_not_0 = module->addWire(NEW_ID, GetSize(sig_y)); + SigSpec y_1 = module->addWire(NEW_ID, GetSize(sig_y)); + SigSpec y_x = module->addWire(NEW_ID, GetSize(sig_y)); + + IdString encoded_type = cell->type == ID($shiftx) ? IdString{ID($shift)} : cell->type; + + if (cell->type == ID($shiftx)) { + std::swap(enc_a.is_0, enc_a.is_x); + } + + auto shift_0 = module->addCell(NEW_ID, encoded_type); + shift_0->parameters = cell->parameters; + shift_0->setPort(ID::A, module->Not(NEW_ID, enc_a.is_0)); + shift_0->setPort(ID::B, enc_b.is_1); + shift_0->setPort(ID::Y, y_not_0); + + auto shift_1 = module->addCell(NEW_ID, encoded_type); + shift_1->parameters = cell->parameters; + shift_1->setPort(ID::A, enc_a.is_1); + shift_1->setPort(ID::B, enc_b.is_1); + shift_1->setPort(ID::Y, y_1); + + auto shift_x = module->addCell(NEW_ID, encoded_type); + shift_x->parameters = cell->parameters; + shift_x->setPort(ID::A, enc_a.is_x); + shift_x->setPort(ID::B, enc_b.is_1); + shift_x->setPort(ID::Y, y_x); + + SigSpec y_0 = module->Not(NEW_ID, y_not_0); + + if (cell->type == ID($shiftx)) + std::swap(y_0, y_x); + + enc_y.connect_0(module->And(NEW_ID, y_0, SigSpec(not_all_x, GetSize(sig_y)))); + enc_y.connect_1(module->And(NEW_ID, y_1, SigSpec(not_all_x, GetSize(sig_y)))); + enc_y.connect_x(module->Or(NEW_ID, y_x, SigSpec(all_x, GetSize(sig_y)))); + + module->remove(cell); + return; + } + + if (cell->type.in(ID($ff))) { + auto &sig_d = cell->getPort(ID::D); + auto &sig_q = cell->getPort(ID::Q); + + auto init_q = initvals(sig_q); + auto init_q_is_1 = init_q; + auto init_q_is_x = init_q; + + for (auto bit : init_q_is_1) + bit = bit == State::S1 ? State::S1 : State::S0; + for (auto bit : init_q_is_x) + bit = bit == State::Sx ? State::S1 : State::S0; + + initvals.remove_init(sig_q); + + auto enc_d = encoded(sig_d); + auto enc_q = encoded(sig_q, true); + + auto data_q = module->addWire(NEW_ID, GetSize(sig_q)); + + module->addFf(NEW_ID, enc_d.is_1, data_q); + module->addFf(NEW_ID, enc_d.is_x, enc_q.is_x); + + initvals.set_init(data_q, init_q_is_1); + initvals.set_init(enc_q.is_x, init_q_is_x); + + enc_q.connect_1_under_x(data_q); + enc_q.auto_0(); + + module->remove(cell); + return; + } + + if (cell->is_builtin_ff() || cell->type == ID($anyinit)) { + FfData ff(&initvals, cell); + + if ((ff.has_clk || ff.has_gclk) && !ff.has_ce && !ff.has_aload && !ff.has_srst && !ff.has_arst && !ff.has_sr) { + if (ff.has_clk && maybe_x(ff.sig_clk)) { + log_warning("Only non-x CLK inputs are currently supported for %s (%s)\n", cell, cell->type.unescape()); + } else { + auto init_q = ff.val_init; + auto init_q_is_1 = init_q; + auto init_q_is_x = init_q; + + if (ff.is_anyinit) { + for (auto bit : init_q_is_1) + bit = State::Sx; + for (auto bit : init_q_is_x) + bit = State::S0; + } else { + for (auto bit : init_q_is_1) + bit = bit == State::S1 ? State::S1 : State::S0; + for (auto bit : init_q_is_x) + bit = bit == State::Sx ? State::S1 : State::S0; + } + + ff.remove(); + + auto enc_d = encoded(ff.sig_d); + auto enc_q = encoded(ff.sig_q, true); + + auto data_q = module->addWire(NEW_ID, GetSize(ff.sig_q)); + + ff.sig_d = enc_d.is_1; + ff.sig_q = data_q; + ff.val_init = init_q_is_1; + ff.emit(); + + ff.name = module->twines().add(NEW_ID); + ff.cell = nullptr; + ff.sig_d = enc_d.is_x; + ff.sig_q = enc_q.is_x; + ff.is_anyinit = false; + ff.val_init = init_q_is_x; + ff.emit(); + + + enc_q.connect_1_under_x(data_q); + enc_q.auto_0(); + + return; + } + } else { + log_warning("Unhandled FF-cell %s (%s), consider running clk2fflogic, async2sync and/or dffunmap\n", cell, cell->type.unescape()); + } + } + + // Celltypes where any input x bit makes the whole output x + if (cell->type.in( + ID($neg), + ID($le), ID($lt), ID($ge), ID($gt), + ID($add), ID($sub), ID($mul), ID($div), ID($mod), ID($divfloor), ID($modfloor) + )) { + + SigSpec inbits_x; + for (auto &conn : cell->connections()) { + if (cell->input(conn.first)) { + auto enc_port = encoded(conn.second); + inbits_x.append(enc_port.is_x); + cell->setPort(conn.first, enc_port.is_1); + } + } + + if (cell->type.in(ID($div), ID($mod), ID($divfloor), ID($modfloor))) { + auto sig_b = cell->getPort(ID::B); + auto invalid = module->LogicNot(NEW_ID, sig_b); + inbits_x.append(invalid); + sig_b[0] = module->Or(NEW_ID, sig_b[0], invalid); + cell->setPort(ID::B, sig_b); + } + + SigBit outbits_x = (GetSize(inbits_x) == 1 ? inbits_x : module->ReduceOr(NEW_ID, inbits_x)); + + bool bool_out = cell->type.in(ID($le), ID($lt), ID($ge), ID($gt)); + + for (auto &conn : cell->connections()) { + if (cell->output(conn.first)) { + auto enc_port = encoded(conn.second, true); + if (bool_out) + enc_port.connect_as_bool(); + + SigSpec new_output = module->addWire(NEW_ID, GetSize(conn.second)); + + enc_port.connect_1_under_x(bool_out ? new_output.extract(0) : new_output); + enc_port.connect_x(SigSpec(outbits_x, GetSize(enc_port))); + enc_port.auto_0(); + + cell->setPort(conn.first, new_output); + } + } + + return; + } + + if (cell->type == ID($bmux)) // TODO might want to support bmux natively anyway + log("Running 'bmuxmap' preserves x-propagation and can be run before 'xprop'.\n"); + if (cell->type == ID($demux)) // TODO might want to support demux natively anyway + log("Running 'demuxmap' preserves x-propagation and can be run before 'xprop'.\n"); + + if (options.required) + log_error("Unhandled cell %s (%s)\n", cell, cell->type.unescape()); + else + log_warning("Unhandled cell %s (%s)\n", cell, cell->type.unescape()); + } + + void split_ports() + { + if (!options.split_inputs && !options.split_outputs) + return; + + int port_id = 1; + + for (auto port : module->ports) { + auto wire = module->wire(port); + if (module->design->selected(module, wire)) { + if (wire->port_input == wire->port_output) { + log_warning("Port %s not an input or an output port which is not supported by xprop\n", wire); + } else if ((options.split_inputs && !options.assume_def_inputs && wire->port_input) || (options.split_outputs && wire->port_output)) { + auto port_d = module->uniquify(module->twines().str(port) + "_d"); + auto port_x = module->uniquify(module->twines().str(port) + "_x"); + + auto wire_d = module->addWire(port_d, GetSize(wire)); + auto wire_x = module->addWire(port_x, GetSize(wire)); + + wire_d->port_input = wire->port_input; + wire_d->port_output = wire->port_output; + wire_d->port_id = port_id++; + + wire_x->port_input = wire->port_input; + wire_x->port_output = wire->port_output; + wire_x->port_id = port_id++; + + if (wire->port_output) { + auto enc = encoded(wire); + module->connect(wire_d, enc.is_1); + module->connect(wire_x, enc.is_x); + + if (options.split_public) { + // Need to hide the original wire so split_public doesn't try to split it again + module->rename(wire, NEW_ID_SUFFIX(wire->name.str())); + } + } else { + auto enc = encoded(wire, true); + + enc.connect_x(wire_x); + enc.connect_1_under_x(wire_d); + enc.auto_0(); + } + + wire->port_input = wire->port_output = false; + wire->port_id = 0; + + continue; + } + } + wire->port_id = port_id++; + } + + module->fixup_ports(); + } + + void split_public() + { + if (!options.split_public) + return; + + for (auto wire : module->selected_wires()) { + if (wire->port_input || wire->port_output || !wire->name.isPublic()) + continue; + int index_d = 0; + int index_x = 0; + std::string wname = wire->name.str(); + auto name_d = module->uniquify(wname + "_d", index_d); + auto name_x = module->uniquify(wname + "_x", index_x); + + auto hdlname = wire->get_hdlname_attribute(); + + auto wire_d = module->addWire(name_d, GetSize(wire)); + auto wire_x = module->addWire(name_x, GetSize(wire)); + + if (!hdlname.empty()) { + auto hdlname_d = hdlname; + auto hdlname_x = hdlname; + hdlname_d.back() += index_d ? stringf("_d_%d", index_d) : "_d"; + hdlname_x.back() += index_x ? stringf("_x_%d", index_x) : "_x"; + wire_d->set_hdlname_attribute(hdlname_d); + wire_x->set_hdlname_attribute(hdlname_x); + } + + auto enc = encoded(wire); + module->connect(wire_d, enc.is_1); + module->connect(wire_x, enc.is_x); + + module->rename(wire, NEW_ID_SUFFIX(wire->name.str())); + } + } + + void encode_remaining() + { + pool enc_undriven_wires; + + for (auto &enc_bit : encoded_bits) { + if (!enc_bit.second.driven) { + log_assert(enc_bit.first.is_wire()); + enc_undriven_wires.insert(enc_bit.first.wire); + } + } + + if (options.formal && !enc_undriven_wires.empty()) { + for (auto &bit : enc_undriven_wires) + log_warning("Found encoded wire %s having a non-encoded driver\n", log_signal(bit)); + + log_error("Found encoded wires having a non-encoded driver, not allowed in -formal mode\n"); + } + + + for (auto wire : enc_undriven_wires) { + SigSpec sig(sigmap(wire)); + + SigSpec orig; + EncodedSig enc; + + for (auto bit : sig) { + auto it = encoded_bits.find(bit); + if (it == encoded_bits.end() || it->second.driven) + continue; + orig.append(bit); + enc.is_0.append(it->second.is_0); + enc.is_1.append(it->second.is_1); + enc.is_x.append(it->second.is_x); + it->second.driven = true; + } + + module->addBweqx(NEW_ID, orig, Const(State::S0, GetSize(orig)), enc.is_0); + module->addBweqx(NEW_ID, orig, Const(State::S1, GetSize(orig)), enc.is_1); + module->addBweqx(NEW_ID, orig, Const(State::Sx, GetSize(orig)), enc.is_x); + } + } +}; + +struct XpropPass : public Pass { + XpropPass() : Pass("xprop", "formal x propagation") {} + bool formatted_help() override { + auto *help = PrettyHelp::get_current(); + help->set_group("formal"); + return false; + } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" xprop [options] [selection]\n"); + log("\n"); + log("This pass transforms the circuit into an equivalent circuit that explicitly\n"); + log("encodes the propagation of x values using purely 2-valued logic. On the\n"); + log("interface between xprop-transformed and non-transformed parts of the design,\n"); + log("appropriate conversions are inserted automatically.\n"); + log("\n"); + log(" -split-inputs\n"); + log(" -split-outputs\n"); + log(" -split-ports\n"); + log(" Replace each input/output/port with two new ports, one carrying the\n"); + log(" defined values (named _d) and one carrying the mask of which\n"); + log(" bits are x (named _x). When a bit in the _x is set\n"); + log(" the corresponding bit in _d is ignored for inputs and\n"); + log(" guaranteed to be 0 for outputs.\n"); + log("\n"); + log(" -split-public\n"); + log(" Replace each public non-port wire with two new wires, one carrying the\n"); + log(" defined values (named _d) and one carrying the mask of which\n"); + log(" bits are x (named _x). When a bit in the _x is set\n"); + log(" the corresponding bit in _d is guaranteed to be 0 for\n"); + log(" outputs.\n"); + log("\n"); + log(" -assume-encoding\n"); + log(" Add encoding invariants as assumptions. This can speed up formal\n"); + log(" verification tasks.\n"); + log("\n"); + log(" -assert-encoding\n"); + log(" Add encoding invariants as assertions. Used for testing the xprop\n"); + log(" pass itself.\n"); + log("\n"); + log(" -assume-def-inputs\n"); + log(" Assume all inputs are fully defined. This adds corresponding\n"); + log(" assumptions to the design and uses these assumptions to optimize the\n"); + log(" xprop encoding.\n"); + log("\n"); + log(" -required\n"); + log(" Produce a runtime error if any encountered cell could not be encoded.\n"); + log("\n"); + log(" -formal\n"); + log(" Produce a runtime error if any encoded cell uses a signal that is\n"); + log(" neither known to be non-x nor driven by another encoded cell.\n"); + log("\n"); + log(" -debug-asserts\n"); + log(" Add assertions checking that the encoding used by this pass never\n"); + log(" produces x values within the encoded signals.\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + XpropOptions options; + + log_header(design, "Executing XPROP pass.\n"); + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + if (args[argidx] == "-split-ports") { + options.split_inputs = true; + options.split_outputs = true; + continue; + } + if (args[argidx] == "-split-inputs") { + options.split_inputs = true; + continue; + } + if (args[argidx] == "-split-outputs") { + options.split_outputs = true; + continue; + } + if (args[argidx] == "-split-public") { + options.split_public = true; + continue; + } + if (args[argidx] == "-assume-encoding") { + options.assume_encoding = true; + continue; + } + if (args[argidx] == "-assert-encoding") { + options.assert_encoding = true; + continue; + } + if (args[argidx] == "-assume-def-inputs") { + options.assume_def_inputs = true; + continue; + } + if (args[argidx] == "-required") { + options.required = true; // TODO check more + continue; + } + if (args[argidx] == "-formal") { + options.formal = true; + options.required = true; + continue; + } + if (args[argidx] == "-debug-asserts") { // TODO documented + options.debug_asserts = true; + options.assert_encoding = true; + continue; + } + break; + } + + if (options.assert_encoding && options.assume_encoding) + log_cmd_error("The options -assert-encoding and -assume-encoding are exclusive.\n"); + + extra_args(args, argidx, design); + + log_push(); + Pass::call(design, "bmuxmap"); + Pass::call(design, "demuxmap"); + log_pop(); + + for (auto module : design->selected_modules()) { + if (options.assume_def_inputs) { + for (auto port : module->ports) { + auto wire = module->wire(port); + if (!module->design->selected(module, wire)) + continue; + + if (wire->port_input) { + module->addAssume(NEW_ID, module->Not(NEW_ID, module->ReduceOr(NEW_ID, module->Bweqx(NEW_ID, wire, Const(State::Sx, GetSize(wire))))), State::S1); + } + } + } + + XpropWorker worker(module, options); + log_debug("Marking all x-bits.\n"); + worker.mark_all_maybe_x(); + log_debug("Repalcing cells.\n"); + worker.process_cells(); + log_debug("Splitting ports.\n"); + worker.split_ports(); + log_debug("Splitting public signals.\n"); + worker.split_public(); + log_debug("Encode remaining signals.\n"); + worker.encode_remaining(); + + } + } +} XpropPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/equiv/CMakeLists.txt b/chips/yosys/passes/equiv/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..50cabf760d3c3554fd4469d2bed4d676669b62a2 --- /dev/null +++ b/chips/yosys/passes/equiv/CMakeLists.txt @@ -0,0 +1,54 @@ +yosys_pass(equiv_make + equiv_make.cc + equiv.h +) +yosys_pass(equiv_miter + equiv_miter.cc + equiv.h +) +yosys_pass(equiv_simple + equiv_simple.cc + equiv.h +) +yosys_pass(equiv_status + equiv_status.cc + equiv.h +) +yosys_pass(equiv_add + equiv_add.cc + equiv.h +) +yosys_pass(equiv_remove + equiv_remove.cc + equiv.h +) +yosys_pass(equiv_induct + equiv_induct.cc + equiv.h +) +yosys_pass(equiv_struct + equiv_struct.cc + equiv.h +) +yosys_pass(equiv_purge + equiv_purge.cc + equiv.h +) +yosys_pass(equiv_mark + equiv_mark.cc + equiv.h +) +yosys_pass(equiv_opt + equiv_opt.cc + equiv.h + REQUIRES + async2sync + check + clk2fflogic + design + equiv_induct + equiv_make + equiv_status + hierarchy + techmap +) diff --git a/chips/yosys/passes/equiv/equiv.h b/chips/yosys/passes/equiv/equiv.h new file mode 100644 index 0000000000000000000000000000000000000000..45beb1520b98e95e196a559da963f850448e62d2 --- /dev/null +++ b/chips/yosys/passes/equiv/equiv.h @@ -0,0 +1,67 @@ +#ifndef EQUIV_H +#define EQUIV_H + +#include "kernel/log.h" +#include "kernel/yosys_common.h" +#include "kernel/sigtools.h" +#include "kernel/satgen.h" +#include "kernel/newcelltypes.h" + +YOSYS_NAMESPACE_BEGIN + +struct EquivBasicConfig { + bool model_undef = false; + int max_seq = 1; + bool set_assumes = false; + bool ignore_unknown_cells = false; + + bool parse(const std::vector& args, size_t& idx) { + if (args[idx] == "-undef") { + model_undef = true; + return true; + } + if (args[idx] == "-seq" && idx+1 < args.size()) { + max_seq = atoi(args[++idx].c_str()); + return true; + } + if (args[idx] == "-set-assumes") { + set_assumes = true; + return true; + } + if (args[idx] == "-ignore-unknown-cells") { + ignore_unknown_cells = true; + return true; + } + return false; + } + static void help(const char* default_seq) { + log(" -undef\n"); + log(" enable modelling of undef states\n"); + log("\n"); + log(" -seq \n"); + log(" the max. number of time steps to be considered (default = %s)\n", default_seq); + log("\n"); + log(" -set-assumes\n"); + log(" set all assumptions provided via $assume cells\n"); + log("\n"); + log(" -ignore-unknown-cells\n"); + log(" ignore all cells that can not be matched to a SAT model\n"); + } +}; + +template +struct EquivWorker { + RTLIL::Module *module; + + ezSatPtr ez; + SatGen satgen; + Config cfg; + + EquivWorker(RTLIL::Module *module, const SigMap *sigmap, Config cfg) : module(module), satgen(ez.get(), sigmap), cfg(cfg) { + satgen.model_undef = cfg.model_undef; + satgen.model_barriers = true; + } +}; + +YOSYS_NAMESPACE_END +#endif // EQUIV_H diff --git a/chips/yosys/passes/equiv/equiv_add.cc b/chips/yosys/passes/equiv/equiv_add.cc new file mode 100644 index 0000000000000000000000000000000000000000..b3c97fa8087c401348d5f5bcc01b2255de98e0a2 --- /dev/null +++ b/chips/yosys/passes/equiv/equiv_add.cc @@ -0,0 +1,177 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "kernel/sigtools.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct EquivAddPass : public Pass { + EquivAddPass() : Pass("equiv_add", "add a $equiv cell") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" equiv_add [-try] gold_sig gate_sig\n"); + log("\n"); + log("This command adds an $equiv cell for the specified signals.\n"); + log("\n"); + log("\n"); + log(" equiv_add [-try] -cell gold_cell gate_cell\n"); + log("\n"); + log("This command adds $equiv cells for the ports of the specified cells.\n"); + log("\n"); + } + void execute(std::vector args, Design *design) override + { + bool try_mode = false; + + if (design->selected_active_module.empty()) + log_cmd_error("This command must be executed in module context!\n"); + + Module *module = design->module(design->selected_active_module); + log_assert(module != nullptr); + + if (GetSize(args) > 1 && args[1] == "-try") { + args.erase(args.begin() + 1); + try_mode = true; + } + + if (GetSize(args) == 4 && args[1] == "-cell") + { + Cell *gold_cell = module->cell(RTLIL::escape_id(args[2])); + Cell *gate_cell = module->cell(RTLIL::escape_id(args[3])); + + if (gold_cell == nullptr) { + if (try_mode) { + log_warning("Can't find gold cell '%s'.\n", args[2]); + return; + } + log_cmd_error("Can't find gold cell '%s'.\n", args[2]); + } + + if (gate_cell == nullptr) { + if (try_mode) { + log_warning("Can't find gate cell '%s'.\n", args[3]); + return; + } + log_cmd_error("Can't find gate cell '%s'.\n", args[3]); + } + + for (auto conn : gold_cell->connections()) + { + auto port = conn.first; + SigSpec gold_sig = gold_cell->getPort(port); + SigSpec gate_sig = gate_cell->getPort(port); + int width = min(GetSize(gold_sig), GetSize(gate_sig)); + + if (gold_cell->input(port) && gate_cell->input(port)) + { + SigSpec combined_sig = module->addWire(NEW_ID, width); + + for (int i = 0; i < width; i++) { + module->addEquiv(NEW_ID, gold_sig[i], gate_sig[i], combined_sig[i]); + gold_sig[i] = gate_sig[i] = combined_sig[i]; + } + + gold_cell->setPort(port, gold_sig); + gate_cell->setPort(port, gate_sig); + continue; + } + + if (gold_cell->output(port) && gate_cell->output(port)) + { + SigSpec new_gold_wire = module->addWire(NEW_ID, width); + SigSpec new_gate_wire = module->addWire(NEW_ID, width); + SigSig gg_conn; + + for (int i = 0; i < width; i++) { + module->addEquiv(NEW_ID, new_gold_wire[i], new_gold_wire[i], gold_sig[i]); + gg_conn.first.append(gate_sig[i]); + gg_conn.second.append(gold_sig[i]); + gold_sig[i] = new_gold_wire[i]; + gate_sig[i] = new_gate_wire[i]; + } + + module->connect(gg_conn); + gold_cell->setPort(port, gold_sig); + gate_cell->setPort(port, gate_sig); + continue; + } + } + } + else + { + if (GetSize(args) != 3) + cmd_error(args, GetSize(args)-1, "Invalid number of arguments."); + + SigSpec gold_signal, gate_signal; + + if (!SigSpec::parse(gate_signal, module, args[2])) { + if (try_mode) { + log_warning("Error in gate signal: %s\n", args[2]); + return; + } + log_cmd_error("Error in gate signal: %s\n", args[2]); + } + + if (!SigSpec::parse_rhs(gate_signal, gold_signal, module, args[1])) { + if (try_mode) { + log_warning("Error in gold signal: %s\n", args[1]); + return; + } + log_cmd_error("Error in gold signal: %s\n", args[1]); + } + + log_assert(GetSize(gold_signal) == GetSize(gate_signal)); + SigSpec equiv_signal = module->addWire(NEW_ID, GetSize(gold_signal)); + + SigMap sigmap(module); + sigmap.apply(gold_signal); + sigmap.apply(gate_signal); + + dict to_equiv_bits; + pool added_equiv_cells; + + for (int i = 0; i < GetSize(gold_signal); i++) { + Cell *equiv_cell = module->addEquiv(NEW_ID, gold_signal[i], gate_signal[i], equiv_signal[i]); + equiv_cell->set_bool_attribute(ID::keep); + to_equiv_bits[gold_signal[i]] = equiv_signal[i]; + to_equiv_bits[gate_signal[i]] = equiv_signal[i]; + added_equiv_cells.insert(equiv_cell); + } + + for (auto cell : module->cells()) + for (auto conn : cell->connections()) + if (!added_equiv_cells.count(cell) && cell->input(conn.first)) { + SigSpec new_sig; + for (auto bit : conn.second) + if (to_equiv_bits.count(sigmap(bit))) + new_sig.append(to_equiv_bits.at(sigmap(bit))); + else + new_sig.append(bit); + if (conn.second != new_sig) + cell->setPort(conn.first, new_sig); + } + } + } +} EquivAddPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/equiv/equiv_induct.cc b/chips/yosys/passes/equiv/equiv_induct.cc new file mode 100644 index 0000000000000000000000000000000000000000..7a13a69abffd0880e1569086ffd532dd3fb7f292 --- /dev/null +++ b/chips/yosys/passes/equiv/equiv_induct.cc @@ -0,0 +1,233 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "passes/equiv/equiv.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct EquivInductWorker : public EquivWorker<> +{ + SigMap sigmap; + + vector cells; + pool workset; + + int success_counter; + + dict ez_step_is_consistent; + SigPool undriven_signals; + + EquivInductWorker(Module *module, const pool &unproven_equiv_cells, EquivBasicConfig cfg) : EquivWorker<>(module, &sigmap, cfg), sigmap(module), + cells(module->selected_cells()), workset(unproven_equiv_cells), + success_counter(0) {} + + void create_timestep(int step) + { + vector ez_equal_terms; + + for (auto cell : cells) { + if (!satgen.importCell(cell, step)) { + report_missing_model(cfg.ignore_unknown_cells, cell); + } + if (cell->type == ID($equiv)) { + SigBit bit_a = sigmap(cell->getPort(ID::A)).as_bit(); + SigBit bit_b = sigmap(cell->getPort(ID::B)).as_bit(); + if (bit_a != bit_b) { + int ez_a = satgen.importSigBit(bit_a, step); + int ez_b = satgen.importSigBit(bit_b, step); + int cond = ez->IFF(ez_a, ez_b); + if (satgen.model_undef) { + cond = ez->AND(cond, ez->NOT(satgen.importUndefSigBit(bit_b, step))); + cond = ez->OR(cond, satgen.importUndefSigBit(bit_a, step)); + } + ez_equal_terms.push_back(cond); + } + } + } + + if (cfg.set_assumes) { + if (step == 1) { + RTLIL::SigSpec assumes_a, assumes_en; + satgen.getAssumes(assumes_a, assumes_en, step); + for (int i = 0; i < GetSize(assumes_a); i++) + log("Import constraint from assume cell: %s when %s.\n", log_signal(assumes_a[i]), log_signal(assumes_en[i])); + } + ez->assume(satgen.importAssumes(step)); + } + + if (satgen.model_undef) { + for (auto bit : undriven_signals.export_all()) + ez->assume(ez->NOT(satgen.importUndefSigBit(bit, step))); + } + + log_assert(!ez_step_is_consistent.count(step)); + ez_step_is_consistent[step] = ez->expression(ez->OpAnd, ez_equal_terms); + } + + void run() + { + log("Found %d unproven $equiv cells in module %s:\n", GetSize(workset), module); + + if (satgen.model_undef) { + for (auto cell : cells) + if (yosys_celltypes.cell_known(cell->type)) + for (auto &conn : cell->connections()) + if (yosys_celltypes.cell_input(cell->type, conn.first)) + undriven_signals.add(sigmap(conn.second)); + for (auto cell : cells) + if (yosys_celltypes.cell_known(cell->type)) + for (auto &conn : cell->connections()) + if (yosys_celltypes.cell_output(cell->type, conn.first)) + undriven_signals.del(sigmap(conn.second)); + } + + create_timestep(1); + + if (satgen.model_undef) { + for (auto bit : satgen.initial_state.export_all()) + ez->assume(ez->NOT(satgen.importUndefSigBit(bit, 1))); + log(" Undef modelling: force def on %d initial reg values and %d inputs.\n", + GetSize(satgen.initial_state), GetSize(undriven_signals)); + } + + for (int step = 1; step <= cfg.max_seq; step++) + { + ez->assume(ez_step_is_consistent[step]); + + log(" Proving existence of base case for step %d. (%d clauses over %d variables)\n", step, ez->numCnfClauses(), ez->numCnfVariables()); + if (!ez->solve()) { + log(" Proof for base case failed. Circuit inherently diverges!\n"); + return; + } + + create_timestep(step+1); + int new_step_not_consistent = ez->NOT(ez_step_is_consistent[step+1]); + ez->bind(new_step_not_consistent); + + log(" Proving induction step %d. (%d clauses over %d variables)\n", step, ez->numCnfClauses(), ez->numCnfVariables()); + if (!ez->solve(new_step_not_consistent)) { + log(" Proof for induction step holds. Entire workset of %d cells proven!\n", GetSize(workset)); + for (auto cell : workset) + cell->setPort(ID::B, cell->getPort(ID::A)); + success_counter += GetSize(workset); + return; + } + + log(" Proof for induction step failed. %s\n", step != cfg.max_seq ? "Extending to next time step." : "Trying to prove individual $equiv from workset."); + } + + workset.sort(); + + for (auto cell : workset) + { + SigBit bit_a = sigmap(cell->getPort(ID::A)).as_bit(); + SigBit bit_b = sigmap(cell->getPort(ID::B)).as_bit(); + + std::string message = stringf(" Trying to prove $equiv for %s:", log_signal(sigmap(cell->getPort(ID::Y)))); + + int ez_a = satgen.importSigBit(bit_a, cfg.max_seq+1); + int ez_b = satgen.importSigBit(bit_b, cfg.max_seq+1); + int cond = ez->XOR(ez_a, ez_b); + + if (satgen.model_undef) + cond = ez->AND(cond, ez->NOT(satgen.importUndefSigBit(bit_a, cfg.max_seq+1))); + + if (!ez->solve(cond)) { + log("%s success!\n", message); + cell->setPort(ID::B, cell->getPort(ID::A)); + success_counter++; + } else { + log("%s failed.\n", message); + } + } + } +}; + +struct EquivInductPass : public Pass { + EquivInductPass() : Pass("equiv_induct", "proving $equiv cells using temporal induction") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" equiv_induct [options] [selection]\n"); + log("\n"); + log("Uses a version of temporal induction to prove $equiv cells.\n"); + log("\n"); + log("Only selected $equiv cells are proven and only selected cells are used to\n"); + log("perform the proof.\n"); + log("\n"); + EquivBasicConfig::help("4"); + log("\n"); + log("This command is very effective in proving complex sequential circuits, when\n"); + log("the internal state of the circuit quickly propagates to $equiv cells.\n"); + log("\n"); + log("However, this command uses a weak definition of 'equivalence': This command\n"); + log("proves that the two circuits will not diverge after they produce equal\n"); + log("outputs (observable points via $equiv) for at least cycles (the \n"); + log("specified via -seq).\n"); + log("\n"); + log("Combined with simulation this is very powerful because simulation can give\n"); + log("you confidence that the circuits start out synced for at least cycles\n"); + log("after reset.\n"); + log("\n"); + } + void execute(std::vector args, Design *design) override + { + int success_counter = 0; + EquivBasicConfig cfg {}; + cfg.max_seq = 4; + + log_header(design, "Executing EQUIV_INDUCT pass.\n"); + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + if (cfg.parse(args, argidx)) + continue; + break; + } + extra_args(args, argidx, design); + + for (auto module : design->selected_modules()) + { + pool unproven_equiv_cells; + vector assume_cells; + + for (auto cell : module->selected_cells()) + if (cell->type == ID($equiv)) { + if (cell->getPort(ID::A) != cell->getPort(ID::B)) + unproven_equiv_cells.insert(cell); + } + + if (unproven_equiv_cells.empty()) { + log("No selected unproven $equiv cells found in %s.\n", module); + continue; + } + + EquivInductWorker worker(module, unproven_equiv_cells, cfg); + worker.run(); + success_counter += worker.success_counter; + } + + log("Proved %d previously unproven $equiv cells.\n", success_counter); + } +} EquivInductPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/equiv/equiv_make.cc b/chips/yosys/passes/equiv/equiv_make.cc new file mode 100644 index 0000000000000000000000000000000000000000..a09908504eed0ceb5442aa8296b359a3df56b21a --- /dev/null +++ b/chips/yosys/passes/equiv/equiv_make.cc @@ -0,0 +1,522 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "kernel/sigtools.h" +#include "kernel/celltypes.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct EquivMakeWorker +{ + Module *gold_mod, *gate_mod, *equiv_mod; + pool wire_names, cell_names; + CellTypes ct; + + bool inames; + vector blacklists; + vector encfiles; + bool make_assert; + + pool blacklist_names; + dict> encdata; + + pool undriven_bits; + SigMap assign_map; + + void read_blacklists() + { + for (auto fn : blacklists) + { + std::ifstream f(fn); + if (f.fail()) + log_cmd_error("Can't open blacklist file '%s'!\n", fn); + + string line, token; + while (std::getline(f, line)) { + while (1) { + token = next_token(line); + if (token.empty()) + break; + IdString name = gold_mod->twines().find(RTLIL::escape_id(token)); + if (name != IdString::Null) + blacklist_names.insert(name); + } + } + } + } + + void read_encfiles() + { + for (auto fn : encfiles) + { + std::ifstream f(fn); + if (f.fail()) + log_cmd_error("Can't open encfile '%s'!\n", fn); + + dict *ed = nullptr; + string line, token; + while (std::getline(f, line)) + { + token = next_token(line); + if (token.empty() || token[0] == '#') + continue; + + if (token == ".fsm") { + IdString modname = gold_mod->twines().find(RTLIL::escape_id(next_token(line))); + (void)modname; + IdString signame = gold_mod->twines().find(RTLIL::escape_id(next_token(line))); + if (encdata.count(signame)) + log_cmd_error("Re-definition of signal '%s' in encfile '%s'!\n", PooledName(gold_mod->design, signame).unescape(), fn); + encdata[signame] = dict(); + ed = &encdata[signame]; + continue; + } + + if (token == ".map") { + Const gold_bits = Const::from_string(next_token(line)); + Const gate_bits = Const::from_string(next_token(line)); + (*ed)[gold_bits] = gate_bits; + continue; + } + + log_cmd_error("Syntax error in encfile '%s'!\n", fn); + } + } + } + + void copy_to_equiv() + { + Module *gold_clone = gold_mod->clone(); + Module *gate_clone = gate_mod->clone(); + + for (auto it : gold_clone->wires().to_vector()) { + if ((it->name.isPublic() || inames) && blacklist_names.count(it->name) == 0) + wire_names.insert(it->name); + gold_clone->rename(it, it->name.str() + "_gold"); + } + + for (auto it : gold_clone->cells().to_vector()) { + if ((it->name.isPublic() || inames) && blacklist_names.count(it->name) == 0) + cell_names.insert(it->name); + gold_clone->rename(it, it->name.str() + "_gold"); + } + + for (auto it : gate_clone->wires().to_vector()) { + if ((it->name.isPublic() || inames) && blacklist_names.count(it->name) == 0) + wire_names.insert(it->name); + gate_clone->rename(it, it->name.str() + "_gate"); + } + + for (auto it : gate_clone->cells().to_vector()) { + if ((it->name.isPublic() || inames) && blacklist_names.count(it->name) == 0) + cell_names.insert(it->name); + gate_clone->rename(it, it->name.str() + "_gate"); + } + + gold_clone->cloneInto(equiv_mod); + gate_clone->cloneInto(equiv_mod); + delete gold_clone; + delete gate_clone; + } + + void add_eq_assertion(const SigSpec &gold_sig, const SigSpec &gate_sig) + { + auto eq_wire = equiv_mod->Eqx(NEW_ID, gold_sig, gate_sig); + equiv_mod->addAssert(NEW_ID_SUFFIX("assert"), eq_wire, State::S1); + } + + void find_same_wires() + { + SigMap assign_map(equiv_mod); + SigMap rd_signal_map; + SigPool primary_inputs; + + // list of cells without added $equiv cells + auto cells_list = equiv_mod->cells().to_vector(); + + for (auto id : wire_names) + { + IdString gold_id = equiv_mod->twines().find(equiv_mod->twines().str(id) + "_gold"); + IdString gate_id = equiv_mod->twines().find(equiv_mod->twines().str(id) + "_gate"); + + Wire *gold_wire = equiv_mod->wire(gold_id); + Wire *gate_wire = equiv_mod->wire(gate_id); + + if (encdata.count(id)) + { + log("Creating encoder/decoder for signal %s.\n", PooledName(equiv_mod->design, id).unescape()); + + Wire *dec_wire = equiv_mod->addWire(equiv_mod->twines().str(id) + "_decoded", gold_wire->width); + Wire *enc_wire = equiv_mod->addWire(equiv_mod->twines().str(id) + "_encoded", gate_wire->width); + + SigSpec dec_a, dec_b, dec_s; + SigSpec enc_a, enc_b, enc_s; + + dec_a = SigSpec(State::Sx, dec_wire->width); + enc_a = SigSpec(State::Sx, enc_wire->width); + + for (auto &it : encdata.at(id)) + { + SigSpec dec_sig = gate_wire, dec_pat = it.second; + SigSpec enc_sig = dec_wire, enc_pat = it.first; + + if (GetSize(dec_sig) != GetSize(dec_pat)) + log_error("Invalid pattern %s for signal %s of size %d!\n", + log_signal(dec_pat), log_signal(dec_sig), GetSize(dec_sig)); + + if (GetSize(enc_sig) != GetSize(enc_pat)) + log_error("Invalid pattern %s for signal %s of size %d!\n", + log_signal(enc_pat), log_signal(enc_sig), GetSize(enc_sig)); + + SigSpec reduced_dec_sig, reduced_dec_pat; + for (int i = 0; i < GetSize(dec_sig); i++) + if (dec_pat[i] == State::S0 || dec_pat[i] == State::S1) { + reduced_dec_sig.append(dec_sig[i]); + reduced_dec_pat.append(dec_pat[i]); + } + + SigSpec reduced_enc_sig, reduced_enc_pat; + for (int i = 0; i < GetSize(enc_sig); i++) + if (enc_pat[i] == State::S0 || enc_pat[i] == State::S1) { + reduced_enc_sig.append(enc_sig[i]); + reduced_enc_pat.append(enc_pat[i]); + } + + SigSpec dec_result = it.first; + for (auto &bit : dec_result) + if (bit != State::S1) bit = State::S0; + + SigSpec enc_result = it.second; + for (auto &bit : enc_result) + if (bit != State::S1) bit = State::S0; + + SigSpec dec_eq = equiv_mod->addWire(NEW_ID); + SigSpec enc_eq = equiv_mod->addWire(NEW_ID); + + equiv_mod->addEq(NEW_ID, reduced_dec_sig, reduced_dec_pat, dec_eq); + cells_list.push_back(equiv_mod->addEq(NEW_ID, reduced_enc_sig, reduced_enc_pat, enc_eq)); + + dec_s.append(dec_eq); + enc_s.append(enc_eq); + dec_b.append(dec_result); + enc_b.append(enc_result); + } + + equiv_mod->addPmux(NEW_ID, dec_a, dec_b, dec_s, dec_wire); + equiv_mod->addPmux(NEW_ID, enc_a, enc_b, enc_s, enc_wire); + + rd_signal_map.add(assign_map(gate_wire), enc_wire); + gate_wire = dec_wire; + } + + if (gold_wire == nullptr || gate_wire == nullptr || gold_wire->width != gate_wire->width) { + if (gold_wire && gold_wire->port_id) + log_error("Can't match gold port `%s' to a gate port.\n", gold_wire); + if (gate_wire && gate_wire->port_id) + log_error("Can't match gate port `%s' to a gold port.\n", gate_wire); + continue; + } + + log("Presumably equivalent wires: %s (%s), %s (%s) -> %s\n", + gold_wire, log_signal(assign_map(gold_wire)), + gate_wire, log_signal(assign_map(gate_wire)), PooledName(equiv_mod->design, id).unescape()); + + if (gold_wire->port_output || gate_wire->port_output) + { + gold_wire->port_input = false; + gate_wire->port_input = false; + gold_wire->port_output = false; + gate_wire->port_output = false; + + Wire *wire = equiv_mod->addWire(id, gold_wire->width); + wire->port_output = true; + + if (make_assert) + { + add_eq_assertion(gold_wire, gate_wire); + equiv_mod->connect(wire, gold_wire); + } + else + { + for (int i = 0; i < wire->width; i++) + equiv_mod->addEquiv(NEW_ID, SigSpec(gold_wire, i), SigSpec(gate_wire, i), SigSpec(wire, i)); + } + + rd_signal_map.add(assign_map(gold_wire), wire); + rd_signal_map.add(assign_map(gate_wire), wire); + } + else + if (gold_wire->port_input || gate_wire->port_input) + { + Wire *wire = equiv_mod->addWire(id, gold_wire->width); + wire->port_input = true; + gold_wire->port_input = false; + gate_wire->port_input = false; + equiv_mod->connect(gold_wire, wire); + equiv_mod->connect(gate_wire, wire); + primary_inputs.add(assign_map(gold_wire)); + primary_inputs.add(assign_map(gate_wire)); + primary_inputs.add(wire); + } + else + { + if (make_assert) + add_eq_assertion(gold_wire, gate_wire); + + else { + Wire *wire = equiv_mod->addWire(id, gold_wire->width); + SigSpec rdmap_gold, rdmap_gate, rdmap_equiv; + + for (int i = 0; i < wire->width; i++) { + if (undriven_bits.count(assign_map(SigBit(gold_wire, i)))) { + log(" Skipping signal bit %s [%d]: undriven on gold side.\n", gold_wire, i); + continue; + } + if (undriven_bits.count(assign_map(SigBit(gate_wire, i)))) { + log(" Skipping signal bit %s [%d]: undriven on gate side.\n", gate_wire, i); + continue; + } + equiv_mod->addEquiv(NEW_ID, SigSpec(gold_wire, i), SigSpec(gate_wire, i), SigSpec(wire, i)); + rdmap_gold.append(SigBit(gold_wire, i)); + rdmap_gate.append(SigBit(gate_wire, i)); + rdmap_equiv.append(SigBit(wire, i)); + } + + rd_signal_map.add(rdmap_gold, rdmap_equiv); + rd_signal_map.add(rdmap_gate, rdmap_equiv); + } + } + } + + for (auto c : cells_list) + for (auto &conn : c->connections()) + if (!ct.cell_output(c->type, conn.first)) { + SigSpec old_sig = assign_map(conn.second); + SigSpec new_sig = rd_signal_map(old_sig); + for (int i = 0; i < GetSize(old_sig); i++) + if (primary_inputs.check(old_sig[i])) + new_sig[i] = old_sig[i]; + if (old_sig != new_sig) { + log("Changing input %s of cell %s (%s): %s -> %s\n", + PooledName(equiv_mod, conn.first).unescape(), c, c->type.unescape(), + log_signal(old_sig), log_signal(new_sig)); + c->setPort(conn.first, new_sig); + } + } + + equiv_mod->fixup_ports(); + } + + void find_same_cells() + { + SigMap assign_map(equiv_mod); + + for (auto id : cell_names) + { + IdString gold_id = equiv_mod->twines().find(equiv_mod->twines().str(id) + "_gold"); + IdString gate_id = equiv_mod->twines().find(equiv_mod->twines().str(id) + "_gate"); + + Cell *gold_cell = equiv_mod->cell(gold_id); + Cell *gate_cell = equiv_mod->cell(gate_id); + + if (gold_cell == nullptr || gate_cell == nullptr || gold_cell->type != gate_cell->type || !ct.cell_known(gold_cell->type) || + gold_cell->parameters != gate_cell->parameters || GetSize(gold_cell->connections()) != GetSize(gate_cell->connections())) + try_next_cell_name: + continue; + + for (auto gold_conn : gold_cell->connections()) + if (!gate_cell->connections().count(gold_conn.first)) + goto try_next_cell_name; + + log("Presumably equivalent cells: %s %s (%s) -> %s\n", + gold_cell, gate_cell, gold_cell->type.unescape(), PooledName(equiv_mod->design, id).unescape()); + + for (auto gold_conn : gold_cell->connections()) + { + SigSpec gold_sig = assign_map(gold_conn.second); + SigSpec gate_sig = assign_map(gate_cell->getPort(gold_conn.first)); + + if (ct.cell_output(gold_cell->type, gold_conn.first)) { + equiv_mod->connect(gate_sig, gold_sig); + continue; + } + + if (make_assert) + { + if (gold_sig != gate_sig) + add_eq_assertion(gold_sig, gate_sig); + } + else + { + for (int i = 0; i < GetSize(gold_sig); i++) + if (gold_sig[i] != gate_sig[i]) { + Wire *w = equiv_mod->addWire(NEW_ID); + equiv_mod->addEquiv(NEW_ID, gold_sig[i], gate_sig[i], w); + gold_sig[i] = w; + } + } + + gold_cell->setPort(gold_conn.first, gold_sig); + } + + equiv_mod->remove(gate_cell); + equiv_mod->rename(gold_cell, id); + } + } + + void find_undriven_nets(bool mark) + { + undriven_bits.clear(); + assign_map.set(equiv_mod); + + for (auto wire : equiv_mod->wires()) { + for (auto bit : assign_map(wire)) + if (bit.wire) + undriven_bits.insert(bit); + } + + for (auto wire : equiv_mod->wires()) { + if (wire->port_input) + for (auto bit : assign_map(wire)) + undriven_bits.erase(bit); + } + + for (auto cell : equiv_mod->cells()) { + for (auto &conn : cell->connections()) + if (!ct.cell_known(cell->type) || ct.cell_output(cell->type, conn.first)) + for (auto bit : assign_map(conn.second)) + undriven_bits.erase(bit); + } + + if (mark) { + SigSpec undriven_sig(undriven_bits); + undriven_sig.sort_and_unify(); + + for (auto chunk : undriven_sig.chunks()) { + log("Setting undriven nets to undef: %s\n", log_signal(chunk)); + equiv_mod->connect(chunk, SigSpec(State::Sx, chunk.width)); + } + } + } + + void run() + { + copy_to_equiv(); + find_undriven_nets(false); + find_same_wires(); + find_same_cells(); + find_undriven_nets(true); + } +}; + +struct EquivMakePass : public Pass { + EquivMakePass() : Pass("equiv_make", "prepare a circuit for equivalence checking") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" equiv_make [options] gold_module gate_module equiv_module\n"); + log("\n"); + log("This creates a module annotated with $equiv cells from two presumably\n"); + log("equivalent modules. Use commands such as 'equiv_simple' and 'equiv_status'\n"); + log("to work with the created equivalent checking module.\n"); + log("\n"); + log(" -inames\n"); + log(" Also match cells and wires with $... names.\n"); + log("\n"); + log(" -blacklist \n"); + log(" Do not match cells or signals that match the names in the file.\n"); + log("\n"); + log(" -encfile \n"); + log(" Match FSM encodings using the description from the file.\n"); + log(" See 'help fsm_recode' for details.\n"); + log("\n"); + log(" -make_assert\n"); + log(" Check equivalence with $assert cells instead of $equiv.\n"); + log(" $eqx (===) is used to compare signals.\n"); + log("\n"); + log("Note: The circuit created by this command is not a miter (with something like\n"); + log("a trigger output), but instead uses $equiv cells to encode the equivalence\n"); + log("checking problem. Use 'miter -equiv' if you want to create a miter circuit.\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + EquivMakeWorker worker; + worker.ct.setup(design); + worker.inames = false; + worker.make_assert = false; + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) + { + if (args[argidx] == "-inames") { + worker.inames = true; + continue; + } + if (args[argidx] == "-blacklist" && argidx+1 < args.size()) { + worker.blacklists.push_back(args[++argidx]); + continue; + } + if (args[argidx] == "-encfile" && argidx+1 < args.size()) { + worker.encfiles.push_back(args[++argidx]); + continue; + } + if (args[argidx] == "-make_assert") { + worker.make_assert = true; + continue; + } + break; + } + + if (argidx+3 != args.size()) + log_cmd_error("Invalid number of arguments.\n"); + + worker.gold_mod = design->module(RTLIL::escape_id(args[argidx])); + worker.gate_mod = design->module(RTLIL::escape_id(args[argidx+1])); + worker.equiv_mod = design->module(RTLIL::escape_id(args[argidx+2])); + + if (worker.gold_mod == nullptr) + log_cmd_error("Can't find gold module %s.\n", args[argidx]); + + if (worker.gate_mod == nullptr) + log_cmd_error("Can't find gate module %s.\n", args[argidx+1]); + + if (worker.equiv_mod != nullptr) + log_cmd_error("Equiv module %s already exists.\n", args[argidx+2]); + + if (worker.gold_mod->has_memories() || worker.gold_mod->has_processes()) + log_cmd_error("Gold module contains memories or processes. Run 'memory' or 'proc' respectively.\n"); + + if (worker.gate_mod->has_memories() || worker.gate_mod->has_processes()) + log_cmd_error("Gate module contains memories or processes. Run 'memory' or 'proc' respectively.\n"); + + worker.read_blacklists(); + worker.read_encfiles(); + + log_header(design, "Executing EQUIV_MAKE pass (creating equiv checking module).\n"); + + worker.equiv_mod = design->addModule(RTLIL::escape_id(args[argidx+2])); + worker.run(); + } +} EquivMakePass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/equiv/equiv_mark.cc b/chips/yosys/passes/equiv/equiv_mark.cc new file mode 100644 index 0000000000000000000000000000000000000000..0f355af4e6aeb04521dee0a9c879f842099e5da2 --- /dev/null +++ b/chips/yosys/passes/equiv/equiv_mark.cc @@ -0,0 +1,239 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "kernel/sigtools.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct EquivMarkWorker +{ + Module *module; + SigMap sigmap; + + // cache for traversing signal flow graph + dict> up_bit2cells; + dict> up_cell2bits; + pool edge_cells, equiv_cells; + + // graph traversal state + pool queue, visited; + + // assigned regions + dict cell_regions; + dict bit_regions; + int next_region; + + // merge-find + mfp region_mf; + + EquivMarkWorker(Module *module) : module(module), sigmap(module) + { + for (auto cell : module->cells()) + { + if (cell->type == ID($equiv)) + equiv_cells.insert(cell->name); + + for (auto &port : cell->connections()) + { + if (cell->input(port.first)) + for (auto bit : sigmap(port.second)) + up_cell2bits[cell->name].insert(bit); + + if (cell->output(port.first)) + for (auto bit : sigmap(port.second)) + up_bit2cells[bit].insert(cell->name); + } + } + + next_region = 0; + } + + void mark() + { + while (!queue.empty()) + { + pool cells; + + for (auto &bit : queue) + { + // log_assert(bit_regions.count(bit) == 0); + bit_regions[bit] = next_region; + visited.insert(bit); + + for (auto cell : up_bit2cells[bit]) + if (edge_cells.count(cell) == 0) + cells.insert(cell); + } + + queue.clear(); + + for (auto cell : cells) + { + if (next_region == 0 && equiv_cells.count(cell)) + continue; + + if (cell_regions.count(cell)) { + if (cell_regions.at(cell) != 0) + region_mf.merge(cell_regions.at(cell), next_region); + continue; + } + + cell_regions[cell] = next_region; + + for (auto bit : up_cell2bits[cell]) + if (visited.count(bit) == 0) + queue.insert(bit); + } + } + + next_region++; + } + + void run() + { + log("Running equiv_mark on module %s:\n", module); + + // marking region 0 + + for (auto wire : module->wires()) + if (wire->port_id > 0) + for (auto bit : sigmap(wire)) + queue.insert(bit); + + for (auto cell_name : equiv_cells) + { + auto cell = module->cell(cell_name); + + SigSpec sig_a = sigmap(cell->getPort(ID::A)); + SigSpec sig_b = sigmap(cell->getPort(ID::B)); + + if (sig_a == sig_b) { + for (auto bit : sig_a) + queue.insert(bit); + edge_cells.insert(cell_name); + cell_regions[cell_name] = 0; + } + } + + mark(); + + // marking unsolved regions + + for (auto cell : module->cells()) + { + if (cell_regions.count(cell->name) || cell->type != ID($equiv)) + continue; + + SigSpec sig_a = sigmap(cell->getPort(ID::A)); + SigSpec sig_b = sigmap(cell->getPort(ID::B)); + + log_assert(sig_a != sig_b); + + for (auto bit : sig_a) + queue.insert(bit); + + for (auto bit : sig_b) + queue.insert(bit); + + cell_regions[cell->name] = next_region; + mark(); + } + + // setting attributes + + dict final_region_map; + int next_final_region = 0; + + dict region_cell_count; + dict region_wire_count; + + for (int i = 0; i < next_region; i++) { + int r = region_mf.find(i); + if (final_region_map.count(r) == 0) + final_region_map[r] = next_final_region++; + final_region_map[i] = final_region_map[r]; + } + + for (auto cell : module->cells()) + { + if (cell_regions.count(cell->name)) { + int r = final_region_map.at(cell_regions.at(cell->name)); + cell->attributes[ID::equiv_region] = Const(r); + region_cell_count[r]++; + } else + cell->attributes.erase(ID::equiv_region); + } + + for (auto wire : module->wires()) + { + pool regions; + for (auto bit : sigmap(wire)) + if (bit_regions.count(bit)) + regions.insert(region_mf.find(bit_regions.at(bit))); + + if (GetSize(regions) == 1) { + int r = final_region_map.at(*regions.begin()); + wire->attributes[ID::equiv_region] = Const(r); + region_wire_count[r]++; + } else + wire->attributes.erase(ID::equiv_region); + } + + for (int i = 0; i < next_final_region; i++) + log(" region %d: %d cells, %d wires\n", i, region_wire_count[i], region_cell_count[i]); + } +}; + +struct EquivMarkPass : public Pass { + EquivMarkPass() : Pass("equiv_mark", "mark equivalence checking regions") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" equiv_mark [options] [selection]\n"); + log("\n"); + log("This command marks the regions in an equivalence checking module. Region 0 is\n"); + log("the proven part of the circuit. Regions with higher numbers are connected\n"); + log("unproven subcricuits. The integer attribute 'equiv_region' is set on all\n"); + log("wires and cells.\n"); + log("\n"); + } + void execute(std::vector args, Design *design) override + { + log_header(design, "Executing EQUIV_MARK pass.\n"); + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + // if (args[argidx] == "-foobar") { + // continue; + // } + break; + } + extra_args(args, argidx, design); + + for (auto module : design->selected_whole_modules_warn()) { + EquivMarkWorker worker(module); + worker.run(); + } + } +} EquivMarkPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/equiv/equiv_miter.cc b/chips/yosys/passes/equiv/equiv_miter.cc new file mode 100644 index 0000000000000000000000000000000000000000..d3ee6829b7db3ff7b97cf3b9f3e45afb4c859cdf --- /dev/null +++ b/chips/yosys/passes/equiv/equiv_miter.cc @@ -0,0 +1,342 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "kernel/sigtools.h" +#include "kernel/celltypes.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct EquivMiterWorker +{ + CellTypes ct; + SigMap sigmap; + + bool mode_trigger; + bool mode_cmp; + bool mode_assert; + bool mode_undef; + + IdString miter_name; + Module *miter_module; + Module *source_module; + + dict bit_to_driver; + pool seed_cells, miter_cells; + pool miter_wires; + + void follow_cone(pool &cone, pool &leaves, Cell *c, bool gold_mode) + { + if (cone.count(c)) + return; + + if (c->type == ID($equiv) && !seed_cells.count(c)) { + leaves.insert(c); + return; + } + + cone.insert(c); + + for (auto &conn : c->connections()) { + if (!ct.cell_input(c->type, conn.first)) + continue; + if (c->type == ID($equiv) && (conn.first == ID::A) != gold_mode) + continue; + for (auto bit : sigmap(conn.second)) + if (bit_to_driver.count(bit)) + follow_cone(cone, leaves, bit_to_driver.at(bit), gold_mode); + } + } + + void find_miter_cells_wires() + { + sigmap.set(source_module); + + // initialize bit_to_driver + + for (auto c : source_module->cells()) + for (auto &conn : c->connections()) + if (ct.cell_output(c->type, conn.first)) + for (auto bit : sigmap(conn.second)) + if (bit.wire) + bit_to_driver[bit] = c; + + // find seed cells + + for (auto c : source_module->selected_cells()) + if (c->type == ID($equiv)) { + log("Seed $equiv cell: %s\n", c); + seed_cells.insert(c); + } + + // follow cone from seed cells to next $equiv + + while (1) + { + pool gold_cone, gold_leaves; + pool gate_cone, gate_leaves; + + for (auto c : seed_cells) { + follow_cone(gold_cone, gold_leaves, c, true); + follow_cone(gate_cone, gate_leaves, c, false); + } + + log("Gold cone: %d cells (%d leaves).\n", GetSize(gold_cone), GetSize(gold_leaves)); + log("Gate cone: %d cells (%d leaves).\n", GetSize(gate_cone), GetSize(gate_leaves)); + + // done if all leaves are shared leaves + + if (gold_leaves == gate_leaves) { + miter_cells = gold_cone; + miter_cells.insert(gate_cone.begin(), gate_cone.end()); + log("Selected %d miter cells.\n", GetSize(miter_cells)); + break; + } + + // remove shared leaves + + for (auto it = gold_leaves.begin(); it != gold_leaves.end(); ) { + auto it2 = gate_leaves.find(*it); + if (it2 != gate_leaves.end()) { + it = gold_leaves.erase(it); + gate_leaves.erase(it2); + } else + ++it; + } + + // add remaining leaves to seeds and re-run + + log("Adding %d gold and %d gate seed cells.\n", GetSize(gold_leaves), GetSize(gate_leaves)); + seed_cells.insert(gold_leaves.begin(), gold_leaves.end()); + seed_cells.insert(gate_leaves.begin(), gate_leaves.end()); + } + + for (auto c : miter_cells) + for (auto &conn : c->connections()) + for (auto bit : sigmap(conn.second)) + if (bit.wire) + miter_wires.insert(bit.wire); + log("Selected %d miter wires.\n", GetSize(miter_wires)); + } + + void copy_to_miter() + { + // copy wires and cells + + for (auto w : miter_wires) + miter_module->addWire(w->name, w->width); + for (auto c : miter_cells) { + auto mc = miter_module->addCell(c->name, c); + for (auto &conn : mc->connections()) + mc->setPort(conn.first, sigmap(conn.second)); + } + + // fixup wire references in cells + + sigmap.clear(); + + struct RewriteSigSpecWorker { + RTLIL::Module * mod; + void operator()(SigSpec &sig) { + vector chunks = sig.chunks(); + for (auto &c : chunks) + if (c.wire != NULL) + c.wire = mod->wires_.at(c.wire->name); + sig = chunks; + } + }; + + RewriteSigSpecWorker rewriteSigSpecWorker; + rewriteSigSpecWorker.mod = miter_module; + miter_module->rewrite_sigspecs(rewriteSigSpecWorker); + + // find undriven or unused wires + + pool driven_bits, used_bits; + + for (auto c : miter_module->cells()) + for (auto &conn : c->connections()) { + if (ct.cell_input(c->type, conn.first)) + for (auto bit : conn.second) + if (bit.wire) + used_bits.insert(bit); + if (ct.cell_output(c->type, conn.first)) + for (auto bit : conn.second) + if (bit.wire) + driven_bits.insert(bit); + } + + // create ports + + for (auto w : miter_module->wires()) { + for (auto bit : SigSpec(w)) { + if (driven_bits.count(bit) && !used_bits.count(bit)) + w->port_output = true; + if (!driven_bits.count(bit) && used_bits.count(bit)) + w->port_input = true; + } + if (w->port_output && w->port_input) + log("Created miter inout port %s.\n", w); + else if (w->port_output) + log("Created miter output port %s.\n", w); + else if (w->port_input) + log("Created miter input port %s.\n", w); + } + + miter_module->fixup_ports(); + } + + void make_stuff() + { + if (!mode_trigger && !mode_cmp && !mode_assert) + return; + + SigSpec trigger_signals; + vector equiv_cells; + + for (auto c : miter_module->cells()) + if (c->type == ID($equiv) && c->getPort(ID::A) != c->getPort(ID::B)) + equiv_cells.push_back(c); + + for (auto c : equiv_cells) + { + SigSpec cmp = mode_undef ? + miter_module->LogicOr(NEW_ID, miter_module->Eqx(NEW_ID, c->getPort(ID::A), State::Sx), + miter_module->Eqx(NEW_ID, c->getPort(ID::A), c->getPort(ID::B))) : + miter_module->Eq(NEW_ID, c->getPort(ID::A), c->getPort(ID::B)); + + if (mode_cmp) { + string cmp_name = stringf("\\cmp%s", log_signal(c->getPort(ID::Y))); + for (int i = 1; i < GetSize(cmp_name); i++) + if (cmp_name[i] == '\\') + cmp_name[i] = '_'; + else if (cmp_name[i] == ' ') + cmp_name = cmp_name.substr(0, i) + cmp_name.substr(i+1); + auto w = miter_module->addWire(cmp_name); + w->port_output = true; + miter_module->connect(w, cmp); + } + + if (mode_assert) + miter_module->addAssert(NEW_ID, cmp, State::S1); + + trigger_signals.append(miter_module->Not(NEW_ID, cmp)); + } + + if (mode_trigger) { + auto w = miter_module->addWire("trigger"); + w->port_output = true; + miter_module->addReduceOr(NEW_ID, trigger_signals, w); + } + + miter_module->fixup_ports(); + } + + void run() + { + log("Creating miter %s from module %s.\n", miter_module, source_module); + find_miter_cells_wires(); + copy_to_miter(); + make_stuff(); + } +}; + +struct EquivMiterPass : public Pass { + EquivMiterPass() : Pass("equiv_miter", "extract miter from equiv circuit") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" equiv_miter [options] miter_module [selection]\n"); + log("\n"); + log("This creates a miter module for further analysis of the selected $equiv cells.\n"); + log("\n"); + log(" -trigger\n"); + log(" Create a trigger output\n"); + log("\n"); + log(" -cmp\n"); + log(" Create cmp_* outputs for individual unproven $equiv cells\n"); + log("\n"); + log(" -assert\n"); + log(" Create a $assert cell for each unproven $equiv cell\n"); + log("\n"); + log(" -undef\n"); + log(" Create compare logic that handles undefs correctly\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + EquivMiterWorker worker; + worker.ct.setup(design); + worker.mode_trigger = false; + worker.mode_cmp = false; + worker.mode_assert = false; + worker.mode_undef = false; + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) + { + if (args[argidx] == "-trigger") { + worker.mode_trigger = true; + continue; + } + if (args[argidx] == "-cmp") { + worker.mode_cmp = true; + continue; + } + if (args[argidx] == "-assert") { + worker.mode_assert = true; + continue; + } + if (args[argidx] == "-undef") { + worker.mode_undef = true; + continue; + } + break; + } + + if (argidx >= args.size()) + log_cmd_error("Invalid number of arguments.\n"); + + worker.miter_name = design->twines().add(RTLIL::escape_id(args[argidx++])); + extra_args(args, argidx, design); + + if (design->module(worker.miter_name)) + log_cmd_error("Miter module %s already exists.\n", PooledName(design, worker.miter_name).unescape()); + + worker.source_module = nullptr; + for (auto m : design->selected_modules()) { + if (worker.source_module != nullptr) + goto found_two_modules; + worker.source_module = m; + } + + if (worker.source_module == nullptr) + found_two_modules: + log_cmd_error("Exactly one module must be selected for 'equiv_miter'!\n"); + + log_header(design, "Executing EQUIV_MITER pass.\n"); + + worker.miter_module = design->addModule(worker.miter_name); + worker.run(); + } +} EquivMiterPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/equiv/equiv_opt.cc b/chips/yosys/passes/equiv/equiv_opt.cc new file mode 100644 index 0000000000000000000000000000000000000000..13dbc23b5f111e0c18891bb45b179ffefa2b5ab7 --- /dev/null +++ b/chips/yosys/passes/equiv/equiv_opt.cc @@ -0,0 +1,233 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2018 whitequark + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/register.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct EquivOptPass:public ScriptPass +{ + EquivOptPass() : ScriptPass("equiv_opt", "prove equivalence for optimized circuit") { } + + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" equiv_opt [options] [command]\n"); + log("\n"); + log("This command uses temporal induction to check circuit equivalence before and\n"); + log("after an optimization pass.\n"); + log("\n"); + log(" -run :\n"); + log(" only run the commands between the labels (see below). an empty\n"); + log(" from label is synonymous to the start of the command list, and empty to\n"); + log(" label is synonymous to the end of the command list.\n"); + log("\n"); + log(" -map \n"); + log(" expand the modules in this file before proving equivalence. this is\n"); + log(" useful for handling architecture-specific primitives.\n"); + log("\n"); + log(" -blacklist \n"); + log(" Do not match cells or signals that match the names in the file\n"); + log(" (passed to equiv_make).\n"); + log("\n"); + log(" -assert\n"); + log(" produce an error if the circuits are not equivalent.\n"); + log("\n"); + log(" -multiclock\n"); + log(" run clk2fflogic before equivalence checking.\n"); + log("\n"); + log(" -async2sync\n"); + log(" run async2sync before equivalence checking.\n"); + log("\n"); + log(" -undef\n"); + log(" enable modelling of undef states during equiv_induct.\n"); + log("\n"); + log(" -nocheck\n"); + log(" disable running check before and after the command under test.\n"); + log("\n"); + log(" -ignore-unknown-cells\n"); + log(" ignore all cells that can not be matched to a SAT model during\n"); + log(" equiv_induct.\n"); + log("\n"); + log("The following commands are executed by this verification command:\n"); + help_script(); + log("\n"); + } + + std::string command, techmap_opts, make_opts; + bool assert, undef, ignore_unknown_cells, multiclock, async2sync, nocheck; + + void clear_flags() override + { + command = ""; + techmap_opts = ""; + make_opts = ""; + assert = false; + undef = false; + ignore_unknown_cells = false; + multiclock = false; + async2sync = false; + nocheck = false; + } + + void execute(std::vector < std::string > args, RTLIL::Design * design) override + { + string run_from, run_to; + clear_flags(); + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + if (args[argidx] == "-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); + continue; + } + if (args[argidx] == "-map" && argidx + 1 < args.size()) { + techmap_opts += " -map " + args[++argidx]; + continue; + } + if (args[argidx] == "-blacklist" && argidx + 1 < args.size()) { + make_opts += " -blacklist " + args[++argidx]; + continue; + } + if (args[argidx] == "-assert") { + assert = true; + continue; + } + if (args[argidx] == "-undef") { + undef = true; + continue; + } + if (args[argidx] == "-ignore-unknown-cells") { + ignore_unknown_cells = true; + continue; + } + if (args[argidx] == "-nocheck") { + nocheck = true; + continue; + } + if (args[argidx] == "-multiclock") { + multiclock = true; + continue; + } + if (args[argidx] == "-async2sync") { + async2sync = true; + continue; + } + break; + } + + for (; argidx < args.size(); argidx++) { + if (command.empty()) { + if (args[argidx].compare(0, 1, "-") == 0) + cmd_error(args, argidx, "Unknown option."); + } else { + command += " "; + } + command += args[argidx]; + } + + if (command.empty()) + log_cmd_error("No optimization pass specified!\n"); + + if (!design->full_selection()) + log_cmd_error("This command only operates on fully selected designs!\n"); + + if (async2sync && multiclock) + log_cmd_error("The '-async2sync' and '-multiclock' options are mutually exclusive!\n"); + + log_header(design, "Executing EQUIV_OPT pass.\n"); + log_push(); + + run_script(design, run_from, run_to); + + log_pop(); + } + + void script() override + { + if (check_label("run_pass")) { + run("hierarchy -auto-top"); + run("design -save preopt"); + if (!nocheck) + run("check -assert", "(unless -nocheck)"); + if (help_mode) + run("[command]"); + else + run(command); + if (!nocheck) + run("check -assert", "(unless -nocheck)"); + run("design -stash postopt"); + } + + if (check_label("prepare")) { + run("design -copy-from preopt -as gold A:top"); + run("design -copy-from postopt -as gate A:top"); + } + + if ((!techmap_opts.empty() || help_mode) && check_label("techmap", "(only with -map)")) { + string opts; + if (help_mode) + opts = " -map ..."; + else + opts = techmap_opts; + run("techmap -wb -D EQUIV -autoproc" + opts); + } + + if (check_label("prove")) { + if (multiclock || help_mode) + run("clk2fflogic", "(only with -multiclock)"); + if (async2sync || help_mode) + run("async2sync", " (only with -async2sync)"); + string opts; + if (help_mode) + opts = " -blacklist ..."; + else + opts = make_opts; + run("equiv_make" + opts + " gold gate equiv"); + string induct_opts; + if (help_mode) + induct_opts = " [-undef] [-ignore-unknown-cells]"; + else { + if (undef) + induct_opts += " -undef"; + if (ignore_unknown_cells) + induct_opts += " -ignore-unknown-cells"; + } + run("equiv_induct" + induct_opts + " equiv"); + if (help_mode) + run("equiv_status [-assert] equiv"); + else if (assert) + run("equiv_status -assert equiv"); + else + run("equiv_status equiv"); + } + + if (check_label("restore")) { + run("design -load preopt"); + } + } +} EquivOptPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/equiv/equiv_purge.cc b/chips/yosys/passes/equiv/equiv_purge.cc new file mode 100644 index 0000000000000000000000000000000000000000..a020acf9455046fea39439bf2155b614a55466e6 --- /dev/null +++ b/chips/yosys/passes/equiv/equiv_purge.cc @@ -0,0 +1,210 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "kernel/sigtools.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct EquivPurgeWorker +{ + Module *module; + SigMap sigmap; + int name_cnt; + + EquivPurgeWorker(Module *module) : module(module), sigmap(module), name_cnt(0) { } + + SigSpec make_output(SigSpec sig, IdString cellname) + { + if (sig.is_wire()) { + Wire *wire = sig.as_wire(); + if (wire->name.isPublic()) { + if (!wire->port_output) { + log(" Module output: %s (%s)\n", log_signal(wire), PooledName(module->design, cellname).unescape()); + wire->port_output = true; + } + return wire; + } + } + + while (1) + { + std::string name = stringf("\\equiv_%d", name_cnt++); + if (module->count_id(module->twines().find(name))) + continue; + + Wire *wire = module->addWire(name, GetSize(sig)); + wire->port_output = true; + module->connect(wire, sig); + log(" Module output: %s (%s)\n", log_signal(wire), PooledName(module->design, cellname).unescape()); + return wire; + } + } + + SigSpec make_input(SigSpec sig) + { + if (sig.is_wire()) { + Wire *wire = sig.as_wire(); + if (wire->name.isPublic()) { + if (!wire->port_output) { + log(" Module input: %s\n", log_signal(wire)); + wire->port_input = true; + } + return module->addWire(NEW_ID, GetSize(sig)); + } + } + + while (1) + { + std::string name = stringf("\\equiv_%d", name_cnt++); + if (module->count_id(module->twines().find(name))) + continue; + + Wire *wire = module->addWire(name, GetSize(sig)); + wire->port_input = true; + module->connect(sig, wire); + log(" Module input: %s (%s)\n", log_signal(wire), log_signal(sig)); + return module->addWire(NEW_ID, GetSize(sig)); + } + } + + void run() + { + log("Running equiv_purge on module %s:\n", module); + + for (auto wire : module->wires()) { + wire->port_input = false; + wire->port_output = false; + } + + pool queue, visited; + + // cache for traversing signal flow graph + dict> up_bit2cells; + dict> up_cell2bits; + + for (auto cell : module->cells()) + { + if (cell->type != ID($equiv)) { + for (auto &port : cell->connections()) { + if (cell->input(port.first)) + for (auto bit : sigmap(port.second)) + up_cell2bits[cell->name].insert(bit); + if (cell->output(port.first)) + for (auto bit : sigmap(port.second)) + up_bit2cells[bit].insert(cell->name); + } + continue; + } + + SigSpec sig_a = sigmap(cell->getPort(ID::A)); + SigSpec sig_b = sigmap(cell->getPort(ID::B)); + SigSpec sig_y = sigmap(cell->getPort(ID::Y)); + + if (sig_a == sig_b) + continue; + + for (auto bit : sig_a) + queue.insert(bit); + + for (auto bit : sig_b) + queue.insert(bit); + + for (auto bit : sig_y) + visited.insert(bit); + + cell->setPort(ID::Y, make_output(sig_y, cell->name)); + } + + SigSpec srcsig; + SigMap rewrite_sigmap(module); + + while (!queue.empty()) + { + pool next_queue; + + for (auto bit : queue) + visited.insert(bit); + + for (auto bit : queue) + { + auto &cells = up_bit2cells[bit]; + + if (cells.empty()) { + srcsig.append(bit); + } else { + for (auto cell : cells) + for (auto bit : up_cell2bits[cell]) + if (visited.count(bit) == 0) + next_queue.insert(bit); + } + } + + next_queue.swap(queue); + } + + srcsig.sort_and_unify(); + + for (SigChunk chunk : srcsig.chunks()) + if (chunk.wire != nullptr) + rewrite_sigmap.add(chunk, make_input(chunk)); + + for (auto cell : module->cells()) + if (cell->type == ID($equiv)) + cell->setPort(ID::Y, rewrite_sigmap(sigmap(cell->getPort(ID::Y)))); + + module->fixup_ports(); + } +}; + +struct EquivPurgePass : public Pass { + EquivPurgePass() : Pass("equiv_purge", "purge equivalence checking module") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" equiv_purge [options] [selection]\n"); + log("\n"); + log("This command removes the proven part of an equivalence checking module, leaving\n"); + log("only the unproven segments in the design. This will also remove and add module\n"); + log("ports as needed.\n"); + log("\n"); + } + void execute(std::vector args, Design *design) override + { + log_header(design, "Executing EQUIV_PURGE pass.\n"); + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + // if (args[argidx] == "-foobar") { + // continue; + // } + break; + } + extra_args(args, argidx, design); + + for (auto module : design->selected_whole_modules_warn()) { + EquivPurgeWorker worker(module); + worker.run(); + } + } +} EquivPurgePass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/equiv/equiv_remove.cc b/chips/yosys/passes/equiv/equiv_remove.cc new file mode 100644 index 0000000000000000000000000000000000000000..c871cd9ef168132d969902835396f118c9e95c2b --- /dev/null +++ b/chips/yosys/passes/equiv/equiv_remove.cc @@ -0,0 +1,83 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct EquivRemovePass : public Pass { + EquivRemovePass() : Pass("equiv_remove", "remove $equiv cells") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" equiv_remove [options] [selection]\n"); + log("\n"); + log("This command removes the selected $equiv cells. If neither -gold nor -gate is\n"); + log("used then only proven cells are removed.\n"); + log("\n"); + log(" -gold\n"); + log(" keep gold circuit\n"); + log("\n"); + log(" -gate\n"); + log(" keep gate circuit\n"); + log("\n"); + } + void execute(std::vector args, Design *design) override + { + bool mode_gold = false; + bool mode_gate = false; + int remove_count = 0; + + log_header(design, "Executing EQUIV_REMOVE pass.\n"); + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + if (args[argidx] == "-gold") { + mode_gold = true; + continue; + } + if (args[argidx] == "-gate") { + mode_gate = true; + continue; + } + break; + } + extra_args(args, argidx, design); + + if (mode_gold && mode_gate) + log_cmd_error("Options -gold and -gate are exclusive.\n"); + + for (auto module : design->selected_modules()) + { + for (auto cell : module->selected_cells()) + if (cell->type == ID($equiv) && (mode_gold || mode_gate || cell->getPort(ID::A) == cell->getPort(ID::B))) { + log("Removing $equiv cell %s.%s (%s).\n", module, cell, log_signal(cell->getPort(ID::Y))); + module->connect(cell->getPort(ID::Y), mode_gate ? cell->getPort(ID::B) : cell->getPort(ID::A)); + module->remove(cell); + remove_count++; + } + } + + log("Removed a total of %d $equiv cells.\n", remove_count); + } +} EquivRemovePass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/equiv/equiv_simple.cc b/chips/yosys/passes/equiv/equiv_simple.cc new file mode 100644 index 0000000000000000000000000000000000000000..99d20e850bf1b3fd35cda747b8a6e487dbd91dce --- /dev/null +++ b/chips/yosys/passes/equiv/equiv_simple.cc @@ -0,0 +1,513 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/log.h" +#include "kernel/yosys.h" +#include "passes/equiv/equiv.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct EquivSimpleConfig : EquivBasicConfig { + bool verbose = false; + bool short_cones = false; + bool group = true; + bool parse(const std::vector& args, size_t& idx) { + if (EquivBasicConfig::parse(args, idx)) + return true; + if (args[idx] == "-v") { + verbose = true; + return true; + } + if (args[idx] == "-short") { + short_cones = true; + return true; + } + if (args[idx] == "-nogroup") { + group = false; + return true; + } + return false; + } + static void help(const char* default_seq) { + EquivBasicConfig::help(default_seq); + log(" -v\n"); + log(" verbose output\n"); + log("\n"); + log(" -short\n"); + log(" create shorter input cones that stop at shared nodes. This yields\n"); + log(" simpler SAT problems but sometimes fails to prove equivalence.\n"); + log("\n"); + log(" -nogroup\n"); + log(" disabling grouping of $equiv cells by output wire\n"); + log("\n"); + } +}; + +struct EquivSimpleWorker : public EquivWorker +{ + const vector &equiv_cells; + const vector &assume_cells; + struct Cone { + pool cells; + pool bits; + void clear() { + cells.clear(); + bits.clear(); + } + }; + + struct DesignModel { + const SigMap &sigmap; + dict &bit2driver; + }; + DesignModel model; + + pool> imported_cells_cache; + + EquivSimpleWorker(const vector &equiv_cells, const vector &assume_cells, DesignModel model, EquivSimpleConfig cfg) : + EquivWorker(equiv_cells.front()->module, &model.sigmap, cfg), equiv_cells(equiv_cells), assume_cells(assume_cells), + model(model) {} + + struct ConeFinder { + DesignModel model; + // Bits we should also analyze in a later iteration (flop inputs) + pool &next_seed; + // Cells and bits we've seen so far while traversing + Cone& cone; + // We're not allowed to traverse past cells and bits in `stop` + const Cone& stop; + // Input bits are bits that no longer can be traversed + // Tracking these is optional + pool* input_bits; + + // Recursively traverses backwards from a cell to find all cells in its input cone + // Adds cell to cone.cells, stops at cells in 'stop' set + // Returns true if stopped on a stop cell + bool find_input_cone(Cell *cell) + { + if (cone.cells.count(cell)) + return false; + + cone.cells.insert(cell); + + if (stop.cells.count(cell)) + return true; + + for (auto &conn : cell->connections()) + if (yosys_celltypes.cell_input(cell->type, conn.first)) + for (auto bit : model.sigmap(conn.second)) { + if (cell->is_builtin_ff()) { + if (!conn.first.in(ID::CLK, ID::C)) + next_seed.insert(bit); + } else + find_input_cone(bit); + } + return false; + } + void find_input_cone(SigBit bit) + { + if (cone.bits.count(bit)) + return; + + cone.bits.insert(bit); + + if (stop.bits.count(bit)) { + if (input_bits != nullptr) input_bits->insert(bit); + return; + } + + if (!model.bit2driver.count(bit)) + return; + + // If the input cone of the driver cell reaches a stop bit, + // then `bit` is an "input bit" + if (find_input_cone(model.bit2driver.at(bit))) + if (input_bits != nullptr) input_bits->insert(bit); + } + void find_input_cone(pool bits) + { + for (auto bit : bits) + find_input_cone(bit); + } + }; + + // Builds (full or short) input cones from the seeds + // Creates full cones (no stops) and optionally short cones (stop at other side's cone) + // Updates seed_a/seed_b with next iteration's FF inputs + // Returns input bits and cone structures for SAT problem construction + std::tuple, Cone, Cone> init_iter(pool& seed_a, pool& seed_b) const + { + // Empty, never inserted to, to traverse full cones + const Cone no_stop; + Cone full_cone_a, full_cone_b; + + // Values of seed_* for the next iteration + pool next_seed_a, next_seed_b; + + { + ConeFinder finder_a {model, next_seed_a, full_cone_a, no_stop, nullptr}; + finder_a.find_input_cone(seed_a); + + ConeFinder finder_b {model, next_seed_b, full_cone_b, no_stop, nullptr}; + finder_b.find_input_cone(seed_b); + } + + Cone short_cone_a, short_cone_b; + pool input_bits; + + if (cfg.short_cones) + { + // Rebuild cones with the knowledge of the full cones. + // Avoids stuffing overlaps in input cones into the solver + // e.g. for A by using the full B cone as stops + next_seed_a.clear(); + ConeFinder short_finder_a = {model, next_seed_a, short_cone_a, short_cone_b, &input_bits}; + short_finder_a.find_input_cone(seed_a); + next_seed_a.swap(seed_a); + + next_seed_b.clear(); + ConeFinder short_finder_b = {model, next_seed_b, short_cone_b, short_cone_a, &input_bits}; + short_finder_b.find_input_cone(seed_b); + next_seed_b.swap(seed_b); + } + else + { + short_cone_a = full_cone_a; + next_seed_a.swap(seed_a); + + short_cone_b = full_cone_b; + next_seed_b.swap(seed_b); + } + return std::make_tuple(input_bits, short_cone_a, short_cone_b); + } + + void report_new_cells(const pool& cells, const Cone& cone_a, const Cone& cone_b) const + { + log(" Adding %d new cells to the problem (%d A, %d B, %d shared).\n", + GetSize(cells), GetSize(cone_a.cells), GetSize(cone_b.cells), + (GetSize(cone_a.cells) + GetSize(cone_b.cells)) - GetSize(cells)); + #if 0 + for (auto cell : short_cells_cone_a) + log(" A-side cell: %s\n", cell); + + for (auto cell : short_cells_cone_b) + log(" B-side cell: %s\n", cell); + #endif + } + void report_new_assume_cells(const pool& extra_problem_cells, int old_size, const pool& problem_cells) const + { + if (cfg.verbose) { + log(" Adding %d new cells to check assumptions (and reusing %d).\n", + GetSize(problem_cells) - old_size, + old_size - (GetSize(problem_cells) - GetSize(extra_problem_cells))); + #if 0 + for (auto cell : extra_problem_cells) + log(" cell: %s\n", cell); + #endif + } + } + + // Ensure the input cones of $assume cells get modelled by the problem + pool add_assumes_to_problem(const Cone& cone_a, const Cone& cone_b) const + { + pool extra_problem_cells; + for (auto assume : assume_cells) { + pool assume_seed, dummy_next_seed, overlap_bits; + assume_seed.insert(model.sigmap(assume->getPort(ID::A)).as_bit()); + assume_seed.insert(model.sigmap(assume->getPort(ID::EN)).as_bit()); + + for (auto& cone : {cone_a, cone_b}) { + Cone assume_cone; + ConeFinder{model, dummy_next_seed, assume_cone, cone, &overlap_bits} + .find_input_cone(assume_seed); + if (GetSize(overlap_bits)) { + extra_problem_cells.insert(assume); + extra_problem_cells.insert(assume_cone.cells.begin(), assume_cone.cells.end()); + overlap_bits.clear(); + } + assume_cone.clear(); + dummy_next_seed.clear(); + } + } + return extra_problem_cells; + } + + void prepare_ezsat(int ez_context, SigBit bit_a, SigBit bit_b) + { + if (satgen.model_undef) + { + int ez_a = satgen.importSigBit(bit_a, cfg.max_seq+1); + int ez_b = satgen.importDefSigBit(bit_b, cfg.max_seq+1); + int ez_undef_a = satgen.importUndefSigBit(bit_a, cfg.max_seq+1); + + ez->assume(ez->XOR(ez_a, ez_b), ez_context); + ez->assume(ez->NOT(ez_undef_a), ez_context); + } + else + { + int ez_a = satgen.importSigBit(bit_a, cfg.max_seq+1); + int ez_b = satgen.importSigBit(bit_b, cfg.max_seq+1); + ez->assume(ez->XOR(ez_a, ez_b), ez_context); + } + } + void construct_ezsat(const pool& input_bits, int step) + { + log("ezsat\n"); + if (cfg.set_assumes) { + log("yep assume\n"); + if (cfg.verbose && step == cfg.max_seq) { + RTLIL::SigSpec assumes_a, assumes_en; + satgen.getAssumes(assumes_a, assumes_en, step+1); + for (int i = 0; i < GetSize(assumes_a); i++) + log(" Import constraint from assume cell: %s when %s (%d).\n", log_signal(assumes_a[i]), log_signal(assumes_en[i]), step); + } + ez->assume(satgen.importAssumes(step+1)); + } + + if (satgen.model_undef) { + for (auto bit : input_bits) + ez->assume(ez->NOT(satgen.importUndefSigBit(bit, step+1))); + } + + if (cfg.verbose) + log(" Problem size at t=%d: %d literals, %d clauses\n", step, ez->numCnfVariables(), ez->numCnfClauses()); + } + + bool prove_equiv_cell(Cell* cell) + { + SigBit bit_a = model.sigmap(cell->getPort(ID::A)).as_bit(); + SigBit bit_b = model.sigmap(cell->getPort(ID::B)).as_bit(); + int ez_context = ez->frozen_literal(); + + prepare_ezsat(ez_context, bit_a, bit_b); + + // Two bits, bit_a, and bit_b, have been marked equivalent in the design + // We will be traversing the input cones for each of them + // In the first iteration, we will using those as starting points + pool seed_a = { bit_a }; + pool seed_b = { bit_b }; + + if (cfg.verbose) { + log(" Trying to prove $equiv cell %s:\n", cell); + log(" A = %s, B = %s, Y = %s\n", log_signal(bit_a), log_signal(bit_b), log_signal(cell->getPort(ID::Y))); + } else { + log(" Trying to prove $equiv for %s:\n", log_signal(cell->getPort(ID::Y))); + } + + int step = cfg.max_seq; + while (1) + { + // Traverse input cones of seed_a and seed_b, potentially finding new seeds + auto [input_bits, cone_a, cone_b] = init_iter(seed_a, seed_b); + + // Cells to model in SAT solver + pool problem_cells; + problem_cells.insert(cone_a.cells.begin(), cone_a.cells.end()); + problem_cells.insert(cone_b.cells.begin(), cone_b.cells.end()); + + if (cfg.verbose) + report_new_cells(problem_cells, cone_a, cone_b); + + if (cfg.set_assumes) { + auto extras = add_assumes_to_problem(cone_a, cone_b); + if (GetSize(extras)) { + auto old_size = GetSize(problem_cells); + problem_cells.insert(extras.begin(), extras.end()); + report_new_assume_cells(extras, old_size, problem_cells); + } + } + + for (auto cell : problem_cells) { + auto key = pair(cell, step+1); + if (!imported_cells_cache.count(key) && !satgen.importCell(cell, step+1)) { + report_missing_model(cfg.ignore_unknown_cells, cell); + } + imported_cells_cache.insert(key); + } + + construct_ezsat(input_bits, step); + + if (!ez->solve(ez_context)) { + std::string message = " success!"; + if (cfg.verbose) + message = " Proved equivalence! Marking $equiv cell as proven."; + log("%s\n", message); + // Replace $equiv cell with a short + cell->setPort(ID::B, cell->getPort(ID::A)); + ez->assume(ez->NOT(ez_context)); + return true; + } + + if (cfg.verbose) + log(" Failed to prove equivalence with sequence length %d.\n", cfg.max_seq - step); + + if (--step < 0) { + if (cfg.verbose) + log(" Reached sequence limit.\n"); + break; + } + + if (seed_a.empty() && seed_b.empty()) { + if (cfg.verbose) + log(" No nets to continue in previous time step.\n"); + break; + } + + if (seed_a.empty()) { + if (cfg.verbose) + log(" No nets on A-side to continue in previous time step.\n"); + break; + } + + if (seed_b.empty()) { + if (cfg.verbose) + log(" No nets on B-side to continue in previous time step.\n"); + break; + } + + if (cfg.verbose) { + #if 0 + log(" Continuing analysis in previous time step with the following nets:\n"); + for (auto bit : seed_a) + log(" A: %s\n", log_signal(bit)); + for (auto bit : seed_b) + log(" B: %s\n", log_signal(bit)); + #else + log(" Continuing analysis in previous time step with %d A- and %d B-nets.\n", GetSize(seed_a), GetSize(seed_b)); + #endif + } + } + + if (!cfg.verbose) + log(" failed.\n"); + + ez->assume(ez->NOT(ez_context)); + return false; + } + + int run() + { + if (GetSize(equiv_cells) > 1) { + SigSpec sig; + for (auto c : equiv_cells) + sig.append(model.sigmap(c->getPort(ID::Y))); + log(" Grouping SAT models for %s:\n", log_signal(sig)); + } + + int counter = 0; + for (auto c : equiv_cells) { + if (prove_equiv_cell(c)) + counter++; + } + return counter; + } + +}; + +struct EquivSimplePass : public Pass { + EquivSimplePass() : Pass("equiv_simple", "try proving simple $equiv instances") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" equiv_simple [options] [selection]\n"); + log("\n"); + log("This command tries to prove $equiv cells using a simple direct SAT approach.\n"); + log("\n"); + EquivSimpleConfig::help("1"); + log("\n"); + } + void execute(std::vector args, Design *design) override + { + EquivSimpleConfig cfg {}; + int success_counter = 0; + + log_header(design, "Executing EQUIV_SIMPLE pass.\n"); + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + if (cfg.parse(args, argidx)) + continue; + break; + } + extra_args(args, argidx, design); + + CellTypes ct; + ct.setup_internals(); + ct.setup_stdcells(); + ct.setup_internals_ff(); + ct.setup_stdcells_mem(); + + for (auto module : design->selected_modules()) + { + SigMap sigmap(module); + dict bit2driver; + dict> unproven_equiv_cells; + vector assumes; + int unproven_cells_counter = 0; + + for (auto cell : module->selected_cells()) { + if (cell->type == ID($equiv) && cell->getPort(ID::A) != cell->getPort(ID::B)) { + auto bit = sigmap(cell->getPort(ID::Y).as_bit()); + auto bit_group = bit; + if (cfg.group && bit_group.wire) + bit_group.offset = 0; + unproven_equiv_cells[bit_group][bit] = cell; + unproven_cells_counter++; + } else if (cell->type == ID($assume)) { + assumes.push_back(cell); + } + } + + if (unproven_equiv_cells.empty()) + continue; + + log("Found %d unproven $equiv cells (%d groups) in %s:\n", + unproven_cells_counter, GetSize(unproven_equiv_cells), module); + + for (auto cell : module->cells()) { + if (!ct.cell_known(cell->type)) + continue; + for (auto &conn : cell->connections()) + if (yosys_celltypes.cell_output(cell->type, conn.first)) + for (auto bit : sigmap(conn.second)) + bit2driver[bit] = cell; + } + + unproven_equiv_cells.sort(); + for (auto [_, d] : unproven_equiv_cells) + { + d.sort(); + + vector cells; + for (auto [_, cell] : d) + cells.push_back(cell); + + EquivSimpleWorker::DesignModel model {sigmap, bit2driver}; + EquivSimpleWorker worker(cells, assumes, model, cfg); + success_counter += worker.run(); + } + } + + log("Proved %d previously unproven $equiv cells.\n", success_counter); + } +} EquivSimplePass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/equiv/equiv_status.cc b/chips/yosys/passes/equiv/equiv_status.cc new file mode 100644 index 0000000000000000000000000000000000000000..da53c60a27bab20f7746ec9cc0e7733e0f837528 --- /dev/null +++ b/chips/yosys/passes/equiv/equiv_status.cc @@ -0,0 +1,94 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct EquivStatusPass : public Pass { + EquivStatusPass() : Pass("equiv_status", "print status of equivalent checking module") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" equiv_status [options] [selection]\n"); + log("\n"); + log("This command prints status information for all selected $equiv cells.\n"); + log("\n"); + log(" -assert\n"); + log(" produce an error if any unproven $equiv cell is found\n"); + log("\n"); + } + void execute(std::vector args, Design *design) override + { + bool assert_mode = false; + int unproven_count = 0; + + log_header(design, "Executing EQUIV_STATUS pass.\n"); + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + if (args[argidx] == "-assert") { + assert_mode = true; + continue; + } + break; + } + extra_args(args, argidx, design); + + for (auto module : design->selected_modules()) + { + vector unproven_equiv_cells; + int proven_equiv_cells = 0; + + for (auto cell : module->selected_cells()) + if (cell->type == ID($equiv)) { + if (cell->getPort(ID::A) != cell->getPort(ID::B)) + unproven_equiv_cells.push_back(cell); + else + proven_equiv_cells++; + } + + if (unproven_equiv_cells.empty() && !proven_equiv_cells) { + log("No $equiv cells found in %s.\n", module); + continue; + } + + log("Found %d $equiv cells in %s:\n", GetSize(unproven_equiv_cells) + proven_equiv_cells, module); + log(" Of those cells %d are proven and %d are unproven.\n", proven_equiv_cells, GetSize(unproven_equiv_cells)); + if (unproven_equiv_cells.empty()) { + log(" Equivalence successfully proven!\n"); + } else { + for (auto cell : unproven_equiv_cells) + log(" Unproven $equiv %s: %s %s\n", cell, log_signal(cell->getPort(ID::A)), log_signal(cell->getPort(ID::B))); + } + + unproven_count += GetSize(unproven_equiv_cells); + } + + if (unproven_count != 0) { + log("Found a total of %d unproven $equiv cells.\n", unproven_count); + if (assert_mode && unproven_count != 0) + log_error("Found %d unproven $equiv cells in 'equiv_status -assert'.\n", unproven_count); + } + } +} EquivStatusPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/equiv/equiv_struct.cc b/chips/yosys/passes/equiv/equiv_struct.cc new file mode 100644 index 0000000000000000000000000000000000000000..81db53bda194a776f39e54639ca46877a5d58f22 --- /dev/null +++ b/chips/yosys/passes/equiv/equiv_struct.cc @@ -0,0 +1,365 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "kernel/sigtools.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct EquivStructWorker +{ + Module *module; + SigMap sigmap; + SigMap equiv_bits; + bool mode_fwd; + bool mode_icells; + int merge_count; + + const pool &fwonly_cells; + + struct merge_key_t + { + IdString type; + vector> parameters; + vector> port_sizes; + vector> connections; + + bool operator==(const merge_key_t &other) const { + return type == other.type && connections == other.connections && + parameters == other.parameters && port_sizes == other.port_sizes; + } + + [[nodiscard]] Hasher hash_into(Hasher h) const { + h.eat(type); + h.eat(parameters); + h.eat(port_sizes); + h.eat(connections); + return h; + } + }; + + dict> merge_cache; + pool fwd_merge_cache, bwd_merge_cache; + + void merge_cell_pair(Cell *cell_a, Cell *cell_b) + { + SigMap merged_map; + merge_count++; + + SigSpec inputs_a, inputs_b; + vector input_names; + + for (auto &port_a : cell_a->connections()) + { + SigSpec bits_a = sigmap(port_a.second); + SigSpec bits_b = sigmap(cell_b->getPort(port_a.first)); + + log_assert(GetSize(bits_a) == GetSize(bits_b)); + + if (!cell_a->output(port_a.first)) + for (int i = 0; i < GetSize(bits_a); i++) + if (bits_a[i] != bits_b[i]) { + inputs_a.append(bits_a[i]); + inputs_b.append(bits_b[i]); + input_names.push_back(GetSize(bits_a) == 1 ? module->twines().str(port_a.first) : + stringf("%s[%d]", module->twines().unescaped_str(port_a.first), i)); + } + } + + for (int i = 0; i < GetSize(inputs_a); i++) { + SigBit bit_a = inputs_a[i], bit_b = inputs_b[i]; + SigBit bit_y = module->addWire(NEW_ID); + log(" New $equiv for input %s: A: %s, B: %s, Y: %s\n", + input_names[i], log_signal(bit_a), log_signal(bit_b), log_signal(bit_y)); + module->addEquiv(NEW_ID, bit_a, bit_b, bit_y); + merged_map.add(bit_a, bit_y); + merged_map.add(bit_b, bit_y); + } + + std::vector outport_names, inport_names; + + for (auto &port_a : cell_a->connections()) + if (cell_a->output(port_a.first)) + outport_names.push_back(port_a.first); + else + inport_names.push_back(port_a.first); + + for (auto &pn : inport_names) + cell_a->setPort(pn, merged_map(sigmap(cell_a->getPort(pn)))); + + for (auto &pn : outport_names) { + SigSpec sig_a = cell_a->getPort(pn); + SigSpec sig_b = cell_b->getPort(pn); + module->connect(sig_b, sig_a); + } + + cell_a->set_bool_attribute(ID::equiv_merged); + module->remove(cell_b); + } + + EquivStructWorker(Module *module, bool mode_fwd, bool mode_icells, const pool &fwonly_cells, int iter_num) : + module(module), sigmap(module), equiv_bits(module), + mode_fwd(mode_fwd), mode_icells(mode_icells), merge_count(0), fwonly_cells(fwonly_cells) + { + log(" Starting iteration %d.\n", iter_num); + + pool equiv_inputs; + pool cells; + + for (auto cell : module->selected_cells()) + if (cell->type == ID($equiv)) { + SigBit sig_a = sigmap(cell->getPort(ID::A).as_bit()); + SigBit sig_b = sigmap(cell->getPort(ID::B).as_bit()); + equiv_bits.add(sig_b, sig_a); + equiv_inputs.insert(sig_a); + equiv_inputs.insert(sig_b); + cells.insert(cell->name); + } else { + if (mode_icells || module->design->module(cell->type)) + cells.insert(cell->name); + } + + for (auto cell : module->selected_cells()) + if (cell->type == ID($equiv)) { + SigBit sig_a = sigmap(cell->getPort(ID::A).as_bit()); + SigBit sig_b = sigmap(cell->getPort(ID::B).as_bit()); + SigBit sig_y = sigmap(cell->getPort(ID::Y).as_bit()); + if (sig_a == sig_b && equiv_inputs.count(sig_y)) { + log(" Purging redundant $equiv cell %s.\n", cell); + module->connect(sig_y, sig_a); + module->remove(cell); + merge_count++; + } + } + + if (merge_count > 0) + return; + + for (auto cell_name : cells) + { + merge_key_t key; + vector> fwd_connections; + + Cell *cell = module->cell(cell_name); + key.type = cell->type; + + for (auto &it : cell->parameters) + key.parameters.push_back(it); + std::sort(key.parameters.begin(), key.parameters.end()); + + for (auto &it : cell->connections()) + key.port_sizes.push_back(make_pair(it.first, GetSize(it.second))); + std::sort(key.port_sizes.begin(), key.port_sizes.end()); + + for (auto &conn : cell->connections()) + { + if (cell->input(conn.first)) { + SigSpec sig = sigmap(conn.second); + for (int i = 0; i < GetSize(sig); i++) + fwd_connections.push_back(std::make_tuple(conn.first, i, sig[i])); + } + + if (cell->output(conn.first)) { + SigSpec sig = equiv_bits(conn.second); + for (int i = 0; i < GetSize(sig); i++) { + key.connections.clear(); + key.connections.push_back(std::make_tuple(conn.first, i, sig[i])); + + if (merge_cache.count(key)) + bwd_merge_cache.insert(key); + merge_cache[key].insert(cell_name); + } + } + } + + std::sort(fwd_connections.begin(), fwd_connections.end()); + key.connections.swap(fwd_connections); + + if (merge_cache.count(key)) + fwd_merge_cache.insert(key); + merge_cache[key].insert(cell_name); + } + + for (int phase = 0; phase < 2; phase++) + { + auto &queue = phase ? bwd_merge_cache : fwd_merge_cache; + + for (auto &key : queue) + { + const char *strategy = nullptr; + vector gold_cells, gate_cells, other_cells; + vector> cell_pairs; + IdString cells_type; + + for (auto cell_name : merge_cache[key]) { + Cell *c = module->cell(cell_name); + if (c != nullptr) { + string n = module->twines().str(cell_name); + cells_type = c->type; + if (GetSize(n) > 5 && n.compare(GetSize(n)-5, std::string::npos, "_gold") == 0) + gold_cells.push_back(c); + else if (GetSize(n) > 5 && n.compare(GetSize(n)-5, std::string::npos, "_gate") == 0) + gate_cells.push_back(c); + else + other_cells.push_back(c); + } + } + + if (phase && fwonly_cells.count(cells_type)) + continue; + + if (GetSize(gold_cells) > 1 || GetSize(gate_cells) > 1 || GetSize(other_cells) > 1) + { + strategy = "deduplicate"; + for (int i = 0; i+1 < GetSize(gold_cells); i += 2) + cell_pairs.push_back(make_pair(gold_cells[i], gold_cells[i+1])); + for (int i = 0; i+1 < GetSize(gate_cells); i += 2) + cell_pairs.push_back(make_pair(gate_cells[i], gate_cells[i+1])); + for (int i = 0; i+1 < GetSize(other_cells); i += 2) + cell_pairs.push_back(make_pair(other_cells[i], other_cells[i+1])); + goto run_strategy; + } + + if (GetSize(gold_cells) == 1 && GetSize(gate_cells) == 1) + { + strategy = "gold-gate-pairs"; + cell_pairs.push_back(make_pair(gold_cells[0], gate_cells[0])); + goto run_strategy; + } + + if (GetSize(gold_cells) == 1 && GetSize(other_cells) == 1) + { + strategy = "gold-guess"; + cell_pairs.push_back(make_pair(gold_cells[0], other_cells[0])); + goto run_strategy; + } + + if (GetSize(other_cells) == 1 && GetSize(gate_cells) == 1) + { + strategy = "gate-guess"; + cell_pairs.push_back(make_pair(other_cells[0], gate_cells[0])); + goto run_strategy; + } + + log_assert(GetSize(gold_cells) + GetSize(gate_cells) + GetSize(other_cells) < 2); + continue; + + run_strategy: + int total_group_size = GetSize(gold_cells) + GetSize(gate_cells) + GetSize(other_cells); + log(" %s merging %d %s cells (from group of %d) using strategy %s:\n", phase ? "Bwd" : "Fwd", + 2*GetSize(cell_pairs), PooledName(module->design, cells_type).unescape(), total_group_size, strategy); + for (auto it : cell_pairs) { + log(" Merging cells %s and %s.\n", it.first, it.second); + merge_cell_pair(it.first, it.second); + } + } + + if (merge_count > 0) + return; + } + + log(" Nothing to merge.\n"); + } +}; + +struct EquivStructPass : public Pass { + EquivStructPass() : Pass("equiv_struct", "structural equivalence checking") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" equiv_struct [options] [selection]\n"); + log("\n"); + log("This command adds additional $equiv cells based on the assumption that the\n"); + log("gold and gate circuit are structurally equivalent. Note that this can introduce\n"); + log("bad $equiv cells in cases where the netlists are not structurally equivalent,\n"); + log("for example when analyzing circuits with cells with commutative inputs. This\n"); + log("command will also de-duplicate gates.\n"); + log("\n"); + log(" -fwd\n"); + log(" by default this command performans forward sweeps until nothing can\n"); + log(" be merged by forwards sweeps, then backward sweeps until forward\n"); + log(" sweeps are effective again. with this option set only forward sweeps\n"); + log(" are performed.\n"); + log("\n"); + log(" -fwonly \n"); + log(" add the specified cell type to the list of cell types that are only\n"); + log(" merged in forward sweeps and never in backward sweeps. $equiv is in\n"); + log(" this list automatically.\n"); + log("\n"); + log(" -icells\n"); + log(" by default, the internal RTL and gate cell types are ignored. add\n"); + log(" this option to also process those cell types with this command.\n"); + log("\n"); + log(" -maxiter \n"); + log(" maximum number of iterations to run before aborting\n"); + log("\n"); + } + void execute(std::vector args, Design *design) override + { + pool fwonly_cells({ ID($equiv) }); + bool mode_icells = false; + bool mode_fwd = false; + int max_iter = -1; + + log_header(design, "Executing EQUIV_STRUCT pass.\n"); + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + if (args[argidx] == "-fwd") { + mode_fwd = true; + continue; + } + if (args[argidx] == "-icells") { + mode_icells = true; + continue; + } + if (args[argidx] == "-fwonly" && argidx+1 < args.size()) { + fwonly_cells.insert(design->twines().add(RTLIL::escape_id(args[++argidx]))); + continue; + } + if (args[argidx] == "-maxiter" && argidx+1 < args.size()) { + max_iter = atoi(args[++argidx].c_str()); + continue; + } + break; + } + extra_args(args, argidx, design); + + for (auto module : design->selected_modules()) { + int module_merge_count = 0; + log("Running equiv_struct on module %s:\n", module); + for (int iter = 0;; iter++) { + if (iter == max_iter) { + log(" Reached iteration limit of %d.\n", iter); + break; + } + EquivStructWorker worker(module, mode_fwd, mode_icells, fwonly_cells, iter+1); + if (worker.merge_count == 0) + break; + module_merge_count += worker.merge_count; + } + if (module_merge_count) + log(" Performed a total of %d merges in module %s.\n", module_merge_count, module); + } + } +} EquivStructPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/fsm/CMakeLists.txt b/chips/yosys/passes/fsm/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..487ef49d362da0a1d871aae67bfc37380aee1aa3 --- /dev/null +++ b/chips/yosys/passes/fsm/CMakeLists.txt @@ -0,0 +1,52 @@ +yosys_core(fsmdata INTERFACE + fsmdata.h + DATA_DIR + include/passes/fsm + DATA_FILES + fsmdata.h +) + +function(yosys_fsm_pass) + yosys_pass(${ARGV} REQUIRES fsmdata) +endfunction() + +yosys_fsm_pass(fsm_detect + fsm_detect.cc +) +yosys_fsm_pass(fsm_extract + fsm_extract.cc +) +yosys_fsm_pass(fsm_opt + fsm_opt.cc +) +yosys_fsm_pass(fsm_expand + fsm_expand.cc + REQUIRES + fsm_opt +) +yosys_fsm_pass(fsm_recode + fsm_recode.cc +) +yosys_fsm_pass(fsm_info + fsm_info.cc +) +yosys_fsm_pass(fsm_export + fsm_export.cc +) +yosys_fsm_pass(fsm_map + fsm_map.cc +) + +yosys_pass(fsm + fsm.cc + REQUIRES + fsm_detect + fsm_expand + fsm_export + fsm_extract + fsm_info + fsm_map + fsm_opt + fsm_recode + opt_clean +) diff --git a/chips/yosys/passes/fsm/fsm.cc b/chips/yosys/passes/fsm/fsm.cc new file mode 100644 index 0000000000000000000000000000000000000000..8e7e09d4c24bf82416c18c77907305a6cc060fa6 --- /dev/null +++ b/chips/yosys/passes/fsm/fsm.cc @@ -0,0 +1,166 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/register.h" +#include "kernel/log.h" +#include +#include + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct FsmPass : public Pass { + FsmPass() : Pass("fsm", "extract and optimize finite state machines") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" fsm [options] [selection]\n"); + log("\n"); + log("This pass calls all the other fsm_* passes in a useful order. This performs\n"); + log("FSM extraction and optimization. It also calls opt_clean as needed:\n"); + log("\n"); + log(" fsm_detect unless got option -nodetect\n"); + log(" fsm_extract\n"); + log("\n"); + log(" fsm_opt\n"); + log(" opt_clean\n"); + log(" fsm_opt\n"); + log("\n"); + log(" fsm_expand if got option -expand\n"); + log(" opt_clean if got option -expand\n"); + log(" fsm_opt if got option -expand\n"); + log("\n"); + log(" fsm_recode unless got option -norecode\n"); + log("\n"); + log(" fsm_info\n"); + log("\n"); + log(" fsm_export if got option -export\n"); + log(" fsm_map unless got option -nomap\n"); + log("\n"); + log("Options:\n"); + log("\n"); + log(" -expand, -norecode, -export, -nomap\n"); + log(" enable or disable passes as indicated above\n"); + log("\n"); + log(" -fullexpand\n"); + log(" call expand with -full option\n"); + log("\n"); + log(" -encoding type\n"); + log(" -fm_set_fsm_file file\n"); + log(" -encfile file\n"); + log(" passed through to fsm_recode pass\n"); + log("\n"); + log("This pass uses a subset of FF types to detect FSMs. Run 'opt -nosdff -nodffe'\n"); + log("before this pass to prepare the design.\n"); + log("\n"); +#ifdef YOSYS_ENABLE_VERIFIC + log("The Verific frontend may merge multiplexers in a way that interferes with FSM\n"); + log("detection. Run 'verific -cfg db_infer_wide_muxes_post_elaboration 0' before\n"); + log("reading the source, and 'bmuxmap' after 'proc' for best results.\n"); + log("\n"); +#endif + } + void execute(std::vector args, RTLIL::Design *design) override + { + bool flag_nomap = false; + bool flag_norecode = false; + bool flag_nodetect = false; + bool flag_expand = false; + bool flag_fullexpand = false; + bool flag_export = false; + std::string fm_set_fsm_file_opt; + std::string encfile_opt; + std::string encoding_opt; + + log_header(design, "Executing FSM pass (extract and optimize FSM).\n"); + log_push(); + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + std::string arg = args[argidx]; + if (arg == "-fm_set_fsm_file" && argidx+1 < args.size() && fm_set_fsm_file_opt.empty()) { + fm_set_fsm_file_opt = " -fm_set_fsm_file " + args[++argidx]; + continue; + } + if (arg == "-encfile" && argidx+1 < args.size() && encfile_opt.empty()) { + encfile_opt = " -encfile " + args[++argidx]; + continue; + } + if (arg == "-encoding" && argidx+1 < args.size() && encoding_opt.empty()) { + encoding_opt = " -encoding " + args[++argidx]; + continue; + } + if (arg == "-nodetect") { + flag_nodetect = true; + continue; + } + if (arg == "-norecode") { + flag_norecode = true; + continue; + } + if (arg == "-nomap") { + flag_nomap = true; + continue; + } + if (arg == "-expand") { + flag_expand = true; + continue; + } + if (arg == "-fullexpand") { + flag_fullexpand = true; + continue; + } + if (arg == "-export") { + flag_export = true; + continue; + } + break; + } + extra_args(args, argidx, design); + + if (!flag_nodetect) + Pass::call(design, "fsm_detect"); + Pass::call(design, "fsm_extract"); + + Pass::call(design, "fsm_opt"); + Pass::call(design, "opt_clean"); + Pass::call(design, "fsm_opt"); + + if (flag_expand || flag_fullexpand) { + Pass::call(design, flag_fullexpand ? "fsm_expand -full" : "fsm_expand"); + Pass::call(design, "opt_clean"); + Pass::call(design, "fsm_opt"); + } + + if (!flag_norecode) + Pass::call(design, "fsm_recode" + fm_set_fsm_file_opt + encfile_opt + encoding_opt); + Pass::call(design, "fsm_info"); + + if (flag_export) + Pass::call(design, "fsm_export"); + + if (!flag_nomap) + Pass::call(design, "fsm_map"); + + log_pop(); + } +} FsmPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/fsm/fsm_detect.cc b/chips/yosys/passes/fsm/fsm_detect.cc new file mode 100644 index 0000000000000000000000000000000000000000..3e95ac7b190338c4c5de5ffa0518db38082dbe48 --- /dev/null +++ b/chips/yosys/passes/fsm/fsm_detect.cc @@ -0,0 +1,352 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/log.h" +#include "kernel/register.h" +#include "kernel/sigtools.h" +#include "kernel/consteval.h" +#include "kernel/celltypes.h" +#include "fsmdata.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct FsmDetectWorker +{ + RTLIL::Module *module; + SigMap assign_map; + typedef std::pair sig2driver_entry_t; + SigSet sig2driver, sig2user; + std::set muxtree_cells; + SigPool sig_at_port; + + FsmDetectWorker(RTLIL::Module *module, const CellTypes &ct) : module(module), assign_map(module) + { + for (auto cell : module->cells()) + for (auto &conn_it : cell->connections()) { + if (ct.cell_output(cell->type, conn_it.first) || !ct.cell_known(cell->type)) { + RTLIL::SigSpec sig = conn_it.second; + assign_map.apply(sig); + sig2driver.insert(sig, sig2driver_entry_t(cell, conn_it.first)); + } + if (!ct.cell_known(cell->type) || ct.cell_input(cell->type, conn_it.first)) { + RTLIL::SigSpec sig = conn_it.second; + assign_map.apply(sig); + sig2user.insert(sig, sig2driver_entry_t(cell, conn_it.first)); + } + } + + for (auto wire : module->wires()) + if (wire->port_id != 0) + sig_at_port.add(assign_map(wire)); + } + + bool check_state_mux_tree(RTLIL::SigSpec old_sig, RTLIL::SigSpec sig, pool &recursion_monitor, dict &mux_tree_cache) + { + if (mux_tree_cache.find(sig) != mux_tree_cache.end()) + return mux_tree_cache.at(sig); + + if (sig.is_fully_const() || old_sig == sig) { + ret_true: + mux_tree_cache[sig] = true; + return true; + } + + if (sig_at_port.check_any(assign_map(sig))) { + ret_false: + mux_tree_cache[sig] = false; + return false; + } + + std::set cellport_list; + sig2driver.find(sig, cellport_list); + for (auto &cellport : cellport_list) + { + if ((cellport.first->type != ID($mux) && cellport.first->type != ID($pmux)) || cellport.second != ID::Y) { + goto ret_false; + } + + if (recursion_monitor.count(cellport.first)) { + log_warning("logic loop in mux tree at signal %s in module %s.\n", + log_signal(sig), module); + goto ret_false; + } + + recursion_monitor.insert(cellport.first); + + RTLIL::SigSpec sig_a = assign_map(cellport.first->getPort(ID::A)); + RTLIL::SigSpec sig_b = assign_map(cellport.first->getPort(ID::B)); + + if (!check_state_mux_tree(old_sig, sig_a, recursion_monitor, mux_tree_cache)) { + recursion_monitor.erase(cellport.first); + goto ret_false; + } + + for (int i = 0; i < sig_b.size(); i += sig_a.size()) + if (!check_state_mux_tree(old_sig, sig_b.extract(i, sig_a.size()), recursion_monitor, mux_tree_cache)) { + recursion_monitor.erase(cellport.first); + goto ret_false; + } + + recursion_monitor.erase(cellport.first); + muxtree_cells.insert(cellport.first); + } + + goto ret_true; + } + + bool check_state_users(RTLIL::SigSpec sig) + { + if (sig_at_port.check_any(assign_map(sig))) + return false; + + std::set cellport_list; + sig2user.find(sig, cellport_list); + for (auto &cellport : cellport_list) { + RTLIL::Cell *cell = cellport.first; + if (muxtree_cells.count(cell) > 0) + continue; + if (cell->type == ID($logic_not) && assign_map(cell->getPort(ID::A)) == sig) + continue; + if (cellport.second != ID::A && cellport.second != ID::B) + return false; + if (!cell->hasPort(ID::A) || !cell->hasPort(ID::B) || !cell->hasPort(ID::Y)) + return false; + for (auto &port_it : cell->connections()) + if (port_it.first != ID::A && port_it.first != ID::B && port_it.first != ID::Y) + return false; + if (assign_map(cell->getPort(ID::A)) == sig && cell->getPort(ID::B).is_fully_const()) + continue; + if (assign_map(cell->getPort(ID::B)) == sig && cell->getPort(ID::A).is_fully_const()) + continue; + return false; + } + + return true; + } + + void detect_fsm(RTLIL::Wire *wire, bool ignore_self_reset=false) + { + bool has_fsm_encoding_attr = wire->attributes.count(ID::fsm_encoding) > 0 && wire->attributes.at(ID::fsm_encoding).decode_string() != "none"; + bool has_fsm_encoding_none = wire->attributes.count(ID::fsm_encoding) > 0 && wire->attributes.at(ID::fsm_encoding).decode_string() == "none"; + bool has_init_attr = wire->attributes.count(ID::init) > 0; + bool is_module_port = sig_at_port.check_any(assign_map(RTLIL::SigSpec(wire))); + bool looks_like_state_reg = false, looks_like_good_state_reg = false; + bool is_self_resetting = false; + + if (has_fsm_encoding_none) + return; + + if (wire->width <= 1) { + if (has_fsm_encoding_attr) { + log_warning("Removing fsm_encoding attribute from 1-bit net: %s.%s\n", wire->module, wire); + wire->attributes.erase(ID::fsm_encoding); + } + return; + } + + std::set cellport_list; + sig2driver.find(RTLIL::SigSpec(wire), cellport_list); + + for (auto &cellport : cellport_list) + { + if ((cellport.first->type != ID($dff) && cellport.first->type != ID($adff)) || cellport.second != ID::Q) + continue; + + muxtree_cells.clear(); + pool recursion_monitor; + RTLIL::SigSpec sig_q = assign_map(cellport.first->getPort(ID::Q)); + RTLIL::SigSpec sig_d = assign_map(cellport.first->getPort(ID::D)); + dict mux_tree_cache; + + if (sig_q != assign_map(wire)) + continue; + + looks_like_state_reg = check_state_mux_tree(sig_q, sig_d, recursion_monitor, mux_tree_cache); + looks_like_good_state_reg = check_state_users(sig_q); + + if (!looks_like_state_reg) + break; + + ConstEval ce(wire->module); + + std::set cellport_list; + sig2user.find(sig_q, cellport_list); + + auto sig_q_bits = sig_q.to_sigbit_pool(); + + for (auto &cellport : cellport_list) + { + RTLIL::Cell *cell = cellport.first; + bool set_output = false, clr_output = false; + + if (cell->type.in(ID($ne), ID($reduce_or), ID($reduce_bool))) + set_output = true; + + if (cell->type.in(ID($eq), ID($logic_not), ID($reduce_and))) + clr_output = true; + + if (set_output || clr_output) { + for (auto &port_it : cell->connections()) + if (cell->input(port_it.first)) + for (auto bit : assign_map(port_it.second)) + if (bit.wire != nullptr && !sig_q_bits.count(bit)) + goto next_cellport; + } + + if (set_output || clr_output) { + for (auto &port_it : cell->connections()) + if (cell->output(port_it.first)) { + SigSpec sig = assign_map(port_it.second); + Const val(set_output ? State::S1 : State::S0, GetSize(sig)); + ce.set(sig, val); + } + } + next_cellport:; + } + + SigSpec sig_y = sig_d, sig_undef; + if (!ignore_self_reset) { + if (cellport.first->type == ID($adff)) { + SigSpec sig_arst = assign_map(cellport.first->getPort(ID::ARST)); + if (ce.eval(sig_arst, sig_undef)) + is_self_resetting = true; + } + else if (ce.eval(sig_y, sig_undef)) + is_self_resetting = true; + } + } + + if (has_fsm_encoding_attr) + { + vector warnings; + + if (is_module_port) + warnings.push_back("Forcing FSM recoding on module port might result in larger circuit.\n"); + + if (!looks_like_good_state_reg) + warnings.push_back("Users of state reg look like FSM recoding might result in larger circuit.\n"); + + if (has_init_attr) + warnings.push_back("Initialization value on FSM state register is ignored. Possible simulation-synthesis mismatch!\n"); + + if (!looks_like_state_reg) + warnings.push_back("Doesn't look like a proper FSM. Possible simulation-synthesis mismatch!\n"); + + if (is_self_resetting) + warnings.push_back("FSM seems to be self-resetting. Possible simulation-synthesis mismatch!\n"); + + if (!warnings.empty()) { + string warnmsg = stringf("Regarding the user-specified fsm_encoding attribute on %s.%s:\n", wire->module, wire); + for (auto w : warnings) warnmsg += " " + w; + log_warning("%s", warnmsg); + } else { + log("FSM state register %s.%s already has fsm_encoding attribute.\n", wire->module, wire); + } + } + else + if (looks_like_state_reg && looks_like_good_state_reg && !has_init_attr && !is_module_port && !is_self_resetting) + { + log("Found FSM state register %s.%s.\n", wire->module, wire); + wire->attributes[ID::fsm_encoding] = RTLIL::Const("auto"); + } + else + if (looks_like_state_reg) + { + log("Not marking %s.%s as FSM state register:\n", wire->module, wire); + + if (is_module_port) + log(" Register is connected to module port.\n"); + + if (!looks_like_good_state_reg) + log(" Users of register don't seem to benefit from recoding.\n"); + + if (has_init_attr) + log(" Register has an initialization value.\n"); + + if (is_self_resetting) + log(" Circuit seems to be self-resetting.\n"); + } + } +}; + +struct FsmDetectPass : public Pass { + FsmDetectPass() : Pass("fsm_detect", "finding FSMs in design") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" fsm_detect [options] [selection]\n"); + log("\n"); + log("This pass detects finite state machines by identifying the state signal.\n"); + log("The state signal is then marked by setting the attribute 'fsm_encoding'\n"); + log("on the state signal to \"auto\".\n"); + log("\n"); + log(" -ignore-self-reset\n"); + log(" Mark FSMs even if they are self-resetting\n"); + log("\n"); + log("Existing 'fsm_encoding' attributes are not changed by this pass.\n"); + log("\n"); + log("Signals can be protected from being detected by this pass by setting the\n"); + log("'fsm_encoding' attribute to \"none\".\n"); + log("\n"); + log("This pass uses a subset of FF types to detect FSMs. Run 'opt -nosdff -nodffe'\n"); + log("before this pass to prepare the design for fsm_detect.\n"); + log("\n"); +#ifdef YOSYS_ENABLE_VERIFIC + log("The Verific frontend may optimize the design in a way that interferes with FSM\n"); + log("detection. Run 'verific -cfg db_infer_wide_muxes_post_elaboration 0' before\n"); + log("reading the source, and 'bmuxmap -pmux' after 'proc' for best results.\n"); + log("\n"); +#endif + } + void execute(std::vector args, RTLIL::Design *design) override + { + log_header(design, "Executing FSM_DETECT pass (finding FSMs in design).\n"); + + bool ignore_self_reset = false; + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) + { + if (args[argidx] == "-ignore-self-reset") { + ignore_self_reset = true; + continue; + } + break; + } + extra_args(args, argidx, design); + + CellTypes ct; + ct.setup_internals(); + ct.setup_internals_anyinit(); + ct.setup_internals_mem(); + ct.setup_stdcells(); + ct.setup_stdcells_mem(); + + for (auto mod : design->selected_modules()) + { + FsmDetectWorker worker(mod, ct); + for (auto wire : mod->selected_wires()) + worker.detect_fsm(wire, ignore_self_reset); + } + } +} FsmDetectPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/fsm/fsm_expand.cc b/chips/yosys/passes/fsm/fsm_expand.cc new file mode 100644 index 0000000000000000000000000000000000000000..a688bbf6659bad539af0314feb710d29f35920a9 --- /dev/null +++ b/chips/yosys/passes/fsm/fsm_expand.cc @@ -0,0 +1,315 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/log.h" +#include "kernel/register.h" +#include "kernel/sigtools.h" +#include "kernel/consteval.h" +#include "kernel/celltypes.h" +#include "kernel/unused_bits.h" +#include "fsmdata.h" +#include + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct FsmExpand +{ + RTLIL::Module *module; + RTLIL::Cell *fsm_cell; + UnusedBits& unused_bits; + bool full_mode; + + SigMap assign_map; + SigSet> sig2driver, sig2user; + CellTypes ct; + + std::set> merged_set; + std::set> current_set; + std::set> no_candidate_set; + + bool already_optimized; + int limit_transitions; + + bool is_cell_merge_candidate(RTLIL::Cell *cell) + { + if (full_mode || cell->type == ID($_MUX_)) + return true; + + if (cell->type.in(ID($mux), ID($pmux))) + if (cell->getPort(ID::A).size() < 2) + return true; + + int in_bits = 0; + RTLIL::SigSpec new_signals; + + if (cell->hasPort(ID::A)) { + in_bits += GetSize(cell->getPort(ID::A)); + new_signals.append(assign_map(cell->getPort(ID::A))); + } + + if (cell->hasPort(ID::B)) { + in_bits += GetSize(cell->getPort(ID::B)); + new_signals.append(assign_map(cell->getPort(ID::B))); + } + + if (cell->hasPort(ID::S)) { + in_bits += GetSize(cell->getPort(ID::S)); + new_signals.append(assign_map(cell->getPort(ID::S))); + } + + if (in_bits > 8) + return false; + + if (cell->hasPort(ID::Y)) + new_signals.append(assign_map(cell->getPort(ID::Y))); + + new_signals.sort_and_unify(); + new_signals.remove_const(); + + new_signals.remove(assign_map(fsm_cell->getPort(ID::CTRL_IN))); + new_signals.remove(assign_map(fsm_cell->getPort(ID::CTRL_OUT))); + + if (new_signals.size() > 3) + return false; + + return true; + } + + void create_current_set() + { + std::vector cell_list; + + for (auto c : sig2driver.find(assign_map(fsm_cell->getPort(ID::CTRL_IN)))) + cell_list.push_back(c); + + for (auto c : sig2user.find(assign_map(fsm_cell->getPort(ID::CTRL_OUT)))) + cell_list.push_back(c); + + current_set.clear(); + for (auto c : cell_list) + { + if (merged_set.count(c) > 0 || current_set.count(c) > 0 || no_candidate_set.count(c) > 0) + continue; + for (auto &p : c->connections()) { + if (p.first != ID::A && p.first != ID::B && p.first != ID::S && p.first != ID::Y) + goto next_cell; + } + if (!is_cell_merge_candidate(c)) { + no_candidate_set.insert(c); + continue; + } + current_set.insert(c); + next_cell:; + } + } + + void optimze_as_needed() + { + if (already_optimized) + return; + + int trans_num = fsm_cell->parameters[ID::TRANS_NUM].as_int(); + if (trans_num > limit_transitions) + { + log(" grown transition table to %d entries -> optimize.\n", trans_num); + FsmData::optimize_fsm(fsm_cell, module, unused_bits); + already_optimized = true; + + trans_num = fsm_cell->parameters[ID::TRANS_NUM].as_int(); + log(" transition table size after optimizaton: %d\n", trans_num); + limit_transitions = 16 * trans_num; + } + } + + void merge_cell_into_fsm(RTLIL::Cell *cell) + { + optimze_as_needed(); + + log(" merging %s cell %s.\n", cell->type, cell->name); + merged_set.insert(cell); + already_optimized = false; + + RTLIL::SigSpec input_sig, output_sig; + + for (auto &p : cell->connections()) + if (ct.cell_output(cell->type, p.first)) + output_sig.append(assign_map(p.second)); + else + input_sig.append(assign_map(p.second)); + input_sig.sort_and_unify(); + input_sig.remove_const(); + + std::vector truth_tab; + + for (int i = 0; i < (1 << input_sig.size()); i++) { + RTLIL::Const in_val(i, input_sig.size()); + RTLIL::SigSpec A, B, S; + if (cell->hasPort(ID::A)) + A = assign_map(cell->getPort(ID::A)); + if (cell->hasPort(ID::B)) + B = assign_map(cell->getPort(ID::B)); + if (cell->hasPort(ID::S)) + S = assign_map(cell->getPort(ID::S)); + A.replace(input_sig, RTLIL::SigSpec(in_val)); + B.replace(input_sig, RTLIL::SigSpec(in_val)); + S.replace(input_sig, RTLIL::SigSpec(in_val)); + log_assert(A.is_fully_const()); + log_assert(B.is_fully_const()); + log_assert(S.is_fully_const()); + truth_tab.push_back(ct.eval(cell, A.as_const(), B.as_const(), S.as_const())); + } + + FsmData fsm_data; + fsm_data.copy_from_cell(fsm_cell); + + fsm_data.num_inputs += input_sig.size(); + RTLIL::SigSpec new_ctrl_in = fsm_cell->getPort(ID::CTRL_IN); + new_ctrl_in.append(input_sig); + fsm_cell->setPort(ID::CTRL_IN, new_ctrl_in); + + fsm_data.num_outputs += output_sig.size(); + RTLIL::SigSpec new_ctrl_out = fsm_cell->getPort(ID::CTRL_OUT); + new_ctrl_out.append(output_sig); + fsm_cell->setPort(ID::CTRL_OUT, new_ctrl_out); + + if (GetSize(input_sig) > 10) + log_warning("Cell %s.%s (%s) has %d input bits, merging into FSM %s.%s might be problematic.\n", + cell->module, cell, cell->type.unescape(), + GetSize(input_sig), fsm_cell->module, fsm_cell); + + if (GetSize(fsm_data.transition_table) > 10000) + log_warning("Transition table for FSM %s.%s already has %d rows, merging more cells " + "into this FSM might be problematic.\n", fsm_cell->module, fsm_cell, + GetSize(fsm_data.transition_table)); + + std::vector new_transition_table; + for (auto &tr : fsm_data.transition_table) { + for (int i = 0; i < (1 << input_sig.size()); i++) { + FsmData::transition_t new_tr = tr; + RTLIL::Const in_val(i, input_sig.size()); + RTLIL::Const out_val = truth_tab[i]; + RTLIL::SigSpec ctrl_in = new_tr.ctrl_in; + RTLIL::SigSpec ctrl_out = new_tr.ctrl_out; + ctrl_in.append(in_val); + ctrl_out.append(out_val); + new_tr.ctrl_in = ctrl_in.as_const(); + new_tr.ctrl_out = ctrl_out.as_const(); + new_transition_table.push_back(new_tr); + } + } + fsm_data.transition_table.swap(new_transition_table); + new_transition_table.clear(); + + fsm_data.copy_to_cell(fsm_cell); + } + + FsmExpand(RTLIL::Cell *cell, RTLIL::Design *design, RTLIL::Module *mod, UnusedBits& unused_bits, bool full) : unused_bits(unused_bits) + { + module = mod; + fsm_cell = cell; + full_mode = full; + + assign_map.set(module); + ct.setup_internals(); + ct.setup_stdcells(); + ct.cell_types.erase(ID($barrier)); // never merge through a barrier + + for (auto &cell_it : module->cells_) { + RTLIL::Cell *c = cell_it.second; + if (ct.cell_known(c->type) && design->selected(mod, c)) + for (auto &p : c->connections()) { + if (ct.cell_output(c->type, p.first)) + sig2driver.insert(assign_map(p.second), c); + else + sig2user.insert(assign_map(p.second), c); + } + } + } + + void execute() + { + log("\n"); + log("Expanding FSM `%s' from module `%s':\n", fsm_cell->name, module->name); + + already_optimized = false; + limit_transitions = 16 * fsm_cell->parameters[ID::TRANS_NUM].as_int(); + + for (create_current_set(); current_set.size() > 0; create_current_set()) { + for (auto c : current_set) + merge_cell_into_fsm(c); + } + + for (auto c : merged_set) + module->remove(c); + + if (merged_set.size() > 0 && !already_optimized) + FsmData::optimize_fsm(fsm_cell, module, unused_bits); + + log(" merged %d cells into FSM.\n", GetSize(merged_set)); + } +}; + +struct FsmExpandPass : public Pass { + FsmExpandPass() : Pass("fsm_expand", "expand FSM cells by merging logic into it") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" fsm_expand [-full] [selection]\n"); + log("\n"); + log("The fsm_extract pass is conservative about the cells that belong to a finite\n"); + log("state machine. This pass can be used to merge additional auxiliary gates into\n"); + log("the finite state machine.\n"); + log("\n"); + log("By default, fsm_expand is still a bit conservative regarding merging larger\n"); + log("word-wide cells. Call with -full to consider all cells for merging.\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + bool full_mode = false; + + log_header(design, "Executing FSM_EXPAND pass (merging auxiliary logic into FSMs).\n"); + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + if (args[argidx] == "-full") { + full_mode = true; + continue; + } + break; + } + extra_args(args, argidx, design); + + for (auto mod : design->selected_modules()) { + UnusedBits unused_bits(mod); + std::vector fsm_cells; + for (auto cell : mod->selected_cells()) + if (cell->type == ID($fsm)) + fsm_cells.push_back(cell); + for (auto c : fsm_cells) { + FsmExpand fsm_expand(c, design, mod, unused_bits, full_mode); + fsm_expand.execute(); + } + } + } +} FsmExpandPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/fsm/fsm_export.cc b/chips/yosys/passes/fsm/fsm_export.cc new file mode 100644 index 0000000000000000000000000000000000000000..c9ffd37ff9893abbc22f0996e9717323cd8cdc7d --- /dev/null +++ b/chips/yosys/passes/fsm/fsm_export.cc @@ -0,0 +1,188 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * Copyright (C) 2012 Martin Schmölzer + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/log.h" +#include "kernel/register.h" +#include "kernel/sigtools.h" +#include "kernel/consteval.h" +#include "kernel/celltypes.h" +#include "fsmdata.h" +#include +#include +#include + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +/** + * Convert a signal into a KISS-compatible textual representation. + */ +std::string kiss_convert_signal(const RTLIL::SigSpec &sig) { + log_assert(sig.is_fully_const()); + return sig.as_const().as_string(); +} + +/** + * Create a KISS2 file from a cell. + * + * The destination file name is taken from the fsm_export attribute if present, + * e.g. (* fsm_export="filename.kiss2" *). If this attribute is not present, + * the file name will be assembled from the module and cell names. + * + * @param module pointer to module which contains the FSM cell. + * @param cell pointer to the FSM cell which should be exported. + */ +void write_kiss2(struct RTLIL::Module *module, struct RTLIL::Cell *cell, std::string filename, bool origenc) { + dict::iterator attr_it; + FsmData fsm_data; + FsmData::transition_t tr; + std::ofstream kiss_file; + std::string kiss_name; + size_t i; + + attr_it = cell->attributes.find(ID::fsm_export); + if (!filename.empty()) { + kiss_name.assign(filename); + } else if (attr_it != cell->attributes.end() && attr_it->second.decode_string() != "") { + kiss_name.assign(attr_it->second.decode_string()); + } + else { + kiss_name.assign(module->name.unescape() + std::string("-") + cell->name.unescape() + ".kiss2"); + } + + log("\n"); + log("Exporting FSM `%s' from module `%s' to file `%s'.\n", + cell->name, + module->name, + kiss_name); + + kiss_file.open(kiss_name, std::ios::out | std::ios::trunc); + + if (!kiss_file.is_open()) { + log_error("Could not open file \"%s\" with write access.\n", kiss_name); + } + + fsm_data.copy_from_cell(cell); + + kiss_file << ".i " << std::dec << fsm_data.num_inputs << std::endl; + kiss_file << ".o " << std::dec << fsm_data.num_outputs << std::endl; + kiss_file << ".p " << std::dec << fsm_data.transition_table.size() << std::endl; + kiss_file << ".s " << std::dec << fsm_data.state_table.size() << std::endl; + if (origenc) { + kiss_file << ".r " << kiss_convert_signal(fsm_data.state_table[fsm_data.reset_state]) << std::endl; + } else { + kiss_file << ".r s" << std::dec << fsm_data.reset_state << std::endl; + } + + for (i = 0; i < fsm_data.transition_table.size(); i++) { + tr = fsm_data.transition_table[i]; + + try { + kiss_file << kiss_convert_signal(tr.ctrl_in) << ' '; + if (origenc) { + kiss_file << kiss_convert_signal(fsm_data.state_table[tr.state_in]) << ' '; + kiss_file << kiss_convert_signal(fsm_data.state_table[tr.state_out]) << ' '; + } else { + kiss_file << 's' << tr.state_in << ' '; + kiss_file << 's' << tr.state_out << ' '; + } + kiss_file << kiss_convert_signal(tr.ctrl_out) << std::endl; + } + catch (int) { + kiss_file.close(); + log_error("exporting an FSM input or output signal failed.\n"); + } + } + + kiss_file.close(); +} + +/** + * Exports Finite State Machines in the design to one file per FSM. Currently, + * only the KISS2 file format is supported. + */ +struct FsmExportPass : public Pass { + FsmExportPass() : Pass("fsm_export", "exporting FSMs to KISS2 files") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" fsm_export [-noauto] [-o filename] [-origenc] [selection]\n"); + log("\n"); + log("This pass creates a KISS2 file for every selected FSM. For FSMs with the\n"); + log("'fsm_export' attribute set, the attribute value is used as filename, otherwise\n"); + log("the module and cell name is used as filename. If the parameter '-o' is given,\n"); + log("the first exported FSM is written to the specified filename. This overwrites\n"); + log("the setting as specified with the 'fsm_export' attribute. All other FSMs are\n"); + log("exported to the default name as mentioned above.\n"); + log("\n"); + log(" -noauto\n"); + log(" only export FSMs that have the 'fsm_export' attribute set\n"); + log("\n"); + log(" -o filename\n"); + log(" filename of the first exported FSM\n"); + log("\n"); + log(" -origenc\n"); + log(" use binary state encoding as state names instead of s0, s1, ...\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + dict::iterator attr_it; + std::string arg; + bool flag_noauto = false; + std::string filename; + bool flag_origenc = false; + size_t argidx; + + log_header(design, "Executing FSM_EXPORT pass (exporting FSMs in KISS2 file format).\n"); + + for (argidx = 1; argidx < args.size(); argidx++) { + arg = args[argidx]; + if (arg == "-noauto") { + flag_noauto = true; + continue; + } + if (arg == "-o") { + argidx++; + filename = args[argidx]; + continue; + } + if (arg == "-origenc") { + flag_origenc = true; + continue; + } + break; + } + extra_args(args, argidx, design); + + for (auto mod : design->selected_modules()) + for (auto cell : mod->selected_cells()) + if (cell->type == ID($fsm)) { + attr_it = cell->attributes.find(ID::fsm_export); + if (!flag_noauto || (attr_it != cell->attributes.end())) { + write_kiss2(mod, cell, filename, flag_origenc); + filename.clear(); + } + } + } +} FsmExportPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/fsm/fsm_extract.cc b/chips/yosys/passes/fsm/fsm_extract.cc new file mode 100644 index 0000000000000000000000000000000000000000..71b6d78946fc79fb22536e5e5d667bd0bbbf168c --- /dev/null +++ b/chips/yosys/passes/fsm/fsm_extract.cc @@ -0,0 +1,493 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +// [[CITE]] +// Yiqiong Shi; Chan Wai Ting; Bah-Hwee Gwee; Ye Ren, "A highly efficient method for extracting FSMs from flattened gate-level netlist," +// Circuits and Systems (ISCAS), Proceedings of 2010 IEEE International Symposium on , vol., no., pp.2610,2613, May 30 2010-June 2 2010 +// doi: 10.1109/ISCAS.2010.5537093 + +#include "kernel/log.h" +#include "kernel/register.h" +#include "kernel/sigtools.h" +#include "kernel/consteval.h" +#include "kernel/celltypes.h" +#include "fsmdata.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct FsmExtractWorker +{ + RTLIL::Module *module; + SigMap assign_map; + typedef std::pair sig2driver_entry_t; + SigSet sig2driver, sig2trigger; + std::map> exclusive_ctrls; + + FsmExtractWorker(RTLIL::Module *module, const CellTypes &ct) : module(module), assign_map(module) + { + for (auto cell : module->cells()) { + for (auto &conn_it : cell->connections()) { + if (ct.cell_output(cell->type, conn_it.first) || !ct.cell_known(cell->type)) { + RTLIL::SigSpec sig = conn_it.second; + assign_map.apply(sig); + sig2driver.insert(sig, sig2driver_entry_t(cell->name, conn_it.first)); + } + if (cell->type != ID($barrier) && ct.cell_input(cell->type, conn_it.first) && cell->hasPort(ID::Y) && + cell->getPort(ID::Y).size() == 1 && (conn_it.first == ID::A || conn_it.first == ID::B)) { + RTLIL::SigSpec sig = conn_it.second; + assign_map.apply(sig); + sig2trigger.insert(sig, sig2driver_entry_t(cell->name, conn_it.first)); + } + } + if (cell->type == ID($pmux)) { + RTLIL::SigSpec sel_sig = assign_map(cell->getPort(ID::S)); + for (auto &bit1 : sel_sig) + for (auto &bit2 : sel_sig) + if (bit1 != bit2) + exclusive_ctrls[bit1].insert(bit2); + } + } + } + + bool find_states(RTLIL::SigSpec sig, const RTLIL::SigSpec &dff_out, RTLIL::SigSpec &ctrl, std::map &states, RTLIL::Const *reset_state = NULL) + { + sig.extend_u0(dff_out.size(), false); + + if (sig == dff_out) + return true; + + assign_map.apply(sig); + if (sig.is_fully_const()) { + if (sig.is_fully_def() && states.count(sig.as_const()) == 0) { + log(" found state code: %s\n", log_signal(sig)); + states[sig.as_const()] = -1; + } + return true; + } + + std::set cellport_list; + sig2driver.find(sig, cellport_list); + + if (GetSize(cellport_list) > 1) { + log(" found %d combined drivers for state signal %s.\n", GetSize(cellport_list), log_signal(sig)); + return false; + } + + if (GetSize(cellport_list) < 1) { + log(" found no driver for state signal %s.\n", log_signal(sig)); + return false; + } + + for (auto &cellport : cellport_list) + { + RTLIL::Cell *cell = module->cell(cellport.first); + if ((cell->type != ID($mux) && cell->type != ID($pmux)) || cellport.second != ID::Y) { + log(" unexpected cell type %s (%s) found in state selection tree.\n", cell->type, cell->name); + return false; + } + + RTLIL::SigSpec sig_a = assign_map(cell->getPort(ID::A)); + RTLIL::SigSpec sig_b = assign_map(cell->getPort(ID::B)); + RTLIL::SigSpec sig_s = assign_map(cell->getPort(ID::S)); + RTLIL::SigSpec sig_y = assign_map(cell->getPort(ID::Y)); + + RTLIL::SigSpec sig_aa = sig; + sig_aa.replace(sig_y, sig_a); + + RTLIL::SigSpec sig_bb; + for (int i = 0; i < GetSize(sig_b)/GetSize(sig_a); i++) { + RTLIL::SigSpec s = sig; + s.replace(sig_y, sig_b.extract(i*GetSize(sig_a), GetSize(sig_a))); + sig_bb.append(s); + } + + if (reset_state && RTLIL::SigSpec(*reset_state).is_fully_undef()) + do { + SigSpec new_reset_state; + if (sig_aa.is_fully_def()) + new_reset_state = sig_aa.as_const(); + else if (sig_bb.is_fully_def()) + new_reset_state = sig_bb.as_const(); + else + break; + new_reset_state.extend_u0(GetSize(*reset_state)); + *reset_state = new_reset_state.as_const(); + log(" found reset state: %s (guessed from mux tree)\n", log_signal(*reset_state)); + } while (0); + + for (auto sig_s_bit : sig_s) { + if (ctrl.extract(sig_s_bit).empty()) { + log(" found ctrl input: %s\n", log_signal(sig_s_bit)); + ctrl.append(sig_s_bit); + } + } + + if (!find_states(sig_aa, dff_out, ctrl, states)) + return false; + + for (int i = 0; i < GetSize(sig_bb)/GetSize(sig_aa); i++) { + if (!find_states(sig_bb.extract(i*GetSize(sig_aa), GetSize(sig_aa)), dff_out, ctrl, states)) + return false; + } + } + + return true; + } + + RTLIL::Const sig2const(ConstEval &ce, RTLIL::SigSpec sig, RTLIL::State noconst_state, RTLIL::SigSpec dont_care = RTLIL::SigSpec()) + { + if (dont_care.size() > 0) { + for (int i = 0; i < GetSize(sig); i++) + if (dont_care.extract(sig[i]).size() > 0) + sig[i] = noconst_state; + } + + ce.assign_map.apply(sig); + ce.values_map.apply(sig); + + for (int i = 0; i < GetSize(sig); i++) + if (sig[i].wire != NULL) + sig[i] = noconst_state; + + return sig.as_const(); + } + + int find_next_state(const FsmData &fsm_data, const std::map &states, int state_in, const RTLIL::Const &next_state) + { + if (states.count(next_state)) + return states.at(next_state); + + // prefer state_in, then try the other states in order + std::vector candidates = {state_in}; + for (int i = 0; i < GetSize(fsm_data.state_table); i++) + candidates.push_back(i); + + for (int i : candidates) { + const RTLIL::Const &state = fsm_data.state_table.at(i); + bool match = true; + // an undef bit can take any value, so only the defined bits must match + for (int j = 0; j < GetSize(next_state); j++) + if (next_state[j] != RTLIL::State::Sx && next_state[j] != state[j]) { + match = false; + break; + } + if (match) + return i; + } + + return -1; + } + + bool find_transitions(ConstEval &ce, ConstEval &ce_nostop, FsmData &fsm_data, std::map &states, int state_in, RTLIL::SigSpec ctrl_in, RTLIL::SigSpec ctrl_out, RTLIL::SigSpec dff_in, RTLIL::SigSpec dont_care) + { + RTLIL::SigSpec undef, constval; + bool ok = true; + + if (ce.eval(ctrl_out, undef) && ce.eval(dff_in, undef)) + { + log_assert(ctrl_out.is_fully_const() && dff_in.is_fully_const()); + + FsmData::transition_t tr; + tr.ctrl_in = sig2const(ce, ctrl_in, RTLIL::State::Sa, dont_care); + tr.ctrl_out = sig2const(ce, ctrl_out, RTLIL::State::Sx); + + std::map ctrl_in_bit_indices; + for (int i = 0; i < GetSize(ctrl_in); i++) + ctrl_in_bit_indices[ctrl_in[i]] = i; + + for (auto &it : ctrl_in_bit_indices) + if (tr.ctrl_in.at(it.second) == State::S1 && exclusive_ctrls.count(it.first) != 0) + for (auto &dc_bit : exclusive_ctrls.at(it.first)) + if (ctrl_in_bit_indices.count(dc_bit)) + tr.ctrl_in.set(ctrl_in_bit_indices.at(dc_bit), RTLIL::State::Sa); + + RTLIL::Const next_state = dff_in.as_const(); + tr.state_in = state_in; + tr.state_out = find_next_state(fsm_data, states, state_in, next_state); + + if (tr.state_out < 0) { + log(" transition: %10s %s -> INVALID_STATE(%s) %s\n", + log_signal(fsm_data.state_table.at(state_in)), log_signal(tr.ctrl_in), + log_signal(next_state), log_signal(tr.ctrl_out)); + return false; + } + + fsm_data.transition_table.push_back(tr); + log(" transition: %10s %s -> %10s %s%s\n", + log_signal(fsm_data.state_table.at(state_in)), log_signal(tr.ctrl_in), + log_signal(fsm_data.state_table[tr.state_out]), log_signal(tr.ctrl_out), + next_state.is_fully_def() ? "" : stringf(" ", log_signal(next_state))); + return true; + } + + log_assert(undef.size() > 0); + log_assert(ce.stop_signals.check_all(undef)); + + undef = undef.extract(0, 1); + constval = undef; + + if (ce_nostop.eval(constval)) + { + ce.push(); + dont_care.append(undef); + ce.set(undef, constval.as_const()); + if (exclusive_ctrls.count(undef) && constval == State::S1) + for (auto &bit : exclusive_ctrls.at(undef)) { + RTLIL::SigSpec bitval = bit; + if (ce.eval(bitval) && bitval != State::S0) + goto found_contradiction_1; + else + ce.set(bit, State::S0); + } + ok = find_transitions(ce, ce_nostop, fsm_data, states, state_in, ctrl_in, ctrl_out, dff_in, dont_care); + found_contradiction_1: + ce.pop(); + } + else + { + ce.push(), ce_nostop.push(); + ce.set(undef, State::S0); + ce_nostop.set(undef, State::S0); + ok = find_transitions(ce, ce_nostop, fsm_data, states, state_in, ctrl_in, ctrl_out, dff_in, dont_care); + ce.pop(), ce_nostop.pop(); + if (!ok) + return false; + + ce.push(), ce_nostop.push(); + ce.set(undef, State::S1); + ce_nostop.set(undef, State::S1); + if (exclusive_ctrls.count(undef)) + for (auto &bit : exclusive_ctrls.at(undef)) { + RTLIL::SigSpec bitval = bit; + if ((ce.eval(bitval) || ce_nostop.eval(bitval)) && bitval != State::S0) + goto found_contradiction_2; + else + ce.set(bit, State::S0), ce_nostop.set(bit, RTLIL::S0); + } + ok = find_transitions(ce, ce_nostop, fsm_data, states, state_in, ctrl_in, ctrl_out, dff_in, dont_care); + found_contradiction_2: + ce.pop(), ce_nostop.pop(); + } + return ok; + } + + void extract_fsm(RTLIL::Wire *wire) + { + log("Extracting FSM `%s' from module `%s'.\n", wire->name, module->name); + + // get input and output signals for state ff + + RTLIL::SigSpec dff_out = assign_map(RTLIL::SigSpec(wire)); + RTLIL::SigSpec dff_in(RTLIL::State::Sm, wire->width); + RTLIL::Const reset_state(RTLIL::State::Sx, wire->width); + + RTLIL::SigSpec clk = State::S0; + RTLIL::SigSpec arst = State::S0; + bool clk_polarity = true; + bool arst_polarity = true; + + std::set cellport_list; + sig2driver.find(dff_out, cellport_list); + for (auto &cellport : cellport_list) { + RTLIL::Cell *cell = module->cell(cellport.first); + if ((cell->type != ID($dff) && cell->type != ID($adff)) || cellport.second != ID::Q) + continue; + log(" found %s cell for state register: %s\n", cell->type, cell->name); + RTLIL::SigSpec sig_q = assign_map(cell->getPort(ID::Q)); + RTLIL::SigSpec sig_d = assign_map(cell->getPort(ID::D)); + clk = cell->getPort(ID::CLK); + clk_polarity = cell->parameters[ID::CLK_POLARITY].as_bool(); + if (cell->type == ID($adff)) { + arst = cell->getPort(ID::ARST); + arst_polarity = cell->parameters[ID::ARST_POLARITY].as_bool(); + reset_state = cell->parameters[ID::ARST_VALUE]; + } + sig_q.replace(dff_out, sig_d, &dff_in); + break; + } + + log(" root of input selection tree: %s\n", log_signal(dff_in)); + if (dff_in.has_marked_bits()) { + log(" fsm extraction failed: incomplete input selection tree root.\n"); + return; + } + + // find states and control inputs + + RTLIL::SigSpec ctrl_in; + std::map states; + if (!arst.is_fully_const()) { + log(" found reset state: %s (from async reset)\n", log_signal(reset_state)); + states[reset_state] = -1; + } + if (!find_states(dff_in, dff_out, ctrl_in, states, &reset_state)) { + log(" fsm extraction failed: state selection tree is not closed.\n"); + return; + } + if (GetSize(states) <= 1) { + log(" fsm extraction failed: at least two states are required.\n"); + return; + } + + // find control outputs + // (add the state signals to the list of control outputs. if everything goes right, this signals + // become unused and can then be removed from the fsm control output) + + RTLIL::SigSpec ctrl_out = dff_in; + cellport_list.clear(); + sig2trigger.find(dff_out, cellport_list); + for (auto &cellport : cellport_list) { + RTLIL::Cell *cell = module->cell(cellport.first); + RTLIL::SigSpec sig_a = assign_map(cell->getPort(ID::A)); + RTLIL::SigSpec sig_b; + if (cell->hasPort(ID::B)) + sig_b = assign_map(cell->getPort(ID::B)); + RTLIL::SigSpec sig_y = assign_map(cell->getPort(ID::Y)); + if (cellport.second == ID::A && !sig_b.is_fully_const()) + continue; + if (cellport.second == ID::B && !sig_a.is_fully_const()) + continue; + log(" found ctrl output: %s\n", log_signal(sig_y)); + ctrl_out.append(sig_y); + } + ctrl_in.remove(ctrl_out); + + ctrl_in.sort_and_unify(); + ctrl_out.sort_and_unify(); + + log(" ctrl inputs: %s\n", log_signal(ctrl_in)); + log(" ctrl outputs: %s\n", log_signal(ctrl_out)); + + // Initialize fsm data struct + + FsmData fsm_data; + fsm_data.num_inputs = ctrl_in.size(); + fsm_data.num_outputs = ctrl_out.size(); + fsm_data.state_bits = wire->width; + fsm_data.reset_state = -1; + for (auto &it : states) { + it.second = fsm_data.state_table.size(); + fsm_data.state_table.push_back(it.first); + } + if (!arst.is_fully_const() || RTLIL::SigSpec(reset_state).is_fully_def()) + fsm_data.reset_state = states[reset_state]; + + // Create transition table + + ConstEval ce(module), ce_nostop(module); + ce.stop(ctrl_in); + for (int state_idx = 0; state_idx < int(fsm_data.state_table.size()); state_idx++) { + ce.push(), ce_nostop.push(); + ce.set(dff_out, fsm_data.state_table[state_idx]); + ce_nostop.set(dff_out, fsm_data.state_table[state_idx]); + bool ok = find_transitions(ce, ce_nostop, fsm_data, states, state_idx, ctrl_in, ctrl_out, dff_in, RTLIL::SigSpec()); + ce.pop(), ce_nostop.pop(); + if (!ok) { + log(" fsm extraction failed: next state matches no state code.\n"); + return; + } + } + + // create fsm cell + + RTLIL::Cell *fsm_cell = module->addCell(stringf("$fsm$%s$%d", wire->name, module->twines().next_autoidx()), ID($fsm)); + fsm_cell->setPort(ID::CLK, clk); + fsm_cell->setPort(ID::ARST, arst); + fsm_cell->parameters[ID::CLK_POLARITY] = clk_polarity ? State::S1 : State::S0; + fsm_cell->parameters[ID::ARST_POLARITY] = arst_polarity ? State::S1 : State::S0; + fsm_cell->setPort(ID::CTRL_IN, ctrl_in); + fsm_cell->setPort(ID::CTRL_OUT, ctrl_out); + fsm_cell->parameters[ID::NAME] = RTLIL::Const(wire->name.str()); + fsm_cell->attributes = wire->attributes; + if(fsm_cell->attributes.count(ID::hdlname)) { + auto hdlname = fsm_cell->get_hdlname_attribute(); + hdlname.pop_back(); + fsm_cell->set_hdlname_attribute(hdlname); + fsm_cell->set_string_attribute(ID(scopename), fsm_cell->get_string_attribute(ID::hdlname)); + fsm_cell->attributes.erase(ID::hdlname); + } + fsm_data.copy_to_cell(fsm_cell); + + // rename original state wire + + wire->attributes.erase(ID::fsm_encoding); + module->rename(wire, stringf("$fsm$oldstate%s", wire->name)); + if(wire->attributes.count(ID::hdlname)) { + auto hdlname = wire->get_hdlname_attribute(); + hdlname.pop_back(); + wire->set_hdlname_attribute(hdlname); + wire->set_string_attribute(ID(scopename), wire->get_string_attribute(ID::hdlname)); + wire->attributes.erase(ID::hdlname); + } + + // unconnect control outputs from old drivers + + cellport_list.clear(); + sig2driver.find(ctrl_out, cellport_list); + for (auto &cellport : cellport_list) { + RTLIL::Cell *cell = module->cell(cellport.first); + RTLIL::SigSpec port_sig = assign_map(cell->getPort(cellport.second)); + RTLIL::SigSpec unconn_sig = port_sig.extract(ctrl_out); + RTLIL::Wire *unconn_wire = module->addWire(stringf("$fsm_unconnect$%d", module->twines().next_autoidx()), unconn_sig.size()); + port_sig.replace(unconn_sig, RTLIL::SigSpec(unconn_wire), &cell->connections_[cellport.second]); + } + } +}; + +struct FsmExtractPass : public Pass { + FsmExtractPass() : Pass("fsm_extract", "extracting FSMs in design") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" fsm_extract [selection]\n"); + log("\n"); + log("This pass operates on all signals marked as FSM state signals using the\n"); + log("'fsm_encoding' attribute. It consumes the logic that creates the state signal\n"); + log("and uses the state signal to generate control signal and replaces it with an\n"); + log("FSM cell.\n"); + log("\n"); + log("The generated FSM cell still generates the original state signal with its\n"); + log("original encoding. The 'fsm_opt' pass can be used in combination with the\n"); + log("'opt_clean' pass to eliminate this signal.\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + log_header(design, "Executing FSM_EXTRACT pass (extracting FSM from design).\n"); + extra_args(args, 1, design); + + CellTypes ct(design); + + for (auto mod : design->selected_modules()) + { + FsmExtractWorker worker(mod, ct); + + std::vector wire_list; + for (auto wire : mod->selected_wires()) + if (wire->attributes.count(ID::fsm_encoding) > 0 && wire->attributes[ID::fsm_encoding].decode_string() != "none") + wire_list.push_back(wire); + for (auto wire : wire_list) + worker.extract_fsm(wire); + } + } +} FsmExtractPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/fsm/fsm_info.cc b/chips/yosys/passes/fsm/fsm_info.cc new file mode 100644 index 0000000000000000000000000000000000000000..7b3b59ee9ddf9d7a8dfd50a4761f24326d67630e --- /dev/null +++ b/chips/yosys/passes/fsm/fsm_info.cc @@ -0,0 +1,61 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/log.h" +#include "kernel/register.h" +#include "kernel/sigtools.h" +#include "kernel/consteval.h" +#include "kernel/celltypes.h" +#include "fsmdata.h" +#include + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct FsmInfoPass : public Pass { + FsmInfoPass() : Pass("fsm_info", "print information on finite state machines") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" fsm_info [selection]\n"); + log("\n"); + log("This pass dumps all internal information on FSM cells. It can be useful for\n"); + log("analyzing the synthesis process and is called automatically by the 'fsm'\n"); + log("pass so that this information is included in the synthesis log file.\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + log_header(design, "Executing FSM_INFO pass (dumping all available information on FSM cells).\n"); + extra_args(args, 1, design); + + for (auto mod : design->selected_modules()) + for (auto cell : mod->selected_cells()) + if (cell->type == ID($fsm)) { + log("\n"); + log("FSM `%s' from module `%s':\n", cell, mod); + FsmData fsm_data; + fsm_data.copy_from_cell(cell); + fsm_data.log_info(cell); + } + } +} FsmInfoPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/fsm/fsm_map.cc b/chips/yosys/passes/fsm/fsm_map.cc new file mode 100644 index 0000000000000000000000000000000000000000..c19edcc889e9f86f1cad88af4abb8050063811e8 --- /dev/null +++ b/chips/yosys/passes/fsm/fsm_map.cc @@ -0,0 +1,350 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/log.h" +#include "kernel/register.h" +#include "kernel/sigtools.h" +#include "kernel/consteval.h" +#include "kernel/celltypes.h" +#include "fsmdata.h" +#include + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +static bool pattern_is_subset(const RTLIL::Const &super_pattern, const RTLIL::Const &sub_pattern) +{ + log_assert(GetSize(super_pattern) == GetSize(sub_pattern)); + for (int i = 0; i < GetSize(super_pattern); i++) + if (sub_pattern[i] == RTLIL::State::S0 || sub_pattern[i] == RTLIL::State::S1) { + if (super_pattern[i] == RTLIL::State::S0 || super_pattern[i] == RTLIL::State::S1) { + if (super_pattern[i] != sub_pattern[i]) + return false; + } else + return false; + } + return true; +} + +static void implement_pattern_cache(RTLIL::Module *module, std::map> &pattern_cache, std::set &fullstate_cache, int num_states, RTLIL::Wire *state_onehot, RTLIL::SigSpec &ctrl_in, RTLIL::SigSpec output) +{ + RTLIL::SigSpec cases_vector; + + for (int in_state : fullstate_cache) + cases_vector.append(RTLIL::SigSpec(state_onehot, in_state)); + + for (auto &it : pattern_cache) + { + RTLIL::Const pattern = it.first; + RTLIL::SigSpec eq_sig_a, eq_sig_b, or_sig; + + for (auto j = 0; j < pattern.size(); j++) + if (pattern[j] == RTLIL::State::S0 || pattern[j] == RTLIL::State::S1) { + eq_sig_a.append(ctrl_in.extract(j, 1)); + eq_sig_b.append(RTLIL::SigSpec(pattern[j])); + } + + for (int in_state : it.second) + if (fullstate_cache.count(in_state) == 0) + or_sig.append(RTLIL::SigSpec(state_onehot, in_state)); + + if (or_sig.size() == 0) + continue; + + RTLIL::SigSpec and_sig; + + if (eq_sig_a.size() > 0) + { + RTLIL::Wire *eq_wire = module->addWire(NEW_ID); + and_sig.append(RTLIL::SigSpec(eq_wire)); + + RTLIL::Cell *eq_cell = module->addCell(NEW_ID, ID($eq)); + eq_cell->setPort(ID::A, eq_sig_a); + eq_cell->setPort(ID::B, eq_sig_b); + eq_cell->setPort(ID::Y, RTLIL::SigSpec(eq_wire)); + eq_cell->parameters[ID::A_SIGNED] = RTLIL::Const(false); + eq_cell->parameters[ID::B_SIGNED] = RTLIL::Const(false); + eq_cell->parameters[ID::A_WIDTH] = RTLIL::Const(eq_sig_a.size()); + eq_cell->parameters[ID::B_WIDTH] = RTLIL::Const(eq_sig_b.size()); + eq_cell->parameters[ID::Y_WIDTH] = RTLIL::Const(1); + } + + std::set complete_in_state_cache = it.second; + + for (auto &it2 : pattern_cache) + if (pattern_is_subset(pattern, it2.first)) + complete_in_state_cache.insert(it2.second.begin(), it2.second.end()); + + if (GetSize(complete_in_state_cache) < num_states) + { + if (or_sig.size() == 1) + { + and_sig.append(or_sig); + } + else + { + RTLIL::Wire *or_wire = module->addWire(NEW_ID); + and_sig.append(RTLIL::SigSpec(or_wire)); + + RTLIL::Cell *or_cell = module->addCell(NEW_ID, ID($reduce_or)); + or_cell->setPort(ID::A, or_sig); + or_cell->setPort(ID::Y, RTLIL::SigSpec(or_wire)); + or_cell->parameters[ID::A_SIGNED] = RTLIL::Const(false); + or_cell->parameters[ID::A_WIDTH] = RTLIL::Const(or_sig.size()); + or_cell->parameters[ID::Y_WIDTH] = RTLIL::Const(1); + } + } + + switch (and_sig.size()) + { + case 2: + { + RTLIL::Wire *and_wire = module->addWire(NEW_ID); + cases_vector.append(RTLIL::SigSpec(and_wire)); + + RTLIL::Cell *and_cell = module->addCell(NEW_ID, ID($and)); + and_cell->setPort(ID::A, and_sig.extract(0, 1)); + and_cell->setPort(ID::B, and_sig.extract(1, 1)); + and_cell->setPort(ID::Y, RTLIL::SigSpec(and_wire)); + and_cell->parameters[ID::A_SIGNED] = RTLIL::Const(false); + and_cell->parameters[ID::B_SIGNED] = RTLIL::Const(false); + and_cell->parameters[ID::A_WIDTH] = RTLIL::Const(1); + and_cell->parameters[ID::B_WIDTH] = RTLIL::Const(1); + and_cell->parameters[ID::Y_WIDTH] = RTLIL::Const(1); + break; + } + case 1: + cases_vector.append(and_sig); + break; + case 0: + cases_vector.append(State::S1); + break; + default: + log_abort(); + } + } + + if (cases_vector.size() > 1) { + RTLIL::Cell *or_cell = module->addCell(NEW_ID, ID($reduce_or)); + or_cell->setPort(ID::A, cases_vector); + or_cell->setPort(ID::Y, output); + or_cell->parameters[ID::A_SIGNED] = RTLIL::Const(false); + or_cell->parameters[ID::A_WIDTH] = RTLIL::Const(cases_vector.size()); + or_cell->parameters[ID::Y_WIDTH] = RTLIL::Const(1); + } else if (cases_vector.size() == 1) { + module->connect(RTLIL::SigSig(output, cases_vector)); + } else { + module->connect(RTLIL::SigSig(output, State::S0)); + } +} + +static void map_fsm(RTLIL::Cell *fsm_cell, RTLIL::Module *module) +{ + log("Mapping FSM `%s' from module `%s'.\n", fsm_cell->name, module->name); + + FsmData fsm_data; + fsm_data.copy_from_cell(fsm_cell); + + RTLIL::SigSpec ctrl_in = fsm_cell->getPort(ID::CTRL_IN); + RTLIL::SigSpec ctrl_out = fsm_cell->getPort(ID::CTRL_OUT); + + // create state register + + RTLIL::Wire *state_wire = module->addWire(module->uniquify(fsm_cell->parameters[ID::NAME].decode_string()), fsm_data.state_bits); + RTLIL::Wire *next_state_wire = module->addWire(NEW_ID, fsm_data.state_bits); + + RTLIL::Cell *state_dff = module->addCell(NEW_ID, ""); + if (fsm_cell->getPort(ID::ARST).is_fully_const()) { + state_dff->type = ID($dff); + } else { + state_dff->type = ID($adff); + state_dff->parameters[ID::ARST_POLARITY] = fsm_cell->parameters[ID::ARST_POLARITY]; + state_dff->parameters[ID::ARST_VALUE] = fsm_data.state_table[fsm_data.reset_state]; + for (auto bit : state_dff->parameters[ID::ARST_VALUE]) + if (bit != RTLIL::State::S1) + bit = RTLIL::State::S0; + state_dff->setPort(ID::ARST, fsm_cell->getPort(ID::ARST)); + } + state_dff->parameters[ID::WIDTH] = RTLIL::Const(fsm_data.state_bits); + state_dff->parameters[ID::CLK_POLARITY] = fsm_cell->parameters[ID::CLK_POLARITY]; + state_dff->setPort(ID::CLK, fsm_cell->getPort(ID::CLK)); + state_dff->setPort(ID::D, RTLIL::SigSpec(next_state_wire)); + state_dff->setPort(ID::Q, RTLIL::SigSpec(state_wire)); + + // decode state register + + bool encoding_is_onehot = true; + + RTLIL::Wire *state_onehot = module->addWire(NEW_ID, fsm_data.state_table.size()); + + for (size_t i = 0; i < fsm_data.state_table.size(); i++) + { + RTLIL::Const state = fsm_data.state_table[i]; + RTLIL::SigSpec sig_a, sig_b; + + for (auto j = 0; j < state.size(); j++) + if (state[j] == RTLIL::State::S0 || state[j] == RTLIL::State::S1) { + sig_a.append(RTLIL::SigSpec(state_wire, j)); + sig_b.append(RTLIL::SigSpec(state[j])); + } + + if (sig_b == RTLIL::SigSpec(RTLIL::State::S1)) + { + module->connect(RTLIL::SigSig(RTLIL::SigSpec(state_onehot, i), sig_a)); + } + else + { + encoding_is_onehot = false; + + RTLIL::Cell *eq_cell = module->addCell(NEW_ID, ID($eq)); + eq_cell->setPort(ID::A, sig_a); + eq_cell->setPort(ID::B, sig_b); + eq_cell->setPort(ID::Y, RTLIL::SigSpec(state_onehot, i)); + eq_cell->parameters[ID::A_SIGNED] = RTLIL::Const(false); + eq_cell->parameters[ID::B_SIGNED] = RTLIL::Const(false); + eq_cell->parameters[ID::A_WIDTH] = RTLIL::Const(sig_a.size()); + eq_cell->parameters[ID::B_WIDTH] = RTLIL::Const(sig_b.size()); + eq_cell->parameters[ID::Y_WIDTH] = RTLIL::Const(1); + } + } + + if (encoding_is_onehot) + state_wire->set_bool_attribute(ID::onehot); + + // generate next_state signal + + if (GetSize(fsm_data.state_table) == 1) + { + module->connect(next_state_wire, fsm_data.state_table.front()); + } + else + { + RTLIL::Wire *next_state_onehot = module->addWire(NEW_ID, fsm_data.state_table.size()); + + for (size_t i = 0; i < fsm_data.state_table.size(); i++) + { + std::map> pattern_cache; + std::set fullstate_cache; + + for (size_t j = 0; j < fsm_data.state_table.size(); j++) + fullstate_cache.insert(j); + + for (auto &tr : fsm_data.transition_table) { + if (tr.state_out == int(i)) + pattern_cache[tr.ctrl_in].insert(tr.state_in); + else + fullstate_cache.erase(tr.state_in); + } + + implement_pattern_cache(module, pattern_cache, fullstate_cache, fsm_data.state_table.size(), state_onehot, ctrl_in, RTLIL::SigSpec(next_state_onehot, i)); + } + + if (encoding_is_onehot) + { + RTLIL::SigSpec next_state_sig(RTLIL::State::Sm, next_state_wire->width); + for (size_t i = 0; i < fsm_data.state_table.size(); i++) { + RTLIL::Const state = fsm_data.state_table[i]; + int bit_idx = -1; + for (auto j = 0; j < state.size(); j++) + if (state[j] == RTLIL::State::S1) + bit_idx = j; + if (bit_idx >= 0) + next_state_sig.replace(bit_idx, RTLIL::SigSpec(next_state_onehot, i)); + } + log_assert(!next_state_sig.has_marked_bits()); + module->connect(RTLIL::SigSig(next_state_wire, next_state_sig)); + } + else + { + RTLIL::SigSpec sig_a(RTLIL::State::Sx, next_state_wire->width); + RTLIL::SigSpec sig_b, sig_s; + + for (size_t i = 0; i < fsm_data.state_table.size(); i++) { + RTLIL::Const state = fsm_data.state_table[i]; + if (int(i) == fsm_data.reset_state) { + sig_a = RTLIL::SigSpec(state); + } else { + sig_b.append(RTLIL::SigSpec(state)); + sig_s.append(RTLIL::SigSpec(next_state_onehot, i)); + } + } + + RTLIL::Cell *mux_cell = module->addCell(NEW_ID, ID($pmux)); + mux_cell->setPort(ID::A, sig_a); + mux_cell->setPort(ID::B, sig_b); + mux_cell->setPort(ID::S, sig_s); + mux_cell->setPort(ID::Y, RTLIL::SigSpec(next_state_wire)); + mux_cell->parameters[ID::WIDTH] = RTLIL::Const(sig_a.size()); + mux_cell->parameters[ID::S_WIDTH] = RTLIL::Const(sig_s.size()); + } + } + + // Generate ctrl_out signal + + for (int i = 0; i < fsm_data.num_outputs; i++) + { + std::map> pattern_cache; + std::set fullstate_cache; + + for (size_t j = 0; j < fsm_data.state_table.size(); j++) + fullstate_cache.insert(j); + + for (auto &tr : fsm_data.transition_table) { + if (tr.ctrl_out[i] == RTLIL::State::S1) + pattern_cache[tr.ctrl_in].insert(tr.state_in); + else + fullstate_cache.erase(tr.state_in); + } + + implement_pattern_cache(module, pattern_cache, fullstate_cache, fsm_data.state_table.size(), state_onehot, ctrl_in, ctrl_out.extract(i, 1)); + } + + // Remove FSM cell + + module->remove(fsm_cell); +} + +struct FsmMapPass : public Pass { + FsmMapPass() : Pass("fsm_map", "mapping FSMs to basic logic") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" fsm_map [selection]\n"); + log("\n"); + log("This pass translates FSM cells to flip-flops and logic.\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + log_header(design, "Executing FSM_MAP pass (mapping FSMs to basic logic).\n"); + extra_args(args, 1, design); + + for (auto mod : design->selected_modules()) { + std::vector fsm_cells; + for (auto cell : mod->selected_cells()) + if (cell->type == ID($fsm)) + fsm_cells.push_back(cell); + for (auto cell : fsm_cells) + map_fsm(cell, mod); + } + } +} FsmMapPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/fsm/fsm_opt.cc b/chips/yosys/passes/fsm/fsm_opt.cc new file mode 100644 index 0000000000000000000000000000000000000000..eae91488f276f2b13c5a9ad288fcc3fffca17e68 --- /dev/null +++ b/chips/yosys/passes/fsm/fsm_opt.cc @@ -0,0 +1,342 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/log.h" +#include "kernel/register.h" +#include "kernel/sigtools.h" +#include "kernel/consteval.h" +#include "kernel/celltypes.h" +#include "kernel/unused_bits.h" +#include "fsmdata.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct FsmOpt +{ + FsmData fsm_data; + RTLIL::Cell *cell; + RTLIL::Module *module; + UnusedBits& unused_bits; + + void opt_unreachable_states() + { + while (1) + { + std::set unreachable_states; + std::vector new_transition_table; + std::vector new_state_table; + std::map old_to_new_state; + + for (int i = 0; i < GetSize(fsm_data.state_table); i++) + if (i != fsm_data.reset_state) + unreachable_states.insert(i); + + for (auto &trans : fsm_data.transition_table) + unreachable_states.erase(trans.state_out); + + if (unreachable_states.empty()) + break; + + for (int i = 0; i < GetSize(fsm_data.state_table); i++) { + if (unreachable_states.count(i)) { + log(" Removing unreachable state %s.\n", log_signal(fsm_data.state_table[i])); + continue; + } + old_to_new_state[i] = GetSize(new_state_table); + new_state_table.push_back(fsm_data.state_table[i]); + } + + for (auto trans : fsm_data.transition_table) { + if (unreachable_states.count(trans.state_in)) + continue; + trans.state_in = old_to_new_state.at(trans.state_in); + trans.state_out = old_to_new_state.at(trans.state_out); + new_transition_table.push_back(trans); + } + + new_transition_table.swap(fsm_data.transition_table); + new_state_table.swap(fsm_data.state_table); + if (fsm_data.reset_state != -1) + fsm_data.reset_state = old_to_new_state.at(fsm_data.reset_state); + } + } + + bool signal_is_unused(RTLIL::SigSpec sig) + { + return unused_bits.check(sig.as_bit()); + } + + void opt_const_and_unused_inputs() + { + RTLIL::SigSpec ctrl_in = cell->getPort(ID::CTRL_IN); + std::vector ctrl_in_used(ctrl_in.size()); + + std::vector new_transition_table; + for (auto &tr : fsm_data.transition_table) { + for (int i = 0; i < ctrl_in.size(); i++) { + RTLIL::SigSpec ctrl_bit = ctrl_in.extract(i, 1); + if (ctrl_bit.is_fully_const()) { + if (tr.ctrl_in[i] <= RTLIL::State::S1 && RTLIL::SigSpec(tr.ctrl_in[i]) != ctrl_bit) + goto delete_this_transition; + continue; + } + if (tr.ctrl_in[i] <= RTLIL::State::S1) + ctrl_in_used[i] = true; + } + new_transition_table.push_back(tr); + delete_this_transition:; + } + + for (int i = int(ctrl_in_used.size())-1; i >= 0; i--) { + if (!ctrl_in_used[i]) { + log(" Removing unused input signal %s.\n", log_signal(cell->getPort(ID::CTRL_IN).extract(i, 1))); + for (auto &tr : new_transition_table) { + RTLIL::SigSpec tmp(tr.ctrl_in); + tmp.remove(i, 1); + tr.ctrl_in = tmp.as_const(); + } + RTLIL::SigSpec new_ctrl_in = cell->getPort(ID::CTRL_IN); + new_ctrl_in.remove(i, 1); + cell->setPort(ID::CTRL_IN, new_ctrl_in); + fsm_data.num_inputs--; + } + } + + fsm_data.transition_table.swap(new_transition_table); + new_transition_table.clear(); + } + + void opt_unused_outputs() + { + for (int i = 0; i < fsm_data.num_outputs; i++) { + RTLIL::SigSpec sig = cell->getPort(ID::CTRL_OUT).extract(i, 1); + if (signal_is_unused(sig)) { + log(" Removing unused output signal %s.\n", log_signal(sig)); + RTLIL::SigSpec new_ctrl_out = cell->getPort(ID::CTRL_OUT); + new_ctrl_out.remove(i, 1); + cell->setPort(ID::CTRL_OUT, new_ctrl_out); + for (auto &tr : fsm_data.transition_table) { + RTLIL::SigSpec tmp(tr.ctrl_out); + tmp.remove(i, 1); + tr.ctrl_out = tmp.as_const(); + } + fsm_data.num_outputs--; + i--; + } + } + } + + void opt_alias_inputs() + { + RTLIL::SigSpec &ctrl_in = cell->connections_[ID::CTRL_IN]; + + for (int i = 0; i < ctrl_in.size(); i++) + for (int j = i+1; j < ctrl_in.size(); j++) + if (ctrl_in.extract(i, 1) == ctrl_in.extract(j, 1)) + { + log(" Optimize handling of signal %s that is connected to inputs %d and %d.\n", log_signal(ctrl_in.extract(i, 1)), i, j); + std::vector new_transition_table; + + for (auto tr : fsm_data.transition_table) + { + RTLIL::State si = tr.ctrl_in[i]; + RTLIL::State sj = tr.ctrl_in[j]; + + if (si > RTLIL::State::S1) { + si = sj; + tr.ctrl_in.set(i, si); + } else if (sj > RTLIL::State::S1) { + sj = si; + tr.ctrl_in.set(j, sj); + } + + if (si == sj) { + RTLIL::SigSpec tmp(tr.ctrl_in); + tmp.remove(j, 1); + tr.ctrl_in = tmp.as_const(); + new_transition_table.push_back(tr); + } + } + + ctrl_in.remove(j--, 1); + fsm_data.num_inputs--; + + fsm_data.transition_table.swap(new_transition_table); + new_transition_table.clear(); + } + } + + void opt_feedback_inputs() + { + RTLIL::SigSpec &ctrl_in = cell->connections_[ID::CTRL_IN]; + RTLIL::SigSpec &ctrl_out = cell->connections_[ID::CTRL_OUT]; + + for (int j = 0; j < ctrl_out.size(); j++) + for (int i = 0; i < ctrl_in.size(); i++) + if (ctrl_in.extract(i, 1) == ctrl_out.extract(j, 1)) + { + log(" Optimize handling of signal %s that is connected to input %d and output %d.\n", log_signal(ctrl_in.extract(i, 1)), i, j); + std::vector new_transition_table; + + for (auto tr : fsm_data.transition_table) + { + RTLIL::State si = tr.ctrl_in[i]; + RTLIL::State sj = tr.ctrl_out[j]; + + if (si > RTLIL::State::S1 || si == sj) { + RTLIL::SigSpec tmp(tr.ctrl_in); + tmp.remove(i, 1); + tr.ctrl_in = tmp.as_const(); + new_transition_table.push_back(tr); + } + } + + ctrl_in.remove(i--, 1); + fsm_data.num_inputs--; + + fsm_data.transition_table.swap(new_transition_table); + new_transition_table.clear(); + } + } + + void opt_find_dont_care_worker(std::set &set, int bit, FsmData::transition_t &tr, bool &did_something) + { + std::set new_set; + + for (auto &pattern : set) + { + if (pattern[bit] > RTLIL::State::S1) { + new_set.insert(pattern); + continue; + } + + RTLIL::Const other_pattern = pattern; + + if (pattern[bit] == RTLIL::State::S1) + other_pattern.set(bit, RTLIL::State::S0); + else + other_pattern.set(bit, RTLIL::State::S1); + + if (set.count(other_pattern) > 0) { + log(" Merging pattern %s and %s from group (%d %d %s).\n", log_signal(pattern), log_signal(other_pattern), + tr.state_in, tr.state_out, log_signal(tr.ctrl_out)); + other_pattern.set(bit, RTLIL::State::Sa); + new_set.insert(other_pattern); + did_something = true; + continue; + } + + new_set.insert(pattern); + } + + set.swap(new_set); + } + + void opt_find_dont_care() + { + typedef std::pair, RTLIL::Const> group_t; + std::map> transitions_by_group; + + for (auto &tr : fsm_data.transition_table) { + group_t group(std::pair(tr.state_in, tr.state_out), tr.ctrl_out); + transitions_by_group[group].insert(tr.ctrl_in); + } + + fsm_data.transition_table.clear(); + for (auto &it : transitions_by_group) + { + FsmData::transition_t tr; + tr.state_in = it.first.first.first; + tr.state_out = it.first.first.second; + tr.ctrl_out = it.first.second; + + bool did_something = true; + while (did_something) { + did_something = false; + for (int i = 0; i < fsm_data.num_inputs; i++) + opt_find_dont_care_worker(it.second, i, tr, did_something); + } + + for (auto &ci : it.second) { + tr.ctrl_in = ci; + fsm_data.transition_table.push_back(tr); + } + } + } + + FsmOpt(RTLIL::Cell *cell, RTLIL::Module *module, UnusedBits& unused_bits) : unused_bits(unused_bits) + { + log("Optimizing FSM `%s' from module `%s'.\n", cell->name, module->name); + + fsm_data.copy_from_cell(cell); + this->cell = cell; + this->module = module; + + opt_unreachable_states(); + + opt_unused_outputs(); + + opt_alias_inputs(); + opt_feedback_inputs(); + opt_find_dont_care(); + + opt_const_and_unused_inputs(); + + fsm_data.copy_to_cell(cell); + } +}; + +PRIVATE_NAMESPACE_END + +void YOSYS_NAMESPACE_PREFIX FsmData::optimize_fsm(RTLIL::Cell *cell, RTLIL::Module *module, UnusedBits& unused_bits) +{ + FsmOpt fsmopt(cell, module, unused_bits); +} + +PRIVATE_NAMESPACE_BEGIN + +struct FsmOptPass : public Pass { + FsmOptPass() : Pass("fsm_opt", "optimize finite state machines") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" fsm_opt [selection]\n"); + log("\n"); + log("This pass optimizes FSM cells. It detects which output signals are actually\n"); + log("not used and removes them from the FSM. This pass is usually used in\n"); + log("combination with the 'opt_clean' pass (see also 'help fsm').\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + log_header(design, "Executing FSM_OPT pass (simple optimizations of FSMs).\n"); + extra_args(args, 1, design); + + for (auto mod : design->selected_modules()) { + UnusedBits unused_bits(mod); + for (auto cell : mod->selected_cells()) + if (cell->type == ID($fsm)) + FsmData::optimize_fsm(cell, mod, unused_bits); + } + } +} FsmOptPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/fsm/fsm_recode.cc b/chips/yosys/passes/fsm/fsm_recode.cc new file mode 100644 index 0000000000000000000000000000000000000000..aa96ec6dec068d1dc332bcabee2332754dc7b1fb --- /dev/null +++ b/chips/yosys/passes/fsm/fsm_recode.cc @@ -0,0 +1,197 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/log.h" +#include "kernel/register.h" +#include "kernel/sigtools.h" +#include "kernel/consteval.h" +#include "kernel/celltypes.h" +#include "kernel/utils.h" +#include "fsmdata.h" +#include +#include +#include + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +static void fm_set_fsm_print(RTLIL::Cell *cell, RTLIL::Module *module, FsmData &fsm_data, const char *prefix, FILE *f) +{ + std::string name = cell->parameters[ID::NAME].decode_string(); + + fprintf(f, "set_fsm_state_vector {"); + for (int i = fsm_data.state_bits-1; i >= 0; i--) + fprintf(f, " %s_reg[%d]", name[0] == '\\' ? name.substr(1).c_str() : name.c_str(), i); + fprintf(f, " } -name {%s_%s} {%s:/WORK/%s}\n", prefix, RTLIL::unescape_id(name).c_str(), + prefix, module->name.unescape().c_str()); + + fprintf(f, "set_fsm_encoding {"); + for (int i = 0; i < GetSize(fsm_data.state_table); i++) { + fprintf(f, " s%d=2#", i); + for (int j = GetSize(fsm_data.state_table[i])-1; j >= 0; j--) + fprintf(f, "%c", fsm_data.state_table[i][j] == RTLIL::State::S1 ? '1' : '0'); + } + fprintf(f, " } -name {%s_%s} {%s:/WORK/%s}\n", + prefix, RTLIL::unescape_id(name).c_str(), + prefix, module->name.unescape().c_str()); +} + +static void fsm_recode(RTLIL::Cell *cell, RTLIL::Module *module, FILE *fm_set_fsm_file, FILE *encfile, std::string default_encoding) +{ + std::string encoding = cell->attributes.count(ID::fsm_encoding) ? cell->attributes.at(ID::fsm_encoding).decode_string() : "auto"; + + log("Recoding FSM `%s' from module `%s' using `%s' encoding:\n", cell->name, module->name, encoding); + + if (encoding != "none" && encoding != "user" && encoding != "one-hot" && encoding != "binary" && encoding != "auto") { + log(" unknown encoding `%s': using auto instead.\n", encoding); + encoding = "auto"; + } + + if (encoding == "none" || encoding == "user") { + log(" nothing to do for encoding `%s'.\n", encoding); + return; + } + + FsmData fsm_data; + fsm_data.copy_from_cell(cell); + + if (fm_set_fsm_file != NULL) + fm_set_fsm_print(cell, module, fsm_data, "r", fm_set_fsm_file); + + if (encoding == "auto") { + if (!default_encoding.empty()) + encoding = default_encoding; + else + encoding = GetSize(fsm_data.state_table) < 32 ? "one-hot" : "binary"; + log(" mapping auto encoding to `%s` for this FSM.\n", encoding); + } + + if (encoding == "one-hot") { + fsm_data.state_bits = fsm_data.state_table.size(); + } else + if (encoding == "binary") { + int new_num_state_bits = ceil_log2(fsm_data.state_table.size()); + if (fsm_data.state_bits == new_num_state_bits) { + log(" existing encoding is already a packed binary encoding.\n"); + return; + } + fsm_data.state_bits = new_num_state_bits; + } else + log_error("FSM encoding `%s' is not supported!\n", encoding); + + if (encfile) + fprintf(encfile, ".fsm %s %s\n", module->name.unescape().c_str(), RTLIL::unescape_id(cell->parameters[ID::NAME].decode_string()).c_str()); + + int state_idx_counter = fsm_data.reset_state >= 0 ? 1 : 0; + for (int i = 0; i < int(fsm_data.state_table.size()); i++) + { + int state_idx = fsm_data.reset_state == i ? 0 : state_idx_counter++; + RTLIL::Const new_code; + + if (encoding == "one-hot") { + new_code = RTLIL::Const(RTLIL::State::Sa, fsm_data.state_bits); + new_code.set(state_idx, RTLIL::State::S1); + } else + if (encoding == "binary") { + new_code = RTLIL::Const(state_idx, fsm_data.state_bits); + } else + log_abort(); + + log(" %s -> %s\n", fsm_data.state_table[i].as_string(), new_code.as_string()); + if (encfile) + fprintf(encfile, ".map %s %s\n", fsm_data.state_table[i].as_string().c_str(), new_code.as_string().c_str()); + fsm_data.state_table[i] = new_code; + } + + if (fm_set_fsm_file != NULL) + fm_set_fsm_print(cell, module, fsm_data, "i", fm_set_fsm_file); + + fsm_data.copy_to_cell(cell); +} + +struct FsmRecodePass : public Pass { + FsmRecodePass() : Pass("fsm_recode", "recoding finite state machines") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" fsm_recode [options] [selection]\n"); + log("\n"); + log("This pass reassign the state encodings for FSM cells. At the moment only\n"); + log("one-hot encoding and binary encoding is supported.\n"); + + log(" -encoding \n"); + log(" specify the encoding scheme used for FSMs without the\n"); + log(" 'fsm_encoding' attribute or with the attribute set to `auto'.\n"); + log("\n"); + log(" -fm_set_fsm_file \n"); + log(" generate a file containing the mapping from old to new FSM encoding\n"); + log(" in form of Synopsys Formality set_fsm_* commands.\n"); + log("\n"); + log(" -encfile \n"); + log(" write the mappings from old to new FSM encoding to a file in the\n"); + log(" following format:\n"); + log("\n"); + log(" .fsm \n"); + log(" .map \n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + FILE *fm_set_fsm_file = NULL; + FILE *encfile = NULL; + std::string default_encoding; + + log_header(design, "Executing FSM_RECODE pass (re-assigning FSM state encoding).\n"); + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + std::string arg = args[argidx]; + if (arg == "-fm_set_fsm_file" && argidx+1 < args.size() && fm_set_fsm_file == NULL) { + fm_set_fsm_file = fopen(args[++argidx].c_str(), "w"); + if (fm_set_fsm_file == NULL) + log_error("Can't open fm_set_fsm_file `%s' for writing: %s\n", args[argidx], strerror(errno)); + continue; + } + if (arg == "-encfile" && argidx+1 < args.size() && encfile == NULL) { + encfile = fopen(args[++argidx].c_str(), "w"); + if (encfile == NULL) + log_error("Can't open encfile `%s' for writing: %s\n", args[argidx], strerror(errno)); + continue; + } + if (arg == "-encoding" && argidx+1 < args.size() && default_encoding.empty()) { + default_encoding = args[++argidx]; + continue; + } + break; + } + extra_args(args, argidx, design); + + for (auto mod : design->selected_modules()) + for (auto cell : mod->selected_cells()) + if (cell->type == ID($fsm)) + fsm_recode(cell, mod, fm_set_fsm_file, encfile, default_encoding); + + if (fm_set_fsm_file != NULL) + fclose(fm_set_fsm_file); + if (encfile != NULL) + fclose(encfile); + } +} FsmRecodePass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/fsm/fsmdata.h b/chips/yosys/passes/fsm/fsmdata.h new file mode 100644 index 0000000000000000000000000000000000000000..b0317a1db3d627ac99c0aa62035c2a9a1c70b922 --- /dev/null +++ b/chips/yosys/passes/fsm/fsmdata.h @@ -0,0 +1,164 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#ifndef FSMDATA_H +#define FSMDATA_H + +#include "kernel/yosys.h" +#include "kernel/unused_bits.h" + +YOSYS_NAMESPACE_BEGIN + +struct FsmData +{ + int num_inputs, num_outputs, state_bits, reset_state; + struct transition_t { int state_in, state_out; RTLIL::Const ctrl_in, ctrl_out; }; + std::vector transition_table; + std::vector state_table; + + void copy_to_cell(RTLIL::Cell *cell) + { + cell->parameters[ID::CTRL_IN_WIDTH] = RTLIL::Const(num_inputs); + cell->parameters[ID::CTRL_OUT_WIDTH] = RTLIL::Const(num_outputs); + + int state_num_log2 = 0; + for (int i = state_table.size(); i > 0; i = i >> 1) + state_num_log2++; + state_num_log2 = max(state_num_log2, 1); + + cell->parameters[ID::STATE_BITS] = RTLIL::Const(state_bits); + cell->parameters[ID::STATE_NUM] = RTLIL::Const(state_table.size()); + cell->parameters[ID::STATE_NUM_LOG2] = RTLIL::Const(state_num_log2); + cell->parameters[ID::STATE_RST] = RTLIL::Const(reset_state); + RTLIL::Const cell_state_table; + for (const RTLIL::Const &c : state_table) + cell_state_table.append(c); + cell->parameters[ID::STATE_TABLE] = std::move(cell_state_table); + + cell->parameters[ID::TRANS_NUM] = RTLIL::Const(transition_table.size()); + RTLIL::Const cell_trans_table; + for (int i = 0; i < int(transition_table.size()); i++) + { + transition_t &tr = transition_table[i]; + + RTLIL::Const const_state_in = RTLIL::Const(tr.state_in, state_num_log2); + RTLIL::Const const_state_out = RTLIL::Const(tr.state_out, state_num_log2); + + // append lsb first + cell_trans_table.append(tr.ctrl_out); + cell_trans_table.append(const_state_out); + cell_trans_table.append(tr.ctrl_in); + cell_trans_table.append(const_state_in); + } + cell->parameters[ID::TRANS_TABLE] = std::move(cell_trans_table); + } + + void copy_from_cell(RTLIL::Cell *cell) + { + num_inputs = cell->parameters[ID::CTRL_IN_WIDTH].as_int(); + num_outputs = cell->parameters[ID::CTRL_OUT_WIDTH].as_int(); + + state_bits = cell->parameters[ID::STATE_BITS].as_int(); + reset_state = cell->parameters[ID::STATE_RST].as_int(); + + int state_num = cell->parameters[ID::STATE_NUM].as_int(); + int state_num_log2 = cell->parameters[ID::STATE_NUM_LOG2].as_int(); + int trans_num = cell->parameters[ID::TRANS_NUM].as_int(); + + if (reset_state < 0 || reset_state >= state_num) + reset_state = -1; + + const RTLIL::Const &state_table = cell->parameters[ID::STATE_TABLE]; + const RTLIL::Const &trans_table = cell->parameters[ID::TRANS_TABLE]; + + for (int i = 0; i < state_num; i++) { + int off_begin = i*state_bits; + RTLIL::Const state_code = state_table.extract(off_begin, state_bits); + this->state_table.push_back(state_code); + } + + for (int i = 0; i < trans_num; i++) + { + int base_offset = i*(num_inputs+num_outputs+2*state_num_log2); + RTLIL::Const ctrl_out = trans_table.extract(base_offset, num_outputs); + RTLIL::Const state_out = trans_table.extract(base_offset + num_outputs, state_num_log2); + RTLIL::Const ctrl_in = trans_table.extract(base_offset + num_outputs + state_num_log2, num_inputs); + RTLIL::Const state_in = trans_table.extract(base_offset + num_outputs + state_num_log2 + num_inputs, state_num_log2); + + transition_t tr; + tr.state_in = state_in.as_int(); + tr.state_out = state_out.as_int(); + tr.ctrl_in = ctrl_in; + tr.ctrl_out = ctrl_out; + + if (tr.state_in < 0 || tr.state_in >= state_num) + tr.state_in = -1; + if (tr.state_out < 0 || tr.state_out >= state_num) + tr.state_out = -1; + + transition_table.push_back(tr); + } + } + + void log_info(RTLIL::Cell *cell) + { + log("-------------------------------------\n"); + log("\n"); + log(" Information on FSM %s (%s):\n", cell->name, cell->parameters[ID::NAME].decode_string()); + log("\n"); + log(" Number of input signals: %3d\n", num_inputs); + log(" Number of output signals: %3d\n", num_outputs); + log(" Number of state bits: %3d\n", state_bits); + + log("\n"); + log(" Input signals:\n"); + RTLIL::SigSpec sig_in = cell->getPort(ID::CTRL_IN); + for (int i = 0; i < GetSize(sig_in); i++) + log(" %3d: %s\n", i, log_signal(sig_in[i])); + + log("\n"); + log(" Output signals:\n"); + RTLIL::SigSpec sig_out = cell->getPort(ID::CTRL_OUT); + for (int i = 0; i < GetSize(sig_out); i++) + log(" %3d: %s\n", i, log_signal(sig_out[i])); + + log("\n"); + log(" State encoding:\n"); + for (int i = 0; i < GetSize(state_table); i++) + log(" %3d: %10s%s\n", i, log_signal(state_table[i], false), + int(i) == reset_state ? " " : ""); + + log("\n"); + log(" Transition Table (state_in, ctrl_in, state_out, ctrl_out):\n"); + for (int i = 0; i < GetSize(transition_table); i++) { + transition_t &tr = transition_table[i]; + log(" %5d: %5d %s -> %5d %s\n", i, tr.state_in, log_signal(tr.ctrl_in), tr.state_out, log_signal(tr.ctrl_out)); + } + + log("\n"); + log("-------------------------------------\n"); + } + + // implemented in fsm_opt.cc + static void optimize_fsm(RTLIL::Cell *cell, RTLIL::Module *module, UnusedBits& unused_bits); +}; + +YOSYS_NAMESPACE_END + +#endif diff --git a/chips/yosys/passes/hierarchy/CMakeLists.txt b/chips/yosys/passes/hierarchy/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..8e4d52aa6a31c1d9b14f69b703eb2b70ead7413f --- /dev/null +++ b/chips/yosys/passes/hierarchy/CMakeLists.txt @@ -0,0 +1,22 @@ +yosys_pass(flatten + flatten.cc +) +yosys_pass(hierarchy + hierarchy.cc + LIBRARIES + verific + REQUIRES + read_rtlil + read_verilog +) +yosys_pass(keep_hierarchy + keep_hierarchy.cc +) +yosys_pass(submod + submod.cc + REQUIRES + opt_clean +) +yosys_pass(uniquify + uniquify.cc +) diff --git a/chips/yosys/passes/hierarchy/flatten.cc b/chips/yosys/passes/hierarchy/flatten.cc new file mode 100644 index 0000000000000000000000000000000000000000..cc597d6b19da9f051bec1e32a0c40f065ed20671 --- /dev/null +++ b/chips/yosys/passes/hierarchy/flatten.cc @@ -0,0 +1,532 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "kernel/utils.h" +#include "kernel/sigtools.h" +#include "kernel/ffinit.h" + +#include +#include +#include +#include + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +template +[[nodiscard]] std::string concat_views(const Args&... views) { + static_assert((std::is_convertible_v && ...), + "All arguments must be convertible to std::string_view."); + const std::size_t total_size = (std::string_view(views).size() + ... + 0); + + std::string result; + result.reserve(total_size); + + (result.append(views), ...); + return result; +} + +std::pair hier_name_parts(RTLIL::Cell *cell, std::string_view object_name_view, const std::string &separator) +{ + if (!object_name_view.empty() && object_name_view[0] == '\\') + return {cell->name.str() + separator, std::string(object_name_view.substr(1))}; + + constexpr std::string_view prefix = "$flatten"; + if (object_name_view.substr(0, prefix.size()) == prefix) + object_name_view.remove_prefix(prefix.size()); + return {"$flatten" + cell->name.str() + separator, std::string(object_name_view)}; +} + +std::string concat_name(RTLIL::Cell *cell, std::string_view object_name_view, const std::string &separator = ".") +{ + auto [prefix, tail] = hier_name_parts(cell, object_name_view, separator); + return prefix + tail; +} + +IdString remap_flattened_name(RTLIL::Design *design, IdString obj_ref, + IdString pub_prefix_ref, IdString priv_prefix_ref, const std::string &separator, dict &memo) +{ + if (auto it = memo.find(obj_ref); it != memo.end()) + return it->second; + + const TwineNode &node = design->twines()[obj_ref]; + IdString parent = design->twines().prefix_of(obj_ref); + IdString result; + if (parent != IdString::Null) { + IdString prefix = remap_flattened_name(design, parent, + pub_prefix_ref, priv_prefix_ref, separator, memo); + result = design->twines().add(TwineSpec::Suffix{prefix, std::string(node.text())}); + } else { + std::string_view obj = node.text(); + if (obj_ref.isPublic()) { + result = design->twines().add(TwineSpec::Suffix{pub_prefix_ref, separator + std::string(obj)}); + } else { + constexpr std::string_view flatten_prefix = "$flatten"; + if (obj.substr(0, flatten_prefix.size()) == flatten_prefix) + obj.remove_prefix(flatten_prefix.size()); + result = design->twines().add(TwineSpec::Suffix{priv_prefix_ref, std::string(obj)}); + } + } + memo[obj_ref] = result; + return result; +} + +void map_sigspec(const dict &map, RTLIL::SigSpec &sig, RTLIL::Module *into = nullptr) +{ + vector chunks = sig; + for (auto &chunk : chunks) + if (chunk.wire != nullptr && chunk.wire->module != into) + chunk.wire = map.at(chunk.wire); + sig = chunks; +} + +struct FlattenWorker +{ + bool ignore_wb = false; + bool create_scopeinfo = true; + bool create_scopename = false; + std::string separator = "."; + bool barriers = false; + bool added_barriers = false; + + std::string cell_hdlname; + std::string cell_scopename; + + template + void map_attributes(RTLIL::Cell *cell, T *object, IdString orig_object_name) + { + if (!create_scopeinfo && object->has_attribute(ID::src)) + object->add_strpool_attribute(ID::src, cell->get_strpool_attribute(ID::src)); + + // Preserve original names via the hdlname attribute, but only for objects with a fully public name. + // If the '-scopename' option is used, also preserve the containing scope of private objects if their scope is fully public. + if (cell->name.isPublic()) { + if (object->has_attribute(ID::hdlname) || orig_object_name.isPublic()) { + std::string new_hdlname = cell_hdlname; + new_hdlname += ' '; + + if (object->has_attribute(ID::hdlname)) { + new_hdlname += object->get_string_attribute(ID(hdlname)); + } else { + new_hdlname += cell->twines().unescaped_str(orig_object_name); + } + object->set_string_attribute(ID(hdlname), new_hdlname); + } else if (object->has_attribute(ID(scopename))) { + std::string new_scopename = cell_hdlname; + new_scopename += ' '; + new_scopename += object->get_string_attribute(ID(scopename)); + object->set_string_attribute(ID(scopename), new_scopename); + } else if (create_scopename) { + object->set_string_attribute(ID::scopename, cell_scopename); + } + } + } + + void flatten_cell(RTLIL::Design *design, RTLIL::Module *module, RTLIL::Cell *cell, RTLIL::Module *tpl, SigMap &sigmap, std::vector &new_cells, const std::string &separator, const dict &hier_wires) + { + // Copy the contents of the flattened cell + + if (cell->name.isPublic()) { + log_assert(!cell->name.empty()); + cell_hdlname = cell->has_attribute(ID::hdlname) ? cell->get_string_attribute(ID(hdlname)) : cell->name.unescape(); + cell_scopename = create_scopename ? cell->name.unescape() : std::string(); + } + + IdString pub_prefix_ref = cell->name; + IdString priv_prefix_ref = design->twines().add("$flatten" + cell->name.str() + separator); + dict remap_memo; + auto make_name = [&](IdString obj_ref) -> IdString { + return module->uniquify(remap_flattened_name(design, obj_ref, pub_prefix_ref, priv_prefix_ref, separator, remap_memo)); + }; + + dict memory_map; + for (auto &tpl_memory_it : tpl->memories) { + RTLIL::Memory *new_memory = module->addMemory(make_name(tpl_memory_it.second->name), tpl_memory_it.second); + map_attributes(cell, new_memory, tpl_memory_it.second->name); + memory_map[design->twines().str(tpl_memory_it.first)] = new_memory->name; + design->select(module, new_memory); + } + + dict wire_map; + dict positional_ports; + for (auto tpl_wire : tpl->wires()) { + if (tpl_wire->port_id > 0) + positional_ports.emplace(design->twines().add(stringf("$%d", tpl_wire->port_id)), tpl_wire->name); + + RTLIL::Wire *new_wire = nullptr; + if (tpl_wire->name.isPublic() && !hier_wires.empty()) { + std::string wire_name = concat_name(cell, tpl_wire->name.str(), separator); + auto hwit = hier_wires.find(wire_name); + RTLIL::Wire *hier_wire = (hwit != hier_wires.end()) ? hwit->second : nullptr; + 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", + module, hier_wire, tpl, tpl_wire, module, cell); + hier_wire->width = GetSize(tpl_wire); + } + new_wire = hier_wire; + } + } + if (new_wire == nullptr) { + new_wire = module->addWire(make_name(tpl_wire->name), tpl_wire); + new_wire->port_input = new_wire->port_output = false; + new_wire->port_id = false; + } + + map_attributes(cell, new_wire, tpl_wire->name); + wire_map[tpl_wire] = new_wire; + design->select(module, new_wire); + } + + for (auto &tpl_proc_it : tpl->processes) { + RTLIL::Process *new_proc = module->addProcess(make_name(tpl_proc_it.second->name), tpl_proc_it.second); + map_attributes(cell, new_proc, tpl_proc_it.second->name); + for (auto new_proc_sync : new_proc->syncs) + for (auto &memwr_action : new_proc_sync->mem_write_actions) { + memwr_action.memid = memory_map.at(design->twines().str(memwr_action.memid)); + } + auto rewriter = [&](RTLIL::SigSpec &sig) { map_sigspec(wire_map, sig); }; + new_proc->rewrite_sigspecs(rewriter); + design->select(module, new_proc); + } + + for (auto tpl_cell : tpl->cells()) { + RTLIL::Cell *new_cell = module->addCell(make_name(tpl_cell->name), tpl_cell); + map_attributes(cell, new_cell, tpl_cell->name); + if (new_cell->has_memid()) { + std::string memid = new_cell->getParam(ID::MEMID).decode_string(); + new_cell->setParam(ID::MEMID, Const(design->twines().str(memory_map.at(memid)))); + } else if (new_cell->is_mem_cell()) { + std::string memid = new_cell->getParam(ID::MEMID).decode_string(); + new_cell->setParam(ID::MEMID, Const(concat_name(cell, memid, separator))); + } + auto rewriter = [&](RTLIL::SigSpec &sig) { map_sigspec(wire_map, sig); }; + new_cell->rewrite_sigspecs(rewriter); + design->select(module, new_cell); + new_cells.push_back(new_cell); + } + + for (auto &tpl_conn_it : tpl->connections()) { + RTLIL::SigSig new_conn = tpl_conn_it; + map_sigspec(wire_map, new_conn.first); + map_sigspec(wire_map, new_conn.second); + module->connect(new_conn); + } + + // Attach port connections of the flattened cell + + pool tpl_driven; + for (auto tpl_cell : tpl->cells()) + for (auto &tpl_conn : tpl_cell->connections()) + if (tpl_cell->output(tpl_conn.first)) + for (auto bit : tpl_conn.second) + tpl_driven.insert(bit); + for (auto &tpl_conn : tpl->connections()) + for (auto bit : tpl_conn.first) + tpl_driven.insert(bit); + + 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) { + std::string port_name_str = design->twines().str(port_name); + if (!port_name_str.empty() && port_name_str[0] == '$') + log_error("Can't map port `%s' of cell `%s' to template `%s'!\n", + port_name_str, cell->name, tpl->name); + continue; + } + + if (GetSize(port_it.second) == 0) + continue; + + RTLIL::Wire *tpl_wire = tpl->wire(port_name); + RTLIL::SigSig new_conn; + bool is_signed = false; + if (tpl_wire->port_output && !tpl_wire->port_input) { + new_conn.first = port_it.second; + new_conn.second = tpl_wire; + is_signed = tpl_wire->is_signed; + } else if (!tpl_wire->port_output && tpl_wire->port_input) { + new_conn.first = tpl_wire; + new_conn.second = port_it.second; + is_signed = new_conn.second.is_wire() && new_conn.second.as_wire()->is_signed; + } else { + SigSpec sig_tpl = tpl_wire, sig_mod = port_it.second; + for (int i = 0; i < GetSize(sig_tpl) && i < GetSize(sig_mod); i++) { + if (tpl_driven.count(sig_tpl[i])) { + new_conn.first.append(sig_mod[i]); + new_conn.second.append(sig_tpl[i]); + } else { + new_conn.first.append(sig_tpl[i]); + new_conn.second.append(sig_mod[i]); + } + } + } + map_sigspec(wire_map, new_conn.first, module); + map_sigspec(wire_map, new_conn.second, module); + + if (new_conn.second.size() > new_conn.first.size()) + new_conn.second.remove(new_conn.first.size(), new_conn.second.size() - new_conn.first.size()); + if (new_conn.second.size() < new_conn.first.size()) + new_conn.second.extend_u0(new_conn.first.size(), is_signed); + 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", + module, cell, PooledName(design, port_it.first).unescape(), log_signal(new_conn.first), log_signal(new_conn.second)); + + if (barriers && !(tpl_wire->port_input && tpl_wire->port_output)) { + // Drive public output wires with barriers and the rest with + // connections + RTLIL::SigSig skip_conn, barrier_conn; + + for (int i = 0; i < GetSize(new_conn.first); i++) { + const auto lhs = new_conn.first[i], rhs = new_conn.second[i]; + log_assert(lhs.is_wire()); + auto& sigsig = !lhs.wire->name.isPublic() || lhs.wire->port_input ? skip_conn : barrier_conn; + sigsig.first.append(lhs); + sigsig.second.append(rhs); + } + + if (!skip_conn.first.empty()) + module->connect(skip_conn); + + if (!barrier_conn.first.empty()) { + module->addBarrier(NEW_ID, barrier_conn.second, barrier_conn.first); + added_barriers = true; + } + } else { + module->connect(new_conn); + } + + sigmap.add(new_conn.first, new_conn.second); + } + + RTLIL::Cell *scopeinfo = nullptr; + RTLIL::IdString cell_name = cell->name; + + if (create_scopeinfo && cell_name.isPublic()) + { + // The $scopeinfo's name will be changed below after removing the flattened cell + scopeinfo = module->addCell(NEW_ID, ID($scopeinfo)); + scopeinfo->setParam(ID::TYPE, RTLIL::Const("module")); + + for (auto const &attr : cell->attributes) + { + if (attr.first == ID::hdlname) + scopeinfo->attributes.insert(attr); + else + scopeinfo->attributes.emplace(design->twines().add(stringf("\\cell_%s", design->twines().unescaped_str(attr.first))), attr.second); + } + + for (auto const &attr : tpl->attributes) + scopeinfo->attributes.emplace(design->twines().add(stringf("\\module_%s", design->twines().unescaped_str(attr.first))), attr.second); + + scopeinfo->attributes.emplace(ID::module, RTLIL::Const(tpl->name.unescape())); + } + + module->remove(cell); + + if (scopeinfo != nullptr) + module->rename(scopeinfo, cell_name); + } + + void flatten_module(RTLIL::Design *design, RTLIL::Module *module, pool &used_modules, const std::string &separator) + { + if (!design->selected_module(module) || module->get_blackbox_attribute(ignore_wb)) + return; + + SigMap sigmap(module); + + dict hier_wires; + for (auto wire : module->wires()) + if (wire->get_bool_attribute(ID::hierconn)) + hier_wires[wire->name.str()] = wire; + + std::vector worklist = module->selected_cells(); + added_barriers = false; + while (!worklist.empty()) + { + RTLIL::Cell *cell = worklist.back(); + worklist.pop_back(); + + IdString cell_type_ref = cell->type; + if (!design->has(cell_type_ref)) + continue; + + RTLIL::Module *tpl = design->module(cell_type_ref); + if (tpl->get_blackbox_attribute(ignore_wb)) + continue; + + if (cell->get_bool_attribute(ID::keep_hierarchy) || tpl->get_bool_attribute(ID::keep_hierarchy)) { + log("Keeping %s.%s (found keep_hierarchy attribute).\n", module, cell); + used_modules.insert(tpl); + continue; + } + + log_debug("Flattening %s.%s (%s).\n", module, cell, cell->type.unescape()); + // If a design is fully selected and has a top module defined, topological sorting ensures that all cells + // added during flattening are black boxes, and flattening is finished in one pass. However, when flattening + // individual modules, this isn't the case, and the newly added cells might have to be flattened further. + flatten_cell(design, module, cell, tpl, sigmap, worklist, separator, hier_wires); + } + + if (added_barriers) { + SigMap init_sigmap(module); + FfInitVals initvals(&init_sigmap, module); + initvals.move_barrier_inits(module); + } + } +}; + +struct FlattenPass : public Pass { + FlattenPass() : Pass("flatten", "flatten design") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" flatten [options] [selection]\n"); + log("\n"); + log("This pass flattens the design by replacing cells by their implementation. This\n"); + log("pass is very similar to the 'techmap' pass. The only difference is that this\n"); + log("pass is using the current design as mapping library.\n"); + log("\n"); + log("Cells and/or modules with the 'keep_hierarchy' attribute set will not be\n"); + log("flattened by this command.\n"); + log("\n"); + log(" -wb\n"); + log(" Ignore the 'whitebox' attribute on cell implementations.\n"); + log("\n"); + log(" -noscopeinfo\n"); + log(" Do not create '$scopeinfo' cells that preserve attributes of cells and\n"); + log(" modules that were removed during flattening. With this option, the\n"); + log(" 'src' attribute of a given cell is merged into all objects replacing\n"); + log(" that cell, with multiple distinct 'src' locations separated by '|'.\n"); + log(" Without this option these 'src' locations can be found via the\n"); + log(" cell_src' and 'module_src' attribute of '$scopeinfo' cells.\n"); + log("\n"); + log(" -scopename\n"); + log(" Create 'scopename' attributes for objects with a private name. This\n"); + log(" attribute records the 'hdlname' of the enclosing scope. For objects\n"); + log(" with a public name the enclosing scope can be found via their\n"); + log(" 'hdlname' attribute.\n"); + log("\n"); + log(" -separator \n"); + log(" Use this separator char instead of '.' when concatenating design levels.\n"); + log("\n"); + log(" -nocleanup\n"); + log(" Don't remove unused submodules, leave a flattened version of each\n"); + log(" submodule in the design.\n"); + log("\n"); + log(" -barriers\n"); + log(" Introduce an optimization barrier (a $barrier cell) when a flattened\n"); + log(" module drives a public wire (experimental).\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + log_header(design, "Executing FLATTEN pass (flatten design).\n"); + log_push(); + + FlattenWorker worker; + + if (design->scratchpad.count("flatten.separator")) + worker.separator = design->scratchpad_get_string("flatten.separator"); + + bool cleanup = true; + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + if (args[argidx] == "-wb") { + worker.ignore_wb = true; + continue; + } + if (args[argidx] == "-noscopeinfo") { + worker.create_scopeinfo = false; + continue; + } + if (args[argidx] == "-scopename") { + worker.create_scopename = true; + continue; + } + if (args[argidx] == "-separator" && argidx + 1 < args.size()) { + worker.separator = args[++argidx]; + continue; + } + if (args[argidx] == "-nocleanup") { + cleanup = false; + continue; + } + if (args[argidx] == "-barriers") { + worker.barriers = true; + log_experimental("flatten -barriers"); + continue; + } + break; + } + extra_args(args, argidx, design); + + RTLIL::Module *top = nullptr; + if (design->full_selection()) + for (auto module : design->modules()) + if (module->get_bool_attribute(ID::top)) + top = module; + + pool used_modules; + if (top == nullptr) + used_modules = design->modules(); + else + used_modules.insert(top); + + TopoSort> topo_modules; + pool worklist = used_modules; + while (!worklist.empty()) { + RTLIL::Module *module = worklist.pop(); + for (auto cell : module->selected_cells()) { + RTLIL::Module *tpl = design->module(cell->type); + if (tpl != nullptr) { + if (!topo_modules.has_node(tpl)) + worklist.insert(tpl); + topo_modules.edge(tpl, module); + } + } + } + + if (!topo_modules.sort()) + log_error("Cannot flatten a design containing recursive instantiations.\n"); + + for (auto module : topo_modules.sorted) + worker.flatten_module(design, module, used_modules, worker.separator); + + if (cleanup && top != nullptr) + for (auto module : design->modules().to_vector()) + if (!used_modules[module] && !module->get_blackbox_attribute(worker.ignore_wb)) { + log("Deleting now unused module %s.\n", module); + design->remove(module); + } + + log_pop(); + } +} FlattenPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/hierarchy/hierarchy.cc b/chips/yosys/passes/hierarchy/hierarchy.cc new file mode 100644 index 0000000000000000000000000000000000000000..5fa344c6ed44af697d5ebd3e918aa28e17fc7a04 --- /dev/null +++ b/chips/yosys/passes/hierarchy/hierarchy.cc @@ -0,0 +1,1610 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * Copyright (C) 2018 Ruben Undheim + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "kernel/celltypes.h" +#include "frontends/verific/verific.h" +#include "frontends/ast/ast.h" +#include +#include +#include + +#ifndef _WIN32 +# include +#endif + + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct generate_port_decl_t { + bool input, output; + string portname; + int index; +}; + +void generate(RTLIL::Design *design, const std::vector &celltypes, const std::vector &portdecls) +{ + std::set found_celltypes; + + for (auto mod : design->modules()) + for (auto cell : mod->cells()) + { + if (design->module(cell->type) != nullptr) + continue; + if (cell->type.begins_with("$") && !cell->type.begins_with("$__")) + continue; + for (auto &pattern : celltypes) + if (patmatch(pattern.c_str(), cell->type.unescape().c_str())) + found_celltypes.insert(cell->type); + } + + for (auto &celltype : found_celltypes) + { + std::set portnames; + std::set parameters; + std::map portwidths; + log("Generate module for cell type %s:\n", design->twines().str(celltype)); + + for (auto mod : design->modules()) + for (auto cell : mod->cells()) + if (cell->type == celltype) { + for (auto &conn : cell->connections()) { + std::string port_name = design->twines().str(conn.first); + if (!port_name.empty() && port_name[0] != '$') + portnames.insert(std::string(port_name)); + portwidths[std::string(port_name)] = max(portwidths[std::string(port_name)], conn.second.size()); + } + for (auto ¶ : cell->parameters) + parameters.insert(para.first); + } + + for (auto &decl : portdecls) + if (decl.index > 0) + portnames.insert(decl.portname); + + std::set indices; + for (int i = 0; i < int(portnames.size()); i++) + indices.insert(i+1); + + std::vector ports(portnames.size()); + + for (auto &decl : portdecls) + if (decl.index > 0) { + portwidths[decl.portname] = max(portwidths[decl.portname], 1); + portwidths[decl.portname] = max(portwidths[decl.portname], portwidths[stringf("$%d", decl.index)]); + log(" port %d: %s [%d:0] %s\n", decl.index, decl.input ? decl.output ? "inout" : "input" : "output", portwidths[decl.portname]-1, RTLIL::unescape_id(decl.portname)); + if (indices.count(decl.index) > ports.size()) + log_error("Port index (%d) exceeds number of found ports (%d).\n", decl.index, int(ports.size())); + if (indices.count(decl.index) == 0) + log_error("Conflict on port index %d.\n", decl.index); + indices.erase(decl.index); + portnames.erase(decl.portname); + ports[decl.index-1] = decl; + } + + while (portnames.size() > 0) { + std::string portname = *portnames.begin(); + for (auto &decl : portdecls) + if (decl.index == 0 && patmatch(decl.portname.c_str(), RTLIL::unescape_id(portname).c_str())) { + generate_port_decl_t d = decl; + d.portname = portname; + d.index = *indices.begin(); + log_assert(!indices.empty()); + indices.erase(d.index); + ports[d.index-1] = d; + portwidths[d.portname] = max(portwidths[d.portname], 1); + log(" port %d: %s [%d:0] %s\n", d.index, d.input ? d.output ? "inout" : "input" : "output", portwidths[d.portname]-1, RTLIL::unescape_id(d.portname)); + goto found_matching_decl; + } + log_error("Can't match port %s.\n", RTLIL::unescape_id(portname)); + found_matching_decl:; + portnames.erase(portname); + } + + log_assert(indices.empty()); + + RTLIL::Module *mod = design->addModule(celltype); + mod->attributes[ID::blackbox] = RTLIL::Const(1); + + for (auto &decl : ports) { + RTLIL::Wire *wire = mod->addWire(decl.portname, portwidths.at(decl.portname)); + wire->port_id = decl.index; + wire->port_input = decl.input; + wire->port_output = decl.output; + } + + mod->fixup_ports(); + + for (auto ¶ : parameters) + log(" ignoring parameter %s.\n", PooledName(design, para).unescape()); + + log(" module %s created.\n", mod); + } +} + +// Return the "basic" type for an array item. +std::string basic_cell_type(const std::string celltype, int pos[3] = nullptr) { + std::string basicType = celltype; + if (celltype.compare(0, strlen("$array:"), "$array:") == 0) { + int pos_idx = celltype.find_first_of(':'); + int pos_num = celltype.find_first_of(':', pos_idx + 1); + int pos_type = celltype.find_first_of(':', pos_num + 1); + basicType = celltype.substr(pos_type + 1); + if (pos != nullptr) { + pos[0] = pos_idx; + pos[1] = pos_num; + pos[2] = pos_type; + } + } + return basicType; +} + +// Try to read a IdString as a numbered connection name ("$123" or similar), +// writing the result to dst. If the string isn't of the right format, ignore +// dst and return false. +bool read_id_num(RTLIL::Design &design, IdString ref, int *dst) +{ + log_assert(dst); + + std::string sv = design.twines().str(ref); + if (sv.empty() || sv[0] != '$' || !('0' <= sv[1] && sv[1] <= '9')) + return false; + + *dst = atoi(std::string(sv).c_str() + 1); + return true; +} + +// A helper struct for expanding a module's interface connections in expand_module +struct IFExpander +{ + IFExpander (RTLIL::Design &design, RTLIL::Module &m) + : design(design), module(m), has_interfaces_not_found(false) + { + // Keep track of all derived interfaces available in the current + // module in 'interfaces_in_module': + for (auto cell : module.cells()) { + if(!cell->get_bool_attribute(ID::is_interface)) + continue; + + interfaces_in_module[cell->name] = design.module(cell->type); + } + } + + RTLIL::Design &design; + RTLIL::Module &module; + dict interfaces_in_module; + + bool has_interfaces_not_found; + std::vector connections_to_remove; + std::vector connections_to_add; + std::vector connections_to_add_signal; + dict interfaces_to_add_to_submodule; + dict modports_used_in_submodule; + + // Reset the per-cell state + void start_cell() + { + has_interfaces_not_found = false; + connections_to_remove.clear(); + connections_to_add.clear(); + connections_to_add_signal.clear(); + interfaces_to_add_to_submodule.clear(); + modports_used_in_submodule.clear(); + } + + // Set has_interfaces_not_found if there are pending interfaces that + // haven't been found yet (and might be found in the future). Print a + // warning if we've already gone over all the cells in the module. + void on_missing_interface(RTLIL::IdString interface_name) + { + // If there are cells that haven't yet been processed, maybe + // we'll find this interface in the future. + if (module.get_bool_attribute(ID::cells_not_processed)) { + has_interfaces_not_found = true; + return; + } + + // Otherwise, we have already gone over all cells in this + // module and the interface has still not been found. Warn + // about it and don't set has_interfaces_not_found (to avoid a + // loop). + log_warning("Could not find interface instance for `%s' in `%s'\n", + PooledName(module.design, interface_name).unescape(), &module); + } + + // Handle an interface connection from the module + void on_interface(RTLIL::Module &submodule, + RTLIL::IdString conn_name, + const RTLIL::SigSpec &conn_signals) + { + // Check if the connected wire is a potential interface in the parent module + std::string interface_name_str = conn_signals[0].wire->name.str(); + // Strip the prefix '$dummywireforinterface' from the dummy wire to get the name + interface_name_str.replace(0,23,""); + interface_name_str = "\\" + interface_name_str; + IdString interface_name = design.twines().add(interface_name_str); + + // If 'interfaces' in the cell have not be been handled yet, we aren't + // ready to derive the sub-module either + if (!module.get_bool_attribute(ID::interfaces_replaced_in_module)) { + on_missing_interface(interface_name); + return; + } + + // Check if the interface instance is present in module. Interface + // instances may either have the plain name or the name appended with + // '_inst_from_top_dummy'. Check for both of them here + int nexactmatch = interfaces_in_module.count(interface_name) > 0; + std::string interface_name_str2 = interface_name_str + "_inst_from_top_dummy"; + IdString interface_name2 = design.twines().add(interface_name_str2); + int nmatch2 = interfaces_in_module.count(interface_name2) > 0; + + // If we can't find either name, this is a missing interface. + if (! (nexactmatch || nmatch2)) { + on_missing_interface(interface_name); + return; + } + + if (nexactmatch != 0) // Choose the one with the plain name if it exists + interface_name2 = interface_name; + + RTLIL::Module *mod_replace_ports = interfaces_in_module.at(interface_name2); + + // Go over all wires in interface, and add replacements to lists. + std::string conn_name_str(design.twines().str(conn_name)); + for (auto mod_wire : mod_replace_ports->wires()) { + std::string member = mod_wire->name.unescape(); + std::string signal_name1 = conn_name_str + "." + member; + std::string signal_name2 = interface_name_str + "." + member; + connections_to_add.push_back(AST::intern_hier_name(&design, signal_name1)); + IdString signal_name2_ref = AST::intern_hier_name(&design, signal_name2); + if(module.wire(signal_name2_ref) == nullptr) { + log_error("Could not find signal '%s' in '%s'\n", + signal_name2, module.name.unescape()); + } + else { + RTLIL::Wire *wire_in_parent = module.wire(signal_name2_ref); + connections_to_add_signal.push_back(wire_in_parent); + } + } + connections_to_remove.push_back(conn_name); + interfaces_to_add_to_submodule[conn_name] = interfaces_in_module.at(interface_name2); + + // Find if the sub-module has set a modport for the current interface + // connection. Add any modports to a dict which will be passed to + // AstModule::derive + string modport_name = submodule.wire(conn_name)->get_string_attribute(ID::interface_modport); + if (!modport_name.empty()) { + modports_used_in_submodule[conn_name] = design.twines().add("\\" + modport_name); + } + } + + // Handle a single connection from the module, making a note to expand + // it if it's an interface connection. + void on_connection(RTLIL::Module &submodule, + RTLIL::IdString conn_name, + const RTLIL::SigSpec &conn_signals) + { + // Does the connection look like an interface + if ( + conn_signals.size() != 1 || + conn_signals[0].wire == nullptr || + conn_signals[0].wire->get_bool_attribute(ID::is_interface) == false || + conn_signals[0].wire->name.str().find("$dummywireforinterface") != 0 + ) + return; + + // Check if the connection is present as an interface in the sub-module's port list + int id; + if (read_id_num(design, conn_name, &id)) { + /* Interface expansion is incompatible with positional arguments + * during expansion, the port list gets each interface signal + * inserted after the interface itself which means that the argument + * positions in the parent module no longer match. + * + * Supporting this would require expanding the interfaces in the + * parent module, renumbering the arguments to match, and then + * iterating over the ports list to find the matching interface + * (refactoring on_interface to accept different conn_names on the + * parent and child). + */ + log_error("Unable to connect `%s' to submodule `%s' with positional interface argument `%s'!\n", + module.name, + submodule.name, + conn_signals[0].wire->name.str().substr(23) + ); + } else { + // Lookup connection by name + const RTLIL::Wire *wire = submodule.wire(conn_name); + if (!wire || !wire->get_bool_attribute(ID::is_interface)) + return; + } + // If the connection looks like an interface, handle it. + on_interface(submodule, conn_name, conn_signals); + } + + // Iterate over the connections in a cell, tracking any interface + // connections + void visit_connections(const RTLIL::Cell &cell, + RTLIL::Module &submodule) + { + for (const auto &conn : cell.connections()) { + on_connection(submodule, conn.first, conn.second); + } + } + + // Add/remove connections to the cell as necessary, replacing any SV + // interface port connection with the individual signal connections. + void rewrite_interface_connections(RTLIL::Cell &cell) const + { + for(unsigned int i=0;i &libdirs) +{ + std::string cell_type = cell.type.str(); + RTLIL::Module *abs_mod = design.module("$abstract" + cell_type); + if (abs_mod) { + cell.type = abs_mod->derive(&design, cell.parameters); + cell.parameters.clear(); + RTLIL::Module *mod = design.module(cell.type); + log_assert(mod); + return mod; + } + + // Internal cell types have no module to load. With check set they + // must at least be known cell types. + if (cell_type[0] == '$') { + if (check && !yosys_celltypes.cell_known(cell.type)) + log_error("Cell type `%s' referenced in module `%s' in cell `%s' is neither a known internal cell type nor part of the design.\n", + cell_type, parent.name, cell.name); + return nullptr; + } + + for (auto &dir : libdirs) { + static const vector> extensions_list = + { + {".v", "verilog"}, + {".sv", "verilog -sv"}, + {".il", "rtlil"} + }; + + for (auto &ext : extensions_list) { + std::string filename = dir + "/" + cell.type.unescape() + ext.first; + if (!check_file_exists(filename)) + continue; + + Frontend::frontend_call(&design, NULL, filename, ext.second); + RTLIL::Module *mod = design.module(cell.type); + if (!mod) + log_error("File `%s' from libdir does not declare module `%s'.\n", + filename, cell_type); + return mod; + } + } + + // We couldn't find the module anywhere. Complain if check is set. + if (check) + log_error("Module `%s' referenced in module `%s' in cell `%s' is not part of the design.\n", + cell_type, parent.name.str().data(), cell.name); + + return nullptr; +} + +// Check that the connections on the cell match those that are defined +// on the type: each named connection should match the name of a port +// and each positional connection should have an index smaller than +// the number of ports. +// +// Also do the same checks on the specified parameters. +void check_cell_connections(const RTLIL::Module &module, RTLIL::Cell &cell, RTLIL::Module &mod) +{ + int id; + for (auto &conn : cell.connections()) { + if (read_id_num(*module.design, conn.first, &id)) { + if (id <= 0 || id > GetSize(mod.ports)) + log_error("Module `%s' referenced in module `%s' in cell `%s' " + "has only %d ports, requested port %d.\n", + cell.type.unescape(), &module, &cell, + GetSize(mod.ports), id); + continue; + } + + const RTLIL::Wire* wire = mod.wire(conn.first); + if (!wire || wire->port_id == 0) { + log_error("Module `%s' referenced in module `%s' in cell `%s' " + "does not have a port named '%s'.\n", + cell.type.unescape(), &module, &cell, + PooledName(module.design, conn.first).unescape()); + } + } + for (auto ¶m : cell.parameters) { + if (read_id_num(*module.design, param.first, &id)) { + if (id <= 0 || id > GetSize(mod.avail_parameters)) + log_error("Module `%s' referenced in module `%s' in cell `%s' " + "has only %d parameters, requested parameter %d.\n", + cell.type.unescape(), &module, &cell, + GetSize(mod.avail_parameters), id); + continue; + } + + std::string param_name = module.twines().str(param.first); + if (mod.avail_parameters.count(param.first) == 0 && + param_name[0] != '$' && + param_name.find('.') == std::string::npos) { + log_error("Module `%s' referenced in module `%s' in cell `%s' " + "does not have a parameter named '%s'.\n", + cell.type.unescape(), &module, &cell, + RTLIL::unescape_id(param_name)); + } + } +} + +bool expand_module(RTLIL::Design *design, RTLIL::Module *module, bool flag_check, bool flag_simcheck, bool flag_smtcheck, + std::vector &libdirs) +{ + bool did_something = false; + std::map> array_cells; + std::string filename; + + bool has_interface_ports = false; + + // If any of the ports are actually interface ports, we will always need to + // reprocess the module: + if(!module->get_bool_attribute(ID::interfaces_replaced_in_module)) { + for (auto wire : module->wires()) { + if ((wire->port_input || wire->port_output) && wire->get_bool_attribute(ID::is_interface)) + has_interface_ports = true; + } + } + + IFExpander if_expander(*design, *module); + + for (auto cell : module->cells()) + { + if_expander.start_cell(); + + if (cell->type.begins_with("$array:")) { + int pos[3]; + basic_cell_type(cell->type.str(), pos); + int pos_idx = pos[0]; + int pos_num = pos[1]; + int pos_type = pos[2]; + int idx = atoi(cell->type.substr(pos_idx + 1, pos_num).c_str()); + int num = atoi(cell->type.substr(pos_num + 1, pos_type).c_str()); + array_cells[cell] = std::pair(idx, num); + cell->type = cell->twines().add(cell->type.str().substr(pos_type + 1)); + } + + dict interfaces_by_name; + dict modports_by_name; + + RTLIL::Module *mod = design->module(cell->type); + if (!mod) + { + mod = get_module(*design, *cell, *module, flag_check || flag_simcheck || flag_smtcheck, libdirs); + + // If we still don't have a module, treat the cell as a black box and skip + // it. Otherwise, we either loaded or derived something so should set the + // did_something flag before returning (to ensure we come back and expand + // the thing we just loaded). + if (mod) + did_something = true; + + continue; + } + + log_assert(mod); + + // Go over all connections and check if any of them are SV + // interfaces. + if_expander.visit_connections(*cell, *mod); + + if (flag_check || flag_simcheck || flag_smtcheck) + check_cell_connections(*module, *cell, *mod); + + if (mod->get_blackbox_attribute()) { + if (flag_simcheck || (flag_smtcheck && !mod->get_bool_attribute(ID::smtlib2_module))) + log_error("Module `%s' referenced in module `%s' in cell `%s' is a blackbox/whitebox module.\n", + cell->type, module->name.str().data(), cell->name); + + // Parametric blackboxes labeled reprocess_after need to be derived + // just so we have correct widths. The instance still points to the + // parametric module and the derived module is discarded via to_delete + if (!cell->parameters.empty() && cell->has_attribute(ID::reprocess_after) && + !design->module(design->twines().find(cell->get_string_attribute(ID::reprocess_after)))) { + size_t num_modules = design->modules_.size(); + IdString derived = mod->derive(design, cell->parameters, true); + if (!derived.empty() && design->modules_.size() > num_modules) + design->module(derived)->set_bool_attribute(ID::to_delete); + } + continue; + } + + // If interface instances not yet found, skip cell for now, and say we did something, so that we will return back here: + if(if_expander.has_interfaces_not_found) { + did_something = true; // waiting for interfaces to be handled + continue; + } + + if_expander.rewrite_interface_connections(*cell); + + // If there are no overridden parameters AND not interfaces, then we can use the existing module instance as the type + // for the cell: + if (cell->parameters.size() == 0 && + (if_expander.interfaces_to_add_to_submodule.size() == 0 || + !(cell->get_bool_attribute(ID::module_not_derived)))) { + // If the cell being processed is an the interface instance itself, go down to "handle_interface_instance:", + // so that the signals of the interface are added to the parent module. + if (mod->get_bool_attribute(ID::is_interface)) { + goto handle_interface_instance; + } + continue; + } + + for (auto &p : if_expander.interfaces_to_add_to_submodule) + interfaces_by_name[p.first] = p.second; + for (auto &p : if_expander.modports_used_in_submodule) + modports_by_name[p.first] = p.second; + cell->type = mod->derive(design, + cell->parameters, + interfaces_by_name, + modports_by_name); + cell->parameters.clear(); + did_something = true; + + handle_interface_instance: + + // We add all the signals of the interface explicitly to the parent module. This is always needed when we encounter + // an interface instance: + if (mod->get_bool_attribute(ID::is_interface) && cell->get_bool_attribute(ID::module_not_derived)) { + cell->set_bool_attribute(ID::is_interface); + RTLIL::Module *derived_module = design->module(cell->type); + if_expander.interfaces_in_module[cell->name] = derived_module; + did_something = true; + } + // We clear 'module_not_derived' such that we will not rederive the cell again (needed when there are interfaces connected to the cell) + cell->attributes.erase(ID::module_not_derived); + } + // Clear the attribute 'cells_not_processed' such that it can be known that we + // have been through all cells at least once, and that we can know whether + // to flag an error because of interface instances not found: + module->attributes.erase(ID::cells_not_processed); + + + // If any interface instances or interface ports were found in the module, we need to rederive it completely: + if ((if_expander.interfaces_in_module.size() > 0 || has_interface_ports) && !module->get_bool_attribute(ID::interfaces_replaced_in_module)) { + module->expand_interfaces(design, if_expander.interfaces_in_module); + return did_something; + } + + // Now that modules have been derived, we may want to reprocess this + // module given the additional available context. + if (module->reprocess_if_necessary(design)) + return true; + + for (auto &it : array_cells) + { + RTLIL::Cell *cell = it.first; + int idx = it.second.first, num = it.second.second; + + if (design->module(cell->type) == nullptr) + log_error("Array cell `%s.%s' of unknown type `%s'.\n", module, cell, cell->type.unescape()); + + RTLIL::Module *mod = design->module(cell->type); + + for (auto &conn : cell->connections_) { + int conn_size = conn.second.size(); + IdString portname = conn.first; + std::string portname_str = module->twines().str(conn.first); + if (portname_str.empty() || portname_str[0] != '$') { + } else { + int port_id = atoi(portname_str.substr(1).data()); + for (auto wire : mod->wires()) + if (wire->port_id == port_id) { + portname = wire->name; + break; + } + } + if (mod->wire(portname) == nullptr) + log_error("Array cell `%s.%s' connects to unknown port `%s'.\n", module, cell, PooledName(module, conn.first).unescape()); + int port_size = mod->wire(portname)->width; + if (conn_size == port_size || conn_size == 0) + continue; + if (conn_size != port_size*num) + log_error("Array cell `%s.%s' has invalid port vs. signal size for port `%s'.\n", module, cell, PooledName(module, conn.first).unescape()); + conn.second = conn.second.extract(port_size*idx, port_size); + } + } + + return did_something; +} + +using ModuleSet = std::set>; + +void hierarchy_worker(RTLIL::Design *design, ModuleSet &used, RTLIL::Module *mod, int indent) +{ + if (used.count(mod) > 0) + return; + + if (indent == 0) + log("Top module: %s\n", mod->name); + else if (!mod->get_blackbox_attribute()) + log("Used module: %*s%s\n", indent, "", mod->name); + used.insert(mod); + + for (auto cell : mod->cells()) { + RTLIL::Module *cm; + if (cell->type.begins_with("$array:")) + cm = design->module(basic_cell_type(cell->type.str())); + else + cm = design->module(cell->type); + if (cm) + hierarchy_worker(design, used, cm, indent+4); + } +} + +void hierarchy_clean(RTLIL::Design *design, RTLIL::Module *top, bool purge_lib) +{ + ModuleSet used; + hierarchy_worker(design, used, top, 0); + + std::vector del_modules; + for (auto mod : design->modules()) + if (used.count(mod) == 0) + del_modules.push_back(mod); + else { + // Now all interface ports must have been exploded, and it is hence + // safe to delete all of the remaining dummy interface ports: + pool del_wires; + for(auto wire : mod->wires()) { + if ((wire->port_input || wire->port_output) && wire->get_bool_attribute(ID::is_interface)) { + del_wires.insert(wire); + } + } + if (del_wires.size() > 0) { + mod->remove(del_wires); + mod->fixup_ports(); + } + } + + int del_counter = 0; + for (auto mod : del_modules) { + if (!purge_lib && mod->get_blackbox_attribute()) + continue; + log("Removing unused module `%s'.\n", mod->name); + design->remove(mod); + del_counter++; + } + + log("Removed %d unused modules.\n", del_counter); +} + +bool set_keep_print(std::map &cache, RTLIL::Module *mod) +{ + if (cache.count(mod) == 0) { + cache[mod] = false; + for (auto c : mod->cells()) { + if (mod->name == c->type) + continue; + RTLIL::Module *m = mod->design->module(c->type); + if ((m != nullptr && set_keep_print(cache, m)) || c->type == ID($print)) { + cache[mod] = true; + break; + } + } + } + return cache[mod]; +} + +bool set_keep_assert(std::map &cache, RTLIL::Module *mod) +{ + if (cache.count(mod) == 0) { + cache[mod] = false; + for (auto c : mod->cells()) { + if (mod->name == c->type) + continue; + RTLIL::Module *m = mod->design->module(c->type); + if ((m != nullptr && set_keep_assert(cache, m)) || c->type.in(ID($check), ID($assert), ID($assume), ID($live), ID($fair), ID($cover))) { + cache[mod] = true; + break; + } + } + } + return cache[mod]; +} + +int find_top_mod_score(Design *design, Module *module, dict &db) +{ + if (db.count(module) == 0) { + int score = 0; + db[module] = 0; + for (auto cell : module->cells()) { + // Is this cell a module instance? + RTLIL::Module *instModule; + if (cell->type.begins_with("$array:")) { + std::string type = basic_cell_type(cell->type.str()); + instModule = design->module(type); + } + else + instModule = design->module(cell->type); + // If there is no instance for this, issue a warning. + if (instModule != nullptr) { + score = max(score, find_top_mod_score(design, instModule, db) + 1); + } + } + db[module] = score; + } + return db.at(module); +} + +RTLIL::Module *check_if_top_has_changed(Design *design, Module *top_mod) +{ + if(top_mod != NULL && top_mod->get_bool_attribute(ID::initial_top)) + return top_mod; + else { + for (auto mod : design->modules()) { + if (mod->get_bool_attribute(ID::top)) { + return mod; + } + } + } + return NULL; +} + +// Find a matching wire for an implicit port connection; traversing generate block scope +RTLIL::Wire *find_implicit_port_wire(Module *module, Cell *cell, const std::string& port) +{ + const std::string &cellname = cell->name.str(); + size_t idx = cellname.size(); + while ((idx = cellname.find_last_of('.', idx-1)) != std::string::npos) { + std::string wire_name = cellname.substr(0, idx+1) + port.substr(1); + IdString ref = module->twines().find(wire_name); + if (ref != IdString::Null) { + Wire *found = module->wire(ref); + if (found != nullptr) + return found; + } + } + IdString ref = module->twines().find(port); + if (ref != IdString::Null) + return module->wire(ref); + return nullptr; +} + +struct HierarchyPass : public Pass { + HierarchyPass() : Pass("hierarchy", "check, expand and clean up design hierarchy") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" hierarchy [-check] [-top ]\n"); + log(" hierarchy -generate \n"); + log("\n"); + log("In parametric designs, a module might exists in several variations with\n"); + log("different parameter values. This pass looks at all modules in the current\n"); + log("design and re-runs the language frontends for the parametric modules as\n"); + log("needed. It also resolves assignments to wired logic data types (wand/wor),\n"); + log("resolves positional module parameters, unrolls array instances, and more.\n"); + log("\n"); + log(" -check\n"); + log(" also check the design hierarchy. this generates an error when\n"); + log(" an unknown module is used as cell type.\n"); + log("\n"); + log(" -simcheck\n"); + log(" like -check, but also throw an error if blackbox modules are\n"); + log(" instantiated, and throw an error if the design has no top module.\n"); + log("\n"); + log(" -smtcheck\n"); + log(" like -simcheck, but allow smtlib2_module modules.\n"); + log("\n"); + log(" -purge_lib\n"); + log(" by default the hierarchy command will not remove library (blackbox)\n"); + log(" modules. use this option to also remove unused blackbox modules.\n"); + log("\n"); + log(" -libdir \n"); + log(" search for files named .v in the specified directory\n"); + log(" for unknown modules and automatically run read_verilog for each\n"); + log(" unknown module.\n"); + log("\n"); + log(" -keep_positionals\n"); + log(" per default this pass also converts positional arguments in cells\n"); + log(" to arguments using port names. This option disables this behavior.\n"); + log("\n"); + log(" -keep_portwidths\n"); + log(" per default this pass adjusts the port width on cells that are\n"); + log(" module instances when the width does not match the module port. This\n"); + log(" option disables this behavior.\n"); + log("\n"); + log(" -nodefaults\n"); + log(" do not resolve input port default values\n"); + log("\n"); + log(" -nokeep_prints\n"); + log(" per default this pass sets the \"keep\" attribute on all modules\n"); + log(" that directly or indirectly display text on the terminal.\n"); + log(" This option disables this behavior.\n"); + log("\n"); + log(" -nokeep_asserts\n"); + log(" per default this pass sets the \"keep\" attribute on all modules\n"); + log(" that directly or indirectly contain one or more formal properties.\n"); + log(" This option disables this behavior.\n"); + log("\n"); + log(" -top \n"); + log(" use the specified top module to build the design hierarchy. Modules\n"); + log(" outside this tree (unused modules) are removed.\n"); + log("\n"); + log(" when the -top option is used, the 'top' attribute will be set on the\n"); + log(" specified top module. otherwise a module with the 'top' attribute set\n"); + log(" will implicitly be used as top module, if such a module exists.\n"); + log("\n"); + log(" -auto-top\n"); + log(" automatically determine the top of the design hierarchy and mark it.\n"); + log("\n"); + log(" -chparam name value \n"); + log(" elaborate the top module using this parameter value. Modules on which\n"); + log(" this parameter does not exist may cause a warning message to be output.\n"); + log(" This option can be specified multiple times to override multiple\n"); + log(" parameters. String values must be passed in double quotes (\").\n"); + log("\n"); + log("In -generate mode this pass generates blackbox modules for the given cell\n"); + log("types (wildcards supported). For this the design is searched for cells that\n"); + log("match the given types and then the given port declarations are used to\n"); + log("determine the direction of the ports. The syntax for a port declaration is:\n"); + log("\n"); + log(" {i|o|io}[@]:\n"); + log("\n"); + log("Input ports are specified with the 'i' prefix, output ports with the 'o'\n"); + log("prefix and inout ports with the 'io' prefix. The optional specifies\n"); + log("the position of the port in the parameter list (needed when instantiated\n"); + log("using positional arguments). When is not specified, the can\n"); + log("also contain wildcard characters.\n"); + log("\n"); + log("This pass ignores the current selection and always operates on all modules\n"); + log("in the current design.\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + log_header(design, "Executing HIERARCHY pass (managing design hierarchy).\n"); + + bool flag_check = false; + bool flag_simcheck = false; + bool flag_smtcheck = false; + bool purge_lib = false; + RTLIL::Module *top_mod = NULL; + std::string load_top_mod; + std::vector libdirs; + + bool auto_top_mode = false; + bool generate_mode = false; + bool keep_positionals = false; + bool keep_portwidths = false; + bool nodefaults = false; + bool nokeep_prints = false; + bool nokeep_asserts = false; + std::vector generate_cells; + std::vector generate_ports; + std::map parameters; + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) + { + if (args[argidx] == "-generate" && !flag_check && !flag_simcheck && !flag_smtcheck && !top_mod) { + generate_mode = true; + log("Entering generate mode.\n"); + std::string message; + while (++argidx < args.size()) { + const char *p = args[argidx].c_str(); + generate_port_decl_t decl; + if (p[0] == 'i' && p[1] == 'o') + decl.input = true, decl.output = true, p += 2; + else if (*p == 'i') + decl.input = true, decl.output = false, p++; + else if (*p == 'o') + decl.input = false, decl.output = true, p++; + else + goto is_celltype; + if (*p == '@') { + char *endptr; + decl.index = strtol(++p, &endptr, 10); + if (decl.index < 1) + goto is_celltype; + p = endptr; + } else + decl.index = 0; + if (*(p++) != ':') + goto is_celltype; + if (*p == 0) + goto is_celltype; + decl.portname = p; + message = stringf("Port declaration: %s", decl.input ? decl.output ? "inout" : "input" : "output"); + if (decl.index >= 1) + message += stringf(" [at position %d]", decl.index); + log("%s %s\n", message, decl.portname); + generate_ports.push_back(decl); + continue; + is_celltype: + log("Celltype: %s\n", args[argidx]); + generate_cells.push_back(RTLIL::unescape_id(args[argidx])); + } + continue; + } + if (args[argidx] == "-check") { + flag_check = true; + continue; + } + if (args[argidx] == "-simcheck") { + flag_simcheck = true; + continue; + } + if (args[argidx] == "-smtcheck") { + flag_smtcheck = true; + continue; + } + if (args[argidx] == "-purge_lib") { + purge_lib = true; + continue; + } + if (args[argidx] == "-keep_positionals") { + keep_positionals = true; + continue; + } + if (args[argidx] == "-keep_portwidths") { + keep_portwidths = true; + continue; + } + if (args[argidx] == "-nodefaults") { + nodefaults = true; + continue; + } + if (args[argidx] == "-nokeep_prints") { + nokeep_prints = true; + continue; + } + if (args[argidx] == "-nokeep_asserts") { + nokeep_asserts = true; + continue; + } + if (args[argidx] == "-libdir" && argidx+1 < args.size()) { + libdirs.push_back(args[++argidx]); + continue; + } + if (args[argidx] == "-top") { + if (++argidx >= args.size()) + log_cmd_error("Option -top requires an additional argument!\n"); + load_top_mod = args[argidx]; + continue; + } + if (args[argidx] == "-auto-top") { + auto_top_mode = true; + continue; + } + if (args[argidx] == "-chparam" && argidx+2 < args.size()) { + const std::string &key = args[++argidx]; + const std::string &value = args[++argidx]; + auto r = parameters.emplace(key, value); + if (!r.second) { + log_warning("-chparam %s already specified: overwriting.\n", key); + r.first->second = value; + } + continue; + } + break; + } + extra_args(args, argidx, design, false); + + if (!load_top_mod.empty()) + { + IdString top_name = design->twines().add(RTLIL::escape_id(load_top_mod)); + IdString abstract_id = design->twines().add("$abstract" + RTLIL::escape_id(load_top_mod)); + top_mod = design->module(top_name); + RTLIL::Module *abstract_mod = design->module(abstract_id); + + dict top_parameters; + if ((top_mod == nullptr && abstract_mod) || top_mod != nullptr) { + for (auto ¶ : parameters) { + SigSpec sig_value; + if (!RTLIL::SigSpec::parse(sig_value, NULL, para.second)) + log_cmd_error("Can't decode value '%s'!\n", para.second); + RTLIL::Const c = sig_value.as_const(); + c.tag_bare_integer_const(para.second); + top_parameters[design->twines().add(RTLIL::escape_id(para.first))] = c; + } + } + + if (top_mod == nullptr && abstract_mod) + top_mod = design->module(abstract_mod->derive(design, top_parameters)); + else if (top_mod != nullptr && !top_parameters.empty()) + top_mod = design->module(top_mod->derive(design, top_parameters)); + + IdString top_name_ref = top_name; + if (top_mod != nullptr && top_mod->name != top_name_ref) { + Module *m = top_mod->clone(); + m->name = top_name_ref; + Module *old_mod = design->module(top_name_ref); + if (old_mod) + design->remove(old_mod); + design->add(m); + top_mod = m; + } + } + + bool verific_mod = false; +#ifdef YOSYS_ENABLE_VERIFIC + if (auto verific_session = VerificSession::deferred_end(design)) { + verific_mod = verific_import_pending; + if (verific_mod) { + if (top_mod == nullptr && !load_top_mod.empty()) { + load_top_mod = verific_import(design, parameters, load_top_mod); + top_mod = design->module(RTLIL::escape_id(load_top_mod)); + } else { + verific_import(design, parameters); + } + } + } +#endif + + if (top_mod == nullptr && !load_top_mod.empty()) + log_cmd_error("Module `%s' not found!\n", load_top_mod); + + if (generate_mode) { + generate(design, generate_cells, generate_ports); + return; + } + + log_push(); + + if (top_mod == nullptr) + for (auto mod : design->modules()) + if (mod->get_bool_attribute(ID::top)) { + log("Attribute `top' found on module `%s'. Setting top module to %s.\n", mod, mod); + top_mod = mod; + } + + if (top_mod == nullptr) + { + std::vector abstract_ids; + for (auto module : design->modules()) + if (module->name.begins_with("$abstract")) + abstract_ids.push_back(module->name); + for (auto abstract_id : abstract_ids) + design->module(abstract_id)->derive(design, {}); + for (auto abstract_id : abstract_ids) + design->remove(design->module(abstract_id)); + } + + if (top_mod == nullptr && auto_top_mode) { + log_header(design, "Finding top of design hierarchy..\n"); + dict db; + for (Module *mod : design->selected_modules()) { + int score = find_top_mod_score(design, mod, db); + log("root of %3d design levels: %-20s\n", score, mod); + if (!top_mod || score > db[top_mod]) + top_mod = mod; + } + if (top_mod != nullptr) + log("Automatically selected %s as design top module.\n", top_mod); + } + + if (top_mod != nullptr && top_mod->name.begins_with("$abstract")) { + IdString top_name = design->twines().add(top_mod->name.str().substr(strlen("$abstract"))); + + dict top_parameters; + for (auto ¶ : parameters) { + SigSpec sig_value; + if (!RTLIL::SigSpec::parse(sig_value, NULL, para.second)) + log_cmd_error("Can't decode value '%s'!\n", para.second); + RTLIL::Const c = sig_value.as_const(); + c.tag_bare_integer_const(para.second); + top_parameters[design->twines().add(RTLIL::escape_id(para.first))] = c; + } + + top_mod = design->module(top_mod->derive(design, top_parameters)); + + IdString top_name_ref = top_name; + if (top_mod != nullptr && top_mod->name != top_name_ref) { + Module *m = top_mod->clone(); + m->name = top_name_ref; + Module *old_mod = design->module(top_name_ref); + if (old_mod) + design->remove(old_mod); + design->add(m); + top_mod = m; + } + } + + if ((flag_simcheck || flag_smtcheck) && top_mod == nullptr) + log_error("Design has no top module.\n"); + + if (top_mod != NULL) { + for (auto mod : design->modules()) + if (mod == top_mod) + mod->attributes[ID::initial_top] = RTLIL::Const(1); + else + mod->attributes.erase(ID::initial_top); + } + + bool did_something = true; + while (did_something) + { + did_something = false; + + ModuleSet used_modules; + if (top_mod != NULL) { + log_header(design, "Analyzing design hierarchy..\n"); + hierarchy_worker(design, used_modules, top_mod, 0); + } else { + for (auto mod : design->modules()) + used_modules.insert(mod); + } + + for (auto module : used_modules) { + if (expand_module(design, module, flag_check, flag_simcheck, flag_smtcheck, libdirs)) + did_something = true; + } + + + // The top module might have changed if interface instances have been detected in it: + RTLIL::Module *tmp_top_mod = check_if_top_has_changed(design, top_mod); + if (tmp_top_mod != NULL) { + if (tmp_top_mod != top_mod){ + top_mod = tmp_top_mod; + top_mod->attributes[ID::initial_top] = RTLIL::Const(1); + did_something = true; + } + } + + // Delete modules marked as 'to_delete': + std::vector modules_to_delete; + for(auto mod : design->modules()) { + if (mod->get_bool_attribute(ID::to_delete)) { + modules_to_delete.push_back(mod); + } + } + for(size_t i=0; iremove(modules_to_delete[i]); + } + } + + + if (top_mod != NULL) { + log_header(design, "Analyzing design hierarchy..\n"); + hierarchy_clean(design, top_mod, purge_lib); + } + + if (top_mod != NULL) { + for (auto mod : design->modules()) { + if (mod == top_mod) + mod->attributes[ID::top] = RTLIL::Const(1); + else + mod->attributes.erase(ID::top); + mod->attributes.erase(ID::initial_top); + } + } + + if (!nokeep_prints) { + std::map cache; + for (auto mod : design->modules()) + if (set_keep_print(cache, mod)) { + log("Module %s directly or indirectly displays text -> setting \"keep\" attribute.\n", mod); + mod->set_bool_attribute(ID::keep); + } + } + + if (!nokeep_asserts) { + std::map cache; + for (auto mod : design->modules()) + if (set_keep_assert(cache, mod)) { + log("Module %s directly or indirectly contains formal properties -> setting \"keep\" attribute.\n", mod); + mod->set_bool_attribute(ID::keep); + } + } + + if (flag_simcheck || flag_smtcheck) { + for (auto mod : design->modules()) { + for (auto cell : mod->cells()) { + if (!cell->type.in(ID($check), ID($assert), ID($assume), ID($live), ID($fair), ID($cover))) + continue; + if (!cell->has_attribute(ID(unsupported_sva))) + continue; + + auto src = cell->get_src_attribute(); + + if (!src.empty()) + src += ": "; + + log_error("%sProperty `%s' in module `%s' uses unsupported SVA constructs. See frontend warnings for details, run `chformal -remove a:unsupported_sva' to ignore.\n", + src, cell->name.unescape(), mod->name.unescape()); + } + } + } + + if (!keep_positionals) + { + std::set pos_mods; + std::map, RTLIL::IdString> pos_map; + std::vector> pos_work; + + for (auto mod : design->modules()) + for (auto cell : mod->cells()) { + RTLIL::Module *cell_mod = design->module(cell->type); + if (cell_mod == nullptr) + continue; + for (auto &conn : cell->connections()) { + std::string conn_name = design->twines().str(conn.first); + if (!conn_name.empty() && conn_name[0] == '$' && '0' <= conn_name[1] && conn_name[1] <= '9') { + pos_mods.insert(design->module(cell->type)); + pos_work.push_back(std::pair(mod, cell)); + break; + } + } + + pool> params_rename; + for (const auto &p : cell->parameters) { + int id; + if (read_id_num(*design, p.first, &id)) { + if (id <= 0 || id > GetSize(cell_mod->avail_parameters)) { + log(" Failed to map positional parameter %d of cell %s.%s (%s).\n", + id, mod, cell, cell->type.unescape()); + } else { + params_rename.insert(std::make_pair(p.first, cell_mod->avail_parameters[id - 1])); + } + } + } + for (const auto &p : params_rename) { + cell->setParam(p.second, cell->getParam(p.first)); + cell->unsetParam(p.first); + } + } + + for (auto module : pos_mods) + for (auto wire : module->wires()) { + if (wire->port_id > 0) + pos_map[std::pair(module, wire->port_id)] = IdString(wire->name); + } + + for (auto &work : pos_work) { + RTLIL::Module *module = work.first; + RTLIL::Cell *cell = work.second; + log("Mapping positional arguments of cell %s.%s (%s).\n", + module, cell, cell->type.unescape()); + dict new_connections_twine; + for (auto &conn : cell->connections()) { + int id; + if (read_id_num(*design, conn.first, &id)) { + std::pair key(design->module(cell->type), id); + if (pos_map.count(key) == 0) { + log(" Failed to map positional argument %d of cell %s.%s (%s).\n", + id, module, cell, cell->type.unescape()); + new_connections_twine[conn.first] = conn.second; + } else + new_connections_twine[pos_map.at(key)] = conn.second; + } else + new_connections_twine[conn.first] = conn.second; + } + cell->connections_ = new_connections_twine; + } + } + + // Determine default values + dict> defaults_db; + if (!nodefaults) + { + for (auto module : design->modules()) + for (auto wire : module->wires()) + if (wire->port_input && wire->attributes.count(ID::defaultvalue)) + defaults_db[module->name][wire->name] = wire->attributes.at(ID::defaultvalue); + } + // Process SV implicit wildcard port connections + ModuleSet blackbox_derivatives; + std::vector design_modules = design->modules(); + for (auto module : design_modules) + { + for (auto cell : module->cells()) + { + if (!cell->get_bool_attribute(ID::wildcard_port_conns)) + continue; + Module *m = design->module(cell->type); + + if (m == nullptr) + log_error("Cell %s.%s (%s) has implicit port connections but the module it instantiates is unknown.\n", + module, cell, cell->type.unescape()); + + // Need accurate port widths for error checking; so must derive blackboxes with dynamic port widths + if (m->get_blackbox_attribute() && !cell->parameters.empty() && m->get_bool_attribute(ID::dynports)) { + IdString new_m_ref = m->derive(design, cell->parameters, true); + if (new_m_ref == IdString{}) + continue; + if (new_m_ref != m->name) { + m = design->module(new_m_ref); + blackbox_derivatives.insert(m); + } + } + + auto old_connections = cell->connections(); + for (auto wire : m->wires()) { + // Find ports of the module that aren't explicitly connected + if (!wire->port_input && !wire->port_output) + continue; + if (old_connections.count(wire->name)) + continue; + // Make sure a wire of correct name exists in the parent + Wire* parent_wire = find_implicit_port_wire(module, cell, wire->name.str()); + + // Missing wires are OK when a default value is set + if (!nodefaults && parent_wire == nullptr && defaults_db.count(cell->type) && defaults_db.at(cell->type).count(wire->name)) + continue; + + if (parent_wire == nullptr) + log_error("No matching wire for implicit port connection `%s' of cell %s.%s (%s).\n", + wire, module, cell, cell->type.unescape()); + if (parent_wire->width != wire->width) + log_error("Width mismatch between wire (%d bits) and port (%d bits) for implicit port connection `%s' of cell %s.%s (%s).\n", + parent_wire->width, wire->width, + wire, module, cell, cell->type.unescape()); + cell->setPort(wire->name, parent_wire); + } + cell->attributes.erase(ID::wildcard_port_conns); + } + } + + if (!nodefaults) + { + for (auto module : design->modules()) + for (auto cell : module->cells()) + { + if (defaults_db.count(cell->type) == 0) + continue; + + if (keep_positionals) { + bool found_positionals = false; + for (auto &conn : cell->connections()) { + std::string conn_name = design->twines().str(conn.first); + if (!conn_name.empty() && conn_name[0] == '$' && '0' <= conn_name[1] && conn_name[1] <= '9') + found_positionals = true; + } + if (found_positionals) + continue; + } + + for (auto &it : defaults_db.at(cell->type)) { + IdString port_ref = it.first; + if (!cell->hasPort(port_ref)) + cell->setPort(port_ref, it.second); + } + } + } + + for (auto module : design_modules) + { + pool wand_wor_index; + dict wand_map, wor_map; + vector new_connections; + + for (auto wire : module->wires()) + { + if (wire->get_bool_attribute(ID::wand)) { + wand_map[wire] = SigSpec(); + wand_wor_index.insert(wire); + } + if (wire->get_bool_attribute(ID::wor)) { + wor_map[wire] = SigSpec(); + wand_wor_index.insert(wire); + } + } + + for (auto &conn : module->connections()) + { + SigSig new_conn; + int cursor = 0; + + for (auto c : conn.first.chunks()) + { + Wire *w = c.wire; + SigSpec rhs = conn.second.extract(cursor, GetSize(c)); + + if (wand_wor_index.count(w) == 0) { + new_conn.first.append(c); + new_conn.second.append(rhs); + } else { + if (wand_map.count(w)) { + SigSpec sig = SigSpec(State::S1, GetSize(w)); + sig.replace(c.offset, rhs); + wand_map.at(w).append(sig); + } else { + SigSpec sig = SigSpec(State::S0, GetSize(w)); + sig.replace(c.offset, rhs); + wor_map.at(w).append(sig); + } + } + cursor += GetSize(c); + } + new_connections.push_back(new_conn); + } + module->new_connections(new_connections); + + for (auto cell : module->cells()) + { + if (!cell->known()) + continue; + + for (auto &conn : cell->connections()) + { + if (!cell->output(conn.first)) + continue; + + SigSpec new_sig; + bool update_port = false; + + for (auto c : conn.second.chunks()) + { + Wire *w = c.wire; + + if (wand_wor_index.count(w) == 0) { + new_sig.append(c); + continue; + } + + Wire *t = module->addWire(NEW_ID, GetSize(c)); + new_sig.append(t); + update_port = true; + + if (wand_map.count(w)) { + SigSpec sig = SigSpec(State::S1, GetSize(w)); + sig.replace(c.offset, t); + wand_map.at(w).append(sig); + } else { + SigSpec sig = SigSpec(State::S0, GetSize(w)); + sig.replace(c.offset, t); + wor_map.at(w).append(sig); + } + } + + if (update_port) + cell->setPort(conn.first, new_sig); + } + } + + for (auto w : wand_wor_index) + { + bool wand = wand_map.count(w); + SigSpec sigs = wand ? wand_map.at(w) : wor_map.at(w); + + if (GetSize(sigs) == 0) + continue; + + if (GetSize(w) == 1) { + if (wand) + module->addReduceAnd(NEW_ID, sigs, w); + else + module->addReduceOr(NEW_ID, sigs, w); + continue; + } + + SigSpec s = sigs.extract(0, GetSize(w)); + for (int i = GetSize(w); i < GetSize(sigs); i += GetSize(w)) { + if (wand) + s = module->And(NEW_ID, s, sigs.extract(i, GetSize(w))); + else + s = module->Or(NEW_ID, s, sigs.extract(i, GetSize(w))); + } + module->connect(w, s); + } + + for (auto cell : module->cells()) + { + Module *m = design->module(cell->type); + + if (m == nullptr) + continue; + + bool boxed_params = false; + if (m->get_blackbox_attribute() && !cell->parameters.empty()) { + if (m->get_bool_attribute(ID::dynports)) { + IdString new_m_ref = m->derive(design, cell->parameters, true); + if (new_m_ref == IdString{}) + continue; + if (new_m_ref != m->name) { + m = design->module(new_m_ref); + blackbox_derivatives.insert(m); + } + } else { + boxed_params = true; + } + } + + for (auto &conn : cell->connections()) + { + Wire *w = m->wire(conn.first); + + if (w == nullptr || w->port_id == 0) + continue; + + if (GetSize(conn.second) == 0) + continue; + + SigSpec sig = conn.second; + + bool resize_widths = !keep_portwidths && GetSize(w) != GetSize(conn.second); + if (resize_widths && verific_mod && boxed_params) + log_debug("Ignoring width mismatch on %s.%s.%s from verific, is port width parametrizable?\n", + module, cell, PooledName(design, conn.first).unescape() + ); + else if (resize_widths) { + if (GetSize(w) < GetSize(conn.second)) + { + int n = GetSize(conn.second) - GetSize(w); + if (!w->port_input && w->port_output) + { + RTLIL::SigSpec out = sig.extract(0, GetSize(w)); + out.extend_u0(GetSize(sig), w->is_signed); + module->connect(sig.extract(GetSize(w), n), out.extract(GetSize(w), n)); + } + sig.remove(GetSize(w), n); + } + else + { + int n = GetSize(w) - GetSize(conn.second); + if (w->port_input && !w->port_output) + sig.extend_u0(GetSize(w), sig.is_wire() && sig.as_wire()->is_signed); + else + sig.append(module->addWire(NEW_ID, n)); + } + + if (!conn.second.is_fully_const() || !w->port_input || w->port_output) + log_warning("Resizing cell port %s.%s.%s from %d bits to %d bits.\n", module, cell, + PooledName(design, conn.first).unescape(), GetSize(conn.second), GetSize(sig)); + cell->setPort(conn.first, sig); + } + + if (w->port_output && !w->port_input && sig.has_const()) + log_error("Output port %s.%s.%s (%s) is connected to constants: %s\n", + module, cell, PooledName(design, conn.first).unescape(), cell->type.unescape(), log_signal(sig)); + } + } + } + + for (auto module : blackbox_derivatives) + design->remove(module); + + log_pop(); + } +} HierarchyPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/hierarchy/keep_hierarchy.cc b/chips/yosys/passes/hierarchy/keep_hierarchy.cc new file mode 100644 index 0000000000000000000000000000000000000000..aa3ac72e3ae0ba077e6f909b7fa152ea43d60fba --- /dev/null +++ b/chips/yosys/passes/hierarchy/keep_hierarchy.cc @@ -0,0 +1,134 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include +#include "kernel/yosys.h" +#include "kernel/cost.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct ThresholdHierarchyKeeping { + Design *design; + CellCosts costs; + dict done; + pool in_progress; + uint64_t threshold; + + ThresholdHierarchyKeeping(Design *design, uint64_t threshold) + : design(design), costs(design), threshold(threshold) {} + + uint64_t visit(RTLIL::Module *module) { + if (module->has_attribute(ID(gate_cost_equivalent))) + return module->attributes[ID(gate_cost_equivalent)].as_int(); + + if (module->has_attribute(ID(keep_hierarchy))) + return 0; + + if (module->get_blackbox_attribute()) + log_error("Missing cost information on instanced blackbox %s\n", module); + + if (done.count(module)) + return done.at(module); + + if (in_progress.count(module)) + log_error("Circular hierarchy\n"); + in_progress.insert(module); + + uint64_t size = 0; + module->has_processes_warn(); + + for (auto cell : module->cells()) { + if (!cell->type.isPublic()) { + size += costs.get(cell); + } else { + RTLIL::Module *submodule = design->module(cell->type); + if (!submodule) + log_error("Hierarchy contains unknown module '%s' (instanced as %s in %s)\n", + cell->type.unescape(), cell, module); + size += visit(submodule); + } + } + + if (size > threshold) { + log("Keeping %s (estimated size above threshold: %" PRIu64 " > %" PRIu64 ").\n", module, size, threshold); + module->set_bool_attribute(ID::keep_hierarchy); + size = 0; + } + + in_progress.erase(module); + done[module] = size; + return size; + } +}; + +struct KeepHierarchyPass : public Pass { + KeepHierarchyPass() : Pass("keep_hierarchy", "selectively add the keep_hierarchy attribute") {} + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" keep_hierarchy [options] [selection]\n"); + log("\n"); + log("Add the keep_hierarchy attribute.\n"); + log("\n"); + log(" -min_cost \n"); + log(" only add the attribute to modules estimated to have more than \n"); + log(" gates after simple techmapping. Intended for tuning trade-offs between\n"); + log(" quality and yosys runtime.\n"); + log("\n"); + log(" When evaluating a module's cost, gates which are within a submodule\n"); + log(" which is marked with the keep_hierarchy attribute are not counted\n"); + log(" towards the upper module's cost. This applies to both when the attribute\n"); + log(" was added by this command or was pre-existing.\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + unsigned int min_cost = 0; + + log_header(design, "Executing KEEP_HIERARCHY pass.\n"); + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + if (args[argidx] == "-min_cost" && argidx+1 < args.size()) { + min_cost = std::stoi(args[++argidx].c_str()); + continue; + } + break; + } + extra_args(args, argidx, design); + + if (min_cost) { + RTLIL::Module *top = design->top_module(); + if (!top) + log_cmd_error("'-min_cost' mode requires a single top module in the design\n"); + + ThresholdHierarchyKeeping worker(design, min_cost); + worker.visit(top); + } else { + for (auto module : design->selected_modules()) { + log("Marking %s.\n", module); + module->set_bool_attribute(ID::keep_hierarchy); + } + } + } +} KeepHierarchyPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/hierarchy/submod.cc b/chips/yosys/passes/hierarchy/submod.cc new file mode 100644 index 0000000000000000000000000000000000000000..2c0b4408d3075a570b5cf2002027330004db1d30 --- /dev/null +++ b/chips/yosys/passes/hierarchy/submod.cc @@ -0,0 +1,430 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/register.h" +#include "kernel/celltypes.h" +#include "kernel/log.h" +#include "kernel/sigtools.h" +#include +#include +#include + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct SubmodWorker +{ + CellTypes ct; + RTLIL::Design *design; + RTLIL::Module *module; + SigMap sigmap; + + bool copy_mode; + bool hidden_mode; + std::string opt_name; + + struct SubModule + { + std::string name, full_name; + pool cells; + }; + + std::map submodules; + + struct wire_flags_t { + RTLIL::Wire *new_wire; + RTLIL::Const is_int_driven; + bool is_int_used, is_ext_driven, is_ext_used; + wire_flags_t(RTLIL::Wire* wire) : new_wire(nullptr), is_int_driven(State::S0, GetSize(wire)), is_int_used(false), is_ext_driven(false), is_ext_used(false) { } + }; + dict wire_flags; + bool flag_found_something; + + void flag_wire(RTLIL::Wire *wire, bool create, bool set_int_used, bool set_ext_driven, bool set_ext_used) + { + if (wire_flags.count(wire) == 0) { + if (!create) + return; + wire_flags.emplace(wire, wire); + } + if (set_int_used) + wire_flags.at(wire).is_int_used = true; + if (set_ext_driven) + wire_flags.at(wire).is_ext_driven = true; + if (set_ext_used) + wire_flags.at(wire).is_ext_used = true; + flag_found_something = true; + } + + void flag_signal(const RTLIL::SigSpec &sig, bool create, bool set_int_driven, bool set_int_used, bool set_ext_driven, bool set_ext_used) + { + for (auto &c : sig.chunks()) + if (c.wire != nullptr) { + flag_wire(c.wire, create, set_int_used, set_ext_driven, set_ext_used); + if (set_int_driven) + for (int i = c.offset; i < c.offset+c.width; i++) { + wire_flags.at(c.wire).is_int_driven.set(i, State::S1); + flag_found_something = true; + } + } + } + + void handle_submodule(SubModule &submod) + { + log("Creating submodule %s (%s) of module %s.\n", submod.name, submod.full_name, module->name); + + wire_flags.clear(); + for (RTLIL::Cell *cell : submod.cells) { + if (ct.cell_known(cell->type)) { + for (auto &conn : cell->connections()) + flag_signal(conn.second, true, ct.cell_output(cell->type, conn.first), ct.cell_input(cell->type, conn.first), false, false); + } else { + log_warning("Port directions for cell %s (%s) are unknown. Assuming inout for all ports.\n", cell->name, cell->type); + for (auto &conn : cell->connections()) + flag_signal(conn.second, true, true, true, false, false); + } + } + for (auto cell : module->cells()) { + if (submod.cells.count(cell) > 0) + continue; + if (ct.cell_known(cell->type)) { + for (auto &conn : cell->connections()) + flag_signal(conn.second, false, false, false, ct.cell_output(cell->type, conn.first), ct.cell_input(cell->type, conn.first)); + } else { + flag_found_something = false; + for (auto &conn : cell->connections()) + flag_signal(conn.second, false, false, false, true, true); + if (flag_found_something) + log_warning("Port directions for cell %s (%s) are unknown. Assuming inout for all ports.\n", cell->name, cell->type); + } + } + + RTLIL::Module *new_mod = design->addModule(submod.full_name); + int auto_name_counter = 1; + + std::set all_wire_names; + for (auto &it : wire_flags) { + all_wire_names.insert(it.first->name); + } + + for (auto &it : wire_flags) + { + RTLIL::Wire *wire = it.first; + wire_flags_t &flags = it.second; + + if (wire->port_input) + flags.is_ext_driven = true; + if (wire->port_output) + flags.is_ext_used = true; + else { + auto sig = sigmap(wire); + for (auto c : sig.chunks()) + if (c.wire && c.wire->port_output) { + flags.is_ext_used = true; + break; + } + } + + bool new_wire_port_input = false; + bool new_wire_port_output = false; + + if (!flags.is_int_driven.is_fully_zero() && flags.is_ext_used) + new_wire_port_output = true; + if (flags.is_ext_driven && flags.is_int_used) + new_wire_port_input = true; + + if (!flags.is_int_driven.is_fully_zero() && flags.is_ext_driven) + new_wire_port_input = true, new_wire_port_output = true; + + std::string new_wire_name; + if (new_wire_port_input || new_wire_port_output) { + if (!wire->name.isPublic()) + while (1) { + std::string next_wire_name = stringf("%s\\n%d", hidden_mode ? "$submod" : "", auto_name_counter++); + if (all_wire_names.count(next_wire_name) == 0) { + all_wire_names.insert(next_wire_name); + new_wire_name = next_wire_name; + break; + } + } + else if (hidden_mode) + new_wire_name = stringf("$submod%s", wire->name.str()); + } + + IdString new_wire_ref = new_wire_name.empty() ? IdString(wire->name) : IdString(design->twines().add(new_wire_name)); + RTLIL::Wire *new_wire = new_mod->addWire(new_wire_ref, wire->width); + new_wire->port_input = new_wire_port_input; + new_wire->port_output = new_wire_port_output; + new_wire->start_offset = wire->start_offset; + new_wire->attributes = wire->attributes; + if (!flags.is_int_driven.is_fully_zero()) { + new_wire->attributes.erase(ID::init); + auto sig = sigmap(wire); + for (int i = 0; i < GetSize(sig); i++) { + if (flags.is_int_driven[i] == State::S0) + continue; + if (!sig[i].wire) + continue; + auto it = sig[i].wire->attributes.find(ID::init); + if (it != sig[i].wire->attributes.end()) { + auto jt = new_wire->attributes.insert(std::make_pair(ID::init, Const(State::Sx, GetSize(sig)))).first; + jt->second.set(i, it->second[sig[i].offset]); + it->second.set(sig[i].offset, State::Sx); + } + } + } + + if (new_wire->port_input && new_wire->port_output) + log(" signal %s: inout %s\n", wire->name, new_wire->name); + else if (new_wire->port_input) + log(" signal %s: input %s\n", wire->name, new_wire->name); + else if (new_wire->port_output) + log(" signal %s: output %s\n", wire->name, new_wire->name); + else + log(" signal %s: internal\n", wire->name); + + flags.new_wire = new_wire; + } + + new_mod->fixup_ports(); + ct.setup_module(new_mod); + + for (RTLIL::Cell *cell : submod.cells) { + RTLIL::Cell *new_cell = new_mod->addCell(cell->name, cell); + for (auto &conn : new_cell->connections_) + for (auto &bit : conn.second) + if (bit.wire != nullptr) { + log_assert(wire_flags.count(bit.wire) > 0); + bit.wire = wire_flags.at(bit.wire).new_wire; + } + log(" cell %s (%s)\n", new_cell->name, new_cell->type); + if (!copy_mode) + module->remove(cell); + } + submod.cells.clear(); + + if (!copy_mode) { + IdString submod_type = design->twines().add(submod.full_name); + RTLIL::Cell *new_cell = module->addCell(submod.full_name, submod_type); + for (auto &it : wire_flags) + { + RTLIL::SigSpec old_sig = sigmap(it.first); + RTLIL::Wire *new_wire = it.second.new_wire; + if (new_wire->port_id > 0) { + if (new_wire->port_output) + for (int i = 0; i < GetSize(old_sig); i++) { + auto &b = old_sig[i]; + // Prevents "ERROR: Mismatch in directionality ..." when flattening + if (!b.wire) + b = module->addWire(NEW_ID); + // Prevents "Warning: multiple conflicting drivers ..." + else if (!it.second.is_int_driven[i]) + b = module->addWire(NEW_ID); + } + new_cell->setPort(new_wire->name, old_sig); + } + } + } + } + + SubmodWorker(RTLIL::Design *design, RTLIL::Module *module, bool copy_mode = false, bool hidden_mode = false, std::string opt_name = std::string()) : + design(design), module(module), sigmap(module), copy_mode(copy_mode), hidden_mode(hidden_mode), opt_name(opt_name) + { + if (!module->is_selected_whole() && opt_name.empty()) + return; + + if (module->processes.size() > 0) { + log("Skipping module %s as it contains processes (run 'proc' pass first).\n", module->name); + return; + } + + if (module->memories.size() > 0) { + log("Skipping module %s as it contains memories (run 'memory' pass first).\n", module->name); + return; + } + + ct.setup_internals(); + ct.setup_internals_anyinit(); + ct.setup_internals_mem(); + ct.setup_stdcells(); + ct.setup_stdcells_mem(); + ct.setup_design(design); + + for (auto port : module->ports) { + auto wire = module->wire(port); + if (wire->port_output) + sigmap.add(wire); + } + + if (opt_name.empty()) + { + for (auto wire : module->wires()) + wire->attributes.erase(ID::submod); + + for (auto cell : module->cells()) + { + if (cell->attributes.count(ID::submod) == 0 || cell->attributes[ID::submod].size() == 0) { + cell->attributes.erase(ID::submod); + continue; + } + + std::string submod_str = cell->attributes[ID::submod].decode_string(); + cell->attributes.erase(ID::submod); + + if (submodules.count(submod_str) == 0) { + submodules[submod_str].name = submod_str; + std::string module_name_str(module->name.str()); + submodules[submod_str].full_name = module_name_str + "_" + submod_str; + while (design->module(design->twines().add(submodules[submod_str].full_name)) != nullptr || + module->count_id(design->twines().add(submodules[submod_str].full_name)) != 0) + submodules[submod_str].full_name += "_"; + } + + submodules[submod_str].cells.insert(cell); + } + } + else + { + for (auto cell : module->cells()) + { + if (!design->selected(module, cell)) + continue; + submodules[opt_name].name = opt_name; + submodules[opt_name].full_name = RTLIL::escape_id(opt_name); + submodules[opt_name].cells.insert(cell); + } + + if (submodules.size() == 0) + log("Nothing selected -> do nothing.\n"); + } + + for (auto &it : submodules) + handle_submodule(it.second); + } +}; + +struct SubmodPass : public Pass { + SubmodPass() : Pass("submod", "moving part of a module to a new submodule") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" submod [options] [selection]\n"); + log("\n"); + log("This pass identifies all cells with the 'submod' attribute and moves them to\n"); + log("a newly created module. The value of the attribute is used as name for the\n"); + log("cell that replaces the group of cells with the same attribute value.\n"); + log("\n"); + log("This pass can be used to create a design hierarchy in flat design. This can\n"); + log("be useful for analyzing or reverse-engineering a design.\n"); + log("\n"); + log("This pass only operates on completely selected modules with no processes\n"); + log("or memories.\n"); + log("\n"); + log(" -copy\n"); + log(" by default the cells are 'moved' from the source module and the source\n"); + log(" module will use an instance of the new module after this command is\n"); + log(" finished. call with -copy to not modify the source module.\n"); + log("\n"); + log(" -name \n"); + log(" don't use the 'submod' attribute but instead use the selection. only\n"); + log(" objects from one module might be selected. the value of the -name option\n"); + log(" is used as the value of the 'submod' attribute instead.\n"); + log("\n"); + log(" -hidden\n"); + log(" instead of creating submodule ports with public names, create ports with\n"); + log(" private names so that a subsequent 'flatten; clean' call will restore\n"); + log(" the original module with original public names.\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + log_header(design, "Executing SUBMOD pass (moving cells to submodules as requested).\n"); + log_push(); + + std::string opt_name; + bool copy_mode = false; + bool hidden_mode = false; + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + if (args[argidx] == "-name" && argidx+1 < args.size()) { + opt_name = args[++argidx]; + continue; + } + if (args[argidx] == "-copy") { + copy_mode = true; + continue; + } + if (args[argidx] == "-hidden") { + hidden_mode = true; + continue; + } + break; + } + extra_args(args, argidx, design); + + if (opt_name.empty()) + { + Pass::call(design, "opt_clean"); + log_header(design, "Continuing SUBMOD pass.\n"); + + std::set handled_modules; + + bool did_something = true; + while (did_something) { + did_something = false; + std::vector queued_modules; + for (auto mod : design->modules()) { + IdString mod_name = mod->name; + if (handled_modules.count(mod_name) == 0 && design->selected_whole_module(mod)) + queued_modules.push_back(mod_name); + } + for (auto &modname : queued_modules) + if (design->module(modname) != nullptr) { + SubmodWorker worker(design, design->module(modname), copy_mode, hidden_mode); + handled_modules.insert(modname); + did_something = true; + } + } + + Pass::call(design, "opt_clean"); + } + else + { + RTLIL::Module *module = nullptr; + for (auto mod : design->selected_modules()) { + if (module != nullptr) + log_cmd_error("More than one module selected: %s %s\n", module->name, mod->name); + module = mod; + } + if (module == nullptr) + log("Nothing selected -> do nothing.\n"); + else { + Pass::call_on_module(design, module, "opt_clean"); + log_header(design, "Continuing SUBMOD pass.\n"); + SubmodWorker worker(design, module, copy_mode, hidden_mode, opt_name); + } + } + + log_pop(); + } +} SubmodPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/hierarchy/uniquify.cc b/chips/yosys/passes/hierarchy/uniquify.cc new file mode 100644 index 0000000000000000000000000000000000000000..c32c04e814ba8160f40a60b2d5597c8cc3d596f0 --- /dev/null +++ b/chips/yosys/passes/hierarchy/uniquify.cc @@ -0,0 +1,107 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct UniquifyPass : public Pass { + UniquifyPass() : Pass("uniquify", "create unique copies of modules") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" uniquify [selection]\n"); + log("\n"); + log("By default, a module that is instantiated by several other modules is only\n"); + log("kept once in the design. This preserves the original modularity of the design\n"); + log("and reduces the overall size of the design in memory. But it prevents certain\n"); + log("optimizations and other operations on the design. This pass creates unique\n"); + log("modules for all selected cells. The created modules are marked with the\n"); + log("'unique' attribute.\n"); + log("\n"); + log("This commands only operates on modules that by themself have the 'unique'\n"); + log("attribute set (the 'top' module is unique implicitly).\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + log_header(design, "Executing UNIQUIFY pass (creating unique copies of modules).\n"); + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) + { + // if (args[argidx] == "-check") { + // flag_check = true; + // continue; + // } + break; + } + extra_args(args, argidx, design); + + bool did_something = true; + int count = 0; + + while (did_something) + { + did_something = false; + + for (auto module : design->selected_modules()) + { + if (!module->get_bool_attribute(ID::unique) && !module->get_bool_attribute(ID::top)) + continue; + + for (auto cell : module->selected_cells()) + { + Module *tmod = design->module(cell->type); + + if (tmod == nullptr) + continue; + + std::string newname = module->name.str() + "." + cell->name.unescape(); + + if (tmod->get_blackbox_attribute()) + continue; + + IdString newname_ref = design->twines().add(newname); + if (tmod->get_bool_attribute(ID::unique) && newname_ref == tmod->name) + continue; + + log("Creating module %s from %s.\n", RTLIL::unescape_id(newname), tmod); + + auto smod = tmod->clone(); + smod->name = newname_ref; + cell->type = newname_ref; + smod->set_bool_attribute(ID::unique); + if (smod->attributes.count(ID::hdlname) == 0) + smod->attributes[ID::hdlname] = RTLIL::Const(tmod->name.unescape()); + design->add(smod); + + did_something = true; + count++; + } + } + } + + log("Created %d unique modules.\n", count); + } +} UniquifyPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/memory/CMakeLists.txt b/chips/yosys/passes/memory/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..9dd6805dba2e59be43785bab9dae1eccee994350 --- /dev/null +++ b/chips/yosys/passes/memory/CMakeLists.txt @@ -0,0 +1,59 @@ +yosys_core(memlib + memlib.cc + memlib.h +) + +function(yosys_memory_pass) + yosys_pass(${ARGV} REQUIRES memlib) +endfunction() + +yosys_memory_pass(memory_dff + memory_dff.cc +) +yosys_memory_pass(memory_share + memory_share.cc +) +yosys_memory_pass(memory_collect + memory_collect.cc +) +yosys_memory_pass(memory_unpack + memory_unpack.cc +) +yosys_memory_pass(memory_bram + memory_bram.cc +) +yosys_memory_pass(memory_map + memory_map.cc +) +yosys_memory_pass(memory_memx + memory_memx.cc +) +yosys_memory_pass(memory_nordff + memory_nordff.cc +) +yosys_memory_pass(memory_narrow + memory_narrow.cc +) +yosys_memory_pass(memory_libmap + memory_libmap.cc +) +yosys_memory_pass(memory_bmux2rom + memory_bmux2rom.cc +) + +yosys_pass(memory + memory.cc + REQUIRES + memory_bmux2rom + memory_bram + memory_collect + memory_dff + memory_map + memory_memx + memory_share + opt_clean + opt_mem + opt_mem_feedback + opt_mem_priority + opt_mem_widen +) diff --git a/chips/yosys/passes/memory/memlib.cc b/chips/yosys/passes/memory/memlib.cc new file mode 100644 index 0000000000000000000000000000000000000000..b7963258b877528ca3b46367c0b86da5134e82a1 --- /dev/null +++ b/chips/yosys/passes/memory/memlib.cc @@ -0,0 +1,1103 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2021 Marcelina Kościelnicka + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "memlib.h" + +#include + +USING_YOSYS_NAMESPACE + +using namespace MemLibrary; + +PRIVATE_NAMESPACE_BEGIN + +typedef dict Options; + +struct ClockDef { + ClkPolKind kind; + std::string name; +}; + +struct RawWrTransDef { + WrTransTargetKind target_kind; + std::string target_group; + WrTransKind kind; +}; + +struct PortWidthDef { + bool tied; + std::vector wr_widths; + std::vector rd_widths; +}; + +struct SrstDef { + ResetValKind val; + SrstKind kind; + bool block_wr; +}; + +struct Empty {}; + +template struct Capability { + T val; + Options opts, portopts; + + Capability(T val, Options opts, Options portopts) : val(val), opts(opts), portopts(portopts) {} +}; + +template using Caps = std::vector>; + +struct PortGroupDef { + PortKind kind; + dict> portopts; + std::vector names; + Caps forbid; + Caps clock; + Caps clken; + Caps wrbe_separate; + Caps width; + Caps rden; + Caps rdwr; + Caps rdinit; + Caps rdarst; + Caps rdsrst; + Caps wrprio; + Caps wrtrans; + Caps optional; + Caps optional_rw; +}; + +struct WidthsDef { + std::vector widths; + WidthMode mode; +}; + +struct ResourceDef { + std::string name; + int count; +}; + +struct RamDef { + std::string id; + dict> opts; + RamKind kind; + Caps forbid; + Caps prune_rom; + Caps ports; + Caps abits; + Caps widths; + Caps resource; + Caps cost; + Caps widthscale; + Caps byte; + Caps init; + Caps style; +}; + +struct Parser { + std::string filename; + std::ifstream infile; + int line_number = 0; + Library &lib; + const pool &defines; + pool &defines_unused; + std::vector tokens; + int token_idx = 0; + bool eof = false; + + std::vector> option_stack; + std::vector> portoption_stack; + RamDef ram; + PortGroupDef port; + bool active = true; + + Parser(std::string filename, Library &lib, const pool &defines, pool &defines_unused) : filename(filename), lib(lib), defines(defines), defines_unused(defines_unused) { + // Note: this rewrites the filename we're opening, but not + // the one we're storing — this is actually correct, so that + // we keep the original filename for diagnostics. + rewrite_filename(filename); + infile.open(filename); + if (infile.fail()) { + log_error("failed to open %s\n", filename); + } + parse(); + infile.close(); + } + + std::string peek_token() { + if (eof) + return ""; + + if (token_idx < GetSize(tokens)) + return tokens[token_idx]; + + tokens.clear(); + token_idx = 0; + + std::string line; + while (std::getline(infile, line)) { + line_number++; + for (string tok = next_token(line); !tok.empty(); tok = next_token(line)) { + if (tok[0] == '#') + break; + if (tok[tok.size()-1] == ';') { + tokens.push_back(tok.substr(0, tok.size()-1)); + tokens.push_back(";"); + } else { + tokens.push_back(tok); + } + } + if (!tokens.empty()) + return tokens[token_idx]; + } + + eof = true; + return ""; + } + + std::string get_token() { + std::string res = peek_token(); + if (!eof) + token_idx++; + return res; + } + + void eat_token(std::string expected) { + std::string token = get_token(); + if (token != expected) { + log_error("%s:%d: expected `%s`, got `%s`.\n", filename, line_number, expected, token); + } + } + + std::string get_id() { + std::string token = get_token(); + if (token.empty() || (token[0] != '$' && token[0] != '\\')) { + log_error("%s:%d: expected id string, got `%s`.\n", filename, line_number, token); + } + return token; + } + + std::string get_name() { + std::string res = get_token(); + bool valid = true; + // Basic sanity check. + if (res.empty() || (!isalpha(res[0]) && res[0] != '_')) + valid = false; + for (char c: res) + if (!isalnum(c) && c != '_') + valid = false; + if (!valid) + log_error("%s:%d: expected name, got `%s`.\n", filename, line_number, res); + return res; + } + + std::string get_string() { + std::string token = get_token(); + if (token.size() < 2 || token[0] != '"' || token[token.size()-1] != '"') { + log_error("%s:%d: expected string, got `%s`.\n", filename, line_number, token); + } + return token.substr(1, token.size()-2); + } + + bool peek_string() { + std::string token = peek_token(); + return !token.empty() && token[0] == '"'; + } + + int get_int() { + std::string token = get_token(); + char *endptr; + long res = strtol(token.c_str(), &endptr, 0); + if (token.empty() || *endptr || res > INT_MAX) { + log_error("%s:%d: expected int, got `%s`.\n", filename, line_number, token); + } + return res; + } + + double get_double() { + std::string token = get_token(); + char *endptr; + double res = strtod(token.c_str(), &endptr); + if (token.empty() || *endptr) { + log_error("%s:%d: expected float, got `%s`.\n", filename, line_number, token); + } + return res; + } + + bool peek_int() { + std::string token = peek_token(); + return !token.empty() && isdigit(token[0]); + } + + void get_semi() { + std::string token = get_token(); + if (token != ";") { + log_error("%s:%d: expected `;`, got `%s`.\n", filename, line_number, token); + } + } + + Const get_value() { + std::string token = peek_token(); + if (!token.empty() && token[0] == '"') { + std::string s = get_string(); + return Const(s); + } else { + return Const(get_int()); + } + } + + bool enter_ifdef(bool polarity) { + bool res = active; + std::string name = get_name(); + defines_unused.erase(name); + if (active) { + if (defines.count(name)) { + active = polarity; + } else { + active = !polarity; + } + } + return res; + } + + void enter_else(bool save) { + get_token(); + active = !active && save; + } + + void enter_option() { + std::string name = get_string(); + Const val = get_value(); + if (active) { + ram.opts[name].insert(val); + } + option_stack.push_back({name, val}); + } + + void exit_option() { + option_stack.pop_back(); + } + + Options get_options() { + Options res; + for (auto it: option_stack) + res[it.first] = it.second; + return res; + } + + void enter_portoption() { + std::string name = get_string(); + Const val = get_value(); + if (active) { + port.portopts[name].insert(val); + } + portoption_stack.push_back({name, val}); + } + + void exit_portoption() { + portoption_stack.pop_back(); + } + + Options get_portoptions() { + Options res; + for (auto it: portoption_stack) + res[it.first] = it.second; + return res; + } + + template void add_cap(Caps &caps, T val) { + if (active) + caps.push_back(Capability(val, get_options(), get_portoptions())); + } + + void parse_port_block() { + if (peek_token() == "{") { + get_token(); + while (peek_token() != "}") + parse_port_item(); + get_token(); + } else { + parse_port_item(); + } + } + + void parse_ram_block() { + if (peek_token() == "{") { + get_token(); + while (peek_token() != "}") + parse_ram_item(); + get_token(); + } else { + parse_ram_item(); + } + } + + void parse_top_block() { + if (peek_token() == "{") { + get_token(); + while (peek_token() != "}") + parse_top_item(); + get_token(); + } else { + parse_top_item(); + } + } + + void parse_port_item() { + std::string token = get_token(); + if (token == "ifdef") { + bool save = enter_ifdef(true); + parse_port_block(); + if (peek_token() == "else") { + enter_else(save); + parse_port_block(); + } + active = save; + } else if (token == "ifndef") { + bool save = enter_ifdef(false); + parse_port_block(); + if (peek_token() == "else") { + enter_else(save); + parse_port_block(); + } + active = save; + } else if (token == "option") { + enter_option(); + parse_port_block(); + exit_option(); + } else if (token == "portoption") { + enter_portoption(); + parse_port_block(); + exit_portoption(); + } else if (token == "clock") { + if (port.kind == PortKind::Ar) { + log_error("%s:%d: `clock` not allowed in async read port.\n", filename, line_number); + } + ClockDef def; + token = get_token(); + if (token == "anyedge") { + def.kind = ClkPolKind::Anyedge; + } else if (token == "posedge") { + def.kind = ClkPolKind::Posedge; + } else if (token == "negedge") { + def.kind = ClkPolKind::Negedge; + } else { + log_error("%s:%d: expected `posedge`, `negedge`, or `anyedge`, got `%s`.\n", filename, line_number, token); + } + if (peek_string()) { + def.name = get_string(); + } + get_semi(); + add_cap(port.clock, def); + } else if (token == "clken") { + if (port.kind == PortKind::Ar) { + log_error("%s:%d: `clken` not allowed in async read port.\n", filename, line_number); + } + get_semi(); + add_cap(port.clken, {}); + } else if (token == "wrbe_separate") { + if (port.kind == PortKind::Ar || port.kind == PortKind::Sr) { + log_error("%s:%d: `wrbe_separate` not allowed in read port.\n", filename, line_number); + } + get_semi(); + add_cap(port.wrbe_separate, {}); + } else if (token == "width") { + PortWidthDef def; + token = peek_token(); + bool is_rw = port.kind == PortKind::Srsw || port.kind == PortKind::Arsw; + if (token == "tied") { + get_token(); + if (!is_rw) + log_error("%s:%d: `tied` only makes sense for read+write ports.\n", filename, line_number); + while (peek_int()) + def.wr_widths.push_back(get_int()); + def.tied = true; + } else if (token == "mix") { + get_token(); + if (!is_rw) + log_error("%s:%d: `mix` only makes sense for read+write ports.\n", filename, line_number); + while (peek_int()) + def.wr_widths.push_back(get_int()); + def.rd_widths = def.wr_widths; + def.tied = false; + } else if (token == "rd") { + get_token(); + if (!is_rw) + log_error("%s:%d: `rd` only makes sense for read+write ports.\n", filename, line_number); + do { + def.rd_widths.push_back(get_int()); + } while (peek_int()); + eat_token("wr"); + do { + def.wr_widths.push_back(get_int()); + } while (peek_int()); + def.tied = false; + } else if (token == "wr") { + get_token(); + if (!is_rw) + log_error("%s:%d: `wr` only makes sense for read+write ports.\n", filename, line_number); + do { + def.wr_widths.push_back(get_int()); + } while (peek_int()); + eat_token("rd"); + do { + def.rd_widths.push_back(get_int()); + } while (peek_int()); + def.tied = false; + } else { + do { + def.wr_widths.push_back(get_int()); + } while (peek_int()); + def.tied = true; + } + get_semi(); + add_cap(port.width, def); + } else if (token == "rden") { + if (port.kind != PortKind::Sr && port.kind != PortKind::Srsw) + log_error("%s:%d: `rden` only allowed on sync read ports.\n", filename, line_number); + get_semi(); + add_cap(port.rden, {}); + } else if (token == "rdwr") { + if (port.kind != PortKind::Srsw) + log_error("%s:%d: `rdwr` only allowed on sync read+write ports.\n", filename, line_number); + RdWrKind kind; + token = get_token(); + if (token == "undefined") { + kind = RdWrKind::Undefined; + } else if (token == "no_change") { + kind = RdWrKind::NoChange; + } else if (token == "new") { + kind = RdWrKind::New; + } else if (token == "old") { + kind = RdWrKind::Old; + } else if (token == "new_only") { + kind = RdWrKind::NewOnly; + } else { + log_error("%s:%d: expected `undefined`, `new`, `old`, `new_only`, or `no_change`, got `%s`.\n", filename, line_number, token); + } + get_semi(); + add_cap(port.rdwr, kind); + } else if (token == "rdinit") { + if (port.kind != PortKind::Sr && port.kind != PortKind::Srsw) + log_error("%s:%d: `%s` only allowed on sync read ports.\n", filename, line_number, token); + ResetValKind kind; + token = get_token(); + if (token == "none") { + kind = ResetValKind::None; + } else if (token == "zero") { + kind = ResetValKind::Zero; + } else if (token == "any") { + kind = ResetValKind::Any; + } else if (token == "no_undef") { + kind = ResetValKind::NoUndef; + } else { + log_error("%s:%d: expected `none`, `zero`, `any`, or `no_undef`, got `%s`.\n", filename, line_number, token); + } + get_semi(); + add_cap(port.rdinit, kind); + } else if (token == "rdarst") { + if (port.kind != PortKind::Sr && port.kind != PortKind::Srsw) + log_error("%s:%d: `%s` only allowed on sync read ports.\n", filename, line_number, token); + ResetValKind kind; + token = get_token(); + if (token == "none") { + kind = ResetValKind::None; + } else if (token == "zero") { + kind = ResetValKind::Zero; + } else if (token == "any") { + kind = ResetValKind::Any; + } else if (token == "no_undef") { + kind = ResetValKind::NoUndef; + } else if (token == "init") { + kind = ResetValKind::Init; + } else { + log_error("%s:%d: expected `none`, `zero`, `any`, `no_undef`, or `init`, got `%s`.\n", filename, line_number, token); + } + get_semi(); + add_cap(port.rdarst, kind); + } else if (token == "rdsrst") { + if (port.kind != PortKind::Sr && port.kind != PortKind::Srsw) + log_error("%s:%d: `%s` only allowed on sync read ports.\n", filename, line_number, token); + SrstDef def; + token = get_token(); + if (token == "none") { + def.val = ResetValKind::None; + } else if (token == "zero") { + def.val = ResetValKind::Zero; + } else if (token == "any") { + def.val = ResetValKind::Any; + } else if (token == "no_undef") { + def.val = ResetValKind::NoUndef; + } else if (token == "init") { + def.val = ResetValKind::Init; + } else { + log_error("%s:%d: expected `none`, `zero`, `any`, `no_undef`, or `init`, got `%s`.\n", filename, line_number, token); + } + if (def.val == ResetValKind::None) { + def.kind = SrstKind::None; + } else { + token = get_token(); + if (token == "ungated") { + def.kind = SrstKind::Ungated; + } else if (token == "gated_clken") { + def.kind = SrstKind::GatedClkEn; + } else if (token == "gated_rden") { + def.kind = SrstKind::GatedRdEn; + } else { + log_error("%s:%d: expected `ungated`, `gated_clken` or `gated_rden`, got `%s`.\n", filename, line_number, token); + } + } + def.block_wr = false; + if (peek_token() == "block_wr") { + get_token(); + def.block_wr = true; + } + get_semi(); + add_cap(port.rdsrst, def); + } else if (token == "wrprio") { + if (port.kind == PortKind::Ar || port.kind == PortKind::Sr) + log_error("%s:%d: `wrprio` only allowed on write ports.\n", filename, line_number); + do { + add_cap(port.wrprio, get_string()); + } while (peek_string()); + get_semi(); + } else if (token == "wrtrans") { + if (port.kind == PortKind::Ar || port.kind == PortKind::Sr) + log_error("%s:%d: `wrtrans` only allowed on write ports.\n", filename, line_number); + token = peek_token(); + RawWrTransDef def; + if (token == "all") { + def.target_kind = WrTransTargetKind::All; + get_token(); + } else { + def.target_kind = WrTransTargetKind::Group; + def.target_group = get_string(); + } + token = get_token(); + if (token == "new") { + def.kind = WrTransKind::New; + } else if (token == "old") { + def.kind = WrTransKind::Old; + } else { + log_error("%s:%d: expected `new` or `old`, got `%s`.\n", filename, line_number, token); + } + get_semi(); + add_cap(port.wrtrans, def); + } else if (token == "forbid") { + get_semi(); + add_cap(port.forbid, {}); + } else if (token == "optional") { + get_semi(); + add_cap(port.optional, {}); + } else if (token == "optional_rw") { + get_semi(); + add_cap(port.optional_rw, {}); + } else if (token == "") { + log_error("%s:%d: unexpected EOF while parsing port item.\n", filename, line_number); + } else { + log_error("%s:%d: unknown port-level item `%s`.\n", filename, line_number, token); + } + } + + void parse_ram_item() { + std::string token = get_token(); + if (token == "ifdef") { + bool save = enter_ifdef(true); + parse_ram_block(); + if (peek_token() == "else") { + enter_else(save); + parse_ram_block(); + } + active = save; + } else if (token == "ifndef") { + bool save = enter_ifdef(false); + parse_ram_block(); + if (peek_token() == "else") { + enter_else(save); + parse_ram_block(); + } + active = save; + } else if (token == "option") { + enter_option(); + parse_ram_block(); + exit_option(); + } else if (token == "prune_rom") { + get_semi(); + add_cap(ram.prune_rom, {}); + } else if (token == "forbid") { + get_semi(); + add_cap(ram.forbid, {}); + } else if (token == "abits") { + int val = get_int(); + if (val < 0) + log_error("%s:%d: abits %d nagative.\n", filename, line_number, val); + get_semi(); + add_cap(ram.abits, val); + } else if (token == "width") { + WidthsDef def; + int w = get_int(); + if (w <= 0) + log_error("%s:%d: width %d not positive.\n", filename, line_number, w); + def.widths.push_back(w); + def.mode = WidthMode::Single; + get_semi(); + add_cap(ram.widths, def); + } else if (token == "widths") { + WidthsDef def; + int last = 0; + do { + int w = get_int(); + if (w <= 0) + log_error("%s:%d: width %d not positive.\n", filename, line_number, w); + if (w < last * 2) + log_error("%s:%d: width %d smaller than %d required for progression.\n", filename, line_number, w, last * 2); + last = w; + def.widths.push_back(w); + } while(peek_int()); + token = get_token(); + if (token == "global") { + def.mode = WidthMode::Global; + } else if (token == "per_port") { + def.mode = WidthMode::PerPort; + } else { + log_error("%s:%d: expected `global`, or `per_port`, got `%s`.\n", filename, line_number, token); + } + get_semi(); + add_cap(ram.widths, def); + } else if (token == "resource") { + ResourceDef def; + def.name = get_string(); + if (peek_int()) + def.count = get_int(); + else + def.count = 1; + get_semi(); + add_cap(ram.resource, def); + } else if (token == "cost") { + add_cap(ram.cost, get_double()); + get_semi(); + } else if (token == "widthscale") { + if (peek_int()) { + add_cap(ram.widthscale, get_double()); + } else { + add_cap(ram.widthscale, 0.0); + } + get_semi(); + } else if (token == "byte") { + int val = get_int(); + if (val <= 0) + log_error("%s:%d: byte width %d not positive.\n", filename, line_number, val); + add_cap(ram.byte, val); + get_semi(); + } else if (token == "init") { + MemoryInitKind kind; + token = get_token(); + if (token == "zero") { + kind = MemoryInitKind::Zero; + } else if (token == "any") { + kind = MemoryInitKind::Any; + } else if (token == "no_undef") { + kind = MemoryInitKind::NoUndef; + } else if (token == "none") { + kind = MemoryInitKind::None; + } else { + log_error("%s:%d: expected `zero`, `any`, `none`, or `no_undef`, got `%s`.\n", filename, line_number, token); + } + get_semi(); + add_cap(ram.init, kind); + } else if (token == "style") { + do { + std::string val = get_string(); + for (auto &c: val) + c = std::tolower(c); + add_cap(ram.style, val); + } while (peek_string()); + get_semi(); + } else if (token == "port") { + port = PortGroupDef(); + token = get_token(); + if (token == "ar") { + port.kind = PortKind::Ar; + } else if (token == "sr") { + port.kind = PortKind::Sr; + } else if (token == "sw") { + port.kind = PortKind::Sw; + } else if (token == "arsw") { + port.kind = PortKind::Arsw; + } else if (token == "srsw") { + port.kind = PortKind::Srsw; + } else { + log_error("%s:%d: expected `ar`, `sr`, `sw`, `arsw`, or `srsw`, got `%s`.\n", filename, line_number, token); + } + do { + port.names.push_back(get_string()); + } while (peek_string()); + parse_port_block(); + if (active) + add_cap(ram.ports, port); + } else if (token == "") { + log_error("%s:%d: unexpected EOF while parsing ram item.\n", filename, line_number); + } else { + log_error("%s:%d: unknown ram-level item `%s`.\n", filename, line_number, token); + } + } + + void parse_top_item() { + std::string token = get_token(); + if (token == "ifdef") { + bool save = enter_ifdef(true); + parse_top_block(); + if (peek_token() == "else") { + enter_else(save); + parse_top_block(); + } + active = save; + } else if (token == "ifndef") { + bool save = enter_ifdef(false); + parse_top_block(); + if (peek_token() == "else") { + enter_else(save); + parse_top_block(); + } + active = save; + } else if (token == "ram") { + int orig_line = line_number; + ram = RamDef(); + token = get_token(); + if (token == "distributed") { + ram.kind = RamKind::Distributed; + } else if (token == "block") { + ram.kind = RamKind::Block; + } else if (token == "huge") { + ram.kind = RamKind::Huge; + } else { + log_error("%s:%d: expected `distributed`, `block`, or `huge`, got `%s`.\n", filename, line_number, token); + } + ram.id = get_id(); + parse_ram_block(); + if (active) { + compile_ram(orig_line); + } + } else if (token == "") { + log_error("%s:%d: unexpected EOF while parsing top item.\n", filename, line_number); + } else { + log_error("%s:%d: unknown top-level item `%s`.\n", filename, line_number, token); + } + } + + bool opts_ok(const Options &def, const Options &var) { + for (auto &it: def) + if (var.at(it.first) != it.second) + return false; + return true; + } + + template const T *find_single_cap(const Caps &caps, const Options &opts, const Options &portopts, const char *name) { + const T *res = nullptr; + for (auto &cap: caps) { + if (!opts_ok(cap.opts, opts)) + continue; + if (!opts_ok(cap.portopts, portopts)) + continue; + if (res) + log_error("%s:%d: duplicate %s cap.\n", filename, line_number, name); + res = &cap.val; + } + return res; + } + + std::vector make_opt_combinations(const dict> &opts) { + std::vector res; + res.push_back(Options()); + for (auto &it: opts) { + std::vector new_res; + for (auto &val: it.second) { + for (Options o: res) { + o[it.first] = val; + new_res.push_back(o); + } + } + res = new_res; + } + return res; + } + + void compile_portgroup(Ram &cram, PortGroupDef &pdef, dict &clk_ids, const dict &port_ids, int orig_line) { + PortGroup grp; + grp.optional = find_single_cap(pdef.optional, cram.options, Options(), "optional"); + grp.optional_rw = find_single_cap(pdef.optional_rw, cram.options, Options(), "optional_rw"); + grp.names = pdef.names; + for (auto portopts: make_opt_combinations(pdef.portopts)) { + bool forbidden = false; + for (auto &fdef: ram.forbid) { + if (opts_ok(fdef.opts, cram.options) && opts_ok(fdef.portopts, portopts)) { + forbidden = true; + } + } + if (forbidden) + continue; + PortVariant var; + var.options = portopts; + var.kind = pdef.kind; + if (pdef.kind == PortKind::Ar) { + var.clk_en = false; + } else { + const ClockDef *cdef = find_single_cap(pdef.clock, cram.options, portopts, "clock"); + if (!cdef) + log_error("%s:%d: missing clock capability.\n", filename, orig_line); + var.clk_pol = cdef->kind; + if (cdef->name.empty()) { + var.clk_shared = -1; + } else { + auto it = clk_ids.find(cdef->name); + bool anyedge = cdef->kind == ClkPolKind::Anyedge; + if (it == clk_ids.end()) { + clk_ids[cdef->name] = var.clk_shared = GetSize(cram.shared_clocks); + RamClock clk; + clk.name = cdef->name; + clk.anyedge = anyedge; + cram.shared_clocks.push_back(clk); + } else { + var.clk_shared = it->second; + if (cram.shared_clocks[var.clk_shared].anyedge != anyedge) { + log_error("%s:%d: named clock \"%s\" used with both posedge/negedge and anyedge clocks.\n", filename, orig_line, cdef->name); + } + } + } + var.clk_en = find_single_cap(pdef.clken, cram.options, portopts, "clken") != nullptr; + } + const PortWidthDef *wdef = find_single_cap(pdef.width, cram.options, portopts, "width"); + if (wdef) { + if (cram.width_mode != WidthMode::PerPort) + log_error("%s:%d: per-port width doesn't make sense for tied dbits.\n", filename, orig_line); + compile_widths(var, cram.dbits, *wdef); + } else { + var.width_tied = true; + var.min_wr_wide_log2 = 0; + var.min_rd_wide_log2 = 0; + var.max_wr_wide_log2 = GetSize(cram.dbits) - 1; + var.max_rd_wide_log2 = GetSize(cram.dbits) - 1; + } + if (pdef.kind == PortKind::Srsw || pdef.kind == PortKind::Sr) { + const RdWrKind *rdwr = find_single_cap(pdef.rdwr, cram.options, portopts, "rdwr"); + var.rdwr = rdwr ? *rdwr : RdWrKind::Undefined; + var.rd_en = find_single_cap(pdef.rden, cram.options, portopts, "rden"); + const ResetValKind *iv = find_single_cap(pdef.rdinit, cram.options, portopts, "rdinit"); + var.rdinitval = iv ? *iv : ResetValKind::None; + const ResetValKind *arv = find_single_cap(pdef.rdarst, cram.options, portopts, "rdarst"); + var.rdarstval = arv ? *arv : ResetValKind::None; + const SrstDef *srv = find_single_cap(pdef.rdsrst, cram.options, portopts, "rdsrst"); + if (srv) { + var.rdsrstval = srv->val; + var.rdsrstmode = srv->kind; + var.rdsrst_block_wr = srv->block_wr; + if (srv->kind == SrstKind::GatedClkEn && !var.clk_en) + log_error("%s:%d: `gated_clken` used without `clken`.\n", filename, orig_line); + if (srv->kind == SrstKind::GatedRdEn && !var.rd_en) + log_error("%s:%d: `gated_rden` used without `rden`.\n", filename, orig_line); + } else { + var.rdsrstval = ResetValKind::None; + var.rdsrstmode = SrstKind::None; + var.rdsrst_block_wr = false; + } + if (var.rdarstval == ResetValKind::Init || var.rdsrstval == ResetValKind::Init) { + if (var.rdinitval != ResetValKind::Any && var.rdinitval != ResetValKind::NoUndef) { + log_error("%s:%d: reset value `init` has to be paired with `any` or `no_undef` initial value.\n", filename, orig_line); + } + } + } + var.wrbe_separate = find_single_cap(pdef.wrbe_separate, cram.options, portopts, "wrbe_separate"); + if (var.wrbe_separate && cram.byte == 0) { + log_error("%s:%d: `wrbe_separate` used without `byte`.\n", filename, orig_line); + } + for (auto &def: pdef.wrprio) { + if (!opts_ok(def.opts, cram.options)) + continue; + if (!opts_ok(def.portopts, portopts)) + continue; + var.wrprio.push_back(port_ids.at(def.val)); + } + for (auto &def: pdef.wrtrans) { + if (!opts_ok(def.opts, cram.options)) + continue; + if (!opts_ok(def.portopts, portopts)) + continue; + WrTransDef tdef; + tdef.target_kind = def.val.target_kind; + if (def.val.target_kind == WrTransTargetKind::Group) + tdef.target_group = port_ids.at(def.val.target_group); + tdef.kind = def.val.kind; + var.wrtrans.push_back(tdef); + } + grp.variants.push_back(var); + } + if (grp.variants.empty()) { + log_error("%s:%d: all port option combinations are forbidden.\n", filename, orig_line); + } + cram.port_groups.push_back(grp); + } + + void compile_ram(int orig_line) { + if (ram.abits.empty()) + log_error("%s:%d: `dims` capability should be specified.\n", filename, orig_line); + if (ram.widths.empty()) + log_error("%s:%d: `widths` capability should be specified.\n", filename, orig_line); + if (ram.ports.empty()) + log_error("%s:%d: at least one port group should be specified.\n", filename, orig_line); + for (auto opts: make_opt_combinations(ram.opts)) { + bool forbidden = false; + for (auto &fdef: ram.forbid) { + if (opts_ok(fdef.opts, opts)) { + forbidden = true; + } + } + if (forbidden) + continue; + Ram cram; + cram.id = ram.id; + cram.kind = ram.kind; + cram.options = opts; + cram.prune_rom = find_single_cap(ram.prune_rom, opts, Options(), "prune_rom"); + const int *abits = find_single_cap(ram.abits, opts, Options(), "abits"); + if (!abits) + continue; + cram.abits = *abits; + const WidthsDef *widths = find_single_cap(ram.widths, opts, Options(), "widths"); + if (!widths) + continue; + cram.dbits = widths->widths; + cram.width_mode = widths->mode; + const ResourceDef *resource = find_single_cap(ram.resource, opts, Options(), "resource"); + if (resource) { + cram.resource_name = resource->name; + cram.resource_count = resource->count; + } else { + cram.resource_count = 1; + } + cram.cost = 0; + for (auto &cap: ram.cost) { + if (opts_ok(cap.opts, opts)) + cram.cost += cap.val; + } + const double *widthscale = find_single_cap(ram.widthscale, opts, Options(), "widthscale"); + if (widthscale) + cram.widthscale = *widthscale ? *widthscale : cram.cost; + else + cram.widthscale = 0; + const int *byte = find_single_cap(ram.byte, opts, Options(), "byte"); + cram.byte = byte ? *byte : 0; + if (GetSize(cram.dbits) - 1 > cram.abits) + log_error("%s:%d: abits %d too small for dbits progression.\n", filename, line_number, cram.abits); + validate_byte(widths->widths, cram.byte); + const MemoryInitKind *ik = find_single_cap(ram.init, opts, Options(), "init"); + cram.init = ik ? *ik : MemoryInitKind::None; + for (auto &sdef: ram.style) + if (opts_ok(sdef.opts, opts)) + cram.style.push_back(sdef.val); + dict port_ids; + int ctr = 0; + for (auto &pdef: ram.ports) { + if (!opts_ok(pdef.opts, opts)) + continue; + for (auto &name: pdef.val.names) + port_ids[name] = ctr; + ctr++; + } + dict clk_ids; + for (auto &pdef: ram.ports) { + if (!opts_ok(pdef.opts, opts)) + continue; + compile_portgroup(cram, pdef.val, clk_ids, port_ids, orig_line); + } + lib.rams.push_back(cram); + } + } + + void validate_byte(const std::vector &widths, int byte) { + if (byte == 0) + return; + if (byte >= widths.back()) + return; + if (widths[0] % byte == 0) { + for (int j = 1; j < GetSize(widths); j++) + if (widths[j] % byte != 0) + log_error("%s:%d: width progression past byte width %d is not divisible.\n", filename, line_number, byte); + return; + } + for (int i = 0; i < GetSize(widths); i++) { + if (widths[i] == byte) { + for (int j = i + 1; j < GetSize(widths); j++) + if (widths[j] % byte != 0) + log_error("%s:%d: width progression past byte width %d is not divisible.\n", filename, line_number, byte); + return; + } + } + log_error("%s:%d: byte width %d invalid for dbits.\n", filename, line_number, byte); + } + + void compile_widths(PortVariant &var, const std::vector &widths, const PortWidthDef &width) { + var.width_tied = width.tied; + auto wr_widths = compile_widthdef(widths, width.wr_widths); + var.min_wr_wide_log2 = wr_widths.first; + var.max_wr_wide_log2 = wr_widths.second; + if (width.tied) { + var.min_rd_wide_log2 = wr_widths.first; + var.max_rd_wide_log2 = wr_widths.second; + } else { + auto rd_widths = compile_widthdef(widths, width.rd_widths); + var.min_rd_wide_log2 = rd_widths.first; + var.max_rd_wide_log2 = rd_widths.second; + } + } + + std::pair compile_widthdef(const std::vector &dbits, const std::vector &widths) { + if (widths.empty()) + return {0, GetSize(dbits) - 1}; + for (int i = 0; i < GetSize(dbits); i++) { + if (dbits[i] == widths[0]) { + for (int j = 0; j < GetSize(widths); j++) { + if (i+j >= GetSize(dbits) || dbits[i+j] != widths[j]) { + log_error("%s:%d: port width %d doesn't match dbits progression.\n", filename, line_number, widths[j]); + } + } + return {i, i + GetSize(widths) - 1}; + } + } + log_error("%s:%d: port width %d invalid for dbits.\n", filename, line_number, widths[0]); + } + + void parse() { + while (peek_token() != "") + parse_top_item(); + } +}; + +PRIVATE_NAMESPACE_END + +Library MemLibrary::parse_library(const std::vector &filenames, const pool &defines) { + Library res; + pool defines_unused = defines; + for (auto &file: filenames) { + Parser(file, res, defines, defines_unused); + } + for (auto def: defines_unused) { + log_warning("define %s not used in the library.\n", def); + } + return res; +} diff --git a/chips/yosys/passes/memory/memlib.h b/chips/yosys/passes/memory/memlib.h new file mode 100644 index 0000000000000000000000000000000000000000..419f530a39a130c4cdf8b5fc96a12b811620f79b --- /dev/null +++ b/chips/yosys/passes/memory/memlib.h @@ -0,0 +1,171 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2021 Marcelina Kościelnicka + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#ifndef MEMLIB_H +#define MEMLIB_H + +#include +#include + +#include "kernel/yosys.h" + +YOSYS_NAMESPACE_BEGIN + +namespace MemLibrary { + +enum class RamKind { + Auto, + Logic, + NotLogic, + Distributed, + Block, + Huge, +}; + +enum class WidthMode { + Single, + Global, + PerPort, +}; + +enum class MemoryInitKind { + None, + Zero, + Any, + NoUndef, +}; + +enum class PortKind { + Sr, + Ar, + Sw, + Srsw, + Arsw, +}; + +enum class ClkPolKind { + Anyedge, + Posedge, + Negedge, +}; + +enum class RdWrKind { + Undefined, + NoChange, + New, + Old, + NewOnly, +}; + +enum class ResetValKind { + None, + Zero, + Any, + NoUndef, + Init, +}; + +enum class SrstKind { + None, + Ungated, + GatedClkEn, + GatedRdEn, +}; + +enum class WrTransTargetKind { + All, + Group, +}; + +enum class WrTransKind { + New, + Old, +}; + +struct WrTransDef { + WrTransTargetKind target_kind; + int target_group = 0; + WrTransKind kind; +}; + +struct PortVariant { + dict options; + PortKind kind; + int clk_shared; + ClkPolKind clk_pol; + bool clk_en = false; + bool width_tied; + int min_wr_wide_log2; + int max_wr_wide_log2; + int min_rd_wide_log2; + int max_rd_wide_log2; + bool rd_en; + RdWrKind rdwr; + ResetValKind rdinitval; + ResetValKind rdarstval; + ResetValKind rdsrstval; + SrstKind rdsrstmode; + bool rdsrst_block_wr; + bool wrbe_separate; + std::vector wrprio; + std::vector wrtrans; +}; + +struct PortGroup { + bool optional; + bool optional_rw; + std::vector names; + std::vector variants; +}; + +struct RamClock { + std::string name; + bool anyedge; +}; + +struct Ram { + std::string id; + RamKind kind; + dict options; + std::vector port_groups; + bool prune_rom; + int abits; + std::vector dbits; + WidthMode width_mode; + std::string resource_name; + int resource_count; + double cost; + double widthscale; + int byte; + MemoryInitKind init; + std::vector style; + std::vector shared_clocks; +}; + +struct Library { + std::vector rams; +}; + +Library parse_library(const std::vector &filenames, const pool &defines); + +} + +YOSYS_NAMESPACE_END + +#endif diff --git a/chips/yosys/passes/memory/memlib.md b/chips/yosys/passes/memory/memlib.md new file mode 100644 index 0000000000000000000000000000000000000000..5ad3f7777a354e21b52ab7153af05ac1984535aa --- /dev/null +++ b/chips/yosys/passes/memory/memlib.md @@ -0,0 +1,505 @@ +# The `memory_libmap` pass + +The `memory_libmap` pass is used to map memories to hardware primitives. To work, +it needs a description of available target memories in a custom format. + + +## Basic structure + +A basic library could look like this: + + # A distributed-class RAM called $__RAM16X4SDP_ + ram distributed $__RAM16X4SDP_ { + # Has 4 address bits (ie. 16 rows). + abits 4; + # Has 4 data bits. + width 4; + # Cost for the selection heuristic. + cost 4; + # Can be initialized to any value on startup. + init any; + # Has a synchronous write port called "W"... + port sw "W" { + # ... with a positive edge clock. + clock posedge; + } + # Has an asynchronous read port called "R". + port ar "R" { + } + } + + # A block-class RAM called $__RAMB9K_ + ram block $__RAMB9K_ { + # Has 13 address bits in the base (most narrow) data width. + abits 13; + # The available widths are: + # - 1 (13 address bits) + # - 2 (12 address bits) + # - 4 (11 address bits) + # - 9 (10 address bits) + # - 18 (9 address bits) + # The width selection is per-port. + widths 1 2 4 9 18 per_port; + # Has a write enable signal with 1 bit for every 9 data bits. + byte 9; + cost 64; + init any; + # Has two synchronous read+write ports, called "A" and "B". + port srsw "A" "B" { + clock posedge; + # Has a clock enable signal (gates both read and write). + clken; + # Has three per-port selectable options for handling read+write behavior: + portoption "RDWR" "NO_CHANGE" { + # When port is writing, reading is not done (output register keeps + # its value). + rdwr no_change; + } + portoption "RDWR" "OLD" { + # When port is writing, the data read is the old value (before the + # write). + rdwr old; + } + portoption "RDWR" "NEW" { + # When port is writing, the data read is the new value. + rdwr new; + } + } + } + +The pass will automatically select between the two available cells and +the logic fallback (mapping the whole memory to LUTs+FFs) based on required +capabilities and cost function. The selected memories will be transformed +to intermediate `$__RAM16X4SDP_` and `$__RAMB9K_` cells that need to be mapped +to actual hardware cells by a `techmap` pass, while memories selected for logic +fallback will be left unmapped and will be later mopped up by `memory_map` pass. + +## RAM definition blocks + +The syntax for a RAM definition is: + + ram { + + + } + +The `` is used as the type of the mapped cell that will be passed to `techmap`. +The memory kind is one of `distributed`, `block`, or `huge`. It describes the general +class of the memory and can be matched on by manual selection attributes. + +The available ram properties are: + +- `abits
;` +- `width ;` +- `widths ... ;` +- `byte ;` +- `cost ;` +- `widthscale [];` +- `resource ;` +- `init ;` +- `style "" "" "" ...;` +- `prune_rom;` + +### RAM dimensions + +The memory dimensions are described by `abits` and `width` or `widths` properties. + +For a simple memory cell with a fixed width, use `abits` and `width` like this: + + abits 4; + width 4; + +This will result in a `2**abits × width` memory cell. + +Multiple-width memories are also possible, and use the `widths` property instead. +The rules for multiple-width memories are: + +- the widths are given in `widths` property in increasing order +- the value in the `abits` property corresponds to the most narrow width +- every width in the list needs to be greater than or equal to twice + the previous width (ie. `1 2 4 9 18` is valid, `1 2 4 7 14` is not) +- it is assumed that, for every width in progression, the word in memory + is made of two smaller words, plus optionally some extra bits (eg. in the above + list, the 9-bit word is made of two 4-bit words and 1 extra bit), and thus + each sequential width in the list corresponds to one fewer usable address bit +- all addresses connected to memory ports are always `abits` bits wide, with const + zero wired to the unused bits corresponding to wide ports + +When multiple widths are specified, they can be `per_port` or `global`. +For the `global` version, the pass has to pick one width for the whole cell, +and it is set on the resulting cell as the `WIDTH` parameter. For the `per_port` +version, the selection is made on per-port basis, and passed using `PORT_*_WIDTH` +parameters. When the mode is `per_port`, the width selection can be fine-tuned +with the port `width` property. + +Specifying dimensions is mandatory. + + +### Byte width + +If the memory cell has per-byte write enables, the `byte` property can be used +to define the byte size (ie. how many data bits correspond to one write enable +bit). + +The property is optional. If not used, it is assumed that there is a single +write enable signal for each writable port. + +The rules for this property are as follows: + +- for every available width, the width needs to be a multiple of the byte size, + or the byte size needs to be larger than the width +- if the byte size is larger than the width, the byte enable signal is assumed + to be one bit wide and cover the whole port +- otherwise, the byte enable signal has one bit for every `byte` bits of the + data port + +The exact kind of byte enable signal is determined by the presence or absence +of the per-port `wrbe_separate` property. + + +### Cost properties + +The `cost` property is used to estimate the cost of using a given mapping. +This is the cost of using one cell, and will be scaled as appropriate if +the mapping requires multiple cells. + +If the `widthscale` property is specified, the mapping is assumed to be flexible, +with cost scaling with the percentage of data width actually used. The value +of the `widthscale` property is how much of the cost is scalable as such. +If the value is omitted, all of the cost is assumed to scale. +Eg. for the following properties: + + width 14; + cost 8; + widthscale 7; + +The cost of a given cell will be assumed to be `(8 - 7) + 7 * (used_bits / 14)`. + +If `widthscale` is used, The pass will attach a `BITS_USED` parameter to mapped +cells, with a bitmask of which data bits of the memory are actually in use. +The parameter width will be the widest width in the `widths` property, and +the bit correspondence is defined accordingly. + +The `cost` property is mandatory. + + +### `init` property + +This property describes the state of the memory at initialization time. Can have +one of the following values: + +- `none`: the memory contents are unpredictable, memories requiring any sort + of initialization will not be mapped to this cell +- `zero`: the memory contents are zero, memories can be mapped to this cell iff + their initialization value is entirely zero or undef +- `any`: the memory contents can be arbitrarily selected, and the initialization + will be passed as the `INIT` parameter to the mapped cell +- `no_undef`: like `any`, but only 0 and 1 bit values are supported (the pass will + convert any x bits to 0) + +The `INIT` parameter is always constructed as a concatenation of words corresponding +to the widest available `widths` setting, so that all available memory cell bits +are covered. + +This property is optional and assumed to be `none` when not present. + + +### `style` property + +Provides a name (or names) for this definition that can be passed to the `ram_style` +or similar attribute to manually select it. Optional and can be used multiple times. + + +### `prune_rom` property + +Specifying this property disqualifies the definition from consideration for source +memories that have no write ports (ie. ROMs). Use this on definitions that have +an obviously superior read-only alternative (eg. LUTRAMs) to make the pass skip +them over quickly. + + +## Port definition blocks + +The syntax for a port group definition is: + + port "NAME 1" "NAME 2" ... { + + } + +A port group definition defines a group of ports with identical properties. +There are as many ports in a group as there are names given. + +Ports come in 5 kinds: + +- `ar`: asynchronous read port +- `sr`: synchronous read port +- `sw`: synchronous write port +- `arsw`: simultaneous synchronous write + asynchronous read with common address (commonly found in LUT RAMs) +- `srsw`: synchronous write + synchronous read with common address + +The port properties available are: + +- `width ;` +- `width ...;` +- `width ...;` +- `width rd ... wr ...;` +- `clock ["SHARED_NAME"];` +- `clken;` +- `rden;` +- `wrbe_separate;` +- `rdwr ;` +- `rdinit ;` +- `rdarst ;` +- `rdsrst [block_wr];` +- `wrprio "NAME" "NAME" ...;` +- `wrtrans <"NAME"|all> ;` +- `optional;` +- `optional_rw;` + +The base signals connected to the mapped cell for ports are: + +- `PORT__ADDR`: the address +- `PORT__WR_DATA`: the write data (for `sw`/`arsw`/`srsw` ports only) +- `PORT__RD_DATA`: the read data (for `ar`/`sr`/`arsw`/`srsw` ports only) +- `PORT__WR_EN`: the write enable or enables (for `sw`/`arsw`/`srsw` ports only) + +The address is always `abits` wide. If a non-narrowest width is used, the appropriate low +bits will be tied to 0. + + +### Port `width` property + +If the RAM has `per_port` widths, the available width selection can be further described +on per-port basis, by using one of the following properties: + +- `width tied;`: any width from the master `widths` list is acceptable, and + (for read+write ports) the read and write width has to be the same +- `width tied ...;`: like above, but limits the width + selection to the given list; the list has to be a contiguous sublist of the + master `widths` list +- `width ...;`: alias for the above, to be used for read-only + or write-only ports +- `width mix;`: any width from the master `widths` list is acceptable, and + read width can be different than write width (only usable for read+write ports) +- `width mix ...;`: like above, but limits the width + selection to the given list; the list has to be a contiguous sublist of the + master `widths` list +- `width rd ... wr ...;`: like above, + but the limitted selection can be different for read and write widths + +If `per_port` widths are in use and this property is not specified, `width tied;` is assumed. + +The parameters attached to the cell in `per_port` widths mode are: + +- `PORT__WIDTH`: the selected width (for `tied` ports) +- `PORT__RD_WIDTH`: the selected read width (for `mix` ports) +- `PORT__WR_WIDTH`: the selected write width (for `mix` ports) + + +### `clock` property + +The `clock` property is used with synchronous ports (and synchronous ports only). +It is mandatory for them and describes the clock polarity and clock sharing. +`anyedge` means that both polarities are supported. + +If a shared clock name is provided, the port is assumed to have a shared clock signal +with all other ports using the same shared name. Otherwise, the port is assumed to +have its own clock signal. + +The port clock is always provided on the memory cell as `PORT__CLK` signal +(even if it is also shared). Shared clocks are also provided as `CLK_` +signals. + +For `anyedge` clocks, the cell gets a `PORT__CLK_POL` parameter that is set +to 1 for `posedge` clocks and 0 for `negedge` clocks. If the clock is shared, +the same information will also be provided as `CLK__POL` parameter. + + +### `clken` and `rden` + +The `clken` property, if present, means that the port has a clock enable signal +gating both reads and writes. Such signal will be provided to the mapped cell +as `PORT__CLK_EN`. It is only applicable to synchronous ports. + +The `rden` property, if present, means that the port has a read clock enable signal. +Such signal will be provided to the mapped cell as `PORT__RD_EN`. It is only +applicable to synchronous read ports (`sr` and `srsw`). + +For `sr` ports, both of these options are effectively equivalent. + + +### `wrbe_separate` and the write enables + +The `wrbe_separate` property specifies that the write byte enables are provided +as a separate signal from the main write enable. It can only be used when the +RAM-level `byte` property is also specified. + +The rules are as follows: + +If no `byte` is specified: + +- `wrbe_separate` is not allowed +- `PORT__WR_EN` signal is single bit + +If `byte` is specified, but `wrbe_separate` is not: + +- `PORT__WR_EN` signal has one bit for every data byte +- `PORT__WR_EN_WIDTH` parameter is the width of the above (only present for multiple-width cells) + +If `byte` is specified and `wrbe_separate` is present: + +- `PORT__WR_EN` signal is single bit +- `PORT__WR_BE` signal has one bit for every data byte +- `PORT__WR_BE_WIDTH` parameter is the width of the above (only present for multiple-width cells) +- a given byte is written iff all of `CLK_EN` (if present), `WR_EN`, and the corresponding `WR_BE` bit are one + +This property can only be used on write ports. + + +### `rdwr` property + +This property is allowed only on `srsw` ports and describes read-write interactions. + +The possible values are: + +- `no_change`: if write is being performed (any bit of `WR_EN` is set), + reading is not performed and the `RD_DATA` keeps its old value +- `undefined`: all `RD_DATA` bits corresponding to enabled `WR_DATA` bits + have undefined value, remaining bits read from memory +- `old`: all `RD_DATA` bits get the previous value in memory +- `new`: all `RD_DATA` bits get the new value in memory (transparent write) +- `new_only`: all `RD_DATA` bits corresponding to enabled `WR_DATA` bits + get the new value, all others are undefined + +If this property is not found on an `srsw` port, `undefined` is assumed. + + +### Read data initial value and resets + +The `rdinit`, `rdarst`, and `rdsrst` are applicable only to synchronous read +ports. + +`rdinit` describes the initial value of the read port data, and can be set to +one of the following: + +- `none`: initial data is indeterminate +- `zero`: initial data is all-0 +- `any`: initial data is arbitrarily configurable, and the selected value + will be attached to the cell as `PORT__RD_INIT_VALUE` parameter +- `no_undef`: like `any`, but only 0 and 1 bits are allowed + +`rdarst` and `rdsrst` describe the asynchronous and synchronous reset capabilities. +The values are similar to `rdinit`: + +- `none`: no reset +- `zero`: reset to all-0 data +- `any`: reset to arbitrary value, the selected value + will be attached to the cell as `PORT__RD_ARST_VALUE` or + `PORT__RD_SRST_VALUE` parameter +- `no_undef`: like `any`, but only 0 and 1 bits are allowed +- `init`: reset to the initial value, as specified by `rdinit` (which must be `any` + or `no_undef` itself) + +If the capability is anything other than `none`, the reset signal +will be provided as `PORT__RD_ARST` or `PORT__RD_SRST`. + +For `rdsrst`, the priority must be additionally specified, as one of: + +- `ungated`: `RD_SRST` has priority over both `CLK_EN` and `RD_EN` (if present) +- `gated_clken`: `CLK_EN` has priority over `RD_SRST`; `RD_SRST` has priority over `RD_EN` if present +- `gated_rden`: `RD_EN` and `CLK_EN` (if present) both have priority over `RD_SRST` + +Also, `rdsrst` can optionally have `block_wr` specified, which means that sync reset +cannot be performed in the same cycle as a write. + +If not provided, `none` is assumed for all three properties. + + +### Write priority + +The `wrprio` property is only allowed on write ports and defines a priority relationship +between port — when `wrprio "B";` is used in definition of port `"A"`, and both ports +simultaneously write to the same memory cell, the value written by port `"A"` will have +precedence. + +This property is optional, and can be used multiple times as necessary. If no relationship +is described for a pair of write ports, no priority will be assumed. + + +### Write transparency + +The `wrtrans` property is only allowed on write ports and defines behavior when +another synchronous read port reads from the memory cell at the same time as the +given port writes it. The values are: + +- `old`: the read port will get the old value of the cell +- `new`: the read port will get the new value of the cell + +This property is optional, and can be used multiple times as necessary. If no relationship +is described for a pair of ports, the value read is assumed to be indeterminate. + +Note that this property is not used to describe the read value on the port itself for `srsw` +ports — for that purpose, the `rdwr` property is used instead. + + +### Optional ports + +The `optional;` property will make the pass attach a `PORT__USED` parameter +with a boolean value specifying whether a given port was meaningfully used in +mapping a given cell. Likewise, `optional_rw;` will attach `PORT__RD_USED` +and `PORT__WR_USED` the specify whether the read / write part in particular +was used. These can be useful if the mapping has some meaningful optimization +to apply for unused ports, but doesn't otherwise influence the selection process. + + +## Options + +For highly configurable cells, multiple variants may be described in one cell description. +All properties and port definitions within a RAM or port definition can be put inside +an `option` block as follows: + + option "NAME" { + + } + +The value and name of an option are arbitrary, and the selected option value +will be provided to the cell as `OPTION_` parameter. Values can be +strings or integers. + + +Likewise, for per-port options, a `portoption` block can be used: + + portoption "NAME" { + + } + +These options will be provided as `PORT__OPTION_` parameters. + +The library parser will simply expand the RAM definition for every possible combination +of option values mentioned in the RAM body, and likewise for port definitions. +This can lead to a combinatorial explosion. + +If some option values cannot be used together, a `forbid` pseudo-property can be used +to discard a given combination, eg: + + option "ABC" 1 { + portoption "DEF" "GHI" { + forbid; + } + } + +will disallow combining the RAM option `ABC = 2` with port option `DEF = "GHI"`. + + +## Ifdefs + +To allow reusing a library for multiple FPGA families with slightly differing +capabilities, `ifdef` (and `ifndef`) blocks are provided: + + ifdef IS_FANCY_FPGA_WITH_CONFIGURABLE_ASYNC_RESET { + rdarst any; + } else { + rdarst zero; + } + +Such blocks can be enabled by passing the `-D` option to the pass. diff --git a/chips/yosys/passes/memory/memory.cc b/chips/yosys/passes/memory/memory.cc new file mode 100644 index 0000000000000000000000000000000000000000..d5dec61987920245dc03e8c7de956af800feea7b --- /dev/null +++ b/chips/yosys/passes/memory/memory.cc @@ -0,0 +1,133 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/register.h" +#include "kernel/log.h" +#include +#include + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct MemoryPass : public Pass { + MemoryPass() : Pass("memory", "translate memories to basic cells") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" memory [-norom] [-nomap] [-nordff] [-nowiden] [-nosat] [-memx] [-no-rw-check] [-bram ] [selection]\n"); + log("\n"); + log("This pass calls all the other memory_* passes in a useful order:\n"); + log("\n"); + log(" opt_mem\n"); + log(" opt_mem_priority\n"); + log(" opt_mem_feedback\n"); + log(" memory_bmux2rom (skipped if called with -norom)\n"); + log(" memory_dff [-no-rw-check] (skipped if called with -nordff or -memx)\n"); + log(" opt_clean\n"); + log(" memory_share [-nowiden] [-nosat]\n"); + log(" opt_mem_widen\n"); + log(" memory_memx (when called with -memx)\n"); + log(" opt_clean\n"); + log(" memory_collect\n"); + log(" memory_bram -rules (when called with -bram)\n"); + log(" memory_map (skipped if called with -nomap)\n"); + log("\n"); + log("This converts memories to word-wide DFFs and address decoders\n"); + log("or multiport memory blocks if called with the -nomap option.\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + bool flag_norom = false; + bool flag_nomap = false; + bool flag_nordff = false; + bool flag_memx = false; + string memory_dff_opts; + string memory_bram_opts; + string memory_share_opts; + + log_header(design, "Executing MEMORY pass.\n"); + log_push(); + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + if (args[argidx] == "-norom") { + flag_norom = true; + continue; + } + if (args[argidx] == "-nomap") { + flag_nomap = true; + continue; + } + if (args[argidx] == "-nordff") { + flag_nordff = true; + continue; + } + if (args[argidx] == "-memx") { + flag_nordff = true; + flag_memx = true; + continue; + } + if (args[argidx] == "-nowiden") { + memory_share_opts += " -nowiden"; + continue; + } + if (args[argidx] == "-nosat") { + memory_share_opts += " -nosat"; + continue; + } + if (args[argidx] == "-no-rw-check") { + memory_dff_opts += " -no-rw-check"; + continue; + } + if (argidx+1 < args.size() && args[argidx] == "-bram") { + memory_bram_opts += " -rules " + args[++argidx]; + continue; + } + break; + } + extra_args(args, argidx, design); + + Pass::call(design, "opt_mem"); + Pass::call(design, "opt_mem_priority"); + Pass::call(design, "opt_mem_feedback"); + if (!flag_norom) + Pass::call(design, "memory_bmux2rom"); + if (!flag_nordff) + Pass::call(design, "memory_dff" + memory_dff_opts); + Pass::call(design, "opt_clean"); + Pass::call(design, "memory_share" + memory_share_opts); + Pass::call(design, "opt_mem_widen"); + if (flag_memx) + Pass::call(design, "memory_memx"); + Pass::call(design, "opt_clean"); + Pass::call(design, "memory_collect"); + + if (!memory_bram_opts.empty()) + Pass::call(design, "memory_bram" + memory_bram_opts); + + if (!flag_nomap) + Pass::call(design, "memory_map"); + + log_pop(); + } +} MemoryPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/memory/memory_bmux2rom.cc b/chips/yosys/passes/memory/memory_bmux2rom.cc new file mode 100644 index 0000000000000000000000000000000000000000..a3fc5a7fc5974ea2ff3218c1851ee5d2f93d5bbf --- /dev/null +++ b/chips/yosys/passes/memory/memory_bmux2rom.cc @@ -0,0 +1,87 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2022 Marcelina Kościelnicka + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "kernel/sigtools.h" +#include "kernel/mem.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct MemoryBmux2RomPass : public Pass { + MemoryBmux2RomPass() : Pass("memory_bmux2rom", "convert muxes to ROMs") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" memory_bmux2rom [options] [selection]\n"); + log("\n"); + log("This pass converts $bmux cells with constant A input to ROMs.\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + log_header(design, "Executing MEMORY_BMUX2ROM pass (converting muxes to ROMs).\n"); + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + break; + } + extra_args(args, argidx, design); + + for (auto module : design->selected_modules()) { + for (auto cell : module->selected_cells()) { + if (cell->type != ID($bmux)) + continue; + + SigSpec sig_a = cell->getPort(ID::A); + if (!sig_a.is_fully_const()) + continue; + + int abits = cell->getParam(ID::S_WIDTH).as_int(); + int width = cell->getParam(ID::WIDTH).as_int(); + if (abits < 3) + continue; + + // Ok, let's do it. + Mem mem(module, NEW_ID, width, 0, 1 << abits); + mem.attributes = cell->attributes; + + MemInit init; + init.addr = 0; + init.data = sig_a.as_const(); + init.en = Const(State::S1, width); + mem.inits.push_back(std::move(init)); + + MemRd rd; + rd.addr = cell->getPort(ID::S); + rd.data = cell->getPort(ID::Y); + rd.init_value = Const(State::Sx, width); + rd.arst_value = Const(State::Sx, width); + rd.srst_value = Const(State::Sx, width); + mem.rd_ports.push_back(std::move(rd)); + + mem.emit(); + module->remove(cell); + } + } + } +} MemoryBmux2RomPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/passes/memory/memory_bram.cc b/chips/yosys/passes/memory/memory_bram.cc new file mode 100644 index 0000000000000000000000000000000000000000..cab5a0987d5bc0e06c2dc924765fa16831d40aa9 --- /dev/null +++ b/chips/yosys/passes/memory/memory_bram.cc @@ -0,0 +1,1344 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "kernel/mem.h" +#include "kernel/ffinit.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct rules_t +{ + Design *design = nullptr; + + struct portinfo_t { + int group, index, dupidx; + int wrmode, enable, transp, clocks, clkpol; + + bool make_transp; + bool make_outreg; + int mapped_port; + }; + + struct bram_t { + PooledName name; + int variant; + + int groups, abits, dbits, init; + vector ports, wrmode, enable, transp, clocks, clkpol; + + static std::string int_list_str(const vector &values) + { + std::string str; + for (int v : values) + str += stringf("%4d", v); + return str; + } + + void dump_config() const + { + log(" bram %s # variant %d\n", name.unescape(), variant); + log(" init %d\n", init); + log(" abits %d\n", abits); + log(" dbits %d\n", dbits); + log(" groups %d\n", groups); + + log(" ports %s\n", int_list_str(ports)); + log(" wrmode%s\n", int_list_str(wrmode)); + log(" enable%s\n", int_list_str(enable)); + log(" transp%s\n", int_list_str(transp)); + log(" clocks%s\n", int_list_str(clocks)); + log(" clkpol%s\n", int_list_str(clkpol)); + log(" endbram\n"); + } + + void check_vectors() const + { + if (groups != GetSize(ports)) log_error("Bram %s variant %d has %d groups but only %d entries in 'ports'.\n", name.unescape(), variant, groups, GetSize(ports)); + if (groups != GetSize(wrmode)) log_error("Bram %s variant %d has %d groups but only %d entries in 'wrmode'.\n", name.unescape(), variant, groups, GetSize(wrmode)); + if (groups != GetSize(enable)) log_error("Bram %s variant %d has %d groups but only %d entries in 'enable'.\n", name.unescape(), variant, groups, GetSize(enable)); + if (groups != GetSize(transp)) log_error("Bram %s variant %d has %d groups but only %d entries in 'transp'.\n", name.unescape(), variant, groups, GetSize(transp)); + if (groups != GetSize(clocks)) log_error("Bram %s variant %d has %d groups but only %d entries in 'clocks'.\n", name.unescape(), variant, groups, GetSize(clocks)); + if (groups != GetSize(clkpol)) log_error("Bram %s variant %d has %d groups but only %d entries in 'clkpol'.\n", name.unescape(), variant, groups, GetSize(clkpol)); + + int group = 0; + for (auto e : enable) + if (e > dbits) log_error("Bram %s variant %d group %d has %d enable bits but only %d dbits.\n", name.unescape(), variant, group, e, dbits); + } + + vector make_portinfos() const + { + vector portinfos; + for (int i = 0; i < groups; i++) + for (int j = 0; j < ports[i]; j++) { + portinfo_t pi; + pi.group = i; + pi.index = j; + pi.dupidx = 0; + pi.wrmode = wrmode[i]; + pi.enable = enable[i]; + pi.transp = transp[i]; + pi.clocks = clocks[i]; + pi.clkpol = clkpol[i]; + pi.mapped_port = -1; + pi.make_transp = false; + pi.make_outreg = false; + portinfos.push_back(pi); + } + return portinfos; + } + + void find_variant_params(TwinePool &twines, dict &variant_params, const bram_t &other) const + { + log_assert(name == other.name); + + if (groups != other.groups) + log_error("Bram %s variants %d and %d have different values for 'groups'.\n", name.unescape(), variant, other.variant); + + if (abits != other.abits) + variant_params[ID::CFG_ABITS] = abits; + if (dbits != other.dbits) + variant_params[ID::CFG_DBITS] = dbits; + if (init != other.init) + variant_params[ID::CFG_INIT] = init; + + for (int i = 0; i < groups; i++) + { + if (ports[i] != other.ports[i]) + log_error("Bram %s variants %d and %d have different number of %c-ports.\n", name.unescape(), variant, other.variant, 'A'+i); + if (wrmode[i] != other.wrmode[i]) + variant_params[twines.add(stringf("\\CFG_WRMODE_%c", 'A' + i))] = wrmode[i]; + if (enable[i] != other.enable[i]) + variant_params[twines.add(stringf("\\CFG_ENABLE_%c", 'A' + i))] = enable[i]; + if (transp[i] != other.transp[i]) + variant_params[twines.add(stringf("\\CFG_TRANSP_%c", 'A' + i))] = transp[i]; + if (clocks[i] != other.clocks[i]) + variant_params[twines.add(stringf("\\CFG_CLOCKS_%c", 'A' + i))] = clocks[i]; + if (clkpol[i] != other.clkpol[i]) + variant_params[twines.add(stringf("\\CFG_CLKPOL_%c", 'A' + i))] = clkpol[i]; + } + } + + }; + + struct match_t { + PooledName name; + dict min_limits, max_limits; + bool or_next_if_better, make_transp, make_outreg; + char shuffle_enable; + vector>> attributes; + }; + + bool attr_icase; + dict> brams; + vector matches; + + std::string map_case(std::string value) const + { + if (attr_icase) { + for (char &c : value) + c = tolower(c); + } + return value; + } + + RTLIL::Const map_case(RTLIL::Const value) const + { + if (value.flags & RTLIL::CONST_FLAG_STRING) + return map_case(value.decode_string()); + return value; + } + + std::ifstream infile; + vector tokens; + vector labels; + int linecount; + + void syntax_error() + { + if (tokens.empty()) + log_error("Unexpected end of rules file in line %d.\n", linecount); + log_error("Syntax error in rules file line %d.\n", linecount); + } + + bool next_line() + { + string line; + while (std::getline(infile, line)) { + tokens.clear(); + labels.clear(); + linecount++; + for (string tok = next_token(line); !tok.empty(); tok = next_token(line)) { + if (tok[0] == '@') { + labels.push_back(tok.substr(1)); + continue; + } + if (tok[0] == '#') + break; + tokens.push_back(tok); + } + if (!tokens.empty()) + return true; + } + return false; + } + + bool parse_single_int(const char *stmt, int &value) + { + if (GetSize(tokens) == 2 && tokens[0] == stmt) { + value = atoi(tokens[1].c_str()); + return true; + } + return false; + } + + bool parse_int_vect(const char *stmt, vector &value) + { + if (GetSize(tokens) >= 2 && tokens[0] == stmt) { + value.resize(GetSize(tokens)-1); + for (int i = 1; i < GetSize(tokens); i++) + value[i-1] = atoi(tokens[i].c_str()); + return true; + } + return false; + } + + void parse_bram() + { + PooledName bram_name(design, design->twines().add(RTLIL::escape_id(tokens[1]))); + + if (GetSize(tokens) != 2) + syntax_error(); + + vector> lines_nolabels; + std::map>> lines_labels; + + while (next_line()) + { + if (GetSize(tokens) == 1 && tokens[0] == "endbram") + break; + if (labels.empty()) + lines_nolabels.push_back(tokens); + for (auto lab : labels) + lines_labels[lab].push_back(tokens); + } + + std::map>> variant_lines; + + if (lines_labels.empty()) + variant_lines[""] = lines_nolabels; + for (auto &it : lines_labels) { + variant_lines[it.first] = lines_nolabels; + variant_lines[it.first].insert(variant_lines[it.first].end(), it.second.begin(), it.second.end()); + } + + for (auto &it : variant_lines) + { + bram_t data; + data.name = bram_name; + data.variant = GetSize(brams[data.name]) + 1; + data.groups = 0; + data.abits = 0; + data.dbits = 0; + data.init = 0; + + for (auto &line_tokens : it.second) + { + tokens = line_tokens; + + if (parse_single_int("groups", data.groups)) + continue; + + if (parse_single_int("abits", data.abits)) + continue; + + if (parse_single_int("dbits", data.dbits)) + continue; + + if (parse_single_int("init", data.init)) + continue; + + if (parse_int_vect("ports", data.ports)) + continue; + + if (parse_int_vect("wrmode", data.wrmode)) + continue; + + if (parse_int_vect("enable", data.enable)) + continue; + + if (parse_int_vect("transp", data.transp)) + continue; + + if (parse_int_vect("clocks", data.clocks)) + continue; + + if (parse_int_vect("clkpol", data.clkpol)) + continue; + + syntax_error(); + } + + data.check_vectors(); + brams[data.name].push_back(data); + } + } + + void parse_match() + { + if (GetSize(tokens) != 2) + syntax_error(); + + match_t data; + data.name = PooledName(design, design->twines().add(RTLIL::escape_id(tokens[1]))); + data.or_next_if_better = false; + data.make_transp = false; + data.make_outreg = false; + data.shuffle_enable = 0; + + while (next_line()) + { + if (!labels.empty()) + syntax_error(); + + if (GetSize(tokens) == 1 && tokens[0] == "endmatch") { + matches.push_back(data); + break; + } + + if (GetSize(tokens) == 3 && tokens[0] == "min") { + data.min_limits[tokens[1]] = atoi(tokens[2].c_str()); + continue; + } + + if (GetSize(tokens) == 3 && tokens[0] == "max") { + data.max_limits[tokens[1]] = atoi(tokens[2].c_str()); + continue; + } + + if (GetSize(tokens) == 2 && tokens[0] == "shuffle_enable" && GetSize(tokens[1]) == 1 && 'A' <= tokens[1][0] && tokens[1][0] <= 'Z') { + data.shuffle_enable = tokens[1][0]; + continue; + } + + if (GetSize(tokens) == 1 && tokens[0] == "make_transp") { + data.make_transp = true; + continue; + } + + if (GetSize(tokens) == 1 && tokens[0] == "make_outreg") { + data.make_transp = true; + data.make_outreg = true; + continue; + } + + if (GetSize(tokens) == 1 && tokens[0] == "or_next_if_better") { + data.or_next_if_better = true; + continue; + } + + if (GetSize(tokens) >= 2 && tokens[0] == "attribute") { + data.attributes.emplace_back(); + for (int idx = 1; idx < GetSize(tokens); idx++) { + size_t c1 = tokens[idx][0] == '!' ? 1 : 0; + size_t c2 = tokens[idx].find("="); + bool exists = (c1 == 0); + IdString key = design->twines().add(RTLIL::escape_id(tokens[idx].substr(c1, c2))); + Const val = c2 != std::string::npos ? tokens[idx].substr(c2+1) : RTLIL::Const(1); + + data.attributes.back().emplace_back(exists, key, map_case(val)); + } + continue; + } + + syntax_error(); + } + } + + void parse(string filename, Design *design) + { + this->design = design; + rewrite_filename(filename); + infile.open(filename); + linecount = 0; + attr_icase = false; + + if (infile.fail()) + log_error("Can't open rules file `%s'.\n", filename); + + while (next_line()) + { + if (!labels.empty()) + syntax_error(); + + if (GetSize(tokens) == 2 && tokens[0] == "attr_icase") { + attr_icase = atoi(tokens[1].c_str()); + continue; + } + + if (tokens[0] == "bram") { + parse_bram(); + continue; + } + + if (tokens[0] == "match") { + parse_match(); + continue; + } + + syntax_error(); + } + + infile.close(); + } +}; + +bool replace_memory(Mem &mem, const rules_t &rules, FfInitVals *initvals, const rules_t::bram_t &bram, const rules_t::match_t &match, dict &match_properties, int mode) +{ + Module *module = mem.module; + + auto portinfos = bram.make_portinfos(); + int dup_count = 1; + + dict> clock_domains; + dict clock_polarities; + dict read_transp; + pool clocks_wr_ports; + pool clkpol_wr_ports; + int clocks_max = 0; + int clkpol_max = 0; + int transp_max = 0; + + clock_polarities[0] = false; + clock_polarities[1] = true; + + for (auto &pi : portinfos) { + if (pi.wrmode) { + clocks_wr_ports.insert(pi.clocks); + if (pi.clkpol > 1) + clkpol_wr_ports.insert(pi.clkpol); + } + clocks_max = max(clocks_max, pi.clocks); + clkpol_max = max(clkpol_max, pi.clkpol); + transp_max = max(transp_max, pi.transp); + } + + log(" Mapping to bram type %s (variant %d):\n", bram.name.unescape(), bram.variant); + // bram.dump_config(); + + std::vector shuffle_map; + if (match.shuffle_enable && bram.dbits >= portinfos.at(match.shuffle_enable - 'A').enable*2 && portinfos.at(match.shuffle_enable - 'A').enable > 0 && !mem.wr_ports.empty()) + { + int bucket_size = bram.dbits / portinfos.at(match.shuffle_enable - 'A').enable; + log(" Shuffle bit order to accommodate enable buckets of size %d..\n", bucket_size); + + // analyze enable structure + + std::vector en_order; + dict> bits_wr_en; + + for (int i = 0; i < mem.width; i++) { + SigSpec sig; + for (auto &port : mem.wr_ports) + sig.append(port.en[i]); + if (bits_wr_en.count(sig) == 0) + en_order.push_back(sig); + bits_wr_en[sig].push_back(i); + } + + for (auto &it : en_order) + { + for (auto bit : bits_wr_en.at(it)) + shuffle_map.push_back(bit); + + while (GetSize(shuffle_map) % bucket_size) + shuffle_map.push_back(-1); + } + + std::string message = " Results of bit order shuffling:"; + for (int v : shuffle_map) + message += stringf(" %d", v); + log("%s\n", message); + + // update mem_*, wr_*, and rd_* variables + } else { + for (int i = 0; i < mem.width; i++) + shuffle_map.push_back(i); + } + + // Align width up to dbits. + while (GetSize(shuffle_map) % bram.dbits) + shuffle_map.push_back(-1); + + // assign write ports + pair wr_clkdom; + for (int cell_port_i = 0, bram_port_i = 0; cell_port_i < GetSize(mem.wr_ports); cell_port_i++) + { + auto &port = mem.wr_ports[cell_port_i]; + + pair clkdom(port.clk, port.clk_polarity); + if (!port.clk_enable) + clkdom = pair(State::S1, false); + wr_clkdom = clkdom; + log(" Write port #%d is in clock domain %s%s.\n", + cell_port_i, clkdom.second ? "" : "!", + port.clk_enable ? log_signal(clkdom.first) : "~async~"); + + for (; bram_port_i < GetSize(portinfos); bram_port_i++) + { + auto &pi = portinfos[bram_port_i]; + + if (pi.wrmode != 1) + skip_bram_wport: + continue; + + if (port.clk_enable) { + if (pi.clocks == 0) { + log(" Bram port %c%d has incompatible clock type.\n", pi.group + 'A', pi.index + 1); + goto skip_bram_wport; + } + if (clock_domains.count(pi.clocks) && clock_domains.at(pi.clocks) != clkdom) { + log(" Bram port %c%d is in a different clock domain.\n", pi.group + 'A', pi.index + 1); + goto skip_bram_wport; + } + if (clock_polarities.count(pi.clkpol) && clock_polarities.at(pi.clkpol) != port.clk_polarity) { + log(" Bram port %c%d has incompatible clock polarity.\n", pi.group + 'A', pi.index + 1); + goto skip_bram_wport; + } + } else { + if (pi.clocks != 0) { + log(" Bram port %c%d has incompatible clock type.\n", pi.group + 'A', pi.index + 1); + goto skip_bram_wport; + } + } + + // We need to check enable compatibility of this port, as well as all + // ports that have priority over this one (because they will be involved + // in emulate_priority logic). + + for (int i = 0; i < GetSize(mem.wr_ports); i++) { + auto &oport = mem.wr_ports[i]; + if (i != cell_port_i && !oport.priority_mask[cell_port_i]) + continue; + SigBit last_en_bit = State::S1; + for (int j = 0; j < GetSize(shuffle_map); j++) { + if (shuffle_map[j] == -1) + continue; + SigBit en_bit = oport.en[shuffle_map[j]]; + if (pi.enable && j % (bram.dbits / pi.enable) == 0) + last_en_bit = en_bit; + if (last_en_bit != en_bit) { + log(" Bram port %c%d has incompatible enable structure.\n", pi.group + 'A', pi.index + 1); + goto skip_bram_wport; + } + } + } + + log(" Mapped to bram port %c%d.\n", pi.group + 'A', pi.index + 1); + pi.mapped_port = cell_port_i; + + if (port.clk_enable) { + clock_domains[pi.clocks] = clkdom; + clock_polarities[pi.clkpol] = clkdom.second; + } + + bram_port_i++; + goto mapped_wr_port; + } + + log(" Failed to map write port #%d.\n", cell_port_i); + return false; + mapped_wr_port:; + } + + // housekeeping stuff for growing more read ports and restarting read port assignments + + int grow_read_ports_cursor = -1; + bool try_growing_more_read_ports = false; + auto backup_clock_domains = clock_domains; + auto backup_clock_polarities = clock_polarities; + + if (0) { +grow_read_ports:; + vector new_portinfos; + for (auto &pi : portinfos) { + if (pi.wrmode == 0) { + pi.mapped_port = -1; + pi.make_outreg = false; + pi.make_transp = false; + } + new_portinfos.push_back(pi); + if (pi.dupidx == dup_count-1) { + if (pi.clocks && !clocks_wr_ports[pi.clocks]) + pi.clocks += clocks_max; + if (pi.clkpol > 1 && !clkpol_wr_ports[pi.clkpol]) + pi.clkpol += clkpol_max; + if (pi.transp > 1) + pi.transp += transp_max; + pi.dupidx++; + new_portinfos.push_back(pi); + } + } + try_growing_more_read_ports = false; + portinfos.swap(new_portinfos); + clock_domains = backup_clock_domains; + clock_polarities = backup_clock_polarities; + dup_count++; + } + + read_transp.clear(); + read_transp[0] = false; + read_transp[1] = true; + + // assign read ports + + for (int cell_port_i = 0; cell_port_i < GetSize(mem.rd_ports); cell_port_i++) + { + auto &port = mem.rd_ports[cell_port_i]; + bool transp = false; + bool non_transp = false; + + if (port.clk_enable) { + for (int i = 0; i < GetSize(mem.wr_ports); i++) + if (port.transparency_mask[i]) + transp = true; + else if (!port.collision_x_mask[i]) + non_transp = true; + } + + pair clkdom(port.clk, port.clk_polarity); + if (!port.clk_enable) + clkdom = pair(State::S1, false); + + log(" Read port #%d is in clock domain %s%s.\n", + cell_port_i, clkdom.second ? "" : "!", + port.clk_enable ? log_signal(clkdom.first) : "~async~"); + + for (int bram_port_i = 0; bram_port_i < GetSize(portinfos); bram_port_i++) + { + auto &pi = portinfos[bram_port_i]; + + if (pi.wrmode != 0 || pi.mapped_port >= 0) + skip_bram_rport: + continue; + + if (port.clk_enable) { + if (pi.clocks == 0) { + if (match.make_outreg) { + pi.make_outreg = true; + goto skip_bram_rport_clkcheck; + } + log(" Bram port %c%d.%d has incompatible clock type.\n", pi.group + 'A', pi.index + 1, pi.dupidx + 1); + goto skip_bram_rport; + } + if (clock_domains.count(pi.clocks) && clock_domains.at(pi.clocks) != clkdom) { + log(" Bram port %c%d.%d is in a different clock domain.\n", pi.group + 'A', pi.index + 1, pi.dupidx + 1); + goto skip_bram_rport; + } + if (clock_polarities.count(pi.clkpol) && clock_polarities.at(pi.clkpol) != port.clk_polarity) { + log(" Bram port %c%d.%d has incompatible clock polarity.\n", pi.group + 'A', pi.index + 1, pi.dupidx + 1); + goto skip_bram_rport; + } + if (non_transp && read_transp.count(pi.transp) && read_transp.at(pi.transp)) { + log(" Bram port %c%d.%d has incompatible read transparency.\n", pi.group + 'A', pi.index + 1, pi.dupidx + 1); + goto skip_bram_rport; + } + if (transp && (non_transp || (read_transp.count(pi.transp) && !read_transp.at(pi.transp)))) { + if (match.make_transp) { + pi.make_transp = true; + } else { + log(" Bram port %c%d.%d has incompatible read transparency.\n", pi.group + 'A', pi.index + 1, pi.dupidx + 1); + goto skip_bram_rport; + } + } + } else { + if (pi.clocks != 0) { + log(" Bram port %c%d.%d has incompatible clock type.\n", pi.group + 'A', pi.index + 1, pi.dupidx + 1); + goto skip_bram_rport; + } + } + + skip_bram_rport_clkcheck: + log(" Mapped to bram port %c%d.%d.\n", pi.group + 'A', pi.index + 1, pi.dupidx + 1); + pi.mapped_port = cell_port_i; + + if (pi.clocks) { + clock_domains[pi.clocks] = clkdom; + clock_polarities[pi.clkpol] = clkdom.second; + if (non_transp) + read_transp[pi.transp] = false; + if (transp && !pi.make_transp) + read_transp[pi.transp] = true; + } + + if (grow_read_ports_cursor < cell_port_i) { + grow_read_ports_cursor = cell_port_i; + try_growing_more_read_ports = true; + } + + goto mapped_rd_port; + } + + log(" Failed to map read port #%d.\n", cell_port_i); + if (try_growing_more_read_ports) { + log(" Growing more read ports by duplicating bram cells.\n"); + goto grow_read_ports; + } + return false; + mapped_rd_port:; + } + + // update properties and re-check conditions + + int dcells = GetSize(shuffle_map) / bram.dbits; + int acells = (mem.size + (1 << bram.abits) - 1) / (1 << bram.abits); + if (mode <= 1) + { + match_properties["dups"] = dup_count; + match_properties["waste"] = match_properties["dups"] * match_properties["bwaste"]; + + int cells = dcells * acells; + match_properties["efficiency"] = (100 * match_properties["bits"]) / (dup_count * cells * bram.dbits * (1 << bram.abits)); + + match_properties["dcells"] = dcells; + match_properties["acells"] = acells; + match_properties["cells"] = cells * dup_count; + + log(" Updated properties: dups=%d waste=%d efficiency=%d\n", + match_properties["dups"], match_properties["waste"], match_properties["efficiency"]); + + for (auto it : match.min_limits) { + if (!match_properties.count(it.first)) + log_error("Unknown property '%s' in match rule for bram type %s.\n", + it.first, match.name.unescape()); + if (match_properties[it.first] >= it.second) + continue; + log(" Rule for bram type %s rejected: requirement 'min %s %d' not met.\n", + match.name.unescape(), it.first, it.second); + return false; + } + for (auto it : match.max_limits) { + if (!match_properties.count(it.first)) + log_error("Unknown property '%s' in match rule for bram type %s.\n", + it.first, match.name.unescape()); + if (match_properties[it.first] <= it.second) + continue; + log(" Rule for bram type %s rejected: requirement 'max %s %d' not met.\n", + match.name.unescape(), it.first, it.second); + return false; + } + + for (const auto &sums : match.attributes) { + bool found = false; + for (const auto &term : sums) { + bool exists = std::get<0>(term); + IdString key = std::get<1>(term); + const Const &value = std::get<2>(term); + auto it = mem.attributes.find(key); + if (it == mem.attributes.end()) { + if (exists) + continue; + found = true; + break; + } + else if (!exists) + continue; + if (rules.map_case(it->second) != value) + continue; + found = true; + break; + } + if (!found) { + std::stringstream ss; + bool exists = std::get<0>(sums.front()); + if (!exists) + ss << "!"; + IdString key = std::get<1>(sums.front()); + ss << PooledName(mem.module, key).unescape(); + const Const &value = rules.map_case(std::get<2>(sums.front())); + if (exists && value != Const(1)) + ss << "=\"" << value.decode_string() << "\""; + + log(" Rule for bram type %s rejected: requirement 'attribute %s ...' not met.\n", + match.name.unescape(), ss.str()); + return false; + } + } + + if (mode == 1) + return true; + } + + // At this point we are commited to replacing the RAM, and can mutate mem. + + // Apply make_outreg and make_transp where necessary. + for (auto &pi : portinfos) { + if (pi.mapped_port == -1 || pi.wrmode) + continue; + auto &port = mem.rd_ports[pi.mapped_port]; + if (pi.make_outreg) { + mem.extract_rdff(pi.mapped_port, initvals); + } else if (port.clk_enable) { + if (!pi.enable && port.en != State::S1) + mem.emulate_rden(pi.mapped_port, initvals); + else + mem.emulate_reset(pi.mapped_port, true, true, true, initvals); + } + if (pi.make_transp) { + for (int i = 0; i < GetSize(mem.wr_ports); i++) + if (port.transparency_mask[i]) + mem.emulate_transparency(i, pi.mapped_port, initvals); + } + } + + // We don't really support priorities, emulate them. + for (int i = 0; i < GetSize(mem.wr_ports); i++) + for (int j = 0; j < i; j++) + mem.emulate_priority(j, i, initvals); + + // Swizzle the init data. Do this before changing mem.width, so that get_init_data works. + bool cell_init = !mem.inits.empty(); + vector initdata; + if (cell_init) { + Const initparam = mem.get_init_data(); + initdata.reserve(mem.size); + for (int i = 0; i < mem.size; i++) { + std::vector val; + for (auto idx : shuffle_map) { + if (idx == -1) + val.push_back(State::Sx); + else + val.push_back(initparam[mem.width * i + idx]); + } + initdata.push_back(Const(val)); + } + } + + // Now the big swizzle. + mem.width = GetSize(shuffle_map); + + // Swizzle write ports. + for (auto &port : mem.wr_ports) { + SigSpec new_en, new_data; + SigBit en_bit = State::S1; + for (auto idx : shuffle_map) { + if (idx == -1) { + new_data.append(State::Sx); + } else { + new_data.append(port.data[idx]); + en_bit = port.en[idx]; + } + new_en.append(en_bit); + } + port.en = new_en; + port.data = new_data; + } + + // Swizzle read ports. + for (auto &port : mem.rd_ports) { + SigSpec new_data = module->addWire(NEW_ID, mem.width); + Const new_init_value = Const(State::Sx, mem.width); + Const new_arst_value = Const(State::Sx, mem.width); + Const new_srst_value = Const(State::Sx, mem.width); + for (int i = 0; i < mem.width; i++) + if (shuffle_map[i] != -1) { + module->connect(port.data[shuffle_map[i]], new_data[i]); + new_init_value.set(i, port.init_value[shuffle_map[i]]); + new_arst_value.set(i, port.arst_value[shuffle_map[i]]); + new_srst_value.set(i, port.srst_value[shuffle_map[i]]); + } + port.data = new_data; + port.init_value = new_init_value; + port.arst_value = new_arst_value; + port.srst_value = new_srst_value; + } + + // prepare variant parameters + + dict variant_params; + for (auto &other_bram : rules.brams.at(bram.name)) + bram.find_variant_params(module->twines(), variant_params, other_bram); + + // actually replace that memory cell + + dict> dout_cache; + + for (int grid_d = 0; grid_d < dcells; grid_d++) + { + for (int grid_a = 0; grid_a < acells; grid_a++) + for (int dupidx = 0; dupidx < dup_count; dupidx++) + { + Cell *c = module->addCell(module->uniquify(stringf("%s.%d.%d.%d", mem.memid.str(), grid_d, grid_a, dupidx)), bram.name); + log(" Creating %s cell at grid position <%d %d %d>: %s\n", bram.name.unescape(), grid_d, grid_a, dupidx, c); + + for (auto &vp : variant_params) + c->setParam(vp.first, vp.second); + + if (cell_init) { + int init_offset = grid_a*(1 << bram.abits) - mem.start_offset; + int init_shift = grid_d*bram.dbits; + int init_size = (1 << bram.abits); + Const initparam(State::Sx, init_size*bram.dbits); + for (int i = 0; i < init_size; i++) + for (int j = 0; j < bram.dbits; j++) + if (init_offset+i < GetSize(initdata) && init_offset+i >= 0) + initparam.set(i*bram.dbits+j, initdata[init_offset+i][init_shift+j]); + else + initparam.set(i*bram.dbits+j, State::Sx); + c->setParam(ID::INIT, initparam); + } + + for (auto &pi : portinfos) + { + if (pi.dupidx != dupidx) + continue; + + string prefix = stringf("%c%d", pi.group + 'A', pi.index + 1); + const char *pf = prefix.c_str(); + + if (pi.clocks && clock_domains.count(pi.clocks)) + c->setPort(stringf("\\CLK%d", (pi.clocks-1) % clocks_max + 1), clock_domains.at(pi.clocks).first); + if (pi.clkpol > 1 && clock_polarities.count(pi.clkpol)) + c->setParam(stringf("\\CLKPOL%d", (pi.clkpol-1) % clkpol_max + 1), clock_polarities.at(pi.clkpol)); + if (pi.transp > 1 && read_transp.count(pi.transp)) + c->setParam(stringf("\\TRANSP%d", (pi.transp-1) % transp_max + 1), read_transp.at(pi.transp)); + + SigSpec addr_ok; + SigSpec sig_addr; + if (pi.mapped_port >= 0) { + if (pi.wrmode == 1) + sig_addr = mem.wr_ports[pi.mapped_port].addr; + else + sig_addr = mem.rd_ports[pi.mapped_port].addr; + } + + if (GetSize(sig_addr) > bram.abits) { + SigSpec extra_addr = sig_addr.extract(bram.abits, GetSize(sig_addr) - bram.abits); + SigSpec extra_addr_sel = SigSpec(grid_a, GetSize(extra_addr)); + addr_ok = module->Eq(NEW_ID, extra_addr, extra_addr_sel); + } + + sig_addr.extend_u0(bram.abits); + c->setPort(stringf("\\%sADDR", pf), sig_addr); + + if (pi.wrmode == 1) { + if (pi.mapped_port == -1) + { + if (pi.enable) + c->setPort(stringf("\\%sEN", pf), Const(State::S0, pi.enable)); + continue; + } + + auto &port = mem.wr_ports[pi.mapped_port]; + SigSpec sig_data = port.data.extract(grid_d * bram.dbits, bram.dbits); + c->setPort(stringf("\\%sDATA", pf), sig_data); + + if (pi.enable) + { + SigSpec sig_en; + int stride = bram.dbits / pi.enable; + for (int i = 0; i < pi.enable; i++) + sig_en.append(port.en[stride * i + grid_d * bram.dbits]); + + if (!addr_ok.empty()) + sig_en = module->Mux(NEW_ID, SigSpec(0, GetSize(sig_en)), sig_en, addr_ok); + + c->setPort(stringf("\\%sEN", pf), sig_en); + + } + } else { + if (pi.mapped_port == -1) + { + if (pi.enable) + c->setPort(stringf("\\%sEN", pf), State::S0); + continue; + } + auto &port = mem.rd_ports[pi.mapped_port]; + SigSpec sig_data = port.data.extract(grid_d * bram.dbits, bram.dbits); + + SigSpec bram_dout = module->addWire(NEW_ID, bram.dbits); + c->setPort(stringf("\\%sDATA", pf), bram_dout); + + SigSpec addr_ok_q = addr_ok; + if (port.clk_enable && !addr_ok.empty()) { + addr_ok_q = module->addWire(NEW_ID); + module->addDffe(NEW_ID, port.clk, port.en, addr_ok, addr_ok_q, port.clk_polarity); + } + + dout_cache[sig_data].first.append(addr_ok_q); + dout_cache[sig_data].second.append(bram_dout); + + if (pi.enable) { + SigSpec sig_en = port.en; + if (!addr_ok.empty()) + sig_en = module->And(NEW_ID, sig_en, addr_ok); + c->setPort(stringf("\\%sEN", pf), sig_en); + } + } + } + } + } + + for (auto &it : dout_cache) + { + if (it.second.first.empty()) + { + log_assert(GetSize(it.first) == GetSize(it.second.second)); + module->connect(it.first, it.second.second); + } + else + { + log_assert(GetSize(it.first)*GetSize(it.second.first) == GetSize(it.second.second)); + module->addPmux(NEW_ID, SigSpec(State::Sx, GetSize(it.first)), it.second.second, it.second.first, it.first); + } + } + + mem.remove(); + return true; +} + +void handle_memory(Mem &mem, const rules_t &rules, FfInitVals *initvals) +{ + log("Processing %s.%s:\n", mem.module, mem.memid.unescape()); + mem.narrow(); + + bool cell_init = !mem.inits.empty(); + + dict match_properties; + match_properties["words"] = mem.size; + match_properties["abits"] = ceil_log2(mem.size); + match_properties["dbits"] = mem.width; + match_properties["wports"] = GetSize(mem.wr_ports); + match_properties["rports"] = GetSize(mem.rd_ports); + match_properties["bits"] = match_properties["words"] * match_properties["dbits"]; + match_properties["ports"] = match_properties["wports"] + match_properties["rports"]; + + std::string message = " Properties:"; + for (auto &it : match_properties) + message += stringf(" %s=%d", it.first, it.second); + log("%s\n", message); + + pool> failed_brams; + dict, tuple> best_rule_cache; + + for (int i = 0; i < GetSize(rules.matches); i++) + { + auto &match = rules.matches.at(i); + + if (!rules.brams.count(rules.matches[i].name)) + log_error("No bram description for resource %s found!\n", rules.matches[i].name.unescape()); + + for (int vi = 0; vi < GetSize(rules.brams.at(match.name)); vi++) + { + auto &bram = rules.brams.at(match.name).at(vi); + bool or_next_if_better = match.or_next_if_better || vi+1 < GetSize(rules.brams.at(match.name)); + + int avail_rd_ports = 0; + int avail_wr_ports = 0; + for (int j = 0; j < bram.groups; j++) { + if (GetSize(bram.wrmode) < j || bram.wrmode.at(j) == 0) + avail_rd_ports += GetSize(bram.ports) < j ? bram.ports.at(j) : 0; + if (GetSize(bram.wrmode) < j || bram.wrmode.at(j) != 0) + avail_wr_ports += GetSize(bram.ports) < j ? bram.ports.at(j) : 0; + } + + log(" Checking rule #%d for bram type %s (variant %d):\n", i+1, bram.name.unescape(), bram.variant); + log(" Bram geometry: abits=%d dbits=%d wports=%d rports=%d\n", bram.abits, bram.dbits, avail_wr_ports, avail_rd_ports); + + int dups = avail_rd_ports ? (match_properties["rports"] + avail_rd_ports - 1) / avail_rd_ports : 1; + match_properties["dups"] = dups; + + log(" Estimated number of duplicates for more read ports: dups=%d\n", match_properties["dups"]); + + int aover = match_properties["words"] % (1 << bram.abits); + int awaste = aover ? (1 << bram.abits) - aover : 0; + match_properties["awaste"] = awaste; + + int dover = match_properties["dbits"] % bram.dbits; + int dwaste = dover ? bram.dbits - dover : 0; + match_properties["dwaste"] = dwaste; + + int bwaste = awaste * bram.dbits + dwaste * (1 << bram.abits) - awaste * dwaste; + match_properties["bwaste"] = bwaste; + + int waste = match_properties["dups"] * bwaste; + match_properties["waste"] = waste; + + int cells = ((match_properties["dbits"] + bram.dbits - 1) / bram.dbits) * ((match_properties["words"] + (1 << bram.abits) - 1) / (1 << bram.abits)); + int efficiency = (100 * match_properties["bits"]) / (dups * cells * bram.dbits * (1 << bram.abits)); + match_properties["efficiency"] = efficiency; + + if (failed_brams.count(pair(bram.name, bram.variant))) + goto next_match_rule; + + log(" Metrics for %s: awaste=%d dwaste=%d bwaste=%d waste=%d efficiency=%d\n", + match.name.unescape(), awaste, dwaste, bwaste, waste, efficiency); + + if (cell_init && bram.init == 0) { + log(" Rule #%d for bram type %s (variant %d) rejected: cannot be initialized.\n", + i+1, bram.name.unescape(), bram.variant); + goto next_match_rule; + } + + for (auto it : match.min_limits) { + if (it.first == "waste" || it.first == "dups" || it.first == "acells" || it.first == "dcells" || it.first == "cells") + continue; + if (!match_properties.count(it.first)) + log_error("Unknown property '%s' in match rule for bram type %s.\n", + it.first, match.name.unescape()); + if (match_properties[it.first] >= it.second) + continue; + log(" Rule #%d for bram type %s (variant %d) rejected: requirement 'min %s %d' not met.\n", + i+1, bram.name.unescape(), bram.variant, it.first, it.second); + goto next_match_rule; + } + + for (auto it : match.max_limits) { + if (it.first == "acells" || it.first == "dcells" || it.first == "cells") + continue; + if (!match_properties.count(it.first)) + log_error("Unknown property '%s' in match rule for bram type %s.\n", + it.first, match.name.unescape()); + if (match_properties[it.first] <= it.second) + continue; + log(" Rule #%d for bram type %s (variant %d) rejected: requirement 'max %s %d' not met.\n", + i+1, bram.name.unescape(), bram.variant, it.first, it.second); + goto next_match_rule; + } + + for (const auto &sums : match.attributes) { + bool found = false; + for (const auto &term : sums) { + bool exists = std::get<0>(term); + IdString key = std::get<1>(term); + const Const &value = std::get<2>(term); + auto it = mem.attributes.find(key); + if (it == mem.attributes.end()) { + if (exists) + continue; + found = true; + break; + } + else if (!exists) + continue; + if (rules.map_case(it->second) != value) + continue; + found = true; + break; + } + if (!found) { + std::stringstream ss; + bool exists = std::get<0>(sums.front()); + if (!exists) + ss << "!"; + IdString key = std::get<1>(sums.front()); + ss << PooledName(mem.module, key).unescape(); + const Const &value = rules.map_case(std::get<2>(sums.front())); + if (exists && value != Const(1)) + ss << "=\"" << value.decode_string() << "\""; + + log(" Rule for bram type %s (variant %d) rejected: requirement 'attribute %s ...' not met.\n", + bram.name.unescape(), bram.variant, ss.str()); + goto next_match_rule; + } + } + + log(" Rule #%d for bram type %s (variant %d) accepted.\n", i+1, bram.name.unescape(), bram.variant); + + if (or_next_if_better || !best_rule_cache.empty()) + { + if (or_next_if_better && i+1 == GetSize(rules.matches) && vi+1 == GetSize(rules.brams.at(match.name))) + log_error("Found 'or_next_if_better' in last match rule.\n"); + + if (!replace_memory(mem, rules, initvals, bram, match, match_properties, 1)) { + log(" Mapping to bram type %s failed.\n", match.name.unescape()); + failed_brams.insert(pair(bram.name, bram.variant)); + goto next_match_rule; + } + + log(" Storing for later selection.\n"); + best_rule_cache[pair(i, vi)] = tuple(match_properties["efficiency"], -match_properties["cells"], -match_properties["acells"]); + + next_match_rule: + if (or_next_if_better || best_rule_cache.empty()) + continue; + + log(" Selecting best of %d rules:\n", GetSize(best_rule_cache)); + pair best_rule = best_rule_cache.begin()->first; + + for (auto &it : best_rule_cache) { + if (it.second > best_rule_cache[best_rule]) + best_rule = it.first; + log(" Efficiency for rule %d.%d: efficiency=%d, cells=%d, acells=%d\n", it.first.first+1, it.first.second+1, + std::get<0>(it.second), -std::get<1>(it.second), -std::get<2>(it.second)); + } + + log(" Selected rule %d.%d with efficiency %d.\n", best_rule.first+1, best_rule.second+1, std::get<0>(best_rule_cache[best_rule])); + best_rule_cache.clear(); + + auto &best_bram = rules.brams.at(rules.matches.at(best_rule.first).name).at(best_rule.second); + if (!replace_memory(mem, rules, initvals, best_bram, rules.matches.at(best_rule.first), match_properties, 2)) + log_error("Mapping to bram type %s (variant %d) after pre-selection failed.\n", best_bram.name.unescape(), best_bram.variant); + return; + } + + if (!replace_memory(mem, rules, initvals, bram, match, match_properties, 0)) { + log(" Mapping to bram type %s failed.\n", match.name.unescape()); + failed_brams.insert(pair(bram.name, bram.variant)); + goto next_match_rule; + } + return; + } + } + + log(" No acceptable bram resources found.\n"); +} + +struct MemoryBramPass : public Pass { + MemoryBramPass() : Pass("memory_bram", "map memories to block rams") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" memory_bram -rules [selection]\n"); + log("\n"); + log("This pass converts the multi-port $mem memory cells into block ram instances.\n"); + log("The given rules file describes the available resources and how they should be\n"); + log("used.\n"); + log("\n"); + log("The rules file contains configuration options, a set of block ram description\n"); + log("and a sequence of match rules.\n"); + log("\n"); + log("The option 'attr_icase' configures how attribute values are matched. The value 0\n"); + log("means case-sensitive, 1 means case-insensitive.\n"); + log("\n"); + log("A block ram description looks like this:\n"); + log("\n"); + log(" bram RAMB1024X32 # name of BRAM cell\n"); + log(" init 1 # set to '1' if BRAM can be initialized\n"); + log(" abits 10 # number of address bits\n"); + log(" dbits 32 # number of data bits\n"); + log(" groups 2 # number of port groups\n"); + log(" ports 1 1 # number of ports in each group\n"); + log(" wrmode 1 0 # set to '1' if this groups is write ports\n"); + log(" enable 4 1 # number of enable bits\n"); + log(" transp 0 2 # transparent (for read ports)\n"); + log(" clocks 1 2 # clock configuration\n"); + log(" clkpol 2 2 # clock polarity configuration\n"); + log(" endbram\n"); + log("\n"); + log("For the option 'transp' the value 0 means non-transparent, 1 means transparent\n"); + log("and a value greater than 1 means configurable. All groups with the same\n"); + log("value greater than 1 share the same configuration bit.\n"); + log("\n"); + log("For the option 'clocks' the value 0 means non-clocked, and a value greater\n"); + log("than 0 means clocked. All groups with the same value share the same clock\n"); + log("signal.\n"); + log("\n"); + log("For the option 'clkpol' the value 0 means negative edge, 1 means positive edge\n"); + log("and a value greater than 1 means configurable. All groups with the same value\n"); + log("greater than 1 share the same configuration bit.\n"); + log("\n"); + log("Using the same bram name in different bram blocks will create different variants\n"); + log("of the bram. Verilog configuration parameters for the bram are created as\n"); + log("needed.\n"); + log("\n"); + log("It is also possible to create variants by repeating statements in the bram block\n"); + log("and appending '@