shregmap -tech xilinx_static to handle INIT
[yosys.git] / passes / techmap / shregmap.cc
index ad5c50cd6adff1e78c333b7ceb0c9a698ef1316c..3868bbb8948b0acc12eaa4732c1f9623aaa24d09 100644 (file)
 USING_YOSYS_NAMESPACE
 PRIVATE_NAMESPACE_BEGIN
 
+struct ShregmapTech
+{
+       virtual ~ShregmapTech() { }
+       virtual void init(const Module * /*module*/, const SigMap &/*sigmap*/) {}
+       virtual void non_chain_user(const SigBit &/*bit*/, const Cell* /*cell*/, IdString /*port*/) {}
+       virtual bool analyze_first(const Cell* /*first_cell*/, const SigMap &/*sigmap*/) { return true; }
+       virtual bool analyze(vector<int> &taps, const vector<SigBit> &qbits) = 0;
+       virtual Cell* fixup(Cell *cell, const vector<int> &taps, const vector<SigBit> &qbits) = 0;
+};
+
 struct ShregmapOptions
 {
-       std::string clkpol;
        int minlen, maxlen;
        int keep_before, keep_after;
+       bool zinit, init, params, ffe;
+       dict<IdString, pair<IdString, IdString>> ffcells;
+       ShregmapTech *tech;
 
        ShregmapOptions()
        {
-               clkpol = "any";
                minlen = 2;
                maxlen = 0;
                keep_before = 0;
                keep_after = 0;
+               zinit = false;
+               init = false;
+               params = false;
+               ffe = false;
+               tech = nullptr;
+       }
+};
+
+struct ShregmapTechGreenpak4 : ShregmapTech
+{
+       virtual bool analyze(vector<int> &taps, const vector<SigBit> &/*qbits*/) override
+       {
+               if (GetSize(taps) > 2 && taps[0] == 0 && taps[2] < 17) {
+                       taps.clear();
+                       return true;
+               }
+
+               if (GetSize(taps) > 2)
+                       return false;
+
+               if (taps.back() > 16) return false;
+
+               return true;
+       }
+
+       virtual Cell* fixup(Cell *cell, const vector<int> &taps, const vector<SigBit> &qbits) override
+       {
+               auto D = cell->getPort("\\D");
+               auto C = cell->getPort("\\C");
+
+               auto newcell = cell->module->addCell(NEW_ID, "\\GP_SHREG");
+               newcell->setPort("\\nRST", State::S1);
+               newcell->setPort("\\CLK", C);
+               newcell->setPort("\\IN", D);
+
+               int i = 0;
+               for (auto tap : taps) {
+                       newcell->setPort(i ? "\\OUTB" : "\\OUTA", qbits[tap]);
+                       newcell->setParam(i ? "\\OUTB_TAP" : "\\OUTA_TAP", tap + 1);
+                       i++;
+               }
+
+               cell->setParam("\\OUTA_INVERT", 0);
+               return newcell;
        }
 };
 
+struct ShregmapTechXilinx7Static : ShregmapTech
+{
+       dict<SigBit, Cell*> sigbit_to_cell;
+       const ShregmapOptions &opts;
+
+       virtual void init(const Module* module, const SigMap &sigmap) override
+       {
+               for (const auto &i : module->cells_) {
+                       auto cell = i.second;
+                       if (!cell->type.in("\\FDRE", "\\FDRE_1","\\FDSE", "\\FDSE_1",
+                                       "\\FDCE", "\\FDCE_1", "\\FDPE", "\\FDPE_1"))
+                               continue;
+
+                       sigbit_to_cell[sigmap(cell->getPort("\\Q"))] = cell;
+               }
+       }
+
+       ShregmapTechXilinx7Static(const ShregmapOptions &opts) : opts(opts) {}
+
+       virtual bool analyze_first(const Cell* first_cell, const SigMap &sigmap) override
+       {
+               if (first_cell->type.in("\\FDRE", "\\FDRE_1")) {
+                       bool is_R_inverted = false;
+                       if (first_cell->hasParam("\\IS_R_INVERTED"))
+                               is_R_inverted = first_cell->getParam("\\IS_R_INVERTED").as_bool();
+                       SigBit R = sigmap(first_cell->getPort("\\R"));
+                       if (R != RTLIL::S0 && R != RTLIL::S1)
+                               return false;
+                       if ((!is_R_inverted && R != RTLIL::S0) || (is_R_inverted && R != RTLIL::S1))
+                               return false;
+                       return true;
+               }
+               if (first_cell->type.in("\\FDSE", "\\FDSE_1")) {
+                       bool is_S_inverted = false;
+                       if (first_cell->hasParam("\\IS_S_INVERTED"))
+                               is_S_inverted = first_cell->getParam("\\IS_S_INVERTED").as_bool();
+                       SigBit S = sigmap(first_cell->getPort("\\S"));
+                       if (S != RTLIL::S0 && S != RTLIL::S1)
+                               return false;
+                       if ((!is_S_inverted && S != RTLIL::S0) || (is_S_inverted && S != RTLIL::S1))
+                               return false;
+                       return true;
+               }
+               if (first_cell->type.in("\\FDCE", "\\FDCE_1")) {
+                       bool is_CLR_inverted = false;
+                       if (first_cell->hasParam("\\IS_CLR_INVERTED"))
+                               is_CLR_inverted = first_cell->getParam("\\IS_CLR_INVERTED").as_bool();
+                       SigBit CLR = sigmap(first_cell->getPort("\\CLR"));
+                       if (CLR != RTLIL::S0 && CLR != RTLIL::S1)
+                               return false;
+                       if ((!is_CLR_inverted && CLR != RTLIL::S0) || (is_CLR_inverted && CLR != RTLIL::S1))
+                               return false;
+                       return true;
+               }
+               if (first_cell->type.in("\\FDPE", "\\FDPE_1")) {
+                       bool is_PRE_inverted = false;
+                       if (first_cell->hasParam("\\IS_PRE_INVERTED"))
+                               is_PRE_inverted = first_cell->getParam("\\IS_PRE_INVERTED").as_bool();
+                       SigBit PRE = sigmap(first_cell->getPort("\\PRE"));
+                       if (PRE != RTLIL::S0 && PRE != RTLIL::S1)
+                               return false;
+                       if ((!is_PRE_inverted && PRE != RTLIL::S0) || (is_PRE_inverted && PRE != RTLIL::S1))
+                               return false;
+                       return true;
+               }
+               return true;
+       }
+
+       virtual bool analyze(vector<int> &taps, const vector<SigBit> &/*qbits*/) override
+       {
+               return GetSize(taps) == 1 && taps[0] >= opts.minlen-1;
+       }
+
+       virtual Cell* fixup(Cell *cell, const vector<int> &/*taps*/, const vector<SigBit> &qbits) override
+       {
+               auto newcell = cell->module->addCell(NEW_ID, "$__SHREG_");
+               newcell->set_src_attribute(cell->get_src_attribute());
+               newcell->setParam("\\DEPTH", cell->getParam("\\DEPTH"));
+
+               if (cell->type.in("$__SHREG_DFF_N_", "$__SHREG_DFF_P_",
+                               "$__SHREG_DFFE_NN_", "$__SHREG_DFFE_NP_", "$__SHREG_DFFE_PN_", "$__SHREG_DFFE_PP_")) {
+                       int param_clkpol = -1;
+                       int param_enpol = 2;
+                       if (cell->type == "$__SHREG_DFF_N_") param_clkpol = 0;
+                       else if (cell->type == "$__SHREG_DFF_P_") param_clkpol = 1;
+                       else if (cell->type == "$__SHREG_DFFE_NN_") param_clkpol = 0, param_enpol = 0;
+                       else if (cell->type == "$__SHREG_DFFE_NP_") param_clkpol = 0, param_enpol = 1;
+                       else if (cell->type == "$__SHREG_DFFE_PN_") param_clkpol = 1, param_enpol = 0;
+                       else if (cell->type == "$__SHREG_DFFE_PP_") param_clkpol = 1, param_enpol = 1;
+                       else log_abort();
+
+                       log_assert(param_clkpol >= 0);
+                       newcell->setParam("\\CLKPOL", param_clkpol);
+                       newcell->setParam("\\ENPOL", param_enpol);
+                       newcell->setParam("\\INIT", cell->getParam("\\INIT"));
+
+                       if (cell->hasPort("\\E"))
+                               newcell->setPort("\\E", cell->getPort("\\E"));
+               }
+               else if (cell->type.in("$__SHREG_FDRE", "$__SHREG_FDRE_1","$__SHREG_FDSE", "$__SHREG_FDSE_1",
+                                       "$__SHREG_FDCE", "$__SHREG_FDCE_1", "$__SHREG_FDPE", "$__SHREG_FDPE_1")) {
+                       int param_clkpol = 1;
+                       if (cell->hasParam("\\IS_C_INVERTED") && cell->getParam("\\IS_C_INVERTED").as_bool())
+                               param_clkpol = 0;
+                       newcell->setParam("\\CLKPOL", param_clkpol);
+                       newcell->setParam("\\ENPOL", 1);
+                       log_assert(cell->getParam("\\INIT").is_fully_undef());
+                       SigSpec INIT;
+                       for (auto q : qbits) {
+                               Cell* reg = sigbit_to_cell.at(q);
+                               INIT.append(SigBit(reg->getParam("\\INIT").as_bool()));
+                       }
+
+                       newcell->setPort("\\E", cell->getPort("\\CE"));
+               }
+               else log_abort();
+
+               newcell->setParam("\\ENPOL", 1);
+
+               newcell->setPort("\\C", cell->getPort("\\C"));
+               newcell->setPort("\\D", cell->getPort("\\D"));
+               newcell->setPort("\\Q", cell->getPort("\\Q"));
+
+               return newcell;
+       }
+};
+
+struct ShregmapTechXilinx7Dynamic : ShregmapTechXilinx7Static
+{
+       dict<SigBit, std::tuple<Cell*,int,int>> sigbit_to_shiftx_offset;
+
+       ShregmapTechXilinx7Dynamic(const ShregmapOptions &opts) : ShregmapTechXilinx7Static(opts) {}
+
+       virtual void init(const Module* module, const SigMap &sigmap) override
+       {
+               for (const auto &i : module->cells_) {
+                       auto cell = i.second;
+                       if (cell->type == "$shiftx") {
+                               if (cell->getParam("\\Y_WIDTH") != 1) continue;
+                               int j = 0;
+                               for (auto bit : sigmap(cell->getPort("\\A")))
+                                       sigbit_to_shiftx_offset[bit] = std::make_tuple(cell, j++, 0);
+                               log_assert(j == cell->getParam("\\A_WIDTH").as_int());
+                       }
+                       else if (cell->type == "$mux") {
+                               int j = 0;
+                               for (auto bit : sigmap(cell->getPort("\\A")))
+                                       sigbit_to_shiftx_offset[bit] = std::make_tuple(cell, 0, j++);
+                               j = 0;
+                               for (auto bit : sigmap(cell->getPort("\\B")))
+                                       sigbit_to_shiftx_offset[bit] = std::make_tuple(cell, 1, j++);
+                       }
+               }
+       }
+
+       virtual void non_chain_user(const SigBit &bit, const Cell *cell, IdString port) override
+       {
+               auto it = sigbit_to_shiftx_offset.find(bit);
+               if (it == sigbit_to_shiftx_offset.end())
+                       return;
+               if (cell) {
+                       if (cell->type == "$shiftx" && port == "\\A")
+                               return;
+                       if (cell->type == "$mux" && (port == "\\A" || port == "\\B"))
+                               return;
+               }
+               sigbit_to_shiftx_offset.erase(it);
+       }
+
+       virtual bool analyze(vector<int> &taps, const vector<SigBit> &qbits) override
+       {
+               if (GetSize(taps) == 1)
+                       return taps[0] >= opts.minlen-1 && sigbit_to_shiftx_offset.count(qbits[0]);
+
+               if (taps.back() < opts.minlen-1)
+                       return false;
+
+               Cell *shiftx = nullptr;
+               int group = 0;
+               for (int i = 0; i < GetSize(taps); ++i) {
+                       // Check taps are sequential
+                       if (i != taps[i])
+                               return false;
+
+                       auto it = sigbit_to_shiftx_offset.find(qbits[i]);
+                       if (it == sigbit_to_shiftx_offset.end())
+                               return false;
+
+                       // Check taps are not connected to a shift register,
+                       // or sequential to the same shift register
+                       if (i == 0) {
+                               int offset;
+                               std::tie(shiftx,offset,group) = it->second;
+                               if (offset != i)
+                                       return false;
+                       }
+                       else {
+                               Cell *shiftx_ = std::get<0>(it->second);
+                               if (shiftx_ != shiftx)
+                                       return false;
+                               int offset = std::get<1>(it->second);
+                               if (offset != i)
+                                       return false;
+                               int group_ = std::get<2>(it->second);
+                               if (group_ != group)
+                                       return false;
+                       }
+               }
+               log_assert(shiftx);
+
+               // Only map if $shiftx exclusively covers the shift register
+               if (shiftx->type == "$shiftx") {
+                       if (GetSize(taps) > shiftx->getParam("\\A_WIDTH").as_int())
+                               return false;
+                       // Due to padding the most significant bits of A may be 1'bx,
+                       //   and if so, discount them
+                       if (GetSize(taps) < shiftx->getParam("\\A_WIDTH").as_int()) {
+                               const SigSpec A = shiftx->getPort("\\A");
+                               const int A_width = shiftx->getParam("\\A_WIDTH").as_int();
+                               for (int i = GetSize(taps); i < A_width; ++i)
+                                       if (A[i] != RTLIL::Sx) return false;
+                       }
+                       else if (GetSize(taps) != shiftx->getParam("\\A_WIDTH").as_int())
+                               return false;
+               }
+               else if (shiftx->type == "$mux") {
+                       if (GetSize(taps) != 2)
+                               return false;
+               }
+               else log_abort();
+
+               return true;
+       }
+
+       virtual Cell* fixup(Cell *cell, const vector<int> &taps, const vector<SigBit> &qbits) override
+       {
+               auto bit = qbits[taps.front()];
+
+               auto it = sigbit_to_shiftx_offset.find(bit);
+               log_assert(it != sigbit_to_shiftx_offset.end());
+
+               Cell* newcell = ShregmapTechXilinx7Static::fixup(cell, taps, qbits);
+               log_assert(newcell);
+               log_assert(newcell->type == "$__SHREG_");
+               newcell->type = "$__XILINX_SHREG_";
+
+               Cell* shiftx = std::get<0>(it->second);
+               RTLIL::SigSpec l_wire;
+               if (shiftx->type == "$shiftx")
+                       l_wire = shiftx->getPort("\\B");
+               else if (shiftx->type == "$mux")
+                       l_wire = shiftx->getPort("\\S");
+               else log_abort();
+
+               newcell->setPort("\\L", l_wire);
+               newcell->setPort("\\Q", shiftx->getPort("\\Y"));
+               shiftx->setPort("\\Y", cell->module->addWire(NEW_ID));
+
+               return newcell;
+       }
+};
+
+
 struct ShregmapWorker
 {
        Module *module;
@@ -47,40 +365,65 @@ struct ShregmapWorker
        const ShregmapOptions &opts;
        int dff_count, shreg_count;
 
-       // next is set to NULL for sigbits that drive non-DFFs
+       pool<Cell*> remove_cells;
+       pool<SigBit> remove_init;
+
+       dict<SigBit, bool> sigbit_init;
        dict<SigBit, Cell*> sigbit_chain_next;
        dict<SigBit, Cell*> sigbit_chain_prev;
+       pool<SigBit> sigbit_with_non_chain_users;
        pool<Cell*> chain_start_cells;
 
        void make_sigbit_chain_next_prev()
        {
-               for (auto wire : module->wires()) {
-                       if (!wire->port_output)
-                               continue;
-                       for (auto bit : sigmap(wire))
-                               sigbit_chain_next[bit] = nullptr;
+               for (auto wire : module->wires())
+               {
+                       if (wire->port_output || wire->get_bool_attribute("\\keep")) {
+                               for (auto bit : sigmap(wire)) {
+                                       sigbit_with_non_chain_users.insert(bit);
+                                       if (opts.tech) opts.tech->non_chain_user(bit, nullptr, {});
+                               }
+                       }
+
+                       if (wire->attributes.count("\\init")) {
+                               SigSpec initsig = sigmap(wire);
+                               Const initval = wire->attributes.at("\\init");
+                               for (int i = 0; i < GetSize(initsig) && i < GetSize(initval); i++)
+                                       if (initval[i] == State::S0 && !opts.zinit)
+                                               sigbit_init[initsig[i]] = false;
+                                       else if (initval[i] == State::S1)
+                                               sigbit_init[initsig[i]] = true;
+                       }
                }
 
                for (auto cell : module->cells())
                {
-                       if ((opts.clkpol != "pos" && cell->type == "$_DFF_N_") ||
-                                       (opts.clkpol != "neg" && cell->type == "$_DFF_P_"))
+                       if (opts.ffcells.count(cell->type) && !cell->get_bool_attribute("\\keep"))
                        {
-                               SigBit d_bit = sigmap(cell->getPort("\\D").as_bit());
-                               if (sigbit_chain_next.count(d_bit))
-                                       sigbit_chain_next[d_bit] = nullptr;
-                               else
-                                       sigbit_chain_next[d_bit] = cell;
-
-                               SigBit q_bit = sigmap(cell->getPort("\\Q").as_bit());
-                               sigbit_chain_prev[q_bit] = cell;
-                               continue;
+                               IdString d_port = opts.ffcells.at(cell->type).first;
+                               IdString q_port = opts.ffcells.at(cell->type).second;
+
+                               SigBit d_bit = sigmap(cell->getPort(d_port).as_bit());
+                               SigBit q_bit = sigmap(cell->getPort(q_port).as_bit());
+
+                               if (opts.init || sigbit_init.count(q_bit) == 0)
+                               {
+                                       if (sigbit_chain_next.count(d_bit)) {
+                                               sigbit_with_non_chain_users.insert(d_bit);
+                                       } else
+                                               sigbit_chain_next[d_bit] = cell;
+
+                                       sigbit_chain_prev[q_bit] = cell;
+                                       continue;
+                               }
                        }
 
                        for (auto conn : cell->connections())
                                if (cell->input(conn.first))
-                                       for (auto bit : sigmap(conn.second))
-                                               sigbit_chain_next[bit] = nullptr;
+                                       for (auto bit : sigmap(conn.second)) {
+                                               sigbit_with_non_chain_users.insert(bit);
+                                               if (opts.tech) opts.tech->non_chain_user(bit, cell, conn.first);
+                                       }
                }
        }
 
@@ -88,8 +431,8 @@ struct ShregmapWorker
        {
                for (auto it : sigbit_chain_next)
                {
-                       if (it.second == nullptr)
-                               continue;
+                       if (opts.tech == nullptr && sigbit_with_non_chain_users.count(it.first))
+                               goto start_cell;
 
                        if (sigbit_chain_prev.count(it.first) != 0)
                        {
@@ -99,7 +442,22 @@ struct ShregmapWorker
                                if (c1->type != c2->type)
                                        goto start_cell;
 
-                               if (sigmap(c1->getPort("\\C")) != c2->getPort("\\C"))
+                               if (c1->parameters != c2->parameters)
+                                       goto start_cell;
+
+                               IdString d_port = opts.ffcells.at(c1->type).first;
+                               IdString q_port = opts.ffcells.at(c1->type).second;
+
+                               auto c1_conn = c1->connections();
+                               auto c2_conn = c1->connections();
+
+                               c1_conn.erase(d_port);
+                               c1_conn.erase(q_port);
+
+                               c2_conn.erase(d_port);
+                               c2_conn.erase(q_port);
+
+                               if (c1_conn != c2_conn)
                                        goto start_cell;
 
                                continue;
@@ -119,7 +477,8 @@ struct ShregmapWorker
                {
                        chain.push_back(c);
 
-                       SigBit q_bit = sigmap(c->getPort("\\Q").as_bit());
+                       IdString q_port = opts.ffcells.at(c->type).second;
+                       SigBit q_bit = sigmap(c->getPort(q_port).as_bit());
 
                        if (sigbit_chain_next.count(q_bit) == 0)
                                break;
@@ -145,48 +504,176 @@ struct ShregmapWorker
                        if (opts.maxlen > 0)
                                depth = std::min(opts.maxlen, depth);
 
-                       Cell *first_cell = chain[cursor], *last_cell = chain[cursor+depth-1];
+                       Cell *first_cell = chain[cursor];
+                       IdString q_port = opts.ffcells.at(first_cell->type).second;
+                       vector<SigBit> qbits;
+                       vector<int> taps;
 
-                       if (depth < 2)
-                               return;
+                       if (opts.tech)
+                       {
+                               if (!opts.tech->analyze_first(first_cell, sigmap)) {
+                                       cursor += depth;
+                                       continue;
+                               }
+
+                               for (int i = 0; i < depth; i++)
+                               {
+                                       Cell *cell = chain[cursor+i];
+                                       auto qbit = sigmap(cell->getPort(q_port));
+                                       qbits.push_back(qbit);
+
+                                       if (sigbit_with_non_chain_users.count(qbit))
+                                               taps.push_back(i);
+                               }
+
+                               while (depth > 0)
+                               {
+                                       if (taps.empty() || taps.back() < depth-1)
+                                               taps.push_back(depth-1);
+
+                                       if (opts.tech->analyze(taps, qbits))
+                                               break;
+
+                                       taps.pop_back();
+                                       depth--;
+                               }
+
+                               depth = 0;
+                               for (auto tap : taps) {
+                                       log_assert(depth < tap+1);
+                                       depth = tap+1;
+                               }
+                       }
+
+                       if (depth < 2) {
+                               cursor++;
+                               continue;
+                       }
+
+                       Cell *last_cell = chain[cursor+depth-1];
 
                        log("Converting %s.%s ... %s.%s to a shift register with depth %d.\n",
                                log_id(module), log_id(first_cell), log_id(module), log_id(last_cell), depth);
 
-                       first_cell->type = "$__DFF_SHREG_" + first_cell->type.substr(6);
-                       first_cell->setPort("\\Q", last_cell->getPort("\\Q"));
+                       dff_count += depth;
+                       shreg_count += 1;
+
+                       string shreg_cell_type_str = "$__SHREG";
+                       if (opts.params) {
+                               shreg_cell_type_str += "_";
+                       } else {
+                               if (first_cell->type[1] != '_')
+                                       shreg_cell_type_str += "_";
+                               shreg_cell_type_str += first_cell->type.substr(1);
+                       }
+
+                       if (opts.init) {
+                               vector<State> initval;
+                               for (int i = depth-1; i >= 0; i--) {
+                                       SigBit bit = sigmap(chain[cursor+i]->getPort(q_port).as_bit());
+                                       if (sigbit_init.count(bit) == 0)
+                                               initval.push_back(State::Sx);
+                                       else if (sigbit_init.at(bit))
+                                               initval.push_back(State::S1);
+                                       else
+                                               initval.push_back(State::S0);
+                                       remove_init.insert(bit);
+                               }
+                               first_cell->setParam("\\INIT", initval);
+                       }
+
+                       if (opts.zinit)
+                               for (int i = depth-1; i >= 0; i--) {
+                                       SigBit bit = sigmap(chain[cursor+i]->getPort(q_port).as_bit());
+                                       remove_init.insert(bit);
+                               }
+
+                       if (opts.params)
+                       {
+                               int param_clkpol = -1;
+                               int param_enpol = 2;
+
+                               if (first_cell->type == "$_DFF_N_") param_clkpol = 0;
+                               if (first_cell->type == "$_DFF_P_") param_clkpol = 1;
+
+                               if (first_cell->type == "$_DFFE_NN_") param_clkpol = 0, param_enpol = 0;
+                               if (first_cell->type == "$_DFFE_NP_") param_clkpol = 0, param_enpol = 1;
+                               if (first_cell->type == "$_DFFE_PN_") param_clkpol = 1, param_enpol = 0;
+                               if (first_cell->type == "$_DFFE_PP_") param_clkpol = 1, param_enpol = 1;
+
+                               log_assert(param_clkpol >= 0);
+                               first_cell->setParam("\\CLKPOL", param_clkpol);
+                               if (opts.ffe) first_cell->setParam("\\ENPOL", param_enpol);
+                       }
+
+                       first_cell->type = shreg_cell_type_str;
+                       first_cell->setPort(q_port, last_cell->getPort(q_port));
                        first_cell->setParam("\\DEPTH", depth);
 
+                       if (opts.tech != nullptr && opts.tech->fixup(first_cell, taps, qbits))
+                               remove_cells.insert(first_cell);
+
                        for (int i = 1; i < depth; i++)
-                               module->remove(chain[cursor+i]);
+                               remove_cells.insert(chain[cursor+i]);
                        cursor += depth;
                }
        }
 
+       void cleanup()
+       {
+               for (auto cell : remove_cells)
+                       module->remove(cell);
+
+               for (auto wire : module->wires())
+               {
+                       if (wire->attributes.count("\\init") == 0)
+                               continue;
+
+                       SigSpec initsig = sigmap(wire);
+                       Const &initval = wire->attributes.at("\\init");
+
+                       for (int i = 0; i < GetSize(initsig) && i < GetSize(initval); i++)
+                               if (remove_init.count(initsig[i]))
+                                       initval[i] = State::Sx;
+
+                       if (SigSpec(initval).is_fully_undef())
+                               wire->attributes.erase("\\init");
+               }
+
+               remove_cells.clear();
+               sigbit_chain_next.clear();
+               sigbit_chain_prev.clear();
+               chain_start_cells.clear();
+       }
+
        ShregmapWorker(Module *module, const ShregmapOptions &opts) :
                        module(module), sigmap(module), opts(opts), dff_count(0), shreg_count(0)
        {
-               make_sigbit_chain_next_prev();
+               if (opts.tech)
+                       opts.tech->init(module, sigmap);
 
+               make_sigbit_chain_next_prev();
                find_chain_start_cells();
 
                for (auto c : chain_start_cells) {
                        vector<Cell*> chain = create_chain(c);
                        process_chain(chain);
                }
+
+               cleanup();
        }
 };
 
 struct ShregmapPass : public Pass {
        ShregmapPass() : Pass("shregmap", "map shift registers") { }
-       virtual void help()
+       void help() YS_OVERRIDE
        {
                //   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
                log("\n");
                log("    shregmap [options] [selection]\n");
                log("\n");
-               log("This pass converts chains of $_DFF_[NP]_ gates to target specific shift register.\n");
-               log("primitives. The generated shift register will be of type $__DFF_SHREG_[NP]_ and\n");
+               log("This pass converts chains of $_DFF_[NP]_ gates to target specific shift register\n");
+               log("primitives. The generated shift register will be of type $__SHREG_DFF_[NP]_ and\n");
                log("will use the same interface as the original $_DFF_*_ cells. The cell parameter\n");
                log("'DEPTH' will contain the depth of the shift register. Use a target-specific\n");
                log("'techmap' map file to convert those cells to the actual target cells.\n");
@@ -208,18 +695,63 @@ struct ShregmapPass : public Pass {
                log("    -clkpol pos|neg|any\n");
                log("        limit match to only positive or negative edge clocks. (default = any)\n");
                log("\n");
+               log("    -enpol pos|neg|none|any_or_none|any\n");
+               log("        limit match to FFs with the specified enable polarity. (default = none)\n");
+               log("\n");
+               log("    -match <cell_type>[:<d_port_name>:<q_port_name>]\n");
+               log("        match the specified cells instead of $_DFF_N_ and $_DFF_P_. If\n");
+               log("        ':<d_port_name>:<q_port_name>' is omitted then 'D' and 'Q' is used\n");
+               log("        by default. E.g. the option '-clkpol pos' is just an alias for\n");
+               log("        '-match $_DFF_P_', which is an alias for '-match $_DFF_P_:D:Q'.\n");
+               log("\n");
+               log("    -params\n");
+               log("        instead of encoding the clock and enable polarity in the cell name by\n");
+               log("        deriving from the original cell name, simply name all generated cells\n");
+               log("        $__SHREG_ and use CLKPOL and ENPOL parameters. An ENPOL value of 2 is\n");
+               log("        used to denote cells without enable input. The ENPOL parameter is\n");
+               log("        omitted when '-enpol none' (or no -enpol option) is passed.\n");
+               log("\n");
+               log("    -zinit\n");
+               log("        assume the shift register is automatically zero-initialized, so it\n");
+               log("        becomes legal to merge zero initialized FFs into the shift register.\n");
+               log("\n");
+               log("    -init\n");
+               log("        map initialized registers to the shift reg, add an INIT parameter to\n");
+               log("        generated cells with the initialization value. (first bit to shift out\n");
+               log("        in LSB position)\n");
+               log("\n");
+               log("    -tech greenpak4\n");
+               log("        map to greenpak4 shift registers.\n");
+               log("\n");
        }
-       virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
+       void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
        {
                ShregmapOptions opts;
+               string clkpol, enpol;
 
-               log_header("Executing SHREGMAP pass (map shift registers).\n");
+               log_header(design, "Executing SHREGMAP pass (map shift registers).\n");
 
                size_t argidx;
                for (argidx = 1; argidx < args.size(); argidx++)
                {
                        if (args[argidx] == "-clkpol" && argidx+1 < args.size()) {
-                               opts.clkpol = args[++argidx];
+                               clkpol = args[++argidx];
+                               continue;
+                       }
+                       if (args[argidx] == "-enpol" && argidx+1 < args.size()) {
+                               enpol = args[++argidx];
+                               continue;
+                       }
+                       if (args[argidx] == "-match" && argidx+1 < args.size()) {
+                               vector<string> match_args = split_tokens(args[++argidx], ":");
+                               if (GetSize(match_args) < 2)
+                                       match_args.push_back("D");
+                               if (GetSize(match_args) < 3)
+                                       match_args.push_back("Q");
+                               IdString id_cell_type(RTLIL::escape_id(match_args[0]));
+                               IdString id_d_port_name(RTLIL::escape_id(match_args[1]));
+                               IdString id_q_port_name(RTLIL::escape_id(match_args[2]));
+                               opts.ffcells[id_cell_type] = make_pair(id_d_port_name, id_q_port_name);
                                continue;
                        }
                        if (args[argidx] == "-minlen" && argidx+1 < args.size()) {
@@ -238,12 +770,94 @@ struct ShregmapPass : public Pass {
                                opts.keep_after = atoi(args[++argidx].c_str());
                                continue;
                        }
+                       if (args[argidx] == "-tech" && argidx+1 < args.size() && opts.tech == nullptr) {
+                               string tech = args[++argidx];
+                               if (tech == "greenpak4") {
+                                       clkpol = "pos";
+                                       opts.zinit = true;
+                                       opts.tech = new ShregmapTechGreenpak4;
+                               }
+                               else if (tech == "xilinx_static" || tech == "xilinx_dynamic") {
+                                       opts.init = true;
+                                       opts.ffcells["$_DFF_P_"] = make_pair(IdString("\\D"), IdString("\\Q"));
+                                       opts.ffcells["$_DFF_N_"] = make_pair(IdString("\\D"), IdString("\\Q"));
+                                       opts.ffcells["$_DFFE_PP_"] = make_pair(IdString("\\D"), IdString("\\Q"));
+                                       opts.ffcells["$_DFFE_PN_"] = make_pair(IdString("\\D"), IdString("\\Q"));
+                                       opts.ffcells["$_DFFE_NP_"] = make_pair(IdString("\\D"), IdString("\\Q"));
+                                       opts.ffcells["$_DFFE_NN_"] = make_pair(IdString("\\D"), IdString("\\Q"));
+                                       opts.ffcells["\\FDRE"] = make_pair(IdString("\\D"), IdString("\\Q"));
+                                       opts.ffcells["\\FDRE_1"] = make_pair(IdString("\\D"), IdString("\\Q"));
+                                       opts.ffcells["\\FDSE"] = make_pair(IdString("\\D"), IdString("\\Q"));
+                                       opts.ffcells["\\FDSE_1"] = make_pair(IdString("\\D"), IdString("\\Q"));
+                                       opts.ffcells["\\FDCE"] = make_pair(IdString("\\D"), IdString("\\Q"));
+                                       opts.ffcells["\\FDCE_1"] = make_pair(IdString("\\D"), IdString("\\Q"));
+                                       opts.ffcells["\\FDPE"] = make_pair(IdString("\\D"), IdString("\\Q"));
+                                       opts.ffcells["\\FDPE_1"] = make_pair(IdString("\\D"), IdString("\\Q"));
+                                       if (tech == "xilinx_static")
+                                               opts.tech = new ShregmapTechXilinx7Static(opts);
+                                       else if (tech == "xilinx_dynamic")
+                                               opts.tech = new ShregmapTechXilinx7Dynamic(opts);
+                               } else {
+                                       argidx--;
+                                       break;
+                               }
+                               continue;
+                       }
+                       if (args[argidx] == "-zinit") {
+                               opts.zinit = true;
+                               continue;
+                       }
+                       if (args[argidx] == "-init") {
+                               opts.init = true;
+                               continue;
+                       }
+                       if (args[argidx] == "-params") {
+                               opts.params = true;
+                               continue;
+                       }
                        break;
                }
                extra_args(args, argidx, design);
 
-               if (opts.clkpol != "pos" && opts.clkpol != "neg" && opts.clkpol != "any")
-                       log_cmd_error("Invalid value for -clkpol: %s\n", opts.clkpol.c_str());
+               if (opts.zinit && opts.init)
+                       log_cmd_error("Options -zinit and -init are exclusive!\n");
+
+               if (opts.ffcells.empty())
+               {
+                       bool clk_pos = clkpol == "" || clkpol == "pos" || clkpol == "any";
+                       bool clk_neg = clkpol == "" || clkpol == "neg" || clkpol == "any";
+
+                       bool en_none = enpol == "" || enpol == "none" || enpol == "any_or_none";
+                       bool en_pos = enpol == "pos" || enpol == "any" || enpol == "any_or_none";
+                       bool en_neg = enpol == "neg" || enpol == "any" || enpol == "any_or_none";
+
+                       if (clk_pos && en_none)
+                               opts.ffcells["$_DFF_P_"] = make_pair(IdString("\\D"), IdString("\\Q"));
+                       if (clk_neg && en_none)
+                               opts.ffcells["$_DFF_N_"] = make_pair(IdString("\\D"), IdString("\\Q"));
+
+                       if (clk_pos && en_pos)
+                               opts.ffcells["$_DFFE_PP_"] = make_pair(IdString("\\D"), IdString("\\Q"));
+                       if (clk_pos && en_neg)
+                               opts.ffcells["$_DFFE_PN_"] = make_pair(IdString("\\D"), IdString("\\Q"));
+
+                       if (clk_neg && en_pos)
+                               opts.ffcells["$_DFFE_NP_"] = make_pair(IdString("\\D"), IdString("\\Q"));
+                       if (clk_neg && en_neg)
+                               opts.ffcells["$_DFFE_NN_"] = make_pair(IdString("\\D"), IdString("\\Q"));
+
+                       if (en_pos || en_neg)
+                               opts.ffe = true;
+               }
+               else
+               {
+                       if (!clkpol.empty())
+                               log_cmd_error("Options -clkpol and -match are exclusive!\n");
+                       if (!enpol.empty())
+                               log_cmd_error("Options -enpol and -match are exclusive!\n");
+                       if (opts.params)
+                               log_cmd_error("Options -params and -match are exclusive!\n");
+               }
 
                int dff_count = 0;
                int shreg_count = 0;
@@ -255,6 +869,11 @@ struct ShregmapPass : public Pass {
                }
 
                log("Converted %d dff cells into %d shift registers.\n", dff_count, shreg_count);
+
+               if (opts.tech != nullptr) {
+                       delete opts.tech;
+                       opts.tech = nullptr;
+               }
        }
 } ShregmapPass;