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