Merge pull request #829 from abdelrahmanhosny/master
[yosys.git] / passes / hierarchy / hierarchy.cc
1 /*
2 * yosys -- Yosys Open SYnthesis Suite
3 *
4 * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
5 * Copyright (C) 2018 Ruben Undheim <ruben.undheim@gmail.com>
6 *
7 * Permission to use, copy, modify, and/or distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
10 *
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 *
19 */
20
21 #include "kernel/yosys.h"
22 #include "frontends/verific/verific.h"
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <set>
26
27 #ifndef _WIN32
28 # include <unistd.h>
29 #endif
30
31
32 USING_YOSYS_NAMESPACE
33 PRIVATE_NAMESPACE_BEGIN
34
35 struct generate_port_decl_t {
36 bool input, output;
37 string portname;
38 int index;
39 };
40
41 void generate(RTLIL::Design *design, const std::vector<std::string> &celltypes, const std::vector<generate_port_decl_t> &portdecls)
42 {
43 std::set<RTLIL::IdString> found_celltypes;
44
45 for (auto i1 : design->modules_)
46 for (auto i2 : i1.second->cells_)
47 {
48 RTLIL::Cell *cell = i2.second;
49 if (design->has(cell->type))
50 continue;
51 if (cell->type.substr(0, 1) == "$" && cell->type.substr(0, 3) != "$__")
52 continue;
53 for (auto &pattern : celltypes)
54 if (patmatch(pattern.c_str(), RTLIL::unescape_id(cell->type).c_str()))
55 found_celltypes.insert(cell->type);
56 }
57
58 for (auto &celltype : found_celltypes)
59 {
60 std::set<RTLIL::IdString> portnames;
61 std::set<RTLIL::IdString> parameters;
62 std::map<RTLIL::IdString, int> portwidths;
63 log("Generate module for cell type %s:\n", celltype.c_str());
64
65 for (auto i1 : design->modules_)
66 for (auto i2 : i1.second->cells_)
67 if (i2.second->type == celltype) {
68 for (auto &conn : i2.second->connections()) {
69 if (conn.first[0] != '$')
70 portnames.insert(conn.first);
71 portwidths[conn.first] = max(portwidths[conn.first], conn.second.size());
72 }
73 for (auto &para : i2.second->parameters)
74 parameters.insert(para.first);
75 }
76
77 for (auto &decl : portdecls)
78 if (decl.index > 0)
79 portnames.insert(decl.portname);
80
81 std::set<int> indices;
82 for (int i = 0; i < int(portnames.size()); i++)
83 indices.insert(i+1);
84
85 std::vector<generate_port_decl_t> ports(portnames.size());
86
87 for (auto &decl : portdecls)
88 if (decl.index > 0) {
89 portwidths[decl.portname] = max(portwidths[decl.portname], 1);
90 portwidths[decl.portname] = max(portwidths[decl.portname], portwidths[stringf("$%d", decl.index)]);
91 log(" port %d: %s [%d:0] %s\n", decl.index, decl.input ? decl.output ? "inout" : "input" : "output", portwidths[decl.portname]-1, RTLIL::id2cstr(decl.portname));
92 if (indices.count(decl.index) > ports.size())
93 log_error("Port index (%d) exceeds number of found ports (%d).\n", decl.index, int(ports.size()));
94 if (indices.count(decl.index) == 0)
95 log_error("Conflict on port index %d.\n", decl.index);
96 indices.erase(decl.index);
97 portnames.erase(decl.portname);
98 ports[decl.index-1] = decl;
99 }
100
101 while (portnames.size() > 0) {
102 RTLIL::IdString portname = *portnames.begin();
103 for (auto &decl : portdecls)
104 if (decl.index == 0 && patmatch(decl.portname.c_str(), RTLIL::unescape_id(portname).c_str())) {
105 generate_port_decl_t d = decl;
106 d.portname = portname.str();
107 d.index = *indices.begin();
108 log_assert(!indices.empty());
109 indices.erase(d.index);
110 ports[d.index-1] = d;
111 portwidths[d.portname] = max(portwidths[d.portname], 1);
112 log(" port %d: %s [%d:0] %s\n", d.index, d.input ? d.output ? "inout" : "input" : "output", portwidths[d.portname]-1, RTLIL::id2cstr(d.portname));
113 goto found_matching_decl;
114 }
115 log_error("Can't match port %s.\n", RTLIL::id2cstr(portname));
116 found_matching_decl:;
117 portnames.erase(portname);
118 }
119
120 log_assert(indices.empty());
121
122 RTLIL::Module *mod = new RTLIL::Module;
123 mod->name = celltype;
124 mod->attributes["\\blackbox"] = RTLIL::Const(1);
125 design->add(mod);
126
127 for (auto &decl : ports) {
128 RTLIL::Wire *wire = mod->addWire(decl.portname, portwidths.at(decl.portname));
129 wire->port_id = decl.index;
130 wire->port_input = decl.input;
131 wire->port_output = decl.output;
132 }
133
134 mod->fixup_ports();
135
136 for (auto &para : parameters)
137 log(" ignoring parameter %s.\n", RTLIL::id2cstr(para));
138
139 log(" module %s created.\n", RTLIL::id2cstr(mod->name));
140 }
141 }
142
143 // Return the "basic" type for an array item.
144 std::string basic_cell_type(const std::string celltype, int pos[3] = nullptr) {
145 std::string basicType = celltype;
146 if (celltype.substr(0, 7) == "$array:") {
147 int pos_idx = celltype.find_first_of(':');
148 int pos_num = celltype.find_first_of(':', pos_idx + 1);
149 int pos_type = celltype.find_first_of(':', pos_num + 1);
150 basicType = celltype.substr(pos_type + 1);
151 if (pos != nullptr) {
152 pos[0] = pos_idx;
153 pos[1] = pos_num;
154 pos[2] = pos_type;
155 }
156 }
157 return basicType;
158 }
159
160 bool expand_module(RTLIL::Design *design, RTLIL::Module *module, bool flag_check, bool flag_simcheck, std::vector<std::string> &libdirs)
161 {
162 bool did_something = false;
163 std::map<RTLIL::Cell*, std::pair<int, int>> array_cells;
164 std::string filename;
165
166 bool has_interface_ports = false;
167
168 // If any of the ports are actually interface ports, we will always need to
169 // reprocess the module:
170 if(!module->get_bool_attribute("\\interfaces_replaced_in_module")) {
171 for (auto &wire : module->wires_) {
172 if ((wire.second->port_input || wire.second->port_output) && wire.second->get_bool_attribute("\\is_interface"))
173 has_interface_ports = true;
174 }
175 }
176
177 // Always keep track of all derived interfaces available in the current module in 'interfaces_in_module':
178 dict<RTLIL::IdString, RTLIL::Module*> interfaces_in_module;
179 for (auto &cell_it : module->cells_)
180 {
181 RTLIL::Cell *cell = cell_it.second;
182 if(cell->get_bool_attribute("\\is_interface")) {
183 RTLIL::Module *intf_module = design->modules_[cell->type];
184 interfaces_in_module[cell->name] = intf_module;
185 }
186 }
187
188 for (auto &cell_it : module->cells_)
189 {
190 RTLIL::Cell *cell = cell_it.second;
191 bool has_interfaces_not_found = false;
192
193 std::vector<RTLIL::IdString> connections_to_remove;
194 std::vector<RTLIL::IdString> connections_to_add_name;
195 std::vector<RTLIL::SigSpec> connections_to_add_signal;
196
197 if (cell->type.substr(0, 7) == "$array:") {
198 int pos[3];
199 basic_cell_type(cell->type.str(), pos);
200 int pos_idx = pos[0];
201 int pos_num = pos[1];
202 int pos_type = pos[2];
203 int idx = atoi(cell->type.str().substr(pos_idx + 1, pos_num).c_str());
204 int num = atoi(cell->type.str().substr(pos_num + 1, pos_type).c_str());
205 array_cells[cell] = std::pair<int, int>(idx, num);
206 cell->type = cell->type.str().substr(pos_type + 1);
207 }
208 dict<RTLIL::IdString, RTLIL::Module*> interfaces_to_add_to_submodule;
209 dict<RTLIL::IdString, RTLIL::IdString> modports_used_in_submodule;
210
211 if (design->modules_.count(cell->type) == 0)
212 {
213 if (design->modules_.count("$abstract" + cell->type.str()))
214 {
215 cell->type = design->modules_.at("$abstract" + cell->type.str())->derive(design, cell->parameters);
216 cell->parameters.clear();
217 did_something = true;
218 continue;
219 }
220
221 if (cell->type[0] == '$')
222 continue;
223
224 for (auto &dir : libdirs)
225 {
226 static const vector<pair<string, string>> extensions_list =
227 {
228 {".v", "verilog"},
229 {".sv", "verilog -sv"},
230 {".il", "ilang"}
231 };
232
233 for (auto &ext : extensions_list)
234 {
235 filename = dir + "/" + RTLIL::unescape_id(cell->type) + ext.first;
236 if (check_file_exists(filename)) {
237 Frontend::frontend_call(design, NULL, filename, ext.second);
238 goto loaded_module;
239 }
240 }
241 }
242
243 if ((flag_check || flag_simcheck) && cell->type[0] != '$')
244 log_error("Module `%s' referenced in module `%s' in cell `%s' is not part of the design.\n",
245 cell->type.c_str(), module->name.c_str(), cell->name.c_str());
246 continue;
247
248 loaded_module:
249 if (design->modules_.count(cell->type) == 0)
250 log_error("File `%s' from libdir does not declare module `%s'.\n", filename.c_str(), cell->type.c_str());
251 did_something = true;
252 } else {
253
254 RTLIL::Module *mod = design->module(cell->type);
255
256 // Go over all connections and see if any of them are SV interfaces. If they are, then add the replacements to
257 // some lists, so that the ports for sub-modules can be replaced further down:
258 for (auto &conn : cell->connections()) {
259 if(mod->wires_.count(conn.first) != 0 && mod->wire(conn.first)->get_bool_attribute("\\is_interface")) { // Check if the connection is present as an interface in the sub-module's port list
260 //const pool<string> &interface_type_pool = mod->wire(conn.first)->get_strpool_attribute("\\interface_type");
261 //for (auto &d : interface_type_pool) { // TODO: Compare interface type to type in parent module (not crucially important, but good for robustness)
262 //}
263
264 // Find if the sub-module has set a modport for the current interface connection:
265 const pool<string> &interface_modport_pool = mod->wire(conn.first)->get_strpool_attribute("\\interface_modport");
266 std::string interface_modport = "";
267 for (auto &d : interface_modport_pool) {
268 interface_modport = "\\" + d;
269 }
270 if(conn.second.bits().size() == 1 && conn.second.bits()[0].wire->get_bool_attribute("\\is_interface")) { // Check if the connected wire is a potential interface in the parent module
271 std::string interface_name_str = conn.second.bits()[0].wire->name.str();
272 interface_name_str.replace(0,23,""); // Strip the prefix '$dummywireforinterface' from the dummy wire to get the name
273 interface_name_str = "\\" + interface_name_str;
274 RTLIL::IdString interface_name = interface_name_str;
275 bool not_found_interface = false;
276 if(module->get_bool_attribute("\\interfaces_replaced_in_module")) { // If 'interfaces' in the cell have not be been handled yet, there is no need to derive the sub-module either
277 // Check if the interface instance is present in module:
278 // Interface instances may either have the plain name or the name appended with '_inst_from_top_dummy'.
279 // Check for both of them here
280 int nexactmatch = interfaces_in_module.count(interface_name) > 0;
281 std::string interface_name_str2 = interface_name_str + "_inst_from_top_dummy";
282 RTLIL::IdString interface_name2 = interface_name_str2;
283 int nmatch2 = interfaces_in_module.count(interface_name2) > 0;
284 if (nexactmatch > 0 || nmatch2 > 0) {
285 if (nexactmatch != 0) // Choose the one with the plain name if it exists
286 interface_name2 = interface_name;
287 RTLIL::Module *mod_replace_ports = interfaces_in_module.at(interface_name2);
288 for (auto &mod_wire : mod_replace_ports->wires_) { // Go over all wires in interface, and add replacements to lists.
289 std::string signal_name1 = conn.first.str() + "." + log_id(mod_wire.first);
290 std::string signal_name2 = interface_name.str() + "." + log_id(mod_wire.first);
291 connections_to_add_name.push_back(RTLIL::IdString(signal_name1));
292 if(module->wires_.count(signal_name2) == 0) {
293 log_error("Could not find signal '%s' in '%s'\n", signal_name2.c_str(), log_id(module->name));
294 }
295 else {
296 RTLIL::Wire *wire_in_parent = module->wire(signal_name2);
297 connections_to_add_signal.push_back(wire_in_parent);
298 }
299 }
300 connections_to_remove.push_back(conn.first);
301 interfaces_to_add_to_submodule[conn.first] = interfaces_in_module.at(interface_name2);
302
303 // Add modports to a dict which will be passed to AstModule::derive
304 if (interface_modport != "") {
305 modports_used_in_submodule[conn.first] = interface_modport;
306 }
307 }
308 else not_found_interface = true;
309 }
310 else not_found_interface = true;
311 // If the interface instance has not already been derived in the module, we cannot complete at this stage. Set "has_interfaces_not_found"
312 // which will delay the expansion of this cell:
313 if (not_found_interface) {
314 // If we have already gone over all cells in this module, and the interface has still not been found - flag it as an error:
315 if(!(module->get_bool_attribute("\\cells_not_processed"))) {
316 log_warning("Could not find interface instance for `%s' in `%s'\n", log_id(interface_name), log_id(module));
317 }
318 else {
319 // Only set has_interfaces_not_found if it would be possible to find them, since otherwiser we will end up in an infinite loop:
320 has_interfaces_not_found = true;
321 }
322 }
323 }
324 }
325 }
326 //
327
328 if (flag_check || flag_simcheck)
329 {
330 for (auto &conn : cell->connections()) {
331 if (conn.first[0] == '$' && '0' <= conn.first[1] && conn.first[1] <= '9') {
332 int id = atoi(conn.first.c_str()+1);
333 if (id <= 0 || id > GetSize(mod->ports))
334 log_error("Module `%s' referenced in module `%s' in cell `%s' has only %d ports, requested port %d.\n",
335 log_id(cell->type), log_id(module), log_id(cell), GetSize(mod->ports), id);
336 } else if (mod->wire(conn.first) == nullptr || mod->wire(conn.first)->port_id == 0)
337 log_error("Module `%s' referenced in module `%s' in cell `%s' does not have a port named '%s'.\n",
338 log_id(cell->type), log_id(module), log_id(cell), log_id(conn.first));
339 }
340 for (auto &param : cell->parameters)
341 if (mod->avail_parameters.count(param.first) == 0 && param.first[0] != '$' && strchr(param.first.c_str(), '.') == NULL)
342 log_error("Module `%s' referenced in module `%s' in cell `%s' does not have a parameter named '%s'.\n",
343 log_id(cell->type), log_id(module), log_id(cell), log_id(param.first));
344
345 }
346 }
347 RTLIL::Module *mod = design->modules_[cell->type];
348
349 if (design->modules_.at(cell->type)->get_blackbox_attribute()) {
350 if (flag_simcheck)
351 log_error("Module `%s' referenced in module `%s' in cell `%s' is a blackbox/whitebox module.\n",
352 cell->type.c_str(), module->name.c_str(), cell->name.c_str());
353 continue;
354 }
355
356 // If interface instances not yet found, skip cell for now, and say we did something, so that we will return back here:
357 if(has_interfaces_not_found) {
358 did_something = true; // waiting for interfaces to be handled
359 continue;
360 }
361
362 // Do the actual replacements of the SV interface port connection with the individual signal connections:
363 for(unsigned int i=0;i<connections_to_add_name.size();i++) {
364 cell->connections_[connections_to_add_name[i]] = connections_to_add_signal[i];
365 }
366 // Remove the connection for the interface itself:
367 for(unsigned int i=0;i<connections_to_remove.size();i++) {
368 cell->connections_.erase(connections_to_remove[i]);
369 }
370
371 // If there are no overridden parameters AND not interfaces, then we can use the existing module instance as the type
372 // for the cell:
373 if (cell->parameters.size() == 0 && (interfaces_to_add_to_submodule.size() == 0 || !(cell->get_bool_attribute("\\module_not_derived")))) {
374 // If the cell being processed is an the interface instance itself, go down to "handle_interface_instance:",
375 // so that the signals of the interface are added to the parent module.
376 if (mod->get_bool_attribute("\\is_interface")) {
377 goto handle_interface_instance;
378 }
379 continue;
380 }
381
382 cell->type = mod->derive(design, cell->parameters, interfaces_to_add_to_submodule, modports_used_in_submodule);
383 cell->parameters.clear();
384 did_something = true;
385
386 handle_interface_instance:
387
388 // We add all the signals of the interface explicitly to the parent module. This is always needed when we encounter
389 // an interface instance:
390 if (mod->get_bool_attribute("\\is_interface") && cell->get_bool_attribute("\\module_not_derived")) {
391 cell->set_bool_attribute("\\is_interface");
392 RTLIL::Module *derived_module = design->modules_[cell->type];
393 interfaces_in_module[cell->name] = derived_module;
394 did_something = true;
395 }
396 // We clear 'module_not_derived' such that we will not rederive the cell again (needed when there are interfaces connected to the cell)
397 cell->attributes.erase("\\module_not_derived");
398 }
399 // Clear the attribute 'cells_not_processed' such that it can be known that we
400 // have been through all cells at least once, and that we can know whether
401 // to flag an error because of interface instances not found:
402 module->attributes.erase("\\cells_not_processed");
403
404
405 // If any interface instances or interface ports were found in the module, we need to rederive it completely:
406 if ((interfaces_in_module.size() > 0 || has_interface_ports) && !module->get_bool_attribute("\\interfaces_replaced_in_module")) {
407 module->reprocess_module(design, interfaces_in_module);
408 return did_something;
409 }
410
411
412 for (auto &it : array_cells)
413 {
414 RTLIL::Cell *cell = it.first;
415 int idx = it.second.first, num = it.second.second;
416
417 if (design->modules_.count(cell->type) == 0)
418 log_error("Array cell `%s.%s' of unknown type `%s'.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(cell->name), RTLIL::id2cstr(cell->type));
419
420 RTLIL::Module *mod = design->modules_[cell->type];
421
422 for (auto &conn : cell->connections_) {
423 int conn_size = conn.second.size();
424 RTLIL::IdString portname = conn.first;
425 if (portname.substr(0, 1) == "$") {
426 int port_id = atoi(portname.substr(1).c_str());
427 for (auto &wire_it : mod->wires_)
428 if (wire_it.second->port_id == port_id) {
429 portname = wire_it.first;
430 break;
431 }
432 }
433 if (mod->wires_.count(portname) == 0)
434 log_error("Array cell `%s.%s' connects to unknown port `%s'.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(cell->name), RTLIL::id2cstr(conn.first));
435 int port_size = mod->wires_.at(portname)->width;
436 if (conn_size == port_size || conn_size == 0)
437 continue;
438 if (conn_size != port_size*num)
439 log_error("Array cell `%s.%s' has invalid port vs. signal size for port `%s'.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(cell->name), RTLIL::id2cstr(conn.first));
440 conn.second = conn.second.extract(port_size*idx, port_size);
441 }
442 }
443
444 return did_something;
445 }
446
447 void hierarchy_worker(RTLIL::Design *design, std::set<RTLIL::Module*, IdString::compare_ptr_by_name<Module>> &used, RTLIL::Module *mod, int indent)
448 {
449 if (used.count(mod) > 0)
450 return;
451
452 if (indent == 0)
453 log("Top module: %s\n", mod->name.c_str());
454 else if (!mod->get_blackbox_attribute())
455 log("Used module: %*s%s\n", indent, "", mod->name.c_str());
456 used.insert(mod);
457
458 for (auto cell : mod->cells()) {
459 std::string celltype = cell->type.str();
460 if (celltype.substr(0, 7) == "$array:") {
461 celltype = basic_cell_type(celltype);
462 }
463 if (design->module(celltype))
464 hierarchy_worker(design, used, design->module(celltype), indent+4);
465 }
466 }
467
468 void hierarchy_clean(RTLIL::Design *design, RTLIL::Module *top, bool purge_lib)
469 {
470 std::set<RTLIL::Module*, IdString::compare_ptr_by_name<Module>> used;
471 hierarchy_worker(design, used, top, 0);
472
473 std::vector<RTLIL::Module*> del_modules;
474 for (auto &it : design->modules_)
475 if (used.count(it.second) == 0)
476 del_modules.push_back(it.second);
477 else {
478 // Now all interface ports must have been exploded, and it is hence
479 // safe to delete all of the remaining dummy interface ports:
480 pool<RTLIL::Wire*> del_wires;
481 for(auto &wire : it.second->wires_) {
482 if ((wire.second->port_input || wire.second->port_output) && wire.second->get_bool_attribute("\\is_interface")) {
483 del_wires.insert(wire.second);
484 }
485 }
486 if (del_wires.size() > 0) {
487 it.second->remove(del_wires);
488 it.second->fixup_ports();
489 }
490 }
491
492 int del_counter = 0;
493 for (auto mod : del_modules) {
494 if (!purge_lib && mod->get_blackbox_attribute())
495 continue;
496 log("Removing unused module `%s'.\n", mod->name.c_str());
497 design->modules_.erase(mod->name);
498 del_counter++;
499 delete mod;
500 }
501
502 log("Removed %d unused modules.\n", del_counter);
503 }
504
505 bool set_keep_assert(std::map<RTLIL::Module*, bool> &cache, RTLIL::Module *mod)
506 {
507 if (cache.count(mod) == 0)
508 for (auto c : mod->cells()) {
509 RTLIL::Module *m = mod->design->module(c->type);
510 if ((m != nullptr && set_keep_assert(cache, m)) || c->type.in("$assert", "$assume", "$live", "$fair", "$cover"))
511 return cache[mod] = true;
512 }
513 return cache[mod];
514 }
515
516 int find_top_mod_score(Design *design, Module *module, dict<Module*, int> &db)
517 {
518 if (db.count(module) == 0) {
519 int score = 0;
520 db[module] = 0;
521 for (auto cell : module->cells()) {
522 std::string celltype = cell->type.str();
523 // Is this an array instance
524 if (celltype.substr(0, 7) == "$array:") {
525 celltype = basic_cell_type(celltype);
526 }
527 // Is this cell a module instance?
528 auto instModule = design->module(celltype);
529 // If there is no instance for this, issue a warning.
530 if (instModule != nullptr) {
531 score = max(score, find_top_mod_score(design, instModule, db) + 1);
532 }
533 }
534 db[module] = score;
535 }
536 return db.at(module);
537 }
538
539 RTLIL::Module *check_if_top_has_changed(Design *design, Module *top_mod)
540 {
541 if(top_mod != NULL && top_mod->get_bool_attribute("\\initial_top"))
542 return top_mod;
543 else {
544 for (auto mod : design->modules()) {
545 if (mod->get_bool_attribute("\\top")) {
546 return mod;
547 }
548 }
549 }
550 return NULL;
551 }
552
553 struct HierarchyPass : public Pass {
554 HierarchyPass() : Pass("hierarchy", "check, expand and clean up design hierarchy") { }
555 void help() YS_OVERRIDE
556 {
557 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
558 log("\n");
559 log(" hierarchy [-check] [-top <module>]\n");
560 log(" hierarchy -generate <cell-types> <port-decls>\n");
561 log("\n");
562 log("In parametric designs, a module might exists in several variations with\n");
563 log("different parameter values. This pass looks at all modules in the current\n");
564 log("design an re-runs the language frontends for the parametric modules as\n");
565 log("needed. It also resolves assignments to wired logic data types (wand/wor),\n");
566 log("resolves positional module parameters, unroll array instances, and more.\n");
567 log("\n");
568 log(" -check\n");
569 log(" also check the design hierarchy. this generates an error when\n");
570 log(" an unknown module is used as cell type.\n");
571 log("\n");
572 log(" -simcheck\n");
573 log(" like -check, but also throw an error if blackbox modules are\n");
574 log(" instantiated, and throw an error if the design has no top module.\n");
575 log("\n");
576 log(" -purge_lib\n");
577 log(" by default the hierarchy command will not remove library (blackbox)\n");
578 log(" modules. use this option to also remove unused blackbox modules.\n");
579 log("\n");
580 log(" -libdir <directory>\n");
581 log(" search for files named <module_name>.v in the specified directory\n");
582 log(" for unknown modules and automatically run read_verilog for each\n");
583 log(" unknown module.\n");
584 log("\n");
585 log(" -keep_positionals\n");
586 log(" per default this pass also converts positional arguments in cells\n");
587 log(" to arguments using port names. This option disables this behavior.\n");
588 log("\n");
589 log(" -keep_portwidths\n");
590 log(" per default this pass adjusts the port width on cells that are\n");
591 log(" module instances when the width does not match the module port. This\n");
592 log(" option disables this behavior.\n");
593 log("\n");
594 log(" -nokeep_asserts\n");
595 log(" per default this pass sets the \"keep\" attribute on all modules\n");
596 log(" that directly or indirectly contain one or more formal properties.\n");
597 log(" This option disables this behavior.\n");
598 log("\n");
599 log(" -top <module>\n");
600 log(" use the specified top module to build the design hierarchy. Modules\n");
601 log(" outside this tree (unused modules) are removed.\n");
602 log("\n");
603 log(" when the -top option is used, the 'top' attribute will be set on the\n");
604 log(" specified top module. otherwise a module with the 'top' attribute set\n");
605 log(" will implicitly be used as top module, if such a module exists.\n");
606 log("\n");
607 log(" -auto-top\n");
608 log(" automatically determine the top of the design hierarchy and mark it.\n");
609 log("\n");
610 log(" -chparam name value \n");
611 log(" elaborate the top module using this parameter value. Modules on which\n");
612 log(" this parameter does not exist may cause a warning message to be output.\n");
613 log(" This option can be specified multiple times to override multiple\n");
614 log(" parameters. String values must be passed in double quotes (\").\n");
615 log("\n");
616 log("In -generate mode this pass generates blackbox modules for the given cell\n");
617 log("types (wildcards supported). For this the design is searched for cells that\n");
618 log("match the given types and then the given port declarations are used to\n");
619 log("determine the direction of the ports. The syntax for a port declaration is:\n");
620 log("\n");
621 log(" {i|o|io}[@<num>]:<portname>\n");
622 log("\n");
623 log("Input ports are specified with the 'i' prefix, output ports with the 'o'\n");
624 log("prefix and inout ports with the 'io' prefix. The optional <num> specifies\n");
625 log("the position of the port in the parameter list (needed when instantiated\n");
626 log("using positional arguments). When <num> is not specified, the <portname> can\n");
627 log("also contain wildcard characters.\n");
628 log("\n");
629 log("This pass ignores the current selection and always operates on all modules\n");
630 log("in the current design.\n");
631 log("\n");
632 }
633 void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
634 {
635 log_header(design, "Executing HIERARCHY pass (managing design hierarchy).\n");
636
637 bool flag_check = false;
638 bool flag_simcheck = false;
639 bool purge_lib = false;
640 RTLIL::Module *top_mod = NULL;
641 std::string load_top_mod;
642 std::vector<std::string> libdirs;
643
644 bool auto_top_mode = false;
645 bool generate_mode = false;
646 bool keep_positionals = false;
647 bool keep_portwidths = false;
648 bool nokeep_asserts = false;
649 std::vector<std::string> generate_cells;
650 std::vector<generate_port_decl_t> generate_ports;
651 std::map<std::string, std::string> parameters;
652
653 size_t argidx;
654 for (argidx = 1; argidx < args.size(); argidx++)
655 {
656 if (args[argidx] == "-generate" && !flag_check && !flag_simcheck && !top_mod) {
657 generate_mode = true;
658 log("Entering generate mode.\n");
659 while (++argidx < args.size()) {
660 const char *p = args[argidx].c_str();
661 generate_port_decl_t decl;
662 if (p[0] == 'i' && p[1] == 'o')
663 decl.input = true, decl.output = true, p += 2;
664 else if (*p == 'i')
665 decl.input = true, decl.output = false, p++;
666 else if (*p == 'o')
667 decl.input = false, decl.output = true, p++;
668 else
669 goto is_celltype;
670 if (*p == '@') {
671 char *endptr;
672 decl.index = strtol(++p, &endptr, 10);
673 if (decl.index < 1)
674 goto is_celltype;
675 p = endptr;
676 } else
677 decl.index = 0;
678 if (*(p++) != ':')
679 goto is_celltype;
680 if (*p == 0)
681 goto is_celltype;
682 decl.portname = p;
683 log("Port declaration: %s", decl.input ? decl.output ? "inout" : "input" : "output");
684 if (decl.index >= 1)
685 log(" [at position %d]", decl.index);
686 log(" %s\n", decl.portname.c_str());
687 generate_ports.push_back(decl);
688 continue;
689 is_celltype:
690 log("Celltype: %s\n", args[argidx].c_str());
691 generate_cells.push_back(RTLIL::unescape_id(args[argidx]));
692 }
693 continue;
694 }
695 if (args[argidx] == "-check") {
696 flag_check = true;
697 continue;
698 }
699 if (args[argidx] == "-simcheck") {
700 flag_simcheck = true;
701 continue;
702 }
703 if (args[argidx] == "-purge_lib") {
704 purge_lib = true;
705 continue;
706 }
707 if (args[argidx] == "-keep_positionals") {
708 keep_positionals = true;
709 continue;
710 }
711 if (args[argidx] == "-keep_portwidths") {
712 keep_portwidths = true;
713 continue;
714 }
715 if (args[argidx] == "-nokeep_asserts") {
716 nokeep_asserts = true;
717 continue;
718 }
719 if (args[argidx] == "-libdir" && argidx+1 < args.size()) {
720 libdirs.push_back(args[++argidx]);
721 continue;
722 }
723 if (args[argidx] == "-top") {
724 if (++argidx >= args.size())
725 log_cmd_error("Option -top requires an additional argument!\n");
726 load_top_mod = args[argidx];
727 continue;
728 }
729 if (args[argidx] == "-auto-top") {
730 auto_top_mode = true;
731 continue;
732 }
733 if (args[argidx] == "-chparam" && argidx+2 < args.size()) {
734 const std::string &key = args[++argidx];
735 const std::string &value = args[++argidx];
736 auto r = parameters.emplace(key, value);
737 if (!r.second) {
738 log_warning("-chparam %s already specified: overwriting.\n", key.c_str());
739 r.first->second = value;
740 }
741 continue;
742 }
743 break;
744 }
745 extra_args(args, argidx, design, false);
746
747 if (!load_top_mod.empty())
748 {
749 IdString top_name = RTLIL::escape_id(load_top_mod);
750 IdString abstract_id = "$abstract" + RTLIL::escape_id(load_top_mod);
751 top_mod = design->module(top_name);
752
753 dict<RTLIL::IdString, RTLIL::Const> top_parameters;
754 for (auto &para : parameters) {
755 SigSpec sig_value;
756 if (!RTLIL::SigSpec::parse(sig_value, NULL, para.second))
757 log_cmd_error("Can't decode value '%s'!\n", para.second.c_str());
758 top_parameters[RTLIL::escape_id(para.first)] = sig_value.as_const();
759 }
760
761 if (top_mod == nullptr && design->module(abstract_id))
762 top_mod = design->module(design->module(abstract_id)->derive(design, top_parameters));
763 else if (top_mod != nullptr && !top_parameters.empty())
764 top_mod = design->module(top_mod->derive(design, top_parameters));
765
766 if (top_mod != nullptr && top_mod->name != top_name) {
767 Module *m = top_mod->clone();
768 m->name = top_name;
769 Module *old_mod = design->module(top_name);
770 if (old_mod)
771 design->remove(old_mod);
772 design->add(m);
773 top_mod = m;
774 }
775 }
776
777 if (top_mod == nullptr && !load_top_mod.empty()) {
778 #ifdef YOSYS_ENABLE_VERIFIC
779 if (verific_import_pending) {
780 verific_import(design, parameters, load_top_mod);
781 top_mod = design->module(RTLIL::escape_id(load_top_mod));
782 }
783 #endif
784 if (top_mod == NULL)
785 log_cmd_error("Module `%s' not found!\n", load_top_mod.c_str());
786 } else {
787 #ifdef YOSYS_ENABLE_VERIFIC
788 if (verific_import_pending)
789 verific_import(design, parameters);
790 #endif
791 }
792
793 if (generate_mode) {
794 generate(design, generate_cells, generate_ports);
795 return;
796 }
797
798 log_push();
799
800 if (top_mod == nullptr)
801 for (auto &mod_it : design->modules_)
802 if (mod_it.second->get_bool_attribute("\\top"))
803 top_mod = mod_it.second;
804
805 if (top_mod == nullptr && auto_top_mode) {
806 log_header(design, "Finding top of design hierarchy..\n");
807 dict<Module*, int> db;
808 for (Module *mod : design->selected_modules()) {
809 int score = find_top_mod_score(design, mod, db);
810 log("root of %3d design levels: %-20s\n", score, log_id(mod));
811 if (!top_mod || score > db[top_mod])
812 top_mod = mod;
813 }
814 if (top_mod != nullptr)
815 log("Automatically selected %s as design top module.\n", log_id(top_mod));
816 }
817
818 if (flag_simcheck && top_mod == nullptr)
819 log_error("Design has no top module.\n");
820
821 if (top_mod != NULL) {
822 for (auto &mod_it : design->modules_)
823 if (mod_it.second == top_mod)
824 mod_it.second->attributes["\\initial_top"] = RTLIL::Const(1);
825 else
826 mod_it.second->attributes.erase("\\initial_top");
827 }
828
829 bool did_something = true;
830 while (did_something)
831 {
832 did_something = false;
833
834 std::set<RTLIL::Module*, IdString::compare_ptr_by_name<Module>> used_modules;
835 if (top_mod != NULL) {
836 log_header(design, "Analyzing design hierarchy..\n");
837 hierarchy_worker(design, used_modules, top_mod, 0);
838 } else {
839 for (auto mod : design->modules())
840 used_modules.insert(mod);
841 }
842
843 for (auto module : used_modules) {
844 if (expand_module(design, module, flag_check, flag_simcheck, libdirs))
845 did_something = true;
846 }
847
848
849 // The top module might have changed if interface instances have been detected in it:
850 RTLIL::Module *tmp_top_mod = check_if_top_has_changed(design, top_mod);
851 if (tmp_top_mod != NULL) {
852 if (tmp_top_mod != top_mod){
853 top_mod = tmp_top_mod;
854 did_something = true;
855 }
856 }
857
858 // Delete modules marked as 'to_delete':
859 std::vector<RTLIL::Module *> modules_to_delete;
860 for(auto &mod_it : design->modules_) {
861 if (mod_it.second->get_bool_attribute("\\to_delete")) {
862 modules_to_delete.push_back(mod_it.second);
863 }
864 }
865 for(size_t i=0; i<modules_to_delete.size(); i++) {
866 design->remove(modules_to_delete[i]);
867 }
868 }
869
870
871 if (top_mod != NULL) {
872 log_header(design, "Analyzing design hierarchy..\n");
873 hierarchy_clean(design, top_mod, purge_lib);
874 }
875
876 if (top_mod != NULL) {
877 for (auto &mod_it : design->modules_) {
878 if (mod_it.second == top_mod)
879 mod_it.second->attributes["\\top"] = RTLIL::Const(1);
880 else
881 mod_it.second->attributes.erase("\\top");
882 mod_it.second->attributes.erase("\\initial_top");
883 }
884 }
885
886 if (!nokeep_asserts) {
887 std::map<RTLIL::Module*, bool> cache;
888 for (auto mod : design->modules())
889 if (set_keep_assert(cache, mod)) {
890 log("Module %s directly or indirectly contains formal properties -> setting \"keep\" attribute.\n", log_id(mod));
891 mod->set_bool_attribute("\\keep");
892 }
893 }
894
895 if (!keep_positionals)
896 {
897 std::set<RTLIL::Module*> pos_mods;
898 std::map<std::pair<RTLIL::Module*,int>, RTLIL::IdString> pos_map;
899 std::vector<std::pair<RTLIL::Module*,RTLIL::Cell*>> pos_work;
900
901 for (auto &mod_it : design->modules_)
902 for (auto &cell_it : mod_it.second->cells_) {
903 RTLIL::Cell *cell = cell_it.second;
904 if (design->modules_.count(cell->type) == 0)
905 continue;
906 for (auto &conn : cell->connections())
907 if (conn.first[0] == '$' && '0' <= conn.first[1] && conn.first[1] <= '9') {
908 pos_mods.insert(design->modules_.at(cell->type));
909 pos_work.push_back(std::pair<RTLIL::Module*,RTLIL::Cell*>(mod_it.second, cell));
910 break;
911 }
912 }
913
914 for (auto module : pos_mods)
915 for (auto &wire_it : module->wires_) {
916 RTLIL::Wire *wire = wire_it.second;
917 if (wire->port_id > 0)
918 pos_map[std::pair<RTLIL::Module*,int>(module, wire->port_id)] = wire->name;
919 }
920
921 for (auto &work : pos_work) {
922 RTLIL::Module *module = work.first;
923 RTLIL::Cell *cell = work.second;
924 log("Mapping positional arguments of cell %s.%s (%s).\n",
925 RTLIL::id2cstr(module->name), RTLIL::id2cstr(cell->name), RTLIL::id2cstr(cell->type));
926 dict<RTLIL::IdString, RTLIL::SigSpec> new_connections;
927 for (auto &conn : cell->connections())
928 if (conn.first[0] == '$' && '0' <= conn.first[1] && conn.first[1] <= '9') {
929 int id = atoi(conn.first.c_str()+1);
930 std::pair<RTLIL::Module*,int> key(design->modules_.at(cell->type), id);
931 if (pos_map.count(key) == 0) {
932 log(" Failed to map positional argument %d of cell %s.%s (%s).\n",
933 id, RTLIL::id2cstr(module->name), RTLIL::id2cstr(cell->name), RTLIL::id2cstr(cell->type));
934 new_connections[conn.first] = conn.second;
935 } else
936 new_connections[pos_map.at(key)] = conn.second;
937 } else
938 new_connections[conn.first] = conn.second;
939 cell->connections_ = new_connections;
940 }
941 }
942
943 std::set<Module*> blackbox_derivatives;
944 std::vector<Module*> design_modules = design->modules();
945
946 for (auto module : design_modules)
947 {
948 pool<Wire*> wand_wor_index;
949 dict<Wire*, SigSpec> wand_map, wor_map;
950 vector<SigSig> new_connections;
951
952 for (auto wire : module->wires())
953 {
954 if (wire->get_bool_attribute("\\wand")) {
955 wand_map[wire] = SigSpec();
956 wand_wor_index.insert(wire);
957 }
958 if (wire->get_bool_attribute("\\wor")) {
959 wor_map[wire] = SigSpec();
960 wand_wor_index.insert(wire);
961 }
962 }
963
964 for (auto &conn : module->connections())
965 {
966 SigSig new_conn;
967 int cursor = 0;
968
969 for (auto c : conn.first.chunks())
970 {
971 Wire *w = c.wire;
972 SigSpec rhs = conn.second.extract(cursor, GetSize(c));
973
974 if (wand_wor_index.count(w) == 0) {
975 new_conn.first.append(c);
976 new_conn.second.append(rhs);
977 } else {
978 if (wand_map.count(w)) {
979 SigSpec sig = SigSpec(State::S1, GetSize(w));
980 sig.replace(c.offset, rhs);
981 wand_map.at(w).append(sig);
982 } else {
983 SigSpec sig = SigSpec(State::S0, GetSize(w));
984 sig.replace(c.offset, rhs);
985 wor_map.at(w).append(sig);
986 }
987 }
988 cursor += GetSize(c);
989 }
990 new_connections.push_back(new_conn);
991 }
992 module->new_connections(new_connections);
993
994 for (auto cell : module->cells())
995 {
996 if (!cell->known())
997 continue;
998
999 for (auto &conn : cell->connections())
1000 {
1001 if (!cell->output(conn.first))
1002 continue;
1003
1004 SigSpec new_sig;
1005 bool update_port = false;
1006
1007 for (auto c : conn.second.chunks())
1008 {
1009 Wire *w = c.wire;
1010
1011 if (wand_wor_index.count(w) == 0) {
1012 new_sig.append(c);
1013 continue;
1014 }
1015
1016 Wire *t = module->addWire(NEW_ID, GetSize(c));
1017 new_sig.append(t);
1018 update_port = true;
1019
1020 if (wand_map.count(w)) {
1021 SigSpec sig = SigSpec(State::S1, GetSize(w));
1022 sig.replace(c.offset, t);
1023 wand_map.at(w).append(sig);
1024 } else {
1025 SigSpec sig = SigSpec(State::S0, GetSize(w));
1026 sig.replace(c.offset, t);
1027 wor_map.at(w).append(sig);
1028 }
1029 }
1030
1031 if (update_port)
1032 cell->setPort(conn.first, new_sig);
1033 }
1034 }
1035
1036 for (auto w : wand_wor_index)
1037 {
1038 bool wand = wand_map.count(w);
1039 SigSpec sigs = wand ? wand_map.at(w) : wor_map.at(w);
1040
1041 if (GetSize(sigs) == 0)
1042 continue;
1043
1044 if (GetSize(w) == 1) {
1045 if (wand)
1046 module->addReduceAnd(NEW_ID, sigs, w);
1047 else
1048 module->addReduceOr(NEW_ID, sigs, w);
1049 continue;
1050 }
1051
1052 SigSpec s = sigs.extract(0, GetSize(w));
1053 for (int i = GetSize(w); i < GetSize(sigs); i += GetSize(w)) {
1054 if (wand)
1055 s = module->And(NEW_ID, s, sigs.extract(i, GetSize(w)));
1056 else
1057 s = module->Or(NEW_ID, s, sigs.extract(i, GetSize(w)));
1058 }
1059 module->connect(w, s);
1060 }
1061
1062 for (auto cell : module->cells())
1063 {
1064 Module *m = design->module(cell->type);
1065
1066 if (m == nullptr)
1067 continue;
1068
1069 if (m->get_blackbox_attribute() && !cell->parameters.empty() && m->get_bool_attribute("\\dynports")) {
1070 IdString new_m_name = m->derive(design, cell->parameters, true);
1071 if (new_m_name.empty())
1072 continue;
1073 if (new_m_name != m->name) {
1074 m = design->module(new_m_name);
1075 blackbox_derivatives.insert(m);
1076 }
1077 }
1078
1079 for (auto &conn : cell->connections())
1080 {
1081 Wire *w = m->wire(conn.first);
1082
1083 if (w == nullptr || w->port_id == 0)
1084 continue;
1085
1086 if (GetSize(conn.second) == 0)
1087 continue;
1088
1089 SigSpec sig = conn.second;
1090
1091 if (!keep_portwidths && GetSize(w) != GetSize(conn.second))
1092 {
1093 if (GetSize(w) < GetSize(conn.second))
1094 {
1095 int n = GetSize(conn.second) - GetSize(w);
1096 if (!w->port_input && w->port_output)
1097 module->connect(sig.extract(GetSize(w), n), Const(0, n));
1098 sig.remove(GetSize(w), n);
1099 }
1100 else
1101 {
1102 int n = GetSize(w) - GetSize(conn.second);
1103 if (w->port_input && !w->port_output)
1104 sig.append(Const(0, n));
1105 else
1106 sig.append(module->addWire(NEW_ID, n));
1107 }
1108
1109 if (!conn.second.is_fully_const() || !w->port_input || w->port_output)
1110 log_warning("Resizing cell port %s.%s.%s from %d bits to %d bits.\n", log_id(module), log_id(cell),
1111 log_id(conn.first), GetSize(conn.second), GetSize(sig));
1112 cell->setPort(conn.first, sig);
1113 }
1114
1115 if (w->port_output && !w->port_input && sig.has_const())
1116 log_error("Output port %s.%s.%s (%s) is connected to constants: %s\n",
1117 log_id(module), log_id(cell), log_id(conn.first), log_id(cell->type), log_signal(sig));
1118 }
1119 }
1120 }
1121
1122 for (auto module : blackbox_derivatives)
1123 design->remove(module);
1124
1125 log_pop();
1126 }
1127 } HierarchyPass;
1128
1129 PRIVATE_NAMESPACE_END