Merge pull request #1340 from YosysHQ/eddie/abc_no_clean
[yosys.git] / passes / techmap / shregmap.cc
1 /*
2 * yosys -- Yosys Open SYnthesis Suite
3 *
4 * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
5 *
6 * Permission to use, copy, modify, and/or distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 *
18 */
19
20 #include "kernel/yosys.h"
21 #include "kernel/sigtools.h"
22
23 USING_YOSYS_NAMESPACE
24 PRIVATE_NAMESPACE_BEGIN
25
26 struct ShregmapTech
27 {
28 virtual ~ShregmapTech() { }
29 virtual bool analyze(vector<int> &taps) = 0;
30 virtual bool fixup(Cell *cell, dict<int, SigBit> &taps) = 0;
31 };
32
33 struct ShregmapOptions
34 {
35 int minlen, maxlen;
36 int keep_before, keep_after;
37 bool zinit, init, params, ffe;
38 dict<IdString, pair<IdString, IdString>> ffcells;
39 ShregmapTech *tech;
40
41 ShregmapOptions()
42 {
43 minlen = 2;
44 maxlen = 0;
45 keep_before = 0;
46 keep_after = 0;
47 zinit = false;
48 init = false;
49 params = false;
50 ffe = false;
51 tech = nullptr;
52 }
53 };
54
55 struct ShregmapTechGreenpak4 : ShregmapTech
56 {
57 bool analyze(vector<int> &taps)
58 {
59 if (GetSize(taps) > 2 && taps[0] == 0 && taps[2] < 17) {
60 taps.clear();
61 return true;
62 }
63
64 if (GetSize(taps) > 2)
65 return false;
66
67 if (taps.back() > 16) return false;
68
69 return true;
70 }
71
72 bool fixup(Cell *cell, dict<int, SigBit> &taps)
73 {
74 auto D = cell->getPort(ID(D));
75 auto C = cell->getPort(ID(C));
76
77 auto newcell = cell->module->addCell(NEW_ID, ID(GP_SHREG));
78 newcell->setPort(ID(nRST), State::S1);
79 newcell->setPort(ID(CLK), C);
80 newcell->setPort(ID(IN), D);
81
82 int i = 0;
83 for (auto tap : taps) {
84 newcell->setPort(i ? ID(OUTB) : ID(OUTA), tap.second);
85 newcell->setParam(i ? ID(OUTB_TAP) : ID(OUTA_TAP), tap.first + 1);
86 i++;
87 }
88
89 cell->setParam(ID(OUTA_INVERT), 0);
90 return false;
91 }
92 };
93
94 struct ShregmapWorker
95 {
96 Module *module;
97 SigMap sigmap;
98
99 const ShregmapOptions &opts;
100 int dff_count, shreg_count;
101
102 pool<Cell*> remove_cells;
103 pool<SigBit> remove_init;
104
105 dict<SigBit, bool> sigbit_init;
106 dict<SigBit, Cell*> sigbit_chain_next;
107 dict<SigBit, Cell*> sigbit_chain_prev;
108 pool<SigBit> sigbit_with_non_chain_users;
109 pool<Cell*> chain_start_cells;
110
111 void make_sigbit_chain_next_prev()
112 {
113 for (auto wire : module->wires())
114 {
115 if (wire->port_output || wire->get_bool_attribute(ID::keep)) {
116 for (auto bit : sigmap(wire))
117 sigbit_with_non_chain_users.insert(bit);
118 }
119
120 if (wire->attributes.count(ID(init))) {
121 SigSpec initsig = sigmap(wire);
122 Const initval = wire->attributes.at(ID(init));
123 for (int i = 0; i < GetSize(initsig) && i < GetSize(initval); i++)
124 if (initval[i] == State::S0 && !opts.zinit)
125 sigbit_init[initsig[i]] = false;
126 else if (initval[i] == State::S1)
127 sigbit_init[initsig[i]] = true;
128 }
129 }
130
131 for (auto cell : module->cells())
132 {
133 if (opts.ffcells.count(cell->type) && !cell->get_bool_attribute(ID::keep))
134 {
135 IdString d_port = opts.ffcells.at(cell->type).first;
136 IdString q_port = opts.ffcells.at(cell->type).second;
137
138 SigBit d_bit = sigmap(cell->getPort(d_port).as_bit());
139 SigBit q_bit = sigmap(cell->getPort(q_port).as_bit());
140
141 if (opts.init || sigbit_init.count(q_bit) == 0)
142 {
143 auto r = sigbit_chain_next.insert(std::make_pair(d_bit, cell));
144 if (!r.second) {
145 // Insertion not successful means that d_bit is already
146 // connected to another register, thus mark it as a
147 // non chain user ...
148 sigbit_with_non_chain_users.insert(d_bit);
149 // ... and clone d_bit into another wire, and use that
150 // wire as a different key in the d_bit-to-cell dictionary
151 // so that it can be identified as another chain
152 // (omitting this common flop)
153 // Link: https://github.com/YosysHQ/yosys/pull/1085
154 Wire *wire = module->addWire(NEW_ID);
155 module->connect(wire, d_bit);
156 sigmap.add(wire, d_bit);
157 sigbit_chain_next.insert(std::make_pair(wire, cell));
158 }
159
160 sigbit_chain_prev[q_bit] = cell;
161 continue;
162 }
163 }
164
165 for (auto conn : cell->connections())
166 if (cell->input(conn.first))
167 for (auto bit : sigmap(conn.second))
168 sigbit_with_non_chain_users.insert(bit);
169 }
170 }
171
172 void find_chain_start_cells()
173 {
174 for (auto it : sigbit_chain_next)
175 {
176 if (opts.tech == nullptr && sigbit_with_non_chain_users.count(it.first))
177 goto start_cell;
178
179 if (sigbit_chain_prev.count(it.first) != 0)
180 {
181 Cell *c1 = sigbit_chain_prev.at(it.first);
182 Cell *c2 = it.second;
183
184 if (c1->type != c2->type)
185 goto start_cell;
186
187 if (c1->parameters != c2->parameters)
188 goto start_cell;
189
190 IdString d_port = opts.ffcells.at(c1->type).first;
191 IdString q_port = opts.ffcells.at(c1->type).second;
192
193 auto c1_conn = c1->connections();
194 auto c2_conn = c2->connections();
195
196 c1_conn.erase(d_port);
197 c1_conn.erase(q_port);
198
199 c2_conn.erase(d_port);
200 c2_conn.erase(q_port);
201
202 if (c1_conn != c2_conn)
203 goto start_cell;
204
205 continue;
206 }
207
208 start_cell:
209 chain_start_cells.insert(it.second);
210 }
211 }
212
213 vector<Cell*> create_chain(Cell *start_cell)
214 {
215 vector<Cell*> chain;
216
217 Cell *c = start_cell;
218 while (c != nullptr)
219 {
220 chain.push_back(c);
221
222 IdString q_port = opts.ffcells.at(c->type).second;
223 SigBit q_bit = sigmap(c->getPort(q_port).as_bit());
224
225 if (sigbit_chain_next.count(q_bit) == 0)
226 break;
227
228 c = sigbit_chain_next.at(q_bit);
229 if (chain_start_cells.count(c) != 0)
230 break;
231 }
232
233 return chain;
234 }
235
236 void process_chain(vector<Cell*> &chain)
237 {
238 if (GetSize(chain) < opts.keep_before + opts.minlen + opts.keep_after)
239 return;
240
241 int cursor = opts.keep_before;
242 while (cursor < GetSize(chain) - opts.keep_after)
243 {
244 int depth = GetSize(chain) - opts.keep_after - cursor;
245
246 if (opts.maxlen > 0)
247 depth = std::min(opts.maxlen, depth);
248
249 Cell *first_cell = chain[cursor];
250 IdString q_port = opts.ffcells.at(first_cell->type).second;
251 dict<int, SigBit> taps_dict;
252
253 if (opts.tech)
254 {
255 vector<SigBit> qbits;
256 vector<int> taps;
257
258 for (int i = 0; i < depth; i++)
259 {
260 Cell *cell = chain[cursor+i];
261 auto qbit = sigmap(cell->getPort(q_port));
262 qbits.push_back(qbit);
263
264 if (sigbit_with_non_chain_users.count(qbit))
265 taps.push_back(i);
266 }
267
268 while (depth > 0)
269 {
270 if (taps.empty() || taps.back() < depth-1)
271 taps.push_back(depth-1);
272
273 if (opts.tech->analyze(taps))
274 break;
275
276 taps.pop_back();
277 depth--;
278 }
279
280 depth = 0;
281 for (auto tap : taps) {
282 taps_dict[tap] = qbits.at(tap);
283 log_assert(depth < tap+1);
284 depth = tap+1;
285 }
286 }
287
288 if (depth < 2) {
289 cursor++;
290 continue;
291 }
292
293 Cell *last_cell = chain[cursor+depth-1];
294
295 log("Converting %s.%s ... %s.%s to a shift register with depth %d.\n",
296 log_id(module), log_id(first_cell), log_id(module), log_id(last_cell), depth);
297
298 dff_count += depth;
299 shreg_count += 1;
300
301 string shreg_cell_type_str = "$__SHREG";
302 if (opts.params) {
303 shreg_cell_type_str += "_";
304 } else {
305 if (first_cell->type[1] != '_')
306 shreg_cell_type_str += "_";
307 shreg_cell_type_str += first_cell->type.substr(1);
308 }
309
310 if (opts.init) {
311 vector<State> initval;
312 for (int i = depth-1; i >= 0; i--) {
313 SigBit bit = sigmap(chain[cursor+i]->getPort(q_port).as_bit());
314 if (sigbit_init.count(bit) == 0)
315 initval.push_back(State::Sx);
316 else if (sigbit_init.at(bit))
317 initval.push_back(State::S1);
318 else
319 initval.push_back(State::S0);
320 remove_init.insert(bit);
321 }
322 first_cell->setParam(ID(INIT), initval);
323 }
324
325 if (opts.zinit)
326 for (int i = depth-1; i >= 0; i--) {
327 SigBit bit = sigmap(chain[cursor+i]->getPort(q_port).as_bit());
328 remove_init.insert(bit);
329 }
330
331 if (opts.params)
332 {
333 int param_clkpol = -1;
334 int param_enpol = 2;
335
336 if (first_cell->type == ID($_DFF_N_)) param_clkpol = 0;
337 if (first_cell->type == ID($_DFF_P_)) param_clkpol = 1;
338
339 if (first_cell->type == ID($_DFFE_NN_)) param_clkpol = 0, param_enpol = 0;
340 if (first_cell->type == ID($_DFFE_NP_)) param_clkpol = 0, param_enpol = 1;
341 if (first_cell->type == ID($_DFFE_PN_)) param_clkpol = 1, param_enpol = 0;
342 if (first_cell->type == ID($_DFFE_PP_)) param_clkpol = 1, param_enpol = 1;
343
344 log_assert(param_clkpol >= 0);
345 first_cell->setParam(ID(CLKPOL), param_clkpol);
346 if (opts.ffe) first_cell->setParam(ID(ENPOL), param_enpol);
347 }
348
349 first_cell->type = shreg_cell_type_str;
350 first_cell->setPort(q_port, last_cell->getPort(q_port));
351 first_cell->setParam(ID(DEPTH), depth);
352
353 if (opts.tech != nullptr && !opts.tech->fixup(first_cell, taps_dict))
354 remove_cells.insert(first_cell);
355
356 for (int i = 1; i < depth; i++)
357 remove_cells.insert(chain[cursor+i]);
358 cursor += depth;
359 }
360 }
361
362 void cleanup()
363 {
364 for (auto cell : remove_cells)
365 module->remove(cell);
366
367 for (auto wire : module->wires())
368 {
369 if (wire->attributes.count(ID(init)) == 0)
370 continue;
371
372 SigSpec initsig = sigmap(wire);
373 Const &initval = wire->attributes.at(ID(init));
374
375 for (int i = 0; i < GetSize(initsig) && i < GetSize(initval); i++)
376 if (remove_init.count(initsig[i]))
377 initval[i] = State::Sx;
378
379 if (SigSpec(initval).is_fully_undef())
380 wire->attributes.erase(ID(init));
381 }
382
383 remove_cells.clear();
384 sigbit_chain_next.clear();
385 sigbit_chain_prev.clear();
386 chain_start_cells.clear();
387 }
388
389 ShregmapWorker(Module *module, const ShregmapOptions &opts) :
390 module(module), sigmap(module), opts(opts), dff_count(0), shreg_count(0)
391 {
392 make_sigbit_chain_next_prev();
393 find_chain_start_cells();
394
395 for (auto c : chain_start_cells) {
396 vector<Cell*> chain = create_chain(c);
397 process_chain(chain);
398 }
399
400 cleanup();
401 }
402 };
403
404 struct ShregmapPass : public Pass {
405 ShregmapPass() : Pass("shregmap", "map shift registers") { }
406 void help() YS_OVERRIDE
407 {
408 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
409 log("\n");
410 log(" shregmap [options] [selection]\n");
411 log("\n");
412 log("This pass converts chains of $_DFF_[NP]_ gates to target specific shift register\n");
413 log("primitives. The generated shift register will be of type $__SHREG_DFF_[NP]_ and\n");
414 log("will use the same interface as the original $_DFF_*_ cells. The cell parameter\n");
415 log("'DEPTH' will contain the depth of the shift register. Use a target-specific\n");
416 log("'techmap' map file to convert those cells to the actual target cells.\n");
417 log("\n");
418 log(" -minlen N\n");
419 log(" minimum length of shift register (default = 2)\n");
420 log(" (this is the length after -keep_before and -keep_after)\n");
421 log("\n");
422 log(" -maxlen N\n");
423 log(" maximum length of shift register (default = no limit)\n");
424 log(" larger chains will be mapped to multiple shift register instances\n");
425 log("\n");
426 log(" -keep_before N\n");
427 log(" number of DFFs to keep before the shift register (default = 0)\n");
428 log("\n");
429 log(" -keep_after N\n");
430 log(" number of DFFs to keep after the shift register (default = 0)\n");
431 log("\n");
432 log(" -clkpol pos|neg|any\n");
433 log(" limit match to only positive or negative edge clocks. (default = any)\n");
434 log("\n");
435 log(" -enpol pos|neg|none|any_or_none|any\n");
436 log(" limit match to FFs with the specified enable polarity. (default = none)\n");
437 log("\n");
438 log(" -match <cell_type>[:<d_port_name>:<q_port_name>]\n");
439 log(" match the specified cells instead of $_DFF_N_ and $_DFF_P_. If\n");
440 log(" ':<d_port_name>:<q_port_name>' is omitted then 'D' and 'Q' is used\n");
441 log(" by default. E.g. the option '-clkpol pos' is just an alias for\n");
442 log(" '-match $_DFF_P_', which is an alias for '-match $_DFF_P_:D:Q'.\n");
443 log("\n");
444 log(" -params\n");
445 log(" instead of encoding the clock and enable polarity in the cell name by\n");
446 log(" deriving from the original cell name, simply name all generated cells\n");
447 log(" $__SHREG_ and use CLKPOL and ENPOL parameters. An ENPOL value of 2 is\n");
448 log(" used to denote cells without enable input. The ENPOL parameter is\n");
449 log(" omitted when '-enpol none' (or no -enpol option) is passed.\n");
450 log("\n");
451 log(" -zinit\n");
452 log(" assume the shift register is automatically zero-initialized, so it\n");
453 log(" becomes legal to merge zero initialized FFs into the shift register.\n");
454 log("\n");
455 log(" -init\n");
456 log(" map initialized registers to the shift reg, add an INIT parameter to\n");
457 log(" generated cells with the initialization value. (first bit to shift out\n");
458 log(" in LSB position)\n");
459 log("\n");
460 log(" -tech greenpak4\n");
461 log(" map to greenpak4 shift registers.\n");
462 log("\n");
463 }
464 void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
465 {
466 ShregmapOptions opts;
467 string clkpol, enpol;
468
469 log_header(design, "Executing SHREGMAP pass (map shift registers).\n");
470
471 size_t argidx;
472 for (argidx = 1; argidx < args.size(); argidx++)
473 {
474 if (args[argidx] == "-clkpol" && argidx+1 < args.size()) {
475 clkpol = args[++argidx];
476 continue;
477 }
478 if (args[argidx] == "-enpol" && argidx+1 < args.size()) {
479 enpol = args[++argidx];
480 continue;
481 }
482 if (args[argidx] == "-match" && argidx+1 < args.size()) {
483 vector<string> match_args = split_tokens(args[++argidx], ":");
484 if (GetSize(match_args) < 2)
485 match_args.push_back("D");
486 if (GetSize(match_args) < 3)
487 match_args.push_back("Q");
488 IdString id_cell_type(RTLIL::escape_id(match_args[0]));
489 IdString id_d_port_name(RTLIL::escape_id(match_args[1]));
490 IdString id_q_port_name(RTLIL::escape_id(match_args[2]));
491 opts.ffcells[id_cell_type] = make_pair(id_d_port_name, id_q_port_name);
492 continue;
493 }
494 if (args[argidx] == "-minlen" && argidx+1 < args.size()) {
495 opts.minlen = atoi(args[++argidx].c_str());
496 continue;
497 }
498 if (args[argidx] == "-maxlen" && argidx+1 < args.size()) {
499 opts.maxlen = atoi(args[++argidx].c_str());
500 continue;
501 }
502 if (args[argidx] == "-keep_before" && argidx+1 < args.size()) {
503 opts.keep_before = atoi(args[++argidx].c_str());
504 continue;
505 }
506 if (args[argidx] == "-keep_after" && argidx+1 < args.size()) {
507 opts.keep_after = atoi(args[++argidx].c_str());
508 continue;
509 }
510 if (args[argidx] == "-tech" && argidx+1 < args.size() && opts.tech == nullptr) {
511 string tech = args[++argidx];
512 if (tech == "greenpak4") {
513 clkpol = "pos";
514 opts.zinit = true;
515 opts.tech = new ShregmapTechGreenpak4;
516 } else {
517 argidx--;
518 break;
519 }
520 continue;
521 }
522 if (args[argidx] == "-zinit") {
523 opts.zinit = true;
524 continue;
525 }
526 if (args[argidx] == "-init") {
527 opts.init = true;
528 continue;
529 }
530 if (args[argidx] == "-params") {
531 opts.params = true;
532 continue;
533 }
534 break;
535 }
536 extra_args(args, argidx, design);
537
538 if (opts.zinit && opts.init)
539 log_cmd_error("Options -zinit and -init are exclusive!\n");
540
541 if (opts.ffcells.empty())
542 {
543 bool clk_pos = clkpol == "" || clkpol == "pos" || clkpol == "any";
544 bool clk_neg = clkpol == "" || clkpol == "neg" || clkpol == "any";
545
546 bool en_none = enpol == "" || enpol == "none" || enpol == "any_or_none";
547 bool en_pos = enpol == "pos" || enpol == "any" || enpol == "any_or_none";
548 bool en_neg = enpol == "neg" || enpol == "any" || enpol == "any_or_none";
549
550 if (clk_pos && en_none)
551 opts.ffcells[ID($_DFF_P_)] = make_pair(IdString(ID(D)), IdString(ID(Q)));
552 if (clk_neg && en_none)
553 opts.ffcells[ID($_DFF_N_)] = make_pair(IdString(ID(D)), IdString(ID(Q)));
554
555 if (clk_pos && en_pos)
556 opts.ffcells[ID($_DFFE_PP_)] = make_pair(IdString(ID(D)), IdString(ID(Q)));
557 if (clk_pos && en_neg)
558 opts.ffcells[ID($_DFFE_PN_)] = make_pair(IdString(ID(D)), IdString(ID(Q)));
559
560 if (clk_neg && en_pos)
561 opts.ffcells[ID($_DFFE_NP_)] = make_pair(IdString(ID(D)), IdString(ID(Q)));
562 if (clk_neg && en_neg)
563 opts.ffcells[ID($_DFFE_NN_)] = make_pair(IdString(ID(D)), IdString(ID(Q)));
564
565 if (en_pos || en_neg)
566 opts.ffe = true;
567 }
568 else
569 {
570 if (!clkpol.empty())
571 log_cmd_error("Options -clkpol and -match are exclusive!\n");
572 if (!enpol.empty())
573 log_cmd_error("Options -enpol and -match are exclusive!\n");
574 if (opts.params)
575 log_cmd_error("Options -params and -match are exclusive!\n");
576 }
577
578 int dff_count = 0;
579 int shreg_count = 0;
580
581 for (auto module : design->selected_modules()) {
582 ShregmapWorker worker(module, opts);
583 dff_count += worker.dff_count;
584 shreg_count += worker.shreg_count;
585 }
586
587 log("Converted %d dff cells into %d shift registers.\n", dff_count, shreg_count);
588
589 if (opts.tech != nullptr) {
590 delete opts.tech;
591 opts.tech = nullptr;
592 }
593 }
594 } ShregmapPass;
595
596 PRIVATE_NAMESPACE_END