improved (fixed) conversion of real values to bit vectors
[yosys.git] / frontends / ast / genrtlil.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 * This is the AST frontend library.
21 *
22 * The AST frontend library is not a frontend on it's own but provides a
23 * generic abstract syntax tree (AST) abstraction for HDL code and can be
24 * used by HDL frontends. See "ast.h" for an overview of the API and the
25 * Verilog frontend for an usage example.
26 *
27 */
28
29 #include "kernel/log.h"
30 #include "libs/sha1/sha1.h"
31 #include "ast.h"
32
33 #include <sstream>
34 #include <stdarg.h>
35 #include <assert.h>
36 #include <algorithm>
37
38 using namespace AST;
39 using namespace AST_INTERNAL;
40
41 // helper function for creating RTLIL code for unary operations
42 static RTLIL::SigSpec uniop2rtlil(AstNode *that, std::string type, int result_width, const RTLIL::SigSpec &arg, bool gen_attributes = true)
43 {
44 std::stringstream sstr;
45 sstr << type << "$" << that->filename << ":" << that->linenum << "$" << (RTLIL::autoidx++);
46
47 RTLIL::Cell *cell = new RTLIL::Cell;
48 cell->attributes["\\src"] = stringf("%s:%d", that->filename.c_str(), that->linenum);
49 cell->name = sstr.str();
50 cell->type = type;
51 current_module->cells[cell->name] = cell;
52
53 RTLIL::Wire *wire = new RTLIL::Wire;
54 wire->attributes["\\src"] = stringf("%s:%d", that->filename.c_str(), that->linenum);
55 wire->name = cell->name + "_Y";
56 wire->width = result_width;
57 current_module->wires[wire->name] = wire;
58
59 RTLIL::SigChunk chunk;
60 chunk.wire = wire;
61 chunk.width = wire->width;
62 chunk.offset = 0;
63
64 RTLIL::SigSpec sig;
65 sig.chunks.push_back(chunk);
66 sig.width = chunk.width;
67
68 if (gen_attributes)
69 for (auto &attr : that->attributes) {
70 if (attr.second->type != AST_CONSTANT)
71 log_error("Attribute `%s' with non-constant value at %s:%d!\n",
72 attr.first.c_str(), that->filename.c_str(), that->linenum);
73 cell->attributes[attr.first] = attr.second->asAttrConst();
74 }
75
76 cell->parameters["\\A_SIGNED"] = RTLIL::Const(that->children[0]->is_signed);
77 cell->parameters["\\A_WIDTH"] = RTLIL::Const(arg.width);
78 cell->connections["\\A"] = arg;
79
80 cell->parameters["\\Y_WIDTH"] = result_width;
81 cell->connections["\\Y"] = sig;
82 return sig;
83 }
84
85 // helper function for extending bit width (preferred over SigSpec::extend() because of correct undef propagation in ConstEval)
86 static void widthExtend(AstNode *that, RTLIL::SigSpec &sig, int width, bool is_signed, std::string celltype)
87 {
88 if (width <= sig.width) {
89 sig.extend(width, is_signed);
90 return;
91 }
92
93 std::stringstream sstr;
94 sstr << "$extend" << "$" << that->filename << ":" << that->linenum << "$" << (RTLIL::autoidx++);
95
96 RTLIL::Cell *cell = new RTLIL::Cell;
97 cell->attributes["\\src"] = stringf("%s:%d", that->filename.c_str(), that->linenum);
98 cell->name = sstr.str();
99 cell->type = celltype;
100 current_module->cells[cell->name] = cell;
101
102 RTLIL::Wire *wire = new RTLIL::Wire;
103 wire->attributes["\\src"] = stringf("%s:%d", that->filename.c_str(), that->linenum);
104 wire->name = cell->name + "_Y";
105 wire->width = width;
106 current_module->wires[wire->name] = wire;
107
108 RTLIL::SigChunk chunk;
109 chunk.wire = wire;
110 chunk.width = wire->width;
111 chunk.offset = 0;
112
113 RTLIL::SigSpec new_sig;
114 new_sig.chunks.push_back(chunk);
115 new_sig.width = chunk.width;
116
117 if (that != NULL)
118 for (auto &attr : that->attributes) {
119 if (attr.second->type != AST_CONSTANT)
120 log_error("Attribute `%s' with non-constant value at %s:%d!\n",
121 attr.first.c_str(), that->filename.c_str(), that->linenum);
122 cell->attributes[attr.first] = attr.second->asAttrConst();
123 }
124
125 cell->parameters["\\A_SIGNED"] = RTLIL::Const(is_signed);
126 cell->parameters["\\A_WIDTH"] = RTLIL::Const(sig.width);
127 cell->connections["\\A"] = sig;
128
129 cell->parameters["\\Y_WIDTH"] = width;
130 cell->connections["\\Y"] = new_sig;
131 sig = new_sig;
132 }
133
134 // helper function for creating RTLIL code for binary operations
135 static RTLIL::SigSpec binop2rtlil(AstNode *that, std::string type, int result_width, const RTLIL::SigSpec &left, const RTLIL::SigSpec &right)
136 {
137 std::stringstream sstr;
138 sstr << type << "$" << that->filename << ":" << that->linenum << "$" << (RTLIL::autoidx++);
139
140 RTLIL::Cell *cell = new RTLIL::Cell;
141 cell->attributes["\\src"] = stringf("%s:%d", that->filename.c_str(), that->linenum);
142 cell->name = sstr.str();
143 cell->type = type;
144 current_module->cells[cell->name] = cell;
145
146 RTLIL::Wire *wire = new RTLIL::Wire;
147 wire->attributes["\\src"] = stringf("%s:%d", that->filename.c_str(), that->linenum);
148 wire->name = cell->name + "_Y";
149 wire->width = result_width;
150 current_module->wires[wire->name] = wire;
151
152 RTLIL::SigChunk chunk;
153 chunk.wire = wire;
154 chunk.width = wire->width;
155 chunk.offset = 0;
156
157 RTLIL::SigSpec sig;
158 sig.chunks.push_back(chunk);
159 sig.width = chunk.width;
160
161 for (auto &attr : that->attributes) {
162 if (attr.second->type != AST_CONSTANT)
163 log_error("Attribute `%s' with non-constant value at %s:%d!\n",
164 attr.first.c_str(), that->filename.c_str(), that->linenum);
165 cell->attributes[attr.first] = attr.second->asAttrConst();
166 }
167
168 cell->parameters["\\A_SIGNED"] = RTLIL::Const(that->children[0]->is_signed);
169 cell->parameters["\\B_SIGNED"] = RTLIL::Const(that->children[1]->is_signed);
170
171 cell->parameters["\\A_WIDTH"] = RTLIL::Const(left.width);
172 cell->parameters["\\B_WIDTH"] = RTLIL::Const(right.width);
173
174 cell->connections["\\A"] = left;
175 cell->connections["\\B"] = right;
176
177 cell->parameters["\\Y_WIDTH"] = result_width;
178 cell->connections["\\Y"] = sig;
179 return sig;
180 }
181
182 // helper function for creating RTLIL code for multiplexers
183 static RTLIL::SigSpec mux2rtlil(AstNode *that, const RTLIL::SigSpec &cond, const RTLIL::SigSpec &left, const RTLIL::SigSpec &right)
184 {
185 assert(cond.width == 1);
186
187 std::stringstream sstr;
188 sstr << "$ternary$" << that->filename << ":" << that->linenum << "$" << (RTLIL::autoidx++);
189
190 RTLIL::Cell *cell = new RTLIL::Cell;
191 cell->attributes["\\src"] = stringf("%s:%d", that->filename.c_str(), that->linenum);
192 cell->name = sstr.str();
193 cell->type = "$mux";
194 current_module->cells[cell->name] = cell;
195
196 RTLIL::Wire *wire = new RTLIL::Wire;
197 wire->attributes["\\src"] = stringf("%s:%d", that->filename.c_str(), that->linenum);
198 wire->name = cell->name + "_Y";
199 wire->width = left.width;
200 current_module->wires[wire->name] = wire;
201
202 RTLIL::SigChunk chunk;
203 chunk.wire = wire;
204 chunk.width = wire->width;
205 chunk.offset = 0;
206
207 RTLIL::SigSpec sig;
208 sig.chunks.push_back(chunk);
209 sig.width = chunk.width;
210
211 for (auto &attr : that->attributes) {
212 if (attr.second->type != AST_CONSTANT)
213 log_error("Attribute `%s' with non-constant value at %s:%d!\n",
214 attr.first.c_str(), that->filename.c_str(), that->linenum);
215 cell->attributes[attr.first] = attr.second->asAttrConst();
216 }
217
218 cell->parameters["\\WIDTH"] = RTLIL::Const(left.width);
219
220 cell->connections["\\A"] = right;
221 cell->connections["\\B"] = left;
222 cell->connections["\\S"] = cond;
223 cell->connections["\\Y"] = sig;
224
225 return sig;
226 }
227
228 // helper class for converting AST always nodes to RTLIL processes
229 struct AST_INTERNAL::ProcessGenerator
230 {
231 // input and output structures
232 AstNode *always;
233 RTLIL::SigSpec initSyncSignals;
234 RTLIL::Process *proc;
235 const RTLIL::SigSpec &outputSignals;
236
237 // This always points to the RTLIL::CaseRule beeing filled at the moment
238 RTLIL::CaseRule *current_case;
239
240 // This two variables contain the replacement pattern to be used in the right hand side
241 // of an assignment. E.g. in the code "foo = bar; foo = func(foo);" the foo in the right
242 // hand side of the 2nd assignment needs to be replace with the temporary signal holding
243 // the value assigned in the first assignment. So when the first assignement is processed
244 // the according information is appended to subst_rvalue_from and subst_rvalue_to.
245 RTLIL::SigSpec subst_rvalue_from, subst_rvalue_to;
246
247 // This two variables contain the replacement pattern to be used in the left hand side
248 // of an assignment. E.g. in the code "always @(posedge clk) foo <= bar" the signal bar
249 // should not be connected to the signal foo. Instead it must be connected to the temporary
250 // signal that is used as input for the register that drives the signal foo.
251 RTLIL::SigSpec subst_lvalue_from, subst_lvalue_to;
252
253 // The code here generates a number of temprorary signal for each output register. This
254 // map helps generating nice numbered names for all this temporary signals.
255 std::map<RTLIL::Wire*, int> new_temp_count;
256
257 // Buffer for generating the init action
258 RTLIL::SigSpec init_lvalue, init_rvalue;
259
260 ProcessGenerator(AstNode *always, RTLIL::SigSpec initSyncSignalsArg = RTLIL::SigSpec()) : always(always), initSyncSignals(initSyncSignalsArg), outputSignals(subst_lvalue_from)
261 {
262 // generate process and simple root case
263 proc = new RTLIL::Process;
264 proc->attributes["\\src"] = stringf("%s:%d", always->filename.c_str(), always->linenum);
265 proc->name = stringf("$proc$%s:%d$%d", always->filename.c_str(), always->linenum, RTLIL::autoidx++);
266 for (auto &attr : always->attributes) {
267 if (attr.second->type != AST_CONSTANT)
268 log_error("Attribute `%s' with non-constant value at %s:%d!\n",
269 attr.first.c_str(), always->filename.c_str(), always->linenum);
270 proc->attributes[attr.first] = attr.second->asAttrConst();
271 }
272 current_module->processes[proc->name] = proc;
273 current_case = &proc->root_case;
274
275 // create initial temporary signal for all output registers
276 collect_lvalues(subst_lvalue_from, always, true, true);
277 subst_lvalue_to = new_temp_signal(subst_lvalue_from);
278
279 bool found_anyedge_syncs = false;
280 for (auto child : always->children)
281 if (child->type == AST_EDGE)
282 found_anyedge_syncs = true;
283
284 if (found_anyedge_syncs) {
285 log("Note: Assuming pure combinatorial block at %s:%d in\n", always->filename.c_str(), always->linenum);
286 log("compliance with IEC 62142(E):2005 / IEEE Std. 1364.1(E):2002. Recommending\n");
287 log("use of @* instead of @(...) for better match of synthesis and simulation.\n");
288 }
289
290 // create syncs for the process
291 bool found_clocked_sync = false;
292 for (auto child : always->children)
293 if (child->type == AST_POSEDGE || child->type == AST_NEGEDGE) {
294 found_clocked_sync = true;
295 if (found_anyedge_syncs)
296 log_error("Found non-synthesizable event list at %s:%d!\n", always->filename.c_str(), always->linenum);
297 RTLIL::SyncRule *syncrule = new RTLIL::SyncRule;
298 syncrule->type = child->type == AST_POSEDGE ? RTLIL::STp : RTLIL::STn;
299 syncrule->signal = child->children[0]->genRTLIL();
300 addChunkActions(syncrule->actions, subst_lvalue_from, subst_lvalue_to, true);
301 proc->syncs.push_back(syncrule);
302 }
303 if (proc->syncs.empty()) {
304 RTLIL::SyncRule *syncrule = new RTLIL::SyncRule;
305 syncrule->type = RTLIL::STa;
306 syncrule->signal = RTLIL::SigSpec();
307 addChunkActions(syncrule->actions, subst_lvalue_from, subst_lvalue_to, true);
308 proc->syncs.push_back(syncrule);
309 }
310
311 // create initial assignments for the temporary signals
312 if ((flag_nolatches || always->get_bool_attribute("\\nolatches") || current_module->get_bool_attribute("\\nolatches")) && !found_clocked_sync) {
313 subst_rvalue_from = subst_lvalue_from;
314 subst_rvalue_to = RTLIL::SigSpec(RTLIL::State::Sx, subst_rvalue_from.width);
315 } else {
316 addChunkActions(current_case->actions, subst_lvalue_to, subst_lvalue_from);
317 }
318
319 // process the AST
320 for (auto child : always->children)
321 if (child->type == AST_BLOCK)
322 processAst(child);
323
324 if (initSyncSignals.width > 0)
325 {
326 RTLIL::SyncRule *sync = new RTLIL::SyncRule;
327 sync->type = RTLIL::SyncType::STi;
328 proc->syncs.push_back(sync);
329
330 assert(init_lvalue.width == init_rvalue.width);
331 init_lvalue.optimize();
332 init_rvalue.optimize();
333
334 int offset = 0;
335 for (size_t i = 0; i < init_lvalue.chunks.size(); i++) {
336 RTLIL::SigSpec lhs = init_lvalue.chunks[i];
337 RTLIL::SigSpec rhs = init_rvalue.extract(offset, init_lvalue.chunks[i].width);
338 sync->actions.push_back(RTLIL::SigSig(lhs, rhs));
339 offset += lhs.width;
340 }
341 }
342 }
343
344 // create new temporary signals
345 RTLIL::SigSpec new_temp_signal(RTLIL::SigSpec sig)
346 {
347 sig.optimize();
348 for (size_t i = 0; i < sig.chunks.size(); i++)
349 {
350 RTLIL::SigChunk &chunk = sig.chunks[i];
351 if (chunk.wire == NULL)
352 continue;
353
354 RTLIL::Wire *wire = new RTLIL::Wire;
355 wire->attributes["\\src"] = stringf("%s:%d", always->filename.c_str(), always->linenum);
356 do {
357 wire->name = stringf("$%d%s[%d:%d]", new_temp_count[chunk.wire]++,
358 chunk.wire->name.c_str(), chunk.width+chunk.offset-1, chunk.offset);;
359 if (chunk.wire->name.find('$') != std::string::npos)
360 wire->name += stringf("$%d", RTLIL::autoidx++);
361 } while (current_module->wires.count(wire->name) > 0);
362 wire->width = chunk.width;
363 current_module->wires[wire->name] = wire;
364
365 chunk.wire = wire;
366 chunk.offset = 0;
367 }
368 return sig;
369 }
370
371 // recursively traverse the AST an collect all assigned signals
372 void collect_lvalues(RTLIL::SigSpec &reg, AstNode *ast, bool type_eq, bool type_le, bool run_sort_and_unify = true)
373 {
374 switch (ast->type)
375 {
376 case AST_CASE:
377 for (auto child : ast->children)
378 if (child != ast->children[0]) {
379 assert(child->type == AST_COND);
380 collect_lvalues(reg, child, type_eq, type_le, false);
381 }
382 break;
383
384 case AST_COND:
385 case AST_ALWAYS:
386 case AST_INITIAL:
387 for (auto child : ast->children)
388 if (child->type == AST_BLOCK)
389 collect_lvalues(reg, child, type_eq, type_le, false);
390 break;
391
392 case AST_BLOCK:
393 for (auto child : ast->children) {
394 if (child->type == AST_ASSIGN_EQ && type_eq)
395 reg.append(child->children[0]->genRTLIL());
396 if (child->type == AST_ASSIGN_LE && type_le)
397 reg.append(child->children[0]->genRTLIL());
398 if (child->type == AST_CASE || child->type == AST_BLOCK)
399 collect_lvalues(reg, child, type_eq, type_le, false);
400 }
401 break;
402
403 default:
404 assert(0);
405 }
406
407 if (run_sort_and_unify)
408 reg.sort_and_unify();
409 }
410
411 // remove all assignments to the given signal pattern in a case and all its children.
412 // e.g. when the last statement in the code "a = 23; if (b) a = 42; a = 0;" is processed this
413 // function is called to clean up the first two assignments as they are overwritten by
414 // the third assignment.
415 void removeSignalFromCaseTree(RTLIL::SigSpec pattern, RTLIL::CaseRule *cs)
416 {
417 for (auto it = cs->actions.begin(); it != cs->actions.end(); it++)
418 it->first.remove2(pattern, &it->second);
419
420 for (auto it = cs->switches.begin(); it != cs->switches.end(); it++)
421 for (auto it2 = (*it)->cases.begin(); it2 != (*it)->cases.end(); it2++)
422 removeSignalFromCaseTree(pattern, *it2);
423 }
424
425 // add an assignment (aka "action") but split it up in chunks. this way huge assignments
426 // are avoided and the generated $mux cells have a more "natural" size.
427 void addChunkActions(std::vector<RTLIL::SigSig> &actions, RTLIL::SigSpec lvalue, RTLIL::SigSpec rvalue, bool inSyncRule = false)
428 {
429 if (inSyncRule && initSyncSignals.width > 0) {
430 init_lvalue.append(lvalue.extract(initSyncSignals));
431 init_rvalue.append(lvalue.extract(initSyncSignals, &rvalue));
432 lvalue.remove2(initSyncSignals, &rvalue);
433 }
434 assert(lvalue.width == rvalue.width);
435 lvalue.optimize();
436 rvalue.optimize();
437
438 int offset = 0;
439 for (size_t i = 0; i < lvalue.chunks.size(); i++) {
440 RTLIL::SigSpec lhs = lvalue.chunks[i];
441 RTLIL::SigSpec rhs = rvalue.extract(offset, lvalue.chunks[i].width);
442 if (inSyncRule && lvalue.chunks[i].wire && lvalue.chunks[i].wire->get_bool_attribute("\\nosync"))
443 rhs = RTLIL::SigSpec(RTLIL::State::Sx, rhs.width);
444 actions.push_back(RTLIL::SigSig(lhs, rhs));
445 offset += lhs.width;
446 }
447 }
448
449 // recursively process the AST and fill the RTLIL::Process
450 void processAst(AstNode *ast)
451 {
452 switch (ast->type)
453 {
454 case AST_BLOCK:
455 for (auto child : ast->children)
456 processAst(child);
457 break;
458
459 case AST_ASSIGN_EQ:
460 case AST_ASSIGN_LE:
461 {
462 RTLIL::SigSpec unmapped_lvalue = ast->children[0]->genRTLIL(), lvalue = unmapped_lvalue;
463 RTLIL::SigSpec rvalue = ast->children[1]->genWidthRTLIL(lvalue.width, &subst_rvalue_from, &subst_rvalue_to);
464 lvalue.replace(subst_lvalue_from, subst_lvalue_to);
465
466 if (ast->type == AST_ASSIGN_EQ) {
467 subst_rvalue_from.remove2(unmapped_lvalue, &subst_rvalue_to);
468 subst_rvalue_from.append(unmapped_lvalue);
469 subst_rvalue_from.optimize();
470 subst_rvalue_to.append(rvalue);
471 subst_rvalue_to.optimize();
472 }
473
474 removeSignalFromCaseTree(lvalue, current_case);
475 current_case->actions.push_back(RTLIL::SigSig(lvalue, rvalue));
476 }
477 break;
478
479 case AST_CASE:
480 {
481 RTLIL::SwitchRule *sw = new RTLIL::SwitchRule;
482 sw->signal = ast->children[0]->genWidthRTLIL(-1, &subst_rvalue_from, &subst_rvalue_to);
483 current_case->switches.push_back(sw);
484
485 for (auto &attr : ast->attributes) {
486 if (attr.second->type != AST_CONSTANT)
487 log_error("Attribute `%s' with non-constant value at %s:%d!\n",
488 attr.first.c_str(), ast->filename.c_str(), ast->linenum);
489 sw->attributes[attr.first] = attr.second->asAttrConst();
490 }
491
492 RTLIL::SigSpec this_case_eq_lvalue;
493 collect_lvalues(this_case_eq_lvalue, ast, true, false);
494
495 RTLIL::SigSpec this_case_eq_ltemp = new_temp_signal(this_case_eq_lvalue);
496
497 RTLIL::SigSpec this_case_eq_rvalue = this_case_eq_lvalue;
498 this_case_eq_rvalue.replace(subst_rvalue_from, subst_rvalue_to);
499
500 RTLIL::SigSpec backup_subst_lvalue_from = subst_lvalue_from;
501 RTLIL::SigSpec backup_subst_lvalue_to = subst_lvalue_to;
502
503 RTLIL::SigSpec backup_subst_rvalue_from = subst_rvalue_from;
504 RTLIL::SigSpec backup_subst_rvalue_to = subst_rvalue_to;
505
506 RTLIL::CaseRule *default_case = NULL;
507 RTLIL::CaseRule *last_generated_case = NULL;
508 for (auto child : ast->children)
509 {
510 if (child == ast->children[0])
511 continue;
512 assert(child->type == AST_COND);
513
514 subst_lvalue_from = backup_subst_lvalue_from;
515 subst_lvalue_to = backup_subst_lvalue_to;
516
517 subst_rvalue_from = backup_subst_rvalue_from;
518 subst_rvalue_to = backup_subst_rvalue_to;
519
520 subst_lvalue_from.remove2(this_case_eq_lvalue, &subst_lvalue_to);
521 subst_lvalue_from.append(this_case_eq_lvalue);
522 subst_lvalue_from.optimize();
523 subst_lvalue_to.append(this_case_eq_ltemp);
524 subst_lvalue_to.optimize();
525
526 RTLIL::CaseRule *backup_case = current_case;
527 current_case = new RTLIL::CaseRule;
528 last_generated_case = current_case;
529 addChunkActions(current_case->actions, this_case_eq_ltemp, this_case_eq_rvalue);
530 for (auto node : child->children) {
531 if (node->type == AST_DEFAULT)
532 default_case = current_case;
533 else if (node->type == AST_BLOCK)
534 processAst(node);
535 else
536 current_case->compare.push_back(node->genWidthRTLIL(sw->signal.width, &subst_rvalue_from, &subst_rvalue_to));
537 }
538 if (default_case != current_case)
539 sw->cases.push_back(current_case);
540 else
541 log_assert(current_case->compare.size() == 0);
542 current_case = backup_case;
543 }
544
545 if (last_generated_case != NULL && ast->get_bool_attribute("\\full_case") && default_case == NULL) {
546 last_generated_case->compare.clear();
547 } else {
548 if (default_case == NULL) {
549 default_case = new RTLIL::CaseRule;
550 addChunkActions(default_case->actions, this_case_eq_ltemp, this_case_eq_rvalue);
551 }
552 sw->cases.push_back(default_case);
553 }
554
555 subst_lvalue_from = backup_subst_lvalue_from;
556 subst_lvalue_to = backup_subst_lvalue_to;
557
558 subst_rvalue_from = backup_subst_rvalue_from;
559 subst_rvalue_to = backup_subst_rvalue_to;
560
561 subst_rvalue_from.remove2(this_case_eq_lvalue, &subst_rvalue_to);
562 subst_rvalue_from.append(this_case_eq_lvalue);
563 subst_rvalue_from.optimize();
564 subst_rvalue_to.append(this_case_eq_ltemp);
565 subst_rvalue_to.optimize();
566
567 this_case_eq_lvalue.replace(subst_lvalue_from, subst_lvalue_to);
568 removeSignalFromCaseTree(this_case_eq_lvalue, current_case);
569 addChunkActions(current_case->actions, this_case_eq_lvalue, this_case_eq_ltemp);
570 }
571 break;
572
573 case AST_WIRE:
574 log_error("Found wire declaration in block without label at at %s:%d!\n", ast->filename.c_str(), ast->linenum);
575 break;
576
577 case AST_TCALL:
578 case AST_FOR:
579 break;
580
581 default:
582 log_abort();
583 }
584 }
585 };
586
587 // detect sign and width of an expression
588 void AstNode::detectSignWidthWorker(int &width_hint, bool &sign_hint)
589 {
590 std::string type_name;
591 bool sub_sign_hint = true;
592 int sub_width_hint = -1;
593 int this_width = 0;
594 AstNode *range = NULL;
595 AstNode *id_ast = NULL;
596
597 switch (type)
598 {
599 case AST_CONSTANT:
600 width_hint = std::max(width_hint, int(bits.size()));
601 if (!is_signed)
602 sign_hint = false;
603 break;
604
605 case AST_REALVALUE:
606 width_hint = std::max(width_hint, 32);
607 break;
608
609 case AST_IDENTIFIER:
610 id_ast = id2ast;
611 if (id_ast == NULL && current_scope.count(str))
612 id_ast = current_scope.at(str);
613 if (!id_ast)
614 log_error("Failed to resolve identifier %s for width detection at %s:%d!\n", str.c_str(), filename.c_str(), linenum);
615 if (id_ast->type == AST_PARAMETER || id_ast->type == AST_LOCALPARAM) {
616 if (id_ast->children.size() > 1 && id_ast->children[1]->range_valid) {
617 this_width = id_ast->children[1]->range_left - id_ast->children[1]->range_right + 1;
618 } else
619 if (id_ast->children[0]->type == AST_CONSTANT) {
620 this_width = id_ast->children[0]->bits.size();
621 } else
622 log_error("Failed to detect width for parameter %s at %s:%d!\n", str.c_str(), filename.c_str(), linenum);
623 if (children.size() != 0)
624 range = children[0];
625 } else if (id_ast->type == AST_WIRE || id_ast->type == AST_AUTOWIRE) {
626 if (!id_ast->range_valid) {
627 if (id_ast->type == AST_AUTOWIRE)
628 this_width = 1;
629 else {
630 // current_ast_mod->dumpAst(NULL, "mod> ");
631 // log("---\n");
632 // id_ast->dumpAst(NULL, "decl> ");
633 // dumpAst(NULL, "ref> ");
634 log_error("Failed to detect with of signal access `%s' at %s:%d!\n", str.c_str(), filename.c_str(), linenum);
635 }
636 } else {
637 this_width = id_ast->range_left - id_ast->range_right + 1;
638 if (children.size() != 0)
639 range = children[0];
640 }
641 } else if (id_ast->type == AST_GENVAR) {
642 this_width = 32;
643 } else if (id_ast->type == AST_MEMORY) {
644 if (!id_ast->children[0]->range_valid)
645 log_error("Failed to detect with of memory access `%s' at %s:%d!\n", str.c_str(), filename.c_str(), linenum);
646 this_width = id_ast->children[0]->range_left - id_ast->children[0]->range_right + 1;
647 } else
648 log_error("Failed to detect width for identifier %s at %s:%d!\n", str.c_str(), filename.c_str(), linenum);
649 if (range) {
650 if (range->children.size() == 1)
651 this_width = 1;
652 else if (!range->range_valid) {
653 AstNode *left_at_zero_ast = children[0]->children[0]->clone();
654 AstNode *right_at_zero_ast = children[0]->children.size() >= 2 ? children[0]->children[1]->clone() : left_at_zero_ast->clone();
655 while (left_at_zero_ast->simplify(true, true, false, 1, -1, false, false)) { }
656 while (right_at_zero_ast->simplify(true, true, false, 1, -1, false, false)) { }
657 if (left_at_zero_ast->type != AST_CONSTANT || right_at_zero_ast->type != AST_CONSTANT)
658 log_error("Unsupported expression on dynamic range select on signal `%s' at %s:%d!\n",
659 str.c_str(), filename.c_str(), linenum);
660 this_width = left_at_zero_ast->integer - right_at_zero_ast->integer + 1;
661 delete left_at_zero_ast;
662 delete right_at_zero_ast;
663 } else
664 this_width = range->range_left - range->range_right + 1;
665 } else
666 width_hint = std::max(width_hint, this_width);
667 if (!id_ast->is_signed)
668 sign_hint = false;
669 break;
670
671 case AST_TO_BITS:
672 while (children[0]->simplify(true, false, false, 1, -1, false, false) == true) { }
673 if (children[0]->type != AST_CONSTANT)
674 log_error("Left operand of tobits expression is not constant at %s:%d!\n", filename.c_str(), linenum);
675 children[1]->detectSignWidthWorker(sub_width_hint, sign_hint);
676 width_hint = std::max(width_hint, children[0]->bitsAsConst().as_int());
677 break;
678
679 case AST_TO_SIGNED:
680 children.at(0)->detectSignWidthWorker(width_hint, sub_sign_hint);
681 break;
682
683 case AST_TO_UNSIGNED:
684 children.at(0)->detectSignWidthWorker(width_hint, sub_sign_hint);
685 sign_hint = false;
686 break;
687
688 case AST_CONCAT:
689 for (auto child : children) {
690 sub_width_hint = 0;
691 sub_sign_hint = true;
692 child->detectSignWidthWorker(sub_width_hint, sub_sign_hint);
693 this_width += sub_width_hint;
694 }
695 width_hint = std::max(width_hint, this_width);
696 sign_hint = false;
697 break;
698
699 case AST_REPLICATE:
700 while (children[0]->simplify(true, false, false, 1, -1, false, true) == true) { }
701 if (children[0]->type != AST_CONSTANT)
702 log_error("Left operand of replicate expression is not constant at %s:%d!\n", filename.c_str(), linenum);
703 children[1]->detectSignWidthWorker(sub_width_hint, sub_sign_hint);
704 width_hint = std::max(width_hint, children[0]->bitsAsConst().as_int() * sub_width_hint);
705 sign_hint = false;
706 break;
707
708 case AST_NEG:
709 case AST_BIT_NOT:
710 case AST_POS:
711 children[0]->detectSignWidthWorker(width_hint, sign_hint);
712 break;
713
714 case AST_BIT_AND:
715 case AST_BIT_OR:
716 case AST_BIT_XOR:
717 case AST_BIT_XNOR:
718 for (auto child : children)
719 child->detectSignWidthWorker(width_hint, sign_hint);
720 break;
721
722 case AST_REDUCE_AND:
723 case AST_REDUCE_OR:
724 case AST_REDUCE_XOR:
725 case AST_REDUCE_XNOR:
726 case AST_REDUCE_BOOL:
727 width_hint = std::max(width_hint, 1);
728 sign_hint = false;
729 break;
730
731 case AST_SHIFT_LEFT:
732 case AST_SHIFT_RIGHT:
733 case AST_SHIFT_SLEFT:
734 case AST_SHIFT_SRIGHT:
735 case AST_POW:
736 children[0]->detectSignWidthWorker(width_hint, sign_hint);
737 break;
738
739 case AST_LT:
740 case AST_LE:
741 case AST_EQ:
742 case AST_NE:
743 case AST_EQX:
744 case AST_NEX:
745 case AST_GE:
746 case AST_GT:
747 width_hint = std::max(width_hint, 1);
748 sign_hint = false;
749 break;
750
751 case AST_ADD:
752 case AST_SUB:
753 case AST_MUL:
754 case AST_DIV:
755 case AST_MOD:
756 for (auto child : children)
757 child->detectSignWidthWorker(width_hint, sign_hint);
758 break;
759
760 case AST_LOGIC_AND:
761 case AST_LOGIC_OR:
762 case AST_LOGIC_NOT:
763 width_hint = std::max(width_hint, 1);
764 sign_hint = false;
765 break;
766
767 case AST_TERNARY:
768 children.at(1)->detectSignWidthWorker(width_hint, sign_hint);
769 children.at(2)->detectSignWidthWorker(width_hint, sign_hint);
770 break;
771
772 case AST_MEMRD:
773 if (!id2ast->is_signed)
774 sign_hint = false;
775 if (!id2ast->children[0]->range_valid)
776 log_error("Failed to detect with of memory access `%s' at %s:%d!\n", str.c_str(), filename.c_str(), linenum);
777 this_width = id2ast->children[0]->range_left - id2ast->children[0]->range_right + 1;
778 width_hint = std::max(width_hint, this_width);
779 break;
780
781 // everything should have been handled above -> print error if not.
782 default:
783 for (auto f : log_files)
784 current_ast->dumpAst(f, "verilog-ast> ");
785 log_error("Don't know how to detect sign and width for %s node at %s:%d!\n",
786 type2str(type).c_str(), filename.c_str(), linenum);
787 }
788 }
789
790 // detect sign and width of an expression
791 void AstNode::detectSignWidth(int &width_hint, bool &sign_hint)
792 {
793 width_hint = -1, sign_hint = true;
794 detectSignWidthWorker(width_hint, sign_hint);
795 }
796
797 // create RTLIL from an AST node
798 // all generated cells, wires and processes are added to the module pointed to by 'current_module'
799 // when the AST node is an expression (AST_ADD, AST_BIT_XOR, etc.), the result signal is returned.
800 //
801 // note that this function is influenced by a number of global variables that might be set when
802 // called from genWidthRTLIL(). also note that this function recursively calls itself to transform
803 // larger expressions into a netlist of cells.
804 RTLIL::SigSpec AstNode::genRTLIL(int width_hint, bool sign_hint)
805 {
806 // in the following big switch() statement there are some uses of
807 // Clifford's Device (http://www.clifford.at/cfun/cliffdev/). In this
808 // cases this variable is used to hold the type of the cell that should
809 // be instanciated for this type of AST node.
810 std::string type_name;
811
812 current_filename = filename;
813 set_line_num(linenum);
814
815 switch (type)
816 {
817 // simply ignore this nodes.
818 // they are eighter leftovers from simplify() or are referenced by other nodes
819 // and are only accessed here thru this references
820 case AST_TASK:
821 case AST_FUNCTION:
822 case AST_AUTOWIRE:
823 case AST_LOCALPARAM:
824 case AST_DEFPARAM:
825 case AST_GENVAR:
826 case AST_GENFOR:
827 case AST_GENBLOCK:
828 case AST_GENIF:
829 case AST_GENCASE:
830 break;
831
832 // remember the parameter, needed for example in techmap
833 case AST_PARAMETER:
834 current_module->avail_parameters.insert(str);
835 break;
836
837 // create an RTLIL::Wire for an AST_WIRE node
838 case AST_WIRE: {
839 if (current_module->wires.count(str) != 0)
840 log_error("Re-definition of signal `%s' at %s:%d!\n",
841 str.c_str(), filename.c_str(), linenum);
842 if (!range_valid)
843 log_error("Signal `%s' with non-constant width at %s:%d!\n",
844 str.c_str(), filename.c_str(), linenum);
845
846 if (range_left < range_right && (range_left != -1 || range_right != 0)) {
847 int tmp = range_left;
848 range_left = range_right;
849 range_right = tmp;
850 }
851
852 RTLIL::Wire *wire = new RTLIL::Wire;
853 wire->attributes["\\src"] = stringf("%s:%d", filename.c_str(), linenum);
854 wire->name = str;
855 wire->width = range_left - range_right + 1;
856 wire->start_offset = range_right;
857 wire->port_id = port_id;
858 wire->port_input = is_input;
859 wire->port_output = is_output;
860 current_module->wires[wire->name] = wire;
861
862 for (auto &attr : attributes) {
863 if (attr.second->type != AST_CONSTANT)
864 log_error("Attribute `%s' with non-constant value at %s:%d!\n",
865 attr.first.c_str(), filename.c_str(), linenum);
866 wire->attributes[attr.first] = attr.second->asAttrConst();
867 }
868 }
869 break;
870
871 // create an RTLIL::Memory for an AST_MEMORY node
872 case AST_MEMORY: {
873 if (current_module->memories.count(str) != 0)
874 log_error("Re-definition of memory `%s' at %s:%d!\n",
875 str.c_str(), filename.c_str(), linenum);
876
877 assert(children.size() >= 2);
878 assert(children[0]->type == AST_RANGE);
879 assert(children[1]->type == AST_RANGE);
880
881 if (!children[0]->range_valid || !children[1]->range_valid)
882 log_error("Memory `%s' with non-constant width or size at %s:%d!\n",
883 str.c_str(), filename.c_str(), linenum);
884
885 RTLIL::Memory *memory = new RTLIL::Memory;
886 memory->attributes["\\src"] = stringf("%s:%d", filename.c_str(), linenum);
887 memory->name = str;
888 memory->width = children[0]->range_left - children[0]->range_right + 1;
889 memory->start_offset = children[0]->range_right;
890 memory->size = children[1]->range_left - children[1]->range_right;
891 current_module->memories[memory->name] = memory;
892
893 if (memory->size < 0)
894 memory->size *= -1;
895 memory->size += std::min(children[1]->range_left, children[1]->range_right) + 1;
896
897 for (auto &attr : attributes) {
898 if (attr.second->type != AST_CONSTANT)
899 log_error("Attribute `%s' with non-constant value at %s:%d!\n",
900 attr.first.c_str(), filename.c_str(), linenum);
901 memory->attributes[attr.first] = attr.second->asAttrConst();
902 }
903 }
904 break;
905
906 // simply return the corresponding RTLIL::SigSpec for an AST_CONSTANT node
907 case AST_CONSTANT:
908 {
909 if (width_hint < 0)
910 detectSignWidth(width_hint, sign_hint);
911
912 is_signed = sign_hint;
913 return RTLIL::SigSpec(bitsAsConst());
914 }
915
916 case AST_REALVALUE:
917 {
918 RTLIL::SigSpec sig = realAsConst(width_hint);
919 log("Warning: converting real value %e to binary %s at %s:%d.\n",
920 realvalue, log_signal(sig), filename.c_str(), linenum);
921 return sig;
922 }
923
924 // simply return the corresponding RTLIL::SigSpec for an AST_IDENTIFIER node
925 // for identifiers with dynamic bit ranges (e.g. "foo[bar]" or "foo[bar+3:bar]") a
926 // shifter cell is created and the output signal of this cell is returned
927 case AST_IDENTIFIER:
928 {
929 RTLIL::Wire *wire = NULL;
930 RTLIL::SigChunk chunk;
931
932 if (id2ast && id2ast->type == AST_AUTOWIRE && current_module->wires.count(str) == 0) {
933 RTLIL::Wire *wire = new RTLIL::Wire;
934 wire->attributes["\\src"] = stringf("%s:%d", filename.c_str(), linenum);
935 wire->name = str;
936 if (flag_autowire)
937 log("Warning: Identifier `%s' is implicitly declared at %s:%d.\n", str.c_str(), filename.c_str(), linenum);
938 else
939 log_error("Identifier `%s' is implicitly declared at %s:%d and `default_nettype is set to none.\n", str.c_str(), filename.c_str(), linenum);
940 current_module->wires[str] = wire;
941 }
942 else if (id2ast->type == AST_PARAMETER || id2ast->type == AST_LOCALPARAM) {
943 if (id2ast->children[0]->type != AST_CONSTANT)
944 log_error("Parameter %s does not evaluate to constant value at %s:%d!\n",
945 str.c_str(), filename.c_str(), linenum);
946 chunk = RTLIL::Const(id2ast->children[0]->bits);
947 goto use_const_chunk;
948 }
949 else if (!id2ast || (id2ast->type != AST_WIRE && id2ast->type != AST_AUTOWIRE &&
950 id2ast->type != AST_MEMORY) || current_module->wires.count(str) == 0)
951 log_error("Identifier `%s' doesn't map to any signal at %s:%d!\n",
952 str.c_str(), filename.c_str(), linenum);
953
954 if (id2ast->type == AST_MEMORY)
955 log_error("Identifier `%s' does map to an unexpanded memory at %s:%d!\n",
956 str.c_str(), filename.c_str(), linenum);
957
958 wire = current_module->wires[str];
959 chunk.wire = wire;
960 chunk.width = wire->width;
961 chunk.offset = 0;
962
963 use_const_chunk:
964 if (children.size() != 0) {
965 assert(children[0]->type == AST_RANGE);
966 if (!children[0]->range_valid) {
967 AstNode *left_at_zero_ast = children[0]->children[0]->clone();
968 AstNode *right_at_zero_ast = children[0]->children.size() >= 2 ? children[0]->children[1]->clone() : left_at_zero_ast->clone();
969 while (left_at_zero_ast->simplify(true, true, false, 1, -1, false, false)) { }
970 while (right_at_zero_ast->simplify(true, true, false, 1, -1, false, false)) { }
971 if (left_at_zero_ast->type != AST_CONSTANT || right_at_zero_ast->type != AST_CONSTANT)
972 log_error("Unsupported expression on dynamic range select on signal `%s' at %s:%d!\n",
973 str.c_str(), filename.c_str(), linenum);
974 int width = left_at_zero_ast->integer - right_at_zero_ast->integer + 1;
975 AstNode *fake_ast = new AstNode(AST_NONE, clone(), children[0]->children.size() >= 2 ?
976 children[0]->children[1]->clone() : children[0]->children[0]->clone());
977 fake_ast->children[0]->delete_children();
978 RTLIL::SigSpec sig = binop2rtlil(fake_ast, "$shr", width,
979 fake_ast->children[0]->genRTLIL(), fake_ast->children[1]->genRTLIL());
980 delete left_at_zero_ast;
981 delete right_at_zero_ast;
982 delete fake_ast;
983 return sig;
984 } else {
985 chunk.offset = children[0]->range_right - id2ast->range_right;
986 chunk.width = children[0]->range_left - children[0]->range_right + 1;
987 if (children[0]->range_left > id2ast->range_left || id2ast->range_right > children[0]->range_right)
988 log_error("Range select out of bounds on signal `%s' at %s:%d!\n",
989 str.c_str(), filename.c_str(), linenum);
990 }
991 }
992
993 RTLIL::SigSpec sig;
994 sig.chunks.push_back(chunk);
995 sig.width = chunk.width;
996
997 if (genRTLIL_subst_from && genRTLIL_subst_to)
998 sig.replace(*genRTLIL_subst_from, *genRTLIL_subst_to);
999
1000 is_signed = children.size() > 0 ? false : id2ast->is_signed && sign_hint;
1001 return sig;
1002 }
1003
1004 // just pass thru the signal. the parent will evaluate the is_signed property and interpret the SigSpec accordingly
1005 case AST_TO_SIGNED:
1006 case AST_TO_UNSIGNED: {
1007 RTLIL::SigSpec sig = children[0]->genRTLIL();
1008 if (sig.width < width_hint)
1009 sig.extend_u0(width_hint, sign_hint);
1010 is_signed = sign_hint;
1011 return sig;
1012 }
1013
1014 // concatenation of signals can be done directly using RTLIL::SigSpec
1015 case AST_CONCAT: {
1016 RTLIL::SigSpec sig;
1017 sig.width = 0;
1018 for (auto it = children.begin(); it != children.end(); it++) {
1019 RTLIL::SigSpec s = (*it)->genRTLIL();
1020 for (size_t i = 0; i < s.chunks.size(); i++) {
1021 sig.chunks.push_back(s.chunks[i]);
1022 sig.width += s.chunks[i].width;
1023 }
1024 }
1025 if (sig.width < width_hint)
1026 sig.extend_u0(width_hint, false);
1027 return sig;
1028 }
1029
1030 // replication of signals can be done directly using RTLIL::SigSpec
1031 case AST_REPLICATE: {
1032 RTLIL::SigSpec left = children[0]->genRTLIL();
1033 RTLIL::SigSpec right = children[1]->genRTLIL();
1034 if (!left.is_fully_const())
1035 log_error("Left operand of replicate expression is not constant at %s:%d!\n", filename.c_str(), linenum);
1036 int count = left.as_int();
1037 RTLIL::SigSpec sig;
1038 for (int i = 0; i < count; i++)
1039 sig.append(right);
1040 if (sig.width < width_hint)
1041 sig.extend_u0(width_hint, false);
1042 is_signed = false;
1043 return sig;
1044 }
1045
1046 // generate cells for unary operations: $not, $pos, $neg
1047 if (0) { case AST_BIT_NOT: type_name = "$not"; }
1048 if (0) { case AST_POS: type_name = "$pos"; }
1049 if (0) { case AST_NEG: type_name = "$neg"; }
1050 {
1051 RTLIL::SigSpec arg = children[0]->genRTLIL(width_hint, sign_hint);
1052 is_signed = children[0]->is_signed;
1053 int width = arg.width;
1054 if (width_hint > 0) {
1055 width = width_hint;
1056 widthExtend(this, arg, width, is_signed, "$pos");
1057 }
1058 return uniop2rtlil(this, type_name, width, arg);
1059 }
1060
1061 // generate cells for binary operations: $and, $or, $xor, $xnor
1062 if (0) { case AST_BIT_AND: type_name = "$and"; }
1063 if (0) { case AST_BIT_OR: type_name = "$or"; }
1064 if (0) { case AST_BIT_XOR: type_name = "$xor"; }
1065 if (0) { case AST_BIT_XNOR: type_name = "$xnor"; }
1066 {
1067 if (width_hint < 0)
1068 detectSignWidth(width_hint, sign_hint);
1069 RTLIL::SigSpec left = children[0]->genRTLIL(width_hint, sign_hint);
1070 RTLIL::SigSpec right = children[1]->genRTLIL(width_hint, sign_hint);
1071 int width = std::max(left.width, right.width);
1072 if (width_hint > 0)
1073 width = width_hint;
1074 is_signed = children[0]->is_signed && children[1]->is_signed;
1075 return binop2rtlil(this, type_name, width, left, right);
1076 }
1077
1078 // generate cells for unary operations: $reduce_and, $reduce_or, $reduce_xor, $reduce_xnor
1079 if (0) { case AST_REDUCE_AND: type_name = "$reduce_and"; }
1080 if (0) { case AST_REDUCE_OR: type_name = "$reduce_or"; }
1081 if (0) { case AST_REDUCE_XOR: type_name = "$reduce_xor"; }
1082 if (0) { case AST_REDUCE_XNOR: type_name = "$reduce_xnor"; }
1083 {
1084 RTLIL::SigSpec arg = children[0]->genRTLIL();
1085 RTLIL::SigSpec sig = uniop2rtlil(this, type_name, std::max(width_hint, 1), arg);
1086 return sig;
1087 }
1088
1089 // generate cells for unary operations: $reduce_bool
1090 // (this is actually just an $reduce_or, but for clearity a different cell type is used)
1091 if (0) { case AST_REDUCE_BOOL: type_name = "$reduce_bool"; }
1092 {
1093 RTLIL::SigSpec arg = children[0]->genRTLIL();
1094 RTLIL::SigSpec sig = arg.width > 1 ? uniop2rtlil(this, type_name, std::max(width_hint, 1), arg) : arg;
1095 return sig;
1096 }
1097
1098 // generate cells for binary operations: $shl, $shr, $sshl, $sshr
1099 if (0) { case AST_SHIFT_LEFT: type_name = "$shl"; }
1100 if (0) { case AST_SHIFT_RIGHT: type_name = "$shr"; }
1101 if (0) { case AST_SHIFT_SLEFT: type_name = "$sshl"; }
1102 if (0) { case AST_SHIFT_SRIGHT: type_name = "$sshr"; }
1103 {
1104 if (width_hint < 0)
1105 detectSignWidth(width_hint, sign_hint);
1106 RTLIL::SigSpec left = children[0]->genRTLIL(width_hint, sign_hint);
1107 RTLIL::SigSpec right = children[1]->genRTLIL();
1108 int width = width_hint > 0 ? width_hint : left.width;
1109 is_signed = children[0]->is_signed;
1110 return binop2rtlil(this, type_name, width, left, right);
1111 }
1112
1113 // generate cells for binary operations: $pow
1114 case AST_POW:
1115 {
1116 int right_width;
1117 bool right_signed;
1118 children[1]->detectSignWidth(right_width, right_signed);
1119 if (width_hint < 0)
1120 detectSignWidth(width_hint, sign_hint);
1121 RTLIL::SigSpec left = children[0]->genRTLIL(width_hint, sign_hint);
1122 RTLIL::SigSpec right = children[1]->genRTLIL(right_width, right_signed);
1123 int width = width_hint > 0 ? width_hint : left.width;
1124 is_signed = children[0]->is_signed;
1125 if (!flag_noopt && left.is_fully_const() && left.as_int() == 2 && !right_signed)
1126 return binop2rtlil(this, "$shl", width, RTLIL::SigSpec(1, left.width), right);
1127 return binop2rtlil(this, "$pow", width, left, right);
1128 }
1129
1130 // generate cells for binary operations: $lt, $le, $eq, $ne, $ge, $gt
1131 if (0) { case AST_LT: type_name = "$lt"; }
1132 if (0) { case AST_LE: type_name = "$le"; }
1133 if (0) { case AST_EQ: type_name = "$eq"; }
1134 if (0) { case AST_NE: type_name = "$ne"; }
1135 if (0) { case AST_EQX: type_name = "$eqx"; }
1136 if (0) { case AST_NEX: type_name = "$nex"; }
1137 if (0) { case AST_GE: type_name = "$ge"; }
1138 if (0) { case AST_GT: type_name = "$gt"; }
1139 {
1140 int width = std::max(width_hint, 1);
1141 width_hint = -1, sign_hint = true;
1142 children[0]->detectSignWidthWorker(width_hint, sign_hint);
1143 children[1]->detectSignWidthWorker(width_hint, sign_hint);
1144 RTLIL::SigSpec left = children[0]->genRTLIL(width_hint, sign_hint);
1145 RTLIL::SigSpec right = children[1]->genRTLIL(width_hint, sign_hint);
1146 RTLIL::SigSpec sig = binop2rtlil(this, type_name, width, left, right);
1147 return sig;
1148 }
1149
1150 // generate cells for binary operations: $add, $sub, $mul, $div, $mod
1151 if (0) { case AST_ADD: type_name = "$add"; }
1152 if (0) { case AST_SUB: type_name = "$sub"; }
1153 if (0) { case AST_MUL: type_name = "$mul"; }
1154 if (0) { case AST_DIV: type_name = "$div"; }
1155 if (0) { case AST_MOD: type_name = "$mod"; }
1156 {
1157 if (width_hint < 0)
1158 detectSignWidth(width_hint, sign_hint);
1159 RTLIL::SigSpec left = children[0]->genRTLIL(width_hint, sign_hint);
1160 RTLIL::SigSpec right = children[1]->genRTLIL(width_hint, sign_hint);
1161 #if 0
1162 int width = std::max(left.width, right.width);
1163 if (width > width_hint && width_hint > 0)
1164 width = width_hint;
1165 if (width < width_hint) {
1166 if (type == AST_ADD || type == AST_SUB || type == AST_DIV)
1167 width++;
1168 if (type == AST_SUB && (!children[0]->is_signed || !children[1]->is_signed))
1169 width = width_hint;
1170 if (type == AST_MUL)
1171 width = std::min(left.width + right.width, width_hint);
1172 }
1173 #else
1174 int width = std::max(std::max(left.width, right.width), width_hint);
1175 #endif
1176 is_signed = children[0]->is_signed && children[1]->is_signed;
1177 return binop2rtlil(this, type_name, width, left, right);
1178 }
1179
1180 // generate cells for binary operations: $logic_and, $logic_or
1181 if (0) { case AST_LOGIC_AND: type_name = "$logic_and"; }
1182 if (0) { case AST_LOGIC_OR: type_name = "$logic_or"; }
1183 {
1184 RTLIL::SigSpec left = children[0]->genRTLIL();
1185 RTLIL::SigSpec right = children[1]->genRTLIL();
1186 return binop2rtlil(this, type_name, std::max(width_hint, 1), left, right);
1187 }
1188
1189 // generate cells for unary operations: $logic_not
1190 case AST_LOGIC_NOT:
1191 {
1192 RTLIL::SigSpec arg = children[0]->genRTLIL();
1193 return uniop2rtlil(this, "$logic_not", std::max(width_hint, 1), arg);
1194 }
1195
1196 // generate multiplexer for ternary operator (aka ?:-operator)
1197 case AST_TERNARY:
1198 {
1199 if (width_hint < 0)
1200 detectSignWidth(width_hint, sign_hint);
1201
1202 RTLIL::SigSpec cond = children[0]->genRTLIL();
1203 RTLIL::SigSpec val1 = children[1]->genRTLIL(width_hint, sign_hint);
1204 RTLIL::SigSpec val2 = children[2]->genRTLIL(width_hint, sign_hint);
1205
1206 if (cond.width > 1)
1207 cond = uniop2rtlil(this, "$reduce_bool", 1, cond, false);
1208
1209 int width = std::max(val1.width, val2.width);
1210 is_signed = children[1]->is_signed && children[2]->is_signed;
1211 widthExtend(this, val1, width, is_signed, "$bu0");
1212 widthExtend(this, val2, width, is_signed, "$bu0");
1213
1214 RTLIL::SigSpec sig = mux2rtlil(this, cond, val1, val2);
1215
1216 if (sig.width < width_hint)
1217 sig.extend_u0(width_hint, sign_hint);
1218 return sig;
1219 }
1220
1221 // generate $memrd cells for memory read ports
1222 case AST_MEMRD:
1223 {
1224 std::stringstream sstr;
1225 sstr << "$memrd$" << str << "$" << filename << ":" << linenum << "$" << (RTLIL::autoidx++);
1226
1227 RTLIL::Cell *cell = new RTLIL::Cell;
1228 cell->attributes["\\src"] = stringf("%s:%d", filename.c_str(), linenum);
1229 cell->name = sstr.str();
1230 cell->type = "$memrd";
1231 current_module->cells[cell->name] = cell;
1232
1233 RTLIL::Wire *wire = new RTLIL::Wire;
1234 wire->attributes["\\src"] = stringf("%s:%d", filename.c_str(), linenum);
1235 wire->name = cell->name + "_DATA";
1236 wire->width = current_module->memories[str]->width;
1237 current_module->wires[wire->name] = wire;
1238
1239 int addr_bits = 1;
1240 while ((1 << addr_bits) < current_module->memories[str]->size)
1241 addr_bits++;
1242
1243 cell->connections["\\CLK"] = RTLIL::SigSpec(RTLIL::State::Sx, 1);
1244 cell->connections["\\ADDR"] = children[0]->genWidthRTLIL(addr_bits);
1245 cell->connections["\\DATA"] = RTLIL::SigSpec(wire);
1246
1247 cell->parameters["\\MEMID"] = RTLIL::Const(str);
1248 cell->parameters["\\ABITS"] = RTLIL::Const(addr_bits);
1249 cell->parameters["\\WIDTH"] = RTLIL::Const(wire->width);
1250
1251 cell->parameters["\\CLK_ENABLE"] = RTLIL::Const(0);
1252 cell->parameters["\\CLK_POLARITY"] = RTLIL::Const(0);
1253 cell->parameters["\\TRANSPARENT"] = RTLIL::Const(0);
1254
1255 return RTLIL::SigSpec(wire);
1256 }
1257
1258 // generate $memwr cells for memory write ports
1259 case AST_MEMWR:
1260 {
1261 std::stringstream sstr;
1262 sstr << "$memwr$" << str << "$" << filename << ":" << linenum << "$" << (RTLIL::autoidx++);
1263
1264 RTLIL::Cell *cell = new RTLIL::Cell;
1265 cell->attributes["\\src"] = stringf("%s:%d", filename.c_str(), linenum);
1266 cell->name = sstr.str();
1267 cell->type = "$memwr";
1268 current_module->cells[cell->name] = cell;
1269
1270 int addr_bits = 1;
1271 while ((1 << addr_bits) < current_module->memories[str]->size)
1272 addr_bits++;
1273
1274 cell->connections["\\CLK"] = RTLIL::SigSpec(RTLIL::State::Sx, 1);
1275 cell->connections["\\ADDR"] = children[0]->genWidthRTLIL(addr_bits);
1276 cell->connections["\\DATA"] = children[1]->genWidthRTLIL(current_module->memories[str]->width);
1277 cell->connections["\\EN"] = children[2]->genRTLIL();
1278
1279 if (cell->connections["\\EN"].width > 1)
1280 cell->connections["\\EN"] = uniop2rtlil(this, "$reduce_bool", 1, cell->connections["\\EN"], false);
1281
1282 cell->parameters["\\MEMID"] = RTLIL::Const(str);
1283 cell->parameters["\\ABITS"] = RTLIL::Const(addr_bits);
1284 cell->parameters["\\WIDTH"] = RTLIL::Const(current_module->memories[str]->width);
1285
1286 cell->parameters["\\CLK_ENABLE"] = RTLIL::Const(0);
1287 cell->parameters["\\CLK_POLARITY"] = RTLIL::Const(0);
1288
1289 cell->parameters["\\PRIORITY"] = RTLIL::Const(RTLIL::autoidx-1);
1290 }
1291 break;
1292
1293 // generate $assert cells
1294 case AST_ASSERT:
1295 {
1296 log_assert(children.size() == 2);
1297
1298 RTLIL::SigSpec check = children[0]->genRTLIL();
1299 log_assert(check.width == 1);
1300
1301 RTLIL::SigSpec en = children[1]->genRTLIL();
1302 log_assert(en.width == 1);
1303
1304 std::stringstream sstr;
1305 sstr << "$assert$" << filename << ":" << linenum << "$" << (RTLIL::autoidx++);
1306
1307 RTLIL::Cell *cell = new RTLIL::Cell;
1308 cell->attributes["\\src"] = stringf("%s:%d", filename.c_str(), linenum);
1309 cell->name = sstr.str();
1310 cell->type = "$assert";
1311 current_module->cells[cell->name] = cell;
1312
1313 for (auto &attr : attributes) {
1314 if (attr.second->type != AST_CONSTANT)
1315 log_error("Attribute `%s' with non-constant value at %s:%d!\n",
1316 attr.first.c_str(), filename.c_str(), linenum);
1317 cell->attributes[attr.first] = attr.second->asAttrConst();
1318 }
1319
1320 cell->connections["\\A"] = check;
1321 cell->connections["\\EN"] = en;
1322 }
1323 break;
1324
1325 // add entries to current_module->connections for assignments (outside of always blocks)
1326 case AST_ASSIGN:
1327 {
1328 if (children[0]->type == AST_IDENTIFIER && children[0]->id2ast && children[0]->id2ast->type == AST_AUTOWIRE) {
1329 RTLIL::SigSpec right = children[1]->genRTLIL();
1330 RTLIL::SigSpec left = children[0]->genWidthRTLIL(right.width);
1331 current_module->connections.push_back(RTLIL::SigSig(left, right));
1332 } else {
1333 RTLIL::SigSpec left = children[0]->genRTLIL();
1334 RTLIL::SigSpec right = children[1]->genWidthRTLIL(left.width);
1335 current_module->connections.push_back(RTLIL::SigSig(left, right));
1336 }
1337 }
1338 break;
1339
1340 // create an RTLIL::Cell for an AST_CELL
1341 case AST_CELL:
1342 {
1343 int port_counter = 0, para_counter = 0;
1344 RTLIL::Cell *cell = new RTLIL::Cell;
1345 cell->attributes["\\src"] = stringf("%s:%d", filename.c_str(), linenum);
1346 cell->name = str;
1347 for (auto it = children.begin(); it != children.end(); it++) {
1348 AstNode *child = *it;
1349 if (child->type == AST_CELLTYPE) {
1350 cell->type = child->str;
1351 if (flag_icells && cell->type.substr(0, 2) == "\\$")
1352 cell->type = cell->type.substr(1);
1353 continue;
1354 }
1355 if (child->type == AST_PARASET) {
1356 if (child->children[0]->type != AST_CONSTANT)
1357 log_error("Parameter `%s' with non-constant value at %s:%d!\n",
1358 child->str.c_str(), filename.c_str(), linenum);
1359 if (child->str.size() == 0) {
1360 char buf[100];
1361 snprintf(buf, 100, "$%d", ++para_counter);
1362 cell->parameters[buf] = child->children[0]->asParaConst();
1363 } else {
1364 cell->parameters[child->str] = child->children[0]->asParaConst();
1365 }
1366 continue;
1367 }
1368 if (child->type == AST_ARGUMENT) {
1369 RTLIL::SigSpec sig;
1370 if (child->children.size() > 0)
1371 sig = child->children[0]->genRTLIL();
1372 if (child->str.size() == 0) {
1373 char buf[100];
1374 snprintf(buf, 100, "$%d", ++port_counter);
1375 cell->connections[buf] = sig;
1376 } else {
1377 cell->connections[child->str] = sig;
1378 }
1379 continue;
1380 }
1381 assert(0);
1382 }
1383 for (auto &attr : attributes) {
1384 if (attr.second->type != AST_CONSTANT)
1385 log_error("Attribute `%s' with non-constant value at %s:%d!\n",
1386 attr.first.c_str(), filename.c_str(), linenum);
1387 cell->attributes[attr.first] = attr.second->asAttrConst();
1388 }
1389 if (current_module->cells.count(cell->name) != 0)
1390 log_error("Re-definition of cell `%s' at %s:%d!\n",
1391 str.c_str(), filename.c_str(), linenum);
1392 current_module->cells[str] = cell;
1393 }
1394 break;
1395
1396 // use ProcessGenerator for always blocks
1397 case AST_ALWAYS: {
1398 AstNode *always = this->clone();
1399 ProcessGenerator generator(always);
1400 ignoreThisSignalsInInitial.append(generator.outputSignals);
1401 delete always;
1402 } break;
1403
1404 case AST_INITIAL: {
1405 AstNode *always = this->clone();
1406 ProcessGenerator generator(always, ignoreThisSignalsInInitial);
1407 delete always;
1408 } break;
1409
1410 // everything should have been handled above -> print error if not.
1411 default:
1412 for (auto f : log_files)
1413 current_ast->dumpAst(f, "verilog-ast> ");
1414 type_name = type2str(type);
1415 log_error("Don't know how to generate RTLIL code for %s node at %s:%d!\n",
1416 type_name.c_str(), filename.c_str(), linenum);
1417 }
1418
1419 return RTLIL::SigSpec();
1420 }
1421
1422 // this is a wrapper for AstNode::genRTLIL() when a specific signal width is requested and/or
1423 // signals must be substituted before beeing used as input values (used by ProcessGenerator)
1424 // note that this is using some global variables to communicate this special settings to AstNode::genRTLIL().
1425 RTLIL::SigSpec AstNode::genWidthRTLIL(int width, RTLIL::SigSpec *subst_from, RTLIL::SigSpec *subst_to)
1426 {
1427 RTLIL::SigSpec *backup_subst_from = genRTLIL_subst_from;
1428 RTLIL::SigSpec *backup_subst_to = genRTLIL_subst_to;
1429
1430 if (subst_from)
1431 genRTLIL_subst_from = subst_from;
1432 if (subst_to)
1433 genRTLIL_subst_to = subst_to;
1434
1435 bool sign_hint = true;
1436 int width_hint = width;
1437 detectSignWidthWorker(width_hint, sign_hint);
1438 RTLIL::SigSpec sig = genRTLIL(width_hint, sign_hint);
1439
1440 genRTLIL_subst_from = backup_subst_from;
1441 genRTLIL_subst_to = backup_subst_to;
1442
1443 if (width >= 0)
1444 sig.extend_u0(width, is_signed);
1445
1446 return sig;
1447 }
1448