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