abc: Use dict/pool instead of std::map/std::set
[yosys.git] / passes / techmap / abc.cc
1 /*
2 * yosys -- Yosys Open SYnthesis Suite
3 *
4 * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
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 // [[CITE]] ABC
21 // Berkeley Logic Synthesis and Verification Group, ABC: A System for Sequential Synthesis and Verification
22 // http://www.eecs.berkeley.edu/~alanmi/abc/
23
24 // [[CITE]] Berkeley Logic Interchange Format (BLIF)
25 // University of California. Berkeley. July 28, 1992
26 // http://www.ece.cmu.edu/~ee760/760docs/blif.pdf
27
28 // [[CITE]] Kahn's Topological sorting algorithm
29 // Kahn, Arthur B. (1962), "Topological sorting of large networks", Communications of the ACM 5 (11): 558-562, doi:10.1145/368996.369025
30 // http://en.wikipedia.org/wiki/Topological_sorting
31
32 #define ABC_COMMAND_LIB "strash; ifraig; scorr; dc2; dretime; strash; &get -n; &dch -f; &nf {D}; &put"
33 #define ABC_COMMAND_CTR "strash; ifraig; scorr; dc2; dretime; strash; &get -n; &dch -f; &nf {D}; &put; buffer; upsize {D}; dnsize {D}; stime -p"
34 #define ABC_COMMAND_LUT "strash; ifraig; scorr; dc2; dretime; strash; dch -f; if; mfs2"
35 #define ABC_COMMAND_SOP "strash; ifraig; scorr; dc2; dretime; strash; dch -f; cover {I} {P}"
36 #define ABC_COMMAND_DFL "strash; ifraig; scorr; dc2; dretime; strash; &get -n; &dch -f; &nf {D}; &put"
37
38 #define ABC_FAST_COMMAND_LIB "strash; dretime; map {D}"
39 #define ABC_FAST_COMMAND_CTR "strash; dretime; map {D}; buffer; upsize {D}; dnsize {D}; stime -p"
40 #define ABC_FAST_COMMAND_LUT "strash; dretime; if"
41 #define ABC_FAST_COMMAND_SOP "strash; dretime; cover {I} {P}"
42 #define ABC_FAST_COMMAND_DFL "strash; dretime; map"
43
44 #include "kernel/register.h"
45 #include "kernel/sigtools.h"
46 #include "kernel/celltypes.h"
47 #include "kernel/ffinit.h"
48 #include "kernel/ff.h"
49 #include "kernel/cost.h"
50 #include "kernel/log.h"
51 #include <stdlib.h>
52 #include <stdio.h>
53 #include <string.h>
54 #include <cctype>
55 #include <cerrno>
56 #include <sstream>
57 #include <climits>
58 #include <vector>
59
60 #ifndef _WIN32
61 # include <unistd.h>
62 # include <dirent.h>
63 #endif
64
65 #include "frontends/blif/blifparse.h"
66
67 #ifdef YOSYS_LINK_ABC
68 extern "C" int Abc_RealMain(int argc, char *argv[]);
69 #endif
70
71 USING_YOSYS_NAMESPACE
72 PRIVATE_NAMESPACE_BEGIN
73
74 enum class gate_type_t {
75 G_NONE,
76 G_FF,
77 G_FF0,
78 G_FF1,
79 G_BUF,
80 G_NOT,
81 G_AND,
82 G_NAND,
83 G_OR,
84 G_NOR,
85 G_XOR,
86 G_XNOR,
87 G_ANDNOT,
88 G_ORNOT,
89 G_MUX,
90 G_NMUX,
91 G_AOI3,
92 G_OAI3,
93 G_AOI4,
94 G_OAI4
95 };
96
97 #define G(_name) gate_type_t::G_ ## _name
98
99 struct gate_t
100 {
101 int id;
102 gate_type_t type;
103 int in1, in2, in3, in4;
104 bool is_port;
105 RTLIL::SigBit bit;
106 RTLIL::State init;
107 };
108
109 bool map_mux4;
110 bool map_mux8;
111 bool map_mux16;
112
113 bool markgroups;
114 int map_autoidx;
115 SigMap assign_map;
116 RTLIL::Module *module;
117 std::vector<gate_t> signal_list;
118 dict<RTLIL::SigBit, int> signal_map;
119 FfInitVals initvals;
120 pool<std::string> enabled_gates;
121 bool cmos_cost;
122 bool had_init;
123
124 bool clk_polarity, en_polarity, arst_polarity, srst_polarity;
125 RTLIL::SigSpec clk_sig, en_sig, arst_sig, srst_sig;
126 dict<int, std::string> pi_map, po_map;
127
128 int map_signal(RTLIL::SigBit bit, gate_type_t gate_type = G(NONE), int in1 = -1, int in2 = -1, int in3 = -1, int in4 = -1)
129 {
130 assign_map.apply(bit);
131
132 if (signal_map.count(bit) == 0) {
133 gate_t gate;
134 gate.id = signal_list.size();
135 gate.type = G(NONE);
136 gate.in1 = -1;
137 gate.in2 = -1;
138 gate.in3 = -1;
139 gate.in4 = -1;
140 gate.is_port = false;
141 gate.bit = bit;
142 gate.init = initvals(bit);
143 signal_list.push_back(gate);
144 signal_map[bit] = gate.id;
145 }
146
147 gate_t &gate = signal_list[signal_map[bit]];
148
149 if (gate_type != G(NONE))
150 gate.type = gate_type;
151 if (in1 >= 0)
152 gate.in1 = in1;
153 if (in2 >= 0)
154 gate.in2 = in2;
155 if (in3 >= 0)
156 gate.in3 = in3;
157 if (in4 >= 0)
158 gate.in4 = in4;
159
160 return gate.id;
161 }
162
163 void mark_port(RTLIL::SigSpec sig)
164 {
165 for (auto &bit : assign_map(sig))
166 if (bit.wire != nullptr && signal_map.count(bit) > 0)
167 signal_list[signal_map[bit]].is_port = true;
168 }
169
170 void extract_cell(RTLIL::Cell *cell, bool keepff)
171 {
172 if (RTLIL::builtin_ff_cell_types().count(cell->type)) {
173 FfData ff(&initvals, cell);
174 gate_type_t type = G(FF);
175 if (!ff.has_clk)
176 return;
177 if (ff.has_gclk)
178 return;
179 if (ff.has_aload)
180 return;
181 if (ff.has_sr)
182 return;
183 if (!ff.is_fine)
184 return;
185 if (clk_polarity != ff.pol_clk)
186 return;
187 if (clk_sig != assign_map(ff.sig_clk))
188 return;
189 if (ff.has_ce) {
190 if (en_polarity != ff.pol_ce)
191 return;
192 if (en_sig != assign_map(ff.sig_ce))
193 return;
194 } else {
195 if (GetSize(en_sig) != 0)
196 return;
197 }
198 if (ff.val_init == State::S1) {
199 type = G(FF1);
200 had_init = true;
201 } else if (ff.val_init == State::S0) {
202 type = G(FF0);
203 had_init = true;
204 }
205 if (ff.has_arst) {
206 if (arst_polarity != ff.pol_arst)
207 return;
208 if (arst_sig != assign_map(ff.sig_arst))
209 return;
210 if (ff.val_arst == State::S1) {
211 if (type == G(FF0))
212 return;
213 type = G(FF1);
214 } else if (ff.val_arst == State::S0) {
215 if (type == G(FF1))
216 return;
217 type = G(FF0);
218 }
219 } else {
220 if (GetSize(arst_sig) != 0)
221 return;
222 }
223 if (ff.has_srst) {
224 if (srst_polarity != ff.pol_srst)
225 return;
226 if (srst_sig != assign_map(ff.sig_srst))
227 return;
228 if (ff.val_srst == State::S1) {
229 if (type == G(FF0))
230 return;
231 type = G(FF1);
232 } else if (ff.val_srst == State::S0) {
233 if (type == G(FF1))
234 return;
235 type = G(FF0);
236 }
237 } else {
238 if (GetSize(srst_sig) != 0)
239 return;
240 }
241
242 if (keepff)
243 for (auto &c : ff.sig_q.chunks())
244 if (c.wire != nullptr)
245 c.wire->attributes[ID::keep] = 1;
246
247 map_signal(ff.sig_q, type, map_signal(ff.sig_d));
248
249 ff.remove();
250 return;
251 }
252
253 if (cell->type.in(ID($_BUF_), ID($_NOT_)))
254 {
255 RTLIL::SigSpec sig_a = cell->getPort(ID::A);
256 RTLIL::SigSpec sig_y = cell->getPort(ID::Y);
257
258 assign_map.apply(sig_a);
259 assign_map.apply(sig_y);
260
261 map_signal(sig_y, cell->type == ID($_BUF_) ? G(BUF) : G(NOT), map_signal(sig_a));
262
263 module->remove(cell);
264 return;
265 }
266
267 if (cell->type.in(ID($_AND_), ID($_NAND_), ID($_OR_), ID($_NOR_), ID($_XOR_), ID($_XNOR_), ID($_ANDNOT_), ID($_ORNOT_)))
268 {
269 RTLIL::SigSpec sig_a = cell->getPort(ID::A);
270 RTLIL::SigSpec sig_b = cell->getPort(ID::B);
271 RTLIL::SigSpec sig_y = cell->getPort(ID::Y);
272
273 assign_map.apply(sig_a);
274 assign_map.apply(sig_b);
275 assign_map.apply(sig_y);
276
277 int mapped_a = map_signal(sig_a);
278 int mapped_b = map_signal(sig_b);
279
280 if (cell->type == ID($_AND_))
281 map_signal(sig_y, G(AND), mapped_a, mapped_b);
282 else if (cell->type == ID($_NAND_))
283 map_signal(sig_y, G(NAND), mapped_a, mapped_b);
284 else if (cell->type == ID($_OR_))
285 map_signal(sig_y, G(OR), mapped_a, mapped_b);
286 else if (cell->type == ID($_NOR_))
287 map_signal(sig_y, G(NOR), mapped_a, mapped_b);
288 else if (cell->type == ID($_XOR_))
289 map_signal(sig_y, G(XOR), mapped_a, mapped_b);
290 else if (cell->type == ID($_XNOR_))
291 map_signal(sig_y, G(XNOR), mapped_a, mapped_b);
292 else if (cell->type == ID($_ANDNOT_))
293 map_signal(sig_y, G(ANDNOT), mapped_a, mapped_b);
294 else if (cell->type == ID($_ORNOT_))
295 map_signal(sig_y, G(ORNOT), mapped_a, mapped_b);
296 else
297 log_abort();
298
299 module->remove(cell);
300 return;
301 }
302
303 if (cell->type.in(ID($_MUX_), ID($_NMUX_)))
304 {
305 RTLIL::SigSpec sig_a = cell->getPort(ID::A);
306 RTLIL::SigSpec sig_b = cell->getPort(ID::B);
307 RTLIL::SigSpec sig_s = cell->getPort(ID::S);
308 RTLIL::SigSpec sig_y = cell->getPort(ID::Y);
309
310 assign_map.apply(sig_a);
311 assign_map.apply(sig_b);
312 assign_map.apply(sig_s);
313 assign_map.apply(sig_y);
314
315 int mapped_a = map_signal(sig_a);
316 int mapped_b = map_signal(sig_b);
317 int mapped_s = map_signal(sig_s);
318
319 map_signal(sig_y, cell->type == ID($_MUX_) ? G(MUX) : G(NMUX), mapped_a, mapped_b, mapped_s);
320
321 module->remove(cell);
322 return;
323 }
324
325 if (cell->type.in(ID($_AOI3_), ID($_OAI3_)))
326 {
327 RTLIL::SigSpec sig_a = cell->getPort(ID::A);
328 RTLIL::SigSpec sig_b = cell->getPort(ID::B);
329 RTLIL::SigSpec sig_c = cell->getPort(ID::C);
330 RTLIL::SigSpec sig_y = cell->getPort(ID::Y);
331
332 assign_map.apply(sig_a);
333 assign_map.apply(sig_b);
334 assign_map.apply(sig_c);
335 assign_map.apply(sig_y);
336
337 int mapped_a = map_signal(sig_a);
338 int mapped_b = map_signal(sig_b);
339 int mapped_c = map_signal(sig_c);
340
341 map_signal(sig_y, cell->type == ID($_AOI3_) ? G(AOI3) : G(OAI3), mapped_a, mapped_b, mapped_c);
342
343 module->remove(cell);
344 return;
345 }
346
347 if (cell->type.in(ID($_AOI4_), ID($_OAI4_)))
348 {
349 RTLIL::SigSpec sig_a = cell->getPort(ID::A);
350 RTLIL::SigSpec sig_b = cell->getPort(ID::B);
351 RTLIL::SigSpec sig_c = cell->getPort(ID::C);
352 RTLIL::SigSpec sig_d = cell->getPort(ID::D);
353 RTLIL::SigSpec sig_y = cell->getPort(ID::Y);
354
355 assign_map.apply(sig_a);
356 assign_map.apply(sig_b);
357 assign_map.apply(sig_c);
358 assign_map.apply(sig_d);
359 assign_map.apply(sig_y);
360
361 int mapped_a = map_signal(sig_a);
362 int mapped_b = map_signal(sig_b);
363 int mapped_c = map_signal(sig_c);
364 int mapped_d = map_signal(sig_d);
365
366 map_signal(sig_y, cell->type == ID($_AOI4_) ? G(AOI4) : G(OAI4), mapped_a, mapped_b, mapped_c, mapped_d);
367
368 module->remove(cell);
369 return;
370 }
371 }
372
373 std::string remap_name(RTLIL::IdString abc_name, RTLIL::Wire **orig_wire = nullptr)
374 {
375 std::string abc_sname = abc_name.substr(1);
376 bool isnew = false;
377 if (abc_sname.compare(0, 4, "new_") == 0)
378 {
379 abc_sname.erase(0, 4);
380 isnew = true;
381 }
382 if (abc_sname.compare(0, 5, "ys__n") == 0)
383 {
384 abc_sname.erase(0, 5);
385 if (std::isdigit(abc_sname.at(0)))
386 {
387 int sid = std::atoi(abc_sname.c_str());
388 size_t postfix_start = abc_sname.find_first_not_of("0123456789");
389 std::string postfix = postfix_start != std::string::npos ? abc_sname.substr(postfix_start) : "";
390
391 if (sid < GetSize(signal_list))
392 {
393 auto sig = signal_list.at(sid);
394 if (sig.bit.wire != nullptr)
395 {
396 std::string s = stringf("$abc$%d$%s", map_autoidx, sig.bit.wire->name.c_str()+1);
397 if (sig.bit.wire->width != 1)
398 s += stringf("[%d]", sig.bit.offset);
399 if (isnew)
400 s += "_new";
401 s += postfix;
402 if (orig_wire != nullptr)
403 *orig_wire = sig.bit.wire;
404 return s;
405 }
406 }
407 }
408 }
409 return stringf("$abc$%d$%s", map_autoidx, abc_name.c_str()+1);
410 }
411
412 void dump_loop_graph(FILE *f, int &nr, dict<int, pool<int>> &edges, pool<int> &workpool, std::vector<int> &in_counts)
413 {
414 if (f == nullptr)
415 return;
416
417 log("Dumping loop state graph to slide %d.\n", ++nr);
418
419 fprintf(f, "digraph \"slide%d\" {\n", nr);
420 fprintf(f, " label=\"slide%d\";\n", nr);
421 fprintf(f, " rankdir=\"TD\";\n");
422
423 pool<int> nodes;
424 for (auto &e : edges) {
425 nodes.insert(e.first);
426 for (auto n : e.second)
427 nodes.insert(n);
428 }
429
430 for (auto n : nodes)
431 fprintf(f, " ys__n%d [label=\"%s\\nid=%d, count=%d\"%s];\n", n, log_signal(signal_list[n].bit),
432 n, in_counts[n], workpool.count(n) ? ", shape=box" : "");
433
434 for (auto &e : edges)
435 for (auto n : e.second)
436 fprintf(f, " ys__n%d -> ys__n%d;\n", e.first, n);
437
438 fprintf(f, "}\n");
439 }
440
441 void handle_loops()
442 {
443 // http://en.wikipedia.org/wiki/Topological_sorting
444 // (Kahn, Arthur B. (1962), "Topological sorting of large networks")
445
446 dict<int, pool<int>> edges;
447 std::vector<int> in_edges_count(signal_list.size());
448 pool<int> workpool;
449
450 FILE *dot_f = nullptr;
451 int dot_nr = 0;
452
453 // uncomment for troubleshooting the loop detection code
454 // dot_f = fopen("test.dot", "w");
455
456 for (auto &g : signal_list) {
457 if (g.type == G(NONE) || g.type == G(FF) || g.type == G(FF0) || g.type == G(FF1)) {
458 workpool.insert(g.id);
459 } else {
460 if (g.in1 >= 0) {
461 edges[g.in1].insert(g.id);
462 in_edges_count[g.id]++;
463 }
464 if (g.in2 >= 0 && g.in2 != g.in1) {
465 edges[g.in2].insert(g.id);
466 in_edges_count[g.id]++;
467 }
468 if (g.in3 >= 0 && g.in3 != g.in2 && g.in3 != g.in1) {
469 edges[g.in3].insert(g.id);
470 in_edges_count[g.id]++;
471 }
472 if (g.in4 >= 0 && g.in4 != g.in3 && g.in4 != g.in2 && g.in4 != g.in1) {
473 edges[g.in4].insert(g.id);
474 in_edges_count[g.id]++;
475 }
476 }
477 }
478
479 dump_loop_graph(dot_f, dot_nr, edges, workpool, in_edges_count);
480
481 while (workpool.size() > 0)
482 {
483 int id = *workpool.begin();
484 workpool.erase(id);
485
486 // log("Removing non-loop node %d from graph: %s\n", id, log_signal(signal_list[id].bit));
487
488 for (int id2 : edges[id]) {
489 log_assert(in_edges_count[id2] > 0);
490 if (--in_edges_count[id2] == 0)
491 workpool.insert(id2);
492 }
493 edges.erase(id);
494
495 dump_loop_graph(dot_f, dot_nr, edges, workpool, in_edges_count);
496
497 while (workpool.size() == 0)
498 {
499 if (edges.size() == 0)
500 break;
501
502 int id1 = edges.begin()->first;
503
504 for (auto &edge_it : edges) {
505 int id2 = edge_it.first;
506 RTLIL::Wire *w1 = signal_list[id1].bit.wire;
507 RTLIL::Wire *w2 = signal_list[id2].bit.wire;
508 if (w1 == nullptr)
509 id1 = id2;
510 else if (w2 == nullptr)
511 continue;
512 else if (w1->name[0] == '$' && w2->name[0] == '\\')
513 id1 = id2;
514 else if (w1->name[0] == '\\' && w2->name[0] == '$')
515 continue;
516 else if (edges[id1].size() < edges[id2].size())
517 id1 = id2;
518 else if (edges[id1].size() > edges[id2].size())
519 continue;
520 else if (w2->name.str() < w1->name.str())
521 id1 = id2;
522 }
523
524 if (edges[id1].size() == 0) {
525 edges.erase(id1);
526 continue;
527 }
528
529 log_assert(signal_list[id1].bit.wire != nullptr);
530
531 std::stringstream sstr;
532 sstr << "$abcloop$" << (autoidx++);
533 RTLIL::Wire *wire = module->addWire(sstr.str());
534
535 bool first_line = true;
536 for (int id2 : edges[id1]) {
537 if (first_line)
538 log("Breaking loop using new signal %s: %s -> %s\n", log_signal(RTLIL::SigSpec(wire)),
539 log_signal(signal_list[id1].bit), log_signal(signal_list[id2].bit));
540 else
541 log(" %*s %s -> %s\n", int(strlen(log_signal(RTLIL::SigSpec(wire)))), "",
542 log_signal(signal_list[id1].bit), log_signal(signal_list[id2].bit));
543 first_line = false;
544 }
545
546 int id3 = map_signal(RTLIL::SigSpec(wire));
547 signal_list[id1].is_port = true;
548 signal_list[id3].is_port = true;
549 log_assert(id3 == int(in_edges_count.size()));
550 in_edges_count.push_back(0);
551 workpool.insert(id3);
552
553 for (int id2 : edges[id1]) {
554 if (signal_list[id2].in1 == id1)
555 signal_list[id2].in1 = id3;
556 if (signal_list[id2].in2 == id1)
557 signal_list[id2].in2 = id3;
558 if (signal_list[id2].in3 == id1)
559 signal_list[id2].in3 = id3;
560 if (signal_list[id2].in4 == id1)
561 signal_list[id2].in4 = id3;
562 }
563 edges[id1].swap(edges[id3]);
564
565 module->connect(RTLIL::SigSig(signal_list[id3].bit, signal_list[id1].bit));
566 dump_loop_graph(dot_f, dot_nr, edges, workpool, in_edges_count);
567 }
568 }
569
570 if (dot_f != nullptr)
571 fclose(dot_f);
572 }
573
574 std::string add_echos_to_abc_cmd(std::string str)
575 {
576 std::string new_str, token;
577 for (size_t i = 0; i < str.size(); i++) {
578 token += str[i];
579 if (str[i] == ';') {
580 while (i+1 < str.size() && str[i+1] == ' ')
581 i++;
582 new_str += "echo + " + token + " " + token + " ";
583 token.clear();
584 }
585 }
586
587 if (!token.empty()) {
588 if (!new_str.empty())
589 new_str += "echo + " + token + "; ";
590 new_str += token;
591 }
592
593 return new_str;
594 }
595
596 std::string fold_abc_cmd(std::string str)
597 {
598 std::string token, new_str = " ";
599 int char_counter = 10;
600
601 for (size_t i = 0; i <= str.size(); i++) {
602 if (i < str.size())
603 token += str[i];
604 if (i == str.size() || str[i] == ';') {
605 if (char_counter + token.size() > 75)
606 new_str += "\n ", char_counter = 14;
607 new_str += token, char_counter += token.size();
608 token.clear();
609 }
610 }
611
612 return new_str;
613 }
614
615 std::string replace_tempdir(std::string text, std::string tempdir_name, bool show_tempdir)
616 {
617 if (show_tempdir)
618 return text;
619
620 while (1) {
621 size_t pos = text.find(tempdir_name);
622 if (pos == std::string::npos)
623 break;
624 text = text.substr(0, pos) + "<abc-temp-dir>" + text.substr(pos + GetSize(tempdir_name));
625 }
626
627 std::string selfdir_name = proc_self_dirname();
628 if (selfdir_name != "/") {
629 while (1) {
630 size_t pos = text.find(selfdir_name);
631 if (pos == std::string::npos)
632 break;
633 text = text.substr(0, pos) + "<yosys-exe-dir>/" + text.substr(pos + GetSize(selfdir_name));
634 }
635 }
636
637 return text;
638 }
639
640 struct abc_output_filter
641 {
642 bool got_cr;
643 int escape_seq_state;
644 std::string linebuf;
645 std::string tempdir_name;
646 bool show_tempdir;
647
648 abc_output_filter(std::string tempdir_name, bool show_tempdir) : tempdir_name(tempdir_name), show_tempdir(show_tempdir)
649 {
650 got_cr = false;
651 escape_seq_state = 0;
652 }
653
654 void next_char(char ch)
655 {
656 if (escape_seq_state == 0 && ch == '\033') {
657 escape_seq_state = 1;
658 return;
659 }
660 if (escape_seq_state == 1) {
661 escape_seq_state = ch == '[' ? 2 : 0;
662 return;
663 }
664 if (escape_seq_state == 2) {
665 if ((ch < '0' || '9' < ch) && ch != ';')
666 escape_seq_state = 0;
667 return;
668 }
669 escape_seq_state = 0;
670 if (ch == '\r') {
671 got_cr = true;
672 return;
673 }
674 if (ch == '\n') {
675 log("ABC: %s\n", replace_tempdir(linebuf, tempdir_name, show_tempdir).c_str());
676 got_cr = false, linebuf.clear();
677 return;
678 }
679 if (got_cr)
680 got_cr = false, linebuf.clear();
681 linebuf += ch;
682 }
683
684 void next_line(const std::string &line)
685 {
686 int pi, po;
687 if (sscanf(line.c_str(), "Start-point = pi%d. End-point = po%d.", &pi, &po) == 2) {
688 log("ABC: Start-point = pi%d (%s). End-point = po%d (%s).\n",
689 pi, pi_map.count(pi) ? pi_map.at(pi).c_str() : "???",
690 po, po_map.count(po) ? po_map.at(po).c_str() : "???");
691 return;
692 }
693
694 for (char ch : line)
695 next_char(ch);
696 }
697 };
698
699 void abc_module(RTLIL::Design *design, RTLIL::Module *current_module, std::string script_file, std::string exe_file,
700 std::vector<std::string> &liberty_files, std::vector<std::string> &genlib_files, std::string constr_file,
701 bool cleanup, vector<int> lut_costs, bool dff_mode, std::string clk_str, bool keepff, std::string delay_target,
702 std::string sop_inputs, std::string sop_products, std::string lutin_shared, bool fast_mode,
703 const std::vector<RTLIL::Cell*> &cells, bool show_tempdir, bool sop_mode, bool abc_dress)
704 {
705 module = current_module;
706 map_autoidx = autoidx++;
707
708 signal_map.clear();
709 signal_list.clear();
710 pi_map.clear();
711 po_map.clear();
712
713 if (clk_str != "$")
714 {
715 clk_polarity = true;
716 clk_sig = RTLIL::SigSpec();
717
718 en_polarity = true;
719 en_sig = RTLIL::SigSpec();
720
721 arst_polarity = true;
722 arst_sig = RTLIL::SigSpec();
723
724 srst_polarity = true;
725 srst_sig = RTLIL::SigSpec();
726 }
727
728 if (!clk_str.empty() && clk_str != "$")
729 {
730 std::string en_str;
731 std::string arst_str;
732 std::string srst_str;
733 if (clk_str.find(',') != std::string::npos) {
734 int pos = clk_str.find(',');
735 en_str = clk_str.substr(pos+1);
736 clk_str = clk_str.substr(0, pos);
737 }
738 if (en_str.find(',') != std::string::npos) {
739 int pos = en_str.find(',');
740 arst_str = en_str.substr(pos+1);
741 arst_str = en_str.substr(0, pos);
742 }
743 if (arst_str.find(',') != std::string::npos) {
744 int pos = arst_str.find(',');
745 srst_str = arst_str.substr(pos+1);
746 srst_str = arst_str.substr(0, pos);
747 }
748 if (clk_str[0] == '!') {
749 clk_polarity = false;
750 clk_str = clk_str.substr(1);
751 }
752 if (module->wire(RTLIL::escape_id(clk_str)) != nullptr)
753 clk_sig = assign_map(module->wire(RTLIL::escape_id(clk_str)));
754 if (en_str != "") {
755 if (en_str[0] == '!') {
756 en_polarity = false;
757 en_str = en_str.substr(1);
758 }
759 if (module->wire(RTLIL::escape_id(en_str)) != nullptr)
760 en_sig = assign_map(module->wire(RTLIL::escape_id(en_str)));
761 }
762 if (arst_str != "") {
763 if (arst_str[0] == '!') {
764 arst_polarity = false;
765 arst_str = arst_str.substr(1);
766 }
767 if (module->wire(RTLIL::escape_id(arst_str)) != nullptr)
768 arst_sig = assign_map(module->wire(RTLIL::escape_id(arst_str)));
769 }
770 if (srst_str != "") {
771 if (srst_str[0] == '!') {
772 srst_polarity = false;
773 srst_str = srst_str.substr(1);
774 }
775 if (module->wire(RTLIL::escape_id(srst_str)) != nullptr)
776 srst_sig = assign_map(module->wire(RTLIL::escape_id(srst_str)));
777 }
778 }
779
780 if (dff_mode && clk_sig.empty())
781 log_cmd_error("Clock domain %s not found.\n", clk_str.c_str());
782
783 std::string tempdir_name = "/tmp/" + proc_program_prefix()+ "yosys-abc-XXXXXX";
784 if (!cleanup)
785 tempdir_name[0] = tempdir_name[4] = '_';
786 tempdir_name = make_temp_dir(tempdir_name);
787 log_header(design, "Extracting gate netlist of module `%s' to `%s/input.blif'..\n",
788 module->name.c_str(), replace_tempdir(tempdir_name, tempdir_name, show_tempdir).c_str());
789
790 std::string abc_script = stringf("read_blif %s/input.blif; ", tempdir_name.c_str());
791
792 if (!liberty_files.empty() || !genlib_files.empty()) {
793 for (std::string liberty_file : liberty_files)
794 abc_script += stringf("read_lib -w %s; ", liberty_file.c_str());
795 for (std::string liberty_file : genlib_files)
796 abc_script += stringf("read_library %s; ", liberty_file.c_str());
797 if (!constr_file.empty())
798 abc_script += stringf("read_constr -v %s; ", constr_file.c_str());
799 } else
800 if (!lut_costs.empty())
801 abc_script += stringf("read_lut %s/lutdefs.txt; ", tempdir_name.c_str());
802 else
803 abc_script += stringf("read_library %s/stdcells.genlib; ", tempdir_name.c_str());
804
805 if (!script_file.empty()) {
806 if (script_file[0] == '+') {
807 for (size_t i = 1; i < script_file.size(); i++)
808 if (script_file[i] == '\'')
809 abc_script += "'\\''";
810 else if (script_file[i] == ',')
811 abc_script += " ";
812 else
813 abc_script += script_file[i];
814 } else
815 abc_script += stringf("source %s", script_file.c_str());
816 } else if (!lut_costs.empty()) {
817 bool all_luts_cost_same = true;
818 for (int this_cost : lut_costs)
819 if (this_cost != lut_costs.front())
820 all_luts_cost_same = false;
821 abc_script += fast_mode ? ABC_FAST_COMMAND_LUT : ABC_COMMAND_LUT;
822 if (all_luts_cost_same && !fast_mode)
823 abc_script += "; lutpack {S}";
824 } else if (!liberty_files.empty() || !genlib_files.empty())
825 abc_script += constr_file.empty() ? (fast_mode ? ABC_FAST_COMMAND_LIB : ABC_COMMAND_LIB) : (fast_mode ? ABC_FAST_COMMAND_CTR : ABC_COMMAND_CTR);
826 else if (sop_mode)
827 abc_script += fast_mode ? ABC_FAST_COMMAND_SOP : ABC_COMMAND_SOP;
828 else
829 abc_script += fast_mode ? ABC_FAST_COMMAND_DFL : ABC_COMMAND_DFL;
830
831 if (script_file.empty() && !delay_target.empty())
832 for (size_t pos = abc_script.find("dretime;"); pos != std::string::npos; pos = abc_script.find("dretime;", pos+1))
833 abc_script = abc_script.substr(0, pos) + "dretime; retime -o {D};" + abc_script.substr(pos+8);
834
835 for (size_t pos = abc_script.find("{D}"); pos != std::string::npos; pos = abc_script.find("{D}", pos))
836 abc_script = abc_script.substr(0, pos) + delay_target + abc_script.substr(pos+3);
837
838 for (size_t pos = abc_script.find("{I}"); pos != std::string::npos; pos = abc_script.find("{I}", pos))
839 abc_script = abc_script.substr(0, pos) + sop_inputs + abc_script.substr(pos+3);
840
841 for (size_t pos = abc_script.find("{P}"); pos != std::string::npos; pos = abc_script.find("{P}", pos))
842 abc_script = abc_script.substr(0, pos) + sop_products + abc_script.substr(pos+3);
843
844 for (size_t pos = abc_script.find("{S}"); pos != std::string::npos; pos = abc_script.find("{S}", pos))
845 abc_script = abc_script.substr(0, pos) + lutin_shared + abc_script.substr(pos+3);
846 if (abc_dress)
847 abc_script += "; dress";
848 abc_script += stringf("; write_blif %s/output.blif", tempdir_name.c_str());
849 abc_script = add_echos_to_abc_cmd(abc_script);
850
851 for (size_t i = 0; i+1 < abc_script.size(); i++)
852 if (abc_script[i] == ';' && abc_script[i+1] == ' ')
853 abc_script[i+1] = '\n';
854
855 std::string buffer = stringf("%s/abc.script", tempdir_name.c_str());
856 FILE *f = fopen(buffer.c_str(), "wt");
857 if (f == nullptr)
858 log_error("Opening %s for writing failed: %s\n", buffer.c_str(), strerror(errno));
859 fprintf(f, "%s\n", abc_script.c_str());
860 fclose(f);
861
862 if (dff_mode || !clk_str.empty())
863 {
864 if (clk_sig.size() == 0)
865 log("No%s clock domain found. Not extracting any FF cells.\n", clk_str.empty() ? "" : " matching");
866 else {
867 log("Found%s %s clock domain: %s", clk_str.empty() ? "" : " matching", clk_polarity ? "posedge" : "negedge", log_signal(clk_sig));
868 if (en_sig.size() != 0)
869 log(", enabled by %s%s", en_polarity ? "" : "!", log_signal(en_sig));
870 if (arst_sig.size() != 0)
871 log(", asynchronously reset by %s%s", arst_polarity ? "" : "!", log_signal(arst_sig));
872 if (srst_sig.size() != 0)
873 log(", synchronously reset by %s%s", srst_polarity ? "" : "!", log_signal(srst_sig));
874 log("\n");
875 }
876 }
877
878 had_init = false;
879 for (auto c : cells)
880 extract_cell(c, keepff);
881
882 for (auto wire : module->wires()) {
883 if (wire->port_id > 0 || wire->get_bool_attribute(ID::keep))
884 mark_port(wire);
885 }
886
887 for (auto cell : module->cells())
888 for (auto &port_it : cell->connections())
889 mark_port(port_it.second);
890
891 if (clk_sig.size() != 0)
892 mark_port(clk_sig);
893
894 if (en_sig.size() != 0)
895 mark_port(en_sig);
896
897 if (arst_sig.size() != 0)
898 mark_port(arst_sig);
899
900 if (srst_sig.size() != 0)
901 mark_port(srst_sig);
902
903 handle_loops();
904
905 buffer = stringf("%s/input.blif", tempdir_name.c_str());
906 f = fopen(buffer.c_str(), "wt");
907 if (f == nullptr)
908 log_error("Opening %s for writing failed: %s\n", buffer.c_str(), strerror(errno));
909
910 fprintf(f, ".model netlist\n");
911
912 int count_input = 0;
913 fprintf(f, ".inputs");
914 for (auto &si : signal_list) {
915 if (!si.is_port || si.type != G(NONE))
916 continue;
917 fprintf(f, " ys__n%d", si.id);
918 pi_map[count_input++] = log_signal(si.bit);
919 }
920 if (count_input == 0)
921 fprintf(f, " dummy_input\n");
922 fprintf(f, "\n");
923
924 int count_output = 0;
925 fprintf(f, ".outputs");
926 for (auto &si : signal_list) {
927 if (!si.is_port || si.type == G(NONE))
928 continue;
929 fprintf(f, " ys__n%d", si.id);
930 po_map[count_output++] = log_signal(si.bit);
931 }
932 fprintf(f, "\n");
933
934 for (auto &si : signal_list)
935 fprintf(f, "# ys__n%-5d %s\n", si.id, log_signal(si.bit));
936
937 for (auto &si : signal_list) {
938 if (si.bit.wire == nullptr) {
939 fprintf(f, ".names ys__n%d\n", si.id);
940 if (si.bit == RTLIL::State::S1)
941 fprintf(f, "1\n");
942 }
943 }
944
945 int count_gates = 0;
946 for (auto &si : signal_list) {
947 if (si.type == G(BUF)) {
948 fprintf(f, ".names ys__n%d ys__n%d\n", si.in1, si.id);
949 fprintf(f, "1 1\n");
950 } else if (si.type == G(NOT)) {
951 fprintf(f, ".names ys__n%d ys__n%d\n", si.in1, si.id);
952 fprintf(f, "0 1\n");
953 } else if (si.type == G(AND)) {
954 fprintf(f, ".names ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.id);
955 fprintf(f, "11 1\n");
956 } else if (si.type == G(NAND)) {
957 fprintf(f, ".names ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.id);
958 fprintf(f, "0- 1\n");
959 fprintf(f, "-0 1\n");
960 } else if (si.type == G(OR)) {
961 fprintf(f, ".names ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.id);
962 fprintf(f, "-1 1\n");
963 fprintf(f, "1- 1\n");
964 } else if (si.type == G(NOR)) {
965 fprintf(f, ".names ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.id);
966 fprintf(f, "00 1\n");
967 } else if (si.type == G(XOR)) {
968 fprintf(f, ".names ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.id);
969 fprintf(f, "01 1\n");
970 fprintf(f, "10 1\n");
971 } else if (si.type == G(XNOR)) {
972 fprintf(f, ".names ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.id);
973 fprintf(f, "00 1\n");
974 fprintf(f, "11 1\n");
975 } else if (si.type == G(ANDNOT)) {
976 fprintf(f, ".names ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.id);
977 fprintf(f, "10 1\n");
978 } else if (si.type == G(ORNOT)) {
979 fprintf(f, ".names ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.id);
980 fprintf(f, "1- 1\n");
981 fprintf(f, "-0 1\n");
982 } else if (si.type == G(MUX)) {
983 fprintf(f, ".names ys__n%d ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.in3, si.id);
984 fprintf(f, "1-0 1\n");
985 fprintf(f, "-11 1\n");
986 } else if (si.type == G(NMUX)) {
987 fprintf(f, ".names ys__n%d ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.in3, si.id);
988 fprintf(f, "0-0 1\n");
989 fprintf(f, "-01 1\n");
990 } else if (si.type == G(AOI3)) {
991 fprintf(f, ".names ys__n%d ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.in3, si.id);
992 fprintf(f, "-00 1\n");
993 fprintf(f, "0-0 1\n");
994 } else if (si.type == G(OAI3)) {
995 fprintf(f, ".names ys__n%d ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.in3, si.id);
996 fprintf(f, "00- 1\n");
997 fprintf(f, "--0 1\n");
998 } else if (si.type == G(AOI4)) {
999 fprintf(f, ".names ys__n%d ys__n%d ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.in3, si.in4, si.id);
1000 fprintf(f, "-0-0 1\n");
1001 fprintf(f, "-00- 1\n");
1002 fprintf(f, "0--0 1\n");
1003 fprintf(f, "0-0- 1\n");
1004 } else if (si.type == G(OAI4)) {
1005 fprintf(f, ".names ys__n%d ys__n%d ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.in3, si.in4, si.id);
1006 fprintf(f, "00-- 1\n");
1007 fprintf(f, "--00 1\n");
1008 } else if (si.type == G(FF)) {
1009 fprintf(f, ".latch ys__n%d ys__n%d 2\n", si.in1, si.id);
1010 } else if (si.type == G(FF0)) {
1011 fprintf(f, ".latch ys__n%d ys__n%d 0\n", si.in1, si.id);
1012 } else if (si.type == G(FF1)) {
1013 fprintf(f, ".latch ys__n%d ys__n%d 1\n", si.in1, si.id);
1014 } else if (si.type != G(NONE))
1015 log_abort();
1016 if (si.type != G(NONE))
1017 count_gates++;
1018 }
1019
1020 fprintf(f, ".end\n");
1021 fclose(f);
1022
1023 log("Extracted %d gates and %d wires to a netlist network with %d inputs and %d outputs.\n",
1024 count_gates, GetSize(signal_list), count_input, count_output);
1025 log_push();
1026 if (count_output > 0)
1027 {
1028 log_header(design, "Executing ABC.\n");
1029
1030 auto &cell_cost = cmos_cost ? CellCosts::cmos_gate_cost() : CellCosts::default_gate_cost();
1031
1032 buffer = stringf("%s/stdcells.genlib", tempdir_name.c_str());
1033 f = fopen(buffer.c_str(), "wt");
1034 if (f == nullptr)
1035 log_error("Opening %s for writing failed: %s\n", buffer.c_str(), strerror(errno));
1036 fprintf(f, "GATE ZERO 1 Y=CONST0;\n");
1037 fprintf(f, "GATE ONE 1 Y=CONST1;\n");
1038 fprintf(f, "GATE BUF %d Y=A; PIN * NONINV 1 999 1 0 1 0\n", cell_cost.at(ID($_BUF_)));
1039 fprintf(f, "GATE NOT %d Y=!A; PIN * INV 1 999 1 0 1 0\n", cell_cost.at(ID($_NOT_)));
1040 if (enabled_gates.count("AND"))
1041 fprintf(f, "GATE AND %d Y=A*B; PIN * NONINV 1 999 1 0 1 0\n", cell_cost.at(ID($_AND_)));
1042 if (enabled_gates.count("NAND"))
1043 fprintf(f, "GATE NAND %d Y=!(A*B); PIN * INV 1 999 1 0 1 0\n", cell_cost.at(ID($_NAND_)));
1044 if (enabled_gates.count("OR"))
1045 fprintf(f, "GATE OR %d Y=A+B; PIN * NONINV 1 999 1 0 1 0\n", cell_cost.at(ID($_OR_)));
1046 if (enabled_gates.count("NOR"))
1047 fprintf(f, "GATE NOR %d Y=!(A+B); PIN * INV 1 999 1 0 1 0\n", cell_cost.at(ID($_NOR_)));
1048 if (enabled_gates.count("XOR"))
1049 fprintf(f, "GATE XOR %d Y=(A*!B)+(!A*B); PIN * UNKNOWN 1 999 1 0 1 0\n", cell_cost.at(ID($_XOR_)));
1050 if (enabled_gates.count("XNOR"))
1051 fprintf(f, "GATE XNOR %d Y=(A*B)+(!A*!B); PIN * UNKNOWN 1 999 1 0 1 0\n", cell_cost.at(ID($_XNOR_)));
1052 if (enabled_gates.count("ANDNOT"))
1053 fprintf(f, "GATE ANDNOT %d Y=A*!B; PIN * UNKNOWN 1 999 1 0 1 0\n", cell_cost.at(ID($_ANDNOT_)));
1054 if (enabled_gates.count("ORNOT"))
1055 fprintf(f, "GATE ORNOT %d Y=A+!B; PIN * UNKNOWN 1 999 1 0 1 0\n", cell_cost.at(ID($_ORNOT_)));
1056 if (enabled_gates.count("AOI3"))
1057 fprintf(f, "GATE AOI3 %d Y=!((A*B)+C); PIN * INV 1 999 1 0 1 0\n", cell_cost.at(ID($_AOI3_)));
1058 if (enabled_gates.count("OAI3"))
1059 fprintf(f, "GATE OAI3 %d Y=!((A+B)*C); PIN * INV 1 999 1 0 1 0\n", cell_cost.at(ID($_OAI3_)));
1060 if (enabled_gates.count("AOI4"))
1061 fprintf(f, "GATE AOI4 %d Y=!((A*B)+(C*D)); PIN * INV 1 999 1 0 1 0\n", cell_cost.at(ID($_AOI4_)));
1062 if (enabled_gates.count("OAI4"))
1063 fprintf(f, "GATE OAI4 %d Y=!((A+B)*(C+D)); PIN * INV 1 999 1 0 1 0\n", cell_cost.at(ID($_OAI4_)));
1064 if (enabled_gates.count("MUX"))
1065 fprintf(f, "GATE MUX %d Y=(A*B)+(S*B)+(!S*A); PIN * UNKNOWN 1 999 1 0 1 0\n", cell_cost.at(ID($_MUX_)));
1066 if (enabled_gates.count("NMUX"))
1067 fprintf(f, "GATE NMUX %d Y=!((A*B)+(S*B)+(!S*A)); PIN * UNKNOWN 1 999 1 0 1 0\n", cell_cost.at(ID($_NMUX_)));
1068 if (map_mux4)
1069 fprintf(f, "GATE MUX4 %d Y=(!S*!T*A)+(S*!T*B)+(!S*T*C)+(S*T*D); PIN * UNKNOWN 1 999 1 0 1 0\n", 2*cell_cost.at(ID($_MUX_)));
1070 if (map_mux8)
1071 fprintf(f, "GATE MUX8 %d Y=(!S*!T*!U*A)+(S*!T*!U*B)+(!S*T*!U*C)+(S*T*!U*D)+(!S*!T*U*E)+(S*!T*U*F)+(!S*T*U*G)+(S*T*U*H); PIN * UNKNOWN 1 999 1 0 1 0\n", 4*cell_cost.at(ID($_MUX_)));
1072 if (map_mux16)
1073 fprintf(f, "GATE MUX16 %d Y=(!S*!T*!U*!V*A)+(S*!T*!U*!V*B)+(!S*T*!U*!V*C)+(S*T*!U*!V*D)+(!S*!T*U*!V*E)+(S*!T*U*!V*F)+(!S*T*U*!V*G)+(S*T*U*!V*H)+(!S*!T*!U*V*I)+(S*!T*!U*V*J)+(!S*T*!U*V*K)+(S*T*!U*V*L)+(!S*!T*U*V*M)+(S*!T*U*V*N)+(!S*T*U*V*O)+(S*T*U*V*P); PIN * UNKNOWN 1 999 1 0 1 0\n", 8*cell_cost.at(ID($_MUX_)));
1074 fclose(f);
1075
1076 if (!lut_costs.empty()) {
1077 buffer = stringf("%s/lutdefs.txt", tempdir_name.c_str());
1078 f = fopen(buffer.c_str(), "wt");
1079 if (f == nullptr)
1080 log_error("Opening %s for writing failed: %s\n", buffer.c_str(), strerror(errno));
1081 for (int i = 0; i < GetSize(lut_costs); i++)
1082 fprintf(f, "%d %d.00 1.00\n", i+1, lut_costs.at(i));
1083 fclose(f);
1084 }
1085
1086 buffer = stringf("%s -s -f %s/abc.script 2>&1", exe_file.c_str(), tempdir_name.c_str());
1087 log("Running ABC command: %s\n", replace_tempdir(buffer, tempdir_name, show_tempdir).c_str());
1088
1089 #ifndef YOSYS_LINK_ABC
1090 abc_output_filter filt(tempdir_name, show_tempdir);
1091 int ret = run_command(buffer, std::bind(&abc_output_filter::next_line, filt, std::placeholders::_1));
1092 #else
1093 // These needs to be mutable, supposedly due to getopt
1094 char *abc_argv[5];
1095 string tmp_script_name = stringf("%s/abc.script", tempdir_name.c_str());
1096 abc_argv[0] = strdup(exe_file.c_str());
1097 abc_argv[1] = strdup("-s");
1098 abc_argv[2] = strdup("-f");
1099 abc_argv[3] = strdup(tmp_script_name.c_str());
1100 abc_argv[4] = 0;
1101 int ret = Abc_RealMain(4, abc_argv);
1102 free(abc_argv[0]);
1103 free(abc_argv[1]);
1104 free(abc_argv[2]);
1105 free(abc_argv[3]);
1106 #endif
1107 if (ret != 0)
1108 log_error("ABC: execution of command \"%s\" failed: return code %d.\n", buffer.c_str(), ret);
1109
1110 buffer = stringf("%s/%s", tempdir_name.c_str(), "output.blif");
1111 std::ifstream ifs;
1112 ifs.open(buffer);
1113 if (ifs.fail())
1114 log_error("Can't open ABC output file `%s'.\n", buffer.c_str());
1115
1116 bool builtin_lib = liberty_files.empty() && genlib_files.empty();
1117 RTLIL::Design *mapped_design = new RTLIL::Design;
1118 parse_blif(mapped_design, ifs, builtin_lib ? ID(DFF) : ID(_dff_), false, sop_mode);
1119
1120 ifs.close();
1121
1122 log_header(design, "Re-integrating ABC results.\n");
1123 RTLIL::Module *mapped_mod = mapped_design->module(ID(netlist));
1124 if (mapped_mod == nullptr)
1125 log_error("ABC output file does not contain a module `netlist'.\n");
1126 for (auto w : mapped_mod->wires()) {
1127 RTLIL::Wire *orig_wire = nullptr;
1128 RTLIL::Wire *wire = module->addWire(remap_name(w->name, &orig_wire));
1129 if (orig_wire != nullptr && orig_wire->attributes.count(ID::src))
1130 wire->attributes[ID::src] = orig_wire->attributes[ID::src];
1131 if (markgroups) wire->attributes[ID::abcgroup] = map_autoidx;
1132 design->select(module, wire);
1133 }
1134
1135 SigMap mapped_sigmap(mapped_mod);
1136 FfInitVals mapped_initvals(&mapped_sigmap, mapped_mod);
1137
1138 dict<std::string, int> cell_stats;
1139 for (auto c : mapped_mod->cells())
1140 {
1141 if (builtin_lib)
1142 {
1143 cell_stats[RTLIL::unescape_id(c->type)]++;
1144 if (c->type.in(ID(ZERO), ID(ONE))) {
1145 RTLIL::SigSig conn;
1146 RTLIL::IdString name_y = remap_name(c->getPort(ID::Y).as_wire()->name);
1147 conn.first = module->wire(name_y);
1148 conn.second = RTLIL::SigSpec(c->type == ID(ZERO) ? 0 : 1, 1);
1149 module->connect(conn);
1150 continue;
1151 }
1152 if (c->type == ID(BUF)) {
1153 RTLIL::SigSig conn;
1154 RTLIL::IdString name_y = remap_name(c->getPort(ID::Y).as_wire()->name);
1155 RTLIL::IdString name_a = remap_name(c->getPort(ID::A).as_wire()->name);
1156 conn.first = module->wire(name_y);
1157 conn.second = module->wire(name_a);
1158 module->connect(conn);
1159 continue;
1160 }
1161 if (c->type == ID(NOT)) {
1162 RTLIL::Cell *cell = module->addCell(remap_name(c->name), ID($_NOT_));
1163 if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx;
1164 for (auto name : {ID::A, ID::Y}) {
1165 RTLIL::IdString remapped_name = remap_name(c->getPort(name).as_wire()->name);
1166 cell->setPort(name, module->wire(remapped_name));
1167 }
1168 design->select(module, cell);
1169 continue;
1170 }
1171 if (c->type.in(ID(AND), ID(OR), ID(XOR), ID(NAND), ID(NOR), ID(XNOR), ID(ANDNOT), ID(ORNOT))) {
1172 RTLIL::Cell *cell = module->addCell(remap_name(c->name), stringf("$_%s_", c->type.c_str()+1));
1173 if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx;
1174 for (auto name : {ID::A, ID::B, ID::Y}) {
1175 RTLIL::IdString remapped_name = remap_name(c->getPort(name).as_wire()->name);
1176 cell->setPort(name, module->wire(remapped_name));
1177 }
1178 design->select(module, cell);
1179 continue;
1180 }
1181 if (c->type.in(ID(MUX), ID(NMUX))) {
1182 RTLIL::Cell *cell = module->addCell(remap_name(c->name), stringf("$_%s_", c->type.c_str()+1));
1183 if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx;
1184 for (auto name : {ID::A, ID::B, ID::S, ID::Y}) {
1185 RTLIL::IdString remapped_name = remap_name(c->getPort(name).as_wire()->name);
1186 cell->setPort(name, module->wire(remapped_name));
1187 }
1188 design->select(module, cell);
1189 continue;
1190 }
1191 if (c->type == ID(MUX4)) {
1192 RTLIL::Cell *cell = module->addCell(remap_name(c->name), ID($_MUX4_));
1193 if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx;
1194 for (auto name : {ID::A, ID::B, ID::C, ID::D, ID::S, ID::T, ID::Y}) {
1195 RTLIL::IdString remapped_name = remap_name(c->getPort(name).as_wire()->name);
1196 cell->setPort(name, module->wire(remapped_name));
1197 }
1198 design->select(module, cell);
1199 continue;
1200 }
1201 if (c->type == ID(MUX8)) {
1202 RTLIL::Cell *cell = module->addCell(remap_name(c->name), ID($_MUX8_));
1203 if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx;
1204 for (auto name : {ID::A, ID::B, ID::C, ID::D, ID::E, ID::F, ID::G, ID::H, ID::S, ID::T, ID::U, ID::Y}) {
1205 RTLIL::IdString remapped_name = remap_name(c->getPort(name).as_wire()->name);
1206 cell->setPort(name, module->wire(remapped_name));
1207 }
1208 design->select(module, cell);
1209 continue;
1210 }
1211 if (c->type == ID(MUX16)) {
1212 RTLIL::Cell *cell = module->addCell(remap_name(c->name), ID($_MUX16_));
1213 if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx;
1214 for (auto name : {ID::A, ID::B, ID::C, ID::D, ID::E, ID::F, ID::G, ID::H, ID::I, ID::J, ID::K,
1215 ID::L, ID::M, ID::N, ID::O, ID::P, ID::S, ID::T, ID::U, ID::V, ID::Y}) {
1216 RTLIL::IdString remapped_name = remap_name(c->getPort(name).as_wire()->name);
1217 cell->setPort(name, module->wire(remapped_name));
1218 }
1219 design->select(module, cell);
1220 continue;
1221 }
1222 if (c->type.in(ID(AOI3), ID(OAI3))) {
1223 RTLIL::Cell *cell = module->addCell(remap_name(c->name), stringf("$_%s_", c->type.c_str()+1));
1224 if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx;
1225 for (auto name : {ID::A, ID::B, ID::C, ID::Y}) {
1226 RTLIL::IdString remapped_name = remap_name(c->getPort(name).as_wire()->name);
1227 cell->setPort(name, module->wire(remapped_name));
1228 }
1229 design->select(module, cell);
1230 continue;
1231 }
1232 if (c->type.in(ID(AOI4), ID(OAI4))) {
1233 RTLIL::Cell *cell = module->addCell(remap_name(c->name), stringf("$_%s_", c->type.c_str()+1));
1234 if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx;
1235 for (auto name : {ID::A, ID::B, ID::C, ID::D, ID::Y}) {
1236 RTLIL::IdString remapped_name = remap_name(c->getPort(name).as_wire()->name);
1237 cell->setPort(name, module->wire(remapped_name));
1238 }
1239 design->select(module, cell);
1240 continue;
1241 }
1242 if (c->type == ID(DFF)) {
1243 log_assert(clk_sig.size() == 1);
1244 FfData ff(module, &initvals, remap_name(c->name));
1245 ff.width = 1;
1246 ff.is_fine = true;
1247 ff.has_clk = true;
1248 ff.pol_clk = clk_polarity;
1249 ff.sig_clk = clk_sig;
1250 if (en_sig.size() != 0) {
1251 log_assert(en_sig.size() == 1);
1252 ff.has_ce = true;
1253 ff.pol_ce = en_polarity;
1254 ff.sig_ce = en_sig;
1255 }
1256 RTLIL::Const init = mapped_initvals(c->getPort(ID::Q));
1257 if (had_init)
1258 ff.val_init = init;
1259 else
1260 ff.val_init = State::Sx;
1261 if (arst_sig.size() != 0) {
1262 log_assert(arst_sig.size() == 1);
1263 ff.has_arst = true;
1264 ff.pol_arst = arst_polarity;
1265 ff.sig_arst = arst_sig;
1266 ff.val_arst = init;
1267 }
1268 if (srst_sig.size() != 0) {
1269 log_assert(srst_sig.size() == 1);
1270 ff.has_srst = true;
1271 ff.pol_srst = srst_polarity;
1272 ff.sig_srst = srst_sig;
1273 ff.val_srst = init;
1274 }
1275 ff.sig_d = module->wire(remap_name(c->getPort(ID::D).as_wire()->name));
1276 ff.sig_q = module->wire(remap_name(c->getPort(ID::Q).as_wire()->name));
1277 RTLIL::Cell *cell = ff.emit();
1278 if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx;
1279 design->select(module, cell);
1280 continue;
1281 }
1282 }
1283 else
1284 cell_stats[RTLIL::unescape_id(c->type)]++;
1285
1286 if (c->type.in(ID(_const0_), ID(_const1_))) {
1287 RTLIL::SigSig conn;
1288 conn.first = module->wire(remap_name(c->connections().begin()->second.as_wire()->name));
1289 conn.second = RTLIL::SigSpec(c->type == ID(_const0_) ? 0 : 1, 1);
1290 module->connect(conn);
1291 continue;
1292 }
1293
1294 if (c->type == ID(_dff_)) {
1295 log_assert(clk_sig.size() == 1);
1296 FfData ff(module, &initvals, remap_name(c->name));
1297 ff.width = 1;
1298 ff.is_fine = true;
1299 ff.has_clk = true;
1300 ff.pol_clk = clk_polarity;
1301 ff.sig_clk = clk_sig;
1302 if (en_sig.size() != 0) {
1303 log_assert(en_sig.size() == 1);
1304 ff.pol_ce = en_polarity;
1305 ff.sig_ce = en_sig;
1306 }
1307 RTLIL::Const init = mapped_initvals(c->getPort(ID::Q));
1308 if (had_init)
1309 ff.val_init = init;
1310 else
1311 ff.val_init = State::Sx;
1312 if (arst_sig.size() != 0) {
1313 log_assert(arst_sig.size() == 1);
1314 ff.pol_arst = arst_polarity;
1315 ff.sig_arst = arst_sig;
1316 ff.val_arst = init;
1317 }
1318 if (srst_sig.size() != 0) {
1319 log_assert(srst_sig.size() == 1);
1320 ff.pol_srst = srst_polarity;
1321 ff.sig_srst = srst_sig;
1322 ff.val_srst = init;
1323 }
1324 ff.sig_d = module->wire(remap_name(c->getPort(ID::D).as_wire()->name));
1325 ff.sig_q = module->wire(remap_name(c->getPort(ID::Q).as_wire()->name));
1326 RTLIL::Cell *cell = ff.emit();
1327 if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx;
1328 design->select(module, cell);
1329 continue;
1330 }
1331
1332 if (c->type == ID($lut) && GetSize(c->getPort(ID::A)) == 1 && c->getParam(ID::LUT).as_int() == 2) {
1333 SigSpec my_a = module->wire(remap_name(c->getPort(ID::A).as_wire()->name));
1334 SigSpec my_y = module->wire(remap_name(c->getPort(ID::Y).as_wire()->name));
1335 module->connect(my_y, my_a);
1336 continue;
1337 }
1338
1339 RTLIL::Cell *cell = module->addCell(remap_name(c->name), c->type);
1340 if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx;
1341 cell->parameters = c->parameters;
1342 for (auto &conn : c->connections()) {
1343 RTLIL::SigSpec newsig;
1344 for (auto &c : conn.second.chunks()) {
1345 if (c.width == 0)
1346 continue;
1347 log_assert(c.width == 1);
1348 newsig.append(module->wire(remap_name(c.wire->name)));
1349 }
1350 cell->setPort(conn.first, newsig);
1351 }
1352 design->select(module, cell);
1353 }
1354
1355 for (auto conn : mapped_mod->connections()) {
1356 if (!conn.first.is_fully_const())
1357 conn.first = module->wire(remap_name(conn.first.as_wire()->name));
1358 if (!conn.second.is_fully_const())
1359 conn.second = module->wire(remap_name(conn.second.as_wire()->name));
1360 module->connect(conn);
1361 }
1362
1363 for (auto &it : cell_stats)
1364 log("ABC RESULTS: %15s cells: %8d\n", it.first.c_str(), it.second);
1365 int in_wires = 0, out_wires = 0;
1366 for (auto &si : signal_list)
1367 if (si.is_port) {
1368 char buffer[100];
1369 snprintf(buffer, 100, "\\ys__n%d", si.id);
1370 RTLIL::SigSig conn;
1371 if (si.type != G(NONE)) {
1372 conn.first = si.bit;
1373 conn.second = module->wire(remap_name(buffer));
1374 out_wires++;
1375 } else {
1376 conn.first = module->wire(remap_name(buffer));
1377 conn.second = si.bit;
1378 in_wires++;
1379 }
1380 module->connect(conn);
1381 }
1382 log("ABC RESULTS: internal signals: %8d\n", int(signal_list.size()) - in_wires - out_wires);
1383 log("ABC RESULTS: input signals: %8d\n", in_wires);
1384 log("ABC RESULTS: output signals: %8d\n", out_wires);
1385
1386 delete mapped_design;
1387 }
1388 else
1389 {
1390 log("Don't call ABC as there is nothing to map.\n");
1391 }
1392
1393 if (cleanup)
1394 {
1395 log("Removing temp directory.\n");
1396 remove_directory(tempdir_name);
1397 }
1398
1399 log_pop();
1400 }
1401
1402 struct AbcPass : public Pass {
1403 AbcPass() : Pass("abc", "use ABC for technology mapping") { }
1404 void help() override
1405 {
1406 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
1407 log("\n");
1408 log(" abc [options] [selection]\n");
1409 log("\n");
1410 log("This pass uses the ABC tool [1] for technology mapping of yosys's internal gate\n");
1411 log("library to a target architecture.\n");
1412 log("\n");
1413 log(" -exe <command>\n");
1414 #ifdef ABCEXTERNAL
1415 log(" use the specified command instead of \"" ABCEXTERNAL "\" to execute ABC.\n");
1416 #else
1417 log(" use the specified command instead of \"<yosys-bindir>/%syosys-abc\" to execute ABC.\n", proc_program_prefix().c_str());
1418 #endif
1419 log(" This can e.g. be used to call a specific version of ABC or a wrapper.\n");
1420 log("\n");
1421 log(" -script <file>\n");
1422 log(" use the specified ABC script file instead of the default script.\n");
1423 log("\n");
1424 log(" if <file> starts with a plus sign (+), then the rest of the filename\n");
1425 log(" string is interpreted as the command string to be passed to ABC. The\n");
1426 log(" leading plus sign is removed and all commas (,) in the string are\n");
1427 log(" replaced with blanks before the string is passed to ABC.\n");
1428 log("\n");
1429 log(" if no -script parameter is given, the following scripts are used:\n");
1430 log("\n");
1431 log(" for -liberty/-genlib without -constr:\n");
1432 log("%s\n", fold_abc_cmd(ABC_COMMAND_LIB).c_str());
1433 log("\n");
1434 log(" for -liberty/-genlib with -constr:\n");
1435 log("%s\n", fold_abc_cmd(ABC_COMMAND_CTR).c_str());
1436 log("\n");
1437 log(" for -lut/-luts (only one LUT size):\n");
1438 log("%s\n", fold_abc_cmd(ABC_COMMAND_LUT "; lutpack {S}").c_str());
1439 log("\n");
1440 log(" for -lut/-luts (different LUT sizes):\n");
1441 log("%s\n", fold_abc_cmd(ABC_COMMAND_LUT).c_str());
1442 log("\n");
1443 log(" for -sop:\n");
1444 log("%s\n", fold_abc_cmd(ABC_COMMAND_SOP).c_str());
1445 log("\n");
1446 log(" otherwise:\n");
1447 log("%s\n", fold_abc_cmd(ABC_COMMAND_DFL).c_str());
1448 log("\n");
1449 log(" -fast\n");
1450 log(" use different default scripts that are slightly faster (at the cost\n");
1451 log(" of output quality):\n");
1452 log("\n");
1453 log(" for -liberty/-genlib without -constr:\n");
1454 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_LIB).c_str());
1455 log("\n");
1456 log(" for -liberty/-genlib with -constr:\n");
1457 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_CTR).c_str());
1458 log("\n");
1459 log(" for -lut/-luts:\n");
1460 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_LUT).c_str());
1461 log("\n");
1462 log(" for -sop:\n");
1463 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_SOP).c_str());
1464 log("\n");
1465 log(" otherwise:\n");
1466 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_DFL).c_str());
1467 log("\n");
1468 log(" -liberty <file>\n");
1469 log(" generate netlists for the specified cell library (using the liberty\n");
1470 log(" file format).\n");
1471 log("\n");
1472 log(" -genlib <file>\n");
1473 log(" generate netlists for the specified cell library (using the SIS Genlib\n");
1474 log(" file format).\n");
1475 log("\n");
1476 log(" -constr <file>\n");
1477 log(" pass this file with timing constraints to ABC.\n");
1478 log(" use with -liberty/-genlib.\n");
1479 log("\n");
1480 log(" a constr file contains two lines:\n");
1481 log(" set_driving_cell <cell_name>\n");
1482 log(" set_load <floating_point_number>\n");
1483 log("\n");
1484 log(" the set_driving_cell statement defines which cell type is assumed to\n");
1485 log(" drive the primary inputs and the set_load statement sets the load in\n");
1486 log(" femtofarads for each primary output.\n");
1487 log("\n");
1488 log(" -D <picoseconds>\n");
1489 log(" set delay target. the string {D} in the default scripts above is\n");
1490 log(" replaced by this option when used, and an empty string otherwise.\n");
1491 log(" this also replaces 'dretime' with 'dretime; retime -o {D}' in the\n");
1492 log(" default scripts above.\n");
1493 log("\n");
1494 log(" -I <num>\n");
1495 log(" maximum number of SOP inputs.\n");
1496 log(" (replaces {I} in the default scripts above)\n");
1497 log("\n");
1498 log(" -P <num>\n");
1499 log(" maximum number of SOP products.\n");
1500 log(" (replaces {P} in the default scripts above)\n");
1501 log("\n");
1502 log(" -S <num>\n");
1503 log(" maximum number of LUT inputs shared.\n");
1504 log(" (replaces {S} in the default scripts above, default: -S 1)\n");
1505 log("\n");
1506 log(" -lut <width>\n");
1507 log(" generate netlist using luts of (max) the specified width.\n");
1508 log("\n");
1509 log(" -lut <w1>:<w2>\n");
1510 log(" generate netlist using luts of (max) the specified width <w2>. All\n");
1511 log(" luts with width <= <w1> have constant cost. for luts larger than <w1>\n");
1512 log(" the area cost doubles with each additional input bit. the delay cost\n");
1513 log(" is still constant for all lut widths.\n");
1514 log("\n");
1515 log(" -luts <cost1>,<cost2>,<cost3>,<sizeN>:<cost4-N>,..\n");
1516 log(" generate netlist using luts. Use the specified costs for luts with 1,\n");
1517 log(" 2, 3, .. inputs.\n");
1518 log("\n");
1519 log(" -sop\n");
1520 log(" map to sum-of-product cells and inverters\n");
1521 log("\n");
1522 // log(" -mux4, -mux8, -mux16\n");
1523 // log(" try to extract 4-input, 8-input, and/or 16-input muxes\n");
1524 // log(" (ignored when used with -liberty/-genlib or -lut)\n");
1525 // log("\n");
1526 log(" -g type1,type2,...\n");
1527 log(" Map to the specified list of gate types. Supported gates types are:\n");
1528 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
1529 log(" AND, NAND, OR, NOR, XOR, XNOR, ANDNOT, ORNOT, MUX,\n");
1530 log(" NMUX, AOI3, OAI3, AOI4, OAI4.\n");
1531 log(" (The NOT gate is always added to this list automatically.)\n");
1532 log("\n");
1533 log(" The following aliases can be used to reference common sets of gate types:\n");
1534 log(" simple: AND OR XOR MUX\n");
1535 log(" cmos2: NAND NOR\n");
1536 log(" cmos3: NAND NOR AOI3 OAI3\n");
1537 log(" cmos4: NAND NOR AOI3 OAI3 AOI4 OAI4\n");
1538 log(" cmos: NAND NOR AOI3 OAI3 AOI4 OAI4 NMUX MUX XOR XNOR\n");
1539 log(" gates: AND NAND OR NOR XOR XNOR ANDNOT ORNOT\n");
1540 log(" aig: AND NAND OR NOR ANDNOT ORNOT\n");
1541 log("\n");
1542 log(" The alias 'all' represent the full set of all gate types.\n");
1543 log("\n");
1544 log(" Prefix a gate type with a '-' to remove it from the list. For example\n");
1545 log(" the arguments 'AND,OR,XOR' and 'simple,-MUX' are equivalent.\n");
1546 log("\n");
1547 log(" The default is 'all,-NMUX,-AOI3,-OAI3,-AOI4,-OAI4'.\n");
1548 log("\n");
1549 log(" -dff\n");
1550 log(" also pass $_DFF_?_ and $_DFFE_??_ cells through ABC. modules with many\n");
1551 log(" clock domains are automatically partitioned in clock domains and each\n");
1552 log(" domain is passed through ABC independently.\n");
1553 log("\n");
1554 log(" -clk [!]<clock-signal-name>[,[!]<enable-signal-name>]\n");
1555 log(" use only the specified clock domain. this is like -dff, but only FF\n");
1556 log(" cells that belong to the specified clock domain are used.\n");
1557 log("\n");
1558 log(" -keepff\n");
1559 log(" set the \"keep\" attribute on flip-flop output wires. (and thus preserve\n");
1560 log(" them, for example for equivalence checking.)\n");
1561 log("\n");
1562 log(" -nocleanup\n");
1563 log(" when this option is used, the temporary files created by this pass\n");
1564 log(" are not removed. this is useful for debugging.\n");
1565 log("\n");
1566 log(" -showtmp\n");
1567 log(" print the temp dir name in log. usually this is suppressed so that the\n");
1568 log(" command output is identical across runs.\n");
1569 log("\n");
1570 log(" -markgroups\n");
1571 log(" set a 'abcgroup' attribute on all objects created by ABC. The value of\n");
1572 log(" this attribute is a unique integer for each ABC process started. This\n");
1573 log(" is useful for debugging the partitioning of clock domains.\n");
1574 log("\n");
1575 log(" -dress\n");
1576 log(" run the 'dress' command after all other ABC commands. This aims to\n");
1577 log(" preserve naming by an equivalence check between the original and post-ABC\n");
1578 log(" netlists (experimental).\n");
1579 log("\n");
1580 log("When no target cell library is specified the Yosys standard cell library is\n");
1581 log("loaded into ABC before the ABC script is executed.\n");
1582 log("\n");
1583 log("Note that this is a logic optimization pass within Yosys that is calling ABC\n");
1584 log("internally. This is not going to \"run ABC on your design\". It will instead run\n");
1585 log("ABC on logic snippets extracted from your design. You will not get any useful\n");
1586 log("output when passing an ABC script that writes a file. Instead write your full\n");
1587 log("design as BLIF file with write_blif and then load that into ABC externally if\n");
1588 log("you want to use ABC to convert your design into another format.\n");
1589 log("\n");
1590 log("[1] http://www.eecs.berkeley.edu/~alanmi/abc/\n");
1591 log("\n");
1592 }
1593 void execute(std::vector<std::string> args, RTLIL::Design *design) override
1594 {
1595 log_header(design, "Executing ABC pass (technology mapping using ABC).\n");
1596 log_push();
1597
1598 assign_map.clear();
1599 signal_list.clear();
1600 signal_map.clear();
1601 initvals.clear();
1602 pi_map.clear();
1603 po_map.clear();
1604
1605 std::string exe_file = yosys_abc_executable;
1606 std::string script_file, default_liberty_file, constr_file, clk_str;
1607 std::vector<std::string> liberty_files, genlib_files;
1608 std::string delay_target, sop_inputs, sop_products, lutin_shared = "-S 1";
1609 bool fast_mode = false, dff_mode = false, keepff = false, cleanup = true;
1610 bool show_tempdir = false, sop_mode = false;
1611 bool abc_dress = false;
1612 vector<int> lut_costs;
1613 markgroups = false;
1614
1615 map_mux4 = false;
1616 map_mux8 = false;
1617 map_mux16 = false;
1618 enabled_gates.clear();
1619 cmos_cost = false;
1620
1621 // get arguments from scratchpad first, then override by command arguments
1622 std::string lut_arg, luts_arg, g_arg;
1623 exe_file = design->scratchpad_get_string("abc.exe", exe_file /* inherit default value if not set */);
1624 script_file = design->scratchpad_get_string("abc.script", script_file);
1625 default_liberty_file = design->scratchpad_get_string("abc.liberty", default_liberty_file);
1626 constr_file = design->scratchpad_get_string("abc.constr", constr_file);
1627 if (design->scratchpad.count("abc.D")) {
1628 delay_target = "-D " + design->scratchpad_get_string("abc.D");
1629 }
1630 if (design->scratchpad.count("abc.I")) {
1631 sop_inputs = "-I " + design->scratchpad_get_string("abc.I");
1632 }
1633 if (design->scratchpad.count("abc.P")) {
1634 sop_products = "-P " + design->scratchpad_get_string("abc.P");
1635 }
1636 if (design->scratchpad.count("abc.S")) {
1637 lutin_shared = "-S " + design->scratchpad_get_string("abc.S");
1638 }
1639 lut_arg = design->scratchpad_get_string("abc.lut", lut_arg);
1640 luts_arg = design->scratchpad_get_string("abc.luts", luts_arg);
1641 sop_mode = design->scratchpad_get_bool("abc.sop", sop_mode);
1642 map_mux4 = design->scratchpad_get_bool("abc.mux4", map_mux4);
1643 map_mux8 = design->scratchpad_get_bool("abc.mux8", map_mux8);
1644 map_mux16 = design->scratchpad_get_bool("abc.mux16", map_mux16);
1645 abc_dress = design->scratchpad_get_bool("abc.dress", abc_dress);
1646 g_arg = design->scratchpad_get_string("abc.g", g_arg);
1647
1648 fast_mode = design->scratchpad_get_bool("abc.fast", fast_mode);
1649 dff_mode = design->scratchpad_get_bool("abc.dff", dff_mode);
1650 if (design->scratchpad.count("abc.clk")) {
1651 clk_str = design->scratchpad_get_string("abc.clk");
1652 dff_mode = true;
1653 }
1654 keepff = design->scratchpad_get_bool("abc.keepff", keepff);
1655 cleanup = !design->scratchpad_get_bool("abc.nocleanup", !cleanup);
1656 keepff = design->scratchpad_get_bool("abc.keepff", keepff);
1657 show_tempdir = design->scratchpad_get_bool("abc.showtmp", show_tempdir);
1658 markgroups = design->scratchpad_get_bool("abc.markgroups", markgroups);
1659
1660 if (design->scratchpad_get_bool("abc.debug")) {
1661 cleanup = false;
1662 show_tempdir = true;
1663 }
1664
1665 size_t argidx, g_argidx;
1666 bool g_arg_from_cmd = false;
1667 #if defined(__wasm)
1668 const char *pwd = ".";
1669 #else
1670 char pwd [PATH_MAX];
1671 if (!getcwd(pwd, sizeof(pwd))) {
1672 log_cmd_error("getcwd failed: %s\n", strerror(errno));
1673 log_abort();
1674 }
1675 #endif
1676 for (argidx = 1; argidx < args.size(); argidx++) {
1677 std::string arg = args[argidx];
1678 if (arg == "-exe" && argidx+1 < args.size()) {
1679 exe_file = args[++argidx];
1680 continue;
1681 }
1682 if (arg == "-script" && argidx+1 < args.size()) {
1683 script_file = args[++argidx];
1684 continue;
1685 }
1686 if (arg == "-liberty" && argidx+1 < args.size()) {
1687 liberty_files.push_back(args[++argidx]);
1688 continue;
1689 }
1690 if (arg == "-genlib" && argidx+1 < args.size()) {
1691 genlib_files.push_back(args[++argidx]);
1692 continue;
1693 }
1694 if (arg == "-constr" && argidx+1 < args.size()) {
1695 constr_file = args[++argidx];
1696 continue;
1697 }
1698 if (arg == "-D" && argidx+1 < args.size()) {
1699 delay_target = "-D " + args[++argidx];
1700 continue;
1701 }
1702 if (arg == "-I" && argidx+1 < args.size()) {
1703 sop_inputs = "-I " + args[++argidx];
1704 continue;
1705 }
1706 if (arg == "-P" && argidx+1 < args.size()) {
1707 sop_products = "-P " + args[++argidx];
1708 continue;
1709 }
1710 if (arg == "-S" && argidx+1 < args.size()) {
1711 lutin_shared = "-S " + args[++argidx];
1712 continue;
1713 }
1714 if (arg == "-lut" && argidx+1 < args.size()) {
1715 lut_arg = args[++argidx];
1716 continue;
1717 }
1718 if (arg == "-luts" && argidx+1 < args.size()) {
1719 luts_arg = args[++argidx];
1720 continue;
1721 }
1722 if (arg == "-sop") {
1723 sop_mode = true;
1724 continue;
1725 }
1726 if (arg == "-mux4") {
1727 map_mux4 = true;
1728 continue;
1729 }
1730 if (arg == "-mux8") {
1731 map_mux8 = true;
1732 continue;
1733 }
1734 if (arg == "-mux16") {
1735 map_mux16 = true;
1736 continue;
1737 }
1738 if (arg == "-dress") {
1739 abc_dress = true;
1740 continue;
1741 }
1742 if (arg == "-g" && argidx+1 < args.size()) {
1743 if (g_arg_from_cmd)
1744 log_cmd_error("Can only use -g once. Please combine.");
1745 g_arg = args[++argidx];
1746 g_argidx = argidx;
1747 g_arg_from_cmd = true;
1748 continue;
1749 }
1750 if (arg == "-fast") {
1751 fast_mode = true;
1752 continue;
1753 }
1754 if (arg == "-dff") {
1755 dff_mode = true;
1756 continue;
1757 }
1758 if (arg == "-clk" && argidx+1 < args.size()) {
1759 clk_str = args[++argidx];
1760 dff_mode = true;
1761 continue;
1762 }
1763 if (arg == "-keepff") {
1764 keepff = true;
1765 continue;
1766 }
1767 if (arg == "-nocleanup") {
1768 cleanup = false;
1769 continue;
1770 }
1771 if (arg == "-showtmp") {
1772 show_tempdir = true;
1773 continue;
1774 }
1775 if (arg == "-markgroups") {
1776 markgroups = true;
1777 continue;
1778 }
1779 break;
1780 }
1781 extra_args(args, argidx, design);
1782
1783 if (genlib_files.empty() && liberty_files.empty() && !default_liberty_file.empty())
1784 liberty_files.push_back(default_liberty_file);
1785
1786 rewrite_filename(script_file);
1787 if (!script_file.empty() && !is_absolute_path(script_file) && script_file[0] != '+')
1788 script_file = std::string(pwd) + "/" + script_file;
1789 for (int i = 0; i < GetSize(liberty_files); i++) {
1790 rewrite_filename(liberty_files[i]);
1791 if (!liberty_files[i].empty() && !is_absolute_path(liberty_files[i]))
1792 liberty_files[i] = std::string(pwd) + "/" + liberty_files[i];
1793 }
1794 for (int i = 0; i < GetSize(genlib_files); i++) {
1795 rewrite_filename(genlib_files[i]);
1796 if (!genlib_files[i].empty() && !is_absolute_path(genlib_files[i]))
1797 genlib_files[i] = std::string(pwd) + "/" + genlib_files[i];
1798 }
1799 rewrite_filename(constr_file);
1800 if (!constr_file.empty() && !is_absolute_path(constr_file))
1801 constr_file = std::string(pwd) + "/" + constr_file;
1802
1803 // handle -lut argument
1804 if (!lut_arg.empty()) {
1805 size_t pos = lut_arg.find_first_of(':');
1806 int lut_mode = 0, lut_mode2 = 0;
1807 if (pos != string::npos) {
1808 lut_mode = atoi(lut_arg.substr(0, pos).c_str());
1809 lut_mode2 = atoi(lut_arg.substr(pos+1).c_str());
1810 } else {
1811 lut_mode = atoi(lut_arg.c_str());
1812 lut_mode2 = lut_mode;
1813 }
1814 lut_costs.clear();
1815 for (int i = 0; i < lut_mode; i++)
1816 lut_costs.push_back(1);
1817 for (int i = lut_mode; i < lut_mode2; i++)
1818 lut_costs.push_back(2 << (i - lut_mode));
1819 }
1820 //handle -luts argument
1821 if (!luts_arg.empty()){
1822 lut_costs.clear();
1823 for (auto &tok : split_tokens(luts_arg, ",")) {
1824 auto parts = split_tokens(tok, ":");
1825 if (GetSize(parts) == 0 && !lut_costs.empty())
1826 lut_costs.push_back(lut_costs.back());
1827 else if (GetSize(parts) == 1)
1828 lut_costs.push_back(atoi(parts.at(0).c_str()));
1829 else if (GetSize(parts) == 2)
1830 while (GetSize(lut_costs) < std::atoi(parts.at(0).c_str()))
1831 lut_costs.push_back(atoi(parts.at(1).c_str()));
1832 else
1833 log_cmd_error("Invalid -luts syntax.\n");
1834 }
1835 }
1836
1837 // handle -g argument
1838 if (!g_arg.empty()){
1839 for (auto g : split_tokens(g_arg, ",")) {
1840 vector<string> gate_list;
1841 bool remove_gates = false;
1842 if (GetSize(g) > 0 && g[0] == '-') {
1843 remove_gates = true;
1844 g = g.substr(1);
1845 }
1846 if (g == "AND") goto ok_gate;
1847 if (g == "NAND") goto ok_gate;
1848 if (g == "OR") goto ok_gate;
1849 if (g == "NOR") goto ok_gate;
1850 if (g == "XOR") goto ok_gate;
1851 if (g == "XNOR") goto ok_gate;
1852 if (g == "ANDNOT") goto ok_gate;
1853 if (g == "ORNOT") goto ok_gate;
1854 if (g == "MUX") goto ok_gate;
1855 if (g == "NMUX") goto ok_gate;
1856 if (g == "AOI3") goto ok_gate;
1857 if (g == "OAI3") goto ok_gate;
1858 if (g == "AOI4") goto ok_gate;
1859 if (g == "OAI4") goto ok_gate;
1860 if (g == "simple") {
1861 gate_list.push_back("AND");
1862 gate_list.push_back("OR");
1863 gate_list.push_back("XOR");
1864 gate_list.push_back("MUX");
1865 goto ok_alias;
1866 }
1867 if (g == "cmos2") {
1868 if (!remove_gates)
1869 cmos_cost = true;
1870 gate_list.push_back("NAND");
1871 gate_list.push_back("NOR");
1872 goto ok_alias;
1873 }
1874 if (g == "cmos3") {
1875 if (!remove_gates)
1876 cmos_cost = true;
1877 gate_list.push_back("NAND");
1878 gate_list.push_back("NOR");
1879 gate_list.push_back("AOI3");
1880 gate_list.push_back("OAI3");
1881 goto ok_alias;
1882 }
1883 if (g == "cmos4") {
1884 if (!remove_gates)
1885 cmos_cost = true;
1886 gate_list.push_back("NAND");
1887 gate_list.push_back("NOR");
1888 gate_list.push_back("AOI3");
1889 gate_list.push_back("OAI3");
1890 gate_list.push_back("AOI4");
1891 gate_list.push_back("OAI4");
1892 goto ok_alias;
1893 }
1894 if (g == "cmos") {
1895 if (!remove_gates)
1896 cmos_cost = true;
1897 gate_list.push_back("NAND");
1898 gate_list.push_back("NOR");
1899 gate_list.push_back("AOI3");
1900 gate_list.push_back("OAI3");
1901 gate_list.push_back("AOI4");
1902 gate_list.push_back("OAI4");
1903 gate_list.push_back("NMUX");
1904 gate_list.push_back("MUX");
1905 gate_list.push_back("XOR");
1906 gate_list.push_back("XNOR");
1907 goto ok_alias;
1908 }
1909 if (g == "gates") {
1910 gate_list.push_back("AND");
1911 gate_list.push_back("NAND");
1912 gate_list.push_back("OR");
1913 gate_list.push_back("NOR");
1914 gate_list.push_back("XOR");
1915 gate_list.push_back("XNOR");
1916 gate_list.push_back("ANDNOT");
1917 gate_list.push_back("ORNOT");
1918 goto ok_alias;
1919 }
1920 if (g == "aig") {
1921 gate_list.push_back("AND");
1922 gate_list.push_back("NAND");
1923 gate_list.push_back("OR");
1924 gate_list.push_back("NOR");
1925 gate_list.push_back("ANDNOT");
1926 gate_list.push_back("ORNOT");
1927 goto ok_alias;
1928 }
1929 if (g == "all") {
1930 gate_list.push_back("AND");
1931 gate_list.push_back("NAND");
1932 gate_list.push_back("OR");
1933 gate_list.push_back("NOR");
1934 gate_list.push_back("XOR");
1935 gate_list.push_back("XNOR");
1936 gate_list.push_back("ANDNOT");
1937 gate_list.push_back("ORNOT");
1938 gate_list.push_back("AOI3");
1939 gate_list.push_back("OAI3");
1940 gate_list.push_back("AOI4");
1941 gate_list.push_back("OAI4");
1942 gate_list.push_back("MUX");
1943 gate_list.push_back("NMUX");
1944 goto ok_alias;
1945 }
1946 if (g_arg_from_cmd)
1947 cmd_error(args, g_argidx, stringf("Unsupported gate type: %s", g.c_str()));
1948 else
1949 log_cmd_error("Unsupported gate type: %s", g.c_str());
1950 ok_gate:
1951 gate_list.push_back(g);
1952 ok_alias:
1953 for (auto gate : gate_list) {
1954 if (remove_gates)
1955 enabled_gates.erase(gate);
1956 else
1957 enabled_gates.insert(gate);
1958 }
1959 }
1960 }
1961
1962 if (!lut_costs.empty() && !(liberty_files.empty() && genlib_files.empty()))
1963 log_cmd_error("Got -lut and -liberty/-genlib! These two options are exclusive.\n");
1964 if (!constr_file.empty() && (liberty_files.empty() && genlib_files.empty()))
1965 log_cmd_error("Got -constr but no -liberty/-genlib!\n");
1966
1967 if (enabled_gates.empty()) {
1968 enabled_gates.insert("AND");
1969 enabled_gates.insert("NAND");
1970 enabled_gates.insert("OR");
1971 enabled_gates.insert("NOR");
1972 enabled_gates.insert("XOR");
1973 enabled_gates.insert("XNOR");
1974 enabled_gates.insert("ANDNOT");
1975 enabled_gates.insert("ORNOT");
1976 // enabled_gates.insert("AOI3");
1977 // enabled_gates.insert("OAI3");
1978 // enabled_gates.insert("AOI4");
1979 // enabled_gates.insert("OAI4");
1980 enabled_gates.insert("MUX");
1981 // enabled_gates.insert("NMUX");
1982 }
1983
1984 for (auto mod : design->selected_modules())
1985 {
1986 if (mod->processes.size() > 0) {
1987 log("Skipping module %s as it contains processes.\n", log_id(mod));
1988 continue;
1989 }
1990
1991 assign_map.set(mod);
1992 initvals.set(&assign_map, mod);
1993
1994 if (!dff_mode || !clk_str.empty()) {
1995 abc_module(design, mod, script_file, exe_file, liberty_files, genlib_files, constr_file, cleanup, lut_costs, dff_mode, clk_str, keepff,
1996 delay_target, sop_inputs, sop_products, lutin_shared, fast_mode, mod->selected_cells(), show_tempdir, sop_mode, abc_dress);
1997 continue;
1998 }
1999
2000 CellTypes ct(design);
2001
2002 std::vector<RTLIL::Cell*> all_cells = mod->selected_cells();
2003 pool<RTLIL::Cell*> unassigned_cells(all_cells.begin(), all_cells.end());
2004
2005 pool<RTLIL::Cell*> expand_queue, next_expand_queue;
2006 pool<RTLIL::Cell*> expand_queue_up, next_expand_queue_up;
2007 pool<RTLIL::Cell*> expand_queue_down, next_expand_queue_down;
2008
2009 typedef tuple<bool, RTLIL::SigSpec, bool, RTLIL::SigSpec, bool, RTLIL::SigSpec, bool, RTLIL::SigSpec> clkdomain_t;
2010 dict<clkdomain_t, std::vector<RTLIL::Cell*>> assigned_cells;
2011 dict<RTLIL::Cell*, clkdomain_t> assigned_cells_reverse;
2012
2013 dict<RTLIL::Cell*, pool<RTLIL::SigBit>> cell_to_bit, cell_to_bit_up, cell_to_bit_down;
2014 dict<RTLIL::SigBit, pool<RTLIL::Cell*>> bit_to_cell, bit_to_cell_up, bit_to_cell_down;
2015
2016 for (auto cell : all_cells)
2017 {
2018 clkdomain_t key;
2019
2020 for (auto &conn : cell->connections())
2021 for (auto bit : conn.second) {
2022 bit = assign_map(bit);
2023 if (bit.wire != nullptr) {
2024 cell_to_bit[cell].insert(bit);
2025 bit_to_cell[bit].insert(cell);
2026 if (ct.cell_input(cell->type, conn.first)) {
2027 cell_to_bit_up[cell].insert(bit);
2028 bit_to_cell_down[bit].insert(cell);
2029 }
2030 if (ct.cell_output(cell->type, conn.first)) {
2031 cell_to_bit_down[cell].insert(bit);
2032 bit_to_cell_up[bit].insert(cell);
2033 }
2034 }
2035 }
2036
2037 if (!RTLIL::builtin_ff_cell_types().count(cell->type))
2038 continue;
2039
2040 FfData ff(&initvals, cell);
2041 if (!ff.has_clk)
2042 continue;
2043 if (ff.has_gclk)
2044 continue;
2045 if (ff.has_aload)
2046 continue;
2047 if (ff.has_sr)
2048 continue;
2049 if (!ff.is_fine)
2050 continue;
2051 key = clkdomain_t(
2052 ff.pol_clk,
2053 ff.sig_clk,
2054 ff.has_ce ? ff.pol_ce : true,
2055 ff.has_ce ? assign_map(ff.sig_ce) : RTLIL::SigSpec(),
2056 ff.has_arst ? ff.pol_arst : true,
2057 ff.has_arst ? assign_map(ff.sig_arst) : RTLIL::SigSpec(),
2058 ff.has_srst ? ff.pol_srst : true,
2059 ff.has_srst ? assign_map(ff.sig_srst) : RTLIL::SigSpec()
2060 );
2061
2062 unassigned_cells.erase(cell);
2063 expand_queue.insert(cell);
2064 expand_queue_up.insert(cell);
2065 expand_queue_down.insert(cell);
2066
2067 assigned_cells[key].push_back(cell);
2068 assigned_cells_reverse[cell] = key;
2069 }
2070
2071 while (!expand_queue_up.empty() || !expand_queue_down.empty())
2072 {
2073 if (!expand_queue_up.empty())
2074 {
2075 RTLIL::Cell *cell = *expand_queue_up.begin();
2076 clkdomain_t key = assigned_cells_reverse.at(cell);
2077 expand_queue_up.erase(cell);
2078
2079 for (auto bit : cell_to_bit_up[cell])
2080 for (auto c : bit_to_cell_up[bit])
2081 if (unassigned_cells.count(c)) {
2082 unassigned_cells.erase(c);
2083 next_expand_queue_up.insert(c);
2084 assigned_cells[key].push_back(c);
2085 assigned_cells_reverse[c] = key;
2086 expand_queue.insert(c);
2087 }
2088 }
2089
2090 if (!expand_queue_down.empty())
2091 {
2092 RTLIL::Cell *cell = *expand_queue_down.begin();
2093 clkdomain_t key = assigned_cells_reverse.at(cell);
2094 expand_queue_down.erase(cell);
2095
2096 for (auto bit : cell_to_bit_down[cell])
2097 for (auto c : bit_to_cell_down[bit])
2098 if (unassigned_cells.count(c)) {
2099 unassigned_cells.erase(c);
2100 next_expand_queue_up.insert(c);
2101 assigned_cells[key].push_back(c);
2102 assigned_cells_reverse[c] = key;
2103 expand_queue.insert(c);
2104 }
2105 }
2106
2107 if (expand_queue_up.empty() && expand_queue_down.empty()) {
2108 expand_queue_up.swap(next_expand_queue_up);
2109 expand_queue_down.swap(next_expand_queue_down);
2110 }
2111 }
2112
2113 while (!expand_queue.empty())
2114 {
2115 RTLIL::Cell *cell = *expand_queue.begin();
2116 clkdomain_t key = assigned_cells_reverse.at(cell);
2117 expand_queue.erase(cell);
2118
2119 for (auto bit : cell_to_bit.at(cell)) {
2120 for (auto c : bit_to_cell[bit])
2121 if (unassigned_cells.count(c)) {
2122 unassigned_cells.erase(c);
2123 next_expand_queue.insert(c);
2124 assigned_cells[key].push_back(c);
2125 assigned_cells_reverse[c] = key;
2126 }
2127 bit_to_cell[bit].clear();
2128 }
2129
2130 if (expand_queue.empty())
2131 expand_queue.swap(next_expand_queue);
2132 }
2133
2134 clkdomain_t key(true, RTLIL::SigSpec(), true, RTLIL::SigSpec(), true, RTLIL::SigSpec(), true, RTLIL::SigSpec());
2135 for (auto cell : unassigned_cells) {
2136 assigned_cells[key].push_back(cell);
2137 assigned_cells_reverse[cell] = key;
2138 }
2139
2140 log_header(design, "Summary of detected clock domains:\n");
2141 for (auto &it : assigned_cells)
2142 log(" %d cells in clk=%s%s, en=%s%s, arst=%s%s, srst=%s%s\n", GetSize(it.second),
2143 std::get<0>(it.first) ? "" : "!", log_signal(std::get<1>(it.first)),
2144 std::get<2>(it.first) ? "" : "!", log_signal(std::get<3>(it.first)),
2145 std::get<4>(it.first) ? "" : "!", log_signal(std::get<5>(it.first)),
2146 std::get<6>(it.first) ? "" : "!", log_signal(std::get<7>(it.first)));
2147
2148 for (auto &it : assigned_cells) {
2149 clk_polarity = std::get<0>(it.first);
2150 clk_sig = assign_map(std::get<1>(it.first));
2151 en_polarity = std::get<2>(it.first);
2152 en_sig = assign_map(std::get<3>(it.first));
2153 arst_polarity = std::get<4>(it.first);
2154 arst_sig = assign_map(std::get<5>(it.first));
2155 srst_polarity = std::get<6>(it.first);
2156 srst_sig = assign_map(std::get<7>(it.first));
2157 abc_module(design, mod, script_file, exe_file, liberty_files, genlib_files, constr_file, cleanup, lut_costs, !clk_sig.empty(), "$",
2158 keepff, delay_target, sop_inputs, sop_products, lutin_shared, fast_mode, it.second, show_tempdir, sop_mode, abc_dress);
2159 assign_map.set(mod);
2160 }
2161 }
2162
2163 assign_map.clear();
2164 signal_list.clear();
2165 signal_map.clear();
2166 initvals.clear();
2167 pi_map.clear();
2168 po_map.clear();
2169
2170 log_pop();
2171 }
2172 } AbcPass;
2173
2174 PRIVATE_NAMESPACE_END