Renamed port access function on RTLIL::Cell, added param access functions
[yosys.git] / passes / techmap / extract.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 #include "kernel/register.h"
21 #include "kernel/sigtools.h"
22 #include "kernel/log.h"
23 #include "libs/subcircuit/subcircuit.h"
24 #include <algorithm>
25 #include <stdlib.h>
26 #include <stdio.h>
27 #include <string.h>
28
29 using RTLIL::id2cstr;
30
31 namespace
32 {
33 class SubCircuitSolver : public SubCircuit::Solver
34 {
35 public:
36 bool ignore_parameters;
37 std::set<std::pair<std::string, std::string>> ignored_parameters;
38 std::set<RTLIL::IdString> cell_attr, wire_attr;
39
40 SubCircuitSolver() : ignore_parameters(false)
41 {
42 }
43
44 bool compareAttributes(const std::set<RTLIL::IdString> &attr, const std::map<RTLIL::IdString, RTLIL::Const> &needleAttr, const std::map<RTLIL::IdString, RTLIL::Const> &haystackAttr)
45 {
46 for (auto &it : attr) {
47 size_t nc = needleAttr.count(it), hc = haystackAttr.count(it);
48 if (nc != hc || (nc > 0 && needleAttr.at(it) != haystackAttr.at(it)))
49 return false;
50 }
51 return true;
52 }
53
54 RTLIL::Const unified_param(RTLIL::IdString cell_type, RTLIL::IdString param, RTLIL::Const value)
55 {
56 if (cell_type.substr(0, 1) != "$" || cell_type.substr(0, 2) == "$_")
57 return value;
58
59 #define param_bool(_n) if (param == _n) return value.as_bool();
60 param_bool("\\ARST_POLARITY");
61 param_bool("\\A_SIGNED");
62 param_bool("\\B_SIGNED");
63 param_bool("\\CLK_ENABLE");
64 param_bool("\\CLK_POLARITY");
65 param_bool("\\CLR_POLARITY");
66 param_bool("\\EN_POLARITY");
67 param_bool("\\SET_POLARITY");
68 param_bool("\\TRANSPARENT");
69 #undef param_bool
70
71 #define param_int(_n) if (param == _n) return value.as_int();
72 param_int("\\ABITS")
73 param_int("\\A_WIDTH")
74 param_int("\\B_WIDTH")
75 param_int("\\CTRL_IN_WIDTH")
76 param_int("\\CTRL_OUT_WIDTH")
77 param_int("\\OFFSET")
78 param_int("\\PRIORITY")
79 param_int("\\RD_PORTS")
80 param_int("\\SIZE")
81 param_int("\\STATE_BITS")
82 param_int("\\STATE_NUM")
83 param_int("\\STATE_NUM_LOG2")
84 param_int("\\STATE_RST")
85 param_int("\\S_WIDTH")
86 param_int("\\TRANS_NUM")
87 param_int("\\WIDTH")
88 param_int("\\WR_PORTS")
89 param_int("\\Y_WIDTH")
90 #undef param_int
91
92 return value;
93 }
94
95 virtual bool userCompareNodes(const std::string &, const std::string &, void *needleUserData,
96 const std::string &, const std::string &, void *haystackUserData, const std::map<std::string, std::string> &portMapping)
97 {
98 RTLIL::Cell *needleCell = (RTLIL::Cell*) needleUserData;
99 RTLIL::Cell *haystackCell = (RTLIL::Cell*) haystackUserData;
100
101 if (!needleCell || !haystackCell) {
102 log_assert(!needleCell && !haystackCell);
103 return true;
104 }
105
106 if (!ignore_parameters) {
107 std::map<RTLIL::IdString, RTLIL::Const> needle_param, haystack_param;
108 for (auto &it : needleCell->parameters)
109 if (!ignored_parameters.count(std::pair<std::string, std::string>(needleCell->type, it.first)))
110 needle_param[it.first] = unified_param(needleCell->type, it.first, it.second);
111 for (auto &it : haystackCell->parameters)
112 if (!ignored_parameters.count(std::pair<std::string, std::string>(haystackCell->type, it.first)))
113 haystack_param[it.first] = unified_param(haystackCell->type, it.first, it.second);
114 if (needle_param != haystack_param)
115 return false;
116 }
117
118 if (cell_attr.size() > 0 && !compareAttributes(cell_attr, needleCell->attributes, haystackCell->attributes))
119 return false;
120
121 if (wire_attr.size() > 0)
122 {
123 RTLIL::Wire *lastNeedleWire = NULL;
124 RTLIL::Wire *lastHaystackWire = NULL;
125 std::map<RTLIL::IdString, RTLIL::Const> emptyAttr;
126
127 for (auto &conn : needleCell->connections())
128 {
129 RTLIL::SigSpec needleSig = conn.second;
130 RTLIL::SigSpec haystackSig = haystackCell->getPort(portMapping.at(conn.first));
131
132 for (int i = 0; i < std::min(needleSig.size(), haystackSig.size()); i++) {
133 RTLIL::Wire *needleWire = needleSig[i].wire, *haystackWire = haystackSig[i].wire;
134 if (needleWire != lastNeedleWire || haystackWire != lastHaystackWire)
135 if (!compareAttributes(wire_attr, needleWire ? needleWire->attributes : emptyAttr, haystackWire ? haystackWire->attributes : emptyAttr))
136 return false;
137 lastNeedleWire = needleWire, lastHaystackWire = haystackWire;
138 }
139 }
140 }
141
142 return true;
143 }
144 };
145
146 struct bit_ref_t {
147 std::string cell, port;
148 int bit;
149 };
150
151 bool module2graph(SubCircuit::Graph &graph, RTLIL::Module *mod, bool constports, RTLIL::Design *sel = NULL,
152 int max_fanout = -1, std::set<std::pair<RTLIL::IdString, RTLIL::IdString>> *split = NULL)
153 {
154 SigMap sigmap(mod);
155 std::map<RTLIL::SigBit, bit_ref_t> sig_bit_ref;
156
157 if (sel && !sel->selected(mod)) {
158 log(" Skipping module %s as it is not selected.\n", id2cstr(mod->name));
159 return false;
160 }
161
162 if (mod->processes.size() > 0) {
163 log(" Skipping module %s as it contains unprocessed processes.\n", id2cstr(mod->name));
164 return false;
165 }
166
167 if (constports) {
168 graph.createNode("$const$0", "$const$0", NULL, true);
169 graph.createNode("$const$1", "$const$1", NULL, true);
170 graph.createNode("$const$x", "$const$x", NULL, true);
171 graph.createNode("$const$z", "$const$z", NULL, true);
172 graph.createPort("$const$0", "\\Y", 1);
173 graph.createPort("$const$1", "\\Y", 1);
174 graph.createPort("$const$x", "\\Y", 1);
175 graph.createPort("$const$z", "\\Y", 1);
176 graph.markExtern("$const$0", "\\Y", 0);
177 graph.markExtern("$const$1", "\\Y", 0);
178 graph.markExtern("$const$x", "\\Y", 0);
179 graph.markExtern("$const$z", "\\Y", 0);
180 }
181
182 std::map<std::pair<RTLIL::Wire*, int>, int> sig_use_count;
183 if (max_fanout > 0)
184 for (auto &cell_it : mod->cells_)
185 {
186 RTLIL::Cell *cell = cell_it.second;
187 if (!sel || sel->selected(mod, cell))
188 for (auto &conn : cell->connections()) {
189 RTLIL::SigSpec conn_sig = conn.second;
190 sigmap.apply(conn_sig);
191 for (auto &bit : conn_sig)
192 if (bit.wire != NULL)
193 sig_use_count[std::pair<RTLIL::Wire*, int>(bit.wire, bit.offset)]++;
194 }
195 }
196
197 // create graph nodes from cells
198 for (auto &cell_it : mod->cells_)
199 {
200 RTLIL::Cell *cell = cell_it.second;
201 if (sel && !sel->selected(mod, cell))
202 continue;
203
204 std::string type = cell->type;
205 if (sel == NULL && type.substr(0, 2) == "\\$")
206 type = type.substr(1);
207 graph.createNode(cell->name, type, (void*)cell);
208
209 for (auto &conn : cell->connections())
210 {
211 graph.createPort(cell->name, conn.first, conn.second.size());
212
213 if (split && split->count(std::pair<RTLIL::IdString, RTLIL::IdString>(cell->type, conn.first)) > 0)
214 continue;
215
216 RTLIL::SigSpec conn_sig = conn.second;
217 sigmap.apply(conn_sig);
218
219 for (int i = 0; i < conn_sig.size(); i++)
220 {
221 auto &bit = conn_sig[i];
222
223 if (bit.wire == NULL) {
224 if (constports) {
225 std::string node = "$const$x";
226 if (bit == RTLIL::State::S0) node = "$const$0";
227 if (bit == RTLIL::State::S1) node = "$const$1";
228 if (bit == RTLIL::State::Sz) node = "$const$z";
229 graph.createConnection(cell->name, conn.first, i, node, "\\Y", 0);
230 } else
231 graph.createConstant(cell->name, conn.first, i, int(bit.data));
232 continue;
233 }
234
235 if (max_fanout > 0 && sig_use_count[std::pair<RTLIL::Wire*, int>(bit.wire, bit.offset)] > max_fanout)
236 continue;
237
238 if (sel && !sel->selected(mod, bit.wire))
239 continue;
240
241 if (sig_bit_ref.count(bit) == 0) {
242 bit_ref_t &bit_ref = sig_bit_ref[bit];
243 bit_ref.cell = cell->name;
244 bit_ref.port = conn.first;
245 bit_ref.bit = i;
246 }
247
248 bit_ref_t &bit_ref = sig_bit_ref[bit];
249 graph.createConnection(bit_ref.cell, bit_ref.port, bit_ref.bit, cell->name, conn.first, i);
250 }
251 }
252 }
253
254 // mark external signals (used in non-selected cells)
255 for (auto &cell_it : mod->cells_)
256 {
257 RTLIL::Cell *cell = cell_it.second;
258 if (sel && !sel->selected(mod, cell))
259 for (auto &conn : cell->connections())
260 {
261 RTLIL::SigSpec conn_sig = conn.second;
262 sigmap.apply(conn_sig);
263
264 for (auto &bit : conn_sig)
265 if (sig_bit_ref.count(bit) != 0) {
266 bit_ref_t &bit_ref = sig_bit_ref[bit];
267 graph.markExtern(bit_ref.cell, bit_ref.port, bit_ref.bit);
268 }
269 }
270 }
271
272 // mark external signals (used in module ports)
273 for (auto &wire_it : mod->wires_)
274 {
275 RTLIL::Wire *wire = wire_it.second;
276 if (wire->port_id > 0)
277 {
278 RTLIL::SigSpec conn_sig(wire);
279 sigmap.apply(conn_sig);
280
281 for (auto &bit : conn_sig)
282 if (sig_bit_ref.count(bit) != 0) {
283 bit_ref_t &bit_ref = sig_bit_ref[bit];
284 graph.markExtern(bit_ref.cell, bit_ref.port, bit_ref.bit);
285 }
286 }
287 }
288
289 // graph.print();
290 return true;
291 }
292
293 RTLIL::Cell *replace(RTLIL::Module *needle, RTLIL::Module *haystack, SubCircuit::Solver::Result &match)
294 {
295 SigMap sigmap(needle);
296 SigSet<std::pair<std::string, int>> sig2port;
297
298 // create new cell
299 RTLIL::Cell *cell = haystack->addCell(stringf("$extract$%s$%d", needle->name.c_str(), autoidx++), needle->name);
300
301 // create cell ports
302 for (auto &it : needle->wires_) {
303 RTLIL::Wire *wire = it.second;
304 if (wire->port_id > 0) {
305 for (int i = 0; i < wire->width; i++)
306 sig2port.insert(sigmap(RTLIL::SigSpec(wire, i)), std::pair<std::string, int>(wire->name, i));
307 cell->setPort(wire->name, RTLIL::SigSpec(RTLIL::State::Sz, wire->width));
308 }
309 }
310
311 // delete replaced cells and connect new ports
312 for (auto &it : match.mappings)
313 {
314 auto &mapping = it.second;
315 RTLIL::Cell *needle_cell = (RTLIL::Cell*)mapping.needleUserData;
316 RTLIL::Cell *haystack_cell = (RTLIL::Cell*)mapping.haystackUserData;
317
318 if (needle_cell == NULL)
319 continue;
320
321 for (auto &conn : needle_cell->connections()) {
322 RTLIL::SigSpec sig = sigmap(conn.second);
323 if (mapping.portMapping.count(conn.first) > 0 && sig2port.has(sigmap(sig))) {
324 for (int i = 0; i < sig.size(); i++)
325 for (auto &port : sig2port.find(sig[i])) {
326 RTLIL::SigSpec bitsig = haystack_cell->getPort(mapping.portMapping[conn.first]).extract(i, 1);
327 RTLIL::SigSpec new_sig = cell->getPort(port.first);
328 new_sig.replace(port.second, bitsig);
329 cell->setPort(port.first, new_sig);
330 }
331 }
332 }
333
334 haystack->remove(haystack_cell);
335 }
336
337 return cell;
338 }
339
340 bool compareSortNeedleList(RTLIL::Module *left, RTLIL::Module *right)
341 {
342 int left_idx = 0, right_idx = 0;
343 if (left->attributes.count("\\extract_order") > 0)
344 left_idx = left->attributes.at("\\extract_order").as_int();
345 if (right->attributes.count("\\extract_order") > 0)
346 right_idx = right->attributes.at("\\extract_order").as_int();
347 if (left_idx != right_idx)
348 return left_idx < right_idx;
349 return left->name < right->name;
350 }
351 }
352
353 struct ExtractPass : public Pass {
354 ExtractPass() : Pass("extract", "find subcircuits and replace them with cells") { }
355 virtual void help()
356 {
357 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
358 log("\n");
359 log(" extract -map <map_file> [options] [selection]\n");
360 log(" extract -mine <out_file> [options] [selection]\n");
361 log("\n");
362 log("This pass looks for subcircuits that are isomorphic to any of the modules\n");
363 log("in the given map file and replaces them with instances of this modules. The\n");
364 log("map file can be a verilog source file (*.v) or an ilang file (*.il).\n");
365 log("\n");
366 log(" -map <map_file>\n");
367 log(" use the modules in this file as reference. This option can be used\n");
368 log(" multiple times.\n");
369 log("\n");
370 log(" -map %%<design-name>\n");
371 log(" use the modules in this in-memory design as reference. This option can\n");
372 log(" be used multiple times.\n");
373 log("\n");
374 log(" -verbose\n");
375 log(" print debug output while analyzing\n");
376 log("\n");
377 log(" -constports\n");
378 log(" also find instances with constant drivers. this may be much\n");
379 log(" slower than the normal operation.\n");
380 log("\n");
381 log(" -nodefaultswaps\n");
382 log(" normally builtin port swapping rules for internal cells are used per\n");
383 log(" default. This turns that off, so e.g. 'a^b' does not match 'b^a'\n");
384 log(" when this option is used.\n");
385 log("\n");
386 log(" -compat <needle_type> <haystack_type>\n");
387 log(" Per default, the cells in the map file (needle) must have the\n");
388 log(" type as the cells in the active design (haystack). This option\n");
389 log(" can be used to register additional pairs of types that should\n");
390 log(" match. This option can be used multiple times.\n");
391 log("\n");
392 log(" -swap <needle_type> <port1>,<port2>[,...]\n");
393 log(" Register a set of swapable ports for a needle cell type.\n");
394 log(" This option can be used multiple times.\n");
395 log("\n");
396 log(" -perm <needle_type> <port1>,<port2>[,...] <portA>,<portB>[,...]\n");
397 log(" Register a valid permutation of swapable ports for a needle\n");
398 log(" cell type. This option can be used multiple times.\n");
399 log("\n");
400 log(" -cell_attr <attribute_name>\n");
401 log(" Attributes on cells with the given name must match.\n");
402 log("\n");
403 log(" -wire_attr <attribute_name>\n");
404 log(" Attributes on wires with the given name must match.\n");
405 log("\n");
406 log(" -ignore_parameters\n");
407 log(" Do not use parameters when matching cells.\n");
408 log("\n");
409 log(" -ignore_param <cell_type> <parameter_name>\n");
410 log(" Do not use this parameter when matching cells.\n");
411 log("\n");
412 log("This pass does not operate on modules with uprocessed processes in it.\n");
413 log("(I.e. the 'proc' pass should be used first to convert processes to netlists.)\n");
414 log("\n");
415 log("This pass can also be used for mining for frequent subcircuits. In this mode\n");
416 log("the following options are to be used instead of the -map option.\n");
417 log("\n");
418 log(" -mine <out_file>\n");
419 log(" mine for frequent subcircuits and write them to the given ilang file\n");
420 log("\n");
421 log(" -mine_cells_span <min> <max>\n");
422 log(" only mine for subcircuits with the specified number of cells\n");
423 log(" default value: 3 5\n");
424 log("\n");
425 log(" -mine_min_freq <num>\n");
426 log(" only mine for subcircuits with at least the specified number of matches\n");
427 log(" default value: 10\n");
428 log("\n");
429 log(" -mine_limit_matches_per_module <num>\n");
430 log(" when calculating the number of matches for a subcircuit, don't count\n");
431 log(" more than the specified number of matches per module\n");
432 log("\n");
433 log(" -mine_max_fanout <num>\n");
434 log(" don't consider internal signals with more than <num> connections\n");
435 log("\n");
436 log("The modules in the map file may have the attribute 'extract_order' set to an\n");
437 log("integer value. Then this value is used to determine the order in which the pass\n");
438 log("tries to map the modules to the design (ascending, default value is 0).\n");
439 log("\n");
440 log("See 'help techmap' for a pass that does the opposite thing.\n");
441 log("\n");
442 }
443 virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
444 {
445 log_header("Executing EXTRACT pass (map subcircuits to cells).\n");
446 log_push();
447
448 SubCircuitSolver solver;
449
450 std::vector<std::string> map_filenames;
451 std::string mine_outfile;
452 bool constports = false;
453 bool nodefaultswaps = false;
454
455 bool mine_mode = false;
456 int mine_cells_min = 3;
457 int mine_cells_max = 5;
458 int mine_min_freq = 10;
459 int mine_limit_mod = -1;
460 int mine_max_fanout = -1;
461 std::set<std::pair<RTLIL::IdString, RTLIL::IdString>> mine_split;
462
463 size_t argidx;
464 for (argidx = 1; argidx < args.size(); argidx++) {
465 if (args[argidx] == "-map" && argidx+1 < args.size()) {
466 if (mine_mode)
467 log_cmd_error("You cannot mix -map and -mine.\n");
468 map_filenames.push_back(args[++argidx]);
469 continue;
470 }
471 if (args[argidx] == "-mine" && argidx+1 < args.size()) {
472 if (!map_filenames.empty())
473 log_cmd_error("You cannot mix -map and -mine.\n");
474 mine_outfile = args[++argidx];
475 mine_mode = true;
476 continue;
477 }
478 if (args[argidx] == "-mine_cells_span" && argidx+2 < args.size()) {
479 mine_cells_min = atoi(args[++argidx].c_str());
480 mine_cells_max = atoi(args[++argidx].c_str());
481 continue;
482 }
483 if (args[argidx] == "-mine_min_freq" && argidx+1 < args.size()) {
484 mine_min_freq = atoi(args[++argidx].c_str());
485 continue;
486 }
487 if (args[argidx] == "-mine_limit_matches_per_module" && argidx+1 < args.size()) {
488 mine_limit_mod = atoi(args[++argidx].c_str());
489 continue;
490 }
491 if (args[argidx] == "-mine_split" && argidx+2 < args.size()) {
492 mine_split.insert(std::pair<RTLIL::IdString, RTLIL::IdString>(RTLIL::escape_id(args[argidx+1]), RTLIL::escape_id(args[argidx+2])));
493 argidx += 2;
494 continue;
495 }
496 if (args[argidx] == "-mine_max_fanout" && argidx+1 < args.size()) {
497 mine_max_fanout = atoi(args[++argidx].c_str());
498 continue;
499 }
500 if (args[argidx] == "-verbose") {
501 solver.setVerbose();
502 continue;
503 }
504 if (args[argidx] == "-constports") {
505 constports = true;
506 continue;
507 }
508 if (args[argidx] == "-nodefaultswaps") {
509 nodefaultswaps = true;
510 continue;
511 }
512 if (args[argidx] == "-compat" && argidx+2 < args.size()) {
513 std::string needle_type = RTLIL::escape_id(args[++argidx]);
514 std::string haystack_type = RTLIL::escape_id(args[++argidx]);
515 solver.addCompatibleTypes(needle_type, haystack_type);
516 continue;
517 }
518 if (args[argidx] == "-swap" && argidx+2 < args.size()) {
519 std::string type = RTLIL::escape_id(args[++argidx]);
520 std::set<std::string> ports;
521 char *ports_str = strdup(args[++argidx].c_str());
522 for (char *sptr, *p = strtok_r(ports_str, ",\t\r\n ", &sptr); p != NULL; p = strtok_r(NULL, ",\t\r\n ", &sptr))
523 ports.insert(RTLIL::escape_id(p));
524 free(ports_str);
525 solver.addSwappablePorts(type, ports);
526 continue;
527 }
528 if (args[argidx] == "-perm" && argidx+3 < args.size()) {
529 std::string type = RTLIL::escape_id(args[++argidx]);
530 std::vector<std::string> map_left, map_right;
531 char *left_str = strdup(args[++argidx].c_str());
532 char *right_str = strdup(args[++argidx].c_str());
533 for (char *sptr, *p = strtok_r(left_str, ",\t\r\n ", &sptr); p != NULL; p = strtok_r(NULL, ",\t\r\n ", &sptr))
534 map_left.push_back(RTLIL::escape_id(p));
535 for (char *sptr, *p = strtok_r(right_str, ",\t\r\n ", &sptr); p != NULL; p = strtok_r(NULL, ",\t\r\n ", &sptr))
536 map_right.push_back(RTLIL::escape_id(p));
537 free(left_str);
538 free(right_str);
539 if (map_left.size() != map_right.size())
540 log_cmd_error("Arguments to -perm are not a valid permutation!\n");
541 std::map<std::string, std::string> map;
542 for (size_t i = 0; i < map_left.size(); i++)
543 map[map_left[i]] = map_right[i];
544 std::sort(map_left.begin(), map_left.end());
545 std::sort(map_right.begin(), map_right.end());
546 if (map_left != map_right)
547 log_cmd_error("Arguments to -perm are not a valid permutation!\n");
548 solver.addSwappablePortsPermutation(type, map);
549 continue;
550 }
551 if (args[argidx] == "-cell_attr" && argidx+1 < args.size()) {
552 solver.cell_attr.insert(RTLIL::escape_id(args[++argidx]));
553 continue;
554 }
555 if (args[argidx] == "-wire_attr" && argidx+1 < args.size()) {
556 solver.wire_attr.insert(RTLIL::escape_id(args[++argidx]));
557 continue;
558 }
559 if (args[argidx] == "-ignore_parameters") {
560 solver.ignore_parameters = true;
561 continue;
562 }
563 if (args[argidx] == "-ignore_param" && argidx+2 < args.size()) {
564 solver.ignored_parameters.insert(std::pair<std::string, std::string>(RTLIL::escape_id(args[argidx+1]), RTLIL::escape_id(args[argidx+2])));
565 argidx += 2;
566 continue;
567 }
568 break;
569 }
570 extra_args(args, argidx, design);
571
572 if (!nodefaultswaps) {
573 solver.addSwappablePorts("$and", "\\A", "\\B");
574 solver.addSwappablePorts("$or", "\\A", "\\B");
575 solver.addSwappablePorts("$xor", "\\A", "\\B");
576 solver.addSwappablePorts("$xnor", "\\A", "\\B");
577 solver.addSwappablePorts("$eq", "\\A", "\\B");
578 solver.addSwappablePorts("$ne", "\\A", "\\B");
579 solver.addSwappablePorts("$eqx", "\\A", "\\B");
580 solver.addSwappablePorts("$nex", "\\A", "\\B");
581 solver.addSwappablePorts("$add", "\\A", "\\B");
582 solver.addSwappablePorts("$mul", "\\A", "\\B");
583 solver.addSwappablePorts("$logic_and", "\\A", "\\B");
584 solver.addSwappablePorts("$logic_or", "\\A", "\\B");
585 solver.addSwappablePorts("$_AND_", "\\A", "\\B");
586 solver.addSwappablePorts("$_OR_", "\\A", "\\B");
587 solver.addSwappablePorts("$_XOR_", "\\A", "\\B");
588 }
589
590 if (map_filenames.empty() && mine_outfile.empty())
591 log_cmd_error("Missing option -map <verilog_or_ilang_file> or -mine <output_ilang_file>.\n");
592
593 RTLIL::Design *map = NULL;
594
595 if (!mine_mode)
596 {
597 map = new RTLIL::Design;
598 for (auto &filename : map_filenames)
599 {
600 if (filename.substr(0, 1) == "%")
601 {
602 if (!saved_designs.count(filename.substr(1))) {
603 delete map;
604 log_cmd_error("Can't saved design `%s'.\n", filename.c_str()+1);
605 }
606 for (auto mod : saved_designs.at(filename.substr(1))->modules())
607 if (!map->has(mod->name))
608 map->add(mod->clone());
609 }
610 else
611 {
612 FILE *f = fopen(filename.c_str(), "rt");
613 if (f == NULL) {
614 delete map;
615 log_cmd_error("Can't open map file `%s'.\n", filename.c_str());
616 }
617 Frontend::frontend_call(map, f, filename, (filename.size() > 3 && filename.substr(filename.size()-3) == ".il") ? "ilang" : "verilog");
618 fclose(f);
619
620 if (filename.size() <= 3 || filename.substr(filename.size()-3) != ".il") {
621 Pass::call(map, "proc");
622 Pass::call(map, "opt_clean");
623 }
624 }
625 }
626 }
627
628 std::map<std::string, RTLIL::Module*> needle_map, haystack_map;
629 std::vector<RTLIL::Module*> needle_list;
630
631 log_header("Creating graphs for SubCircuit library.\n");
632
633 if (!mine_mode)
634 for (auto &mod_it : map->modules_) {
635 SubCircuit::Graph mod_graph;
636 std::string graph_name = "needle_" + RTLIL::unescape_id(mod_it.first);
637 log("Creating needle graph %s.\n", graph_name.c_str());
638 if (module2graph(mod_graph, mod_it.second, constports)) {
639 solver.addGraph(graph_name, mod_graph);
640 needle_map[graph_name] = mod_it.second;
641 needle_list.push_back(mod_it.second);
642 }
643 }
644
645 for (auto &mod_it : design->modules_) {
646 SubCircuit::Graph mod_graph;
647 std::string graph_name = "haystack_" + RTLIL::unescape_id(mod_it.first);
648 log("Creating haystack graph %s.\n", graph_name.c_str());
649 if (module2graph(mod_graph, mod_it.second, constports, design, mine_mode ? mine_max_fanout : -1, mine_mode ? &mine_split : NULL)) {
650 solver.addGraph(graph_name, mod_graph);
651 haystack_map[graph_name] = mod_it.second;
652 }
653 }
654
655 if (!mine_mode)
656 {
657 std::vector<SubCircuit::Solver::Result> results;
658 log_header("Running solver from SubCircuit library.\n");
659
660 std::sort(needle_list.begin(), needle_list.end(), compareSortNeedleList);
661
662 for (auto needle : needle_list)
663 for (auto &haystack_it : haystack_map) {
664 log("Solving for %s in %s.\n", ("needle_" + RTLIL::unescape_id(needle->name)).c_str(), haystack_it.first.c_str());
665 solver.solve(results, "needle_" + RTLIL::unescape_id(needle->name), haystack_it.first, false);
666 }
667 log("Found %zd matches.\n", results.size());
668
669 if (results.size() > 0)
670 {
671 log_header("Substitute SubCircuits with cells.\n");
672
673 for (int i = 0; i < int(results.size()); i++) {
674 auto &result = results[i];
675 log("\nMatch #%d: (%s in %s)\n", i, result.needleGraphId.c_str(), result.haystackGraphId.c_str());
676 for (const auto &it : result.mappings) {
677 log(" %s -> %s", it.first.c_str(), it.second.haystackNodeId.c_str());
678 for (const auto & it2 : it.second.portMapping)
679 log(" %s:%s", it2.first.c_str(), it2.second.c_str());
680 log("\n");
681 }
682 RTLIL::Cell *new_cell = replace(needle_map.at(result.needleGraphId), haystack_map.at(result.haystackGraphId), result);
683 design->select(haystack_map.at(result.haystackGraphId), new_cell);
684 log(" new cell: %s\n", id2cstr(new_cell->name));
685 }
686 }
687 }
688 else
689 {
690 std::vector<SubCircuit::Solver::MineResult> results;
691
692 log_header("Running miner from SubCircuit library.\n");
693 solver.mine(results, mine_cells_min, mine_cells_max, mine_min_freq, mine_limit_mod);
694
695 map = new RTLIL::Design;
696
697 int needleCounter = 0;
698 for (auto &result: results)
699 {
700 log("\nFrequent SubCircuit with %d nodes and %d matches:\n", int(result.nodes.size()), result.totalMatchesAfterLimits);
701 log(" primary match in %s:", id2cstr(haystack_map.at(result.graphId)->name));
702 for (auto &node : result.nodes)
703 log(" %s", id2cstr(node.nodeId));
704 log("\n");
705 for (auto &it : result.matchesPerGraph)
706 log(" matches in %s: %d\n", id2cstr(haystack_map.at(it.first)->name), it.second);
707
708 RTLIL::Module *mod = haystack_map.at(result.graphId);
709 std::set<RTLIL::Cell*> cells;
710 std::set<RTLIL::Wire*> wires;
711
712 SigMap sigmap(mod);
713
714 for (auto &node : result.nodes)
715 cells.insert((RTLIL::Cell*)node.userData);
716
717 for (auto cell : cells)
718 for (auto &conn : cell->connections()) {
719 RTLIL::SigSpec sig = sigmap(conn.second);
720 for (auto &chunk : sig.chunks())
721 if (chunk.wire != NULL)
722 wires.insert(chunk.wire);
723 }
724
725 RTLIL::Module *newMod = new RTLIL::Module;
726 newMod->name = stringf("\\needle%05d_%s_%dx", needleCounter++, id2cstr(haystack_map.at(result.graphId)->name), result.totalMatchesAfterLimits);
727 map->add(newMod);
728
729 int portCounter = 1;
730 for (auto wire : wires) {
731 RTLIL::Wire *newWire = newMod->addWire(wire->name, wire->width);
732 newWire->port_id = portCounter++;
733 newWire->port_input = true;
734 newWire->port_output = true;
735 }
736
737 for (auto cell : cells) {
738 RTLIL::Cell *newCell = newMod->addCell(cell->name, cell->type);
739 newCell->parameters = cell->parameters;
740 for (auto &conn : cell->connections()) {
741 std::vector<RTLIL::SigChunk> chunks = sigmap(conn.second);
742 for (auto &chunk : chunks)
743 if (chunk.wire != NULL)
744 chunk.wire = newMod->wires_.at(chunk.wire->name);
745 newCell->setPort(conn.first, chunks);
746 }
747 }
748 }
749
750 FILE *f = fopen(mine_outfile.c_str(), "wt");
751 if (f == NULL)
752 log_error("Can't open output file `%s'.\n", mine_outfile.c_str());
753 Backend::backend_call(map, f, mine_outfile, "ilang");
754 fclose(f);
755 }
756
757 delete map;
758 log_pop();
759 }
760 } ExtractPass;
761