Add fileinfo to firrtl backend for assignments and non-instance cells
[yosys.git] / backends / firrtl / firrtl.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/rtlil.h"
21 #include "kernel/register.h"
22 #include "kernel/sigtools.h"
23 #include "kernel/celltypes.h"
24 #include "kernel/cellaigs.h"
25 #include "kernel/log.h"
26 #include <algorithm>
27 #include <string>
28 #include <vector>
29 #include <cmath>
30
31 USING_YOSYS_NAMESPACE
32 PRIVATE_NAMESPACE_BEGIN
33
34 pool<string> used_names;
35 dict<IdString, string> namecache;
36 int autoid_counter;
37
38 typedef unsigned FDirection;
39 static const FDirection FD_NODIRECTION = 0x0;
40 static const FDirection FD_IN = 0x1;
41 static const FDirection FD_OUT = 0x2;
42 static const FDirection FD_INOUT = 0x3;
43 static const int FIRRTL_MAX_DSH_WIDTH_ERROR = 20; // For historic reasons, this is actually one greater than the maximum allowed shift width
44
45 // Shamelessly copied from ilang_backend.cc. Something better is surely possible here.
46 void dump_const(std::ostream &f, const RTLIL::Const &data, int width = -1, int offset = 0, bool autoint = true)
47 {
48 if (width < 0)
49 width = data.bits.size() - offset;
50 if ((data.flags & RTLIL::CONST_FLAG_STRING) == 0 || width != (int)data.bits.size()) {
51 if (width == 32 && autoint) {
52 int32_t val = 0;
53 for (int i = 0; i < width; i++) {
54 log_assert(offset+i < (int)data.bits.size());
55 switch (data.bits[offset+i]) {
56 case RTLIL::S0: break;
57 case RTLIL::S1: val |= 1 << i; break;
58 default: val = -1; break;
59 }
60 }
61 if (val >= 0) {
62 f << stringf("%d", val);
63 return;
64 }
65 }
66 f << stringf("%d'", width);
67 for (int i = offset+width-1; i >= offset; i--) {
68 log_assert(i < (int)data.bits.size());
69 switch (data.bits[i]) {
70 case RTLIL::S0: f << stringf("0"); break;
71 case RTLIL::S1: f << stringf("1"); break;
72 case RTLIL::Sx: f << stringf("x"); break;
73 case RTLIL::Sz: f << stringf("z"); break;
74 case RTLIL::Sa: f << stringf("-"); break;
75 case RTLIL::Sm: f << stringf("m"); break;
76 }
77 }
78 } else {
79 f << stringf("\"");
80 std::string str = data.decode_string();
81 for (size_t i = 0; i < str.size(); i++) {
82 if (str[i] == '\n')
83 f << stringf("\\n");
84 else if (str[i] == '\t')
85 f << stringf("\\t");
86 else if (str[i] < 32)
87 f << stringf("\\%03o", str[i]);
88 else if (str[i] == '"')
89 f << stringf("\\\"");
90 else if (str[i] == '\\')
91 f << stringf("\\\\");
92 else
93 f << str[i];
94 }
95 f << stringf("\"");
96 }
97 }
98
99 std::string getFileinfo(dict<RTLIL::IdString, RTLIL::Const> attributes)
100 {
101 std::ostringstream fileinfo;
102 for (auto &it : attributes) {
103 if (it.first == "\\src") {
104 fileinfo << "@[";
105 dump_const(fileinfo, it.second);
106 fileinfo << "]";
107 }
108 }
109 return fileinfo.str();
110 }
111
112 // Get a port direction with respect to a specific module.
113 FDirection getPortFDirection(IdString id, Module *module)
114 {
115 Wire *wire = module->wires_.at(id);
116 FDirection direction = FD_NODIRECTION;
117 if (wire && wire->port_id)
118 {
119 if (wire->port_input)
120 direction |= FD_IN;
121 if (wire->port_output)
122 direction |= FD_OUT;
123 }
124 return direction;
125 }
126
127 string next_id()
128 {
129 string new_id;
130
131 while (1) {
132 new_id = stringf("_%d", autoid_counter++);
133 if (used_names.count(new_id) == 0) break;
134 }
135
136 used_names.insert(new_id);
137 return new_id;
138 }
139
140 const char *make_id(IdString id)
141 {
142 if (namecache.count(id) != 0)
143 return namecache.at(id).c_str();
144
145 string new_id = log_id(id);
146
147 for (int i = 0; i < GetSize(new_id); i++)
148 {
149 char &ch = new_id[i];
150 if ('a' <= ch && ch <= 'z') continue;
151 if ('A' <= ch && ch <= 'Z') continue;
152 if ('0' <= ch && ch <= '9' && i != 0) continue;
153 if ('_' == ch) continue;
154 ch = '_';
155 }
156
157 while (used_names.count(new_id) != 0)
158 new_id += '_';
159
160 namecache[id] = new_id;
161 used_names.insert(new_id);
162 return namecache.at(id).c_str();
163 }
164
165 struct FirrtlWorker
166 {
167 Module *module;
168 std::ostream &f;
169
170 dict<SigBit, pair<string, int>> reverse_wire_map;
171 string unconn_id;
172 RTLIL::Design *design;
173 std::string indent;
174
175 // Define read/write ports and memories.
176 // We'll collect their definitions and emit the corresponding FIRRTL definitions at the appropriate point in module construction.
177 // For the moment, we don't handle $readmemh or $readmemb.
178 // These will be part of a subsequent PR.
179 struct read_port {
180 string name;
181 bool clk_enable;
182 bool clk_parity;
183 bool transparent;
184 RTLIL::SigSpec clk;
185 RTLIL::SigSpec ena;
186 RTLIL::SigSpec addr;
187 read_port(string name, bool clk_enable, bool clk_parity, bool transparent, RTLIL::SigSpec clk, RTLIL::SigSpec ena, RTLIL::SigSpec addr) : name(name), clk_enable(clk_enable), clk_parity(clk_parity), transparent(transparent), clk(clk), ena(ena), addr(addr) {
188 // Current (3/13/2019) conventions:
189 // generate a constant 0 for clock and a constant 1 for enable if they are undefined.
190 if (!clk.is_fully_def())
191 this->clk = SigSpec(State::S0);
192 if (!ena.is_fully_def())
193 this->ena = SigSpec(State::S1);
194 }
195 string gen_read(const char * indent) {
196 string addr_expr = make_expr(addr);
197 string ena_expr = make_expr(ena);
198 string clk_expr = make_expr(clk);
199 string addr_str = stringf("%s%s.addr <= %s\n", indent, name.c_str(), addr_expr.c_str());
200 string ena_str = stringf("%s%s.en <= %s\n", indent, name.c_str(), ena_expr.c_str());
201 string clk_str = stringf("%s%s.clk <= asClock(%s)\n", indent, name.c_str(), clk_expr.c_str());
202 return addr_str + ena_str + clk_str;
203 }
204 };
205 struct write_port : read_port {
206 RTLIL::SigSpec mask;
207 write_port(string name, bool clk_enable, bool clk_parity, bool transparent, RTLIL::SigSpec clk, RTLIL::SigSpec ena, RTLIL::SigSpec addr, RTLIL::SigSpec mask) : read_port(name, clk_enable, clk_parity, transparent, clk, ena, addr), mask(mask) {
208 if (!clk.is_fully_def())
209 this->clk = SigSpec(RTLIL::Const(0));
210 if (!ena.is_fully_def())
211 this->ena = SigSpec(RTLIL::Const(0));
212 if (!mask.is_fully_def())
213 this->ena = SigSpec(RTLIL::Const(1));
214 }
215 string gen_read(const char * /* indent */) {
216 log_error("gen_read called on write_port: %s\n", name.c_str());
217 return stringf("gen_read called on write_port: %s\n", name.c_str());
218 }
219 string gen_write(const char * indent) {
220 string addr_expr = make_expr(addr);
221 string ena_expr = make_expr(ena);
222 string clk_expr = make_expr(clk);
223 string mask_expr = make_expr(mask);
224 string mask_str = stringf("%s%s.mask <= %s\n", indent, name.c_str(), mask_expr.c_str());
225 string addr_str = stringf("%s%s.addr <= %s\n", indent, name.c_str(), addr_expr.c_str());
226 string ena_str = stringf("%s%s.en <= %s\n", indent, name.c_str(), ena_expr.c_str());
227 string clk_str = stringf("%s%s.clk <= asClock(%s)\n", indent, name.c_str(), clk_expr.c_str());
228 return addr_str + ena_str + clk_str + mask_str;
229 }
230 };
231 /* Memories defined within this module. */
232 struct memory {
233 Cell *pCell; // for error reporting
234 string name; // memory name
235 int abits; // number of address bits
236 int size; // size (in units) of the memory
237 int width; // size (in bits) of each element
238 int read_latency;
239 int write_latency;
240 vector<read_port> read_ports;
241 vector<write_port> write_ports;
242 std::string init_file;
243 std::string init_file_srcFileSpec;
244 string srcLine;
245 memory(Cell *pCell, string name, int abits, int size, int width) : pCell(pCell), name(name), abits(abits), size(size), width(width), read_latency(0), write_latency(1), init_file(""), init_file_srcFileSpec("") {
246 // Provide defaults for abits or size if one (but not the other) is specified.
247 if (this->abits == 0 && this->size != 0) {
248 this->abits = ceil_log2(this->size);
249 } else if (this->abits != 0 && this->size == 0) {
250 this->size = 1 << this->abits;
251 }
252 // Sanity-check this construction.
253 if (this->name == "") {
254 log_error("Nameless memory%s\n", this->atLine());
255 }
256 if (this->abits == 0 && this->size == 0) {
257 log_error("Memory %s has zero address bits and size%s\n", this->name.c_str(), this->atLine());
258 }
259 if (this->width == 0) {
260 log_error("Memory %s has zero width%s\n", this->name.c_str(), this->atLine());
261 }
262 }
263 // We need a default constructor for the dict insert.
264 memory() : pCell(0), read_latency(0), write_latency(1), init_file(""), init_file_srcFileSpec(""){}
265
266 const char *atLine() {
267 if (srcLine == "") {
268 if (pCell) {
269 auto p = pCell->attributes.find("\\src");
270 srcLine = " at " + p->second.decode_string();
271 }
272 }
273 return srcLine.c_str();
274 }
275 void add_memory_read_port(read_port &rp) {
276 read_ports.push_back(rp);
277 }
278 void add_memory_write_port(write_port &wp) {
279 write_ports.push_back(wp);
280 }
281 void add_memory_file(std::string init_file, std::string init_file_srcFileSpec) {
282 this->init_file = init_file;
283 this->init_file_srcFileSpec = init_file_srcFileSpec;
284 }
285
286 };
287 dict<string, memory> memories;
288
289 void register_memory(memory &m)
290 {
291 memories[m.name] = m;
292 }
293
294 void register_reverse_wire_map(string id, SigSpec sig)
295 {
296 for (int i = 0; i < GetSize(sig); i++)
297 reverse_wire_map[sig[i]] = make_pair(id, i);
298 }
299
300 FirrtlWorker(Module *module, std::ostream &f, RTLIL::Design *theDesign) : module(module), f(f), design(theDesign), indent(" ")
301 {
302 }
303
304 static string make_expr(const SigSpec &sig)
305 {
306 string expr;
307
308 for (auto chunk : sig.chunks())
309 {
310 string new_expr;
311
312 if (chunk.wire == nullptr)
313 {
314 std::vector<RTLIL::State> bits = chunk.data;
315 new_expr = stringf("UInt<%d>(\"h", GetSize(bits));
316
317 while (GetSize(bits) % 4 != 0)
318 bits.push_back(State::S0);
319
320 for (int i = GetSize(bits)-4; i >= 0; i -= 4)
321 {
322 int val = 0;
323 if (bits[i+0] == State::S1) val += 1;
324 if (bits[i+1] == State::S1) val += 2;
325 if (bits[i+2] == State::S1) val += 4;
326 if (bits[i+3] == State::S1) val += 8;
327 new_expr.push_back(val < 10 ? '0' + val : 'a' + val - 10);
328 }
329
330 new_expr += "\")";
331 }
332 else if (chunk.offset == 0 && chunk.width == chunk.wire->width)
333 {
334 new_expr = make_id(chunk.wire->name);
335 }
336 else
337 {
338 string wire_id = make_id(chunk.wire->name);
339 new_expr = stringf("bits(%s, %d, %d)", wire_id.c_str(), chunk.offset + chunk.width - 1, chunk.offset);
340 }
341
342 if (expr.empty())
343 expr = new_expr;
344 else
345 expr = "cat(" + new_expr + ", " + expr + ")";
346 }
347
348 return expr;
349 }
350
351 std::string fid(RTLIL::IdString internal_id)
352 {
353 return make_id(internal_id);
354 }
355
356 std::string cellname(RTLIL::Cell *cell)
357 {
358 return fid(cell->name).c_str();
359 }
360
361 void process_instance(RTLIL::Cell *cell, vector<string> &wire_exprs)
362 {
363 std::string cell_type = fid(cell->type);
364 std::string instanceOf;
365 // If this is a parameterized module, its parent module is encoded in the cell type
366 if (cell->type.begins_with("$paramod"))
367 {
368 std::string::iterator it;
369 for (it = cell_type.begin(); it < cell_type.end(); it++)
370 {
371 switch (*it) {
372 case '\\': /* FALL_THROUGH */
373 case '=': /* FALL_THROUGH */
374 case '\'': /* FALL_THROUGH */
375 case '$': instanceOf.append("_"); break;
376 default: instanceOf.append(1, *it); break;
377 }
378 }
379 }
380 else
381 {
382 instanceOf = cell_type;
383 }
384
385 std::string cell_name = cellname(cell);
386 std::string cell_name_comment;
387 if (cell_name != fid(cell->name))
388 cell_name_comment = " /* " + fid(cell->name) + " */ ";
389 else
390 cell_name_comment = "";
391 // Find the module corresponding to this instance.
392 auto instModule = design->module(cell->type);
393 // If there is no instance for this, just return.
394 if (instModule == NULL)
395 {
396 log_warning("No instance for %s.%s\n", cell_type.c_str(), cell_name.c_str());
397 return;
398 }
399 auto cellFileinfo = getFileinfo(cell->attributes);
400 wire_exprs.push_back(stringf("%s" "inst %s%s of %s %s", indent.c_str(), cell_name.c_str(), cell_name_comment.c_str(), instanceOf.c_str(), cellFileinfo.c_str()));
401
402 for (auto it = cell->connections().begin(); it != cell->connections().end(); ++it) {
403 if (it->second.size() > 0) {
404 const SigSpec &secondSig = it->second;
405 const std::string firstName = cell_name + "." + make_id(it->first);
406 const std::string secondExpr = make_expr(secondSig);
407 // Find the direction for this port.
408 FDirection dir = getPortFDirection(it->first, instModule);
409 std::string sourceExpr, sinkExpr;
410 const SigSpec *sinkSig = nullptr;
411 switch (dir) {
412 case FD_INOUT:
413 log_warning("Instance port connection %s.%s is INOUT; treating as OUT\n", cell_type.c_str(), log_signal(it->second));
414 /* FALLTHRU */
415 case FD_OUT:
416 sourceExpr = firstName;
417 sinkExpr = secondExpr;
418 sinkSig = &secondSig;
419 break;
420 case FD_NODIRECTION:
421 log_warning("Instance port connection %s.%s is NODIRECTION; treating as IN\n", cell_type.c_str(), log_signal(it->second));
422 /* FALLTHRU */
423 case FD_IN:
424 sourceExpr = secondExpr;
425 sinkExpr = firstName;
426 break;
427 default:
428 log_error("Instance port %s.%s unrecognized connection direction 0x%x !\n", cell_type.c_str(), log_signal(it->second), dir);
429 break;
430 }
431 // Check for subfield assignment.
432 std::string bitsString = "bits(";
433 if (sinkExpr.compare(0, bitsString.length(), bitsString) == 0) {
434 if (sinkSig == nullptr)
435 log_error("Unknown subfield %s.%s\n", cell_type.c_str(), sinkExpr.c_str());
436 // Don't generate the assignment here.
437 // Add the source and sink to the "reverse_wire_map" and we'll output the assignment
438 // as part of the coalesced subfield assignments for this wire.
439 register_reverse_wire_map(sourceExpr, *sinkSig);
440 } else {
441 wire_exprs.push_back(stringf("\n%s%s <= %s %s", indent.c_str(), sinkExpr.c_str(), sourceExpr.c_str(), cellFileinfo.c_str()));
442 }
443 }
444 }
445 wire_exprs.push_back(stringf("\n"));
446
447 }
448
449 // Given an expression for a shift amount, and a maximum width,
450 // generate the FIRRTL expression for equivalent dynamic shift taking into account FIRRTL shift semantics.
451 std::string gen_dshl(const string b_expr, const int b_width)
452 {
453 string result = b_expr;
454 if (b_width >= FIRRTL_MAX_DSH_WIDTH_ERROR) {
455 int max_shift_width_bits = FIRRTL_MAX_DSH_WIDTH_ERROR - 1;
456 string max_shift_string = stringf("UInt<%d>(%d)", max_shift_width_bits, (1<<max_shift_width_bits) - 1);
457 // Deal with the difference in semantics between FIRRTL and verilog
458 result = stringf("mux(gt(%s, %s), %s, bits(%s, %d, 0))", b_expr.c_str(), max_shift_string.c_str(), max_shift_string.c_str(), b_expr.c_str(), max_shift_width_bits - 1);
459 }
460 return result;
461 }
462
463 void run()
464 {
465 auto moduleFileinfo = getFileinfo(module->attributes);
466 f << stringf(" module %s: %s\n", make_id(module->name), moduleFileinfo.c_str());
467 vector<string> port_decls, wire_decls, cell_exprs, wire_exprs;
468
469 for (auto wire : module->wires())
470 {
471 const auto wireName = make_id(wire->name);
472 auto wireFileinfo = getFileinfo(wire->attributes);
473
474 // If a wire has initial data, issue a warning since FIRRTL doesn't currently support it.
475 if (wire->attributes.count("\\init")) {
476 log_warning("Initial value (%s) for (%s.%s) not supported\n",
477 wire->attributes.at("\\init").as_string().c_str(),
478 log_id(module), log_id(wire));
479 }
480 if (wire->port_id)
481 {
482 if (wire->port_input && wire->port_output)
483 log_error("Module port %s.%s is inout!\n", log_id(module), log_id(wire));
484 port_decls.push_back(stringf(" %s %s: UInt<%d> %s\n", wire->port_input ? "input" : "output",
485 wireName, wire->width, wireFileinfo.c_str()));
486 }
487 else
488 {
489 wire_decls.push_back(stringf(" wire %s: UInt<%d> %s\n", wireName, wire->width, wireFileinfo.c_str()));
490 }
491 }
492
493 for (auto cell : module->cells())
494 {
495 static Const ndef(0, 0);
496
497 // Is this cell is a module instance?
498 if (cell->type[0] != '$')
499 {
500 process_instance(cell, wire_exprs);
501 continue;
502 }
503 // Not a module instance. Set up cell properties
504 bool extract_y_bits = false; // Assume no extraction of final bits will be required.
505 int a_width = cell->parameters.at("\\A_WIDTH", ndef).as_int(); // The width of "A"
506 int b_width = cell->parameters.at("\\B_WIDTH", ndef).as_int(); // The width of "A"
507 const int y_width = cell->parameters.at("\\Y_WIDTH", ndef).as_int(); // The width of the result
508 const bool a_signed = cell->parameters.at("\\A_SIGNED", ndef).as_bool();
509 const bool b_signed = cell->parameters.at("\\B_SIGNED", ndef).as_bool();
510 bool firrtl_is_signed = a_signed; // The result is signed (subsequent code may change this).
511 int firrtl_width = 0;
512 string primop;
513 bool always_uint = false;
514 string y_id = make_id(cell->name);
515 std::string cellFileinfo = getFileinfo(cell->attributes);
516
517 if (cell->type.in("$not", "$logic_not", "$neg", "$reduce_and", "$reduce_or", "$reduce_xor", "$reduce_bool", "$reduce_xnor"))
518 {
519 string a_expr = make_expr(cell->getPort("\\A"));
520 wire_decls.push_back(stringf(" wire %s: UInt<%d> %s\n", y_id.c_str(), y_width, cellFileinfo.c_str()));
521
522 if (a_signed) {
523 a_expr = "asSInt(" + a_expr + ")";
524 }
525
526 // Don't use the results of logical operations (a single bit) to control padding
527 if (!(cell->type.in("$eq", "$eqx", "$gt", "$ge", "$lt", "$le", "$ne", "$nex", "$reduce_bool", "$logic_not") && y_width == 1) ) {
528 a_expr = stringf("pad(%s, %d)", a_expr.c_str(), y_width);
529 }
530
531 // Assume the FIRRTL width is a single bit.
532 firrtl_width = 1;
533 if (cell->type == "$not") primop = "not";
534 else if (cell->type == "$neg") {
535 primop = "neg";
536 firrtl_is_signed = true; // Result of "neg" is signed (an SInt).
537 firrtl_width = a_width;
538 } else if (cell->type == "$logic_not") {
539 primop = "eq";
540 a_expr = stringf("%s, UInt(0)", a_expr.c_str());
541 }
542 else if (cell->type == "$reduce_and") primop = "andr";
543 else if (cell->type == "$reduce_or") primop = "orr";
544 else if (cell->type == "$reduce_xor") primop = "xorr";
545 else if (cell->type == "$reduce_xnor") {
546 primop = "not";
547 a_expr = stringf("xorr(%s)", a_expr.c_str());
548 }
549 else if (cell->type == "$reduce_bool") {
550 primop = "neq";
551 // Use the sign of the a_expr and its width as the type (UInt/SInt) and width of the comparand.
552 a_expr = stringf("%s, %cInt<%d>(0)", a_expr.c_str(), a_signed ? 'S' : 'U', a_width);
553 }
554
555 string expr = stringf("%s(%s)", primop.c_str(), a_expr.c_str());
556
557 if ((firrtl_is_signed && !always_uint))
558 expr = stringf("asUInt(%s)", expr.c_str());
559
560 cell_exprs.push_back(stringf(" %s <= %s %s\n", y_id.c_str(), expr.c_str(), cellFileinfo.c_str()));
561 register_reverse_wire_map(y_id, cell->getPort("\\Y"));
562
563 continue;
564 }
565 if (cell->type.in("$add", "$sub", "$mul", "$div", "$mod", "$xor", "$xnor", "$and", "$or", "$eq", "$eqx",
566 "$gt", "$ge", "$lt", "$le", "$ne", "$nex", "$shr", "$sshr", "$sshl", "$shl",
567 "$logic_and", "$logic_or", "$pow"))
568 {
569 string a_expr = make_expr(cell->getPort("\\A"));
570 string b_expr = make_expr(cell->getPort("\\B"));
571 std::string cellFileinfo = getFileinfo(cell->attributes);
572 wire_decls.push_back(stringf(" wire %s: UInt<%d> %s\n", y_id.c_str(), y_width, cellFileinfo.c_str()));
573
574 if (a_signed) {
575 a_expr = "asSInt(" + a_expr + ")";
576 // Expand the "A" operand to the result width
577 if (a_width < y_width) {
578 a_expr = stringf("pad(%s, %d)", a_expr.c_str(), y_width);
579 a_width = y_width;
580 }
581 }
582 // Shift amount is always unsigned, and needn't be padded to result width,
583 // otherwise, we need to cast the b_expr appropriately
584 if (b_signed && !cell->type.in("$shr", "$sshr", "$shl", "$sshl", "$pow")) {
585 b_expr = "asSInt(" + b_expr + ")";
586 // Expand the "B" operand to the result width
587 if (b_width < y_width) {
588 b_expr = stringf("pad(%s, %d)", b_expr.c_str(), y_width);
589 b_width = y_width;
590 }
591 }
592
593 // For the arithmetic ops, expand operand widths to result widths befor performing the operation.
594 // This corresponds (according to iverilog) to what verilog compilers implement.
595 if (cell->type.in("$add", "$sub", "$mul", "$div", "$mod", "$xor", "$xnor", "$and", "$or"))
596 {
597 if (a_width < y_width) {
598 a_expr = stringf("pad(%s, %d)", a_expr.c_str(), y_width);
599 a_width = y_width;
600 }
601 if (b_width < y_width) {
602 b_expr = stringf("pad(%s, %d)", b_expr.c_str(), y_width);
603 b_width = y_width;
604 }
605 }
606 // Assume the FIRRTL width is the width of "A"
607 firrtl_width = a_width;
608 auto a_sig = cell->getPort("\\A");
609
610 if (cell->type == "$add") {
611 primop = "add";
612 firrtl_is_signed = a_signed | b_signed;
613 firrtl_width = max(a_width, b_width);
614 } else if (cell->type == "$sub") {
615 primop = "sub";
616 firrtl_is_signed = true;
617 int a_widthInc = (!a_signed && b_signed) ? 2 : (a_signed && !b_signed) ? 1 : 0;
618 int b_widthInc = (a_signed && !b_signed) ? 2 : (!a_signed && b_signed) ? 1 : 0;
619 firrtl_width = max(a_width + a_widthInc, b_width + b_widthInc);
620 } else if (cell->type == "$mul") {
621 primop = "mul";
622 firrtl_is_signed = a_signed | b_signed;
623 firrtl_width = a_width + b_width;
624 } else if (cell->type == "$div") {
625 primop = "div";
626 firrtl_is_signed = a_signed | b_signed;
627 firrtl_width = a_width;
628 } else if (cell->type == "$mod") {
629 primop = "rem";
630 firrtl_width = min(a_width, b_width);
631 } else if (cell->type == "$and") {
632 primop = "and";
633 always_uint = true;
634 firrtl_width = max(a_width, b_width);
635 }
636 else if (cell->type == "$or" ) {
637 primop = "or";
638 always_uint = true;
639 firrtl_width = max(a_width, b_width);
640 }
641 else if (cell->type == "$xor") {
642 primop = "xor";
643 always_uint = true;
644 firrtl_width = max(a_width, b_width);
645 }
646 else if (cell->type == "$xnor") {
647 primop = "xnor";
648 always_uint = true;
649 firrtl_width = max(a_width, b_width);
650 }
651 else if ((cell->type == "$eq") | (cell->type == "$eqx")) {
652 primop = "eq";
653 always_uint = true;
654 firrtl_width = 1;
655 }
656 else if ((cell->type == "$ne") | (cell->type == "$nex")) {
657 primop = "neq";
658 always_uint = true;
659 firrtl_width = 1;
660 }
661 else if (cell->type == "$gt") {
662 primop = "gt";
663 always_uint = true;
664 firrtl_width = 1;
665 }
666 else if (cell->type == "$ge") {
667 primop = "geq";
668 always_uint = true;
669 firrtl_width = 1;
670 }
671 else if (cell->type == "$lt") {
672 primop = "lt";
673 always_uint = true;
674 firrtl_width = 1;
675 }
676 else if (cell->type == "$le") {
677 primop = "leq";
678 always_uint = true;
679 firrtl_width = 1;
680 }
681 else if ((cell->type == "$shl") | (cell->type == "$sshl")) {
682 // FIRRTL will widen the result (y) by the amount of the shift.
683 // We'll need to offset this by extracting the un-widened portion as Verilog would do.
684 extract_y_bits = true;
685 // Is the shift amount constant?
686 auto b_sig = cell->getPort("\\B");
687 if (b_sig.is_fully_const()) {
688 primop = "shl";
689 int shift_amount = b_sig.as_int();
690 b_expr = std::to_string(shift_amount);
691 firrtl_width = a_width + shift_amount;
692 } else {
693 primop = "dshl";
694 // Convert from FIRRTL left shift semantics.
695 b_expr = gen_dshl(b_expr, b_width);
696 firrtl_width = a_width + (1 << b_width) - 1;
697 }
698 }
699 else if ((cell->type == "$shr") | (cell->type == "$sshr")) {
700 // We don't need to extract a specific range of bits.
701 extract_y_bits = false;
702 // Is the shift amount constant?
703 auto b_sig = cell->getPort("\\B");
704 if (b_sig.is_fully_const()) {
705 primop = "shr";
706 int shift_amount = b_sig.as_int();
707 b_expr = std::to_string(shift_amount);
708 firrtl_width = max(1, a_width - shift_amount);
709 } else {
710 primop = "dshr";
711 firrtl_width = a_width;
712 }
713 // We'll need to do some special fixups if the source (and thus result) is signed.
714 if (firrtl_is_signed) {
715 // If this is a "logical" shift right, pretend the source is unsigned.
716 if (cell->type == "$shr") {
717 a_expr = "asUInt(" + a_expr + ")";
718 }
719 }
720 }
721 else if ((cell->type == "$logic_and")) {
722 primop = "and";
723 a_expr = "neq(" + a_expr + ", UInt(0))";
724 b_expr = "neq(" + b_expr + ", UInt(0))";
725 always_uint = true;
726 firrtl_width = 1;
727 }
728 else if ((cell->type == "$logic_or")) {
729 primop = "or";
730 a_expr = "neq(" + a_expr + ", UInt(0))";
731 b_expr = "neq(" + b_expr + ", UInt(0))";
732 always_uint = true;
733 firrtl_width = 1;
734 }
735 else if ((cell->type == "$pow")) {
736 if (a_sig.is_fully_const() && a_sig.as_int() == 2) {
737 // We'll convert this to a shift. To simplify things, change the a_expr to "1"
738 // so we can use b_expr directly as a shift amount.
739 // Only support 2 ** N (i.e., shift left)
740 // FIRRTL will widen the result (y) by the amount of the shift.
741 // We'll need to offset this by extracting the un-widened portion as Verilog would do.
742 a_expr = firrtl_is_signed ? "SInt(1)" : "UInt(1)";
743 extract_y_bits = true;
744 // Is the shift amount constant?
745 auto b_sig = cell->getPort("\\B");
746 if (b_sig.is_fully_const()) {
747 primop = "shl";
748 int shiftAmount = b_sig.as_int();
749 if (shiftAmount < 0) {
750 log_error("Negative power exponent - %d: %s.%s\n", shiftAmount, log_id(module), log_id(cell));
751 }
752 b_expr = std::to_string(shiftAmount);
753 firrtl_width = a_width + shiftAmount;
754 } else {
755 primop = "dshl";
756 // Convert from FIRRTL left shift semantics.
757 b_expr = gen_dshl(b_expr, b_width);
758 firrtl_width = a_width + (1 << b_width) - 1;
759 }
760 } else {
761 log_error("Non power 2: %s.%s\n", log_id(module), log_id(cell));
762 }
763 }
764
765 if (!cell->parameters.at("\\B_SIGNED").as_bool()) {
766 b_expr = "asUInt(" + b_expr + ")";
767 }
768
769 string expr;
770 // Deal with $xnor == ~^ (not xor)
771 if (primop == "xnor") {
772 expr = stringf("not(xor(%s, %s))", a_expr.c_str(), b_expr.c_str());
773 } else {
774 expr = stringf("%s(%s, %s)", primop.c_str(), a_expr.c_str(), b_expr.c_str());
775 }
776
777 // Deal with FIRRTL's "shift widens" semantics, or the need to widen the FIRRTL result.
778 // If the operation is signed, the FIRRTL width will be 1 one bit larger.
779 if (extract_y_bits) {
780 expr = stringf("bits(%s, %d, 0)", expr.c_str(), y_width - 1);
781 } else if (firrtl_is_signed && (firrtl_width + 1) < y_width) {
782 expr = stringf("pad(%s, %d)", expr.c_str(), y_width);
783 }
784
785 if ((firrtl_is_signed && !always_uint))
786 expr = stringf("asUInt(%s)", expr.c_str());
787
788 cell_exprs.push_back(stringf(" %s <= %s %s\n", y_id.c_str(), expr.c_str(), cellFileinfo.c_str()));
789 register_reverse_wire_map(y_id, cell->getPort("\\Y"));
790
791 continue;
792 }
793
794 if (cell->type.in("$mux"))
795 {
796 int width = cell->parameters.at("\\WIDTH").as_int();
797 string a_expr = make_expr(cell->getPort("\\A"));
798 string b_expr = make_expr(cell->getPort("\\B"));
799 string s_expr = make_expr(cell->getPort("\\S"));
800 wire_decls.push_back(stringf(" wire %s: UInt<%d> %s\n", y_id.c_str(), width, cellFileinfo.c_str()));
801
802 string expr = stringf("mux(%s, %s, %s)", s_expr.c_str(), b_expr.c_str(), a_expr.c_str());
803
804 cell_exprs.push_back(stringf(" %s <= %s %s\n", y_id.c_str(), expr.c_str(), cellFileinfo.c_str()));
805 register_reverse_wire_map(y_id, cell->getPort("\\Y"));
806
807 continue;
808 }
809
810 if (cell->type.in("$mem"))
811 {
812 string mem_id = make_id(cell->name);
813 int abits = cell->parameters.at("\\ABITS").as_int();
814 int width = cell->parameters.at("\\WIDTH").as_int();
815 int size = cell->parameters.at("\\SIZE").as_int();
816 memory m(cell, mem_id, abits, size, width);
817 int rd_ports = cell->parameters.at("\\RD_PORTS").as_int();
818 int wr_ports = cell->parameters.at("\\WR_PORTS").as_int();
819
820 Const initdata = cell->parameters.at("\\INIT");
821 for (State bit : initdata.bits)
822 if (bit != State::Sx)
823 log_error("Memory with initialization data: %s.%s\n", log_id(module), log_id(cell));
824
825 Const rd_clk_enable = cell->parameters.at("\\RD_CLK_ENABLE");
826 Const wr_clk_enable = cell->parameters.at("\\WR_CLK_ENABLE");
827 Const wr_clk_polarity = cell->parameters.at("\\WR_CLK_POLARITY");
828
829 int offset = cell->parameters.at("\\OFFSET").as_int();
830 if (offset != 0)
831 log_error("Memory with nonzero offset: %s.%s\n", log_id(module), log_id(cell));
832
833 for (int i = 0; i < rd_ports; i++)
834 {
835 if (rd_clk_enable[i] != State::S0)
836 log_error("Clocked read port %d on memory %s.%s.\n", i, log_id(module), log_id(cell));
837
838 SigSpec addr_sig = cell->getPort("\\RD_ADDR").extract(i*abits, abits);
839 SigSpec data_sig = cell->getPort("\\RD_DATA").extract(i*width, width);
840 string addr_expr = make_expr(addr_sig);
841 string name(stringf("%s.r%d", m.name.c_str(), i));
842 bool clk_enable = false;
843 bool clk_parity = true;
844 bool transparency = false;
845 SigSpec ena_sig = RTLIL::SigSpec(RTLIL::State::S1, 1);
846 SigSpec clk_sig = RTLIL::SigSpec(RTLIL::State::S0, 1);
847 read_port rp(name, clk_enable, clk_parity, transparency, clk_sig, ena_sig, addr_sig);
848 m.add_memory_read_port(rp);
849 cell_exprs.push_back(rp.gen_read(indent.c_str()));
850 register_reverse_wire_map(stringf("%s.data", name.c_str()), data_sig);
851 }
852
853 for (int i = 0; i < wr_ports; i++)
854 {
855 if (wr_clk_enable[i] != State::S1)
856 log_error("Unclocked write port %d on memory %s.%s.\n", i, log_id(module), log_id(cell));
857
858 if (wr_clk_polarity[i] != State::S1)
859 log_error("Negedge write port %d on memory %s.%s.\n", i, log_id(module), log_id(cell));
860
861 string name(stringf("%s.w%d", m.name.c_str(), i));
862 bool clk_enable = true;
863 bool clk_parity = true;
864 bool transparency = false;
865 SigSpec addr_sig =cell->getPort("\\WR_ADDR").extract(i*abits, abits);
866 string addr_expr = make_expr(addr_sig);
867 SigSpec data_sig =cell->getPort("\\WR_DATA").extract(i*width, width);
868 string data_expr = make_expr(data_sig);
869 SigSpec clk_sig = cell->getPort("\\WR_CLK").extract(i);
870 string clk_expr = make_expr(clk_sig);
871
872 SigSpec wen_sig = cell->getPort("\\WR_EN").extract(i*width, width);
873 string wen_expr = make_expr(wen_sig[0]);
874
875 for (int i = 1; i < GetSize(wen_sig); i++)
876 if (wen_sig[0] != wen_sig[i])
877 log_error("Complex write enable on port %d on memory %s.%s.\n", i, log_id(module), log_id(cell));
878
879 SigSpec mask_sig = RTLIL::SigSpec(RTLIL::State::S1, 1);
880 write_port wp(name, clk_enable, clk_parity, transparency, clk_sig, wen_sig[0], addr_sig, mask_sig);
881 m.add_memory_write_port(wp);
882 cell_exprs.push_back(stringf("%s%s.data <= %s\n", indent.c_str(), name.c_str(), data_expr.c_str()));
883 cell_exprs.push_back(wp.gen_write(indent.c_str()));
884 }
885 register_memory(m);
886 continue;
887 }
888
889 if (cell->type.in("$memwr", "$memrd", "$meminit"))
890 {
891 std::string cell_type = fid(cell->type);
892 std::string mem_id = make_id(cell->parameters["\\MEMID"].decode_string());
893 int abits = cell->parameters.at("\\ABITS").as_int();
894 int width = cell->parameters.at("\\WIDTH").as_int();
895 memory *mp = nullptr;
896 if (cell->type == "$meminit" ) {
897 log_error("$meminit (%s.%s.%s) currently unsupported\n", log_id(module), log_id(cell), mem_id.c_str());
898 } else {
899 // It's a $memwr or $memrd. Remember the read/write port parameters for the eventual FIRRTL memory definition.
900 auto addrSig = cell->getPort("\\ADDR");
901 auto dataSig = cell->getPort("\\DATA");
902 auto enableSig = cell->getPort("\\EN");
903 auto clockSig = cell->getPort("\\CLK");
904 Const clk_enable = cell->parameters.at("\\CLK_ENABLE");
905 Const clk_polarity = cell->parameters.at("\\CLK_POLARITY");
906
907 // Do we already have an entry for this memory?
908 if (memories.count(mem_id) == 0) {
909 memory m(cell, mem_id, abits, 0, width);
910 register_memory(m);
911 }
912 mp = &memories.at(mem_id);
913 int portNum = 0;
914 bool transparency = false;
915 string data_expr = make_expr(dataSig);
916 if (cell->type.in("$memwr")) {
917 portNum = (int) mp->write_ports.size();
918 write_port wp(stringf("%s.w%d", mem_id.c_str(), portNum), clk_enable.as_bool(), clk_polarity.as_bool(), transparency, clockSig, enableSig, addrSig, dataSig);
919 mp->add_memory_write_port(wp);
920 cell_exprs.push_back(stringf("%s%s.data <= %s\n", indent.c_str(), wp.name.c_str(), data_expr.c_str()));
921 cell_exprs.push_back(wp.gen_write(indent.c_str()));
922 } else if (cell->type.in("$memrd")) {
923 portNum = (int) mp->read_ports.size();
924 read_port rp(stringf("%s.r%d", mem_id.c_str(), portNum), clk_enable.as_bool(), clk_polarity.as_bool(), transparency, clockSig, enableSig, addrSig);
925 mp->add_memory_read_port(rp);
926 cell_exprs.push_back(rp.gen_read(indent.c_str()));
927 register_reverse_wire_map(stringf("%s.data", rp.name.c_str()), dataSig);
928 }
929 }
930 continue;
931 }
932
933 if (cell->type.in("$dff"))
934 {
935 bool clkpol = cell->parameters.at("\\CLK_POLARITY").as_bool();
936 if (clkpol == false)
937 log_error("Negative edge clock on FF %s.%s.\n", log_id(module), log_id(cell));
938
939 int width = cell->parameters.at("\\WIDTH").as_int();
940 string expr = make_expr(cell->getPort("\\D"));
941 string clk_expr = "asClock(" + make_expr(cell->getPort("\\CLK")) + ")";
942
943 wire_decls.push_back(stringf(" reg %s: UInt<%d>, %s %s\n", y_id.c_str(), width, clk_expr.c_str(), cellFileinfo.c_str()));
944
945 cell_exprs.push_back(stringf(" %s <= %s %s\n", y_id.c_str(), expr.c_str(), cellFileinfo.c_str()));
946 register_reverse_wire_map(y_id, cell->getPort("\\Q"));
947
948 continue;
949 }
950
951 // This may be a parameterized module - paramod.
952 if (cell->type.begins_with("$paramod"))
953 {
954 process_instance(cell, wire_exprs);
955 continue;
956 }
957 if (cell->type == "$shiftx") {
958 // assign y = a[b +: y_width];
959 // We'll extract the correct bits as part of the primop.
960
961 string a_expr = make_expr(cell->getPort("\\A"));
962 // Get the initial bit selector
963 string b_expr = make_expr(cell->getPort("\\B"));
964 wire_decls.push_back(stringf(" wire %s: UInt<%d>\n", y_id.c_str(), y_width));
965
966 if (cell->getParam("\\B_SIGNED").as_bool()) {
967 // Use validif to constrain the selection (test the sign bit)
968 auto b_string = b_expr.c_str();
969 int b_sign = cell->parameters.at("\\B_WIDTH").as_int() - 1;
970 b_expr = stringf("validif(not(bits(%s, %d, %d)), %s)", b_string, b_sign, b_sign, b_string);
971 }
972 string expr = stringf("dshr(%s, %s)", a_expr.c_str(), b_expr.c_str());
973
974 cell_exprs.push_back(stringf(" %s <= %s\n", y_id.c_str(), expr.c_str()));
975 register_reverse_wire_map(y_id, cell->getPort("\\Y"));
976 continue;
977 }
978 if (cell->type == "$shift") {
979 // assign y = a >> b;
980 // where b may be negative
981
982 string a_expr = make_expr(cell->getPort("\\A"));
983 string b_expr = make_expr(cell->getPort("\\B"));
984 auto b_string = b_expr.c_str();
985 string expr;
986 wire_decls.push_back(stringf(" wire %s: UInt<%d>\n", y_id.c_str(), y_width));
987
988 if (cell->getParam("\\B_SIGNED").as_bool()) {
989 // We generate a left or right shift based on the sign of b.
990 std::string dshl = stringf("bits(dshl(%s, %s), 0, %d)", a_expr.c_str(), gen_dshl(b_expr, b_width).c_str(), y_width);
991 std::string dshr = stringf("dshr(%s, %s)", a_expr.c_str(), b_string);
992 expr = stringf("mux(%s < 0, %s, %s)",
993 b_string,
994 dshl.c_str(),
995 dshr.c_str()
996 );
997 } else {
998 expr = stringf("dshr(%s, %s)", a_expr.c_str(), b_string);
999 }
1000 cell_exprs.push_back(stringf(" %s <= %s\n", y_id.c_str(), expr.c_str()));
1001 register_reverse_wire_map(y_id, cell->getPort("\\Y"));
1002 continue;
1003 }
1004 if (cell->type == "$pos") {
1005 // assign y = a;
1006 // printCell(cell);
1007 string a_expr = make_expr(cell->getPort("\\A"));
1008 // Verilog appears to treat the result as signed, so if the result is wider than "A",
1009 // we need to pad.
1010 if (a_width < y_width) {
1011 a_expr = stringf("pad(%s, %d)", a_expr.c_str(), y_width);
1012 }
1013 wire_decls.push_back(stringf(" wire %s: UInt<%d>\n", y_id.c_str(), y_width));
1014 cell_exprs.push_back(stringf(" %s <= %s\n", y_id.c_str(), a_expr.c_str()));
1015 register_reverse_wire_map(y_id, cell->getPort("\\Y"));
1016 continue;
1017 }
1018 log_error("Cell type not supported: %s (%s.%s)\n", log_id(cell->type), log_id(module), log_id(cell));
1019 }
1020
1021 for (auto conn : module->connections())
1022 {
1023 string y_id = next_id();
1024 int y_width = GetSize(conn.first);
1025 string expr = make_expr(conn.second);
1026
1027 wire_decls.push_back(stringf(" wire %s: UInt<%d>\n", y_id.c_str(), y_width));
1028 cell_exprs.push_back(stringf(" %s <= %s\n", y_id.c_str(), expr.c_str()));
1029 register_reverse_wire_map(y_id, conn.first);
1030 }
1031
1032 for (auto wire : module->wires())
1033 {
1034 string expr;
1035 std::string wireFileinfo = getFileinfo(wire->attributes);
1036
1037 if (wire->port_input)
1038 continue;
1039
1040 int cursor = 0;
1041 bool is_valid = false;
1042 bool make_unconn_id = false;
1043
1044 while (cursor < wire->width)
1045 {
1046 int chunk_width = 1;
1047 string new_expr;
1048
1049 SigBit start_bit(wire, cursor);
1050
1051 if (reverse_wire_map.count(start_bit))
1052 {
1053 pair<string, int> start_map = reverse_wire_map.at(start_bit);
1054
1055 while (cursor+chunk_width < wire->width)
1056 {
1057 SigBit stop_bit(wire, cursor+chunk_width);
1058
1059 if (reverse_wire_map.count(stop_bit) == 0)
1060 break;
1061
1062 pair<string, int> stop_map = reverse_wire_map.at(stop_bit);
1063 stop_map.second -= chunk_width;
1064
1065 if (start_map != stop_map)
1066 break;
1067
1068 chunk_width++;
1069 }
1070
1071 new_expr = stringf("bits(%s, %d, %d)", start_map.first.c_str(),
1072 start_map.second + chunk_width - 1, start_map.second);
1073 is_valid = true;
1074 }
1075 else
1076 {
1077 if (unconn_id.empty()) {
1078 unconn_id = next_id();
1079 make_unconn_id = true;
1080 }
1081 new_expr = unconn_id;
1082 }
1083
1084 if (expr.empty())
1085 expr = new_expr;
1086 else
1087 expr = "cat(" + new_expr + ", " + expr + ")";
1088
1089 cursor += chunk_width;
1090 }
1091
1092 if (is_valid) {
1093 if (make_unconn_id) {
1094 wire_decls.push_back(stringf(" wire %s: UInt<1> %s\n", unconn_id.c_str(), wireFileinfo.c_str()));
1095 // `invalid` is a firrtl construction for simulation so we will not
1096 // tag it with a @[fileinfo] tag as it doesn't directly correspond to
1097 // a specific line of verilog code.
1098 wire_decls.push_back(stringf(" %s is invalid\n", unconn_id.c_str()));
1099 }
1100 wire_exprs.push_back(stringf(" %s <= %s %s\n", make_id(wire->name), expr.c_str(), wireFileinfo.c_str()));
1101 } else {
1102 if (make_unconn_id) {
1103 unconn_id.clear();
1104 }
1105 // `invalid` is a firrtl construction for simulation so we will not
1106 // tag it with a @[fileinfo] tag as it doesn't directly correspond to
1107 // a specific line of verilog code.
1108 wire_decls.push_back(stringf(" %s is invalid\n", make_id(wire->name)));
1109 }
1110 }
1111
1112 for (auto str : port_decls)
1113 f << str;
1114
1115 f << stringf("\n");
1116
1117 for (auto str : wire_decls)
1118 f << str;
1119
1120 f << stringf("\n");
1121
1122 // If we have any memory definitions, output them.
1123 for (auto kv : memories) {
1124 memory &m = kv.second;
1125 f << stringf(" mem %s:\n", m.name.c_str());
1126 f << stringf(" data-type => UInt<%d>\n", m.width);
1127 f << stringf(" depth => %d\n", m.size);
1128 for (int i = 0; i < (int) m.read_ports.size(); i += 1) {
1129 f << stringf(" reader => r%d\n", i);
1130 }
1131 for (int i = 0; i < (int) m.write_ports.size(); i += 1) {
1132 f << stringf(" writer => w%d\n", i);
1133 }
1134 f << stringf(" read-latency => %d\n", m.read_latency);
1135 f << stringf(" write-latency => %d\n", m.write_latency);
1136 f << stringf(" read-under-write => undefined\n");
1137 }
1138 f << stringf("\n");
1139
1140 for (auto str : cell_exprs)
1141 f << str;
1142
1143 f << stringf("\n");
1144
1145 for (auto str : wire_exprs)
1146 f << str;
1147 }
1148 };
1149
1150 struct FirrtlBackend : public Backend {
1151 FirrtlBackend() : Backend("firrtl", "write design to a FIRRTL file") { }
1152 void help() YS_OVERRIDE
1153 {
1154 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
1155 log("\n");
1156 log(" write_firrtl [options] [filename]\n");
1157 log("\n");
1158 log("Write a FIRRTL netlist of the current design.\n");
1159 log("The following commands are executed by this command:\n");
1160 log(" pmuxtree\n");
1161 log("\n");
1162 }
1163 void execute(std::ostream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
1164 {
1165 size_t argidx = args.size(); // We aren't expecting any arguments.
1166
1167 // If we weren't explicitly passed a filename, use the last argument (if it isn't a flag).
1168 if (filename == "") {
1169 if (argidx > 0 && args[argidx - 1][0] != '-') {
1170 // extra_args and friends need to see this argument.
1171 argidx -= 1;
1172 filename = args[argidx];
1173 }
1174 }
1175 extra_args(f, filename, args, argidx);
1176
1177 if (!design->full_selection())
1178 log_cmd_error("This command only operates on fully selected designs!\n");
1179
1180 log_header(design, "Executing FIRRTL backend.\n");
1181 log_push();
1182
1183 Pass::call(design, stringf("pmuxtree"));
1184
1185 namecache.clear();
1186 autoid_counter = 0;
1187
1188 // Get the top module, or a reasonable facsimile - we need something for the circuit name.
1189 Module *top = design->top_module();
1190 Module *last = nullptr;
1191 // Generate module and wire names.
1192 for (auto module : design->modules()) {
1193 make_id(module->name);
1194 last = module;
1195 if (top == nullptr && module->get_bool_attribute("\\top")) {
1196 top = module;
1197 }
1198 for (auto wire : module->wires())
1199 if (wire->port_id)
1200 make_id(wire->name);
1201 }
1202
1203 if (top == nullptr)
1204 top = last;
1205
1206 auto circuitFileinfo = getFileinfo(top->attributes);
1207 *f << stringf("circuit %s: %s\n", make_id(top->name), circuitFileinfo.c_str());
1208
1209 for (auto module : design->modules())
1210 {
1211 FirrtlWorker worker(module, *f, design);
1212 worker.run();
1213 }
1214
1215 namecache.clear();
1216 autoid_counter = 0;
1217 }
1218 } FirrtlBackend;
1219
1220 PRIVATE_NAMESPACE_END