SigSpec refactoring: change RTLIL::SigSpec::chunks() to be read-only, created interim...
[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 for (size_t i = 0; i < sig.chunks().size(); i++)
313 {
314 RTLIL::SigChunk &chunk = sig.chunks_rw()[i];
315 if (chunk.wire == NULL)
316 continue;
317
318 RTLIL::Wire *wire = new RTLIL::Wire;
319 wire->attributes["\\src"] = stringf("%s:%d", always->filename.c_str(), always->linenum);
320 do {
321 wire->name = stringf("$%d%s[%d:%d]", new_temp_count[chunk.wire]++,
322 chunk.wire->name.c_str(), chunk.width+chunk.offset-1, chunk.offset);;
323 if (chunk.wire->name.find('$') != std::string::npos)
324 wire->name += stringf("$%d", RTLIL::autoidx++);
325 } while (current_module->wires.count(wire->name) > 0);
326 wire->width = chunk.width;
327 current_module->wires[wire->name] = wire;
328
329 chunk.wire = wire;
330 chunk.offset = 0;
331 }
332 return sig;
333 }
334
335 // recursively traverse the AST an collect all assigned signals
336 void collect_lvalues(RTLIL::SigSpec &reg, AstNode *ast, bool type_eq, bool type_le, bool run_sort_and_unify = true)
337 {
338 switch (ast->type)
339 {
340 case AST_CASE:
341 for (auto child : ast->children)
342 if (child != ast->children[0]) {
343 assert(child->type == AST_COND);
344 collect_lvalues(reg, child, type_eq, type_le, false);
345 }
346 break;
347
348 case AST_COND:
349 case AST_ALWAYS:
350 case AST_INITIAL:
351 for (auto child : ast->children)
352 if (child->type == AST_BLOCK)
353 collect_lvalues(reg, child, type_eq, type_le, false);
354 break;
355
356 case AST_BLOCK:
357 for (auto child : ast->children) {
358 if (child->type == AST_ASSIGN_EQ && type_eq)
359 reg.append(child->children[0]->genRTLIL());
360 if (child->type == AST_ASSIGN_LE && type_le)
361 reg.append(child->children[0]->genRTLIL());
362 if (child->type == AST_CASE || child->type == AST_BLOCK)
363 collect_lvalues(reg, child, type_eq, type_le, false);
364 }
365 break;
366
367 default:
368 assert(0);
369 }
370
371 if (run_sort_and_unify)
372 reg.sort_and_unify();
373 }
374
375 // remove all assignments to the given signal pattern in a case and all its children.
376 // e.g. when the last statement in the code "a = 23; if (b) a = 42; a = 0;" is processed this
377 // function is called to clean up the first two assignments as they are overwritten by
378 // the third assignment.
379 void removeSignalFromCaseTree(RTLIL::SigSpec pattern, RTLIL::CaseRule *cs)
380 {
381 for (auto it = cs->actions.begin(); it != cs->actions.end(); it++)
382 it->first.remove2(pattern, &it->second);
383
384 for (auto it = cs->switches.begin(); it != cs->switches.end(); it++)
385 for (auto it2 = (*it)->cases.begin(); it2 != (*it)->cases.end(); it2++)
386 removeSignalFromCaseTree(pattern, *it2);
387 }
388
389 // add an assignment (aka "action") but split it up in chunks. this way huge assignments
390 // are avoided and the generated $mux cells have a more "natural" size.
391 void addChunkActions(std::vector<RTLIL::SigSig> &actions, RTLIL::SigSpec lvalue, RTLIL::SigSpec rvalue, bool inSyncRule = false)
392 {
393 if (inSyncRule && initSyncSignals.size() > 0) {
394 init_lvalue.append(lvalue.extract(initSyncSignals));
395 init_rvalue.append(lvalue.extract(initSyncSignals, &rvalue));
396 lvalue.remove2(initSyncSignals, &rvalue);
397 }
398 assert(lvalue.size() == rvalue.size());
399 lvalue.optimize();
400 rvalue.optimize();
401
402 int offset = 0;
403 for (size_t i = 0; i < lvalue.chunks().size(); i++) {
404 RTLIL::SigSpec lhs = lvalue.chunks()[i];
405 RTLIL::SigSpec rhs = rvalue.extract(offset, lvalue.chunks()[i].width);
406 if (inSyncRule && lvalue.chunks()[i].wire && lvalue.chunks()[i].wire->get_bool_attribute("\\nosync"))
407 rhs = RTLIL::SigSpec(RTLIL::State::Sx, rhs.size());
408 actions.push_back(RTLIL::SigSig(lhs, rhs));
409 offset += lhs.size();
410 }
411 }
412
413 // recursively process the AST and fill the RTLIL::Process
414 void processAst(AstNode *ast)
415 {
416 switch (ast->type)
417 {
418 case AST_BLOCK:
419 for (auto child : ast->children)
420 processAst(child);
421 break;
422
423 case AST_ASSIGN_EQ:
424 case AST_ASSIGN_LE:
425 {
426 RTLIL::SigSpec unmapped_lvalue = ast->children[0]->genRTLIL(), lvalue = unmapped_lvalue;
427 RTLIL::SigSpec rvalue = ast->children[1]->genWidthRTLIL(lvalue.size(), &subst_rvalue_from, &subst_rvalue_to);
428 lvalue.replace(subst_lvalue_from, subst_lvalue_to);
429
430 if (ast->type == AST_ASSIGN_EQ) {
431 subst_rvalue_from.remove2(unmapped_lvalue, &subst_rvalue_to);
432 subst_rvalue_from.append(unmapped_lvalue);
433 subst_rvalue_from.optimize();
434 subst_rvalue_to.append(rvalue);
435 subst_rvalue_to.optimize();
436 }
437
438 removeSignalFromCaseTree(lvalue, current_case);
439 current_case->actions.push_back(RTLIL::SigSig(lvalue, rvalue));
440 }
441 break;
442
443 case AST_CASE:
444 {
445 RTLIL::SwitchRule *sw = new RTLIL::SwitchRule;
446 sw->signal = ast->children[0]->genWidthRTLIL(-1, &subst_rvalue_from, &subst_rvalue_to);
447 current_case->switches.push_back(sw);
448
449 for (auto &attr : ast->attributes) {
450 if (attr.second->type != AST_CONSTANT)
451 log_error("Attribute `%s' with non-constant value at %s:%d!\n",
452 attr.first.c_str(), ast->filename.c_str(), ast->linenum);
453 sw->attributes[attr.first] = attr.second->asAttrConst();
454 }
455
456 RTLIL::SigSpec this_case_eq_lvalue;
457 collect_lvalues(this_case_eq_lvalue, ast, true, false);
458
459 RTLIL::SigSpec this_case_eq_ltemp = new_temp_signal(this_case_eq_lvalue);
460
461 RTLIL::SigSpec this_case_eq_rvalue = this_case_eq_lvalue;
462 this_case_eq_rvalue.replace(subst_rvalue_from, subst_rvalue_to);
463
464 RTLIL::SigSpec backup_subst_lvalue_from = subst_lvalue_from;
465 RTLIL::SigSpec backup_subst_lvalue_to = subst_lvalue_to;
466
467 RTLIL::SigSpec backup_subst_rvalue_from = subst_rvalue_from;
468 RTLIL::SigSpec backup_subst_rvalue_to = subst_rvalue_to;
469
470 RTLIL::CaseRule *default_case = NULL;
471 RTLIL::CaseRule *last_generated_case = NULL;
472 for (auto child : ast->children)
473 {
474 if (child == ast->children[0])
475 continue;
476 assert(child->type == AST_COND);
477
478 subst_lvalue_from = backup_subst_lvalue_from;
479 subst_lvalue_to = backup_subst_lvalue_to;
480
481 subst_rvalue_from = backup_subst_rvalue_from;
482 subst_rvalue_to = backup_subst_rvalue_to;
483
484 subst_lvalue_from.remove2(this_case_eq_lvalue, &subst_lvalue_to);
485 subst_lvalue_from.append(this_case_eq_lvalue);
486 subst_lvalue_from.optimize();
487 subst_lvalue_to.append(this_case_eq_ltemp);
488 subst_lvalue_to.optimize();
489
490 RTLIL::CaseRule *backup_case = current_case;
491 current_case = new RTLIL::CaseRule;
492 last_generated_case = current_case;
493 addChunkActions(current_case->actions, this_case_eq_ltemp, this_case_eq_rvalue);
494 for (auto node : child->children) {
495 if (node->type == AST_DEFAULT)
496 default_case = current_case;
497 else if (node->type == AST_BLOCK)
498 processAst(node);
499 else
500 current_case->compare.push_back(node->genWidthRTLIL(sw->signal.size(), &subst_rvalue_from, &subst_rvalue_to));
501 }
502 if (default_case != current_case)
503 sw->cases.push_back(current_case);
504 else
505 log_assert(current_case->compare.size() == 0);
506 current_case = backup_case;
507 }
508
509 if (last_generated_case != NULL && ast->get_bool_attribute("\\full_case") && default_case == NULL) {
510 last_generated_case->compare.clear();
511 } else {
512 if (default_case == NULL) {
513 default_case = new RTLIL::CaseRule;
514 addChunkActions(default_case->actions, this_case_eq_ltemp, this_case_eq_rvalue);
515 }
516 sw->cases.push_back(default_case);
517 }
518
519 subst_lvalue_from = backup_subst_lvalue_from;
520 subst_lvalue_to = backup_subst_lvalue_to;
521
522 subst_rvalue_from = backup_subst_rvalue_from;
523 subst_rvalue_to = backup_subst_rvalue_to;
524
525 subst_rvalue_from.remove2(this_case_eq_lvalue, &subst_rvalue_to);
526 subst_rvalue_from.append(this_case_eq_lvalue);
527 subst_rvalue_from.optimize();
528 subst_rvalue_to.append(this_case_eq_ltemp);
529 subst_rvalue_to.optimize();
530
531 this_case_eq_lvalue.replace(subst_lvalue_from, subst_lvalue_to);
532 removeSignalFromCaseTree(this_case_eq_lvalue, current_case);
533 addChunkActions(current_case->actions, this_case_eq_lvalue, this_case_eq_ltemp);
534 }
535 break;
536
537 case AST_WIRE:
538 log_error("Found wire declaration in block without label at at %s:%d!\n", ast->filename.c_str(), ast->linenum);
539 break;
540
541 case AST_TCALL:
542 case AST_FOR:
543 break;
544
545 default:
546 log_abort();
547 }
548 }
549 };
550
551 // detect sign and width of an expression
552 void AstNode::detectSignWidthWorker(int &width_hint, bool &sign_hint, bool *found_real)
553 {
554 std::string type_name;
555 bool sub_sign_hint = true;
556 int sub_width_hint = -1;
557 int this_width = 0;
558 AstNode *range = NULL;
559 AstNode *id_ast = NULL;
560
561 bool local_found_real = false;
562 if (found_real == NULL)
563 found_real = &local_found_real;
564
565 switch (type)
566 {
567 case AST_CONSTANT:
568 width_hint = std::max(width_hint, int(bits.size()));
569 if (!is_signed)
570 sign_hint = false;
571 break;
572
573 case AST_REALVALUE:
574 *found_real = true;
575 width_hint = std::max(width_hint, 32);
576 break;
577
578 case AST_IDENTIFIER:
579 id_ast = id2ast;
580 if (id_ast == NULL && current_scope.count(str))
581 id_ast = current_scope.at(str);
582 if (!id_ast)
583 log_error("Failed to resolve identifier %s for width detection at %s:%d!\n", str.c_str(), filename.c_str(), linenum);
584 if (id_ast->type == AST_PARAMETER || id_ast->type == AST_LOCALPARAM) {
585 if (id_ast->children.size() > 1 && id_ast->children[1]->range_valid) {
586 this_width = id_ast->children[1]->range_left - id_ast->children[1]->range_right + 1;
587 } else
588 if (id_ast->children[0]->type == AST_CONSTANT) {
589 this_width = id_ast->children[0]->bits.size();
590 } else
591 log_error("Failed to detect width for parameter %s at %s:%d!\n", str.c_str(), filename.c_str(), linenum);
592 if (children.size() != 0)
593 range = children[0];
594 } else if (id_ast->type == AST_WIRE || id_ast->type == AST_AUTOWIRE) {
595 if (!id_ast->range_valid) {
596 if (id_ast->type == AST_AUTOWIRE)
597 this_width = 1;
598 else {
599 // current_ast_mod->dumpAst(NULL, "mod> ");
600 // log("---\n");
601 // id_ast->dumpAst(NULL, "decl> ");
602 // dumpAst(NULL, "ref> ");
603 log_error("Failed to detect with of signal access `%s' at %s:%d!\n", str.c_str(), filename.c_str(), linenum);
604 }
605 } else {
606 this_width = id_ast->range_left - id_ast->range_right + 1;
607 if (children.size() != 0)
608 range = children[0];
609 }
610 } else if (id_ast->type == AST_GENVAR) {
611 this_width = 32;
612 } else if (id_ast->type == AST_MEMORY) {
613 if (!id_ast->children[0]->range_valid)
614 log_error("Failed to detect with of memory access `%s' at %s:%d!\n", str.c_str(), filename.c_str(), linenum);
615 this_width = id_ast->children[0]->range_left - id_ast->children[0]->range_right + 1;
616 } else
617 log_error("Failed to detect width for identifier %s at %s:%d!\n", str.c_str(), filename.c_str(), linenum);
618 if (range) {
619 if (range->children.size() == 1)
620 this_width = 1;
621 else if (!range->range_valid) {
622 AstNode *left_at_zero_ast = children[0]->children[0]->clone();
623 AstNode *right_at_zero_ast = children[0]->children.size() >= 2 ? children[0]->children[1]->clone() : left_at_zero_ast->clone();
624 while (left_at_zero_ast->simplify(true, true, false, 1, -1, false, false)) { }
625 while (right_at_zero_ast->simplify(true, true, false, 1, -1, false, false)) { }
626 if (left_at_zero_ast->type != AST_CONSTANT || right_at_zero_ast->type != AST_CONSTANT)
627 log_error("Unsupported expression on dynamic range select on signal `%s' at %s:%d!\n",
628 str.c_str(), filename.c_str(), linenum);
629 this_width = left_at_zero_ast->integer - right_at_zero_ast->integer + 1;
630 delete left_at_zero_ast;
631 delete right_at_zero_ast;
632 } else
633 this_width = range->range_left - range->range_right + 1;
634 } else
635 width_hint = std::max(width_hint, this_width);
636 if (!id_ast->is_signed)
637 sign_hint = false;
638 break;
639
640 case AST_TO_BITS:
641 while (children[0]->simplify(true, false, false, 1, -1, false, false) == true) { }
642 if (children[0]->type != AST_CONSTANT)
643 log_error("Left operand of tobits expression is not constant at %s:%d!\n", filename.c_str(), linenum);
644 children[1]->detectSignWidthWorker(sub_width_hint, sign_hint);
645 width_hint = std::max(width_hint, children[0]->bitsAsConst().as_int());
646 break;
647
648 case AST_TO_SIGNED:
649 children.at(0)->detectSignWidthWorker(width_hint, sub_sign_hint);
650 break;
651
652 case AST_TO_UNSIGNED:
653 children.at(0)->detectSignWidthWorker(width_hint, sub_sign_hint);
654 sign_hint = false;
655 break;
656
657 case AST_CONCAT:
658 for (auto child : children) {
659 sub_width_hint = 0;
660 sub_sign_hint = true;
661 child->detectSignWidthWorker(sub_width_hint, sub_sign_hint);
662 this_width += sub_width_hint;
663 }
664 width_hint = std::max(width_hint, this_width);
665 sign_hint = false;
666 break;
667
668 case AST_REPLICATE:
669 while (children[0]->simplify(true, false, false, 1, -1, false, true) == true) { }
670 if (children[0]->type != AST_CONSTANT)
671 log_error("Left operand of replicate expression is not constant at %s:%d!\n", filename.c_str(), linenum);
672 children[1]->detectSignWidthWorker(sub_width_hint, sub_sign_hint);
673 width_hint = std::max(width_hint, children[0]->bitsAsConst().as_int() * sub_width_hint);
674 sign_hint = false;
675 break;
676
677 case AST_NEG:
678 case AST_BIT_NOT:
679 case AST_POS:
680 children[0]->detectSignWidthWorker(width_hint, sign_hint, found_real);
681 break;
682
683 case AST_BIT_AND:
684 case AST_BIT_OR:
685 case AST_BIT_XOR:
686 case AST_BIT_XNOR:
687 for (auto child : children)
688 child->detectSignWidthWorker(width_hint, sign_hint, found_real);
689 break;
690
691 case AST_REDUCE_AND:
692 case AST_REDUCE_OR:
693 case AST_REDUCE_XOR:
694 case AST_REDUCE_XNOR:
695 case AST_REDUCE_BOOL:
696 width_hint = std::max(width_hint, 1);
697 sign_hint = false;
698 break;
699
700 case AST_SHIFT_LEFT:
701 case AST_SHIFT_RIGHT:
702 case AST_SHIFT_SLEFT:
703 case AST_SHIFT_SRIGHT:
704 case AST_POW:
705 children[0]->detectSignWidthWorker(width_hint, sign_hint, found_real);
706 break;
707
708 case AST_LT:
709 case AST_LE:
710 case AST_EQ:
711 case AST_NE:
712 case AST_EQX:
713 case AST_NEX:
714 case AST_GE:
715 case AST_GT:
716 width_hint = std::max(width_hint, 1);
717 sign_hint = false;
718 break;
719
720 case AST_ADD:
721 case AST_SUB:
722 case AST_MUL:
723 case AST_DIV:
724 case AST_MOD:
725 for (auto child : children)
726 child->detectSignWidthWorker(width_hint, sign_hint, found_real);
727 break;
728
729 case AST_LOGIC_AND:
730 case AST_LOGIC_OR:
731 case AST_LOGIC_NOT:
732 width_hint = std::max(width_hint, 1);
733 sign_hint = false;
734 break;
735
736 case AST_TERNARY:
737 children.at(1)->detectSignWidthWorker(width_hint, sign_hint, found_real);
738 children.at(2)->detectSignWidthWorker(width_hint, sign_hint, found_real);
739 break;
740
741 case AST_MEMRD:
742 if (!id2ast->is_signed)
743 sign_hint = false;
744 if (!id2ast->children[0]->range_valid)
745 log_error("Failed to detect with of memory access `%s' at %s:%d!\n", str.c_str(), filename.c_str(), linenum);
746 this_width = id2ast->children[0]->range_left - id2ast->children[0]->range_right + 1;
747 width_hint = std::max(width_hint, this_width);
748 break;
749
750 // everything should have been handled above -> print error if not.
751 default:
752 for (auto f : log_files)
753 current_ast->dumpAst(f, "verilog-ast> ");
754 log_error("Don't know how to detect sign and width for %s node at %s:%d!\n",
755 type2str(type).c_str(), filename.c_str(), linenum);
756 }
757
758 if (*found_real)
759 sign_hint = true;
760 }
761
762 // detect sign and width of an expression
763 void AstNode::detectSignWidth(int &width_hint, bool &sign_hint, bool *found_real)
764 {
765 width_hint = -1;
766 sign_hint = true;
767 if (found_real)
768 *found_real = false;
769 detectSignWidthWorker(width_hint, sign_hint, found_real);
770 }
771
772 // create RTLIL from an AST node
773 // all generated cells, wires and processes are added to the module pointed to by 'current_module'
774 // when the AST node is an expression (AST_ADD, AST_BIT_XOR, etc.), the result signal is returned.
775 //
776 // note that this function is influenced by a number of global variables that might be set when
777 // called from genWidthRTLIL(). also note that this function recursively calls itself to transform
778 // larger expressions into a netlist of cells.
779 RTLIL::SigSpec AstNode::genRTLIL(int width_hint, bool sign_hint)
780 {
781 // in the following big switch() statement there are some uses of
782 // Clifford's Device (http://www.clifford.at/cfun/cliffdev/). In this
783 // cases this variable is used to hold the type of the cell that should
784 // be instanciated for this type of AST node.
785 std::string type_name;
786
787 current_filename = filename;
788 set_line_num(linenum);
789
790 switch (type)
791 {
792 // simply ignore this nodes.
793 // they are eighter leftovers from simplify() or are referenced by other nodes
794 // and are only accessed here thru this references
795 case AST_TASK:
796 case AST_FUNCTION:
797 case AST_AUTOWIRE:
798 case AST_LOCALPARAM:
799 case AST_DEFPARAM:
800 case AST_GENVAR:
801 case AST_GENFOR:
802 case AST_GENBLOCK:
803 case AST_GENIF:
804 case AST_GENCASE:
805 break;
806
807 // remember the parameter, needed for example in techmap
808 case AST_PARAMETER:
809 current_module->avail_parameters.insert(str);
810 break;
811
812 // create an RTLIL::Wire for an AST_WIRE node
813 case AST_WIRE: {
814 if (current_module->wires.count(str) != 0)
815 log_error("Re-definition of signal `%s' at %s:%d!\n",
816 str.c_str(), filename.c_str(), linenum);
817 if (!range_valid)
818 log_error("Signal `%s' with non-constant width at %s:%d!\n",
819 str.c_str(), filename.c_str(), linenum);
820
821 if (range_left < range_right && (range_left != -1 || range_right != 0)) {
822 int tmp = range_left;
823 range_left = range_right;
824 range_right = tmp;
825 }
826
827 RTLIL::Wire *wire = new RTLIL::Wire;
828 wire->attributes["\\src"] = stringf("%s:%d", filename.c_str(), linenum);
829 wire->name = str;
830 wire->width = range_left - range_right + 1;
831 wire->start_offset = range_right;
832 wire->port_id = port_id;
833 wire->port_input = is_input;
834 wire->port_output = is_output;
835 current_module->wires[wire->name] = wire;
836
837 for (auto &attr : attributes) {
838 if (attr.second->type != AST_CONSTANT)
839 log_error("Attribute `%s' with non-constant value at %s:%d!\n",
840 attr.first.c_str(), filename.c_str(), linenum);
841 wire->attributes[attr.first] = attr.second->asAttrConst();
842 }
843 }
844 break;
845
846 // create an RTLIL::Memory for an AST_MEMORY node
847 case AST_MEMORY: {
848 if (current_module->memories.count(str) != 0)
849 log_error("Re-definition of memory `%s' at %s:%d!\n",
850 str.c_str(), filename.c_str(), linenum);
851
852 assert(children.size() >= 2);
853 assert(children[0]->type == AST_RANGE);
854 assert(children[1]->type == AST_RANGE);
855
856 if (!children[0]->range_valid || !children[1]->range_valid)
857 log_error("Memory `%s' with non-constant width or size at %s:%d!\n",
858 str.c_str(), filename.c_str(), linenum);
859
860 RTLIL::Memory *memory = new RTLIL::Memory;
861 memory->attributes["\\src"] = stringf("%s:%d", filename.c_str(), linenum);
862 memory->name = str;
863 memory->width = children[0]->range_left - children[0]->range_right + 1;
864 memory->start_offset = children[0]->range_right;
865 memory->size = children[1]->range_left - children[1]->range_right;
866 current_module->memories[memory->name] = memory;
867
868 if (memory->size < 0)
869 memory->size *= -1;
870 memory->size += std::min(children[1]->range_left, children[1]->range_right) + 1;
871
872 for (auto &attr : attributes) {
873 if (attr.second->type != AST_CONSTANT)
874 log_error("Attribute `%s' with non-constant value at %s:%d!\n",
875 attr.first.c_str(), filename.c_str(), linenum);
876 memory->attributes[attr.first] = attr.second->asAttrConst();
877 }
878 }
879 break;
880
881 // simply return the corresponding RTLIL::SigSpec for an AST_CONSTANT node
882 case AST_CONSTANT:
883 {
884 if (width_hint < 0)
885 detectSignWidth(width_hint, sign_hint);
886
887 is_signed = sign_hint;
888 return RTLIL::SigSpec(bitsAsConst());
889 }
890
891 case AST_REALVALUE:
892 {
893 RTLIL::SigSpec sig = realAsConst(width_hint);
894 log("Warning: converting real value %e to binary %s at %s:%d.\n",
895 realvalue, log_signal(sig), filename.c_str(), linenum);
896 return sig;
897 }
898
899 // simply return the corresponding RTLIL::SigSpec for an AST_IDENTIFIER node
900 // for identifiers with dynamic bit ranges (e.g. "foo[bar]" or "foo[bar+3:bar]") a
901 // shifter cell is created and the output signal of this cell is returned
902 case AST_IDENTIFIER:
903 {
904 RTLIL::Wire *wire = NULL;
905 RTLIL::SigChunk chunk;
906
907 if (id2ast && id2ast->type == AST_AUTOWIRE && current_module->wires.count(str) == 0) {
908 RTLIL::Wire *wire = new RTLIL::Wire;
909 wire->attributes["\\src"] = stringf("%s:%d", filename.c_str(), linenum);
910 wire->name = str;
911 if (flag_autowire)
912 log("Warning: Identifier `%s' is implicitly declared at %s:%d.\n", str.c_str(), filename.c_str(), linenum);
913 else
914 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);
915 current_module->wires[str] = wire;
916 }
917 else if (id2ast->type == AST_PARAMETER || id2ast->type == AST_LOCALPARAM) {
918 if (id2ast->children[0]->type != AST_CONSTANT)
919 log_error("Parameter %s does not evaluate to constant value at %s:%d!\n",
920 str.c_str(), filename.c_str(), linenum);
921 chunk = RTLIL::Const(id2ast->children[0]->bits);
922 goto use_const_chunk;
923 }
924 else if (!id2ast || (id2ast->type != AST_WIRE && id2ast->type != AST_AUTOWIRE &&
925 id2ast->type != AST_MEMORY) || current_module->wires.count(str) == 0)
926 log_error("Identifier `%s' doesn't map to any signal at %s:%d!\n",
927 str.c_str(), filename.c_str(), linenum);
928
929 if (id2ast->type == AST_MEMORY)
930 log_error("Identifier `%s' does map to an unexpanded memory at %s:%d!\n",
931 str.c_str(), filename.c_str(), linenum);
932
933 wire = current_module->wires[str];
934 chunk.wire = wire;
935 chunk.width = wire->width;
936 chunk.offset = 0;
937
938 use_const_chunk:
939 if (children.size() != 0) {
940 assert(children[0]->type == AST_RANGE);
941 if (!children[0]->range_valid) {
942 AstNode *left_at_zero_ast = children[0]->children[0]->clone();
943 AstNode *right_at_zero_ast = children[0]->children.size() >= 2 ? children[0]->children[1]->clone() : left_at_zero_ast->clone();
944 while (left_at_zero_ast->simplify(true, true, false, 1, -1, false, false)) { }
945 while (right_at_zero_ast->simplify(true, true, false, 1, -1, false, false)) { }
946 if (left_at_zero_ast->type != AST_CONSTANT || right_at_zero_ast->type != AST_CONSTANT)
947 log_error("Unsupported expression on dynamic range select on signal `%s' at %s:%d!\n",
948 str.c_str(), filename.c_str(), linenum);
949 int width = left_at_zero_ast->integer - right_at_zero_ast->integer + 1;
950 AstNode *fake_ast = new AstNode(AST_NONE, clone(), children[0]->children.size() >= 2 ?
951 children[0]->children[1]->clone() : children[0]->children[0]->clone());
952 fake_ast->children[0]->delete_children();
953 RTLIL::SigSpec sig = binop2rtlil(fake_ast, "$shr", width,
954 fake_ast->children[0]->genRTLIL(), fake_ast->children[1]->genRTLIL());
955 delete left_at_zero_ast;
956 delete right_at_zero_ast;
957 delete fake_ast;
958 return sig;
959 } else {
960 chunk.offset = children[0]->range_right - id2ast->range_right;
961 chunk.width = children[0]->range_left - children[0]->range_right + 1;
962 if (children[0]->range_left > id2ast->range_left || id2ast->range_right > children[0]->range_right)
963 log_error("Range select out of bounds on signal `%s' at %s:%d!\n",
964 str.c_str(), filename.c_str(), linenum);
965 }
966 }
967
968 RTLIL::SigSpec sig(chunk);
969
970 if (genRTLIL_subst_from && genRTLIL_subst_to)
971 sig.replace(*genRTLIL_subst_from, *genRTLIL_subst_to);
972
973 is_signed = children.size() > 0 ? false : id2ast->is_signed && sign_hint;
974 return sig;
975 }
976
977 // just pass thru the signal. the parent will evaluate the is_signed property and interpret the SigSpec accordingly
978 case AST_TO_SIGNED:
979 case AST_TO_UNSIGNED: {
980 RTLIL::SigSpec sig = children[0]->genRTLIL();
981 if (sig.size() < width_hint)
982 sig.extend_u0(width_hint, sign_hint);
983 is_signed = sign_hint;
984 return sig;
985 }
986
987 // concatenation of signals can be done directly using RTLIL::SigSpec
988 case AST_CONCAT: {
989 RTLIL::SigSpec sig;
990 for (auto it = children.begin(); it != children.end(); it++)
991 sig.append((*it)->genRTLIL());
992 if (sig.size() < width_hint)
993 sig.extend_u0(width_hint, false);
994 return sig;
995 }
996
997 // replication of signals can be done directly using RTLIL::SigSpec
998 case AST_REPLICATE: {
999 RTLIL::SigSpec left = children[0]->genRTLIL();
1000 RTLIL::SigSpec right = children[1]->genRTLIL();
1001 if (!left.is_fully_const())
1002 log_error("Left operand of replicate expression is not constant at %s:%d!\n", filename.c_str(), linenum);
1003 int count = left.as_int();
1004 RTLIL::SigSpec sig;
1005 for (int i = 0; i < count; i++)
1006 sig.append(right);
1007 if (sig.size() < width_hint)
1008 sig.extend_u0(width_hint, false);
1009 is_signed = false;
1010 return sig;
1011 }
1012
1013 // generate cells for unary operations: $not, $pos, $neg
1014 if (0) { case AST_BIT_NOT: type_name = "$not"; }
1015 if (0) { case AST_POS: type_name = "$pos"; }
1016 if (0) { case AST_NEG: type_name = "$neg"; }
1017 {
1018 RTLIL::SigSpec arg = children[0]->genRTLIL(width_hint, sign_hint);
1019 is_signed = children[0]->is_signed;
1020 int width = arg.size();
1021 if (width_hint > 0) {
1022 width = width_hint;
1023 widthExtend(this, arg, width, is_signed, "$pos");
1024 }
1025 return uniop2rtlil(this, type_name, width, arg);
1026 }
1027
1028 // generate cells for binary operations: $and, $or, $xor, $xnor
1029 if (0) { case AST_BIT_AND: type_name = "$and"; }
1030 if (0) { case AST_BIT_OR: type_name = "$or"; }
1031 if (0) { case AST_BIT_XOR: type_name = "$xor"; }
1032 if (0) { case AST_BIT_XNOR: type_name = "$xnor"; }
1033 {
1034 if (width_hint < 0)
1035 detectSignWidth(width_hint, sign_hint);
1036 RTLIL::SigSpec left = children[0]->genRTLIL(width_hint, sign_hint);
1037 RTLIL::SigSpec right = children[1]->genRTLIL(width_hint, sign_hint);
1038 int width = std::max(left.size(), right.size());
1039 if (width_hint > 0)
1040 width = width_hint;
1041 is_signed = children[0]->is_signed && children[1]->is_signed;
1042 return binop2rtlil(this, type_name, width, left, right);
1043 }
1044
1045 // generate cells for unary operations: $reduce_and, $reduce_or, $reduce_xor, $reduce_xnor
1046 if (0) { case AST_REDUCE_AND: type_name = "$reduce_and"; }
1047 if (0) { case AST_REDUCE_OR: type_name = "$reduce_or"; }
1048 if (0) { case AST_REDUCE_XOR: type_name = "$reduce_xor"; }
1049 if (0) { case AST_REDUCE_XNOR: type_name = "$reduce_xnor"; }
1050 {
1051 RTLIL::SigSpec arg = children[0]->genRTLIL();
1052 RTLIL::SigSpec sig = uniop2rtlil(this, type_name, std::max(width_hint, 1), arg);
1053 return sig;
1054 }
1055
1056 // generate cells for unary operations: $reduce_bool
1057 // (this is actually just an $reduce_or, but for clearity a different cell type is used)
1058 if (0) { case AST_REDUCE_BOOL: type_name = "$reduce_bool"; }
1059 {
1060 RTLIL::SigSpec arg = children[0]->genRTLIL();
1061 RTLIL::SigSpec sig = arg.size() > 1 ? uniop2rtlil(this, type_name, std::max(width_hint, 1), arg) : arg;
1062 return sig;
1063 }
1064
1065 // generate cells for binary operations: $shl, $shr, $sshl, $sshr
1066 if (0) { case AST_SHIFT_LEFT: type_name = "$shl"; }
1067 if (0) { case AST_SHIFT_RIGHT: type_name = "$shr"; }
1068 if (0) { case AST_SHIFT_SLEFT: type_name = "$sshl"; }
1069 if (0) { case AST_SHIFT_SRIGHT: type_name = "$sshr"; }
1070 {
1071 if (width_hint < 0)
1072 detectSignWidth(width_hint, sign_hint);
1073 RTLIL::SigSpec left = children[0]->genRTLIL(width_hint, sign_hint);
1074 RTLIL::SigSpec right = children[1]->genRTLIL();
1075 int width = width_hint > 0 ? width_hint : left.size();
1076 is_signed = children[0]->is_signed;
1077 return binop2rtlil(this, type_name, width, left, right);
1078 }
1079
1080 // generate cells for binary operations: $pow
1081 case AST_POW:
1082 {
1083 int right_width;
1084 bool right_signed;
1085 children[1]->detectSignWidth(right_width, right_signed);
1086 if (width_hint < 0)
1087 detectSignWidth(width_hint, sign_hint);
1088 RTLIL::SigSpec left = children[0]->genRTLIL(width_hint, sign_hint);
1089 RTLIL::SigSpec right = children[1]->genRTLIL(right_width, right_signed);
1090 int width = width_hint > 0 ? width_hint : left.size();
1091 is_signed = children[0]->is_signed;
1092 if (!flag_noopt && left.is_fully_const() && left.as_int() == 2 && !right_signed)
1093 return binop2rtlil(this, "$shl", width, RTLIL::SigSpec(1, left.size()), right);
1094 return binop2rtlil(this, "$pow", width, left, right);
1095 }
1096
1097 // generate cells for binary operations: $lt, $le, $eq, $ne, $ge, $gt
1098 if (0) { case AST_LT: type_name = "$lt"; }
1099 if (0) { case AST_LE: type_name = "$le"; }
1100 if (0) { case AST_EQ: type_name = "$eq"; }
1101 if (0) { case AST_NE: type_name = "$ne"; }
1102 if (0) { case AST_EQX: type_name = "$eqx"; }
1103 if (0) { case AST_NEX: type_name = "$nex"; }
1104 if (0) { case AST_GE: type_name = "$ge"; }
1105 if (0) { case AST_GT: type_name = "$gt"; }
1106 {
1107 int width = std::max(width_hint, 1);
1108 width_hint = -1, sign_hint = true;
1109 children[0]->detectSignWidthWorker(width_hint, sign_hint);
1110 children[1]->detectSignWidthWorker(width_hint, sign_hint);
1111 RTLIL::SigSpec left = children[0]->genRTLIL(width_hint, sign_hint);
1112 RTLIL::SigSpec right = children[1]->genRTLIL(width_hint, sign_hint);
1113 RTLIL::SigSpec sig = binop2rtlil(this, type_name, width, left, right);
1114 return sig;
1115 }
1116
1117 // generate cells for binary operations: $add, $sub, $mul, $div, $mod
1118 if (0) { case AST_ADD: type_name = "$add"; }
1119 if (0) { case AST_SUB: type_name = "$sub"; }
1120 if (0) { case AST_MUL: type_name = "$mul"; }
1121 if (0) { case AST_DIV: type_name = "$div"; }
1122 if (0) { case AST_MOD: type_name = "$mod"; }
1123 {
1124 if (width_hint < 0)
1125 detectSignWidth(width_hint, sign_hint);
1126 RTLIL::SigSpec left = children[0]->genRTLIL(width_hint, sign_hint);
1127 RTLIL::SigSpec right = children[1]->genRTLIL(width_hint, sign_hint);
1128 #if 0
1129 int width = std::max(left.size(), right.size());
1130 if (width > width_hint && width_hint > 0)
1131 width = width_hint;
1132 if (width < width_hint) {
1133 if (type == AST_ADD || type == AST_SUB || type == AST_DIV)
1134 width++;
1135 if (type == AST_SUB && (!children[0]->is_signed || !children[1]->is_signed))
1136 width = width_hint;
1137 if (type == AST_MUL)
1138 width = std::min(left.size() + right.size(), width_hint);
1139 }
1140 #else
1141 int width = std::max(std::max(left.size(), right.size()), width_hint);
1142 #endif
1143 is_signed = children[0]->is_signed && children[1]->is_signed;
1144 return binop2rtlil(this, type_name, width, left, right);
1145 }
1146
1147 // generate cells for binary operations: $logic_and, $logic_or
1148 if (0) { case AST_LOGIC_AND: type_name = "$logic_and"; }
1149 if (0) { case AST_LOGIC_OR: type_name = "$logic_or"; }
1150 {
1151 RTLIL::SigSpec left = children[0]->genRTLIL();
1152 RTLIL::SigSpec right = children[1]->genRTLIL();
1153 return binop2rtlil(this, type_name, std::max(width_hint, 1), left, right);
1154 }
1155
1156 // generate cells for unary operations: $logic_not
1157 case AST_LOGIC_NOT:
1158 {
1159 RTLIL::SigSpec arg = children[0]->genRTLIL();
1160 return uniop2rtlil(this, "$logic_not", std::max(width_hint, 1), arg);
1161 }
1162
1163 // generate multiplexer for ternary operator (aka ?:-operator)
1164 case AST_TERNARY:
1165 {
1166 if (width_hint < 0)
1167 detectSignWidth(width_hint, sign_hint);
1168
1169 RTLIL::SigSpec cond = children[0]->genRTLIL();
1170 RTLIL::SigSpec val1 = children[1]->genRTLIL(width_hint, sign_hint);
1171 RTLIL::SigSpec val2 = children[2]->genRTLIL(width_hint, sign_hint);
1172
1173 if (cond.size() > 1)
1174 cond = uniop2rtlil(this, "$reduce_bool", 1, cond, false);
1175
1176 int width = std::max(val1.size(), val2.size());
1177 is_signed = children[1]->is_signed && children[2]->is_signed;
1178 widthExtend(this, val1, width, is_signed, "$bu0");
1179 widthExtend(this, val2, width, is_signed, "$bu0");
1180
1181 RTLIL::SigSpec sig = mux2rtlil(this, cond, val1, val2);
1182
1183 if (sig.size() < width_hint)
1184 sig.extend_u0(width_hint, sign_hint);
1185 return sig;
1186 }
1187
1188 // generate $memrd cells for memory read ports
1189 case AST_MEMRD:
1190 {
1191 std::stringstream sstr;
1192 sstr << "$memrd$" << str << "$" << filename << ":" << linenum << "$" << (RTLIL::autoidx++);
1193
1194 RTLIL::Cell *cell = new RTLIL::Cell;
1195 cell->attributes["\\src"] = stringf("%s:%d", filename.c_str(), linenum);
1196 cell->name = sstr.str();
1197 cell->type = "$memrd";
1198 current_module->cells[cell->name] = cell;
1199
1200 RTLIL::Wire *wire = new RTLIL::Wire;
1201 wire->attributes["\\src"] = stringf("%s:%d", filename.c_str(), linenum);
1202 wire->name = cell->name + "_DATA";
1203 wire->width = current_module->memories[str]->width;
1204 current_module->wires[wire->name] = wire;
1205
1206 int addr_bits = 1;
1207 while ((1 << addr_bits) < current_module->memories[str]->size)
1208 addr_bits++;
1209
1210 cell->connections["\\CLK"] = RTLIL::SigSpec(RTLIL::State::Sx, 1);
1211 cell->connections["\\ADDR"] = children[0]->genWidthRTLIL(addr_bits);
1212 cell->connections["\\DATA"] = RTLIL::SigSpec(wire);
1213
1214 cell->parameters["\\MEMID"] = RTLIL::Const(str);
1215 cell->parameters["\\ABITS"] = RTLIL::Const(addr_bits);
1216 cell->parameters["\\WIDTH"] = RTLIL::Const(wire->width);
1217
1218 cell->parameters["\\CLK_ENABLE"] = RTLIL::Const(0);
1219 cell->parameters["\\CLK_POLARITY"] = RTLIL::Const(0);
1220 cell->parameters["\\TRANSPARENT"] = RTLIL::Const(0);
1221
1222 return RTLIL::SigSpec(wire);
1223 }
1224
1225 // generate $memwr cells for memory write ports
1226 case AST_MEMWR:
1227 {
1228 std::stringstream sstr;
1229 sstr << "$memwr$" << str << "$" << filename << ":" << linenum << "$" << (RTLIL::autoidx++);
1230
1231 RTLIL::Cell *cell = new RTLIL::Cell;
1232 cell->attributes["\\src"] = stringf("%s:%d", filename.c_str(), linenum);
1233 cell->name = sstr.str();
1234 cell->type = "$memwr";
1235 current_module->cells[cell->name] = cell;
1236
1237 int addr_bits = 1;
1238 while ((1 << addr_bits) < current_module->memories[str]->size)
1239 addr_bits++;
1240
1241 cell->connections["\\CLK"] = RTLIL::SigSpec(RTLIL::State::Sx, 1);
1242 cell->connections["\\ADDR"] = children[0]->genWidthRTLIL(addr_bits);
1243 cell->connections["\\DATA"] = children[1]->genWidthRTLIL(current_module->memories[str]->width);
1244 cell->connections["\\EN"] = children[2]->genRTLIL();
1245
1246 cell->parameters["\\MEMID"] = RTLIL::Const(str);
1247 cell->parameters["\\ABITS"] = RTLIL::Const(addr_bits);
1248 cell->parameters["\\WIDTH"] = RTLIL::Const(current_module->memories[str]->width);
1249
1250 cell->parameters["\\CLK_ENABLE"] = RTLIL::Const(0);
1251 cell->parameters["\\CLK_POLARITY"] = RTLIL::Const(0);
1252
1253 cell->parameters["\\PRIORITY"] = RTLIL::Const(RTLIL::autoidx-1);
1254 }
1255 break;
1256
1257 // generate $assert cells
1258 case AST_ASSERT:
1259 {
1260 log_assert(children.size() == 2);
1261
1262 RTLIL::SigSpec check = children[0]->genRTLIL();
1263 log_assert(check.size() == 1);
1264
1265 RTLIL::SigSpec en = children[1]->genRTLIL();
1266 log_assert(en.size() == 1);
1267
1268 std::stringstream sstr;
1269 sstr << "$assert$" << filename << ":" << linenum << "$" << (RTLIL::autoidx++);
1270
1271 RTLIL::Cell *cell = new RTLIL::Cell;
1272 cell->attributes["\\src"] = stringf("%s:%d", filename.c_str(), linenum);
1273 cell->name = sstr.str();
1274 cell->type = "$assert";
1275 current_module->cells[cell->name] = cell;
1276
1277 for (auto &attr : attributes) {
1278 if (attr.second->type != AST_CONSTANT)
1279 log_error("Attribute `%s' with non-constant value at %s:%d!\n",
1280 attr.first.c_str(), filename.c_str(), linenum);
1281 cell->attributes[attr.first] = attr.second->asAttrConst();
1282 }
1283
1284 cell->connections["\\A"] = check;
1285 cell->connections["\\EN"] = en;
1286 }
1287 break;
1288
1289 // add entries to current_module->connections for assignments (outside of always blocks)
1290 case AST_ASSIGN:
1291 {
1292 if (children[0]->type == AST_IDENTIFIER && children[0]->id2ast && children[0]->id2ast->type == AST_AUTOWIRE) {
1293 RTLIL::SigSpec right = children[1]->genRTLIL();
1294 RTLIL::SigSpec left = children[0]->genWidthRTLIL(right.size());
1295 current_module->connections.push_back(RTLIL::SigSig(left, right));
1296 } else {
1297 RTLIL::SigSpec left = children[0]->genRTLIL();
1298 RTLIL::SigSpec right = children[1]->genWidthRTLIL(left.size());
1299 current_module->connections.push_back(RTLIL::SigSig(left, right));
1300 }
1301 }
1302 break;
1303
1304 // create an RTLIL::Cell for an AST_CELL
1305 case AST_CELL:
1306 {
1307 int port_counter = 0, para_counter = 0;
1308 RTLIL::Cell *cell = new RTLIL::Cell;
1309 cell->attributes["\\src"] = stringf("%s:%d", filename.c_str(), linenum);
1310 cell->name = str;
1311 for (auto it = children.begin(); it != children.end(); it++) {
1312 AstNode *child = *it;
1313 if (child->type == AST_CELLTYPE) {
1314 cell->type = child->str;
1315 if (flag_icells && cell->type.substr(0, 2) == "\\$")
1316 cell->type = cell->type.substr(1);
1317 continue;
1318 }
1319 if (child->type == AST_PARASET) {
1320 if (child->children[0]->type != AST_CONSTANT)
1321 log_error("Parameter `%s' with non-constant value at %s:%d!\n",
1322 child->str.c_str(), filename.c_str(), linenum);
1323 if (child->str.size() == 0) {
1324 char buf[100];
1325 snprintf(buf, 100, "$%d", ++para_counter);
1326 cell->parameters[buf] = child->children[0]->asParaConst();
1327 } else {
1328 cell->parameters[child->str] = child->children[0]->asParaConst();
1329 }
1330 continue;
1331 }
1332 if (child->type == AST_ARGUMENT) {
1333 RTLIL::SigSpec sig;
1334 if (child->children.size() > 0)
1335 sig = child->children[0]->genRTLIL();
1336 if (child->str.size() == 0) {
1337 char buf[100];
1338 snprintf(buf, 100, "$%d", ++port_counter);
1339 cell->connections[buf] = sig;
1340 } else {
1341 cell->connections[child->str] = sig;
1342 }
1343 continue;
1344 }
1345 assert(0);
1346 }
1347 for (auto &attr : attributes) {
1348 if (attr.second->type != AST_CONSTANT)
1349 log_error("Attribute `%s' with non-constant value at %s:%d!\n",
1350 attr.first.c_str(), filename.c_str(), linenum);
1351 cell->attributes[attr.first] = attr.second->asAttrConst();
1352 }
1353 if (current_module->cells.count(cell->name) != 0)
1354 log_error("Re-definition of cell `%s' at %s:%d!\n",
1355 str.c_str(), filename.c_str(), linenum);
1356 current_module->cells[str] = cell;
1357 }
1358 break;
1359
1360 // use ProcessGenerator for always blocks
1361 case AST_ALWAYS: {
1362 AstNode *always = this->clone();
1363 ProcessGenerator generator(always);
1364 ignoreThisSignalsInInitial.append(generator.outputSignals);
1365 delete always;
1366 } break;
1367
1368 case AST_INITIAL: {
1369 AstNode *always = this->clone();
1370 ProcessGenerator generator(always, ignoreThisSignalsInInitial);
1371 delete always;
1372 } break;
1373
1374 // everything should have been handled above -> print error if not.
1375 default:
1376 for (auto f : log_files)
1377 current_ast->dumpAst(f, "verilog-ast> ");
1378 type_name = type2str(type);
1379 log_error("Don't know how to generate RTLIL code for %s node at %s:%d!\n",
1380 type_name.c_str(), filename.c_str(), linenum);
1381 }
1382
1383 return RTLIL::SigSpec();
1384 }
1385
1386 // this is a wrapper for AstNode::genRTLIL() when a specific signal width is requested and/or
1387 // signals must be substituted before beeing used as input values (used by ProcessGenerator)
1388 // note that this is using some global variables to communicate this special settings to AstNode::genRTLIL().
1389 RTLIL::SigSpec AstNode::genWidthRTLIL(int width, RTLIL::SigSpec *subst_from, RTLIL::SigSpec *subst_to)
1390 {
1391 RTLIL::SigSpec *backup_subst_from = genRTLIL_subst_from;
1392 RTLIL::SigSpec *backup_subst_to = genRTLIL_subst_to;
1393
1394 if (subst_from)
1395 genRTLIL_subst_from = subst_from;
1396 if (subst_to)
1397 genRTLIL_subst_to = subst_to;
1398
1399 bool sign_hint = true;
1400 int width_hint = width;
1401 detectSignWidthWorker(width_hint, sign_hint);
1402 RTLIL::SigSpec sig = genRTLIL(width_hint, sign_hint);
1403
1404 genRTLIL_subst_from = backup_subst_from;
1405 genRTLIL_subst_to = backup_subst_to;
1406
1407 if (width >= 0)
1408 sig.extend_u0(width, is_signed);
1409
1410 return sig;
1411 }
1412