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