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