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