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