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