Get rid of debugging stuff in abc9
[yosys.git] / passes / techmap / abc9.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; strash; &get -n; &dch -f; &nf {D}; &put"
33 #define ABC_COMMAND_CTR "strash; ifraig; scorr; dc2; dretime; strash; &get -n; &dch -f; &nf {D}; &put; buffer; upsize {D}; dnsize {D}; stime -p"
34 #define ABC_COMMAND_LUT "&st; &fraig; &scorr; &dc2; &retime; &dch -f; &if;"/*" &mfs"*/
35 #define ABC_COMMAND_SOP "strash; ifraig; scorr; dc2; dretime; strash; dch -f; cover {I} {P}"
36 #define ABC_COMMAND_DFL "strash; ifraig; scorr; dc2; dretime; strash; &get -n; &dch -f; &nf {D}; &put"
37
38 #define ABC_FAST_COMMAND_LIB "strash; dretime; map {D}"
39 #define ABC_FAST_COMMAND_CTR "strash; dretime; map {D}; buffer; upsize {D}; dnsize {D}; stime -p"
40 #define ABC_FAST_COMMAND_LUT "strash; dretime; if"
41 #define ABC_FAST_COMMAND_SOP "strash; dretime; cover -I {I} -P {P}"
42 #define ABC_FAST_COMMAND_DFL "strash; dretime; map"
43
44 #include "kernel/register.h"
45 #include "kernel/sigtools.h"
46 #include "kernel/celltypes.h"
47 #include "kernel/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/aiger/aigerparse.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 bool map_mux4;
71 bool map_mux8;
72 bool map_mux16;
73
74 bool markgroups;
75 int map_autoidx;
76 SigMap assign_map;
77 RTLIL::Module *module;
78 std::map<RTLIL::SigBit, int> signal_map;
79 std::map<RTLIL::SigBit, RTLIL::State> signal_init;
80 pool<std::string> enabled_gates;
81 bool recover_init;
82
83 bool clk_polarity, en_polarity;
84 RTLIL::SigSpec clk_sig, en_sig;
85 dict<int, std::string> pi_map, po_map;
86
87 std::string remap_name(RTLIL::IdString abc_name)
88 {
89 std::stringstream sstr;
90 sstr << "$abc$" << map_autoidx << "$" << abc_name.substr(1);
91 return sstr.str();
92 }
93
94 void handle_loops(RTLIL::Design *design, RTLIL::Module *module)
95 {
96 design->selection_stack.emplace_back(false);
97 RTLIL::Selection& sel = design->selection_stack.back();
98 sel.select(module);
99 Pass::call(design, "scc -set_attr abc_scc_id {}");
100
101 sel = RTLIL::Selection(false);
102
103 // For every unique SCC found, (arbitrarily) find the first
104 // cell in the component, and select (and mark) all its output
105 // wires
106 pool<RTLIL::Const> ids_seen;
107 for (auto cell : module->cells()) {
108 auto it = cell->attributes.find("\\abc_scc_id");
109 if (it != cell->attributes.end()) {
110 auto r = ids_seen.insert(it->second);
111 if (r.second) {
112 for (const auto &c : cell->connections()) {
113 if (c.second.is_fully_const()) continue;
114 if (cell->output(c.first)) {
115 SigBit b = c.second.as_bit();
116 Wire *w = b.wire;
117 w->set_bool_attribute("\\abc_scc_break");
118 sel.select(module, w);
119 }
120 }
121 }
122 cell->attributes.erase(it);
123 }
124 }
125
126 // Then cut those selected wires to expose them as new PO/PI
127 Pass::call(design, "expose -cut -sep .abc");
128
129 design->selection_stack.pop_back();
130 }
131
132 std::string add_echos_to_abc_cmd(std::string str)
133 {
134 std::string new_str, token;
135 for (size_t i = 0; i < str.size(); i++) {
136 token += str[i];
137 if (str[i] == ';') {
138 while (i+1 < str.size() && str[i+1] == ' ')
139 i++;
140 new_str += "echo + " + token + " " + token + " ";
141 token.clear();
142 }
143 }
144
145 if (!token.empty()) {
146 if (!new_str.empty())
147 new_str += "echo + " + token + "; ";
148 new_str += token;
149 }
150
151 return new_str;
152 }
153
154 std::string fold_abc_cmd(std::string str)
155 {
156 std::string token, new_str = " ";
157 int char_counter = 10;
158
159 for (size_t i = 0; i <= str.size(); i++) {
160 if (i < str.size())
161 token += str[i];
162 if (i == str.size() || str[i] == ';') {
163 if (char_counter + token.size() > 75)
164 new_str += "\n ", char_counter = 14;
165 new_str += token, char_counter += token.size();
166 token.clear();
167 }
168 }
169
170 return new_str;
171 }
172
173 std::string replace_tempdir(std::string text, std::string tempdir_name, bool show_tempdir)
174 {
175 if (show_tempdir)
176 return text;
177
178 while (1) {
179 size_t pos = text.find(tempdir_name);
180 if (pos == std::string::npos)
181 break;
182 text = text.substr(0, pos) + "<abc-temp-dir>" + text.substr(pos + GetSize(tempdir_name));
183 }
184
185 std::string selfdir_name = proc_self_dirname();
186 if (selfdir_name != "/") {
187 while (1) {
188 size_t pos = text.find(selfdir_name);
189 if (pos == std::string::npos)
190 break;
191 text = text.substr(0, pos) + "<yosys-exe-dir>/" + text.substr(pos + GetSize(selfdir_name));
192 }
193 }
194
195 return text;
196 }
197
198 struct abc_output_filter
199 {
200 bool got_cr;
201 int escape_seq_state;
202 std::string linebuf;
203 std::string tempdir_name;
204 bool show_tempdir;
205
206 abc_output_filter(std::string tempdir_name, bool show_tempdir) : tempdir_name(tempdir_name), show_tempdir(show_tempdir)
207 {
208 got_cr = false;
209 escape_seq_state = 0;
210 }
211
212 void next_char(char ch)
213 {
214 if (escape_seq_state == 0 && ch == '\033') {
215 escape_seq_state = 1;
216 return;
217 }
218 if (escape_seq_state == 1) {
219 escape_seq_state = ch == '[' ? 2 : 0;
220 return;
221 }
222 if (escape_seq_state == 2) {
223 if ((ch < '0' || '9' < ch) && ch != ';')
224 escape_seq_state = 0;
225 return;
226 }
227 escape_seq_state = 0;
228 if (ch == '\r') {
229 got_cr = true;
230 return;
231 }
232 if (ch == '\n') {
233 log("ABC: %s\n", replace_tempdir(linebuf, tempdir_name, show_tempdir).c_str());
234 got_cr = false, linebuf.clear();
235 return;
236 }
237 if (got_cr)
238 got_cr = false, linebuf.clear();
239 linebuf += ch;
240 }
241
242 void next_line(const std::string &line)
243 {
244 int pi, po;
245 if (sscanf(line.c_str(), "Start-point = pi%d. End-point = po%d.", &pi, &po) == 2) {
246 log("ABC: Start-point = pi%d (%s). End-point = po%d (%s).\n",
247 pi, pi_map.count(pi) ? pi_map.at(pi).c_str() : "???",
248 po, po_map.count(po) ? po_map.at(po).c_str() : "???");
249 return;
250 }
251
252 for (char ch : line)
253 next_char(ch);
254 }
255 };
256
257 static std::pair<RTLIL::IdString, int> wideports_split(std::string name)
258 {
259 int pos = -1;
260
261 if (name.empty() || name.back() != ']')
262 goto failed;
263
264 for (int i = 0; i+1 < GetSize(name); i++) {
265 if (name[i] == '[')
266 pos = i;
267 else if (name[i] < '0' || name[i] > '9')
268 pos = -1;
269 else if (i == pos+1 && name[i] == '0' && name[i+1] != ']')
270 pos = -1;
271 }
272
273 if (pos >= 0)
274 return std::pair<RTLIL::IdString, int>(RTLIL::escape_id(name.substr(0, pos)), atoi(name.c_str() + pos+1));
275
276 failed:
277 return std::pair<RTLIL::IdString, int>(name, 0);
278 }
279
280 void abc9_module(RTLIL::Design *design, RTLIL::Module *current_module, std::string script_file, std::string exe_file,
281 std::string liberty_file, std::string constr_file, bool cleanup, vector<int> lut_costs, bool dff_mode, std::string clk_str,
282 bool keepff, std::string delay_target, std::string sop_inputs, std::string sop_products, std::string lutin_shared, bool fast_mode,
283 const std::vector<RTLIL::Cell*> &cells, bool show_tempdir, bool sop_mode)
284 {
285 module = current_module;
286 map_autoidx = autoidx++;
287
288 signal_map.clear();
289 pi_map.clear();
290 po_map.clear();
291 recover_init = false;
292
293 if (clk_str != "$")
294 {
295 clk_polarity = true;
296 clk_sig = RTLIL::SigSpec();
297
298 en_polarity = true;
299 en_sig = RTLIL::SigSpec();
300 }
301
302 if (!clk_str.empty() && clk_str != "$")
303 {
304 if (clk_str.find(',') != std::string::npos) {
305 int pos = clk_str.find(',');
306 std::string en_str = clk_str.substr(pos+1);
307 clk_str = clk_str.substr(0, pos);
308 if (en_str[0] == '!') {
309 en_polarity = false;
310 en_str = en_str.substr(1);
311 }
312 if (module->wires_.count(RTLIL::escape_id(en_str)) != 0)
313 en_sig = assign_map(RTLIL::SigSpec(module->wires_.at(RTLIL::escape_id(en_str)), 0));
314 }
315 if (clk_str[0] == '!') {
316 clk_polarity = false;
317 clk_str = clk_str.substr(1);
318 }
319 if (module->wires_.count(RTLIL::escape_id(clk_str)) != 0)
320 clk_sig = assign_map(RTLIL::SigSpec(module->wires_.at(RTLIL::escape_id(clk_str)), 0));
321 }
322
323 if (dff_mode && clk_sig.empty())
324 log_cmd_error("Clock domain %s not found.\n", clk_str.c_str());
325
326 std::string tempdir_name = "/tmp/yosys-abc-XXXXXX";
327 if (!cleanup)
328 tempdir_name[0] = tempdir_name[4] = '_';
329 tempdir_name = make_temp_dir(tempdir_name);
330 log_header(design, "Extracting gate netlist of module `%s' to `%s/input.xaig'..\n",
331 module->name.c_str(), replace_tempdir(tempdir_name, tempdir_name, show_tempdir).c_str());
332
333 std::string abc_script = stringf("&read %s/input.xaig; &ps; ", tempdir_name.c_str());
334
335 if (!liberty_file.empty()) {
336 abc_script += stringf("read_lib -w %s; ", liberty_file.c_str());
337 if (!constr_file.empty())
338 abc_script += stringf("read_constr -v %s; ", constr_file.c_str());
339 } else
340 if (!lut_costs.empty())
341 abc_script += stringf("read_lut %s/lutdefs.txt; ", tempdir_name.c_str());
342 else
343 abc_script += stringf("read_library %s/stdcells.genlib; ", tempdir_name.c_str());
344
345 if (!script_file.empty()) {
346 if (script_file[0] == '+') {
347 for (size_t i = 1; i < script_file.size(); i++)
348 if (script_file[i] == '\'')
349 abc_script += "'\\''";
350 else if (script_file[i] == ',')
351 abc_script += " ";
352 else
353 abc_script += script_file[i];
354 } else
355 abc_script += stringf("source %s", script_file.c_str());
356 } else if (!lut_costs.empty()) {
357 bool all_luts_cost_same = true;
358 for (int this_cost : lut_costs)
359 if (this_cost != lut_costs.front())
360 all_luts_cost_same = false;
361 abc_script += fast_mode ? ABC_FAST_COMMAND_LUT : ABC_COMMAND_LUT;
362 //if (all_luts_cost_same && !fast_mode)
363 // abc_script += "; lutpack {S}";
364 } else if (!liberty_file.empty())
365 abc_script += constr_file.empty() ? (fast_mode ? ABC_FAST_COMMAND_LIB : ABC_COMMAND_LIB) : (fast_mode ? ABC_FAST_COMMAND_CTR : ABC_COMMAND_CTR);
366 else if (sop_mode)
367 abc_script += fast_mode ? ABC_FAST_COMMAND_SOP : ABC_COMMAND_SOP;
368 else
369 abc_script += fast_mode ? ABC_FAST_COMMAND_DFL : ABC_COMMAND_DFL;
370
371 if (script_file.empty() && !delay_target.empty())
372 for (size_t pos = abc_script.find("dretime;"); pos != std::string::npos; pos = abc_script.find("dretime;", pos+1))
373 abc_script = abc_script.substr(0, pos) + "dretime; retime -o {D};" + abc_script.substr(pos+8);
374
375 for (size_t pos = abc_script.find("{D}"); pos != std::string::npos; pos = abc_script.find("{D}", pos))
376 abc_script = abc_script.substr(0, pos) + delay_target + abc_script.substr(pos+3);
377
378 for (size_t pos = abc_script.find("{I}"); pos != std::string::npos; pos = abc_script.find("{D}", pos))
379 abc_script = abc_script.substr(0, pos) + sop_inputs + abc_script.substr(pos+3);
380
381 for (size_t pos = abc_script.find("{P}"); pos != std::string::npos; pos = abc_script.find("{D}", pos))
382 abc_script = abc_script.substr(0, pos) + sop_products + abc_script.substr(pos+3);
383
384 for (size_t pos = abc_script.find("{S}"); pos != std::string::npos; pos = abc_script.find("{S}", pos))
385 abc_script = abc_script.substr(0, pos) + lutin_shared + abc_script.substr(pos+3);
386
387 abc_script += stringf("; &ps; &write %s/output.xaig", tempdir_name.c_str());
388 abc_script = add_echos_to_abc_cmd(abc_script);
389
390 for (size_t i = 0; i+1 < abc_script.size(); i++)
391 if (abc_script[i] == ';' && abc_script[i+1] == ' ')
392 abc_script[i+1] = '\n';
393
394 FILE *f = fopen(stringf("%s/abc.script", tempdir_name.c_str()).c_str(), "wt");
395 fprintf(f, "%s\n", abc_script.c_str());
396 fclose(f);
397
398 if (dff_mode || !clk_str.empty())
399 {
400 if (clk_sig.size() == 0)
401 log("No%s clock domain found. Not extracting any FF cells.\n", clk_str.empty() ? "" : " matching");
402 else {
403 log("Found%s %s clock domain: %s", clk_str.empty() ? "" : " matching", clk_polarity ? "posedge" : "negedge", log_signal(clk_sig));
404 if (en_sig.size() != 0)
405 log(", enabled by %s%s", en_polarity ? "" : "!", log_signal(en_sig));
406 log("\n");
407 }
408 }
409
410 Pass::call(design, "aigmap; clean;");
411
412 handle_loops(design, module);
413
414 Pass::call(design, stringf("write_xaiger -O -map %s/input.symbols %s/input.xaig; ", tempdir_name.c_str(), tempdir_name.c_str()));
415
416 // Now 'unexpose' those wires by undoing
417 // the expose operation -- remove them from PO/PI
418 // and re-connecting them back together
419 for (auto wire : module->wires()) {
420 auto it = wire->attributes.find("\\abc_scc_break");
421 if (it != wire->attributes.end()) {
422 wire->attributes.erase(it);
423 log_assert(wire->port_output);
424 wire->port_output = false;
425 RTLIL::Wire *i_wire = module->wire(wire->name.str() + ".abci");
426 log_assert(i_wire);
427 log_assert(i_wire->port_input);
428 i_wire->port_input = false;
429 module->connect(i_wire, wire);
430 }
431 }
432 module->fixup_ports();
433
434 log_push();
435
436 //if (count_output > 0)
437 {
438 log_header(design, "Executing ABC.\n");
439
440 std::string buffer = stringf("%s/stdcells.genlib", tempdir_name.c_str());
441 f = fopen(buffer.c_str(), "wt");
442 if (f == NULL)
443 log_error("Opening %s for writing failed: %s\n", buffer.c_str(), strerror(errno));
444 fprintf(f, "GATE ZERO 1 Y=CONST0;\n");
445 fprintf(f, "GATE ONE 1 Y=CONST1;\n");
446 fprintf(f, "GATE BUF %d Y=A; PIN * NONINV 1 999 1 0 1 0\n", get_cell_cost("$_BUF_"));
447 fprintf(f, "GATE NOT %d Y=!A; PIN * INV 1 999 1 0 1 0\n", get_cell_cost("$_NOT_"));
448 if (enabled_gates.empty() || enabled_gates.count("AND"))
449 fprintf(f, "GATE AND %d Y=A*B; PIN * NONINV 1 999 1 0 1 0\n", get_cell_cost("$_AND_"));
450 if (enabled_gates.empty() || enabled_gates.count("NAND"))
451 fprintf(f, "GATE NAND %d Y=!(A*B); PIN * INV 1 999 1 0 1 0\n", get_cell_cost("$_NAND_"));
452 if (enabled_gates.empty() || enabled_gates.count("OR"))
453 fprintf(f, "GATE OR %d Y=A+B; PIN * NONINV 1 999 1 0 1 0\n", get_cell_cost("$_OR_"));
454 if (enabled_gates.empty() || enabled_gates.count("NOR"))
455 fprintf(f, "GATE NOR %d Y=!(A+B); PIN * INV 1 999 1 0 1 0\n", get_cell_cost("$_NOR_"));
456 if (enabled_gates.empty() || enabled_gates.count("XOR"))
457 fprintf(f, "GATE XOR %d Y=(A*!B)+(!A*B); PIN * UNKNOWN 1 999 1 0 1 0\n", get_cell_cost("$_XOR_"));
458 if (enabled_gates.empty() || enabled_gates.count("XNOR"))
459 fprintf(f, "GATE XNOR %d Y=(A*B)+(!A*!B); PIN * UNKNOWN 1 999 1 0 1 0\n", get_cell_cost("$_XNOR_"));
460 if (enabled_gates.empty() || enabled_gates.count("ANDNOT"))
461 fprintf(f, "GATE ANDNOT %d Y=A*!B; PIN * UNKNOWN 1 999 1 0 1 0\n", get_cell_cost("$_ANDNOT_"));
462 if (enabled_gates.empty() || enabled_gates.count("ORNOT"))
463 fprintf(f, "GATE ORNOT %d Y=A+!B; PIN * UNKNOWN 1 999 1 0 1 0\n", get_cell_cost("$_ORNOT_"));
464 if (enabled_gates.empty() || enabled_gates.count("AOI3"))
465 fprintf(f, "GATE AOI3 %d Y=!((A*B)+C); PIN * INV 1 999 1 0 1 0\n", get_cell_cost("$_AOI3_"));
466 if (enabled_gates.empty() || enabled_gates.count("OAI3"))
467 fprintf(f, "GATE OAI3 %d Y=!((A+B)*C); PIN * INV 1 999 1 0 1 0\n", get_cell_cost("$_OAI3_"));
468 if (enabled_gates.empty() || enabled_gates.count("AOI4"))
469 fprintf(f, "GATE AOI4 %d Y=!((A*B)+(C*D)); PIN * INV 1 999 1 0 1 0\n", get_cell_cost("$_AOI4_"));
470 if (enabled_gates.empty() || enabled_gates.count("OAI4"))
471 fprintf(f, "GATE OAI4 %d Y=!((A+B)*(C+D)); PIN * INV 1 999 1 0 1 0\n", get_cell_cost("$_OAI4_"));
472 if (enabled_gates.empty() || enabled_gates.count("MUX"))
473 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_"));
474 if (map_mux4)
475 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_"));
476 if (map_mux8)
477 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_"));
478 if (map_mux16)
479 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_"));
480 fclose(f);
481
482 if (!lut_costs.empty()) {
483 buffer = stringf("%s/lutdefs.txt", tempdir_name.c_str());
484 f = fopen(buffer.c_str(), "wt");
485 if (f == NULL)
486 log_error("Opening %s for writing failed: %s\n", buffer.c_str(), strerror(errno));
487 for (int i = 0; i < GetSize(lut_costs); i++)
488 fprintf(f, "%d %d.00 1.00\n", i+1, lut_costs.at(i));
489 fclose(f);
490 }
491
492 buffer = stringf("%s -s -f %s/abc.script 2>&1", exe_file.c_str(), tempdir_name.c_str());
493 log("Running ABC command: %s\n", replace_tempdir(buffer, tempdir_name, show_tempdir).c_str());
494
495 #ifndef YOSYS_LINK_ABC
496 abc_output_filter filt(tempdir_name, show_tempdir);
497 int ret = run_command(buffer, std::bind(&abc_output_filter::next_line, filt, std::placeholders::_1));
498 #else
499 // These needs to be mutable, supposedly due to getopt
500 char *abc_argv[5];
501 string tmp_script_name = stringf("%s/abc.script", tempdir_name.c_str());
502 abc_argv[0] = strdup(exe_file.c_str());
503 abc_argv[1] = strdup("-s");
504 abc_argv[2] = strdup("-f");
505 abc_argv[3] = strdup(tmp_script_name.c_str());
506 abc_argv[4] = 0;
507 int ret = Abc_RealMain(4, abc_argv);
508 free(abc_argv[0]);
509 free(abc_argv[1]);
510 free(abc_argv[2]);
511 free(abc_argv[3]);
512 #endif
513 if (ret != 0)
514 log_error("ABC: execution of command \"%s\" failed: return code %d.\n", buffer.c_str(), ret);
515
516 buffer = stringf("%s/%s", tempdir_name.c_str(), "output.xaig");
517 std::ifstream ifs;
518 ifs.open(buffer);
519 if (ifs.fail())
520 log_error("Can't open ABC output file `%s'.\n", buffer.c_str());
521
522 bool builtin_lib = liberty_file.empty();
523 RTLIL::Design *mapped_design = new RTLIL::Design;
524 //parse_blif(mapped_design, ifs, builtin_lib ? "\\DFF" : "\\_dff_", false, sop_mode);
525 buffer = stringf("%s/%s", tempdir_name.c_str(), "input.symbols");
526 AigerReader reader(mapped_design, ifs, "\\netlist", "\\clk", buffer, true /* wideports */);
527 reader.parse_xaiger();
528
529 ifs.close();
530
531 log_header(design, "Re-integrating ABC results.\n");
532 RTLIL::Module *mapped_mod = mapped_design->modules_["\\netlist"];
533 if (mapped_mod == NULL)
534 log_error("ABC output file does not contain a module `netlist'.\n");
535 pool<RTLIL::SigBit> output_bits;
536 for (auto &it : mapped_mod->wires_) {
537 RTLIL::Wire *w = it.second;
538 RTLIL::Wire *remap_wire = module->addWire(remap_name(w->name), GetSize(w));
539 if (markgroups) remap_wire->attributes["\\abcgroup"] = map_autoidx;
540 design->select(module, remap_wire);
541 if (w->port_output) {
542 RTLIL::Wire *wire = module->wire(w->name);
543 if (wire) {
544 for (int i = 0; i < GetSize(wire); i++)
545 output_bits.insert({wire, i});
546 }
547 else {
548 if (w->name.str() == "\\__dummy_o__") {
549 log("Don't call ABC as there is nothing to map.\n");
550 goto cleanup;
551 }
552
553 auto r = wideports_split(w->name.str());
554 wire = module->wire(r.first);
555 log_assert(wire);
556 int i = r.second;
557 output_bits.insert({wire, i});
558 }
559 }
560 }
561
562 std::map<std::string, int> cell_stats;
563 for (auto c : mapped_mod->cells())
564 {
565 if (builtin_lib)
566 {
567 cell_stats[RTLIL::unescape_id(c->type)]++;
568 if (c->type == "\\ZERO" || c->type == "\\ONE") {
569 RTLIL::SigSig conn;
570 conn.first = RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\Y").as_wire()->name)]);
571 conn.second = RTLIL::SigSpec(c->type == "\\ZERO" ? 0 : 1, 1);
572 module->connect(conn);
573 continue;
574 }
575 if (c->type == "\\BUF") {
576 RTLIL::SigSig conn;
577 conn.first = RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\Y").as_wire()->name)]);
578 conn.second = RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\A").as_wire()->name)]);
579 module->connect(conn);
580 continue;
581 }
582 if (c->type == "\\NOT") {
583 RTLIL::Cell *cell = module->addCell(remap_name(c->name), "$_NOT_");
584 if (markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
585 cell->setPort("\\A", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\A").as_wire()->name)]));
586 cell->setPort("\\Y", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\Y").as_wire()->name)]));
587 design->select(module, cell);
588 continue;
589 }
590 if (c->type == "\\AND" || c->type == "\\OR" || c->type == "\\XOR" || c->type == "\\NAND" || c->type == "\\NOR" ||
591 c->type == "\\XNOR" || c->type == "\\ANDNOT" || c->type == "\\ORNOT") {
592 RTLIL::Cell *cell = module->addCell(remap_name(c->name), "$_" + c->type.substr(1) + "_");
593 if (markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
594 cell->setPort("\\A", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\A").as_wire()->name)]));
595 cell->setPort("\\B", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\B").as_wire()->name)]));
596 cell->setPort("\\Y", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\Y").as_wire()->name)]));
597 design->select(module, cell);
598 continue;
599 }
600 if (c->type == "\\MUX") {
601 RTLIL::Cell *cell = module->addCell(remap_name(c->name), "$_MUX_");
602 if (markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
603 cell->setPort("\\A", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\A").as_wire()->name)]));
604 cell->setPort("\\B", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\B").as_wire()->name)]));
605 cell->setPort("\\S", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\S").as_wire()->name)]));
606 cell->setPort("\\Y", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\Y").as_wire()->name)]));
607 design->select(module, cell);
608 continue;
609 }
610 if (c->type == "\\MUX4") {
611 RTLIL::Cell *cell = module->addCell(remap_name(c->name), "$_MUX4_");
612 if (markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
613 cell->setPort("\\A", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\A").as_wire()->name)]));
614 cell->setPort("\\B", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\B").as_wire()->name)]));
615 cell->setPort("\\C", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\C").as_wire()->name)]));
616 cell->setPort("\\D", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\D").as_wire()->name)]));
617 cell->setPort("\\S", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\S").as_wire()->name)]));
618 cell->setPort("\\T", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\T").as_wire()->name)]));
619 cell->setPort("\\Y", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\Y").as_wire()->name)]));
620 design->select(module, cell);
621 continue;
622 }
623 if (c->type == "\\MUX8") {
624 RTLIL::Cell *cell = module->addCell(remap_name(c->name), "$_MUX8_");
625 if (markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
626 cell->setPort("\\A", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\A").as_wire()->name)]));
627 cell->setPort("\\B", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\B").as_wire()->name)]));
628 cell->setPort("\\C", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\C").as_wire()->name)]));
629 cell->setPort("\\D", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\D").as_wire()->name)]));
630 cell->setPort("\\E", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\E").as_wire()->name)]));
631 cell->setPort("\\F", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\F").as_wire()->name)]));
632 cell->setPort("\\G", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\G").as_wire()->name)]));
633 cell->setPort("\\H", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\H").as_wire()->name)]));
634 cell->setPort("\\S", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\S").as_wire()->name)]));
635 cell->setPort("\\T", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\T").as_wire()->name)]));
636 cell->setPort("\\U", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\U").as_wire()->name)]));
637 cell->setPort("\\Y", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\Y").as_wire()->name)]));
638 design->select(module, cell);
639 continue;
640 }
641 if (c->type == "\\MUX16") {
642 RTLIL::Cell *cell = module->addCell(remap_name(c->name), "$_MUX16_");
643 if (markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
644 cell->setPort("\\A", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\A").as_wire()->name)]));
645 cell->setPort("\\B", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\B").as_wire()->name)]));
646 cell->setPort("\\C", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\C").as_wire()->name)]));
647 cell->setPort("\\D", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\D").as_wire()->name)]));
648 cell->setPort("\\E", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\E").as_wire()->name)]));
649 cell->setPort("\\F", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\F").as_wire()->name)]));
650 cell->setPort("\\G", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\G").as_wire()->name)]));
651 cell->setPort("\\H", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\H").as_wire()->name)]));
652 cell->setPort("\\I", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\I").as_wire()->name)]));
653 cell->setPort("\\J", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\J").as_wire()->name)]));
654 cell->setPort("\\K", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\K").as_wire()->name)]));
655 cell->setPort("\\L", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\L").as_wire()->name)]));
656 cell->setPort("\\M", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\M").as_wire()->name)]));
657 cell->setPort("\\N", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\N").as_wire()->name)]));
658 cell->setPort("\\O", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\O").as_wire()->name)]));
659 cell->setPort("\\P", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\P").as_wire()->name)]));
660 cell->setPort("\\S", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\S").as_wire()->name)]));
661 cell->setPort("\\T", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\T").as_wire()->name)]));
662 cell->setPort("\\U", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\U").as_wire()->name)]));
663 cell->setPort("\\V", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\V").as_wire()->name)]));
664 cell->setPort("\\Y", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\Y").as_wire()->name)]));
665 design->select(module, cell);
666 continue;
667 }
668 if (c->type == "\\AOI3" || c->type == "\\OAI3") {
669 RTLIL::Cell *cell = module->addCell(remap_name(c->name), "$_" + c->type.substr(1) + "_");
670 if (markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
671 cell->setPort("\\A", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\A").as_wire()->name)]));
672 cell->setPort("\\B", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\B").as_wire()->name)]));
673 cell->setPort("\\C", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\C").as_wire()->name)]));
674 cell->setPort("\\Y", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\Y").as_wire()->name)]));
675 design->select(module, cell);
676 continue;
677 }
678 if (c->type == "\\AOI4" || c->type == "\\OAI4") {
679 RTLIL::Cell *cell = module->addCell(remap_name(c->name), "$_" + c->type.substr(1) + "_");
680 if (markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
681 cell->setPort("\\A", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\A").as_wire()->name)]));
682 cell->setPort("\\B", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\B").as_wire()->name)]));
683 cell->setPort("\\C", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\C").as_wire()->name)]));
684 cell->setPort("\\D", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\D").as_wire()->name)]));
685 cell->setPort("\\Y", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\Y").as_wire()->name)]));
686 design->select(module, cell);
687 continue;
688 }
689 if (c->type == "\\DFF") {
690 log_assert(clk_sig.size() == 1);
691 RTLIL::Cell *cell;
692 if (en_sig.size() == 0) {
693 cell = module->addCell(remap_name(c->name), clk_polarity ? "$_DFF_P_" : "$_DFF_N_");
694 } else {
695 log_assert(en_sig.size() == 1);
696 cell = module->addCell(remap_name(c->name), stringf("$_DFFE_%c%c_", clk_polarity ? 'P' : 'N', en_polarity ? 'P' : 'N'));
697 cell->setPort("\\E", en_sig);
698 }
699 if (markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
700 cell->setPort("\\D", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\D").as_wire()->name)]));
701 cell->setPort("\\Q", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\Q").as_wire()->name)]));
702 cell->setPort("\\C", clk_sig);
703 design->select(module, cell);
704 continue;
705 }
706 }
707 else
708 cell_stats[RTLIL::unescape_id(c->type)]++;
709
710 if (c->type == "\\_const0_" || c->type == "\\_const1_") {
711 RTLIL::SigSig conn;
712 conn.first = RTLIL::SigSpec(module->wires_[remap_name(c->connections().begin()->second.as_wire()->name)]);
713 conn.second = RTLIL::SigSpec(c->type == "\\_const0_" ? 0 : 1, 1);
714 module->connect(conn);
715 continue;
716 }
717
718 if (c->type == "\\_dff_") {
719 log_assert(clk_sig.size() == 1);
720 RTLIL::Cell *cell;
721 if (en_sig.size() == 0) {
722 cell = module->addCell(remap_name(c->name), clk_polarity ? "$_DFF_P_" : "$_DFF_N_");
723 } else {
724 log_assert(en_sig.size() == 1);
725 cell = module->addCell(remap_name(c->name), stringf("$_DFFE_%c%c_", clk_polarity ? 'P' : 'N', en_polarity ? 'P' : 'N'));
726 cell->setPort("\\E", en_sig);
727 }
728 if (markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
729 cell->setPort("\\D", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\D").as_wire()->name)]));
730 cell->setPort("\\Q", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\Q").as_wire()->name)]));
731 cell->setPort("\\C", clk_sig);
732 design->select(module, cell);
733 continue;
734 }
735
736 if (c->type == "$lut" && GetSize(c->getPort("\\A")) == 1 && c->getParam("\\LUT").as_int() == 2) {
737 SigSpec my_a = module->wires_[remap_name(c->getPort("\\A").as_wire()->name)];
738 SigSpec my_y = module->wires_[remap_name(c->getPort("\\Y").as_wire()->name)];
739 module->connect(my_y, my_a);
740 continue;
741 }
742
743 RTLIL::Cell *cell = module->addCell(remap_name(c->name), c->type);
744 if (markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
745 cell->parameters = c->parameters;
746 for (auto &conn : c->connections()) {
747 RTLIL::SigSpec newsig;
748 for (auto c : conn.second.chunks()) {
749 if (c.width == 0)
750 continue;
751 //log_assert(c.width == 1);
752 c.wire = module->wires_[remap_name(c.wire->name)];
753 newsig.append(c);
754 }
755 cell->setPort(conn.first, newsig);
756 }
757 design->select(module, cell);
758 }
759
760 // Copy connections (and rename) from mapped_mod to module
761 for (auto conn : mapped_mod->connections()) {
762 if (!conn.first.is_fully_const()) {
763 auto chunks = conn.first.chunks();
764 for (auto &c : chunks)
765 c.wire = module->wires_[remap_name(c.wire->name)];
766 conn.first = std::move(chunks);
767 }
768 if (!conn.second.is_fully_const()) {
769 auto chunks = conn.second.chunks();
770 for (auto &c : chunks)
771 if (c.wire)
772 c.wire = module->wires_[remap_name(c.wire->name)];
773 conn.second = std::move(chunks);
774 }
775 module->connect(conn);
776 }
777
778 if (recover_init)
779 for (auto wire : mapped_mod->wires()) {
780 if (wire->attributes.count("\\init")) {
781 Wire *w = module->wires_[remap_name(wire->name)];
782 log_assert(w->attributes.count("\\init") == 0);
783 w->attributes["\\init"] = wire->attributes.at("\\init");
784 }
785 }
786
787 for (auto &it : cell_stats)
788 log("ABC RESULTS: %15s cells: %8d\n", it.first.c_str(), it.second);
789 int in_wires = 0, out_wires = 0;
790 //for (auto &si : signal_list)
791 // if (si.is_port) {
792 // char buffer[100];
793 // snprintf(buffer, 100, "\\n%d", si.id);
794 // RTLIL::SigSig conn;
795 // if (si.type != G(NONE)) {
796 // conn.first = si.bit;
797 // conn.second = RTLIL::SigSpec(module->wires_[remap_name(buffer)]);
798 // out_wires++;
799 // } else {
800 // conn.first = RTLIL::SigSpec(module->wires_[remap_name(buffer)]);
801 // conn.second = si.bit;
802 // in_wires++;
803 // }
804 // module->connect(conn);
805 // }
806
807 // Go through all cell output connections,
808 // and for those output ports driving wires
809 // also driven by mapped_mod, disconnect them
810 for (auto cell : module->cells()) {
811 for (auto &it : cell->connections_) {
812 auto port_name = it.first;
813 if (!cell->output(port_name)) continue;
814 auto &signal = it.second;
815 if (!signal.is_bit()) continue;
816 if (output_bits.count(signal.as_bit()))
817 signal = module->addWire(NEW_ID);
818 }
819 }
820 // Do the same for module connections
821 for (auto &it : module->connections_) {
822 auto &signal = it.first;
823 if (!signal.is_bit()) continue;
824 if (output_bits.count(signal.as_bit()))
825 signal = module->addWire(NEW_ID);
826 }
827
828 // Stitch in mapped_mod's inputs/outputs into module
829 for (auto &it : mapped_mod->wires_) {
830 RTLIL::Wire *w = it.second;
831 if (!w->port_input && !w->port_output)
832 continue;
833 RTLIL::Wire *wire = module->wire(w->name);
834 RTLIL::Wire *remap_wire = module->wire(remap_name(w->name));
835 RTLIL::SigSpec signal;
836 if (wire) {
837 signal = RTLIL::SigSpec(wire, 0, GetSize(remap_wire));
838 }
839 else {
840 auto r = wideports_split(w->name.str());
841 wire = module->wire(r.first);
842 log_assert(wire);
843 int i = r.second;
844 signal = RTLIL::SigSpec(wire, i);
845 }
846 log_assert(GetSize(signal) >= GetSize(remap_wire));
847
848 if (w->port_input) {
849 RTLIL::SigSig conn;
850 conn.first = remap_wire;
851 conn.second = signal;
852 in_wires++;
853 module->connect(conn);
854 }
855 else if (w->port_output) {
856 RTLIL::SigSig conn;
857 conn.first = signal;
858 conn.second = remap_wire;
859 out_wires++;
860 module->connect(conn);
861 }
862 else log_abort();
863 }
864
865 //log("ABC RESULTS: internal signals: %8d\n", int(signal_list.size()) - in_wires - out_wires);
866 log("ABC RESULTS: input signals: %8d\n", in_wires);
867 log("ABC RESULTS: output signals: %8d\n", out_wires);
868
869 delete mapped_design;
870 }
871 //else
872 //{
873 // log("Don't call ABC as there is nothing to map.\n");
874 //}
875
876 Pass::call(design, "clean");
877
878 cleanup:
879 if (cleanup)
880 {
881 log("Removing temp directory.\n");
882 remove_directory(tempdir_name);
883 }
884
885 log_pop();
886 }
887
888 struct Abc9Pass : public Pass {
889 Abc9Pass() : Pass("abc9", "use ABC for technology mapping") { }
890 void help() YS_OVERRIDE
891 {
892 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
893 log("\n");
894 log(" abc9 [options] [selection]\n");
895 log("\n");
896 log("This pass uses the ABC tool [1] for technology mapping of yosys's internal gate\n");
897 log("library to a target architecture.\n");
898 log("\n");
899 log(" -exe <command>\n");
900 #ifdef ABCEXTERNAL
901 log(" use the specified command instead of \"" ABCEXTERNAL "\" to execute ABC.\n");
902 #else
903 log(" use the specified command instead of \"<yosys-bindir>/yosys-abc\" to execute ABC.\n");
904 #endif
905 log(" This can e.g. be used to call a specific version of ABC or a wrapper.\n");
906 log("\n");
907 log(" -script <file>\n");
908 log(" use the specified ABC script file instead of the default script.\n");
909 log("\n");
910 log(" if <file> starts with a plus sign (+), then the rest of the filename\n");
911 log(" string is interpreted as the command string to be passed to ABC. The\n");
912 log(" leading plus sign is removed and all commas (,) in the string are\n");
913 log(" replaced with blanks before the string is passed to ABC.\n");
914 log("\n");
915 log(" if no -script parameter is given, the following scripts are used:\n");
916 log("\n");
917 log(" for -liberty without -constr:\n");
918 log("%s\n", fold_abc_cmd(ABC_COMMAND_LIB).c_str());
919 log("\n");
920 log(" for -liberty with -constr:\n");
921 log("%s\n", fold_abc_cmd(ABC_COMMAND_CTR).c_str());
922 log("\n");
923 log(" for -lut/-luts (only one LUT size):\n");
924 log("%s\n", fold_abc_cmd(ABC_COMMAND_LUT "; lutpack {S}").c_str());
925 log("\n");
926 log(" for -lut/-luts (different LUT sizes):\n");
927 log("%s\n", fold_abc_cmd(ABC_COMMAND_LUT).c_str());
928 log("\n");
929 log(" for -sop:\n");
930 log("%s\n", fold_abc_cmd(ABC_COMMAND_SOP).c_str());
931 log("\n");
932 log(" otherwise:\n");
933 log("%s\n", fold_abc_cmd(ABC_COMMAND_DFL).c_str());
934 log("\n");
935 log(" -fast\n");
936 log(" use different default scripts that are slightly faster (at the cost\n");
937 log(" of output quality):\n");
938 log("\n");
939 log(" for -liberty without -constr:\n");
940 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_LIB).c_str());
941 log("\n");
942 log(" for -liberty with -constr:\n");
943 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_CTR).c_str());
944 log("\n");
945 log(" for -lut/-luts:\n");
946 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_LUT).c_str());
947 log("\n");
948 log(" for -sop:\n");
949 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_SOP).c_str());
950 log("\n");
951 log(" otherwise:\n");
952 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_DFL).c_str());
953 log("\n");
954 log(" -liberty <file>\n");
955 log(" generate netlists for the specified cell library (using the liberty\n");
956 log(" file format).\n");
957 log("\n");
958 log(" -constr <file>\n");
959 log(" pass this file with timing constraints to ABC. use with -liberty.\n");
960 log("\n");
961 log(" a constr file contains two lines:\n");
962 log(" set_driving_cell <cell_name>\n");
963 log(" set_load <floating_point_number>\n");
964 log("\n");
965 log(" the set_driving_cell statement defines which cell type is assumed to\n");
966 log(" drive the primary inputs and the set_load statement sets the load in\n");
967 log(" femtofarads for each primary output.\n");
968 log("\n");
969 log(" -D <picoseconds>\n");
970 log(" set delay target. the string {D} in the default scripts above is\n");
971 log(" replaced by this option when used, and an empty string otherwise.\n");
972 log(" this also replaces 'dretime' with 'dretime; retime -o {D}' in the\n");
973 log(" default scripts above.\n");
974 log("\n");
975 log(" -I <num>\n");
976 log(" maximum number of SOP inputs.\n");
977 log(" (replaces {I} in the default scripts above)\n");
978 log("\n");
979 log(" -P <num>\n");
980 log(" maximum number of SOP products.\n");
981 log(" (replaces {P} in the default scripts above)\n");
982 log("\n");
983 log(" -S <num>\n");
984 log(" maximum number of LUT inputs shared.\n");
985 log(" (replaces {S} in the default scripts above, default: -S 1)\n");
986 log("\n");
987 log(" -lut <width>\n");
988 log(" generate netlist using luts of (max) the specified width.\n");
989 log("\n");
990 log(" -lut <w1>:<w2>\n");
991 log(" generate netlist using luts of (max) the specified width <w2>. All\n");
992 log(" luts with width <= <w1> have constant cost. for luts larger than <w1>\n");
993 log(" the area cost doubles with each additional input bit. the delay cost\n");
994 log(" is still constant for all lut widths.\n");
995 log("\n");
996 log(" -luts <cost1>,<cost2>,<cost3>,<sizeN>:<cost4-N>,..\n");
997 log(" generate netlist using luts. Use the specified costs for luts with 1,\n");
998 log(" 2, 3, .. inputs.\n");
999 log("\n");
1000 log(" -sop\n");
1001 log(" map to sum-of-product cells and inverters\n");
1002 log("\n");
1003 // log(" -mux4, -mux8, -mux16\n");
1004 // log(" try to extract 4-input, 8-input, and/or 16-input muxes\n");
1005 // log(" (ignored when used with -liberty or -lut)\n");
1006 // log("\n");
1007 log(" -g type1,type2,...\n");
1008 log(" Map to the specified list of gate types. Supported gates types are:\n");
1009 log(" AND, NAND, OR, NOR, XOR, XNOR, ANDNOT, ORNOT, MUX, AOI3, OAI3, AOI4, OAI4.\n");
1010 log(" (The NOT gate is always added to this list automatically.)\n");
1011 log("\n");
1012 log(" The following aliases can be used to reference common sets of gate types:\n");
1013 log(" simple: AND OR XOR MUX\n");
1014 log(" cmos2: NAND NOR\n");
1015 log(" cmos3: NAND NOR AOI3 OAI3\n");
1016 log(" cmos4: NAND NOR AOI3 OAI3 AOI4 OAI4\n");
1017 log(" gates: AND NAND OR NOR XOR XNOR ANDNOT ORNOT\n");
1018 log(" aig: AND NAND OR NOR ANDNOT ORNOT\n");
1019 log("\n");
1020 log(" Prefix a gate type with a '-' to remove it from the list. For example\n");
1021 log(" the arguments 'AND,OR,XOR' and 'simple,-MUX' are equivalent.\n");
1022 log("\n");
1023 log(" -dff\n");
1024 log(" also pass $_DFF_?_ and $_DFFE_??_ cells through ABC. modules with many\n");
1025 log(" clock domains are automatically partitioned in clock domains and each\n");
1026 log(" domain is passed through ABC independently.\n");
1027 log("\n");
1028 log(" -clk [!]<clock-signal-name>[,[!]<enable-signal-name>]\n");
1029 log(" use only the specified clock domain. this is like -dff, but only FF\n");
1030 log(" cells that belong to the specified clock domain are used.\n");
1031 log("\n");
1032 log(" -keepff\n");
1033 log(" set the \"keep\" attribute on flip-flop output wires. (and thus preserve\n");
1034 log(" them, for example for equivalence checking.)\n");
1035 log("\n");
1036 log(" -nocleanup\n");
1037 log(" when this option is used, the temporary files created by this pass\n");
1038 log(" are not removed. this is useful for debugging.\n");
1039 log("\n");
1040 log(" -showtmp\n");
1041 log(" print the temp dir name in log. usually this is suppressed so that the\n");
1042 log(" command output is identical across runs.\n");
1043 log("\n");
1044 log(" -markgroups\n");
1045 log(" set a 'abcgroup' attribute on all objects created by ABC. The value of\n");
1046 log(" this attribute is a unique integer for each ABC process started. This\n");
1047 log(" is useful for debugging the partitioning of clock domains.\n");
1048 log("\n");
1049 log("When neither -liberty nor -lut is used, the Yosys standard cell library is\n");
1050 log("loaded into ABC before the ABC script is executed.\n");
1051 log("\n");
1052 log("Note that this is a logic optimization pass within Yosys that is calling ABC\n");
1053 log("internally. This is not going to \"run ABC on your design\". It will instead run\n");
1054 log("ABC on logic snippets extracted from your design. You will not get any useful\n");
1055 log("output when passing an ABC script that writes a file. Instead write your full\n");
1056 log("design as BLIF file with write_blif and the load that into ABC externally if\n");
1057 log("you want to use ABC to convert your design into another format.\n");
1058 log("\n");
1059 log("[1] http://www.eecs.berkeley.edu/~alanmi/abc/\n");
1060 log("\n");
1061 }
1062 void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
1063 {
1064 log_header(design, "Executing ABC9 pass (technology mapping using ABC).\n");
1065 log_push();
1066
1067 assign_map.clear();
1068 signal_map.clear();
1069 signal_init.clear();
1070 pi_map.clear();
1071 po_map.clear();
1072
1073 #ifdef ABCEXTERNAL
1074 std::string exe_file = ABCEXTERNAL;
1075 #else
1076 std::string exe_file = proc_self_dirname() + "yosys-abc";
1077 #endif
1078 std::string script_file, liberty_file, constr_file, clk_str;
1079 std::string delay_target, sop_inputs, sop_products, lutin_shared = "-S 1";
1080 bool fast_mode = false, dff_mode = false, keepff = false, cleanup = true;
1081 bool show_tempdir = false, sop_mode = false;
1082 show_tempdir = true; cleanup = true;
1083 vector<int> lut_costs;
1084 markgroups = false;
1085
1086 map_mux4 = false;
1087 map_mux8 = false;
1088 map_mux16 = false;
1089 enabled_gates.clear();
1090
1091 #ifdef _WIN32
1092 #ifndef ABCEXTERNAL
1093 if (!check_file_exists(exe_file + ".exe") && check_file_exists(proc_self_dirname() + "..\\yosys-abc.exe"))
1094 exe_file = proc_self_dirname() + "..\\yosys-abc";
1095 #endif
1096 #endif
1097
1098 size_t argidx;
1099 char pwd [PATH_MAX];
1100 if (!getcwd(pwd, sizeof(pwd))) {
1101 log_cmd_error("getcwd failed: %s\n", strerror(errno));
1102 log_abort();
1103 }
1104 for (argidx = 1; argidx < args.size(); argidx++) {
1105 std::string arg = args[argidx];
1106 if (arg == "-exe" && argidx+1 < args.size()) {
1107 exe_file = args[++argidx];
1108 continue;
1109 }
1110 if (arg == "-script" && argidx+1 < args.size()) {
1111 script_file = args[++argidx];
1112 rewrite_filename(script_file);
1113 if (!script_file.empty() && !is_absolute_path(script_file) && script_file[0] != '+')
1114 script_file = std::string(pwd) + "/" + script_file;
1115 continue;
1116 }
1117 if (arg == "-liberty" && argidx+1 < args.size()) {
1118 liberty_file = args[++argidx];
1119 rewrite_filename(liberty_file);
1120 if (!liberty_file.empty() && !is_absolute_path(liberty_file))
1121 liberty_file = std::string(pwd) + "/" + liberty_file;
1122 continue;
1123 }
1124 if (arg == "-constr" && argidx+1 < args.size()) {
1125 rewrite_filename(constr_file);
1126 constr_file = args[++argidx];
1127 if (!constr_file.empty() && !is_absolute_path(constr_file))
1128 constr_file = std::string(pwd) + "/" + constr_file;
1129 continue;
1130 }
1131 if (arg == "-D" && argidx+1 < args.size()) {
1132 delay_target = "-D " + args[++argidx];
1133 continue;
1134 }
1135 if (arg == "-I" && argidx+1 < args.size()) {
1136 sop_inputs = "-I " + args[++argidx];
1137 continue;
1138 }
1139 if (arg == "-P" && argidx+1 < args.size()) {
1140 sop_products = "-P " + args[++argidx];
1141 continue;
1142 }
1143 if (arg == "-S" && argidx+1 < args.size()) {
1144 lutin_shared = "-S " + args[++argidx];
1145 continue;
1146 }
1147 if (arg == "-lut" && argidx+1 < args.size()) {
1148 string arg = args[++argidx];
1149 size_t pos = arg.find_first_of(':');
1150 int lut_mode = 0, lut_mode2 = 0;
1151 if (pos != string::npos) {
1152 lut_mode = atoi(arg.substr(0, pos).c_str());
1153 lut_mode2 = atoi(arg.substr(pos+1).c_str());
1154 } else {
1155 lut_mode = atoi(arg.c_str());
1156 lut_mode2 = lut_mode;
1157 }
1158 lut_costs.clear();
1159 for (int i = 0; i < lut_mode; i++)
1160 lut_costs.push_back(1);
1161 for (int i = lut_mode; i < lut_mode2; i++)
1162 lut_costs.push_back(2 << (i - lut_mode));
1163 continue;
1164 }
1165 if (arg == "-luts" && argidx+1 < args.size()) {
1166 lut_costs.clear();
1167 for (auto &tok : split_tokens(args[++argidx], ",")) {
1168 auto parts = split_tokens(tok, ":");
1169 if (GetSize(parts) == 0 && !lut_costs.empty())
1170 lut_costs.push_back(lut_costs.back());
1171 else if (GetSize(parts) == 1)
1172 lut_costs.push_back(atoi(parts.at(0).c_str()));
1173 else if (GetSize(parts) == 2)
1174 while (GetSize(lut_costs) < atoi(parts.at(0).c_str()))
1175 lut_costs.push_back(atoi(parts.at(1).c_str()));
1176 else
1177 log_cmd_error("Invalid -luts syntax.\n");
1178 }
1179 continue;
1180 }
1181 if (arg == "-sop") {
1182 sop_mode = true;
1183 continue;
1184 }
1185 if (arg == "-mux4") {
1186 map_mux4 = true;
1187 continue;
1188 }
1189 if (arg == "-mux8") {
1190 map_mux8 = true;
1191 continue;
1192 }
1193 if (arg == "-mux16") {
1194 map_mux16 = true;
1195 continue;
1196 }
1197 if (arg == "-g" && argidx+1 < args.size()) {
1198 for (auto g : split_tokens(args[++argidx], ",")) {
1199 vector<string> gate_list;
1200 bool remove_gates = false;
1201 if (GetSize(g) > 0 && g[0] == '-') {
1202 remove_gates = true;
1203 g = g.substr(1);
1204 }
1205 if (g == "AND") goto ok_gate;
1206 if (g == "NAND") goto ok_gate;
1207 if (g == "OR") goto ok_gate;
1208 if (g == "NOR") goto ok_gate;
1209 if (g == "XOR") goto ok_gate;
1210 if (g == "XNOR") goto ok_gate;
1211 if (g == "ANDNOT") goto ok_gate;
1212 if (g == "ORNOT") goto ok_gate;
1213 if (g == "MUX") goto ok_gate;
1214 if (g == "AOI3") goto ok_gate;
1215 if (g == "OAI3") goto ok_gate;
1216 if (g == "AOI4") goto ok_gate;
1217 if (g == "OAI4") goto ok_gate;
1218 if (g == "simple") {
1219 gate_list.push_back("AND");
1220 gate_list.push_back("OR");
1221 gate_list.push_back("XOR");
1222 gate_list.push_back("MUX");
1223 goto ok_alias;
1224 }
1225 if (g == "cmos2") {
1226 gate_list.push_back("NAND");
1227 gate_list.push_back("NOR");
1228 goto ok_alias;
1229 }
1230 if (g == "cmos3") {
1231 gate_list.push_back("NAND");
1232 gate_list.push_back("NOR");
1233 gate_list.push_back("AOI3");
1234 gate_list.push_back("OAI3");
1235 goto ok_alias;
1236 }
1237 if (g == "cmos4") {
1238 gate_list.push_back("NAND");
1239 gate_list.push_back("NOR");
1240 gate_list.push_back("AOI3");
1241 gate_list.push_back("OAI3");
1242 gate_list.push_back("AOI4");
1243 gate_list.push_back("OAI4");
1244 goto ok_alias;
1245 }
1246 if (g == "gates") {
1247 gate_list.push_back("AND");
1248 gate_list.push_back("NAND");
1249 gate_list.push_back("OR");
1250 gate_list.push_back("NOR");
1251 gate_list.push_back("XOR");
1252 gate_list.push_back("XNOR");
1253 gate_list.push_back("ANDNOT");
1254 gate_list.push_back("ORNOT");
1255 goto ok_alias;
1256 }
1257 if (g == "aig") {
1258 gate_list.push_back("AND");
1259 gate_list.push_back("NAND");
1260 gate_list.push_back("OR");
1261 gate_list.push_back("NOR");
1262 gate_list.push_back("ANDNOT");
1263 gate_list.push_back("ORNOT");
1264 goto ok_alias;
1265 }
1266 cmd_error(args, argidx, stringf("Unsupported gate type: %s", g.c_str()));
1267 ok_gate:
1268 gate_list.push_back(g);
1269 ok_alias:
1270 for (auto gate : gate_list) {
1271 if (remove_gates)
1272 enabled_gates.erase(gate);
1273 else
1274 enabled_gates.insert(gate);
1275 }
1276 }
1277 continue;
1278 }
1279 if (arg == "-fast") {
1280 fast_mode = true;
1281 continue;
1282 }
1283 if (arg == "-dff") {
1284 dff_mode = true;
1285 continue;
1286 }
1287 if (arg == "-clk" && argidx+1 < args.size()) {
1288 clk_str = args[++argidx];
1289 dff_mode = true;
1290 continue;
1291 }
1292 if (arg == "-keepff") {
1293 keepff = true;
1294 continue;
1295 }
1296 if (arg == "-nocleanup") {
1297 cleanup = false;
1298 continue;
1299 }
1300 if (arg == "-showtmp") {
1301 show_tempdir = true;
1302 continue;
1303 }
1304 if (arg == "-markgroups") {
1305 markgroups = true;
1306 continue;
1307 }
1308 break;
1309 }
1310 extra_args(args, argidx, design);
1311
1312 if (!lut_costs.empty() && !liberty_file.empty())
1313 log_cmd_error("Got -lut and -liberty! This two options are exclusive.\n");
1314 if (!constr_file.empty() && liberty_file.empty())
1315 log_cmd_error("Got -constr but no -liberty!\n");
1316
1317 for (auto mod : design->selected_modules())
1318 {
1319 if (mod->processes.size() > 0) {
1320 log("Skipping module %s as it contains processes.\n", log_id(mod));
1321 continue;
1322 }
1323
1324 assign_map.set(mod);
1325 signal_init.clear();
1326
1327 for (Wire *wire : mod->wires())
1328 if (wire->attributes.count("\\init")) {
1329 SigSpec initsig = assign_map(wire);
1330 Const initval = wire->attributes.at("\\init");
1331 for (int i = 0; i < GetSize(initsig) && i < GetSize(initval); i++)
1332 switch (initval[i]) {
1333 case State::S0:
1334 signal_init[initsig[i]] = State::S0;
1335 break;
1336 case State::S1:
1337 signal_init[initsig[i]] = State::S0;
1338 break;
1339 default:
1340 break;
1341 }
1342 }
1343
1344 if (!dff_mode || !clk_str.empty()) {
1345 abc9_module(design, mod, script_file, exe_file, liberty_file, constr_file, cleanup, lut_costs, dff_mode, clk_str, keepff,
1346 delay_target, sop_inputs, sop_products, lutin_shared, fast_mode, mod->selected_cells(), show_tempdir, sop_mode);
1347 continue;
1348 }
1349
1350 CellTypes ct(design);
1351
1352 std::vector<RTLIL::Cell*> all_cells = mod->selected_cells();
1353 std::set<RTLIL::Cell*> unassigned_cells(all_cells.begin(), all_cells.end());
1354
1355 std::set<RTLIL::Cell*> expand_queue, next_expand_queue;
1356 std::set<RTLIL::Cell*> expand_queue_up, next_expand_queue_up;
1357 std::set<RTLIL::Cell*> expand_queue_down, next_expand_queue_down;
1358
1359 typedef tuple<bool, RTLIL::SigSpec, bool, RTLIL::SigSpec> clkdomain_t;
1360 std::map<clkdomain_t, std::vector<RTLIL::Cell*>> assigned_cells;
1361 std::map<RTLIL::Cell*, clkdomain_t> assigned_cells_reverse;
1362
1363 std::map<RTLIL::Cell*, std::set<RTLIL::SigBit>> cell_to_bit, cell_to_bit_up, cell_to_bit_down;
1364 std::map<RTLIL::SigBit, std::set<RTLIL::Cell*>> bit_to_cell, bit_to_cell_up, bit_to_cell_down;
1365
1366 for (auto cell : all_cells)
1367 {
1368 clkdomain_t key;
1369
1370 for (auto &conn : cell->connections())
1371 for (auto bit : conn.second) {
1372 bit = assign_map(bit);
1373 if (bit.wire != nullptr) {
1374 cell_to_bit[cell].insert(bit);
1375 bit_to_cell[bit].insert(cell);
1376 if (ct.cell_input(cell->type, conn.first)) {
1377 cell_to_bit_up[cell].insert(bit);
1378 bit_to_cell_down[bit].insert(cell);
1379 }
1380 if (ct.cell_output(cell->type, conn.first)) {
1381 cell_to_bit_down[cell].insert(bit);
1382 bit_to_cell_up[bit].insert(cell);
1383 }
1384 }
1385 }
1386
1387 if (cell->type == "$_DFF_N_" || cell->type == "$_DFF_P_")
1388 {
1389 key = clkdomain_t(cell->type == "$_DFF_P_", assign_map(cell->getPort("\\C")), true, RTLIL::SigSpec());
1390 }
1391 else
1392 if (cell->type == "$_DFFE_NN_" || cell->type == "$_DFFE_NP_" || cell->type == "$_DFFE_PN_" || cell->type == "$_DFFE_PP_")
1393 {
1394 bool this_clk_pol = cell->type == "$_DFFE_PN_" || cell->type == "$_DFFE_PP_";
1395 bool this_en_pol = cell->type == "$_DFFE_NP_" || cell->type == "$_DFFE_PP_";
1396 key = clkdomain_t(this_clk_pol, assign_map(cell->getPort("\\C")), this_en_pol, assign_map(cell->getPort("\\E")));
1397 }
1398 else
1399 continue;
1400
1401 unassigned_cells.erase(cell);
1402 expand_queue.insert(cell);
1403 expand_queue_up.insert(cell);
1404 expand_queue_down.insert(cell);
1405
1406 assigned_cells[key].push_back(cell);
1407 assigned_cells_reverse[cell] = key;
1408 }
1409
1410 while (!expand_queue_up.empty() || !expand_queue_down.empty())
1411 {
1412 if (!expand_queue_up.empty())
1413 {
1414 RTLIL::Cell *cell = *expand_queue_up.begin();
1415 clkdomain_t key = assigned_cells_reverse.at(cell);
1416 expand_queue_up.erase(cell);
1417
1418 for (auto bit : cell_to_bit_up[cell])
1419 for (auto c : bit_to_cell_up[bit])
1420 if (unassigned_cells.count(c)) {
1421 unassigned_cells.erase(c);
1422 next_expand_queue_up.insert(c);
1423 assigned_cells[key].push_back(c);
1424 assigned_cells_reverse[c] = key;
1425 expand_queue.insert(c);
1426 }
1427 }
1428
1429 if (!expand_queue_down.empty())
1430 {
1431 RTLIL::Cell *cell = *expand_queue_down.begin();
1432 clkdomain_t key = assigned_cells_reverse.at(cell);
1433 expand_queue_down.erase(cell);
1434
1435 for (auto bit : cell_to_bit_down[cell])
1436 for (auto c : bit_to_cell_down[bit])
1437 if (unassigned_cells.count(c)) {
1438 unassigned_cells.erase(c);
1439 next_expand_queue_up.insert(c);
1440 assigned_cells[key].push_back(c);
1441 assigned_cells_reverse[c] = key;
1442 expand_queue.insert(c);
1443 }
1444 }
1445
1446 if (expand_queue_up.empty() && expand_queue_down.empty()) {
1447 expand_queue_up.swap(next_expand_queue_up);
1448 expand_queue_down.swap(next_expand_queue_down);
1449 }
1450 }
1451
1452 while (!expand_queue.empty())
1453 {
1454 RTLIL::Cell *cell = *expand_queue.begin();
1455 clkdomain_t key = assigned_cells_reverse.at(cell);
1456 expand_queue.erase(cell);
1457
1458 for (auto bit : cell_to_bit.at(cell)) {
1459 for (auto c : bit_to_cell[bit])
1460 if (unassigned_cells.count(c)) {
1461 unassigned_cells.erase(c);
1462 next_expand_queue.insert(c);
1463 assigned_cells[key].push_back(c);
1464 assigned_cells_reverse[c] = key;
1465 }
1466 bit_to_cell[bit].clear();
1467 }
1468
1469 if (expand_queue.empty())
1470 expand_queue.swap(next_expand_queue);
1471 }
1472
1473 clkdomain_t key(true, RTLIL::SigSpec(), true, RTLIL::SigSpec());
1474 for (auto cell : unassigned_cells) {
1475 assigned_cells[key].push_back(cell);
1476 assigned_cells_reverse[cell] = key;
1477 }
1478
1479 log_header(design, "Summary of detected clock domains:\n");
1480 for (auto &it : assigned_cells)
1481 log(" %d cells in clk=%s%s, en=%s%s\n", GetSize(it.second),
1482 std::get<0>(it.first) ? "" : "!", log_signal(std::get<1>(it.first)),
1483 std::get<2>(it.first) ? "" : "!", log_signal(std::get<3>(it.first)));
1484
1485 for (auto &it : assigned_cells) {
1486 clk_polarity = std::get<0>(it.first);
1487 clk_sig = assign_map(std::get<1>(it.first));
1488 en_polarity = std::get<2>(it.first);
1489 en_sig = assign_map(std::get<3>(it.first));
1490 abc9_module(design, mod, script_file, exe_file, liberty_file, constr_file, cleanup, lut_costs, !clk_sig.empty(), "$",
1491 keepff, delay_target, sop_inputs, sop_products, lutin_shared, fast_mode, it.second, show_tempdir, sop_mode);
1492 assign_map.set(mod);
1493 }
1494 }
1495
1496 assign_map.clear();
1497 signal_map.clear();
1498 signal_init.clear();
1499 pi_map.clear();
1500 po_map.clear();
1501
1502 log_pop();
1503 }
1504 } Abc9Pass;
1505
1506 PRIVATE_NAMESPACE_END