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