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