equiv_purge bugfix, using SigChunk in Yosys namespace
[yosys.git] / passes / techmap / techmap.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/yosys.h"
21 #include "kernel/utils.h"
22 #include "kernel/sigtools.h"
23 #include "libs/sha1/sha1.h"
24
25 #include <stdlib.h>
26 #include <stdio.h>
27 #include <string.h>
28
29 #include "simplemap.h"
30 #include "passes/techmap/techmap.inc"
31
32 YOSYS_NAMESPACE_BEGIN
33
34 // see maccmap.cc
35 extern void maccmap(RTLIL::Module *module, RTLIL::Cell *cell, bool unmap = false);
36
37 YOSYS_NAMESPACE_END
38
39 USING_YOSYS_NAMESPACE
40 PRIVATE_NAMESPACE_BEGIN
41
42 void apply_prefix(std::string prefix, std::string &id)
43 {
44 if (id[0] == '\\')
45 id = prefix + "." + id.substr(1);
46 else
47 id = "$techmap" + prefix + "." + id;
48 }
49
50 void apply_prefix(std::string prefix, RTLIL::SigSpec &sig, RTLIL::Module *module)
51 {
52 vector<SigChunk> chunks = sig;
53 for (auto &chunk : chunks)
54 if (chunk.wire != NULL) {
55 std::string wire_name = chunk.wire->name.str();
56 apply_prefix(prefix, wire_name);
57 log_assert(module->wires_.count(wire_name) > 0);
58 chunk.wire = module->wires_[wire_name];
59 }
60 sig = chunks;
61 }
62
63 struct TechmapWorker
64 {
65 std::map<RTLIL::IdString, void(*)(RTLIL::Module*, RTLIL::Cell*)> simplemap_mappers;
66 std::map<std::pair<RTLIL::IdString, std::map<RTLIL::IdString, RTLIL::Const>>, RTLIL::Module*> techmap_cache;
67 std::map<RTLIL::Module*, bool> techmap_do_cache;
68 std::set<RTLIL::Module*, RTLIL::IdString::compare_ptr_by_name<RTLIL::Module>> module_queue;
69 dict<Module*, SigMap> sigmaps;
70
71 pool<IdString> flatten_do_list;
72 pool<IdString> flatten_done_list;
73 pool<Cell*> flatten_keep_list;
74
75 struct TechmapWireData {
76 RTLIL::Wire *wire;
77 RTLIL::SigSpec value;
78 };
79
80 typedef std::map<std::string, std::vector<TechmapWireData>> TechmapWires;
81
82 bool extern_mode;
83 bool assert_mode;
84 bool flatten_mode;
85 bool recursive_mode;
86 bool autoproc_mode;
87
88 TechmapWorker()
89 {
90 extern_mode = false;
91 assert_mode = false;
92 flatten_mode = false;
93 recursive_mode = false;
94 autoproc_mode = false;
95 }
96
97 std::string constmap_tpl_name(SigMap &sigmap, RTLIL::Module *tpl, RTLIL::Cell *cell, bool verbose)
98 {
99 std::string constmap_info;
100 std::map<RTLIL::SigBit, std::pair<RTLIL::IdString, int>> connbits_map;
101
102 for (auto conn : cell->connections())
103 for (int i = 0; i < GetSize(conn.second); i++) {
104 RTLIL::SigBit bit = sigmap(conn.second[i]);
105 if (bit.wire == nullptr) {
106 if (verbose)
107 log(" Constant input on bit %d of port %s: %s\n", i, log_id(conn.first), log_signal(bit));
108 constmap_info += stringf("|%s %d %d", log_id(conn.first), i, bit.data);
109 } else if (connbits_map.count(bit)) {
110 if (verbose)
111 log(" Bit %d of port %s and bit %d of port %s are connected.\n", i, log_id(conn.first),
112 connbits_map.at(bit).second, log_id(connbits_map.at(bit).first));
113 constmap_info += stringf("|%s %d %s %d", log_id(conn.first), i,
114 log_id(connbits_map.at(bit).first), connbits_map.at(bit).second);
115 } else {
116 connbits_map[bit] = std::pair<RTLIL::IdString, int>(conn.first, i);
117 constmap_info += stringf("|%s %d", log_id(conn.first), i);
118 }
119 }
120
121 return stringf("$paramod$constmap:%s%s", sha1(constmap_info).c_str(), tpl->name.c_str());
122 }
123
124 TechmapWires techmap_find_special_wires(RTLIL::Module *module)
125 {
126 TechmapWires result;
127
128 if (module == NULL)
129 return result;
130
131 for (auto &it : module->wires_) {
132 const char *p = it.first.c_str();
133 if (*p == '$')
134 continue;
135
136 const char *q = strrchr(p+1, '.');
137 p = q ? q+1 : p+1;
138
139 if (!strncmp(p, "_TECHMAP_", 9)) {
140 TechmapWireData record;
141 record.wire = it.second;
142 record.value = it.second;
143 result[p].push_back(record);
144 it.second->attributes["\\keep"] = RTLIL::Const(1);
145 it.second->attributes["\\_techmap_special_"] = RTLIL::Const(1);
146 }
147 }
148
149 if (!result.empty()) {
150 SigMap sigmap(module);
151 for (auto &it1 : result)
152 for (auto &it2 : it1.second)
153 sigmap.apply(it2.value);
154 }
155
156 return result;
157 }
158
159 void techmap_module_worker(RTLIL::Design *design, RTLIL::Module *module, RTLIL::Cell *cell, RTLIL::Module *tpl)
160 {
161 if (tpl->processes.size() != 0) {
162 log("Technology map yielded processes:");
163 for (auto &it : tpl->processes)
164 log(" %s",RTLIL::id2cstr(it.first));
165 log("\n");
166 if (autoproc_mode) {
167 Pass::call_on_module(tpl->design, tpl, "proc");
168 log_assert(GetSize(tpl->processes) == 0);
169 } else
170 log_error("Technology map yielded processes -> this is not supported (use -autoproc to run 'proc' automatically).\n");
171 }
172
173 std::string orig_cell_name;
174 pool<string> extra_src_attrs;
175
176 if (!flatten_mode)
177 {
178 for (auto &it : tpl->cells_)
179 if (it.first == "\\_TECHMAP_REPLACE_") {
180 orig_cell_name = cell->name.str();
181 module->rename(cell, stringf("$techmap%d", autoidx++) + cell->name.str());
182 break;
183 }
184
185 extra_src_attrs = cell->get_strpool_attribute("\\src");
186 }
187
188 dict<IdString, IdString> memory_renames;
189
190 for (auto &it : tpl->memories) {
191 std::string m_name = it.first.str();
192 apply_prefix(cell->name.str(), m_name);
193 RTLIL::Memory *m = new RTLIL::Memory;
194 m->name = m_name;
195 m->width = it.second->width;
196 m->start_offset = it.second->start_offset;
197 m->size = it.second->size;
198 m->attributes = it.second->attributes;
199 if (m->attributes.count("\\src"))
200 m->add_strpool_attribute("\\src", extra_src_attrs);
201 module->memories[m->name] = m;
202 memory_renames[it.first] = m->name;
203 design->select(module, m);
204 }
205
206 std::map<RTLIL::IdString, RTLIL::IdString> positional_ports;
207
208 for (auto &it : tpl->wires_) {
209 if (it.second->port_id > 0)
210 positional_ports[stringf("$%d", it.second->port_id)] = it.first;
211 std::string w_name = it.second->name.str();
212 apply_prefix(cell->name.str(), w_name);
213 RTLIL::Wire *w = module->addWire(w_name, it.second);
214 w->port_input = false;
215 w->port_output = false;
216 w->port_id = 0;
217 if (it.second->get_bool_attribute("\\_techmap_special_"))
218 w->attributes.clear();
219 if (w->attributes.count("\\src"))
220 w->add_strpool_attribute("\\src", extra_src_attrs);
221 design->select(module, w);
222 }
223
224 SigMap tpl_sigmap(tpl);
225 pool<SigBit> tpl_written_bits;
226
227 for (auto &it1 : tpl->cells_)
228 for (auto &it2 : it1.second->connections_)
229 if (it1.second->output(it2.first))
230 for (auto bit : tpl_sigmap(it2.second))
231 tpl_written_bits.insert(bit);
232 for (auto &it1 : tpl->connections_)
233 for (auto bit : tpl_sigmap(it1.first))
234 tpl_written_bits.insert(bit);
235
236 SigMap port_signal_map;
237
238 for (auto &it : cell->connections()) {
239 RTLIL::IdString portname = it.first;
240 if (positional_ports.count(portname) > 0)
241 portname = positional_ports.at(portname);
242 if (tpl->wires_.count(portname) == 0 || tpl->wires_.at(portname)->port_id == 0) {
243 if (portname.substr(0, 1) == "$")
244 log_error("Can't map port `%s' of cell `%s' to template `%s'!\n", portname.c_str(), cell->name.c_str(), tpl->name.c_str());
245 continue;
246 }
247 RTLIL::Wire *w = tpl->wires_.at(portname);
248 RTLIL::SigSig c;
249 if (w->port_output && !w->port_input) {
250 c.first = it.second;
251 c.second = RTLIL::SigSpec(w);
252 apply_prefix(cell->name.str(), c.second, module);
253 } else if (!w->port_output && w->port_input) {
254 c.first = RTLIL::SigSpec(w);
255 c.second = it.second;
256 apply_prefix(cell->name.str(), c.first, module);
257 } else {
258 SigSpec sig_tpl = w, sig_tpl_pf = w, sig_mod = it.second;
259 apply_prefix(cell->name.str(), sig_tpl_pf, module);
260 for (int i = 0; i < GetSize(sig_tpl) && i < GetSize(sig_mod); i++) {
261 if (tpl_written_bits.count(tpl_sigmap(sig_tpl[i]))) {
262 c.first.append(sig_mod[i]);
263 c.second.append(sig_tpl_pf[i]);
264 } else {
265 c.first.append(sig_tpl_pf[i]);
266 c.second.append(sig_mod[i]);
267 }
268 }
269 }
270 if (c.second.size() > c.first.size())
271 c.second.remove(c.first.size(), c.second.size() - c.first.size());
272 if (c.second.size() < c.first.size())
273 c.second.append(RTLIL::SigSpec(RTLIL::State::S0, c.first.size() - c.second.size()));
274 log_assert(c.first.size() == c.second.size());
275 if (flatten_mode) {
276 // more conservative approach:
277 // connect internal and external wires
278 if (sigmaps.count(module) == 0)
279 sigmaps[module].set(module);
280 if (sigmaps.at(module)(c.first).has_const())
281 log_error("Mismatch in directionality for cell port %s.%s.%s: %s <= %s\n",
282 log_id(module), log_id(cell), log_id(it.first), log_signal(c.first), log_signal(c.second));
283 module->connect(c);
284 } else {
285 // approach that yields nicer outputs:
286 // replace internal wires that are connected to external wires
287 if (w->port_output)
288 port_signal_map.add(c.second, c.first);
289 else
290 port_signal_map.add(c.first, c.second);
291 }
292 }
293
294 for (auto &it : tpl->cells_)
295 {
296 std::string c_name = it.second->name.str();
297
298 if (!flatten_mode && c_name == "\\_TECHMAP_REPLACE_")
299 c_name = orig_cell_name;
300 else
301 apply_prefix(cell->name.str(), c_name);
302
303 RTLIL::Cell *c = module->addCell(c_name, it.second);
304 design->select(module, c);
305
306 if (!flatten_mode && c->type.substr(0, 2) == "\\$")
307 c->type = c->type.substr(1);
308
309 for (auto &it2 : c->connections_) {
310 apply_prefix(cell->name.str(), it2.second, module);
311 port_signal_map.apply(it2.second);
312 }
313
314 if (c->type == "$memrd" || c->type == "$memwr" || c->type == "$meminit") {
315 IdString memid = c->getParam("\\MEMID").decode_string();
316 log_assert(memory_renames.count(memid));
317 c->setParam("\\MEMID", Const(memory_renames[memid].str()));
318 }
319
320 if (c->attributes.count("\\src"))
321 c->add_strpool_attribute("\\src", extra_src_attrs);
322 }
323
324 for (auto &it : tpl->connections()) {
325 RTLIL::SigSig c = it;
326 apply_prefix(cell->name.str(), c.first, module);
327 apply_prefix(cell->name.str(), c.second, module);
328 port_signal_map.apply(c.first);
329 port_signal_map.apply(c.second);
330 module->connect(c);
331 }
332
333 module->remove(cell);
334 }
335
336 bool techmap_module(RTLIL::Design *design, RTLIL::Module *module, RTLIL::Design *map, std::set<RTLIL::Cell*> &handled_cells,
337 const std::map<RTLIL::IdString, std::set<RTLIL::IdString, RTLIL::sort_by_id_str>> &celltypeMap, bool in_recursion)
338 {
339 std::string mapmsg_prefix = in_recursion ? "Recursively mapping" : "Mapping";
340
341 if (!design->selected(module))
342 return false;
343
344 bool log_continue = false;
345 bool did_something = false;
346
347 SigMap sigmap(module);
348
349 TopoSort<RTLIL::Cell*, RTLIL::IdString::compare_ptr_by_name<RTLIL::Cell>> cells;
350 std::map<RTLIL::Cell*, std::set<RTLIL::SigBit>> cell_to_inbit;
351 std::map<RTLIL::SigBit, std::set<RTLIL::Cell*>> outbit_to_cell;
352
353 for (auto cell : module->cells())
354 {
355 if (!design->selected(module, cell) || handled_cells.count(cell) > 0)
356 continue;
357
358 std::string cell_type = cell->type.str();
359 if (in_recursion && cell_type.substr(0, 2) == "\\$")
360 cell_type = cell_type.substr(1);
361
362 if (celltypeMap.count(cell_type) == 0) {
363 if (assert_mode && cell_type.back() != '_')
364 log_error("(ASSERT MODE) No matching template cell for type %s found.\n", log_id(cell_type));
365 continue;
366 }
367
368 if (flatten_mode) {
369 bool keepit = cell->get_bool_attribute("\\keep_hierarchy");
370 for (auto &tpl_name : celltypeMap.at(cell_type))
371 if (map->modules_[tpl_name]->get_bool_attribute("\\keep_hierarchy"))
372 keepit = true;
373 if (keepit) {
374 if (!flatten_keep_list[cell]) {
375 log("Keeping %s.%s (found keep_hierarchy property).\n", log_id(module), log_id(cell));
376 flatten_keep_list.insert(cell);
377 }
378 if (!flatten_done_list[cell->type])
379 flatten_do_list.insert(cell->type);
380 continue;
381 }
382 }
383
384 for (auto &conn : cell->connections())
385 {
386 RTLIL::SigSpec sig = sigmap(conn.second);
387 sig.remove_const();
388
389 if (GetSize(sig) == 0)
390 continue;
391
392 for (auto &tpl_name : celltypeMap.at(cell_type)) {
393 RTLIL::Module *tpl = map->modules_[tpl_name];
394 RTLIL::Wire *port = tpl->wire(conn.first);
395 if (port && port->port_input)
396 cell_to_inbit[cell].insert(sig.begin(), sig.end());
397 if (port && port->port_output)
398 for (auto &bit : sig)
399 outbit_to_cell[bit].insert(cell);
400 }
401 }
402
403 cells.node(cell);
404 }
405
406 for (auto &it_right : cell_to_inbit)
407 for (auto &it_sigbit : it_right.second)
408 for (auto &it_left : outbit_to_cell[it_sigbit])
409 cells.edge(it_left, it_right.first);
410
411 cells.sort();
412
413 for (auto cell : cells.sorted)
414 {
415 log_assert(handled_cells.count(cell) == 0);
416 log_assert(cell == module->cell(cell->name));
417 bool mapped_cell = false;
418
419 std::string cell_type = cell->type.str();
420 if (in_recursion && cell_type.substr(0, 2) == "\\$")
421 cell_type = cell_type.substr(1);
422
423 for (auto &tpl_name : celltypeMap.at(cell_type))
424 {
425 RTLIL::IdString derived_name = tpl_name;
426 RTLIL::Module *tpl = map->modules_[tpl_name];
427 std::map<RTLIL::IdString, RTLIL::Const> parameters(cell->parameters.begin(), cell->parameters.end());
428
429 if (tpl->get_bool_attribute("\\blackbox"))
430 continue;
431
432 if (!flatten_mode)
433 {
434 std::string extmapper_name;
435
436 if (tpl->get_bool_attribute("\\techmap_simplemap"))
437 extmapper_name = "simplemap";
438
439 if (tpl->get_bool_attribute("\\techmap_maccmap"))
440 extmapper_name = "maccmap";
441
442 if (tpl->attributes.count("\\techmap_wrap"))
443 extmapper_name = "wrap";
444
445 if (!extmapper_name.empty())
446 {
447 cell->type = cell_type;
448
449 if ((extern_mode && !in_recursion) || extmapper_name == "wrap")
450 {
451 std::string m_name = stringf("$extern:%s:%s", extmapper_name.c_str(), log_id(cell->type));
452
453 for (auto &c : cell->parameters)
454 m_name += stringf(":%s=%s", log_id(c.first), log_signal(c.second));
455
456 if (extmapper_name == "wrap")
457 m_name += ":" + sha1(tpl->attributes.at("\\techmap_wrap").decode_string());
458
459 RTLIL::Design *extmapper_design = extern_mode && !in_recursion ? design : tpl->design;
460 RTLIL::Module *extmapper_module = extmapper_design->module(m_name);
461
462 if (extmapper_module == nullptr)
463 {
464 extmapper_module = extmapper_design->addModule(m_name);
465 RTLIL::Cell *extmapper_cell = extmapper_module->addCell(cell->type, cell);
466
467 int port_counter = 1;
468 for (auto &c : extmapper_cell->connections_) {
469 RTLIL::Wire *w = extmapper_module->addWire(c.first, GetSize(c.second));
470 if (w->name == "\\Y" || w->name == "\\Q")
471 w->port_output = true;
472 else
473 w->port_input = true;
474 w->port_id = port_counter++;
475 c.second = w;
476 }
477
478 extmapper_module->fixup_ports();
479 extmapper_module->check();
480
481 if (extmapper_name == "simplemap") {
482 log("Creating %s with simplemap.\n", log_id(extmapper_module));
483 if (simplemap_mappers.count(extmapper_cell->type) == 0)
484 log_error("No simplemap mapper for cell type %s found!\n", log_id(extmapper_cell->type));
485 simplemap_mappers.at(extmapper_cell->type)(extmapper_module, extmapper_cell);
486 extmapper_module->remove(extmapper_cell);
487 }
488
489 if (extmapper_name == "maccmap") {
490 log("Creating %s with maccmap.\n", log_id(extmapper_module));
491 if (extmapper_cell->type != "$macc")
492 log_error("The maccmap mapper can only map $macc (not %s) cells!\n", log_id(extmapper_cell->type));
493 maccmap(extmapper_module, extmapper_cell);
494 extmapper_module->remove(extmapper_cell);
495 }
496
497 if (extmapper_name == "wrap") {
498 std::string cmd_string = tpl->attributes.at("\\techmap_wrap").decode_string();
499 log("Running \"%s\" on wrapper %s.\n", cmd_string.c_str(), log_id(extmapper_module));
500 Pass::call_on_module(extmapper_design, extmapper_module, cmd_string);
501 log_continue = true;
502 }
503 }
504
505 cell->type = extmapper_module->name;
506 cell->parameters.clear();
507
508 if (!extern_mode || in_recursion) {
509 tpl = extmapper_module;
510 goto use_wrapper_tpl;
511 }
512
513 log("%s %s.%s (%s) to %s.\n", mapmsg_prefix.c_str(), log_id(module), log_id(cell), log_id(cell->type), log_id(extmapper_module));
514 }
515 else
516 {
517 log("%s %s.%s (%s) with %s.\n", mapmsg_prefix.c_str(), log_id(module), log_id(cell), log_id(cell->type), extmapper_name.c_str());
518
519 if (extmapper_name == "simplemap") {
520 if (simplemap_mappers.count(cell->type) == 0)
521 log_error("No simplemap mapper for cell type %s found!\n", RTLIL::id2cstr(cell->type));
522 simplemap_mappers.at(cell->type)(module, cell);
523 }
524
525 if (extmapper_name == "maccmap") {
526 if (cell->type != "$macc")
527 log_error("The maccmap mapper can only map $macc (not %s) cells!\n", log_id(cell->type));
528 maccmap(module, cell);
529 }
530
531 module->remove(cell);
532 cell = NULL;
533 }
534
535 did_something = true;
536 mapped_cell = true;
537 break;
538 }
539
540 for (auto conn : cell->connections()) {
541 if (conn.first.substr(0, 1) == "$")
542 continue;
543 if (tpl->wires_.count(conn.first) > 0 && tpl->wires_.at(conn.first)->port_id > 0)
544 continue;
545 if (!conn.second.is_fully_const() || parameters.count(conn.first) > 0 || tpl->avail_parameters.count(conn.first) == 0)
546 goto next_tpl;
547 parameters[conn.first] = conn.second.as_const();
548 }
549
550 if (0) {
551 next_tpl:
552 continue;
553 }
554
555 if (tpl->avail_parameters.count("\\_TECHMAP_CELLTYPE_") != 0)
556 parameters["\\_TECHMAP_CELLTYPE_"] = RTLIL::unescape_id(cell->type);
557
558 for (auto conn : cell->connections()) {
559 if (tpl->avail_parameters.count(stringf("\\_TECHMAP_CONSTMSK_%s_", RTLIL::id2cstr(conn.first))) != 0) {
560 std::vector<RTLIL::SigBit> v = sigmap(conn.second).to_sigbit_vector();
561 for (auto &bit : v)
562 bit = RTLIL::SigBit(bit.wire == NULL ? RTLIL::State::S1 : RTLIL::State::S0);
563 parameters[stringf("\\_TECHMAP_CONSTMSK_%s_", RTLIL::id2cstr(conn.first))] = RTLIL::SigSpec(v).as_const();
564 }
565 if (tpl->avail_parameters.count(stringf("\\_TECHMAP_CONSTVAL_%s_", RTLIL::id2cstr(conn.first))) != 0) {
566 std::vector<RTLIL::SigBit> v = sigmap(conn.second).to_sigbit_vector();
567 for (auto &bit : v)
568 if (bit.wire != NULL)
569 bit = RTLIL::SigBit(RTLIL::State::Sx);
570 parameters[stringf("\\_TECHMAP_CONSTVAL_%s_", RTLIL::id2cstr(conn.first))] = RTLIL::SigSpec(v).as_const();
571 }
572 }
573
574 int unique_bit_id_counter = 0;
575 std::map<RTLIL::SigBit, int> unique_bit_id;
576 unique_bit_id[RTLIL::State::S0] = unique_bit_id_counter++;
577 unique_bit_id[RTLIL::State::S1] = unique_bit_id_counter++;
578 unique_bit_id[RTLIL::State::Sx] = unique_bit_id_counter++;
579 unique_bit_id[RTLIL::State::Sz] = unique_bit_id_counter++;
580
581 for (auto conn : cell->connections())
582 if (tpl->avail_parameters.count(stringf("\\_TECHMAP_CONNMAP_%s_", RTLIL::id2cstr(conn.first))) != 0) {
583 for (auto &bit : sigmap(conn.second).to_sigbit_vector())
584 if (unique_bit_id.count(bit) == 0)
585 unique_bit_id[bit] = unique_bit_id_counter++;
586 }
587
588 int bits = 0;
589 for (int i = 0; i < 32; i++)
590 if (((unique_bit_id_counter-1) & (1 << i)) != 0)
591 bits = i;
592 if (tpl->avail_parameters.count("\\_TECHMAP_BITS_CONNMAP_"))
593 parameters["\\_TECHMAP_BITS_CONNMAP_"] = bits;
594
595 for (auto conn : cell->connections())
596 if (tpl->avail_parameters.count(stringf("\\_TECHMAP_CONNMAP_%s_", RTLIL::id2cstr(conn.first))) != 0) {
597 RTLIL::Const value;
598 for (auto &bit : sigmap(conn.second).to_sigbit_vector()) {
599 RTLIL::Const chunk(unique_bit_id.at(bit), bits);
600 value.bits.insert(value.bits.end(), chunk.bits.begin(), chunk.bits.end());
601 }
602 parameters[stringf("\\_TECHMAP_CONNMAP_%s_", RTLIL::id2cstr(conn.first))] = value;
603 }
604 }
605
606 if (0) {
607 use_wrapper_tpl:;
608 // do not register techmap_wrap modules with techmap_cache
609 } else {
610 std::pair<RTLIL::IdString, std::map<RTLIL::IdString, RTLIL::Const>> key(tpl_name, parameters);
611 if (techmap_cache.count(key) > 0) {
612 tpl = techmap_cache[key];
613 } else {
614 if (cell->parameters.size() != 0) {
615 derived_name = tpl->derive(map, dict<RTLIL::IdString, RTLIL::Const>(parameters.begin(), parameters.end()));
616 tpl = map->module(derived_name);
617 log_continue = true;
618 }
619 techmap_cache[key] = tpl;
620 }
621 }
622
623 if (flatten_mode) {
624 techmap_do_cache[tpl] = true;
625 } else {
626 RTLIL::Module *constmapped_tpl = map->module(constmap_tpl_name(sigmap, tpl, cell, false));
627 if (constmapped_tpl != nullptr)
628 tpl = constmapped_tpl;
629 }
630
631 if (techmap_do_cache.count(tpl) == 0)
632 {
633 bool keep_running = true;
634 techmap_do_cache[tpl] = true;
635
636 std::set<std::string> techmap_wire_names;
637
638 while (keep_running)
639 {
640 TechmapWires twd = techmap_find_special_wires(tpl);
641 keep_running = false;
642
643 for (auto &it : twd)
644 techmap_wire_names.insert(it.first);
645
646 for (auto &it : twd["_TECHMAP_FAIL_"]) {
647 RTLIL::SigSpec value = it.value;
648 if (value.is_fully_const() && value.as_bool()) {
649 log("Not using module `%s' from techmap as it contains a %s marker wire with non-zero value %s.\n",
650 derived_name.c_str(), RTLIL::id2cstr(it.wire->name), log_signal(value));
651 techmap_do_cache[tpl] = false;
652 }
653 }
654
655 if (!techmap_do_cache[tpl])
656 break;
657
658 for (auto &it : twd)
659 {
660 if (it.first.substr(0, 12) != "_TECHMAP_DO_" || it.second.empty())
661 continue;
662
663 auto &data = it.second.front();
664
665 if (!data.value.is_fully_const())
666 log_error("Techmap yielded config wire %s with non-const value %s.\n", RTLIL::id2cstr(data.wire->name), log_signal(data.value));
667
668 techmap_wire_names.erase(it.first);
669
670 const char *p = data.wire->name.c_str();
671 const char *q = strrchr(p+1, '.');
672 q = q ? q : p+1;
673
674 std::string cmd_string = data.value.as_const().decode_string();
675
676 restart_eval_cmd_string:
677 if (cmd_string.rfind("CONSTMAP; ", 0) == 0)
678 {
679 cmd_string = cmd_string.substr(strlen("CONSTMAP; "));
680
681 log("Analyzing pattern of constant bits for this cell:\n");
682 RTLIL::IdString new_tpl_name = constmap_tpl_name(sigmap, tpl, cell, true);
683 log("Creating constmapped module `%s'.\n", log_id(new_tpl_name));
684 log_assert(map->module(new_tpl_name) == nullptr);
685
686 RTLIL::Module *new_tpl = map->addModule(new_tpl_name);
687 tpl->cloneInto(new_tpl);
688
689 techmap_do_cache.erase(tpl);
690 techmap_do_cache[new_tpl] = true;
691 tpl = new_tpl;
692
693 std::map<RTLIL::SigBit, RTLIL::SigBit> port_new2old_map;
694 std::map<RTLIL::SigBit, RTLIL::SigBit> port_connmap;
695 std::map<RTLIL::SigBit, RTLIL::SigBit> cellbits_to_tplbits;
696
697 for (auto wire : tpl->wires().to_vector())
698 {
699 if (!wire->port_input || wire->port_output)
700 continue;
701
702 RTLIL::IdString port_name = wire->name;
703 tpl->rename(wire, NEW_ID);
704
705 RTLIL::Wire *new_wire = tpl->addWire(port_name, wire);
706 wire->port_input = false;
707 wire->port_id = 0;
708
709 for (int i = 0; i < wire->width; i++) {
710 port_new2old_map[RTLIL::SigBit(new_wire, i)] = RTLIL::SigBit(wire, i);
711 port_connmap[RTLIL::SigBit(wire, i)] = RTLIL::SigBit(new_wire, i);
712 }
713 }
714
715 for (auto conn : cell->connections())
716 for (int i = 0; i < GetSize(conn.second); i++)
717 {
718 RTLIL::SigBit bit = sigmap(conn.second[i]);
719 RTLIL::SigBit tplbit(tpl->wire(conn.first), i);
720
721 if (bit.wire == nullptr)
722 {
723 RTLIL::SigBit oldbit = port_new2old_map.at(tplbit);
724 port_connmap.at(oldbit) = bit;
725 }
726 else if (cellbits_to_tplbits.count(bit))
727 {
728 RTLIL::SigBit oldbit = port_new2old_map.at(tplbit);
729 port_connmap.at(oldbit) = cellbits_to_tplbits[bit];
730 }
731 else
732 cellbits_to_tplbits[bit] = tplbit;
733 }
734
735 RTLIL::SigSig port_conn;
736 for (auto &it : port_connmap) {
737 port_conn.first.append_bit(it.first);
738 port_conn.second.append_bit(it.second);
739 }
740 tpl->connect(port_conn);
741
742 tpl->check();
743 goto restart_eval_cmd_string;
744 }
745
746 if (cmd_string.rfind("RECURSION; ", 0) == 0)
747 {
748 cmd_string = cmd_string.substr(strlen("RECURSION; "));
749 while (techmap_module(map, tpl, map, handled_cells, celltypeMap, true)) { }
750 goto restart_eval_cmd_string;
751 }
752
753 Pass::call_on_module(map, tpl, cmd_string);
754
755 log_assert(!strncmp(q, "_TECHMAP_DO_", 12));
756 std::string new_name = data.wire->name.substr(0, q-p) + "_TECHMAP_DONE_" + data.wire->name.substr(q-p+12);
757 while (tpl->wires_.count(new_name))
758 new_name += "_";
759 tpl->rename(data.wire->name, new_name);
760
761 keep_running = true;
762 break;
763 }
764 }
765
766 TechmapWires twd = techmap_find_special_wires(tpl);
767 for (auto &it : twd) {
768 if (it.first != "_TECHMAP_FAIL_" && it.first.substr(0, 12) != "_TECHMAP_DO_" && it.first.substr(0, 14) != "_TECHMAP_DONE_")
769 log_error("Techmap yielded unknown config wire %s.\n", it.first.c_str());
770 if (techmap_do_cache[tpl])
771 for (auto &it2 : it.second)
772 if (!it2.value.is_fully_const())
773 log_error("Techmap yielded config wire %s with non-const value %s.\n", RTLIL::id2cstr(it2.wire->name), log_signal(it2.value));
774 techmap_wire_names.erase(it.first);
775 }
776
777 for (auto &it : techmap_wire_names)
778 log_error("Techmap special wire %s disappeared. This is considered a fatal error.\n", RTLIL::id2cstr(it));
779
780 if (recursive_mode) {
781 if (log_continue) {
782 log_header("Continuing TECHMAP pass.\n");
783 log_continue = false;
784 }
785 while (techmap_module(map, tpl, map, handled_cells, celltypeMap, true)) { }
786 }
787 }
788
789 if (techmap_do_cache.at(tpl) == false)
790 continue;
791
792 if (log_continue) {
793 log_header("Continuing TECHMAP pass.\n");
794 log_continue = false;
795 }
796
797 if (extern_mode && !in_recursion)
798 {
799 std::string m_name = stringf("$extern:%s", log_id(tpl));
800
801 if (!design->module(m_name))
802 {
803 RTLIL::Module *m = design->addModule(m_name);
804 tpl->cloneInto(m);
805
806 for (auto cell : m->cells()) {
807 if (cell->type.substr(0, 2) == "\\$")
808 cell->type = cell->type.substr(1);
809 }
810
811 module_queue.insert(m);
812 }
813
814 log("%s %s.%s to imported %s.\n", mapmsg_prefix.c_str(), log_id(module), log_id(cell), log_id(m_name));
815 cell->type = m_name;
816 cell->parameters.clear();
817 }
818 else
819 {
820 log("%s %s.%s using %s.\n", mapmsg_prefix.c_str(), log_id(module), log_id(cell), log_id(tpl));
821 techmap_module_worker(design, module, cell, tpl);
822 cell = NULL;
823 }
824 did_something = true;
825 mapped_cell = true;
826 break;
827 }
828
829 if (assert_mode && !mapped_cell)
830 log_error("(ASSERT MODE) Failed to map cell %s.%s (%s).\n", log_id(module), log_id(cell), log_id(cell->type));
831
832 handled_cells.insert(cell);
833 }
834
835 if (log_continue) {
836 log_header("Continuing TECHMAP pass.\n");
837 log_continue = false;
838 }
839
840 return did_something;
841 }
842 };
843
844 struct TechmapPass : public Pass {
845 TechmapPass() : Pass("techmap", "generic technology mapper") { }
846 virtual void help()
847 {
848 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
849 log("\n");
850 log(" techmap [-map filename] [selection]\n");
851 log("\n");
852 log("This pass implements a very simple technology mapper that replaces cells in\n");
853 log("the design with implementations given in form of a Verilog or ilang source\n");
854 log("file.\n");
855 log("\n");
856 log(" -map filename\n");
857 log(" the library of cell implementations to be used.\n");
858 log(" without this parameter a builtin library is used that\n");
859 log(" transforms the internal RTL cells to the internal gate\n");
860 log(" library.\n");
861 log("\n");
862 log(" -map %%<design-name>\n");
863 log(" like -map above, but with an in-memory design instead of a file.\n");
864 log("\n");
865 log(" -extern\n");
866 log(" load the cell implementations as separate modules into the design\n");
867 log(" instead of inlining them.\n");
868 log("\n");
869 log(" -max_iter <number>\n");
870 log(" only run the specified number of iterations.\n");
871 log("\n");
872 log(" -recursive\n");
873 log(" instead of the iterative breadth-first algorithm use a recursive\n");
874 log(" depth-first algorithm. both methods should yield equivalent results,\n");
875 log(" but may differ in performance.\n");
876 log("\n");
877 log(" -autoproc\n");
878 log(" Automatically call \"proc\" on implementations that contain processes.\n");
879 log("\n");
880 log(" -assert\n");
881 log(" this option will cause techmap to exit with an error if it can't map\n");
882 log(" a selected cell. only cell types that end on an underscore are accepted\n");
883 log(" as final cell types by this mode.\n");
884 log("\n");
885 log(" -D <define>, -I <incdir>\n");
886 log(" this options are passed as-is to the Verilog frontend for loading the\n");
887 log(" map file. Note that the Verilog frontend is also called with the\n");
888 log(" '-ignore_redef' option set.\n");
889 log("\n");
890 log("When a module in the map file has the 'techmap_celltype' attribute set, it will\n");
891 log("match cells with a type that match the text value of this attribute. Otherwise\n");
892 log("the module name will be used to match the cell.\n");
893 log("\n");
894 log("When a module in the map file has the 'techmap_simplemap' attribute set, techmap\n");
895 log("will use 'simplemap' (see 'help simplemap') to map cells matching the module.\n");
896 log("\n");
897 log("When a module in the map file has the 'techmap_maccmap' attribute set, techmap\n");
898 log("will use 'maccmap' (see 'help maccmap') to map cells matching the module.\n");
899 log("\n");
900 log("When a module in the map file has the 'techmap_wrap' attribute set, techmap\n");
901 log("will create a wrapper for the cell and then run the command string that the\n");
902 log("attribute is set to on the wrapper module.\n");
903 log("\n");
904 log("All wires in the modules from the map file matching the pattern _TECHMAP_*\n");
905 log("or *._TECHMAP_* are special wires that are used to pass instructions from\n");
906 log("the mapping module to the techmap command. At the moment the following special\n");
907 log("wires are supported:\n");
908 log("\n");
909 log(" _TECHMAP_FAIL_\n");
910 log(" When this wire is set to a non-zero constant value, techmap will not\n");
911 log(" use this module and instead try the next module with a matching\n");
912 log(" 'techmap_celltype' attribute.\n");
913 log("\n");
914 log(" When such a wire exists but does not have a constant value after all\n");
915 log(" _TECHMAP_DO_* commands have been executed, an error is generated.\n");
916 log("\n");
917 log(" _TECHMAP_DO_*\n");
918 log(" This wires are evaluated in alphabetical order. The constant text value\n");
919 log(" of this wire is a yosys command (or sequence of commands) that is run\n");
920 log(" by techmap on the module. A common use case is to run 'proc' on modules\n");
921 log(" that are written using always-statements.\n");
922 log("\n");
923 log(" When such a wire has a non-constant value at the time it is to be\n");
924 log(" evaluated, an error is produced. That means it is possible for such a\n");
925 log(" wire to start out as non-constant and evaluate to a constant value\n");
926 log(" during processing of other _TECHMAP_DO_* commands.\n");
927 log("\n");
928 log(" A _TECHMAP_DO_* command may start with the special token 'CONSTMAP; '.\n");
929 log(" in this case techmap will create a copy for each distinct configuration\n");
930 log(" of constant inputs and shorted inputs at this point and import the\n");
931 log(" constant and connected bits into the map module. All further commands\n");
932 log(" are executed in this copy. This is a very convenient way of creating\n");
933 log(" optimized specializations of techmap modules without using the special\n");
934 log(" parameters described below.\n");
935 log("\n");
936 log(" A _TECHMAP_DO_* command may start with the special token 'RECURSION; '.\n");
937 log(" then techmap will recursively replace the cells in the module with their\n");
938 log(" implementation. This is not affected by the -max_iter option.\n");
939 log("\n");
940 log(" It is possible to combine both prefixes to 'RECURSION; CONSTMAP; '.\n");
941 log("\n");
942 log("In addition to this special wires, techmap also supports special parameters in\n");
943 log("modules in the map file:\n");
944 log("\n");
945 log(" _TECHMAP_CELLTYPE_\n");
946 log(" When a parameter with this name exists, it will be set to the type name\n");
947 log(" of the cell that matches the module.\n");
948 log("\n");
949 log(" _TECHMAP_CONSTMSK_<port-name>_\n");
950 log(" _TECHMAP_CONSTVAL_<port-name>_\n");
951 log(" When this pair of parameters is available in a module for a port, then\n");
952 log(" former has a 1-bit for each constant input bit and the latter has the\n");
953 log(" value for this bit. The unused bits of the latter are set to undef (x).\n");
954 log("\n");
955 log(" _TECHMAP_BITS_CONNMAP_\n");
956 log(" _TECHMAP_CONNMAP_<port-name>_\n");
957 log(" For an N-bit port, the _TECHMAP_CONNMAP_<port-name>_ parameter, if it\n");
958 log(" exists, will be set to an N*_TECHMAP_BITS_CONNMAP_ bit vector containing\n");
959 log(" N words (of _TECHMAP_BITS_CONNMAP_ bits each) that assign each single\n");
960 log(" bit driver a unique id. The values 0-3 are reserved for 0, 1, x, and z.\n");
961 log(" This can be used to detect shorted inputs.\n");
962 log("\n");
963 log("When a module in the map file has a parameter where the according cell in the\n");
964 log("design has a port, the module from the map file is only used if the port in\n");
965 log("the design is connected to a constant value. The parameter is then set to the\n");
966 log("constant value.\n");
967 log("\n");
968 log("A cell with the name _TECHMAP_REPLACE_ in the map file will inherit the name\n");
969 log("of the cell that is being replaced.\n");
970 log("\n");
971 log("See 'help extract' for a pass that does the opposite thing.\n");
972 log("\n");
973 log("See 'help flatten' for a pass that does flatten the design (which is\n");
974 log("essentially techmap but using the design itself as map library).\n");
975 log("\n");
976 }
977 virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
978 {
979 log_header("Executing TECHMAP pass (map to technology primitives).\n");
980 log_push();
981
982 TechmapWorker worker;
983 simplemap_get_mappers(worker.simplemap_mappers);
984
985 std::vector<std::string> map_files;
986 std::string verilog_frontend = "verilog -ignore_redef";
987 int max_iter = -1;
988
989 size_t argidx;
990 for (argidx = 1; argidx < args.size(); argidx++) {
991 if (args[argidx] == "-map" && argidx+1 < args.size()) {
992 map_files.push_back(args[++argidx]);
993 continue;
994 }
995 if (args[argidx] == "-max_iter" && argidx+1 < args.size()) {
996 max_iter = atoi(args[++argidx].c_str());
997 continue;
998 }
999 if (args[argidx] == "-D" && argidx+1 < args.size()) {
1000 verilog_frontend += " -D " + args[++argidx];
1001 continue;
1002 }
1003 if (args[argidx] == "-I" && argidx+1 < args.size()) {
1004 verilog_frontend += " -I " + args[++argidx];
1005 continue;
1006 }
1007 if (args[argidx] == "-assert") {
1008 worker.assert_mode = true;
1009 continue;
1010 }
1011 if (args[argidx] == "-extern") {
1012 worker.extern_mode = true;
1013 continue;
1014 }
1015 if (args[argidx] == "-recursive") {
1016 worker.recursive_mode = true;
1017 continue;
1018 }
1019 if (args[argidx] == "-autoproc") {
1020 worker.autoproc_mode = true;
1021 continue;
1022 }
1023 break;
1024 }
1025 extra_args(args, argidx, design);
1026
1027 RTLIL::Design *map = new RTLIL::Design;
1028 if (map_files.empty()) {
1029 std::istringstream f(stdcells_code);
1030 Frontend::frontend_call(map, &f, "<techmap.v>", verilog_frontend);
1031 } else
1032 for (auto &fn : map_files)
1033 if (fn.substr(0, 1) == "%") {
1034 if (!saved_designs.count(fn.substr(1))) {
1035 delete map;
1036 log_cmd_error("Can't saved design `%s'.\n", fn.c_str()+1);
1037 }
1038 for (auto mod : saved_designs.at(fn.substr(1))->modules())
1039 if (!map->has(mod->name))
1040 map->add(mod->clone());
1041 } else {
1042 std::ifstream f;
1043 rewrite_filename(fn);
1044 f.open(fn.c_str());
1045 if (f.fail())
1046 log_cmd_error("Can't open map file `%s'\n", fn.c_str());
1047 Frontend::frontend_call(map, &f, fn, (fn.size() > 3 && fn.substr(fn.size()-3) == ".il") ? "ilang" : verilog_frontend);
1048 }
1049
1050 std::map<RTLIL::IdString, std::set<RTLIL::IdString, RTLIL::sort_by_id_str>> celltypeMap;
1051 for (auto &it : map->modules_) {
1052 if (it.second->attributes.count("\\techmap_celltype") && !it.second->attributes.at("\\techmap_celltype").bits.empty()) {
1053 char *p = strdup(it.second->attributes.at("\\techmap_celltype").decode_string().c_str());
1054 for (char *q = strtok(p, " \t\r\n"); q; q = strtok(NULL, " \t\r\n"))
1055 celltypeMap[RTLIL::escape_id(q)].insert(it.first);
1056 free(p);
1057 } else {
1058 string module_name = it.first.str();
1059 if (module_name.substr(0, 2) == "\\$")
1060 module_name = module_name.substr(1);
1061 celltypeMap[module_name].insert(it.first);
1062 }
1063 }
1064
1065 for (auto module : design->modules())
1066 worker.module_queue.insert(module);
1067
1068 while (!worker.module_queue.empty())
1069 {
1070 RTLIL::Module *module = *worker.module_queue.begin();
1071 worker.module_queue.erase(module);
1072
1073 bool did_something = true;
1074 std::set<RTLIL::Cell*> handled_cells;
1075 while (did_something) {
1076 did_something = false;
1077 if (worker.techmap_module(design, module, map, handled_cells, celltypeMap, false))
1078 did_something = true;
1079 if (did_something)
1080 module->check();
1081 if (max_iter > 0 && --max_iter == 0)
1082 break;
1083 }
1084 }
1085
1086 log("No more expansions possible.\n");
1087 delete map;
1088
1089 log_pop();
1090 }
1091 } TechmapPass;
1092
1093 struct FlattenPass : public Pass {
1094 FlattenPass() : Pass("flatten", "flatten design") { }
1095 virtual void help()
1096 {
1097 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
1098 log("\n");
1099 log(" flatten [selection]\n");
1100 log("\n");
1101 log("This pass flattens the design by replacing cells by their implementation. This\n");
1102 log("pass is very similar to the 'techmap' pass. The only difference is that this\n");
1103 log("pass is using the current design as mapping library.\n");
1104 log("\n");
1105 log("Cells and/or modules with the 'keep_hierarchy' attribute set will not be\n");
1106 log("flattened by this command.\n");
1107 log("\n");
1108 }
1109 virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
1110 {
1111 log_header("Executing FLATTEN pass (flatten design).\n");
1112 log_push();
1113
1114 extra_args(args, 1, design);
1115
1116 TechmapWorker worker;
1117 worker.flatten_mode = true;
1118
1119 std::map<RTLIL::IdString, std::set<RTLIL::IdString, RTLIL::sort_by_id_str>> celltypeMap;
1120 for (auto module : design->modules())
1121 celltypeMap[module->name].insert(module->name);
1122
1123 RTLIL::Module *top_mod = NULL;
1124 if (design->full_selection())
1125 for (auto mod : design->modules())
1126 if (mod->get_bool_attribute("\\top"))
1127 top_mod = mod;
1128
1129 std::set<RTLIL::Cell*> handled_cells;
1130 if (top_mod != NULL) {
1131 worker.flatten_do_list.insert(top_mod->name);
1132 while (!worker.flatten_do_list.empty()) {
1133 auto mod = design->module(*worker.flatten_do_list.begin());
1134 while (worker.techmap_module(design, mod, design, handled_cells, celltypeMap, false)) { }
1135 worker.flatten_done_list.insert(mod->name);
1136 worker.flatten_do_list.erase(mod->name);
1137 }
1138 } else {
1139 for (auto mod : vector<Module*>(design->modules()))
1140 while (worker.techmap_module(design, mod, design, handled_cells, celltypeMap, false)) { }
1141 }
1142
1143 log("No more expansions possible.\n");
1144
1145 if (top_mod != NULL)
1146 {
1147 pool<RTLIL::IdString> used_modules, new_used_modules;
1148 new_used_modules.insert(top_mod->name);
1149 while (!new_used_modules.empty()) {
1150 pool<RTLIL::IdString> queue;
1151 queue.swap(new_used_modules);
1152 for (auto modname : queue)
1153 used_modules.insert(modname);
1154 for (auto modname : queue)
1155 for (auto cell : design->module(modname)->cells())
1156 if (design->module(cell->type) && !used_modules[cell->type])
1157 new_used_modules.insert(cell->type);
1158 }
1159
1160 dict<RTLIL::IdString, RTLIL::Module*> new_modules;
1161 for (auto mod : vector<Module*>(design->modules()))
1162 if (used_modules[mod->name] || mod->get_bool_attribute("\\blackbox")) {
1163 new_modules[mod->name] = mod;
1164 } else {
1165 log("Deleting now unused module %s.\n", log_id(mod));
1166 delete mod;
1167 }
1168 design->modules_.swap(new_modules);
1169 }
1170
1171 log_pop();
1172 }
1173 } FlattenPass;
1174
1175 PRIVATE_NAMESPACE_END