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