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