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