verilog: disallow overriding global parameters
[yosys.git] / frontends / ast / genrtlil.cc
1 /*
2 * yosys -- Yosys Open SYnthesis Suite
3 *
4 * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
5 *
6 * Permission to use, copy, modify, and/or distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 *
18 * ---
19 *
20 * This is the AST frontend library.
21 *
22 * The AST frontend library is not a frontend on it's own but provides a
23 * generic abstract syntax tree (AST) abstraction for HDL code and can be
24 * used by HDL frontends. See "ast.h" for an overview of the API and the
25 * Verilog frontend for an usage example.
26 *
27 */
28
29 #include "kernel/log.h"
30 #include "kernel/utils.h"
31 #include "libs/sha1/sha1.h"
32 #include "ast.h"
33
34 #include <sstream>
35 #include <stdarg.h>
36 #include <algorithm>
37
38 YOSYS_NAMESPACE_BEGIN
39
40 using namespace AST;
41 using namespace AST_INTERNAL;
42
43 // helper function for creating RTLIL code for unary operations
44 static RTLIL::SigSpec uniop2rtlil(AstNode *that, IdString type, int result_width, const RTLIL::SigSpec &arg, bool gen_attributes = true)
45 {
46 IdString name = stringf("%s$%s:%d$%d", type.c_str(), that->filename.c_str(), that->location.first_line, autoidx++);
47 RTLIL::Cell *cell = current_module->addCell(name, type);
48 set_src_attr(cell, that);
49
50 RTLIL::Wire *wire = current_module->addWire(cell->name.str() + "_Y", result_width);
51 set_src_attr(wire, that);
52 wire->is_signed = that->is_signed;
53
54 if (gen_attributes)
55 for (auto &attr : that->attributes) {
56 if (attr.second->type != AST_CONSTANT)
57 log_file_error(that->filename, that->location.first_line, "Attribute `%s' with non-constant value!\n", attr.first.c_str());
58 cell->attributes[attr.first] = attr.second->asAttrConst();
59 }
60
61 cell->parameters[ID::A_SIGNED] = RTLIL::Const(that->children[0]->is_signed);
62 cell->parameters[ID::A_WIDTH] = RTLIL::Const(arg.size());
63 cell->setPort(ID::A, arg);
64
65 cell->parameters[ID::Y_WIDTH] = result_width;
66 cell->setPort(ID::Y, wire);
67 return wire;
68 }
69
70 // helper function for extending bit width (preferred over SigSpec::extend() because of correct undef propagation in ConstEval)
71 static void widthExtend(AstNode *that, RTLIL::SigSpec &sig, int width, bool is_signed)
72 {
73 if (width <= sig.size()) {
74 sig.extend_u0(width, is_signed);
75 return;
76 }
77
78 IdString name = stringf("$extend$%s:%d$%d", that->filename.c_str(), that->location.first_line, autoidx++);
79 RTLIL::Cell *cell = current_module->addCell(name, ID($pos));
80 set_src_attr(cell, that);
81
82 RTLIL::Wire *wire = current_module->addWire(cell->name.str() + "_Y", width);
83 set_src_attr(wire, that);
84 wire->is_signed = that->is_signed;
85
86 if (that != NULL)
87 for (auto &attr : that->attributes) {
88 if (attr.second->type != AST_CONSTANT)
89 log_file_error(that->filename, that->location.first_line, "Attribute `%s' with non-constant value!\n", attr.first.c_str());
90 cell->attributes[attr.first] = attr.second->asAttrConst();
91 }
92
93 cell->parameters[ID::A_SIGNED] = RTLIL::Const(is_signed);
94 cell->parameters[ID::A_WIDTH] = RTLIL::Const(sig.size());
95 cell->setPort(ID::A, sig);
96
97 cell->parameters[ID::Y_WIDTH] = width;
98 cell->setPort(ID::Y, wire);
99 sig = wire;
100 }
101
102 // helper function for creating RTLIL code for binary operations
103 static RTLIL::SigSpec binop2rtlil(AstNode *that, IdString type, int result_width, const RTLIL::SigSpec &left, const RTLIL::SigSpec &right)
104 {
105 IdString name = stringf("%s$%s:%d$%d", type.c_str(), that->filename.c_str(), that->location.first_line, autoidx++);
106 RTLIL::Cell *cell = current_module->addCell(name, type);
107 set_src_attr(cell, that);
108
109 RTLIL::Wire *wire = current_module->addWire(cell->name.str() + "_Y", result_width);
110 set_src_attr(wire, that);
111 wire->is_signed = that->is_signed;
112
113 for (auto &attr : that->attributes) {
114 if (attr.second->type != AST_CONSTANT)
115 log_file_error(that->filename, that->location.first_line, "Attribute `%s' with non-constant value!\n", attr.first.c_str());
116 cell->attributes[attr.first] = attr.second->asAttrConst();
117 }
118
119 cell->parameters[ID::A_SIGNED] = RTLIL::Const(that->children[0]->is_signed);
120 cell->parameters[ID::B_SIGNED] = RTLIL::Const(that->children[1]->is_signed);
121
122 cell->parameters[ID::A_WIDTH] = RTLIL::Const(left.size());
123 cell->parameters[ID::B_WIDTH] = RTLIL::Const(right.size());
124
125 cell->setPort(ID::A, left);
126 cell->setPort(ID::B, right);
127
128 cell->parameters[ID::Y_WIDTH] = result_width;
129 cell->setPort(ID::Y, wire);
130 return wire;
131 }
132
133 // helper function for creating RTLIL code for multiplexers
134 static RTLIL::SigSpec mux2rtlil(AstNode *that, const RTLIL::SigSpec &cond, const RTLIL::SigSpec &left, const RTLIL::SigSpec &right)
135 {
136 log_assert(cond.size() == 1);
137
138 std::stringstream sstr;
139 sstr << "$ternary$" << that->filename << ":" << that->location.first_line << "$" << (autoidx++);
140
141 RTLIL::Cell *cell = current_module->addCell(sstr.str(), ID($mux));
142 set_src_attr(cell, that);
143
144 RTLIL::Wire *wire = current_module->addWire(cell->name.str() + "_Y", left.size());
145 set_src_attr(wire, that);
146 wire->is_signed = that->is_signed;
147
148 for (auto &attr : that->attributes) {
149 if (attr.second->type != AST_CONSTANT)
150 log_file_error(that->filename, that->location.first_line, "Attribute `%s' with non-constant value!\n", attr.first.c_str());
151 cell->attributes[attr.first] = attr.second->asAttrConst();
152 }
153
154 cell->parameters[ID::WIDTH] = RTLIL::Const(left.size());
155
156 cell->setPort(ID::A, right);
157 cell->setPort(ID::B, left);
158 cell->setPort(ID::S, cond);
159 cell->setPort(ID::Y, wire);
160
161 return wire;
162 }
163
164 // helper class for rewriting simple lookahead references in AST always blocks
165 struct AST_INTERNAL::LookaheadRewriter
166 {
167 dict<IdString, pair<AstNode*, AstNode*>> lookaheadids;
168
169 void collect_lookaheadids(AstNode *node)
170 {
171 if (node->lookahead) {
172 log_assert(node->type == AST_IDENTIFIER);
173 if (!lookaheadids.count(node->str)) {
174 AstNode *wire = new AstNode(AST_WIRE);
175 for (auto c : node->id2ast->children)
176 wire->children.push_back(c->clone());
177 wire->str = stringf("$lookahead%s$%d", node->str.c_str(), autoidx++);
178 wire->attributes[ID::nosync] = AstNode::mkconst_int(1, false);
179 wire->is_logic = true;
180 while (wire->simplify(true, false, false, 1, -1, false, false)) { }
181 current_ast_mod->children.push_back(wire);
182 lookaheadids[node->str] = make_pair(node->id2ast, wire);
183 wire->genRTLIL();
184 }
185 }
186
187 for (auto child : node->children)
188 collect_lookaheadids(child);
189 }
190
191 bool has_lookaheadids(AstNode *node)
192 {
193 if (node->type == AST_IDENTIFIER && lookaheadids.count(node->str) != 0)
194 return true;
195
196 for (auto child : node->children)
197 if (has_lookaheadids(child))
198 return true;
199
200 return false;
201 }
202
203 bool has_nonlookaheadids(AstNode *node)
204 {
205 if (node->type == AST_IDENTIFIER && lookaheadids.count(node->str) == 0)
206 return true;
207
208 for (auto child : node->children)
209 if (has_nonlookaheadids(child))
210 return true;
211
212 return false;
213 }
214
215 void rewrite_lookaheadids(AstNode *node, bool lhs = false)
216 {
217 if (node->type == AST_ASSIGN_LE)
218 {
219 if (has_lookaheadids(node->children[0]))
220 {
221 if (has_nonlookaheadids(node->children[0]))
222 log_error("incompatible mix of lookahead and non-lookahead IDs in LHS expression.\n");
223
224 rewrite_lookaheadids(node->children[0], true);
225 node->type = AST_ASSIGN_EQ;
226 }
227
228 rewrite_lookaheadids(node->children[1], lhs);
229 return;
230 }
231
232 if (node->type == AST_IDENTIFIER && (node->lookahead || lhs)) {
233 AstNode *newwire = lookaheadids.at(node->str).second;
234 node->str = newwire->str;
235 node->id2ast = newwire;
236 lhs = false;
237 }
238
239 for (auto child : node->children)
240 rewrite_lookaheadids(child, lhs);
241 }
242
243 LookaheadRewriter(AstNode *top)
244 {
245 // top->dumpAst(NULL, "REWRITE-BEFORE> ");
246 // top->dumpVlog(NULL, "REWRITE-BEFORE> ");
247
248 AstNode *block = nullptr;
249
250 for (auto c : top->children)
251 if (c->type == AST_BLOCK) {
252 log_assert(block == nullptr);
253 block = c;
254 }
255 log_assert(block != nullptr);
256
257 collect_lookaheadids(block);
258 rewrite_lookaheadids(block);
259
260 for (auto it : lookaheadids)
261 {
262 AstNode *ref_orig = new AstNode(AST_IDENTIFIER);
263 ref_orig->str = it.second.first->str;
264 ref_orig->id2ast = it.second.first;
265 ref_orig->was_checked = true;
266
267 AstNode *ref_temp = new AstNode(AST_IDENTIFIER);
268 ref_temp->str = it.second.second->str;
269 ref_temp->id2ast = it.second.second;
270 ref_temp->was_checked = true;
271
272 AstNode *init_assign = new AstNode(AST_ASSIGN_EQ, ref_temp->clone(), ref_orig->clone());
273 AstNode *final_assign = new AstNode(AST_ASSIGN_LE, ref_orig, ref_temp);
274
275 block->children.insert(block->children.begin(), init_assign);
276 block->children.push_back(final_assign);
277 }
278
279 // top->dumpAst(NULL, "REWRITE-AFTER> ");
280 // top->dumpVlog(NULL, "REWRITE-AFTER> ");
281 }
282 };
283
284 // helper class for converting AST always nodes to RTLIL processes
285 struct AST_INTERNAL::ProcessGenerator
286 {
287 // input and output structures
288 AstNode *always;
289 RTLIL::SigSpec initSyncSignals;
290 RTLIL::Process *proc;
291 RTLIL::SigSpec outputSignals;
292
293 // This always points to the RTLIL::CaseRule being filled at the moment
294 RTLIL::CaseRule *current_case;
295
296 // This map contains the replacement pattern to be used in the right hand side
297 // of an assignment. E.g. in the code "foo = bar; foo = func(foo);" the foo in the right
298 // hand side of the 2nd assignment needs to be replace with the temporary signal holding
299 // the value assigned in the first assignment. So when the first assignment is processed
300 // the according information is appended to subst_rvalue_from and subst_rvalue_to.
301 stackmap<RTLIL::SigBit, RTLIL::SigBit> subst_rvalue_map;
302
303 // This map contains the replacement pattern to be used in the left hand side
304 // of an assignment. E.g. in the code "always @(posedge clk) foo <= bar" the signal bar
305 // should not be connected to the signal foo. Instead it must be connected to the temporary
306 // signal that is used as input for the register that drives the signal foo.
307 stackmap<RTLIL::SigBit, RTLIL::SigBit> subst_lvalue_map;
308
309 // The code here generates a number of temporary signal for each output register. This
310 // map helps generating nice numbered names for all this temporary signals.
311 std::map<RTLIL::Wire*, int> new_temp_count;
312
313 // Buffer for generating the init action
314 RTLIL::SigSpec init_lvalue, init_rvalue;
315
316 ProcessGenerator(AstNode *always, RTLIL::SigSpec initSyncSignalsArg = RTLIL::SigSpec()) : always(always), initSyncSignals(initSyncSignalsArg)
317 {
318 // rewrite lookahead references
319 LookaheadRewriter la_rewriter(always);
320
321 // generate process and simple root case
322 proc = new RTLIL::Process;
323 set_src_attr(proc, always);
324 proc->name = stringf("$proc$%s:%d$%d", always->filename.c_str(), always->location.first_line, autoidx++);
325 for (auto &attr : always->attributes) {
326 if (attr.second->type != AST_CONSTANT)
327 log_file_error(always->filename, always->location.first_line, "Attribute `%s' with non-constant value!\n",
328 attr.first.c_str());
329 proc->attributes[attr.first] = attr.second->asAttrConst();
330 }
331 current_module->processes[proc->name] = proc;
332 current_case = &proc->root_case;
333
334 // create initial temporary signal for all output registers
335 RTLIL::SigSpec subst_lvalue_from, subst_lvalue_to;
336 collect_lvalues(subst_lvalue_from, always, true, true);
337 subst_lvalue_to = new_temp_signal(subst_lvalue_from);
338 subst_lvalue_map = subst_lvalue_from.to_sigbit_map(subst_lvalue_to);
339
340 bool found_global_syncs = false;
341 bool found_anyedge_syncs = false;
342 for (auto child : always->children)
343 {
344 if ((child->type == AST_POSEDGE || child->type == AST_NEGEDGE) && GetSize(child->children) == 1 && child->children.at(0)->type == AST_IDENTIFIER &&
345 child->children.at(0)->id2ast && child->children.at(0)->id2ast->type == AST_WIRE && child->children.at(0)->id2ast->get_bool_attribute(ID::gclk)) {
346 found_global_syncs = true;
347 }
348 if (child->type == AST_EDGE) {
349 if (GetSize(child->children) == 1 && child->children.at(0)->type == AST_IDENTIFIER && child->children.at(0)->str == "\\$global_clock")
350 found_global_syncs = true;
351 else
352 found_anyedge_syncs = true;
353 }
354 }
355
356 if (found_anyedge_syncs) {
357 if (found_global_syncs)
358 log_file_error(always->filename, always->location.first_line, "Found non-synthesizable event list!\n");
359 log("Note: Assuming pure combinatorial block at %s in\n", always->loc_string().c_str());
360 log("compliance with IEC 62142(E):2005 / IEEE Std. 1364.1(E):2002. Recommending\n");
361 log("use of @* instead of @(...) for better match of synthesis and simulation.\n");
362 }
363
364 // create syncs for the process
365 bool found_clocked_sync = false;
366 for (auto child : always->children)
367 if (child->type == AST_POSEDGE || child->type == AST_NEGEDGE) {
368 if (GetSize(child->children) == 1 && child->children.at(0)->type == AST_IDENTIFIER && child->children.at(0)->id2ast &&
369 child->children.at(0)->id2ast->type == AST_WIRE && child->children.at(0)->id2ast->get_bool_attribute(ID::gclk))
370 continue;
371 found_clocked_sync = true;
372 if (found_global_syncs || found_anyedge_syncs)
373 log_file_error(always->filename, always->location.first_line, "Found non-synthesizable event list!\n");
374 RTLIL::SyncRule *syncrule = new RTLIL::SyncRule;
375 syncrule->type = child->type == AST_POSEDGE ? RTLIL::STp : RTLIL::STn;
376 syncrule->signal = child->children[0]->genRTLIL();
377 if (GetSize(syncrule->signal) != 1)
378 log_file_error(always->filename, always->location.first_line, "Found posedge/negedge event on a signal that is not 1 bit wide!\n");
379 addChunkActions(syncrule->actions, subst_lvalue_from, subst_lvalue_to, true);
380 proc->syncs.push_back(syncrule);
381 }
382 if (proc->syncs.empty()) {
383 RTLIL::SyncRule *syncrule = new RTLIL::SyncRule;
384 syncrule->type = found_global_syncs ? RTLIL::STg : RTLIL::STa;
385 syncrule->signal = RTLIL::SigSpec();
386 addChunkActions(syncrule->actions, subst_lvalue_from, subst_lvalue_to, true);
387 proc->syncs.push_back(syncrule);
388 }
389
390 // create initial assignments for the temporary signals
391 if ((flag_nolatches || always->get_bool_attribute(ID::nolatches) || current_module->get_bool_attribute(ID::nolatches)) && !found_clocked_sync) {
392 subst_rvalue_map = subst_lvalue_from.to_sigbit_dict(RTLIL::SigSpec(RTLIL::State::Sx, GetSize(subst_lvalue_from)));
393 } else {
394 addChunkActions(current_case->actions, subst_lvalue_to, subst_lvalue_from);
395 }
396
397 // process the AST
398 for (auto child : always->children)
399 if (child->type == AST_BLOCK)
400 processAst(child);
401
402 for (auto sync: proc->syncs)
403 processMemWrites(sync);
404
405 if (initSyncSignals.size() > 0)
406 {
407 RTLIL::SyncRule *sync = new RTLIL::SyncRule;
408 sync->type = RTLIL::SyncType::STi;
409 proc->syncs.push_back(sync);
410
411 log_assert(init_lvalue.size() == init_rvalue.size());
412
413 int offset = 0;
414 for (auto &init_lvalue_c : init_lvalue.chunks()) {
415 RTLIL::SigSpec lhs = init_lvalue_c;
416 RTLIL::SigSpec rhs = init_rvalue.extract(offset, init_lvalue_c.width);
417 remove_unwanted_lvalue_bits(lhs, rhs);
418 sync->actions.push_back(RTLIL::SigSig(lhs, rhs));
419 offset += lhs.size();
420 }
421 }
422
423 outputSignals = RTLIL::SigSpec(subst_lvalue_from);
424 }
425
426 void remove_unwanted_lvalue_bits(RTLIL::SigSpec &lhs, RTLIL::SigSpec &rhs)
427 {
428 RTLIL::SigSpec new_lhs, new_rhs;
429
430 log_assert(GetSize(lhs) == GetSize(rhs));
431 for (int i = 0; i < GetSize(lhs); i++) {
432 if (lhs[i].wire == nullptr)
433 continue;
434 new_lhs.append(lhs[i]);
435 new_rhs.append(rhs[i]);
436 }
437
438 lhs = new_lhs;
439 rhs = new_rhs;
440 }
441
442 // create new temporary signals
443 RTLIL::SigSpec new_temp_signal(RTLIL::SigSpec sig)
444 {
445 std::vector<RTLIL::SigChunk> chunks = sig.chunks();
446
447 for (int i = 0; i < GetSize(chunks); i++)
448 {
449 RTLIL::SigChunk &chunk = chunks[i];
450 if (chunk.wire == NULL)
451 continue;
452
453 std::string wire_name;
454 do {
455 wire_name = stringf("$%d%s[%d:%d]", new_temp_count[chunk.wire]++,
456 chunk.wire->name.c_str(), chunk.width+chunk.offset-1, chunk.offset);;
457 if (chunk.wire->name.str().find('$') != std::string::npos)
458 wire_name += stringf("$%d", autoidx++);
459 } while (current_module->wires_.count(wire_name) > 0);
460
461 RTLIL::Wire *wire = current_module->addWire(wire_name, chunk.width);
462 set_src_attr(wire, always);
463
464 chunk.wire = wire;
465 chunk.offset = 0;
466 }
467
468 return chunks;
469 }
470
471 // recursively traverse the AST and collect all assigned signals
472 void collect_lvalues(RTLIL::SigSpec &reg, AstNode *ast, bool type_eq, bool type_le, bool run_sort_and_unify = true)
473 {
474 switch (ast->type)
475 {
476 case AST_CASE:
477 for (auto child : ast->children)
478 if (child != ast->children[0]) {
479 log_assert(child->type == AST_COND || child->type == AST_CONDX || child->type == AST_CONDZ);
480 collect_lvalues(reg, child, type_eq, type_le, false);
481 }
482 break;
483
484 case AST_COND:
485 case AST_CONDX:
486 case AST_CONDZ:
487 case AST_ALWAYS:
488 case AST_INITIAL:
489 for (auto child : ast->children)
490 if (child->type == AST_BLOCK)
491 collect_lvalues(reg, child, type_eq, type_le, false);
492 break;
493
494 case AST_BLOCK:
495 for (auto child : ast->children) {
496 if (child->type == AST_ASSIGN_EQ && type_eq)
497 reg.append(child->children[0]->genRTLIL());
498 if (child->type == AST_ASSIGN_LE && type_le)
499 reg.append(child->children[0]->genRTLIL());
500 if (child->type == AST_CASE || child->type == AST_BLOCK)
501 collect_lvalues(reg, child, type_eq, type_le, false);
502 }
503 break;
504
505 default:
506 log_abort();
507 }
508
509 if (run_sort_and_unify) {
510 std::set<RTLIL::SigBit> sorted_reg;
511 for (auto bit : reg)
512 if (bit.wire)
513 sorted_reg.insert(bit);
514 reg = RTLIL::SigSpec(sorted_reg);
515 }
516 }
517
518 // remove all assignments to the given signal pattern in a case and all its children.
519 // e.g. when the last statement in the code "a = 23; if (b) a = 42; a = 0;" is processed this
520 // function is called to clean up the first two assignments as they are overwritten by
521 // the third assignment.
522 void removeSignalFromCaseTree(const RTLIL::SigSpec &pattern, RTLIL::CaseRule *cs)
523 {
524 for (auto it = cs->actions.begin(); it != cs->actions.end(); it++)
525 it->first.remove2(pattern, &it->second);
526
527 for (auto it = cs->switches.begin(); it != cs->switches.end(); it++)
528 for (auto it2 = (*it)->cases.begin(); it2 != (*it)->cases.end(); it2++)
529 removeSignalFromCaseTree(pattern, *it2);
530 }
531
532 // add an assignment (aka "action") but split it up in chunks. this way huge assignments
533 // are avoided and the generated $mux cells have a more "natural" size.
534 void addChunkActions(std::vector<RTLIL::SigSig> &actions, RTLIL::SigSpec lvalue, RTLIL::SigSpec rvalue, bool inSyncRule = false)
535 {
536 if (inSyncRule && initSyncSignals.size() > 0) {
537 init_lvalue.append(lvalue.extract(initSyncSignals));
538 init_rvalue.append(lvalue.extract(initSyncSignals, &rvalue));
539 lvalue.remove2(initSyncSignals, &rvalue);
540 }
541 log_assert(lvalue.size() == rvalue.size());
542
543 int offset = 0;
544 for (auto &lvalue_c : lvalue.chunks()) {
545 RTLIL::SigSpec lhs = lvalue_c;
546 RTLIL::SigSpec rhs = rvalue.extract(offset, lvalue_c.width);
547 if (inSyncRule && lvalue_c.wire && lvalue_c.wire->get_bool_attribute(ID::nosync))
548 rhs = RTLIL::SigSpec(RTLIL::State::Sx, rhs.size());
549 remove_unwanted_lvalue_bits(lhs, rhs);
550 actions.push_back(RTLIL::SigSig(lhs, rhs));
551 offset += lhs.size();
552 }
553 }
554
555 // recursively process the AST and fill the RTLIL::Process
556 void processAst(AstNode *ast)
557 {
558 switch (ast->type)
559 {
560 case AST_BLOCK:
561 for (auto child : ast->children)
562 processAst(child);
563 break;
564
565 case AST_ASSIGN_EQ:
566 case AST_ASSIGN_LE:
567 {
568 RTLIL::SigSpec unmapped_lvalue = ast->children[0]->genRTLIL(), lvalue = unmapped_lvalue;
569 RTLIL::SigSpec rvalue = ast->children[1]->genWidthRTLIL(lvalue.size(), &subst_rvalue_map.stdmap());
570
571 pool<SigBit> lvalue_sigbits;
572 for (int i = 0; i < GetSize(lvalue); i++) {
573 if (lvalue_sigbits.count(lvalue[i]) > 0) {
574 unmapped_lvalue.remove(i);
575 lvalue.remove(i);
576 rvalue.remove(i--);
577 } else
578 lvalue_sigbits.insert(lvalue[i]);
579 }
580
581 lvalue.replace(subst_lvalue_map.stdmap());
582
583 if (ast->type == AST_ASSIGN_EQ) {
584 for (int i = 0; i < GetSize(unmapped_lvalue); i++)
585 subst_rvalue_map.set(unmapped_lvalue[i], rvalue[i]);
586 }
587
588 removeSignalFromCaseTree(lvalue, current_case);
589 remove_unwanted_lvalue_bits(lvalue, rvalue);
590 current_case->actions.push_back(RTLIL::SigSig(lvalue, rvalue));
591 }
592 break;
593
594 case AST_CASE:
595 {
596 RTLIL::SwitchRule *sw = new RTLIL::SwitchRule;
597 set_src_attr(sw, ast);
598 sw->signal = ast->children[0]->genWidthRTLIL(-1, &subst_rvalue_map.stdmap());
599 current_case->switches.push_back(sw);
600
601 for (auto &attr : ast->attributes) {
602 if (attr.second->type != AST_CONSTANT)
603 log_file_error(ast->filename, ast->location.first_line, "Attribute `%s' with non-constant value!\n", attr.first.c_str());
604 sw->attributes[attr.first] = attr.second->asAttrConst();
605 }
606
607 RTLIL::SigSpec this_case_eq_lvalue;
608 collect_lvalues(this_case_eq_lvalue, ast, true, false);
609
610 RTLIL::SigSpec this_case_eq_ltemp = new_temp_signal(this_case_eq_lvalue);
611
612 RTLIL::SigSpec this_case_eq_rvalue = this_case_eq_lvalue;
613 this_case_eq_rvalue.replace(subst_rvalue_map.stdmap());
614
615 RTLIL::CaseRule *default_case = NULL;
616 RTLIL::CaseRule *last_generated_case = NULL;
617 for (auto child : ast->children)
618 {
619 if (child == ast->children[0])
620 continue;
621 log_assert(child->type == AST_COND || child->type == AST_CONDX || child->type == AST_CONDZ);
622
623 subst_lvalue_map.save();
624 subst_rvalue_map.save();
625
626 for (int i = 0; i < GetSize(this_case_eq_lvalue); i++)
627 subst_lvalue_map.set(this_case_eq_lvalue[i], this_case_eq_ltemp[i]);
628
629 RTLIL::CaseRule *backup_case = current_case;
630 current_case = new RTLIL::CaseRule;
631 set_src_attr(current_case, child);
632 last_generated_case = current_case;
633 addChunkActions(current_case->actions, this_case_eq_ltemp, this_case_eq_rvalue);
634 for (auto node : child->children) {
635 if (node->type == AST_DEFAULT)
636 default_case = current_case;
637 else if (node->type == AST_BLOCK)
638 processAst(node);
639 else
640 current_case->compare.push_back(node->genWidthRTLIL(sw->signal.size(), &subst_rvalue_map.stdmap()));
641 }
642 if (default_case != current_case)
643 sw->cases.push_back(current_case);
644 else
645 log_assert(current_case->compare.size() == 0);
646 current_case = backup_case;
647
648 subst_lvalue_map.restore();
649 subst_rvalue_map.restore();
650 }
651
652 if (last_generated_case != NULL && ast->get_bool_attribute(ID::full_case) && default_case == NULL) {
653 #if 0
654 // this is a valid transformation, but as optimization it is premature.
655 // better: add a default case that assigns 'x' to everything, and let later
656 // optimizations take care of the rest
657 last_generated_case->compare.clear();
658 #else
659 default_case = new RTLIL::CaseRule;
660 addChunkActions(default_case->actions, this_case_eq_ltemp, SigSpec(State::Sx, GetSize(this_case_eq_rvalue)));
661 sw->cases.push_back(default_case);
662 #endif
663 } else {
664 if (default_case == NULL) {
665 default_case = new RTLIL::CaseRule;
666 addChunkActions(default_case->actions, this_case_eq_ltemp, this_case_eq_rvalue);
667 }
668 sw->cases.push_back(default_case);
669 }
670
671 for (int i = 0; i < GetSize(this_case_eq_lvalue); i++)
672 subst_rvalue_map.set(this_case_eq_lvalue[i], this_case_eq_ltemp[i]);
673
674 this_case_eq_lvalue.replace(subst_lvalue_map.stdmap());
675 removeSignalFromCaseTree(this_case_eq_lvalue, current_case);
676 addChunkActions(current_case->actions, this_case_eq_lvalue, this_case_eq_ltemp);
677 }
678 break;
679
680 case AST_WIRE:
681 log_file_error(ast->filename, ast->location.first_line, "Found reg declaration in block without label!\n");
682 break;
683
684 case AST_ASSIGN:
685 log_file_error(ast->filename, ast->location.first_line, "Found continous assignment in always/initial block!\n");
686 break;
687
688 case AST_PARAMETER:
689 case AST_LOCALPARAM:
690 log_file_error(ast->filename, ast->location.first_line, "Found parameter declaration in block without label!\n");
691 break;
692
693 case AST_NONE:
694 case AST_TCALL:
695 case AST_FOR:
696 break;
697
698 default:
699 // ast->dumpAst(NULL, "ast> ");
700 // current_ast_mod->dumpAst(NULL, "mod> ");
701 log_abort();
702 }
703 }
704
705 void processMemWrites(RTLIL::SyncRule *sync)
706 {
707 // Maps per-memid AST_MEMWR IDs to indices in the mem_write_actions array.
708 dict<std::pair<std::string, int>, int> port_map;
709 for (auto child : always->children)
710 if (child->type == AST_MEMWR)
711 {
712 std::string memid = child->str;
713 int portid = child->children[3]->asInt(false);
714 int cur_idx = GetSize(sync->mem_write_actions);
715 RTLIL::MemWriteAction action;
716 set_src_attr(&action, child);
717 action.memid = memid;
718 action.address = child->children[0]->genWidthRTLIL(-1, &subst_rvalue_map.stdmap());
719 action.data = child->children[1]->genWidthRTLIL(current_module->memories[memid]->width, &subst_rvalue_map.stdmap());
720 action.enable = child->children[2]->genWidthRTLIL(-1, &subst_rvalue_map.stdmap());
721 RTLIL::Const orig_priority_mask = child->children[4]->bitsAsConst();
722 RTLIL::Const priority_mask = RTLIL::Const(0, cur_idx);
723 for (int i = 0; i < portid; i++) {
724 int new_bit = port_map[std::make_pair(memid, i)];
725 priority_mask.bits[new_bit] = orig_priority_mask.bits[i];
726 }
727 action.priority_mask = priority_mask;
728 sync->mem_write_actions.push_back(action);
729 port_map[std::make_pair(memid, portid)] = cur_idx;
730 }
731 }
732 };
733
734 // detect sign and width of an expression
735 void AstNode::detectSignWidthWorker(int &width_hint, bool &sign_hint, bool *found_real)
736 {
737 std::string type_name;
738 bool sub_sign_hint = true;
739 int sub_width_hint = -1;
740 int this_width = 0;
741 AstNode *range = NULL;
742 AstNode *id_ast = NULL;
743
744 bool local_found_real = false;
745 if (found_real == NULL)
746 found_real = &local_found_real;
747
748 switch (type)
749 {
750 case AST_NONE:
751 // unallocated enum, ignore
752 break;
753 case AST_CONSTANT:
754 width_hint = max(width_hint, int(bits.size()));
755 if (!is_signed)
756 sign_hint = false;
757 break;
758
759 case AST_REALVALUE:
760 *found_real = true;
761 width_hint = max(width_hint, 32);
762 break;
763
764 case AST_IDENTIFIER:
765 id_ast = id2ast;
766 if (id_ast == NULL && current_scope.count(str))
767 id_ast = current_scope.at(str);
768 if (!id_ast)
769 log_file_error(filename, location.first_line, "Failed to resolve identifier %s for width detection!\n", str.c_str());
770 if (id_ast->type == AST_PARAMETER || id_ast->type == AST_LOCALPARAM || id_ast->type == AST_ENUM_ITEM) {
771 if (id_ast->children.size() > 1 && id_ast->children[1]->range_valid) {
772 this_width = id_ast->children[1]->range_left - id_ast->children[1]->range_right + 1;
773 } else
774 if (id_ast->children[0]->type != AST_CONSTANT)
775 while (id_ast->simplify(true, false, false, 1, -1, false, true)) { }
776 if (id_ast->children[0]->type == AST_CONSTANT)
777 this_width = id_ast->children[0]->bits.size();
778 else
779 log_file_error(filename, location.first_line, "Failed to detect width for parameter %s!\n", str.c_str());
780 if (children.size() != 0)
781 range = children[0];
782 } else if (id_ast->type == AST_WIRE || id_ast->type == AST_AUTOWIRE) {
783 if (!id_ast->range_valid) {
784 if (id_ast->type == AST_AUTOWIRE)
785 this_width = 1;
786 else {
787 // current_ast_mod->dumpAst(NULL, "mod> ");
788 // log("---\n");
789 // id_ast->dumpAst(NULL, "decl> ");
790 // dumpAst(NULL, "ref> ");
791 log_file_error(filename, location.first_line, "Failed to detect width of signal access `%s'!\n", str.c_str());
792 }
793 } else {
794 this_width = id_ast->range_left - id_ast->range_right + 1;
795 if (children.size() != 0)
796 range = children[0];
797 }
798 } else if (id_ast->type == AST_GENVAR) {
799 this_width = 32;
800 } else if (id_ast->type == AST_MEMORY) {
801 if (!id_ast->children[0]->range_valid)
802 log_file_error(filename, location.first_line, "Failed to detect width of memory access `%s'!\n", str.c_str());
803 this_width = id_ast->children[0]->range_left - id_ast->children[0]->range_right + 1;
804 if (children.size() > 1)
805 range = children[1];
806 } else
807 log_file_error(filename, location.first_line, "Failed to detect width for identifier %s!\n", str.c_str());
808 if (range) {
809 if (range->children.size() == 1)
810 this_width = 1;
811 else if (!range->range_valid) {
812 AstNode *left_at_zero_ast = children[0]->children[0]->clone();
813 AstNode *right_at_zero_ast = children[0]->children.size() >= 2 ? children[0]->children[1]->clone() : left_at_zero_ast->clone();
814 while (left_at_zero_ast->simplify(true, true, false, 1, -1, false, false)) { }
815 while (right_at_zero_ast->simplify(true, true, false, 1, -1, false, false)) { }
816 if (left_at_zero_ast->type != AST_CONSTANT || right_at_zero_ast->type != AST_CONSTANT)
817 log_file_error(filename, location.first_line, "Unsupported expression on dynamic range select on signal `%s'!\n", str.c_str());
818 this_width = abs(int(left_at_zero_ast->integer - right_at_zero_ast->integer)) + 1;
819 delete left_at_zero_ast;
820 delete right_at_zero_ast;
821 } else
822 this_width = range->range_left - range->range_right + 1;
823 sign_hint = false;
824 }
825 width_hint = max(width_hint, this_width);
826 if (!id_ast->is_signed)
827 sign_hint = false;
828 break;
829
830 case AST_TO_BITS:
831 while (children[0]->simplify(true, false, false, 1, -1, false, false) == true) { }
832 if (children[0]->type != AST_CONSTANT)
833 log_file_error(filename, location.first_line, "Left operand of tobits expression is not constant!\n");
834 children[1]->detectSignWidthWorker(sub_width_hint, sign_hint);
835 width_hint = max(width_hint, children[0]->bitsAsConst().as_int());
836 break;
837
838 case AST_TO_SIGNED:
839 children.at(0)->detectSignWidthWorker(width_hint, sub_sign_hint);
840 break;
841
842 case AST_TO_UNSIGNED:
843 children.at(0)->detectSignWidthWorker(width_hint, sub_sign_hint);
844 sign_hint = false;
845 break;
846
847 case AST_SELFSZ:
848 sub_width_hint = 0;
849 children.at(0)->detectSignWidthWorker(sub_width_hint, sign_hint);
850 break;
851
852 case AST_CAST_SIZE:
853 while (children.at(0)->simplify(true, false, false, 1, -1, false, false)) { }
854 if (children.at(0)->type != AST_CONSTANT)
855 log_file_error(filename, location.first_line, "Static cast with non constant expression!\n");
856 children.at(1)->detectSignWidthWorker(width_hint, sign_hint);
857 width_hint = children.at(0)->bitsAsConst().as_int();
858 if (width_hint <= 0)
859 log_file_error(filename, location.first_line, "Static cast with zero or negative size!\n");
860 break;
861
862 case AST_CONCAT:
863 for (auto child : children) {
864 sub_width_hint = 0;
865 sub_sign_hint = true;
866 child->detectSignWidthWorker(sub_width_hint, sub_sign_hint);
867 this_width += sub_width_hint;
868 }
869 width_hint = max(width_hint, this_width);
870 sign_hint = false;
871 break;
872
873 case AST_REPLICATE:
874 while (children[0]->simplify(true, false, false, 1, -1, false, true) == true) { }
875 if (children[0]->type != AST_CONSTANT)
876 log_file_error(filename, location.first_line, "Left operand of replicate expression is not constant!\n");
877 children[1]->detectSignWidthWorker(sub_width_hint, sub_sign_hint);
878 width_hint = max(width_hint, children[0]->bitsAsConst().as_int() * sub_width_hint);
879 sign_hint = false;
880 break;
881
882 case AST_NEG:
883 case AST_BIT_NOT:
884 case AST_POS:
885 children[0]->detectSignWidthWorker(width_hint, sign_hint, found_real);
886 break;
887
888 case AST_BIT_AND:
889 case AST_BIT_OR:
890 case AST_BIT_XOR:
891 case AST_BIT_XNOR:
892 for (auto child : children)
893 child->detectSignWidthWorker(width_hint, sign_hint, found_real);
894 break;
895
896 case AST_REDUCE_AND:
897 case AST_REDUCE_OR:
898 case AST_REDUCE_XOR:
899 case AST_REDUCE_XNOR:
900 case AST_REDUCE_BOOL:
901 width_hint = max(width_hint, 1);
902 sign_hint = false;
903 break;
904
905 case AST_SHIFT_LEFT:
906 case AST_SHIFT_RIGHT:
907 case AST_SHIFT_SLEFT:
908 case AST_SHIFT_SRIGHT:
909 case AST_SHIFTX:
910 case AST_SHIFT:
911 case AST_POW:
912 children[0]->detectSignWidthWorker(width_hint, sign_hint, found_real);
913 break;
914
915 case AST_LT:
916 case AST_LE:
917 case AST_EQ:
918 case AST_NE:
919 case AST_EQX:
920 case AST_NEX:
921 case AST_GE:
922 case AST_GT:
923 width_hint = max(width_hint, 1);
924 sign_hint = false;
925 break;
926
927 case AST_ADD:
928 case AST_SUB:
929 case AST_MUL:
930 case AST_DIV:
931 case AST_MOD:
932 for (auto child : children)
933 child->detectSignWidthWorker(width_hint, sign_hint, found_real);
934 break;
935
936 case AST_LOGIC_AND:
937 case AST_LOGIC_OR:
938 case AST_LOGIC_NOT:
939 width_hint = max(width_hint, 1);
940 sign_hint = false;
941 break;
942
943 case AST_TERNARY:
944 children.at(1)->detectSignWidthWorker(width_hint, sign_hint, found_real);
945 children.at(2)->detectSignWidthWorker(width_hint, sign_hint, found_real);
946 break;
947
948 case AST_MEMRD:
949 if (!id2ast->is_signed)
950 sign_hint = false;
951 if (!id2ast->children[0]->range_valid)
952 log_file_error(filename, location.first_line, "Failed to detect width of memory access `%s'!\n", str.c_str());
953 this_width = id2ast->children[0]->range_left - id2ast->children[0]->range_right + 1;
954 width_hint = max(width_hint, this_width);
955 break;
956
957 case AST_FCALL:
958 if (str == "\\$anyconst" || str == "\\$anyseq" || str == "\\$allconst" || str == "\\$allseq") {
959 if (GetSize(children) == 1) {
960 while (children[0]->simplify(true, false, false, 1, -1, false, true) == true) { }
961 if (children[0]->type != AST_CONSTANT)
962 log_file_error(filename, location.first_line, "System function %s called with non-const argument!\n",
963 RTLIL::unescape_id(str).c_str());
964 width_hint = max(width_hint, int(children[0]->asInt(true)));
965 }
966 break;
967 }
968 if (str == "\\$past") {
969 if (GetSize(children) > 0) {
970 sub_width_hint = 0;
971 sub_sign_hint = true;
972 children.at(0)->detectSignWidthWorker(sub_width_hint, sub_sign_hint);
973 width_hint = max(width_hint, sub_width_hint);
974 sign_hint = false;
975 }
976 break;
977 }
978 if (current_scope.count(str))
979 {
980 // This width detection is needed for function calls which are
981 // unelaborated, which currently only applies to calls to recursive
982 // functions reached by unevaluated ternary branches.
983 const AstNode *func = current_scope.at(str);
984 if (func->type != AST_FUNCTION)
985 log_file_error(filename, location.first_line, "Function call to %s resolved to something that isn't a function!\n", RTLIL::unescape_id(str).c_str());
986 const AstNode *wire = nullptr;
987 for (const AstNode *child : func->children)
988 if (child->str == func->str) {
989 wire = child;
990 break;
991 }
992 log_assert(wire && wire->type == AST_WIRE);
993 sign_hint = wire->is_signed;
994 width_hint = 1;
995 if (!wire->children.empty())
996 {
997 log_assert(wire->children.size() == 1);
998 const AstNode *range = wire->children.at(0);
999 log_assert(range->type == AST_RANGE && range->children.size() == 2);
1000 AstNode *left = range->children.at(0)->clone();
1001 AstNode *right = range->children.at(1)->clone();
1002 while (left->simplify(true, false, false, 1, -1, false, true)) { }
1003 while (right->simplify(true, false, false, 1, -1, false, true)) { }
1004 if (left->type != AST_CONSTANT || right->type != AST_CONSTANT)
1005 log_file_error(filename, location.first_line, "Function %s has non-constant width!",
1006 RTLIL::unescape_id(str).c_str());
1007 width_hint = abs(int(left->asInt(true) - right->asInt(true)));
1008 delete left;
1009 delete right;
1010 }
1011 break;
1012 }
1013 YS_FALLTHROUGH
1014
1015 // everything should have been handled above -> print error if not.
1016 default:
1017 for (auto f : log_files)
1018 current_ast_mod->dumpAst(f, "verilog-ast> ");
1019 log_file_error(filename, location.first_line, "Don't know how to detect sign and width for %s node!\n", type2str(type).c_str());
1020 }
1021
1022 if (*found_real)
1023 sign_hint = true;
1024 }
1025
1026 // detect sign and width of an expression
1027 void AstNode::detectSignWidth(int &width_hint, bool &sign_hint, bool *found_real)
1028 {
1029 width_hint = -1;
1030 sign_hint = true;
1031 if (found_real)
1032 *found_real = false;
1033 detectSignWidthWorker(width_hint, sign_hint, found_real);
1034
1035 constexpr int kWidthLimit = 1 << 24;
1036 if (width_hint >= kWidthLimit)
1037 log_file_error(filename, location.first_line,
1038 "Expression width %d exceeds implementation limit of %d!\n",
1039 width_hint, kWidthLimit);
1040 }
1041
1042 static void check_unique_id(RTLIL::Module *module, RTLIL::IdString id,
1043 const AstNode *node, const char *to_add_kind)
1044 {
1045 auto already_exists = [&](const RTLIL::AttrObject *existing, const char *existing_kind) {
1046 std::string src = existing->get_string_attribute(ID::src);
1047 std::string location_str = "earlier";
1048 if (!src.empty())
1049 location_str = "at " + src;
1050 log_file_error(node->filename, node->location.first_line,
1051 "Cannot add %s `%s' because a %s with the same name was already created %s!\n",
1052 to_add_kind, id.c_str(), existing_kind, location_str.c_str());
1053 };
1054
1055 if (const RTLIL::Wire *wire = module->wire(id))
1056 already_exists(wire, "signal");
1057 if (const RTLIL::Cell *cell = module->cell(id))
1058 already_exists(cell, "cell");
1059 if (module->processes.count(id))
1060 already_exists(module->processes.at(id), "process");
1061 if (module->memories.count(id))
1062 already_exists(module->memories.at(id), "memory");
1063 }
1064
1065 // create RTLIL from an AST node
1066 // all generated cells, wires and processes are added to the module pointed to by 'current_module'
1067 // when the AST node is an expression (AST_ADD, AST_BIT_XOR, etc.), the result signal is returned.
1068 //
1069 // note that this function is influenced by a number of global variables that might be set when
1070 // called from genWidthRTLIL(). also note that this function recursively calls itself to transform
1071 // larger expressions into a netlist of cells.
1072 RTLIL::SigSpec AstNode::genRTLIL(int width_hint, bool sign_hint)
1073 {
1074 // in the following big switch() statement there are some uses of
1075 // Clifford's Device (http://www.clifford.at/cfun/cliffdev/). In this
1076 // cases this variable is used to hold the type of the cell that should
1077 // be instantiated for this type of AST node.
1078 IdString type_name;
1079
1080 current_filename = filename;
1081
1082 switch (type)
1083 {
1084 // simply ignore this nodes.
1085 // they are either leftovers from simplify() or are referenced by other nodes
1086 // and are only accessed here thru this references
1087 case AST_NONE:
1088 case AST_TASK:
1089 case AST_FUNCTION:
1090 case AST_DPI_FUNCTION:
1091 case AST_AUTOWIRE:
1092 case AST_DEFPARAM:
1093 case AST_GENVAR:
1094 case AST_GENFOR:
1095 case AST_GENBLOCK:
1096 case AST_GENIF:
1097 case AST_GENCASE:
1098 case AST_PACKAGE:
1099 case AST_ENUM:
1100 case AST_MODPORT:
1101 case AST_MODPORTMEMBER:
1102 case AST_TYPEDEF:
1103 case AST_STRUCT:
1104 case AST_UNION:
1105 break;
1106 case AST_INTERFACEPORT: {
1107 // If a port in a module with unknown type is found, mark it with the attribute 'is_interface'
1108 // This is used by the hierarchy pass to know when it can replace interface connection with the individual
1109 // signals.
1110 RTLIL::IdString id = str;
1111 check_unique_id(current_module, id, this, "interface port");
1112 RTLIL::Wire *wire = current_module->addWire(id, 1);
1113 set_src_attr(wire, this);
1114 wire->start_offset = 0;
1115 wire->port_id = port_id;
1116 wire->port_input = true;
1117 wire->port_output = true;
1118 wire->set_bool_attribute(ID::is_interface);
1119 if (children.size() > 0) {
1120 for(size_t i=0; i<children.size();i++) {
1121 if(children[i]->type == AST_INTERFACEPORTTYPE) {
1122 std::pair<std::string,std::string> res = AST::split_modport_from_type(children[i]->str);
1123 wire->attributes[ID::interface_type] = res.first;
1124 if (res.second != "")
1125 wire->attributes[ID::interface_modport] = res.second;
1126 break;
1127 }
1128 }
1129 }
1130 wire->upto = 0;
1131 }
1132 break;
1133 case AST_INTERFACEPORTTYPE:
1134 break;
1135
1136 // remember the parameter, needed for example in techmap
1137 case AST_PARAMETER:
1138 current_module->avail_parameters(str);
1139 if (GetSize(children) >= 1 && children[0]->type == AST_CONSTANT) {
1140 current_module->parameter_default_values[str] = children[0]->asParaConst();
1141 }
1142 YS_FALLTHROUGH
1143 case AST_LOCALPARAM:
1144 if (flag_pwires)
1145 {
1146 if (GetSize(children) < 1 || children[0]->type != AST_CONSTANT)
1147 log_file_error(filename, location.first_line, "Parameter `%s' with non-constant value!\n", str.c_str());
1148
1149 RTLIL::Const val = children[0]->bitsAsConst();
1150 RTLIL::IdString id = str;
1151 check_unique_id(current_module, id, this, "pwire");
1152 RTLIL::Wire *wire = current_module->addWire(id, GetSize(val));
1153 current_module->connect(wire, val);
1154 wire->is_signed = children[0]->is_signed;
1155
1156 set_src_attr(wire, this);
1157 wire->attributes[type == AST_PARAMETER ? ID::parameter : ID::localparam] = 1;
1158
1159 for (auto &attr : attributes) {
1160 if (attr.second->type != AST_CONSTANT)
1161 log_file_error(filename, location.first_line, "Attribute `%s' with non-constant value!\n", attr.first.c_str());
1162 wire->attributes[attr.first] = attr.second->asAttrConst();
1163 }
1164 }
1165 break;
1166
1167 // create an RTLIL::Wire for an AST_WIRE node
1168 case AST_WIRE: {
1169 if (!range_valid)
1170 log_file_error(filename, location.first_line, "Signal `%s' with non-constant width!\n", str.c_str());
1171
1172 if (!(range_left + 1 >= range_right))
1173 log_file_error(filename, location.first_line, "Signal `%s' with invalid width range %d!\n", str.c_str(), range_left - range_right + 1);
1174
1175 RTLIL::IdString id = str;
1176 check_unique_id(current_module, id, this, "signal");
1177 RTLIL::Wire *wire = current_module->addWire(id, range_left - range_right + 1);
1178 set_src_attr(wire, this);
1179 wire->start_offset = range_right;
1180 wire->port_id = port_id;
1181 wire->port_input = is_input;
1182 wire->port_output = is_output;
1183 wire->upto = range_swapped;
1184 wire->is_signed = is_signed;
1185
1186 for (auto &attr : attributes) {
1187 if (attr.second->type != AST_CONSTANT)
1188 log_file_error(filename, location.first_line, "Attribute `%s' with non-constant value!\n", attr.first.c_str());
1189 wire->attributes[attr.first] = attr.second->asAttrConst();
1190 }
1191
1192 if (is_wand) wire->set_bool_attribute(ID::wand);
1193 if (is_wor) wire->set_bool_attribute(ID::wor);
1194 }
1195 break;
1196
1197 // create an RTLIL::Memory for an AST_MEMORY node
1198 case AST_MEMORY: {
1199 log_assert(children.size() >= 2);
1200 log_assert(children[0]->type == AST_RANGE);
1201 log_assert(children[1]->type == AST_RANGE);
1202
1203 if (!children[0]->range_valid || !children[1]->range_valid)
1204 log_file_error(filename, location.first_line, "Memory `%s' with non-constant width or size!\n", str.c_str());
1205
1206 RTLIL::Memory *memory = new RTLIL::Memory;
1207 set_src_attr(memory, this);
1208 memory->name = str;
1209 memory->width = children[0]->range_left - children[0]->range_right + 1;
1210 if (children[1]->range_right < children[1]->range_left) {
1211 memory->start_offset = children[1]->range_right;
1212 memory->size = children[1]->range_left - children[1]->range_right + 1;
1213 } else {
1214 memory->start_offset = children[1]->range_left;
1215 memory->size = children[1]->range_right - children[1]->range_left + 1;
1216 }
1217 check_unique_id(current_module, memory->name, this, "memory");
1218 current_module->memories[memory->name] = memory;
1219
1220 for (auto &attr : attributes) {
1221 if (attr.second->type != AST_CONSTANT)
1222 log_file_error(filename, location.first_line, "Attribute `%s' with non-constant value!\n", attr.first.c_str());
1223 memory->attributes[attr.first] = attr.second->asAttrConst();
1224 }
1225 }
1226 break;
1227
1228 // simply return the corresponding RTLIL::SigSpec for an AST_CONSTANT node
1229 case AST_CONSTANT:
1230 case AST_REALVALUE:
1231 {
1232 if (width_hint < 0)
1233 detectSignWidth(width_hint, sign_hint);
1234 is_signed = sign_hint;
1235
1236 if (type == AST_CONSTANT) {
1237 if (is_unsized) {
1238 return RTLIL::SigSpec(bitsAsUnsizedConst(width_hint));
1239 } else {
1240 return RTLIL::SigSpec(bitsAsConst());
1241 }
1242 }
1243
1244 RTLIL::SigSpec sig = realAsConst(width_hint);
1245 log_file_warning(filename, location.first_line, "converting real value %e to binary %s.\n", realvalue, log_signal(sig));
1246 return sig;
1247 }
1248
1249 // simply return the corresponding RTLIL::SigSpec for an AST_IDENTIFIER node
1250 // for identifiers with dynamic bit ranges (e.g. "foo[bar]" or "foo[bar+3:bar]") a
1251 // shifter cell is created and the output signal of this cell is returned
1252 case AST_IDENTIFIER:
1253 {
1254 RTLIL::Wire *wire = NULL;
1255 RTLIL::SigChunk chunk;
1256 bool is_interface = false;
1257
1258 int add_undef_bits_msb = 0;
1259 int add_undef_bits_lsb = 0;
1260
1261 log_assert(id2ast != nullptr);
1262
1263 if (id2ast->type == AST_AUTOWIRE && current_module->wires_.count(str) == 0) {
1264 RTLIL::Wire *wire = current_module->addWire(str);
1265 set_src_attr(wire, this);
1266 wire->name = str;
1267 if (flag_autowire)
1268 log_file_warning(filename, location.first_line, "Identifier `%s' is implicitly declared.\n", str.c_str());
1269 else
1270 log_file_error(filename, location.first_line, "Identifier `%s' is implicitly declared and `default_nettype is set to none.\n", str.c_str());
1271 }
1272 else if (id2ast->type == AST_PARAMETER || id2ast->type == AST_LOCALPARAM || id2ast->type == AST_ENUM_ITEM) {
1273 if (id2ast->children[0]->type != AST_CONSTANT)
1274 log_file_error(filename, location.first_line, "Parameter %s does not evaluate to constant value!\n", str.c_str());
1275 chunk = RTLIL::Const(id2ast->children[0]->bits);
1276 goto use_const_chunk;
1277 }
1278 else if ((id2ast->type == AST_WIRE || id2ast->type == AST_AUTOWIRE || id2ast->type == AST_MEMORY) && current_module->wires_.count(str) != 0) {
1279 RTLIL::Wire *current_wire = current_module->wire(str);
1280 if (current_wire->get_bool_attribute(ID::is_interface))
1281 is_interface = true;
1282 // Ignore
1283 }
1284 // If an identifier is found that is not already known, assume that it is an interface:
1285 else if (1) { // FIXME: Check if sv_mode first?
1286 is_interface = true;
1287 }
1288 else {
1289 log_file_error(filename, location.first_line, "Identifier `%s' doesn't map to any signal!\n", str.c_str());
1290 }
1291
1292 if (id2ast->type == AST_MEMORY)
1293 log_file_error(filename, location.first_line, "Identifier `%s' does map to an unexpanded memory!\n", str.c_str());
1294
1295 // If identifier is an interface, create a RTLIL::SigSpec with a dummy wire with a attribute called 'is_interface'
1296 // This makes it possible for the hierarchy pass to see what are interface connections and then replace them
1297 // with the individual signals:
1298 if (is_interface) {
1299 IdString dummy_wire_name = stringf("$dummywireforinterface%s", str.c_str());
1300 RTLIL::Wire *dummy_wire = current_module->wire(dummy_wire_name);
1301 if (!dummy_wire) {
1302 dummy_wire = current_module->addWire(dummy_wire_name);
1303 dummy_wire->set_bool_attribute(ID::is_interface);
1304 }
1305 return dummy_wire;
1306 }
1307
1308 wire = current_module->wires_[str];
1309 chunk.wire = wire;
1310 chunk.width = wire->width;
1311 chunk.offset = 0;
1312
1313 use_const_chunk:
1314 if (children.size() != 0) {
1315 if (children[0]->type != AST_RANGE)
1316 log_file_error(filename, location.first_line, "Single range expected.\n");
1317 int source_width = id2ast->range_left - id2ast->range_right + 1;
1318 int source_offset = id2ast->range_right;
1319 if (!children[0]->range_valid) {
1320 AstNode *left_at_zero_ast = children[0]->children[0]->clone();
1321 AstNode *right_at_zero_ast = children[0]->children.size() >= 2 ? children[0]->children[1]->clone() : left_at_zero_ast->clone();
1322 while (left_at_zero_ast->simplify(true, true, false, 1, -1, false, false)) { }
1323 while (right_at_zero_ast->simplify(true, true, false, 1, -1, false, false)) { }
1324 if (left_at_zero_ast->type != AST_CONSTANT || right_at_zero_ast->type != AST_CONSTANT)
1325 log_file_error(filename, location.first_line, "Unsupported expression on dynamic range select on signal `%s'!\n", str.c_str());
1326 int width = abs(int(left_at_zero_ast->integer - right_at_zero_ast->integer)) + 1;
1327 AstNode *fake_ast = new AstNode(AST_NONE, clone(), children[0]->children.size() >= 2 ?
1328 children[0]->children[1]->clone() : children[0]->children[0]->clone());
1329 fake_ast->children[0]->delete_children();
1330
1331 int fake_ast_width = 0;
1332 bool fake_ast_sign = true;
1333 fake_ast->children[1]->detectSignWidth(fake_ast_width, fake_ast_sign);
1334 RTLIL::SigSpec shift_val = fake_ast->children[1]->genRTLIL(fake_ast_width, fake_ast_sign);
1335
1336 if (id2ast->range_right != 0) {
1337 shift_val = current_module->Sub(NEW_ID, shift_val, id2ast->range_right, fake_ast_sign);
1338 fake_ast->children[1]->is_signed = true;
1339 }
1340 if (id2ast->range_swapped) {
1341 shift_val = current_module->Sub(NEW_ID, RTLIL::SigSpec(source_width - width), shift_val, fake_ast_sign);
1342 fake_ast->children[1]->is_signed = true;
1343 }
1344 if (GetSize(shift_val) >= 32)
1345 fake_ast->children[1]->is_signed = true;
1346 RTLIL::SigSpec sig = binop2rtlil(fake_ast, ID($shiftx), width, fake_ast->children[0]->genRTLIL(), shift_val);
1347 delete left_at_zero_ast;
1348 delete right_at_zero_ast;
1349 delete fake_ast;
1350 return sig;
1351 } else {
1352 chunk.width = children[0]->range_left - children[0]->range_right + 1;
1353 chunk.offset = children[0]->range_right - source_offset;
1354 if (id2ast->range_swapped)
1355 chunk.offset = (id2ast->range_left - id2ast->range_right + 1) - (chunk.offset + chunk.width);
1356 if (chunk.offset >= source_width || chunk.offset + chunk.width < 0) {
1357 if (chunk.width == 1)
1358 log_file_warning(filename, location.first_line, "Range select out of bounds on signal `%s': Setting result bit to undef.\n",
1359 str.c_str());
1360 else
1361 log_file_warning(filename, location.first_line, "Range select [%d:%d] out of bounds on signal `%s': Setting all %d result bits to undef.\n",
1362 children[0]->range_left, children[0]->range_right, str.c_str(), chunk.width);
1363 chunk = RTLIL::SigChunk(RTLIL::State::Sx, chunk.width);
1364 } else {
1365 if (chunk.width + chunk.offset > source_width) {
1366 add_undef_bits_msb = (chunk.width + chunk.offset) - source_width;
1367 chunk.width -= add_undef_bits_msb;
1368 }
1369 if (chunk.offset < 0) {
1370 add_undef_bits_lsb = -chunk.offset;
1371 chunk.width -= add_undef_bits_lsb;
1372 chunk.offset += add_undef_bits_lsb;
1373 }
1374 if (add_undef_bits_lsb)
1375 log_file_warning(filename, location.first_line, "Range [%d:%d] select out of bounds on signal `%s': Setting %d LSB bits to undef.\n",
1376 children[0]->range_left, children[0]->range_right, str.c_str(), add_undef_bits_lsb);
1377 if (add_undef_bits_msb)
1378 log_file_warning(filename, location.first_line, "Range [%d:%d] select out of bounds on signal `%s': Setting %d MSB bits to undef.\n",
1379 children[0]->range_left, children[0]->range_right, str.c_str(), add_undef_bits_msb);
1380 }
1381 }
1382 }
1383
1384 RTLIL::SigSpec sig = { RTLIL::SigSpec(RTLIL::State::Sx, add_undef_bits_msb), chunk, RTLIL::SigSpec(RTLIL::State::Sx, add_undef_bits_lsb) };
1385
1386 if (genRTLIL_subst_ptr)
1387 sig.replace(*genRTLIL_subst_ptr);
1388
1389 is_signed = children.size() > 0 ? false : id2ast->is_signed && sign_hint;
1390 return sig;
1391 }
1392
1393 // just pass thru the signal. the parent will evaluate the is_signed property and interpret the SigSpec accordingly
1394 case AST_TO_SIGNED:
1395 case AST_TO_UNSIGNED:
1396 case AST_SELFSZ: {
1397 RTLIL::SigSpec sig = children[0]->genRTLIL();
1398 if (sig.size() < width_hint)
1399 sig.extend_u0(width_hint, sign_hint);
1400 is_signed = sign_hint;
1401 return sig;
1402 }
1403
1404 // changing the size of signal can be done directly using RTLIL::SigSpec
1405 case AST_CAST_SIZE: {
1406 RTLIL::SigSpec size = children[0]->genRTLIL();
1407 RTLIL::SigSpec sig = children[1]->genRTLIL();
1408 if (!size.is_fully_const())
1409 log_file_error(filename, location.first_line, "Static cast with non constant expression!\n");
1410 int width = size.as_int();
1411 if (width <= 0)
1412 log_file_error(filename, location.first_line, "Static cast with zero or negative size!\n");
1413 sig.extend_u0(width, sign_hint);
1414 is_signed = sign_hint;
1415 return sig;
1416 }
1417
1418 // concatenation of signals can be done directly using RTLIL::SigSpec
1419 case AST_CONCAT: {
1420 RTLIL::SigSpec sig;
1421 for (auto it = children.begin(); it != children.end(); it++)
1422 sig.append((*it)->genRTLIL());
1423 if (sig.size() < width_hint)
1424 sig.extend_u0(width_hint, false);
1425 return sig;
1426 }
1427
1428 // replication of signals can be done directly using RTLIL::SigSpec
1429 case AST_REPLICATE: {
1430 RTLIL::SigSpec left = children[0]->genRTLIL();
1431 RTLIL::SigSpec right = children[1]->genRTLIL();
1432 if (!left.is_fully_const())
1433 log_file_error(filename, location.first_line, "Left operand of replicate expression is not constant!\n");
1434 int count = left.as_int();
1435 RTLIL::SigSpec sig;
1436 for (int i = 0; i < count; i++)
1437 sig.append(right);
1438 if (sig.size() < width_hint)
1439 sig.extend_u0(width_hint, false);
1440 is_signed = false;
1441 return sig;
1442 }
1443
1444 // generate cells for unary operations: $not, $pos, $neg
1445 if (0) { case AST_BIT_NOT: type_name = ID($not); }
1446 if (0) { case AST_POS: type_name = ID($pos); }
1447 if (0) { case AST_NEG: type_name = ID($neg); }
1448 {
1449 RTLIL::SigSpec arg = children[0]->genRTLIL(width_hint, sign_hint);
1450 is_signed = children[0]->is_signed;
1451 int width = arg.size();
1452 if (width_hint > 0) {
1453 width = width_hint;
1454 widthExtend(this, arg, width, is_signed);
1455 }
1456 return uniop2rtlil(this, type_name, width, arg);
1457 }
1458
1459 // generate cells for binary operations: $and, $or, $xor, $xnor
1460 if (0) { case AST_BIT_AND: type_name = ID($and); }
1461 if (0) { case AST_BIT_OR: type_name = ID($or); }
1462 if (0) { case AST_BIT_XOR: type_name = ID($xor); }
1463 if (0) { case AST_BIT_XNOR: type_name = ID($xnor); }
1464 {
1465 if (width_hint < 0)
1466 detectSignWidth(width_hint, sign_hint);
1467 RTLIL::SigSpec left = children[0]->genRTLIL(width_hint, sign_hint);
1468 RTLIL::SigSpec right = children[1]->genRTLIL(width_hint, sign_hint);
1469 int width = max(left.size(), right.size());
1470 if (width_hint > 0)
1471 width = width_hint;
1472 is_signed = children[0]->is_signed && children[1]->is_signed;
1473 return binop2rtlil(this, type_name, width, left, right);
1474 }
1475
1476 // generate cells for unary operations: $reduce_and, $reduce_or, $reduce_xor, $reduce_xnor
1477 if (0) { case AST_REDUCE_AND: type_name = ID($reduce_and); }
1478 if (0) { case AST_REDUCE_OR: type_name = ID($reduce_or); }
1479 if (0) { case AST_REDUCE_XOR: type_name = ID($reduce_xor); }
1480 if (0) { case AST_REDUCE_XNOR: type_name = ID($reduce_xnor); }
1481 {
1482 RTLIL::SigSpec arg = children[0]->genRTLIL();
1483 RTLIL::SigSpec sig = uniop2rtlil(this, type_name, max(width_hint, 1), arg);
1484 return sig;
1485 }
1486
1487 // generate cells for unary operations: $reduce_bool
1488 // (this is actually just an $reduce_or, but for clarity a different cell type is used)
1489 if (0) { case AST_REDUCE_BOOL: type_name = ID($reduce_bool); }
1490 {
1491 RTLIL::SigSpec arg = children[0]->genRTLIL();
1492 RTLIL::SigSpec sig = arg.size() > 1 ? uniop2rtlil(this, type_name, max(width_hint, 1), arg) : arg;
1493 return sig;
1494 }
1495
1496 // generate cells for binary operations: $shl, $shr, $sshl, $sshr
1497 if (0) { case AST_SHIFT_LEFT: type_name = ID($shl); }
1498 if (0) { case AST_SHIFT_RIGHT: type_name = ID($shr); }
1499 if (0) { case AST_SHIFT_SLEFT: type_name = ID($sshl); }
1500 if (0) { case AST_SHIFT_SRIGHT: type_name = ID($sshr); }
1501 if (0) { case AST_SHIFTX: type_name = ID($shiftx); }
1502 if (0) { case AST_SHIFT: type_name = ID($shift); }
1503 {
1504 if (width_hint < 0)
1505 detectSignWidth(width_hint, sign_hint);
1506 RTLIL::SigSpec left = children[0]->genRTLIL(width_hint, sign_hint);
1507 RTLIL::SigSpec right = children[1]->genRTLIL();
1508 int width = width_hint > 0 ? width_hint : left.size();
1509 is_signed = children[0]->is_signed;
1510 return binop2rtlil(this, type_name, width, left, right);
1511 }
1512
1513 // generate cells for binary operations: $pow
1514 case AST_POW:
1515 {
1516 int right_width;
1517 bool right_signed;
1518 children[1]->detectSignWidth(right_width, right_signed);
1519 if (width_hint < 0)
1520 detectSignWidth(width_hint, sign_hint);
1521 RTLIL::SigSpec left = children[0]->genRTLIL(width_hint, sign_hint);
1522 RTLIL::SigSpec right = children[1]->genRTLIL(right_width, right_signed);
1523 int width = width_hint > 0 ? width_hint : left.size();
1524 is_signed = children[0]->is_signed;
1525 if (!flag_noopt && left.is_fully_const() && left.as_int() == 2 && !right_signed)
1526 return binop2rtlil(this, ID($shl), width, RTLIL::SigSpec(1, left.size()), right);
1527 return binop2rtlil(this, ID($pow), width, left, right);
1528 }
1529
1530 // generate cells for binary operations: $lt, $le, $eq, $ne, $ge, $gt
1531 if (0) { case AST_LT: type_name = ID($lt); }
1532 if (0) { case AST_LE: type_name = ID($le); }
1533 if (0) { case AST_EQ: type_name = ID($eq); }
1534 if (0) { case AST_NE: type_name = ID($ne); }
1535 if (0) { case AST_EQX: type_name = ID($eqx); }
1536 if (0) { case AST_NEX: type_name = ID($nex); }
1537 if (0) { case AST_GE: type_name = ID($ge); }
1538 if (0) { case AST_GT: type_name = ID($gt); }
1539 {
1540 int width = max(width_hint, 1);
1541 width_hint = -1, sign_hint = true;
1542 children[0]->detectSignWidthWorker(width_hint, sign_hint);
1543 children[1]->detectSignWidthWorker(width_hint, sign_hint);
1544 RTLIL::SigSpec left = children[0]->genRTLIL(width_hint, sign_hint);
1545 RTLIL::SigSpec right = children[1]->genRTLIL(width_hint, sign_hint);
1546 RTLIL::SigSpec sig = binop2rtlil(this, type_name, width, left, right);
1547 return sig;
1548 }
1549
1550 // generate cells for binary operations: $add, $sub, $mul, $div, $mod
1551 if (0) { case AST_ADD: type_name = ID($add); }
1552 if (0) { case AST_SUB: type_name = ID($sub); }
1553 if (0) { case AST_MUL: type_name = ID($mul); }
1554 if (0) { case AST_DIV: type_name = ID($div); }
1555 if (0) { case AST_MOD: type_name = ID($mod); }
1556 {
1557 if (width_hint < 0)
1558 detectSignWidth(width_hint, sign_hint);
1559 RTLIL::SigSpec left = children[0]->genRTLIL(width_hint, sign_hint);
1560 RTLIL::SigSpec right = children[1]->genRTLIL(width_hint, sign_hint);
1561 #if 0
1562 int width = max(left.size(), right.size());
1563 if (width > width_hint && width_hint > 0)
1564 width = width_hint;
1565 if (width < width_hint) {
1566 if (type == AST_ADD || type == AST_SUB || type == AST_DIV)
1567 width++;
1568 if (type == AST_SUB && (!children[0]->is_signed || !children[1]->is_signed))
1569 width = width_hint;
1570 if (type == AST_MUL)
1571 width = min(left.size() + right.size(), width_hint);
1572 }
1573 #else
1574 int width = max(max(left.size(), right.size()), width_hint);
1575 #endif
1576 is_signed = children[0]->is_signed && children[1]->is_signed;
1577 return binop2rtlil(this, type_name, width, left, right);
1578 }
1579
1580 // generate cells for binary operations: $logic_and, $logic_or
1581 if (0) { case AST_LOGIC_AND: type_name = ID($logic_and); }
1582 if (0) { case AST_LOGIC_OR: type_name = ID($logic_or); }
1583 {
1584 RTLIL::SigSpec left = children[0]->genRTLIL();
1585 RTLIL::SigSpec right = children[1]->genRTLIL();
1586 return binop2rtlil(this, type_name, max(width_hint, 1), left, right);
1587 }
1588
1589 // generate cells for unary operations: $logic_not
1590 case AST_LOGIC_NOT:
1591 {
1592 RTLIL::SigSpec arg = children[0]->genRTLIL();
1593 return uniop2rtlil(this, ID($logic_not), max(width_hint, 1), arg);
1594 }
1595
1596 // generate multiplexer for ternary operator (aka ?:-operator)
1597 case AST_TERNARY:
1598 {
1599 if (width_hint < 0)
1600 detectSignWidth(width_hint, sign_hint);
1601 is_signed = sign_hint;
1602
1603 RTLIL::SigSpec cond = children[0]->genRTLIL();
1604 RTLIL::SigSpec sig;
1605
1606 if (cond.is_fully_def())
1607 {
1608 if (cond.as_bool()) {
1609 sig = children[1]->genRTLIL(width_hint, sign_hint);
1610 log_assert(is_signed == children[1]->is_signed);
1611 } else {
1612 sig = children[2]->genRTLIL(width_hint, sign_hint);
1613 log_assert(is_signed == children[2]->is_signed);
1614 }
1615
1616 widthExtend(this, sig, sig.size(), is_signed);
1617 }
1618 else
1619 {
1620 RTLIL::SigSpec val1 = children[1]->genRTLIL(width_hint, sign_hint);
1621 RTLIL::SigSpec val2 = children[2]->genRTLIL(width_hint, sign_hint);
1622
1623 if (cond.size() > 1)
1624 cond = uniop2rtlil(this, ID($reduce_bool), 1, cond, false);
1625
1626 int width = max(val1.size(), val2.size());
1627 log_assert(is_signed == children[1]->is_signed);
1628 log_assert(is_signed == children[2]->is_signed);
1629 widthExtend(this, val1, width, is_signed);
1630 widthExtend(this, val2, width, is_signed);
1631
1632 sig = mux2rtlil(this, cond, val1, val2);
1633 }
1634
1635 if (sig.size() < width_hint)
1636 sig.extend_u0(width_hint, sign_hint);
1637 return sig;
1638 }
1639
1640 // generate $memrd cells for memory read ports
1641 case AST_MEMRD:
1642 {
1643 std::stringstream sstr;
1644 sstr << "$memrd$" << str << "$" << filename << ":" << location.first_line << "$" << (autoidx++);
1645
1646 RTLIL::Cell *cell = current_module->addCell(sstr.str(), ID($memrd));
1647 set_src_attr(cell, this);
1648
1649 RTLIL::Wire *wire = current_module->addWire(cell->name.str() + "_DATA", current_module->memories[str]->width);
1650 set_src_attr(wire, this);
1651
1652 int mem_width, mem_size, addr_bits;
1653 is_signed = id2ast->is_signed;
1654 wire->is_signed = is_signed;
1655 id2ast->meminfo(mem_width, mem_size, addr_bits);
1656
1657 RTLIL::SigSpec addr_sig = children[0]->genRTLIL();
1658
1659 cell->setPort(ID::CLK, RTLIL::SigSpec(RTLIL::State::Sx, 1));
1660 cell->setPort(ID::EN, RTLIL::SigSpec(RTLIL::State::Sx, 1));
1661 cell->setPort(ID::ADDR, addr_sig);
1662 cell->setPort(ID::DATA, RTLIL::SigSpec(wire));
1663
1664 cell->parameters[ID::MEMID] = RTLIL::Const(str);
1665 cell->parameters[ID::ABITS] = RTLIL::Const(GetSize(addr_sig));
1666 cell->parameters[ID::WIDTH] = RTLIL::Const(wire->width);
1667
1668 cell->parameters[ID::CLK_ENABLE] = RTLIL::Const(0);
1669 cell->parameters[ID::CLK_POLARITY] = RTLIL::Const(0);
1670 cell->parameters[ID::TRANSPARENT] = RTLIL::Const(0);
1671
1672 if (!sign_hint)
1673 is_signed = false;
1674
1675 return RTLIL::SigSpec(wire);
1676 }
1677
1678 // generate $meminit cells
1679 case AST_MEMINIT:
1680 {
1681 std::stringstream sstr;
1682 sstr << "$meminit$" << str << "$" << filename << ":" << location.first_line << "$" << (autoidx++);
1683
1684 RTLIL::Cell *cell = current_module->addCell(sstr.str(), ID($meminit));
1685 set_src_attr(cell, this);
1686
1687 int mem_width, mem_size, addr_bits;
1688 id2ast->meminfo(mem_width, mem_size, addr_bits);
1689
1690 if (children[2]->type != AST_CONSTANT)
1691 log_file_error(filename, location.first_line, "Memory init with non-constant word count!\n");
1692 int num_words = int(children[2]->asInt(false));
1693 cell->parameters[ID::WORDS] = RTLIL::Const(num_words);
1694
1695 SigSpec addr_sig = children[0]->genRTLIL();
1696
1697 cell->setPort(ID::ADDR, addr_sig);
1698 cell->setPort(ID::DATA, children[1]->genWidthRTLIL(current_module->memories[str]->width * num_words));
1699
1700 cell->parameters[ID::MEMID] = RTLIL::Const(str);
1701 cell->parameters[ID::ABITS] = RTLIL::Const(GetSize(addr_sig));
1702 cell->parameters[ID::WIDTH] = RTLIL::Const(current_module->memories[str]->width);
1703
1704 cell->parameters[ID::PRIORITY] = RTLIL::Const(autoidx-1);
1705 }
1706 break;
1707
1708 // generate $assert cells
1709 case AST_ASSERT:
1710 case AST_ASSUME:
1711 case AST_LIVE:
1712 case AST_FAIR:
1713 case AST_COVER:
1714 {
1715 IdString celltype;
1716 if (type == AST_ASSERT) celltype = ID($assert);
1717 if (type == AST_ASSUME) celltype = ID($assume);
1718 if (type == AST_LIVE) celltype = ID($live);
1719 if (type == AST_FAIR) celltype = ID($fair);
1720 if (type == AST_COVER) celltype = ID($cover);
1721
1722 log_assert(children.size() == 2);
1723
1724 RTLIL::SigSpec check = children[0]->genRTLIL();
1725 if (GetSize(check) != 1)
1726 check = current_module->ReduceBool(NEW_ID, check);
1727
1728 RTLIL::SigSpec en = children[1]->genRTLIL();
1729 if (GetSize(en) != 1)
1730 en = current_module->ReduceBool(NEW_ID, en);
1731
1732 IdString cellname;
1733 if (str.empty())
1734 cellname = stringf("%s$%s:%d$%d", celltype.c_str(), filename.c_str(), location.first_line, autoidx++);
1735 else
1736 cellname = str;
1737
1738 check_unique_id(current_module, cellname, this, "procedural assertion");
1739 RTLIL::Cell *cell = current_module->addCell(cellname, celltype);
1740 set_src_attr(cell, this);
1741
1742 for (auto &attr : attributes) {
1743 if (attr.second->type != AST_CONSTANT)
1744 log_file_error(filename, location.first_line, "Attribute `%s' with non-constant value!\n", attr.first.c_str());
1745 cell->attributes[attr.first] = attr.second->asAttrConst();
1746 }
1747
1748 cell->setPort(ID::A, check);
1749 cell->setPort(ID::EN, en);
1750 }
1751 break;
1752
1753 // add entries to current_module->connections for assignments (outside of always blocks)
1754 case AST_ASSIGN:
1755 {
1756 RTLIL::SigSpec left = children[0]->genRTLIL();
1757 RTLIL::SigSpec right = children[1]->genWidthRTLIL(left.size());
1758 if (left.has_const()) {
1759 RTLIL::SigSpec new_left, new_right;
1760 for (int i = 0; i < GetSize(left); i++)
1761 if (left[i].wire) {
1762 new_left.append(left[i]);
1763 new_right.append(right[i]);
1764 }
1765 log_file_warning(filename, location.first_line, "Ignoring assignment to constant bits:\n"
1766 " old assignment: %s = %s\n new assignment: %s = %s.\n",
1767 log_signal(left), log_signal(right),
1768 log_signal(new_left), log_signal(new_right));
1769 left = new_left;
1770 right = new_right;
1771 }
1772 current_module->connect(RTLIL::SigSig(left, right));
1773 }
1774 break;
1775
1776 // create an RTLIL::Cell for an AST_CELL
1777 case AST_CELL:
1778 {
1779 int port_counter = 0, para_counter = 0;
1780
1781 RTLIL::IdString id = str;
1782 check_unique_id(current_module, id, this, "cell");
1783 RTLIL::Cell *cell = current_module->addCell(id, "");
1784 set_src_attr(cell, this);
1785 // Set attribute 'module_not_derived' which will be cleared again after the hierarchy pass
1786 cell->set_bool_attribute(ID::module_not_derived);
1787
1788 for (auto it = children.begin(); it != children.end(); it++) {
1789 AstNode *child = *it;
1790 if (child->type == AST_CELLTYPE) {
1791 cell->type = child->str;
1792 if (flag_icells && cell->type.begins_with("\\$"))
1793 cell->type = cell->type.substr(1);
1794 continue;
1795 }
1796 if (child->type == AST_PARASET) {
1797 int extra_const_flags = 0;
1798 IdString paraname = child->str.empty() ? stringf("$%d", ++para_counter) : child->str;
1799 if (child->children[0]->type == AST_REALVALUE) {
1800 log_file_warning(filename, location.first_line, "Replacing floating point parameter %s.%s = %f with string.\n",
1801 log_id(cell), log_id(paraname), child->children[0]->realvalue);
1802 extra_const_flags = RTLIL::CONST_FLAG_REAL;
1803 auto strnode = AstNode::mkconst_str(stringf("%f", child->children[0]->realvalue));
1804 strnode->cloneInto(child->children[0]);
1805 delete strnode;
1806 }
1807 if (child->children[0]->type != AST_CONSTANT)
1808 log_file_error(filename, location.first_line, "Parameter %s.%s with non-constant value!\n",
1809 log_id(cell), log_id(paraname));
1810 cell->parameters[paraname] = child->children[0]->asParaConst();
1811 cell->parameters[paraname].flags |= extra_const_flags;
1812 continue;
1813 }
1814 if (child->type == AST_ARGUMENT) {
1815 RTLIL::SigSpec sig;
1816 if (child->children.size() > 0) {
1817 AstNode *arg = child->children[0];
1818 int local_width_hint = -1;
1819 bool local_sign_hint = false;
1820 // don't inadvertently attempt to detect the width of interfaces
1821 if (arg->type != AST_IDENTIFIER || !arg->id2ast || arg->id2ast->type != AST_CELL)
1822 arg->detectSignWidth(local_width_hint, local_sign_hint);
1823 sig = arg->genRTLIL(local_width_hint, local_sign_hint);
1824 log_assert(local_sign_hint == arg->is_signed);
1825 if (sig.is_wire()) {
1826 // if the resulting SigSpec is a wire, its
1827 // signedness should match that of the AstNode
1828 log_assert(arg->is_signed == sig.as_wire()->is_signed);
1829 } else if (arg->is_signed) {
1830 // non-trivial signed nodes are indirected through
1831 // signed wires to enable sign extension
1832 RTLIL::IdString wire_name = NEW_ID;
1833 RTLIL::Wire *wire = current_module->addWire(wire_name, GetSize(sig));
1834 wire->is_signed = true;
1835 current_module->connect(wire, sig);
1836 sig = wire;
1837 }
1838 }
1839 if (child->str.size() == 0) {
1840 char buf[100];
1841 snprintf(buf, 100, "$%d", ++port_counter);
1842 cell->setPort(buf, sig);
1843 } else {
1844 cell->setPort(child->str, sig);
1845 }
1846 continue;
1847 }
1848 log_abort();
1849 }
1850 for (auto &attr : attributes) {
1851 if (attr.second->type != AST_CONSTANT)
1852 log_file_error(filename, location.first_line, "Attribute `%s' with non-constant value.\n", attr.first.c_str());
1853 cell->attributes[attr.first] = attr.second->asAttrConst();
1854 }
1855 if (cell->type == ID($specify2)) {
1856 int src_width = GetSize(cell->getPort(ID::SRC));
1857 int dst_width = GetSize(cell->getPort(ID::DST));
1858 bool full = cell->getParam(ID::FULL).as_bool();
1859 if (!full && src_width != dst_width)
1860 log_file_error(filename, location.first_line, "Parallel specify SRC width does not match DST width.\n");
1861 cell->setParam(ID::SRC_WIDTH, Const(src_width));
1862 cell->setParam(ID::DST_WIDTH, Const(dst_width));
1863 }
1864 else if (cell->type == ID($specify3)) {
1865 int dat_width = GetSize(cell->getPort(ID::DAT));
1866 int dst_width = GetSize(cell->getPort(ID::DST));
1867 if (dat_width != dst_width)
1868 log_file_error(filename, location.first_line, "Specify DAT width does not match DST width.\n");
1869 int src_width = GetSize(cell->getPort(ID::SRC));
1870 cell->setParam(ID::SRC_WIDTH, Const(src_width));
1871 cell->setParam(ID::DST_WIDTH, Const(dst_width));
1872 }
1873 else if (cell->type == ID($specrule)) {
1874 int src_width = GetSize(cell->getPort(ID::SRC));
1875 int dst_width = GetSize(cell->getPort(ID::DST));
1876 cell->setParam(ID::SRC_WIDTH, Const(src_width));
1877 cell->setParam(ID::DST_WIDTH, Const(dst_width));
1878 }
1879 }
1880 break;
1881
1882 // use ProcessGenerator for always blocks
1883 case AST_ALWAYS: {
1884 AstNode *always = this->clone();
1885 ProcessGenerator generator(always);
1886 ignoreThisSignalsInInitial.append(generator.outputSignals);
1887 delete always;
1888 } break;
1889
1890 case AST_INITIAL: {
1891 AstNode *always = this->clone();
1892 ProcessGenerator generator(always, ignoreThisSignalsInInitial);
1893 delete always;
1894 } break;
1895
1896 case AST_TECALL: {
1897 int sz = children.size();
1898 if (str == "$info") {
1899 if (sz > 0)
1900 log_file_info(filename, location.first_line, "%s.\n", children[0]->str.c_str());
1901 else
1902 log_file_info(filename, location.first_line, "\n");
1903 } else if (str == "$warning") {
1904 if (sz > 0)
1905 log_file_warning(filename, location.first_line, "%s.\n", children[0]->str.c_str());
1906 else
1907 log_file_warning(filename, location.first_line, "\n");
1908 } else if (str == "$error") {
1909 if (sz > 0)
1910 log_file_error(filename, location.first_line, "%s.\n", children[0]->str.c_str());
1911 else
1912 log_file_error(filename, location.first_line, "\n");
1913 } else if (str == "$fatal") {
1914 // TODO: 1st parameter, if exists, is 0,1 or 2, and passed to $finish()
1915 // if no parameter is given, default value is 1
1916 // dollar_finish(sz ? children[0] : 1);
1917 // perhaps create & use log_file_fatal()
1918 if (sz > 0)
1919 log_file_error(filename, location.first_line, "FATAL: %s.\n", children[0]->str.c_str());
1920 else
1921 log_file_error(filename, location.first_line, "FATAL.\n");
1922 } else {
1923 log_file_error(filename, location.first_line, "Unknown elabortoon system task '%s'.\n", str.c_str());
1924 }
1925 } break;
1926
1927 case AST_FCALL: {
1928 if (str == "\\$anyconst" || str == "\\$anyseq" || str == "\\$allconst" || str == "\\$allseq")
1929 {
1930 string myid = stringf("%s$%d", str.c_str() + 1, autoidx++);
1931 int width = width_hint;
1932
1933 if (GetSize(children) > 1)
1934 log_file_error(filename, location.first_line, "System function %s got %d arguments, expected 1 or 0.\n",
1935 RTLIL::unescape_id(str).c_str(), GetSize(children));
1936
1937 if (GetSize(children) == 1) {
1938 if (children[0]->type != AST_CONSTANT)
1939 log_file_error(filename, location.first_line, "System function %s called with non-const argument!\n",
1940 RTLIL::unescape_id(str).c_str());
1941 width = children[0]->asInt(true);
1942 }
1943
1944 if (width <= 0)
1945 log_file_error(filename, location.first_line, "Failed to detect width of %s!\n", RTLIL::unescape_id(str).c_str());
1946
1947 Cell *cell = current_module->addCell(myid, str.substr(1));
1948 set_src_attr(cell, this);
1949 cell->parameters[ID::WIDTH] = width;
1950
1951 if (attributes.count(ID::reg)) {
1952 auto &attr = attributes.at(ID::reg);
1953 if (attr->type != AST_CONSTANT)
1954 log_file_error(filename, location.first_line, "Attribute `reg' with non-constant value!\n");
1955 cell->attributes[ID::reg] = attr->asAttrConst();
1956 }
1957
1958 Wire *wire = current_module->addWire(myid + "_wire", width);
1959 set_src_attr(wire, this);
1960 cell->setPort(ID::Y, wire);
1961
1962 is_signed = sign_hint;
1963 return SigSpec(wire);
1964 }
1965 }
1966 YS_FALLTHROUGH
1967
1968 // everything should have been handled above -> print error if not.
1969 default:
1970 for (auto f : log_files)
1971 current_ast_mod->dumpAst(f, "verilog-ast> ");
1972 type_name = type2str(type);
1973 log_file_error(filename, location.first_line, "Don't know how to generate RTLIL code for %s node!\n", type_name.c_str());
1974 }
1975
1976 return RTLIL::SigSpec();
1977 }
1978
1979 // this is a wrapper for AstNode::genRTLIL() when a specific signal width is requested and/or
1980 // signals must be substituted before being used as input values (used by ProcessGenerator)
1981 // note that this is using some global variables to communicate this special settings to AstNode::genRTLIL().
1982 RTLIL::SigSpec AstNode::genWidthRTLIL(int width, const dict<RTLIL::SigBit, RTLIL::SigBit> *new_subst_ptr)
1983 {
1984 const dict<RTLIL::SigBit, RTLIL::SigBit> *backup_subst_ptr = genRTLIL_subst_ptr;
1985
1986 if (new_subst_ptr)
1987 genRTLIL_subst_ptr = new_subst_ptr;
1988
1989 bool sign_hint = true;
1990 int width_hint = width;
1991 detectSignWidthWorker(width_hint, sign_hint);
1992 RTLIL::SigSpec sig = genRTLIL(width_hint, sign_hint);
1993
1994 genRTLIL_subst_ptr = backup_subst_ptr;
1995
1996 if (width >= 0)
1997 sig.extend_u0(width, is_signed);
1998
1999 return sig;
2000 }
2001
2002 YOSYS_NAMESPACE_END