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