Merge branch 'koriakin/xc7nocarrymux' into xaig
[yosys.git] / frontends / ast / simplify.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 "frontends/verilog/verilog_frontend.h"
32 #include "ast.h"
33
34 #include <sstream>
35 #include <stdarg.h>
36 #include <stdlib.h>
37 #include <math.h>
38
39 YOSYS_NAMESPACE_BEGIN
40
41 using namespace AST;
42 using namespace AST_INTERNAL;
43
44 // convert the AST into a simpler AST that has all parameters substituted by their
45 // values, unrolled for-loops, expanded generate blocks, etc. when this function
46 // is done with an AST it can be converted into RTLIL using genRTLIL().
47 //
48 // this function also does all name resolving and sets the id2ast member of all
49 // nodes that link to a different node using names and lexical scoping.
50 bool AstNode::simplify(bool const_fold, bool at_zero, bool in_lvalue, int stage, int width_hint, bool sign_hint, bool in_param)
51 {
52 static int recursion_counter = 0;
53 static bool deep_recursion_warning = false;
54
55 if (recursion_counter++ == 1000 && deep_recursion_warning) {
56 log_warning("Deep recursion in AST simplifier.\nDoes this design contain insanely long expressions?\n");
57 deep_recursion_warning = false;
58 }
59
60 AstNode *newNode = NULL;
61 bool did_something = false;
62
63 #if 0
64 log("-------------\n");
65 log("AST simplify[%d] depth %d at %s:%d on %s %p:\n", stage, recursion_counter, filename.c_str(), linenum, type2str(type).c_str(), this);
66 log("const_fold=%d, at_zero=%d, in_lvalue=%d, stage=%d, width_hint=%d, sign_hint=%d, in_param=%d\n",
67 int(const_fold), int(at_zero), int(in_lvalue), int(stage), int(width_hint), int(sign_hint), int(in_param));
68 // dumpAst(NULL, "> ");
69 #endif
70
71 if (stage == 0)
72 {
73 log_assert(type == AST_MODULE || type == AST_INTERFACE);
74
75 deep_recursion_warning = true;
76 while (simplify(const_fold, at_zero, in_lvalue, 1, width_hint, sign_hint, in_param)) { }
77
78 if (!flag_nomem2reg && !get_bool_attribute("\\nomem2reg"))
79 {
80 dict<AstNode*, pool<std::string>> mem2reg_places;
81 dict<AstNode*, uint32_t> mem2reg_candidates, dummy_proc_flags;
82 uint32_t flags = flag_mem2reg ? AstNode::MEM2REG_FL_ALL : 0;
83 mem2reg_as_needed_pass1(mem2reg_places, mem2reg_candidates, dummy_proc_flags, flags);
84
85 pool<AstNode*> mem2reg_set;
86 for (auto &it : mem2reg_candidates)
87 {
88 AstNode *mem = it.first;
89 uint32_t memflags = it.second;
90 bool this_nomeminit = flag_nomeminit;
91 log_assert((memflags & ~0x00ffff00) == 0);
92
93 if (mem->get_bool_attribute("\\nomem2reg"))
94 continue;
95
96 if (mem->get_bool_attribute("\\nomeminit") || get_bool_attribute("\\nomeminit"))
97 this_nomeminit = true;
98
99 if (memflags & AstNode::MEM2REG_FL_FORCED)
100 goto silent_activate;
101
102 if (memflags & AstNode::MEM2REG_FL_EQ2)
103 goto verbose_activate;
104
105 if (memflags & AstNode::MEM2REG_FL_SET_ASYNC)
106 goto verbose_activate;
107
108 if ((memflags & AstNode::MEM2REG_FL_SET_INIT) && (memflags & AstNode::MEM2REG_FL_SET_ELSE) && this_nomeminit)
109 goto verbose_activate;
110
111 if (memflags & AstNode::MEM2REG_FL_CMPLX_LHS)
112 goto verbose_activate;
113
114 if ((memflags & AstNode::MEM2REG_FL_CONST_LHS) && !(memflags & AstNode::MEM2REG_FL_VAR_LHS))
115 goto verbose_activate;
116
117 // log("Note: Not replacing memory %s with list of registers (flags=0x%08lx).\n", mem->str.c_str(), long(memflags));
118 continue;
119
120 verbose_activate:
121 if (mem2reg_set.count(mem) == 0) {
122 std::string message = stringf("Replacing memory %s with list of registers.", mem->str.c_str());
123 bool first_element = true;
124 for (auto &place : mem2reg_places[it.first]) {
125 message += stringf("%s%s", first_element ? " See " : ", ", place.c_str());
126 first_element = false;
127 }
128 log_warning("%s\n", message.c_str());
129 }
130
131 silent_activate:
132 // log("Note: Replacing memory %s with list of registers (flags=0x%08lx).\n", mem->str.c_str(), long(memflags));
133 mem2reg_set.insert(mem);
134 }
135
136 for (auto node : mem2reg_set)
137 {
138 int mem_width, mem_size, addr_bits;
139 node->meminfo(mem_width, mem_size, addr_bits);
140
141 int data_range_left = node->children[0]->range_left;
142 int data_range_right = node->children[0]->range_right;
143
144 if (node->children[0]->range_swapped)
145 std::swap(data_range_left, data_range_right);
146
147 for (int i = 0; i < mem_size; i++) {
148 AstNode *reg = new AstNode(AST_WIRE, new AstNode(AST_RANGE,
149 mkconst_int(data_range_left, true), mkconst_int(data_range_right, true)));
150 reg->str = stringf("%s[%d]", node->str.c_str(), i);
151 reg->is_reg = true;
152 reg->is_signed = node->is_signed;
153 children.push_back(reg);
154 while (reg->simplify(true, false, false, 1, -1, false, false)) { }
155 }
156 }
157
158 AstNode *async_block = NULL;
159 while (mem2reg_as_needed_pass2(mem2reg_set, this, NULL, async_block)) { }
160
161 vector<AstNode*> delnodes;
162 mem2reg_remove(mem2reg_set, delnodes);
163
164 for (auto node : delnodes)
165 delete node;
166 }
167
168 while (simplify(const_fold, at_zero, in_lvalue, 2, width_hint, sign_hint, in_param)) { }
169 recursion_counter--;
170 return false;
171 }
172
173 current_filename = filename;
174 set_line_num(linenum);
175
176 // we do not look inside a task or function
177 // (but as soon as a task or function is instantiated we process the generated AST as usual)
178 if (type == AST_FUNCTION || type == AST_TASK) {
179 recursion_counter--;
180 return false;
181 }
182
183 // deactivate all calls to non-synthesis system tasks
184 // note that $display, $finish, and $stop are used for synthesis-time DRC so they're not in this list
185 if ((type == AST_FCALL || type == AST_TCALL) && (str == "$strobe" || str == "$monitor" || str == "$time" ||
186 str == "$dumpfile" || str == "$dumpvars" || str == "$dumpon" || str == "$dumpoff" || str == "$dumpall")) {
187 log_file_warning(filename, linenum, "Ignoring call to system %s %s.\n", type == AST_FCALL ? "function" : "task", str.c_str());
188 delete_children();
189 str = std::string();
190 }
191
192 if ((type == AST_TCALL) && (str == "$display" || str == "$write") && (!current_always || current_always->type != AST_INITIAL)) {
193 log_file_warning(filename, linenum, "System task `%s' outside initial block is unsupported.\n", str.c_str());
194 delete_children();
195 str = std::string();
196 }
197
198 // print messages if this a call to $display() or $write()
199 // This code implements only a small subset of Verilog-2005 $display() format specifiers,
200 // but should be good enough for most uses
201 if ((type == AST_TCALL) && ((str == "$display") || (str == "$write")))
202 {
203 int nargs = GetSize(children);
204 if (nargs < 1)
205 log_file_error(filename, linenum, "System task `%s' got %d arguments, expected >= 1.\n",
206 str.c_str(), int(children.size()));
207
208 // First argument is the format string
209 AstNode *node_string = children[0];
210 while (node_string->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
211 if (node_string->type != AST_CONSTANT)
212 log_file_error(filename, linenum, "Failed to evaluate system task `%s' with non-constant 1st argument.\n", str.c_str());
213 std::string sformat = node_string->bitsAsConst().decode_string();
214
215 // Other arguments are placeholders. Process the string as we go through it
216 std::string sout;
217 int next_arg = 1;
218 for (size_t i = 0; i < sformat.length(); i++)
219 {
220 // format specifier
221 if (sformat[i] == '%')
222 {
223 // If there's no next character, that's a problem
224 if (i+1 >= sformat.length())
225 log_file_error(filename, linenum, "System task `%s' called with `%%' at end of string.\n", str.c_str());
226
227 char cformat = sformat[++i];
228
229 // %% is special, does not need a matching argument
230 if (cformat == '%')
231 {
232 sout += '%';
233 continue;
234 }
235
236 // Simplify the argument
237 AstNode *node_arg = nullptr;
238
239 // Everything from here on depends on the format specifier
240 switch (cformat)
241 {
242 case 's':
243 case 'S':
244 case 'd':
245 case 'D':
246 case 'x':
247 case 'X':
248 if (next_arg >= GetSize(children))
249 log_file_error(filename, linenum, "Missing argument for %%%c format specifier in system task `%s'.\n",
250 cformat, str.c_str());
251
252 node_arg = children[next_arg++];
253 while (node_arg->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
254 if (node_arg->type != AST_CONSTANT)
255 log_file_error(filename, linenum, "Failed to evaluate system task `%s' with non-constant argument.\n", str.c_str());
256 break;
257
258 case 'm':
259 case 'M':
260 break;
261
262 default:
263 log_file_error(filename, linenum, "System task `%s' called with invalid/unsupported format specifier.\n", str.c_str());
264 break;
265 }
266
267 switch (cformat)
268 {
269 case 's':
270 case 'S':
271 sout += node_arg->bitsAsConst().decode_string();
272 break;
273
274 case 'd':
275 case 'D':
276 {
277 char tmp[128];
278 snprintf(tmp, sizeof(tmp), "%d", node_arg->bitsAsConst().as_int());
279 sout += tmp;
280 }
281 break;
282
283 case 'x':
284 case 'X':
285 {
286 char tmp[128];
287 snprintf(tmp, sizeof(tmp), "%x", node_arg->bitsAsConst().as_int());
288 sout += tmp;
289 }
290 break;
291
292 case 'm':
293 case 'M':
294 sout += log_id(current_module->name);
295 break;
296
297 default:
298 log_abort();
299 }
300 }
301
302 // not a format specifier
303 else
304 sout += sformat[i];
305 }
306
307 // Finally, print the message (only include a \n for $display, not for $write)
308 log("%s", sout.c_str());
309 if (str == "$display")
310 log("\n");
311 delete_children();
312 str = std::string();
313 }
314
315 // activate const folding if this is anything that must be evaluated statically (ranges, parameters, attributes, etc.)
316 if (type == AST_WIRE || type == AST_PARAMETER || type == AST_LOCALPARAM || type == AST_DEFPARAM || type == AST_PARASET || type == AST_RANGE || type == AST_PREFIX)
317 const_fold = true;
318 if (type == AST_IDENTIFIER && current_scope.count(str) > 0 && (current_scope[str]->type == AST_PARAMETER || current_scope[str]->type == AST_LOCALPARAM))
319 const_fold = true;
320
321 // in certain cases a function must be evaluated constant. this is what in_param controls.
322 if (type == AST_PARAMETER || type == AST_LOCALPARAM || type == AST_DEFPARAM || type == AST_PARASET || type == AST_PREFIX)
323 in_param = true;
324
325 std::map<std::string, AstNode*> backup_scope;
326
327 // create name resolution entries for all objects with names
328 // also merge multiple declarations for the same wire (e.g. "output foobar; reg foobar;")
329 if (type == AST_MODULE) {
330 current_scope.clear();
331 std::map<std::string, AstNode*> this_wire_scope;
332 for (size_t i = 0; i < children.size(); i++) {
333 AstNode *node = children[i];
334 if (node->type == AST_WIRE) {
335 if (node->children.size() == 1 && node->children[0]->type == AST_RANGE) {
336 for (auto c : node->children[0]->children) {
337 if (!c->is_simple_const_expr()) {
338 if (attributes.count("\\dynports"))
339 delete attributes.at("\\dynports");
340 attributes["\\dynports"] = AstNode::mkconst_int(1, true);
341 }
342 }
343 }
344 if (this_wire_scope.count(node->str) > 0) {
345 AstNode *first_node = this_wire_scope[node->str];
346 if (first_node->is_input && node->is_reg)
347 goto wires_are_incompatible;
348 if (!node->is_input && !node->is_output && node->is_reg && node->children.size() == 0)
349 goto wires_are_compatible;
350 if (first_node->children.size() == 0 && node->children.size() == 1 && node->children[0]->type == AST_RANGE) {
351 AstNode *r = node->children[0];
352 if (r->range_valid && r->range_left == 0 && r->range_right == 0) {
353 delete r;
354 node->children.pop_back();
355 }
356 }
357 if (first_node->children.size() != node->children.size())
358 goto wires_are_incompatible;
359 for (size_t j = 0; j < node->children.size(); j++) {
360 AstNode *n1 = first_node->children[j], *n2 = node->children[j];
361 if (n1->type == AST_RANGE && n2->type == AST_RANGE && n1->range_valid && n2->range_valid) {
362 if (n1->range_left != n2->range_left)
363 goto wires_are_incompatible;
364 if (n1->range_right != n2->range_right)
365 goto wires_are_incompatible;
366 } else if (*n1 != *n2)
367 goto wires_are_incompatible;
368 }
369 if (first_node->range_left != node->range_left)
370 goto wires_are_incompatible;
371 if (first_node->range_right != node->range_right)
372 goto wires_are_incompatible;
373 if (first_node->port_id == 0 && (node->is_input || node->is_output))
374 goto wires_are_incompatible;
375 wires_are_compatible:
376 if (node->is_input)
377 first_node->is_input = true;
378 if (node->is_output)
379 first_node->is_output = true;
380 if (node->is_reg)
381 first_node->is_reg = true;
382 if (node->is_logic)
383 first_node->is_logic = true;
384 if (node->is_signed)
385 first_node->is_signed = true;
386 for (auto &it : node->attributes) {
387 if (first_node->attributes.count(it.first) > 0)
388 delete first_node->attributes[it.first];
389 first_node->attributes[it.first] = it.second->clone();
390 }
391 children.erase(children.begin()+(i--));
392 did_something = true;
393 delete node;
394 continue;
395 wires_are_incompatible:
396 if (stage > 1)
397 log_file_error(filename, linenum, "Incompatible re-declaration of wire %s.\n", node->str.c_str());
398 continue;
399 }
400 this_wire_scope[node->str] = node;
401 }
402 if (node->type == AST_PARAMETER || node->type == AST_LOCALPARAM || node->type == AST_WIRE || node->type == AST_AUTOWIRE || node->type == AST_GENVAR ||
403 node->type == AST_MEMORY || node->type == AST_FUNCTION || node->type == AST_TASK || node->type == AST_DPI_FUNCTION || node->type == AST_CELL) {
404 backup_scope[node->str] = current_scope[node->str];
405 current_scope[node->str] = node;
406 }
407 }
408 for (size_t i = 0; i < children.size(); i++) {
409 AstNode *node = children[i];
410 if (node->type == AST_PARAMETER || node->type == AST_LOCALPARAM || node->type == AST_WIRE || node->type == AST_AUTOWIRE || node->type == AST_MEMORY)
411 while (node->simplify(true, false, false, 1, -1, false, node->type == AST_PARAMETER || node->type == AST_LOCALPARAM))
412 did_something = true;
413 }
414 }
415
416 auto backup_current_block = current_block;
417 auto backup_current_block_child = current_block_child;
418 auto backup_current_top_block = current_top_block;
419 auto backup_current_always = current_always;
420 auto backup_current_always_clocked = current_always_clocked;
421
422 if (type == AST_ALWAYS || type == AST_INITIAL)
423 {
424 if (current_always != nullptr)
425 log_file_error(filename, linenum, "Invalid nesting of always blocks and/or initializations.\n");
426
427 current_always = this;
428 current_always_clocked = false;
429
430 if (type == AST_ALWAYS)
431 for (auto child : children) {
432 if (child->type == AST_POSEDGE || child->type == AST_NEGEDGE)
433 current_always_clocked = true;
434 if (child->type == AST_EDGE && GetSize(child->children) == 1 &&
435 child->children[0]->type == AST_IDENTIFIER && child->children[0]->str == "\\$global_clock")
436 current_always_clocked = true;
437 }
438 }
439
440 int backup_width_hint = width_hint;
441 bool backup_sign_hint = sign_hint;
442
443 bool detect_width_simple = false;
444 bool child_0_is_self_determined = false;
445 bool child_1_is_self_determined = false;
446 bool child_2_is_self_determined = false;
447 bool children_are_self_determined = false;
448 bool reset_width_after_children = false;
449
450 switch (type)
451 {
452 case AST_ASSIGN_EQ:
453 case AST_ASSIGN_LE:
454 case AST_ASSIGN:
455 while (!children[0]->basic_prep && children[0]->simplify(false, false, true, stage, -1, false, in_param) == true)
456 did_something = true;
457 while (!children[1]->basic_prep && children[1]->simplify(false, false, false, stage, -1, false, in_param) == true)
458 did_something = true;
459 children[0]->detectSignWidth(backup_width_hint, backup_sign_hint);
460 children[1]->detectSignWidth(width_hint, sign_hint);
461 width_hint = max(width_hint, backup_width_hint);
462 child_0_is_self_determined = true;
463 // test only once, before optimizations and memory mappings but after assignment LHS was mapped to an identifier
464 if (children[0]->id2ast && !children[0]->was_checked) {
465 if ((type == AST_ASSIGN_LE || type == AST_ASSIGN_EQ) && children[0]->id2ast->is_logic)
466 children[0]->id2ast->is_reg = true; // if logic type is used in a block asignment
467 if ((type == AST_ASSIGN_LE || type == AST_ASSIGN_EQ) && !children[0]->id2ast->is_reg)
468 log_warning("wire '%s' is assigned in a block at %s:%d.\n", children[0]->str.c_str(), filename.c_str(), linenum);
469 if (type == AST_ASSIGN && children[0]->id2ast->is_reg) {
470 bool is_rand_reg = false;
471 if (children[1]->type == AST_FCALL) {
472 if (children[1]->str == "\\$anyconst")
473 is_rand_reg = true;
474 if (children[1]->str == "\\$anyseq")
475 is_rand_reg = true;
476 if (children[1]->str == "\\$allconst")
477 is_rand_reg = true;
478 if (children[1]->str == "\\$allseq")
479 is_rand_reg = true;
480 }
481 if (!is_rand_reg)
482 log_warning("reg '%s' is assigned in a continuous assignment at %s:%d.\n", children[0]->str.c_str(), filename.c_str(), linenum);
483 }
484 children[0]->was_checked = true;
485 }
486 break;
487
488 case AST_PARAMETER:
489 case AST_LOCALPARAM:
490 while (!children[0]->basic_prep && children[0]->simplify(false, false, false, stage, -1, false, true) == true)
491 did_something = true;
492 children[0]->detectSignWidth(width_hint, sign_hint);
493 if (children.size() > 1 && children[1]->type == AST_RANGE) {
494 while (!children[1]->basic_prep && children[1]->simplify(false, false, false, stage, -1, false, true) == true)
495 did_something = true;
496 if (!children[1]->range_valid)
497 log_file_error(filename, linenum, "Non-constant width range on parameter decl.\n");
498 width_hint = max(width_hint, children[1]->range_left - children[1]->range_right + 1);
499 }
500 break;
501
502 case AST_TO_BITS:
503 case AST_TO_SIGNED:
504 case AST_TO_UNSIGNED:
505 case AST_CONCAT:
506 case AST_REPLICATE:
507 case AST_REDUCE_AND:
508 case AST_REDUCE_OR:
509 case AST_REDUCE_XOR:
510 case AST_REDUCE_XNOR:
511 case AST_REDUCE_BOOL:
512 detect_width_simple = true;
513 children_are_self_determined = true;
514 break;
515
516 case AST_NEG:
517 case AST_BIT_NOT:
518 case AST_POS:
519 case AST_BIT_AND:
520 case AST_BIT_OR:
521 case AST_BIT_XOR:
522 case AST_BIT_XNOR:
523 case AST_ADD:
524 case AST_SUB:
525 case AST_MUL:
526 case AST_DIV:
527 case AST_MOD:
528 detect_width_simple = true;
529 break;
530
531 case AST_SHIFT_LEFT:
532 case AST_SHIFT_RIGHT:
533 case AST_SHIFT_SLEFT:
534 case AST_SHIFT_SRIGHT:
535 case AST_POW:
536 detect_width_simple = true;
537 child_1_is_self_determined = true;
538 break;
539
540 case AST_LT:
541 case AST_LE:
542 case AST_EQ:
543 case AST_NE:
544 case AST_EQX:
545 case AST_NEX:
546 case AST_GE:
547 case AST_GT:
548 width_hint = -1;
549 sign_hint = true;
550 for (auto child : children) {
551 while (!child->basic_prep && child->simplify(false, false, in_lvalue, stage, -1, false, in_param) == true)
552 did_something = true;
553 child->detectSignWidthWorker(width_hint, sign_hint);
554 }
555 reset_width_after_children = true;
556 break;
557
558 case AST_LOGIC_AND:
559 case AST_LOGIC_OR:
560 case AST_LOGIC_NOT:
561 detect_width_simple = true;
562 children_are_self_determined = true;
563 break;
564
565 case AST_TERNARY:
566 detect_width_simple = true;
567 child_0_is_self_determined = true;
568 break;
569
570 case AST_MEMRD:
571 detect_width_simple = true;
572 children_are_self_determined = true;
573 break;
574
575 case AST_FCALL:
576 case AST_TCALL:
577 children_are_self_determined = true;
578 break;
579
580 default:
581 width_hint = -1;
582 sign_hint = false;
583 }
584
585 if (detect_width_simple && width_hint < 0) {
586 if (type == AST_REPLICATE)
587 while (children[0]->simplify(true, false, in_lvalue, stage, -1, false, true) == true)
588 did_something = true;
589 for (auto child : children)
590 while (!child->basic_prep && child->simplify(false, false, in_lvalue, stage, -1, false, in_param) == true)
591 did_something = true;
592 detectSignWidth(width_hint, sign_hint);
593 }
594
595 if (type == AST_FCALL && str == "\\$past")
596 detectSignWidth(width_hint, sign_hint);
597
598 if (type == AST_TERNARY) {
599 int width_hint_left, width_hint_right;
600 bool sign_hint_left, sign_hint_right;
601 bool found_real_left, found_real_right;
602 children[1]->detectSignWidth(width_hint_left, sign_hint_left, &found_real_left);
603 children[2]->detectSignWidth(width_hint_right, sign_hint_right, &found_real_right);
604 if (found_real_left || found_real_right) {
605 child_1_is_self_determined = true;
606 child_2_is_self_determined = true;
607 }
608 }
609
610 if (type == AST_CONDX && children.size() > 0 && children.at(0)->type == AST_CONSTANT) {
611 for (auto &bit : children.at(0)->bits)
612 if (bit == State::Sz || bit == State::Sx)
613 bit = State::Sa;
614 }
615
616 if (type == AST_CONDZ && children.size() > 0 && children.at(0)->type == AST_CONSTANT) {
617 for (auto &bit : children.at(0)->bits)
618 if (bit == State::Sz)
619 bit = State::Sa;
620 }
621
622 if (const_fold && type == AST_CASE)
623 {
624 while (children[0]->simplify(const_fold, at_zero, in_lvalue, stage, width_hint, sign_hint, in_param)) { }
625 if (children[0]->type == AST_CONSTANT && children[0]->bits_only_01()) {
626 std::vector<AstNode*> new_children;
627 new_children.push_back(children[0]);
628 for (int i = 1; i < GetSize(children); i++) {
629 AstNode *child = children[i];
630 log_assert(child->type == AST_COND || child->type == AST_CONDX || child->type == AST_CONDZ);
631 for (auto v : child->children) {
632 if (v->type == AST_DEFAULT)
633 goto keep_const_cond;
634 if (v->type == AST_BLOCK)
635 continue;
636 while (v->simplify(const_fold, at_zero, in_lvalue, stage, width_hint, sign_hint, in_param)) { }
637 if (v->type == AST_CONSTANT && v->bits_only_01()) {
638 if (v->bits == children[0]->bits) {
639 while (i+1 < GetSize(children))
640 delete children[++i];
641 goto keep_const_cond;
642 }
643 continue;
644 }
645 goto keep_const_cond;
646 }
647 if (0)
648 keep_const_cond:
649 new_children.push_back(child);
650 else
651 delete child;
652 }
653 new_children.swap(children);
654 }
655 }
656
657 // simplify all children first
658 // (iterate by index as e.g. auto wires can add new children in the process)
659 for (size_t i = 0; i < children.size(); i++) {
660 bool did_something_here = true;
661 bool backup_flag_autowire = flag_autowire;
662 if ((type == AST_GENFOR || type == AST_FOR) && i >= 3)
663 break;
664 if ((type == AST_GENIF || type == AST_GENCASE) && i >= 1)
665 break;
666 if (type == AST_GENBLOCK)
667 break;
668 if (type == AST_BLOCK && !str.empty())
669 break;
670 if (type == AST_PREFIX && i >= 1)
671 break;
672 if (type == AST_DEFPARAM && i == 0)
673 flag_autowire = true;
674 while (did_something_here && i < children.size()) {
675 bool const_fold_here = const_fold, in_lvalue_here = in_lvalue;
676 int width_hint_here = width_hint;
677 bool sign_hint_here = sign_hint;
678 bool in_param_here = in_param;
679 if (i == 0 && (type == AST_REPLICATE || type == AST_WIRE))
680 const_fold_here = true, in_param_here = true;
681 if (type == AST_PARAMETER || type == AST_LOCALPARAM)
682 const_fold_here = true;
683 if (i == 0 && (type == AST_ASSIGN || type == AST_ASSIGN_EQ || type == AST_ASSIGN_LE))
684 in_lvalue_here = true;
685 if (type == AST_BLOCK) {
686 current_block = this;
687 current_block_child = children[i];
688 }
689 if ((type == AST_ALWAYS || type == AST_INITIAL) && children[i]->type == AST_BLOCK)
690 current_top_block = children[i];
691 if (i == 0 && child_0_is_self_determined)
692 width_hint_here = -1, sign_hint_here = false;
693 if (i == 1 && child_1_is_self_determined)
694 width_hint_here = -1, sign_hint_here = false;
695 if (i == 2 && child_2_is_self_determined)
696 width_hint_here = -1, sign_hint_here = false;
697 if (children_are_self_determined)
698 width_hint_here = -1, sign_hint_here = false;
699 did_something_here = children[i]->simplify(const_fold_here, at_zero, in_lvalue_here, stage, width_hint_here, sign_hint_here, in_param_here);
700 if (did_something_here)
701 did_something = true;
702 }
703 if (stage == 2 && children[i]->type == AST_INITIAL && current_ast_mod != this) {
704 current_ast_mod->children.push_back(children[i]);
705 children.erase(children.begin() + (i--));
706 did_something = true;
707 }
708 flag_autowire = backup_flag_autowire;
709 }
710 for (auto &attr : attributes) {
711 while (attr.second->simplify(true, false, false, stage, -1, false, true))
712 did_something = true;
713 }
714
715 if (reset_width_after_children) {
716 width_hint = backup_width_hint;
717 sign_hint = backup_sign_hint;
718 if (width_hint < 0)
719 detectSignWidth(width_hint, sign_hint);
720 }
721
722 current_block = backup_current_block;
723 current_block_child = backup_current_block_child;
724 current_top_block = backup_current_top_block;
725 current_always = backup_current_always;
726 current_always_clocked = backup_current_always_clocked;
727
728 for (auto it = backup_scope.begin(); it != backup_scope.end(); it++) {
729 if (it->second == NULL)
730 current_scope.erase(it->first);
731 else
732 current_scope[it->first] = it->second;
733 }
734
735 current_filename = filename;
736 set_line_num(linenum);
737
738 if (type == AST_MODULE)
739 current_scope.clear();
740
741 // convert defparam nodes to cell parameters
742 if (type == AST_DEFPARAM && !children.empty())
743 {
744 if (children[0]->type != AST_IDENTIFIER)
745 log_file_error(filename, linenum, "Module name in defparam contains non-constant expressions!\n");
746
747 string modname, paramname = children[0]->str;
748
749 size_t pos = paramname.rfind('.');
750
751 while (pos != 0 && pos != std::string::npos)
752 {
753 modname = paramname.substr(0, pos);
754
755 if (current_scope.count(modname))
756 break;
757
758 pos = paramname.rfind('.', pos - 1);
759 }
760
761 if (pos == std::string::npos)
762 log_file_error(filename, linenum, "Can't find object for defparam `%s`!\n", RTLIL::unescape_id(paramname).c_str());
763
764 paramname = "\\" + paramname.substr(pos+1);
765
766 if (current_scope.at(modname)->type != AST_CELL)
767 log_file_error(filename, linenum, "Defparam argument `%s . %s` does not match a cell!\n",
768 RTLIL::unescape_id(modname).c_str(), RTLIL::unescape_id(paramname).c_str());
769
770 AstNode *paraset = new AstNode(AST_PARASET, children[1]->clone(), GetSize(children) > 2 ? children[2]->clone() : NULL);
771 paraset->str = paramname;
772
773 AstNode *cell = current_scope.at(modname);
774 cell->children.insert(cell->children.begin() + 1, paraset);
775 delete_children();
776 }
777
778 // resolve constant prefixes
779 if (type == AST_PREFIX) {
780 if (children[0]->type != AST_CONSTANT) {
781 // dumpAst(NULL, "> ");
782 log_file_error(filename, linenum, "Index in generate block prefix syntax is not constant!\n");
783 }
784 if (children[1]->type == AST_PREFIX)
785 children[1]->simplify(const_fold, at_zero, in_lvalue, stage, width_hint, sign_hint, in_param);
786 log_assert(children[1]->type == AST_IDENTIFIER);
787 newNode = children[1]->clone();
788 const char *second_part = children[1]->str.c_str();
789 if (second_part[0] == '\\')
790 second_part++;
791 newNode->str = stringf("%s[%d].%s", str.c_str(), children[0]->integer, second_part);
792 goto apply_newNode;
793 }
794
795 // evaluate TO_BITS nodes
796 if (type == AST_TO_BITS) {
797 if (children[0]->type != AST_CONSTANT)
798 log_file_error(filename, linenum, "Left operand of to_bits expression is not constant!\n");
799 if (children[1]->type != AST_CONSTANT)
800 log_file_error(filename, linenum, "Right operand of to_bits expression is not constant!\n");
801 RTLIL::Const new_value = children[1]->bitsAsConst(children[0]->bitsAsConst().as_int(), children[1]->is_signed);
802 newNode = mkconst_bits(new_value.bits, children[1]->is_signed);
803 goto apply_newNode;
804 }
805
806 // annotate constant ranges
807 if (type == AST_RANGE) {
808 bool old_range_valid = range_valid;
809 range_valid = false;
810 range_swapped = false;
811 range_left = -1;
812 range_right = 0;
813 log_assert(children.size() >= 1);
814 if (children[0]->type == AST_CONSTANT) {
815 range_valid = true;
816 range_left = children[0]->integer;
817 if (children.size() == 1)
818 range_right = range_left;
819 }
820 if (children.size() >= 2) {
821 if (children[1]->type == AST_CONSTANT)
822 range_right = children[1]->integer;
823 else
824 range_valid = false;
825 }
826 if (old_range_valid != range_valid)
827 did_something = true;
828 if (range_valid && range_left >= 0 && range_right > range_left) {
829 int tmp = range_right;
830 range_right = range_left;
831 range_left = tmp;
832 range_swapped = true;
833 }
834 }
835
836 // annotate wires with their ranges
837 if (type == AST_WIRE) {
838 if (children.size() > 0) {
839 if (children[0]->range_valid) {
840 if (!range_valid)
841 did_something = true;
842 range_valid = true;
843 range_swapped = children[0]->range_swapped;
844 range_left = children[0]->range_left;
845 range_right = children[0]->range_right;
846 }
847 } else {
848 if (!range_valid)
849 did_something = true;
850 range_valid = true;
851 range_swapped = false;
852 range_left = 0;
853 range_right = 0;
854 }
855 }
856
857 // resolve multiranges on memory decl
858 if (type == AST_MEMORY && children.size() > 1 && children[1]->type == AST_MULTIRANGE)
859 {
860 int total_size = 1;
861 multirange_dimensions.clear();
862 for (auto range : children[1]->children) {
863 if (!range->range_valid)
864 log_file_error(filename, linenum, "Non-constant range on memory decl.\n");
865 multirange_dimensions.push_back(min(range->range_left, range->range_right));
866 multirange_dimensions.push_back(max(range->range_left, range->range_right) - min(range->range_left, range->range_right) + 1);
867 total_size *= multirange_dimensions.back();
868 }
869 delete children[1];
870 children[1] = new AstNode(AST_RANGE, AstNode::mkconst_int(0, true), AstNode::mkconst_int(total_size-1, true));
871 did_something = true;
872 }
873
874 // resolve multiranges on memory access
875 if (type == AST_IDENTIFIER && id2ast && id2ast->type == AST_MEMORY && children.size() > 0 && children[0]->type == AST_MULTIRANGE)
876 {
877 AstNode *index_expr = nullptr;
878
879 for (int i = 0; 2*i < GetSize(id2ast->multirange_dimensions); i++)
880 {
881 if (GetSize(children[0]->children) < i)
882 log_file_error(filename, linenum, "Insufficient number of array indices for %s.\n", log_id(str));
883
884 AstNode *new_index_expr = children[0]->children[i]->children.at(0)->clone();
885
886 if (id2ast->multirange_dimensions[2*i])
887 new_index_expr = new AstNode(AST_SUB, new_index_expr, AstNode::mkconst_int(id2ast->multirange_dimensions[2*i], true));
888
889 if (i == 0)
890 index_expr = new_index_expr;
891 else
892 index_expr = new AstNode(AST_ADD, new AstNode(AST_MUL, index_expr, AstNode::mkconst_int(id2ast->multirange_dimensions[2*i+1], true)), new_index_expr);
893 }
894
895 for (int i = GetSize(id2ast->multirange_dimensions)/2; i < GetSize(children[0]->children); i++)
896 children.push_back(children[0]->children[i]->clone());
897
898 delete children[0];
899 if (index_expr == nullptr)
900 children.erase(children.begin());
901 else
902 children[0] = new AstNode(AST_RANGE, index_expr);
903
904 did_something = true;
905 }
906
907 // trim/extend parameters
908 if (type == AST_PARAMETER || type == AST_LOCALPARAM) {
909 if (children.size() > 1 && children[1]->type == AST_RANGE) {
910 if (!children[1]->range_valid)
911 log_file_error(filename, linenum, "Non-constant width range on parameter decl.\n");
912 int width = std::abs(children[1]->range_left - children[1]->range_right) + 1;
913 if (children[0]->type == AST_REALVALUE) {
914 RTLIL::Const constvalue = children[0]->realAsConst(width);
915 log_file_warning(filename, linenum, "converting real value %e to binary %s.\n",
916 children[0]->realvalue, log_signal(constvalue));
917 delete children[0];
918 children[0] = mkconst_bits(constvalue.bits, sign_hint);
919 did_something = true;
920 }
921 if (children[0]->type == AST_CONSTANT) {
922 if (width != int(children[0]->bits.size())) {
923 RTLIL::SigSpec sig(children[0]->bits);
924 sig.extend_u0(width, children[0]->is_signed);
925 AstNode *old_child_0 = children[0];
926 children[0] = mkconst_bits(sig.as_const().bits, is_signed);
927 delete old_child_0;
928 }
929 children[0]->is_signed = is_signed;
930 }
931 range_valid = true;
932 range_swapped = children[1]->range_swapped;
933 range_left = children[1]->range_left;
934 range_right = children[1]->range_right;
935 } else
936 if (children.size() > 1 && children[1]->type == AST_REALVALUE && children[0]->type == AST_CONSTANT) {
937 double as_realvalue = children[0]->asReal(sign_hint);
938 delete children[0];
939 children[0] = new AstNode(AST_REALVALUE);
940 children[0]->realvalue = as_realvalue;
941 did_something = true;
942 }
943 }
944
945 // annotate identifiers using scope resolution and create auto-wires as needed
946 if (type == AST_IDENTIFIER) {
947 if (current_scope.count(str) == 0) {
948 for (auto node : current_ast_mod->children) {
949 if ((node->type == AST_PARAMETER || node->type == AST_LOCALPARAM || node->type == AST_WIRE || node->type == AST_AUTOWIRE || node->type == AST_GENVAR ||
950 node->type == AST_MEMORY || node->type == AST_FUNCTION || node->type == AST_TASK || node->type == AST_DPI_FUNCTION) && str == node->str) {
951 current_scope[node->str] = node;
952 break;
953 }
954 }
955 }
956 if (current_scope.count(str) == 0) {
957 if (flag_autowire || str == "\\$global_clock") {
958 AstNode *auto_wire = new AstNode(AST_AUTOWIRE);
959 auto_wire->str = str;
960 current_ast_mod->children.push_back(auto_wire);
961 current_scope[str] = auto_wire;
962 did_something = true;
963 } else {
964 log_file_error(filename, linenum, "Identifier `%s' is implicitly declared and `default_nettype is set to none.\n", str.c_str());
965 }
966 }
967 if (id2ast != current_scope[str]) {
968 id2ast = current_scope[str];
969 did_something = true;
970 }
971 }
972
973 // split memory access with bit select to individual statements
974 if (type == AST_IDENTIFIER && children.size() == 2 && children[0]->type == AST_RANGE && children[1]->type == AST_RANGE && !in_lvalue)
975 {
976 if (id2ast == NULL || id2ast->type != AST_MEMORY || children[0]->children.size() != 1)
977 log_file_error(filename, linenum, "Invalid bit-select on memory access!\n");
978
979 int mem_width, mem_size, addr_bits;
980 id2ast->meminfo(mem_width, mem_size, addr_bits);
981
982 int data_range_left = id2ast->children[0]->range_left;
983 int data_range_right = id2ast->children[0]->range_right;
984
985 if (id2ast->children[0]->range_swapped)
986 std::swap(data_range_left, data_range_right);
987
988 std::stringstream sstr;
989 sstr << "$mem2bits$" << str << "$" << filename << ":" << linenum << "$" << (autoidx++);
990 std::string wire_id = sstr.str();
991
992 AstNode *wire = new AstNode(AST_WIRE, new AstNode(AST_RANGE, mkconst_int(data_range_left, true), mkconst_int(data_range_right, true)));
993 wire->str = wire_id;
994 if (current_block)
995 wire->attributes["\\nosync"] = AstNode::mkconst_int(1, false);
996 current_ast_mod->children.push_back(wire);
997 while (wire->simplify(true, false, false, 1, -1, false, false)) { }
998
999 AstNode *data = clone();
1000 delete data->children[1];
1001 data->children.pop_back();
1002
1003 AstNode *assign = new AstNode(AST_ASSIGN_EQ, new AstNode(AST_IDENTIFIER), data);
1004 assign->children[0]->str = wire_id;
1005 assign->children[0]->was_checked = true;
1006
1007 if (current_block)
1008 {
1009 size_t assign_idx = 0;
1010 while (assign_idx < current_block->children.size() && current_block->children[assign_idx] != current_block_child)
1011 assign_idx++;
1012 log_assert(assign_idx < current_block->children.size());
1013 current_block->children.insert(current_block->children.begin()+assign_idx, assign);
1014 wire->is_reg = true;
1015 }
1016 else
1017 {
1018 AstNode *proc = new AstNode(AST_ALWAYS, new AstNode(AST_BLOCK));
1019 proc->children[0]->children.push_back(assign);
1020 current_ast_mod->children.push_back(proc);
1021 }
1022
1023 newNode = new AstNode(AST_IDENTIFIER, children[1]->clone());
1024 newNode->str = wire_id;
1025 newNode->id2ast = wire;
1026 goto apply_newNode;
1027 }
1028
1029 if (type == AST_WHILE)
1030 log_file_error(filename, linenum, "While loops are only allowed in constant functions!\n");
1031
1032 if (type == AST_REPEAT)
1033 {
1034 AstNode *count = children[0];
1035 AstNode *body = children[1];
1036
1037 // eval count expression
1038 while (count->simplify(true, false, false, stage, 32, true, false)) { }
1039
1040 if (count->type != AST_CONSTANT)
1041 log_file_error(filename, linenum, "Repeat loops outside must have constant repeat counts!\n");
1042
1043 // convert to a block with the body repeated n times
1044 type = AST_BLOCK;
1045 children.clear();
1046 for (int i = 0; i < count->bitsAsConst().as_int(); i++)
1047 children.insert(children.begin(), body->clone());
1048
1049 delete count;
1050 delete body;
1051 did_something = true;
1052 }
1053
1054 // unroll for loops and generate-for blocks
1055 if ((type == AST_GENFOR || type == AST_FOR) && children.size() != 0)
1056 {
1057 AstNode *init_ast = children[0];
1058 AstNode *while_ast = children[1];
1059 AstNode *next_ast = children[2];
1060 AstNode *body_ast = children[3];
1061
1062 while (body_ast->type == AST_GENBLOCK && body_ast->str.empty() &&
1063 body_ast->children.size() == 1 && body_ast->children.at(0)->type == AST_GENBLOCK)
1064 body_ast = body_ast->children.at(0);
1065
1066 if (init_ast->type != AST_ASSIGN_EQ)
1067 log_file_error(filename, linenum, "Unsupported 1st expression of generate for-loop!\n");
1068 if (next_ast->type != AST_ASSIGN_EQ)
1069 log_file_error(filename, linenum, "Unsupported 3rd expression of generate for-loop!\n");
1070
1071 if (type == AST_GENFOR) {
1072 if (init_ast->children[0]->id2ast == NULL || init_ast->children[0]->id2ast->type != AST_GENVAR)
1073 log_file_error(filename, linenum, "Left hand side of 1st expression of generate for-loop is not a gen var!\n");
1074 if (next_ast->children[0]->id2ast == NULL || next_ast->children[0]->id2ast->type != AST_GENVAR)
1075 log_file_error(filename, linenum, "Left hand side of 3rd expression of generate for-loop is not a gen var!\n");
1076 } else {
1077 if (init_ast->children[0]->id2ast == NULL || init_ast->children[0]->id2ast->type != AST_WIRE)
1078 log_file_error(filename, linenum, "Left hand side of 1st expression of generate for-loop is not a register!\n");
1079 if (next_ast->children[0]->id2ast == NULL || next_ast->children[0]->id2ast->type != AST_WIRE)
1080 log_file_error(filename, linenum, "Left hand side of 3rd expression of generate for-loop is not a register!\n");
1081 }
1082
1083 if (init_ast->children[0]->id2ast != next_ast->children[0]->id2ast)
1084 log_file_error(filename, linenum, "Incompatible left-hand sides in 1st and 3rd expression of generate for-loop!\n");
1085
1086 // eval 1st expression
1087 AstNode *varbuf = init_ast->children[1]->clone();
1088 {
1089 int expr_width_hint = -1;
1090 bool expr_sign_hint = true;
1091 varbuf->detectSignWidth(expr_width_hint, expr_sign_hint);
1092 while (varbuf->simplify(true, false, false, stage, 32, true, false)) { }
1093 }
1094
1095 if (varbuf->type != AST_CONSTANT)
1096 log_file_error(filename, linenum, "Right hand side of 1st expression of generate for-loop is not constant!\n");
1097
1098 varbuf = new AstNode(AST_LOCALPARAM, varbuf);
1099 varbuf->str = init_ast->children[0]->str;
1100
1101 AstNode *backup_scope_varbuf = current_scope[varbuf->str];
1102 current_scope[varbuf->str] = varbuf;
1103
1104 size_t current_block_idx = 0;
1105 if (type == AST_FOR) {
1106 while (current_block_idx < current_block->children.size() &&
1107 current_block->children[current_block_idx] != current_block_child)
1108 current_block_idx++;
1109 }
1110
1111 while (1)
1112 {
1113 // eval 2nd expression
1114 AstNode *buf = while_ast->clone();
1115 {
1116 int expr_width_hint = -1;
1117 bool expr_sign_hint = true;
1118 buf->detectSignWidth(expr_width_hint, expr_sign_hint);
1119 while (buf->simplify(true, false, false, stage, expr_width_hint, expr_sign_hint, false)) { }
1120 }
1121
1122 if (buf->type != AST_CONSTANT)
1123 log_file_error(filename, linenum, "2nd expression of generate for-loop is not constant!\n");
1124
1125 if (buf->integer == 0) {
1126 delete buf;
1127 break;
1128 }
1129 delete buf;
1130
1131 // expand body
1132 int index = varbuf->children[0]->integer;
1133 if (body_ast->type == AST_GENBLOCK)
1134 buf = body_ast->clone();
1135 else
1136 buf = new AstNode(AST_GENBLOCK, body_ast->clone());
1137 if (buf->str.empty()) {
1138 std::stringstream sstr;
1139 sstr << "$genblock$" << filename << ":" << linenum << "$" << (autoidx++);
1140 buf->str = sstr.str();
1141 }
1142 std::map<std::string, std::string> name_map;
1143 std::stringstream sstr;
1144 sstr << buf->str << "[" << index << "].";
1145 buf->expand_genblock(varbuf->str, sstr.str(), name_map);
1146
1147 if (type == AST_GENFOR) {
1148 for (size_t i = 0; i < buf->children.size(); i++) {
1149 buf->children[i]->simplify(false, false, false, stage, -1, false, false);
1150 current_ast_mod->children.push_back(buf->children[i]);
1151 }
1152 } else {
1153 for (size_t i = 0; i < buf->children.size(); i++)
1154 current_block->children.insert(current_block->children.begin() + current_block_idx++, buf->children[i]);
1155 }
1156 buf->children.clear();
1157 delete buf;
1158
1159 // eval 3rd expression
1160 buf = next_ast->children[1]->clone();
1161 {
1162 int expr_width_hint = -1;
1163 bool expr_sign_hint = true;
1164 buf->detectSignWidth(expr_width_hint, expr_sign_hint);
1165 while (buf->simplify(true, false, false, stage, expr_width_hint, expr_sign_hint, true)) { }
1166 }
1167
1168 if (buf->type != AST_CONSTANT)
1169 log_file_error(filename, linenum, "Right hand side of 3rd expression of generate for-loop is not constant!\n");
1170
1171 delete varbuf->children[0];
1172 varbuf->children[0] = buf;
1173 }
1174
1175 if (type == AST_FOR) {
1176 AstNode *buf = next_ast->clone();
1177 delete buf->children[1];
1178 buf->children[1] = varbuf->children[0]->clone();
1179 current_block->children.insert(current_block->children.begin() + current_block_idx++, buf);
1180 }
1181
1182 current_scope[varbuf->str] = backup_scope_varbuf;
1183 delete varbuf;
1184 delete_children();
1185 did_something = true;
1186 }
1187
1188 // check for local objects in unnamed block
1189 if (type == AST_BLOCK && str.empty())
1190 {
1191 for (size_t i = 0; i < children.size(); i++)
1192 if (children[i]->type == AST_WIRE || children[i]->type == AST_MEMORY || children[i]->type == AST_PARAMETER || children[i]->type == AST_LOCALPARAM)
1193 log_file_error(children[i]->filename, children[i]->linenum, "Local declaration in unnamed block is an unsupported SystemVerilog feature!\n");
1194 }
1195
1196 // transform block with name
1197 if (type == AST_BLOCK && !str.empty())
1198 {
1199 std::map<std::string, std::string> name_map;
1200 expand_genblock(std::string(), str + ".", name_map);
1201
1202 std::vector<AstNode*> new_children;
1203 for (size_t i = 0; i < children.size(); i++)
1204 if (children[i]->type == AST_WIRE || children[i]->type == AST_MEMORY || children[i]->type == AST_PARAMETER || children[i]->type == AST_LOCALPARAM) {
1205 children[i]->simplify(false, false, false, stage, -1, false, false);
1206 current_ast_mod->children.push_back(children[i]);
1207 current_scope[children[i]->str] = children[i];
1208 } else
1209 new_children.push_back(children[i]);
1210
1211 children.swap(new_children);
1212 did_something = true;
1213 str.clear();
1214 }
1215
1216 // simplify unconditional generate block
1217 if (type == AST_GENBLOCK && children.size() != 0)
1218 {
1219 if (!str.empty()) {
1220 std::map<std::string, std::string> name_map;
1221 expand_genblock(std::string(), str + ".", name_map);
1222 }
1223
1224 for (size_t i = 0; i < children.size(); i++) {
1225 children[i]->simplify(false, false, false, stage, -1, false, false);
1226 current_ast_mod->children.push_back(children[i]);
1227 }
1228
1229 children.clear();
1230 did_something = true;
1231 }
1232
1233 // simplify generate-if blocks
1234 if (type == AST_GENIF && children.size() != 0)
1235 {
1236 AstNode *buf = children[0]->clone();
1237 while (buf->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
1238 if (buf->type != AST_CONSTANT) {
1239 // for (auto f : log_files)
1240 // dumpAst(f, "verilog-ast> ");
1241 log_file_error(filename, linenum, "Condition for generate if is not constant!\n");
1242 }
1243 if (buf->asBool() != 0) {
1244 delete buf;
1245 buf = children[1]->clone();
1246 } else {
1247 delete buf;
1248 buf = children.size() > 2 ? children[2]->clone() : NULL;
1249 }
1250
1251 if (buf)
1252 {
1253 if (buf->type != AST_GENBLOCK)
1254 buf = new AstNode(AST_GENBLOCK, buf);
1255
1256 if (!buf->str.empty()) {
1257 std::map<std::string, std::string> name_map;
1258 buf->expand_genblock(std::string(), buf->str + ".", name_map);
1259 }
1260
1261 for (size_t i = 0; i < buf->children.size(); i++) {
1262 buf->children[i]->simplify(false, false, false, stage, -1, false, false);
1263 current_ast_mod->children.push_back(buf->children[i]);
1264 }
1265
1266 buf->children.clear();
1267 delete buf;
1268 }
1269
1270 delete_children();
1271 did_something = true;
1272 }
1273
1274 // simplify generate-case blocks
1275 if (type == AST_GENCASE && children.size() != 0)
1276 {
1277 AstNode *buf = children[0]->clone();
1278 while (buf->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
1279 if (buf->type != AST_CONSTANT) {
1280 // for (auto f : log_files)
1281 // dumpAst(f, "verilog-ast> ");
1282 log_file_error(filename, linenum, "Condition for generate case is not constant!\n");
1283 }
1284
1285 bool ref_signed = buf->is_signed;
1286 RTLIL::Const ref_value = buf->bitsAsConst();
1287 delete buf;
1288
1289 AstNode *selected_case = NULL;
1290 for (size_t i = 1; i < children.size(); i++)
1291 {
1292 log_assert(children.at(i)->type == AST_COND || children.at(i)->type == AST_CONDX || children.at(i)->type == AST_CONDZ);
1293
1294 AstNode *this_genblock = NULL;
1295 for (auto child : children.at(i)->children) {
1296 log_assert(this_genblock == NULL);
1297 if (child->type == AST_GENBLOCK)
1298 this_genblock = child;
1299 }
1300
1301 for (auto child : children.at(i)->children)
1302 {
1303 if (child->type == AST_DEFAULT) {
1304 if (selected_case == NULL)
1305 selected_case = this_genblock;
1306 continue;
1307 }
1308 if (child->type == AST_GENBLOCK)
1309 continue;
1310
1311 buf = child->clone();
1312 while (buf->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
1313 if (buf->type != AST_CONSTANT) {
1314 // for (auto f : log_files)
1315 // dumpAst(f, "verilog-ast> ");
1316 log_file_error(filename, linenum, "Expression in generate case is not constant!\n");
1317 }
1318
1319 bool is_selected = RTLIL::const_eq(ref_value, buf->bitsAsConst(), ref_signed && buf->is_signed, ref_signed && buf->is_signed, 1).as_bool();
1320 delete buf;
1321
1322 if (is_selected) {
1323 selected_case = this_genblock;
1324 i = children.size();
1325 break;
1326 }
1327 }
1328 }
1329
1330 if (selected_case != NULL)
1331 {
1332 log_assert(selected_case->type == AST_GENBLOCK);
1333 buf = selected_case->clone();
1334
1335 if (!buf->str.empty()) {
1336 std::map<std::string, std::string> name_map;
1337 buf->expand_genblock(std::string(), buf->str + ".", name_map);
1338 }
1339
1340 for (size_t i = 0; i < buf->children.size(); i++) {
1341 buf->children[i]->simplify(false, false, false, stage, -1, false, false);
1342 current_ast_mod->children.push_back(buf->children[i]);
1343 }
1344
1345 buf->children.clear();
1346 delete buf;
1347 }
1348
1349 delete_children();
1350 did_something = true;
1351 }
1352
1353 // unroll cell arrays
1354 if (type == AST_CELLARRAY)
1355 {
1356 if (!children.at(0)->range_valid)
1357 log_file_error(filename, linenum, "Non-constant array range on cell array.\n");
1358
1359 newNode = new AstNode(AST_GENBLOCK);
1360 int num = max(children.at(0)->range_left, children.at(0)->range_right) - min(children.at(0)->range_left, children.at(0)->range_right) + 1;
1361
1362 for (int i = 0; i < num; i++) {
1363 int idx = children.at(0)->range_left > children.at(0)->range_right ? children.at(0)->range_right + i : children.at(0)->range_right - i;
1364 AstNode *new_cell = children.at(1)->clone();
1365 newNode->children.push_back(new_cell);
1366 new_cell->str += stringf("[%d]", idx);
1367 if (new_cell->type == AST_PRIMITIVE) {
1368 log_file_error(filename, linenum, "Cell arrays of primitives are currently not supported.\n");
1369 } else {
1370 log_assert(new_cell->children.at(0)->type == AST_CELLTYPE);
1371 new_cell->children.at(0)->str = stringf("$array:%d:%d:%s", i, num, new_cell->children.at(0)->str.c_str());
1372 }
1373 }
1374
1375 goto apply_newNode;
1376 }
1377
1378 // replace primitives with assignments
1379 if (type == AST_PRIMITIVE)
1380 {
1381 if (children.size() < 2)
1382 log_file_error(filename, linenum, "Insufficient number of arguments for primitive `%s'!\n", str.c_str());
1383
1384 std::vector<AstNode*> children_list;
1385 for (auto child : children) {
1386 log_assert(child->type == AST_ARGUMENT);
1387 log_assert(child->children.size() == 1);
1388 children_list.push_back(child->children[0]);
1389 child->children.clear();
1390 delete child;
1391 }
1392 children.clear();
1393
1394 if (str == "bufif0" || str == "bufif1" || str == "notif0" || str == "notif1")
1395 {
1396 if (children_list.size() != 3)
1397 log_file_error(filename, linenum, "Invalid number of arguments for primitive `%s'!\n", str.c_str());
1398
1399 std::vector<RTLIL::State> z_const(1, RTLIL::State::Sz);
1400
1401 AstNode *mux_input = children_list.at(1);
1402 if (str == "notif0" || str == "notif1") {
1403 mux_input = new AstNode(AST_BIT_NOT, mux_input);
1404 }
1405 AstNode *node = new AstNode(AST_TERNARY, children_list.at(2));
1406 if (str == "bufif0") {
1407 node->children.push_back(AstNode::mkconst_bits(z_const, false));
1408 node->children.push_back(mux_input);
1409 } else {
1410 node->children.push_back(mux_input);
1411 node->children.push_back(AstNode::mkconst_bits(z_const, false));
1412 }
1413
1414 str.clear();
1415 type = AST_ASSIGN;
1416 children.push_back(children_list.at(0));
1417 children.back()->was_checked = true;
1418 children.push_back(node);
1419 did_something = true;
1420 }
1421 else
1422 {
1423 AstNodeType op_type = AST_NONE;
1424 bool invert_results = false;
1425
1426 if (str == "and")
1427 op_type = AST_BIT_AND;
1428 if (str == "nand")
1429 op_type = AST_BIT_AND, invert_results = true;
1430 if (str == "or")
1431 op_type = AST_BIT_OR;
1432 if (str == "nor")
1433 op_type = AST_BIT_OR, invert_results = true;
1434 if (str == "xor")
1435 op_type = AST_BIT_XOR;
1436 if (str == "xnor")
1437 op_type = AST_BIT_XOR, invert_results = true;
1438 if (str == "buf")
1439 op_type = AST_POS;
1440 if (str == "not")
1441 op_type = AST_POS, invert_results = true;
1442 log_assert(op_type != AST_NONE);
1443
1444 AstNode *node = children_list[1];
1445 if (op_type != AST_POS)
1446 for (size_t i = 2; i < children_list.size(); i++)
1447 node = new AstNode(op_type, node, children_list[i]);
1448 if (invert_results)
1449 node = new AstNode(AST_BIT_NOT, node);
1450
1451 str.clear();
1452 type = AST_ASSIGN;
1453 children.push_back(children_list[0]);
1454 children.back()->was_checked = true;
1455 children.push_back(node);
1456 did_something = true;
1457 }
1458 }
1459
1460 // replace dynamic ranges in left-hand side expressions (e.g. "foo[bar] <= 1'b1;") with
1461 // a big case block that selects the correct single-bit assignment.
1462 if (type == AST_ASSIGN_EQ || type == AST_ASSIGN_LE) {
1463 if (children[0]->type != AST_IDENTIFIER || children[0]->children.size() == 0)
1464 goto skip_dynamic_range_lvalue_expansion;
1465 if (children[0]->children[0]->range_valid || did_something)
1466 goto skip_dynamic_range_lvalue_expansion;
1467 if (children[0]->id2ast == NULL || children[0]->id2ast->type != AST_WIRE)
1468 goto skip_dynamic_range_lvalue_expansion;
1469 if (!children[0]->id2ast->range_valid)
1470 goto skip_dynamic_range_lvalue_expansion;
1471 int source_width = children[0]->id2ast->range_left - children[0]->id2ast->range_right + 1;
1472 int result_width = 1;
1473 AstNode *shift_expr = NULL;
1474 AstNode *range = children[0]->children[0];
1475 if (range->children.size() == 1) {
1476 shift_expr = range->children[0]->clone();
1477 } else {
1478 shift_expr = range->children[1]->clone();
1479 AstNode *left_at_zero_ast = range->children[0]->clone();
1480 AstNode *right_at_zero_ast = range->children[1]->clone();
1481 while (left_at_zero_ast->simplify(true, true, false, stage, -1, false, false)) { }
1482 while (right_at_zero_ast->simplify(true, true, false, stage, -1, false, false)) { }
1483 if (left_at_zero_ast->type != AST_CONSTANT || right_at_zero_ast->type != AST_CONSTANT)
1484 log_file_error(filename, linenum, "Unsupported expression on dynamic range select on signal `%s'!\n", str.c_str());
1485 result_width = abs(int(left_at_zero_ast->integer - right_at_zero_ast->integer)) + 1;
1486 }
1487 did_something = true;
1488 newNode = new AstNode(AST_CASE, shift_expr);
1489 for (int i = 0; i <= source_width-result_width; i++) {
1490 int start_bit = children[0]->id2ast->range_right + i;
1491 AstNode *cond = new AstNode(AST_COND, mkconst_int(start_bit, true));
1492 AstNode *lvalue = children[0]->clone();
1493 lvalue->delete_children();
1494 lvalue->children.push_back(new AstNode(AST_RANGE,
1495 mkconst_int(start_bit+result_width-1, true), mkconst_int(start_bit, true)));
1496 cond->children.push_back(new AstNode(AST_BLOCK, new AstNode(type, lvalue, children[1]->clone())));
1497 newNode->children.push_back(cond);
1498 }
1499 goto apply_newNode;
1500 }
1501 skip_dynamic_range_lvalue_expansion:;
1502
1503 if (stage > 1 && (type == AST_ASSERT || type == AST_ASSUME || type == AST_LIVE || type == AST_FAIR || type == AST_COVER) && current_block != NULL)
1504 {
1505 std::stringstream sstr;
1506 sstr << "$formal$" << filename << ":" << linenum << "$" << (autoidx++);
1507 std::string id_check = sstr.str() + "_CHECK", id_en = sstr.str() + "_EN";
1508
1509 AstNode *wire_check = new AstNode(AST_WIRE);
1510 wire_check->str = id_check;
1511 wire_check->was_checked = true;
1512 current_ast_mod->children.push_back(wire_check);
1513 current_scope[wire_check->str] = wire_check;
1514 while (wire_check->simplify(true, false, false, 1, -1, false, false)) { }
1515
1516 AstNode *wire_en = new AstNode(AST_WIRE);
1517 wire_en->str = id_en;
1518 wire_en->was_checked = true;
1519 current_ast_mod->children.push_back(wire_en);
1520 if (current_always_clocked) {
1521 current_ast_mod->children.push_back(new AstNode(AST_INITIAL, new AstNode(AST_BLOCK, new AstNode(AST_ASSIGN_LE, new AstNode(AST_IDENTIFIER), AstNode::mkconst_int(0, false, 1)))));
1522 current_ast_mod->children.back()->children[0]->children[0]->children[0]->str = id_en;
1523 current_ast_mod->children.back()->children[0]->children[0]->children[0]->was_checked = true;
1524 }
1525 current_scope[wire_en->str] = wire_en;
1526 while (wire_en->simplify(true, false, false, 1, -1, false, false)) { }
1527
1528 std::vector<RTLIL::State> x_bit;
1529 x_bit.push_back(RTLIL::State::Sx);
1530
1531 AstNode *assign_check = new AstNode(AST_ASSIGN_LE, new AstNode(AST_IDENTIFIER), mkconst_bits(x_bit, false));
1532 assign_check->children[0]->str = id_check;
1533 assign_check->children[0]->was_checked = true;
1534
1535 AstNode *assign_en = new AstNode(AST_ASSIGN_LE, new AstNode(AST_IDENTIFIER), mkconst_int(0, false, 1));
1536 assign_en->children[0]->str = id_en;
1537 assign_en->children[0]->was_checked = true;
1538
1539 AstNode *default_signals = new AstNode(AST_BLOCK);
1540 default_signals->children.push_back(assign_check);
1541 default_signals->children.push_back(assign_en);
1542 current_top_block->children.insert(current_top_block->children.begin(), default_signals);
1543
1544 assign_check = new AstNode(AST_ASSIGN_LE, new AstNode(AST_IDENTIFIER), new AstNode(AST_REDUCE_BOOL, children[0]->clone()));
1545 assign_check->children[0]->str = id_check;
1546 assign_check->children[0]->was_checked = true;
1547
1548 if (current_always == nullptr || current_always->type != AST_INITIAL) {
1549 assign_en = new AstNode(AST_ASSIGN_LE, new AstNode(AST_IDENTIFIER), mkconst_int(1, false, 1));
1550 } else {
1551 assign_en = new AstNode(AST_ASSIGN_LE, new AstNode(AST_IDENTIFIER), new AstNode(AST_FCALL));
1552 assign_en->children[1]->str = "\\$initstate";
1553 }
1554 assign_en->children[0]->str = id_en;
1555 assign_en->children[0]->was_checked = true;
1556
1557 newNode = new AstNode(AST_BLOCK);
1558 newNode->children.push_back(assign_check);
1559 newNode->children.push_back(assign_en);
1560
1561 AstNode *assertnode = new AstNode(type);
1562 assertnode->str = str;
1563 assertnode->children.push_back(new AstNode(AST_IDENTIFIER));
1564 assertnode->children.push_back(new AstNode(AST_IDENTIFIER));
1565 assertnode->children[0]->str = id_check;
1566 assertnode->children[1]->str = id_en;
1567 assertnode->attributes.swap(attributes);
1568 current_ast_mod->children.push_back(assertnode);
1569
1570 goto apply_newNode;
1571 }
1572
1573 if (stage > 1 && (type == AST_ASSERT || type == AST_ASSUME || type == AST_LIVE || type == AST_FAIR || type == AST_COVER) && children.size() == 1)
1574 {
1575 children.push_back(mkconst_int(1, false, 1));
1576 did_something = true;
1577 }
1578
1579 // found right-hand side identifier for memory -> replace with memory read port
1580 if (stage > 1 && type == AST_IDENTIFIER && id2ast != NULL && id2ast->type == AST_MEMORY && !in_lvalue &&
1581 children.size() == 1 && children[0]->type == AST_RANGE && children[0]->children.size() == 1) {
1582 newNode = new AstNode(AST_MEMRD, children[0]->children[0]->clone());
1583 newNode->str = str;
1584 newNode->id2ast = id2ast;
1585 goto apply_newNode;
1586 }
1587
1588 // assignment with nontrivial member in left-hand concat expression -> split assignment
1589 if ((type == AST_ASSIGN_EQ || type == AST_ASSIGN_LE) && children[0]->type == AST_CONCAT && width_hint > 0)
1590 {
1591 bool found_nontrivial_member = false;
1592
1593 for (auto child : children[0]->children) {
1594 if (child->type == AST_IDENTIFIER && child->id2ast != NULL && child->id2ast->type == AST_MEMORY)
1595 found_nontrivial_member = true;
1596 }
1597
1598 if (found_nontrivial_member)
1599 {
1600 newNode = new AstNode(AST_BLOCK);
1601
1602 AstNode *wire_tmp = new AstNode(AST_WIRE, new AstNode(AST_RANGE, mkconst_int(width_hint-1, true), mkconst_int(0, true)));
1603 wire_tmp->str = stringf("$splitcmplxassign$%s:%d$%d", filename.c_str(), linenum, autoidx++);
1604 current_ast_mod->children.push_back(wire_tmp);
1605 current_scope[wire_tmp->str] = wire_tmp;
1606 wire_tmp->attributes["\\nosync"] = AstNode::mkconst_int(1, false);
1607 while (wire_tmp->simplify(true, false, false, 1, -1, false, false)) { }
1608 wire_tmp->is_logic = true;
1609
1610 AstNode *wire_tmp_id = new AstNode(AST_IDENTIFIER);
1611 wire_tmp_id->str = wire_tmp->str;
1612
1613 newNode->children.push_back(new AstNode(AST_ASSIGN_EQ, wire_tmp_id, children[1]->clone()));
1614 newNode->children.back()->was_checked = true;
1615
1616 int cursor = 0;
1617 for (auto child : children[0]->children)
1618 {
1619 int child_width_hint = -1;
1620 bool child_sign_hint = true;
1621 child->detectSignWidth(child_width_hint, child_sign_hint);
1622
1623 AstNode *rhs = wire_tmp_id->clone();
1624 rhs->children.push_back(new AstNode(AST_RANGE, AstNode::mkconst_int(cursor+child_width_hint-1, true), AstNode::mkconst_int(cursor, true)));
1625 newNode->children.push_back(new AstNode(type, child->clone(), rhs));
1626
1627 cursor += child_width_hint;
1628 }
1629
1630 goto apply_newNode;
1631 }
1632 }
1633
1634 // assignment with memory in left-hand side expression -> replace with memory write port
1635 if (stage > 1 && (type == AST_ASSIGN_EQ || type == AST_ASSIGN_LE) && children[0]->type == AST_IDENTIFIER &&
1636 children[0]->id2ast && children[0]->id2ast->type == AST_MEMORY && children[0]->id2ast->children.size() >= 2 &&
1637 children[0]->id2ast->children[0]->range_valid && children[0]->id2ast->children[1]->range_valid &&
1638 (children[0]->children.size() == 1 || children[0]->children.size() == 2) && children[0]->children[0]->type == AST_RANGE)
1639 {
1640 std::stringstream sstr;
1641 sstr << "$memwr$" << children[0]->str << "$" << filename << ":" << linenum << "$" << (autoidx++);
1642 std::string id_addr = sstr.str() + "_ADDR", id_data = sstr.str() + "_DATA", id_en = sstr.str() + "_EN";
1643
1644 int mem_width, mem_size, addr_bits;
1645 bool mem_signed = children[0]->id2ast->is_signed;
1646 children[0]->id2ast->meminfo(mem_width, mem_size, addr_bits);
1647
1648 int data_range_left = children[0]->id2ast->children[0]->range_left;
1649 int data_range_right = children[0]->id2ast->children[0]->range_right;
1650 int mem_data_range_offset = std::min(data_range_left, data_range_right);
1651
1652 int addr_width_hint = -1;
1653 bool addr_sign_hint = true;
1654 children[0]->children[0]->children[0]->detectSignWidthWorker(addr_width_hint, addr_sign_hint);
1655 addr_bits = std::max(addr_bits, addr_width_hint);
1656
1657 AstNode *wire_addr = new AstNode(AST_WIRE, new AstNode(AST_RANGE, mkconst_int(addr_bits-1, true), mkconst_int(0, true)));
1658 wire_addr->str = id_addr;
1659 wire_addr->was_checked = true;
1660 current_ast_mod->children.push_back(wire_addr);
1661 current_scope[wire_addr->str] = wire_addr;
1662 while (wire_addr->simplify(true, false, false, 1, -1, false, false)) { }
1663
1664 AstNode *wire_data = new AstNode(AST_WIRE, new AstNode(AST_RANGE, mkconst_int(mem_width-1, true), mkconst_int(0, true)));
1665 wire_data->str = id_data;
1666 wire_data->was_checked = true;
1667 wire_data->is_signed = mem_signed;
1668 current_ast_mod->children.push_back(wire_data);
1669 current_scope[wire_data->str] = wire_data;
1670 while (wire_data->simplify(true, false, false, 1, -1, false, false)) { }
1671
1672 AstNode *wire_en = nullptr;
1673 if (current_always->type != AST_INITIAL) {
1674 wire_en = new AstNode(AST_WIRE, new AstNode(AST_RANGE, mkconst_int(mem_width-1, true), mkconst_int(0, true)));
1675 wire_en->str = id_en;
1676 wire_en->was_checked = true;
1677 current_ast_mod->children.push_back(wire_en);
1678 current_scope[wire_en->str] = wire_en;
1679 while (wire_en->simplify(true, false, false, 1, -1, false, false)) { }
1680 }
1681
1682 std::vector<RTLIL::State> x_bits_addr, x_bits_data, set_bits_en;
1683 for (int i = 0; i < addr_bits; i++)
1684 x_bits_addr.push_back(RTLIL::State::Sx);
1685 for (int i = 0; i < mem_width; i++)
1686 x_bits_data.push_back(RTLIL::State::Sx);
1687 for (int i = 0; i < mem_width; i++)
1688 set_bits_en.push_back(RTLIL::State::S1);
1689
1690 AstNode *assign_addr = new AstNode(AST_ASSIGN_LE, new AstNode(AST_IDENTIFIER), mkconst_bits(x_bits_addr, false));
1691 assign_addr->children[0]->str = id_addr;
1692 assign_addr->children[0]->was_checked = true;
1693
1694 AstNode *assign_data = new AstNode(AST_ASSIGN_LE, new AstNode(AST_IDENTIFIER), mkconst_bits(x_bits_data, false));
1695 assign_data->children[0]->str = id_data;
1696 assign_data->children[0]->was_checked = true;
1697
1698 AstNode *assign_en = nullptr;
1699 if (current_always->type != AST_INITIAL) {
1700 assign_en = new AstNode(AST_ASSIGN_LE, new AstNode(AST_IDENTIFIER), mkconst_int(0, false, mem_width));
1701 assign_en->children[0]->str = id_en;
1702 assign_en->children[0]->was_checked = true;
1703 }
1704
1705 AstNode *default_signals = new AstNode(AST_BLOCK);
1706 default_signals->children.push_back(assign_addr);
1707 default_signals->children.push_back(assign_data);
1708 if (current_always->type != AST_INITIAL)
1709 default_signals->children.push_back(assign_en);
1710 current_top_block->children.insert(current_top_block->children.begin(), default_signals);
1711
1712 assign_addr = new AstNode(AST_ASSIGN_LE, new AstNode(AST_IDENTIFIER), children[0]->children[0]->children[0]->clone());
1713 assign_addr->children[0]->str = id_addr;
1714 assign_addr->children[0]->was_checked = true;
1715
1716 if (children[0]->children.size() == 2)
1717 {
1718 if (children[0]->children[1]->range_valid)
1719 {
1720 int offset = children[0]->children[1]->range_right;
1721 int width = children[0]->children[1]->range_left - offset + 1;
1722 offset -= mem_data_range_offset;
1723
1724 std::vector<RTLIL::State> padding_x(offset, RTLIL::State::Sx);
1725
1726 assign_data = new AstNode(AST_ASSIGN_LE, new AstNode(AST_IDENTIFIER),
1727 new AstNode(AST_CONCAT, mkconst_bits(padding_x, false), children[1]->clone()));
1728 assign_data->children[0]->str = id_data;
1729 assign_data->children[0]->was_checked = true;
1730
1731 if (current_always->type != AST_INITIAL) {
1732 for (int i = 0; i < mem_width; i++)
1733 set_bits_en[i] = offset <= i && i < offset+width ? RTLIL::State::S1 : RTLIL::State::S0;
1734 assign_en = new AstNode(AST_ASSIGN_LE, new AstNode(AST_IDENTIFIER), mkconst_bits(set_bits_en, false));
1735 assign_en->children[0]->str = id_en;
1736 assign_en->children[0]->was_checked = true;
1737 }
1738 }
1739 else
1740 {
1741 AstNode *the_range = children[0]->children[1];
1742 AstNode *left_at_zero_ast = the_range->children[0]->clone();
1743 AstNode *right_at_zero_ast = the_range->children.size() >= 2 ? the_range->children[1]->clone() : left_at_zero_ast->clone();
1744 AstNode *offset_ast = right_at_zero_ast->clone();
1745
1746 if (mem_data_range_offset)
1747 offset_ast = new AstNode(AST_SUB, offset_ast, mkconst_int(mem_data_range_offset, true));
1748
1749 while (left_at_zero_ast->simplify(true, true, false, 1, -1, false, false)) { }
1750 while (right_at_zero_ast->simplify(true, true, false, 1, -1, false, false)) { }
1751 if (left_at_zero_ast->type != AST_CONSTANT || right_at_zero_ast->type != AST_CONSTANT)
1752 log_file_error(filename, linenum, "Unsupported expression on dynamic range select on signal `%s'!\n", str.c_str());
1753 int width = abs(int(left_at_zero_ast->integer - right_at_zero_ast->integer)) + 1;
1754
1755 assign_data = new AstNode(AST_ASSIGN_LE, new AstNode(AST_IDENTIFIER),
1756 new AstNode(AST_SHIFT_LEFT, children[1]->clone(), offset_ast->clone()));
1757 assign_data->children[0]->str = id_data;
1758 assign_data->children[0]->was_checked = true;
1759
1760 if (current_always->type != AST_INITIAL) {
1761 for (int i = 0; i < mem_width; i++)
1762 set_bits_en[i] = i < width ? RTLIL::State::S1 : RTLIL::State::S0;
1763 assign_en = new AstNode(AST_ASSIGN_LE, new AstNode(AST_IDENTIFIER),
1764 new AstNode(AST_SHIFT_LEFT, mkconst_bits(set_bits_en, false), offset_ast->clone()));
1765 assign_en->children[0]->str = id_en;
1766 assign_en->children[0]->was_checked = true;
1767 }
1768
1769 delete left_at_zero_ast;
1770 delete right_at_zero_ast;
1771 delete offset_ast;
1772 }
1773 }
1774 else
1775 {
1776 assign_data = new AstNode(AST_ASSIGN_LE, new AstNode(AST_IDENTIFIER), children[1]->clone());
1777 assign_data->children[0]->str = id_data;
1778 assign_data->children[0]->was_checked = true;
1779
1780 if (current_always->type != AST_INITIAL) {
1781 assign_en = new AstNode(AST_ASSIGN_LE, new AstNode(AST_IDENTIFIER), mkconst_bits(set_bits_en, false));
1782 assign_en->children[0]->str = id_en;
1783 assign_en->children[0]->was_checked = true;
1784 }
1785 }
1786
1787 newNode = new AstNode(AST_BLOCK);
1788 newNode->children.push_back(assign_addr);
1789 newNode->children.push_back(assign_data);
1790 if (current_always->type != AST_INITIAL)
1791 newNode->children.push_back(assign_en);
1792
1793 AstNode *wrnode = new AstNode(current_always->type == AST_INITIAL ? AST_MEMINIT : AST_MEMWR);
1794 wrnode->children.push_back(new AstNode(AST_IDENTIFIER));
1795 wrnode->children.push_back(new AstNode(AST_IDENTIFIER));
1796 if (current_always->type != AST_INITIAL)
1797 wrnode->children.push_back(new AstNode(AST_IDENTIFIER));
1798 else
1799 wrnode->children.push_back(AstNode::mkconst_int(1, false));
1800 wrnode->str = children[0]->str;
1801 wrnode->id2ast = children[0]->id2ast;
1802 wrnode->children[0]->str = id_addr;
1803 wrnode->children[1]->str = id_data;
1804 if (current_always->type != AST_INITIAL)
1805 wrnode->children[2]->str = id_en;
1806 current_ast_mod->children.push_back(wrnode);
1807
1808 goto apply_newNode;
1809 }
1810
1811 // replace function and task calls with the code from the function or task
1812 if ((type == AST_FCALL || type == AST_TCALL) && !str.empty())
1813 {
1814 if (type == AST_FCALL)
1815 {
1816 if (str == "\\$initstate")
1817 {
1818 int myidx = autoidx++;
1819
1820 AstNode *wire = new AstNode(AST_WIRE);
1821 wire->str = stringf("$initstate$%d_wire", myidx);
1822 current_ast_mod->children.push_back(wire);
1823 while (wire->simplify(true, false, false, 1, -1, false, false)) { }
1824
1825 AstNode *cell = new AstNode(AST_CELL, new AstNode(AST_CELLTYPE), new AstNode(AST_ARGUMENT, new AstNode(AST_IDENTIFIER)));
1826 cell->str = stringf("$initstate$%d", myidx);
1827 cell->children[0]->str = "$initstate";
1828 cell->children[1]->str = "\\Y";
1829 cell->children[1]->children[0]->str = wire->str;
1830 cell->children[1]->children[0]->id2ast = wire;
1831 current_ast_mod->children.push_back(cell);
1832 while (cell->simplify(true, false, false, 1, -1, false, false)) { }
1833
1834 newNode = new AstNode(AST_IDENTIFIER);
1835 newNode->str = wire->str;
1836 newNode->id2ast = wire;
1837 goto apply_newNode;
1838 }
1839
1840 if (str == "\\$past")
1841 {
1842 if (width_hint < 0)
1843 goto replace_fcall_later;
1844
1845 int num_steps = 1;
1846
1847 if (GetSize(children) != 1 && GetSize(children) != 2)
1848 log_file_error(filename, linenum, "System function %s got %d arguments, expected 1 or 2.\n",
1849 RTLIL::unescape_id(str).c_str(), int(children.size()));
1850
1851 if (!current_always_clocked)
1852 log_file_error(filename, linenum, "System function %s is only allowed in clocked blocks.\n",
1853 RTLIL::unescape_id(str).c_str());
1854
1855 if (GetSize(children) == 2)
1856 {
1857 AstNode *buf = children[1]->clone();
1858 while (buf->simplify(true, false, false, stage, -1, false, false)) { }
1859 if (buf->type != AST_CONSTANT)
1860 log_file_error(filename, linenum, "Failed to evaluate system function `%s' with non-constant value.\n", str.c_str());
1861
1862 num_steps = buf->asInt(true);
1863 delete buf;
1864 }
1865
1866 AstNode *block = nullptr;
1867
1868 for (auto child : current_always->children)
1869 if (child->type == AST_BLOCK)
1870 block = child;
1871
1872 log_assert(block != nullptr);
1873
1874 if (num_steps == 0) {
1875 newNode = children[0]->clone();
1876 goto apply_newNode;
1877 }
1878
1879 int myidx = autoidx++;
1880 AstNode *outreg = nullptr;
1881
1882 for (int i = 0; i < num_steps; i++)
1883 {
1884 AstNode *reg = new AstNode(AST_WIRE, new AstNode(AST_RANGE,
1885 mkconst_int(width_hint-1, true), mkconst_int(0, true)));
1886
1887 reg->str = stringf("$past$%s:%d$%d$%d", filename.c_str(), linenum, myidx, i);
1888 reg->is_reg = true;
1889
1890 current_ast_mod->children.push_back(reg);
1891
1892 while (reg->simplify(true, false, false, 1, -1, false, false)) { }
1893
1894 AstNode *regid = new AstNode(AST_IDENTIFIER);
1895 regid->str = reg->str;
1896 regid->id2ast = reg;
1897 regid->was_checked = true;
1898
1899 AstNode *rhs = nullptr;
1900
1901 if (outreg == nullptr) {
1902 rhs = children.at(0)->clone();
1903 } else {
1904 rhs = new AstNode(AST_IDENTIFIER);
1905 rhs->str = outreg->str;
1906 rhs->id2ast = outreg;
1907 }
1908
1909 block->children.push_back(new AstNode(AST_ASSIGN_LE, regid, rhs));
1910 outreg = reg;
1911 }
1912
1913 newNode = new AstNode(AST_IDENTIFIER);
1914 newNode->str = outreg->str;
1915 newNode->id2ast = outreg;
1916 goto apply_newNode;
1917 }
1918
1919 if (str == "\\$stable" || str == "\\$rose" || str == "\\$fell" || str == "\\$changed")
1920 {
1921 if (GetSize(children) != 1)
1922 log_file_error(filename, linenum, "System function %s got %d arguments, expected 1.\n",
1923 RTLIL::unescape_id(str).c_str(), int(children.size()));
1924
1925 if (!current_always_clocked)
1926 log_file_error(filename, linenum, "System function %s is only allowed in clocked blocks.\n",
1927 RTLIL::unescape_id(str).c_str());
1928
1929 AstNode *present = children.at(0)->clone();
1930 AstNode *past = clone();
1931 past->str = "\\$past";
1932
1933 if (str == "\\$stable")
1934 newNode = new AstNode(AST_EQ, past, present);
1935
1936 else if (str == "\\$changed")
1937 newNode = new AstNode(AST_NE, past, present);
1938
1939 else if (str == "\\$rose")
1940 newNode = new AstNode(AST_LOGIC_AND,
1941 new AstNode(AST_LOGIC_NOT, new AstNode(AST_BIT_AND, past, mkconst_int(1,false))),
1942 new AstNode(AST_BIT_AND, present, mkconst_int(1,false)));
1943
1944 else if (str == "\\$fell")
1945 newNode = new AstNode(AST_LOGIC_AND,
1946 new AstNode(AST_BIT_AND, past, mkconst_int(1,false)),
1947 new AstNode(AST_LOGIC_NOT, new AstNode(AST_BIT_AND, present, mkconst_int(1,false))));
1948
1949 else
1950 log_abort();
1951
1952 goto apply_newNode;
1953 }
1954
1955 // $anyconst and $anyseq are mapped in AstNode::genRTLIL()
1956 if (str == "\\$anyconst" || str == "\\$anyseq" || str == "\\$allconst" || str == "\\$allseq") {
1957 recursion_counter--;
1958 return false;
1959 }
1960
1961 if (str == "\\$clog2")
1962 {
1963 if (children.size() != 1)
1964 log_file_error(filename, linenum, "System function %s got %d arguments, expected 1.\n",
1965 RTLIL::unescape_id(str).c_str(), int(children.size()));
1966
1967 AstNode *buf = children[0]->clone();
1968 while (buf->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
1969 if (buf->type != AST_CONSTANT)
1970 log_file_error(filename, linenum, "Failed to evaluate system function `%s' with non-constant value.\n", str.c_str());
1971
1972 RTLIL::Const arg_value = buf->bitsAsConst();
1973 if (arg_value.as_bool())
1974 arg_value = const_sub(arg_value, 1, false, false, GetSize(arg_value));
1975 delete buf;
1976
1977 uint32_t result = 0;
1978 for (size_t i = 0; i < arg_value.bits.size(); i++)
1979 if (arg_value.bits.at(i) == RTLIL::State::S1)
1980 result = i + 1;
1981
1982 newNode = mkconst_int(result, true);
1983 goto apply_newNode;
1984 }
1985
1986 if (str == "\\$size" || str == "\\$bits")
1987 {
1988 if (str == "\\$bits" && children.size() != 1)
1989 log_file_error(filename, linenum, "System function %s got %d arguments, expected 1.\n",
1990 RTLIL::unescape_id(str).c_str(), int(children.size()));
1991
1992 if (str == "\\$size" && children.size() != 1 && children.size() != 2)
1993 log_file_error(filename, linenum, "System function %s got %d arguments, expected 1 or 2.\n",
1994 RTLIL::unescape_id(str).c_str(), int(children.size()));
1995
1996 int dim = 1;
1997 if (str == "\\$size" && children.size() == 2) {
1998 AstNode *buf = children[1]->clone();
1999 // Evaluate constant expression
2000 while (buf->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
2001 dim = buf->asInt(false);
2002 delete buf;
2003 }
2004 AstNode *buf = children[0]->clone();
2005 int mem_depth = 1;
2006 AstNode *id_ast = NULL;
2007
2008 // Is this needed?
2009 //while (buf->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
2010 buf->detectSignWidth(width_hint, sign_hint);
2011
2012 if (buf->type == AST_IDENTIFIER) {
2013 id_ast = buf->id2ast;
2014 if (id_ast == NULL && current_scope.count(buf->str))
2015 id_ast = current_scope.at(buf->str);
2016 if (!id_ast)
2017 log_file_error(filename, linenum, "Failed to resolve identifier %s for width detection!\n", buf->str.c_str());
2018 if (id_ast->type == AST_MEMORY) {
2019 // We got here only if the argument is a memory
2020 // Otherwise $size() and $bits() return the expression width
2021 AstNode *mem_range = id_ast->children[1];
2022 if (str == "\\$bits") {
2023 if (mem_range->type == AST_RANGE) {
2024 if (!mem_range->range_valid)
2025 log_file_error(filename, linenum, "Failed to detect width of memory access `%s'!\n", buf->str.c_str());
2026 mem_depth = mem_range->range_left - mem_range->range_right + 1;
2027 } else
2028 log_file_error(filename, linenum, "Unknown memory depth AST type in `%s'!\n", buf->str.c_str());
2029 } else {
2030 // $size()
2031 if (mem_range->type == AST_RANGE) {
2032 if (!mem_range->range_valid)
2033 log_file_error(filename, linenum, "Failed to detect width of memory access `%s'!\n", buf->str.c_str());
2034 int dims;
2035 if (id_ast->multirange_dimensions.empty())
2036 dims = 1;
2037 else
2038 dims = GetSize(id_ast->multirange_dimensions)/2;
2039 if (dim == 1)
2040 width_hint = (dims > 1) ? id_ast->multirange_dimensions[1] : (mem_range->range_left - mem_range->range_right + 1);
2041 else if (dim <= dims) {
2042 width_hint = id_ast->multirange_dimensions[2*dim-1];
2043 } else if ((dim > dims+1) || (dim < 0))
2044 log_file_error(filename, linenum, "Dimension %d out of range in `%s', as it only has dimensions 1..%d!\n", dim, buf->str.c_str(), dims+1);
2045 } else
2046 log_file_error(filename, linenum, "Unknown memory depth AST type in `%s'!\n", buf->str.c_str());
2047 }
2048 }
2049 }
2050 delete buf;
2051
2052 newNode = mkconst_int(width_hint * mem_depth, false);
2053 goto apply_newNode;
2054 }
2055
2056 if (str == "\\$ln" || str == "\\$log10" || str == "\\$exp" || str == "\\$sqrt" || str == "\\$pow" ||
2057 str == "\\$floor" || str == "\\$ceil" || str == "\\$sin" || str == "\\$cos" || str == "\\$tan" ||
2058 str == "\\$asin" || str == "\\$acos" || str == "\\$atan" || str == "\\$atan2" || str == "\\$hypot" ||
2059 str == "\\$sinh" || str == "\\$cosh" || str == "\\$tanh" || str == "\\$asinh" || str == "\\$acosh" || str == "\\$atanh" ||
2060 str == "\\$rtoi" || str == "\\$itor")
2061 {
2062 bool func_with_two_arguments = str == "\\$pow" || str == "\\$atan2" || str == "\\$hypot";
2063 double x = 0, y = 0;
2064
2065 if (func_with_two_arguments) {
2066 if (children.size() != 2)
2067 log_file_error(filename, linenum, "System function %s got %d arguments, expected 2.\n",
2068 RTLIL::unescape_id(str).c_str(), int(children.size()));
2069 } else {
2070 if (children.size() != 1)
2071 log_file_error(filename, linenum, "System function %s got %d arguments, expected 1.\n",
2072 RTLIL::unescape_id(str).c_str(), int(children.size()));
2073 }
2074
2075 if (children.size() >= 1) {
2076 while (children[0]->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
2077 if (!children[0]->isConst())
2078 log_file_error(filename, linenum, "Failed to evaluate system function `%s' with non-constant argument.\n",
2079 RTLIL::unescape_id(str).c_str());
2080 int child_width_hint = width_hint;
2081 bool child_sign_hint = sign_hint;
2082 children[0]->detectSignWidth(child_width_hint, child_sign_hint);
2083 x = children[0]->asReal(child_sign_hint);
2084 }
2085
2086 if (children.size() >= 2) {
2087 while (children[1]->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
2088 if (!children[1]->isConst())
2089 log_file_error(filename, linenum, "Failed to evaluate system function `%s' with non-constant argument.\n",
2090 RTLIL::unescape_id(str).c_str());
2091 int child_width_hint = width_hint;
2092 bool child_sign_hint = sign_hint;
2093 children[1]->detectSignWidth(child_width_hint, child_sign_hint);
2094 y = children[1]->asReal(child_sign_hint);
2095 }
2096
2097 if (str == "\\$rtoi") {
2098 newNode = AstNode::mkconst_int(x, true);
2099 } else {
2100 newNode = new AstNode(AST_REALVALUE);
2101 if (str == "\\$ln") newNode->realvalue = ::log(x);
2102 else if (str == "\\$log10") newNode->realvalue = ::log10(x);
2103 else if (str == "\\$exp") newNode->realvalue = ::exp(x);
2104 else if (str == "\\$sqrt") newNode->realvalue = ::sqrt(x);
2105 else if (str == "\\$pow") newNode->realvalue = ::pow(x, y);
2106 else if (str == "\\$floor") newNode->realvalue = ::floor(x);
2107 else if (str == "\\$ceil") newNode->realvalue = ::ceil(x);
2108 else if (str == "\\$sin") newNode->realvalue = ::sin(x);
2109 else if (str == "\\$cos") newNode->realvalue = ::cos(x);
2110 else if (str == "\\$tan") newNode->realvalue = ::tan(x);
2111 else if (str == "\\$asin") newNode->realvalue = ::asin(x);
2112 else if (str == "\\$acos") newNode->realvalue = ::acos(x);
2113 else if (str == "\\$atan") newNode->realvalue = ::atan(x);
2114 else if (str == "\\$atan2") newNode->realvalue = ::atan2(x, y);
2115 else if (str == "\\$hypot") newNode->realvalue = ::hypot(x, y);
2116 else if (str == "\\$sinh") newNode->realvalue = ::sinh(x);
2117 else if (str == "\\$cosh") newNode->realvalue = ::cosh(x);
2118 else if (str == "\\$tanh") newNode->realvalue = ::tanh(x);
2119 else if (str == "\\$asinh") newNode->realvalue = ::asinh(x);
2120 else if (str == "\\$acosh") newNode->realvalue = ::acosh(x);
2121 else if (str == "\\$atanh") newNode->realvalue = ::atanh(x);
2122 else if (str == "\\$itor") newNode->realvalue = x;
2123 else log_abort();
2124 }
2125 goto apply_newNode;
2126 }
2127
2128 if (current_scope.count(str) != 0 && current_scope[str]->type == AST_DPI_FUNCTION)
2129 {
2130 AstNode *dpi_decl = current_scope[str];
2131
2132 std::string rtype, fname;
2133 std::vector<std::string> argtypes;
2134 std::vector<AstNode*> args;
2135
2136 rtype = RTLIL::unescape_id(dpi_decl->children.at(0)->str);
2137 fname = RTLIL::unescape_id(dpi_decl->children.at(1)->str);
2138
2139 for (int i = 2; i < GetSize(dpi_decl->children); i++)
2140 {
2141 if (i-2 >= GetSize(children))
2142 log_file_error(filename, linenum, "Insufficient number of arguments in DPI function call.\n");
2143
2144 argtypes.push_back(RTLIL::unescape_id(dpi_decl->children.at(i)->str));
2145 args.push_back(children.at(i-2)->clone());
2146 while (args.back()->simplify(true, false, false, stage, -1, false, true)) { }
2147
2148 if (args.back()->type != AST_CONSTANT && args.back()->type != AST_REALVALUE)
2149 log_file_error(filename, linenum, "Failed to evaluate DPI function with non-constant argument.\n");
2150 }
2151
2152 newNode = dpi_call(rtype, fname, argtypes, args);
2153
2154 for (auto arg : args)
2155 delete arg;
2156
2157 goto apply_newNode;
2158 }
2159
2160 if (current_scope.count(str) == 0 || current_scope[str]->type != AST_FUNCTION)
2161 log_file_error(filename, linenum, "Can't resolve function name `%s'.\n", str.c_str());
2162 }
2163
2164 if (type == AST_TCALL)
2165 {
2166 if (str == "$finish" || str == "$stop")
2167 {
2168 if (!current_always || current_always->type != AST_INITIAL)
2169 log_file_error(filename, linenum, "System task `%s' outside initial block is unsupported.\n", str.c_str());
2170
2171 log_file_error(filename, linenum, "System task `%s' executed.\n", str.c_str());
2172 }
2173
2174 if (str == "\\$readmemh" || str == "\\$readmemb")
2175 {
2176 if (GetSize(children) < 2 || GetSize(children) > 4)
2177 log_file_error(filename, linenum, "System function %s got %d arguments, expected 2-4.\n",
2178 RTLIL::unescape_id(str).c_str(), int(children.size()));
2179
2180 AstNode *node_filename = children[0]->clone();
2181 while (node_filename->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
2182 if (node_filename->type != AST_CONSTANT)
2183 log_file_error(filename, linenum, "Failed to evaluate system function `%s' with non-constant 1st argument.\n", str.c_str());
2184
2185 AstNode *node_memory = children[1]->clone();
2186 while (node_memory->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
2187 if (node_memory->type != AST_IDENTIFIER || node_memory->id2ast == nullptr || node_memory->id2ast->type != AST_MEMORY)
2188 log_file_error(filename, linenum, "Failed to evaluate system function `%s' with non-memory 2nd argument.\n", str.c_str());
2189
2190 int start_addr = -1, finish_addr = -1;
2191
2192 if (GetSize(children) > 2) {
2193 AstNode *node_addr = children[2]->clone();
2194 while (node_addr->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
2195 if (node_addr->type != AST_CONSTANT)
2196 log_file_error(filename, linenum, "Failed to evaluate system function `%s' with non-constant 3rd argument.\n", str.c_str());
2197 start_addr = int(node_addr->asInt(false));
2198 }
2199
2200 if (GetSize(children) > 3) {
2201 AstNode *node_addr = children[3]->clone();
2202 while (node_addr->simplify(true, false, false, stage, width_hint, sign_hint, false)) { }
2203 if (node_addr->type != AST_CONSTANT)
2204 log_file_error(filename, linenum, "Failed to evaluate system function `%s' with non-constant 4th argument.\n", str.c_str());
2205 finish_addr = int(node_addr->asInt(false));
2206 }
2207
2208 bool unconditional_init = false;
2209 if (current_always->type == AST_INITIAL) {
2210 pool<AstNode*> queue;
2211 log_assert(current_always->children[0]->type == AST_BLOCK);
2212 queue.insert(current_always->children[0]);
2213 while (!unconditional_init && !queue.empty()) {
2214 pool<AstNode*> next_queue;
2215 for (auto n : queue)
2216 for (auto c : n->children) {
2217 if (c == this)
2218 unconditional_init = true;
2219 next_queue.insert(c);
2220 }
2221 next_queue.swap(queue);
2222 }
2223 }
2224
2225 newNode = readmem(str == "\\$readmemh", node_filename->bitsAsConst().decode_string(), node_memory->id2ast, start_addr, finish_addr, unconditional_init);
2226 delete node_filename;
2227 delete node_memory;
2228 goto apply_newNode;
2229 }
2230
2231 if (current_scope.count(str) == 0 || current_scope[str]->type != AST_TASK)
2232 log_file_error(filename, linenum, "Can't resolve task name `%s'.\n", str.c_str());
2233 }
2234
2235 AstNode *decl = current_scope[str];
2236
2237 std::stringstream sstr;
2238 sstr << "$func$" << str << "$" << filename << ":" << linenum << "$" << (autoidx++) << "$";
2239 std::string prefix = sstr.str();
2240
2241 bool recommend_const_eval = false;
2242 bool require_const_eval = in_param ? false : has_const_only_constructs(recommend_const_eval);
2243 if ((in_param || recommend_const_eval || require_const_eval) && !decl->attributes.count("\\via_celltype"))
2244 {
2245 bool all_args_const = true;
2246 for (auto child : children) {
2247 while (child->simplify(true, false, false, 1, -1, false, true)) { }
2248 if (child->type != AST_CONSTANT)
2249 all_args_const = false;
2250 }
2251
2252 if (all_args_const) {
2253 AstNode *func_workspace = current_scope[str]->clone();
2254 newNode = func_workspace->eval_const_function(this);
2255 delete func_workspace;
2256 goto apply_newNode;
2257 }
2258
2259 if (in_param)
2260 log_file_error(filename, linenum, "Non-constant function call in constant expression.\n");
2261 if (require_const_eval)
2262 log_file_error(filename, linenum, "Function %s can only be called with constant arguments.\n", str.c_str());
2263 }
2264
2265 size_t arg_count = 0;
2266 std::map<std::string, std::string> replace_rules;
2267 vector<AstNode*> added_mod_children;
2268 dict<std::string, AstNode*> wire_cache;
2269 vector<AstNode*> new_stmts;
2270 vector<AstNode*> output_assignments;
2271
2272 if (current_block == NULL)
2273 {
2274 log_assert(type == AST_FCALL);
2275
2276 AstNode *wire = NULL;
2277 for (auto child : decl->children)
2278 if (child->type == AST_WIRE && child->str == str)
2279 wire = child->clone();
2280 log_assert(wire != NULL);
2281
2282 wire->str = prefix + str;
2283 wire->port_id = 0;
2284 wire->is_input = false;
2285 wire->is_output = false;
2286
2287 current_ast_mod->children.push_back(wire);
2288 while (wire->simplify(true, false, false, 1, -1, false, false)) { }
2289
2290 AstNode *lvalue = new AstNode(AST_IDENTIFIER);
2291 lvalue->str = wire->str;
2292
2293 AstNode *always = new AstNode(AST_ALWAYS, new AstNode(AST_BLOCK,
2294 new AstNode(AST_ASSIGN_EQ, lvalue, clone())));
2295 always->children[0]->children[0]->was_checked = true;
2296
2297 current_ast_mod->children.push_back(always);
2298
2299 goto replace_fcall_with_id;
2300 }
2301
2302 if (decl->attributes.count("\\via_celltype"))
2303 {
2304 std::string celltype = decl->attributes.at("\\via_celltype")->asAttrConst().decode_string();
2305 std::string outport = str;
2306
2307 if (celltype.find(' ') != std::string::npos) {
2308 int pos = celltype.find(' ');
2309 outport = RTLIL::escape_id(celltype.substr(pos+1));
2310 celltype = RTLIL::escape_id(celltype.substr(0, pos));
2311 } else
2312 celltype = RTLIL::escape_id(celltype);
2313
2314 AstNode *cell = new AstNode(AST_CELL, new AstNode(AST_CELLTYPE));
2315 cell->str = prefix.substr(0, GetSize(prefix)-1);
2316 cell->children[0]->str = celltype;
2317
2318 for (auto attr : decl->attributes)
2319 if (attr.first.str().rfind("\\via_celltype_defparam_", 0) == 0)
2320 {
2321 AstNode *cell_arg = new AstNode(AST_PARASET, attr.second->clone());
2322 cell_arg->str = RTLIL::escape_id(attr.first.str().substr(strlen("\\via_celltype_defparam_")));
2323 cell->children.push_back(cell_arg);
2324 }
2325
2326 for (auto child : decl->children)
2327 if (child->type == AST_WIRE && (child->is_input || child->is_output || (type == AST_FCALL && child->str == str)))
2328 {
2329 AstNode *wire = child->clone();
2330 wire->str = prefix + wire->str;
2331 wire->port_id = 0;
2332 wire->is_input = false;
2333 wire->is_output = false;
2334 current_ast_mod->children.push_back(wire);
2335 while (wire->simplify(true, false, false, 1, -1, false, false)) { }
2336
2337 AstNode *wire_id = new AstNode(AST_IDENTIFIER);
2338 wire_id->str = wire->str;
2339
2340 if ((child->is_input || child->is_output) && arg_count < children.size())
2341 {
2342 AstNode *arg = children[arg_count++]->clone();
2343 AstNode *assign = child->is_input ?
2344 new AstNode(AST_ASSIGN_EQ, wire_id->clone(), arg) :
2345 new AstNode(AST_ASSIGN_EQ, arg, wire_id->clone());
2346 assign->children[0]->was_checked = true;
2347
2348 for (auto it = current_block->children.begin(); it != current_block->children.end(); it++) {
2349 if (*it != current_block_child)
2350 continue;
2351 current_block->children.insert(it, assign);
2352 break;
2353 }
2354 }
2355
2356 AstNode *cell_arg = new AstNode(AST_ARGUMENT, wire_id);
2357 cell_arg->str = child->str == str ? outport : child->str;
2358 cell->children.push_back(cell_arg);
2359 }
2360
2361 current_ast_mod->children.push_back(cell);
2362 goto replace_fcall_with_id;
2363 }
2364
2365 for (auto child : decl->children)
2366 if (child->type == AST_WIRE || child->type == AST_MEMORY || child->type == AST_PARAMETER || child->type == AST_LOCALPARAM)
2367 {
2368 AstNode *wire = nullptr;
2369
2370 if (wire_cache.count(child->str))
2371 {
2372 wire = wire_cache.at(child->str);
2373 if (wire->children.empty()) {
2374 for (auto c : child->children)
2375 wire->children.push_back(c->clone());
2376 } else if (!child->children.empty()) {
2377 while (child->simplify(true, false, false, stage, -1, false, false)) { }
2378 if (GetSize(child->children) == GetSize(wire->children)) {
2379 for (int i = 0; i < GetSize(child->children); i++)
2380 if (*child->children.at(i) != *wire->children.at(i))
2381 goto tcall_incompatible_wires;
2382 } else {
2383 tcall_incompatible_wires:
2384 log_file_error(filename, linenum, "Incompatible re-declaration of wire %s.\n", child->str.c_str());
2385 }
2386 }
2387 }
2388 else
2389 {
2390 wire = child->clone();
2391 wire->str = prefix + wire->str;
2392 wire->port_id = 0;
2393 wire->is_input = false;
2394 wire->is_output = false;
2395 wire->is_reg = true;
2396 wire->attributes["\\nosync"] = AstNode::mkconst_int(1, false);
2397 wire_cache[child->str] = wire;
2398
2399 current_ast_mod->children.push_back(wire);
2400 added_mod_children.push_back(wire);
2401 }
2402
2403 if (child->type == AST_WIRE)
2404 while (wire->simplify(true, false, false, 1, -1, false, false)) { }
2405
2406 replace_rules[child->str] = wire->str;
2407 current_scope[wire->str] = wire;
2408
2409 if ((child->is_input || child->is_output) && arg_count < children.size())
2410 {
2411 AstNode *arg = children[arg_count++]->clone();
2412 AstNode *wire_id = new AstNode(AST_IDENTIFIER);
2413 wire_id->str = wire->str;
2414 AstNode *assign = child->is_input ?
2415 new AstNode(AST_ASSIGN_EQ, wire_id, arg) :
2416 new AstNode(AST_ASSIGN_EQ, arg, wire_id);
2417 assign->children[0]->was_checked = true;
2418 if (child->is_input)
2419 new_stmts.push_back(assign);
2420 else
2421 output_assignments.push_back(assign);
2422 }
2423 }
2424
2425 for (auto child : added_mod_children) {
2426 child->replace_ids(prefix, replace_rules);
2427 while (child->simplify(true, false, false, 1, -1, false, false)) { }
2428 }
2429
2430 for (auto child : decl->children)
2431 if (child->type != AST_WIRE && child->type != AST_MEMORY && child->type != AST_PARAMETER && child->type != AST_LOCALPARAM)
2432 {
2433 AstNode *stmt = child->clone();
2434 stmt->replace_ids(prefix, replace_rules);
2435 new_stmts.push_back(stmt);
2436 }
2437
2438 new_stmts.insert(new_stmts.end(), output_assignments.begin(), output_assignments.end());
2439
2440 for (auto it = current_block->children.begin(); ; it++) {
2441 log_assert(it != current_block->children.end());
2442 if (*it == current_block_child) {
2443 current_block->children.insert(it, new_stmts.begin(), new_stmts.end());
2444 break;
2445 }
2446 }
2447
2448 replace_fcall_with_id:
2449 if (type == AST_FCALL) {
2450 delete_children();
2451 type = AST_IDENTIFIER;
2452 str = prefix + str;
2453 }
2454 if (type == AST_TCALL)
2455 str = "";
2456 did_something = true;
2457 }
2458
2459 replace_fcall_later:;
2460
2461 // perform const folding when activated
2462 if (const_fold)
2463 {
2464 bool string_op;
2465 std::vector<RTLIL::State> tmp_bits;
2466 RTLIL::Const (*const_func)(const RTLIL::Const&, const RTLIL::Const&, bool, bool, int);
2467 RTLIL::Const dummy_arg;
2468
2469 switch (type)
2470 {
2471 case AST_IDENTIFIER:
2472 if (current_scope.count(str) > 0 && (current_scope[str]->type == AST_PARAMETER || current_scope[str]->type == AST_LOCALPARAM)) {
2473 if (current_scope[str]->children[0]->type == AST_CONSTANT) {
2474 if (children.size() != 0 && children[0]->type == AST_RANGE && children[0]->range_valid) {
2475 std::vector<RTLIL::State> data;
2476 bool param_upto = current_scope[str]->range_valid && current_scope[str]->range_swapped;
2477 int param_offset = current_scope[str]->range_valid ? current_scope[str]->range_right : 0;
2478 int param_width = current_scope[str]->range_valid ? current_scope[str]->range_left - current_scope[str]->range_right + 1 :
2479 GetSize(current_scope[str]->children[0]->bits);
2480 int tmp_range_left = children[0]->range_left, tmp_range_right = children[0]->range_right;
2481 if (param_upto) {
2482 tmp_range_left = (param_width + 2*param_offset) - children[0]->range_right - 1;
2483 tmp_range_right = (param_width + 2*param_offset) - children[0]->range_left - 1;
2484 }
2485 for (int i = tmp_range_right; i <= tmp_range_left; i++) {
2486 int index = i - param_offset;
2487 if (0 <= index && index < param_width)
2488 data.push_back(current_scope[str]->children[0]->bits[index]);
2489 else
2490 data.push_back(RTLIL::State::Sx);
2491 }
2492 newNode = mkconst_bits(data, false);
2493 } else
2494 if (children.size() == 0)
2495 newNode = current_scope[str]->children[0]->clone();
2496 } else
2497 if (current_scope[str]->children[0]->isConst())
2498 newNode = current_scope[str]->children[0]->clone();
2499 }
2500 else if (at_zero && current_scope.count(str) > 0 && (current_scope[str]->type == AST_WIRE || current_scope[str]->type == AST_AUTOWIRE)) {
2501 newNode = mkconst_int(0, sign_hint, width_hint);
2502 }
2503 break;
2504 case AST_BIT_NOT:
2505 if (children[0]->type == AST_CONSTANT) {
2506 RTLIL::Const y = RTLIL::const_not(children[0]->bitsAsConst(width_hint, sign_hint), dummy_arg, sign_hint, false, width_hint);
2507 newNode = mkconst_bits(y.bits, sign_hint);
2508 }
2509 break;
2510 case AST_TO_SIGNED:
2511 case AST_TO_UNSIGNED:
2512 if (children[0]->type == AST_CONSTANT) {
2513 RTLIL::Const y = children[0]->bitsAsConst(width_hint, sign_hint);
2514 newNode = mkconst_bits(y.bits, type == AST_TO_SIGNED);
2515 }
2516 break;
2517 if (0) { case AST_BIT_AND: const_func = RTLIL::const_and; }
2518 if (0) { case AST_BIT_OR: const_func = RTLIL::const_or; }
2519 if (0) { case AST_BIT_XOR: const_func = RTLIL::const_xor; }
2520 if (0) { case AST_BIT_XNOR: const_func = RTLIL::const_xnor; }
2521 if (children[0]->type == AST_CONSTANT && children[1]->type == AST_CONSTANT) {
2522 RTLIL::Const y = const_func(children[0]->bitsAsConst(width_hint, sign_hint),
2523 children[1]->bitsAsConst(width_hint, sign_hint), sign_hint, sign_hint, width_hint);
2524 newNode = mkconst_bits(y.bits, sign_hint);
2525 }
2526 break;
2527 if (0) { case AST_REDUCE_AND: const_func = RTLIL::const_reduce_and; }
2528 if (0) { case AST_REDUCE_OR: const_func = RTLIL::const_reduce_or; }
2529 if (0) { case AST_REDUCE_XOR: const_func = RTLIL::const_reduce_xor; }
2530 if (0) { case AST_REDUCE_XNOR: const_func = RTLIL::const_reduce_xnor; }
2531 if (0) { case AST_REDUCE_BOOL: const_func = RTLIL::const_reduce_bool; }
2532 if (children[0]->type == AST_CONSTANT) {
2533 RTLIL::Const y = const_func(RTLIL::Const(children[0]->bits), dummy_arg, false, false, -1);
2534 newNode = mkconst_bits(y.bits, false);
2535 }
2536 break;
2537 case AST_LOGIC_NOT:
2538 if (children[0]->type == AST_CONSTANT) {
2539 RTLIL::Const y = RTLIL::const_logic_not(RTLIL::Const(children[0]->bits), dummy_arg, children[0]->is_signed, false, -1);
2540 newNode = mkconst_bits(y.bits, false);
2541 } else
2542 if (children[0]->isConst()) {
2543 newNode = mkconst_int(children[0]->asReal(sign_hint) == 0, false, 1);
2544 }
2545 break;
2546 if (0) { case AST_LOGIC_AND: const_func = RTLIL::const_logic_and; }
2547 if (0) { case AST_LOGIC_OR: const_func = RTLIL::const_logic_or; }
2548 if (children[0]->type == AST_CONSTANT && children[1]->type == AST_CONSTANT) {
2549 RTLIL::Const y = const_func(RTLIL::Const(children[0]->bits), RTLIL::Const(children[1]->bits),
2550 children[0]->is_signed, children[1]->is_signed, -1);
2551 newNode = mkconst_bits(y.bits, false);
2552 } else
2553 if (children[0]->isConst() && children[1]->isConst()) {
2554 if (type == AST_LOGIC_AND)
2555 newNode = mkconst_int((children[0]->asReal(sign_hint) != 0) && (children[1]->asReal(sign_hint) != 0), false, 1);
2556 else
2557 newNode = mkconst_int((children[0]->asReal(sign_hint) != 0) || (children[1]->asReal(sign_hint) != 0), false, 1);
2558 }
2559 break;
2560 if (0) { case AST_SHIFT_LEFT: const_func = RTLIL::const_shl; }
2561 if (0) { case AST_SHIFT_RIGHT: const_func = RTLIL::const_shr; }
2562 if (0) { case AST_SHIFT_SLEFT: const_func = RTLIL::const_sshl; }
2563 if (0) { case AST_SHIFT_SRIGHT: const_func = RTLIL::const_sshr; }
2564 if (0) { case AST_POW: const_func = RTLIL::const_pow; }
2565 if (children[0]->type == AST_CONSTANT && children[1]->type == AST_CONSTANT) {
2566 RTLIL::Const y = const_func(children[0]->bitsAsConst(width_hint, sign_hint),
2567 RTLIL::Const(children[1]->bits), sign_hint, type == AST_POW ? children[1]->is_signed : false, width_hint);
2568 newNode = mkconst_bits(y.bits, sign_hint);
2569 } else
2570 if (type == AST_POW && children[0]->isConst() && children[1]->isConst()) {
2571 newNode = new AstNode(AST_REALVALUE);
2572 newNode->realvalue = pow(children[0]->asReal(sign_hint), children[1]->asReal(sign_hint));
2573 }
2574 break;
2575 if (0) { case AST_LT: const_func = RTLIL::const_lt; }
2576 if (0) { case AST_LE: const_func = RTLIL::const_le; }
2577 if (0) { case AST_EQ: const_func = RTLIL::const_eq; }
2578 if (0) { case AST_NE: const_func = RTLIL::const_ne; }
2579 if (0) { case AST_EQX: const_func = RTLIL::const_eqx; }
2580 if (0) { case AST_NEX: const_func = RTLIL::const_nex; }
2581 if (0) { case AST_GE: const_func = RTLIL::const_ge; }
2582 if (0) { case AST_GT: const_func = RTLIL::const_gt; }
2583 if (children[0]->type == AST_CONSTANT && children[1]->type == AST_CONSTANT) {
2584 int cmp_width = max(children[0]->bits.size(), children[1]->bits.size());
2585 bool cmp_signed = children[0]->is_signed && children[1]->is_signed;
2586 RTLIL::Const y = const_func(children[0]->bitsAsConst(cmp_width, cmp_signed),
2587 children[1]->bitsAsConst(cmp_width, cmp_signed), cmp_signed, cmp_signed, 1);
2588 newNode = mkconst_bits(y.bits, false);
2589 } else
2590 if (children[0]->isConst() && children[1]->isConst()) {
2591 bool cmp_signed = (children[0]->type == AST_REALVALUE || children[0]->is_signed) && (children[1]->type == AST_REALVALUE || children[1]->is_signed);
2592 switch (type) {
2593 case AST_LT: newNode = mkconst_int(children[0]->asReal(cmp_signed) < children[1]->asReal(cmp_signed), false, 1); break;
2594 case AST_LE: newNode = mkconst_int(children[0]->asReal(cmp_signed) <= children[1]->asReal(cmp_signed), false, 1); break;
2595 case AST_EQ: newNode = mkconst_int(children[0]->asReal(cmp_signed) == children[1]->asReal(cmp_signed), false, 1); break;
2596 case AST_NE: newNode = mkconst_int(children[0]->asReal(cmp_signed) != children[1]->asReal(cmp_signed), false, 1); break;
2597 case AST_EQX: newNode = mkconst_int(children[0]->asReal(cmp_signed) == children[1]->asReal(cmp_signed), false, 1); break;
2598 case AST_NEX: newNode = mkconst_int(children[0]->asReal(cmp_signed) != children[1]->asReal(cmp_signed), false, 1); break;
2599 case AST_GE: newNode = mkconst_int(children[0]->asReal(cmp_signed) >= children[1]->asReal(cmp_signed), false, 1); break;
2600 case AST_GT: newNode = mkconst_int(children[0]->asReal(cmp_signed) > children[1]->asReal(cmp_signed), false, 1); break;
2601 default: log_abort();
2602 }
2603 }
2604 break;
2605 if (0) { case AST_ADD: const_func = RTLIL::const_add; }
2606 if (0) { case AST_SUB: const_func = RTLIL::const_sub; }
2607 if (0) { case AST_MUL: const_func = RTLIL::const_mul; }
2608 if (0) { case AST_DIV: const_func = RTLIL::const_div; }
2609 if (0) { case AST_MOD: const_func = RTLIL::const_mod; }
2610 if (children[0]->type == AST_CONSTANT && children[1]->type == AST_CONSTANT) {
2611 RTLIL::Const y = const_func(children[0]->bitsAsConst(width_hint, sign_hint),
2612 children[1]->bitsAsConst(width_hint, sign_hint), sign_hint, sign_hint, width_hint);
2613 newNode = mkconst_bits(y.bits, sign_hint);
2614 } else
2615 if (children[0]->isConst() && children[1]->isConst()) {
2616 newNode = new AstNode(AST_REALVALUE);
2617 switch (type) {
2618 case AST_ADD: newNode->realvalue = children[0]->asReal(sign_hint) + children[1]->asReal(sign_hint); break;
2619 case AST_SUB: newNode->realvalue = children[0]->asReal(sign_hint) - children[1]->asReal(sign_hint); break;
2620 case AST_MUL: newNode->realvalue = children[0]->asReal(sign_hint) * children[1]->asReal(sign_hint); break;
2621 case AST_DIV: newNode->realvalue = children[0]->asReal(sign_hint) / children[1]->asReal(sign_hint); break;
2622 case AST_MOD: newNode->realvalue = fmod(children[0]->asReal(sign_hint), children[1]->asReal(sign_hint)); break;
2623 default: log_abort();
2624 }
2625 }
2626 break;
2627 if (0) { case AST_POS: const_func = RTLIL::const_pos; }
2628 if (0) { case AST_NEG: const_func = RTLIL::const_neg; }
2629 if (children[0]->type == AST_CONSTANT) {
2630 RTLIL::Const y = const_func(children[0]->bitsAsConst(width_hint, sign_hint), dummy_arg, sign_hint, false, width_hint);
2631 newNode = mkconst_bits(y.bits, sign_hint);
2632 } else
2633 if (children[0]->isConst()) {
2634 newNode = new AstNode(AST_REALVALUE);
2635 if (type == AST_POS)
2636 newNode->realvalue = +children[0]->asReal(sign_hint);
2637 else
2638 newNode->realvalue = -children[0]->asReal(sign_hint);
2639 }
2640 break;
2641 case AST_TERNARY:
2642 if (children[0]->isConst())
2643 {
2644 bool found_sure_true = false;
2645 bool found_maybe_true = false;
2646
2647 if (children[0]->type == AST_CONSTANT)
2648 for (auto &bit : children[0]->bits) {
2649 if (bit == RTLIL::State::S1)
2650 found_sure_true = true;
2651 if (bit > RTLIL::State::S1)
2652 found_maybe_true = true;
2653 }
2654 else
2655 found_sure_true = children[0]->asReal(sign_hint) != 0;
2656
2657 AstNode *choice = NULL, *not_choice = NULL;
2658 if (found_sure_true)
2659 choice = children[1], not_choice = children[2];
2660 else if (!found_maybe_true)
2661 choice = children[2], not_choice = children[1];
2662
2663 if (choice != NULL) {
2664 if (choice->type == AST_CONSTANT) {
2665 int other_width_hint = width_hint;
2666 bool other_sign_hint = sign_hint, other_real = false;
2667 not_choice->detectSignWidth(other_width_hint, other_sign_hint, &other_real);
2668 if (other_real) {
2669 newNode = new AstNode(AST_REALVALUE);
2670 choice->detectSignWidth(width_hint, sign_hint);
2671 newNode->realvalue = choice->asReal(sign_hint);
2672 } else {
2673 RTLIL::Const y = choice->bitsAsConst(width_hint, sign_hint);
2674 if (choice->is_string && y.bits.size() % 8 == 0 && sign_hint == false)
2675 newNode = mkconst_str(y.bits);
2676 else
2677 newNode = mkconst_bits(y.bits, sign_hint);
2678 }
2679 } else
2680 if (choice->isConst()) {
2681 newNode = choice->clone();
2682 }
2683 } else if (children[1]->type == AST_CONSTANT && children[2]->type == AST_CONSTANT) {
2684 RTLIL::Const a = children[1]->bitsAsConst(width_hint, sign_hint);
2685 RTLIL::Const b = children[2]->bitsAsConst(width_hint, sign_hint);
2686 log_assert(a.bits.size() == b.bits.size());
2687 for (size_t i = 0; i < a.bits.size(); i++)
2688 if (a.bits[i] != b.bits[i])
2689 a.bits[i] = RTLIL::State::Sx;
2690 newNode = mkconst_bits(a.bits, sign_hint);
2691 } else if (children[1]->isConst() && children[2]->isConst()) {
2692 newNode = new AstNode(AST_REALVALUE);
2693 if (children[1]->asReal(sign_hint) == children[2]->asReal(sign_hint))
2694 newNode->realvalue = children[1]->asReal(sign_hint);
2695 else
2696 // IEEE Std 1800-2012 Sec. 11.4.11 states that the entry in Table 7-1 for
2697 // the data type in question should be returned if the ?: is ambiguous. The
2698 // value in Table 7-1 for the 'real' type is 0.0.
2699 newNode->realvalue = 0.0;
2700 }
2701 }
2702 break;
2703 case AST_CONCAT:
2704 string_op = !children.empty();
2705 for (auto it = children.begin(); it != children.end(); it++) {
2706 if ((*it)->type != AST_CONSTANT)
2707 goto not_const;
2708 if (!(*it)->is_string)
2709 string_op = false;
2710 tmp_bits.insert(tmp_bits.end(), (*it)->bits.begin(), (*it)->bits.end());
2711 }
2712 newNode = string_op ? mkconst_str(tmp_bits) : mkconst_bits(tmp_bits, false);
2713 break;
2714 case AST_REPLICATE:
2715 if (children.at(0)->type != AST_CONSTANT || children.at(1)->type != AST_CONSTANT)
2716 goto not_const;
2717 for (int i = 0; i < children[0]->bitsAsConst().as_int(); i++)
2718 tmp_bits.insert(tmp_bits.end(), children.at(1)->bits.begin(), children.at(1)->bits.end());
2719 newNode = children.at(1)->is_string ? mkconst_str(tmp_bits) : mkconst_bits(tmp_bits, false);
2720 break;
2721 default:
2722 not_const:
2723 break;
2724 }
2725 }
2726
2727 // if any of the above set 'newNode' -> use 'newNode' as template to update 'this'
2728 if (newNode) {
2729 apply_newNode:
2730 // fprintf(stderr, "----\n");
2731 // dumpAst(stderr, "- ");
2732 // newNode->dumpAst(stderr, "+ ");
2733 log_assert(newNode != NULL);
2734 newNode->filename = filename;
2735 newNode->linenum = linenum;
2736 newNode->cloneInto(this);
2737 delete newNode;
2738 did_something = true;
2739 }
2740
2741 if (!did_something)
2742 basic_prep = true;
2743
2744 recursion_counter--;
2745 return did_something;
2746 }
2747
2748 static void replace_result_wire_name_in_function(AstNode *node, std::string &from, std::string &to)
2749 {
2750 for (auto &it : node->children)
2751 replace_result_wire_name_in_function(it, from, to);
2752 if (node->str == from)
2753 node->str = to;
2754 }
2755
2756 // replace a readmem[bh] TCALL ast node with a block of memory assignments
2757 AstNode *AstNode::readmem(bool is_readmemh, std::string mem_filename, AstNode *memory, int start_addr, int finish_addr, bool unconditional_init)
2758 {
2759 int mem_width, mem_size, addr_bits;
2760 memory->meminfo(mem_width, mem_size, addr_bits);
2761
2762 AstNode *block = new AstNode(AST_BLOCK);
2763
2764 AstNode *meminit = nullptr;
2765 int next_meminit_cursor=0;
2766 vector<State> meminit_bits;
2767 int meminit_size=0;
2768
2769 std::ifstream f;
2770 f.open(mem_filename.c_str());
2771 yosys_input_files.insert(mem_filename);
2772
2773 if (f.fail())
2774 log_file_error(filename, linenum, "Can not open file `%s` for %s.\n", mem_filename.c_str(), str.c_str());
2775
2776 log_assert(GetSize(memory->children) == 2 && memory->children[1]->type == AST_RANGE && memory->children[1]->range_valid);
2777 int range_left = memory->children[1]->range_left, range_right = memory->children[1]->range_right;
2778 int range_min = min(range_left, range_right), range_max = max(range_left, range_right);
2779
2780 if (start_addr < 0)
2781 start_addr = range_min;
2782
2783 if (finish_addr < 0)
2784 finish_addr = range_max + 1;
2785
2786 bool in_comment = false;
2787 int increment = start_addr <= finish_addr ? +1 : -1;
2788 int cursor = start_addr;
2789
2790 while (!f.eof())
2791 {
2792 std::string line, token;
2793 std::getline(f, line);
2794
2795 for (int i = 0; i < GetSize(line); i++) {
2796 if (in_comment && line.substr(i, 2) == "*/") {
2797 line[i] = ' ';
2798 line[i+1] = ' ';
2799 in_comment = false;
2800 continue;
2801 }
2802 if (!in_comment && line.substr(i, 2) == "/*")
2803 in_comment = true;
2804 if (in_comment)
2805 line[i] = ' ';
2806 }
2807
2808 while (1)
2809 {
2810 token = next_token(line, " \t\r\n");
2811 if (token.empty() || token.substr(0, 2) == "//")
2812 break;
2813
2814 if (token[0] == '@') {
2815 token = token.substr(1);
2816 const char *nptr = token.c_str();
2817 char *endptr;
2818 cursor = strtol(nptr, &endptr, 16);
2819 if (!*nptr || *endptr)
2820 log_file_error(filename, linenum, "Can not parse address `%s` for %s.\n", nptr, str.c_str());
2821 continue;
2822 }
2823
2824 AstNode *value = VERILOG_FRONTEND::const2ast(stringf("%d'%c", mem_width, is_readmemh ? 'h' : 'b') + token);
2825
2826 if (unconditional_init)
2827 {
2828 if (meminit == nullptr || cursor != next_meminit_cursor)
2829 {
2830 if (meminit != nullptr) {
2831 meminit->children[1] = AstNode::mkconst_bits(meminit_bits, false);
2832 meminit->children[2] = AstNode::mkconst_int(meminit_size, false);
2833 }
2834
2835 meminit = new AstNode(AST_MEMINIT);
2836 meminit->children.push_back(AstNode::mkconst_int(cursor, false));
2837 meminit->children.push_back(nullptr);
2838 meminit->children.push_back(nullptr);
2839 meminit->str = memory->str;
2840 meminit->id2ast = memory;
2841 meminit_bits.clear();
2842 meminit_size = 0;
2843
2844 current_ast_mod->children.push_back(meminit);
2845 next_meminit_cursor = cursor;
2846 }
2847
2848 meminit_size++;
2849 next_meminit_cursor++;
2850 meminit_bits.insert(meminit_bits.end(), value->bits.begin(), value->bits.end());
2851 delete value;
2852 }
2853 else
2854 {
2855 block->children.push_back(new AstNode(AST_ASSIGN_EQ, new AstNode(AST_IDENTIFIER, new AstNode(AST_RANGE, AstNode::mkconst_int(cursor, false))), value));
2856 block->children.back()->children[0]->str = memory->str;
2857 block->children.back()->children[0]->id2ast = memory;
2858 block->children.back()->children[0]->was_checked = true;
2859 }
2860
2861 cursor += increment;
2862 if ((cursor == finish_addr+increment) || (increment > 0 && cursor > range_max) || (increment < 0 && cursor < range_min))
2863 break;
2864 }
2865
2866 if ((cursor == finish_addr+increment) || (increment > 0 && cursor > range_max) || (increment < 0 && cursor < range_min))
2867 break;
2868 }
2869
2870 if (meminit != nullptr) {
2871 meminit->children[1] = AstNode::mkconst_bits(meminit_bits, false);
2872 meminit->children[2] = AstNode::mkconst_int(meminit_size, false);
2873 }
2874
2875 return block;
2876 }
2877
2878 // annotate the names of all wires and other named objects in a generate block
2879 void AstNode::expand_genblock(std::string index_var, std::string prefix, std::map<std::string, std::string> &name_map)
2880 {
2881 if (!index_var.empty() && type == AST_IDENTIFIER && str == index_var) {
2882 current_scope[index_var]->children[0]->cloneInto(this);
2883 return;
2884 }
2885
2886 if ((type == AST_IDENTIFIER || type == AST_FCALL || type == AST_TCALL) && name_map.count(str) > 0)
2887 str = name_map[str];
2888
2889 std::map<std::string, std::string> backup_name_map;
2890
2891 for (size_t i = 0; i < children.size(); i++) {
2892 AstNode *child = children[i];
2893 if (child->type == AST_WIRE || child->type == AST_MEMORY || child->type == AST_PARAMETER || child->type == AST_LOCALPARAM ||
2894 child->type == AST_FUNCTION || child->type == AST_TASK || child->type == AST_CELL) {
2895 if (backup_name_map.size() == 0)
2896 backup_name_map = name_map;
2897 std::string new_name = prefix[0] == '\\' ? prefix.substr(1) : prefix;
2898 size_t pos = child->str.rfind('.');
2899 if (pos == std::string::npos)
2900 pos = child->str[0] == '\\' && prefix[0] == '\\' ? 1 : 0;
2901 else
2902 pos = pos + 1;
2903 new_name = child->str.substr(0, pos) + new_name + child->str.substr(pos);
2904 if (new_name[0] != '$' && new_name[0] != '\\')
2905 new_name = prefix[0] + new_name;
2906 name_map[child->str] = new_name;
2907 if (child->type == AST_FUNCTION)
2908 replace_result_wire_name_in_function(child, child->str, new_name);
2909 else
2910 child->str = new_name;
2911 current_scope[new_name] = child;
2912 }
2913 }
2914
2915 for (size_t i = 0; i < children.size(); i++) {
2916 AstNode *child = children[i];
2917 // AST_PREFIX member names should not be prefixed; a nested AST_PREFIX
2918 // still needs to recursed-into
2919 if (type == AST_PREFIX && i == 1 && child->type == AST_IDENTIFIER)
2920 continue;
2921 if (child->type != AST_FUNCTION && child->type != AST_TASK)
2922 child->expand_genblock(index_var, prefix, name_map);
2923 }
2924
2925 if (backup_name_map.size() > 0)
2926 name_map.swap(backup_name_map);
2927 }
2928
2929 // rename stuff (used when tasks of functions are instantiated)
2930 void AstNode::replace_ids(const std::string &prefix, const std::map<std::string, std::string> &rules)
2931 {
2932 if (type == AST_BLOCK)
2933 {
2934 std::map<std::string, std::string> new_rules = rules;
2935 std::string new_prefix = prefix + str;
2936
2937 for (auto child : children)
2938 if (child->type == AST_WIRE) {
2939 new_rules[child->str] = new_prefix + child->str;
2940 child->str = new_prefix + child->str;
2941 }
2942
2943 for (auto child : children)
2944 if (child->type != AST_WIRE)
2945 child->replace_ids(new_prefix, new_rules);
2946 }
2947 else
2948 {
2949 if (type == AST_IDENTIFIER && rules.count(str) > 0)
2950 str = rules.at(str);
2951 for (auto child : children)
2952 child->replace_ids(prefix, rules);
2953 }
2954 }
2955
2956 // helper function for mem2reg_as_needed_pass1
2957 static void mark_memories_assign_lhs_complex(dict<AstNode*, pool<std::string>> &mem2reg_places,
2958 dict<AstNode*, uint32_t> &mem2reg_candidates, AstNode *that)
2959 {
2960 for (auto &child : that->children)
2961 mark_memories_assign_lhs_complex(mem2reg_places, mem2reg_candidates, child);
2962
2963 if (that->type == AST_IDENTIFIER && that->id2ast && that->id2ast->type == AST_MEMORY) {
2964 AstNode *mem = that->id2ast;
2965 if (!(mem2reg_candidates[mem] & AstNode::MEM2REG_FL_CMPLX_LHS))
2966 mem2reg_places[mem].insert(stringf("%s:%d", that->filename.c_str(), that->linenum));
2967 mem2reg_candidates[mem] |= AstNode::MEM2REG_FL_CMPLX_LHS;
2968 }
2969 }
2970
2971 // find memories that should be replaced by registers
2972 void AstNode::mem2reg_as_needed_pass1(dict<AstNode*, pool<std::string>> &mem2reg_places,
2973 dict<AstNode*, uint32_t> &mem2reg_candidates, dict<AstNode*, uint32_t> &proc_flags, uint32_t &flags)
2974 {
2975 uint32_t children_flags = 0;
2976 int lhs_children_counter = 0;
2977
2978 if (type == AST_ASSIGN || type == AST_ASSIGN_LE || type == AST_ASSIGN_EQ)
2979 {
2980 // mark all memories that are used in a complex expression on the left side of an assignment
2981 for (auto &lhs_child : children[0]->children)
2982 mark_memories_assign_lhs_complex(mem2reg_places, mem2reg_candidates, lhs_child);
2983
2984 if (children[0]->type == AST_IDENTIFIER && children[0]->id2ast && children[0]->id2ast->type == AST_MEMORY)
2985 {
2986 AstNode *mem = children[0]->id2ast;
2987
2988 // activate mem2reg if this is assigned in an async proc
2989 if (flags & AstNode::MEM2REG_FL_ASYNC) {
2990 if (!(mem2reg_candidates[mem] & AstNode::MEM2REG_FL_SET_ASYNC))
2991 mem2reg_places[mem].insert(stringf("%s:%d", filename.c_str(), linenum));
2992 mem2reg_candidates[mem] |= AstNode::MEM2REG_FL_SET_ASYNC;
2993 }
2994
2995 // remember if this is assigned blocking (=)
2996 if (type == AST_ASSIGN_EQ) {
2997 if (!(proc_flags[mem] & AstNode::MEM2REG_FL_EQ1))
2998 mem2reg_places[mem].insert(stringf("%s:%d", filename.c_str(), linenum));
2999 proc_flags[mem] |= AstNode::MEM2REG_FL_EQ1;
3000 }
3001
3002 // for proper (non-init) writes: remember if this is a constant index or not
3003 if ((flags & MEM2REG_FL_INIT) == 0) {
3004 if (children[0]->children.size() && children[0]->children[0]->type == AST_RANGE && children[0]->children[0]->children.size()) {
3005 if (children[0]->children[0]->children[0]->type == AST_CONSTANT)
3006 mem2reg_candidates[mem] |= AstNode::MEM2REG_FL_CONST_LHS;
3007 else
3008 mem2reg_candidates[mem] |= AstNode::MEM2REG_FL_VAR_LHS;
3009 }
3010 }
3011
3012 // remember where this is
3013 if (flags & MEM2REG_FL_INIT) {
3014 if (!(mem2reg_candidates[mem] & AstNode::MEM2REG_FL_SET_INIT))
3015 mem2reg_places[mem].insert(stringf("%s:%d", filename.c_str(), linenum));
3016 mem2reg_candidates[mem] |= AstNode::MEM2REG_FL_SET_INIT;
3017 } else {
3018 if (!(mem2reg_candidates[mem] & AstNode::MEM2REG_FL_SET_ELSE))
3019 mem2reg_places[mem].insert(stringf("%s:%d", filename.c_str(), linenum));
3020 mem2reg_candidates[mem] |= AstNode::MEM2REG_FL_SET_ELSE;
3021 }
3022 }
3023
3024 lhs_children_counter = 1;
3025 }
3026
3027 if (type == AST_IDENTIFIER && id2ast && id2ast->type == AST_MEMORY)
3028 {
3029 AstNode *mem = id2ast;
3030
3031 // flag if used after blocking assignment (in same proc)
3032 if ((proc_flags[mem] & AstNode::MEM2REG_FL_EQ1) && !(mem2reg_candidates[mem] & AstNode::MEM2REG_FL_EQ2)) {
3033 mem2reg_places[mem].insert(stringf("%s:%d", filename.c_str(), linenum));
3034 mem2reg_candidates[mem] |= AstNode::MEM2REG_FL_EQ2;
3035 }
3036 }
3037
3038 // also activate if requested, either by using mem2reg attribute or by declaring array as 'wire' instead of 'reg'
3039 if (type == AST_MEMORY && (get_bool_attribute("\\mem2reg") || (flags & AstNode::MEM2REG_FL_ALL) || !is_reg))
3040 mem2reg_candidates[this] |= AstNode::MEM2REG_FL_FORCED;
3041
3042 if (type == AST_MODULE && get_bool_attribute("\\mem2reg"))
3043 children_flags |= AstNode::MEM2REG_FL_ALL;
3044
3045 dict<AstNode*, uint32_t> *proc_flags_p = NULL;
3046
3047 if (type == AST_ALWAYS) {
3048 int count_edge_events = 0;
3049 for (auto child : children)
3050 if (child->type == AST_POSEDGE || child->type == AST_NEGEDGE)
3051 count_edge_events++;
3052 if (count_edge_events != 1)
3053 children_flags |= AstNode::MEM2REG_FL_ASYNC;
3054 proc_flags_p = new dict<AstNode*, uint32_t>;
3055 }
3056
3057 if (type == AST_INITIAL) {
3058 children_flags |= AstNode::MEM2REG_FL_INIT;
3059 proc_flags_p = new dict<AstNode*, uint32_t>;
3060 }
3061
3062 uint32_t backup_flags = flags;
3063 flags |= children_flags;
3064 log_assert((flags & ~0x000000ff) == 0);
3065
3066 for (auto child : children)
3067 {
3068 if (lhs_children_counter > 0) {
3069 lhs_children_counter--;
3070 if (child->children.size() && child->children[0]->type == AST_RANGE && child->children[0]->children.size()) {
3071 for (auto c : child->children[0]->children) {
3072 if (proc_flags_p)
3073 c->mem2reg_as_needed_pass1(mem2reg_places, mem2reg_candidates, *proc_flags_p, flags);
3074 else
3075 c->mem2reg_as_needed_pass1(mem2reg_places, mem2reg_candidates, proc_flags, flags);
3076 }
3077 }
3078 } else
3079 if (proc_flags_p)
3080 child->mem2reg_as_needed_pass1(mem2reg_places, mem2reg_candidates, *proc_flags_p, flags);
3081 else
3082 child->mem2reg_as_needed_pass1(mem2reg_places, mem2reg_candidates, proc_flags, flags);
3083 }
3084
3085 flags &= ~children_flags | backup_flags;
3086
3087 if (proc_flags_p) {
3088 #ifndef NDEBUG
3089 for (auto it : *proc_flags_p)
3090 log_assert((it.second & ~0xff000000) == 0);
3091 #endif
3092 delete proc_flags_p;
3093 }
3094 }
3095
3096 bool AstNode::mem2reg_check(pool<AstNode*> &mem2reg_set)
3097 {
3098 if (type != AST_IDENTIFIER || !id2ast || !mem2reg_set.count(id2ast))
3099 return false;
3100
3101 if (children.empty() || children[0]->type != AST_RANGE || GetSize(children[0]->children) != 1)
3102 log_file_error(filename, linenum, "Invalid array access.\n");
3103
3104 return true;
3105 }
3106
3107 void AstNode::mem2reg_remove(pool<AstNode*> &mem2reg_set, vector<AstNode*> &delnodes)
3108 {
3109 log_assert(mem2reg_set.count(this) == 0);
3110
3111 if (mem2reg_set.count(id2ast))
3112 id2ast = nullptr;
3113
3114 for (size_t i = 0; i < children.size(); i++) {
3115 if (mem2reg_set.count(children[i]) > 0) {
3116 delnodes.push_back(children[i]);
3117 children.erase(children.begin() + (i--));
3118 } else {
3119 children[i]->mem2reg_remove(mem2reg_set, delnodes);
3120 }
3121 }
3122 }
3123
3124 // actually replace memories with registers
3125 bool AstNode::mem2reg_as_needed_pass2(pool<AstNode*> &mem2reg_set, AstNode *mod, AstNode *block, AstNode *&async_block)
3126 {
3127 bool did_something = false;
3128
3129 if (type == AST_BLOCK)
3130 block = this;
3131
3132 if (type == AST_FUNCTION || type == AST_TASK)
3133 return false;
3134
3135 if (type == AST_MEMINIT && id2ast && mem2reg_set.count(id2ast))
3136 {
3137 log_assert(children[0]->type == AST_CONSTANT);
3138 log_assert(children[1]->type == AST_CONSTANT);
3139 log_assert(children[2]->type == AST_CONSTANT);
3140
3141 int cursor = children[0]->asInt(false);
3142 Const data = children[1]->bitsAsConst();
3143 int length = children[2]->asInt(false);
3144
3145 if (length != 0)
3146 {
3147 AstNode *block = new AstNode(AST_INITIAL, new AstNode(AST_BLOCK));
3148 mod->children.push_back(block);
3149 block = block->children[0];
3150
3151 int wordsz = GetSize(data) / length;
3152
3153 for (int i = 0; i < length; i++) {
3154 block->children.push_back(new AstNode(AST_ASSIGN_EQ, new AstNode(AST_IDENTIFIER, new AstNode(AST_RANGE, AstNode::mkconst_int(cursor+i, false))), mkconst_bits(data.extract(i*wordsz, wordsz).bits, false)));
3155 block->children.back()->children[0]->str = str;
3156 block->children.back()->children[0]->id2ast = id2ast;
3157 block->children.back()->children[0]->was_checked = true;
3158 }
3159 }
3160
3161 AstNode *newNode = new AstNode(AST_NONE);
3162 newNode->cloneInto(this);
3163 delete newNode;
3164
3165 did_something = true;
3166 }
3167
3168 if (type == AST_ASSIGN && block == NULL && children[0]->mem2reg_check(mem2reg_set))
3169 {
3170 if (async_block == NULL) {
3171 async_block = new AstNode(AST_ALWAYS, new AstNode(AST_BLOCK));
3172 mod->children.push_back(async_block);
3173 }
3174
3175 AstNode *newNode = clone();
3176 newNode->type = AST_ASSIGN_EQ;
3177 newNode->children[0]->was_checked = true;
3178 async_block->children[0]->children.push_back(newNode);
3179
3180 newNode = new AstNode(AST_NONE);
3181 newNode->cloneInto(this);
3182 delete newNode;
3183
3184 did_something = true;
3185 }
3186
3187 if ((type == AST_ASSIGN_LE || type == AST_ASSIGN_EQ) && children[0]->mem2reg_check(mem2reg_set) &&
3188 children[0]->children[0]->children[0]->type != AST_CONSTANT)
3189 {
3190 std::stringstream sstr;
3191 sstr << "$mem2reg_wr$" << children[0]->str << "$" << filename << ":" << linenum << "$" << (autoidx++);
3192 std::string id_addr = sstr.str() + "_ADDR", id_data = sstr.str() + "_DATA";
3193
3194 int mem_width, mem_size, addr_bits;
3195 bool mem_signed = children[0]->id2ast->is_signed;
3196 children[0]->id2ast->meminfo(mem_width, mem_size, addr_bits);
3197
3198 AstNode *wire_addr = new AstNode(AST_WIRE, new AstNode(AST_RANGE, mkconst_int(addr_bits-1, true), mkconst_int(0, true)));
3199 wire_addr->str = id_addr;
3200 wire_addr->is_reg = true;
3201 wire_addr->was_checked = true;
3202 wire_addr->attributes["\\nosync"] = AstNode::mkconst_int(1, false);
3203 mod->children.push_back(wire_addr);
3204 while (wire_addr->simplify(true, false, false, 1, -1, false, false)) { }
3205
3206 AstNode *wire_data = new AstNode(AST_WIRE, new AstNode(AST_RANGE, mkconst_int(mem_width-1, true), mkconst_int(0, true)));
3207 wire_data->str = id_data;
3208 wire_data->is_reg = true;
3209 wire_data->was_checked = true;
3210 wire_data->is_signed = mem_signed;
3211 wire_data->attributes["\\nosync"] = AstNode::mkconst_int(1, false);
3212 mod->children.push_back(wire_data);
3213 while (wire_data->simplify(true, false, false, 1, -1, false, false)) { }
3214
3215 log_assert(block != NULL);
3216 size_t assign_idx = 0;
3217 while (assign_idx < block->children.size() && block->children[assign_idx] != this)
3218 assign_idx++;
3219 log_assert(assign_idx < block->children.size());
3220
3221 AstNode *assign_addr = new AstNode(AST_ASSIGN_EQ, new AstNode(AST_IDENTIFIER), children[0]->children[0]->children[0]->clone());
3222 assign_addr->children[0]->str = id_addr;
3223 assign_addr->children[0]->was_checked = true;
3224 block->children.insert(block->children.begin()+assign_idx+1, assign_addr);
3225
3226 AstNode *case_node = new AstNode(AST_CASE, new AstNode(AST_IDENTIFIER));
3227 case_node->children[0]->str = id_addr;
3228 for (int i = 0; i < mem_size; i++) {
3229 if (children[0]->children[0]->children[0]->type == AST_CONSTANT && int(children[0]->children[0]->children[0]->integer) != i)
3230 continue;
3231 AstNode *cond_node = new AstNode(AST_COND, AstNode::mkconst_int(i, false, addr_bits), new AstNode(AST_BLOCK));
3232 AstNode *assign_reg = new AstNode(type, new AstNode(AST_IDENTIFIER), new AstNode(AST_IDENTIFIER));
3233 if (children[0]->children.size() == 2)
3234 assign_reg->children[0]->children.push_back(children[0]->children[1]->clone());
3235 assign_reg->children[0]->str = stringf("%s[%d]", children[0]->str.c_str(), i);
3236 assign_reg->children[1]->str = id_data;
3237 cond_node->children[1]->children.push_back(assign_reg);
3238 case_node->children.push_back(cond_node);
3239 }
3240 block->children.insert(block->children.begin()+assign_idx+2, case_node);
3241
3242 children[0]->delete_children();
3243 children[0]->range_valid = false;
3244 children[0]->id2ast = NULL;
3245 children[0]->str = id_data;
3246 type = AST_ASSIGN_EQ;
3247 children[0]->was_checked = true;
3248
3249 did_something = true;
3250 }
3251
3252 if (mem2reg_check(mem2reg_set))
3253 {
3254 AstNode *bit_part_sel = NULL;
3255 if (children.size() == 2)
3256 bit_part_sel = children[1]->clone();
3257
3258 if (children[0]->children[0]->type == AST_CONSTANT)
3259 {
3260 int id = children[0]->children[0]->integer;
3261 str = stringf("%s[%d]", str.c_str(), id);
3262
3263 delete_children();
3264 range_valid = false;
3265 id2ast = NULL;
3266 }
3267 else
3268 {
3269 std::stringstream sstr;
3270 sstr << "$mem2reg_rd$" << str << "$" << filename << ":" << linenum << "$" << (autoidx++);
3271 std::string id_addr = sstr.str() + "_ADDR", id_data = sstr.str() + "_DATA";
3272
3273 int mem_width, mem_size, addr_bits;
3274 bool mem_signed = id2ast->is_signed;
3275 id2ast->meminfo(mem_width, mem_size, addr_bits);
3276
3277 AstNode *wire_addr = new AstNode(AST_WIRE, new AstNode(AST_RANGE, mkconst_int(addr_bits-1, true), mkconst_int(0, true)));
3278 wire_addr->str = id_addr;
3279 wire_addr->is_reg = true;
3280 wire_addr->was_checked = true;
3281 if (block)
3282 wire_addr->attributes["\\nosync"] = AstNode::mkconst_int(1, false);
3283 mod->children.push_back(wire_addr);
3284 while (wire_addr->simplify(true, false, false, 1, -1, false, false)) { }
3285
3286 AstNode *wire_data = new AstNode(AST_WIRE, new AstNode(AST_RANGE, mkconst_int(mem_width-1, true), mkconst_int(0, true)));
3287 wire_data->str = id_data;
3288 wire_data->is_reg = true;
3289 wire_data->was_checked = true;
3290 wire_data->is_signed = mem_signed;
3291 if (block)
3292 wire_data->attributes["\\nosync"] = AstNode::mkconst_int(1, false);
3293 mod->children.push_back(wire_data);
3294 while (wire_data->simplify(true, false, false, 1, -1, false, false)) { }
3295
3296 AstNode *assign_addr = new AstNode(block ? AST_ASSIGN_EQ : AST_ASSIGN, new AstNode(AST_IDENTIFIER), children[0]->children[0]->clone());
3297 assign_addr->children[0]->str = id_addr;
3298 assign_addr->children[0]->was_checked = true;
3299
3300 AstNode *case_node = new AstNode(AST_CASE, new AstNode(AST_IDENTIFIER));
3301 case_node->children[0]->str = id_addr;
3302
3303 for (int i = 0; i < mem_size; i++) {
3304 if (children[0]->children[0]->type == AST_CONSTANT && int(children[0]->children[0]->integer) != i)
3305 continue;
3306 AstNode *cond_node = new AstNode(AST_COND, AstNode::mkconst_int(i, false, addr_bits), new AstNode(AST_BLOCK));
3307 AstNode *assign_reg = new AstNode(AST_ASSIGN_EQ, new AstNode(AST_IDENTIFIER), new AstNode(AST_IDENTIFIER));
3308 assign_reg->children[0]->str = id_data;
3309 assign_reg->children[0]->was_checked = true;
3310 assign_reg->children[1]->str = stringf("%s[%d]", str.c_str(), i);
3311 cond_node->children[1]->children.push_back(assign_reg);
3312 case_node->children.push_back(cond_node);
3313 }
3314
3315 std::vector<RTLIL::State> x_bits;
3316 for (int i = 0; i < mem_width; i++)
3317 x_bits.push_back(RTLIL::State::Sx);
3318
3319 AstNode *cond_node = new AstNode(AST_COND, new AstNode(AST_DEFAULT), new AstNode(AST_BLOCK));
3320 AstNode *assign_reg = new AstNode(AST_ASSIGN_EQ, new AstNode(AST_IDENTIFIER), AstNode::mkconst_bits(x_bits, false));
3321 assign_reg->children[0]->str = id_data;
3322 assign_reg->children[0]->was_checked = true;
3323 cond_node->children[1]->children.push_back(assign_reg);
3324 case_node->children.push_back(cond_node);
3325
3326 if (block)
3327 {
3328 size_t assign_idx = 0;
3329 while (assign_idx < block->children.size() && !block->children[assign_idx]->contains(this))
3330 assign_idx++;
3331 log_assert(assign_idx < block->children.size());
3332 block->children.insert(block->children.begin()+assign_idx, case_node);
3333 block->children.insert(block->children.begin()+assign_idx, assign_addr);
3334 }
3335 else
3336 {
3337 AstNode *proc = new AstNode(AST_ALWAYS, new AstNode(AST_BLOCK));
3338 proc->children[0]->children.push_back(case_node);
3339 mod->children.push_back(proc);
3340 mod->children.push_back(assign_addr);
3341 }
3342
3343 delete_children();
3344 range_valid = false;
3345 id2ast = NULL;
3346 str = id_data;
3347 }
3348
3349 if (bit_part_sel)
3350 children.push_back(bit_part_sel);
3351
3352 did_something = true;
3353 }
3354
3355 log_assert(id2ast == NULL || mem2reg_set.count(id2ast) == 0);
3356
3357 auto children_list = children;
3358 for (size_t i = 0; i < children_list.size(); i++)
3359 if (children_list[i]->mem2reg_as_needed_pass2(mem2reg_set, mod, block, async_block))
3360 did_something = true;
3361
3362 return did_something;
3363 }
3364
3365 // calculate memory dimensions
3366 void AstNode::meminfo(int &mem_width, int &mem_size, int &addr_bits)
3367 {
3368 log_assert(type == AST_MEMORY);
3369
3370 mem_width = children[0]->range_left - children[0]->range_right + 1;
3371 mem_size = children[1]->range_left - children[1]->range_right;
3372
3373 if (mem_size < 0)
3374 mem_size *= -1;
3375 mem_size += min(children[1]->range_left, children[1]->range_right) + 1;
3376
3377 addr_bits = 1;
3378 while ((1 << addr_bits) < mem_size)
3379 addr_bits++;
3380 }
3381
3382 bool AstNode::has_const_only_constructs(bool &recommend_const_eval)
3383 {
3384 if (type == AST_FOR)
3385 recommend_const_eval = true;
3386 if (type == AST_WHILE || type == AST_REPEAT)
3387 return true;
3388 if (type == AST_FCALL && current_scope.count(str))
3389 if (current_scope[str]->has_const_only_constructs(recommend_const_eval))
3390 return true;
3391 for (auto child : children)
3392 if (child->AstNode::has_const_only_constructs(recommend_const_eval))
3393 return true;
3394 return false;
3395 }
3396
3397 bool AstNode::is_simple_const_expr()
3398 {
3399 if (type == AST_IDENTIFIER)
3400 return false;
3401 for (auto child : children)
3402 if (!child->is_simple_const_expr())
3403 return false;
3404 return true;
3405 }
3406
3407 // helper function for AstNode::eval_const_function()
3408 void AstNode::replace_variables(std::map<std::string, AstNode::varinfo_t> &variables, AstNode *fcall)
3409 {
3410 if (type == AST_IDENTIFIER && variables.count(str)) {
3411 int offset = variables.at(str).offset, width = variables.at(str).val.bits.size();
3412 if (!children.empty()) {
3413 if (children.size() != 1 || children.at(0)->type != AST_RANGE)
3414 log_file_error(filename, linenum, "Memory access in constant function is not supported\n%s:%d: ...called from here.\n",
3415 fcall->filename.c_str(), fcall->linenum);
3416 children.at(0)->replace_variables(variables, fcall);
3417 while (simplify(true, false, false, 1, -1, false, true)) { }
3418 if (!children.at(0)->range_valid)
3419 log_file_error(filename, linenum, "Non-constant range\n%s:%d: ... called from here.\n",
3420 fcall->filename.c_str(), fcall->linenum);
3421 offset = min(children.at(0)->range_left, children.at(0)->range_right);
3422 width = min(std::abs(children.at(0)->range_left - children.at(0)->range_right) + 1, width);
3423 }
3424 offset -= variables.at(str).offset;
3425 std::vector<RTLIL::State> &var_bits = variables.at(str).val.bits;
3426 std::vector<RTLIL::State> new_bits(var_bits.begin() + offset, var_bits.begin() + offset + width);
3427 AstNode *newNode = mkconst_bits(new_bits, variables.at(str).is_signed);
3428 newNode->cloneInto(this);
3429 delete newNode;
3430 return;
3431 }
3432
3433 for (auto &child : children)
3434 child->replace_variables(variables, fcall);
3435 }
3436
3437 // evaluate functions with all-const arguments
3438 AstNode *AstNode::eval_const_function(AstNode *fcall)
3439 {
3440 std::map<std::string, AstNode*> backup_scope;
3441 std::map<std::string, AstNode::varinfo_t> variables;
3442 bool delete_temp_block = false;
3443 AstNode *block = NULL;
3444
3445 size_t argidx = 0;
3446 for (auto child : children)
3447 {
3448 if (child->type == AST_BLOCK)
3449 {
3450 log_assert(block == NULL);
3451 block = child;
3452 continue;
3453 }
3454
3455 if (child->type == AST_WIRE)
3456 {
3457 while (child->simplify(true, false, false, 1, -1, false, true)) { }
3458 if (!child->range_valid)
3459 log_file_error(child->filename, child->linenum, "Can't determine size of variable %s\n%s:%d: ... called from here.\n",
3460 child->str.c_str(), fcall->filename.c_str(), fcall->linenum);
3461 variables[child->str].val = RTLIL::Const(RTLIL::State::Sx, abs(child->range_left - child->range_right)+1);
3462 variables[child->str].offset = min(child->range_left, child->range_right);
3463 variables[child->str].is_signed = child->is_signed;
3464 if (child->is_input && argidx < fcall->children.size())
3465 variables[child->str].val = fcall->children.at(argidx++)->bitsAsConst(variables[child->str].val.bits.size());
3466 backup_scope[child->str] = current_scope[child->str];
3467 current_scope[child->str] = child;
3468 continue;
3469 }
3470
3471 log_assert(block == NULL);
3472 delete_temp_block = true;
3473 block = new AstNode(AST_BLOCK);
3474 block->children.push_back(child->clone());
3475 }
3476
3477 log_assert(block != NULL);
3478 log_assert(variables.count(str) != 0);
3479
3480 while (!block->children.empty())
3481 {
3482 AstNode *stmt = block->children.front();
3483
3484 #if 0
3485 log("-----------------------------------\n");
3486 for (auto &it : variables)
3487 log("%20s %40s\n", it.first.c_str(), log_signal(it.second.val));
3488 stmt->dumpAst(NULL, "stmt> ");
3489 #endif
3490
3491 if (stmt->type == AST_ASSIGN_EQ)
3492 {
3493 if (stmt->children.at(0)->type == AST_IDENTIFIER && stmt->children.at(0)->children.size() != 0 &&
3494 stmt->children.at(0)->children.at(0)->type == AST_RANGE)
3495 stmt->children.at(0)->children.at(0)->replace_variables(variables, fcall);
3496 stmt->children.at(1)->replace_variables(variables, fcall);
3497 while (stmt->simplify(true, false, false, 1, -1, false, true)) { }
3498
3499 if (stmt->type != AST_ASSIGN_EQ)
3500 continue;
3501
3502 if (stmt->children.at(1)->type != AST_CONSTANT)
3503 log_file_error(stmt->filename, stmt->linenum, "Non-constant expression in constant function\n%s:%d: ... called from here. X\n",
3504 fcall->filename.c_str(), fcall->linenum);
3505
3506 if (stmt->children.at(0)->type != AST_IDENTIFIER)
3507 log_file_error(stmt->filename, stmt->linenum, "Unsupported composite left hand side in constant function\n%s:%d: ... called from here.\n",
3508 fcall->filename.c_str(), fcall->linenum);
3509
3510 if (!variables.count(stmt->children.at(0)->str))
3511 log_file_error(stmt->filename, stmt->linenum, "Assignment to non-local variable in constant function\n%s:%d: ... called from here.\n",
3512 fcall->filename.c_str(), fcall->linenum);
3513
3514 if (stmt->children.at(0)->children.empty()) {
3515 variables[stmt->children.at(0)->str].val = stmt->children.at(1)->bitsAsConst(variables[stmt->children.at(0)->str].val.bits.size());
3516 } else {
3517 AstNode *range = stmt->children.at(0)->children.at(0);
3518 if (!range->range_valid)
3519 log_file_error(range->filename, range->linenum, "Non-constant range\n%s:%d: ... called from here.\n",
3520 fcall->filename.c_str(), fcall->linenum);
3521 int offset = min(range->range_left, range->range_right);
3522 int width = std::abs(range->range_left - range->range_right) + 1;
3523 varinfo_t &v = variables[stmt->children.at(0)->str];
3524 RTLIL::Const r = stmt->children.at(1)->bitsAsConst(v.val.bits.size());
3525 for (int i = 0; i < width; i++)
3526 v.val.bits.at(i+offset-v.offset) = r.bits.at(i);
3527 }
3528
3529 delete block->children.front();
3530 block->children.erase(block->children.begin());
3531 continue;
3532 }
3533
3534 if (stmt->type == AST_FOR)
3535 {
3536 block->children.insert(block->children.begin(), stmt->children.at(0));
3537 stmt->children.at(3)->children.push_back(stmt->children.at(2));
3538 stmt->children.erase(stmt->children.begin() + 2);
3539 stmt->children.erase(stmt->children.begin());
3540 stmt->type = AST_WHILE;
3541 continue;
3542 }
3543
3544 if (stmt->type == AST_WHILE)
3545 {
3546 AstNode *cond = stmt->children.at(0)->clone();
3547 cond->replace_variables(variables, fcall);
3548 while (cond->simplify(true, false, false, 1, -1, false, true)) { }
3549
3550 if (cond->type != AST_CONSTANT)
3551 log_file_error(stmt->filename, stmt->linenum, "Non-constant expression in constant function\n%s:%d: ... called from here.\n",
3552 fcall->filename.c_str(), fcall->linenum);
3553
3554 if (cond->asBool()) {
3555 block->children.insert(block->children.begin(), stmt->children.at(1)->clone());
3556 } else {
3557 delete block->children.front();
3558 block->children.erase(block->children.begin());
3559 }
3560
3561 delete cond;
3562 continue;
3563 }
3564
3565 if (stmt->type == AST_REPEAT)
3566 {
3567 AstNode *num = stmt->children.at(0)->clone();
3568 num->replace_variables(variables, fcall);
3569 while (num->simplify(true, false, false, 1, -1, false, true)) { }
3570
3571 if (num->type != AST_CONSTANT)
3572 log_file_error(stmt->filename, stmt->linenum, "Non-constant expression in constant function\n%s:%d: ... called from here.\n",
3573 fcall->filename.c_str(), fcall->linenum);
3574
3575 block->children.erase(block->children.begin());
3576 for (int i = 0; i < num->bitsAsConst().as_int(); i++)
3577 block->children.insert(block->children.begin(), stmt->children.at(1)->clone());
3578
3579 delete stmt;
3580 delete num;
3581 continue;
3582 }
3583
3584 if (stmt->type == AST_CASE)
3585 {
3586 AstNode *expr = stmt->children.at(0)->clone();
3587 expr->replace_variables(variables, fcall);
3588 while (expr->simplify(true, false, false, 1, -1, false, true)) { }
3589
3590 AstNode *sel_case = NULL;
3591 for (size_t i = 1; i < stmt->children.size(); i++)
3592 {
3593 bool found_match = false;
3594 log_assert(stmt->children.at(i)->type == AST_COND || stmt->children.at(i)->type == AST_CONDX || stmt->children.at(i)->type == AST_CONDZ);
3595
3596 if (stmt->children.at(i)->children.front()->type == AST_DEFAULT) {
3597 sel_case = stmt->children.at(i)->children.back();
3598 continue;
3599 }
3600
3601 for (size_t j = 0; j+1 < stmt->children.at(i)->children.size() && !found_match; j++)
3602 {
3603 AstNode *cond = stmt->children.at(i)->children.at(j)->clone();
3604 cond->replace_variables(variables, fcall);
3605
3606 cond = new AstNode(AST_EQ, expr->clone(), cond);
3607 while (cond->simplify(true, false, false, 1, -1, false, true)) { }
3608
3609 if (cond->type != AST_CONSTANT)
3610 log_file_error(stmt->filename, stmt->linenum, "Non-constant expression in constant function\n%s:%d: ... called from here.\n",
3611 fcall->filename.c_str(), fcall->linenum);
3612
3613 found_match = cond->asBool();
3614 delete cond;
3615 }
3616
3617 if (found_match) {
3618 sel_case = stmt->children.at(i)->children.back();
3619 break;
3620 }
3621 }
3622
3623 block->children.erase(block->children.begin());
3624 if (sel_case)
3625 block->children.insert(block->children.begin(), sel_case->clone());
3626 delete stmt;
3627 delete expr;
3628 continue;
3629 }
3630
3631 if (stmt->type == AST_BLOCK)
3632 {
3633 block->children.erase(block->children.begin());
3634 block->children.insert(block->children.begin(), stmt->children.begin(), stmt->children.end());
3635 stmt->children.clear();
3636 delete stmt;
3637 continue;
3638 }
3639
3640 log_file_error(stmt->filename, stmt->linenum, "Unsupported language construct in constant function\n%s:%d: ... called from here.\n",
3641 fcall->filename.c_str(), fcall->linenum);
3642 log_abort();
3643 }
3644
3645 if (delete_temp_block)
3646 delete block;
3647
3648 for (auto &it : backup_scope)
3649 if (it.second == NULL)
3650 current_scope.erase(it.first);
3651 else
3652 current_scope[it.first] = it.second;
3653
3654 return AstNode::mkconst_bits(variables.at(str).val.bits, variables.at(str).is_signed);
3655 }
3656
3657 YOSYS_NAMESPACE_END