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