From 1d0f0d668ade740c928c66c400476924abf62384 Mon Sep 17 00:00:00 2001 From: Clifford Wolf Date: Thu, 31 Mar 2016 08:43:28 +0200 Subject: Renamed opt_const to opt_expr --- backends/btor/verilog2btor.sh | 2 +- manual/APPNOTE_012_Verilog_to_BTOR.tex | 4 +- manual/CHAPTER_Optimize.tex | 16 +- manual/CHAPTER_Overview.tex | 2 +- manual/PRESENTATION_ExSyn.tex | 6 +- passes/opt/Makefile.inc | 2 +- passes/opt/opt.cc | 28 +- passes/opt/opt_const.cc | 1163 ------------------------------- passes/opt/opt_expr.cc | 1164 ++++++++++++++++++++++++++++++++ passes/sat/miter.cc | 8 +- techlibs/common/prep.cc | 4 +- techlibs/common/synth.cc | 4 +- techlibs/common/techmap.v | 4 +- techlibs/ice40/ice40_opt.cc | 8 +- techlibs/ice40/synth_ice40.cc | 4 +- 15 files changed, 1210 insertions(+), 1209 deletions(-) delete mode 100644 passes/opt/opt_const.cc create mode 100644 passes/opt/opt_expr.cc diff --git a/backends/btor/verilog2btor.sh b/backends/btor/verilog2btor.sh index 1c537d5bd..dfd7f1a85 100755 --- a/backends/btor/verilog2btor.sh +++ b/backends/btor/verilog2btor.sh @@ -22,7 +22,7 @@ hierarchy -top $3; hierarchy -libdir $DIR; hierarchy -check; proc; -opt; opt_const -mux_undef; opt; +opt; opt_expr -mux_undef; opt; rename -hide;;; #techmap -map +/pmux2mux.v;; splice; opt; diff --git a/manual/APPNOTE_012_Verilog_to_BTOR.tex b/manual/APPNOTE_012_Verilog_to_BTOR.tex index 245a6b0b8..1bc277876 100644 --- a/manual/APPNOTE_012_Verilog_to_BTOR.tex +++ b/manual/APPNOTE_012_Verilog_to_BTOR.tex @@ -208,7 +208,7 @@ read_verilog -sv $1; hierarchy -top $3; hierarchy -libdir $DIR; hierarchy -check; proc; opt; -opt_const -mux_undef; opt; +opt_expr -mux_undef; opt; rename -hide;;; splice; opt; memory_dff -wr_only; memory_collect;; @@ -263,7 +263,7 @@ read_verilog -sv $1; hierarchy -top $3; hierarchy -libdir $DIR; hierarchy -check; proc; opt; -opt_const -mux_undef; opt; +opt_expr -mux_undef; opt; rename -hide;;; splice; opt; memory;; diff --git a/manual/CHAPTER_Optimize.tex b/manual/CHAPTER_Optimize.tex index d09b3c478..07f5a26e6 100644 --- a/manual/CHAPTER_Optimize.tex +++ b/manual/CHAPTER_Optimize.tex @@ -15,7 +15,7 @@ passes that each perform a simple optimization: \begin{itemize} \item Once at the beginning of {\tt opt}: \begin{itemize} -\item {\tt opt\_const} +\item {\tt opt\_expr} \item {\tt opt\_share -nomux} \end{itemize} \item Repeat until result is stable: @@ -25,13 +25,13 @@ passes that each perform a simple optimization: \item {\tt opt\_share} \item {\tt opt\_rmdff} \item {\tt opt\_clean} -\item {\tt opt\_const} +\item {\tt opt\_expr} \end{itemize} \end{itemize} The following section describes each of the {\tt opt\_*} passes. -\subsection{The opt\_const pass} +\subsection{The opt\_expr pass} This pass performs const folding on the internal combinational cell types described in Chap.~\ref{chapter:celllib}. This means a cell with all constant @@ -57,11 +57,11 @@ this pass can also optimize cells with some constant inputs. $a$ & 1 & $a$ \\ 1 & $b$ & $b$ \\ \end{tabular} - \caption{Const folding rules for {\tt\$\_AND\_} cells as used in {\tt opt\_const}.} - \label{tab:opt_const_and} + \caption{Const folding rules for {\tt\$\_AND\_} cells as used in {\tt opt\_expr}.} + \label{tab:opt_expr_and} \end{table} -Table~\ref{tab:opt_const_and} shows the replacement rules used for optimizing +Table~\ref{tab:opt_expr_and} shows the replacement rules used for optimizing an {\tt\$\_AND\_} gate. The first three rules implement the obvious const folding rules. Note that `any' might include dynamic values calculated by other parts of the circuit. The following three lines propagate undef (X) states. @@ -76,10 +76,10 @@ an undef value or a 1 and therefore the output can be set to undef. The last two lines simply replace an {\tt\$\_AND\_} gate with one constant-1 input with a buffer. -Besides this basic const folding the {\tt opt\_const} pass can replace 1-bit wide +Besides this basic const folding the {\tt opt\_expr} pass can replace 1-bit wide {\tt \$eq} and {\tt \$ne} cells with buffers or not-gates if one input is constant. -The {\tt opt\_const} pass is very conservative regarding optimizing {\tt \$mux} cells, +The {\tt opt\_expr} pass is very conservative regarding optimizing {\tt \$mux} cells, as these cells are often used to model decision-trees and breaking these trees can interfere with other optimizations. diff --git a/manual/CHAPTER_Overview.tex b/manual/CHAPTER_Overview.tex index 032c0f8c3..4ce314825 100644 --- a/manual/CHAPTER_Overview.tex +++ b/manual/CHAPTER_Overview.tex @@ -488,7 +488,7 @@ select.cc}, {\tt show.cc}, \dots) and a couple of other small utility libraries. \item {\tt passes/} \\ This directory contains a subdirectory for each pass or group of passes. For example as of this writing the directory {\tt passes/opt/} contains the code for seven -passes: {\tt opt}, {\tt opt\_const}, {\tt opt\_muxtree}, {\tt opt\_reduce}, +passes: {\tt opt}, {\tt opt\_expr}, {\tt opt\_muxtree}, {\tt opt\_reduce}, {\tt opt\_rmdff}, {\tt opt\_rmunused} and {\tt opt\_share}. \item {\tt techlibs/} \\ diff --git a/manual/PRESENTATION_ExSyn.tex b/manual/PRESENTATION_ExSyn.tex index 1b56374d6..b57063c9c 100644 --- a/manual/PRESENTATION_ExSyn.tex +++ b/manual/PRESENTATION_ExSyn.tex @@ -144,7 +144,7 @@ The {\tt opt} command implements a series of simple optimizations. It also is a macro command that calls other commands: \begin{lstlisting}[xleftmargin=0.5cm, basicstyle=\ttfamily\fontsize{8pt}{10pt}\selectfont, language=ys] -opt_const # const folding +opt_expr # const folding and simple expression rewriting opt_share -nomux # merging identical cells do @@ -153,7 +153,7 @@ do opt_share # merging identical cells opt_rmdff # remove/simplify registers with constant inputs opt_clean # remove unused objects (cells, wires) from design - opt_const # const folding + opt_expr # const folding and simple expression rewriting while [changed design] \end{lstlisting} @@ -161,7 +161,7 @@ The command {\tt clean} can be used as alias for {\tt opt\_clean}. And {\tt ;;} can be used as shortcut for {\tt clean}. For example: \begin{lstlisting}[xleftmargin=0.5cm, basicstyle=\ttfamily\fontsize{8pt}{10pt}\selectfont, language=ys] -proc; opt; memory; opt_const;; fsm;; +proc; opt; memory; opt_expr;; fsm;; \end{lstlisting} \end{frame} diff --git a/passes/opt/Makefile.inc b/passes/opt/Makefile.inc index 43defb788..dd9088a66 100644 --- a/passes/opt/Makefile.inc +++ b/passes/opt/Makefile.inc @@ -5,7 +5,7 @@ OBJS += passes/opt/opt_muxtree.o OBJS += passes/opt/opt_reduce.o OBJS += passes/opt/opt_rmdff.o OBJS += passes/opt/opt_clean.o -OBJS += passes/opt/opt_const.o +OBJS += passes/opt/opt_expr.o ifneq ($(SMALL),1) OBJS += passes/opt/share.o diff --git a/passes/opt/opt.cc b/passes/opt/opt.cc index f5389d8ee..db35a1775 100644 --- a/passes/opt/opt.cc +++ b/passes/opt/opt.cc @@ -37,7 +37,7 @@ struct OptPass : public Pass { log("a series of trivial optimizations and cleanups. This pass executes the other\n"); log("passes in the following order:\n"); log("\n"); - log(" opt_const [-mux_undef] [-mux_bool] [-undriven] [-clkinv] [-fine] [-full] [-keepdc]\n"); + log(" opt_expr [-mux_undef] [-mux_bool] [-undriven] [-clkinv] [-fine] [-full] [-keepdc]\n"); log(" opt_share [-share_all] -nomux\n"); log("\n"); log(" do\n"); @@ -46,13 +46,13 @@ struct OptPass : public Pass { log(" opt_share [-share_all]\n"); log(" opt_rmdff\n"); log(" opt_clean [-purge]\n"); - log(" opt_const [-mux_undef] [-mux_bool] [-undriven] [-clkinv] [-fine] [-full] [-keepdc]\n"); + log(" opt_expr [-mux_undef] [-mux_bool] [-undriven] [-clkinv] [-fine] [-full] [-keepdc]\n"); log(" while \n"); log("\n"); log("When called with -fast the following script is used instead:\n"); log("\n"); log(" do\n"); - log(" opt_const [-mux_undef] [-mux_bool] [-undriven] [-clkinv] [-fine] [-full] [-keepdc]\n"); + log(" opt_expr [-mux_undef] [-mux_bool] [-undriven] [-clkinv] [-fine] [-full] [-keepdc]\n"); log(" opt_share [-share_all]\n"); log(" opt_rmdff\n"); log(" opt_clean [-purge]\n"); @@ -66,7 +66,7 @@ struct OptPass : public Pass { virtual void execute(std::vector args, RTLIL::Design *design) { std::string opt_clean_args; - std::string opt_const_args; + std::string opt_expr_args; std::string opt_reduce_args; std::string opt_share_args; bool fast_mode = false; @@ -81,33 +81,33 @@ struct OptPass : public Pass { continue; } if (args[argidx] == "-mux_undef") { - opt_const_args += " -mux_undef"; + opt_expr_args += " -mux_undef"; continue; } if (args[argidx] == "-mux_bool") { - opt_const_args += " -mux_bool"; + opt_expr_args += " -mux_bool"; continue; } if (args[argidx] == "-undriven") { - opt_const_args += " -undriven"; + opt_expr_args += " -undriven"; continue; } if (args[argidx] == "-clkinv") { - opt_const_args += " -clkinv"; + opt_expr_args += " -clkinv"; continue; } if (args[argidx] == "-fine") { - opt_const_args += " -fine"; + opt_expr_args += " -fine"; opt_reduce_args += " -fine"; continue; } if (args[argidx] == "-full") { - opt_const_args += " -full"; + opt_expr_args += " -full"; opt_reduce_args += " -full"; continue; } if (args[argidx] == "-keepdc") { - opt_const_args += " -keepdc"; + opt_expr_args += " -keepdc"; continue; } if (args[argidx] == "-share_all") { @@ -125,7 +125,7 @@ struct OptPass : public Pass { if (fast_mode) { while (1) { - Pass::call(design, "opt_const" + opt_const_args); + Pass::call(design, "opt_expr" + opt_expr_args); Pass::call(design, "opt_share" + opt_share_args); design->scratchpad_unset("opt.did_something"); Pass::call(design, "opt_rmdff"); @@ -138,7 +138,7 @@ struct OptPass : public Pass { } else { - Pass::call(design, "opt_const" + opt_const_args); + Pass::call(design, "opt_expr" + opt_expr_args); Pass::call(design, "opt_share -nomux" + opt_share_args); while (1) { design->scratchpad_unset("opt.did_something"); @@ -147,7 +147,7 @@ struct OptPass : public Pass { Pass::call(design, "opt_share" + opt_share_args); Pass::call(design, "opt_rmdff"); Pass::call(design, "opt_clean" + opt_clean_args); - Pass::call(design, "opt_const" + opt_const_args); + Pass::call(design, "opt_expr" + opt_expr_args); if (design->scratchpad_get_bool("opt.did_something") == false) break; log_header("Rerunning OPT passes. (Maybe there is more to do..)\n"); diff --git a/passes/opt/opt_const.cc b/passes/opt/opt_const.cc deleted file mode 100644 index 0fcacf0a8..000000000 --- a/passes/opt/opt_const.cc +++ /dev/null @@ -1,1163 +0,0 @@ -/* - * yosys -- Yosys Open SYnthesis Suite - * - * Copyright (C) 2012 Clifford 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/celltypes.h" -#include "kernel/utils.h" -#include "kernel/log.h" -#include -#include -#include - -USING_YOSYS_NAMESPACE -PRIVATE_NAMESPACE_BEGIN - -bool did_something; - -void replace_undriven(RTLIL::Design *design, RTLIL::Module *module) -{ - CellTypes ct(design); - SigMap sigmap(module); - SigPool driven_signals; - SigPool used_signals; - SigPool all_signals; - - for (auto cell : module->cells()) - for (auto &conn : cell->connections()) { - if (!ct.cell_known(cell->type) || ct.cell_output(cell->type, conn.first)) - driven_signals.add(sigmap(conn.second)); - if (!ct.cell_known(cell->type) || ct.cell_input(cell->type, conn.first)) - used_signals.add(sigmap(conn.second)); - } - - for (auto wire : module->wires()) { - if (wire->port_input) - driven_signals.add(sigmap(wire)); - if (wire->port_output) - used_signals.add(sigmap(wire)); - all_signals.add(sigmap(wire)); - } - - all_signals.del(driven_signals); - RTLIL::SigSpec undriven_signals = all_signals.export_all(); - - for (auto &c : undriven_signals.chunks()) - { - RTLIL::SigSpec sig = c; - - if (c.wire->name[0] == '$') - sig = used_signals.extract(sig); - if (sig.size() == 0) - continue; - - log("Setting undriven signal in %s to undef: %s\n", RTLIL::id2cstr(module->name), log_signal(c)); - module->connect(RTLIL::SigSig(c, RTLIL::SigSpec(RTLIL::State::Sx, c.width))); - did_something = true; - } -} - -void replace_cell(SigMap &assign_map, RTLIL::Module *module, RTLIL::Cell *cell, std::string info, std::string out_port, RTLIL::SigSpec out_val) -{ - RTLIL::SigSpec Y = cell->getPort(out_port); - out_val.extend_u0(Y.size(), false); - - log("Replacing %s cell `%s' (%s) in module `%s' with constant driver `%s = %s'.\n", - cell->type.c_str(), cell->name.c_str(), info.c_str(), - module->name.c_str(), log_signal(Y), log_signal(out_val)); - // log_cell(cell); - assign_map.add(Y, out_val); - module->connect(Y, out_val); - module->remove(cell); - did_something = true; -} - -bool group_cell_inputs(RTLIL::Module *module, RTLIL::Cell *cell, bool commutative, SigMap &sigmap) -{ - std::string b_name = cell->hasPort("\\B") ? "\\B" : "\\A"; - - bool a_signed = cell->parameters.at("\\A_SIGNED").as_bool(); - bool b_signed = cell->parameters.at(b_name + "_SIGNED").as_bool(); - - RTLIL::SigSpec sig_a = sigmap(cell->getPort("\\A")); - RTLIL::SigSpec sig_b = sigmap(cell->getPort(b_name)); - RTLIL::SigSpec sig_y = sigmap(cell->getPort("\\Y")); - - sig_a.extend_u0(sig_y.size(), a_signed); - sig_b.extend_u0(sig_y.size(), b_signed); - - std::vector bits_a = sig_a, bits_b = sig_b, bits_y = sig_y; - - enum { GRP_DYN, GRP_CONST_A, GRP_CONST_B, GRP_CONST_AB, GRP_N }; - std::map, std::set> grouped_bits[GRP_N]; - - for (int i = 0; i < GetSize(bits_y); i++) - { - int group_idx = GRP_DYN; - RTLIL::SigBit bit_a = bits_a[i], bit_b = bits_b[i]; - - if (cell->type == "$or" && (bit_a == RTLIL::State::S1 || bit_b == RTLIL::State::S1)) - bit_a = bit_b = RTLIL::State::S1; - - if (cell->type == "$and" && (bit_a == RTLIL::State::S0 || bit_b == RTLIL::State::S0)) - bit_a = bit_b = RTLIL::State::S0; - - if (bit_a.wire == NULL && bit_b.wire == NULL) - group_idx = GRP_CONST_AB; - else if (bit_a.wire == NULL) - group_idx = GRP_CONST_A; - else if (bit_b.wire == NULL && commutative) - group_idx = GRP_CONST_A, std::swap(bit_a, bit_b); - else if (bit_b.wire == NULL) - group_idx = GRP_CONST_B; - - grouped_bits[group_idx][std::pair(bit_a, bit_b)].insert(bits_y[i]); - } - - for (int i = 0; i < GRP_N; i++) - if (GetSize(grouped_bits[i]) == GetSize(bits_y)) - return false; - - log("Replacing %s cell `%s' in module `%s' with cells using grouped bits:\n", - log_id(cell->type), log_id(cell), log_id(module)); - - for (int i = 0; i < GRP_N; i++) - { - if (grouped_bits[i].empty()) - continue; - - RTLIL::Wire *new_y = module->addWire(NEW_ID, GetSize(grouped_bits[i])); - RTLIL::SigSpec new_a, new_b; - RTLIL::SigSig new_conn; - - for (auto &it : grouped_bits[i]) { - for (auto &bit : it.second) { - new_conn.first.append_bit(bit); - new_conn.second.append_bit(RTLIL::SigBit(new_y, new_a.size())); - } - new_a.append_bit(it.first.first); - new_b.append_bit(it.first.second); - } - - RTLIL::Cell *c = module->addCell(NEW_ID, cell->type); - - c->setPort("\\A", new_a); - c->parameters["\\A_WIDTH"] = new_a.size(); - c->parameters["\\A_SIGNED"] = false; - - if (b_name == "\\B") { - c->setPort("\\B", new_b); - c->parameters["\\B_WIDTH"] = new_b.size(); - c->parameters["\\B_SIGNED"] = false; - } - - c->setPort("\\Y", new_y); - c->parameters["\\Y_WIDTH"] = new_y->width; - c->check(); - - module->connect(new_conn); - - log(" New cell `%s': A=%s", log_id(c), log_signal(new_a)); - if (b_name == "\\B") - log(", B=%s", log_signal(new_b)); - log("\n"); - } - - cover_list("opt.opt_const.fine.group", "$not", "$pos", "$and", "$or", "$xor", "$xnor", cell->type.str()); - - module->remove(cell); - did_something = true; - return true; -} - -void handle_polarity_inv(Cell *cell, IdString port, IdString param, const SigMap &assign_map, const dict &invert_map) -{ - SigSpec sig = assign_map(cell->getPort(port)); - if (invert_map.count(sig)) { - log("Inverting %s of %s cell `%s' in module `%s': %s -> %s\n", - log_id(port), log_id(cell->type), log_id(cell), log_id(cell->module), - log_signal(sig), log_signal(invert_map.at(sig))); - cell->setPort(port, (invert_map.at(sig))); - cell->setParam(param, !cell->getParam(param).as_bool()); - } -} - -void handle_clkpol_celltype_swap(Cell *cell, string type1, string type2, IdString port, const SigMap &assign_map, const dict &invert_map) -{ - log_assert(GetSize(type1) == GetSize(type2)); - string cell_type = cell->type.str(); - - if (GetSize(type1) != GetSize(cell_type)) - return; - - for (int i = 0; i < GetSize(type1); i++) { - log_assert((type1[i] == '?') == (type2[i] == '?')); - if (type1[i] == '?') { - if (cell_type[i] != '0' && cell_type[i] != '1' && cell_type[i] != 'N' && cell_type[i] != 'P') - return; - type1[i] = cell_type[i]; - type2[i] = cell_type[i]; - } - } - - if (cell->type.in(type1, type2)) { - SigSpec sig = assign_map(cell->getPort(port)); - if (invert_map.count(sig)) { - log("Inverting %s of %s cell `%s' in module `%s': %s -> %s\n", - log_id(port), log_id(cell->type), log_id(cell), log_id(cell->module), - log_signal(sig), log_signal(invert_map.at(sig))); - cell->setPort(port, (invert_map.at(sig))); - cell->type = cell->type == type1 ? type2 : type1; - } - } -} - -bool is_one_or_minus_one(const Const &value, bool is_signed, bool &is_negative) -{ - bool all_bits_one = true; - bool last_bit_one = true; - - if (GetSize(value.bits) < 1) - return false; - - if (GetSize(value.bits) == 1) { - if (value.bits[0] != State::S1) - return false; - if (is_signed) - is_negative = true; - return true; - } - - for (int i = 0; i < GetSize(value.bits); i++) { - if (value.bits[i] != State::S1) - all_bits_one = false; - if (value.bits[i] != (i ? State::S0 : State::S1)) - last_bit_one = false; - } - - if (all_bits_one && is_signed) { - is_negative = true; - return true; - } - - return last_bit_one; -} - -void replace_const_cells(RTLIL::Design *design, RTLIL::Module *module, bool consume_x, bool mux_undef, bool mux_bool, bool do_fine, bool keepdc, bool clkinv) -{ - if (!design->selected(module)) - return; - - CellTypes ct_combinational; - ct_combinational.setup_internals(); - ct_combinational.setup_stdcells(); - - SigMap assign_map(module); - dict invert_map; - - TopoSort> cells; - dict> cell_to_inbit; - dict> outbit_to_cell; - - for (auto cell : module->cells()) - if (design->selected(module, cell) && cell->type[0] == '$') { - if ((cell->type == "$_NOT_" || cell->type == "$not" || cell->type == "$logic_not") && - cell->getPort("\\A").size() == 1 && cell->getPort("\\Y").size() == 1) - invert_map[assign_map(cell->getPort("\\Y"))] = assign_map(cell->getPort("\\A")); - if ((cell->type == "$mux" || cell->type == "$_MUX_") && cell->getPort("\\A") == SigSpec(State::S1) && cell->getPort("\\B") == SigSpec(State::S0)) - invert_map[assign_map(cell->getPort("\\Y"))] = assign_map(cell->getPort("\\S")); - if (ct_combinational.cell_known(cell->type)) - for (auto &conn : cell->connections()) { - RTLIL::SigSpec sig = assign_map(conn.second); - sig.remove_const(); - if (ct_combinational.cell_input(cell->type, conn.first)) - cell_to_inbit[cell].insert(sig.begin(), sig.end()); - if (ct_combinational.cell_output(cell->type, conn.first)) - for (auto &bit : sig) - outbit_to_cell[bit].insert(cell); - } - cells.node(cell); - } - - for (auto &it_right : cell_to_inbit) - for (auto &it_sigbit : it_right.second) - for (auto &it_left : outbit_to_cell[it_sigbit]) - cells.edge(it_left, it_right.first); - - cells.sort(); - - for (auto cell : cells.sorted) - { -#define ACTION_DO(_p_, _s_) do { cover("opt.opt_const.action_" S__LINE__); replace_cell(assign_map, module, cell, input.as_string(), _p_, _s_); goto next_cell; } while (0) -#define ACTION_DO_Y(_v_) ACTION_DO("\\Y", RTLIL::SigSpec(RTLIL::State::S ## _v_)) - - if (clkinv) - { - if (cell->type.in("$dff", "$dffe", "$dffsr", "$adff", "$fsm", "$memrd", "$memwr")) - handle_polarity_inv(cell, "\\CLK", "\\CLK_POLARITY", assign_map, invert_map); - - if (cell->type.in("$sr", "$dffsr", "$dlatchsr")) { - handle_polarity_inv(cell, "\\SET", "\\SET_POLARITY", assign_map, invert_map); - handle_polarity_inv(cell, "\\CLR", "\\CLR_POLARITY", assign_map, invert_map); - } - - if (cell->type.in("$dffe", "$dlatch", "$dlatchsr")) - handle_polarity_inv(cell, "\\EN", "\\EN_POLARITY", assign_map, invert_map); - - handle_clkpol_celltype_swap(cell, "$_SR_N?_", "$_SR_P?_", "\\S", assign_map, invert_map); - handle_clkpol_celltype_swap(cell, "$_SR_?N_", "$_SR_?P_", "\\R", assign_map, invert_map); - - handle_clkpol_celltype_swap(cell, "$_DFF_N_", "$_DFF_P_", "\\C", assign_map, invert_map); - - handle_clkpol_celltype_swap(cell, "$_DFFE_N?_", "$_DFFE_P?_", "\\C", assign_map, invert_map); - handle_clkpol_celltype_swap(cell, "$_DFFE_?N_", "$_DFFE_?P_", "\\E", assign_map, invert_map); - - handle_clkpol_celltype_swap(cell, "$_DFF_N??_", "$_DFF_P??_", "\\C", assign_map, invert_map); - handle_clkpol_celltype_swap(cell, "$_DFF_?N?_", "$_DFF_?P?_", "\\R", assign_map, invert_map); - - handle_clkpol_celltype_swap(cell, "$_DFFSR_N??_", "$_DFFSR_P??_", "\\C", assign_map, invert_map); - handle_clkpol_celltype_swap(cell, "$_DFFSR_?N?_", "$_DFFSR_?P?_", "\\S", assign_map, invert_map); - handle_clkpol_celltype_swap(cell, "$_DFFSR_??N_", "$_DFFSR_??P_", "\\R", assign_map, invert_map); - - handle_clkpol_celltype_swap(cell, "$_DLATCH_N_", "$_DLATCH_P_", "\\E", assign_map, invert_map); - - handle_clkpol_celltype_swap(cell, "$_DLATCHSR_N??_", "$_DLATCHSR_P??_", "\\E", assign_map, invert_map); - handle_clkpol_celltype_swap(cell, "$_DLATCHSR_?N?_", "$_DLATCHSR_?P?_", "\\S", assign_map, invert_map); - handle_clkpol_celltype_swap(cell, "$_DLATCHSR_??N_", "$_DLATCHSR_??P_", "\\R", assign_map, invert_map); - } - - if (do_fine) - { - if (cell->type == "$not" || cell->type == "$pos" || - cell->type == "$and" || cell->type == "$or" || cell->type == "$xor" || cell->type == "$xnor") - if (group_cell_inputs(module, cell, true, assign_map)) - goto next_cell; - - if (cell->type == "$reduce_and") - { - RTLIL::SigSpec sig_a = assign_map(cell->getPort("\\A")); - - RTLIL::State new_a = RTLIL::State::S1; - for (auto &bit : sig_a.to_sigbit_vector()) - if (bit == RTLIL::State::Sx) { - if (new_a == RTLIL::State::S1) - new_a = RTLIL::State::Sx; - } else if (bit == RTLIL::State::S0) { - new_a = RTLIL::State::S0; - break; - } else if (bit.wire != NULL) { - new_a = RTLIL::State::Sm; - } - - if (new_a != RTLIL::State::Sm && RTLIL::SigSpec(new_a) != sig_a) { - cover("opt.opt_const.fine.$reduce_and"); - log("Replacing port A of %s cell `%s' in module `%s' with constant driver: %s -> %s\n", - cell->type.c_str(), cell->name.c_str(), module->name.c_str(), log_signal(sig_a), log_signal(new_a)); - cell->setPort("\\A", sig_a = new_a); - cell->parameters.at("\\A_WIDTH") = 1; - did_something = true; - } - } - - if (cell->type == "$logic_not" || cell->type == "$logic_and" || cell->type == "$logic_or" || cell->type == "$reduce_or" || cell->type == "$reduce_bool") - { - RTLIL::SigSpec sig_a = assign_map(cell->getPort("\\A")); - - RTLIL::State new_a = RTLIL::State::S0; - for (auto &bit : sig_a.to_sigbit_vector()) - if (bit == RTLIL::State::Sx) { - if (new_a == RTLIL::State::S0) - new_a = RTLIL::State::Sx; - } else if (bit == RTLIL::State::S1) { - new_a = RTLIL::State::S1; - break; - } else if (bit.wire != NULL) { - new_a = RTLIL::State::Sm; - } - - if (new_a != RTLIL::State::Sm && RTLIL::SigSpec(new_a) != sig_a) { - cover_list("opt.opt_const.fine.A", "$logic_not", "$logic_and", "$logic_or", "$reduce_or", "$reduce_bool", cell->type.str()); - log("Replacing port A of %s cell `%s' in module `%s' with constant driver: %s -> %s\n", - cell->type.c_str(), cell->name.c_str(), module->name.c_str(), log_signal(sig_a), log_signal(new_a)); - cell->setPort("\\A", sig_a = new_a); - cell->parameters.at("\\A_WIDTH") = 1; - did_something = true; - } - } - - if (cell->type == "$logic_and" || cell->type == "$logic_or") - { - RTLIL::SigSpec sig_b = assign_map(cell->getPort("\\B")); - - RTLIL::State new_b = RTLIL::State::S0; - for (auto &bit : sig_b.to_sigbit_vector()) - if (bit == RTLIL::State::Sx) { - if (new_b == RTLIL::State::S0) - new_b = RTLIL::State::Sx; - } else if (bit == RTLIL::State::S1) { - new_b = RTLIL::State::S1; - break; - } else if (bit.wire != NULL) { - new_b = RTLIL::State::Sm; - } - - if (new_b != RTLIL::State::Sm && RTLIL::SigSpec(new_b) != sig_b) { - cover_list("opt.opt_const.fine.B", "$logic_and", "$logic_or", cell->type.str()); - log("Replacing port B of %s cell `%s' in module `%s' with constant driver: %s -> %s\n", - cell->type.c_str(), cell->name.c_str(), module->name.c_str(), log_signal(sig_b), log_signal(new_b)); - cell->setPort("\\B", sig_b = new_b); - cell->parameters.at("\\B_WIDTH") = 1; - did_something = true; - } - } - } - - if (cell->type == "$logic_or" && (assign_map(cell->getPort("\\A")) == RTLIL::State::S1 || assign_map(cell->getPort("\\B")) == RTLIL::State::S1)) { - cover("opt.opt_const.one_high"); - replace_cell(assign_map, module, cell, "one high", "\\Y", RTLIL::State::S1); - goto next_cell; - } - - if (cell->type == "$logic_and" && (assign_map(cell->getPort("\\A")) == RTLIL::State::S0 || assign_map(cell->getPort("\\B")) == RTLIL::State::S0)) { - cover("opt.opt_const.one_low"); - replace_cell(assign_map, module, cell, "one low", "\\Y", RTLIL::State::S0); - goto next_cell; - } - - if (cell->type == "$reduce_xor" || cell->type == "$reduce_xnor" || cell->type == "$shift" || cell->type == "$shiftx" || - cell->type == "$shl" || cell->type == "$shr" || cell->type == "$sshl" || cell->type == "$sshr" || - cell->type == "$lt" || cell->type == "$le" || cell->type == "$ge" || cell->type == "$gt" || - cell->type == "$neg" || cell->type == "$add" || cell->type == "$sub" || - cell->type == "$mul" || cell->type == "$div" || cell->type == "$mod" || cell->type == "$pow") - { - RTLIL::SigSpec sig_a = assign_map(cell->getPort("\\A")); - RTLIL::SigSpec sig_b = cell->hasPort("\\B") ? assign_map(cell->getPort("\\B")) : RTLIL::SigSpec(); - - if (cell->type == "$shl" || cell->type == "$shr" || cell->type == "$sshl" || cell->type == "$sshr" || cell->type == "$shift" || cell->type == "$shiftx") - sig_a = RTLIL::SigSpec(); - - for (auto &bit : sig_a.to_sigbit_vector()) - if (bit == RTLIL::State::Sx) - goto found_the_x_bit; - - for (auto &bit : sig_b.to_sigbit_vector()) - if (bit == RTLIL::State::Sx) - goto found_the_x_bit; - - if (0) { - found_the_x_bit: - cover_list("opt.opt_const.xbit", "$reduce_xor", "$reduce_xnor", "$shl", "$shr", "$sshl", "$sshr", "$shift", "$shiftx", - "$lt", "$le", "$ge", "$gt", "$neg", "$add", "$sub", "$mul", "$div", "$mod", "$pow", cell->type.str()); - if (cell->type == "$reduce_xor" || cell->type == "$reduce_xnor" || - cell->type == "$lt" || cell->type == "$le" || cell->type == "$ge" || cell->type == "$gt") - replace_cell(assign_map, module, cell, "x-bit in input", "\\Y", RTLIL::State::Sx); - else - replace_cell(assign_map, module, cell, "x-bit in input", "\\Y", RTLIL::SigSpec(RTLIL::State::Sx, cell->getPort("\\Y").size())); - goto next_cell; - } - } - - if ((cell->type == "$_NOT_" || cell->type == "$not" || cell->type == "$logic_not") && cell->getPort("\\Y").size() == 1 && - invert_map.count(assign_map(cell->getPort("\\A"))) != 0) { - cover_list("opt.opt_const.invert.double", "$_NOT_", "$not", "$logic_not", cell->type.str()); - replace_cell(assign_map, module, cell, "double_invert", "\\Y", invert_map.at(assign_map(cell->getPort("\\A")))); - goto next_cell; - } - - if ((cell->type == "$_MUX_" || cell->type == "$mux") && invert_map.count(assign_map(cell->getPort("\\S"))) != 0) { - cover_list("opt.opt_const.invert.muxsel", "$_MUX_", "$mux", cell->type.str()); - log("Optimizing away select inverter for %s cell `%s' in module `%s'.\n", log_id(cell->type), log_id(cell), log_id(module)); - RTLIL::SigSpec tmp = cell->getPort("\\A"); - cell->setPort("\\A", cell->getPort("\\B")); - cell->setPort("\\B", tmp); - cell->setPort("\\S", invert_map.at(assign_map(cell->getPort("\\S")))); - did_something = true; - goto next_cell; - } - - if (cell->type == "$_NOT_") { - RTLIL::SigSpec input = cell->getPort("\\A"); - assign_map.apply(input); - if (input.match("1")) ACTION_DO_Y(0); - if (input.match("0")) ACTION_DO_Y(1); - if (input.match("*")) ACTION_DO_Y(x); - } - - if (cell->type == "$_AND_") { - RTLIL::SigSpec input; - input.append(cell->getPort("\\B")); - input.append(cell->getPort("\\A")); - assign_map.apply(input); - if (input.match(" 0")) ACTION_DO_Y(0); - if (input.match("0 ")) ACTION_DO_Y(0); - if (input.match("11")) ACTION_DO_Y(1); - if (input.match("**")) ACTION_DO_Y(x); - if (input.match("1*")) ACTION_DO_Y(x); - if (input.match("*1")) ACTION_DO_Y(x); - if (consume_x) { - if (input.match(" *")) ACTION_DO_Y(0); - if (input.match("* ")) ACTION_DO_Y(0); - } - if (input.match(" 1")) ACTION_DO("\\Y", input.extract(1, 1)); - if (input.match("1 ")) ACTION_DO("\\Y", input.extract(0, 1)); - } - - if (cell->type == "$_OR_") { - RTLIL::SigSpec input; - input.append(cell->getPort("\\B")); - input.append(cell->getPort("\\A")); - assign_map.apply(input); - if (input.match(" 1")) ACTION_DO_Y(1); - if (input.match("1 ")) ACTION_DO_Y(1); - if (input.match("00")) ACTION_DO_Y(0); - if (input.match("**")) ACTION_DO_Y(x); - if (input.match("0*")) ACTION_DO_Y(x); - if (input.match("*0")) ACTION_DO_Y(x); - if (consume_x) { - if (input.match(" *")) ACTION_DO_Y(1); - if (input.match("* ")) ACTION_DO_Y(1); - } - if (input.match(" 0")) ACTION_DO("\\Y", input.extract(1, 1)); - if (input.match("0 ")) ACTION_DO("\\Y", input.extract(0, 1)); - } - - if (cell->type == "$_XOR_") { - RTLIL::SigSpec input; - input.append(cell->getPort("\\B")); - input.append(cell->getPort("\\A")); - assign_map.apply(input); - if (input.match("00")) ACTION_DO_Y(0); - if (input.match("01")) ACTION_DO_Y(1); - if (input.match("10")) ACTION_DO_Y(1); - if (input.match("11")) ACTION_DO_Y(0); - if (input.match(" *")) ACTION_DO_Y(x); - if (input.match("* ")) ACTION_DO_Y(x); - if (input.match(" 0")) ACTION_DO("\\Y", input.extract(1, 1)); - if (input.match("0 ")) ACTION_DO("\\Y", input.extract(0, 1)); - } - - if (cell->type == "$_MUX_") { - RTLIL::SigSpec input; - input.append(cell->getPort("\\S")); - input.append(cell->getPort("\\B")); - input.append(cell->getPort("\\A")); - assign_map.apply(input); - if (input.extract(2, 1) == input.extract(1, 1)) - ACTION_DO("\\Y", input.extract(2, 1)); - if (input.match(" 0")) ACTION_DO("\\Y", input.extract(2, 1)); - if (input.match(" 1")) ACTION_DO("\\Y", input.extract(1, 1)); - if (input.match("01 ")) ACTION_DO("\\Y", input.extract(0, 1)); - if (input.match("10 ")) { - cover("opt.opt_const.mux_to_inv"); - cell->type = "$_NOT_"; - cell->setPort("\\A", input.extract(0, 1)); - cell->unsetPort("\\B"); - cell->unsetPort("\\S"); - goto next_cell; - } - if (input.match("11 ")) ACTION_DO_Y(1); - if (input.match("00 ")) ACTION_DO_Y(0); - if (input.match("** ")) ACTION_DO_Y(x); - if (input.match("01*")) ACTION_DO_Y(x); - if (input.match("10*")) ACTION_DO_Y(x); - if (mux_undef) { - if (input.match("* ")) ACTION_DO("\\Y", input.extract(1, 1)); - if (input.match(" * ")) ACTION_DO("\\Y", input.extract(2, 1)); - if (input.match(" *")) ACTION_DO("\\Y", input.extract(2, 1)); - } - } - - if (cell->type == "$eq" || cell->type == "$ne" || cell->type == "$eqx" || cell->type == "$nex") - { - RTLIL::SigSpec a = cell->getPort("\\A"); - RTLIL::SigSpec b = cell->getPort("\\B"); - - if (cell->parameters["\\A_WIDTH"].as_int() != cell->parameters["\\B_WIDTH"].as_int()) { - int width = max(cell->parameters["\\A_WIDTH"].as_int(), cell->parameters["\\B_WIDTH"].as_int()); - a.extend_u0(width, cell->parameters["\\A_SIGNED"].as_bool() && cell->parameters["\\B_SIGNED"].as_bool()); - b.extend_u0(width, cell->parameters["\\A_SIGNED"].as_bool() && cell->parameters["\\B_SIGNED"].as_bool()); - } - - RTLIL::SigSpec new_a, new_b; - - log_assert(GetSize(a) == GetSize(b)); - for (int i = 0; i < GetSize(a); i++) { - if (a[i].wire == NULL && b[i].wire == NULL && a[i] != b[i] && a[i].data <= RTLIL::State::S1 && b[i].data <= RTLIL::State::S1) { - cover_list("opt.opt_const.eqneq.isneq", "$eq", "$ne", "$eqx", "$nex", cell->type.str()); - RTLIL::SigSpec new_y = RTLIL::SigSpec((cell->type == "$eq" || cell->type == "$eqx") ? RTLIL::State::S0 : RTLIL::State::S1); - new_y.extend_u0(cell->parameters["\\Y_WIDTH"].as_int(), false); - replace_cell(assign_map, module, cell, "isneq", "\\Y", new_y); - goto next_cell; - } - if (a[i] == b[i]) - continue; - new_a.append(a[i]); - new_b.append(b[i]); - } - - if (new_a.size() == 0) { - cover_list("opt.opt_const.eqneq.empty", "$eq", "$ne", "$eqx", "$nex", cell->type.str()); - RTLIL::SigSpec new_y = RTLIL::SigSpec((cell->type == "$eq" || cell->type == "$eqx") ? RTLIL::State::S1 : RTLIL::State::S0); - new_y.extend_u0(cell->parameters["\\Y_WIDTH"].as_int(), false); - replace_cell(assign_map, module, cell, "empty", "\\Y", new_y); - goto next_cell; - } - - if (new_a.size() < a.size() || new_b.size() < b.size()) { - cover_list("opt.opt_const.eqneq.resize", "$eq", "$ne", "$eqx", "$nex", cell->type.str()); - cell->setPort("\\A", new_a); - cell->setPort("\\B", new_b); - cell->parameters["\\A_WIDTH"] = new_a.size(); - cell->parameters["\\B_WIDTH"] = new_b.size(); - } - } - - if ((cell->type == "$eq" || cell->type == "$ne") && cell->parameters["\\Y_WIDTH"].as_int() == 1 && - cell->parameters["\\A_WIDTH"].as_int() == 1 && cell->parameters["\\B_WIDTH"].as_int() == 1) - { - RTLIL::SigSpec a = assign_map(cell->getPort("\\A")); - RTLIL::SigSpec b = assign_map(cell->getPort("\\B")); - - if (a.is_fully_const() && !b.is_fully_const()) { - cover_list("opt.opt_const.eqneq.swapconst", "$eq", "$ne", cell->type.str()); - cell->setPort("\\A", b); - cell->setPort("\\B", a); - std::swap(a, b); - } - - if (b.is_fully_const()) { - if (b.as_bool() == (cell->type == "$eq")) { - RTLIL::SigSpec input = b; - ACTION_DO("\\Y", cell->getPort("\\A")); - } else { - cover_list("opt.opt_const.eqneq.isnot", "$eq", "$ne", cell->type.str()); - log("Replacing %s cell `%s' in module `%s' with inverter.\n", log_id(cell->type), log_id(cell), log_id(module)); - cell->type = "$not"; - cell->parameters.erase("\\B_WIDTH"); - cell->parameters.erase("\\B_SIGNED"); - cell->unsetPort("\\B"); - did_something = true; - } - goto next_cell; - } - } - - if ((cell->type == "$eq" || cell->type == "$ne") && - (assign_map(cell->getPort("\\A")).is_fully_zero() || assign_map(cell->getPort("\\B")).is_fully_zero())) - { - cover_list("opt.opt_const.eqneq.cmpzero", "$eq", "$ne", cell->type.str()); - log("Replacing %s cell `%s' in module `%s' with %s.\n", log_id(cell->type), log_id(cell), - log_id(module), "$eq" ? "$logic_not" : "$reduce_bool"); - cell->type = cell->type == "$eq" ? "$logic_not" : "$reduce_bool"; - if (assign_map(cell->getPort("\\A")).is_fully_zero()) { - cell->setPort("\\A", cell->getPort("\\B")); - cell->setParam("\\A_SIGNED", cell->getParam("\\B_SIGNED")); - cell->setParam("\\A_WIDTH", cell->getParam("\\B_WIDTH")); - } - cell->unsetPort("\\B"); - cell->unsetParam("\\B_SIGNED"); - cell->unsetParam("\\B_WIDTH"); - did_something = true; - goto next_cell; - } - - if (cell->type.in("$shl", "$shr", "$sshl", "$sshr", "$shift", "$shiftx") && assign_map(cell->getPort("\\B")).is_fully_const()) - { - bool sign_ext = cell->type == "$sshr" && cell->getParam("\\A_SIGNED").as_bool(); - int shift_bits = assign_map(cell->getPort("\\B")).as_int(cell->type.in("$shift", "$shiftx") && cell->getParam("\\B_SIGNED").as_bool()); - - if (cell->type.in("$shl", "$sshl")) - shift_bits *= -1; - - RTLIL::SigSpec sig_a = assign_map(cell->getPort("\\A")); - RTLIL::SigSpec sig_y(cell->type == "$shiftx" ? RTLIL::State::Sx : RTLIL::State::S0, cell->getParam("\\Y_WIDTH").as_int()); - - if (GetSize(sig_a) < GetSize(sig_y)) - sig_a.extend_u0(GetSize(sig_y), cell->getParam("\\A_SIGNED").as_bool()); - - for (int i = 0; i < GetSize(sig_y); i++) { - int idx = i + shift_bits; - if (0 <= idx && idx < GetSize(sig_a)) - sig_y[i] = sig_a[idx]; - else if (GetSize(sig_a) <= idx && sign_ext) - sig_y[i] = sig_a[GetSize(sig_a)-1]; - } - - cover_list("opt.opt_const.constshift", "$shl", "$shr", "$sshl", "$sshr", "$shift", "$shiftx", cell->type.str()); - - log("Replacing %s cell `%s' (B=%s, SHR=%d) in module `%s' with fixed wiring: %s\n", - log_id(cell->type), log_id(cell), log_signal(assign_map(cell->getPort("\\B"))), shift_bits, log_id(module), log_signal(sig_y)); - - module->connect(cell->getPort("\\Y"), sig_y); - module->remove(cell); - - did_something = true; - goto next_cell; - } - - if (!keepdc) - { - bool identity_wrt_a = false; - bool identity_wrt_b = false; - bool arith_inverse = false; - - if (cell->type == "$add" || cell->type == "$sub" || cell->type == "$or" || cell->type == "$xor") - { - RTLIL::SigSpec a = assign_map(cell->getPort("\\A")); - RTLIL::SigSpec b = assign_map(cell->getPort("\\B")); - - if (cell->type != "$sub" && a.is_fully_const() && a.as_bool() == false) - identity_wrt_b = true; - - if (b.is_fully_const() && b.as_bool() == false) - identity_wrt_a = true; - } - - if (cell->type == "$shl" || cell->type == "$shr" || cell->type == "$sshl" || cell->type == "$sshr" || cell->type == "$shift" || cell->type == "$shiftx") - { - RTLIL::SigSpec b = assign_map(cell->getPort("\\B")); - - if (b.is_fully_const() && b.as_bool() == false) - identity_wrt_a = true; - } - - if (cell->type == "$mul") - { - RTLIL::SigSpec a = assign_map(cell->getPort("\\A")); - RTLIL::SigSpec b = assign_map(cell->getPort("\\B")); - - if (a.is_fully_const() && is_one_or_minus_one(a.as_const(), cell->getParam("\\A_SIGNED").as_bool(), arith_inverse)) - identity_wrt_b = true; - else - if (b.is_fully_const() && is_one_or_minus_one(b.as_const(), cell->getParam("\\B_SIGNED").as_bool(), arith_inverse)) - identity_wrt_a = true; - } - - if (cell->type == "$div") - { - RTLIL::SigSpec b = assign_map(cell->getPort("\\B")); - - if (b.is_fully_const() && b.size() <= 32 && b.as_int() == 1) - identity_wrt_a = true; - } - - if (identity_wrt_a || identity_wrt_b) - { - if (identity_wrt_a) - cover_list("opt.opt_const.identwrt.a", "$add", "$sub", "$or", "$xor", "$shl", "$shr", "$sshl", "$sshr", "$shift", "$shiftx", "$mul", "$div", cell->type.str()); - if (identity_wrt_b) - cover_list("opt.opt_const.identwrt.b", "$add", "$sub", "$or", "$xor", "$shl", "$shr", "$sshl", "$sshr", "$shift", "$shiftx", "$mul", "$div", cell->type.str()); - - log("Replacing %s cell `%s' in module `%s' with identity for port %c.\n", - cell->type.c_str(), cell->name.c_str(), module->name.c_str(), identity_wrt_a ? 'A' : 'B'); - - if (!identity_wrt_a) { - cell->setPort("\\A", cell->getPort("\\B")); - cell->parameters.at("\\A_WIDTH") = cell->parameters.at("\\B_WIDTH"); - cell->parameters.at("\\A_SIGNED") = cell->parameters.at("\\B_SIGNED"); - } - - cell->type = arith_inverse ? "$neg" : "$pos"; - cell->unsetPort("\\B"); - cell->parameters.erase("\\B_WIDTH"); - cell->parameters.erase("\\B_SIGNED"); - cell->check(); - - did_something = true; - goto next_cell; - } - } - - if (mux_bool && (cell->type == "$mux" || cell->type == "$_MUX_") && - cell->getPort("\\A") == RTLIL::SigSpec(0, 1) && cell->getPort("\\B") == RTLIL::SigSpec(1, 1)) { - cover_list("opt.opt_const.mux_bool", "$mux", "$_MUX_", cell->type.str()); - replace_cell(assign_map, module, cell, "mux_bool", "\\Y", cell->getPort("\\S")); - goto next_cell; - } - - if (mux_bool && (cell->type == "$mux" || cell->type == "$_MUX_") && - cell->getPort("\\A") == RTLIL::SigSpec(1, 1) && cell->getPort("\\B") == RTLIL::SigSpec(0, 1)) { - cover_list("opt.opt_const.mux_invert", "$mux", "$_MUX_", cell->type.str()); - log("Replacing %s cell `%s' in module `%s' with inverter.\n", log_id(cell->type), log_id(cell), log_id(module)); - cell->setPort("\\A", cell->getPort("\\S")); - cell->unsetPort("\\B"); - cell->unsetPort("\\S"); - if (cell->type == "$mux") { - Const width = cell->parameters["\\WIDTH"]; - cell->parameters["\\A_WIDTH"] = width; - cell->parameters["\\Y_WIDTH"] = width; - cell->parameters["\\A_SIGNED"] = 0; - cell->parameters.erase("\\WIDTH"); - cell->type = "$not"; - } else - cell->type = "$_NOT_"; - did_something = true; - goto next_cell; - } - - if (consume_x && mux_bool && (cell->type == "$mux" || cell->type == "$_MUX_") && cell->getPort("\\A") == RTLIL::SigSpec(0, 1)) { - cover_list("opt.opt_const.mux_and", "$mux", "$_MUX_", cell->type.str()); - log("Replacing %s cell `%s' in module `%s' with and-gate.\n", log_id(cell->type), log_id(cell), log_id(module)); - cell->setPort("\\A", cell->getPort("\\S")); - cell->unsetPort("\\S"); - if (cell->type == "$mux") { - Const width = cell->parameters["\\WIDTH"]; - cell->parameters["\\A_WIDTH"] = width; - cell->parameters["\\B_WIDTH"] = width; - cell->parameters["\\Y_WIDTH"] = width; - cell->parameters["\\A_SIGNED"] = 0; - cell->parameters["\\B_SIGNED"] = 0; - cell->parameters.erase("\\WIDTH"); - cell->type = "$and"; - } else - cell->type = "$_AND_"; - did_something = true; - goto next_cell; - } - - if (consume_x && mux_bool && (cell->type == "$mux" || cell->type == "$_MUX_") && cell->getPort("\\B") == RTLIL::SigSpec(1, 1)) { - cover_list("opt.opt_const.mux_or", "$mux", "$_MUX_", cell->type.str()); - log("Replacing %s cell `%s' in module `%s' with or-gate.\n", log_id(cell->type), log_id(cell), log_id(module)); - cell->setPort("\\B", cell->getPort("\\S")); - cell->unsetPort("\\S"); - if (cell->type == "$mux") { - Const width = cell->parameters["\\WIDTH"]; - cell->parameters["\\A_WIDTH"] = width; - cell->parameters["\\B_WIDTH"] = width; - cell->parameters["\\Y_WIDTH"] = width; - cell->parameters["\\A_SIGNED"] = 0; - cell->parameters["\\B_SIGNED"] = 0; - cell->parameters.erase("\\WIDTH"); - cell->type = "$or"; - } else - cell->type = "$_OR_"; - did_something = true; - goto next_cell; - } - - if (mux_undef && (cell->type == "$mux" || cell->type == "$pmux")) { - RTLIL::SigSpec new_a, new_b, new_s; - int width = cell->getPort("\\A").size(); - if ((cell->getPort("\\A").is_fully_undef() && cell->getPort("\\B").is_fully_undef()) || - cell->getPort("\\S").is_fully_undef()) { - cover_list("opt.opt_const.mux_undef", "$mux", "$pmux", cell->type.str()); - replace_cell(assign_map, module, cell, "mux_undef", "\\Y", cell->getPort("\\A")); - goto next_cell; - } - for (int i = 0; i < cell->getPort("\\S").size(); i++) { - RTLIL::SigSpec old_b = cell->getPort("\\B").extract(i*width, width); - RTLIL::SigSpec old_s = cell->getPort("\\S").extract(i, 1); - if (old_b.is_fully_undef() || old_s.is_fully_undef()) - continue; - new_b.append(old_b); - new_s.append(old_s); - } - new_a = cell->getPort("\\A"); - if (new_a.is_fully_undef() && new_s.size() > 0) { - new_a = new_b.extract((new_s.size()-1)*width, width); - new_b = new_b.extract(0, (new_s.size()-1)*width); - new_s = new_s.extract(0, new_s.size()-1); - } - if (new_s.size() == 0) { - cover_list("opt.opt_const.mux_empty", "$mux", "$pmux", cell->type.str()); - replace_cell(assign_map, module, cell, "mux_empty", "\\Y", new_a); - goto next_cell; - } - if (new_a == RTLIL::SigSpec(RTLIL::State::S0) && new_b == RTLIL::SigSpec(RTLIL::State::S1)) { - cover_list("opt.opt_const.mux_sel01", "$mux", "$pmux", cell->type.str()); - replace_cell(assign_map, module, cell, "mux_sel01", "\\Y", new_s); - goto next_cell; - } - if (cell->getPort("\\S").size() != new_s.size()) { - cover_list("opt.opt_const.mux_reduce", "$mux", "$pmux", cell->type.str()); - log("Optimized away %d select inputs of %s cell `%s' in module `%s'.\n", - GetSize(cell->getPort("\\S")) - GetSize(new_s), log_id(cell->type), log_id(cell), log_id(module)); - cell->setPort("\\A", new_a); - cell->setPort("\\B", new_b); - cell->setPort("\\S", new_s); - if (new_s.size() > 1) { - cell->type = "$pmux"; - cell->parameters["\\S_WIDTH"] = new_s.size(); - } else { - cell->type = "$mux"; - cell->parameters.erase("\\S_WIDTH"); - } - did_something = true; - } - } - -#define FOLD_1ARG_CELL(_t) \ - if (cell->type == "$" #_t) { \ - RTLIL::SigSpec a = cell->getPort("\\A"); \ - assign_map.apply(a); \ - if (a.is_fully_const()) { \ - RTLIL::Const dummy_arg(RTLIL::State::S0, 1); \ - RTLIL::SigSpec y(RTLIL::const_ ## _t(a.as_const(), dummy_arg, \ - cell->parameters["\\A_SIGNED"].as_bool(), false, \ - cell->parameters["\\Y_WIDTH"].as_int())); \ - cover("opt.opt_const.const.$" #_t); \ - replace_cell(assign_map, module, cell, stringf("%s", log_signal(a)), "\\Y", y); \ - goto next_cell; \ - } \ - } -#define FOLD_2ARG_CELL(_t) \ - if (cell->type == "$" #_t) { \ - RTLIL::SigSpec a = cell->getPort("\\A"); \ - RTLIL::SigSpec b = cell->getPort("\\B"); \ - assign_map.apply(a), assign_map.apply(b); \ - if (a.is_fully_const() && b.is_fully_const()) { \ - RTLIL::SigSpec y(RTLIL::const_ ## _t(a.as_const(), b.as_const(), \ - cell->parameters["\\A_SIGNED"].as_bool(), \ - cell->parameters["\\B_SIGNED"].as_bool(), \ - cell->parameters["\\Y_WIDTH"].as_int())); \ - cover("opt.opt_const.const.$" #_t); \ - replace_cell(assign_map, module, cell, stringf("%s, %s", log_signal(a), log_signal(b)), "\\Y", y); \ - goto next_cell; \ - } \ - } - - FOLD_1ARG_CELL(not) - FOLD_2ARG_CELL(and) - FOLD_2ARG_CELL(or) - FOLD_2ARG_CELL(xor) - FOLD_2ARG_CELL(xnor) - - FOLD_1ARG_CELL(reduce_and) - FOLD_1ARG_CELL(reduce_or) - FOLD_1ARG_CELL(reduce_xor) - FOLD_1ARG_CELL(reduce_xnor) - FOLD_1ARG_CELL(reduce_bool) - - FOLD_1ARG_CELL(logic_not) - FOLD_2ARG_CELL(logic_and) - FOLD_2ARG_CELL(logic_or) - - FOLD_2ARG_CELL(shl) - FOLD_2ARG_CELL(shr) - FOLD_2ARG_CELL(sshl) - FOLD_2ARG_CELL(sshr) - FOLD_2ARG_CELL(shift) - FOLD_2ARG_CELL(shiftx) - - FOLD_2ARG_CELL(lt) - FOLD_2ARG_CELL(le) - FOLD_2ARG_CELL(eq) - FOLD_2ARG_CELL(ne) - FOLD_2ARG_CELL(gt) - FOLD_2ARG_CELL(ge) - - FOLD_2ARG_CELL(add) - FOLD_2ARG_CELL(sub) - FOLD_2ARG_CELL(mul) - FOLD_2ARG_CELL(div) - FOLD_2ARG_CELL(mod) - FOLD_2ARG_CELL(pow) - - FOLD_1ARG_CELL(pos) - FOLD_1ARG_CELL(neg) - - // be very conservative with optimizing $mux cells as we do not want to break mux trees - if (cell->type == "$mux") { - RTLIL::SigSpec input = assign_map(cell->getPort("\\S")); - RTLIL::SigSpec inA = assign_map(cell->getPort("\\A")); - RTLIL::SigSpec inB = assign_map(cell->getPort("\\B")); - if (input.is_fully_const()) - ACTION_DO("\\Y", input.as_bool() ? cell->getPort("\\B") : cell->getPort("\\A")); - else if (inA == inB) - ACTION_DO("\\Y", cell->getPort("\\A")); - } - - if (!keepdc && cell->type == "$mul") - { - bool a_signed = cell->parameters["\\A_SIGNED"].as_bool(); - bool b_signed = cell->parameters["\\B_SIGNED"].as_bool(); - bool swapped_ab = false; - - RTLIL::SigSpec sig_a = assign_map(cell->getPort("\\A")); - RTLIL::SigSpec sig_b = assign_map(cell->getPort("\\B")); - RTLIL::SigSpec sig_y = assign_map(cell->getPort("\\Y")); - - if (sig_b.is_fully_const() && sig_b.size() <= 32) - std::swap(sig_a, sig_b), std::swap(a_signed, b_signed), swapped_ab = true; - - if (sig_a.is_fully_def() && sig_a.size() <= 32) - { - int a_val = sig_a.as_int(); - - if (a_val == 0) - { - cover("opt.opt_const.mul_shift.zero"); - - log("Replacing multiply-by-zero cell `%s' in module `%s' with zero-driver.\n", - cell->name.c_str(), module->name.c_str()); - - module->connect(RTLIL::SigSig(sig_y, RTLIL::SigSpec(0, sig_y.size()))); - module->remove(cell); - - did_something = true; - goto next_cell; - } - - for (int i = 1; i < (a_signed ? sig_a.size()-1 : sig_a.size()); i++) - if (a_val == (1 << i)) - { - if (swapped_ab) - cover("opt.opt_const.mul_shift.swapped"); - else - cover("opt.opt_const.mul_shift.unswapped"); - - log("Replacing multiply-by-%d cell `%s' in module `%s' with shift-by-%d.\n", - a_val, cell->name.c_str(), module->name.c_str(), i); - - if (!swapped_ab) { - cell->setPort("\\A", cell->getPort("\\B")); - cell->parameters.at("\\A_WIDTH") = cell->parameters.at("\\B_WIDTH"); - cell->parameters.at("\\A_SIGNED") = cell->parameters.at("\\B_SIGNED"); - } - - std::vector new_b = RTLIL::SigSpec(i, 6); - - while (GetSize(new_b) > 1 && new_b.back() == RTLIL::State::S0) - new_b.pop_back(); - - cell->type = "$shl"; - cell->parameters["\\B_WIDTH"] = GetSize(new_b); - cell->parameters["\\B_SIGNED"] = false; - cell->setPort("\\B", new_b); - cell->check(); - - did_something = true; - goto next_cell; - } - } - } - - next_cell:; -#undef ACTION_DO -#undef ACTION_DO_Y -#undef FOLD_1ARG_CELL -#undef FOLD_2ARG_CELL - } -} - -struct OptConstPass : public Pass { - OptConstPass() : Pass("opt_const", "perform const folding") { } - virtual void help() - { - // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| - log("\n"); - log(" opt_const [options] [selection]\n"); - log("\n"); - log("This pass performs const folding on internal cell types with constant inputs.\n"); - log("\n"); - log(" -mux_undef\n"); - log(" remove 'undef' inputs from $mux, $pmux and $_MUX_ cells\n"); - log("\n"); - log(" -mux_bool\n"); - log(" replace $mux cells with inverters or buffers when possible\n"); - log("\n"); - log(" -undriven\n"); - log(" replace undriven nets with undef (x) constants\n"); - log("\n"); - log(" -clkinv\n"); - log(" optimize clock inverters by changing FF types\n"); - log("\n"); - log(" -fine\n"); - log(" perform fine-grain optimizations\n"); - log("\n"); - log(" -full\n"); - log(" alias for -mux_undef -mux_bool -undriven -fine\n"); - log("\n"); - log(" -keepdc\n"); - log(" some optimizations change the behavior of the circuit with respect to\n"); - log(" don't-care bits. for example in 'a+0' a single x-bit in 'a' will cause\n"); - log(" all result bits to be set to x. this behavior changes when 'a+0' is\n"); - log(" replaced by 'a'. the -keepdc option disables all such optimizations.\n"); - log("\n"); - } - virtual void execute(std::vector args, RTLIL::Design *design) - { - bool mux_undef = false; - bool mux_bool = false; - bool undriven = false; - bool clkinv = false; - bool do_fine = false; - bool keepdc = false; - - log_header("Executing OPT_CONST pass (perform const folding).\n"); - log_push(); - - size_t argidx; - for (argidx = 1; argidx < args.size(); argidx++) { - if (args[argidx] == "-mux_undef") { - mux_undef = true; - continue; - } - if (args[argidx] == "-mux_bool") { - mux_bool = true; - continue; - } - if (args[argidx] == "-undriven") { - undriven = true; - continue; - } - if (args[argidx] == "-clkinv") { - clkinv = true; - continue; - } - if (args[argidx] == "-fine") { - do_fine = true; - continue; - } - if (args[argidx] == "-full") { - mux_undef = true; - mux_bool = true; - undriven = true; - do_fine = true; - continue; - } - if (args[argidx] == "-keepdc") { - keepdc = true; - continue; - } - break; - } - extra_args(args, argidx, design); - - for (auto module : design->selected_modules()) - { - if (undriven) - replace_undriven(design, module); - - do { - do { - did_something = false; - replace_const_cells(design, module, false, mux_undef, mux_bool, do_fine, keepdc, clkinv); - if (did_something) - design->scratchpad_set_bool("opt.did_something", true); - } while (did_something); - replace_const_cells(design, module, true, mux_undef, mux_bool, do_fine, keepdc, clkinv); - } while (did_something); - } - - log_pop(); - } -} OptConstPass; - -PRIVATE_NAMESPACE_END diff --git a/passes/opt/opt_expr.cc b/passes/opt/opt_expr.cc new file mode 100644 index 000000000..09dacf394 --- /dev/null +++ b/passes/opt/opt_expr.cc @@ -0,0 +1,1164 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Clifford 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/celltypes.h" +#include "kernel/utils.h" +#include "kernel/log.h" +#include +#include +#include + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +bool did_something; + +void replace_undriven(RTLIL::Design *design, RTLIL::Module *module) +{ + CellTypes ct(design); + SigMap sigmap(module); + SigPool driven_signals; + SigPool used_signals; + SigPool all_signals; + + for (auto cell : module->cells()) + for (auto &conn : cell->connections()) { + if (!ct.cell_known(cell->type) || ct.cell_output(cell->type, conn.first)) + driven_signals.add(sigmap(conn.second)); + if (!ct.cell_known(cell->type) || ct.cell_input(cell->type, conn.first)) + used_signals.add(sigmap(conn.second)); + } + + for (auto wire : module->wires()) { + if (wire->port_input) + driven_signals.add(sigmap(wire)); + if (wire->port_output) + used_signals.add(sigmap(wire)); + all_signals.add(sigmap(wire)); + } + + all_signals.del(driven_signals); + RTLIL::SigSpec undriven_signals = all_signals.export_all(); + + for (auto &c : undriven_signals.chunks()) + { + RTLIL::SigSpec sig = c; + + if (c.wire->name[0] == '$') + sig = used_signals.extract(sig); + if (sig.size() == 0) + continue; + + log("Setting undriven signal in %s to undef: %s\n", RTLIL::id2cstr(module->name), log_signal(c)); + module->connect(RTLIL::SigSig(c, RTLIL::SigSpec(RTLIL::State::Sx, c.width))); + did_something = true; + } +} + +void replace_cell(SigMap &assign_map, RTLIL::Module *module, RTLIL::Cell *cell, std::string info, std::string out_port, RTLIL::SigSpec out_val) +{ + RTLIL::SigSpec Y = cell->getPort(out_port); + out_val.extend_u0(Y.size(), false); + + log("Replacing %s cell `%s' (%s) in module `%s' with constant driver `%s = %s'.\n", + cell->type.c_str(), cell->name.c_str(), info.c_str(), + module->name.c_str(), log_signal(Y), log_signal(out_val)); + // log_cell(cell); + assign_map.add(Y, out_val); + module->connect(Y, out_val); + module->remove(cell); + did_something = true; +} + +bool group_cell_inputs(RTLIL::Module *module, RTLIL::Cell *cell, bool commutative, SigMap &sigmap) +{ + std::string b_name = cell->hasPort("\\B") ? "\\B" : "\\A"; + + bool a_signed = cell->parameters.at("\\A_SIGNED").as_bool(); + bool b_signed = cell->parameters.at(b_name + "_SIGNED").as_bool(); + + RTLIL::SigSpec sig_a = sigmap(cell->getPort("\\A")); + RTLIL::SigSpec sig_b = sigmap(cell->getPort(b_name)); + RTLIL::SigSpec sig_y = sigmap(cell->getPort("\\Y")); + + sig_a.extend_u0(sig_y.size(), a_signed); + sig_b.extend_u0(sig_y.size(), b_signed); + + std::vector bits_a = sig_a, bits_b = sig_b, bits_y = sig_y; + + enum { GRP_DYN, GRP_CONST_A, GRP_CONST_B, GRP_CONST_AB, GRP_N }; + std::map, std::set> grouped_bits[GRP_N]; + + for (int i = 0; i < GetSize(bits_y); i++) + { + int group_idx = GRP_DYN; + RTLIL::SigBit bit_a = bits_a[i], bit_b = bits_b[i]; + + if (cell->type == "$or" && (bit_a == RTLIL::State::S1 || bit_b == RTLIL::State::S1)) + bit_a = bit_b = RTLIL::State::S1; + + if (cell->type == "$and" && (bit_a == RTLIL::State::S0 || bit_b == RTLIL::State::S0)) + bit_a = bit_b = RTLIL::State::S0; + + if (bit_a.wire == NULL && bit_b.wire == NULL) + group_idx = GRP_CONST_AB; + else if (bit_a.wire == NULL) + group_idx = GRP_CONST_A; + else if (bit_b.wire == NULL && commutative) + group_idx = GRP_CONST_A, std::swap(bit_a, bit_b); + else if (bit_b.wire == NULL) + group_idx = GRP_CONST_B; + + grouped_bits[group_idx][std::pair(bit_a, bit_b)].insert(bits_y[i]); + } + + for (int i = 0; i < GRP_N; i++) + if (GetSize(grouped_bits[i]) == GetSize(bits_y)) + return false; + + log("Replacing %s cell `%s' in module `%s' with cells using grouped bits:\n", + log_id(cell->type), log_id(cell), log_id(module)); + + for (int i = 0; i < GRP_N; i++) + { + if (grouped_bits[i].empty()) + continue; + + RTLIL::Wire *new_y = module->addWire(NEW_ID, GetSize(grouped_bits[i])); + RTLIL::SigSpec new_a, new_b; + RTLIL::SigSig new_conn; + + for (auto &it : grouped_bits[i]) { + for (auto &bit : it.second) { + new_conn.first.append_bit(bit); + new_conn.second.append_bit(RTLIL::SigBit(new_y, new_a.size())); + } + new_a.append_bit(it.first.first); + new_b.append_bit(it.first.second); + } + + RTLIL::Cell *c = module->addCell(NEW_ID, cell->type); + + c->setPort("\\A", new_a); + c->parameters["\\A_WIDTH"] = new_a.size(); + c->parameters["\\A_SIGNED"] = false; + + if (b_name == "\\B") { + c->setPort("\\B", new_b); + c->parameters["\\B_WIDTH"] = new_b.size(); + c->parameters["\\B_SIGNED"] = false; + } + + c->setPort("\\Y", new_y); + c->parameters["\\Y_WIDTH"] = new_y->width; + c->check(); + + module->connect(new_conn); + + log(" New cell `%s': A=%s", log_id(c), log_signal(new_a)); + if (b_name == "\\B") + log(", B=%s", log_signal(new_b)); + log("\n"); + } + + cover_list("opt.opt_expr.fine.group", "$not", "$pos", "$and", "$or", "$xor", "$xnor", cell->type.str()); + + module->remove(cell); + did_something = true; + return true; +} + +void handle_polarity_inv(Cell *cell, IdString port, IdString param, const SigMap &assign_map, const dict &invert_map) +{ + SigSpec sig = assign_map(cell->getPort(port)); + if (invert_map.count(sig)) { + log("Inverting %s of %s cell `%s' in module `%s': %s -> %s\n", + log_id(port), log_id(cell->type), log_id(cell), log_id(cell->module), + log_signal(sig), log_signal(invert_map.at(sig))); + cell->setPort(port, (invert_map.at(sig))); + cell->setParam(param, !cell->getParam(param).as_bool()); + } +} + +void handle_clkpol_celltype_swap(Cell *cell, string type1, string type2, IdString port, const SigMap &assign_map, const dict &invert_map) +{ + log_assert(GetSize(type1) == GetSize(type2)); + string cell_type = cell->type.str(); + + if (GetSize(type1) != GetSize(cell_type)) + return; + + for (int i = 0; i < GetSize(type1); i++) { + log_assert((type1[i] == '?') == (type2[i] == '?')); + if (type1[i] == '?') { + if (cell_type[i] != '0' && cell_type[i] != '1' && cell_type[i] != 'N' && cell_type[i] != 'P') + return; + type1[i] = cell_type[i]; + type2[i] = cell_type[i]; + } + } + + if (cell->type.in(type1, type2)) { + SigSpec sig = assign_map(cell->getPort(port)); + if (invert_map.count(sig)) { + log("Inverting %s of %s cell `%s' in module `%s': %s -> %s\n", + log_id(port), log_id(cell->type), log_id(cell), log_id(cell->module), + log_signal(sig), log_signal(invert_map.at(sig))); + cell->setPort(port, (invert_map.at(sig))); + cell->type = cell->type == type1 ? type2 : type1; + } + } +} + +bool is_one_or_minus_one(const Const &value, bool is_signed, bool &is_negative) +{ + bool all_bits_one = true; + bool last_bit_one = true; + + if (GetSize(value.bits) < 1) + return false; + + if (GetSize(value.bits) == 1) { + if (value.bits[0] != State::S1) + return false; + if (is_signed) + is_negative = true; + return true; + } + + for (int i = 0; i < GetSize(value.bits); i++) { + if (value.bits[i] != State::S1) + all_bits_one = false; + if (value.bits[i] != (i ? State::S0 : State::S1)) + last_bit_one = false; + } + + if (all_bits_one && is_signed) { + is_negative = true; + return true; + } + + return last_bit_one; +} + +void replace_const_cells(RTLIL::Design *design, RTLIL::Module *module, bool consume_x, bool mux_undef, bool mux_bool, bool do_fine, bool keepdc, bool clkinv) +{ + if (!design->selected(module)) + return; + + CellTypes ct_combinational; + ct_combinational.setup_internals(); + ct_combinational.setup_stdcells(); + + SigMap assign_map(module); + dict invert_map; + + TopoSort> cells; + dict> cell_to_inbit; + dict> outbit_to_cell; + + for (auto cell : module->cells()) + if (design->selected(module, cell) && cell->type[0] == '$') { + if ((cell->type == "$_NOT_" || cell->type == "$not" || cell->type == "$logic_not") && + cell->getPort("\\A").size() == 1 && cell->getPort("\\Y").size() == 1) + invert_map[assign_map(cell->getPort("\\Y"))] = assign_map(cell->getPort("\\A")); + if ((cell->type == "$mux" || cell->type == "$_MUX_") && cell->getPort("\\A") == SigSpec(State::S1) && cell->getPort("\\B") == SigSpec(State::S0)) + invert_map[assign_map(cell->getPort("\\Y"))] = assign_map(cell->getPort("\\S")); + if (ct_combinational.cell_known(cell->type)) + for (auto &conn : cell->connections()) { + RTLIL::SigSpec sig = assign_map(conn.second); + sig.remove_const(); + if (ct_combinational.cell_input(cell->type, conn.first)) + cell_to_inbit[cell].insert(sig.begin(), sig.end()); + if (ct_combinational.cell_output(cell->type, conn.first)) + for (auto &bit : sig) + outbit_to_cell[bit].insert(cell); + } + cells.node(cell); + } + + for (auto &it_right : cell_to_inbit) + for (auto &it_sigbit : it_right.second) + for (auto &it_left : outbit_to_cell[it_sigbit]) + cells.edge(it_left, it_right.first); + + cells.sort(); + + for (auto cell : cells.sorted) + { +#define ACTION_DO(_p_, _s_) do { cover("opt.opt_expr.action_" S__LINE__); replace_cell(assign_map, module, cell, input.as_string(), _p_, _s_); goto next_cell; } while (0) +#define ACTION_DO_Y(_v_) ACTION_DO("\\Y", RTLIL::SigSpec(RTLIL::State::S ## _v_)) + + if (clkinv) + { + if (cell->type.in("$dff", "$dffe", "$dffsr", "$adff", "$fsm", "$memrd", "$memwr")) + handle_polarity_inv(cell, "\\CLK", "\\CLK_POLARITY", assign_map, invert_map); + + if (cell->type.in("$sr", "$dffsr", "$dlatchsr")) { + handle_polarity_inv(cell, "\\SET", "\\SET_POLARITY", assign_map, invert_map); + handle_polarity_inv(cell, "\\CLR", "\\CLR_POLARITY", assign_map, invert_map); + } + + if (cell->type.in("$dffe", "$dlatch", "$dlatchsr")) + handle_polarity_inv(cell, "\\EN", "\\EN_POLARITY", assign_map, invert_map); + + handle_clkpol_celltype_swap(cell, "$_SR_N?_", "$_SR_P?_", "\\S", assign_map, invert_map); + handle_clkpol_celltype_swap(cell, "$_SR_?N_", "$_SR_?P_", "\\R", assign_map, invert_map); + + handle_clkpol_celltype_swap(cell, "$_DFF_N_", "$_DFF_P_", "\\C", assign_map, invert_map); + + handle_clkpol_celltype_swap(cell, "$_DFFE_N?_", "$_DFFE_P?_", "\\C", assign_map, invert_map); + handle_clkpol_celltype_swap(cell, "$_DFFE_?N_", "$_DFFE_?P_", "\\E", assign_map, invert_map); + + handle_clkpol_celltype_swap(cell, "$_DFF_N??_", "$_DFF_P??_", "\\C", assign_map, invert_map); + handle_clkpol_celltype_swap(cell, "$_DFF_?N?_", "$_DFF_?P?_", "\\R", assign_map, invert_map); + + handle_clkpol_celltype_swap(cell, "$_DFFSR_N??_", "$_DFFSR_P??_", "\\C", assign_map, invert_map); + handle_clkpol_celltype_swap(cell, "$_DFFSR_?N?_", "$_DFFSR_?P?_", "\\S", assign_map, invert_map); + handle_clkpol_celltype_swap(cell, "$_DFFSR_??N_", "$_DFFSR_??P_", "\\R", assign_map, invert_map); + + handle_clkpol_celltype_swap(cell, "$_DLATCH_N_", "$_DLATCH_P_", "\\E", assign_map, invert_map); + + handle_clkpol_celltype_swap(cell, "$_DLATCHSR_N??_", "$_DLATCHSR_P??_", "\\E", assign_map, invert_map); + handle_clkpol_celltype_swap(cell, "$_DLATCHSR_?N?_", "$_DLATCHSR_?P?_", "\\S", assign_map, invert_map); + handle_clkpol_celltype_swap(cell, "$_DLATCHSR_??N_", "$_DLATCHSR_??P_", "\\R", assign_map, invert_map); + } + + if (do_fine) + { + if (cell->type == "$not" || cell->type == "$pos" || + cell->type == "$and" || cell->type == "$or" || cell->type == "$xor" || cell->type == "$xnor") + if (group_cell_inputs(module, cell, true, assign_map)) + goto next_cell; + + if (cell->type == "$reduce_and") + { + RTLIL::SigSpec sig_a = assign_map(cell->getPort("\\A")); + + RTLIL::State new_a = RTLIL::State::S1; + for (auto &bit : sig_a.to_sigbit_vector()) + if (bit == RTLIL::State::Sx) { + if (new_a == RTLIL::State::S1) + new_a = RTLIL::State::Sx; + } else if (bit == RTLIL::State::S0) { + new_a = RTLIL::State::S0; + break; + } else if (bit.wire != NULL) { + new_a = RTLIL::State::Sm; + } + + if (new_a != RTLIL::State::Sm && RTLIL::SigSpec(new_a) != sig_a) { + cover("opt.opt_expr.fine.$reduce_and"); + log("Replacing port A of %s cell `%s' in module `%s' with constant driver: %s -> %s\n", + cell->type.c_str(), cell->name.c_str(), module->name.c_str(), log_signal(sig_a), log_signal(new_a)); + cell->setPort("\\A", sig_a = new_a); + cell->parameters.at("\\A_WIDTH") = 1; + did_something = true; + } + } + + if (cell->type == "$logic_not" || cell->type == "$logic_and" || cell->type == "$logic_or" || cell->type == "$reduce_or" || cell->type == "$reduce_bool") + { + RTLIL::SigSpec sig_a = assign_map(cell->getPort("\\A")); + + RTLIL::State new_a = RTLIL::State::S0; + for (auto &bit : sig_a.to_sigbit_vector()) + if (bit == RTLIL::State::Sx) { + if (new_a == RTLIL::State::S0) + new_a = RTLIL::State::Sx; + } else if (bit == RTLIL::State::S1) { + new_a = RTLIL::State::S1; + break; + } else if (bit.wire != NULL) { + new_a = RTLIL::State::Sm; + } + + if (new_a != RTLIL::State::Sm && RTLIL::SigSpec(new_a) != sig_a) { + cover_list("opt.opt_expr.fine.A", "$logic_not", "$logic_and", "$logic_or", "$reduce_or", "$reduce_bool", cell->type.str()); + log("Replacing port A of %s cell `%s' in module `%s' with constant driver: %s -> %s\n", + cell->type.c_str(), cell->name.c_str(), module->name.c_str(), log_signal(sig_a), log_signal(new_a)); + cell->setPort("\\A", sig_a = new_a); + cell->parameters.at("\\A_WIDTH") = 1; + did_something = true; + } + } + + if (cell->type == "$logic_and" || cell->type == "$logic_or") + { + RTLIL::SigSpec sig_b = assign_map(cell->getPort("\\B")); + + RTLIL::State new_b = RTLIL::State::S0; + for (auto &bit : sig_b.to_sigbit_vector()) + if (bit == RTLIL::State::Sx) { + if (new_b == RTLIL::State::S0) + new_b = RTLIL::State::Sx; + } else if (bit == RTLIL::State::S1) { + new_b = RTLIL::State::S1; + break; + } else if (bit.wire != NULL) { + new_b = RTLIL::State::Sm; + } + + if (new_b != RTLIL::State::Sm && RTLIL::SigSpec(new_b) != sig_b) { + cover_list("opt.opt_expr.fine.B", "$logic_and", "$logic_or", cell->type.str()); + log("Replacing port B of %s cell `%s' in module `%s' with constant driver: %s -> %s\n", + cell->type.c_str(), cell->name.c_str(), module->name.c_str(), log_signal(sig_b), log_signal(new_b)); + cell->setPort("\\B", sig_b = new_b); + cell->parameters.at("\\B_WIDTH") = 1; + did_something = true; + } + } + } + + if (cell->type == "$logic_or" && (assign_map(cell->getPort("\\A")) == RTLIL::State::S1 || assign_map(cell->getPort("\\B")) == RTLIL::State::S1)) { + cover("opt.opt_expr.one_high"); + replace_cell(assign_map, module, cell, "one high", "\\Y", RTLIL::State::S1); + goto next_cell; + } + + if (cell->type == "$logic_and" && (assign_map(cell->getPort("\\A")) == RTLIL::State::S0 || assign_map(cell->getPort("\\B")) == RTLIL::State::S0)) { + cover("opt.opt_expr.one_low"); + replace_cell(assign_map, module, cell, "one low", "\\Y", RTLIL::State::S0); + goto next_cell; + } + + if (cell->type == "$reduce_xor" || cell->type == "$reduce_xnor" || cell->type == "$shift" || cell->type == "$shiftx" || + cell->type == "$shl" || cell->type == "$shr" || cell->type == "$sshl" || cell->type == "$sshr" || + cell->type == "$lt" || cell->type == "$le" || cell->type == "$ge" || cell->type == "$gt" || + cell->type == "$neg" || cell->type == "$add" || cell->type == "$sub" || + cell->type == "$mul" || cell->type == "$div" || cell->type == "$mod" || cell->type == "$pow") + { + RTLIL::SigSpec sig_a = assign_map(cell->getPort("\\A")); + RTLIL::SigSpec sig_b = cell->hasPort("\\B") ? assign_map(cell->getPort("\\B")) : RTLIL::SigSpec(); + + if (cell->type == "$shl" || cell->type == "$shr" || cell->type == "$sshl" || cell->type == "$sshr" || cell->type == "$shift" || cell->type == "$shiftx") + sig_a = RTLIL::SigSpec(); + + for (auto &bit : sig_a.to_sigbit_vector()) + if (bit == RTLIL::State::Sx) + goto found_the_x_bit; + + for (auto &bit : sig_b.to_sigbit_vector()) + if (bit == RTLIL::State::Sx) + goto found_the_x_bit; + + if (0) { + found_the_x_bit: + cover_list("opt.opt_expr.xbit", "$reduce_xor", "$reduce_xnor", "$shl", "$shr", "$sshl", "$sshr", "$shift", "$shiftx", + "$lt", "$le", "$ge", "$gt", "$neg", "$add", "$sub", "$mul", "$div", "$mod", "$pow", cell->type.str()); + if (cell->type == "$reduce_xor" || cell->type == "$reduce_xnor" || + cell->type == "$lt" || cell->type == "$le" || cell->type == "$ge" || cell->type == "$gt") + replace_cell(assign_map, module, cell, "x-bit in input", "\\Y", RTLIL::State::Sx); + else + replace_cell(assign_map, module, cell, "x-bit in input", "\\Y", RTLIL::SigSpec(RTLIL::State::Sx, cell->getPort("\\Y").size())); + goto next_cell; + } + } + + if ((cell->type == "$_NOT_" || cell->type == "$not" || cell->type == "$logic_not") && cell->getPort("\\Y").size() == 1 && + invert_map.count(assign_map(cell->getPort("\\A"))) != 0) { + cover_list("opt.opt_expr.invert.double", "$_NOT_", "$not", "$logic_not", cell->type.str()); + replace_cell(assign_map, module, cell, "double_invert", "\\Y", invert_map.at(assign_map(cell->getPort("\\A")))); + goto next_cell; + } + + if ((cell->type == "$_MUX_" || cell->type == "$mux") && invert_map.count(assign_map(cell->getPort("\\S"))) != 0) { + cover_list("opt.opt_expr.invert.muxsel", "$_MUX_", "$mux", cell->type.str()); + log("Optimizing away select inverter for %s cell `%s' in module `%s'.\n", log_id(cell->type), log_id(cell), log_id(module)); + RTLIL::SigSpec tmp = cell->getPort("\\A"); + cell->setPort("\\A", cell->getPort("\\B")); + cell->setPort("\\B", tmp); + cell->setPort("\\S", invert_map.at(assign_map(cell->getPort("\\S")))); + did_something = true; + goto next_cell; + } + + if (cell->type == "$_NOT_") { + RTLIL::SigSpec input = cell->getPort("\\A"); + assign_map.apply(input); + if (input.match("1")) ACTION_DO_Y(0); + if (input.match("0")) ACTION_DO_Y(1); + if (input.match("*")) ACTION_DO_Y(x); + } + + if (cell->type == "$_AND_") { + RTLIL::SigSpec input; + input.append(cell->getPort("\\B")); + input.append(cell->getPort("\\A")); + assign_map.apply(input); + if (input.match(" 0")) ACTION_DO_Y(0); + if (input.match("0 ")) ACTION_DO_Y(0); + if (input.match("11")) ACTION_DO_Y(1); + if (input.match("**")) ACTION_DO_Y(x); + if (input.match("1*")) ACTION_DO_Y(x); + if (input.match("*1")) ACTION_DO_Y(x); + if (consume_x) { + if (input.match(" *")) ACTION_DO_Y(0); + if (input.match("* ")) ACTION_DO_Y(0); + } + if (input.match(" 1")) ACTION_DO("\\Y", input.extract(1, 1)); + if (input.match("1 ")) ACTION_DO("\\Y", input.extract(0, 1)); + } + + if (cell->type == "$_OR_") { + RTLIL::SigSpec input; + input.append(cell->getPort("\\B")); + input.append(cell->getPort("\\A")); + assign_map.apply(input); + if (input.match(" 1")) ACTION_DO_Y(1); + if (input.match("1 ")) ACTION_DO_Y(1); + if (input.match("00")) ACTION_DO_Y(0); + if (input.match("**")) ACTION_DO_Y(x); + if (input.match("0*")) ACTION_DO_Y(x); + if (input.match("*0")) ACTION_DO_Y(x); + if (consume_x) { + if (input.match(" *")) ACTION_DO_Y(1); + if (input.match("* ")) ACTION_DO_Y(1); + } + if (input.match(" 0")) ACTION_DO("\\Y", input.extract(1, 1)); + if (input.match("0 ")) ACTION_DO("\\Y", input.extract(0, 1)); + } + + if (cell->type == "$_XOR_") { + RTLIL::SigSpec input; + input.append(cell->getPort("\\B")); + input.append(cell->getPort("\\A")); + assign_map.apply(input); + if (input.match("00")) ACTION_DO_Y(0); + if (input.match("01")) ACTION_DO_Y(1); + if (input.match("10")) ACTION_DO_Y(1); + if (input.match("11")) ACTION_DO_Y(0); + if (input.match(" *")) ACTION_DO_Y(x); + if (input.match("* ")) ACTION_DO_Y(x); + if (input.match(" 0")) ACTION_DO("\\Y", input.extract(1, 1)); + if (input.match("0 ")) ACTION_DO("\\Y", input.extract(0, 1)); + } + + if (cell->type == "$_MUX_") { + RTLIL::SigSpec input; + input.append(cell->getPort("\\S")); + input.append(cell->getPort("\\B")); + input.append(cell->getPort("\\A")); + assign_map.apply(input); + if (input.extract(2, 1) == input.extract(1, 1)) + ACTION_DO("\\Y", input.extract(2, 1)); + if (input.match(" 0")) ACTION_DO("\\Y", input.extract(2, 1)); + if (input.match(" 1")) ACTION_DO("\\Y", input.extract(1, 1)); + if (input.match("01 ")) ACTION_DO("\\Y", input.extract(0, 1)); + if (input.match("10 ")) { + cover("opt.opt_expr.mux_to_inv"); + cell->type = "$_NOT_"; + cell->setPort("\\A", input.extract(0, 1)); + cell->unsetPort("\\B"); + cell->unsetPort("\\S"); + goto next_cell; + } + if (input.match("11 ")) ACTION_DO_Y(1); + if (input.match("00 ")) ACTION_DO_Y(0); + if (input.match("** ")) ACTION_DO_Y(x); + if (input.match("01*")) ACTION_DO_Y(x); + if (input.match("10*")) ACTION_DO_Y(x); + if (mux_undef) { + if (input.match("* ")) ACTION_DO("\\Y", input.extract(1, 1)); + if (input.match(" * ")) ACTION_DO("\\Y", input.extract(2, 1)); + if (input.match(" *")) ACTION_DO("\\Y", input.extract(2, 1)); + } + } + + if (cell->type == "$eq" || cell->type == "$ne" || cell->type == "$eqx" || cell->type == "$nex") + { + RTLIL::SigSpec a = cell->getPort("\\A"); + RTLIL::SigSpec b = cell->getPort("\\B"); + + if (cell->parameters["\\A_WIDTH"].as_int() != cell->parameters["\\B_WIDTH"].as_int()) { + int width = max(cell->parameters["\\A_WIDTH"].as_int(), cell->parameters["\\B_WIDTH"].as_int()); + a.extend_u0(width, cell->parameters["\\A_SIGNED"].as_bool() && cell->parameters["\\B_SIGNED"].as_bool()); + b.extend_u0(width, cell->parameters["\\A_SIGNED"].as_bool() && cell->parameters["\\B_SIGNED"].as_bool()); + } + + RTLIL::SigSpec new_a, new_b; + + log_assert(GetSize(a) == GetSize(b)); + for (int i = 0; i < GetSize(a); i++) { + if (a[i].wire == NULL && b[i].wire == NULL && a[i] != b[i] && a[i].data <= RTLIL::State::S1 && b[i].data <= RTLIL::State::S1) { + cover_list("opt.opt_expr.eqneq.isneq", "$eq", "$ne", "$eqx", "$nex", cell->type.str()); + RTLIL::SigSpec new_y = RTLIL::SigSpec((cell->type == "$eq" || cell->type == "$eqx") ? RTLIL::State::S0 : RTLIL::State::S1); + new_y.extend_u0(cell->parameters["\\Y_WIDTH"].as_int(), false); + replace_cell(assign_map, module, cell, "isneq", "\\Y", new_y); + goto next_cell; + } + if (a[i] == b[i]) + continue; + new_a.append(a[i]); + new_b.append(b[i]); + } + + if (new_a.size() == 0) { + cover_list("opt.opt_expr.eqneq.empty", "$eq", "$ne", "$eqx", "$nex", cell->type.str()); + RTLIL::SigSpec new_y = RTLIL::SigSpec((cell->type == "$eq" || cell->type == "$eqx") ? RTLIL::State::S1 : RTLIL::State::S0); + new_y.extend_u0(cell->parameters["\\Y_WIDTH"].as_int(), false); + replace_cell(assign_map, module, cell, "empty", "\\Y", new_y); + goto next_cell; + } + + if (new_a.size() < a.size() || new_b.size() < b.size()) { + cover_list("opt.opt_expr.eqneq.resize", "$eq", "$ne", "$eqx", "$nex", cell->type.str()); + cell->setPort("\\A", new_a); + cell->setPort("\\B", new_b); + cell->parameters["\\A_WIDTH"] = new_a.size(); + cell->parameters["\\B_WIDTH"] = new_b.size(); + } + } + + if ((cell->type == "$eq" || cell->type == "$ne") && cell->parameters["\\Y_WIDTH"].as_int() == 1 && + cell->parameters["\\A_WIDTH"].as_int() == 1 && cell->parameters["\\B_WIDTH"].as_int() == 1) + { + RTLIL::SigSpec a = assign_map(cell->getPort("\\A")); + RTLIL::SigSpec b = assign_map(cell->getPort("\\B")); + + if (a.is_fully_const() && !b.is_fully_const()) { + cover_list("opt.opt_expr.eqneq.swapconst", "$eq", "$ne", cell->type.str()); + cell->setPort("\\A", b); + cell->setPort("\\B", a); + std::swap(a, b); + } + + if (b.is_fully_const()) { + if (b.as_bool() == (cell->type == "$eq")) { + RTLIL::SigSpec input = b; + ACTION_DO("\\Y", cell->getPort("\\A")); + } else { + cover_list("opt.opt_expr.eqneq.isnot", "$eq", "$ne", cell->type.str()); + log("Replacing %s cell `%s' in module `%s' with inverter.\n", log_id(cell->type), log_id(cell), log_id(module)); + cell->type = "$not"; + cell->parameters.erase("\\B_WIDTH"); + cell->parameters.erase("\\B_SIGNED"); + cell->unsetPort("\\B"); + did_something = true; + } + goto next_cell; + } + } + + if ((cell->type == "$eq" || cell->type == "$ne") && + (assign_map(cell->getPort("\\A")).is_fully_zero() || assign_map(cell->getPort("\\B")).is_fully_zero())) + { + cover_list("opt.opt_expr.eqneq.cmpzero", "$eq", "$ne", cell->type.str()); + log("Replacing %s cell `%s' in module `%s' with %s.\n", log_id(cell->type), log_id(cell), + log_id(module), "$eq" ? "$logic_not" : "$reduce_bool"); + cell->type = cell->type == "$eq" ? "$logic_not" : "$reduce_bool"; + if (assign_map(cell->getPort("\\A")).is_fully_zero()) { + cell->setPort("\\A", cell->getPort("\\B")); + cell->setParam("\\A_SIGNED", cell->getParam("\\B_SIGNED")); + cell->setParam("\\A_WIDTH", cell->getParam("\\B_WIDTH")); + } + cell->unsetPort("\\B"); + cell->unsetParam("\\B_SIGNED"); + cell->unsetParam("\\B_WIDTH"); + did_something = true; + goto next_cell; + } + + if (cell->type.in("$shl", "$shr", "$sshl", "$sshr", "$shift", "$shiftx") && assign_map(cell->getPort("\\B")).is_fully_const()) + { + bool sign_ext = cell->type == "$sshr" && cell->getParam("\\A_SIGNED").as_bool(); + int shift_bits = assign_map(cell->getPort("\\B")).as_int(cell->type.in("$shift", "$shiftx") && cell->getParam("\\B_SIGNED").as_bool()); + + if (cell->type.in("$shl", "$sshl")) + shift_bits *= -1; + + RTLIL::SigSpec sig_a = assign_map(cell->getPort("\\A")); + RTLIL::SigSpec sig_y(cell->type == "$shiftx" ? RTLIL::State::Sx : RTLIL::State::S0, cell->getParam("\\Y_WIDTH").as_int()); + + if (GetSize(sig_a) < GetSize(sig_y)) + sig_a.extend_u0(GetSize(sig_y), cell->getParam("\\A_SIGNED").as_bool()); + + for (int i = 0; i < GetSize(sig_y); i++) { + int idx = i + shift_bits; + if (0 <= idx && idx < GetSize(sig_a)) + sig_y[i] = sig_a[idx]; + else if (GetSize(sig_a) <= idx && sign_ext) + sig_y[i] = sig_a[GetSize(sig_a)-1]; + } + + cover_list("opt.opt_expr.constshift", "$shl", "$shr", "$sshl", "$sshr", "$shift", "$shiftx", cell->type.str()); + + log("Replacing %s cell `%s' (B=%s, SHR=%d) in module `%s' with fixed wiring: %s\n", + log_id(cell->type), log_id(cell), log_signal(assign_map(cell->getPort("\\B"))), shift_bits, log_id(module), log_signal(sig_y)); + + module->connect(cell->getPort("\\Y"), sig_y); + module->remove(cell); + + did_something = true; + goto next_cell; + } + + if (!keepdc) + { + bool identity_wrt_a = false; + bool identity_wrt_b = false; + bool arith_inverse = false; + + if (cell->type == "$add" || cell->type == "$sub" || cell->type == "$or" || cell->type == "$xor") + { + RTLIL::SigSpec a = assign_map(cell->getPort("\\A")); + RTLIL::SigSpec b = assign_map(cell->getPort("\\B")); + + if (cell->type != "$sub" && a.is_fully_const() && a.as_bool() == false) + identity_wrt_b = true; + + if (b.is_fully_const() && b.as_bool() == false) + identity_wrt_a = true; + } + + if (cell->type == "$shl" || cell->type == "$shr" || cell->type == "$sshl" || cell->type == "$sshr" || cell->type == "$shift" || cell->type == "$shiftx") + { + RTLIL::SigSpec b = assign_map(cell->getPort("\\B")); + + if (b.is_fully_const() && b.as_bool() == false) + identity_wrt_a = true; + } + + if (cell->type == "$mul") + { + RTLIL::SigSpec a = assign_map(cell->getPort("\\A")); + RTLIL::SigSpec b = assign_map(cell->getPort("\\B")); + + if (a.is_fully_const() && is_one_or_minus_one(a.as_const(), cell->getParam("\\A_SIGNED").as_bool(), arith_inverse)) + identity_wrt_b = true; + else + if (b.is_fully_const() && is_one_or_minus_one(b.as_const(), cell->getParam("\\B_SIGNED").as_bool(), arith_inverse)) + identity_wrt_a = true; + } + + if (cell->type == "$div") + { + RTLIL::SigSpec b = assign_map(cell->getPort("\\B")); + + if (b.is_fully_const() && b.size() <= 32 && b.as_int() == 1) + identity_wrt_a = true; + } + + if (identity_wrt_a || identity_wrt_b) + { + if (identity_wrt_a) + cover_list("opt.opt_expr.identwrt.a", "$add", "$sub", "$or", "$xor", "$shl", "$shr", "$sshl", "$sshr", "$shift", "$shiftx", "$mul", "$div", cell->type.str()); + if (identity_wrt_b) + cover_list("opt.opt_expr.identwrt.b", "$add", "$sub", "$or", "$xor", "$shl", "$shr", "$sshl", "$sshr", "$shift", "$shiftx", "$mul", "$div", cell->type.str()); + + log("Replacing %s cell `%s' in module `%s' with identity for port %c.\n", + cell->type.c_str(), cell->name.c_str(), module->name.c_str(), identity_wrt_a ? 'A' : 'B'); + + if (!identity_wrt_a) { + cell->setPort("\\A", cell->getPort("\\B")); + cell->parameters.at("\\A_WIDTH") = cell->parameters.at("\\B_WIDTH"); + cell->parameters.at("\\A_SIGNED") = cell->parameters.at("\\B_SIGNED"); + } + + cell->type = arith_inverse ? "$neg" : "$pos"; + cell->unsetPort("\\B"); + cell->parameters.erase("\\B_WIDTH"); + cell->parameters.erase("\\B_SIGNED"); + cell->check(); + + did_something = true; + goto next_cell; + } + } + + if (mux_bool && (cell->type == "$mux" || cell->type == "$_MUX_") && + cell->getPort("\\A") == RTLIL::SigSpec(0, 1) && cell->getPort("\\B") == RTLIL::SigSpec(1, 1)) { + cover_list("opt.opt_expr.mux_bool", "$mux", "$_MUX_", cell->type.str()); + replace_cell(assign_map, module, cell, "mux_bool", "\\Y", cell->getPort("\\S")); + goto next_cell; + } + + if (mux_bool && (cell->type == "$mux" || cell->type == "$_MUX_") && + cell->getPort("\\A") == RTLIL::SigSpec(1, 1) && cell->getPort("\\B") == RTLIL::SigSpec(0, 1)) { + cover_list("opt.opt_expr.mux_invert", "$mux", "$_MUX_", cell->type.str()); + log("Replacing %s cell `%s' in module `%s' with inverter.\n", log_id(cell->type), log_id(cell), log_id(module)); + cell->setPort("\\A", cell->getPort("\\S")); + cell->unsetPort("\\B"); + cell->unsetPort("\\S"); + if (cell->type == "$mux") { + Const width = cell->parameters["\\WIDTH"]; + cell->parameters["\\A_WIDTH"] = width; + cell->parameters["\\Y_WIDTH"] = width; + cell->parameters["\\A_SIGNED"] = 0; + cell->parameters.erase("\\WIDTH"); + cell->type = "$not"; + } else + cell->type = "$_NOT_"; + did_something = true; + goto next_cell; + } + + if (consume_x && mux_bool && (cell->type == "$mux" || cell->type == "$_MUX_") && cell->getPort("\\A") == RTLIL::SigSpec(0, 1)) { + cover_list("opt.opt_expr.mux_and", "$mux", "$_MUX_", cell->type.str()); + log("Replacing %s cell `%s' in module `%s' with and-gate.\n", log_id(cell->type), log_id(cell), log_id(module)); + cell->setPort("\\A", cell->getPort("\\S")); + cell->unsetPort("\\S"); + if (cell->type == "$mux") { + Const width = cell->parameters["\\WIDTH"]; + cell->parameters["\\A_WIDTH"] = width; + cell->parameters["\\B_WIDTH"] = width; + cell->parameters["\\Y_WIDTH"] = width; + cell->parameters["\\A_SIGNED"] = 0; + cell->parameters["\\B_SIGNED"] = 0; + cell->parameters.erase("\\WIDTH"); + cell->type = "$and"; + } else + cell->type = "$_AND_"; + did_something = true; + goto next_cell; + } + + if (consume_x && mux_bool && (cell->type == "$mux" || cell->type == "$_MUX_") && cell->getPort("\\B") == RTLIL::SigSpec(1, 1)) { + cover_list("opt.opt_expr.mux_or", "$mux", "$_MUX_", cell->type.str()); + log("Replacing %s cell `%s' in module `%s' with or-gate.\n", log_id(cell->type), log_id(cell), log_id(module)); + cell->setPort("\\B", cell->getPort("\\S")); + cell->unsetPort("\\S"); + if (cell->type == "$mux") { + Const width = cell->parameters["\\WIDTH"]; + cell->parameters["\\A_WIDTH"] = width; + cell->parameters["\\B_WIDTH"] = width; + cell->parameters["\\Y_WIDTH"] = width; + cell->parameters["\\A_SIGNED"] = 0; + cell->parameters["\\B_SIGNED"] = 0; + cell->parameters.erase("\\WIDTH"); + cell->type = "$or"; + } else + cell->type = "$_OR_"; + did_something = true; + goto next_cell; + } + + if (mux_undef && (cell->type == "$mux" || cell->type == "$pmux")) { + RTLIL::SigSpec new_a, new_b, new_s; + int width = cell->getPort("\\A").size(); + if ((cell->getPort("\\A").is_fully_undef() && cell->getPort("\\B").is_fully_undef()) || + cell->getPort("\\S").is_fully_undef()) { + cover_list("opt.opt_expr.mux_undef", "$mux", "$pmux", cell->type.str()); + replace_cell(assign_map, module, cell, "mux_undef", "\\Y", cell->getPort("\\A")); + goto next_cell; + } + for (int i = 0; i < cell->getPort("\\S").size(); i++) { + RTLIL::SigSpec old_b = cell->getPort("\\B").extract(i*width, width); + RTLIL::SigSpec old_s = cell->getPort("\\S").extract(i, 1); + if (old_b.is_fully_undef() || old_s.is_fully_undef()) + continue; + new_b.append(old_b); + new_s.append(old_s); + } + new_a = cell->getPort("\\A"); + if (new_a.is_fully_undef() && new_s.size() > 0) { + new_a = new_b.extract((new_s.size()-1)*width, width); + new_b = new_b.extract(0, (new_s.size()-1)*width); + new_s = new_s.extract(0, new_s.size()-1); + } + if (new_s.size() == 0) { + cover_list("opt.opt_expr.mux_empty", "$mux", "$pmux", cell->type.str()); + replace_cell(assign_map, module, cell, "mux_empty", "\\Y", new_a); + goto next_cell; + } + if (new_a == RTLIL::SigSpec(RTLIL::State::S0) && new_b == RTLIL::SigSpec(RTLIL::State::S1)) { + cover_list("opt.opt_expr.mux_sel01", "$mux", "$pmux", cell->type.str()); + replace_cell(assign_map, module, cell, "mux_sel01", "\\Y", new_s); + goto next_cell; + } + if (cell->getPort("\\S").size() != new_s.size()) { + cover_list("opt.opt_expr.mux_reduce", "$mux", "$pmux", cell->type.str()); + log("Optimized away %d select inputs of %s cell `%s' in module `%s'.\n", + GetSize(cell->getPort("\\S")) - GetSize(new_s), log_id(cell->type), log_id(cell), log_id(module)); + cell->setPort("\\A", new_a); + cell->setPort("\\B", new_b); + cell->setPort("\\S", new_s); + if (new_s.size() > 1) { + cell->type = "$pmux"; + cell->parameters["\\S_WIDTH"] = new_s.size(); + } else { + cell->type = "$mux"; + cell->parameters.erase("\\S_WIDTH"); + } + did_something = true; + } + } + +#define FOLD_1ARG_CELL(_t) \ + if (cell->type == "$" #_t) { \ + RTLIL::SigSpec a = cell->getPort("\\A"); \ + assign_map.apply(a); \ + if (a.is_fully_const()) { \ + RTLIL::Const dummy_arg(RTLIL::State::S0, 1); \ + RTLIL::SigSpec y(RTLIL::const_ ## _t(a.as_const(), dummy_arg, \ + cell->parameters["\\A_SIGNED"].as_bool(), false, \ + cell->parameters["\\Y_WIDTH"].as_int())); \ + cover("opt.opt_expr.const.$" #_t); \ + replace_cell(assign_map, module, cell, stringf("%s", log_signal(a)), "\\Y", y); \ + goto next_cell; \ + } \ + } +#define FOLD_2ARG_CELL(_t) \ + if (cell->type == "$" #_t) { \ + RTLIL::SigSpec a = cell->getPort("\\A"); \ + RTLIL::SigSpec b = cell->getPort("\\B"); \ + assign_map.apply(a), assign_map.apply(b); \ + if (a.is_fully_const() && b.is_fully_const()) { \ + RTLIL::SigSpec y(RTLIL::const_ ## _t(a.as_const(), b.as_const(), \ + cell->parameters["\\A_SIGNED"].as_bool(), \ + cell->parameters["\\B_SIGNED"].as_bool(), \ + cell->parameters["\\Y_WIDTH"].as_int())); \ + cover("opt.opt_expr.const.$" #_t); \ + replace_cell(assign_map, module, cell, stringf("%s, %s", log_signal(a), log_signal(b)), "\\Y", y); \ + goto next_cell; \ + } \ + } + + FOLD_1ARG_CELL(not) + FOLD_2ARG_CELL(and) + FOLD_2ARG_CELL(or) + FOLD_2ARG_CELL(xor) + FOLD_2ARG_CELL(xnor) + + FOLD_1ARG_CELL(reduce_and) + FOLD_1ARG_CELL(reduce_or) + FOLD_1ARG_CELL(reduce_xor) + FOLD_1ARG_CELL(reduce_xnor) + FOLD_1ARG_CELL(reduce_bool) + + FOLD_1ARG_CELL(logic_not) + FOLD_2ARG_CELL(logic_and) + FOLD_2ARG_CELL(logic_or) + + FOLD_2ARG_CELL(shl) + FOLD_2ARG_CELL(shr) + FOLD_2ARG_CELL(sshl) + FOLD_2ARG_CELL(sshr) + FOLD_2ARG_CELL(shift) + FOLD_2ARG_CELL(shiftx) + + FOLD_2ARG_CELL(lt) + FOLD_2ARG_CELL(le) + FOLD_2ARG_CELL(eq) + FOLD_2ARG_CELL(ne) + FOLD_2ARG_CELL(gt) + FOLD_2ARG_CELL(ge) + + FOLD_2ARG_CELL(add) + FOLD_2ARG_CELL(sub) + FOLD_2ARG_CELL(mul) + FOLD_2ARG_CELL(div) + FOLD_2ARG_CELL(mod) + FOLD_2ARG_CELL(pow) + + FOLD_1ARG_CELL(pos) + FOLD_1ARG_CELL(neg) + + // be very conservative with optimizing $mux cells as we do not want to break mux trees + if (cell->type == "$mux") { + RTLIL::SigSpec input = assign_map(cell->getPort("\\S")); + RTLIL::SigSpec inA = assign_map(cell->getPort("\\A")); + RTLIL::SigSpec inB = assign_map(cell->getPort("\\B")); + if (input.is_fully_const()) + ACTION_DO("\\Y", input.as_bool() ? cell->getPort("\\B") : cell->getPort("\\A")); + else if (inA == inB) + ACTION_DO("\\Y", cell->getPort("\\A")); + } + + if (!keepdc && cell->type == "$mul") + { + bool a_signed = cell->parameters["\\A_SIGNED"].as_bool(); + bool b_signed = cell->parameters["\\B_SIGNED"].as_bool(); + bool swapped_ab = false; + + RTLIL::SigSpec sig_a = assign_map(cell->getPort("\\A")); + RTLIL::SigSpec sig_b = assign_map(cell->getPort("\\B")); + RTLIL::SigSpec sig_y = assign_map(cell->getPort("\\Y")); + + if (sig_b.is_fully_const() && sig_b.size() <= 32) + std::swap(sig_a, sig_b), std::swap(a_signed, b_signed), swapped_ab = true; + + if (sig_a.is_fully_def() && sig_a.size() <= 32) + { + int a_val = sig_a.as_int(); + + if (a_val == 0) + { + cover("opt.opt_expr.mul_shift.zero"); + + log("Replacing multiply-by-zero cell `%s' in module `%s' with zero-driver.\n", + cell->name.c_str(), module->name.c_str()); + + module->connect(RTLIL::SigSig(sig_y, RTLIL::SigSpec(0, sig_y.size()))); + module->remove(cell); + + did_something = true; + goto next_cell; + } + + for (int i = 1; i < (a_signed ? sig_a.size()-1 : sig_a.size()); i++) + if (a_val == (1 << i)) + { + if (swapped_ab) + cover("opt.opt_expr.mul_shift.swapped"); + else + cover("opt.opt_expr.mul_shift.unswapped"); + + log("Replacing multiply-by-%d cell `%s' in module `%s' with shift-by-%d.\n", + a_val, cell->name.c_str(), module->name.c_str(), i); + + if (!swapped_ab) { + cell->setPort("\\A", cell->getPort("\\B")); + cell->parameters.at("\\A_WIDTH") = cell->parameters.at("\\B_WIDTH"); + cell->parameters.at("\\A_SIGNED") = cell->parameters.at("\\B_SIGNED"); + } + + std::vector new_b = RTLIL::SigSpec(i, 6); + + while (GetSize(new_b) > 1 && new_b.back() == RTLIL::State::S0) + new_b.pop_back(); + + cell->type = "$shl"; + cell->parameters["\\B_WIDTH"] = GetSize(new_b); + cell->parameters["\\B_SIGNED"] = false; + cell->setPort("\\B", new_b); + cell->check(); + + did_something = true; + goto next_cell; + } + } + } + + next_cell:; +#undef ACTION_DO +#undef ACTION_DO_Y +#undef FOLD_1ARG_CELL +#undef FOLD_2ARG_CELL + } +} + +struct OptExprPass : public Pass { + OptExprPass() : Pass("opt_expr", "perform const folding and simple expression rewriting") { } + virtual void help() + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" opt_expr [options] [selection]\n"); + log("\n"); + log("This pass performs const folding on internal cell types with constant inputs.\n"); + log("It also performs some simple expression rewritring.\n"); + log("\n"); + log(" -mux_undef\n"); + log(" remove 'undef' inputs from $mux, $pmux and $_MUX_ cells\n"); + log("\n"); + log(" -mux_bool\n"); + log(" replace $mux cells with inverters or buffers when possible\n"); + log("\n"); + log(" -undriven\n"); + log(" replace undriven nets with undef (x) constants\n"); + log("\n"); + log(" -clkinv\n"); + log(" optimize clock inverters by changing FF types\n"); + log("\n"); + log(" -fine\n"); + log(" perform fine-grain optimizations\n"); + log("\n"); + log(" -full\n"); + log(" alias for -mux_undef -mux_bool -undriven -fine\n"); + log("\n"); + log(" -keepdc\n"); + log(" some optimizations change the behavior of the circuit with respect to\n"); + log(" don't-care bits. for example in 'a+0' a single x-bit in 'a' will cause\n"); + log(" all result bits to be set to x. this behavior changes when 'a+0' is\n"); + log(" replaced by 'a'. the -keepdc option disables all such optimizations.\n"); + log("\n"); + } + virtual void execute(std::vector args, RTLIL::Design *design) + { + bool mux_undef = false; + bool mux_bool = false; + bool undriven = false; + bool clkinv = false; + bool do_fine = false; + bool keepdc = false; + + log_header("Executing OPT_CONST pass (perform const folding).\n"); + log_push(); + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + if (args[argidx] == "-mux_undef") { + mux_undef = true; + continue; + } + if (args[argidx] == "-mux_bool") { + mux_bool = true; + continue; + } + if (args[argidx] == "-undriven") { + undriven = true; + continue; + } + if (args[argidx] == "-clkinv") { + clkinv = true; + continue; + } + if (args[argidx] == "-fine") { + do_fine = true; + continue; + } + if (args[argidx] == "-full") { + mux_undef = true; + mux_bool = true; + undriven = true; + do_fine = true; + continue; + } + if (args[argidx] == "-keepdc") { + keepdc = true; + continue; + } + break; + } + extra_args(args, argidx, design); + + for (auto module : design->selected_modules()) + { + if (undriven) + replace_undriven(design, module); + + do { + do { + did_something = false; + replace_const_cells(design, module, false, mux_undef, mux_bool, do_fine, keepdc, clkinv); + if (did_something) + design->scratchpad_set_bool("opt.did_something", true); + } while (did_something); + replace_const_cells(design, module, true, mux_undef, mux_bool, do_fine, keepdc, clkinv); + } while (did_something); + } + + log_pop(); + } +} OptExprPass; + +PRIVATE_NAMESPACE_END diff --git a/passes/sat/miter.cc b/passes/sat/miter.cc index 682299ef2..e809425c8 100644 --- a/passes/sat/miter.cc +++ b/passes/sat/miter.cc @@ -254,7 +254,7 @@ void create_miter_equiv(struct Pass *that, std::vector args, RTLIL: if (flag_flatten) { log_push(); - Pass::call_on_module(design, miter_module, "flatten; opt_const -keepdc -undriven;;"); + Pass::call_on_module(design, miter_module, "flatten; opt_expr -keepdc -undriven;;"); log_pop(); } } @@ -327,7 +327,7 @@ void create_miter_assert(struct Pass *that, std::vector args, RTLIL if (flag_flatten) { log_push(); - Pass::call_on_module(design, module, "opt_const -keepdc -undriven;;"); + Pass::call_on_module(design, module, "opt_expr -keepdc -undriven;;"); log_pop(); } } @@ -361,7 +361,7 @@ struct MiterPass : public Pass { log(" also create an 'assert' cell that checks if trigger is always low.\n"); log("\n"); log(" -flatten\n"); - log(" call 'flatten; opt_const -keepdc -undriven;;' on the miter circuit.\n"); + log(" call 'flatten; opt_expr -keepdc -undriven;;' on the miter circuit.\n"); log("\n"); log("\n"); log(" miter -assert [options] module [miter_name]\n"); @@ -375,7 +375,7 @@ struct MiterPass : public Pass { log(" keep module output ports.\n"); log("\n"); log(" -flatten\n"); - log(" call 'flatten; opt_const -keepdc -undriven;;' on the miter circuit.\n"); + log(" call 'flatten; opt_expr -keepdc -undriven;;' on the miter circuit.\n"); log("\n"); } virtual void execute(std::vector args, RTLIL::Design *design) diff --git a/techlibs/common/prep.cc b/techlibs/common/prep.cc index 8bae920d0..911737947 100644 --- a/techlibs/common/prep.cc +++ b/techlibs/common/prep.cc @@ -69,7 +69,7 @@ struct PrepPass : public Pass { log("\n"); log(" prep:\n"); log(" proc\n"); - log(" opt_const\n"); + log(" opt_expr -keepdc\n"); log(" opt_clean\n"); log(" check\n"); log(" opt -keepdc\n"); @@ -134,7 +134,7 @@ struct PrepPass : public Pass { if (check_label(active, run_from, run_to, "coarse")) { Pass::call(design, "proc"); - Pass::call(design, "opt_const"); + Pass::call(design, "opt_expr -keepdc"); Pass::call(design, "opt_clean"); Pass::call(design, "check"); Pass::call(design, "opt -keepdc"); diff --git a/techlibs/common/synth.cc b/techlibs/common/synth.cc index 83d00f328..c837e1378 100644 --- a/techlibs/common/synth.cc +++ b/techlibs/common/synth.cc @@ -81,7 +81,7 @@ struct SynthPass : public Pass { log("\n"); log(" coarse:\n"); log(" proc\n"); - log(" opt_const\n"); + log(" opt_expr\n"); log(" opt_clean\n"); log(" check\n"); log(" opt\n"); @@ -180,7 +180,7 @@ struct SynthPass : public Pass { if (check_label(active, run_from, run_to, "coarse")) { Pass::call(design, "proc"); - Pass::call(design, "opt_const"); + Pass::call(design, "opt_expr"); Pass::call(design, "opt_clean"); Pass::call(design, "check"); Pass::call(design, "opt"); diff --git a/techlibs/common/techmap.v b/techlibs/common/techmap.v index ae08c3d17..a623bb516 100644 --- a/techlibs/common/techmap.v +++ b/techlibs/common/techmap.v @@ -93,7 +93,7 @@ module _90_shift_ops_shr_shl_sshl_sshr (A, B, Y); localparam BB_WIDTH = `MIN($clog2(shift_left ? Y_WIDTH : A_SIGNED ? WIDTH : A_WIDTH) + 1, B_WIDTH); wire [1023:0] _TECHMAP_DO_00_ = "proc;;"; - wire [1023:0] _TECHMAP_DO_01_ = "RECURSION; CONSTMAP; opt_muxtree; opt_const -mux_undef -mux_bool -fine;;;"; + wire [1023:0] _TECHMAP_DO_01_ = "RECURSION; CONSTMAP; opt_muxtree; opt_expr -mux_undef -mux_bool -fine;;;"; integer i; reg [WIDTH-1:0] buffer; @@ -136,7 +136,7 @@ module _90_shift_shiftx (A, B, Y); localparam extbit = _TECHMAP_CELLTYPE_ == "$shift" ? 1'b0 : 1'bx; wire [1023:0] _TECHMAP_DO_00_ = "proc;;"; - wire [1023:0] _TECHMAP_DO_01_ = "CONSTMAP; opt_muxtree; opt_const -mux_undef -mux_bool -fine;;;"; + wire [1023:0] _TECHMAP_DO_01_ = "CONSTMAP; opt_muxtree; opt_expr -mux_undef -mux_bool -fine;;;"; integer i; reg [WIDTH-1:0] buffer; diff --git a/techlibs/ice40/ice40_opt.cc b/techlibs/ice40/ice40_opt.cc index 677ac8d77..69c222808 100644 --- a/techlibs/ice40/ice40_opt.cc +++ b/techlibs/ice40/ice40_opt.cc @@ -127,7 +127,7 @@ struct Ice40OptPass : public Pass { log("\n"); log(" do\n"); log(" \n"); - log(" opt_const -mux_undef -undriven [-full]\n"); + log(" opt_expr -mux_undef -undriven [-full]\n"); log(" opt_share\n"); log(" opt_rmdff\n"); log(" opt_clean\n"); @@ -136,14 +136,14 @@ struct Ice40OptPass : public Pass { } virtual void execute(std::vector args, RTLIL::Design *design) { - string opt_const_args = "-mux_undef -undriven"; + string opt_expr_args = "-mux_undef -undriven"; log_header("Executing ICE40_OPT pass (performing simple optimizations).\n"); log_push(); size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { if (args[argidx] == "-full") { - opt_const_args += " -full"; + opt_expr_args += " -full"; continue; } break; @@ -158,7 +158,7 @@ struct Ice40OptPass : public Pass { for (auto module : design->selected_modules()) run_ice40_opts(module); - Pass::call(design, "opt_const " + opt_const_args); + Pass::call(design, "opt_expr " + opt_expr_args); Pass::call(design, "opt_share"); Pass::call(design, "opt_rmdff"); Pass::call(design, "opt_clean"); diff --git a/techlibs/ice40/synth_ice40.cc b/techlibs/ice40/synth_ice40.cc index 92d53f4ab..f24d31a8c 100644 --- a/techlibs/ice40/synth_ice40.cc +++ b/techlibs/ice40/synth_ice40.cc @@ -106,7 +106,7 @@ struct SynthIce40Pass : public Pass { log(" dffsr2dff\n"); log(" dff2dffe -direct-match $_DFF_*\n"); log(" techmap -map +/ice40/cells_map.v\n"); - log(" opt_const -mux_undef\n"); + log(" opt_expr -mux_undef\n"); log(" simplemap\n"); log(" ice40_ffinit\n"); log(" ice40_ffssr\n"); @@ -247,7 +247,7 @@ struct SynthIce40Pass : public Pass { Pass::call(design, "dffsr2dff"); Pass::call(design, "dff2dffe -direct-match $_DFF_*"); Pass::call(design, "techmap -map +/ice40/cells_map.v"); - Pass::call(design, "opt_const -mux_undef"); + Pass::call(design, "opt_expr -mux_undef"); Pass::call(design, "simplemap"); Pass::call(design, "ice40_ffinit"); Pass::call(design, "ice40_ffssr"); -- cgit v1.2.3 From ec93680bd583b670e03ed98b4b1081eab8d0f3f6 Mon Sep 17 00:00:00 2001 From: Clifford Wolf Date: Thu, 31 Mar 2016 08:52:49 +0200 Subject: Renamed opt_share to opt_merge --- manual/CHAPTER_Optimize.tex | 6 +- manual/CHAPTER_Overview.tex | 4 +- manual/PRESENTATION_ExSyn.tex | 4 +- passes/memory/memory_share.cc | 2 +- passes/opt/Makefile.inc | 2 +- passes/opt/opt.cc | 16 +- passes/opt/opt_merge.cc | 341 ++++++++++++++++++++++++++++++++++++++++++ passes/opt/opt_share.cc | 341 ------------------------------------------ techlibs/ice40/ice40_opt.cc | 4 +- 9 files changed, 360 insertions(+), 360 deletions(-) create mode 100644 passes/opt/opt_merge.cc delete mode 100644 passes/opt/opt_share.cc diff --git a/manual/CHAPTER_Optimize.tex b/manual/CHAPTER_Optimize.tex index 07f5a26e6..4b09c2231 100644 --- a/manual/CHAPTER_Optimize.tex +++ b/manual/CHAPTER_Optimize.tex @@ -16,13 +16,13 @@ passes that each perform a simple optimization: \item Once at the beginning of {\tt opt}: \begin{itemize} \item {\tt opt\_expr} -\item {\tt opt\_share -nomux} +\item {\tt opt\_merge -nomux} \end{itemize} \item Repeat until result is stable: \begin{itemize} \item {\tt opt\_muxtree} \item {\tt opt\_reduce} -\item {\tt opt\_share} +\item {\tt opt\_merge} \item {\tt opt\_rmdff} \item {\tt opt\_clean} \item {\tt opt\_expr} @@ -130,7 +130,7 @@ This pass identifies unused signals and cells and removes them from the design. creates an \B{unused\_bits} attribute on wires with unused bits. This attribute can be used for debugging or by other optimization passes. -\subsection{The opt\_share pass} +\subsection{The opt\_merge pass} This pass performs trivial resource sharing. This means that this pass identifies cells with identical inputs and replaces them with a single instance of the cell. diff --git a/manual/CHAPTER_Overview.tex b/manual/CHAPTER_Overview.tex index 4ce314825..964875d57 100644 --- a/manual/CHAPTER_Overview.tex +++ b/manual/CHAPTER_Overview.tex @@ -489,7 +489,7 @@ select.cc}, {\tt show.cc}, \dots) and a couple of other small utility libraries. This directory contains a subdirectory for each pass or group of passes. For example as of this writing the directory {\tt passes/opt/} contains the code for seven passes: {\tt opt}, {\tt opt\_expr}, {\tt opt\_muxtree}, {\tt opt\_reduce}, -{\tt opt\_rmdff}, {\tt opt\_rmunused} and {\tt opt\_share}. +{\tt opt\_rmdff}, {\tt opt\_rmunused} and {\tt opt\_merge}. \item {\tt techlibs/} \\ This directory contains simulation models and standard implementations for the @@ -513,7 +513,7 @@ Yosys. So it is not needed to add additional commands to a central list of comma \end{sloppypar} Good starting points for reading example source code to learn how to write passes -are {\tt passes/opt/opt\_rmdff.cc} and {\tt passes/opt/opt\_share.cc}. +are {\tt passes/opt/opt\_rmdff.cc} and {\tt passes/opt/opt\_merge.cc}. See the top-level README file for a quick {\it Getting Started} guide and build instructions. The Yosys build is based solely on Makefiles. diff --git a/manual/PRESENTATION_ExSyn.tex b/manual/PRESENTATION_ExSyn.tex index b57063c9c..655720ebc 100644 --- a/manual/PRESENTATION_ExSyn.tex +++ b/manual/PRESENTATION_ExSyn.tex @@ -145,12 +145,12 @@ is a macro command that calls other commands: \begin{lstlisting}[xleftmargin=0.5cm, basicstyle=\ttfamily\fontsize{8pt}{10pt}\selectfont, language=ys] opt_expr # const folding and simple expression rewriting -opt_share -nomux # merging identical cells +opt_merge -nomux # merging identical cells do opt_muxtree # remove never-active branches from multiplexer tree opt_reduce # consolidate trees of boolean ops to reduce functions - opt_share # merging identical cells + opt_merge # merging identical cells opt_rmdff # remove/simplify registers with constant inputs opt_clean # remove unused objects (cells, wires) from design opt_expr # const folding and simple expression rewriting diff --git a/passes/memory/memory_share.cc b/passes/memory/memory_share.cc index 3a6fd0b44..ab9edb6e7 100644 --- a/passes/memory/memory_share.cc +++ b/passes/memory/memory_share.cc @@ -746,7 +746,7 @@ struct MemorySharePass : public Pass { log("\n"); log("Note that in addition to the algorithms implemented in this pass, the $memrd\n"); log("and $memwr cells are also subject to generic resource sharing passes (and other\n"); - log("optimizations) such as opt_share.\n"); + log("optimizations) such as \"share\" and \"opt_merge\".\n"); log("\n"); } virtual void execute(std::vector args, RTLIL::Design *design) { diff --git a/passes/opt/Makefile.inc b/passes/opt/Makefile.inc index dd9088a66..a8b1537bb 100644 --- a/passes/opt/Makefile.inc +++ b/passes/opt/Makefile.inc @@ -1,6 +1,6 @@ OBJS += passes/opt/opt.o -OBJS += passes/opt/opt_share.o +OBJS += passes/opt/opt_merge.o OBJS += passes/opt/opt_muxtree.o OBJS += passes/opt/opt_reduce.o OBJS += passes/opt/opt_rmdff.o diff --git a/passes/opt/opt.cc b/passes/opt/opt.cc index db35a1775..c25adac97 100644 --- a/passes/opt/opt.cc +++ b/passes/opt/opt.cc @@ -38,12 +38,12 @@ struct OptPass : public Pass { log("passes in the following order:\n"); log("\n"); log(" opt_expr [-mux_undef] [-mux_bool] [-undriven] [-clkinv] [-fine] [-full] [-keepdc]\n"); - log(" opt_share [-share_all] -nomux\n"); + log(" opt_merge [-share_all] -nomux\n"); log("\n"); log(" do\n"); log(" opt_muxtree\n"); log(" opt_reduce [-fine] [-full]\n"); - log(" opt_share [-share_all]\n"); + log(" opt_merge [-share_all]\n"); log(" opt_rmdff\n"); log(" opt_clean [-purge]\n"); log(" opt_expr [-mux_undef] [-mux_bool] [-undriven] [-clkinv] [-fine] [-full] [-keepdc]\n"); @@ -53,7 +53,7 @@ struct OptPass : public Pass { log("\n"); log(" do\n"); log(" opt_expr [-mux_undef] [-mux_bool] [-undriven] [-clkinv] [-fine] [-full] [-keepdc]\n"); - log(" opt_share [-share_all]\n"); + log(" opt_merge [-share_all]\n"); log(" opt_rmdff\n"); log(" opt_clean [-purge]\n"); log(" while \n"); @@ -68,7 +68,7 @@ struct OptPass : public Pass { std::string opt_clean_args; std::string opt_expr_args; std::string opt_reduce_args; - std::string opt_share_args; + std::string opt_merge_args; bool fast_mode = false; log_header("Executing OPT pass (performing simple optimizations).\n"); @@ -111,7 +111,7 @@ struct OptPass : public Pass { continue; } if (args[argidx] == "-share_all") { - opt_share_args += " -share_all"; + opt_merge_args += " -share_all"; continue; } if (args[argidx] == "-fast") { @@ -126,7 +126,7 @@ struct OptPass : public Pass { { while (1) { Pass::call(design, "opt_expr" + opt_expr_args); - Pass::call(design, "opt_share" + opt_share_args); + Pass::call(design, "opt_merge" + opt_merge_args); design->scratchpad_unset("opt.did_something"); Pass::call(design, "opt_rmdff"); if (design->scratchpad_get_bool("opt.did_something") == false) @@ -139,12 +139,12 @@ struct OptPass : public Pass { else { Pass::call(design, "opt_expr" + opt_expr_args); - Pass::call(design, "opt_share -nomux" + opt_share_args); + Pass::call(design, "opt_merge -nomux" + opt_merge_args); while (1) { design->scratchpad_unset("opt.did_something"); Pass::call(design, "opt_muxtree"); Pass::call(design, "opt_reduce" + opt_reduce_args); - Pass::call(design, "opt_share" + opt_share_args); + Pass::call(design, "opt_merge" + opt_merge_args); Pass::call(design, "opt_rmdff"); Pass::call(design, "opt_clean" + opt_clean_args); Pass::call(design, "opt_expr" + opt_expr_args); diff --git a/passes/opt/opt_merge.cc b/passes/opt/opt_merge.cc new file mode 100644 index 000000000..fe1ad685a --- /dev/null +++ b/passes/opt/opt_merge.cc @@ -0,0 +1,341 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Clifford 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/log.h" +#include "kernel/celltypes.h" +#include "libs/sha1/sha1.h" +#include +#include +#include + +#define USE_CELL_HASH_CACHE + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct OptMergeWorker +{ + RTLIL::Design *design; + RTLIL::Module *module; + SigMap assign_map; + SigMap dff_init_map; + bool mode_share_all; + + CellTypes ct; + int total_count; +#ifdef USE_CELL_HASH_CACHE + dict cell_hash_cache; +#endif + +#ifdef USE_CELL_HASH_CACHE + std::string int_to_hash_string(unsigned int v) + { + if (v == 0) + return "0"; + std::string str = ""; + while (v > 0) { + str += 'a' + (v & 15); + v = v >> 4; + } + return str; + } + + std::string hash_cell_parameters_and_connections(const RTLIL::Cell *cell) + { + if (cell_hash_cache.count(cell) > 0) + return cell_hash_cache[cell]; + + std::string hash_string = cell->type.str() + "\n"; + + for (auto &it : cell->parameters) + hash_string += "P " + it.first.str() + "=" + it.second.as_string() + "\n"; + + const dict *conn = &cell->connections(); + dict alt_conn; + + if (cell->type == "$and" || cell->type == "$or" || cell->type == "$xor" || cell->type == "$xnor" || cell->type == "$add" || cell->type == "$mul" || + cell->type == "$logic_and" || cell->type == "$logic_or" || cell->type == "$_AND_" || cell->type == "$_OR_" || cell->type == "$_XOR_") { + alt_conn = *conn; + if (assign_map(alt_conn.at("\\A")) < assign_map(alt_conn.at("\\B"))) { + alt_conn["\\A"] = conn->at("\\B"); + alt_conn["\\B"] = conn->at("\\A"); + } + conn = &alt_conn; + } else + if (cell->type == "$reduce_xor" || cell->type == "$reduce_xnor") { + alt_conn = *conn; + assign_map.apply(alt_conn.at("\\A")); + alt_conn.at("\\A").sort(); + conn = &alt_conn; + } else + if (cell->type == "$reduce_and" || cell->type == "$reduce_or" || cell->type == "$reduce_bool") { + alt_conn = *conn; + assign_map.apply(alt_conn.at("\\A")); + alt_conn.at("\\A").sort_and_unify(); + conn = &alt_conn; + } + + for (auto &it : *conn) { + if (cell->output(it.first)) + continue; + RTLIL::SigSpec sig = it.second; + assign_map.apply(sig); + hash_string += "C " + it.first.str() + "="; + for (auto &chunk : sig.chunks()) { + if (chunk.wire) + hash_string += "{" + chunk.wire->name.str() + " " + + int_to_hash_string(chunk.offset) + " " + + int_to_hash_string(chunk.width) + "}"; + else + hash_string += RTLIL::Const(chunk.data).as_string(); + } + hash_string += "\n"; + } + + cell_hash_cache[cell] = sha1(hash_string); + return cell_hash_cache[cell]; + } +#endif + + bool compare_cell_parameters_and_connections(const RTLIL::Cell *cell1, const RTLIL::Cell *cell2, bool <) + { +#ifdef USE_CELL_HASH_CACHE + std::string hash1 = hash_cell_parameters_and_connections(cell1); + std::string hash2 = hash_cell_parameters_and_connections(cell2); + + if (hash1 != hash2) { + lt = hash1 < hash2; + return true; + } +#endif + + if (cell1->parameters != cell2->parameters) { + std::map p1(cell1->parameters.begin(), cell1->parameters.end()); + std::map p2(cell2->parameters.begin(), cell2->parameters.end()); + lt = p1 < p2; + return true; + } + + dict conn1 = cell1->connections(); + dict conn2 = cell2->connections(); + + for (auto &it : conn1) { + if (cell1->output(it.first)) + it.second = RTLIL::SigSpec(); + else + assign_map.apply(it.second); + } + + for (auto &it : conn2) { + if (cell2->output(it.first)) + it.second = RTLIL::SigSpec(); + else + assign_map.apply(it.second); + } + + if (cell1->type == "$and" || cell1->type == "$or" || cell1->type == "$xor" || cell1->type == "$xnor" || cell1->type == "$add" || cell1->type == "$mul" || + cell1->type == "$logic_and" || cell1->type == "$logic_or" || cell1->type == "$_AND_" || cell1->type == "$_OR_" || cell1->type == "$_XOR_") { + if (conn1.at("\\A") < conn1.at("\\B")) { + RTLIL::SigSpec tmp = conn1["\\A"]; + conn1["\\A"] = conn1["\\B"]; + conn1["\\B"] = tmp; + } + if (conn2.at("\\A") < conn2.at("\\B")) { + RTLIL::SigSpec tmp = conn2["\\A"]; + conn2["\\A"] = conn2["\\B"]; + conn2["\\B"] = tmp; + } + } else + if (cell1->type == "$reduce_xor" || cell1->type == "$reduce_xnor") { + conn1["\\A"].sort(); + conn2["\\A"].sort(); + } else + if (cell1->type == "$reduce_and" || cell1->type == "$reduce_or" || cell1->type == "$reduce_bool") { + conn1["\\A"].sort_and_unify(); + conn2["\\A"].sort_and_unify(); + } + + if (conn1 != conn2) { + std::map c1(conn1.begin(), conn1.end()); + std::map c2(conn2.begin(), conn2.end()); + lt = c1 < c2; + return true; + } + + if (cell1->type.substr(0, 1) == "$" && conn1.count("\\Q") != 0) { + std::vector q1 = dff_init_map(cell1->getPort("\\Q")).to_sigbit_vector(); + std::vector q2 = dff_init_map(cell2->getPort("\\Q")).to_sigbit_vector(); + for (size_t i = 0; i < q1.size(); i++) + if ((q1.at(i).wire == NULL || q2.at(i).wire == NULL) && q1.at(i) != q2.at(i)) { + lt = q1.at(i) < q2.at(i); + return true; + } + } + + return false; + } + + bool compare_cells(const RTLIL::Cell *cell1, const RTLIL::Cell *cell2) + { + if (cell1->type != cell2->type) + return cell1->type < cell2->type; + + if ((!mode_share_all && !ct.cell_known(cell1->type)) || !cell1->known()) + return cell1 < cell2; + + if (cell1->has_keep_attr() || cell2->has_keep_attr()) + return cell1 < cell2; + + bool lt; + if (compare_cell_parameters_and_connections(cell1, cell2, lt)) + return lt; + + return false; + } + + struct CompareCells { + OptMergeWorker *that; + CompareCells(OptMergeWorker *that) : that(that) {} + bool operator()(const RTLIL::Cell *cell1, const RTLIL::Cell *cell2) const { + return that->compare_cells(cell1, cell2); + } + }; + + OptMergeWorker(RTLIL::Design *design, RTLIL::Module *module, bool mode_nomux, bool mode_share_all) : + design(design), module(module), assign_map(module), mode_share_all(mode_share_all) + { + total_count = 0; + ct.setup_internals(); + ct.setup_internals_mem(); + ct.setup_stdcells(); + ct.setup_stdcells_mem(); + + if (mode_nomux) { + ct.cell_types.erase("$mux"); + ct.cell_types.erase("$pmux"); + } + + log("Finding identical cells in module `%s'.\n", module->name.c_str()); + assign_map.set(module); + + dff_init_map.set(module); + for (auto &it : module->wires_) + if (it.second->attributes.count("\\init") != 0) + dff_init_map.add(it.second, it.second->attributes.at("\\init")); + + bool did_something = true; + while (did_something) + { +#ifdef USE_CELL_HASH_CACHE + cell_hash_cache.clear(); +#endif + std::vector cells; + cells.reserve(module->cells_.size()); + for (auto &it : module->cells_) { + if (!design->selected(module, it.second)) + continue; + if (ct.cell_known(it.second->type) || (mode_share_all && it.second->known())) + cells.push_back(it.second); + } + + did_something = false; + std::map sharemap(CompareCells(this)); + for (auto cell : cells) + { + if (sharemap.count(cell) > 0) { + did_something = true; + log(" Cell `%s' is identical to cell `%s'.\n", cell->name.c_str(), sharemap[cell]->name.c_str()); + for (auto &it : cell->connections()) { + if (cell->output(it.first)) { + RTLIL::SigSpec other_sig = sharemap[cell]->getPort(it.first); + log(" Redirecting output %s: %s = %s\n", it.first.c_str(), + log_signal(it.second), log_signal(other_sig)); + module->connect(RTLIL::SigSig(it.second, other_sig)); + assign_map.add(it.second, other_sig); + } + } + log(" Removing %s cell `%s' from module `%s'.\n", cell->type.c_str(), cell->name.c_str(), module->name.c_str()); +#ifdef USE_CELL_HASH_CACHE + cell_hash_cache.erase(cell); +#endif + module->remove(cell); + total_count++; + } else { + sharemap[cell] = cell; + } + } + } + } +}; + +struct OptMergePass : public Pass { + OptMergePass() : Pass("opt_merge", "consolidate identical cells") { } + virtual void help() + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" opt_merge [options] [selection]\n"); + log("\n"); + log("This pass identifies cells with identical type and input signals. Such cells\n"); + log("are then merged to one cell.\n"); + log("\n"); + log(" -nomux\n"); + log(" Do not merge MUX cells.\n"); + log("\n"); + log(" -share_all\n"); + log(" Operate on all cell types, not just built-in types.\n"); + log("\n"); + } + virtual void execute(std::vector args, RTLIL::Design *design) + { + log_header("Executing OPT_SHARE pass (detect identical cells).\n"); + + bool mode_nomux = false; + bool mode_share_all = false; + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + std::string arg = args[argidx]; + if (arg == "-nomux") { + mode_nomux = true; + continue; + } + if (arg == "-share_all") { + mode_share_all = true; + continue; + } + break; + } + extra_args(args, argidx, design); + + int total_count = 0; + for (auto module : design->selected_modules()) { + OptMergeWorker worker(design, module, mode_nomux, mode_share_all); + total_count += worker.total_count; + } + + if (total_count) + design->scratchpad_set_bool("opt.did_something", true); + log("Removed a total of %d cells.\n", total_count); + } +} OptMergePass; + +PRIVATE_NAMESPACE_END diff --git a/passes/opt/opt_share.cc b/passes/opt/opt_share.cc deleted file mode 100644 index 46752e43b..000000000 --- a/passes/opt/opt_share.cc +++ /dev/null @@ -1,341 +0,0 @@ -/* - * yosys -- Yosys Open SYnthesis Suite - * - * Copyright (C) 2012 Clifford 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/log.h" -#include "kernel/celltypes.h" -#include "libs/sha1/sha1.h" -#include -#include -#include - -#define USE_CELL_HASH_CACHE - -USING_YOSYS_NAMESPACE -PRIVATE_NAMESPACE_BEGIN - -struct OptShareWorker -{ - RTLIL::Design *design; - RTLIL::Module *module; - SigMap assign_map; - SigMap dff_init_map; - bool mode_share_all; - - CellTypes ct; - int total_count; -#ifdef USE_CELL_HASH_CACHE - dict cell_hash_cache; -#endif - -#ifdef USE_CELL_HASH_CACHE - std::string int_to_hash_string(unsigned int v) - { - if (v == 0) - return "0"; - std::string str = ""; - while (v > 0) { - str += 'a' + (v & 15); - v = v >> 4; - } - return str; - } - - std::string hash_cell_parameters_and_connections(const RTLIL::Cell *cell) - { - if (cell_hash_cache.count(cell) > 0) - return cell_hash_cache[cell]; - - std::string hash_string = cell->type.str() + "\n"; - - for (auto &it : cell->parameters) - hash_string += "P " + it.first.str() + "=" + it.second.as_string() + "\n"; - - const dict *conn = &cell->connections(); - dict alt_conn; - - if (cell->type == "$and" || cell->type == "$or" || cell->type == "$xor" || cell->type == "$xnor" || cell->type == "$add" || cell->type == "$mul" || - cell->type == "$logic_and" || cell->type == "$logic_or" || cell->type == "$_AND_" || cell->type == "$_OR_" || cell->type == "$_XOR_") { - alt_conn = *conn; - if (assign_map(alt_conn.at("\\A")) < assign_map(alt_conn.at("\\B"))) { - alt_conn["\\A"] = conn->at("\\B"); - alt_conn["\\B"] = conn->at("\\A"); - } - conn = &alt_conn; - } else - if (cell->type == "$reduce_xor" || cell->type == "$reduce_xnor") { - alt_conn = *conn; - assign_map.apply(alt_conn.at("\\A")); - alt_conn.at("\\A").sort(); - conn = &alt_conn; - } else - if (cell->type == "$reduce_and" || cell->type == "$reduce_or" || cell->type == "$reduce_bool") { - alt_conn = *conn; - assign_map.apply(alt_conn.at("\\A")); - alt_conn.at("\\A").sort_and_unify(); - conn = &alt_conn; - } - - for (auto &it : *conn) { - if (cell->output(it.first)) - continue; - RTLIL::SigSpec sig = it.second; - assign_map.apply(sig); - hash_string += "C " + it.first.str() + "="; - for (auto &chunk : sig.chunks()) { - if (chunk.wire) - hash_string += "{" + chunk.wire->name.str() + " " + - int_to_hash_string(chunk.offset) + " " + - int_to_hash_string(chunk.width) + "}"; - else - hash_string += RTLIL::Const(chunk.data).as_string(); - } - hash_string += "\n"; - } - - cell_hash_cache[cell] = sha1(hash_string); - return cell_hash_cache[cell]; - } -#endif - - bool compare_cell_parameters_and_connections(const RTLIL::Cell *cell1, const RTLIL::Cell *cell2, bool <) - { -#ifdef USE_CELL_HASH_CACHE - std::string hash1 = hash_cell_parameters_and_connections(cell1); - std::string hash2 = hash_cell_parameters_and_connections(cell2); - - if (hash1 != hash2) { - lt = hash1 < hash2; - return true; - } -#endif - - if (cell1->parameters != cell2->parameters) { - std::map p1(cell1->parameters.begin(), cell1->parameters.end()); - std::map p2(cell2->parameters.begin(), cell2->parameters.end()); - lt = p1 < p2; - return true; - } - - dict conn1 = cell1->connections(); - dict conn2 = cell2->connections(); - - for (auto &it : conn1) { - if (cell1->output(it.first)) - it.second = RTLIL::SigSpec(); - else - assign_map.apply(it.second); - } - - for (auto &it : conn2) { - if (cell2->output(it.first)) - it.second = RTLIL::SigSpec(); - else - assign_map.apply(it.second); - } - - if (cell1->type == "$and" || cell1->type == "$or" || cell1->type == "$xor" || cell1->type == "$xnor" || cell1->type == "$add" || cell1->type == "$mul" || - cell1->type == "$logic_and" || cell1->type == "$logic_or" || cell1->type == "$_AND_" || cell1->type == "$_OR_" || cell1->type == "$_XOR_") { - if (conn1.at("\\A") < conn1.at("\\B")) { - RTLIL::SigSpec tmp = conn1["\\A"]; - conn1["\\A"] = conn1["\\B"]; - conn1["\\B"] = tmp; - } - if (conn2.at("\\A") < conn2.at("\\B")) { - RTLIL::SigSpec tmp = conn2["\\A"]; - conn2["\\A"] = conn2["\\B"]; - conn2["\\B"] = tmp; - } - } else - if (cell1->type == "$reduce_xor" || cell1->type == "$reduce_xnor") { - conn1["\\A"].sort(); - conn2["\\A"].sort(); - } else - if (cell1->type == "$reduce_and" || cell1->type == "$reduce_or" || cell1->type == "$reduce_bool") { - conn1["\\A"].sort_and_unify(); - conn2["\\A"].sort_and_unify(); - } - - if (conn1 != conn2) { - std::map c1(conn1.begin(), conn1.end()); - std::map c2(conn2.begin(), conn2.end()); - lt = c1 < c2; - return true; - } - - if (cell1->type.substr(0, 1) == "$" && conn1.count("\\Q") != 0) { - std::vector q1 = dff_init_map(cell1->getPort("\\Q")).to_sigbit_vector(); - std::vector q2 = dff_init_map(cell2->getPort("\\Q")).to_sigbit_vector(); - for (size_t i = 0; i < q1.size(); i++) - if ((q1.at(i).wire == NULL || q2.at(i).wire == NULL) && q1.at(i) != q2.at(i)) { - lt = q1.at(i) < q2.at(i); - return true; - } - } - - return false; - } - - bool compare_cells(const RTLIL::Cell *cell1, const RTLIL::Cell *cell2) - { - if (cell1->type != cell2->type) - return cell1->type < cell2->type; - - if ((!mode_share_all && !ct.cell_known(cell1->type)) || !cell1->known()) - return cell1 < cell2; - - if (cell1->has_keep_attr() || cell2->has_keep_attr()) - return cell1 < cell2; - - bool lt; - if (compare_cell_parameters_and_connections(cell1, cell2, lt)) - return lt; - - return false; - } - - struct CompareCells { - OptShareWorker *that; - CompareCells(OptShareWorker *that) : that(that) {} - bool operator()(const RTLIL::Cell *cell1, const RTLIL::Cell *cell2) const { - return that->compare_cells(cell1, cell2); - } - }; - - OptShareWorker(RTLIL::Design *design, RTLIL::Module *module, bool mode_nomux, bool mode_share_all) : - design(design), module(module), assign_map(module), mode_share_all(mode_share_all) - { - total_count = 0; - ct.setup_internals(); - ct.setup_internals_mem(); - ct.setup_stdcells(); - ct.setup_stdcells_mem(); - - if (mode_nomux) { - ct.cell_types.erase("$mux"); - ct.cell_types.erase("$pmux"); - } - - log("Finding identical cells in module `%s'.\n", module->name.c_str()); - assign_map.set(module); - - dff_init_map.set(module); - for (auto &it : module->wires_) - if (it.second->attributes.count("\\init") != 0) - dff_init_map.add(it.second, it.second->attributes.at("\\init")); - - bool did_something = true; - while (did_something) - { -#ifdef USE_CELL_HASH_CACHE - cell_hash_cache.clear(); -#endif - std::vector cells; - cells.reserve(module->cells_.size()); - for (auto &it : module->cells_) { - if (!design->selected(module, it.second)) - continue; - if (ct.cell_known(it.second->type) || (mode_share_all && it.second->known())) - cells.push_back(it.second); - } - - did_something = false; - std::map sharemap(CompareCells(this)); - for (auto cell : cells) - { - if (sharemap.count(cell) > 0) { - did_something = true; - log(" Cell `%s' is identical to cell `%s'.\n", cell->name.c_str(), sharemap[cell]->name.c_str()); - for (auto &it : cell->connections()) { - if (cell->output(it.first)) { - RTLIL::SigSpec other_sig = sharemap[cell]->getPort(it.first); - log(" Redirecting output %s: %s = %s\n", it.first.c_str(), - log_signal(it.second), log_signal(other_sig)); - module->connect(RTLIL::SigSig(it.second, other_sig)); - assign_map.add(it.second, other_sig); - } - } - log(" Removing %s cell `%s' from module `%s'.\n", cell->type.c_str(), cell->name.c_str(), module->name.c_str()); -#ifdef USE_CELL_HASH_CACHE - cell_hash_cache.erase(cell); -#endif - module->remove(cell); - total_count++; - } else { - sharemap[cell] = cell; - } - } - } - } -}; - -struct OptSharePass : public Pass { - OptSharePass() : Pass("opt_share", "consolidate identical cells") { } - virtual void help() - { - // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| - log("\n"); - log(" opt_share [options] [selection]\n"); - log("\n"); - log("This pass identifies cells with identical type and input signals. Such cells\n"); - log("are then merged to one cell.\n"); - log("\n"); - log(" -nomux\n"); - log(" Do not merge MUX cells.\n"); - log("\n"); - log(" -share_all\n"); - log(" Operate on all cell types, not just built-in types.\n"); - log("\n"); - } - virtual void execute(std::vector args, RTLIL::Design *design) - { - log_header("Executing OPT_SHARE pass (detect identical cells).\n"); - - bool mode_nomux = false; - bool mode_share_all = false; - - size_t argidx; - for (argidx = 1; argidx < args.size(); argidx++) { - std::string arg = args[argidx]; - if (arg == "-nomux") { - mode_nomux = true; - continue; - } - if (arg == "-share_all") { - mode_share_all = true; - continue; - } - break; - } - extra_args(args, argidx, design); - - int total_count = 0; - for (auto module : design->selected_modules()) { - OptShareWorker worker(design, module, mode_nomux, mode_share_all); - total_count += worker.total_count; - } - - if (total_count) - design->scratchpad_set_bool("opt.did_something", true); - log("Removed a total of %d cells.\n", total_count); - } -} OptSharePass; - -PRIVATE_NAMESPACE_END diff --git a/techlibs/ice40/ice40_opt.cc b/techlibs/ice40/ice40_opt.cc index 69c222808..5730847ce 100644 --- a/techlibs/ice40/ice40_opt.cc +++ b/techlibs/ice40/ice40_opt.cc @@ -128,7 +128,7 @@ struct Ice40OptPass : public Pass { log(" do\n"); log(" \n"); log(" opt_expr -mux_undef -undriven [-full]\n"); - log(" opt_share\n"); + log(" opt_merge\n"); log(" opt_rmdff\n"); log(" opt_clean\n"); log(" while \n"); @@ -159,7 +159,7 @@ struct Ice40OptPass : public Pass { run_ice40_opts(module); Pass::call(design, "opt_expr " + opt_expr_args); - Pass::call(design, "opt_share"); + Pass::call(design, "opt_merge"); Pass::call(design, "opt_rmdff"); Pass::call(design, "opt_clean"); -- cgit v1.2.3 From e2f6d61c004776f2f573f3c5b70ad352ce6b4e1a Mon Sep 17 00:00:00 2001 From: Clifford Wolf Date: Thu, 31 Mar 2016 09:56:56 +0200 Subject: Typo fixes in opt_expr and opt_merge --- passes/opt/opt_expr.cc | 2 +- passes/opt/opt_merge.cc | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/passes/opt/opt_expr.cc b/passes/opt/opt_expr.cc index 09dacf394..9e713935d 100644 --- a/passes/opt/opt_expr.cc +++ b/passes/opt/opt_expr.cc @@ -1101,7 +1101,7 @@ struct OptExprPass : public Pass { bool do_fine = false; bool keepdc = false; - log_header("Executing OPT_CONST pass (perform const folding).\n"); + log_header("Executing OPT_EXPR pass (perform const folding).\n"); log_push(); size_t argidx; diff --git a/passes/opt/opt_merge.cc b/passes/opt/opt_merge.cc index fe1ad685a..13b3082fd 100644 --- a/passes/opt/opt_merge.cc +++ b/passes/opt/opt_merge.cc @@ -306,7 +306,7 @@ struct OptMergePass : public Pass { } virtual void execute(std::vector args, RTLIL::Design *design) { - log_header("Executing OPT_SHARE pass (detect identical cells).\n"); + log_header("Executing OPT_MERGE pass (detect identical cells).\n"); bool mode_nomux = false; bool mode_share_all = false; -- cgit v1.2.3 From e5dd5c0bcccd4e79921e6a28b550a5960a93ee07 Mon Sep 17 00:00:00 2001 From: Clifford Wolf Date: Thu, 31 Mar 2016 09:57:23 +0200 Subject: Preserve empty $pmux default cases --- passes/proc/proc_rmdead.cc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/passes/proc/proc_rmdead.cc b/passes/proc/proc_rmdead.cc index f60d4b30d..af17e8d38 100644 --- a/passes/proc/proc_rmdead.cc +++ b/passes/proc/proc_rmdead.cc @@ -51,8 +51,8 @@ void proc_rmdead(RTLIL::SwitchRule *sw, int &counter) counter++; continue; } - if (pool.empty()) - sw->cases[i]->compare.clear(); + // if (pool.empty()) + // sw->cases[i]->compare.clear(); } for (auto switch_it : sw->cases[i]->switches) -- cgit v1.2.3 From 6f1b6dc322bf6cceeadef7c666b8ff333ec6f2bf Mon Sep 17 00:00:00 2001 From: Clifford Wolf Date: Thu, 31 Mar 2016 09:57:44 +0200 Subject: Added log_dump() support for dict<> and pool<> containers --- kernel/log.h | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/kernel/log.h b/kernel/log.h index 28baf9886..c0be23b08 100644 --- a/kernel/log.h +++ b/kernel/log.h @@ -230,6 +230,32 @@ static inline void log_dump_args_worker(const char *p YS_ATTRIBUTE(unused)) { lo void log_dump_val_worker(RTLIL::IdString v); void log_dump_val_worker(RTLIL::SigSpec v); +template +static inline void log_dump_val_worker(dict &v) { + log("{"); + bool first = true; + for (auto &it : v) { + log(first ? " " : ", "); + log_dump_val_worker(it.first); + log(": "); + log_dump_val_worker(it.second); + first = false; + } + log(" }"); +} + +template +static inline void log_dump_val_worker(pool &v) { + log("{"); + bool first = true; + for (auto &it : v) { + log(first ? " " : ", "); + log_dump_val_worker(it); + first = false; + } + log(" }"); +} + template static inline void log_dump_val_worker(T *ptr) { log("%p", ptr); } -- cgit v1.2.3 From 6cafd08ac1090f405168187632fab4308129c599 Mon Sep 17 00:00:00 2001 From: Clifford Wolf Date: Thu, 31 Mar 2016 09:58:55 +0200 Subject: Improved opt_merge support for $pmux cells --- passes/opt/opt_merge.cc | 50 +++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 46 insertions(+), 4 deletions(-) diff --git a/passes/opt/opt_merge.cc b/passes/opt/opt_merge.cc index 13b3082fd..07019aac9 100644 --- a/passes/opt/opt_merge.cc +++ b/passes/opt/opt_merge.cc @@ -45,6 +45,29 @@ struct OptMergeWorker dict cell_hash_cache; #endif + static void sort_pmux_conn(dict &conn) + { + SigSpec sig_s = conn.at("\\S"); + SigSpec sig_b = conn.at("\\B"); + + int s_width = GetSize(sig_s); + int width = GetSize(sig_b) / s_width; + + vector> sb_pairs; + for (int i = 0; i < s_width; i++) + sb_pairs.push_back(pair(sig_s[i], sig_b.extract(i*width, width))); + + std::sort(sb_pairs.begin(), sb_pairs.end()); + + conn["\\S"] = SigSpec(); + conn["\\B"] = SigSpec(); + + for (auto &it : sb_pairs) { + conn["\\S"].append(it.first); + conn["\\B"].append(it.second); + } + } + #ifdef USE_CELL_HASH_CACHE std::string int_to_hash_string(unsigned int v) { @@ -91,25 +114,40 @@ struct OptMergeWorker assign_map.apply(alt_conn.at("\\A")); alt_conn.at("\\A").sort_and_unify(); conn = &alt_conn; + } else + if (cell->type == "$pmux") { + alt_conn = *conn; + assign_map.apply(alt_conn.at("\\A")); + assign_map.apply(alt_conn.at("\\B")); + assign_map.apply(alt_conn.at("\\S")); + sort_pmux_conn(alt_conn); + conn = &alt_conn; } + vector hash_conn_strings; + for (auto &it : *conn) { if (cell->output(it.first)) continue; RTLIL::SigSpec sig = it.second; assign_map.apply(sig); - hash_string += "C " + it.first.str() + "="; + string s = "C " + it.first.str() + "="; for (auto &chunk : sig.chunks()) { if (chunk.wire) - hash_string += "{" + chunk.wire->name.str() + " " + + s += "{" + chunk.wire->name.str() + " " + int_to_hash_string(chunk.offset) + " " + int_to_hash_string(chunk.width) + "}"; else - hash_string += RTLIL::Const(chunk.data).as_string(); + s += RTLIL::Const(chunk.data).as_string(); } - hash_string += "\n"; + hash_conn_strings.push_back(s + "\n"); } + std::sort(hash_conn_strings.begin(), hash_conn_strings.end()); + + for (auto it : hash_conn_strings) + hash_string += it; + cell_hash_cache[cell] = sha1(hash_string); return cell_hash_cache[cell]; } @@ -171,6 +209,10 @@ struct OptMergeWorker if (cell1->type == "$reduce_and" || cell1->type == "$reduce_or" || cell1->type == "$reduce_bool") { conn1["\\A"].sort_and_unify(); conn2["\\A"].sort_and_unify(); + } else + if (cell1->type == "$pmux") { + sort_pmux_conn(conn1); + sort_pmux_conn(conn2); } if (conn1 != conn2) { -- cgit v1.2.3 From 25533190818b0fe207be9a4626a9a273a08ae219 Mon Sep 17 00:00:00 2001 From: Clifford Wolf Date: Thu, 31 Mar 2016 11:16:34 +0200 Subject: Added ScriptPass helper class for script-like passes --- kernel/register.cc | 59 ++++++++++++ kernel/register.h | 17 ++++ kernel/yosys.cc | 6 +- techlibs/common/synth.cc | 153 +++++++++++++------------------ techlibs/ice40/synth_ice40.cc | 205 ++++++++++++++++-------------------------- 5 files changed, 222 insertions(+), 218 deletions(-) diff --git a/kernel/register.cc b/kernel/register.cc index 49a67324d..ebe3055ac 100644 --- a/kernel/register.cc +++ b/kernel/register.cc @@ -80,6 +80,7 @@ Pass::pre_post_exec_state_t Pass::pre_execute() state.begin_ns = PerformanceTimer::query(); state.parent_pass = current_pass; current_pass = this; + clear_flags(); return state; } @@ -99,6 +100,10 @@ void Pass::help() log("\n"); } +void Pass::clear_flags() +{ +} + void Pass::cmd_log_args(const std::vector &args) { if (args.size() <= 1) @@ -282,6 +287,60 @@ void Pass::call_on_module(RTLIL::Design *design, RTLIL::Module *module, std::vec design->selected_active_module = backup_selected_active_module; } +bool ScriptPass::check_label(std::string label, std::string info) +{ + if (active_design == nullptr) { + log("\n"); + if (info.empty()) + log(" %s:\n", label.c_str()); + else + log(" %s: %s\n", label.c_str(), info.c_str()); + return true; + } else { + if (!active_run_from.empty() && active_run_from == active_run_to) { + block_active = (label == active_run_from); + } else { + if (label == active_run_from) + block_active = true; + if (label == active_run_to) + block_active = false; + } + return block_active; + } +} + +void ScriptPass::run(std::string command, std::string info) +{ + if (active_design == nullptr) { + if (info.empty()) + log(" %s\n", command.c_str()); + else + log(" %s %s\n", command.c_str(), info.c_str()); + } else + Pass::call(active_design, command); +} + +void ScriptPass::run_script(RTLIL::Design *design, std::string run_from, std::string run_to) +{ + help_mode = false; + active_design = design; + block_active = run_from.empty(); + active_run_from = run_from; + active_run_to = run_to; + script(); +} + +void ScriptPass::help_script() +{ + clear_flags(); + help_mode = true; + active_design = nullptr; + block_active = true; + active_run_from.clear(); + active_run_to.clear(); + script(); +} + Frontend::Frontend(std::string name, std::string short_help) : Pass(name.rfind("=", 0) == 0 ? name.substr(1) : "read_" + name, short_help), frontend_name(name.rfind("=", 0) == 0 ? name.substr(1) : name) diff --git a/kernel/register.h b/kernel/register.h index 0ef07b760..8024c56a0 100644 --- a/kernel/register.h +++ b/kernel/register.h @@ -31,6 +31,7 @@ struct Pass virtual ~Pass(); virtual void help(); + virtual void clear_flags(); virtual void execute(std::vector args, RTLIL::Design *design) = 0; int call_counter; @@ -63,6 +64,22 @@ struct Pass static void done_register(); }; +struct ScriptPass : Pass +{ + bool block_active, help_mode; + RTLIL::Design *active_design; + std::string active_run_from, active_run_to; + + ScriptPass(std::string name, std::string short_help = "** document me **") : Pass(name, short_help) { } + + virtual void script() = 0; + + bool check_label(std::string label, std::string info = std::string()); + void run(std::string command, std::string info = std::string()); + void run_script(RTLIL::Design *design, std::string run_from = std::string(), std::string run_to = std::string()); + void help_script(); +}; + struct Frontend : Pass { // for reading of here documents diff --git a/kernel/yosys.cc b/kernel/yosys.cc index 501d94224..8da57fd4e 100644 --- a/kernel/yosys.cc +++ b/kernel/yosys.cc @@ -1100,8 +1100,8 @@ struct HistoryPass : public Pass { } HistoryPass; #endif -struct ScriptPass : public Pass { - ScriptPass() : Pass("script", "execute commands from script file") { } +struct ScriptCmdPass : public Pass { + ScriptCmdPass() : Pass("script", "execute commands from script file") { } virtual void help() { log("\n"); log(" script [:]\n"); @@ -1127,7 +1127,7 @@ struct ScriptPass : public Pass { else extra_args(args, 2, design, false); } -} ScriptPass; +} ScriptCmdPass; YOSYS_NAMESPACE_END diff --git a/techlibs/common/synth.cc b/techlibs/common/synth.cc index c837e1378..8eb1aeba4 100644 --- a/techlibs/common/synth.cc +++ b/techlibs/common/synth.cc @@ -25,22 +25,11 @@ USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN -bool check_label(bool &active, std::string run_from, std::string run_to, std::string label) +struct SynthPass : public ScriptPass { - if (!run_from.empty() && run_from == run_to) { - active = (label == run_from); - } else { - if (label == run_from) - active = true; - if (label == run_to) - active = false; - } - return active; -} + SynthPass() : ScriptPass("synth", "generic synthesis script") { } -struct SynthPass : public Pass { - SynthPass() : Pass("synth", "generic synthesis script") { } - virtual void help() + virtual void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); @@ -75,49 +64,28 @@ struct SynthPass : public Pass { log("\n"); log("\n"); log("The following commands are executed by this synthesis command:\n"); + help_script(); log("\n"); - log(" begin:\n"); - log(" hierarchy -check [-top ]\n"); - log("\n"); - log(" coarse:\n"); - log(" proc\n"); - log(" opt_expr\n"); - log(" opt_clean\n"); - log(" check\n"); - log(" opt\n"); - log(" wreduce\n"); - log(" alumacc\n"); - log(" share\n"); - log(" opt\n"); - log(" fsm\n"); - log(" opt -fast\n"); - log(" memory -nomap\n"); - log(" opt_clean\n"); - log("\n"); - log(" fine:\n"); - log(" opt -fast -full\n"); - log(" memory_map\n"); - log(" opt -full\n"); - log(" techmap\n"); - log(" opt -fast\n"); - #ifdef YOSYS_ENABLE_ABC - log(" abc -fast\n"); - log(" opt -fast\n"); - #endif - log("\n"); - log(" check:\n"); - log(" hierarchy -check\n"); - log(" stat\n"); - log(" check\n"); - log("\n"); } - virtual void execute(std::vector args, RTLIL::Design *design) + + std::string top_module, fsm_opts, memory_opts; + bool noalumacc, nofsm, noabc; + + virtual void clear_flags() YS_OVERRIDE + { + top_module.clear(); + fsm_opts.clear(); + memory_opts.clear(); + + noalumacc = false; + nofsm = false; + noabc = false; + } + + virtual void execute(std::vector args, RTLIL::Design *design) YS_OVERRIDE { - std::string top_module, fsm_opts, memory_opts; - std::string run_from, run_to; - bool noalumacc = false; - bool nofsm = false; - bool noabc = false; + string run_from, run_to; + clear_flags(); size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) @@ -164,62 +132,69 @@ struct SynthPass : public Pass { if (!design->full_selection()) log_cmd_error("This comannd only operates on fully selected designs!\n"); - bool active = run_from.empty(); - log_header("Executing SYNTH pass.\n"); log_push(); - if (check_label(active, run_from, run_to, "begin")) + run_script(design, run_from, run_to); + + log_pop(); + } + + virtual void script() YS_OVERRIDE + { + if (check_label("begin")) { - if (top_module.empty()) - Pass::call(design, stringf("hierarchy -check")); - else - Pass::call(design, stringf("hierarchy -check -top %s", top_module.c_str())); + if (help_mode) { + run("hierarchy -check [-top ]"); + } else { + if (top_module.empty()) + run(stringf("hierarchy -check")); + else + run(stringf("hierarchy -check -top %s", top_module.c_str())); + } } - if (check_label(active, run_from, run_to, "coarse")) + if (check_label("coarse")) { - Pass::call(design, "proc"); - Pass::call(design, "opt_expr"); - Pass::call(design, "opt_clean"); - Pass::call(design, "check"); - Pass::call(design, "opt"); - Pass::call(design, "wreduce"); + run("proc"); + run("opt_expr"); + run("opt_clean"); + run("check"); + run("opt"); + run("wreduce"); if (!noalumacc) - Pass::call(design, "alumacc"); - Pass::call(design, "share"); - Pass::call(design, "opt"); + run("alumacc"); + run("share"); + run("opt"); if (!nofsm) - Pass::call(design, "fsm" + fsm_opts); - Pass::call(design, "opt -fast"); - Pass::call(design, "memory -nomap" + memory_opts); - Pass::call(design, "opt_clean"); + run("fsm" + fsm_opts); + run("opt -fast"); + run("memory -nomap" + memory_opts); + run("opt_clean"); } - if (check_label(active, run_from, run_to, "fine")) + if (check_label("fine")) { - Pass::call(design, "opt -fast -full"); - Pass::call(design, "memory_map"); - Pass::call(design, "opt -full"); - Pass::call(design, "techmap"); - Pass::call(design, "opt -fast"); + run("opt -fast -full"); + run("memory_map"); + run("opt -full"); + run("techmap"); + run("opt -fast"); if (!noabc) { #ifdef YOSYS_ENABLE_ABC - Pass::call(design, "abc -fast"); - Pass::call(design, "opt -fast"); + run("abc -fast"); + run("opt -fast"); #endif } } - if (check_label(active, run_from, run_to, "check")) + if (check_label("check")) { - Pass::call(design, "hierarchy -check"); - Pass::call(design, "stat"); - Pass::call(design, "check"); + run("hierarchy -check"); + run("stat"); + run("check"); } - - log_pop(); } } SynthPass; diff --git a/techlibs/ice40/synth_ice40.cc b/techlibs/ice40/synth_ice40.cc index f24d31a8c..2ed7642ae 100644 --- a/techlibs/ice40/synth_ice40.cc +++ b/techlibs/ice40/synth_ice40.cc @@ -25,18 +25,11 @@ USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN -bool check_label(bool &active, std::string run_from, std::string run_to, std::string label) +struct SynthIce40Pass : public ScriptPass { - if (label == run_from) - active = true; - if (label == run_to) - active = false; - return active; -} + SynthIce40Pass() : ScriptPass("synth_ice40", "synthesis for iCE40 FPGAs") { } -struct SynthIce40Pass : public Pass { - SynthIce40Pass() : Pass("synth_ice40", "synthesis for iCE40 FPGAs") { } - virtual void help() + virtual void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); @@ -77,73 +70,30 @@ struct SynthIce40Pass : public Pass { log("\n"); log("\n"); log("The following commands are executed by this synthesis command:\n"); + help_script(); log("\n"); - log(" begin:\n"); - log(" read_verilog -lib +/ice40/cells_sim.v\n"); - log(" hierarchy -check -top \n"); - log("\n"); - log(" flatten: (unless -noflatten)\n"); - log(" proc\n"); - log(" flatten\n"); - log(" tribuf -logic\n"); - log("\n"); - log(" coarse:\n"); - log(" synth -run coarse\n"); - log("\n"); - log(" bram: (skip if -nobram)\n"); - log(" memory_bram -rules +/ice40/brams.txt\n"); - log(" techmap -map +/ice40/brams_map.v\n"); - log("\n"); - log(" fine:\n"); - log(" opt -fast -mux_undef -undriven -fine\n"); - log(" memory_map\n"); - log(" opt -undriven -fine\n"); - log(" techmap -map +/techmap.v [-map +/ice40/arith_map.v]\n"); - log(" abc -dff (only if -retime)\n"); - log(" ice40_opt\n"); - log("\n"); - log(" map_ffs:\n"); - log(" dffsr2dff\n"); - log(" dff2dffe -direct-match $_DFF_*\n"); - log(" techmap -map +/ice40/cells_map.v\n"); - log(" opt_expr -mux_undef\n"); - log(" simplemap\n"); - log(" ice40_ffinit\n"); - log(" ice40_ffssr\n"); - log(" ice40_opt -full\n"); - log("\n"); - log(" map_luts:\n"); - log(" abc (only if -abc2)\n"); - log(" ice40_opt (only if -abc2)\n"); - log(" abc -lut 4\n"); - log(" clean\n"); - log("\n"); - log(" map_cells:\n"); - log(" techmap -map +/ice40/cells_map.v\n"); - log(" clean\n"); - log("\n"); - log(" check:\n"); - log(" hierarchy -check\n"); - log(" stat\n"); - log(" check -noinit\n"); - log("\n"); - log(" blif:\n"); - log(" write_blif -gates -attr -param \n"); - log("\n"); - log(" edif:\n"); - log(" write_edif \n"); - log("\n"); } - virtual void execute(std::vector args, RTLIL::Design *design) + + string top_opt = "-auto-top"; + string blif_file, edif_file; + bool nocarry, nobram, flatten, retime, abc2; + + virtual void clear_flags() YS_OVERRIDE + { + top_opt = "-auto-top"; + blif_file = ""; + edif_file = ""; + nocarry = false; + nobram = false; + flatten = true; + retime = false; + abc2 = false; + } + + virtual void execute(std::vector args, RTLIL::Design *design) YS_OVERRIDE { - std::string top_opt = "-auto-top"; std::string run_from, run_to; - std::string blif_file, edif_file; - bool nocarry = false; - bool nobram = false; - bool flatten = true; - bool retime = false; - bool abc2 = false; + clear_flags(); size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) @@ -199,97 +149,100 @@ struct SynthIce40Pass : public Pass { if (!design->full_selection()) log_cmd_error("This comannd only operates on fully selected designs!\n"); - bool active = run_from.empty(); - log_header("Executing SYNTH_ICE40 pass.\n"); log_push(); - if (check_label(active, run_from, run_to, "begin")) + run_script(design, run_from, run_to); + + log_pop(); + } + + virtual void script() YS_OVERRIDE + { + if (check_label("begin")) { - Pass::call(design, "read_verilog -lib +/ice40/cells_sim.v"); - Pass::call(design, stringf("hierarchy -check %s", top_opt.c_str())); + run("read_verilog -lib +/ice40/cells_sim.v"); + run(stringf("hierarchy -check %s", help_mode ? "-top " : top_opt.c_str())); } - if (flatten && check_label(active, run_from, run_to, "flatten")) + if (flatten && check_label("flatten", "(unless -noflatten)")) { - Pass::call(design, "proc"); - Pass::call(design, "flatten"); - Pass::call(design, "tribuf -logic"); + run("proc"); + run("flatten"); + run("tribuf -logic"); } - if (check_label(active, run_from, run_to, "coarse")) + if (check_label("coarse")) { - Pass::call(design, "synth -run coarse"); + run("synth -run coarse"); } - if (!nobram && check_label(active, run_from, run_to, "bram")) + if (!nobram && check_label("bram", "(skip if -nobram)")) { - Pass::call(design, "memory_bram -rules +/ice40/brams.txt"); - Pass::call(design, "techmap -map +/ice40/brams_map.v"); + run("memory_bram -rules +/ice40/brams.txt"); + run("techmap -map +/ice40/brams_map.v"); } - if (check_label(active, run_from, run_to, "fine")) + if (check_label("fine")) { - Pass::call(design, "opt -fast -mux_undef -undriven -fine"); - Pass::call(design, "memory_map"); - Pass::call(design, "opt -undriven -fine"); + run("opt -fast -mux_undef -undriven -fine"); + run("memory_map"); + run("opt -undriven -fine"); if (nocarry) - Pass::call(design, "techmap"); + run("techmap"); else - Pass::call(design, "techmap -map +/techmap.v -map +/ice40/arith_map.v"); - if (retime) - Pass::call(design, "abc -dff"); - Pass::call(design, "ice40_opt"); + run("techmap -map +/techmap.v -map +/ice40/arith_map.v"); + if (retime || help_mode) + run("abc -dff", "(only if -retime)"); + run("ice40_opt"); } - if (check_label(active, run_from, run_to, "map_ffs")) + if (check_label("map_ffs")) { - Pass::call(design, "dffsr2dff"); - Pass::call(design, "dff2dffe -direct-match $_DFF_*"); - Pass::call(design, "techmap -map +/ice40/cells_map.v"); - Pass::call(design, "opt_expr -mux_undef"); - Pass::call(design, "simplemap"); - Pass::call(design, "ice40_ffinit"); - Pass::call(design, "ice40_ffssr"); - Pass::call(design, "ice40_opt -full"); + run("dffsr2dff"); + run("dff2dffe -direct-match $_DFF_*"); + run("techmap -map +/ice40/cells_map.v"); + run("opt_expr -mux_undef"); + run("simplemap"); + run("ice40_ffinit"); + run("ice40_ffssr"); + run("ice40_opt -full"); } - if (check_label(active, run_from, run_to, "map_luts")) + if (check_label("map_luts")) { - if (abc2) { - Pass::call(design, "abc"); - Pass::call(design, "ice40_opt"); + if (abc2 || help_mode) { + run("abc", " (only if -abc2)"); + run("ice40_opt", "(only if -abc2)"); } - Pass::call(design, "abc -lut 4"); - Pass::call(design, "clean"); + run("abc -lut 4"); + run("clean"); } - if (check_label(active, run_from, run_to, "map_cells")) + if (check_label("map_cells")) { - Pass::call(design, "techmap -map +/ice40/cells_map.v"); - Pass::call(design, "clean"); + run("techmap -map +/ice40/cells_map.v"); + run("clean"); } - if (check_label(active, run_from, run_to, "check")) + if (check_label("check")) { - Pass::call(design, "hierarchy -check"); - Pass::call(design, "stat"); - Pass::call(design, "check -noinit"); + run("hierarchy -check"); + run("stat"); + run("check -noinit"); } - if (check_label(active, run_from, run_to, "blif")) + if (check_label("blif")) { - if (!blif_file.empty()) - Pass::call(design, stringf("write_blif -gates -attr -param %s", blif_file.c_str())); + if (!blif_file.empty() || help_mode) + run(stringf("write_blif -gates -attr -param %s", help_mode ? "" : blif_file.c_str())); } - if (check_label(active, run_from, run_to, "edif")) + if (check_label("edif")) { - if (!edif_file.empty()) - Pass::call(design, stringf("write_edif %s", edif_file.c_str())); + if (!edif_file.empty() || help_mode) + run(stringf("write_edif %s", help_mode ? "" : edif_file.c_str())); } - - log_pop(); } } SynthIce40Pass; -- cgit v1.2.3